<!-- Generated from the Command Code docs: https://commandcode.ai/docs -->

# ModApi reference

`export default function (cmd: ModApi)` - the factory. `ModFactory = (cmd: ModApi) => void | Promise<void>`. Every `add*` / `on` / `hooks` call returns `Disposable { dispose(): void }` - `.dispose()` undoes exactly that one registration (idempotent; a second call is a no-op). Disposables make a registration retractable and are the seam future hot-reload will recycle.

## Fields

| Member | Type | Notes |
|---|---|---|
| `cmd.name` | `string` | the mod's name (from filename / manifest) |
| `cmd.cwd` | `string` | workspace root |
| `cmd.session` | `ModSessionApi \| undefined` | persistence seam; undefined until bound |
| `cmd.events` | `ModEventBus` | `emit(channel, data?)` / `on(channel, handler)` cross-mod bus |
| `cmd.ui` | `ModUi` | `notify` / `confirm` / `select` / `input` / `setStatus` / `widget` / `refreshWidgets` / `pane` / `openPane` / `closePane` / `toast` / `copy` / `override` / `setTitle` / `capabilities` |
| `cmd.sessions` | `ModSessionControls` | `compact` / `tree` / `leafId` / `navigateTree` / `setLabel` |
| `cmd.state` | `ModStateApi` | `get` / `set` / `subscribe` - session values that survive a hot reload |
| `cmd.store` | `ModStoreApi` | `get` / `set` / `delete` - values kept across sessions (`~/.commandcode/mods/.store/<mod>.json`) |
| `cmd.clock` | `ModClockApi` | `every` / `after` - timers cancelled with the mod |
| `cmd.model` | `ModModelApi` | `complete` - one prompt on the session's model client |
| `cmd.prompt` | `ModPromptApi` | `submit` - start a turn of its own once the session is idle |
| `cmd.process` | `ModProcessApi` | `spawn` - run a process and stream its output as it arrives |
| `cmd.audio` | `ModAudioApi` | `play` / `bell` - sound files shipped with the mod, and the terminal bell |

## Registration methods

Call these while the mod's factory runs. Each one returns a `Disposable`.

| Method | Signature |
|---|---|
| `cmd.hooks` | `(hooks: ModHooks) => Disposable` |
| `cmd.addTool` | `(tool: ToolModule) => Disposable` |
| `cmd.addCommand` | `(command: {name; description?; argumentHint?; handler}) => Disposable` |
| `cmd.addFlag` | `(name, {type: 'boolean'\|'string'; default?; description?}) => Disposable` |
| `cmd.addProvider` | `(module: ProviderModule) => Disposable` |
| `cmd.addRenderer` | `(customType: string, (data) => readonly string[]) => Disposable` |
| `cmd.addShortcut` | `(keys: string, {description?; handler}) => Disposable` |
| `cmd.addSkillsPath` | `(path: string) => Disposable` |
| `cmd.on` | `(event: AgentEventType \| 'session_start' \| 'session_shutdown', handler) => Disposable` |
| `cmd.addAgent` | `(definition: {name; description; systemPrompt; tools?; disallowedTools?; model?; maxTurns?}) => Disposable` |
| `cmd.expose` | `(name, fn) => Disposable` |

What each does:

