Define a mod
defineMod describes a mod: its name, its state, its options, its hotkeys, and the setup function that adds everything to Claude Code and returns the methods it offers other mods. registerMod registers the definition with Claude Code.
defineMod
defineMod<State, Name, Options, Hotkeys>(definition: ModDefinition<State, Name, Options, Hotkeys>): ModDefinition<State, Name, Options, Hotkeys>type ModDefinition<State, Name, Options, Hotkeys> = {
readonly name: Name
readonly state?: State
readonly options?: Options
readonly hotkeys?: Hotkeys
readonly installer?: readonly Step<State>[]
setup(mod: Mod<State, Options, Hotkeys>): Api | void | Promise<Api | void>
}nameis the mod's name. Use thenamein.claude-plugin/plugin.json. Claude Mod Manager (cmod) keys the saved state and the options by this name, and the data folder and the Skill overrides by the plugin's name, so the two must match.defineModthrowsdefineMod: the mod needs a name, such as the name in .claude-plugin/plugin.json.for a blank name.stateholds the starting values, grouped by how long they last. state.md explains the groups.optionsdeclares what a person sets, such as a token, and typesmod.options. options.md explains them.hotkeysdeclares the key combos the mod listens for, each with a title and an optional default combo the person can change (Hotkeys).installerlists the steps the person finishes in Claude Code after the options, such as signing in. install-steps.md explains them.setupruns once when the mod starts. It adds listeners, widgets, views, pages, panes, styles, and jobs. It may beasync. What it returns is the mod's API: an object of methods other mods call. Return nothing for a mod that offers none. dependencies.md explains it.
import { defineMod, sessions } from '../node_modules/@cmodjs/core/mod.js'
export const myMod = defineMod({
name: 'my-mod',
state: { session: { isGreeted: false } },
setup(mod) {
sessions.current.onPrompt(() => {
if (mod.state.session.isGreeted) return
mod.state.session.isGreeted = true
mod.toast(`Hello from ${mod.name}`)
})
},
})When setup runs
Claude Code loads the mod at the start of each session. cmod then checks that the mod is set up, and runs its install step when it is not, with a loading toast above the prompt (install-steps.md). An option with no default and no value is asked on the mod's install view, the Install <name> tab of the Sidebar. Then cmod loads the saved state, runs setup, marks as open each of the mod's panes that Claude Code already shows, and opens the install view again for each installer step the mod declares that is not done.
The first time a mod starts on a device, cmod shows the toast Installed under its name. Opened, it lists the mod's plugin.json description, what setup added, such as Adds the my-mod pane, the Branch widget and /deploy., and what its install step set up, with a Settings button that opens Settings at the mod. A new version shows no toast of the mod's own: each running session keeps the version it loaded, and the cmod plugin's Plugins changed toast names <mod> updated to <version> with a Reload button (commands.md). A new session and /reload-plugins show no toast.
When a step fails, the mod stays stopped. Once another session sets it up, the mod starts at the next prompt of every session it stopped in, with no /reload-plugins.
A mod that loads while a session runs, such as after /reload-plugins or /plugin install, hears no SessionStart from Claude Code. cmod runs its onSessionStart and beforeSessionStart listeners before the next prompt instead, once, with the source resume.
When a step fails, the mod does not start. An error toast above the prompt names the failure, with the fix under it:
<mod>: state.<group> is not a lifetime. …or<mod>: state.<group> is not an object of values. …when the declared state is not valid (state.md).its state did not load: <error>when reading the saved values fails.it needs <titles>when the person chose Not now on an option with no default, or no one can answer, as inclaude -p(options.md). This one saysRetry asks for it., andRetryopens the question again.its setup function threw: <error>whensetupthrows or rejects.its open panes did not load: <error>when Claude Code cannot list the open panes.the details of its session did not load: <error>when Claude Code cannot name the session's id, model, or start time.
Each of these has Retry, which starts the mod again, and Report and ✕ (ui.md). A failed step is critical, so its toast shows for an installed mod too.
Rules
A mod's rules/ folder holds rules in Claude Code's own rule format: one Markdown file per rule, with an optional paths list in its front matter. A rule without paths applies to every conversation, and a rule with paths applies when Claude reads a matching file.
my-mod/
└── rules/
├── tests.md <- applies to every conversation
└── sql.md <- front matter paths: ["**/*.sql"]While the mod is on, cmod links the folder into Claude Code's rules folder: a mod the person installed links at <config>/rules/<mod>, and a mod turned on for one project at <project>/.claude/rules/<mod>. A mod turned off for one project keeps its rules out of that project through claudeMdExcludes in the project's .claude/settings.local.json. A rule the person excluded with claudeMdExcludes stays out of the notes too. Turning the mod off and removing the mod remove the link, and an update links the new version's folder. cmod changes only the links and exclusions it made.
Claude Code reads rules without paths only as a session starts. So when cmod links a mod's rules into a running session, it adds them to the conversation as one note, and when it removes the link, one note says the mod's rules no longer apply. A rule taken out of the folder is withdrawn by a note too. When an update changes a rule without paths, one note gives its new text. Claude Code loads rules with paths itself, at the read that matches.
The Installed toast lists the rules, as in Adds 2 rules: sql and tests.
Release notes
A mod's CHANGELOG.md, at its root, holds what changed in each version, written for the people who use it. It follows the Keep a Changelog format: an ## [Unreleased] section for what is not released yet, then one ## [<version>] - <date> section per release, newest first, with its entries under ### Added, ### Changed, ### Removed, and ### Fixed. A breaking change goes under Changed or Removed, and raises the major version.
# Changelog
## [Unreleased]
## [1.4.0] - 2026-10-13
### Added
- /rollback undoes the last deploy, including its database migration.
### Removed
- /deploy-old. Use /deploy --legacy instead.cmod publishreleases the version's section as the GitHub release's notes, and refuses a version with no section (commands.md). Every release ships the file.- Settings shows the mod's Changelog, the whole file with the installed version at the top of the view.
- A linked checkout whose version has no section yet shows its
[Unreleased]section, so the notes show as soon as the version moves. cmod newwrites the file with an[Unreleased]and a[0.1.0]section.
Register the mod with Claude Code
hooks/hooks.json names hooks/register.ts as the plugin's hooks module. register.ts calls registerMod and does nothing else:
import { registerMod, type AddHook, type PluginOptions } from '../node_modules/@cmodjs/core/register.js'
import { myMod } from '../src/mod.js'
export function register(addHook: AddHook, options: PluginOptions): void {
registerMod(addHook, myMod, options)
}registerMod<State, Options>(addHook: AddHook, definition: ModDefinition<State, string, Options>, options: PluginOptions): void
registerPermissionCheck(addHook: AddHook): void
registeredMod(): ModDefinition | undefinedAddHook is the function Claude Code passes register to add each hook, and PluginOptions the values it passes with it.
registerMod registers one handler per Claude Code event the mod can use, and routes each event to the mod. options is what Claude Code passes register: the values of the mod's options (options.md). registeredMod returns the definition registerMod got, for cmod check to read the mod's options without starting it. registerMod leaves out Claude Code's permission check, the events tool.check and PermissionRequest.
A mod that hears permissions calls registerPermissionCheck after registerMod. That covers sessions.current.onPermissionCheck, beforePermissionCheck, onPermissionRequest, beforePermissionRequest, and the permissions job:
export function register(addHook: AddHook, options: PluginOptions): void {
registerMod(addHook, myMod, options)
registerPermissionCheck(addHook)
}A mod that allows or asks, with a before method or an ask rule of the permissions job, also declares "approve": true in its package.json "cmod". cmod check adds the line when it is missing. Anthropic's plugin directory does not list a mod that can approve Claude's tool calls, so cmod publish leaves the code that allows and asks out of the bundle of a mod without "approve": true, and Claude Code decides those calls itself. A mod that only refuses needs no approve, and its bundle holds no code that allows, so the plugin directory can list it. A mod without registerPermissionCheck has no part in Claude Code's permission check, so the plugin directory reads it as one that never answers a permission. Without it, each of those methods and mod.use(permissions(…)) throws <mod>: <method> hears Claude Code's permission check, so hooks/register.ts must call registerPermissionCheck(addHook) after registerMod. where it is called, so a mod that calls one in setup does not start. cmod check fails a mod whose src/ uses one while register.ts does not call registerPermissionCheck.
Where an organization manages Claude Code, Claude Code passes a mod the person installed over on its classic hooks, the notes it adds to a prompt, its Skill and instruction-file text, and compactions, and runs those only for a plugin the organization lists in managed settings. There, the on and before methods built on them hear nothing until the organization lists the mod and the cmod plugin. claude plugin validate names each such hook.
Keep register.ts this small. Claude Code checks a hooks module before it loads it, and refuses some shapes, such as a $ passed to a function in another module. The plugin directory reads the bundled module too, and flags it when the name of register's first parameter is declared anywhere else in the bundle. @cmodjs/core declares on as a key, so name that parameter addHook. Declare register as a function, as here: cmod publish bundles the hooks module into one file, and Claude Code refuses a bundled register that is not one.
mod: this mod
setup gets mod, of type Mod<State, Options, Hotkeys>. Every listener, render, and job gets the same mod. mod holds what belongs to this mod: its name, its folders, its values, its hotkeys, and what it adds to Claude Code.
type Mod<State, Options, Hotkeys> = {
readonly name: string
readonly folder: string
readonly dataFolder: string
readonly cacheFolder: string
readonly secrets: { get(key): Promise<string | undefined>; store(key, value): Promise<void>; delete(key): Promise<void> }
readonly state: Readonly<State>
readonly options: OptionValues<Options>
readonly hotkeys: { readonly [name in keyof Hotkeys]: Hotkey }
every(ms, listener): Timer
after(ms, listener): Timer
use(job): Handle
log(text, options?): void
readonly widgets: { add(widget): Widget }
readonly views: { add(view): View }
readonly pages: { add(page): Page }
readonly settings: { add(view): View; open(): Promise<void> }
readonly panes: { add(pane): Pane }
readonly styles: { add(style): Style }
readonly toast: Toast
ask(question, options?): Promise<string>
readonly dependencies: CmodDependencies
}nameis the mod's name fromdefineMod.folderis the plugin's own folder, where the files the mod ships live.dataFolderis the mod's own folder in the cmod store:$XDG_DATA_HOME/cmod/data/<plugin name>, or~/.local/share/cmod/data/<plugin name>whenXDG_DATA_HOMEis not set. The install step and eachprogramjob's program get the same folder asCMOD_DATA. cmod deletes it when the mod is removed (install-steps.md). It holds what the mod cannot rebuild, such as a chat history, andcmod datalists it so a person can move it to another computer (commands.md).cacheFolderholds what the mod can rebuild, such as an index or a download:$XDG_CACHE_HOME/cmod/<plugin name>, or~/.cache/cmod/<plugin name>whenXDG_CACHE_HOMEis not set. The install step and eachprogramjob's program get the same folder asCMOD_CACHE, andcmod downloadputs each program it fetches in itsbin/. cmod creates it withdataFolderbefore the install step, and deletes it withdataFolderwhen the mod is removed. Nothing copies it to another computer, so the mod builds it again wherever it is missing.secretskeeps the mod's own keys, such as a token it got from a sign-in, out of its files (mod.secrets).stateholds the mod's values. Assign to a key to change it (state.md).optionsholds the values a person set for the mod's options, typed from their declaration. Read-only (options.md).hotkeysholds each hotkeydefineModdeclared (Hotkeys).everyandafterrun a listener on a timer while the session runs.useadds a job, such as a slash command or a tool, and returns its handle (jobs.md).logwrites a line, under the mod's name, to Claude Code's debug log.widgets,views,pages,settings,panes, andstylesadd the mod's widgets, views, pages, views in Settings, panes, and styles.toastshows a short message andaskasks a question (ui.md).dependenciescalls the methods of other mods (dependencies.md).
Everything that is Claude Code's or the computer's rather than the mod's is an import from mod.js, so a function in any file calls it without being handed mod:
import { clipboard, commands, config, device, fs, http, metadata, model, process, providers, sessions, settings } from '../node_modules/@cmodjs/core/mod.js'sessionsis the conversations: the one the mod runs in, every other one, and search across them. Everything that happens in a session, from a prompt to a permission dialog, is a method on it (session.md).commandsis every slash command: it lists them, runs one, and hears or changes each run.settingsis Claude Code'ssettings.jsonfiles: the person's, the project's, and the project's local one.configis the rows of Claude Code's/configmenu.modelasks a model one question, outside the conversation.fsreads, writes, lists, finds, and watches files.metadatareads and changes the mod's keys in one file's metadata.processruns a program.httpfetches a URL.deviceis the computer the session runs on.clipboardputs text on the person's clipboard (ui.md).
Each import works once the mod has started, in setup and anything it adds.
Take back what the mod added
Every add call, every on and before method, fs.onChange, settings.beforeChange, settings.onChange, and hotkey.onPress return a part or a Subscription, and each has remove(), which takes back what the call added. So a mod turns a feature off and on while it runs. Everything a mod adds is taken back when the mod stops, so a mod that keeps a feature for the whole session ignores what the call returns.
type Subscription = { remove(): void }const watching = sessions.current.onToolCall({ name: 'Edit' }, () => void (mod.state.session.edits += 1))
mod.use(slashCommand({ name: 'stop-counting', description: 'Stop counting edits', reply: () => watching.remove() }))mod.secrets
mod.secrets.get(key: string): Promise<string | undefined>
mod.secrets.store(key: string, value: string): Promise<void>
mod.secrets.delete(key: string): Promise<void>secrets keeps a key the mod gets by itself, such as the token a sign-in returns, apart from its files, as VS Code's SecretStorage does. get answers undefined for a secret the mod never stored or deleted, store replaces the value a key had, and delete of a missing key does nothing. A key the person types in is an option instead: option.secret shows it in /config, where Claude Code keeps it (options.md).
const token = (await mod.secrets.get('token')) ?? (await signIn())
await mod.secrets.store('token', token)- Every mod's secrets live as plain values in
secrets.jsonat the root of the cmod store, such as~/.local/share/cmod/secrets.json, which only you can read and write, on every platform and with no keychain, so a Mac nobody sits at never waits on a keychain prompt. The file sits outside every mod's data folder, so copying a mod's data never copies its secrets. - Each mod gets only its own secrets. They are kept apart, not locked away: any program you run can read your files.
- A value never goes in a command's arguments, a log, a toast, or an error.
mod.secretshands it tocmod secretson stdin, and a mod's own program reads it from stdout ofcmod secrets get <mod> <key>, run asprograms/cmodin the cmod store, such as~/.local/share/cmod/programs/cmod(commands.md). storeof an empty value fails, becausedeleteremoves a secret.- cmod deletes the mod's secrets with its data folder when the mod is removed.
mod.every and mod.after
mod.every(ms: number, listener: () => unknown): Timer
mod.after(ms: number, listener: () => unknown): Timer
type Timer = { readonly isRunning: boolean; stop(): void }every runs listener every ms milliseconds until the session ends or the mod calls stop(). A tick that comes while the last run is still going is skipped, so a slow run never stacks up. A run that goes on past three ticks and a minute, such as one awaiting a request that never answers, writes one warning to the Log in Settings, <mod>: one run of its every <ms> ms timer has gone on for <s> s, so the timer skipped every tick since., so give what a run awaits a deadline. after runs listener once, ms milliseconds from now, unless the mod calls stop() first. isRunning is true until the timer stops, and an after timer stops once it ran. A run that throws shows the error toast The every <ms> ms timer failed, or The after <ms> ms timer failed, and the next tick of an every runs again. ms is a whole number above 0 and at most 2147483647, and any other ms stops setup with <mod>: mod.every is <ms>. Give a whole number of milliseconds above 0 and at most 2147483647.
A watch that reacts on its own is every plus mod.state plus a prompt with no trigger: every checks the outside world, writes what it found to mod.state, and the panes and the prompt follow the state (jobs.md).
mod.every(60_000, async () => {
const { stdout } = await process.run(['gh', 'run', 'list', '--limit', '1', '--json', 'conclusion'])
mod.state.session.ci = JSON.parse(stdout)[0]?.conclusion ?? 'running'
})mod.log
mod.log(text: string, options?: { to?: 'debug' | 'transcript'; level?: 'warning' | 'error' }): voidlog writes <mod>: <text> to Claude Code's debug log, which claude --debug shows. It is for what helps the mod's author find a fault and the person never needs to see. Tell the person with a toast instead (ui.md).
With { to: 'transcript' }, the line shows dim in the conversation, where the person reads it and Claude never does, such as "Formatted 3 files" after a turn.
With a level, the line is a failure the mod works around and goes on past, and it goes to the Log in Settings and cmod log too, which counts each repeat with the versions it happened on. An error shows a toast only where cmod shows a failure the mod throws: for a mod run from its checkout, in a session working inside it (ui.md). A warning never shows one. Throw instead when the listener or handler cannot go on.
mod.log(`The rule ${name} did not load, so ${mod.name} skips it: ${messageOf(error)}`, { level: 'error' })Hotkeys
A hotkey is a key combo the mod listens for, such as alt+shift+p to show a view. The mod declares each one with a title and an optional default combo, and the person changes the combo in Settings, under the mod, Hotkeys, the way VS Code handles an extension's keybindings.
hotkeys?: { readonly [name: string]: { readonly title: string; readonly default?: Combo } }
type Hotkey = {
readonly title: string
readonly combo: Combo | undefined
onPress(listener: () => unknown): Subscription
}- A name is letters, digits, and
_, starting with a letter.titleis the label Settings shows beside the combo. - A combo is one or two of
ctrl,alt,shift, andmeta, in that order, then a key: a letter, a digit,f1tof12,tab,enter,escape,space,backspace,delete, an arrow,home,end,pageup,pagedown, or a mark such as/.ctrl+q,alt+shift+p, andctrl+shift+kare combos. defineModthrows for a name, a title, or a combo that is not one, and for two hotkeys with one default.cmod checkwrites the hotkeys intopackage.json"cmod".hotkeys, andcmod publishrefuses a mod whosepackage.jsondiffers fromdefineMod. The install question lists each default combo, andcmod setupbinds it in Claude Code'skeybindings.json. A combo the person already bound to something else keeps their binding, and the hotkey has no combo until they pick one in Settings.- A hotkey without a
defaultstarts unbound. The install question and the Installed toast leave it out, and Settings lists it as unbound until the person binds it there or withcmod hotkeys set(commands.md). Leave outdefaultwhen the person should choose the key, such as for an action few people press. combois the combo bound when the mod started, orundefinedwhenkeybindings.jsonbinds none to the hotkey, such as when another binding kept the default or the hotkey has no default.onPressrunslistenereach time the person presses the combo. A view, page, or pane the listener opens shows at any width, because the press is the person's own (ui.md).tested.hotkey(name)presses a hotkey in a test (testing.md).
export const myMod = defineMod({
name: 'my-mod',
hotkeys: {
toggle: { title: 'Show or hide the view', default: 'alt+shift+n' },
},
setup(mod) {
const view = mod.views.add(myView)
mod.hotkeys.toggle.onPress(() => view.toggle({ focus: true }))
},
})commands: slash commands
commands.list(): Promise<CommandInfo[]>
commands.run(name: string, args?: string): Promise<{ text?: string; note?: string }>
commands.beforeRun(matcher?, listener: (run: CommandRun) => Answer | void, options?): Subscription
commands.onRun(matcher?, listener: (run: CommandRun) => unknown, options?): Subscription
type CommandInfo = { name: string; description: string; source: 'builtin' | 'plugin' | 'user' | 'mcp'; plugin?: string }
type CommandRun = { name: string; args: string; source?: 'builtin' | 'plugin' | 'user' | 'mcp'; from: Sender; session: string; cwd: string }listanswers every command the person can type: Claude Code's own, each plugin's, the person's and the project's, and each MCP server's prompts.runruns a command, a built-in such ascompactincluded, the way the person typing/<name> <args>would. It resolves the text the command printed and the note it left Claude.beforeRunruns just before any command runs, typed or run by a mod, and its answer changes it:{ args?, note? }runs it with new arguments and adds a note Claude reads after its output,{ result, exitCode? }answers in its place without running it, and{ refuse }runs nothing and shows the reason as its output.exitCodeis what aclaude -p "/lint"run exits with.onRunhears each command once it ran.- A command a project or a plugin writes as a Markdown prompt, such as
/review, also reachesbeforePromptafterbeforeRun, as its text goes to Claude (session.md). A built-in such as/modelreaches only these two.
commands.beforeRun({ name: 'compact' }, () => (mod.state.session.isDeploying ? { refuse: 'Compact once the deploy finishes.' } : undefined))
commands.onRun({ name: 'model' }, (run) => mod.log(`model set to ${run.args}`))A command of the mod's own is a slashCommand job (jobs.md).
settings: Claude Code's settings files
settings.user.read(): Promise<Settings>
settings.user.update(values: Readonly<Record<string, unknown>>): Promise<void>
settings.project.read(): Promise<Settings>
settings.project.update(values: Readonly<Record<string, unknown>>): Promise<void>
settings.local.read(): Promise<Settings>
settings.local.update(values: Readonly<Record<string, unknown>>): Promise<void>
settings.beforeChange(matcher?, listener: (change: SettingsFileChange) => { refuse: string } | void): Subscription
settings.onChange(matcher?, listener: (change: SettingsFileChange) => unknown): Subscriptionsettings.user is the person's own ~/.claude/settings.json, settings.project is the project's .claude/settings.json, and settings.local is the project's .claude/settings.local.json.
readanswers the values in that one file, such as(await settings.user.read())['enabledPlugins'].updatemergesvaluesinto that file as a JSON Merge Patch (RFC 7396).mcpServersinsettings.projectgoes to the project's.mcp.json, where Claude Code reads a project's servers.- An object merges into the object already at that key, at every depth, so every key it does not name stays as it was.
nullremoves the key at its depth. An array or any other value replaces the value. To replace a whole object, read it and set each key you drop tonull. - The file's comments and formatting stay as they were.
- Removing the mod takes out each value it set that still equals what it set, then each object that leaves empty. A value the person changed since stays.
- Change a Claude Code settings file with
update, neverfs.write, because a whole-file write loses the person's own edits and leaves the mod's values behind when it is removed.
A mod that points Claude Code at its local proxy sets one variable in env, and the person's other variables stay:
await settings.user.update({ env: { ANTHROPIC_BASE_URL: 'http://127.0.0.1:8317' } })beforeChange hears each settings file Claude Code sees edited while the session runs, and a Skill file edited, before Claude Code loads it, and { refuse } keeps Claude Code on the values it had. onChange hears the same change once Claude Code loaded it, so read answers the new values there, and never hears a change a beforeChange refused. source is 'user', 'project', 'local', 'policy', or 'skills', and path is the file, when Claude Code names it:
type SettingsFileChange = { source: 'user' | 'project' | 'local' | 'policy' | 'skills'; path?: string }
settings.beforeChange({ source: /^(user|project)$/ }, () => ({ refuse: 'Settings are locked while the deploy runs.' }))
settings.onChange({ source: 'user' }, async () => mod.log(`The theme is ${String((await settings.user.read())['theme'])}.`))config: the /config menu
config.list(): Promise<ConfigRow[]>
type ConfigRow = { key: string; label: string; description?: string; kind: 'boolean' | 'choice' | 'text' | 'number'; value: boolean | string | number | readonly string[]; options?: readonly string[]; plugin?: string; isLocked: boolean }config.list answers every row of Claude Code's /config menu, its own and each plugin's, with the value each holds now. plugin names the plugin a row belongs to, and Claude Code's own rows have none. isLocked is true when a managed setting or the organization's policy holds the value.
model: one question outside the conversation
model.complete(request: ModelCompleteRequest, options?: ModelCompleteOptions): Promise<ModelCompleteResult>complete asks a model one question through Claude Code's own login, outside the conversation, so the answer costs no context and the person sees no turn. The request names the model, such as 'haiku', and the prompt, and takes system, maxTokens, effort, and timeoutMs. timeoutMs stops a model that is slow or down, so the listener that waits on it still answers in time. options.signal stops the call when its AbortController aborts.
The call never rejects for what the model did. The result's isAnswered is true with the reply's text, or false with a reason, such as 'api-error' or 'aborted'.
Give the listener that waits on it time too, with its timeoutMs (session.md), which also covers the work around the call:
sessions.current.beforeTurnEnd(async (turn, { signal }) => {
const verdict = await model.complete({ model: 'haiku', prompt: `Does this reply ask the person to do work Claude could do itself? Answer yes or no.\n\n${turn.answer ?? ''}`, timeoutMs: 8000 }, { signal })
if (verdict.isAnswered && verdict.text.trim().toLowerCase().startsWith('yes')) return { refuse: 'Do that work yourself, then reply.' }
}, { timeoutMs: 9000 })process: run a program
process.run(argv: readonly string[], options?: ProcessRunOptions): Promise<ProcessRunResult>
process.spawn(argv: readonly string[], options?: ProcessSpawnOptions): SubprocessBoth run a program without a shell. argv[0] is the program and the rest are its arguments. A bare name that cmod installed, such as hello, runs from cmod's programs folder (install-steps.md), and any other name runs through Claude Code's PATH.
options.cwdis the program's folder, absolute or relative to the session's working folder. Without it the program runs in the session's working folder.options.envsets variables over Claude Code's own environment.runtakesstdin, andspawntakesinput: text written to standard input, which then closes.runtakestimeoutMs: Claude Code kills the program after it, 30 seconds by default and 10 minutes at most.longestMs, exported frommod.js, is those 10 minutes in milliseconds,600000.runresolves{ exitCode, stdout, stderr, isStdoutTruncated, isStderrTruncated }once the program exits, whatever its exit code. It keeps the first 4 MiB of each stream. A program ended by a signal hasexitCode1.runrejects when the program cannot start, and when it is still running attimeoutMs. It reads the whole output, so a background process the program leaves writing holds the call until the timeout.spawnanswers aSubprocess, which streams{ stream: 'stdout' | 'stderr', text }pieces as the program writes them. Itsresultresolves{ code, signal }once the stream is read to its end. Its first pull rejects when the program cannot start.- The
for awaitloop over aspawnis the program's life. Leaving the loop, or callingreturn()on the stream, kills the program, and so does unloading the mod. Returning from the listener does not.
A job's deadline bounds the whole callback that makes these calls (jobs.md).
import { defineMod, process, sessions } from '../node_modules/@cmodjs/core/mod.js'
export const myMod = defineMod({
name: 'my-mod',
setup() {
sessions.current.beforeSessionStart(async () => {
const { exitCode, stdout } = await process.run(['git', 'branch', '--show-current'], { cwd: sessions.current.project })
if (exitCode !== 0) return
return { note: `The git branch is ${stdout.trim()}.` }
})
},
})fs: files
fs.read(path: string): Promise<string>
fs.write(path: string, text: string): Promise<void>
fs.list(path?: string): Promise<Entry[]>
fs.exists(path: string): Promise<boolean>
fs.stat(path: string, options?: StatOptions): Promise<Stat>
fs.find(glob: string | readonly string[]): Promise<readonly FileMatch[]>
fs.onChange({ path: string | readonly string[] }, listener: (change: FileChange) => unknown): Subscriptiontype FileChange = { path: string; type: 'change' | 'add' | 'unlink' }
type Entry = { name: string; isFile: boolean; isFolder: boolean; isLink: boolean; size: number; modifiedAt: number }
type Stat = { isFile: boolean; isFolder: boolean; isLink: boolean; size: number; modifiedAt: number; realPath?: string }- A relative path is under the session's working folder. An absolute path is used as given.
~/.claudeand$CLAUDE_CONFIG_DIRare Claude Code's config folder, and~and$HOMEare the home folder. Text is UTF-8. readrejects a missing file and a file over 4 MiB.writewrites the whole file and creates its folders.listlists a folder, the working folder without a path. A symbolic link is neither a file nor a folder, withisLinktrue.modifiedAtis the time it last changed, in milliseconds since 1970.existsanswers whether the path leads to a file or a folder.statanswers what the path leads to, following a symbolic link, and rejects a missing path. WithStatOptions{ resolve: true }it also answersrealPath: the absolute path, every symbolic link followed.onChangehears each file that changes, appears, or goes at a path or under a folder, the mod's own saves included. cmod checks the paths twice a second, and at most 2000 files under one call's folders. A call over more stops, with an error toast that names its paths. It works fromsetupor any time later, and for a path that does not exist yet. A relative path is under the session's working folder.pathtakes strings only, unlike other matchers:
fs.onChange({ path: `${mod.dataFolder}/history` }, ({ path, type }) => mod.toast(`${path}: ${type}`))A file the mod ships is under mod.folder. A file the mod keeps for itself belongs in mod.dataFolder, or in mod.cacheFolder when the mod can build it again.
find answers every file a glob matches, each with its metadata, so a mod finds the Skills, agents, scripts, or notes it acts on in one call:
type FileMatch = { readonly path: string; readonly name?: string; readonly metadata: Readonly<Record<string, string>>; readonly error?: string }- A glob starting with
~/.claudestarts at Claude Code's config folder,CLAUDE_CONFIG_DIRwhen it is set. One starting with~/starts at home, one starting with/is absolute, and any other starts at the project. Several globs answer each file once. pathis absolute.nameis a Markdown file's frontmattername.metadataholds the mod's own keys, bare, asmetadata.readanswers them.findfollows symbolic links into the folders they point at, once each. It skips.gitandnode_modulesunless the glob names them.- A file whose metadata cmod cannot read comes back with empty
metadataand anerrornaming the line, and cmod logs it once. A file cmod cannot open comes back the same way, with anerrornaming the reason. - A folder cmod cannot list, such as one it has no permission to read, is left out, and cmod writes
<mod>: fs.find skipped <folder>: <reason>to Claude Code's debug log once. - cmod keeps what it read of each file until the file's modified time or size changes.
const skills = await fs.find(['~/.claude/skills/*/SKILL.md', '.claude/skills/*/SKILL.md'])
const planning = skills.filter((skill) => skill.metadata['tags']?.split(' ').includes('plan'))metadata: a file's own keys
metadata.read(path: string): Promise<Readonly<Record<string, string>>>
metadata.update(path: string, change: (metadata: Record<string, string>) => void): Promise<void>Metadata is a file's own set of string keys, kept in the file, so it moves and is committed with the file. Each mod reads and writes its own keys only: the file stores them as <mod>.<key>, and the mod sees them bare. A value is one line of text, and a list is one space-separated string.
Where a file keeps its metadata depends on its type:
---
name: plan
metadata:
my-mod.tags: plan build
---#!/bin/sh
# /// metadata
# my-mod.tags: plan build
# ///- A Markdown file keeps it in its frontmatter, under
metadata:. - A
.sh,.py,.ts,.js,.yaml, or.tomlfile keeps it in a/// metadatacomment block after any shebang, in the file's own comment,#or//, the way PEP 723 keeps a Python script's dependencies. - Any other file keeps it in a sidecar,
<file>.meta.
update hands change the mod's current keys, and writes what change leaves. It changes only the metadata block, keeps other mods' keys, writes nothing when nothing changed, and removes an empty block. It writes through a symbolic link to the file it points at. A key is letters, digits, _, ., and -, and update rejects any other key and a value with a line break.
read rejects when cmod cannot open the file or read its metadata, with the reason or the line. update rejects the same way and writes nothing, so it never overwrites metadata it could not read.
await metadata.update('.claude/skills/plan/SKILL.md', (keys) => {
keys['tags'] = 'plan build'
})cmod check reads the metadata of every file the mod ships, and fails one cmod cannot read.
http: fetch a URL
http.fetch(url: string, options?: HttpOptions): Promise<HttpResponse>optionstakesmethod(GETby default),headers,bodyas text, andsocketPath, the absolute path of a Unix socket the request goes over.- The response is
{ status, ok, headers, text }.okis true for a 2xx status. Header names are lower case. - A mod reaches the address its own
programjob answers on the same way (jobs.md).
device: the computer the session runs on
device.read(): Promise<Device>
type Device = { id: string; name: string; os: 'darwin' | 'linux'; arch: 'arm64' | 'x64' }idis the same on one computer for every session, mod, and reinstall, and differs between computers. cmod reads it from the operating system and stores nothing: the IOPlatformUUID on macOS, and on Linux/etc/machine-id, or/var/lib/dbus/machine-idwhen that holds none, as systemd and D-Bus read them, hashed for cmod the way systemd'ssd_id128_get_machine_app_specifichashes a machine id for an app, so the id never shows the computer's own.nameis the name the computer goes by on its network: its LocalHostName on macOS, such asMac-mini, and its hostname on Linux.osandarchare the names cmod's builds use, such asdarwinandarm64.readreads the computer the first time the mod calls it, and answers the same device after that. It rejects on a computer other than macOS or Linux on arm64 or x64. It also rejects on a Linux computer where neither/etc/machine-idnor/var/lib/dbus/machine-idholds a machine id, as in many containers, with a sentence that names both files.- A mod's program that runs with no session, such as over
ssh, reads the same device withcmod device --json(commands.md). - Each turn names the device it ran on, as
turn.device(session.md), so a mod tells which computer ran each turn of a session that moved between computers. A start on a computer without a machine id names no device, so the turns after it keep the device of the start before, or have none.
const here = await device.read()
const elsewhere = (await sessions.current.turns()).filter((turn) => turn.device !== undefined && turn.device.id !== here.id)mods: the other mods that run
mods.isLoaded(name: string): Promise<boolean>Answers whether a mod runs in this Claude Code process, so a mod calls another mod it does not list only when the person has it (dependencies.md).
provide and providers: the mods that answer an interface
provide<Name extends InterfaceName>(name: Name, methods: InterfaceMethods<Name>): Provided<Name>
providers<Name extends InterfaceName>(name: Name): Promise<InterfaceProvider<Name>[]>
type Provided<Name> = Subscription & { tell(event, payload): void; ask(event, payload): Promise<unknown[]> }provide answers the interface's methods while the mod runs in this session, for callers in this session, until remove() on the Provided it returns. From a program, after connect() from rpc.js, it answers them for every session on the computer. tell tells one of the interface's events, typed from its events, to every on listener that hears this provider, and ask asks every before listener of the event and resolves their answers. providers answers each mod and program that provides the interface now, with its methods and its events (dependencies.md).
messageOf
messageOf(error: unknown): stringReturns an Error's message, or the value as text. Use it in a catch, where the error is unknown.
import { defineMod, fs, messageOf, sessions } from '../node_modules/@cmodjs/core/mod.js'
export const myMod = defineMod({
name: 'my-mod',
setup(mod) {
sessions.current.onTurnEnd(async () => {
await fs.write(`${mod.dataFolder}/last-stop.txt`, new Date().toISOString()).catch((error: unknown) => {
mod.toast.error('Could not save the last stop', { description: messageOf(error) })
})
})
},
})shell.js and path.js: read a command line
shell.js reads a Bash line the way cmod does for a tool call's files (session.md), and path.js is node:path's POSIX functions, which a mod cannot import from Node:
parseShell(line: string): ParsedShell
type ParsedShell = { commands: ShellCommand[]; reads: string[]; writes: string[]; fetches: string[]; isFullyParsed: boolean }
type ShellCommand = { argv: [string, ...string[]]; folder: string; input?: number; runner?: number }
resolve(...paths): string join(...paths): string dirname(path): string basename(path, suffix?): string
extname(path): string relative(from, to): string isAbsolute(path): boolean normalize(path): stringcommandslists every command the line runs, those insidesudo,bash -c,$(…), and heredocs included, with flags such as-rfsplit into-rand-f.folderis where a command runs, as the line wrote it:''for the folder the line starts in,srcaftercd src,/tmpaftercd /tmp, and~/paftercd ~/p.resolve(call.cwd, folder)makes it absolute.inputis the index incommandsof the command whose output this one reads through|or|&, and is absent for a command that reads no pipe.cat a.ts | head -5givesheadtheinput0. A wrapper such astimeout 5 cat a.tswrites the output of the command it runs, soinputnamescat, nottimeout.runneris the index incommandsof the command that runs this one, such assudo,xargs,find -exec, orbash -c, and is absent for a command the line's own shell runs,$(…)and( … )included.sudo rm xgivesrmtherunner0, and insudo bash -c 'rm x'the runners chain fromrmtobashtosudo.reads,writes, andfetchesare the paths and URLs the commands name, as written. A{}in afind -execaction stands for each start path of thefind, sofind build -exec rm {} +writesbuild, asfind build -deletedoes, while itsargvkeeps{}. A path that holds a shell expansion makesisFullyParsedfalse, and so does a line the parser cannot read.resolvehas no working folder to start from in Claude Code, so pass an absolute folder first, such asresolve(sessions.current.cwd, path).
import { basename, resolve } from '../node_modules/@cmodjs/core/path.js'
import { parseShell } from '../node_modules/@cmodjs/core/shell.js'
import { sessions } from '../node_modules/@cmodjs/core/mod.js'
sessions.current.onToolCall({ name: 'Bash' }, (call) => {
for (const { argv, folder } of parseShell(String(call.input['command'])).commands) {
if (basename(argv[0]) === 'git') mod.toast(`git runs in ${resolve(call.cwd, folder)}`)
}
})