@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
@@ -0,0 +1,49 @@
1
+ # How KnightCode Works
2
+
3
+ KnightCode coordinates model requests, tool execution, context assembly, and session storage. A session is KnightCode's record of a conversation, including messages, tool calls and results, model changes, compactions, and other events.
4
+
5
+ Messages and events in a session form a tree. Each path through that tree is a branch. The branch ending at the current entry is the active branch and supplies the history for the next model request.
6
+
7
+ ## Agent loop
8
+
9
+ A submitted message is added to the active branch. KnightCode builds a model request from the system prompt, active branch, available tools, and model settings, then sends it through the selected provider.
10
+
11
+ The provider streams an assistant response, which can contain text and tool calls. KnightCode records the response, executes each tool call, and records the results. That completes one turn. If tool results or queued messages require another model request, KnightCode starts another turn. Otherwise, the run ends.
12
+
13
+ Steering messages enter after the current assistant turn. Follow-up messages enter after the agent has finished its pending work. Aborting stops the current run and returns queued messages to the editor.
14
+
15
+ ## Context
16
+
17
+ The active branch supplies conversation history. KnightCode converts its session entries into model-compatible user, assistant, and tool-result messages.
18
+
19
+ KnightCode builds the system prompt from its base instructions and discovered context files. The request also carries tool definitions and skill descriptions.
20
+
21
+ Full skill instructions are loaded on demand. Extensions can add instructions or transform context.
22
+
23
+ Prompt templates expand editor input before it becomes a user message. Selected files, images, pasted text, and shell output can become message content.
24
+
25
+ ## Sessions
26
+
27
+ Persistent sessions are JSONL files. Each tree entry has an ID and refers to its parent. The current entry identifies the active branch.
28
+
29
+ Continuing from an earlier entry creates another branch in the same file. Forking and cloning copy selected history into a new session file.
30
+
31
+ Model context is reconstructed from the active branch. Compaction inserts a summary entry that replaces older messages in subsequent model requests. The original entries remain in the session tree.
32
+
33
+ ## Interfaces
34
+
35
+ Interactive mode renders session and agent events in the terminal. Print mode runs a prompt and writes the final response. JSON mode writes agent events as JSONL.
36
+
37
+ RPC mode accepts JSONL commands on stdin and writes responses and events to stdout. The TypeScript SDK creates and controls agent sessions in process.
38
+
39
+ All interfaces use the same agent and session mechanisms.
40
+
41
+ ## Extensions and resources
42
+
43
+ Extensions are TypeScript modules loaded into the KnightCode process. Their factory functions register tools, commands, shortcuts, providers, event handlers, renderers, and terminal UI.
44
+
45
+ Skills provide on-demand instructions and supporting files. Prompt templates provide reusable message text. Themes provide terminal colors. KnightCode packages distribute these resources through npm or git.
46
+
47
+ ## Trust and permissions
48
+
49
+ KnightCode resolves project trust before loading project settings and resources. After the trust decision and project-resource loading, KnightCode loads context files. Enabled tools use the operating-system permissions of the KnightCode process. Extensions execute inside that process.
package/bin/docs/index.md CHANGED
@@ -1,84 +1,39 @@
1
- # KnightCode Documentation
1
+ # KnightCode
2
2
 
3
- KnightCode is a minimal terminal coding harness. It is designed to stay small at the core while being extended through TypeScript extensions, skills, prompt templates, themes, and knightcode packages.
3
+ KnightCode is an extensible AI agent that works from your terminal. Give it a goal and a working folder, and it can inspect files, run commands, edit content, and work through multi-step tasks.
4
4
 
5
- ## Quick start
5
+ Use KnightCode for software development, research notes, writing projects, data files, or hobby work. You can use KnightCode as is, prompt it to adapt itself to your workflow, or build other applications powered by KnightCode using the SDK.
6
6
 
7
- Install KnightCode with npm:
7
+ ## Start using KnightCode
8
8
 
