command-code 1.93.1 → 1.93.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +7 -1
- package/dist/bundled/agent-browser/SKILL.md +73 -0
- package/dist/bundled/command-code-knowledge/SKILL.md +68 -0
- package/dist/bundled/command-code-knowledge/live-models.ts +284 -0
- package/dist/bundled/command-code-knowledge/reference/byok.md +389 -0
- package/dist/bundled/command-code-knowledge/reference/custom-agents.md +341 -0
- package/dist/bundled/command-code-knowledge/reference/custom-slash-commands.md +423 -0
- package/dist/bundled/command-code-knowledge/reference/headless.md +381 -0
- package/dist/bundled/command-code-knowledge/reference/hooks.md +1107 -0
- package/dist/bundled/command-code-knowledge/reference/mcp.md +648 -0
- package/dist/bundled/command-code-knowledge/reference/memory.md +137 -0
- package/dist/bundled/command-code-knowledge/reference/models.md +145 -0
- package/dist/bundled/command-code-knowledge/reference/permissions.md +486 -0
- package/dist/bundled/command-code-knowledge/reference/plan-mode.md +283 -0
- package/dist/bundled/command-code-knowledge/reference/plans.md +16 -0
- package/dist/bundled/command-code-knowledge/reference/product-help.md +490 -0
- package/dist/bundled/command-code-knowledge/reference/sessions.md +377 -0
- package/dist/bundled/command-code-knowledge/reference/skills.md +1009 -0
- package/dist/bundled/command-code-knowledge/reference/tools.md +522 -0
- package/dist/bundled/config/SKILL.md +18 -0
- package/dist/bundled/config/references/permissions.md +27 -0
- package/dist/bundled/config/references/settings.md +50 -0
- package/dist/bundled/design/SKILL.md +448 -0
- package/dist/bundled/design/references/accessibility.md +404 -0
- package/dist/bundled/design/references/border.md +161 -0
- package/dist/bundled/design/references/button.md +192 -0
- package/dist/bundled/design/references/checkup.md +164 -0
- package/dist/bundled/design/references/color.md +245 -0
- package/dist/bundled/design/references/create.md +291 -0
- package/dist/bundled/design/references/design-html.md +227 -0
- package/dist/bundled/design/references/deslop.md +285 -0
- package/dist/bundled/design/references/finish.md +156 -0
- package/dist/bundled/design/references/interaction.md +186 -0
- package/dist/bundled/design/references/layout.md +216 -0
- package/dist/bundled/design/references/media.md +112 -0
- package/dist/bundled/design/references/motion.md +237 -0
- package/dist/bundled/design/references/redesign.md +197 -0
- package/dist/bundled/design/references/refine.md +193 -0
- package/dist/bundled/design/references/reflexes.md +132 -0
- package/dist/bundled/design/references/relayout.md +207 -0
- package/dist/bundled/design/references/report-html.md +235 -0
- package/dist/bundled/design/references/responsive.md +233 -0
- package/dist/bundled/design/references/review.md +164 -0
- package/dist/bundled/design/references/setup.md +119 -0
- package/dist/bundled/design/references/severity.md +111 -0
- package/dist/bundled/design/references/shadow.md +164 -0
- package/dist/bundled/design/references/smell.md +213 -0
- package/dist/bundled/design/references/style-3d.md +23 -0
- package/dist/bundled/design/references/style-bento.md +21 -0
- package/dist/bundled/design/references/style-editorial.md +23 -0
- package/dist/bundled/design/references/style-futuristic.md +21 -0
- package/dist/bundled/design/references/style-glassmorphism.md +52 -0
- package/dist/bundled/design/references/style-maximalism.md +20 -0
- package/dist/bundled/design/references/style-minimalism.md +21 -0
- package/dist/bundled/design/references/style-neo-brutalism.md +21 -0
- package/dist/bundled/design/references/style-retro-futurism.md +21 -0
- package/dist/bundled/design/references/style-swiss.md +20 -0
- package/dist/bundled/design/references/style.md +77 -0
- package/dist/bundled/design/references/surface.md +163 -0
- package/dist/bundled/design/references/system.md +73 -0
- package/dist/bundled/design/references/typeset.md +210 -0
- package/dist/bundled/design/references/variants.md +193 -0
- package/dist/bundled/design/references/voice.md +184 -0
- package/dist/bundled/design/references/writing.md +174 -0
- package/dist/bundled/design/scripts/check/color.mjs +213 -0
- package/dist/bundled/design/scripts/check/contrast.mjs +141 -0
- package/dist/bundled/design/scripts/check/css.mjs +223 -0
- package/dist/bundled/design/scripts/check/named-colors.mjs +152 -0
- package/dist/bundled/design/scripts/check/pair.mjs +61 -0
- package/dist/bundled/design/scripts/check/preview.mjs +27 -0
- package/dist/bundled/design/scripts/check/reflexes.mjs +257 -0
- package/dist/bundled/design/scripts/check/sources.mjs +237 -0
- package/dist/bundled/design/scripts/check.mjs +165 -0
- package/dist/bundled/loop/SKILL.md +16 -0
- package/dist/bundled/mod-builder/SKILL.md +135 -0
- package/dist/bundled/mod-builder/examples/block-dangerous-commands.ts +41 -0
- package/dist/bundled/mod-builder/examples/custom-entry-renderer.ts +32 -0
- package/dist/bundled/mod-builder/examples/custom-tool.ts +53 -0
- package/dist/bundled/mod-builder/examples/flags-and-options.ts +29 -0
- package/dist/bundled/mod-builder/examples/input-shortcuts.ts +41 -0
- package/dist/bundled/mod-builder/examples/kitchen-sink.ts +129 -0
- package/dist/bundled/mod-builder/examples/lifecycle-hooks.ts +64 -0
- package/dist/bundled/mod-builder/examples/model-router.ts +43 -0
- package/dist/bundled/mod-builder/examples/observe-events.ts +30 -0
- package/dist/bundled/mod-builder/examples/pane-and-buttons.ts +60 -0
- package/dist/bundled/mod-builder/examples/pane-form.ts +68 -0
- package/dist/bundled/mod-builder/examples/permission-policy.ts +34 -0
- package/dist/bundled/mod-builder/examples/redact-secrets.ts +46 -0
- package/dist/bundled/mod-builder/examples/slash-command.ts +33 -0
- package/dist/bundled/mod-builder/examples/spinner-count.ts +47 -0
- package/dist/bundled/mod-builder/examples/stream-filter.ts +70 -0
- package/dist/bundled/mod-builder/reference/api.md +140 -0
- package/dist/bundled/mod-builder/reference/hooks-and-events.md +347 -0
- package/dist/bundled/mod-builder/reference/overview.md +271 -0
- package/dist/bundled/mod-builder/reference/packaging.md +187 -0
- package/dist/bundled/mod-builder/reference/ui.md +253 -0
- package/dist/bundled/mod-builder/reference/verify.md +67 -0
- package/dist/bundled/skill-builder/SKILL.md +104 -0
- package/dist/cli.mjs +16 -0
- package/dist/index.mjs +2 -0
- package/package.json +1 -1
- package/vsix/commandcode-vscode.vsix +0 -0
|
@@ -0,0 +1,347 @@
|
|
|
1
|
+
<!-- Generated from the Command Code docs: https://commandcode.ai/docs -->
|
|
2
|
+
|
|
3
|
+
# Hooks and events
|
|
4
|
+
|
|
5
|
+
The harness's extension seam. A **mod** is a plain object of lifecycle hooks that mutates agent state or changes loop decisions. Pure observers (UI, telemetry, loggers) are **not** mods - they subscribe to the `AgentEvent` stream. Hooks change behavior; subscribers watch it. In a loadable mod, `cmd.hooks({...})` registers the hooks and `cmd.on(event, ...)` subscribes to events.
|
|
6
|
+
|
|
7
|
+
A mod may also contribute **tools**, and every hook receives a **`ModContext`** (`{emit, signal, cwd, session?}`) as an extra last argument, so a mod can raise its own events and persist durable state without extra plumbing.
|
|
8
|
+
|
|
9
|
+
## Where each hook fires
|
|
10
|
+
|
|
11
|
+
One `run()` = one user turn → many model turns ("rounds"). The loop below is the agent loop, verbatim in ordering; mod hooks are marked `◆`, events `→`.
|
|
12
|
+
|
|
13
|
+
```bash
|
|
14
|
+
run({state, userInput?, config})
|
|
15
|
+
fork AbortController; working := state (+ user message when userInput given)
|
|
16
|
+
ctx := {emit, signal, cwd, session} - built ONCE per run,
|
|
17
|
+
passed as the LAST argument to every ◆ hook below
|
|
18
|
+
→ run_start {sessionId}
|
|
19
|
+
poll getSteeringMessages once (catch pre-run queued input)
|
|
20
|
+
loop:
|
|
21
|
+
abort check ──────────────────────────────────► stop: interrupted (→ interrupted)
|
|
22
|
+
◆ onTurnStart (each mod, in order; returns new state)
|
|
23
|
+
→ turn_start {turnNumber}
|
|
24
|
+
read live permission mode ONCE - pinned for this round
|
|
25
|
+
◆ beforeModelRequest (each mod; later wins) → the model for THIS request; the
|
|
26
|
+
deferred-tools prompt and tool list below are built for it
|
|
27
|
+
resolve systemPrompt (string | builder({sessionId, state, permissionMode}))
|
|
28
|
+
◆ appendSystemPrompt (each mod; non-empty returns joined with '\n\n', in
|
|
29
|
+
registration order, and appended AFTER the base prompt)
|
|
30
|
+
◆ transformSystemPrompt (each mod; the FULL prompt threaded mod→mod)
|
|
31
|
+
◆ transformContext (each mod; messages threaded mod→mod; result is EPHEMERAL -
|
|
32
|
+
used for this call only, never written back to state.messages)
|
|
33
|
+
prepareForSend (core wire-validity pass: orphan heal, merge, strip meta)
|
|
34
|
+
→ message_start
|
|
35
|
+
→ model_request_start {model}
|
|
36
|
+
modelClient.complete(...) (streams → text_delta / thinking_* /
|
|
37
|
+
message_update / continuation_recovery /
|
|
38
|
+
tool_input_coerced; retry → api_retry)
|
|
39
|
+
◆ transformTextDelta on every streamed text chunk (each mod, threaded;
|
|
40
|
+
sync), BEFORE its → text_delta; a retry starts the chunk log over
|
|
41
|
+
→ model_request_end {model, usage, stopReason}
|
|
42
|
+
◆ transformTextDelta {delta: '', done: true} (flush; output → text_delta)
|
|
43
|
+
assistant text := the rewritten chunks, joined, per text block
|
|
44
|
+
→ message_end {content} (the rewritten content)
|
|
45
|
+
◆ transformMessage on every message before it is committed
|
|
46
|
+
(user input, assistant reply, tool results, steering, follow-ups)
|
|
47
|
+
working += assistant message (provider-executed blocks filtered out)
|
|
48
|
+
if client tool calls:
|
|
49
|
+
runTools(...) (see tool-dispatch order below)
|
|
50
|
+
working += tool-results user message
|
|
51
|
+
working := setModState(...) for every afterToolCall `modState`
|
|
52
|
+
contribution across the batch (BEFORE onTurnEnd runs)
|
|
53
|
+
any deny ────────────────────────► pendingStop: permission_denied
|
|
54
|
+
any terminate ───────────────────► pendingStop: terminate
|
|
55
|
+
else poll getSteeringMessages → append (source 'steering')
|
|
56
|
+
◆ onTurnEnd (each mod; receives THIS turn's usage; returns new state)
|
|
57
|
+
→ turn_end {turnNumber, hadToolCalls, usage}
|
|
58
|
+
onCommit(working) ← the durability boundary
|
|
59
|
+
pendingStop? ──────────────────────► stop
|
|
60
|
+
◆ shouldStopAfterTurn (any true) ──► stop: stop_hook
|
|
61
|
+
turnNumber ≥ maxTurns ─────────────► stop: max_turns
|
|
62
|
+
if no tool calls:
|
|
63
|
+
no follow-up wanted ─────────────► ◆ onStop (any continue → keep going)
|
|
64
|
+
else stop: end_turn
|
|
65
|
+
◆ prepareNextTurn (merged; later mods win) → may swap model / effort
|
|
66
|
+
◆ onRunEnd (each mod, awaited)
|
|
67
|
+
→ run_end {result}
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
### Tool-dispatch order
|
|
71
|
+
|
|
72
|
+
```bash
|
|
73
|
+
for each tool_use: → tool_queued {toolCallId, toolName, input} ← ALWAYS the original input
|
|
74
|
+
phase 1 - permissions (always sequential):
|
|
75
|
+
permissions.generateDescription (5s timeout → null)
|
|
76
|
+
permissions.check({toolName, input, description, permissionMode})
|
|
77
|
+
throw ⇒ deny (fail closed)
|
|
78
|
+
deny → tool_denied; batch aborted: every call gets a tool_result,
|
|
79
|
+
run stops with permission_denied AFTER the turn commits
|
|
80
|
+
phase 2 - execution (sequential, or parallel when config.toolExecution='parallel'):
|
|
81
|
+
◆ beforeToolCall (each mod, in order; `input` rewrites CHAIN mod→mod;
|
|
82
|
+
execution uses the LAST mod's input; a mod may also set `terminate`)
|
|
83
|
+
block ⇒ → tool_hook_blocked {hookOutput}; the block reason becomes the
|
|
84
|
+
tool_result text; NO tool_running / tool_completed / tool_errored fires
|
|
85
|
+
result ⇒ the tool does NOT run; the answer is its (successful) output
|
|
86
|
+
→ tool_running {toolCallId, toolName, description}
|
|
87
|
+
toolRunner.execute({toolName, input: <possibly rewritten>, signal, onUpdate})
|
|
88
|
+
◆ afterToolCall (each mod, in order; sees current content, may replace it,
|
|
89
|
+
append `additionalContext`, flip `isError`, set `terminate`, or persist
|
|
90
|
+
`modState`)
|
|
91
|
+
beforeToolCall additionalContext strings appended to the final content
|
|
92
|
+
→ tool_completed {result} (or → tool_errored {error})
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
### Ordering guarantees mod authors can rely on
|
|
96
|
+
|
|
97
|
+
- Every hook receives `ModContext` (`{emit, signal, cwd, session?}`) as its LAST argument. It's declared optional on every hook signature, so a hook that only declares the params object keeps compiling and running unchanged; the core always supplies a real object at runtime.
|
|
98
|
+
- `beforeToolCall` completes (for every mod) **before** `tool_running` is emitted. Its `input` rewrites chain across mods, but the `tool_queued` event fired with the ORIGINAL input before any hook ran and is never re-emitted - display always shows what the model asked for, only execution sees the rewrite.
|
|
99
|
+
- `afterToolCall` completes **before** `tool_completed` / `tool_errored` is emitted - the terminal event carries the post-hook content, and its `isError` (when set) decides which of the two fires, independent of whether execution itself threw.
|
|
100
|
+
- `afterToolCall`'s `modState` is committed right after the batch's tool-result message is appended - BEFORE `onTurnEnd` runs, so `onTurnEnd` sees it.
|
|
101
|
+
- `onTurnStart` precedes `turn_start`; `onTurnEnd` precedes `turn_end` and `onCommit`.
|
|
102
|
+
- `onCommit` fires once per completed turn with the full serializable state.
|
|
103
|
+
- `shouldStopAfterTurn` is evaluated **after** the turn commits, so a stop_hook never loses the turn that triggered it.
|
|
104
|
+
- `prepareNextTurn` runs only when the loop actually continues (never on a stopping turn).
|
|
105
|
+
- `onRunEnd` is **awaited** before the `run_end` event - it is the place for must-complete work (flush, trigger learning); event subscribers must never be.
|
|
106
|
+
- Mods run in **registration order** in every phase; the built-ins come first and caller mods last (they see post-compaction context and post-hook tool results).
|
|
107
|
+
- Hooks **never throw** upward: the runner catches per-mod, per-hook. A failing `transformContext` leaves messages unchanged; a failing `onTurnStart`/`onTurnEnd` keeps the prior state; a failing `shouldStopAfterTurn` means "don't stop"; failing tool hooks are skipped. Every catch site ALSO emits a `mod_error {modId, hook, error}` event before falling back to its no-crash default - the decision the loop makes is unchanged, but the degradation is never silent.
|
|
108
|
+
|
|
109
|
+
## The hook contracts
|
|
110
|
+
|
|
111
|
+
### `transformContext({messages, state, signal?}, ctx?) → messages`
|
|
112
|
+
|
|
113
|
+
Fires once per round, after `appendSystemPrompt`, before `prepareForSend`. Messages are threaded through every mod in order - each receives the previous mod's output. **The result is used for this model call only and never written back to `state.messages`**: the durable log is untouched (compaction relies on this - the recorded transcript stays complete). Return the input array unchanged (same reference) to signal "no change".
|
|
114
|
+
|
|
115
|
+
### `shouldStopAfterTurn({state, turnNumber}, ctx?) → boolean`
|
|
116
|
+
|
|
117
|
+
Fires after the turn commits. **Any** mod returning `true` ends the run with `stopReason: 'stop_hook'` - first true short-circuits. This is *early stop* (goal budget spent); it is the opposite of the Stop hook forcing continuation.
|
|
118
|
+
|
|
119
|
+
### `prepareNextTurn({state, turnNumber}, ctx?) → {model?, effort?} | undefined`
|
|
120
|
+
|
|
121
|
+
Fires at the bottom of a continuing round. Results are merged across mods - later mods override earlier ones per field. A returned `model`/`effort` applies from the **next** model call onward (`config` is never mutated). `effort` is tri-state: a `ThinkingEffort` sets it, `null` **resets** it to the incoming model's own default, and omitting the field leaves the current effort unchanged. Send `null` (not an omitted field) when swapping to a model that should run at its own default - otherwise the run keeps the outgoing model's effort.
|
|
122
|
+
|
|
123
|
+
### `appendSystemPrompt({state}, ctx?) → string | undefined`
|
|
124
|
+
|
|
125
|
+
Fires once per round, right after the round's base `systemPrompt` resolves and before `transformContext`. Every mod's non-empty return is joined with `'\n\n'`, in registration order, and appended AFTER the base prompt. May return a plain string OR a Promise. **Must be byte-stable across rounds for the same durable inputs** - the provider's prompt-prefix cache keys off the system prompt's bytes, so a value that changes turn-to-turn without a corresponding `state`/`modState` change busts the cache every round. Compute once, store in `modState`, read it back.
|
|
126
|
+
|
|
127
|
+
### `beforeToolCall({toolCallId, toolName, input, state}, ctx?) → {block?, additionalContext?, input?, terminate?} | undefined`
|
|
128
|
+
|
|
129
|
+
Fires per tool call, after the permission check passed, before execution.
|
|
130
|
+
|
|
131
|
+
- `block: true` - the tool does not run. The core emits `tool_hook_blocked` with `hookOutput` = your `additionalContext` (or `'Blocked by a pre-tool hook.'`), and that same text becomes the tool_result the model sees. Later mods' `beforeToolCall` for this call do not run. No `tool_running`/`tool_completed`/`tool_errored` is emitted for a blocked call.
|
|
132
|
+
- `additionalContext` (without `block`) - collected across mods and appended as extra text blocks to the tool_result **after** execution and after `afterToolCall` overrides.
|
|
133
|
+
- `input` - rewrites the input the tool actually executes with. **Chained across mods**: the next mod's `input` param is YOUR rewrite, not the original.
|
|
134
|
+
- `terminate: true` - stops the run after this tool batch finishes. ANY-semantics (one hook, on one call, in one batch, is enough). Combines with `block` on the same return value.
|
|
135
|
+
- `undefined` - no opinion.
|
|
136
|
+
|
|
137
|
+
- `result` - answer the call WITHOUT running the tool: this content is the tool's successful output (unlike `block`, which is an error). Later mods' `beforeToolCall` for this call do not run; `afterToolCall` still does, so a post-hook sees the answer like any real result. `block` wins when both are set.
|
|
138
|
+
|
|
139
|
+
### `beforeModelRequest({state, turnNumber, model}, ctx?) → {model?} | undefined`
|
|
140
|
+
|
|
141
|
+
Fires once per model request, at the start of the round, before the round's prompt, context, and tools are built. The tool list and the deferred-tools prompt are then built for the model the request goes to, so a model that cannot load deferred tools gets every tool inline, the same as picking it with `/model`. A returned `model` sends **this request only** to that model; the next request goes back to the run's model (use `prepareNextTurn` to switch for the rest of the run). Later mods win. A swapped request drops the run's explicit BYOK route, which belongs to the run's model. `model_request_start` / `model_request_end` report the model the request actually went to.
|
|
142
|
+
|
|
143
|
+
The other hooks of the round have not run yet, so a value one of them stores is from the previous round. To route on context size, measure `state.messages` inside `beforeModelRequest` itself.
|
|
144
|
+
|
|
145
|
+
### `transformSystemPrompt({system, state}, ctx?) → string`
|
|
146
|
+
|
|
147
|
+
Fires once per round, after `appendSystemPrompt`: receives the round's **full** system prompt (base + every append) and returns the prompt to send, so a mod can replace, edit, or drop parts of it. Threaded mod to mod. Returning the input unchanged keeps the structured, cache-friendly sections; any change sends one flat string, so keep the result byte-stable across rounds or the prompt-prefix cache misses every turn.
|
|
148
|
+
|
|
149
|
+
### `transformMessage({message, state}, ctx?) → AgentMessage`
|
|
150
|
+
|
|
151
|
+
Fires for every message the loop commits: the person's input, each model reply, each tool-result batch, steering and follow-up messages. The returned message is what the transcript stores **and** what every later request sends, which makes it the place for secret redaction and PII masking. Threaded mod to mod. The role and every `tool_use` / `tool_result` id must survive: a rewrite that changes them is rejected with `mod_error {hook: 'transformMessage'}` and the previous message is kept. Live streaming events (`text_delta`, `message_end`) still show the model's raw output; the transcript holds the rewrite. To change what is shown as well, use `transformTextDelta`.
|
|
152
|
+
|
|
153
|
+
### `transformTextDelta({delta, done, turnNumber, attempt, state}, ctx?) → string`
|
|
154
|
+
|
|
155
|
+
Fires for every chunk of the model's answer text as it streams, **before** the `text_delta` event for it goes out. Return the chunk to show (rewritten or as is), or `''` to drop it. Threaded mod to mod; a dropped chunk stops there, so later mods never see it. What the feed shows and what the transcript keeps are the same text: the committed assistant message (and `message_end`, and the live `message_update`) carries exactly the rewritten chunks, joined, each in the text block it streamed into. Thinking and tool calls are untouched.
|
|
156
|
+
|
|
157
|
+
- **Synchronous and fast.** It runs inside the model stream. A hook that throws, or returns a promise or a non-string, is skipped for that chunk with `mod_error {hook: 'transformTextDelta'}`, and the chunk passes on as the previous mod handed it.
|
|
158
|
+
- **The final flush.** When the response is complete, every mod is called once more with `{delta: '', done: true}`. Return anything you held back (the start of a key split across two chunks) and it streams as one last `text_delta` and lands at the end of the last text block.
|
|
159
|
+
- **Retries.** `attempt` counts this request's attempts from 0. A mid-stream retry throws the abandoned attempt's chunks away (the feed marks the seam with `stream_restart`), so a mod that keeps state across chunks should start over when `turnNumber` or `attempt` changes.
|
|
160
|
+
- **Non-streaming clients.** A response that arrived with no text deltas still goes through the hook, one chunk per text block, with no `text_delta` events invented for it.
|
|
161
|
+
- Runs **before** `transformMessage`, which still sees the (rewritten) assistant message on commit.
|
|
162
|
+
|
|
163
|
+
### `afterToolCall({toolCallId, toolName, input, result, isError, state}, ctx?) → {content?, terminate?, additionalContext?, isError?, modState?} | undefined`
|
|
164
|
+
|
|
165
|
+
Fires per tool call after execution (also after an execution error - `result` is then the error text content). `input` is the FINAL input the tool actually ran with (after any `beforeToolCall` rewrites).
|
|
166
|
+
|
|
167
|
+
- `isError` (param) - whether the tool's OWN execution failed, read before any hook override and threaded across mods like `result`. This is the **PostToolUse vs PostToolUseFailure** distinction: a hook can branch on `isError` to react only to failures. It is the INPUT signal; the returned `isError` field below is the OUTPUT override that selects the terminal event.
|
|
168
|
+
- `content` **replaces** the tool result the model will see (threaded mod→mod).
|
|
169
|
+
- `terminate: true` ends the run with `stopReason: 'terminate'` **after the whole batch finishes**.
|
|
170
|
+
- `additionalContext` - appended as a SEPARATE text block after `content` (and after any `beforeToolCall` additionalContext strings).
|
|
171
|
+
- `isError` - overrides whether the terminal event is `tool_completed` or `tool_errored`, independent of whether execution itself threw.
|
|
172
|
+
- `modState` - a `Record<string, unknown>` merged into `state.modState[mod.id]` right after the tool-result message commits - a full replace of that mod's slot, exactly like `setModState`. The durable-state channel for tool hooks: neither tool hook can return a whole `AgentState` the way `onTurnStart`/`onTurnEnd` can.
|
|
173
|
+
|
|
174
|
+
### `onTurnStart({state, turnNumber}, ctx?) → AgentState` / `onTurnEnd({state, turnNumber, hadToolCalls, usage}, ctx?) → AgentState`
|
|
175
|
+
|
|
176
|
+
The only hooks that can **persist state changes** unconditionally - they return the new `AgentState` (typically via `setModState`), which the loop threads onward and commits. `onTurnEnd`'s `usage` is *this turn's* token usage. Both fire every round, including the round that stops.
|
|
177
|
+
|
|
178
|
+
### `onRunEnd({state, result}, ctx?) → void`
|
|
179
|
+
|
|
180
|
+
Fires once, awaited, after the loop exits and before the `run_end` event. `state` is the final state; `result` carries `finalText`, `stopReason`, `turnCount`, accumulated `usage`. Cannot alter the result. This is the "must-complete work" hook (learning, flushes).
|
|
181
|
+
|
|
182
|
+
### `onStop({state, stopReason, turnNumber, lastAssistantText}, ctx?) → {continue?, reason?} | undefined`
|
|
183
|
+
|
|
184
|
+
The **Stop hook** - the mods' force-continue channel. Fires when a turn WOULD end the run **naturally** - the model returned no tool calls and no follow-up provider wants to continue. Returning `{continue: true}` keeps the run going: `reason` (or a neutral default) is appended as an automated `source: 'stop_hook'` user turn, so the model is told why it must keep working.
|
|
185
|
+
|
|
186
|
+
- **ANY** mod returning `continue` wins (first wins, short-circuits).
|
|
187
|
+
- Does **NOT** fire for hard stops (`max_turns`, `terminate`, `permission_denied`, `interrupted`).
|
|
188
|
+
- A follow-up provider (e.g. the continuation nudger) gets first say; `onStop` is consulted only when the provider declines.
|
|
189
|
+
- The loop caps consecutive stop-hook continuations at **8** - a hook that always says `continue` can't loop forever.
|
|
190
|
+
- Distinct from `shouldStopAfterTurn` (force EARLY stop) and `onRunEnd` (observe the stop): only `onStop` can push a finished run onward.
|
|
191
|
+
|
|
192
|
+
```ts
|
|
193
|
+
const persistUntilTestsPass = {
|
|
194
|
+
id: 'until-green',
|
|
195
|
+
onStop: async ({lastAssistantText}) => {
|
|
196
|
+
if (/all tests pass/i.test(lastAssistantText)) return {continue: false};
|
|
197
|
+
return {continue: true, reason: 'Tests are not green yet - keep going.'};
|
|
198
|
+
},
|
|
199
|
+
};
|
|
200
|
+
```
|
|
201
|
+
|
|
202
|
+
## `ModContext.session`: saved mod data
|
|
203
|
+
|
|
204
|
+
The harness's tree-format session store gives mods a durable, per-entry seam onto the SAME append-only file the transcript lives in. Available in a loadable mod as `cmd.session` and inside hooks as `ctx.session`. Two entry kinds:
|
|
205
|
+
|
|
206
|
+
- **`appendCustomEntry({customType, data?})`** - a `custom` tree entry. Mod-private data; **never** sent to the LLM, never rendered. Use it for durable bookkeeping a mod wants to survive resume (counters, cursors, cached decisions).
|
|
207
|
+
- **`appendCustomMessageEntry({customType, content, display, details?})`** - a `custom_message` tree entry. Content the model SHOULD see: it is projected as an ordinary `user` message on the NEXT turn (`display: true` also renders it in the TUI with distinct styling; `display: false` is context-only). The call returns `{entryId, message}` - a mod MUST fold `message` onto the `AgentState` it hands back from its hook for the model to see it that turn.
|
|
208
|
+
- **`getCustomEntries({customType})`** - reads back every `custom` entry this mod itself wrote (filtered by `customType`), in file order, over the ACTIVE branch's full entry list. The standard reload pattern: a mod with in-memory state seeds it from `getCustomEntries` at first `onTurnStart`.
|
|
209
|
+
|
|
210
|
+
```ts
|
|
211
|
+
const MOD_ID = 'turn-counter';
|
|
212
|
+
const CUSTOM_TYPE = 'turn-counter/count';
|
|
213
|
+
|
|
214
|
+
const mod = {
|
|
215
|
+
id: MOD_ID,
|
|
216
|
+
onTurnStart: async ({state}, ctx) => {
|
|
217
|
+
if (!ctx?.session) return state; // a bare unit-test config without a store
|
|
218
|
+
const priorCount = ctx.session.getCustomEntries({
|
|
219
|
+
customType: CUSTOM_TYPE,
|
|
220
|
+
}).length;
|
|
221
|
+
ctx.session.appendCustomEntry({customType: CUSTOM_TYPE, data: {count: priorCount + 1}});
|
|
222
|
+
return state;
|
|
223
|
+
},
|
|
224
|
+
};
|
|
225
|
+
```
|
|
226
|
+
|
|
227
|
+
`session` is absent (not merely empty) only for a bare unit-test config built without a durable store - every hook must treat `ctx.session` as possibly `undefined` and no-op gracefully. A `--no-session` run DOES populate `session` - entries still append and are readable for the lifetime of the process, they simply never touch disk.
|
|
228
|
+
|
|
229
|
+
## `modState` conventions
|
|
230
|
+
|
|
231
|
+
`AgentState.modState` is a `Readonly<Record<string, unknown>>` - one slot per mod, keyed by the mod's `id`:
|
|
232
|
+
|
|
233
|
+
```ts
|
|
234
|
+
const value = getModState<MyShape>({state, modId: 'my-mod'}); // undefined when unset
|
|
235
|
+
const next = setModState({state, modId: 'my-mod', value: {...}}); // fresh AgentState
|
|
236
|
+
```
|
|
237
|
+
|
|
238
|
+
- **Namespacing is by convention**: write only your own `id`'s slot.
|
|
239
|
+
- Values must be **JSON-serializable** - `modState` is persisted with the session and survives resume. Run-scoped/volatile data (budgets, locks, in-flight promises) belongs in the mod factory's closure instead.
|
|
240
|
+
- `onTurnStart`/`onTurnEnd` return the whole `AgentState` (typically via `setModState`). `afterToolCall` can also persist state via its `modState` return field. `beforeToolCall` has no state channel; a before-hook that needs to accumulate data stores it in the closure and flushes it via `afterToolCall`'s `modState` or `onTurnEnd`.
|
|
241
|
+
- Custom data never goes into `state.messages`: the message union is closed wire types. When a mod must put something in front of the model, it emits real messages via `transformContext` (or `appendCustomMessageEntry`).
|
|
242
|
+
|
|
243
|
+
## `AgentEvent` catalog
|
|
244
|
+
|
|
245
|
+
One sync sink, fan out with `createEventBus`. Payloads are snapshots - never live references.
|
|
246
|
+
|
|
247
|
+
| Event | Fires | Payload highlights |
|
|
248
|
+
|---|---|---|
|
|
249
|
+
| `run_start` / `run_end` | run boundaries | `sessionId` / `result` |
|
|
250
|
+
| `turn_start` / `turn_end` | round boundaries (after onTurnStart / onTurnEnd) | `turnNumber`; end adds `hadToolCalls`, this turn's `usage` |
|
|
251
|
+
| `message_start` | before each model call | - |
|
|
252
|
+
| `text_delta`, `thinking_start/delta/end` | streaming | deltas; `thinking_end` carries full text |
|
|
253
|
+
| `message_update` | streaming (ModelClient-accumulated) | whole partial assistant message incl. partial tool JSON |
|
|
254
|
+
| `message_end` | response complete | full assistant content |
|
|
255
|
+
| `model_request_start/end` | bracket the inference call | `model`; end adds `usage`, raw-preferred `stopReason` |
|
|
256
|
+
| `tool_queued` | per call, before permission checks | `input` - the ORIGINAL input, never the rewritten one |
|
|
257
|
+
| `tool_denied` | permission denied | - (batch then aborts) |
|
|
258
|
+
| `tool_hook_blocked` | a mod's beforeToolCall blocked | `hookOutput` - **terminal for that call**: no tool_running/completed/errored follows |
|
|
259
|
+
| `tool_running` | execution begins (after beforeToolCall) | `description` from permissions.generateDescription |
|
|
260
|
+
| `tool_update` | streaming tool progress | `partial` content |
|
|
261
|
+
| `tool_completed` / `tool_errored` | after afterToolCall | post-hook `result` / `error` text; `afterToolCall`'s `isError` can select which one fires |
|
|
262
|
+
| `tool_hooks` | emitted by the user-hooks mod, before the phase's terminal tool event | `phase: 'pre'\|'post'`, `lines`, `outcome` |
|
|
263
|
+
| `subagent_start` / `subagent_stop` | the `agent` tool brackets a nested sub-agent run | `toolCallId`, `subagentType`; stop adds `tokensUsed` |
|
|
264
|
+
| `subagent_progress` | per child tool call inside a running sub-agent | `toolCallId`, `subagentType`, `toolName`, `toolInput`, `tokensUsed` |
|
|
265
|
+
| `api_retry` | retry loop, after 3 silent attempts | `attempt`, `error`, `delayMs` |
|
|
266
|
+
| `compaction_start` / `compaction_done` | compaction mod | `tokensSaved` (done, only when > 0) |
|
|
267
|
+
| `notice` | user-facing info/warning | `level`, `message` |
|
|
268
|
+
| `skill_loaded` | a skill was activated by an explicit user `/name` invocation | `name` |
|
|
269
|
+
| `session_titled` | the auto-generated session title was persisted | `title` |
|
|
270
|
+
| `permission_mode_changed` | the effective permission mode changed (shift+tab, `/plan`, enter/exit plan tools) | `mode` |
|
|
271
|
+
| `config_setting_changed` | a setting changed through the `config` tool | `setting`, `value`, `previousValue?` |
|
|
272
|
+
| `continuation_recovery` | a turn was auto-continued (pause/empty/length/intent) | `kind`, `attempt`, `maxAttempts` |
|
|
273
|
+
| `tool_input_coerced` | ModelClient rescued malformed (array/null) tool input | `rawType`, `recovered` |
|
|
274
|
+
| `tool_input_repaired` | repair layer rewrote tool input pre-execution (fires whether or not the call then ran) | `rulesFired`, `hintCount`, `receivedKeys`, `repaired` |
|
|
275
|
+
| `mod_error` | a mod hook threw (any phase), or a mod tool collided with an existing tool | `modId`, `hook`, `error` |
|
|
276
|
+
| `interrupted` | abort observed | - |
|
|
277
|
+
| `run_error` | non-retryable failure | the raw `Error` |
|
|
278
|
+
|
|
279
|
+
## Example: a write quota mod
|
|
280
|
+
|
|
281
|
+
Blocks writes outside an allowlist, counts tool activity durably in modState, and reports at run end. Exercises the block channel, the closure-vs-modState split, and `onRunEnd`.
|
|
282
|
+
|
|
283
|
+
```ts
|
|
284
|
+
import type {AgentMod, AgentState} from '@commandcode/harness';
|
|
285
|
+
import {getModState, setModState} from '@commandcode/harness';
|
|
286
|
+
|
|
287
|
+
const MOD_ID = 'write-quota';
|
|
288
|
+
|
|
289
|
+
interface WriteQuotaState {
|
|
290
|
+
readonly writesThisSession: number; // durable - survives resume
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
export function createWriteQuotaMod(options: {
|
|
294
|
+
readonly allowedRoot: string;
|
|
295
|
+
readonly maxWrites: number;
|
|
296
|
+
readonly report: (summary: string) => void;
|
|
297
|
+
}): AgentMod {
|
|
298
|
+
// Run-scoped tally lives in the closure; flushed into modState at turn end
|
|
299
|
+
// (beforeToolCall cannot return state - see modState conventions).
|
|
300
|
+
let writesThisTurn = 0;
|
|
301
|
+
|
|
302
|
+
return {
|
|
303
|
+
id: MOD_ID,
|
|
304
|
+
|
|
305
|
+
beforeToolCall: async ({toolName, input, state}) => {
|
|
306
|
+
if (toolName !== 'write_file' && toolName !== 'edit_file') return undefined;
|
|
307
|
+
const path = typeof input.file_path === 'string' ? input.file_path : '';
|
|
308
|
+
if (!path.startsWith(options.allowedRoot)) {
|
|
309
|
+
// Block: this text becomes the tool_result the model sees, and the
|
|
310
|
+
// core emits tool_hook_blocked. The run continues - the model adapts.
|
|
311
|
+
return {
|
|
312
|
+
block: true,
|
|
313
|
+
additionalContext: `Writes outside ${options.allowedRoot} are not allowed.`,
|
|
314
|
+
};
|
|
315
|
+
}
|
|
316
|
+
const durable = getModState<WriteQuotaState>({state, modId: MOD_ID});
|
|
317
|
+
if ((durable?.writesThisSession ?? 0) + writesThisTurn >= options.maxWrites) {
|
|
318
|
+
return {block: true, additionalContext: 'Write quota exhausted for this session.'};
|
|
319
|
+
}
|
|
320
|
+
writesThisTurn += 1;
|
|
321
|
+
return undefined;
|
|
322
|
+
},
|
|
323
|
+
|
|
324
|
+
onTurnEnd: async ({state}) => {
|
|
325
|
+
if (writesThisTurn === 0) return state;
|
|
326
|
+
const durable = getModState<WriteQuotaState>({state, modId: MOD_ID});
|
|
327
|
+
const next: AgentState = setModState({
|
|
328
|
+
state,
|
|
329
|
+
modId: MOD_ID,
|
|
330
|
+
value: {writesThisSession: (durable?.writesThisSession ?? 0) + writesThisTurn},
|
|
331
|
+
});
|
|
332
|
+
writesThisTurn = 0;
|
|
333
|
+
return next; // committed via onCommit at the turn boundary
|
|
334
|
+
},
|
|
335
|
+
|
|
336
|
+
onRunEnd: async ({state, result}) => {
|
|
337
|
+
const durable = getModState<WriteQuotaState>({state, modId: MOD_ID});
|
|
338
|
+
options.report(
|
|
339
|
+
`run stopped (${result.stopReason}) after ${result.turnCount} turns; ` +
|
|
340
|
+
`${durable?.writesThisSession ?? 0} writes used`,
|
|
341
|
+
);
|
|
342
|
+
},
|
|
343
|
+
};
|
|
344
|
+
}
|
|
345
|
+
```
|
|
346
|
+
|
|
347
|
+
Wire it as a loadable mod (`cmd.hooks({...})` with the same handlers) - or, when embedding the harness, `createHarness({..., mods: [createWriteQuotaMod({...})]})`.
|
|
@@ -0,0 +1,271 @@
|
|
|
1
|
+
<!-- Generated from the Command Code docs: https://commandcode.ai/docs -->
|
|
2
|
+
|
|
3
|
+
# Mods
|
|
4
|
+
|
|
5
|
+
> **Experimental.** The `ModApi` is new and still taking shape. Surfaces and signatures can change as we learn from how mods get built - so pin what you ship, and tell us what's missing. Your feedback is what stabilizes it.
|
|
6
|
+
|
|
7
|
+
Mods are TypeScript packages that let you modify almost any behavior of Command Code. They're far more powerful than the plugin or extension APIs you'll find in other agents - though you can absolutely use one to build a plugin or an extension. Each mod is written against the `ModApi`: a plain TypeScript file that Command Code discovers on disk, loads at startup, and compiles onto its agent loop. One file can add tools the model calls, slash commands, mutating lifecycle hooks, event observers, typed-input interception, permission answers, transcript redaction, per-request model routing, panes and widgets with buttons, toasts, sub-agent types, configurable flags, and model providers. Mods hot-reload when you save them. Command Code's own built-in features - providers, session titling, the update notice - are built as mods against this very same API. If Command Code can do it, a mod can change it.
|
|
8
|
+
|
|
9
|
+
A loadable mod IS an `AgentMod` once loaded; the mod host just builds it from a factory file instead of a code import:
|
|
10
|
+
|
|
11
|
+
```bash
|
|
12
|
+
~/.commandcode/mods/review-guard.ts
|
|
13
|
+
│ one file = one mod
|
|
14
|
+
▼ jiti · TypeScript, no build step
|
|
15
|
+
default-export factory(cmd: ModApi)
|
|
16
|
+
│
|
|
17
|
+
▼ createModHost().register(...)
|
|
18
|
+
hooks + addTool ──► ONE AgentMod
|
|
19
|
+
id `mod:<name>`,
|
|
20
|
+
appended after built-ins
|
|
21
|
+
addCommand ──► /slash dispatch
|
|
22
|
+
+ TUI autocomplete
|
|
23
|
+
on(event) ──► AgentEvent bus
|
|
24
|
+
(observe-only)
|
|
25
|
+
hooks.transformInput ──► typed-prompt
|
|
26
|
+
interception
|
|
27
|
+
addProvider ──► ProviderModule
|
|
28
|
+
addRenderer ──► custom feed entries
|
|
29
|
+
queueMessage ──► steering drains
|
|
30
|
+
ui.widget / ui.pane ──► bands, panes, buttons
|
|
31
|
+
(element tree, any host)
|
|
32
|
+
addAgent ──► task tool agent types
|
|
33
|
+
prompt.submit ──► a turn of its own
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
The factory receives the API bound as `cmd`. Registration verbs are all `add*` and each returns a `Disposable` - call `.dispose()` to undo exactly that one registration.
|
|
37
|
+
|
|
38
|
+
This page is the whole mods surface end to end: the quick start and loading rules first, then the full **ModApi reference**, the **hooks and events** contract, the **UI surface**, **packaging and install**, and how to **verify a mod**. Jump to any section from the sidebar.
|
|
39
|
+
|
|
40
|
+
---
|
|
41
|
+
|
|
42
|
+
## Just ask Command Code to build it
|
|
43
|
+
|
|
44
|
+
You rarely need to hand-write a mod. Command Code already knows this entire API - describe the behavior you want and it writes the mod, loads it with `--mod`, and iterates until it works. The fastest way in is to ask what's possible, then ask for the one you want:
|
|
45
|
+
|
|
46
|
+
```text copy filename="Prompt"
|
|
47
|
+
What kinds of mods can I build for Command Code? Show me a few examples.
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
```text copy filename="Prompt"
|
|
51
|
+
Build me a mod that roasts me every time I greet you with "hi".
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
```text copy filename="Prompt"
|
|
55
|
+
Add a /standup slash command that summarizes what changed in git today.
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
```text copy filename="Prompt"
|
|
59
|
+
Block any shell command containing "rm -rf" unless I confirm it first.
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
Under the hood it reads the [bundled examples](#runnable-examples) and writes against the same `ModApi` this page documents. When it's done, `cmd --mod ./your-mod.ts` tries it instantly - no build step.
|
|
63
|
+
|
|
64
|
+
### A real one, built by asking
|
|
65
|
+
|
|
66
|
+
[`cmd-mod-hi`](https://github.com/ahmadawais/cmd-mod-hi) started as exactly that prompt - "roast me when I say hi" - and shipped to npm. Install it and greet your agent:
|
|
67
|
+
|
|
68
|
+
```bash
|
|
69
|
+
cmd mods add npm:cmd-mod-hi -g
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
Then type `hi`, `yo`, `howdy`, or `hello` and watch it judge you; `/hi-stats` tallies the damage. The whole mod is one `transformInput` hook plus a renderer:
|
|
73
|
+
|
|
74
|
+
```ts
|
|
75
|
+
import type {ModApi} from '@commandcode/harness';
|
|
76
|
+
|
|
77
|
+
const roasts = [
|
|
78
|
+
'"hi" — bold. groundbreaking. truly pushing the boundaries of human communication.',
|
|
79
|
+
'you typed "hi" and pressed enter. your ancestors are weeping.',
|
|
80
|
+
// …a dozen more
|
|
81
|
+
];
|
|
82
|
+
|
|
83
|
+
let greetingCount = 0;
|
|
84
|
+
|
|
85
|
+
export default function (cmd: ModApi): void {
|
|
86
|
+
cmd.addRenderer('hi-roast', (data: {text: string}) => ['[cmd-mod-hi]: ' + data.text]);
|
|
87
|
+
|
|
88
|
+
cmd.addCommand({
|
|
89
|
+
name: 'hi-stats',
|
|
90
|
+
description: 'See how many times you\'ve been roasted for saying "hi"',
|
|
91
|
+
handler: () => ({message: `[cmd-mod-hi]: You've been roasted ${greetingCount} times.`}),
|
|
92
|
+
});
|
|
93
|
+
|
|
94
|
+
cmd.hooks({
|
|
95
|
+
transformInput({text}) {
|
|
96
|
+
if (/^(hi|hello|hey|yo|sup|howdy)[.!?\s]*$/.test(text.trim().toLowerCase())) {
|
|
97
|
+
greetingCount += 1;
|
|
98
|
+
cmd.showEntry('hi-roast', {text: roasts[greetingCount % roasts.length]});
|
|
99
|
+
}
|
|
100
|
+
return undefined; // let the greeting through - the roast is a side show
|
|
101
|
+
},
|
|
102
|
+
});
|
|
103
|
+
}
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
Want to understand what it's doing, or write one by hand? The rest of this page is the full reference.
|
|
107
|
+
|
|
108
|
+
---
|
|
109
|
+
|
|
110
|
+
## Quick start
|
|
111
|
+
|
|
112
|
+
Create `~/.commandcode/mods/review-guard.ts`:
|
|
113
|
+
|
|
114
|
+
```ts
|
|
115
|
+
import type {ModApi} from '@commandcode/harness';
|
|
116
|
+
|
|
117
|
+
export default function (cmd: ModApi) {
|
|
118
|
+
// Block dangerous writes (a mutating hook - see the hooks catalog).
|
|
119
|
+
cmd.hooks({
|
|
120
|
+
beforeToolCall: async ({toolName, input}) => {
|
|
121
|
+
if (toolName !== 'shell_command') return undefined;
|
|
122
|
+
const command = typeof input.command === 'string' ? input.command : '';
|
|
123
|
+
if (!command.includes('rm -rf')) return undefined;
|
|
124
|
+
const allow = await cmd.ui.confirm({title: 'Allow rm -rf?'});
|
|
125
|
+
return allow ? undefined : {block: true, additionalContext: 'Blocked by review-guard.'};
|
|
126
|
+
},
|
|
127
|
+
});
|
|
128
|
+
|
|
129
|
+
// A tool the model can call.
|
|
130
|
+
cmd.addTool({
|
|
131
|
+
schema: {
|
|
132
|
+
name: 'count_todos',
|
|
133
|
+
description: 'Count TODO markers in the repo',
|
|
134
|
+
input_schema: {type: 'object', properties: {}, required: []},
|
|
135
|
+
},
|
|
136
|
+
run: async () => {
|
|
137
|
+
const result = await cmd.exec({command: 'grep', args: ['-rc', 'TODO', '.']});
|
|
138
|
+
return {ok: true, content: [{type: 'text', text: result.stdout}]};
|
|
139
|
+
},
|
|
140
|
+
});
|
|
141
|
+
|
|
142
|
+
// A host slash command: /todos in the TUI.
|
|
143
|
+
cmd.addCommand({
|
|
144
|
+
name: 'todos',
|
|
145
|
+
description: 'Summarize open TODOs',
|
|
146
|
+
handler: () => ({prompt: 'List every TODO comment in this repo and rank by urgency.'}),
|
|
147
|
+
});
|
|
148
|
+
|
|
149
|
+
// Observe the event stream (never mutates - mutation is what hooks are for).
|
|
150
|
+
cmd.on('turn_end', () => cmd.ui.notify('turn finished'));
|
|
151
|
+
}
|
|
152
|
+
```
|
|
153
|
+
|
|
154
|
+
It loads on the next session (or `cmd --mod ./review-guard.ts` to try it without installing). The factory may be async; jiti compiles the TypeScript at load time, so there is no build step.
|
|
155
|
+
|
|
156
|
+
---
|
|
157
|
+
|
|
158
|
+
## Where mods load from
|
|
159
|
+
|
|
160
|
+
| Location | Scope | Notes |
|
|
161
|
+
|---|---|---|
|
|
162
|
+
| built-in | shipped | compiled-in first-party mods (providers, titling, …); registered first |
|
|
163
|
+
| `~/.commandcode/mods/*.ts` | user | loose files, one mod each |
|
|
164
|
+
| `~/.commandcode/mods/<dir>/` | user | `package.json` manifest → `mods/` dir → `index.ts` |
|
|
165
|
+
| `<project>/.commandcode/mods/…` | project | same layout; loads only once the workspace is trusted |
|
|
166
|
+
| settings `mods.paths` | user/project | explicit files/dirs, relative to the settings scope |
|
|
167
|
+
| settings `mods.sources` | user/project | installed packages (see [Install and share mods](./packaging.md#install-and-share-mods)) |
|
|
168
|
+
| `--mod <path>` | session | repeatable; loads ahead of installed, wins name collisions |
|
|
169
|
+
|
|
170
|
+
Dot-entries and `node_modules` are never scanned (the package registry lives under `mods/.registry/` precisely so discovery skips it). Duplicate mod names keep the first and warn. Disable without deleting via settings:
|
|
171
|
+
|
|
172
|
+
```json
|
|
173
|
+
{"mods": {"disabled": ["review-guard"]}}
|
|
174
|
+
```
|
|
175
|
+
|
|
176
|
+
Turn off every installed mod at once with `{"mods": {"disableAll": true}}` (any settings file; a disable wins), or for one session with `cmd --safe-mode`. Both still load the built-in mods, which are Command Code itself; safe mode also skips `--mod` paths.
|
|
177
|
+
|
|
178
|
+
---
|
|
179
|
+
|
|
180
|
+
## The one rule: hooks mutate, `on` observes
|
|
181
|
+
|
|
182
|
+
- **`cmd.hooks({...})`** is the only place that can change behavior - block, rewrite, or answer a tool call (`beforeToolCall`), rewrite a result (`afterToolCall`), add to or edit the system prompt (`appendSystemPrompt`, `transformSystemPrompt`), redact what the transcript keeps (`transformMessage`), rewrite the answer as it streams (`transformTextDelta`), send one request to another model (`beforeModelRequest`), answer a permission prompt (`onPermissionRequest`), rewrite typed input (`transformInput`), force a finished run to keep going (`onStop`), react to session start/end (`onSessionStart`/`onSessionEnd`), or run post-turn work (`onRunEnd`). Multiple `hooks()` calls compose in registration order.
|
|
183
|
+
- **`cmd.on(event, ...)`** only observes - it cannot block or rewrite. Handlers are isolated (a throw becomes a `mod_error` event, never a crash).
|
|
184
|
+
|
|
185
|
+
If you find yourself wanting an `on` handler to stop a tool, you want a hook instead. The full mutating surface is in [Hooks and events](./hooks-and-events.md#hooks-and-events); the full registration/live surface is the [ModApi reference](./api.md#mod-api-reference).
|
|
186
|
+
|
|
187
|
+
---
|
|
188
|
+
|
|
189
|
+
## Built-in mods
|
|
190
|
+
|
|
191
|
+
Command Code's own features ride this exact API. First-party providers (`provider-anthropic` / `provider-copilot` / `provider-openai`), the update notice, and the harness-side titling and taste-learning triggers are **built-in mods**: compiled-in factories registered on the same host before any discovered mod. They are not special - they use `cmd.addProvider`, `cmd.on`, and `cmd.hooks` like any mod, appear in `cmd mods list` with source `builtin`, and honor the same disable key:
|
|
192
|
+
|
|
193
|
+
```json
|
|
194
|
+
{"mods": {"disabled": ["provider-copilot", "update-notice", "titling", "learning"]}}
|
|
195
|
+
```
|
|
196
|
+
|
|
197
|
+
The `launch-day` built-in plays a one-time GTA VI intro during its launch window (00:00 on November 19 to 12:00 on November 20, local time), once per person and only in an interactive terminal with enough colours and room. While it plays, the welcome COMMAND banner keeps its classic purple; as the intro rolls up into it, the banner turns to sunset colours (in place, in windows at least 40 rows tall), and later sessions in the window open on it. `/gta` replays it and `/gta off` stops and skips it; `cmd mods disable launch-day` or `COMMANDCODE_LAUNCH_DAY=0` turns it off.
|
|
198
|
+
|
|
199
|
+
Some built-ins are **opt-in** and are disabled by default; `cmd mods list --builtin` marks them `disabled by default`. The session todo checklist (`todo_write`, the TODOS panel, `/todos`, `ctrl+x`) is the `todos` mod: enable it with `cmd mods enable todos` (project level; `-g` for the user level), which adds it to the `enabled` key in the settings file:
|
|
200
|
+
|
|
201
|
+
```json
|
|
202
|
+
{"mods": {"enabled": ["todos"]}}
|
|
203
|
+
```
|
|
204
|
+
|
|
205
|
+
`cmd mods disable <name>` disables the mod. A disable in any settings file wins and keeps the mod disabled. The change takes effect on the next session or `/reload`; see [Turn a mod on or off](./packaging.md#turn-a-mod-on-or-off).
|
|
206
|
+
|
|
207
|
+
Built-in mods always win a name collision against a discovered mod of the same name (the loader shadows the file with a warning), and they are compiled in - never jiti-loaded from a writable path, so they are not supply-chain surface. Structural harness mods (workspace, compaction, checkpoints) are load-bearing for correctness and stay unconditional; only the observer-style built-ins above are disable-able.
|
|
208
|
+
|
|
209
|
+
---
|
|
210
|
+
|
|
211
|
+
## Runnable examples
|
|
212
|
+
|
|
213
|
+
Command Code ships runnable, single-file example mods and reads them itself. You don't need to find them on disk - just ask:
|
|
214
|
+
|
|
215
|
+
```
|
|
216
|
+
build a mod that blocks dangerous shell commands
|
|
217
|
+
```
|
|
218
|
+
|
|
219
|
+
Command Code opens the matching example and works from it. Every example loads through the real mod loader in CI on every test run, so what it copies is proven to load.
|
|
220
|
+
|
|
221
|
+
Ask for any of these by name or by what you want:
|
|
222
|
+
|
|
223
|
+
| File | Shows |
|
|
224
|
+
|---|---|
|
|
225
|
+
| `slash-command.ts` | `addCommand` - a `/command` returning `{prompt}` or `{message}` |
|
|
226
|
+
| `custom-tool.ts` | `addTool` - a model-callable tool with `run` + `exec` |
|
|
227
|
+
| `block-dangerous-commands.ts` | `hooks.beforeToolCall` - block/allow with a confirm |
|
|
228
|
+
| `input-shortcuts.ts` | `hooks.transformInput` - rewrite / handle typed input |
|
|
229
|
+
| `observe-events.ts` | `on(event)` + the cross-mod `events` bus |
|
|
230
|
+
| `custom-entry-renderer.ts` | `addRenderer` + `showEntry` - styled feed rows |
|
|
231
|
+
| `flags-and-options.ts` | `addFlag` / `getFlag` + `--mod-option` |
|
|
232
|
+
| `lifecycle-hooks.ts` | `hooks.onStop` (Stop) + `onSessionStart`/`onSessionEnd` + `afterToolCall` `isError` + `on('subagent_start'/'subagent_stop')` |
|
|
233
|
+
| `pane-and-buttons.ts` | `ui.pane` + `ui.widget` + buttons + `cmd.state` + `ui.toast` |
|
|
234
|
+
| `pane-form.ts` | a focused form pane: `input` + `select` + `markdown` elements, `openPane(id, {focus: true})` |
|
|
235
|
+
| `spinner-count.ts` | `ui.override` - a tool-call count beside the spinner, compact shell rows |
|
|
236
|
+
| `redact-secrets.ts` | `hooks.transformMessage` - mask keys before the transcript keeps them |
|
|
237
|
+
| `permission-policy.ts` | `hooks.onPermissionRequest` - answer prompts with a team policy |
|
|
238
|
+
| `model-router.ts` | `hooks.beforeModelRequest` + `cmd.model.complete` |
|
|
239
|
+
| `stream-filter.ts` | `hooks.transformTextDelta` - redact keys as the answer streams + `cmd.process.spawn` |
|
|
240
|
+
| `kitchen-sink.ts` | every capability in one annotated file |
|
|
241
|
+
|
|
242
|
+
---
|
|
243
|
+
|
|
244
|
+
## What mods cannot do
|
|
245
|
+
|
|
246
|
+
These limits are deliberate.
|
|
247
|
+
|
|
248
|
+
- **Hooks mutate, `on` observes.** Event handlers cannot block tools or rewrite context; that is what `cmd.hooks` is for.
|
|
249
|
+
- **Project mods are trust-gated** like project skills: they load only after the workspace trust prompt, because a mod is arbitrary code. User-scope and `--mod` mods always load. There is no sandbox - install packages you trust. Package installs run npm with `--ignore-scripts` (mods are jiti-loaded TypeScript; they need no build step, so lifecycle scripts are pure attack surface).
|
|
250
|
+
- **Print mode loads user-scope and `--mod` mods only**, with the ui bridge degraded to headless defaults (confirm → false, select/input → undefined - never auto-approved; `setStatus`/`widget` render nowhere, and `cmd.ui.capabilities.status` is false). Project mods stay out of headless runs because print never shows a trust prompt; pass `--dangerously-skip-permissions` to opt a repo's own mods into a headless run (CI).
|
|
251
|
+
- **Mod-queued messages don't echo in the feed** the way typed input does - they land in the transcript and steer the model, but the visible record is the model's response.
|
|
252
|
+
- **Rendering is data, not components.** Widgets, panes, and feed renderers return strings or a small element tree (text, row, box, button, progress, divider, input, select, markdown) that each host draws; mods never mount React components. That keeps a mod host-agnostic, and a crashing render degrades to a one-line warning, never a broken screen.
|
|
253
|
+
- **Mods hot-reload on save.** In the interactive TUI every file-backed mod is watched: saving it re-imports the file and swaps the mod in place. The old code gets `onSessionEnd` with `reason: 'reload'` and every registration it made is disposed, except tools added with `addTool`, which keep the old code until the next session. `cmd.state` is kept, and the new code's `onSessionStart` fires with `source: 'reload'`. A save that throws while loading keeps the old code running, and the feed says why. `/mods reload [name]` does the same on demand; `COMMANDCODE_MODS_HOT_RELOAD=0` turns the watcher off. Tools a mod adds take effect on the next session, because the tool set is fixed per session. Built-in mods never reload.
|
|
254
|
+
- **Mods restyle rows, never the permission prompt.** `cmd.ui.override` covers the spinner, tool rows, user messages, and command output. What a person is asked to approve is always drawn by Command Code, so the permission prompt (and every other approval dialog) is not on the list and never will be.
|
|
255
|
+
- **Permission answers stop at the prompt.** `onPermissionRequest` only sees prompts the engine was about to show you: deny rules, plan mode, and dont-ask always win, and a safety-forced prompt can be denied by a mod but never allowed. In a headless run, where the prompt would otherwise be auto-answered, the mod's answer is used too.
|
|
256
|
+
- **Session controls stop at the harness surface.** `cmd.sessions` covers what the live harness owns (compact, tree, navigate, labels); creating/switching/forking sessions is host lifecycle, not harness state, and stays with the host UI.
|
|
257
|
+
|
|
258
|
+
Embedders wire the same machinery directly: `createModHost` + `loadMods` + `createHarness({modHost})` (or `createNodeHarnessSession({modHost})`), all exported from `@commandcode/harness`.
|
|
259
|
+
|
|
260
|
+
---
|
|
261
|
+
|
|
262
|
+
## Reference overview
|
|
263
|
+
|
|
264
|
+
The rest of this page is the complete reference, in order:
|
|
265
|
+
|
|
266
|
+
- [ModApi reference](./api.md#mod-api-reference): every field, registration verb, and live method.
|
|
267
|
+
- [Hooks and events](./hooks-and-events.md#hooks-and-events): the mutating lifecycle, the `AgentEvent` catalog.
|
|
268
|
+
- [UI surface](./ui.md#ui-surface): dialogs, footer status, editor widgets, custom feed rendering.
|
|
269
|
+
- [Install and share mods](./packaging.md#install-and-share-mods): `cmd mods add`, packages, filtering, turning mods on and off.
|
|
270
|
+
- [Listing a mod on the mods hub](./packaging.md#listing-a-mod-on-the-mods-hub): get your mod on the Command Code mods hub.
|
|
271
|
+
- [Verify a mod](./verify.md#verify-a-mod): load it, list it, test it, ship it.
|