- `cmd.hooks(hooks)` - the mutating lifecycle hooks: the `AgentMod` surface (transformContext, beforeToolCall, afterToolCall, onTurnStart/End, appendSystemPrompt, shouldStopAfterTurn, prepareNextTurn, onRunEnd, **onStop**) **plus `transformInput`, `onSessionStart`, and `onSessionEnd`**. Multiple calls compose in order with mod-runner semantics (threading, chaining, any-true, later-wins). See [the hook contracts](./hooks-and-events.md#the-hook-contracts) for the full contract of each hook.
- `cmd.addTool(toolModule)` - a `ToolModule` the model can call; same collision policy as `AgentMod.tools` (existing names win, collision emits `mod_error`). The tool's `run` receives `{input, runtime, signal}` and returns `{ok: true, content: [{type: 'text', text}]}` or `{ok: false, error}`. Mark `readOnly: true` when the tool never mutates (stays available in plan mode).
- `cmd.addCommand({name, description, handler})` - a `/name` slash command. The handler returns data, not callbacks: `{prompt}` submits an automated turn, `{message}` renders an info row, nothing = pure side effect. It gets `{args, ui, cwd, exec}`. First registration of a name wins across mods.
- `cmd.addFlag(name, {type, default})` / `cmd.getFlag(name)` - named options; values come from repeatable `--mod-option name=value` CLI flags (defaults apply otherwise).
- `cmd.on(event, handler)` - observe any `AgentEvent` plus the host lifecycle events `session_start` / `session_shutdown` (fired when a harness binds the host and when a session switch or dispose replaces it). Handlers are isolated: a throw becomes a `mod_error {hook: 'on:<event>'}` event, never a crash.
- `cmd.addProvider(providerModule)` - register a model provider through the same `ProviderModule` seam the built-ins use (id, transport, auth hooks, model list). The host appends mod providers to its set - mods extend the provider set, never replace it.
- `cmd.addRenderer(customType, data => lines)` - a renderer for a custom entry type; returns the lines to print (style them with ansi escapes - picocolors, `@commandcode/tui` helpers, or raw codes). First registration per type wins across mods.
- `cmd.addAgent(definition)` - a sub-agent type the model can delegate to through the `task` tool, next to the bundled and on-disk agents. `tools` defaults to `'*'`. An agent name that already exists (bundled, project, user, or another mod's) is skipped with a warning. Read live, so a reload's agents show up on the next turn.
- `cmd.expose(name, fn)` / `cmd.use(mod, name)` - share a function with other mods and call one another mod shared. `use` answers `undefined` until that mod has loaded and exposed the name, so call it from a hook or command, not only at factory time.
- `cmd.addShortcut(keys, {description, handler})` - a keyboard shortcut in the interactive TUI. `keys` is a `modifier+key` chord that **must include Ctrl or Alt** (`alt+r`, `ctrl+r`); a modifier-less or Shift-only chord (`p`, `enter`, `shift+p`) is rejected with a warning, because it would also type into the prompt, and so is a `Ctrl+Shift` chord whose key reaches the terminal as a bare control byte — letters, digits, Enter, Tab, Backspace (`ctrl+shift+p`, `ctrl+shift+enter`) — where the Shift never arrives (arrow / navigation keys keep their modifiers, so `ctrl+shift+up` is fine). `ctrl+m`, `ctrl+i`, `ctrl+h` and `ctrl+[` are rejected too: terminals send them as Enter, Tab, Backspace and Escape. A chord a built-in already owns (`ctrl+c`, `ctrl+o`, an editor key like `ctrl+k`) is rejected the same way — the host's own bindings run first, so it would never fire — and so are the keys the prompt handles itself (`alt+w`, `ctrl+z`, `ctrl+g`, `ctrl+s`, `ctrl+v`, `alt+v`), which stay taken even when rebound. The handler gets the same `{args, ui, cwd, exec}` context a command handler does and may return the same `{message}` / `{prompt}` result. The host dispatches mod shortcuts AFTER its own bindings, so a mod can add keys but never shadow interrupt, exit, mode cycling, or the transcript toggles; `Esc` stays host-owned. First registration per chord wins across mods; `/hotkeys` lists them under **Mods**. Headless hosts never fire shortcuts.
- `cmd.addSkillsPath(path)` - an extra skills location (one skill directory, or a directory of skills) for this session's skill discovery. Relative paths resolve against the mod's own file, so a package can point at the `./skills` it ships. Collected at factory time. A package can declare the same thing without code through its manifest - see [Turn a mod into a package](./packaging.md#turn-a-mod-into-a-package).

## Live methods

These work any time after the harness binds to the mod host.

| Method | Signature |
|---|---|
| `cmd.getFlag` | `(name) => boolean \| string \| undefined` |
| `cmd.showEntry` | `(customType, data?) => void` |
| `cmd.queueMessage` | `({content, deliverAs?: 'steer' \| 'follow-up'}) => void` |
| `cmd.sendUserMessage` | `(content, {deliverAs?}) => void` |
| `cmd.exec` | `({command, args?, cwd?, signal?}) => Promise<{stdout, stderr, code}>` |
| `cmd.process.spawn` | `({command, args?, cwd?, signal?, onOutput: (chunk, stream) => void}) => Promise<{code}>` |
| `cmd.setSessionName` / `setModel` / `setEffort` | `(value) => void` (buffered pre-bind) |
| `cmd.getSessionName` / `getModel` / `getEffort` | `() => value \| undefined` (undefined pre-bind) |
| `cmd.getContextUsage` | `() => {tokens, contextWindow, percent} \| undefined` |
| `cmd.getCommands` | `() => readonly {name, description?, mod}[]` |
| `cmd.isIdle` | `() => boolean` |
| `cmd.shutdown` | `() => void` |
| `cmd.getAllTools` / `getActiveTools` | `() => readonly string[]` |
| `cmd.getToolInfo` | `() => readonly {name, description, readOnly, active}[]` |
| `cmd.setActiveTools` | `(names: readonly string[]) => void` |
| `cmd.use` | `(mod, name) => fn \| undefined` |
| `cmd.state.get` / `set` / `subscribe` | `(key) => T \| undefined` / `(key, value) => void` / `(key, listener) => Disposable` |
| `cmd.store.get` / `set` / `delete` | `(key) => T \| undefined` / `(key, value) => Promise<void>` / `(key) => Promise<void>` |
| `cmd.clock.every` / `after` | `(ms, callback) => Disposable` |
| `cmd.model.complete` | `({prompt, system?, model?, maxOutputTokens?, signal?}) => Promise<ModModelCompleteResult>` |
| `cmd.prompt.submit` | `(text) => void` |
| `cmd.ui.copy` | `(text) => Promise<ModCopyResult>` |
| `cmd.audio.play` | `({file, timeoutMs?}) => Promise<ModAudioResult>` |
| `cmd.audio.bell` | `() => ModAudioResult` |

Details:

- `cmd.ui` - `notify` (a `notice` feed row), `confirm` / `select` / `input` (the Interaction question modal in the TUI; deterministic defaults headless: false/undefined), `setStatus`, `widget`, `refreshWidgets`, `pane` + `openPane(id, {focus?})` / `closePane`, `toast`, `override`, `setTitle`. The full dialog/status/widget/override contract is in [UI surface](./ui.md#ui-surface).
- `cmd.queueMessage({content, deliverAs})` - `steer` lands after the current tool batch (behind any queued user messages in the same poll), `follow-up` only when the run would stop (ahead of continuation nudges, behind queued user input). Queued messages steer a run that is already going; they never START one.
- `cmd.sendUserMessage(content, {deliverAs})` - a REAL user message: echoed in the feed like typed input and, when the agent is idle, starting a turn right away. While a run is going, `steer` (default) queues it behind the active turn exactly as typing would, and `follow-up` holds it until the run would stop. Headless there is no submit path, so it falls back to `queueMessage` with the same `deliverAs`.
- `cmd.getSessionName()` / `getModel()` / `getEffort()` - the live values behind the setters; `undefined` before a session binds.
- `cmd.getContextUsage()` - `{tokens, contextWindow, percent}` for the bound session: `tokens` and `percent` are `null` until the first model call has measured the window (never a misleading 0%).
- `cmd.getCommands()` - every slash command mods registered on this host (`{name, description, mod}`), so a mod can discover siblings or avoid a taken name. Built-in commands are host-owned and not listed.
- `cmd.isIdle()` - `false` while an agent run is in flight on the bound harness (`run_start` … `run_end`), `true` otherwise and pre-bind.
- `cmd.shutdown()` - asks the interactive host to exit once the current turn settles (the same path as `/exit`). Headless: no-op - the print run ends on its own.
- `cmd.getToolInfo()` - the registered tools with `description`, `readOnly`, and `active` (per the mod-managed filter) - the descriptive counterpart of `getAllTools()`'s bare names.
- `cmd.session` - the `ModSessionApi` persistence seam (appendCustomEntry / appendCustomMessageEntry / getCustomEntries), undefined until bound. See [ModContext.session - the mods' persistence surface](./hooks-and-events.md#mod-context-session-saved-mod-data).
- `cmd.showEntry(customType, data)` - render a custom entry into the live feed through the renderer registered for that type (unrendered types pretty-print as JSON). The TUI wires the sink; headless runs drop entries. Pair with `cmd.session.appendCustomEntry` when the data should also persist.
- `cmd.sessions` - live session controls: `compact()`, `tree()` (the session branch tree as stable `{id, label, children}` nodes), `leafId()`, `navigateTree({targetId, summarize?, customInstructions?})`, and `setLabel({targetId, label})`. These read live harness state, so unlike the buffered setters they throw with a clear message when no session is bound yet.
- `cmd.exec({command, args})` - run a process through the harness Runtime (args are shell-quoted).
- `cmd.process.spawn({command, args, onOutput})` - the same command line as `cmd.exec`, but every stdout/stderr chunk reaches `onOutput(chunk, stream)` as the process produces it (`stream` is `'stdout'` or `'stderr'`), so a mod can show progress, tail a log, or react to a line without waiting for the exit. Resolves `{code}` when the process exits; aborting `signal` kills the process tree and rejects. A throwing `onOutput` becomes `mod_error {hook: 'on:process'}` and the process keeps running. Output is not buffered for you: keep what you need from the chunks.
- `cmd.getAllTools()` / `cmd.getActiveTools()` / `cmd.setActiveTools(names)` - a mod-managed tool filter: disabled tools vanish from the model's schemas and refuse execution.
- `cmd.events` - a tiny cross-mod pub/sub bus (`emit` / `on`).
- `cmd.state` - values the host holds for the session, namespaced per mod. They survive a hot reload (module variables start over), and `set` repaints every widget and pane, so a drawing that reads state is always current. `subscribe(key, listener)` hears this mod's writes to that key.
- `cmd.store` - values kept across sessions, one JSON file per mod. `get` is synchronous (the file is read before the factory runs); `set` and `delete` write through.
- `cmd.clock.every(ms, fn)` / `after(ms, fn)` - timers owned by the mod: cancelled by their `Disposable`, and all of them when the mod reloads. They never hold the process open, and a throwing callback becomes `mod_error` while the timer keeps its schedule.
- `cmd.model.complete({prompt})` - one text completion on the session's model client, with no transcript and no tools, billed and attributed like the session. It always resolves: `{isAnswered: true, text, model}` or `{isAnswered: false, reason: 'unavailable' | 'error' | 'aborted'}` (unavailable before a session binds).
- `cmd.prompt.submit(text)` - submit a prompt as if typed: in the TUI it starts a turn once the session is idle and queues behind a running one. Headless, it rides the follow-up queue.
- `cmd.ui.copy(text)` - copy text to the user's clipboard with the same helper `/copy` uses (the terminal over SSH; `isConfirmed: false` then). See [Clipboard and sound](./ui.md#clipboard-and-sound).
- `cmd.audio.play({file})` / `cmd.audio.bell()` - play a sound file shipped with the mod, or ring the terminal bell. See [Clipboard and sound](./ui.md#clipboard-and-sound).

## `ModHooks`: hooks that change behavior

Every hook is optional, and hooks from several `cmd.hooks()` calls compose.

`transformContext`, `appendSystemPrompt`, `transformSystemPrompt`, `transformMessage`, `transformTextDelta`, `beforeModelRequest`, `beforeToolCall`, `afterToolCall`, `onTurnStart`, `onTurnEnd`, `shouldStopAfterTurn`, `prepareNextTurn`, `onRunEnd`, `onStop`, plus the host-level `transformInput`, `onPermissionRequest`, `onSessionStart`, and `onSessionEnd`.

- `beforeToolCall` returns `{block?, input?, additionalContext?, terminate?, result?}`. `result` answers the call without running the tool.
- `beforeModelRequest` returns `{model?}` for one request.
- `transformSystemPrompt` returns the full system prompt to send.
- `transformMessage` returns the message the transcript keeps.
- `transformTextDelta` returns the answer chunk to show (synchronously), or `''` to drop or hold it back.
- `onPermissionRequest` returns `'allow' | 'deny' | undefined`.
- `afterToolCall` receives an `isError` param (PostToolUse vs PostToolUseFailure) and returns `{content?, isError?, additionalContext?, terminate?, modState?}`.
- `onStop` receives `{state, stopReason, turnNumber, lastAssistantText}` and returns `{continue?, reason?}`.
- `transformInput` returns `{action:'continue'} \| {action:'transform', text} \| {action:'handled', message?}`.
- `onSessionStart`/`onSessionEnd` receive `{source}` / `{reason}`.

The per-hook contracts, ordering guarantees, and error policy are in [the hook contracts](./hooks-and-events.md#the-hook-contracts).

- `transformInput({text})` intercepts typed user prompts before they reach the model (the mods' **UserPromptSubmit** hook): return `{action: 'transform', text}` to rewrite (handlers chain - the next sees the rewrite), `{action: 'handled', message?}` to consume the prompt entirely (an optional info row renders in its place), or `undefined`/`{action: 'continue'}` to pass through. Only real typed input is intercepted - automated turns, meta messages, image-carrying prompts, and slash commands never route through it; a throwing handler is skipped (`mod_error {hook: 'transformInput'}`), never a swallowed prompt. It lives in `hooks` because it MUTATES what the agent sees.
- `onStop({state, stopReason, turnNumber, lastAssistantText})` is the **Stop** hook - return `{continue: true, reason?}` to force a run that would otherwise finish to keep going (the reason rides an automated turn). Fires only on natural completion, any-mod wins, and the loop caps consecutive continuations.
- `onPermissionRequest({toolName, input, description, isSafetyPrompt})` answers a permission prompt before the person sees it. It fires only where the engine would ask a human, so deny rules, plan mode, and dont-ask have already decided everything they cover. Every hook is asked, and **deny wins**: any `'deny'` answers the prompt, and `'allow'` holds only when no hook denies, so a mod that blocks something cannot be overridden by another that allows it. A throwing hook is skipped (`mod_error`). On a safety-forced prompt (`isSafetyPrompt`: a sensitive write, a risky command) `'deny'` works but `'allow'` is ignored and the person is asked.
- `onSessionStart({source})` / `onSessionEnd({reason})` are the once-per-session **SessionStart** / **SessionEnd** hooks - fired when the host binds to / tears down a session (`source: 'startup' | 'resume' | 'reload'`, `reason: 'shutdown' | 'replaced' | 'reload'`). `reload` is this mod's own hot reload, in the same session: the old code ends with it and the new code starts with it. Act through the mod's captured `cmd`; they run fire-and-forget (a throw becomes `mod_error`), so a session hook never blocks bind/dispose. Pure observation is also available via `cmd.on('session_start' | 'session_shutdown')` - these named hooks add the typed metadata.

## `on` event types

Any `AgentEvent['type']` - including `run_start`, `run_end`, `turn_start`, `turn_end`, `model_request_start`, `model_request_end`, `tool_running`, `tool_completed`, `tool_errored`, `subagent_start`, `subagent_stop`, `subagent_progress`, `compaction_start`, `compaction_done`, `notice`, `session_titled`, `permission_mode_changed`, `config_setting_changed`, `mod_error` - plus the two host lifecycle events `session_start` / `session_shutdown`. (`subagent_start`/`subagent_stop` are SubagentStart/Stop; `compaction_start`/`compaction_done` are Pre/PostCompact; `notice` is Notification.) The full payload catalog is in [the AgentEvent catalog](./hooks-and-events.md#agent-event-catalog).
