@knightcodeai/cli-linux-arm64 0.9.1 → 0.9.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 (45) hide show
  1. package/bin/CHANGELOG.md +60 -0
  2. package/bin/README.md +52 -19
  3. package/bin/docs/cli-integration.md +106 -0
  4. package/bin/docs/cli.md +270 -0
  5. package/bin/docs/compaction.md +56 -37
  6. package/bin/docs/configuration.md +46 -0
  7. package/bin/docs/containerization.md +86 -54
  8. package/bin/docs/custom-provider.md +132 -785
  9. package/bin/docs/docs.json +143 -103
  10. package/bin/docs/environment-variables.md +5 -4
  11. package/bin/docs/extensions.md +134 -2956
  12. package/bin/docs/how-knightcode-works.md +49 -0
  13. package/bin/docs/index.md +24 -69
  14. package/bin/docs/json.md +193 -65
  15. package/bin/docs/keybindings.md +56 -101
  16. package/bin/docs/llama-cpp.md +3 -3
  17. package/bin/docs/message-types.md +261 -0
  18. package/bin/docs/models.md +64 -547
  19. package/bin/docs/packages.md +66 -167
  20. package/bin/docs/prompt-templates.md +31 -68
  21. package/bin/docs/providers.md +103 -241
  22. package/bin/docs/quickstart.md +61 -106
  23. package/bin/docs/rpc-commands.md +854 -0
  24. package/bin/docs/rpc-extension-ui.md +200 -0
  25. package/bin/docs/rpc.md +129 -1556
  26. package/bin/docs/sdk.md +76 -1160
  27. package/bin/docs/security.md +70 -32
  28. package/bin/docs/session-format.md +25 -216
  29. package/bin/docs/sessions.md +38 -143
  30. package/bin/docs/settings.md +111 -389
  31. package/bin/docs/shell-aliases.md +85 -5
  32. package/bin/docs/skills.md +51 -189
  33. package/bin/docs/slash-commands.md +63 -0
  34. package/bin/docs/terminal-setup.md +107 -79
  35. package/bin/docs/termux.md +74 -83
  36. package/bin/docs/themes.md +68 -280
  37. package/bin/docs/tmux.md +31 -39
  38. package/bin/docs/tui.md +69 -923
  39. package/bin/docs/usage.md +79 -286
  40. package/bin/docs/windows.md +43 -17
  41. package/bin/export-html/template.js +6 -1
  42. package/bin/knightcode +2 -2
  43. package/bin/package.json +6 -6
  44. package/package.json +1 -1
  45. package/bin/docs/development.md +0 -71