9
- ```bash
10
- npm install -g --ignore-scripts @knightcodeai/cli
11
- ```
9
+ New to KnightCode? Follow the [Quickstart](quickstart.md) to install KnightCode, connect a model, and complete your first task.
12
10
 
13
- `--ignore-scripts` disables dependency lifecycle scripts during install. KnightCode does not require install scripts for normal npm installs.
11
+ If KnightCode is already installed, choose what you want to do:
14
12
 
15
- On Linux or macOS, you can also use the installer:
13
+ - [Use KnightCode interactively](usage.md) to add files, run commands, direct ongoing work, and export results.
14
+ - [Choose a model](models.md) or connect a subscription, API key, local model, or compatible endpoint.
15
+ - [Continue or branch a session](sessions.md) to resume work or explore another approach without losing history.
16
+ - [Configure KnightCode](configuration.md) for your preferences, working folders, instructions, and reusable resources.
17
+ - [Understand how KnightCode works](how-knightcode-works.md), including tools, context, sessions, and the agent loop.
16
18
 
17
- ```bash
18
- curl -fsSL https://knightcode.dev/install.sh | sh
19
- ```
19
+ ## Customize KnightCode
20
20
 
21
- To uninstall knightcode itself, use npm for curl and npm installs:
21
+ KnightCode can reuse prompts, load specialized instructions, add executable integrations, change its terminal interface, connect model services, and distribute these resources as packages.
22
+ Use the [Quickstart customization chooser](quickstart.md#choose-how-to-customize-knightcode) to select the smallest mechanism that meets your need.
22
23
 
23
- ```bash
24
- npm uninstall -g @knightcodeai/cli
25
- ```
24
+ ## Automate or embed KnightCode
26
25
 
27
- For pnpm, Yarn, or Bun installs, use the matching global remove command: `pnpm remove -g @knightcodeai/cli`, `yarn global remove @knightcodeai/cli`, or `bun uninstall -g @knightcodeai/cli`.
26
+ - Use [print mode](cli.md#invocation-and-output) for one-off and scripted tasks.
27
+ - Use [JSON event stream mode](json.md) to consume structured events from one run.
28
+ - Use [RPC mode](rpc.md) to control a separate KnightCode process.
29
+ - Use the [TypeScript SDK](sdk.md) to run KnightCode inside an application.
28
30
 
29
- Then run it in a project directory:
31
+ ## Find reference and setup information
30
32
 
31
- ```bash
32
- knightcode
33
- ```
33
+ Use the reference pages to look up [CLI options](cli.md), [settings](settings.md), [provider authentication](providers.md), [keybindings](keybindings.md), and [environment variables](environment-variables.md).
34
34
 
35
- Authenticate with `/login` for subscription providers, or set an API key such as `ANTHROPIC_API_KEY` before starting knightcode.
35
+ For platform-specific help, see [Terminal Setup](terminal-setup.md), [Windows](windows.md), [tmux](tmux.md), [Termux on Android](termux.md), or [Containerization](containerization.md).
36
36
 
37
- For the full first-run flow, see [Quickstart](quickstart.md).
37
+ ## Work safely
38
38
 
39
- ## Start here
40
-
41
- - [Quickstart](quickstart.md) - install, authenticate, and run a first session.
42
- - [Using KnightCode](usage.md) - interactive mode, slash commands, context files, and CLI reference.
43
- - [Providers](providers.md) - subscription and API-key setup for built-in providers.
44
- - [llama.cpp](llama-cpp.md) - run a local router and manage models with `/llama`.
45
- - [Security](security.md) - project trust, sandbox boundaries, and vulnerability reporting.
46
- - [Containerization](containerization.md) - sandbox knightcode with Gondolin, Docker, or OpenShell.
47
- - [Settings](settings.md) - global and project settings.
48
- - [Keybindings](keybindings.md) - default shortcuts and custom keybindings.
49
- - [Sessions](sessions.md) - session management, branching, and tree navigation.
50
- - [Compaction](compaction.md) - context compaction and branch summarization.
51
-
52
- ## Customization
53
-
54
- - [Extensions](extensions.md) - TypeScript modules for tools, commands, events, and custom UI.
55
- - [Skills](skills.md) - Agent Skills for reusable on-demand capabilities.
56
- - [Prompt templates](prompt-templates.md) - reusable prompts that expand from slash commands.
57
- - [Themes](themes.md) - built-in and custom terminal themes.
58
- - [KnightCode packages](packages.md) - bundle and share extensions, skills, prompts, and themes.
59
- - [Custom models](models.md) - add model entries for supported provider APIs.
60
- - [Custom providers](custom-provider.md) - implement custom APIs and OAuth flows.
61
-
62
- ## Programmatic usage
63
-
64
- - [SDK](sdk.md) - embed knightcode in Node.js applications.
65
- - [RPC mode](rpc.md) - integrate over stdin/stdout JSONL.
66
- - [JSON event stream mode](json.md) - print mode with structured events.
67
- - [TUI components](tui.md) - build custom terminal UI for extensions.
68
-
69
- ## Reference
70
-
71
- - [Environment variables](environment-variables.md) - KnightCode process configuration and session metadata available to bash tools.
72
- - [Session format](session-format.md) - JSONL session file format, entry types, and SessionManager API.
73
-
74
- ## Platform setup
75
-
76
- - [Windows](windows.md)
77
- - [Termux on Android](termux.md)
78
- - [tmux](tmux.md)
79
- - [Terminal setup](terminal-setup.md)
80
- - [Shell aliases](shell-aliases.md)
81
-
82
- ## Development
83
-
84
- - [Development](development.md) - local setup, project structure, and debugging.
39
+ KnightCode's tools and extensions run with the permissions of the KnightCode process. Project trust controls which project resources KnightCode loads, but it does not sandbox tool calls. Review [Security](security.md) before using untrusted files, repositories, extensions, or unattended automation.
package/bin/docs/json.md CHANGED
@@ -1,98 +1,226 @@
1
- # JSON Event Stream Mode
1
+ # JSON Event Stream
2
+
3
+ JSON mode emits structured progress for one invocation:
2
4
 
3
5
  ```bash
4
- knightcode --mode json "Your prompt"
6
+ knightcode --mode json "Review this repository"
5
7
  ```
6
8
 
7
- Outputs all session events as JSON lines to stdout. Useful for integrating knightcode into other tools or custom UIs.
9
+ KnightCode writes one session header followed by session events, then exits after the supplied prompts finish. RPC mode emits the same session-event shapes but has no session header because it is a bidirectional, long-lived protocol. See [RPC Mode](rpc.md).
8
10
 
9
- ## Event Types
11
+ This page is the canonical reference for events shared by JSON and RPC mode. Message values use the [shared message types](message-types.md).
10
12
 
11
- Wire events use `JsonAgentSessionEvent`. It matches
12
- [`AgentSessionEvent`](https://github.com/KnightCodeAI/knightcode/blob/main/packages/coding-agent/src/core/agent-session.ts)
13
- except that streaming message updates omit cumulative snapshots:
13
+ ## Framing and process I/O
14
14
 
15
- ```typescript
16
- type WithoutPartial<T> = T extends { partial: unknown } ? Omit<T, "partial"> : T;
15
+ The stream uses strict JSONL framing. Each record is one JSON object terminated by LF (`\n`). Split records only on LF and strip an optional preceding carriage return. Unicode line and paragraph separators are valid inside JSON strings and are not record boundaries.
17
16
 
18
- type JsonAssistantMessageEvent<T> = T extends { type: "toolcall_start"; partial: unknown }
19
- ? WithoutPartial<T> & { id: string; toolName: string }
20
- : WithoutPartial<T>;
17
+ Node.js `readline` is not suitable for this stream because it also recognizes those Unicode separators. Use a byte or UTF-8 stream decoder and split on LF.
21
18
 
22
- type JsonAgentSessionEvent =
23
- | Exclude<AgentSessionEvent, { type: "message_update" }>
24
- | {
25
- type: "message_update";
26
- usage: Usage;
27
- assistantMessageEvent: JsonAssistantMessageEvent<AssistantMessageEvent>;
28
- };
19
+ Read stdout continuously. A reader that stops consuming records can stall KnightCode when the pipe buffer fills. Stdout is reserved for JSONL; diagnostics and application logging go to stderr.
20
+
21
+ ## Session header
22
+
23
+ The first JSON-mode record is the current [session header](session-format.md#sessionheader):
24
+
25
+ ```json
26
+ {"type":"session","version":3,"id":"uuid","timestamp":"2024-12-03T14:00:00.000Z","cwd":"/path"}
29
27
  ```
30
28
 
31
- `queue_update` emits the full pending steering and follow-up queues whenever they change. `compaction_start` and `compaction_end` cover both manual and automatic compaction.
29
+ RPC mode does not emit this record. Use [`get_state`](rpc-commands.md#get_state) for its current session ID and file.
32
30
 
33
- Other base events come from
34
- [`AgentEvent`](https://github.com/KnightCodeAI/knightcode/blob/main/packages/agent/src/types.ts):
31
+ ## Event sequence
35
32
 
36
- ```typescript
37
- type AgentEvent =
38
- // Agent lifecycle
39
- | { type: "agent_start" }
40
- | { type: "agent_end"; messages: AgentMessage[] }
41
- // Turn lifecycle
42
- | { type: "turn_start" }
43
- | { type: "turn_end"; message: AgentMessage; toolResults: ToolResultMessage[] }
44
- // Message lifecycle
45
- | { type: "message_start"; message: AgentMessage }
46
- | { type: "message_update"; message: AgentMessage; assistantMessageEvent: AssistantMessageEvent }
47
- | { type: "message_end"; message: AgentMessage }
48
- // Tool execution
49
- | { type: "tool_execution_start"; toolCallId: string; toolName: string; args: any }
50
- | { type: "tool_execution_update"; toolCallId: string; toolName: string; args: any; partialResult: any }
51
- | { type: "tool_execution_end"; toolCallId: string; toolName: string; result: any; isError: boolean };
33
+ A basic run produces records like these:
34
+
35
+ ```json
36
+ {"type":"agent_start"}
37
+ {"type":"turn_start"}
38
+ {"type":"message_start","message":{"role":"user","content":"Review this repository","timestamp":1733234401000}}
39
+ {"type":"message_end","message":{"role":"user","content":"Review this repository","timestamp":1733234401000}}
40
+ {"type":"message_start","message":{"role":"assistant","content":[],"stopReason":"pending","...":"..."}}
41
+ {"type":"message_update","usage":{"...":"..."},"assistantMessageEvent":{"type":"text_delta","contentIndex":0,"delta":"Hello"}}
42
+ {"type":"message_end","message":{"role":"assistant","...":"..."}}
43
+ {"type":"turn_end","message":{"role":"assistant","...":"..."},"toolResults":[]}
44
+ {"type":"agent_end","messages":[{"...":"..."}],"willRetry":false}
45
+ {"type":"agent_settled"}
52
46
  ```
53
47
 
54
- ## Message Types
48
+ `agent_end` closes one low-level agent run. Automatic retry, overflow recovery, compaction retry, steering, or follow-up work can still continue. `agent_settled` means KnightCode has no remaining automatic work for that session-level run.
49
+
50
+ ## Agent and turn events
55
51
 
56
- Base messages from [`packages/ai/src/types.ts`](https://github.com/KnightCodeAI/knightcode/blob/main/packages/ai/src/types.ts#L134):
57
- - `UserMessage` (line 134)
58
- - `AssistantMessage` (line 140)
59
- - `ToolResultMessage` (line 152)
52
+ | Event | Fields | Meaning |
53
+ |---|---|---|
54
+ | `agent_start` | None | A low-level agent run started. |
55
+ | `agent_end` | `messages`, `willRetry` | That low-level run ended. `messages` contains messages generated by the run. |
56
+ | `agent_settled` | None | KnightCode will not continue automatically through retries, compaction recovery, or queued messages. |
57
+ | `turn_start` | None | One assistant turn started. |
58
+ | `turn_end` | `message`, `toolResults` | One assistant response and its resulting tool calls finished. |
60
59
 
61
- Extended messages from [`packages/coding-agent/src/core/messages.ts`](https://github.com/KnightCodeAI/knightcode/blob/main/packages/coding-agent/src/core/messages.ts#L29):
62
- - `BashExecutionMessage` (line 29)
63
- - `CustomMessage` (line 46)
64
- - `BranchSummaryMessage` (line 55)
65
- - `CompactionSummaryMessage` (line 62)
60
+ A turn is one assistant response plus any tool calls and tool results produced by that response.
66
61
 
67
- ## Output Format
62
+ ## Message events
68
63
 
69
- Each line is a JSON object. The first line is the session header:
64
+ | Event | Fields | Meaning |
65
+ |---|---|---|
66
+ | `message_start` | `message` | A message started. |
67
+ | `message_update` | `usage`, `assistantMessageEvent` | An assistant message emitted a content-block update. |
68
+ | `message_end` | `message` | A message completed. This is the authoritative final message. |
69
+
70
+ ### Reconstruct streaming messages
71
+
72
+ Wire `message_update` records are delta-only. They omit the SDK event's cumulative `message` field and every `assistantMessageEvent.partial` snapshot so stream size remains linear.
73
+
74
+ The nested event is one of:
75
+
76
+ | Type | Fields in addition to `type` | Meaning |
77
+ |---|---|---|
78
+ | `start` | None | The provider stream started; its cumulative `partial` field is removed on the wire. |
79
+ | `text_start` | `contentIndex` | A text block started. |
80
+ | `text_delta` | `contentIndex`, `delta` | Append text to the block. |
81
+ | `text_end` | `contentIndex`, `content` | The text block ended with authoritative content. |
82
+ | `thinking_start` | `contentIndex` | A thinking block started. |
83
+ | `thinking_delta` | `contentIndex`, `delta` | Append thinking text to the block. |
84
+ | `thinking_end` | `contentIndex`, `content` | The thinking block ended with authoritative content. |
85
+ | `toolcall_start` | `contentIndex`, `id`, `toolName` | A tool-call block started. |
86
+ | `toolcall_delta` | `contentIndex`, `delta` | Append serialized argument data. |
87
+ | `toolcall_end` | `contentIndex`, `toolCall` | The tool call ended with the complete `ToolCall`. |
88
+ | `done` | `reason`, `message` | The provider stream completed successfully. |
89
+ | `error` | `reason`, `error` | The provider stream ended with an error or abort message. |
90
+
91
+ The normal agent loop translates provider-level `start`, `done`, and `error` into `message_start` and `message_end` session events rather than emitting them as `message_update`. They remain admitted by the exported `JsonAgentSessionEvent` transformation for callers that construct a matching session event.
92
+
93
+ Use `contentIndex` to identify the content block. Buffer `delta` fields for a live display, but replace reconstructed data with the completed content in `text_end`, `thinking_end`, or `toolcall_end`. Replace the whole partial message with `message_end.message` when it arrives.
94
+
95
+ The top-level `usage` is the latest cumulative provider-reported usage for the assistant response. It can remain zero until completion when a provider does not report usage while streaming.
70
96
 
71
97
  ```json
72
- {"type":"session","version":3,"id":"uuid","timestamp":"...","cwd":"/path"}
98
+ {"type":"message_update","usage":{"input":100,"output":1,"cacheRead":0,"cacheWrite":0,"totalTokens":101,"cost":{"input":0,"output":0,"cacheRead":0,"cacheWrite":0,"total":0}},"assistantMessageEvent":{"type":"text_delta","contentIndex":0,"delta":"Hello "}}
73
99
  ```
74
100
 
75
- Followed by events as they occur:
101
+ ## Tool execution events
102
+
103
+ | Event | Fields | Meaning |
104
+ |---|---|---|
105
+ | `tool_execution_start` | `toolCallId`, `toolName`, `args` | Tool execution started. |
106
+ | `tool_execution_update` | `toolCallId`, `toolName`, `args`, `partialResult` | The tool reported a partial result. |
107
+ | `tool_execution_end` | `toolCallId`, `toolName`, `result`, `isError` | Tool execution finished. |
108
+
109
+ Use `toolCallId` to correlate the lifecycle. `partialResult` is the latest partial result supplied by the tool. Whether it replaces or extends an earlier update depends on that tool's result contract.
76
110
 
77
111
  ```json
78
- {"type":"agent_start"}
79
- {"type":"turn_start"}
80
- {"type":"message_start","message":{"role":"assistant","content":[],...}}
81
- {"type":"message_update","usage":{...},"assistantMessageEvent":{"type":"text_delta","contentIndex":0,"delta":"Hello"}}
82
- {"type":"message_end","message":{...}}
83
- {"type":"turn_end","message":{...},"toolResults":[]}
84
- {"type":"agent_end","messages":[...]}
112
+ {"type":"tool_execution_start","toolCallId":"call_abc123","toolName":"bash","args":{"command":"ls -la"}}
113
+ {"type":"tool_execution_update","toolCallId":"call_abc123","toolName":"bash","args":{"command":"ls -la"},"partialResult":{"content":[{"type":"text","text":"partial output"}],"details":{}}}
114
+ {"type":"tool_execution_end","toolCallId":"call_abc123","toolName":"bash","result":{"content":[{"type":"text","text":"complete output"}],"details":{}},"isError":false}
85
115
  ```
86
116
 
87
- `message_update` records are delta-only. They omit both the cumulative `message` field and
88
- `assistantMessageEvent.partial` to keep stream size linear. The top-level `usage` field contains
89
- the latest cumulative provider-reported usage and may remain zero when a provider only reports
90
- usage at completion. Use `contentIndex` and `delta` to assemble live text, thinking, or tool-call
91
- arguments if needed. A `toolcall_start` event also includes the constant-sized `id` and `toolName`
92
- fields. `message_end` contains the final authoritative message.
117
+ ## Queue and state events
118
+
119
+ | Event | Fields | Meaning |
120
+ |---|---|---|
121
+ | `queue_update` | `steering`, `followUp` | The pending steering or follow-up queue changed. Both fields contain the complete current queue. |
122
+ | `entry_appended` | `entry` | An extension appended a custom session entry through `knightcode.appendEntry()`. |
123
+ | `session_info_changed` | `name` | The session display name changed. An absent `name` means it was cleared. |
124
+ | `thinking_level_changed` | `level` | The active thinking level changed. |
125
+
126
+ The `entry` value uses a persisted [session entry type](session-format.md#entry-types).
127
+
128
+ ## Compaction events
129
+
130
+ `compaction_start` reports why compaction began:
131
+
132
+ ```json
133
+ {"type":"compaction_start","reason":"threshold"}
134
+ ```
135
+
136
+ `reason` is `"manual"`, `"threshold"`, or `"overflow"`.
137
+
138
+ `compaction_end` contains the result when compaction succeeds:
139
+
140
+ ```json
141
+ {
142
+ "type": "compaction_end",
143
+ "reason": "threshold",
144
+ "result": {
145
+ "summary": "Summary of conversation...",
146
+ "firstKeptEntryId": "abc123",
147
+ "tokensBefore": 150000,
148
+ "estimatedTokensAfter": 32000,
149
+ "usage": {"...": "..."},
150
+ "details": {}
151
+ },
152
+ "aborted": false,
153
+ "willRetry": false
154
+ }
155
+ ```
156
+
157
+ If compaction was aborted, `result` is absent and `aborted` is true. If it failed, `result` is absent, `aborted` is false, and `errorMessage` describes the failure. Successful overflow recovery sets `willRetry` to true before KnightCode retries the prompt.
158
+
159
+ See [Compaction and Branch Summaries](compaction.md) for result semantics.
160
+
161
+ ## Retry events
162
+
163
+ Assistant-turn retry emits:
164
+
165
+ ```json
166
+ {"type":"auto_retry_start","attempt":1,"maxAttempts":3,"delayMs":2000,"errorMessage":"529 overloaded"}
167
+ {"type":"auto_retry_end","success":true,"attempt":2}
168
+ ```
169
+
170
+ On final failure, `auto_retry_end` has `success: false` and a `finalError` string.
171
+
172
+ Compaction and branch-summary retry emit:
173
+
174
+ ```json
175
+ {"type":"summarization_retry_scheduled","attempt":1,"maxAttempts":3,"delayMs":2000,"errorMessage":"terminated"}
176
+ {"type":"summarization_retry_attempt_start","source":"compaction","reason":"threshold"}
177
+ {"type":"summarization_retry_finished"}
178
+ ```
179
+
180
+ For a branch summary, `source` is `"branchSummary"` and `reason` is absent. The `reason` on a compaction retry is `"manual"`, `"threshold"`, or `"overflow"`.
181
+
182
+ ## RPC-only events
183
+
184
+ A direct RPC [`bash`](rpc-commands.md#bash) command emits one `bash_execution_update` for each output chunk. Its optional `id` matches the command ID. The final command response can contain truncated output, but these events stream all output:
185
+
186
+ ```json
187
+ {"type":"bash_execution_update","id":"req-1","delta":"total 48\n"}
188
+ ```
189
+
190
+ RPC also adds `extension_error` when an extension handler throws:
191
+
192
+ ```json
193
+ {"type":"extension_error","extensionPath":"/path/to/extension.ts","event":"tool_call","error":"Error message"}
194
+ ```
195
+
196
+ Extension UI records are a separate RPC subprotocol, not `AgentSessionEvent` values. See [RPC Extension UI](rpc-extension-ui.md).
197
+
198
+ ## TypeScript types
199
+
200
+ The SDK's `AgentSessionEvent` contains cumulative streaming snapshots for in-process consumers. JSON and RPC transform only `message_update`:
201
+
202
+ ```typescript
203
+ type WithoutPartial<T> = T extends { partial: unknown } ? Omit<T, "partial"> : T;
204
+
205
+ type JsonAssistantMessageEvent<T> = T extends { type: "toolcall_start"; partial: unknown }
206
+ ? WithoutPartial<T> & { id: string; toolName: string }
207
+ : WithoutPartial<T>;
208
+
209
+ type JsonAgentSessionEvent =
210
+ | Exclude<AgentSessionEvent, { type: "message_update" }>
211
+ | {
212
+ type: "message_update";
213
+ usage: Usage;
214
+ assistantMessageEvent: JsonAssistantMessageEvent<AssistantMessageEvent>;
215
+ };
216
+ ```
217
+
218
+ Use the exported `JsonAgentSessionEvent` type from `@knightcodeai/cli`. Its implementation is in [`json-event.ts`](https://github.com/KnightCodeAI/knightcode/blob/main/packages/cli/src/modes/json-event.ts).
93
219
 
94
220
  ## Example
95
221
 
222
+ Print completed messages from a one-shot run:
223
+
96
224
  ```bash
97
225
  knightcode --mode json "List files" 2>/dev/null | jq -c 'select(.type == "message_end")'
98
226
  ```