command-code 1.92.0 → 1.93.1

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.
Files changed (92) hide show
  1. package/CHANGELOG.md +15 -0
  2. package/package.json +1 -1
  3. package/vsix/commandcode-vscode.vsix +0 -0
  4. package/dist/bundled/agent-browser/SKILL.md +0 -73
  5. package/dist/bundled/command-code-knowledge/SKILL.md +0 -68
  6. package/dist/bundled/command-code-knowledge/live-models.ts +0 -284
  7. package/dist/bundled/command-code-knowledge/reference/byok.md +0 -389
  8. package/dist/bundled/command-code-knowledge/reference/custom-agents.md +0 -341
  9. package/dist/bundled/command-code-knowledge/reference/custom-slash-commands.md +0 -423
  10. package/dist/bundled/command-code-knowledge/reference/headless.md +0 -381
  11. package/dist/bundled/command-code-knowledge/reference/hooks.md +0 -1107
  12. package/dist/bundled/command-code-knowledge/reference/mcp.md +0 -636
  13. package/dist/bundled/command-code-knowledge/reference/memory.md +0 -137
  14. package/dist/bundled/command-code-knowledge/reference/models.md +0 -145
  15. package/dist/bundled/command-code-knowledge/reference/permissions.md +0 -486
  16. package/dist/bundled/command-code-knowledge/reference/plan-mode.md +0 -283
  17. package/dist/bundled/command-code-knowledge/reference/plans.md +0 -16
  18. package/dist/bundled/command-code-knowledge/reference/product-help.md +0 -490
  19. package/dist/bundled/command-code-knowledge/reference/sessions.md +0 -377
  20. package/dist/bundled/command-code-knowledge/reference/skills.md +0 -1009
  21. package/dist/bundled/command-code-knowledge/reference/tools.md +0 -522
  22. package/dist/bundled/config/SKILL.md +0 -18
  23. package/dist/bundled/config/references/permissions.md +0 -27
  24. package/dist/bundled/config/references/settings.md +0 -49
  25. package/dist/bundled/design/SKILL.md +0 -441
  26. package/dist/bundled/design/references/accessibility.md +0 -404
  27. package/dist/bundled/design/references/border.md +0 -161
  28. package/dist/bundled/design/references/button.md +0 -192
  29. package/dist/bundled/design/references/checkup.md +0 -162
  30. package/dist/bundled/design/references/color.md +0 -245
  31. package/dist/bundled/design/references/create.md +0 -291
  32. package/dist/bundled/design/references/design-html.md +0 -227
  33. package/dist/bundled/design/references/deslop.md +0 -283
  34. package/dist/bundled/design/references/finish.md +0 -156
  35. package/dist/bundled/design/references/interaction.md +0 -186
  36. package/dist/bundled/design/references/layout.md +0 -216
  37. package/dist/bundled/design/references/media.md +0 -112
  38. package/dist/bundled/design/references/motion.md +0 -237
  39. package/dist/bundled/design/references/redesign.md +0 -197
  40. package/dist/bundled/design/references/refine.md +0 -193
  41. package/dist/bundled/design/references/relayout.md +0 -207
  42. package/dist/bundled/design/references/report-html.md +0 -235
  43. package/dist/bundled/design/references/responsive.md +0 -233
  44. package/dist/bundled/design/references/review.md +0 -164
  45. package/dist/bundled/design/references/setup.md +0 -119
  46. package/dist/bundled/design/references/severity.md +0 -111
  47. package/dist/bundled/design/references/shadow.md +0 -164
  48. package/dist/bundled/design/references/smell.md +0 -211
  49. package/dist/bundled/design/references/style-3d.md +0 -23
  50. package/dist/bundled/design/references/style-bento.md +0 -21
  51. package/dist/bundled/design/references/style-editorial.md +0 -23
  52. package/dist/bundled/design/references/style-futuristic.md +0 -21
  53. package/dist/bundled/design/references/style-glassmorphism.md +0 -52
  54. package/dist/bundled/design/references/style-maximalism.md +0 -20
  55. package/dist/bundled/design/references/style-minimalism.md +0 -21
  56. package/dist/bundled/design/references/style-neo-brutalism.md +0 -21
  57. package/dist/bundled/design/references/style-retro-futurism.md +0 -21
  58. package/dist/bundled/design/references/style-swiss.md +0 -20
  59. package/dist/bundled/design/references/style.md +0 -77
  60. package/dist/bundled/design/references/surface.md +0 -163
  61. package/dist/bundled/design/references/system.md +0 -73
  62. package/dist/bundled/design/references/typeset.md +0 -210
  63. package/dist/bundled/design/references/variants.md +0 -193
  64. package/dist/bundled/design/references/voice.md +0 -184
  65. package/dist/bundled/design/references/writing.md +0 -174
  66. package/dist/bundled/loop/SKILL.md +0 -16
  67. package/dist/bundled/mod-builder/SKILL.md +0 -135
  68. package/dist/bundled/mod-builder/examples/block-dangerous-commands.ts +0 -41
  69. package/dist/bundled/mod-builder/examples/custom-entry-renderer.ts +0 -32
  70. package/dist/bundled/mod-builder/examples/custom-tool.ts +0 -53
  71. package/dist/bundled/mod-builder/examples/flags-and-options.ts +0 -29
  72. package/dist/bundled/mod-builder/examples/input-shortcuts.ts +0 -41
  73. package/dist/bundled/mod-builder/examples/kitchen-sink.ts +0 -129
  74. package/dist/bundled/mod-builder/examples/lifecycle-hooks.ts +0 -64
  75. package/dist/bundled/mod-builder/examples/model-router.ts +0 -43
  76. package/dist/bundled/mod-builder/examples/observe-events.ts +0 -30
  77. package/dist/bundled/mod-builder/examples/pane-and-buttons.ts +0 -60
  78. package/dist/bundled/mod-builder/examples/pane-form.ts +0 -68
  79. package/dist/bundled/mod-builder/examples/permission-policy.ts +0 -34
  80. package/dist/bundled/mod-builder/examples/redact-secrets.ts +0 -46
  81. package/dist/bundled/mod-builder/examples/slash-command.ts +0 -33
  82. package/dist/bundled/mod-builder/examples/spinner-count.ts +0 -47
  83. package/dist/bundled/mod-builder/examples/stream-filter.ts +0 -70
  84. package/dist/bundled/mod-builder/reference/api.md +0 -140
  85. package/dist/bundled/mod-builder/reference/hooks-and-events.md +0 -347
  86. package/dist/bundled/mod-builder/reference/overview.md +0 -271
  87. package/dist/bundled/mod-builder/reference/packaging.md +0 -187
  88. package/dist/bundled/mod-builder/reference/ui.md +0 -253
  89. package/dist/bundled/mod-builder/reference/verify.md +0 -67
  90. package/dist/bundled/skill-builder/SKILL.md +0 -104
  91. package/dist/cli.mjs +0 -16
  92. package/dist/index.mjs +0 -2