@@ -1,3037 +1,215 @@
1
- > knightcode can create extensions. Ask it to build one for your use case.
2
-
3
- # Extensions
4
-
5
- Extensions are TypeScript modules that extend knightcode's behavior. They can subscribe to lifecycle events, register custom tools callable by the LLM, add commands, and more.
6
-
7
- > **Placement for /reload:** Put extensions in `~/.knightcode/agent/extensions/` (global) or `.knightcode/extensions/` (project-local) for auto-discovery. Use `knightcode -e ./path.ts` only for quick tests. Extensions in auto-discovered locations can be hot-reloaded with `/reload`.
8
-
9
- **Key capabilities:**
10
- - **Custom tools** - Register tools the LLM can call via `knightcode.registerTool()`
11
- - **Event interception** - Block or modify tool calls, inject context, customize compaction
12
- - **User interaction** - Prompt users via `ctx.ui` (select, confirm, input, notify)
13
- - **Custom UI components** - Full TUI components with keyboard input via `ctx.ui.custom()` for complex interactions
14
- - **Custom commands** - Register commands like `/mycommand` via `knightcode.registerCommand()`
15
- - **Session persistence** - Store state that survives restarts via `knightcode.appendEntry()`
16
- - **Custom rendering** - Control how tool calls/results and messages appear in TUI
17
-
18
- **Example use cases:**
19
- - Permission gates (confirm before `rm -rf`, `sudo`, etc.)
20
- - Git checkpointing (stash at each turn, restore on branch)
21
- - Path protection (block writes to `.env`, `node_modules/`)
22
- - Custom compaction (summarize conversation your way)
23
- - Conversation summaries (see `summarize.ts` example)
24
- - Interactive tools (questions, wizards, custom dialogs)
25
- - Stateful tools (todo lists, connection pools)
26
- - External integrations (file watchers, webhooks, CI triggers)
27
- - Games while you wait (see `snake.ts` example)
28
-
29
- See [examples/extensions/](../examples/extensions/) for working implementations.
30
-
31
- ## Table of Contents
32
-
33
- - [Quick Start](#quick-start)
34
- - [Extension Locations](#extension-locations)
35
- - [Available Imports](#available-imports)
36
- - [Writing an Extension](#writing-an-extension)
37
- - [Extension Styles](#extension-styles)
38
- - [Events](#events)
39
- - [Lifecycle Overview](#lifecycle-overview)
40
- - [Resource Events](#resource-events)
41
- - [Session Events](#session-events)
42
- - [Agent Events](#agent-events)
43
- - [Model Events](#model-events)
44
- - [Tool Events](#tool-events)
45
- - [ExtensionContext](#extensioncontext)
46
- - [ExtensionCommandContext](#extensioncommandcontext)
47
- - [ExtensionAPI Methods](#extensionapi-methods)
48
- - [State Management](#state-management)
49
- - [Custom Tools](#custom-tools)
50
- - [Dynamic Tool Loading](#dynamic-tool-loading)
51
- - [Custom UI](#custom-ui)
52
- - [Error Handling](#error-handling)
53
- - [Mode Behavior](#mode-behavior)
54
- - [Examples Reference](#examples-reference)
55
-
56
- ## Quick Start
57
-
58
- Create `~/.knightcode/agent/extensions/my-extension.ts`:
59
-
60
- ```typescript
61
- import type { ExtensionAPI } from "@knightcodeai/cli";
62
- import { Type } from "typebox";
63
-
64
- export default function (knightcode: ExtensionAPI) {
65
- // React to events
66
- knightcode.on("session_start", async (_event, ctx) => {
67
- ctx.ui.notify("Extension loaded!", "info");
68
- });
69
-
70
- knightcode.on("tool_call", async (event, ctx) => {
71
- if (event.toolName === "bash" && event.input.command?.includes("rm -rf")) {
72
- const ok = await ctx.ui.confirm("Dangerous!", "Allow rm -rf?");
73
- if (!ok) return { block: true, reason: "Blocked by user" };
74
- }
75
- });
76
-
77
- // Register a custom tool
78
- knightcode.registerTool({
79
- name: "greet",
80
- label: "Greet",
81
- description: "Greet someone by name",
82
- parameters: Type.Object({
83
- name: Type.String({ description: "Name to greet" }),
84
- }),
85
- async execute(toolCallId, params, signal, onUpdate, ctx) {
86
- return {
87
- content: [{ type: "text", text: `Hello, ${params.name}!` }],
88
- details: {},
89
- };
90
- },
91
- });
92
-
93
- // Register a command
94
- knightcode.registerCommand("hello", {
95
- description: "Say hello",
96
- handler: async (args, ctx) => {
97
- ctx.ui.notify(`Hello ${args || "world"}!`, "info");
98
- },
99
- });
100
- }
101
- ```
102
-
103
- Test with `--extension` (or `-e`) flag:
104
-
105
- ```bash
106
- knightcode -e ./my-extension.ts
107
- ```
108
-
109
- ## Extension Locations
110
-
111
- > **Security:** Extensions run with your full system permissions and can execute arbitrary code. Only install from sources you trust.
112
-
113
- Extensions are auto-discovered from trusted locations. Project-local `.knightcode/extensions` entries load only after the project is trusted.
114
-
115
- | Location | Scope |
116
- |----------|-------|
117
- | `~/.knightcode/agent/extensions/*.ts` | Global (all projects) |
118
- | `~/.knightcode/agent/extensions/*/index.ts` | Global (subdirectory) |
119
- | `.knightcode/extensions/*.ts` | Project-local |
120
- | `.knightcode/extensions/*/index.ts` | Project-local (subdirectory) |
121
-
122
- Additional paths via `settings.json`:
123
-
124
- ```json
125
- {
126
- "packages": [
127
- "npm:@foo/bar@1.0.0",
128
- "git:github.com/user/repo@v1"
129
- ],
130
- "extensions": [
131
- "/path/to/local/extension.ts",
132
- "/path/to/local/extension/dir"
133
- ]
134
- }
135
- ```
136
-
137
- To share extensions via npm or git as knightcode packages, see [packages.md](packages.md).
138
-
139
- ## Available Imports
140
-
141
- | Package | Purpose |
142
- |---------|---------|
143
- | `@knightcodeai/cli` | Extension types (`ExtensionAPI`, `ExtensionContext`, events) |
144
- | `typebox` | Schema definitions for tool parameters |
145
- | `@knightcode/ai` | AI utilities (`StringEnum` for Google-compatible enums) |
146
- | `@knightcode/tui` | TUI components for custom rendering |
147
-
148
- npm dependencies work too. Add a `package.json` next to your extension (or in a parent directory), run `npm install`, and imports from `node_modules/` are resolved automatically.
149
-
150
- For distributed knightcode packages installed with `knightcode install` (npm or git), runtime deps must be in `dependencies`. Package installation uses production installs (`npm install --omit=dev`) by default, so `devDependencies` are not available at runtime; when `npmCommand` is configured, git packages use plain `install` for compatibility with wrappers.
151
-
152
- Node.js built-ins (`node:fs`, `node:path`, etc.) are also available.
153
-
154
- ## Writing an Extension
155
-
156
- An extension exports a default factory function that receives `ExtensionAPI`. The factory can be synchronous or asynchronous:
157
-
158
- ```typescript
159
- import type { ExtensionAPI } from "@knightcodeai/cli";
160
-
161
- export default function (knightcode: ExtensionAPI) {
162
- // Subscribe to events
163
- knightcode.on("event_name", async (event, ctx) => {
164
- // ctx.ui for user interaction
165
- const ok = await ctx.ui.confirm("Title", "Are you sure?");
166
- ctx.ui.notify("Done!", "info");
167
- ctx.ui.setStatus("my-ext", "Processing..."); // Footer status
168
- ctx.ui.setWidget("my-ext", ["Line 1", "Line 2"]); // Widget above editor (default)
169
- });
170
-
171
- // Register tools, commands, shortcuts, flags
172
- knightcode.registerTool({ ... });
173
- knightcode.registerCommand("name", { ... });
174
- knightcode.registerShortcut("ctrl+x", { ... });
175
- knightcode.registerFlag("my-flag", { ... });
176
- }
177
- ```
178
-
179
- Extensions are loaded via [jiti](https://github.com/unjs/jiti), so TypeScript works without compilation.
180
-
181
- If the factory returns a `Promise`, knightcode awaits it before continuing startup. That means async initialization completes before `session_start`, before `resources_discover`, and before provider registrations queued via `knightcode.registerProvider()` are flushed.
182
-
183
- ### Async factory functions
184
-
185
- Use an async factory for one-time startup work such as fetching remote configuration or dynamically discovering available models.
186
-
187
- ```typescript
188
- import type { ExtensionAPI } from "@knightcodeai/cli";
189
-
190
- export default async function (knightcode: ExtensionAPI) {
191
- const response = await fetch("http://localhost:1234/v1/models");
192
- const payload = (await response.json()) as {
193
- data: Array<{
194
- id: string;
195
- name?: string;
196
- context_window?: number;
197
- max_tokens?: number;
198
- }>;
199
- };
200
-
201
- knightcode.registerProvider("local-openai", {
202
- baseUrl: "http://localhost:1234/v1",
203
- apiKey: "$LOCAL_OPENAI_API_KEY",
204
- api: "openai-completions",
205
- models: payload.data.map((model) => ({
206
- id: model.id,
207
- name: model.name ?? model.id,
208
- reasoning: false,
209
- input: ["text"],
210
- cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
211
- contextWindow: model.context_window ?? 128000,
212
- maxTokens: model.max_tokens ?? 4096,
213
- })),
214
- });
215
- }
216
- ```
217
-
218
- This pattern makes the fetched models available during normal startup and to `knightcode --list-models`.
219
-
220
- ### Long-lived resources and shutdown
221
-
222
- Extension factories may run in invocations that never start a session. Do not start background resources such as processes, sockets, file watchers, or timers from the factory.
223
-
224
- Defer background resource startup until `session_start` or the command/tool/event that needs the resource. Register an idempotent `session_shutdown` handler to close any session-scoped resources you start.
225
-
226
- ### Extension Styles
227
-
228
- **Single file** - simplest, for small extensions:
229
-
230
- ```
231
- ~/.knightcode/agent/extensions/
232
- └── my-extension.ts
233
- ```
234
-
235
- **Directory with index.ts** - for multi-file extensions:
236
-
237
- ```
238
- ~/.knightcode/agent/extensions/
239
- └── my-extension/
240
- ├── index.ts # Entry point (exports default function)
241
- ├── tools.ts # Helper module
242
- └── utils.ts # Helper module
243
- ```
244
-
245
- **Package with dependencies** - for extensions that need npm packages:
246
-
247
- ```
248
- ~/.knightcode/agent/extensions/
249
- └── my-extension/
250
- ├── package.json # Declares dependencies and entry points
251
- ├── package-lock.json
252
- ├── node_modules/ # After npm install
253
- └── src/
254
- └── index.ts
255
- ```
256
-
257
- ```json
258
- // package.json
259
- {
260
- "name": "my-extension",
261
- "dependencies": {
262
- "zod": "^3.0.0",
263
- "chalk": "^5.0.0"
264
- },
265
- "knightcode": {
266
- "extensions": ["./src/index.ts"]
267
- }
268
- }
269
- ```
270
-
271
- Run `npm install` in the extension directory, then imports from `node_modules/` work automatically.
272
-
273
- ## Events
274
-
275
- ### Lifecycle Overview
276
-
277
- ```
278
- knightcode starts
279
- │
280
- ├─► project_trust (user/global and CLI extensions only, before project resources load)
281
- ├─► session_start { reason: "startup" }
282
- └─► resources_discover { reason: "startup" }
283
- │
284
- ▼
285
- user sends prompt ─────────────────────────────────────────┐
286
- │ │
287
- ├─► (extension commands checked first, bypass if found) │
288
- ├─► input (can intercept, transform, or handle) │
289
- ├─► (skill/template expansion if not handled) │
290
- ├─► before_agent_start (can inject message, modify system prompt)
291
- ├─► agent_start │
292
- ├─► message_start / message_update / message_end │
293
- │ │
294
- │ ┌─── turn (repeats while LLM calls tools) ───┐ │
295
- │ │ │ │
296
- │ ├─► turn_start │ │
297
- │ ├─► context (can modify messages) │ │
298
- │ ├─► before_provider_headers (can mutate headers) |
299
- │ ├─► before_provider_request (can inspect or replace payload)
300
- │ ├─► after_provider_response (status + headers, before stream consume)
301
- │ │ │ │
302
- │ │ LLM responds, may call tools: │ │
303
- │ │ ├─► tool_execution_start │ │
304
- │ │ ├─► tool_call (can block) │ │
305
- │ │ ├─► tool_execution_update │ │
306
- │ │ ├─► tool_result (can modify) │ │
307
- │ │ └─► tool_execution_end │ │
308
- │ │ │ │
309
- │ └─► turn_end │ │
310
- │ │
311
- ├─► agent_end │
312
- └─► agent_settled (no retry/compaction/follow-up left) │
313
- │
314
- user sends another prompt ◄────────────────────────────────┘
315
-
316
- /new (new session) or /resume (switch session)
317
- ├─► session_before_switch (can cancel)
318
- ├─► session_shutdown
319
- ├─► session_start { reason: "new" | "resume", previousSessionFile? }
320
- └─► resources_discover { reason: "startup" }
321
-
322
- /fork or /clone
323
- ├─► session_before_fork (can cancel)
324
- ├─► session_shutdown
325
- ├─► session_start { reason: "fork", previousSessionFile }
326
- └─► resources_discover { reason: "startup" }
327
-
328
- /name or knightcode.setSessionName()
329
- └─► session_info_changed
330
-
331
- /compact or auto-compaction
332
- ├─► session_before_compact (can cancel or customize)
333
- ├─► session_compact (success)
334
- └─► session_compact_failed (failure or abort)
335
-
336
- /tree, /undo, or double-Escape navigation
337
- ├─► session_before_tree (can cancel or customize)
338
- └─► session_tree
339
-
340
- /model or Ctrl+P (model selection/cycling)
341
- ├─► thinking_level_select (if model change changes/clamps thinking level)
342
- └─► model_select
343
-
344
- thinking level changes (settings, keybinding, knightcode.setThinkingLevel())
345
- └─► thinking_level_select
346
-
347
- exit (Ctrl+C, Ctrl+D, SIGHUP, SIGTERM)
348
- └─► session_shutdown
349
- ```
350
-
351
- ### Startup Events
352
-
353
- #### project_trust
354
-
355
- Fired before knightcode decides whether to trust a project with dynamic configs (`.knightcode` or `.agents/skills`). It runs during startup and when session replacement (for example `/resume`) enters a cwd whose trust has not been resolved in the current process. Only user/global extensions and CLI `-e` extensions participate; project-local extensions are not loaded until after trust is resolved.
356
-
357
- ```typescript
358
- knightcode.on("project_trust", async (event, ctx) => {
359
- // event.cwd - current working directory
360
- // ctx has a limited trust context: cwd, mode, hasUI, and select/confirm/input/notify UI helpers
361
- if (await ctx.ui.confirm("Trust project?", event.cwd)) {
362
- return { trusted: "yes", remember: true };
363
- }
364
- return { trusted: "undecided" };
365
- });
366
- ```
367
-
368
- A `project_trust` handler must return `{ trusted: "yes" | "no" | "undecided" }`. A user/global or CLI extension that returns `"yes"` or `"no"` owns the decision; the first yes/no decision wins and suppresses the built-in trust prompt. Use `remember: true` to persist a yes/no decision; otherwise it applies only to the current process. Return `"undecided"` to let later handlers or the built-in trust flow decide. Check `ctx.hasUI` before prompting. If no handler returns yes/no, normal trust resolution continues: saved `trust.json` decisions apply first, then `defaultProjectTrust` controls whether knightcode asks, trusts, or declines by default.
369
-
370
- ### Resource Events
371
-
372
- #### resources_discover
373
-
374
- Fired after `session_start` so extensions can contribute additional skill, prompt, and theme paths.
375
- The startup path uses `reason: "startup"`. Reload uses `reason: "reload"`.
376
-
377
- ```typescript
378
- knightcode.on("resources_discover", async (event, _ctx) => {
379
- // event.cwd - current working directory
380
- // event.reason - "startup" | "reload"
381
- return {
382
- skillPaths: ["/path/to/skills"],
383
- promptPaths: ["/path/to/prompts"],
384
- themePaths: ["/path/to/themes"],
385
- };
386
- });
387
- ```
388
-
389
- ### Session Events
390
-
391
- See [Session Format](session-format.md) for session storage internals and the SessionManager API.
392
-
393
- #### session_start
394
-
395
- Fired when a session is started, loaded, or reloaded.
396
-
397
- ```typescript
398
- knightcode.on("session_start", async (event, ctx) => {
399
- // event.reason - "startup" | "reload" | "new" | "resume" | "fork"
400
- // event.previousSessionFile - present for "new", "resume", and "fork"
401
- ctx.ui.notify(`Session: ${ctx.sessionManager.getSessionFile() ?? "ephemeral"}`, "info");
402
- });
403
- ```
404
-
405
- #### session_info_changed
406
-
407
- Fired when the current session display name is set via `/name`, RPC, or `knightcode.setSessionName()`.
408
-
409
- ```typescript
410
- knightcode.on("session_info_changed", async (event, ctx) => {
411
- // event.name - current normalized name, or undefined if cleared
412
- ctx.ui.notify(`Session renamed: ${event.name ?? "(none)"}`, "info");
413
- });
414
- ```
415
-
416
- #### session_before_switch
417
-
418
- Fired before starting a new session (`/new`) or switching sessions (`/resume`).
419
-
420
- ```typescript
421
- knightcode.on("session_before_switch", async (event, ctx) => {
422
- // event.reason - "new" or "resume"
423
- // event.targetSessionFile - session we're switching to (only for "resume")
424
-
425
- if (event.reason === "new") {
426
- const ok = await ctx.ui.confirm("Clear?", "Delete all messages?");
427
- if (!ok) return { cancel: true };
428
- }
429
- });
430
- ```
431
-
432
- After a successful switch or new-session action, knightcode emits `session_shutdown` for the old extension instance, reloads and rebinds extensions for the new session, then emits `session_start` with `reason: "new" | "resume"` and `previousSessionFile`.
433
- Do cleanup work in `session_shutdown`, then reestablish any in-memory state in `session_start`.
434
-
435
- #### session_before_fork
436
-
437
- Fired when forking via `/fork` or cloning via `/clone`.
438
-
439
- ```typescript
440
- knightcode.on("session_before_fork", async (event, ctx) => {
441
- // event.entryId - ID of the selected entry
442
- // event.position - "before" for /fork, "at" for /clone
443
- return { cancel: true }; // Cancel fork/clone
444
- // OR
445
- return { skipConversationRestore: true }; // Reserved for future conversation restore control
446
- });
447
- ```
448
-
449
- After a successful fork or clone, knightcode emits `session_shutdown` for the old extension instance, reloads and rebinds extensions for the new session, then emits `session_start` with `reason: "fork"` and `previousSessionFile`.
450
- Do cleanup work in `session_shutdown`, then reestablish any in-memory state in `session_start`.
451
-
452
- #### session_before_compact / session_compact / session_compact_failed
453
-
454
- Fired on compaction. See [compaction.md](compaction.md) for details.
455
-
456
- ```typescript
457
- knightcode.on("session_before_compact", async (event, ctx) => {
458
- const { preparation, branchEntries, customInstructions, reason, willRetry, signal } = event;
459
-
460
- // reason - "manual" (/compact), "threshold", or "overflow"
461
- // willRetry - whether the aborted turn is retried after compaction (overflow recovery)
462
-
463
- // Cancel:
464
- return { cancel: true };
465
-
466
- // Custom summary:
467
- return {
468
- compaction: {
469
- summary: "...",
470
- firstKeptEntryId: preparation.firstKeptEntryId,
471
- tokensBefore: preparation.tokensBefore,
472
- // usage: summaryResponse.usage, // Optional; included in session totals
473
- }
474
- };
475
- });
476
-
477
- knightcode.on("session_compact", async (event, ctx) => {
478
- // event.compactionEntry - the saved compaction
479
- // event.fromExtension - whether extension provided it
480
- // event.reason - "manual" (/compact), "threshold", or "overflow"
481
- // event.willRetry - whether the aborted turn is retried after compaction (overflow recovery)
482
- });
483
-
484
- knightcode.on("session_compact_failed", async (event, ctx) => {
485
- // event.reason - "manual" (/compact), "threshold", or "overflow"
486
- // event.errorMessage - present for non-abort failures
487
- // event.aborted - true for cancelled/aborted compactions
488
- // event.willRetry - whether the aborted turn would have retried after compaction
489
- // event.fromExtension - whether extension-provided compaction content was being used
490
- });
491
- ```
492
-
493
- #### session_before_tree / session_tree
494
-
495
- Fired on `/tree`, `/undo`, and double-Escape navigation. See [Sessions](sessions.md) for tree navigation concepts.
496
-
497
- ```typescript
498
- knightcode.on("session_before_tree", async (event, ctx) => {
499
- const { preparation, signal } = event;
500
- return { cancel: true };
501
- // OR provide custom summary:
502
- return {
503
- summary: {
504
- summary: "...",
505
- // usage: summaryResponse.usage, // Optional; included in session totals
506
- details: {},
507
- },
508
- };
509
- });
510
-
511
- knightcode.on("session_tree", async (event, ctx) => {
512
- // event.newLeafId, oldLeafId, summaryEntry, fromExtension
513
- });
514
- ```
515
-
516
- #### session_shutdown
517
-
518
- Fired before a started session runtime is torn down. Use this to clean up resources opened from `session_start` or other session-scoped hooks.
519
-
520
- ```typescript
521
- knightcode.on("session_shutdown", async (event, ctx) => {
522
- // event.reason - "quit" | "reload" | "new" | "resume" | "fork"
523
- // event.targetSessionFile - destination session for session replacement flows
524
- // Cleanup, save state, etc.
525
- });
526
- ```
527
-
528
- ### Agent Events
529
-
530
- #### before_agent_start
531
-
532
- Fired after user submits prompt, before agent loop. Can inject a message and/or modify the system prompt.
533
-
534
- ```typescript
535
- knightcode.on("before_agent_start", async (event, ctx) => {
536
- // event.prompt - user's prompt text
537
- // event.images - attached images (if any)
538
- // event.systemPrompt - current chained system prompt for this handler
539
- // (includes changes from earlier before_agent_start handlers)
540
- // event.systemPromptOptions - structured options used to build the system prompt
541
- // .customPrompt - exact prompt prefix from --system-prompt, SYSTEM.md, or custom templates
542
- // .forceSystemPrompt - optional exact replacement for the complete prompt
543
- // .selectedTools - tools currently active in the prompt
544
- // .toolSnippets - one-line descriptions for each tool
545
- // .toolGuidelines - guideline bullets keyed by tool name
546
- // .promptGuidelines - additional custom guideline bullets
547
- // .sections - custom XML-wrapped sections keyed by tag name
548
- // .appendSystemPrompt - text from --append-system-prompt flags
549
- // .cwd - working directory
550
- // .contextFiles - AGENTS.md files and other loaded context files
551
- // .skills - loaded skills
552
-
553
- return {
554
- // Inject a persistent message (stored in session, sent to LLM)
555
- message: {
556
- customType: "my-extension",
557
- content: "Additional context for the LLM",
558
- display: true,
559
- },
560
- // Replace the system prompt for this turn (chained across extensions)
561
- systemPrompt: event.systemPrompt + "\n\nExtra instructions for this turn...",
562
- };
563
- });
564
- ```
565
-
566
- The `systemPromptOptions` field gives extensions access to the same structured data KnightCode uses to build the system prompt. Collections are mutable. Prefer changing `sections`, `selectedTools`, or `promptGuidelines`: KnightCode diffs the resulting prompt sections against what the model already has and appends one system message patching only the changed sections. Returning `systemPrompt`, or setting `forceSystemPrompt`, replaces the whole prompt for the run: every provider receives the forced text as its leading system prompt (a cache miss when it changes), and the session transcript keeps recording the structured sections. Tool selection changes update both the prompt contributions and executable provider tools; calling `knightcode.setActiveTools()` inside the handler has the same effect as editing `selectedTools`. Models that accept system messages mid-conversation receive the patch in place and keep their cached prefix; other models get the replayed prompt as their system prompt, which is a cache miss once per change.
567
-
568
- Inside `before_agent_start`, `event.systemPrompt` and `ctx.getSystemPrompt()` both reflect the chained system prompt as of the current handler. Later `before_agent_start` handlers can still modify it again.
569
-
570
- #### agent_start / agent_end / agent_settled
571
-
572
- `agent_start` fires when a low-level agent run begins. `agent_end` fires when that run ends, but KnightCode may still auto-retry, auto-compact and retry, or continue with queued follow-up messages. Use `agent_settled` for status integrations that need to know KnightCode will not continue running automatically.
573
-
574
- ```typescript
575
- knightcode.on("agent_start", async (_event, ctx) => {});
576
-
577
- knightcode.on("agent_end", async (event, ctx) => {
578
- // event.messages - messages from this low-level run
579
- });
580
-
581
- knightcode.on("agent_settled", async (_event, ctx) => {
582
- // ctx.isIdle() is true here unless another extension started a new run.
583
- });
584
- ```
585
-
586
- #### ui_prompt_start / ui_prompt_end
587
-
588
- Notification-only lifecycle events for blocking user-facing extension UI prompts. They fire around `ctx.ui.select()`, `ctx.ui.confirm()`, `ctx.ui.input()`, `ctx.ui.editor()`, and `ctx.ui.custom()` so host/status integrations can report "waiting for user" instead of just "running".
589
-
590
- Nested or overlapping prompts are coalesced into one outer waiting span. Handlers are invoked best-effort and are not awaited before showing or closing the prompt.
591
-
592
- ```typescript
593
- knightcode.on("ui_prompt_start", async (event, ctx) => {
594
- // event.reason === "ui_prompt"
595
- // event.kind: "select" | "confirm" | "input" | "editor" | "custom"
596
- // event.title: prompt title when available
597
- });
598
-
599
- knightcode.on("ui_prompt_end", async (event, ctx) => {
600
- // KnightCode is no longer waiting on that UI prompt span.
601
- });
602
- ```
603
-
604
- #### turn_start / turn_end
605
-
606
- Fired for each turn (one LLM response + tool calls).
607
-
608
- ```typescript
609
- knightcode.on("turn_start", async (event, ctx) => {
610
- // event.turnIndex, event.timestamp
611
- });
612
-
613
- knightcode.on("turn_end", async (event, ctx) => {
614
- // event.turnIndex, event.message, event.toolResults
615
- });
616
- ```
617
-
618
- #### message_start / message_update / message_end
619
-
620
- Fired for message lifecycle updates.
621
-
622
- - `message_start` and `message_end` fire for user, assistant, and toolResult messages.
623
- - `message_update` fires for assistant streaming updates.
624
- - `message_end` handlers can return `{ message }` to replace the finalized message. The replacement must keep the same `role`.
625
-
626
- ```typescript
627
- knightcode.on("message_start", async (event, ctx) => {
628
- // event.message
629
- });
630
-
631
- knightcode.on("message_update", async (event, ctx) => {
632
- // event.message
633
- // event.assistantMessageEvent (token-by-token stream event)
634
- });
635
-
636
- knightcode.on("message_end", async (event, ctx) => {
637
- if (event.message.role !== "assistant") return;
638
-
639
- return {
640
- message: {
641
- ...event.message,
642
- usage: {
643
- ...event.message.usage,
644
- cost: {
645
- ...event.message.usage.cost,
646
- total: 0.123,
647
- },
648
- },
649
- },
650
- };
651
- });
652
- ```
653
-
654
- #### tool_execution_start / tool_execution_update / tool_execution_end
655
-
656
- Fired for tool execution lifecycle updates.
657
-
658
- In parallel tool mode:
659
- - `tool_execution_start` is emitted in assistant source order during the preflight phase
660
- - `tool_execution_update` events may interleave across tools
661
- - `tool_execution_end` is emitted in tool completion order after each tool is finalized
662
- - final `toolResult` message events are still emitted later in assistant source order
663
-
664
- ```typescript
665
- knightcode.on("tool_execution_start", async (event, ctx) => {
666
- // event.toolCallId, event.toolName, event.args
667
- });
668
-
669
- knightcode.on("tool_execution_update", async (event, ctx) => {
670
- // event.toolCallId, event.toolName, event.args, event.partialResult
671
- });
672
-
673
- knightcode.on("tool_execution_end", async (event, ctx) => {
674
- // event.toolCallId, event.toolName, event.result, event.isError
675
- });
676
- ```
677
-
678
- #### context
679
-
680
- Fired before each LLM call. Modify messages non-destructively. See [Session Format](session-format.md) for message types.
681
-
682
- ```typescript
683
- knightcode.on("context", async (event, ctx) => {
684
- // event.messages - deep copy, safe to modify
685
- const filtered = event.messages.filter(m => !shouldPrune(m));
686
- return { messages: filtered };
687
- });
688
- ```
689
-
690
- #### before_provider_headers
691
-
692
- Fired after the outgoing HTTP headers are assembled. Use it to add, override, or remove request headers.
693
-
694
- Handlers mutate `event.headers` in place. Set a key to a string to add or override it, or to `null` to delete it.
695
-
696
- ```typescript
697
- knightcode.on("before_provider_headers", (event, ctx) => {
698
- // Add or override — e.g. a session id for gateway tracing/attribution
699
- event.headers["x-session-id"] = ctx.sessionManager.getSessionId();
700
-
701
- // Drop a tracking header knightcode adds for this call
702
- event.headers["X-OpenRouter-Title"] = null;
703
- });
704
- ```
705
-
706
- Runs once per provider request; retries reuse the same headers rather than re-firing the hook.
707
-
708
- #### before_provider_request
709
-
710
- Fired after the provider-specific payload is built, right before the request is sent. Handlers run in extension load order. Returning `undefined` keeps the payload unchanged. Returning any other value replaces the payload for later handlers and for the actual request.
711
-
712
- This hook can rewrite provider-level system instructions or remove them entirely. Those payload-level changes are not reflected by `ctx.getSystemPrompt()`, which reports KnightCode's system prompt string rather than the final serialized provider payload.
713
-
714
- ```typescript
715
- knightcode.on("before_provider_request", (event, ctx) => {
716
- console.log(JSON.stringify(event.payload, null, 2));
717
-
718
- // Optional: replace payload
719
- // return { ...event.payload, temperature: 0 };
720
- });
721
- ```
722
-
723
- This is mainly useful for debugging provider serialization and cache behavior.
724
-
725
- #### after_provider_response
726
-
727
- Fired after an HTTP response is received and before its stream body is consumed. Handlers run in extension load order.
728
-
729
- ```typescript
730
- knightcode.on("after_provider_response", (event, ctx) => {
731
- // event.status - HTTP status code
732
- // event.headers - normalized response headers
733
- if (event.status === 429) {
734
- console.log("rate limited", event.headers["retry-after"]);
735
- }
736
- });
737
- ```
738
-
739
- Header availability depends on provider and transport. Providers that abstract HTTP responses may not expose headers.
740
-
741
- #### cache_warming_decision
742
-
743
- Fired before each prompt-cache refresh with KnightCode's decision filled in. The event carries only KnightCode's cost estimates; use `ctx.model`, `ctx.isIdle()`, and `ctx.getContextUsage()` for everything else.
744
-
745
- ```typescript
746
- knightcode.on("cache_warming_decision", (event, ctx) => {
747
- // event.warmCost: price of this refresh
748
- // event.missCost: extra price of the next request if the entry is lost
749
- // event.continuationProbability: KnightCode's estimate that a request arrives in time
750
- // event.action: "warm" | "stop", KnightCode's decision
751
-
752
- if (ctx.model?.provider === "my-provider") {
753
- return { action: "stop" };
754
- }
755
- });
756
- ```
757
-
758
- Return `{ action: "warm" }` or `{ action: "stop" }` to override; the last handler that returns an action wins. `"stop"` ends warming until the next real request.
759
-
760
- ### Model Events
761
-
762
- #### model_select
763
-
764
- Fired when the model changes via `/model` command, model cycling (`Ctrl+P`), or session restore.
765
-
766
- ```typescript
767
- knightcode.on("model_select", async (event, ctx) => {
768
- // event.model - newly selected model
769
- // event.previousModel - previous model (undefined if first selection)
770
- // event.source - "set" | "cycle" | "restore"
771
-
772
- const prev = event.previousModel
773
- ? `${event.previousModel.provider}/${event.previousModel.id}`
774
- : "none";
775
- const next = `${event.model.provider}/${event.model.id}`;
776
-
777
- ctx.ui.notify(`Model changed (${event.source}): ${prev} -> ${next}`, "info");
778
- });
779
- ```
780
-
781
- Use this to update UI elements (status bars, footers) or perform model-specific initialization when the active model changes.
782
-
783
- #### thinking_level_select
784
-
785
- Fired when the thinking level changes. This is notification-only; handler return values are ignored.
786
-
787
- ```typescript
788
- knightcode.on("thinking_level_select", async (event, ctx) => {
789
- // event.level - newly selected thinking level
790
- // event.previousLevel - previous thinking level
791
-
792
- ctx.ui.setStatus("thinking", `thinking: ${event.level}`);
793
- });
794
- ```
795
-
796
- Use this to update extension UI when `knightcode.setThinkingLevel()`, model changes, or built-in thinking-level controls change the active thinking level.
797
-
798
- ### Tool Events
799
-
800
- #### tool_call
801
-
802
- Fired after `tool_execution_start`, before the tool executes. **Can block.** Use `isToolCallEventType` to narrow and get typed inputs.
803
-
804
- Before `tool_call` runs, knightcode waits for previously emitted Agent events to finish draining through `AgentSession`. This means `ctx.sessionManager` is up to date through the current assistant tool-calling message.
805
-
806
- In the default parallel tool execution mode, sibling tool calls from the same assistant message are preflighted sequentially, then executed concurrently. `tool_call` is not guaranteed to see sibling tool results from that same assistant message in `ctx.sessionManager`.
807
-
808
- `event.input` is mutable. Mutate it in place to patch tool arguments before execution.
809
-
810
- Behavior guarantees:
811
- - Mutations to `event.input` affect the actual tool execution
812
- - Later `tool_call` handlers see mutations made by earlier handlers
813
- - No re-validation is performed after your mutation
814
- - Return values from `tool_call` control blocking via `{ block: true, reason?: string, terminate?: boolean }`
815
- - `terminate` only applies to a blocked call; the agent stops early only when every finalized result in the batch is terminating
816
-
817
- ```typescript
818
- import { isToolCallEventType } from "@knightcodeai/cli";
819
-
820
- knightcode.on("tool_call", async (event, ctx) => {
821
- // event.toolName - "bash", "read", "write", "edit", etc.
822
- // event.toolCallId
823
- // event.input - tool parameters (mutable)
824
-
825
- // Built-in tools: no type params needed
826
- if (isToolCallEventType("bash", event)) {
827
- // event.input is { command: string; timeout?: number }
828
- event.input.command = `source ~/.profile\n${event.input.command}`;
829
-
830
- if (event.input.command.includes("rm -rf")) {
831
- return { block: true, reason: "Dangerous command", terminate: true };
832
- }
833
- }
834
-
835
- if (isToolCallEventType("read", event)) {
836
- // event.input is { path: string; offset?: number; limit?: number }
837
- console.log(`Reading: ${event.input.path}`);
838
- }
839
- });
840
- ```
841
-
842
- #### Typing custom tool input
843
-
844
- Custom tools should export their input type:
845
-
846
- ```typescript
847
- // my-extension.ts
848
- export type MyToolInput = Static<typeof myToolSchema>;
849
- ```
850
-
851
- Use `isToolCallEventType` with explicit type parameters:
852
-
853
- ```typescript
854
- import { isToolCallEventType } from "@knightcodeai/cli";
855
- import type { MyToolInput } from "my-extension";
856
-
857
- knightcode.on("tool_call", (event) => {
858
- if (isToolCallEventType<"my_tool", MyToolInput>("my_tool", event)) {
859
- event.input.action; // typed
860
- }
861
- });
862
- ```
863
-
864
- #### tool_result
865
-
866
- Fired after tool execution finishes and before `tool_execution_end` plus the final tool result message events are emitted. **Can modify result.**
867
-
868
- In parallel tool mode, `tool_result` and `tool_execution_end` may interleave in tool completion order, while final `toolResult` message events are still emitted later in assistant source order.
869
-
870
- `tool_result` handlers chain like middleware:
871
- - Handlers run in extension load order
872
- - Each handler sees the latest result after previous handler changes
873
- - Handlers can return partial patches (`content`, `details`, `isError`, or `usage`); omitted fields keep their current values
874
-
875
- Use `ctx.signal` for nested async work inside the handler. This lets Esc cancel model calls, `fetch()`, and other abort-aware operations started by the extension.
876
-
877
- ```typescript
878
- import { isBashToolResult } from "@knightcodeai/cli";
879
-
880
- knightcode.on("tool_result", async (event, ctx) => {
881
- // event.toolName, event.toolCallId, event.input
882
- // event.content, event.details, event.isError, event.usage
883
-
884
- if (isBashToolResult(event)) {
885
- // event.details is typed as BashToolDetails
886
- }
887
-
888
- const response = await fetch("https://example.com/summarize", {
889
- method: "POST",
890
- body: JSON.stringify({ content: event.content }),
891
- signal: ctx.signal,
892
- });
893
-
894
- // Modify result:
895
- return { content: [...], details: {...}, isError: false, usage: nestedModelUsage };
896
- });
897
- ```
898
-
899
- ### User Bash Events
900
-
901
- #### user_bash
902
-
903
- Fired when user executes `!` or `!!` commands. **Can intercept.**
904
-
905
- ```typescript
906
- import { createLocalBashOperations } from "@knightcodeai/cli";
907
-
908
- knightcode.on("user_bash", (event, ctx) => {
909
- // event.command - the bash command
910
- // event.excludeFromContext - true if !! prefix
911
- // event.cwd - working directory
912
-
913
- // Option 1: Provide custom operations (e.g., SSH)
914
- return { operations: remoteBashOps };
915
-
916
- // Option 2: Wrap knightcode's built-in local bash backend
917
- const local = createLocalBashOperations();
918
- return {
919
- operations: {
920
- exec(command, cwd, options) {
921
- return local.exec(`source ~/.profile\n${command}`, cwd, options);
922
- }
923
- }
924
- };
925
-
926
- // Option 3: Full replacement - return result directly
927
- return { result: { output: "...", exitCode: 0, cancelled: false, truncated: false } };
928
- });
929
- ```
930
-
931
- Returning `undefined` continues to the next handler, then local execution if none handles the event. A valid result stops propagation: `operations` executes the command through the supplied backend, while `result` records the completed command without executing it.
932
-
933
- ### Input Events
934
-
935
- #### input
936
-
937
- Fired when user input is received, after extension commands are checked but before skill and template expansion. The event sees the raw input text, so `/skill:foo` and `/template` are not yet expanded.
938
-
939
- **Processing order:**
940
- 1. Extension commands (`/cmd`) checked first - if found, handler runs and input event is skipped
941
- 2. `input` event fires - can intercept, transform, or handle
942
- 3. If not handled: skill commands (`/skill:name`) expanded to skill content
943
- 4. If not handled: prompt templates (`/template`) expanded to template content
944
- 5. Agent processing begins (`before_agent_start`, etc.)
945
-
946
- ```typescript
947
- knightcode.on("input", async (event, ctx) => {
948
- // event.text - raw input (before skill/template expansion)
949
- // event.images - attached images, if any
950
- // event.source - "interactive" (typed), "rpc" (API), or "extension" (via sendUserMessage)
951
- // event.streamingBehavior - "steer" | "followUp" | undefined
952
- // undefined when idle, "steer" for mid-stream interrupts,
953
- // "followUp" for messages queued until the agent finishes
954
-
955
- // Transform: rewrite input before expansion
956
- if (event.text.startsWith("?quick "))
957
- return { action: "transform", text: `Respond briefly: ${event.text.slice(7)}` };
958
-
959
- // Handle: respond without LLM (extension shows its own feedback)
960
- if (event.text === "ping") {
961
- ctx.ui.notify("pong", "info");
962
- return { action: "handled" };
963
- }
964
-
965
- // Route by source: skip processing for extension-injected messages
966
- if (event.source === "extension") return { action: "continue" };
967
-
968
- // Intercept skill commands before expansion
969
- if (event.text.startsWith("/skill:")) {
970
- // Could transform, block, or let pass through
971
- }
972
-
973
- return { action: "continue" }; // Default: pass through to expansion
974
- });
975
- ```
976
-
977
- **Results:**
978
- - `continue` - pass through unchanged (default if handler returns nothing)
979
- - `transform` - modify text/images, then continue to expansion
980
- - `handled` - skip agent entirely (first handler to return this wins)
981
-
982
- Transforms chain across handlers. See [input-transform.ts](../examples/extensions/input-transform.ts) and [input-transform-streaming.ts](../examples/extensions/input-transform-streaming.ts) for `streamingBehavior`-aware routing.
983
-
984
- ## ExtensionContext
985
-
986
- All handlers receive `ctx: ExtensionContext`.
987
-
988
- ### ctx.ui
989
-
990
- UI methods for user interaction. See [Custom UI](#custom-ui) for full details.
991
-
992
- ### ctx.mode
993
-
994
- Current run mode: `"tui"`, `"rpc"`, `"json"`, or `"print"`. Use `ctx.mode === "tui"` to guard terminal-only features such as `custom()`, component factories, terminal input, and direct TUI rendering.
995
-
996
- ### ctx.hasUI
997
-
998
- `true` in TUI and RPC modes. `false` in print mode (`-p`) and JSON mode. Use this to guard dialog methods (`select`, `confirm`, `input`, `editor`) and fire-and-forget methods (`notify`, `setStatus`, `setWidget`, `setTitle`, `setEditorText`) that work in both TUI and RPC modes. In RPC mode, some TUI-specific methods are no-ops or return defaults (see [rpc.md](rpc.md#extension-ui-protocol)).
999
-
1000
- ### ctx.cwd
1001
-
1002
- Current working directory.
1003
-
1004
- Use `CONFIG_DIR_NAME` instead of hardcoding `.knightcode` when constructing project-local config paths. Rebranded distributions can use a different config directory name.
1005
-
1006
- ```typescript
1007
- import { CONFIG_DIR_NAME, type ExtensionAPI } from "@knightcodeai/cli";
1008
- import { join } from "node:path";
1009
-
1010
- export default function (knightcode: ExtensionAPI) {
1011
- knightcode.on("session_start", (_event, ctx) => {
1012
- const projectConfigPath = join(ctx.cwd, CONFIG_DIR_NAME, "my-extension.json");
1013
- // ...
1014
- });
1015
- }
1016
- ```
1017
-
1018
- ### ctx.isProjectTrusted()
1019
-
1020
- Returns whether project-local trust is active for the current session context. This includes temporary trust decisions and CLI trust overrides, not just saved decisions in the global trust store.
1021
-
1022
- Use this before reading project-local extension configuration that should only be honored for trusted projects.
1023
-
1024
- ### ctx.sessionManager
1025
-
1026
- Read-only access to session state. See [Session Format](session-format.md) for the full SessionManager API and entry types.
1027
-
1028
- For `tool_call`, this state is synchronized through the current assistant message before handlers run. In parallel tool execution mode it is still not guaranteed to include sibling tool results from the same assistant message.
1029
-
1030
- ```typescript
1031
- ctx.sessionManager.getEntries() // All entries
1032
- ctx.sessionManager.getBranch() // Current branch
1033
- ctx.sessionManager.buildContextEntries() // Active branch entries with compaction applied
1034
- ctx.sessionManager.getLeafId() // Current leaf entry ID
1035
- ```
1036
-
1037
- ### ctx.modelRegistry / ctx.model / ctx.thinkingLevel / ctx.scopedModels
1038
-
1039
- Access to models, providers, and resolved authentication. `ctx.modelRegistry.getProvider(id)` returns the effective @knightcode/ai provider, while `getProviderAuth(id)` resolves its current API key, headers, base URL, and provider-scoped environment without requiring a loaded model. `ctx.model` is the active model, and `ctx.thinkingLevel` is its current effective thinking level.
1040
-
1041
- `ctx.scopedModels` is the read-only list of models scoped to the current session — the same set the `/scoped-models` command shows. It is resolved at session start from the `--models` CLI flag and the `enabledModels` setting (matched against the available catalogue with minimatch on `provider/modelId` or a bare `modelId`). It is empty when no scoping is configured, meaning every available model is usable. Each entry is `{ model, thinkingLevel? }`, where `thinkingLevel` is set only when a pattern pinned it (e.g. `anthropic/*:high`). Use it to populate a model picker that mirrors the built-in one instead of enumerating the whole catalogue via `ctx.modelRegistry.getAvailable()`.
1042
-
1043
- #### Streaming model calls
1044
-
1045
- Use `ctx.modelRegistry.streamSimple(model, context, options)` for provider-neutral options such as `reasoning`, or `stream()` for API-specific options. Both use configured providers and resolve authentication, including for providers registered with `knightcode.registerProvider()`. Use these instead of `@knightcode/ai/compat` streaming functions, which cannot see extension provider registrations.
1046
-
1047
- Both return an `AssistantMessageEventStream`. Iterate it for response events and await `.result()` for the final message. Setup failures produce error events and error results.
1048
-
1049
- ### ctx.signal
1050
-
1051
- The current agent abort signal, or `undefined` when no agent turn is active.
1052
-
1053
- Use this for abort-aware nested work started by extension handlers, for example:
1054
- - `fetch(..., { signal: ctx.signal })`
1055
- - model calls that accept `signal`
1056
- - file or process helpers that accept `AbortSignal`
1057
-
1058
- `ctx.signal` is typically defined during active turn events such as `tool_call`, `tool_result`, `message_update`, and `turn_end`.
1059
- It is usually `undefined` in idle or non-turn contexts such as session events, extension commands, and shortcuts fired while knightcode is idle.
1060
-
1061
- ```typescript
1062
- knightcode.on("tool_result", async (event, ctx) => {
1063
- const response = await fetch("https://example.com/api", {
1064
- method: "POST",
1065
- body: JSON.stringify(event),
1066
- signal: ctx.signal,
1067
- });
1068
-
1069
- const data = await response.json();
1070
- return { details: data };
1071
- });
1072
- ```
1073
-
1074
- ### ctx.isIdle() / ctx.abort() / ctx.hasPendingMessages()
1075
-
1076
- Control flow helpers. `ctx.isIdle()` is false while KnightCode is processing an agent run, automatic retry, auto-compaction retry, or queued continuation.
1077
-
1078
- ### ctx.shutdown()
1079
-
1080
- Request a graceful shutdown of knightcode.
1081
-
1082
- - **Interactive mode:** Deferred until the agent becomes idle (after processing all queued steering and follow-up messages).
1083
- - **RPC mode:** Deferred until the next idle state (after completing the current command response, when waiting for the next command).
1084
- - **Print mode:** No-op. The process exits automatically when all prompts are processed.
1085
-
1086
- Emits `session_shutdown` event to all extensions before exiting. Available in all contexts (event handlers, tools, commands, shortcuts).
1087
-
1088
- ```typescript
1089
- knightcode.on("tool_call", (event, ctx) => {
1090
- if (isFatal(event.input)) {
1091
- ctx.shutdown();
1092
- }
1093
- });
1094
- ```
1095
-
1096
- ### ctx.getContextUsage()
1097
-
1098
- Returns current context usage for the active model. Uses last assistant usage when available, then estimates tokens for trailing messages.
1099
-
1100
- ```typescript
1101
- const usage = ctx.getContextUsage();
1102
- if (usage && usage.tokens > 100_000) {
1103
- // ...
1104
- }
1105
- ```
1106
-
1107
- ### ctx.compact()
1108
-
1109
- Trigger compaction without awaiting completion. Use `onComplete` and `onError` for follow-up actions.
1110
-
1111
- ```typescript
1112
- ctx.compact({
1113
- customInstructions: "Focus on recent changes",
1114
- onComplete: (result) => {
1115
- ctx.ui.notify("Compaction completed", "info");
1116
- },
1117
- onError: (error) => {
1118
- ctx.ui.notify(`Compaction failed: ${error.message}`, "error");
1119
- },
1120
- });
1121
- ```
1122
-
1123
- ### ctx.getSystemPrompt()
1124
-
1125
- Returns KnightCode's current system prompt string.
1126
-
1127
- - During `before_agent_start`, this reflects chained system-prompt changes made so far for the current turn.
1128
- - It does not include later `context` message mutations.
1129
- - It does not include `before_provider_request` payload rewrites.
1130
- - If later-loaded extensions run after yours, they can still change what is ultimately sent.
1131
-
1132
- ```typescript
1133
- knightcode.on("before_agent_start", (event, ctx) => {
1134
- const prompt = ctx.getSystemPrompt();
1135
- console.log(`System prompt length: ${prompt.length}`);
1136
- });
1137
- ```
1138
-
1139
- ## ExtensionCommandContext
1140
-
1141
- Command handlers receive `ExtensionCommandContext`, which extends `ExtensionContext` with session control methods. These are only available in commands because they can deadlock if called from event handlers.
1142
-
1143
- ### ctx.getSystemPromptOptions()
1144
-
1145
- Returns the base inputs KnightCode currently uses to build the system prompt.
1146
-
1147
- ```typescript
1148
- const options = ctx.getSystemPromptOptions();
1149
- const contextPaths = options.contextFiles?.map((file) => file.path) ?? [];
1150
- ```
1151
-
1152
- This has the same shape and mutability as `before_agent_start` `event.systemPromptOptions`: custom or forced prompt, active tools, tool snippets, per-tool and custom rules, custom sections, appended prompt text, cwd, loaded context files, and loaded skills. It may include full context file contents, so treat it as sensitive extension-local data and avoid exposing it through command lists, logs, or autocomplete metadata.
1153
-
1154
- This reports the current base prompt inputs. It does not include per-turn `before_agent_start` chained system-prompt changes, later `context` event message mutations, or `before_provider_request` payload rewrites.
1155
-
1156
- ### ctx.waitForIdle()
1157
-
1158
- Wait for the agent to fully settle, including automatic retries, auto-compaction retries, and queued continuations:
1159
-
1160
- ```typescript
1161
- knightcode.registerCommand("my-cmd", {
1162
- handler: async (args, ctx) => {
1163
- await ctx.waitForIdle();
1164
- // Agent is now idle, safe to modify session
1165
- },
1166
- });
1167
- ```
1168
-
1169
- ### ctx.newSession(options?)
1170
-
1171
- Create a new session:
1172
-
1173
- ```typescript
1174
- const parentSession = ctx.sessionManager.getSessionFile();
1175
- const kickoff = "Continue in the replacement session";
1176
-
1177
- const result = await ctx.newSession({
1178
- parentSession,
1179
- setup: async (sm) => {
1180
- sm.appendMessage({
1181
- role: "user",
1182
- content: [{ type: "text", text: "Context from previous session..." }],
1183
- timestamp: Date.now(),
1184
- });
1185
- },
1186
- withSession: async (ctx) => {
1187
- // Use only the replacement-session ctx here.
1188
- await ctx.sendUserMessage(kickoff);
1189
- },
1190
- });
1191
-
1192
- if (result.cancelled) {
1193
- // An extension cancelled the new session
1194
- }
1195
- ```
1196
-
1197
- Options:
1198
- - `parentSession`: parent session file to record in the new session header
1199
- - `setup`: mutate the new session's `SessionManager` before `withSession` runs
1200
- - `withSession`: run post-switch work against a fresh replacement-session context. Do not use captured old `knightcode` / command `ctx`; see [Session replacement lifecycle and footguns](#session-replacement-lifecycle-and-footguns).
1201
-
1202
- ### ctx.fork(entryId, options?)
1203
-
1204
- Fork from a specific entry, creating a new session file:
1205
-
1206
- ```typescript
1207
- const result = await ctx.fork("entry-id-123", {
1208
- withSession: async (ctx) => {
1209
- // Use only the replacement-session ctx here.
1210
- ctx.ui.notify("Now in the forked session", "info");
1211
- },
1212
- });
1213
- if (result.cancelled) {
1214
- // An extension cancelled the fork
1215
- }
1216
-
1217
- const cloneResult = await ctx.fork("entry-id-456", { position: "at" });
1218
- if (cloneResult.cancelled) {
1219
- // An extension cancelled the clone
1220
- }
1221
- ```
1222
-
1223
- Options:
1224
- - `position`: `"before"` (default) forks before the selected user message, restoring that prompt into the editor
1225
- - `position`: `"at"` duplicates the active path through the selected entry without restoring editor text
1226
- - `withSession`: run post-switch work against a fresh replacement-session context. Do not use captured old `knightcode` / command `ctx`; see [Session replacement lifecycle and footguns](#session-replacement-lifecycle-and-footguns).
1227
-
1228
- ### ctx.navigateTree(targetId, options?)
1229
-
1230
- Navigate to a different point in the session tree. Rejects while an agent response, manual or automatic compaction, or another tree navigation is active, even with `summarize: false`. These conflicts leave the active branch unchanged and reject the promise rather than returning `{ cancelled: true }`. Wait for the active operation to finish (for example, with `await ctx.waitForIdle()` in a command handler) and retry:
1231
-
1232
- ```typescript
1233
- const result = await ctx.navigateTree("entry-id-456", {
1234
- summarize: true,
1235
- customInstructions: "Focus on error handling changes",
1236
- replaceInstructions: false, // true = replace default prompt entirely
1237
- label: "review-checkpoint",
1238
- });
1239
- ```
1240
-
1241
- Options:
1242
- - `summarize`: Whether to generate a summary of the abandoned branch
1243
- - `customInstructions`: Custom instructions for the summarizer
1244
- - `replaceInstructions`: If true, `customInstructions` replaces the default prompt instead of being appended
1245
- - `label`: Label to attach to the branch summary entry (or target entry if not summarizing)
1246
-
1247
- ### ctx.switchSession(sessionPath, options?)
1248
-
1249
- Switch to a different session file:
1250
-
1251
- ```typescript
1252
- const result = await ctx.switchSession("/path/to/session.jsonl", {
1253
- withSession: async (ctx) => {
1254
- await ctx.sendUserMessage("Resume work in the replacement session");
1255
- },
1256
- });
1257
- if (result.cancelled) {
1258
- // An extension cancelled the switch via session_before_switch
1259
- }
1260
- ```
1261
-
1262
- Options:
1263
- - `withSession`: run post-switch work against a fresh replacement-session context. Do not use captured old `knightcode` / command `ctx`; see [Session replacement lifecycle and footguns](#session-replacement-lifecycle-and-footguns).
1264
-
1265
- To discover available sessions, use the static `SessionManager.list()` or `SessionManager.listAll()` methods:
1266
-
1267
- ```typescript
1268
- import { SessionManager } from "@knightcodeai/cli";
1269
-
1270
- knightcode.registerCommand("switch", {
1271
- description: "Switch to another session",
1272
- handler: async (args, ctx) => {
1273
- const sessions = await SessionManager.list(ctx.cwd);
1274
- if (sessions.length === 0) return;
1275
- const choice = await ctx.ui.select(
1276
- "Pick session:",
1277
- sessions.map(s => s.file),
1278
- );
1279
- if (choice) {
1280
- await ctx.switchSession(choice, {
1281
- withSession: async (ctx) => {
1282
- ctx.ui.notify("Switched session", "info");
1283
- },
1284
- });
1285
- }
1286
- },
1287
- });
1288
- ```
1289
-
1290
- ### Session replacement lifecycle and footguns
1291
-
1292
- `withSession` receives a fresh `ReplacedSessionContext`, which extends `ExtensionCommandContext` with async `sendMessage()` and `sendUserMessage()` helpers bound to the replacement session.
1293
-
1294
- Lifecycle and footguns:
1295
- - `withSession` runs only after the old session has emitted `session_shutdown`, the old runtime has been torn down, the replacement session has been rebound, and the new extension instance has already received `session_start`.
1296
- - The callback still executes in the original closure, not inside the new extension instance. That means your old extension instance may already have run its shutdown cleanup before `withSession` starts.
1297
- - Captured old `knightcode` / old command `ctx` session-bound objects are stale after replacement and will throw if used. Use only the `ctx` passed to `withSession` for session-bound work.
1298
- - Previously extracted raw objects are still your responsibility. For example, if you capture `const sm = ctx.sessionManager` before replacement, `sm` is still the old `SessionManager` object. Do not reuse it after replacement.
1299
- - Code in `withSession` should assume any state invalidated by your `session_shutdown` handler is already gone. Only capture plain data that survives shutdown cleanly, such as strings, ids, and serialized config.
1300
-
1301
- Safe pattern:
1302
-
1303
- ```typescript
1304
- knightcode.registerCommand("handoff", {
1305
- handler: async (_args, ctx) => {
1306
- const kickoff = "Continue from the replacement session";
1307
- await ctx.newSession({
1308
- withSession: async (ctx) => {
1309
- await ctx.sendUserMessage(kickoff);
1310
- },
1311
- });
1312
- },
1313
- });
1314
- ```
1315
-
1316
- Unsafe pattern:
1317
-
1318
- ```typescript
1319
- knightcode.registerCommand("handoff", {
1320
- handler: async (_args, ctx) => {
1321
- const oldSessionManager = ctx.sessionManager;
1322
- await ctx.newSession({
1323
- withSession: async (_ctx) => {
1324
- // stale old objects: do not do this
1325
- oldSessionManager.getSessionFile();
1326
- knightcode.sendUserMessage("wrong");
1327
- },
1328
- });
1329
- },
1330
- });
1331
- ```
1332
-
1333
- ### ctx.reload()
1334
-
1335
- Run the same reload flow as `/reload`.
1336
-
1337
- ```typescript
1338
- knightcode.registerCommand("reload-runtime", {
1339
- description: "Reload extensions, skills, prompts, themes, and context files",
1340
- handler: async (_args, ctx) => {
1341
- await ctx.reload();
1342
- return;
1343
- },
1344
- });
1345
- ```
1346
-
1347
- Important behavior:
1348
- - `await ctx.reload()` emits `session_shutdown` for the current extension runtime
1349
- - It then reloads resources and emits `session_start` with `reason: "reload"` and `resources_discover` with reason `"reload"`
1350
- - The currently running command handler still continues in the old call frame
1351
- - Code after `await ctx.reload()` still runs from the pre-reload version
1352
- - Code after `await ctx.reload()` must not assume old in-memory extension state is still valid
1353
- - After the handler returns, future commands/events/tool calls use the new extension version
1354
-
1355
- For predictable behavior, treat reload as terminal for that handler (`await ctx.reload(); return;`).
1356
-
1357
- Tools run with `ExtensionContext`, so they cannot call `ctx.reload()` directly. Use a command as the reload entrypoint, then expose a tool that queues that command as a follow-up user message.
1358
-
1359
- Example tool the LLM can call to trigger reload:
1360
-
1361
- ```typescript
1362
- import type { ExtensionAPI } from "@knightcodeai/cli";
1363
- import { Type } from "typebox";
1364
-
1365
- export default function (knightcode: ExtensionAPI) {
1366
- knightcode.registerCommand("reload-runtime", {
1367
- description: "Reload extensions, skills, prompts, themes, and context files",
1368
- handler: async (_args, ctx) => {
1369
- await ctx.reload();
1370
- return;
1371
- },
1372
- });
1373
-
1374
- knightcode.registerTool({
1375
- name: "reload_runtime",
1376
- label: "Reload Runtime",
1377
- description: "Reload extensions, skills, prompts, themes, and context files",
1378
- parameters: Type.Object({}),
1379
- async execute() {
1380
- knightcode.sendUserMessage("/reload-runtime", { deliverAs: "followUp" });
1381
- return {
1382
- content: [{ type: "text", text: "Queued /reload-runtime as a follow-up command." }],
1383
- };
1384
- },
1385
- });
1386
- }
1387
- ```
1388
-
1389
- ## ExtensionAPI Methods
1390
-
1391
- ### knightcode.on(event, handler)
1392
-
1393
- Subscribe to events. Returns an unsubscribe function that removes only that registration. See [Events](#events) for event types and return values.
1394
-
1395
- ```typescript
1396
- const unsubscribe = knightcode.on("agent_end", async (event) => {
1397
- unsubscribe();
1398
- await updateIntegration(event.messages);
1399
- });
1400
- ```
1401
-
1402
- Handlers run in extension load order, then registration order within each extension. Adding or removing a handler does not affect a dispatch already in progress.
1403
-
1404
- ### knightcode.registerTool(definition)
1405
-
1406
- Register a custom tool callable by the LLM. See [Custom Tools](#custom-tools) for full details.
1407
-
1408
- `knightcode.registerTool()` works both during extension load and after startup. You can call it inside `session_start`, command handlers, or other event handlers. New tools are refreshed immediately in the same session, so they appear in `knightcode.getAllTools()` and are callable by the LLM without `/reload`.
1409
-
1410
- Use `knightcode.setActiveTools()` to enable or disable tools (including dynamically added tools) at runtime.
1411
-
1412
- Use `promptSnippet` to opt a custom tool into a one-line entry in `Available tools`, and `promptGuidelines` to append tool-specific bullets to the default `Guidelines` section when the tool is active.
1413
-
1414
- **Important:** `promptGuidelines` bullets are appended flat to the `Guidelines` section with no tool name prefix. Each guideline must name the tool it refers to — avoid "Use this tool when..." because the LLM cannot tell which tool "this" means. Write "Use my_tool when..." instead.
1415
-
1416
- See [dynamic-tools.ts](../examples/extensions/dynamic-tools.ts) for a full example.
1417
-
1418
- ```typescript
1419
- import { Type } from "typebox";
1420
- import { StringEnum } from "@knightcode/ai";
1421
-
1422
- knightcode.registerTool({
1423
- name: "my_tool",
1424
- label: "My Tool",
1425
- description: "What this tool does",
1426
- promptSnippet: "Summarize or transform text according to action",
1427
- promptGuidelines: ["Use my_tool when the user asks to summarize previously generated text."],
1428
- parameters: Type.Object({
1429
- action: StringEnum(["list", "add"] as const),
1430
- text: Type.Optional(Type.String()),
1431
- }),
1432
- prepareArguments(args) {
1433
- // Optional compatibility shim. Runs before schema validation.
1434
- // Return the current schema shape, for example to fold legacy fields
1435
- // into the modern parameter object.
1436
- return args;
1437
- },
1438
-
1439
- async execute(toolCallId, params, signal, onUpdate, ctx) {
1440
- // Stream progress
1441
- onUpdate?.({ content: [{ type: "text", text: "Working..." }] });
1442
-
1443
- return {
1444
- content: [{ type: "text", text: "Done" }],
1445
- details: { result: "..." },
1446
- };
1447
- },
1448
-
1449
- // Optional: Custom rendering
1450
- renderCall(args, theme, context) { ... },
1451
- renderResult(result, options, theme, context) { ... },
1452
- });
1453
- ```
1454
-
1455
- ### knightcode.sendMessage(message, options?)
1456
-
1457
- Inject a custom message into the session. Custom messages participate in LLM context. For durable TUI-only content that should not be sent to the LLM, use [`knightcode.appendEntry()`](#piappendentrycustomtype-data) with [`knightcode.registerEntryRenderer()`](#piregisterentryrenderercustomtype-renderer).
1458
-
1459
- ```typescript
1460
- knightcode.sendMessage({
1461
- customType: "my-extension",
1462
- content: "Message text",
1463
- display: true,
1464
- details: { ... },
1465
- }, {
1466
- triggerTurn: true,
1467
- deliverAs: "steer",
1468
- });
1469
- ```
1470
-
1471
- **Options:**
1472
- - `deliverAs` - Delivery mode:
1473
- - `"steer"` (default) - Queues the message while streaming. Delivered after the current assistant turn finishes executing its tool calls, before the next LLM call.
1474
- - `"followUp"` - Waits for agent to finish. Delivered only when agent has no more tool calls.
1475
- - `"nextTurn"` - Queued for next user prompt. Does not interrupt or trigger anything.
1476
- - `triggerTurn: true` - If agent is idle, trigger an LLM response immediately. Only applies to `"steer"` and `"followUp"` modes (ignored for `"nextTurn"`).
1477
-
1478
- ### knightcode.sendUserMessage(content, options?)
1479
-
1480
- Send a user message to the agent. Unlike `sendMessage()` which sends custom messages, this sends an actual user message that appears as if typed by the user. Always triggers a turn.
1481
-
1482
- ```typescript
1483
- // Simple text message
1484
- knightcode.sendUserMessage("What is 2+2?");
1485
-
1486
- // With content array (text + images)
1487
- knightcode.sendUserMessage([
1488
- { type: "text", text: "Describe this image:" },
1489
- { type: "image", source: { type: "base64", mediaType: "image/png", data: "..." } },
1490
- ]);
1491
-
1492
- // During streaming - must specify delivery mode
1493
- knightcode.sendUserMessage("Focus on error handling", { deliverAs: "steer" });
1494
- knightcode.sendUserMessage("And then summarize", { deliverAs: "followUp" });
1495
-
1496
- // Opt in to extension command dispatch and skill/prompt template expansion
1497
- knightcode.sendUserMessage("/review src/index.ts", { expandPromptTemplates: true });
1498
- ```
1499
-
1500
- **Options:**
1501
- - `deliverAs` - Required when agent is streaming:
1502
- - `"steer"` - Queues the message for delivery after the current assistant turn finishes executing its tool calls
1503
- - `"followUp"` - Waits for agent to finish all tools
1504
- - `expandPromptTemplates` - Dispatch extension commands and expand skill commands and prompt templates. Defaults to `false`.
1505
-
1506
- When not streaming, the message is sent immediately and triggers a new turn. When streaming without `deliverAs`, throws an error.
1507
-
1508
- See [send-user-message.ts](../examples/extensions/send-user-message.ts) for a complete example.
1509
-
1510
- ### knightcode.appendEntry(customType, data?)
1511
-
1512
- Persist extension data. Custom entries do NOT participate in LLM context. In interactive mode, they can also render inside the chat transcript when paired with `knightcode.registerEntryRenderer()`.
1513
-
1514
- ```typescript
1515
- knightcode.appendEntry("my-state", { count: 42 });
1516
- knightcode.appendEntry("status-card", { title: "Indexed files", count: 17 });
1517
-
1518
- // Restore on reload
1519
- knightcode.on("session_start", async (_event, ctx) => {
1520
- for (const entry of ctx.sessionManager.getEntries()) {
1521
- if (entry.type === "custom" && entry.customType === "my-state") {
1522
- // Reconstruct from entry.data
1523
- }
1524
- }
1525
- });
1526
- ```
1527
-
1528
- ### knightcode.setSessionName(name)
1529
-
1530
- Set the session display name (shown in session selector instead of first message).
1531
-
1532
- ```typescript
1533
- knightcode.setSessionName("Refactor auth module");
1534
- ```
1535
-
1536
- ### knightcode.getSessionName()
1537
-
1538
- Get the current session name, if set.
1539
-
1540
- ```typescript
1541
- const name = knightcode.getSessionName();
1542
- if (name) {
1543
- console.log(`Session: ${name}`);
1544
- }
1545
- ```
1546
-
1547
- ### knightcode.setLabel(entryId, label)
1548
-
1549
- Set or clear a label on an entry. Labels are user-defined markers for bookmarking and navigation (shown in `/tree` selector).
1550
-
1551
- ```typescript
1552
- // Set a label
1553
- knightcode.setLabel(entryId, "checkpoint-before-refactor");
1554
-
1555
- // Clear a label
1556
- knightcode.setLabel(entryId, undefined);
1557
-
1558
- // Read labels via sessionManager
1559
- const label = ctx.sessionManager.getLabel(entryId);
1560
- ```
1561
-
1562
- Labels persist in the session and survive restarts. Use them to mark important points (turns, checkpoints) in the conversation tree.
1563
-
1564
- ### knightcode.registerCommand(name, options)
1565
-
1566
- Register a command.
1567
-
1568
- If multiple extensions register the same command name, knightcode keeps them all and assigns numeric invocation suffixes in load order, for example `/review:1` and `/review:2`.
1569
-
1570
- ```typescript
1571
- knightcode.registerCommand("stats", {
1572
- description: "Show session statistics",
1573
- handler: async (args, ctx) => {
1574
- const count = ctx.sessionManager.getEntries().length;
1575
- ctx.ui.notify(`${count} entries`, "info");
1576
- }
1577
- });
1578
- ```
1579
-
1580
- Optional: add argument auto-completion for `/command ...`:
1581
-
1582
- ```typescript
1583
- import type { AutocompleteItem } from "@knightcode/tui";
1584
-
1585
- knightcode.registerCommand("deploy", {
1586
- description: "Deploy to an environment",
1587
- getArgumentCompletions: (prefix: string): AutocompleteItem[] | null => {
1588
- const envs = ["dev", "staging", "prod"];
1589
- const items = envs.map((e) => ({ value: e, label: e }));
1590
- const filtered = items.filter((i) => i.value.startsWith(prefix));
1591
- return filtered.length > 0 ? filtered : null;
1592
- },
1593
- handler: async (args, ctx) => {
1594
- ctx.ui.notify(`Deploying: ${args}`, "info");
1595
- },
1596
- });
1597
- ```
1598
-
1599
- ### knightcode.getCommands()
1600
-
1601
- Get the slash commands available for invocation via `prompt` in the current session. Includes extension commands, prompt templates, and skill commands.
1602
- The list matches the RPC `get_commands` ordering: extensions first, then templates, then skills.
1603
-
1604
- ```typescript
1605
- const commands = knightcode.getCommands();
1606
- const bySource = commands.filter((command) => command.source === "extension");
1607
- const userScoped = commands.filter((command) => command.sourceInfo.scope === "user");
1608
- ```
1609
-
1610
- Each entry has this shape:
1611
-
1612
- ```typescript
1613
- {
1614
- name: string; // Invokable command name without the leading slash. May be suffixed like "review:1"
1615
- description?: string;
1616
- source: "extension" | "prompt" | "skill";
1617
- sourceInfo: {
1618
- path: string;
1619
- source: string;
1620
- scope: "user" | "project" | "temporary";
1621
- origin: "package" | "top-level";
1622
- baseDir?: string;
1623
- };
1624
- }
1625
- ```
1626
-
1627
- Use `sourceInfo` as the canonical provenance field. Do not infer ownership from command names or from ad hoc path parsing.
1628
-
1629
- Built-in interactive commands (like `/model` and `/settings`) are not included here. They are handled only in interactive
1630
- mode and would not execute if sent via `prompt`.
1631
-
1632
- ### knightcode.registerMessageRenderer(customType, renderer)
1633
-
1634
- Register a custom TUI renderer for custom messages with your `customType`. Custom messages are created with `knightcode.sendMessage()` and participate in LLM context. See [Custom UI](#custom-ui).
1635
-
1636
- ### knightcode.registerMarkdownTransformer(transformer)
1637
-
1638
- Register a transformer for the Markdown in normal user text, assistant text, and thinking blocks. Transformers run in extension load order, and each transformer receives the Markdown returned by the previous transformer. After the chain finishes, KnightCode renders the transformed content with its built-in renderer.
1639
-
1640
- The transformer receives the Markdown string and a context with:
1641
-
1642
- - `messageType` — `"user"`, `"assistant"`, or `"assistant-thinking"`
1643
- - `isStreaming` — `true` for partial assistant updates; `false` for user, finalized assistant, and restored messages
1644
- - `availableWidth` — exact terminal columns available for the transformed Markdown content
1645
-
1646
- Return the transformed Markdown:
1647
-
1648
- ```typescript
1649
- knightcode.registerMarkdownTransformer((markdown, { messageType, isStreaming }) => {
1650
- if (isStreaming || messageType === "assistant-thinking") return markdown;
1651
- return markdown.replaceAll("-->", "→");
1652
- });
1653
- ```
1654
-
1655
- If a transformer throws, KnightCode keeps the Markdown produced so far and continues with the next transformer. The hook is display-only: the original message remains unchanged in the session and model context. It runs for new user messages, assistant streaming updates, restored session messages, and terminal width changes, so transformers should remain synchronous and inexpensive.
1656
-
1657
- ### knightcode.registerEntryRenderer(customType, renderer)
1658
-
1659
- Register a custom TUI renderer for custom entries with your `customType`. Custom entries are created with `knightcode.appendEntry()` and do not participate in LLM context.
1660
-
1661
- ```typescript
1662
- import { Box, Text } from "@knightcode/tui";
1663
-
1664
- knightcode.registerEntryRenderer("status-card", (entry, { expanded }, theme) => {
1665
- const data = entry.data as { title: string; count: number };
1666
- const box = new Box(1, 1, (text) => theme.bg("customMessageBg", text));
1667
- box.addChild(new Text(`${theme.bold(data.title)}: ${data.count}`));
1668
- if (expanded) {
1669
- box.addChild(new Text(theme.fg("dim", JSON.stringify(data, null, 2))));
1670
- }
1671
- return box;
1672
- });
1673
-
1674
- knightcode.appendEntry("status-card", { title: "Indexed files", count: 17 });
1675
- ```
1676
-
1677
- ### knightcode.registerShortcut(shortcut, options)
1678
-
1679
- Register a keyboard shortcut. See [keybindings.md](keybindings.md) for the shortcut format and built-in keybindings.
1680
-
1681
- ```typescript
1682
- knightcode.registerShortcut("ctrl+shift+p", {
1683
- description: "Toggle plan mode",
1684
- handler: async (ctx) => {
1685
- ctx.ui.notify("Toggled!");
1686
- },
1687
- });
1688
- ```
1689
-
1690
- ### knightcode.registerFlag(name, options)
1691
-
1692
- Register a CLI flag.
1693
-
1694
- ```typescript
1695
- knightcode.registerFlag("plan", {
1696
- description: "Start in plan mode",
1697
- type: "boolean",
1698
- default: false,
1699
- });
1700
-
1701
- // Check value
1702
- if (knightcode.getFlag("plan")) {
1703
- // Plan mode enabled
1704
- }
1705
- ```
1706
-
1707
- ### knightcode.exec(command, args, options?)
1708
-
1709
- Execute a shell command.
1710
-
1711
- ```typescript
1712
- const result = await knightcode.exec("git", ["status"], { signal, timeout: 5000 });
1713
- // result.stdout, result.stderr, result.code, result.killed
1714
- ```
1715
-
1716
- ### knightcode.getActiveTools() / knightcode.getAllTools() / knightcode.setActiveTools(names)
1717
-
1718
- Manage active tools. This works for both built-in tools and dynamically registered tools. `knightcode.getActiveTools()` returns the active tool names as `string[]`; `knightcode.getAllTools()` returns metadata for all configured tools.
1719
-
1720
- ```typescript
1721
- const active = knightcode.getActiveTools(); // ["read", "bash", ...]
1722
- const all = knightcode.getAllTools();
1723
- // all = [{
1724
- // name: "read",
1725
- // description: "Read file contents...",
1726
- // parameters: ...,
1727
- // promptGuidelines: ["Use read to examine files instead of cat or sed."],
1728
- // sourceInfo: { path: "<builtin:read>", source: "builtin", scope: "temporary", origin: "top-level" }
1729
- // }, ...]
1730
- const builtinTools = all.filter((t) => t.sourceInfo.source === "builtin");
1731
- const extensionTools = all.filter((t) => t.sourceInfo.source !== "builtin" && t.sourceInfo.source !== "sdk");
1732
- knightcode.setActiveTools([...new Set([...active, "my_custom_tool"])]); // Keep current tools and enable my_custom_tool
1733
- knightcode.setActiveTools(["read", "bash"]); // Switch to read-only
1734
- ```
1735
-
1736
- `knightcode.getAllTools()` returns `name`, `description`, `parameters`, `promptGuidelines`, and `sourceInfo`.
1737
-
1738
- Typical `sourceInfo.source` values:
1739
- - `builtin` for built-in tools
1740
- - `sdk` for tools passed via `createAgentSession({ customTools })`
1741
- - extension source metadata for tools registered by extensions
1742
-
1743
- ### knightcode.setModel(model)
1744
-
1745
- Set the model for the current session. The change is recorded in session history and restored when that session is resumed, but it does not change the configured `defaultProvider` or `defaultModel` used by new sessions. Returns `false` if authentication is not configured for the model's provider. See [models.md](models.md) for configuring custom models.
1746
-
1747
- ```typescript
1748
- const model = ctx.modelRegistry.find("anthropic", "claude-sonnet-4-5");
1749
- if (model) {
1750
- const success = await knightcode.setModel(model);
1751
- if (!success) {
1752
- ctx.ui.notify("Authentication is not configured for this model's provider", "error");
1753
- }
1754
- }
1755
- ```
1756
-
1757
- ### knightcode.getThinkingLevel() / knightcode.setThinkingLevel(level)
1758
-
1759
- Get the current thinking level. Level is clamped to model capabilities (non-reasoning models always use "off"). Changes emit `thinking_level_select`.
1760
-
1761
- `knightcode.setThinkingLevel()` changes the thinking level for the current session. The change is recorded in session history and restored when that session is resumed, but it does not change the configured default used by new sessions.
1762
-
1763
- ```typescript
1764
- const current = knightcode.getThinkingLevel(); // "off" | "minimal" | "low" | "medium" | "high" | "xhigh" | "max"
1765
- knightcode.setThinkingLevel("high");
1766
- ```
1767
-
1768
- ### knightcode.events
1769
-
1770
- Shared event bus for communication between extensions:
1771
-
1772
- ```typescript
1773
- knightcode.events.on("my:event", (data) => { ... });
1774
- knightcode.events.emit("my:event", { ... });
1775
- ```
1776
-
1777
- ### knightcode.registerProvider(name, config)
1778
-
1779
- Register or override a model provider dynamically. Useful for proxies, custom endpoints, or team-wide model configurations.
1780
-
1781
- Calls made during the extension factory function are queued and applied once the runner initialises. Calls made after that — for example from a command handler following a user setup flow — take effect immediately without requiring a `/reload`.
1782
-
1783
- Dynamic providers can implement `refreshModels`. KnightCode calls it during model refresh, publishes the returned list synchronously through the provider, and passes the canonical credential/stored-catalog/network/signal context. The extension decides whether to persist catalog metadata through generation-checked `context.publish({ persist: entry })`; live servers such as llama.cpp can return models without persisting them.
1784
-
1785
- `context.signal` is always a concrete signal and provider callbacks must pass it to blocking I/O. Public `ModelRuntime.refresh()` and `ModelRegistry.refresh()` calls accept an optional signal and are unbounded when it is omitted; extensions and applications choose their own deadlines. Cancellation stops the caller waiting even if a provider ignores the signal, but cooperation is still required to stop the underlying work.
1786
-
1787
- Extensions that need native provider auth, filtering, refresh, or stream behavior can register a complete `Provider` from `@knightcode/ai`. The provider becomes the composition base and `models.json` overrides still apply above it.
1788
-
1789
- ```typescript
1790
- import { createProvider, openAICompletionsApi } from "@knightcode/ai";
1791
-
1792
- const provider = createProvider({
1793
- id: "local-server",
1794
- name: "Local Server",
1795
- baseUrl: "http://localhost:8080/v1",
1796
- auth: {
1797
- apiKey: {
1798
- name: "Local server setup",
1799
- async login(interaction) {
1800
- return {
1801
- type: "api_key",
1802
- key: await interaction.prompt({ type: "secret", message: "API key" }),
1803
- };
1804
- },
1805
- async resolve({ credential }) {
1806
- return credential?.key
1807
- ? { auth: { apiKey: credential.key }, source: "stored API key" }
1808
- : undefined;
1809
- },
1810
- },
1811
- },
1812
- models: [],
1813
- api: openAICompletionsApi(),
1814
- });
1815
-
1816
- knightcode.registerProvider(provider);
1817
-
1818
- // Register a new provider with custom models
1819
- knightcode.registerProvider("my-proxy", {
1820
- name: "My Proxy",
1821
- baseUrl: "https://proxy.example.com",
1822
- apiKey: "$PROXY_API_KEY", // env var reference
1823
- api: "anthropic-messages",
1824
- models: [
1825
- {
1826
- id: "claude-sonnet-4-20250514",
1827
- name: "Claude 4 Sonnet (proxy)",
1828
- reasoning: false,
1829
- input: ["text", "image"],
1830
- cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
1831
- contextWindow: 200000,
1832
- maxTokens: 16384
1833
- }
1834
- ]
1835
- });
1836
-
1837
- // Register a live llama.cpp catalog without persisting discovered models
1838
- knightcode.registerProvider("llama.cpp", {
1839
- baseUrl: "http://localhost:8080/v1",
1840
- apiKey: "local",
1841
- api: "openai-completions",
1842
- async refreshModels({ signal }) {
1843
- const response = await fetch("http://localhost:8080/v1/models", { signal });
1844
- const { data } = await response.json();
1845
- return data.map(({ id }) => ({
1846
- id,
1847
- name: id,
1848
- reasoning: false,
1849
- input: ["text"],
1850
- cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
1851
- contextWindow: 128000,
1852
- maxTokens: 16384
1853
- }));
1854
- }
1855
- });
1856
-
1857
- // Override baseUrl for an existing provider (keeps all models)
1858
- knightcode.registerProvider("anthropic", {
1859
- baseUrl: "https://proxy.example.com"
1860
- });
1861
-
1862
- // Register provider with OAuth support for /login
1863
- knightcode.registerProvider("corporate-ai", {
1864
- baseUrl: "https://ai.corp.com",
1865
- api: "openai-responses",
1866
- models: [...],
1867
- oauth: {
1868
- name: "Corporate AI (SSO)",
1869
- async login(callbacks) {
1870
- // Custom OAuth flow
1871
- callbacks.onAuth({ url: "https://sso.corp.com/..." });
1872
- const code = await callbacks.onPrompt({ message: "Enter code:" });
1873
- return { refresh: code, access: code, expires: Date.now() + 3600000 };
1874
- },
1875
- async refreshToken(credentials, signal) {
1876
- signal.throwIfAborted();
1877
- // Refresh logic
1878
- return credentials;
1879
- },
1880
- getApiKey(credentials) {
1881
- return credentials.access;
1882
- }
1883
- }
1884
- });
1885
- ```
1886
-
1887
- The object form accepts a complete @knightcode/ai `Provider`, including native `auth`, `getModels`, `refreshModels`, `filterModels`, `stream`, and `streamSimple` behavior.
1888
-
1889
- **Legacy config options:**
1890
- - `name` - Display name for the provider in UI such as `/login`.
1891
- - `baseUrl` - API endpoint URL. Required when defining models.
1892
- - `apiKey` - API key literal, environment interpolation (`$ENV_VAR` or `${ENV_VAR}`), or leading `!command`. Required when defining models (unless `oauth` provided). `$$` escapes `$`, and `$!` escapes a literal `!` without triggering command execution.
1893
- - `api` - API type: `"anthropic-messages"`, `"openai-completions"`, `"openai-responses"`, etc.
1894
- - `headers` - Custom headers to include in requests.
1895
- - `authHeader` - If true, adds `Authorization: Bearer` header automatically.
1896
- - `models` - Array of model definitions. If provided, replaces all existing models for this provider. Model definitions can set `baseUrl` to override the provider endpoint for that model.
1897
- - `refreshModels` - Async dynamic discovery callback. Its returned models replace extension-provided models. `context.stored` contains the persisted provider snapshot; use generation-checked `context.publish({ persist: entry })` only when updated catalog data should persist. Use `persist: null` to delete that snapshot.
1898
- - `oauth` - OAuth provider config for `/login` support. When provided, the provider appears in the login menu.
1899
- - `streamSimple` - Custom streaming implementation for non-standard APIs.
1900
-
1901
- See [custom-provider.md](custom-provider.md) for advanced topics: custom streaming APIs, OAuth details, model definition reference.
1902
-
1903
- ### knightcode.unregisterProvider(name)
1904
-
1905
- Remove a previously registered provider and its models. Built-in models that were overridden by the provider are restored. Has no effect if the provider was not registered.
1906
-
1907
- Like `registerProvider`, this takes effect immediately when called after the initial load phase, so a `/reload` is not required.
1908
-
1909
- ```typescript
1910
- knightcode.registerCommand("my-setup-teardown", {
1911
- description: "Remove the custom proxy provider",
1912
- handler: async (_args, _ctx) => {
1913
- knightcode.unregisterProvider("my-proxy");
1914
- },
1915
- });
1916
- ```
1917
-
1918
- ## State Management
1919
-
1920
- Extensions with state should store it in tool result `details` for proper branching support:
1921
-
1922
- ```typescript
1923
- export default function (knightcode: ExtensionAPI) {
1924
- let items: string[] = [];
1925
-
1926
- // Reconstruct state from session
1927
- knightcode.on("session_start", async (_event, ctx) => {
1928
- items = [];
1929
- for (const entry of ctx.sessionManager.getBranch()) {
1930
- if (entry.type === "message" && entry.message.role === "toolResult") {
1931
- if (entry.message.toolName === "my_tool") {
1932
- items = entry.message.details?.items ?? [];
1933
- }
1934
- }
1935
- }
1936
- });
1937
-
1938
- knightcode.registerTool({
1939
- name: "my_tool",
1940
- // ...
1941
- async execute(toolCallId, params, signal, onUpdate, ctx) {
1942
- items.push("new item");
1943
- return {
1944
- content: [{ type: "text", text: "Added" }],
1945
- details: { items: [...items] }, // Store for reconstruction
1946
- };
1947
- },
1948
- });
1949
- }
1950
- ```
1951
-
1952
- ## Custom Tools
1953
-
1954
- Register tools the LLM can call via `knightcode.registerTool()`. Tools appear in the system prompt and can have custom rendering.
1955
-
1956
- Use `promptSnippet` for a short one-line entry in the `Available tools` section in the default system prompt. If omitted, custom tools are left out of that section.
1957
-
1958
- Use `promptGuidelines` to add tool-specific bullets to the default system prompt `Guidelines` section. These bullets are included only while the tool is active (for example, after `knightcode.setActiveTools([...])`).
1959
-
1960
- **Important:** `promptGuidelines` bullets are appended flat to the `Guidelines` section with no tool name prefix or grouping. Each guideline must name the tool it refers to — avoid "Use this tool when..." because the LLM cannot tell which tool "this" means. Write "Use my_tool when..." instead.
1961
-
1962
- Note: Some models are idiots and include the @ prefix in tool path arguments. Built-in tools strip a leading @ before resolving paths. If your custom tool accepts a path, normalize a leading @ as well.
1963
-
1964
- If your custom tool mutates files, use `withFileMutationQueue()` so it participates in the same per-file queue as built-in `edit` and `write`. This matters because tool calls run in parallel by default. Without the queue, two tools can read the same old file contents, compute different updates, and then whichever write lands last overwrites the other.
1965
-
1966
- Example failure case: your custom tool edits `foo.ts` while built-in `edit` also changes `foo.ts` in the same assistant turn. If your tool does not participate in the queue, both can read the original `foo.ts`, apply separate changes, and one of those changes is lost.
1967
-
1968
- Pass the real target file path to `withFileMutationQueue()`, not the raw user argument. Resolve it to an absolute path first, relative to `ctx.cwd` or your tool's working directory. For existing files, the helper canonicalizes through `realpath()`, so symlink aliases for the same file share one queue. For new files, it falls back to the resolved absolute path because there is nothing to `realpath()` yet.
1969
-
1970
- Queue the entire mutation window on that target path. That includes read-modify-write logic, not just the final write.
1971
-
1972
- ```typescript
1973
- import { withFileMutationQueue } from "@knightcodeai/cli";
1974
- import { mkdir, readFile, writeFile } from "node:fs/promises";
1975
- import { dirname, resolve } from "node:path";
1976
-
1977
- async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
1978
- const absolutePath = resolve(ctx.cwd, params.path);
1979
-
1980
- return withFileMutationQueue(absolutePath, async () => {
1981
- await mkdir(dirname(absolutePath), { recursive: true });
1982
- const current = await readFile(absolutePath, "utf8");
1983
- const next = current.replace(params.oldText, params.newText);
1984
- await writeFile(absolutePath, next, "utf8");
1985
-
1986
- return {
1987
- content: [{ type: "text", text: `Updated ${params.path}` }],
1988
- details: {},
1989
- };
1990
- });
1991
- }
1992
- ```
1993
-
1994
- ### Tool Definition
1995
-
1996
- ```typescript
1997
- import { Type } from "typebox";
1998
- import { StringEnum } from "@knightcode/ai";
1999
- import { Text } from "@knightcode/tui";
2000
-
2001
- knightcode.registerTool({
2002
- name: "my_tool",
2003
- label: "My Tool",
2004
- description: "What this tool does (shown to LLM)",
2005
- promptSnippet: "List or add items in the project todo list",
2006
- promptGuidelines: [
2007
- "Use my_tool for todo planning instead of direct file edits when the user asks for a task list."
2008
- ],
2009
- parameters: Type.Object({
2010
- action: StringEnum(["list", "add"] as const), // Use StringEnum for Google compatibility
2011
- text: Type.Optional(Type.String()),
2012
- }),
2013
- prepareArguments(args) {
2014
- if (!args || typeof args !== "object") return args;
2015
- const input = args as { action?: string; oldAction?: string };
2016
- if (typeof input.oldAction === "string" && input.action === undefined) {
2017
- return { ...input, action: input.oldAction };
2018
- }
2019
- return args;
2020
- },
2021
-
2022
- async execute(toolCallId, params, signal, onUpdate, ctx) {
2023
- // Check for cancellation
2024
- if (signal?.aborted) {
2025
- return { content: [{ type: "text", text: "Cancelled" }] };
2026
- }
2027
-
2028
- // Stream progress updates
2029
- onUpdate?.({
2030
- content: [{ type: "text", text: "Working..." }],
2031
- details: { progress: 50 },
2032
- });
2033
-
2034
- // Run commands via knightcode.exec (captured from extension closure)
2035
- const result = await knightcode.exec("some-command", [], { signal });
2036
-
2037
- // Return result
2038
- return {
2039
- content: [{ type: "text", text: "Done" }], // Sent to LLM
2040
- details: { data: result }, // For rendering & state
2041
- // usage: nestedModelResponse.usage, // Optional nested LLM usage
2042
- // Optional: stop after this tool batch when every finalized tool result
2043
- // in the batch also returns terminate: true.
2044
- terminate: true,
2045
- };
2046
- },
2047
-
2048
- // Optional: Custom rendering
2049
- renderCall(args, theme, context) { ... },
2050
- renderResult(result, options, theme, context) { ... },
2051
- });
2052
- ```
2053
-
2054
- **Usage accounting:** If a tool makes nested LLM calls, return their combined `Usage` as `usage`. KnightCode persists it on the tool result and includes it in footer, `/session`, and RPC session totals. `tool_result` handlers can inspect or replace this value.
2055
-
2056
- **Signaling errors:** To mark a tool execution as failed (sets `isError: true` on the result and reports it to the LLM), throw an error from `execute`. Returning a value never sets the error flag regardless of what properties you include in the return object.
2057
-
2058
- **Early termination:** Return `terminate: true` from `execute()` to hint that the automatic follow-up LLM call should be skipped after the current tool batch. This only takes effect when every finalized tool result in that batch is terminating. See [examples/extensions/structured-output.ts](../examples/extensions/structured-output.ts) for a minimal example where the agent ends on a final structured-output tool call.
2059
-
2060
- ```typescript
2061
- // Correct: throw to signal an error
2062
- async execute(toolCallId, params) {
2063
- if (!isValid(params.input)) {
2064
- throw new Error(`Invalid input: ${params.input}`);
2065
- }
2066
- return { content: [{ type: "text", text: "OK" }], details: {} };
2067
- }
2068
- ```
2069
-
2070
- **Important:** Use `StringEnum` from `@knightcode/ai` for string enums. `Type.Union`/`Type.Literal` doesn't work with Google's API.
2071
-
2072
- **Argument preparation:** `prepareArguments(args)` is optional. If defined, it runs before schema validation and before `execute()`. Use it to mimic an older accepted input shape when knightcode resumes an older session whose stored tool call arguments no longer match the current schema. Return the object you want validated against `parameters`. Keep the public schema strict. Do not add deprecated compatibility fields to `parameters` just to keep old resumed sessions working.
2073
-
2074
- Example: an older session may contain an `edit` tool call with top-level `oldText` and `newText`, while the current schema only accepts `edits: [{ oldText, newText }]`.
2075
-
2076
- ```typescript
2077
- knightcode.registerTool({
2078
- name: "edit",
2079
- label: "Edit",
2080
- description: "Edit a single file using exact text replacement",
2081
- parameters: Type.Object({
2082
- path: Type.String(),
2083
- edits: Type.Array(
2084
- Type.Object({
2085
- oldText: Type.String(),
2086
- newText: Type.String(),
2087
- }),
2088
- ),
2089
- }),
2090
- prepareArguments(args) {
2091
- if (!args || typeof args !== "object") return args;
2092
-
2093
- const input = args as {
2094
- path?: string;
2095
- edits?: Array<{ oldText: string; newText: string }>;
2096
- oldText?: unknown;
2097
- newText?: unknown;
2098
- };
2099
-
2100
- if (typeof input.oldText !== "string" || typeof input.newText !== "string") {
2101
- return args;
2102
- }
2103
-
2104
- return {
2105
- ...input,
2106
- edits: [...(input.edits ?? []), { oldText: input.oldText, newText: input.newText }],
2107
- };
2108
- },
2109
- async execute(toolCallId, params, signal, onUpdate, ctx) {
2110
- // params now matches the current schema
2111
- return {
2112
- content: [{ type: "text", text: `Applying ${params.edits.length} edit block(s)` }],
2113
- details: {},
2114
- };
2115
- },
2116
- });
2117
- ```
2118
-
2119
- ### Overriding Built-in Tools
2120
-
2121
- Extensions can override built-in tools (`read`, `bash`, `powershell`, `edit`, `write`, `grep`, `find`, `ls`) by registering a tool with the same name. Interactive mode displays a warning when this happens.
2122
-
2123
- ```bash
2124
- # Extension's read tool replaces built-in read
2125
- knightcode -e ./tool-override.ts
2126
- ```
2127
-
2128
- Alternatively, use `--no-builtin-tools` to start without any built-in tools while keeping extension tools enabled:
2129
- ```bash
2130
- # No built-in tools, only extension tools
2131
- knightcode --no-builtin-tools -e ./my-extension.ts
2132
- ```
2133
-
2134
- See [examples/extensions/tool-override.ts](../examples/extensions/tool-override.ts) for a complete example that overrides `read` with logging and access control.
2135
-
2136
- **Rendering:** Built-in renderer inheritance is resolved per slot. Execution override and rendering override are independent. If your override omits `renderCall`, the built-in `renderCall` is used. If your override omits `renderResult`, the built-in `renderResult` is used. If your override omits both, the built-in renderer is used automatically (syntax highlighting, diffs, etc.). This lets you wrap built-in tools for logging or access control without reimplementing the UI.
2137
-
2138
- **Prompt metadata:** `promptSnippet` and `promptGuidelines` are not inherited from the built-in tool. If your override should keep those prompt instructions, define them on the override explicitly.
2139
-
2140
- **Your implementation must match the exact result shape**, including the `details` type. The UI and session logic depend on these shapes for rendering and state tracking.
2141
-
2142
- Built-in tool implementations:
2143
- - [read.ts](https://github.com/KnightCodeAI/knightcode/blob/main/packages/coding-agent/src/core/tools/read.ts) - `ReadToolDetails`
2144
- - [bash.ts](https://github.com/KnightCodeAI/knightcode/blob/main/packages/coding-agent/src/core/tools/bash.ts) - `BashToolDetails`
2145
- - [powershell.ts](https://github.com/KnightCodeAI/knightcode/blob/main/packages/coding-agent/src/core/tools/powershell.ts) - `PowerShellToolDetails`
2146
- - [edit.ts](https://github.com/KnightCodeAI/knightcode/blob/main/packages/coding-agent/src/core/tools/edit.ts)
2147
- - [write.ts](https://github.com/KnightCodeAI/knightcode/blob/main/packages/coding-agent/src/core/tools/write.ts)
2148
- - [grep.ts](https://github.com/KnightCodeAI/knightcode/blob/main/packages/coding-agent/src/core/tools/grep.ts) - `GrepToolDetails`
2149
- - [find.ts](https://github.com/KnightCodeAI/knightcode/blob/main/packages/coding-agent/src/core/tools/find.ts) - `FindToolDetails`
2150
- - [ls.ts](https://github.com/KnightCodeAI/knightcode/blob/main/packages/coding-agent/src/core/tools/ls.ts) - `LsToolDetails`
2151
-
2152
- ### Remote Execution
2153
-
2154
- Built-in tools support pluggable operations for delegating to remote systems (SSH, containers, etc.):
2155
-
2156
- ```typescript
2157
- import { createReadTool, createBashTool, type ReadOperations } from "@knightcodeai/cli";
2158
-
2159
- // Create tool with custom operations
2160
- const remoteRead = createReadTool(cwd, {
2161
- operations: {
2162
- readFile: (path) => sshExec(remote, `cat ${path}`),
2163
- access: (path) => sshExec(remote, `test -r ${path}`).then(() => {}),
2164
- }
2165
- });
2166
-
2167
- // Register, checking flag at execution time
2168
- knightcode.registerTool({
2169
- ...remoteRead,
2170
- async execute(id, params, signal, onUpdate, _ctx) {
2171
- const ssh = getSshConfig();
2172
- if (ssh) {
2173
- const tool = createReadTool(cwd, { operations: createRemoteOps(ssh) });
2174
- return tool.execute(id, params, signal, onUpdate);
2175
- }
2176
- return localRead.execute(id, params, signal, onUpdate);
2177
- },
2178
- });
2179
- ```
2180
-
2181
- **Operations interfaces:** `ReadOperations`, `WriteOperations`, `EditOperations`, `BashOperations`, `PowerShellOperations`, `LsOperations`, `GrepOperations`, `FindOperations`
2182
-
2183
- For `user_bash`, extensions can reuse knightcode's local shell backend via `createLocalBashOperations()` instead of reimplementing local process spawning, shell resolution, and process-tree termination.
2184
-
2185
- The `bash` and `powershell` tools also support a spawn hook to adjust the command, cwd, or env before execution:
2186
-
2187
- ```typescript
2188
- import { createBashTool } from "@knightcodeai/cli";
2189
-
2190
- const bashTool = createBashTool(cwd, {
2191
- spawnHook: ({ command, cwd, env }) => ({
2192
- command: `source ~/.profile\n${command}`,
2193
- cwd: `/mnt/sandbox${cwd}`,
2194
- env: { ...env, CI: "1" },
2195
- }),
2196
- });
2197
- ```
2198
-
2199
- `createBashTool()` and `createPowerShellTool()` expose the current session to commands through `KNIGHTCODE_SESSION_ID`, `KNIGHTCODE_SESSION_FILE`, `KNIGHTCODE_PROVIDER`, `KNIGHTCODE_MODEL`, and `KNIGHTCODE_REASONING_LEVEL`. Injection happens before `spawnHook`, so hooks receive these values in `env` and preserve them when they spread the existing environment as above. Set `exposeSessionEnvironment: false` to disable them:
2200
-
2201
- ```typescript
2202
- const bashTool = createBashTool(cwd, {
2203
- exposeSessionEnvironment: false,
2204
- });
2205
- ```
2206
-
2207
- See [Shell tool session environment](environment-variables.md#shell-tool-session-environment) for variable semantics. See [examples/extensions/ssh.ts](../examples/extensions/ssh.ts) for a complete SSH example with `--ssh` flag.
2208
-
2209
- ### Output Truncation
2210
-
2211
- **Tools MUST truncate their output** to avoid overwhelming the LLM context. Large outputs can cause:
2212
- - Context overflow errors (prompt too long)
2213
- - Compaction failures
2214
- - Degraded model performance
2215
-
2216
- The built-in limit is **50KB** (~10k tokens) and **2000 lines**, whichever is hit first. Use the exported truncation utilities:
2217
-
2218
- ```typescript
2219
- import {
2220
- truncateHead, // Keep first N lines/bytes (good for file reads, search results)
2221
- truncateTail, // Keep last N lines/bytes (good for logs, command output)
2222
- truncateLine, // Truncate a single line to maxBytes with ellipsis
2223
- formatSize, // Human-readable size (e.g., "50KB", "1.5MB")
2224
- DEFAULT_MAX_BYTES, // 50KB
2225
- DEFAULT_MAX_LINES, // 2000
2226
- } from "@knightcodeai/cli";
2227
-
2228
- async execute(toolCallId, params, signal, onUpdate, ctx) {
2229
- const output = await runCommand();
2230
-
2231
- // Apply truncation
2232
- const truncation = truncateHead(output, {
2233
- maxLines: DEFAULT_MAX_LINES,
2234
- maxBytes: DEFAULT_MAX_BYTES,
2235
- });
2236
-
2237
- let result = truncation.content;
2238
-
2239
- if (truncation.truncated) {
2240
- // Write full output to temp file
2241
- const tempFile = writeTempFile(output);
2242
-
2243
- // Inform the LLM where to find complete output
2244
- result += `\n\n[Output truncated: ${truncation.outputLines} of ${truncation.totalLines} lines`;
2245
- result += ` (${formatSize(truncation.outputBytes)} of ${formatSize(truncation.totalBytes)}).`;
2246
- result += ` Full output saved to: ${tempFile}]`;
2247
- }
2248
-
2249
- return { content: [{ type: "text", text: result }] };
2250
- }
2251
- ```
2252
-
2253
- **Key points:**
2254
- - Use `truncateHead` for content where the beginning matters (search results, file reads)
2255
- - Use `truncateTail` for content where the end matters (logs, command output)
2256
- - Always inform the LLM when output is truncated and where to find the full version
2257
- - Document the truncation limits in your tool's description
2258
-
2259
- See [examples/extensions/truncated-tool.ts](../examples/extensions/truncated-tool.ts) for a complete example wrapping `rg` (ripgrep) with proper truncation.
2260
-
2261
- ### Multiple Tools
2262
-
2263
- One extension can register multiple tools with shared state:
2264
-
2265
- ```typescript
2266
- export default function (knightcode: ExtensionAPI) {
2267
- let connection = null;
2268
-
2269
- knightcode.registerTool({ name: "db_connect", ... });
2270
- knightcode.registerTool({ name: "db_query", ... });
2271
- knightcode.registerTool({ name: "db_close", ... });
2272
-
2273
- knightcode.on("session_shutdown", async () => {
2274
- connection?.close();
2275
- });
2276
- }
2277
- ```
2278
-
2279
- ### Custom Rendering
2280
-
2281
- Tools can provide `renderCall` and `renderResult` for custom TUI display. See [tui.md](tui.md) for the full component API and [tool-execution.ts](https://github.com/KnightCodeAI/knightcode/blob/main/packages/coding-agent/src/modes/interactive/components/tool-execution.ts) for how tool rows are composed.
2282
-
2283
- By default, tool output is wrapped in a `Box` that handles padding and background. A defined `renderCall` or `renderResult` must return a `Component`. If a slot renderer is not defined, `tool-execution.ts` uses fallback rendering for that slot.
2284
-
2285
- Set `renderShell: "self"` when the tool should render its own shell instead of using the default `Box`. This is useful for tools that need complete control over framing or background behavior, for example large previews that must stay visually stable after the tool settles.
2286
-
2287
- ```typescript
2288
- knightcode.registerTool({
2289
- name: "my_tool",
2290
- label: "My Tool",
2291
- description: "Custom shell example",
2292
- parameters: Type.Object({}),
2293
- renderShell: "self",
2294
- async execute() {
2295
- return { content: [{ type: "text", text: "ok" }], details: undefined };
2296
- },
2297
- renderCall(args, theme, context) {
2298
- return new Text(theme.fg("accent", "my custom shell"), 0, 0);
2299
- },
2300
- });
2301
- ```
2302
-
2303
- `renderCall` and `renderResult` each receive a `context` object with:
2304
- - `args` - the current tool call arguments
2305
- - `state` - shared row-local state across `renderCall` and `renderResult`
2306
- - `lastComponent` - the previously returned component for that slot, if any
2307
- - `invalidate()` - request a rerender of this tool row
2308
- - `toolCallId`, `cwd`, `executionStarted`, `argsComplete`, `isPartial`, `expanded`, `showImages`, `isError`
2309
-
2310
- Use `context.state` for cross-slot shared state. Keep slot-local caches on the returned component instance when you want to reuse and mutate the same component across renders.
2311
-
2312
- #### renderCall
2313
-
2314
- Renders the tool call or header:
2315
-
2316
- ```typescript
2317
- import { Text } from "@knightcode/tui";
2318
-
2319
- renderCall(args, theme, context) {
2320
- const text = (context.lastComponent as Text | undefined) ?? new Text("", 0, 0);
2321
- let content = theme.fg("toolTitle", theme.bold("my_tool "));
2322
- content += theme.fg("muted", args.action);
2323
- if (args.text) {
2324
- content += " " + theme.fg("dim", `"${args.text}"`);
2325
- }
2326
- text.setText(content);
2327
- return text;
2328
- }
2329
- ```
2330
-
2331
- #### renderResult
2332
-
2333
- Renders the tool result or output:
2334
-
2335
- ```typescript
2336
- renderResult(result, { expanded, isPartial }, theme, context) {
2337
- if (isPartial) {
2338
- return new Text(theme.fg("warning", "Processing..."), 0, 0);
2339
- }
2340
-
2341
- if (result.details?.error) {
2342
- return new Text(theme.fg("error", `Error: ${result.details.error}`), 0, 0);
2343
- }
2344
-
2345
- let text = theme.fg("success", "✓ Done");
2346
- if (expanded && result.details?.items) {
2347
- for (const item of result.details.items) {
2348
- text += "\n " + theme.fg("dim", item);
2349
- }
2350
- }
2351
- return new Text(text, 0, 0);
2352
- }
2353
- ```
2354
-
2355
- If a slot intentionally has no visible content, return an empty `Component` such as an empty `Container`.
2356
-
2357
- #### Keybinding Hints
2358
-
2359
- Use `keyHint()` to display keybinding hints that respect the active keybinding configuration:
2360
-
2361
- ```typescript
2362
- import { keyHint } from "@knightcodeai/cli";
2363
-
2364
- renderResult(result, { expanded }, theme, context) {
2365
- let text = theme.fg("success", "✓ Done");
2366
- if (!expanded) {
2367
- text += ` (${keyHint("app.tools.expand", "to expand")})`;
2368
- }
2369
- return new Text(text, 0, 0);
2370
- }
2371
- ```
2372
-
2373
- Available functions:
2374
- - `keyHint(keybinding, description)` - Formats a configured keybinding id such as `"app.tools.expand"` or `"tui.select.confirm"`
2375
- - `keyText(keybinding)` - Returns the raw configured key text for a keybinding id
2376
- - `rawKeyHint(key, description)` - Format a raw key string
2377
-
2378
- Use namespaced keybinding ids:
2379
- - Coding-agent ids use the `app.*` namespace, for example `app.tools.expand`, `app.editor.external`, `app.session.rename`
2380
- - Shared TUI ids use the `tui.*` namespace, for example `tui.select.confirm`, `tui.select.cancel`, `tui.input.tab`
2381
-
2382
- For the exhaustive list of keybinding ids and defaults, see [keybindings.md](keybindings.md). `keybindings.json` uses those same namespaced ids.
2383
-
2384
- Custom editors and `ctx.ui.custom()` components receive `keybindings: KeybindingsManager` as an injected argument. They should use that injected manager directly instead of calling `getKeybindings()` or `setKeybindings()`.
2385
-
2386
- #### Best Practices
2387
-
2388
- - Use `Text` with padding `(0, 0)`. The default Box handles padding.
2389
- - Use `\n` for multi-line content.
2390
- - Handle `isPartial` for streaming progress.
2391
- - Support `expanded` for detail on demand.
2392
- - Keep default view compact.
2393
- - Read `context.args` in `renderResult` instead of copying args into `context.state`.
2394
- - Use `context.state` only for data that must be shared across call and result slots.
2395
- - Reuse `context.lastComponent` when the same component instance can be updated in place.
2396
- - Use `renderShell: "self"` only when the default boxed shell gets in the way. In self-shell mode the tool is responsible for its own framing, padding, and background.
2397
-
2398
- #### Fallback
1
+ # Extensions
2399
2
 
2400
- If a slot renderer is not defined or throws:
2401
- - `renderCall`: Shows the tool name
2402
- - `renderResult`: Shows raw text from `content`
3
+ Extensions are TypeScript modules that add executable behavior to KnightCode. Use one when a workflow needs tools, commands, event handlers, model providers, session state, or terminal UI rather than instructions alone.
2403
4
 
2404
- ### Dynamic Tool Loading
5
+ An extension runs inside the KnightCode process with the same operating-system permissions. It can inspect prompts, tool calls, files, credentials, and session history, so load extensions only from sources you trust.
2405
6
 
2406
- Extensions can register many tools while keeping only a small initial set active. A tool can then change the active set with `knightcode.setActiveTools()` during execution. KnightCode stores the initial prompt and tool loadout in the transcript's first system message, then appends tool and prompt deltas before the next model request. Providers that cannot represent a transition receive a complete transcript checkpoint, which may invalidate the cached prefix.
7
+ Typical extensions add an agent tool, protect paths, confirm dangerous commands, react to session events, modify context, expose a command, or display persistent status.
2407
8
 
2408
- The lifecycle is:
9
+ <a id="quick-start"></a>
10
+ <a id="writing-an-extension"></a>
11
+ <a id="create-an-extension"></a>
2409
12
 
2410
- 1. Register every tool with `knightcode.registerTool()` so it appears in `knightcode.getAllTools()`.
2411
- 2. Keep loader tools, such as `search_tools`, active and leave searchable tools inactive.
2412
- 3. During loader execution, call `knightcode.setActiveTools()` with the desired active tool names. Names must already be registered; unknown names are ignored.
13
+ ## Create and load an extension
2413
14
 
2414
- #### Search tool example
15
+ An extension exports a default factory that receives `ExtensionAPI`. The factory registers capabilities for the current extension runtime.
2415
16
 
2416
- The following extension registers two searchable tools, removes them from the initial active set, and keeps only `search_tools` as their loader. The example uses simple keyword matching, but the search implementation could use BM25, embeddings, a remote catalog, or project-specific routing.
17
+ Create `~/.knightcode/agent/extensions/hello.ts`:
2417
18
 
2418
19
  ```typescript
2419
20
  import type { ExtensionAPI } from "@knightcodeai/cli";
2420
- import { Type } from "typebox";
2421
-
2422
- const SEARCHABLE_TOOL_NAMES = new Set(["lookup_weather", "search_issues"]);
2423
21
 
2424
22
  export default function (knightcode: ExtensionAPI) {
2425
- knightcode.registerTool({
2426
- name: "lookup_weather",
2427
- label: "Lookup Weather",
2428
- description: "Look up the current weather for a city",
2429
- parameters: Type.Object({ city: Type.String() }),
2430
- async execute(_toolCallId, params) {
2431
- return {
2432
- content: [{ type: "text", text: `Weather for ${params.city}: sunny` }],
2433
- details: {},
2434
- };
2435
- },
2436
- });
2437
-
2438
- knightcode.registerTool({
2439
- name: "search_issues",
2440
- label: "Search Issues",
2441
- description: "Search project issues by keyword",
2442
- parameters: Type.Object({ query: Type.String() }),
2443
- async execute(_toolCallId, params) {
2444
- return {
2445
- content: [{ type: "text", text: `No open issues matching ${params.query}` }],
2446
- details: {},
2447
- };
2448
- },
2449
- });
2450
-
2451
- knightcode.registerTool({
2452
- name: "search_tools",
2453
- label: "Search Tools",
2454
- description: "Search for and enable tools relevant to a task",
2455
- promptSnippet: "Search for additional tools when the active tools cannot perform the task",
2456
- promptGuidelines: [
2457
- "Use search_tools when a task requires a capability that is not currently available.",
2458
- ],
2459
- parameters: Type.Object({
2460
- query: Type.String({ description: "Capability or task to search for" }),
2461
- limit: Type.Optional(Type.Integer({ minimum: 1, maximum: 10 })),
2462
- }),
2463
- async execute(_toolCallId, params) {
2464
- const terms = params.query.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean);
2465
- const matches = knightcode.getAllTools()
2466
- .filter((tool) => SEARCHABLE_TOOL_NAMES.has(tool.name))
2467
- .map((tool) => ({
2468
- tool,
2469
- score: terms.reduce(
2470
- (score, term) =>
2471
- score + (`${tool.name} ${tool.description}`.toLowerCase().includes(term) ? 1 : 0),
2472
- 0,
2473
- ),
2474
- }))
2475
- .filter((match) => match.score > 0)
2476
- .sort((a, b) => b.score - a.score)
2477
- .slice(0, params.limit ?? 3)
2478
- .map((match) => match.tool.name);
2479
-
2480
- if (matches.length === 0) {
2481
- return {
2482
- content: [{ type: "text", text: `No tools found for: ${params.query}` }],
2483
- details: { matches: [] },
2484
- };
2485
- }
2486
-
2487
- const active = knightcode.getActiveTools();
2488
- const added = matches.filter((name) => !active.includes(name));
2489
- knightcode.setActiveTools([...new Set([...active, ...added])]);
2490
-
2491
- return {
2492
- content: [{
2493
- type: "text",
2494
- text: added.length > 0
2495
- ? `Loaded tools: ${added.join(", ")}`
2496
- : `Matching tools already active: ${matches.join(", ")}`,
2497
- }],
2498
- details: { matches, added },
2499
- };
23
+ knightcode.registerCommand("hello", {
24
+ description: "Show a greeting",
25
+ handler: async (name, ctx) => {
26
+ ctx.ui.notify(`Hello, ${name || "world"}!`, "info");
2500
27
  },
2501
28
  });
2502
-
2503
- knightcode.on("session_start", () => {
2504
- // Keep searchable tools registered but initially inactive. Preserve built-ins
2505
- // and tools owned by other extensions, and keep the loader itself active.
2506
- const initialTools = knightcode.getActiveTools().filter(
2507
- (name) => !SEARCHABLE_TOOL_NAMES.has(name),
2508
- );
2509
- knightcode.setActiveTools([...new Set([...initialTools, "search_tools"])]);
2510
- });
2511
29
  }
2512
30
  ```
2513
31
 
2514
- When `search_tools` adds a match, the model receives the complete updated tool list on the immediately following request.
2515
-
2516
- ## Custom UI
32
+ Start KnightCode and run `/hello`. During development, load a file directly:
2517
33
 
2518
- Extensions can interact with users via `ctx.ui` methods and customize how messages/tools render.
2519
-
2520
- **For custom components, see [tui.md](tui.md)** which has copy-paste patterns for:
2521
- - Selection dialogs (SelectList)
2522
- - Async operations with cancel (BorderedLoader)
2523
- - Settings toggles (SettingsList)
2524
- - Status indicators (setStatus)
2525
- - Working message, visibility, and indicator during streaming (`setWorkingMessage`, `setWorkingVisible`, `setWorkingIndicator`)
2526
- - Widgets above/below editor (setWidget)
2527
- - Autocomplete providers layered on top of built-in slash/path completion (addAutocompleteProvider)
2528
- - Custom footers (setFooter)
2529
-
2530
- ### Dialogs
2531
-
2532
- ```typescript
2533
- // Select from options
2534
- const choice = await ctx.ui.select("Pick one:", ["A", "B", "C"]);
2535
-
2536
- // Confirm dialog
2537
- const ok = await ctx.ui.confirm("Delete?", "This cannot be undone");
2538
-
2539
- // Text input
2540
- const name = await ctx.ui.input("Name:", "placeholder");
2541
-
2542
- // Multi-line editor
2543
- const text = await ctx.ui.editor("Edit:", "prefilled text");
2544
-
2545
- // Notification (non-blocking)
2546
- ctx.ui.notify("Done!", "info"); // "info" | "warning" | "error"
34
+ ```bash
35
+ knightcode --extension ./hello.ts
2547
36
  ```
2548
37
 
2549
- #### Timed Dialogs with Countdown
38
+ KnightCode uses `jiti`, so local TypeScript extensions do not need a separate compilation step. Use [KnightCode packages](packages.md) for distributed extensions and dependencies.
2550
39
 
2551
- Dialogs support a `timeout` option that auto-dismisses with a live countdown display:
40
+ <a id="extension-locations"></a>
41
+ <a id="available-imports"></a>
42
+ <a id="choose-where-it-loads"></a>
2552
43
 
2553
- ```typescript
2554
- // Dialog shows "Title (5s)" → "Title (4s)" → ... → auto-dismisses at 0
2555
- const confirmed = await ctx.ui.confirm(
2556
- "Timed Confirmation",
2557
- "This dialog will auto-cancel in 5 seconds. Confirm?",
2558
- { timeout: 5000 }
2559
- );
2560
-
2561
- if (confirmed) {
2562
- // User confirmed
2563
- } else {
2564
- // User cancelled or timed out
2565
- }
2566
- ```
44
+ ## Add it to KnightCode
2567
45
 
2568
- **Return values on timeout:**
2569
- - `select()` returns `undefined`
2570
- - `confirm()` returns `false`
2571
- - `input()` returns `undefined`
46
+ Place the extension in your user or project extensions directory. KnightCode loads direct TypeScript or JavaScript files and subdirectories containing an `index.ts` or `index.js` entry point.
2572
47
 
2573
- #### Manual Dismissal with AbortSignal
48
+ Use a single file for a small extension and a directory for a multi-file implementation. Put npm dependencies in a nearby `package.json`. See [Configuration](configuration.md) for conventional locations and [Settings](settings.md#resources) for additional paths.
2574
49
 
2575
- For more control (e.g., to distinguish timeout from user cancel), use `AbortSignal`:
50
+ Reload replaces the extension runtime, so code after `await ctx.reload()` must not reuse state from the old runtime. Only personal and explicit command-line extensions can participate in the `project_trust` event that runs before project extensions load.
2576
51
 
2577
- ```typescript
2578
- const controller = new AbortController();
2579
- const timeoutId = setTimeout(() => controller.abort(), 5000);
2580
-
2581
- const confirmed = await ctx.ui.confirm(
2582
- "Timed Confirmation",
2583
- "This dialog will auto-cancel in 5 seconds. Confirm?",
2584
- { signal: controller.signal }
2585
- );
2586
-
2587
- clearTimeout(timeoutId);
2588
-
2589
- if (confirmed) {
2590
- // User confirmed
2591
- } else if (controller.signal.aborted) {
2592
- // Dialog timed out
2593
- } else {
2594
- // User cancelled (pressed Escape or selected "No")
2595
- }
2596
- ```
52
+ <a id="understand-the-lifecycle"></a>
2597
53
 
2598
- See [examples/extensions/timed-confirm.ts](../examples/extensions/timed-confirm.ts) for complete examples.
54
+ ## Respect the runtime lifecycle
2599
55
 
2600
- ### Widgets, Status, and Footer
56
+ The factory can be synchronous or asynchronous. KnightCode waits for an asynchronous factory before startup continues, allowing it to fetch configuration or register providers needed during startup.
2601
57
 
2602
- ```typescript
2603
- // Status in footer (persistent until cleared)
2604
- ctx.ui.setStatus("my-ext", "Processing...");
2605
- ctx.ui.setStatus("my-ext", undefined); // Clear
2606
-
2607
- // Working loader (shown during streaming)
2608
- ctx.ui.setWorkingMessage("Thinking deeply...");
2609
- ctx.ui.setWorkingMessage(); // Restore default
2610
- ctx.ui.setWorkingVisible(false); // Hide the built-in working loader row entirely
2611
- ctx.ui.setWorkingVisible(true); // Show the built-in working loader row
2612
-
2613
- // Working indicator (shown during streaming)
2614
- ctx.ui.setWorkingIndicator({ frames: [ctx.ui.theme.fg("accent", "●")] }); // Static dot
2615
- ctx.ui.setWorkingIndicator({
2616
- frames: [
2617
- ctx.ui.theme.fg("dim", "·"),
2618
- ctx.ui.theme.fg("muted", "•"),
2619
- ctx.ui.theme.fg("accent", "●"),
2620
- ctx.ui.theme.fg("muted", "•"),
2621
- ],
2622
- intervalMs: 120,
2623
- });
2624
- ctx.ui.setWorkingIndicator({ frames: [] }); // Hide indicator
2625
- ctx.ui.setWorkingIndicator(); // Restore default spinner
2626
-
2627
- // Widget above editor (default)
2628
- ctx.ui.setWidget("my-widget", ["Line 1", "Line 2"]);
2629
- // Widget below editor
2630
- ctx.ui.setWidget("my-widget", ["Line 1", "Line 2"], { placement: "belowEditor" });
2631
- ctx.ui.setWidget("my-widget", (tui, theme) => new Text(theme.fg("accent", "Custom"), 0, 0));
2632
- ctx.ui.setWidget("my-widget", undefined); // Clear
2633
-
2634
- // Custom footer (replaces built-in footer entirely)
2635
- ctx.ui.setFooter((tui, theme) => ({
2636
- render(width) { return [theme.fg("dim", "Custom footer")]; },
2637
- invalidate() {},
2638
- }));
2639
- ctx.ui.setFooter(undefined); // Restore built-in footer
2640
-
2641
- // Terminal title
2642
- ctx.ui.setTitle("knightcode - my-project");
2643
-
2644
- // Editor text
2645
- ctx.ui.setEditorText("Prefill text");
2646
- const current = ctx.ui.getEditorText();
2647
-
2648
- // Paste into editor (triggers paste handling, including collapse for large content)
2649
- ctx.ui.pasteToEditor("pasted content");
2650
-
2651
- // Stack custom autocomplete behavior on top of the built-in provider
2652
- ctx.ui.addAutocompleteProvider((current) => ({
2653
- triggerCharacters: ["#"],
2654
- async getSuggestions(lines, line, col, options) {
2655
- const beforeCursor = (lines[line] ?? "").slice(0, col);
2656
- const match = beforeCursor.match(/(?:^|[ \t])#([^\s#]*)$/);
2657
- if (!match) {
2658
- return current.getSuggestions(lines, line, col, options);
2659
- }
2660
-
2661
- return {
2662
- prefix: `#${match[1] ?? ""}`,
2663
- items: [{ value: "#2983", label: "#2983", description: "Extension API for autocomplete" }],
2664
- };
2665
- },
2666
- applyCompletion(lines, line, col, item, prefix) {
2667
- return current.applyCompletion(lines, line, col, item, prefix);
2668
- },
2669
- shouldTriggerFileCompletion(lines, line, col) {
2670
- return current.shouldTriggerFileCompletion?.(lines, line, col) ?? true;
2671
- },
2672
- }));
2673
-
2674
- // Tool output expansion
2675
- const wasExpanded = ctx.ui.getToolsExpanded();
2676
- ctx.ui.setToolsExpanded(true);
2677
- ctx.ui.setToolsExpanded(wasExpanded);
2678
-
2679
- // Custom editor (vim mode, emacs mode, etc.)
2680
- ctx.ui.setEditorComponent((tui, theme, keybindings) => new VimEditor(tui, theme, keybindings));
2681
- const currentEditor = ctx.ui.getEditorComponent();
2682
- ctx.ui.setEditorComponent((tui, theme, keybindings) =>
2683
- new WrappedEditor(tui, theme, keybindings, currentEditor?.(tui, theme, keybindings))
2684
- );
2685
- ctx.ui.setEditorComponent(undefined); // Restore default editor
2686
-
2687
- // Theme management (see themes.md for creating themes)
2688
- const themes = ctx.ui.getAllThemes(); // [{ name: "dark", path: "/..." | undefined }, ...]
2689
- const lightTheme = ctx.ui.getTheme("light"); // Load without switching
2690
- const result = ctx.ui.setTheme("light"); // Switch by name
2691
- if (!result.success) {
2692
- ctx.ui.notify(`Failed: ${result.error}`, "error");
2693
- }
2694
- ctx.ui.setTheme(lightTheme!); // Or switch by Theme object
2695
- ctx.ui.theme.fg("accent", "styled text"); // Access current theme
2696
- ```
58
+ Do not start processes, sockets, watchers, or timers in the factory because some invocations load extensions without starting a session.
59
+ Start long-lived resources from `session_start` or from the command or tool that needs them.
60
+ Close session-scoped resources from an idempotent `session_shutdown` handler.
2697
61
 
2698
- Custom working-indicator frames are rendered verbatim. If you want colors, add them to the frame strings yourself, for example with `ctx.ui.theme.fg(...)`.
62
+ A run proceeds from input and `before_agent_start`, through model, message, and tool events, to `agent_end`.
63
+ Automatic retries, recovery, compaction, or queued work can continue afterward.
64
+ <a id="agent_start--agent_end--agent_before_settle--agent_settled"></a>
2699
65
 
2700
- ### Autocomplete Providers
66
+ `agent_before_settle` is the final actionable boundary: it can append entries and request one continuation.
67
+ `agent_settled` is final and notification-only; use it when an integration needs to know KnightCode will not continue automatically.
2701
68
 
2702
- Use `ctx.ui.addAutocompleteProvider()` to stack custom autocomplete logic on top of the built-in slash-command and path provider. Set `triggerCharacters` for custom natural triggers such as `$`.
69
+ <a id="extensionapi-methods"></a>
2703
70
 
2704
- Typical pattern:
71
+ ## Choose an integration point
2705
72
 
2706
- - inspect the text before the cursor
2707
- - return your own suggestions when your extension-specific syntax matches
2708
- - otherwise delegate to `current.getSuggestions(...)`
2709
- - delegate `applyCompletion(...)` unless you need custom insertion behavior
73
+ | Capability | Main API |
74
+ |---|---|
75
+ | Observe or modify lifecycle behavior | `knightcode.on()` |
76
+ | Add a model-callable operation | `knightcode.registerTool()` |
77
+ | Add a `/` command | `knightcode.registerCommand()` |
78
+ | Add a shortcut or CLI flag | `knightcode.registerShortcut()` or `knightcode.registerFlag()` |
79
+ | Send user or custom messages | `knightcode.sendUserMessage()` or `knightcode.sendMessage()` |
80
+ | Persist non-context session data | `knightcode.appendEntry()` |
81
+ | Change active tools, model, or thinking level | Session control methods on `knightcode` |
82
+ | Add a model provider | `knightcode.registerProvider()` |
83
+ | Add terminal rendering | Renderer registration and `ctx.ui` |
84
+ | Communicate with another extension | `knightcode.events` |
2710
85
 
2711
- ```typescript
2712
- knightcode.on("session_start", (_event, ctx) => {
2713
- ctx.ui.addAutocompleteProvider((current) => ({
2714
- triggerCharacters: ["#"],
2715
- async getSuggestions(lines, cursorLine, cursorCol, options) {
2716
- const line = lines[cursorLine] ?? "";
2717
- const beforeCursor = line.slice(0, cursorCol);
2718
- const match = beforeCursor.match(/(?:^|[ \t])#([^\s#]*)$/);
2719
- if (!match) {
2720
- return current.getSuggestions(lines, cursorLine, cursorCol, options);
2721
- }
2722
-
2723
- return {
2724
- prefix: `#${match[1] ?? ""}`,
2725
- items: [
2726
- { value: "#2983", label: "#2983", description: "Extension API for registering custom @ autocomplete providers" },
2727
- { value: "#2753", label: "#2753", description: "Reload stale resource settings" },
2728
- ],
2729
- };
2730
- },
86
+ Use the exported declarations in [`extensions/types.ts`](https://github.com/KnightCodeAI/knightcode/blob/main/packages/cli/src/core/extensions/types.ts) for exact event, context, tool, and result types.
2731
87
 
2732
- applyCompletion(lines, cursorLine, cursorCol, item, prefix) {
2733
- return current.applyCompletion(lines, cursorLine, cursorCol, item, prefix);
2734
- },
88
+ ## Follow the extension contracts
2735
89
 
2736
- shouldTriggerFileCompletion(lines, cursorLine, cursorCol) {
2737
- return current.shouldTriggerFileCompletion?.(lines, cursorLine, cursorCol) ?? true;
2738
- },
2739
- }));
2740
- });
2741
- ```
90
+ <a id="events"></a>
91
+ <a id="work-with-events"></a>
2742
92
 
2743
- See [github-issue-autocomplete.ts](../examples/extensions/github-issue-autocomplete.ts) for a complete example that preloads the latest open GitHub issues with `gh issue list` and filters them locally for fast `#...` completion. It requires GitHub CLI (`gh`) and a GitHub repository checkout.
93
+ ### Events and concurrency
2744
94
 
2745
- ### Custom Components
95
+ Handlers run in extension load and registration order. `knightcode.on()` returns a function that unsubscribes that registration; changes do not affect a dispatch already in progress.
96
+ Some events notify; others transform data, replace results, or cancel an operation.
97
+ Use each event’s declared result type rather than assuming every return value has an effect.
2746
98
 
2747
- For complex UI, use `ctx.ui.custom()`. This temporarily replaces the editor with your component until `done()` is called:
99
+ Events cover resource discovery, sessions, agent and message lifecycle, providers, tools, and raw input.
2748
100
 
2749
- ```typescript
2750
- import { Text, Component } from "@knightcode/tui";
101
+ `before_agent_start` exposes both the current prompt and its structured `systemPromptOptions`. Prefer changing prompt sections, selected tools, or guidelines so KnightCode can append a transcript delta. Returning `systemPrompt`, or setting `forceSystemPrompt`, replaces the whole prompt for that run while the transcript continues recording the structured sections. Providers receive the forced text as their leading system prompt.
2751
102
 
2752
- const result = await ctx.ui.custom<boolean>((tui, theme, keybindings, done) => {
2753
- const text = new Text("Press Enter to confirm, Escape to cancel", 1, 1);
103
+ `message_end` can replace a finalized message while preserving its role. `tool_call` can mutate input or block execution. `tool_result` handlers compose, with each handler seeing prior changes.
2754
104
 
2755
- text.onKey = (key) => {
2756
- if (key === "return") done(true);
2757
- if (key === "escape") done(false);
2758
- return true;
2759
- };
105
+ <a id="context_with_system"></a>
2760
106
 
2761
- return text;
2762
- });
107
+ `context` transforms conversation messages without prompt and tool system messages; KnightCode restores that state afterward. Use `context_with_system` only when a request-local transformation must own the complete transcript, and keep a system message at index zero.
2763
108
 
2764
- if (result) {
2765
- // User pressed Enter
2766
- }
2767
- ```
109
+ `turn_end` and `agent_before_settle` are actionable boundaries. Their handlers can chain proposed `custom`, `custom_message`, `context_edit`, or `compaction` entries and return `continue: true` for one next model request. Guard continuation conditions because an unconditional continuation can loop. Use the exported event declarations for the complete validation and ordering contract.
2768
110
 
2769
- The callback receives:
2770
- - `tui` - TUI instance (for screen dimensions, focus management)
2771
- - `theme` - Current theme for styling
2772
- - `keybindings` - App keybinding manager (for checking shortcuts)
2773
- - `done(value)` - Call to close component and return value
111
+ <a id="cache_warming_decision"></a>
2774
112
 
2775
- See [tui.md](tui.md) for the full component API.
113
+ `cache_warming_decision` can override an idle prompt-cache refresh with `{ action: "warm" }` or `{ action: "stop" }`. The last handler that returns an action wins.
2776
114
 
2777
- #### Overlay Mode (Experimental)
115
+ Tool calls from one assistant message can run in parallel.
116
+ Do not assume a sibling call or result exists when another tool event runs.
117
+ Use `ctx.signal` for nested work owned by an active turn; commands and idle session events often have no operation signal.
2778
118
 
2779
- Pass `{ overlay: true }` to render the component as a floating modal on top of existing content, without clearing the screen:
119
+ A `user_bash` handler that returns `undefined` passes the command to the next handler and then to local execution if no handler handles it. Returning `operations` or `result` stops propagation. A handler failure blocks the command rather than falling through to local execution.
2780
120
 
2781
- ```typescript
2782
- const result = await ctx.ui.custom<string | null>(
2783
- (tui, theme, keybindings, done) => new MyOverlayComponent({ onClose: done }),
2784
- { overlay: true }
2785
- );
2786
- ```
121
+ <a id="custom-tools"></a>
122
+ <a id="register-tools"></a>
2787
123
 
2788
- For advanced positioning (anchors, margins, percentages, responsive visibility), pass `overlayOptions`. Use `onHandle` to control focus or visibility programmatically:
124
+ ### Tools
2789
125
 
2790
- ```typescript
2791
- const result = await ctx.ui.custom<string | null>(
2792
- (tui, theme, keybindings, done) => new MyOverlayComponent({ onClose: done }),
2793
- {
2794
- overlay: true,
2795
- overlayOptions: { anchor: "top-right", width: "50%", margin: 2 },
2796
- onHandle: (handle) => {
2797
- handle.focus(); // focus this overlay and bring it to the visual front
2798
- // handle.unfocus({ target: editorComponent }); // release input to a specific component
2799
- // handle.setHidden(true/false); // toggle visibility
2800
- // handle.hide(); // permanently remove
2801
- }
2802
- }
2803
- );
2804
- ```
126
+ A custom tool defines a name, model-facing description, TypeBox parameter schema, and `execute()` function.
127
+ Its result requires model-facing `content` and a `details` field for rendering or state reconstruction.
128
+ Use `details: undefined` when there are no structured details. If the tool makes nested model calls, include their `usage` in the result so session totals remain accurate.
2805
129
 
2806
- A focused visible overlay can reclaim input after temporary non-overlay custom UI closes. If you intentionally want another component to keep input while the overlay stays visible, call `handle.unfocus({ target })`. Passing `{ target: null }` releases the overlay without focusing another component.
130
+ Throw from `execute()` to produce a failed tool result.
131
+ Returning an object does not mark it as an error.
132
+ Return `terminate: true` only when the agent should skip its automatic follow-up after every completed tool in that batch agrees to terminate.
2807
133
 
2808
- See [tui.md](tui.md) for the full `OverlayOptions` and `OverlayHandle` API and [overlay-qa-tests.ts](../examples/extensions/overlay-qa-tests.ts) for examples.
134
+ Use sequential execution when tools share mutable in-memory state.
135
+ File-mutating tools should wrap the complete read-modify-write operation with `withFileMutationQueue()`.
136
+ Truncate large model-facing results and tell the model where to read the complete output.
2809
137
 
2810
- ### Custom Editor
138
+ See [`hello.ts`](../examples/extensions/hello.ts), [`todo.ts`](../examples/extensions/todo.ts), [`dynamic-tools.ts`](../examples/extensions/dynamic-tools.ts), and [`truncated-tool.ts`](../examples/extensions/truncated-tool.ts).
2811
139
 
2812
- Replace the main input editor with a custom implementation (vim mode, emacs mode, etc.):
140
+ ### Activate tools dynamically
2813
141
 
2814
- ```typescript
2815
- import { CustomEditor, type ExtensionAPI } from "@knightcodeai/cli";
2816
- import { matchesKey } from "@knightcode/tui";
2817
-
2818
- class VimEditor extends CustomEditor {
2819
- private mode: "normal" | "insert" = "insert";
2820
-
2821
- handleInput(data: string): void {
2822
- if (matchesKey(data, "escape") && this.mode === "insert") {
2823
- this.mode = "normal";
2824
- return;
2825
- }
2826
- if (this.mode === "normal" && data === "i") {
2827
- this.mode = "insert";
2828
- return;
2829
- }
2830
- super.handleInput(data); // App keybindings + text editing
2831
- }
2832
- }
142
+ Register every tool first, keep optional tools inactive, and use `knightcode.setActiveTools()` from a loader tool to select the desired active tools. Names must already be registered; unknown names are ignored.
2833
143
 
2834
- export default function (knightcode: ExtensionAPI) {
2835
- knightcode.on("session_start", (_event, ctx) => {
2836
- ctx.ui.setEditorComponent((tui, theme, keybindings) =>
2837
- new VimEditor(tui, theme, keybindings)
2838
- );
2839
- });
2840
- }
2841
- ```
144
+ KnightCode records the initial prompt and tool set in the transcript's first system message, then appends tool and prompt changes before the next model request. Providers that cannot represent the transition receive a complete transcript checkpoint, which can invalidate the cached prefix.
2842
145
 
2843
- **Key points:**
2844
- - Extend `CustomEditor` (not base `Editor`) to get app keybindings (escape to abort, ctrl+d, model switching)
2845
- - Call `super.handleInput(data)` for keys you don't handle
2846
- - Custom editors keep the standalone working row by default. Pass `{ embedWorkingStatus: true }` as the fourth `CustomEditor` constructor argument to use the built-in editor-border spinner instead.
2847
- - Factory receives `tui`, `theme`, and `keybindings` from the app
2848
- - Use `ctx.ui.getEditorComponent()` before `setEditorComponent()` to wrap the previously configured custom editor
2849
- - Pass `undefined` to restore default: `ctx.ui.setEditorComponent(undefined)`
146
+ <a id="extensioncontext"></a>
147
+ <a id="extensioncommandcontext"></a>
148
+ <a id="use-extension-context"></a>
2850
149
 
2851
- To compose with another extension that already replaced the editor, capture the previous factory before setting yours:
150
+ ### Context and session changes
2852
151
 
2853
- ```typescript
2854
- const previous = ctx.ui.getEditorComponent();
2855
- ctx.ui.setEditorComponent((tui, theme, keybindings) =>
2856
- new MyEditor(tui, theme, keybindings, { base: previous?.(tui, theme, keybindings) })
2857
- );
2858
- ```
152
+ `ExtensionContext` provides the working directory, mode, UI, session manager, model runtime, abort signal, context usage, and controls for compaction and shutdown.
153
+ Use `ctx.modelRegistry.streamSimple()` for provider-neutral nested model calls.
2859
154
 
2860
- See [tui.md](tui.md) Pattern 7 for a complete example with mode indicator.
155
+ Command handlers receive `ExtensionCommandContext`, which adds operations for waiting until idle, reloading, tree navigation, and session replacement.
156
+ These operations are command-only because calling them from lifecycle handlers can deadlock the runtime.
2861
157
 
2862
- ### Message and Entry Rendering
158
+ Session replacement invalidates the old context. Capture only plain data before switching, then use the fresh context supplied to `withSession` for session-bound work.
2863
159
 
2864
- Register a custom renderer for messages with your `customType`. Use message renderers for content that should participate in LLM context:
160
+ <a id="state-management"></a>
161
+ <a id="persist-state"></a>
2865
162
 
2866
- ```typescript
2867
- import { Text } from "@knightcode/tui";
163
+ ### State
2868
164
 
2869
- knightcode.registerMessageRenderer("my-extension", (message, options, theme) => {
2870
- const { expanded, outputPad } = options;
2871
- let text = theme.fg("accent", `[${message.customType}] `);
2872
- text += message.content;
165
+ Choose storage based on how state participates in the conversation:
2873
166
 
2874
- if (expanded && message.details) {
2875
- text += "\n" + theme.fg("dim", JSON.stringify(message.details, null, 2));
2876
- }
167
+ | State | Storage |
168
+ |---|---|
169
+ | Tool state that follows the active branch | Tool-result `details` |
170
+ | Durable data excluded from model context | `knightcode.appendEntry()` |
171
+ | Custom content stored and sent to the model | `knightcode.sendMessage()` |
172
+ | Data outside one session | External storage |
2877
173
 
2878
- return new Text(text, outputPad, 0);
2879
- });
2880
- ```
174
+ Reconstruct branch-sensitive state from `ctx.sessionManager.getBranch()` during `session_start`.
175
+ Do not rebuild it from every file entry because abandoned branches represent alternative histories.
176
+ Register an entry or message renderer when custom stored content should appear in the transcript.
2881
177
 
2882
- Messages are sent via `knightcode.sendMessage()`:
178
+ <a id="custom-ui"></a>
179
+ <a id="mode-behavior"></a>
180
+ <a id="interact-with-the-user"></a>
181
+ <a id="account-for-each-mode"></a>
2883
182
 
2884
- ```typescript
2885
- knightcode.sendMessage({
2886
- customType: "my-extension", // Matches registerMessageRenderer
2887
- content: "Status update",
2888
- display: true, // Show in TUI
2889
- details: { ... }, // Available in renderer
2890
- });
2891
- ```
183
+ ### UI and modes
2892
184
 
2893
- For TUI-only content that should not be sent to the LLM, render custom entries instead:
185
+ `ctx.ui` provides dialogs, notifications, status text, widgets, titles, editor access, and custom components.
186
+ Use `ctx.ui.custom()` only when the interaction needs its own rendering and input.
187
+ See [Terminal UI](tui.md) for component, focus, overlay, theme, and performance guidance.
2894
188
 
2895
- ```typescript
2896
- knightcode.registerEntryRenderer("my-card", (entry, options, theme) => {
2897
- return new Text(theme.fg("accent", JSON.stringify(entry.data)));
2898
- });
189
+ Extensions load in interactive, RPC, JSON, and print modes.
190
+ Interactive mode provides the complete terminal UI.
191
+ RPC can forward supported dialogs and notifications through the [RPC Extension UI protocol](rpc-extension-ui.md), but not custom terminal components; JSON and print modes have no UI.
192
+ Guard terminal-only behavior with `ctx.mode === "tui"` and use `ctx.hasUI` for interactions supported by interactive and RPC clients.
2899
193
 
2900
- knightcode.appendEntry("my-card", { status: "done" });
2901
- ```
194
+ Keep tool and event behavior independent from rendering so non-interactive modes remain functional.
2902
195
 
2903
- ### Theme Colors
196
+ <a id="error-handling"></a>
197
+ <a id="handle-errors-and-shutdown"></a>
2904
198
 
2905
- All render functions receive a `theme` object. See [themes.md](themes.md) for creating custom themes and the full color palette.
199
+ ### Errors and cleanup
2906
200
 
2907
- ```typescript
2908
- // Foreground colors
2909
- theme.fg("toolTitle", text) // Tool names
2910
- theme.fg("accent", text) // Highlights
2911
- theme.fg("success", text) // Success (green)
2912
- theme.fg("error", text) // Errors (red)
2913
- theme.fg("warning", text) // Warnings (yellow)
2914
- theme.fg("muted", text) // Secondary text
2915
- theme.fg("dim", text) // Tertiary text
2916
-
2917
- // Text styles
2918
- theme.bold(text)
2919
- theme.italic(text)
2920
- theme.strikethrough(text)
2921
- ```
201
+ KnightCode reports handler errors and continues where possible. A `tool_call` handler failure blocks the tool as a fail-safe; a tool execution failure becomes an error result for the model.
2922
202
 
2923
- For syntax highlighting in custom tool renderers:
203
+ Release resources in `session_shutdown` even when normal operation attempted cleanup.
204
+ Keep cleanup idempotent because cancellation, reload, session replacement, and process exit can converge on the same path.
205
+ Use `ctx.shutdown()` to request an orderly process shutdown.
2924
206
 
2925
- ```typescript
2926
- import { highlightCode, getLanguageFromPath } from "@knightcodeai/cli";
207
+ <a id="examples-reference"></a>
208
+ <a id="use-examples-as-the-implementation-reference"></a>
2927
209
 
2928
- // Highlight code with explicit language
2929
- const highlighted = highlightCode("const x = 1;", "typescript", theme);
210
+ ## Examples and reference
2930
211
 
2931
- // Auto-detect language from file path
2932
- const lang = getLanguageFromPath("/path/to/file.rs"); // "rust"
2933
- const highlighted = highlightCode(code, lang, theme);
2934
- ```
212
+ The checked [extension examples](../examples/extensions/) cover tools, lifecycle events, commands, flags, shortcuts, state, rendering, providers, OAuth, remote execution, and terminal components.
213
+ Start with the smallest example matching your integration point.
2935
214
 
2936
- ## Error Handling
2937
-
2938
- - Extension errors are logged, agent continues
2939
- - `tool_call` errors block the tool (fail-safe)
2940
- - Tool `execute` errors must be signaled by throwing; the thrown error is caught, reported to the LLM with `isError: true`, and execution continues
2941
-
2942
- ## Mode Behavior
2943
-
2944
- | Mode | `ctx.mode` | `ctx.hasUI` | Notes |
2945
- |------|------------|-------------|-------|
2946
- | Interactive | `"tui"` | `true` | Full TUI with terminal rendering |
2947
- | RPC (`--mode rpc`) | `"rpc"` | `true` | Dialogs and notifications via JSON protocol; `custom()` returns `undefined`. See [rpc.md](rpc.md) |
2948
- | JSON (`--mode json`) | `"json"` | `false` | Event stream to stdout; UI methods are no-ops |
2949
- | Print (`-p`) | `"print"` | `false` | Extensions run but can't prompt |
2950
-
2951
- Use `ctx.mode === "tui"` before TUI-specific features (`custom()`, component factories, terminal input). Use `ctx.hasUI` before dialog and notification methods that work in both TUI and RPC modes.
2952
-
2953
- ## Examples Reference
2954
-
2955
- All examples in [examples/extensions/](../examples/extensions/).
2956
-
2957
- | Example | Description | Key APIs |
2958
- |---------|-------------|----------|
2959
- | **Tools** |||
2960
- | `hello.ts` | Minimal tool registration | `registerTool` |
2961
- | `question.ts` | Tool with user interaction | `registerTool`, `ui.select` |
2962
- | `questionnaire.ts` | Multi-step wizard tool | `registerTool`, `ui.custom` |
2963
- | `todo.ts` | Stateful tool with persistence | `registerTool`, `appendEntry`, `renderResult`, session events |
2964
- | `dynamic-tools.ts` | Register tools after startup and during commands | `registerTool`, `session_start`, `registerCommand` |
2965
- | `structured-output.ts` | Final structured-output tool with `terminate: true` | `registerTool`, terminating tool results |
2966
- | `truncated-tool.ts` | Output truncation example | `registerTool`, `truncateHead` |
2967
- | `tool-override.ts` | Override built-in read tool | `registerTool` (same name as built-in) |
2968
- | **Commands** |||
2969
- | `pirate.ts` | Modify system prompt per-turn | `registerCommand`, `before_agent_start` |
2970
- | `summarize.ts` | Conversation summary command | `registerCommand`, `ui.custom` |
2971
- | `handoff.ts` | Cross-provider model handoff | `registerCommand`, `ui.editor`, `ui.custom` |
2972
- | `qna.ts` | Q&A with custom UI | `registerCommand`, `ui.custom`, `setEditorText` |
2973
- | `send-user-message.ts` | Inject user messages | `registerCommand`, `sendUserMessage` |
2974
- | `reload-runtime.ts` | Reload command and LLM tool handoff | `registerCommand`, `ctx.reload()`, `sendUserMessage` |
2975
- | `shutdown-command.ts` | Graceful shutdown command | `registerCommand`, `shutdown()` |
2976
- | **Events & Gates** |||
2977
- | `permission-gate.ts` | Block dangerous commands | `on("tool_call")`, `ui.confirm` |
2978
- | `project-trust.ts` | Decide or defer project trust from a user/global or CLI extension | `on("project_trust")`, trust UI, required trust result |
2979
- | `protected-paths.ts` | Block writes to specific paths | `on("tool_call")` |
2980
- | `confirm-destructive.ts` | Confirm session changes | `on("session_before_switch")`, `on("session_before_fork")` |
2981
- | `dirty-repo-guard.ts` | Warn on dirty git repo | `on("session_before_*")`, `exec` |
2982
- | `input-transform.ts` | Transform user input | `on("input")` |
2983
- | `input-transform-streaming.ts` | Streaming-aware input transform | `on("input")`, `streamingBehavior` |
2984
- | `model-status.ts` | React to model changes | `on("model_select")`, `setStatus` |
2985
- | `provider-payload.ts` | Inspect payloads and provider response headers | `on("before_provider_request")`, `on("after_provider_response")` |
2986
- | `system-prompt-header.ts` | Display system prompt info | `on("agent_start")`, `getSystemPrompt` |
2987
- | `claude-rules.ts` | Load rules from files | `on("session_start")`, `on("before_agent_start")` |
2988
- | `prompt-customizer.ts` | Add context-aware tool guidance using `systemPromptOptions` | `on("before_agent_start")`, `BuildSystemPromptOptions` |
2989
- | `file-trigger.ts` | File watcher triggers messages | `sendMessage` |
2990
- | **Compaction & Sessions** |||
2991
- | `custom-compaction.ts` | Custom compaction summary | `on("session_before_compact")` |
2992
- | `trigger-compact.ts` | Trigger compaction manually | `compact()` |
2993
- | `git-checkpoint.ts` | Git stash on turns | `on("turn_start")`, `on("session_before_fork")`, `exec` |
2994
- | `git-merge-and-resolve.ts` | Fetch, merge, and resolve conflicts | `on("agent_end")`, `exec`, `sendUserMessage` |
2995
- | `auto-commit-on-exit.ts` | Commit on shutdown | `on("session_shutdown")`, `exec` |
2996
- | **UI Components** |||
2997
- | `status-line.ts` | Footer status indicator | `setStatus`, session events |
2998
- | `working-indicator.ts` | Customize the streaming working indicator | `setWorkingIndicator`, `registerCommand` |
2999
- | `github-issue-autocomplete.ts` | Add `#1234` issue completions on top of built-in autocomplete by preloading recent open issues from `gh issue list` | `addAutocompleteProvider`, `on("session_start")`, `exec` |
3000
- | `custom-footer.ts` | Replace footer entirely | `registerCommand`, `setFooter` |
3001
- | `custom-header.ts` | Replace startup header | `on("session_start")`, `setHeader` |
3002
- | `modal-editor.ts` | Vim-style modal editor | `setEditorComponent`, `CustomEditor` |
3003
- | `rainbow-editor.ts` | Custom editor styling | `setEditorComponent` |
3004
- | `widget-placement.ts` | Widget above/below editor | `setWidget` |
3005
- | `overlay-test.ts` | Overlay components | `ui.custom` with overlay options |
3006
- | `overlay-qa-tests.ts` | Comprehensive overlay tests | `ui.custom`, all overlay options |
3007
- | `notify.ts` | Simple notifications | `ui.notify` |
3008
- | `timed-confirm.ts` | Dialogs with timeout | `ui.confirm` with timeout/signal |
3009
- | `mac-system-theme.ts` | Auto-switch theme | `setTheme`, `exec` |
3010
- | **Complex Extensions** |||
3011
- | `plan-mode/` | Full plan mode implementation | All event types, `registerCommand`, `registerShortcut`, `registerFlag`, `setStatus`, `setWidget`, `sendMessage`, `setActiveTools` |
3012
- | `preset.ts` | Saveable presets (model, tools, thinking) | `registerCommand`, `registerShortcut`, `registerFlag`, `setModel`, `setActiveTools`, `setThinkingLevel`, `appendEntry` |
3013
- | `tools.ts` | Toggle tools on/off UI | `registerCommand`, `setActiveTools`, `SettingsList`, session events |
3014
- | **Remote & Sandbox** |||
3015
- | `ssh.ts` | SSH remote execution | `registerFlag`, `on("user_bash")`, `on("before_agent_start")`, tool operations |
3016
- | `interactive-shell.ts` | Persistent shell session | `on("user_bash")` |
3017
- | `sandbox/` | Sandboxed tool execution | Tool operations |
3018
- | `gondolin/` | Route built-in tools and `!` commands into a Gondolin micro-VM | Tool operations, built-in tool overrides, `on("user_bash")` |
3019
- | `subagent/` | Spawn sub-agents | `registerTool`, `exec` |
3020
- | **Games** |||
3021
- | `snake.ts` | Snake game | `registerCommand`, `ui.custom`, keyboard handling |
3022
- | `space-invaders.ts` | Space Invaders game | `registerCommand`, `ui.custom` |
3023
- | `doom-overlay/` | Doom in overlay | `ui.custom` with overlay |
3024
- | **Providers** |||
3025
- | `custom-provider-anthropic/` | Custom Anthropic proxy | `registerProvider` |
3026
- | `custom-provider-gitlab-duo/` | GitLab Duo integration | `registerProvider` with OAuth |
3027
- | **Messages & Communication** |||
3028
- | `message-renderer.ts` | Custom message rendering | `registerMessageRenderer`, `sendMessage` |
3029
- | `entry-renderer.ts` | TUI-only custom entry rendering | `registerEntryRenderer`, `appendEntry` |
3030
- | `event-bus.ts` | Inter-extension events | `knightcode.events` |
3031
- | **Session Metadata** |||
3032
- | `session-name.ts` | Name sessions for selector | `setSessionName`, `getSessionName` |
3033
- | `bookmark.ts` | Bookmark entries for /tree | `setLabel` |
3034
- | **Misc** |||
3035
- | `inline-bash.ts` | Inline bash in tool calls | `on("tool_call")` |
3036
- | `bash-spawn-hook.ts` | Adjust bash command, cwd, and env before execution | `createBashTool`, `spawnHook` |
3037
- | `with-deps/` | Extension with npm dependencies | Package structure with `package.json` |
215
+ Use [Custom Providers](custom-provider.md) for model-service integrations, [Terminal UI](tui.md) for custom components, and [KnightCode Packages](packages.md) to install or distribute extensions with other resources.