command-code 1.93.1 → 1.93.3

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 (102) hide show
  1. package/CHANGELOG.md +18 -1
  2. package/dist/bundled/agent-browser/SKILL.md +73 -0
  3. package/dist/bundled/command-code-knowledge/SKILL.md +68 -0
  4. package/dist/bundled/command-code-knowledge/live-models.ts +284 -0
  5. package/dist/bundled/command-code-knowledge/reference/byok.md +390 -0
  6. package/dist/bundled/command-code-knowledge/reference/custom-agents.md +341 -0
  7. package/dist/bundled/command-code-knowledge/reference/custom-slash-commands.md +423 -0
  8. package/dist/bundled/command-code-knowledge/reference/headless.md +381 -0
  9. package/dist/bundled/command-code-knowledge/reference/hooks.md +1107 -0
  10. package/dist/bundled/command-code-knowledge/reference/mcp.md +648 -0
  11. package/dist/bundled/command-code-knowledge/reference/memory.md +137 -0
  12. package/dist/bundled/command-code-knowledge/reference/models.md +145 -0
  13. package/dist/bundled/command-code-knowledge/reference/permissions.md +486 -0
  14. package/dist/bundled/command-code-knowledge/reference/plan-mode.md +283 -0
  15. package/dist/bundled/command-code-knowledge/reference/plans.md +16 -0
  16. package/dist/bundled/command-code-knowledge/reference/product-help.md +490 -0
  17. package/dist/bundled/command-code-knowledge/reference/sessions.md +377 -0
  18. package/dist/bundled/command-code-knowledge/reference/skills.md +1009 -0
  19. package/dist/bundled/command-code-knowledge/reference/tools.md +522 -0
  20. package/dist/bundled/config/SKILL.md +18 -0
  21. package/dist/bundled/config/references/permissions.md +27 -0
  22. package/dist/bundled/config/references/settings.md +50 -0
  23. package/dist/bundled/design/SKILL.md +448 -0
  24. package/dist/bundled/design/references/accessibility.md +404 -0
  25. package/dist/bundled/design/references/border.md +161 -0
  26. package/dist/bundled/design/references/button.md +192 -0
  27. package/dist/bundled/design/references/checkup.md +164 -0
  28. package/dist/bundled/design/references/color.md +245 -0
  29. package/dist/bundled/design/references/create.md +291 -0
  30. package/dist/bundled/design/references/design-html.md +227 -0
  31. package/dist/bundled/design/references/deslop.md +285 -0
  32. package/dist/bundled/design/references/finish.md +156 -0
  33. package/dist/bundled/design/references/interaction.md +186 -0
  34. package/dist/bundled/design/references/layout.md +216 -0
  35. package/dist/bundled/design/references/media.md +112 -0
  36. package/dist/bundled/design/references/motion.md +237 -0
  37. package/dist/bundled/design/references/redesign.md +197 -0
  38. package/dist/bundled/design/references/refine.md +193 -0
  39. package/dist/bundled/design/references/reflexes.md +132 -0
  40. package/dist/bundled/design/references/relayout.md +207 -0
  41. package/dist/bundled/design/references/report-html.md +235 -0
  42. package/dist/bundled/design/references/responsive.md +233 -0
  43. package/dist/bundled/design/references/review.md +164 -0
  44. package/dist/bundled/design/references/setup.md +119 -0
  45. package/dist/bundled/design/references/severity.md +111 -0
  46. package/dist/bundled/design/references/shadow.md +164 -0
  47. package/dist/bundled/design/references/smell.md +213 -0
  48. package/dist/bundled/design/references/style-3d.md +23 -0
  49. package/dist/bundled/design/references/style-bento.md +21 -0
  50. package/dist/bundled/design/references/style-editorial.md +23 -0
  51. package/dist/bundled/design/references/style-futuristic.md +21 -0
  52. package/dist/bundled/design/references/style-glassmorphism.md +52 -0
  53. package/dist/bundled/design/references/style-maximalism.md +20 -0
  54. package/dist/bundled/design/references/style-minimalism.md +21 -0
  55. package/dist/bundled/design/references/style-neo-brutalism.md +21 -0
  56. package/dist/bundled/design/references/style-retro-futurism.md +21 -0
  57. package/dist/bundled/design/references/style-swiss.md +20 -0
  58. package/dist/bundled/design/references/style.md +77 -0
  59. package/dist/bundled/design/references/surface.md +163 -0
  60. package/dist/bundled/design/references/system.md +73 -0
  61. package/dist/bundled/design/references/typeset.md +210 -0
  62. package/dist/bundled/design/references/variants.md +193 -0
  63. package/dist/bundled/design/references/voice.md +184 -0
  64. package/dist/bundled/design/references/writing.md +174 -0
  65. package/dist/bundled/design/scripts/check/color.mjs +213 -0
  66. package/dist/bundled/design/scripts/check/contrast.mjs +141 -0
  67. package/dist/bundled/design/scripts/check/css.mjs +223 -0
  68. package/dist/bundled/design/scripts/check/named-colors.mjs +152 -0
  69. package/dist/bundled/design/scripts/check/pair.mjs +61 -0
  70. package/dist/bundled/design/scripts/check/preview.mjs +27 -0
  71. package/dist/bundled/design/scripts/check/reflexes.mjs +257 -0
  72. package/dist/bundled/design/scripts/check/sources.mjs +237 -0
  73. package/dist/bundled/design/scripts/check.mjs +165 -0
  74. package/dist/bundled/loop/SKILL.md +16 -0
  75. package/dist/bundled/mod-builder/SKILL.md +135 -0
  76. package/dist/bundled/mod-builder/examples/block-dangerous-commands.ts +41 -0
  77. package/dist/bundled/mod-builder/examples/custom-entry-renderer.ts +32 -0
  78. package/dist/bundled/mod-builder/examples/custom-tool.ts +53 -0
  79. package/dist/bundled/mod-builder/examples/flags-and-options.ts +29 -0
  80. package/dist/bundled/mod-builder/examples/input-shortcuts.ts +41 -0
  81. package/dist/bundled/mod-builder/examples/kitchen-sink.ts +129 -0
  82. package/dist/bundled/mod-builder/examples/lifecycle-hooks.ts +64 -0
  83. package/dist/bundled/mod-builder/examples/model-router.ts +43 -0
  84. package/dist/bundled/mod-builder/examples/observe-events.ts +30 -0
  85. package/dist/bundled/mod-builder/examples/pane-and-buttons.ts +60 -0
  86. package/dist/bundled/mod-builder/examples/pane-form.ts +68 -0
  87. package/dist/bundled/mod-builder/examples/permission-policy.ts +34 -0
  88. package/dist/bundled/mod-builder/examples/redact-secrets.ts +46 -0
  89. package/dist/bundled/mod-builder/examples/slash-command.ts +33 -0
  90. package/dist/bundled/mod-builder/examples/spinner-count.ts +47 -0
  91. package/dist/bundled/mod-builder/examples/stream-filter.ts +70 -0
  92. package/dist/bundled/mod-builder/reference/api.md +140 -0
  93. package/dist/bundled/mod-builder/reference/hooks-and-events.md +347 -0
  94. package/dist/bundled/mod-builder/reference/overview.md +271 -0
  95. package/dist/bundled/mod-builder/reference/packaging.md +187 -0
  96. package/dist/bundled/mod-builder/reference/ui.md +253 -0
  97. package/dist/bundled/mod-builder/reference/verify.md +67 -0
  98. package/dist/bundled/skill-builder/SKILL.md +104 -0
  99. package/dist/cli.mjs +16 -0
  100. package/dist/index.mjs +2 -0
  101. package/package.json +1 -1
  102. package/vsix/commandcode-vscode.vsix +0 -0