@@ -1,64 +0,0 @@
1
- // Example mod: the cross-agent lifecycle hooks — Stop, SessionStart/End, PostToolUseFailure,
2
- // and SubagentStart/Stop. Together with beforeToolCall (PreToolUse), afterToolCall (PostToolUse),
3
- // and transformInput (UserPromptSubmit), a mod can register a handler for every lifecycle hook
4
- // point the major coding agents expose. See harness/docs/mods-api.md#cross-agent-hook-parity.
5
-
6
- import type {ModApi} from '@commandcode/harness';
7
-
8
- export default function (cmd: ModApi): void {
9
- // SessionStart / SessionEnd — once per session, with typed source/reason the bare
10
- // `session_start` / `session_shutdown` events don't carry.
11
- cmd.hooks({
12
- onSessionStart: ({source}) => {
13
- cmd.ui.notify(`session started (${source})`);
14
- },
15
- onSessionEnd: ({reason}) => {
16
- cmd.ui.notify(`session ending (${reason})`);
17
- },
18
- });
19
-
20
- // PostToolUse vs PostToolUseFailure — the afterToolCall hook's `isError` param tells you
21
- // whether the tool's own execution failed, so you can react only to failures.
22
- let toolFailures = 0;
23
- cmd.hooks({
24
- afterToolCall: async ({toolName, isError}) => {
25
- if (isError) {
26
- toolFailures += 1;
27
- return {
28
- additionalContext: `(${toolName} failed — ${toolFailures} failure(s) so far this run)`,
29
- };
30
- }
31
- return undefined;
32
- },
33
- });
34
-
35
- // The Stop hook — force-continue a run that would otherwise finish. Here: keep going until
36
- // the model says it is done, but never more than a couple of nudges (the loop also caps this).
37
- let nudges = 0;
38
- cmd.hooks({
39
- onStop: async ({lastAssistantText}) => {
40
- if (/\bdone\b/i.test(lastAssistantText) || nudges >= 2) {
41
- return {continue: false};
42
- }
43
- nudges += 1;
44
- return {
45
- continue: true,
46
- reason: 'If the task is complete, say "done". Otherwise keep working.',
47
- };
48
- },
49
- });
50
-
51
- // SubagentStart / SubagentStop — observe the `task` tool bracketing a nested sub-agent run.
52
- cmd.on('subagent_start', event => {
53
- if (event.type === 'subagent_start') {
54
- cmd.ui.notify(`sub-agent started: ${event.subagentType}`);
55
- }
56
- });
57
- cmd.on('subagent_stop', event => {
58
- if (event.type === 'subagent_stop') {
59
- cmd.ui.notify(
60
- `sub-agent ${event.subagentType} done (~${event.tokensUsed} tokens)`,
61
- );
62
- }
63
- });
64
- }
@@ -1,43 +0,0 @@
1
- // Example mod: route requests between models, and call a model yourself.
2
- //
3
- // hooks.beforeModelRequest runs at the start of each request's round, so its tools and prompt are
4
- // built for the model it picks. Returning {model} sends THAT request to another model; the next request goes back to the session's model (use
5
- // prepareNextTurn to switch for the rest of a run). Here: the first request of each run, which
6
- // usually just reads the prompt and picks tools, goes to a cheaper model.
7
- //
8
- // cmd.model.complete runs one prompt on the session's own client, with no transcript and no
9
- // tools. It always resolves: {isAnswered: true, text} or {isAnswered: false, reason}.
10
-
11
- import type {ModApi} from '@commandcode/harness';
12
-
13
- export default function (cmd: ModApi): void {
14
- cmd.addFlag('router-model', {
15
- type: 'string',
16
- description: 'Model for the first request of each run',
17
- });
18
-
19
- cmd.hooks({
20
- beforeModelRequest: async ({turnNumber}) => {
21
- const cheap = cmd.getFlag('router-model');
22
- if (turnNumber !== 1 || typeof cheap !== 'string' || !cheap)
23
- return undefined;
24
- return {model: cheap};
25
- },
26
- });
27
-
28
- cmd.addCommand({
29
- name: 'haiku',
30
- description:
31
- 'Write a haiku about the argument with a one-shot model call',
32
- argumentHint: '<topic>',
33
- handler: async ({args}) => {
34
- const result = await cmd.model.complete({
35
- prompt: `Write a haiku about: ${args || 'code review'}`,
36
- maxOutputTokens: 200,
37
- });
38
- if (!result.isAnswered)
39
- return {message: `No haiku (${result.reason}).`};
40
- return {message: result.text};
41
- },
42
- });
43
- }
@@ -1,30 +0,0 @@
1
- // Example mod: observe the event stream (never mutate).
2
- //
3
- // cmd.on subscribes to any AgentEvent type plus the host lifecycle events
4
- // `session_start` / `session_shutdown`. Observers CANNOT block tools or rewrite context —
5
- // that is what cmd.hooks is for. The boundary is deliberate: hooks mutate, `on` observes.
6
- //
7
- // Handlers are isolated: a throw becomes a `mod_error` event, never a crashed session.
8
- // Every cmd.on returns a Disposable — call .dispose() to stop observing.
9
- //
10
- // Common event types: run_start, run_end, turn_start, turn_end, model_request_start,
11
- // model_request_end, tool_running, tool_completed, tool_errored, notice.
12
-
13
- import type {ModApi} from '@commandcode/harness';
14
-
15
- export default function (cmd: ModApi): void {
16
- let toolCalls = 0;
17
-
18
- cmd.on('tool_completed', () => {
19
- toolCalls += 1;
20
- });
21
-
22
- cmd.on('run_end', () => {
23
- cmd.ui.notify(`turn finished — ${toolCalls} tool call(s) this session`);
24
- });
25
-
26
- // The cross-mod bus lets mods talk to each other without knowing about one another.
27
- cmd.on('tool_errored', () => {
28
- cmd.events.emit('tool-failed', {at: toolCalls});
29
- });
30
- }
@@ -1,60 +0,0 @@
1
- // Example mod: a live pane with buttons, a band above the prompt, and a toast.
2
- //
3
- // cmd.ui.pane draws a titled panel the person opens and closes; cmd.ui.widget draws a band of
4
- // lines around the prompt. Both take a `render` that returns plain data: strings, or elements
5
- // ({type: 'text' | 'row' | 'box' | 'button' | 'progress' | 'divider'}). Never React components,
6
- // so the same mod draws in any host.
7
- //
8
- // Values a drawing reads live in cmd.state: host-held, so they survive a hot reload, and
9
- // setting one repaints every widget and pane. While the pane is open, Alt+<hotkey> presses its
10
- // buttons and Alt+0 closes it.
11
-
12
- import type {ModApi} from '@commandcode/harness';
13
-
14
- export default function (cmd: ModApi): void {
15
- const calls = (): number => cmd.state.get<number>('calls') ?? 0;
16
-
17
- cmd.on('tool_completed', () => {
18
- cmd.state.set('calls', calls() + 1);
19
- });
20
-
21
- // The band above the prompt: one line, always visible.
22
- cmd.ui.widget({
23
- placement: 'above-editor',
24
- render: () => [
25
- {type: 'text', text: `tool calls: ${calls()}`, dim: true},
26
- ],
27
- });
28
-
29
- cmd.ui.pane({
30
- id: 'calls',
31
- title: 'Tool calls',
32
- render: () => [
33
- {type: 'progress', label: 'budget', value: calls() / 50, width: 20},
34
- {
35
- type: 'row',
36
- children: [
37
- {type: 'text', text: `${calls()} of 50`, bold: true},
38
- {
39
- type: 'button',
40
- label: 'Reset',
41
- hotkey: 'r',
42
- onPress: () => {
43
- cmd.state.set('calls', 0);
44
- cmd.ui.toast('Counter reset', {level: 'success'});
45
- },
46
- },
47
- ],
48
- },
49
- ],
50
- });
51
-
52
- // /calls opens the pane.
53
- cmd.addCommand({
54
- name: 'calls',
55
- description: 'Show the tool-call counter pane',
56
- handler: () => {
57
- cmd.ui.openPane('calls');
58
- },
59
- });
60
- }
@@ -1,68 +0,0 @@
1
- // Example mod: a small form in a pane, with a text input, a select, markdown, and a button.
2
- //
3
- // `input` and `select` elements only take keys while their pane has focus: `/standup` opens the
4
- // pane with focus (dialog-like), and Alt+↑ focuses the newest open pane from the prompt. While
5
- // focused, Tab walks the fields, ←/→ choose an option, Enter submits or picks, and Esc goes
6
- // back to the prompt. Typing never reaches a pane that does not have focus.
7
- //
8
- // The values live in cmd.state, so they survive a hot reload and setting one repaints the pane.
9
-
10
- import type {ModApi} from '@commandcode/harness';
11
-
12
- const MOODS = [
13
- {label: 'Great', value: 'great'},
14
- {label: 'Okay', value: 'okay'},
15
- {label: 'Blocked', value: 'blocked'},
16
- ] as const;
17
-
18
- export default function (cmd: ModApi): void {
19
- const note = (): string => cmd.state.get<string>('note') ?? '';
20
- const mood = (): string => cmd.state.get<string>('mood') ?? 'okay';
21
-
22
- cmd.ui.pane({
23
- id: 'standup',
24
- title: 'Standup',
25
- render: () => [
26
- {
27
- type: 'markdown',
28
- text: '**Today**: one line, then pick how it is going.',
29
- },
30
- {
31
- type: 'input',
32
- key: 'note',
33
- placeholder: 'what are you working on?',
34
- value: note(),
35
- onSubmit: text => cmd.state.set('note', text.trim()),
36
- },
37
- {
38
- type: 'select',
39
- key: 'mood',
40
- options: MOODS,
41
- value: mood(),
42
- onSelect: value => cmd.state.set('mood', value),
43
- },
44
- {
45
- type: 'button',
46
- label: 'Post',
47
- hotkey: 's',
48
- onPress: () => {
49
- if (!note()) {
50
- cmd.ui.toast('Type a note first', {level: 'warning'});
51
- return;
52
- }
53
- cmd.ui.notify(`standup (${mood()}): ${note()}`);
54
- cmd.ui.closePane('standup');
55
- },
56
- },
57
- ],
58
- });
59
-
60
- // /standup opens the form with the keyboard in it.
61
- cmd.addCommand({
62
- name: 'standup',
63
- description: 'Post a one-line standup from a form pane',
64
- handler: () => {
65
- cmd.ui.openPane('standup', {focus: true});
66
- },
67
- });
68
- }
@@ -1,34 +0,0 @@
1
- // Example mod: answer permission prompts with a team policy.
2
- //
3
- // hooks.onPermissionRequest fires ONLY where Command Code was about to ask you. Deny rules,
4
- // plan mode, and dont-ask have already run, so a mod can never undo them. Return 'allow' or
5
- // 'deny' to answer for the person, or undefined to let them decide. A prompt a safety check
6
- // forced (isSafetyPrompt: a sensitive file, a risky command) can be denied but never allowed:
7
- // an 'allow' there is ignored and you are asked as usual.
8
-
9
- import type {ModApi} from '@commandcode/harness';
10
-
11
- // Anything that can chain or redirect a second command goes to the person: without this,
12
- // `git status && npm publish` would pass as a safe `git status`.
13
- const SHELL_CONTROL = /[;&|`<>\n]|\$\(/;
14
-
15
- // Anchored at both ends, so the whole command must be one of these.
16
- const SAFE_SHELL = [
17
- /^git (status|diff|log)( .*)?$/,
18
- /^pnpm (test|lint|typecheck)( .*)?$/,
19
- ];
20
-
21
- export default function (cmd: ModApi): void {
22
- cmd.hooks({
23
- onPermissionRequest: ({toolName, input}) => {
24
- if (toolName !== 'shell_command') return undefined;
25
- const command =
26
- typeof input.command === 'string' ? input.command : '';
27
- if (/\bcurl\b.*\|\s*(ba)?sh\b/.test(command)) return 'deny';
28
- if (SHELL_CONTROL.test(command)) return undefined;
29
- if (SAFE_SHELL.some(pattern => pattern.test(command)))
30
- return 'allow';
31
- return undefined;
32
- },
33
- });
34
- }
@@ -1,46 +0,0 @@
1
- // Example mod: redact secrets from everything the transcript keeps.
2
- //
3
- // hooks.transformMessage sees every message before it is committed: your prompt, each model
4
- // reply, every tool result, steering and follow-up messages. What it returns is what the
5
- // transcript stores AND what every later request sends, so a key a tool printed never reaches
6
- // the model on the next turn. The role and every tool_use / tool_result id must stay as they
7
- // were; a rewrite that changes them is rejected and the message is kept.
8
-
9
- import type {ModApi} from '@commandcode/harness';
10
-
11
- const SECRET_PATTERNS = [
12
- /\bsk-[A-Za-z0-9_-]{16,}\b/g, // API keys
13
- /\bgh[pousr]_[A-Za-z0-9]{20,}\b/g, // GitHub tokens
14
- /\bAKIA[0-9A-Z]{16}\b/g, // AWS access key ids
15
- ];
16
-
17
- function redact(text: string): string {
18
- return SECRET_PATTERNS.reduce(
19
- (current, pattern) => current.replace(pattern, '[REDACTED]'),
20
- text,
21
- );
22
- }
23
-
24
- export default function (cmd: ModApi): void {
25
- cmd.hooks({
26
- transformMessage: ({message}) => {
27
- if (message.role === 'assistant') return message;
28
- return {
29
- ...message,
30
- content: message.content.map(block => {
31
- if (block.type === 'text')
32
- return {...block, text: redact(block.text)};
33
- if (block.type !== 'tool_result') return block;
34
- return {
35
- ...block,
36
- content: block.content.map(part =>
37
- part.type === 'text'
38
- ? {...part, text: redact(part.text)}
39
- : part,
40
- ),
41
- };
42
- }),
43
- };
44
- },
45
- });
46
- }
@@ -1,33 +0,0 @@
1
- // Example mod: a slash command.
2
- //
3
- // Drop this file at ~/.commandcode/mods/standup.ts and `/standup` appears in the TUI
4
- // slash menu. A command handler returns DATA, never a live callback:
5
- // { prompt } → submitted as an automated turn (the model runs it)
6
- // { message } → rendered as an info row (no model turn)
7
- // nothing → pure side effect (e.g. it only called cmd.ui / cmd.exec)
8
- //
9
- // The handler receives { args, ui, cwd, exec } — `args` is the raw text after the
10
- // command name (`/standup since=yesterday` → args === "since=yesterday").
11
-
12
- import type {ModApi} from '@commandcode/harness';
13
-
14
- export default function (cmd: ModApi): void {
15
- cmd.addCommand({
16
- name: 'standup',
17
- description: 'Summarize what changed today for standup',
18
- argumentHint: '[since]',
19
- handler: ({args}) => {
20
- const since = args.trim() || 'this morning';
21
- return {
22
- prompt: `Summarize the git commits and working changes since ${since} as three standup bullets: done, in-progress, blockers.`,
23
- };
24
- },
25
- });
26
-
27
- // A second command that renders an info row instead of running the model.
28
- cmd.addCommand({
29
- name: 'where',
30
- description: 'Print the current working directory',
31
- handler: ({cwd}) => ({message: `You are in ${cwd}`}),
32
- });
33
- }
@@ -1,47 +0,0 @@
1
- // Example mod: restyle built-in rows with cmd.ui.override.
2
- //
3
- // `spinner` appends nodes after the working status line, so "tool calls: 3" sits beside the
4
- // spinner while the agent works. `tool_row` draws a tool's row instead of the built-in one;
5
- // returning undefined keeps the built-in row, and `next()` is what mods loaded after this one
6
- // drew (undefined when nobody did). A throwing override falls back to the built-in drawing.
7
- //
8
- // The permission prompt is never overridable: what a person approves is always drawn by the host.
9
-
10
- import type {ModApi, ModUiOverrideProps} from '@commandcode/harness';
11
-
12
- function statusMark(status: ModUiOverrideProps['tool_row']['status']): string {
13
- if (status === 'error') return '✗';
14
- if (status === 'pending') return '…';
15
- return '✓';
16
- }
17
-
18
- export default function (cmd: ModApi): void {
19
- const calls = (): number => cmd.state.get<number>('calls') ?? 0;
20
-
21
- cmd.on('tool_completed', () => {
22
- cmd.state.set('calls', calls() + 1);
23
- });
24
- // One count per run: reset when the agent starts working on a new prompt.
25
- cmd.on('run_start', () => {
26
- cmd.state.set('calls', 0);
27
- });
28
-
29
- cmd.ui.override('spinner', (_props, next) => [
30
- {type: 'text', text: `tool calls: ${calls()}`, color: 'cyan'},
31
- ...(next() ?? []),
32
- ]);
33
-
34
- // Shell rows as one compact line; every other tool keeps its built-in row.
35
- cmd.ui.override('tool_row', ({toolName, input, status}) => {
36
- if (toolName !== 'shell_command') return undefined;
37
- return [
38
- {
39
- type: 'row',
40
- children: [
41
- {type: 'text', text: statusMark(status), bold: true},
42
- {type: 'text', text: `$ ${input}`, dim: true},
43
- ],
44
- },
45
- ];
46
- });
47
- }
@@ -1,70 +0,0 @@
1
- // Example mod: filter the model's answer as it streams, and stream a process's output.
2
- //
3
- // hooks.transformTextDelta sees every chunk of the answer before it is shown. Return the chunk
4
- // to show (rewritten or not), or '' to hold it back. When the answer is complete it is called
5
- // once more with {delta: '', done: true}: return whatever you held back. The transcript keeps
6
- // exactly what was shown. It must be synchronous and fast: it runs inside the stream.
7
- //
8
- // A key can arrive split across chunks ("sk-ab" then "cdef..."), so this filter holds back a
9
- // tail that might be the start of one and decides when the next chunk (or the end) arrives.
10
- //
11
- // cmd.process.spawn runs a command and hands each stdout/stderr chunk to onOutput as it is
12
- // produced; cmd.exec only answers once the process exits.
13
-
14
- import type {ModApi} from '@commandcode/harness';
15
-
16
- const KEY_PATTERN = /\bsk-[A-Za-z0-9_-]{16,}/g;
17
- // A tail that could still grow into a key: "s", "sk", "sk-", "sk-abc...".
18
- const MAYBE_KEY_TAIL = /(?:\bs|\bsk|\bsk-[A-Za-z0-9_-]*)$/;
19
-
20
- function redact(text: string): string {
21
- return text.replace(KEY_PATTERN, '[REDACTED]');
22
- }
23
-
24
- export default function (cmd: ModApi): void {
25
- // Held-back text, for the stream it belongs to. A retry or a new turn starts a new stream.
26
- let held = '';
27
- let stream = '';
28
-
29
- cmd.hooks({
30
- transformTextDelta: ({delta, done, turnNumber, attempt}) => {
31
- const id = `${turnNumber}:${attempt}`;
32
- if (id !== stream) {
33
- stream = id;
34
- held = '';
35
- }
36
- const text = held + delta;
37
- if (done) {
38
- held = '';
39
- return redact(text);
40
- }
41
- const tail = MAYBE_KEY_TAIL.exec(text)?.[0] ?? '';
42
- held = tail;
43
- return redact(text.slice(0, text.length - tail.length));
44
- },
45
- });
46
-
47
- cmd.addCommand({
48
- name: 'stream',
49
- description: 'Run a command and show its latest output line as it runs',
50
- argumentHint: '<command>',
51
- handler: async ({args}) => {
52
- if (!args.trim()) return {message: 'usage: /stream <command>'};
53
- let lines = 0;
54
- cmd.ui.setStatus(`running ${args}`);
55
- try {
56
- const {code} = await cmd.process.spawn({
57
- command: args,
58
- onOutput: (chunk, from) => {
59
- const last = chunk.trimEnd().split('\n').at(-1) ?? '';
60
- lines += chunk.split('\n').length - 1;
61
- if (last) cmd.ui.setStatus(`${from}: ${last}`);
62
- },
63
- });
64
- return {message: `${args} exited ${code} after ${lines} lines`};
65
- } finally {
66
- cmd.ui.setStatus(null);
67
- }
68
- },
69
- });
70
- }
@@ -1,140 +0,0 @@
1
- <!-- Generated from the Command Code docs: https://commandcode.ai/docs -->
2
-
3
- # ModApi reference
4
-
5
- `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.
6
-
7
- ## Fields
8
-
9
- | Member | Type | Notes |
10
- |---|---|---|
11
- | `cmd.name` | `string` | the mod's name (from filename / manifest) |
12
- | `cmd.cwd` | `string` | workspace root |
13
- | `cmd.session` | `ModSessionApi \| undefined` | persistence seam; undefined until bound |
14
- | `cmd.events` | `ModEventBus` | `emit(channel, data?)` / `on(channel, handler)` cross-mod bus |
15
- | `cmd.ui` | `ModUi` | `notify` / `confirm` / `select` / `input` / `setStatus` / `widget` / `refreshWidgets` / `pane` / `openPane` / `closePane` / `toast` / `copy` / `override` / `setTitle` / `capabilities` |
16
- | `cmd.sessions` | `ModSessionControls` | `compact` / `tree` / `leafId` / `navigateTree` / `setLabel` |
17
- | `cmd.state` | `ModStateApi` | `get` / `set` / `subscribe` - session values that survive a hot reload |
18
- | `cmd.store` | `ModStoreApi` | `get` / `set` / `delete` - values kept across sessions (`~/.commandcode/mods/.store/<mod>.json`) |
19
- | `cmd.clock` | `ModClockApi` | `every` / `after` - timers cancelled with the mod |
20
- | `cmd.model` | `ModModelApi` | `complete` - one prompt on the session's model client |
21
- | `cmd.prompt` | `ModPromptApi` | `submit` - start a turn of its own once the session is idle |
22
- | `cmd.process` | `ModProcessApi` | `spawn` - run a process and stream its output as it arrives |
23
- | `cmd.audio` | `ModAudioApi` | `play` / `bell` - sound files shipped with the mod, and the terminal bell |
24
-
25
- ## Registration methods
26
-
27
- Call these while the mod's factory runs. Each one returns a `Disposable`.
28
-
29
- | Method | Signature |
30
- |---|---|
31
- | `cmd.hooks` | `(hooks: ModHooks) => Disposable` |
32
- | `cmd.addTool` | `(tool: ToolModule) => Disposable` |
33
- | `cmd.addCommand` | `(command: {name; description?; argumentHint?; handler}) => Disposable` |
34
- | `cmd.addFlag` | `(name, {type: 'boolean'\|'string'; default?; description?}) => Disposable` |
35
- | `cmd.addProvider` | `(module: ProviderModule) => Disposable` |
36
- | `cmd.addRenderer` | `(customType: string, (data) => readonly string[]) => Disposable` |
37
- | `cmd.addShortcut` | `(keys: string, {description?; handler}) => Disposable` |
38
- | `cmd.addSkillsPath` | `(path: string) => Disposable` |
39
- | `cmd.on` | `(event: AgentEventType \| 'session_start' \| 'session_shutdown', handler) => Disposable` |
40
- | `cmd.addAgent` | `(definition: {name; description; systemPrompt; tools?; disallowedTools?; model?; maxTurns?}) => Disposable` |
41
- | `cmd.expose` | `(name, fn) => Disposable` |
42
-
43
- What each does:
44
-
45
- - `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.
46
- - `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).
47
- - `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.
48
- - `cmd.addFlag(name, {type, default})` / `cmd.getFlag(name)` - named options; values come from repeatable `--mod-option name=value` CLI flags (defaults apply otherwise).
49
- - `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.
50
- - `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.
51
- - `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.
52
- - `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.
53
- - `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.
54
- - `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.
55
- - `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).
56
-
57
- ## Live methods
58
-
59
- These work any time after the harness binds to the mod host.
60
-
61
- | Method | Signature |
62
- |---|---|
63
- | `cmd.getFlag` | `(name) => boolean \| string \| undefined` |
64
- | `cmd.showEntry` | `(customType, data?) => void` |
65
- | `cmd.queueMessage` | `({content, deliverAs?: 'steer' \| 'follow-up'}) => void` |
66
- | `cmd.sendUserMessage` | `(content, {deliverAs?}) => void` |
67
- | `cmd.exec` | `({command, args?, cwd?, signal?}) => Promise<{stdout, stderr, code}>` |
68
- | `cmd.process.spawn` | `({command, args?, cwd?, signal?, onOutput: (chunk, stream) => void}) => Promise<{code}>` |
69
- | `cmd.setSessionName` / `setModel` / `setEffort` | `(value) => void` (buffered pre-bind) |
70
- | `cmd.getSessionName` / `getModel` / `getEffort` | `() => value \| undefined` (undefined pre-bind) |
71
- | `cmd.getContextUsage` | `() => {tokens, contextWindow, percent} \| undefined` |
72
- | `cmd.getCommands` | `() => readonly {name, description?, mod}[]` |
73
- | `cmd.isIdle` | `() => boolean` |
74
- | `cmd.shutdown` | `() => void` |
75
- | `cmd.getAllTools` / `getActiveTools` | `() => readonly string[]` |
76
- | `cmd.getToolInfo` | `() => readonly {name, description, readOnly, active}[]` |
77
- | `cmd.setActiveTools` | `(names: readonly string[]) => void` |
78
- | `cmd.use` | `(mod, name) => fn \| undefined` |
79
- | `cmd.state.get` / `set` / `subscribe` | `(key) => T \| undefined` / `(key, value) => void` / `(key, listener) => Disposable` |
80
- | `cmd.store.get` / `set` / `delete` | `(key) => T \| undefined` / `(key, value) => Promise<void>` / `(key) => Promise<void>` |
81
- | `cmd.clock.every` / `after` | `(ms, callback) => Disposable` |
82
- | `cmd.model.complete` | `({prompt, system?, model?, maxOutputTokens?, signal?}) => Promise<ModModelCompleteResult>` |
83
- | `cmd.prompt.submit` | `(text) => void` |
84
- | `cmd.ui.copy` | `(text) => Promise<ModCopyResult>` |
85
- | `cmd.audio.play` | `({file, timeoutMs?}) => Promise<ModAudioResult>` |
86
- | `cmd.audio.bell` | `() => ModAudioResult` |
87
-
88
- Details:
89
-
90
- - `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).
91
- - `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.
92
- - `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`.
93
- - `cmd.getSessionName()` / `getModel()` / `getEffort()` - the live values behind the setters; `undefined` before a session binds.
94
- - `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%).
95
- - `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.
96
- - `cmd.isIdle()` - `false` while an agent run is in flight on the bound harness (`run_start` … `run_end`), `true` otherwise and pre-bind.
97
- - `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.
98
- - `cmd.getToolInfo()` - the registered tools with `description`, `readOnly`, and `active` (per the mod-managed filter) - the descriptive counterpart of `getAllTools()`'s bare names.
99
- - `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).
100
- - `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.
101
- - `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.
102
- - `cmd.exec({command, args})` - run a process through the harness Runtime (args are shell-quoted).
103
- - `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.
104
- - `cmd.getAllTools()` / `cmd.getActiveTools()` / `cmd.setActiveTools(names)` - a mod-managed tool filter: disabled tools vanish from the model's schemas and refuse execution.
105
- - `cmd.events` - a tiny cross-mod pub/sub bus (`emit` / `on`).
106
- - `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.
107
- - `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.
108
- - `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.
109
- - `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).
110
- - `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.
111
- - `cmd.ui.copy(text)` - write text to the system clipboard with the same helper `/copy` uses. See [Clipboard and sound](./ui.md#clipboard-and-sound).
112
- - `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).
113
-
114
- ## `ModHooks`: hooks that change behavior
115
-
116
- Every hook is optional, and hooks from several `cmd.hooks()` calls compose.
117
-
118
- `transformContext`, `appendSystemPrompt`, `transformSystemPrompt`, `transformMessage`, `transformTextDelta`, `beforeModelRequest`, `beforeToolCall`, `afterToolCall`, `onTurnStart`, `onTurnEnd`, `shouldStopAfterTurn`, `prepareNextTurn`, `onRunEnd`, `onStop`, plus the host-level `transformInput`, `onPermissionRequest`, `onSessionStart`, and `onSessionEnd`.
119
-
120
- - `beforeToolCall` returns `{block?, input?, additionalContext?, terminate?, result?}`. `result` answers the call without running the tool.
121
- - `beforeModelRequest` returns `{model?}` for one request.
122
- - `transformSystemPrompt` returns the full system prompt to send.
123
- - `transformMessage` returns the message the transcript keeps.
124
- - `transformTextDelta` returns the answer chunk to show (synchronously), or `''` to drop or hold it back.
125
- - `onPermissionRequest` returns `'allow' | 'deny' | undefined`.
126
- - `afterToolCall` receives an `isError` param (PostToolUse vs PostToolUseFailure) and returns `{content?, isError?, additionalContext?, terminate?, modState?}`.
127
- - `onStop` receives `{state, stopReason, turnNumber, lastAssistantText}` and returns `{continue?, reason?}`.
128
- - `transformInput` returns `{action:'continue'} \| {action:'transform', text} \| {action:'handled', message?}`.
129
- - `onSessionStart`/`onSessionEnd` receive `{source}` / `{reason}`.
130
-
131
- The per-hook contracts, ordering guarantees, and error policy are in [the hook contracts](./hooks-and-events.md#the-hook-contracts).
132
-
133
- - `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.
134
- - `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.
135
- - `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.
136
- - `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.
137
-
138
- ## `on` event types
139
-
140
- 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).