@@ -0,0 +1,135 @@
1
+ ---
2
+ name: mod-builder
3
+ description: Build a Command Code mod (a loadable plugin) end to end — a TypeScript file that registers tools, slash commands, lifecycle hooks, event observers, input interception, custom renderers, flags, or a model provider through the ModApi. Use when the user wants to create, build, generate, or scaffold a mod, extend Command Code with custom behavior, add a custom tool or slash command, intercept input, block or rewrite tool calls, or turn a workflow into a reusable plugin.
4
+ ---
5
+
6
+ # Mod Builder
7
+
8
+ You are building a **mod**: a TypeScript file that Command Code discovers on disk and loads
9
+ onto its agent loop. A mod is the plugin unit — it can add tools the model calls, slash
10
+ commands, mutating lifecycle hooks, event observers, typed-input interception, custom feed
11
+ rendering, configurable flags, and model providers. This is the same API Command Code's own
12
+ built-in features (providers, titling, update notice) are written against.
13
+
14
+ Two resources ship next to this file — use them instead of searching the codebase:
15
+
16
+ - `examples/` — runnable, single-file example mods, one per capability. Read the one
17
+ closest to the job and adapt it.
18
+ - `reference/` — the full mods documentation, generated from the public docs
19
+ (commandcode.ai/docs/mods). This is the authoritative API reference:
20
+
21
+ <!-- generated:reference-index:start -->
22
+ - `reference/overview.md` — Mods
23
+ - `reference/api.md` — ModApi reference
24
+ - `reference/hooks-and-events.md` — Hooks and events
25
+ - `reference/ui.md` — UI surface
26
+ - `reference/packaging.md` — Install and share mods
27
+ - `reference/verify.md` — Verify a mod
28
+ <!-- generated:reference-index:end -->
29
+
30
+ ## 1. The shape of a mod
31
+
32
+ A mod is a file that default-exports a factory. The factory receives the API bound as `cmd`
33
+ and registers everything up front (it may be async):
34
+
35
+ ```typescript
36
+ import type {ModApi} from '@commandcode/harness';
37
+
38
+ export default function (cmd: ModApi) {
39
+ cmd.addCommand({name: 'hello', handler: () => ({message: 'hi from a mod'})});
40
+ }
41
+ ```
42
+
43
+ Save it at `~/.commandcode/mods/hello.ts` (personal) or `<project>/.commandcode/mods/hello.ts`
44
+ (project — loads once the workspace is trusted). It loads next session, or test it now with
45
+ `cmd --mod ./hello.ts`. No build step — jiti compiles the TypeScript at load.
46
+
47
+ ## 2. Pick the capability
48
+
49
+ Every registration verb is `add*` and returns a `Disposable` (`.dispose()` undoes it). Match
50
+ the job to the seam, then open the matching example file:
51
+
52
+ | The mod should… | Use | Example |
53
+ |---|---|---|
54
+ | add a `/command` | `cmd.addCommand({name, handler})` | `examples/slash-command.ts` |
55
+ | add a tool the model calls | `cmd.addTool({schema, run})` | `examples/custom-tool.ts` |
56
+ | block or rewrite a tool call | `cmd.hooks({beforeToolCall})` | `examples/block-dangerous-commands.ts` |
57
+ | rewrite or consume typed input | `cmd.hooks({transformInput})` | `examples/input-shortcuts.ts` |
58
+ | keep a finished run going / react to session start·end | `cmd.hooks({onStop, onSessionStart, onSessionEnd})` | `examples/lifecycle-hooks.ts` |
59
+ | react to what happens | `cmd.on(event, handler)` | `examples/observe-events.ts` |
60
+ | print custom styled feed rows | `cmd.addRenderer` + `cmd.showEntry` | `examples/custom-entry-renderer.ts` |
61
+ | take configurable options | `cmd.addFlag` + `cmd.getFlag` | `examples/flags-and-options.ts` |
62
+ | rewrite the answer as it streams / stream a process's output | `cmd.hooks({transformTextDelta})` + `cmd.process.spawn` | `examples/stream-filter.ts` |
63
+ | everything at once (a tour) | — | `examples/kitchen-sink.ts` |
64
+
65
+ ## 3. The one rule: hooks mutate, `on` observes
66
+
67
+ - **`cmd.hooks({...})`** is the only place that can change behavior — block a tool
68
+ (`beforeToolCall`), rewrite a result (`afterToolCall`), add to the prompt
69
+ (`appendSystemPrompt`), rewrite typed input (`transformInput`), force a finished run to
70
+ keep going (`onStop`), react to session start/end (`onSessionStart`/`onSessionEnd`), or run
71
+ post-turn work (`onRunEnd`). See `reference/hooks-and-events.md` for the full set. Multiple
72
+ `hooks()` calls compose in registration order.
73
+ - **`cmd.on(event, ...)`** only observes — it cannot block or rewrite. Handlers are isolated
74
+ (a throw becomes a `mod_error` event, never a crash).
75
+
76
+ If you find yourself wanting an `on` handler to stop a tool, you want a hook instead.
77
+
78
+ ## 4. Tools and commands, precisely
79
+
80
+ - **Tool `run`** receives `{input, runtime, signal}` and returns
81
+ `{ok: true, content: [{type: 'text', text}]}` or `{ok: false, error}`. Mark
82
+ `readOnly: true` when the tool never mutates (stays available in plan mode). A mod tool
83
+ whose name collides with an existing tool is skipped with a `mod_error` — pick a distinct,
84
+ namespaced name.
85
+ - **Command `handler`** returns DATA, never a live callback: `{prompt}` runs an automated
86
+ model turn, `{message}` renders an info row, nothing = pure side effect. It gets
87
+ `{args, ui, cwd, exec}`.
88
+
89
+ ## 5. Verify what you built
90
+
91
+ Do NOT declare the mod done until it demonstrably loads and its surface works. The loop
92
+ (full detail in `reference/verify.md`):
93
+
94
+ 1. **Load it without installing** — `cmd --mod ./your-mod.ts`. A file that fails to import,
95
+ exports no factory, or throws in its factory becomes a warning — never a crashed session —
96
+ so an unchecked mod can fail silently.
97
+ 2. **Confirm it registered** — `cmd mods list` must show the mod with zero load warnings.
98
+ If it is missing, the printed warning says why (import error, no default-export factory,
99
+ factory threw, duplicate name).
100
+ 3. **Exercise every registered surface** — a slash command must appear in `/` autocomplete
101
+ and run; a tool must be callable by the model by name; a hook must be triggered (ask for
102
+ the guarded action and watch the block/rewrite land); a widget/status must render around
103
+ the input panel.
104
+ 4. **Iterate with `/reload`** — mods load once per process; `/reload` restarts and
105
+ re-imports every mod.
106
+ 5. **Headless check when CI matters** — `cmd -p "…" --mod ./your-mod.ts`; dialogs resolve
107
+ deterministic defaults (confirm → false, select/input → undefined), so the mod must
108
+ behave sensibly under them.
109
+
110
+ Working inside the Command Code repo itself? The examples are validated by
111
+ `packages/harness/src/mod-host/__tests__/examples.test.ts` — run it after touching them, and
112
+ run `pnpm generate:knowledge` after editing the docs under `packages/docs/src/app/mods/`
113
+ (the `reference/` files here are generated from them).
114
+
115
+ ## 6. Ship it (optional)
116
+
117
+ - Personal: leave it in `~/.commandcode/mods/`.
118
+ - A package: a `package.json` with `{"keywords": ["cmd-mod"], "commandcode": {"mods": ["./index.ts"]}}`,
119
+ installed via `cmd mods add npm:<name>` / `cmd mods add owner/repo` / `cmd mods add ./local-dir`.
120
+ Include the exact `cmd-mod` keyword so maintainers can discover it for review.
121
+ After publishing with `pnpm publish`, submit an entry to `mods/registry.json`
122
+ in the public `CommandCodeAI/command-code` repo. Publishing alone does not list
123
+ a mod on the [mods hub](https://commandcode.ai/mods). The reviewed entry supplies
124
+ its description and categories; `npm` enables live package metadata and monthly
125
+ downloads, and a GitHub `repo` enables stars. Full packaging and submission
126
+ detail: `reference/packaging.md`.
127
+
128
+ ## Boundaries to state up front
129
+
130
+ - **No sandbox** — a mod is arbitrary code; install packages you trust. Project mods are
131
+ trust-gated like project skills.
132
+ - **Reload is `/reload`** — mods load once per process; `/reload` restarts and re-imports.
133
+ - **Providers extend, never replace** — `cmd.addProvider` adds to the provider set.
134
+ - **Rendering is line-based** — `cmd.addRenderer` returns styled text lines, not React
135
+ components, so a mod renders in any host and a broken renderer can't break the screen.
@@ -0,0 +1,41 @@
1
+ // Example mod: a policy guard that can BLOCK a tool call.
2
+ //
3
+ // cmd.hooks are the mutating lifecycle. `beforeToolCall` runs before every tool executes
4
+ // and may:
5
+ // return { block: true, additionalContext } → the call never runs; the model is told why
6
+ // return { input: rewritten } → the call runs with rewritten input
7
+ // return undefined → allow unchanged
8
+ //
9
+ // This is where you'd enforce org policy, sandbox paths, or require confirmation. The guard
10
+ // below refuses `rm -rf` and force-pushes unless the user confirms in the TUI.
11
+
12
+ import type {ModApi} from '@commandcode/harness';
13
+
14
+ const DANGEROUS = [
15
+ /\brm\s+-rf\b/,
16
+ /\bgit\s+push\b.*--force\b/,
17
+ /\bgit\s+push\s+-f\b/,
18
+ ];
19
+
20
+ export default function (cmd: ModApi): void {
21
+ cmd.hooks({
22
+ beforeToolCall: async ({toolName, input}) => {
23
+ if (toolName !== 'shell_command') return undefined;
24
+ const command =
25
+ typeof input.command === 'string' ? input.command : '';
26
+ if (!DANGEROUS.some(pattern => pattern.test(command)))
27
+ return undefined;
28
+
29
+ const allow = await cmd.ui.confirm({
30
+ title: 'Dangerous command',
31
+ message: `Allow: ${command}`,
32
+ });
33
+ if (allow) return undefined;
34
+ return {
35
+ block: true,
36
+ additionalContext:
37
+ 'Blocked by the safety mod. Ask the user to run this manually if it is really intended.',
38
+ };
39
+ },
40
+ });
41
+ }
@@ -0,0 +1,32 @@
1
+ // Example mod: render a custom entry into the feed with your own styling.
2
+ //
3
+ // Two pieces:
4
+ // cmd.addRenderer(type, data => lines) → registers how a custom entry type prints
5
+ // cmd.showEntry(type, data) → pushes an entry of that type into the live feed
6
+ //
7
+ // Rendering is line-based: the renderer returns styled terminal lines (use raw ansi escape
8
+ // codes, picocolors, or @commandcode/tui helpers). Unrendered types pretty-print as JSON.
9
+ // The TUI wires the feed sink; headless runs drop entries. A throwing renderer degrades to
10
+ // a warning notice, never a broken screen.
11
+ //
12
+ // Pair showEntry with cmd.session.appendCustomEntry when the data should also persist to
13
+ // the transcript.
14
+
15
+ import type {ModApi} from '@commandcode/harness';
16
+
17
+ const GREEN = '\x1b[32m';
18
+ const DIM = '\x1b[2m';
19
+ const RESET = '\x1b[0m';
20
+
21
+ export default function (cmd: ModApi): void {
22
+ cmd.addRenderer('score', data => {
23
+ const {label, value} = data as {label: string; value: number};
24
+ const bar = '█'.repeat(Math.max(0, Math.min(10, value)));
25
+ return [`${GREEN}${label}${RESET} ${bar} ${DIM}${value}/10${RESET}`];
26
+ });
27
+
28
+ // Show a scored entry whenever a run finishes (contrived — a real mod would compute it).
29
+ cmd.on('run_end', () => {
30
+ cmd.showEntry('score', {label: 'confidence', value: 8});
31
+ });
32
+ }
@@ -0,0 +1,53 @@
1
+ // Example mod: a tool the MODEL can call.
2
+ //
3
+ // cmd.addTool registers a ToolModule — the same shape the built-in tools use. The model
4
+ // sees the schema and decides when to call it; `run` receives the parsed input plus the
5
+ // harness Runtime (filesystem + shell), and returns a result:
6
+ // { ok: true, content: [{type: 'text', text}] } → success, text goes back to the model
7
+ // { ok: false, error } → the model sees the error and can retry
8
+ //
9
+ // Mark `readOnly: true` if the tool never mutates — it then stays available in plan mode
10
+ // and takes the read-only permission fast-path.
11
+
12
+ import type {ModApi} from '@commandcode/harness';
13
+
14
+ export default function (cmd: ModApi): void {
15
+ cmd.addTool({
16
+ schema: {
17
+ name: 'count_todos',
18
+ description:
19
+ 'Count TODO/FIXME markers across the repository and report the total.',
20
+ input_schema: {
21
+ type: 'object',
22
+ properties: {
23
+ path: {
24
+ type: 'string',
25
+ description:
26
+ 'Directory to search (defaults to the repo root).',
27
+ },
28
+ },
29
+ required: [],
30
+ },
31
+ },
32
+ readOnly: true,
33
+ run: async ({input}) => {
34
+ const path = typeof input.path === 'string' ? input.path : '.';
35
+ const result = await cmd.exec({
36
+ command: 'grep',
37
+ args: ['-rIoE', 'TODO|FIXME', path],
38
+ });
39
+ const count = result.stdout
40
+ .split('\n')
41
+ .filter(line => line.length > 0).length;
42
+ return {
43
+ ok: true,
44
+ content: [
45
+ {
46
+ type: 'text',
47
+ text: `${count} TODO/FIXME markers in ${path}`,
48
+ },
49
+ ],
50
+ };
51
+ },
52
+ });
53
+ }
@@ -0,0 +1,29 @@
1
+ // Example mod: declare configurable flags.
2
+ //
3
+ // cmd.addFlag declares a named option with a type and default. The user sets it at launch
4
+ // with repeatable `--mod-option name=value`:
5
+ // cmd --mod-option verbose=true --mod-option reviewer=alice
6
+ //
7
+ // Read the live value with cmd.getFlag(name). Boolean-declared flags coerce "true"/"false"
8
+ // text to a boolean; string flags keep the text verbatim. A flag only belongs to the mod
9
+ // that declared it.
10
+
11
+ import type {ModApi} from '@commandcode/harness';
12
+
13
+ export default function (cmd: ModApi): void {
14
+ cmd.addFlag('verbose', {
15
+ type: 'boolean',
16
+ default: false,
17
+ description: 'Announce every finished turn.',
18
+ });
19
+ cmd.addFlag('reviewer', {
20
+ type: 'string',
21
+ default: 'the team',
22
+ description: 'Who to address review summaries to.',
23
+ });
24
+
25
+ cmd.on('run_end', () => {
26
+ if (cmd.getFlag('verbose') !== true) return;
27
+ cmd.ui.notify(`turn done — summary is for ${cmd.getFlag('reviewer')}`);
28
+ });
29
+ }
@@ -0,0 +1,41 @@
1
+ // Example mod: intercept what the user types before the model sees it.
2
+ //
3
+ // hooks.transformInput runs on every typed user prompt. Return:
4
+ // { action: 'transform', text } → rewrite the prompt (handlers chain; the next
5
+ // mod sees your rewrite)
6
+ // { action: 'handled', message? } → consume the prompt entirely; no model turn runs
7
+ // (an optional info row renders in its place)
8
+ // { action: 'continue' } / undefined → pass through unchanged
9
+ //
10
+ // Automated turns, meta messages, slash commands, and image-carrying prompts never reach
11
+ // transformInput — it only sees text the USER typed. A throwing handler is skipped, never
12
+ // blocking the prompt.
13
+
14
+ import type {ModApi} from '@commandcode/harness';
15
+
16
+ const SHORTCUTS: Record<string, string> = {
17
+ '#ship':
18
+ 'Run the test suite, then the linter, then summarize what is left before this can ship.',
19
+ '#review': 'Review the current git diff for bugs and risky changes.',
20
+ };
21
+
22
+ export default function (cmd: ModApi): void {
23
+ cmd.hooks({
24
+ transformInput: ({text}) => {
25
+ const trimmed = text.trim();
26
+
27
+ // A local slash-like command handled entirely by the mod.
28
+ if (trimmed === '#help') {
29
+ return {
30
+ action: 'handled',
31
+ message: `Shortcuts: ${Object.keys(SHORTCUTS).join(', ')}`,
32
+ };
33
+ }
34
+
35
+ const expansion = SHORTCUTS[trimmed];
36
+ if (expansion) return {action: 'transform', text: expansion};
37
+
38
+ return {action: 'continue'};
39
+ },
40
+ });
41
+ }
@@ -0,0 +1,129 @@
1
+ // Example mod: the KITCHEN SINK — every ModApi capability in one file, so you can see how
2
+ // the pieces fit together. In practice a mod does one job; this one is a tour.
3
+ //
4
+ // A mod is a TypeScript file that default-exports a factory. The factory receives the API
5
+ // bound as `cmd` and registers everything up front. It may be async (await setup work
6
+ // before returning). Every registration returns a Disposable — call .dispose() to undo
7
+ // exactly that one registration.
8
+
9
+ import type {ModApi} from '@commandcode/harness';
10
+
11
+ export default function (cmd: ModApi): void {
12
+ // ── identity ──────────────────────────────────────────────────────────────────────
13
+ // cmd.name is this mod's name; cmd.cwd is the workspace root.
14
+
15
+ // ── flags: configurable options (cmd --mod-option strict=true) ──────────────────────
16
+ cmd.addFlag('strict', {type: 'boolean', default: false});
17
+
18
+ // ── hooks: the MUTATING lifecycle (compose in registration order) ───────────────────
19
+ cmd.hooks({
20
+ // Add to the system prompt every request.
21
+ appendSystemPrompt: () => 'Prefer small, reviewable diffs.',
22
+
23
+ // Rewrite or block a tool call before it runs.
24
+ beforeToolCall: async ({toolName, input}) => {
25
+ if (toolName !== 'shell_command') return undefined;
26
+ const command =
27
+ typeof input.command === 'string' ? input.command : '';
28
+ if (
29
+ cmd.getFlag('strict') === true &&
30
+ command.includes('--no-verify')
31
+ )
32
+ return {
33
+ block: true,
34
+ additionalContext: 'strict mode forbids --no-verify',
35
+ };
36
+ return undefined;
37
+ },
38
+
39
+ // Inspect or rewrite a tool result after it runs.
40
+ afterToolCall: async ({result}) => {
41
+ if (typeof result !== 'string' || !result.includes('DEPRECATED'))
42
+ return undefined;
43
+ return {
44
+ additionalContext:
45
+ 'A tool result mentioned DEPRECATED — flag it.',
46
+ };
47
+ },
48
+
49
+ // Intercept typed input before the model sees it.
50
+ transformInput: ({text}) =>
51
+ text.trim() === '#note'
52
+ ? {action: 'handled', message: 'noted.'}
53
+ : {action: 'continue'},
54
+
55
+ // Fires once the run completes (post-turn work).
56
+ onRunEnd: async () => {
57
+ cmd.showEntry('summary', {tools: 'see feed'});
58
+ },
59
+ });
60
+
61
+ // ── a tool the model can call ───────────────────────────────────────────────────────
62
+ cmd.addTool({
63
+ schema: {
64
+ name: 'repo_size',
65
+ description: 'Report the number of tracked files.',
66
+ input_schema: {type: 'object', properties: {}, required: []},
67
+ },
68
+ readOnly: true,
69
+ run: async () => {
70
+ const {stdout} = await cmd.exec({
71
+ command: 'git',
72
+ args: ['ls-files'],
73
+ });
74
+ const count = stdout.split('\n').filter(Boolean).length;
75
+ return {
76
+ ok: true,
77
+ content: [{type: 'text', text: `${count} tracked files`}],
78
+ };
79
+ },
80
+ });
81
+
82
+ // ── a slash command ─────────────────────────────────────────────────────────────────
83
+ cmd.addCommand({
84
+ name: 'sink-status',
85
+ description: 'Show mod status',
86
+ handler: () => ({message: `strict = ${cmd.getFlag('strict')}`}),
87
+ });
88
+
89
+ // ── a custom feed renderer + the entry it renders ──────────────────────────────────
90
+ cmd.addRenderer('summary', data => [`◆ summary: ${JSON.stringify(data)}`]);
91
+
92
+ // ── observe events (never mutate here) ──────────────────────────────────────────────
93
+ cmd.on('tool_errored', () => cmd.ui.notify('a tool errored', 'warning'));
94
+
95
+ // ── a keyboard shortcut (interactive TUI only; dispatched after host bindings) ──────
96
+ cmd.addShortcut('alt+u', {
97
+ description: 'Show context usage',
98
+ handler: () => {
99
+ const usage = cmd.getContextUsage();
100
+ if (!usage || usage.percent === null)
101
+ return {message: 'context window not measured yet'};
102
+ return {
103
+ message: `${cmd.getModel()} · ${usage.percent}% of ${usage.contextWindow} tokens`,
104
+ };
105
+ },
106
+ });
107
+
108
+ // ── skills shipped beside this mod (resolved against this file) ────────────────────
109
+ // cmd.addSkillsPath('./skills');
110
+
111
+ // ── live surfaces (usable any time after the harness binds) ─────────────────────────
112
+ // cmd.ui.notify / confirm / select / input — talk to the user; ui.setTitle — the tab.
113
+ // cmd.queueMessage({content, deliverAs}) — steer the running loop or queue a follow-up.
114
+ // cmd.sendUserMessage(text) — a real user turn (starts one when idle).
115
+ // cmd.session — durable custom-entry persistence (undefined until bound).
116
+ // cmd.sessions — compact(), tree(), leafId(), navigateTree(...), setLabel(...).
117
+ // cmd.setModel / setEffort / setSessionName, and their get* counterparts.
118
+ // cmd.getContextUsage / getCommands / getToolInfo / isIdle — live reads.
119
+ // cmd.getAllTools / getActiveTools / setActiveTools — a mod-managed tool filter.
120
+ // cmd.shutdown() — exit once the turn settles.
121
+ //
122
+ // Example: on the first run, greet once via a queued steering message.
123
+ let greeted = false;
124
+ cmd.on('run_start', () => {
125
+ if (greeted) return;
126
+ greeted = true;
127
+ cmd.queueMessage({content: 'Remember to keep the change focused.'});
128
+ });
129
+ }
@@ -0,0 +1,64 @@
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
+ }
@@ -0,0 +1,43 @@
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
+ }
@@ -0,0 +1,30 @@
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
+ }
@@ -0,0 +1,60 @@
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
+ }