@knightcodeai/cli 0.17.4 → 0.18.0

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 (281) hide show
  1. package/CHANGELOG.md +1293 -0
  2. package/README.md +2 -2
  3. package/dist/bundle/chunks/anthropic-messages-A2IH2IY3.js +6 -0
  4. package/dist/bundle/chunks/anthropic.js +101 -0
  5. package/dist/bundle/chunks/azure-openai-responses-XZILQZOG.js +2 -0
  6. package/dist/bundle/chunks/bedrock-converse-stream.js +89 -0
  7. package/dist/bundle/chunks/chunk-4CRI7BMY.js +2 -0
  8. package/dist/bundle/chunks/chunk-57BPR4HF.js +2 -0
  9. package/dist/bundle/chunks/chunk-A5LJINMT.js +2 -0
  10. package/dist/bundle/chunks/chunk-AANBXVWQ.js +2 -0
  11. package/dist/bundle/chunks/chunk-ACHHEROF.js +7 -0
  12. package/dist/bundle/chunks/chunk-AFR2OW6S.js +108 -0
  13. package/dist/bundle/chunks/chunk-AHB7JV5B.js +2 -0
  14. package/dist/bundle/chunks/chunk-B2FT7RH5.js +2 -0
  15. package/dist/bundle/chunks/chunk-BRKUE2MD.js +2 -0
  16. package/dist/bundle/chunks/chunk-DKOURXGU.js +2 -0
  17. package/dist/bundle/chunks/chunk-DVFCXHT4.js +2 -0
  18. package/dist/bundle/chunks/chunk-EPYT326Y.js +30 -0
  19. package/dist/bundle/chunks/chunk-ETOMYYZC.js +2 -0
  20. package/dist/bundle/chunks/chunk-FA32X2UJ.js +7 -0
  21. package/dist/bundle/chunks/chunk-FHM6KUY3.js +44 -0
  22. package/dist/bundle/chunks/chunk-FO7CEQB3.js +11 -0
  23. package/dist/bundle/chunks/chunk-GHVXUCGU.js +130 -0
  24. package/dist/bundle/chunks/chunk-HHWP56PR.js +2 -0
  25. package/dist/bundle/chunks/chunk-HSL72VZI.js +2 -0
  26. package/dist/bundle/chunks/chunk-HUQB436V.js +2 -0
  27. package/dist/bundle/chunks/chunk-HWXGL4YB.js +2 -0
  28. package/dist/bundle/chunks/chunk-KQKUEQJA.js +6 -0
  29. package/dist/bundle/chunks/chunk-M5GCRGV6.js +1333 -0
  30. package/dist/bundle/chunks/chunk-MB4QRS7Y.js +9 -0
  31. package/dist/bundle/chunks/chunk-MXIWLMNT.js +8 -0
  32. package/dist/bundle/chunks/chunk-N6VDWLND.js +2 -0
  33. package/dist/bundle/chunks/chunk-NCIBB66G.js +2 -0
  34. package/dist/bundle/chunks/chunk-NDQ5OW6U.js +2 -0
  35. package/dist/bundle/chunks/chunk-NNCIIYD6.js +2 -0
  36. package/dist/bundle/chunks/chunk-O6JSP6YG.js +6 -0
  37. package/dist/bundle/chunks/chunk-OFST7FDG.js +2 -0
  38. package/dist/bundle/chunks/chunk-SPAUY3RD.js +12 -0
  39. package/dist/bundle/chunks/chunk-U5XE4RWR.js +2 -0
  40. package/dist/bundle/chunks/chunk-UZWP3NHW.js +2 -0
  41. package/dist/bundle/chunks/chunk-V5ANFNKF.js +11 -0
  42. package/dist/bundle/chunks/chunk-VJJ6J35N.js +20 -0
  43. package/dist/bundle/chunks/chunk-XIRAUXOE.js +58 -0
  44. package/dist/bundle/chunks/chunk-ZW7FVRHT.js +31 -0
  45. package/dist/bundle/chunks/cli-6ZTWO6GL.js +51 -0
  46. package/dist/bundle/chunks/cloudflare-workers-ai-system-one-6E2UM7IG.js +2 -0
  47. package/dist/bundle/chunks/codemode-worker.js +478 -0
  48. package/dist/bundle/chunks/dist-DKI7Q6GY.js +13 -0
  49. package/dist/bundle/chunks/easter-egg-3d-FDCGDUF3.js +2 -0
  50. package/dist/bundle/chunks/execute-VSDU5VSN.js +499 -0
  51. package/dist/bundle/chunks/github-copilot.js +2 -0
  52. package/dist/bundle/chunks/google-generative-ai-CSWR3ORZ.js +2 -0
  53. package/dist/bundle/chunks/google-vertex-QIDRFOFB.js +2 -0
  54. package/dist/bundle/chunks/image-resize-worker.js +2 -0
  55. package/dist/bundle/chunks/jiti-loader-BXVX3Y2R.js +21 -0
  56. package/dist/bundle/chunks/jiti-static-loader-NNBCFAO5.js +2 -0
  57. package/dist/bundle/chunks/kimi-coding.js +2 -0
  58. package/dist/bundle/chunks/knightcode-messages-3GNOTMSI.js +8 -0
  59. package/dist/bundle/chunks/lib-IHWMWJDR.js +9 -0
  60. package/dist/bundle/chunks/llama-cpp-classify-HRPRKOZA.js +22 -0
  61. package/dist/bundle/chunks/meta.js +2 -0
  62. package/dist/bundle/chunks/mistral-conversations-46TK5OBA.js +5 -0
  63. package/dist/bundle/chunks/multipart-parser-VTTMF2EO.js +3 -0
  64. package/dist/bundle/chunks/node-7S3GFMOZ.js +16 -0
  65. package/dist/bundle/chunks/node-MAEICQNS.js +2 -0
  66. package/dist/bundle/chunks/openai-chatgpt.js +101 -0
  67. package/dist/bundle/chunks/openai-codex-responses-IT7VEKUU.js +10 -0
  68. package/dist/bundle/chunks/openai-codex.js +101 -0
  69. package/dist/bundle/chunks/openai-completions-LOKIW33V.js +7 -0
  70. package/dist/bundle/chunks/openai-decisions-4F3LWHMG.js +5 -0
  71. package/dist/bundle/chunks/openai-responses-OK36GJXP.js +3 -0
  72. package/dist/bundle/chunks/openrouter-images-ZI7LLZ4Y.js +2 -0
  73. package/dist/bundle/chunks/openrouter.js +101 -0
  74. package/dist/bundle/chunks/radius.js +101 -0
  75. package/dist/bundle/chunks/runtime-RMPIV5AR.js +2 -0
  76. package/dist/bundle/chunks/src-ETRMT73D.js +4 -0
  77. package/dist/bundle/chunks/typesafe-system-one-J2CJBWEH.js +2 -0
  78. package/dist/bundle/chunks/virtual-modules-EGJP3AJA.js +2 -0
  79. package/dist/bundle/chunks/xai.js +2 -0
  80. package/dist/bundle/cli-runtime.js +3 -0
  81. package/dist/bundle/cli.js +5 -0
  82. package/dist/bundle/native/darwin/prebuilds/darwin-arm64/darwin-platform.node +0 -0
  83. package/dist/bundle/native/darwin/prebuilds/darwin-x64/darwin-platform.node +0 -0
  84. package/dist/bundle/native/linux/prebuilds/linux-arm64/linux-platform-x11.node +0 -0
  85. package/dist/bundle/native/linux/prebuilds/linux-x64/linux-platform-x11.node +0 -0
  86. package/dist/bundle/native/win32/prebuilds/win32-arm64/win32-platform.node +0 -0
  87. package/dist/bundle/native/win32/prebuilds/win32-x64/win32-platform.node +0 -0
  88. package/dist/core/export-html/template.css +1015 -0
  89. package/dist/core/export-html/template.html +55 -0
  90. package/dist/core/export-html/template.js +1929 -0
  91. package/dist/core/export-html/vendor/highlight.min.js +1213 -0
  92. package/dist/core/export-html/vendor/marked.min.js +78 -0
  93. package/dist/modes/interactive/theme/dark.json +74 -0
  94. package/dist/modes/interactive/theme/light.json +74 -0
  95. package/dist/modes/interactive/theme/system-theme.ts +579 -0
  96. package/dist/modes/interactive/theme/theme-controller.ts +253 -0
  97. package/dist/modes/interactive/theme/theme-schema.ts +145 -0
  98. package/dist/modes/interactive/theme/theme-tokens.ts +145 -0
  99. package/dist/modes/interactive/theme/theme.ts +1076 -0
  100. package/docs/app-server.md +479 -0
  101. package/docs/app-server.schema.json +8128 -0
  102. package/docs/cli-integration.md +106 -0
  103. package/docs/cli.md +393 -0
  104. package/docs/codemode.md +230 -0
  105. package/docs/compaction.md +463 -0
  106. package/docs/configuration.md +48 -0
  107. package/docs/containerization.md +143 -0
  108. package/docs/custom-provider.md +173 -0
  109. package/docs/desktop.md +73 -0
  110. package/docs/docs.json +236 -0
  111. package/docs/environment-variables.md +138 -0
  112. package/docs/extensions.md +314 -0
  113. package/docs/how-knightcode-works.md +49 -0
  114. package/docs/images/doom-extension.png +0 -0
  115. package/docs/images/interactive-mode.png +0 -0
  116. package/docs/images/tree-view.png +0 -0
  117. package/docs/index.md +39 -0
  118. package/docs/json.md +226 -0
  119. package/docs/keybindings.md +197 -0
  120. package/docs/llama-cpp.md +121 -0
  121. package/docs/mcp.md +272 -0
  122. package/docs/message-types.md +279 -0
  123. package/docs/models-configuration.md +187 -0
  124. package/docs/models.md +221 -0
  125. package/docs/nvidia-rtx-llama-cpp.md +96 -0
  126. package/docs/packages.md +129 -0
  127. package/docs/plan-mode.md +121 -0
  128. package/docs/prompt-templates.md +59 -0
  129. package/docs/providers.md +282 -0
  130. package/docs/quickstart.md +128 -0
  131. package/docs/remote.md +87 -0
  132. package/docs/rpc-commands.md +860 -0
  133. package/docs/rpc-extension-ui.md +214 -0
  134. package/docs/rpc.md +193 -0
  135. package/docs/sdk.md +197 -0
  136. package/docs/security.md +99 -0
  137. package/docs/session-format.md +358 -0
  138. package/docs/sessions.md +135 -0
  139. package/docs/settings.md +220 -0
  140. package/docs/shell-aliases.md +93 -0
  141. package/docs/skills.md +93 -0
  142. package/docs/slash-commands.md +78 -0
  143. package/docs/terminal-setup.md +242 -0
  144. package/docs/termux.md +117 -0
  145. package/docs/themes.md +140 -0
  146. package/docs/tmux.md +55 -0
  147. package/docs/tui.md +125 -0
  148. package/docs/usage.md +167 -0
  149. package/docs/virtual-models.md +114 -0
  150. package/docs/windows.md +67 -0
  151. package/examples/README.md +36 -0
  152. package/examples/extensions/README.md +214 -0
  153. package/examples/extensions/auto-commit-on-exit.ts +55 -0
  154. package/examples/extensions/bash-spawn-hook.ts +30 -0
  155. package/examples/extensions/bookmark.ts +50 -0
  156. package/examples/extensions/border-status-editor.ts +151 -0
  157. package/examples/extensions/built-in-tool-renderer.ts +225 -0
  158. package/examples/extensions/claude-rules.ts +89 -0
  159. package/examples/extensions/commands.ts +72 -0
  160. package/examples/extensions/confirm-destructive.ts +60 -0
  161. package/examples/extensions/custom-compaction.ts +118 -0
  162. package/examples/extensions/custom-footer.ts +66 -0
  163. package/examples/extensions/custom-header.ts +73 -0
  164. package/examples/extensions/custom-provider-anthropic/index.ts +617 -0
  165. package/examples/extensions/custom-provider-anthropic/package-lock.json +24 -0
  166. package/examples/extensions/custom-provider-anthropic/package.json +19 -0
  167. package/examples/extensions/custom-provider-gitlab-duo/index.ts +399 -0
  168. package/examples/extensions/custom-provider-gitlab-duo/package.json +16 -0
  169. package/examples/extensions/custom-provider-gitlab-duo/test.ts +82 -0
  170. package/examples/extensions/debug-provider.ts +90 -0
  171. package/examples/extensions/dirty-repo-guard.ts +56 -0
  172. package/examples/extensions/doom-overlay/README.md +46 -0
  173. package/examples/extensions/doom-overlay/doom/build.sh +152 -0
  174. package/examples/extensions/doom-overlay/doom/doomgeneric_knightcode.c +72 -0
  175. package/examples/extensions/doom-overlay/doom-component.ts +132 -0
  176. package/examples/extensions/doom-overlay/doom-engine.ts +173 -0
  177. package/examples/extensions/doom-overlay/doom-keys.ts +104 -0
  178. package/examples/extensions/doom-overlay/index.ts +74 -0
  179. package/examples/extensions/doom-overlay/wad-finder.ts +55 -0
  180. package/examples/extensions/dynamic-resources/SKILL.md +8 -0
  181. package/examples/extensions/dynamic-resources/dynamic.json +75 -0
  182. package/examples/extensions/dynamic-resources/dynamic.md +5 -0
  183. package/examples/extensions/dynamic-resources/index.ts +15 -0
  184. package/examples/extensions/dynamic-tools.ts +74 -0
  185. package/examples/extensions/entry-renderer.ts +41 -0
  186. package/examples/extensions/event-bus.ts +43 -0
  187. package/examples/extensions/file-trigger.ts +41 -0
  188. package/examples/extensions/git-checkpoint.ts +53 -0
  189. package/examples/extensions/git-merge-and-resolve.ts +115 -0
  190. package/examples/extensions/github-issue-autocomplete.ts +185 -0
  191. package/examples/extensions/gondolin/index.ts +531 -0
  192. package/examples/extensions/gondolin/package-lock.json +185 -0
  193. package/examples/extensions/gondolin/package.json +19 -0
  194. package/examples/extensions/handoff.ts +190 -0
  195. package/examples/extensions/hello.ts +26 -0
  196. package/examples/extensions/hidden-thinking-label.ts +53 -0
  197. package/examples/extensions/inline-bash.ts +94 -0
  198. package/examples/extensions/input-transform-streaming.ts +39 -0
  199. package/examples/extensions/input-transform.ts +43 -0
  200. package/examples/extensions/interactive-shell.ts +196 -0
  201. package/examples/extensions/jev-router.ts +113 -0
  202. package/examples/extensions/mac-system-theme.ts +47 -0
  203. package/examples/extensions/message-renderer.ts +59 -0
  204. package/examples/extensions/minimal-mode.ts +353 -0
  205. package/examples/extensions/modal-editor.ts +85 -0
  206. package/examples/extensions/model-status.ts +31 -0
  207. package/examples/extensions/notify.ts +57 -0
  208. package/examples/extensions/overlay-qa-tests.ts +1450 -0
  209. package/examples/extensions/overlay-test.ts +153 -0
  210. package/examples/extensions/permission-gate.ts +34 -0
  211. package/examples/extensions/pirate.ts +47 -0
  212. package/examples/extensions/plan-mode/README.md +66 -0
  213. package/examples/extensions/plan-mode/index.ts +387 -0
  214. package/examples/extensions/plan-mode/utils.ts +168 -0
  215. package/examples/extensions/preset.ts +436 -0
  216. package/examples/extensions/project-trust.ts +64 -0
  217. package/examples/extensions/prompt-customizer.ts +49 -0
  218. package/examples/extensions/protected-paths.ts +30 -0
  219. package/examples/extensions/provider-payload.ts +18 -0
  220. package/examples/extensions/qna.ts +118 -0
  221. package/examples/extensions/question.ts +278 -0
  222. package/examples/extensions/questionnaire.ts +440 -0
  223. package/examples/extensions/rainbow-editor.ts +88 -0
  224. package/examples/extensions/reload-runtime.ts +37 -0
  225. package/examples/extensions/rpc-demo.ts +118 -0
  226. package/examples/extensions/sandbox/index.ts +321 -0
  227. package/examples/extensions/sandbox/package-lock.json +92 -0
  228. package/examples/extensions/sandbox/package.json +19 -0
  229. package/examples/extensions/send-user-message.ts +97 -0
  230. package/examples/extensions/session-name.ts +27 -0
  231. package/examples/extensions/shutdown-command.ts +63 -0
  232. package/examples/extensions/snake.ts +343 -0
  233. package/examples/extensions/space-invaders.ts +560 -0
  234. package/examples/extensions/ssh.ts +220 -0
  235. package/examples/extensions/status-line.ts +32 -0
  236. package/examples/extensions/structured-output.ts +65 -0
  237. package/examples/extensions/subagent/README.md +177 -0
  238. package/examples/extensions/subagent/agents/planner.md +37 -0
  239. package/examples/extensions/subagent/agents/reviewer.md +35 -0
  240. package/examples/extensions/subagent/agents/scout.md +50 -0
  241. package/examples/extensions/subagent/agents/worker.md +24 -0
  242. package/examples/extensions/subagent/agents.ts +157 -0
  243. package/examples/extensions/subagent/index.ts +1010 -0
  244. package/examples/extensions/subagent/prompts/implement-and-review.md +10 -0
  245. package/examples/extensions/subagent/prompts/implement.md +10 -0
  246. package/examples/extensions/subagent/prompts/scout-and-plan.md +9 -0
  247. package/examples/extensions/summarize.ts +199 -0
  248. package/examples/extensions/system-prompt-header.ts +17 -0
  249. package/examples/extensions/tic-tac-toe.ts +1004 -0
  250. package/examples/extensions/timed-confirm.ts +70 -0
  251. package/examples/extensions/titlebar-spinner.ts +58 -0
  252. package/examples/extensions/todo.ts +294 -0
  253. package/examples/extensions/tool-override.ts +144 -0
  254. package/examples/extensions/tools.ts +146 -0
  255. package/examples/extensions/trigger-compact.ts +50 -0
  256. package/examples/extensions/truncated-tool.ts +195 -0
  257. package/examples/extensions/widget-placement.ts +9 -0
  258. package/examples/extensions/with-deps/index.ts +32 -0
  259. package/examples/extensions/with-deps/package-lock.json +31 -0
  260. package/examples/extensions/with-deps/package.json +22 -0
  261. package/examples/extensions/working-indicator.ts +121 -0
  262. package/examples/extensions/working-message-test.ts +25 -0
  263. package/examples/rpc-client.ts +35 -0
  264. package/examples/rpc-extension-ui.ts +661 -0
  265. package/examples/sdk/01-minimal.ts +26 -0
  266. package/examples/sdk/02-custom-model.ts +49 -0
  267. package/examples/sdk/03-custom-prompt.ts +70 -0
  268. package/examples/sdk/04-skills.ts +55 -0
  269. package/examples/sdk/05-tools.ts +48 -0
  270. package/examples/sdk/06-extensions.ts +94 -0
  271. package/examples/sdk/07-context-files.ts +42 -0
  272. package/examples/sdk/08-prompt-templates.ts +51 -0
  273. package/examples/sdk/09-api-keys-and-oauth.ts +34 -0
  274. package/examples/sdk/10-settings.ts +53 -0
  275. package/examples/sdk/11-sessions.ts +52 -0
  276. package/examples/sdk/12-full-control.ts +74 -0
  277. package/examples/sdk/13-session-runtime.ts +67 -0
  278. package/examples/sdk/14-codemode-mcp.ts +61 -0
  279. package/examples/sdk/README.md +141 -0
  280. package/package.json +15 -15
  281. package/bin/knightcode +0 -62
@@ -0,0 +1,463 @@
1
+ # Compaction Reference
2
+
3
+ This reference describes automatic compaction, branch summarization, persisted entries, and extension hooks. For the user workflow, see [Sessions and Context](sessions.md#manage-conversation-context).
4
+
5
+ **Source files** ([knightcode](https://github.com/KnightCodeAI/knightcode)):
6
+ - [`packages/cli/src/core/compaction/compaction.ts`](https://github.com/KnightCodeAI/knightcode/blob/main/packages/cli/src/core/compaction/compaction.ts) - Auto-compaction logic
7
+ - [`packages/cli/src/core/compaction/branch-summarization.ts`](https://github.com/KnightCodeAI/knightcode/blob/main/packages/cli/src/core/compaction/branch-summarization.ts) - Branch summarization
8
+ - [`packages/cli/src/core/compaction/utils.ts`](https://github.com/KnightCodeAI/knightcode/blob/main/packages/cli/src/core/compaction/utils.ts) - Shared utilities (file tracking, serialization)
9
+ - [`packages/cli/src/core/session-manager.ts`](https://github.com/KnightCodeAI/knightcode/blob/main/packages/cli/src/core/session-manager.ts) - Entry types (`CompactionEntry`, `BranchSummaryEntry`)
10
+ - [`packages/cli/src/core/extensions/types.ts`](https://github.com/KnightCodeAI/knightcode/blob/main/packages/cli/src/core/extensions/types.ts) - Extension event types
11
+
12
+ For TypeScript definitions in your project, inspect `node_modules/@knightcodeai/cli/dist/`.
13
+
14
+ ## Overview
15
+
16
+ KnightCode has two summarization mechanisms:
17
+
18
+ | Mechanism | Trigger | Purpose |
19
+ |-----------|---------|---------|
20
+ | Compaction | Context exceeds threshold, or `/compact` | Summarize old messages to free up context |
21
+ | Branch summarization | `/tree` navigation | Preserve context when switching branches |
22
+
23
+ Both use closely related structured formats and track file operations cumulatively. Summarization requests disable prompt-cache writes because these one-off prompts are unlikely to be reused.
24
+
25
+ ## Compaction
26
+
27
+ ### When It Triggers
28
+
29
+ Auto-compaction triggers when:
30
+
31
+ ```
32
+ contextTokens > contextWindow - reserveTokens
33
+ ```
34
+
35
+ By default, `reserveTokens` is 16384 tokens (configurable in `~/.knightcode/agent/settings.json` or `<project-dir>/.knightcode/settings.json`). It only decides when compaction starts. Summary requests use the model's output limit, reduced when needed so input and output fit the context window.
36
+
37
+ During a multi-turn agent run, KnightCode checks the canonical projected context after tools finish and their results are appended, before starting the next assistant response. If the threshold is crossed, KnightCode compacts during `prepareNextTurn`, then performs the existing catch-up steering poll before `turn_start`. It skips this between-turn check when the completed tool batch terminates the run and no queued message requires another response. KnightCode also checks before a new user prompt and performs final-attempt overflow recovery after the low-level run ends.
38
+
39
+ A provider context-overflow error or an early final `stopReason: "length"` can select one compact-and-retry recovery attempt. Length responses with tool calls retain their synthetic failed tool results and follow the ordinary tool/queue scheduler rather than forcing the run to end.
40
+
41
+ You can also trigger manually with `/compact [instructions]`, where optional instructions focus the summary.
42
+
43
+ ### How It Works
44
+
45
+ 1. **Find cut point**: Walk backwards through the finalized session projection, accumulating token estimates until `keepRecentTokens` (default 20k, configurable in `~/.knightcode/agent/settings.json` or `<project-dir>/.knightcode/settings.json`) is reached
46
+ 2. **Extract messages**: Collect projected messages from the previous kept boundary (or session start) up to the cut point
47
+ 3. **Generate summary**: Call LLM to summarize with structured format, passing the previous summary as iterative context when present
48
+ 4. **Append entry**: Save `CompactionEntry` with summary and `firstKeptEntryId`
49
+ 5. **Rebuilds context**: Session rebuilds the context for the next request, using summary + messages from `firstKeptEntryId` onwards
50
+
51
+ ```
52
+ Before compaction:
53
+
54
+ entry: 0 1 2 3 4 5 6 7 8 9
55
+ ┌─────┬─────┬─────┬──────┬─────┬─────┬──────┬──────┬─────┬─────┐
56
+ │ hdr │ usr │ ass │ tool │ usr │ ass │ tool │ tool │ ass │ tool│
57
+ └─────┴─────┴─────┴──────┴─────┴─────┴──────┴──────┴─────┴─────┘
58
+ └────────┬───────┘ └──────────────┬──────────────┘
59
+ messagesToSummarize kept messages
60
+ ↑
61
+ firstKeptEntryId (entry 4)
62
+
63
+ After compaction (new entry appended):
64
+
65
+ entry: 0 1 2 3 4 5 6 7 8 9 10
66
+ ┌─────┬─────┬─────┬──────┬─────┬─────┬──────┬──────┬─────┬─────┬─────┐
67
+ │ hdr │ usr │ ass │ tool │ usr │ ass │ tool │ tool │ ass │ tool│ cmp │
68
+ └─────┴─────┴─────┴──────┴─────┴─────┴──────┴──────┴─────┴─────┴─────┘
69
+ └──────────┬──────┘ └──────────────────────┬───────────────────┘
70
+ not sent to LLM sent to LLM
71
+ ↑
72
+ starts from firstKeptEntryId
73
+
74
+ What the LLM sees:
75
+
76
+ ┌────────┬─────────┬─────┬─────┬──────┬──────┬─────┬──────┐
77
+ │ system │ summary │ usr │ ass │ tool │ tool │ ass │ tool │
78
+ └────────┴─────────┴─────┴─────┴──────┴──────┴─────┴──────┘
79
+ ↑ ↑ └─────────────────┬────────────────┘
80
+ prompt from cmp messages from firstKeptEntryId
81
+ ```
82
+
83
+ On repeated compactions, the summarized span starts at the previous compaction's kept boundary (`firstKeptEntryId`), not at the compaction entry itself, falling back to the entry after the previous compaction if that kept entry cannot be found in the path. A retain-none compaction records its own ID as `firstKeptEntryId`; repeated compaction starts after that entry. This preserves messages that survived the earlier compaction by including them in the next summarization pass as well. KnightCode also recalculates `tokensBefore` from the rebuilt, context-edited session projection before writing the new `CompactionEntry`, so the token count reflects the actual pre-compaction context being replaced. Omitted raw entries remain stored but do not affect cut selection, summaries, checkpoints, or token estimates.
84
+
85
+ ### Overflow and Length Recovery Ordering
86
+
87
+ Recovery preserves the existing lifecycle and queue order. The completed attempt remains visible to `turn_end` and `agent_end`; post-run recovery then repairs persisted model context before a fresh retry:
88
+
89
+ ```text
90
+ persist final assistant response
91
+ → extension/public turn_end
92
+ → extension/public agent_end
93
+ → append context_edit omissions for the selected attempt
94
+ → for overflow/length: run session_before_compact and append compaction on success
95
+ → start the retry as a fresh run
96
+ ```
97
+
98
+ If recovery compaction fails or is cancelled, KnightCode keeps the omission edits, appends no compaction, and schedules no internal retry. Existing queued work remains governed by ordinary steering and follow-up rules. `agent_before_settle` sees the repaired projection after recovery processing. Raw transcript history, exports, billing totals, and history-search extensions can still inspect the omitted attempt.
99
+
100
+ ### Split user-message spans
101
+
102
+ A user-message span starts with a user message and includes all turns until the next user message. Normally, compaction cuts at user-message boundaries.
103
+
104
+ When one user-message span exceeds `keepRecentTokens`, the cut point lands within that span at an assistant message. This is a split user-message span:
105
+
106
+ ```
107
+ Split user-message span (one span exceeds budget):
108
+
109
+ entry: 0 1 2 3 4 5 6 7 8
110
+ ┌─────┬─────┬─────┬──────┬─────┬──────┬──────┬─────┬──────┐
111
+ │ hdr │ usr │ ass │ tool │ ass │ tool │ tool │ ass │ tool │
112
+ └─────┴─────┴─────┴──────┴─────┴──────┴──────┴─────┴──────┘
113
+ ↑ ↑
114
+ turnStartIndex = 1 firstKeptEntryId = 7
115
+ │ │
116
+ └──── turnPrefixMessages (1-6) ───────┘
117
+ └── kept (7-8)
118
+
119
+ isSplitTurn = true
120
+ messagesToSummarize = [] (no earlier user-message spans)
121
+ turnPrefixMessages = [usr, ass, tool, ass, tool, tool]
122
+ ```
123
+
124
+ For split user-message spans, KnightCode generates two summaries and merges them:
125
+ 1. **History summary**: Previous context (if any)
126
+ 2. **User-message-span prefix summary**: The early part of the split user-message span
127
+
128
+ ### Cut Point Rules
129
+
130
+ Valid cut points are:
131
+ - User messages
132
+ - Assistant messages
133
+ - BashExecution messages
134
+ - Custom messages (custom_message, branch_summary)
135
+
136
+ Never cut at tool results (they must stay with their tool call).
137
+
138
+ Preparation advances the kept boundary into a context-invisible suffix only when that suffix contains an omitted assistant attempt and no unomitted context-producing entries. Recovery `context_edit` omissions satisfy this rule; intrinsically context-invisible metadata may coexist with them. Metadata alone and newly appended custom messages do not move the cut. A replacement edit affecting the candidate input or summarized prefix also blocks advancement because the omitted assistant answered the pre-edit input; replacements of suffix entries that are ultimately omitted remain safe. This allows an over-budget recovered input to be summarized while retaining the edits that keep the abandoned attempt omitted, without making bookkeeping change whether new model input is preserved verbatim.
139
+
140
+ ### CompactionEntry Structure
141
+
142
+ Defined in [`session-manager.ts`](https://github.com/KnightCodeAI/knightcode/blob/main/packages/cli/src/core/session-manager.ts):
143
+
144
+ ```typescript
145
+ interface CompactionEntry<T = unknown> {
146
+ type: "compaction";
147
+ id: string;
148
+ parentId: string | null;
149
+ timestamp: string;
150
+ summary: string;
151
+ firstKeptEntryId: string;
152
+ tokensBefore: number;
153
+ usage?: Usage; // LLM usage that generated the summary
154
+ fromHook?: boolean; // true if provided by extension (legacy field name)
155
+ details?: T; // implementation-specific data
156
+ }
157
+
158
+ // Default compaction uses this for details (from compaction.ts):
159
+ interface CompactionDetails {
160
+ readFiles: string[];
161
+ modifiedFiles: string[];
162
+ }
163
+ ```
164
+
165
+ Extensions can store any JSON-serializable data in `details`. The default compaction tracks file operations, but custom extension implementations can use their own structure. Generated and extension-provided summaries store their LLM `usage` when available so session totals include summarization work.
166
+
167
+ See [`prepareCompaction()`](https://github.com/KnightCodeAI/knightcode/blob/main/packages/cli/src/core/compaction/compaction.ts) and [`compact()`](https://github.com/KnightCodeAI/knightcode/blob/main/packages/cli/src/core/compaction/compaction.ts) for the implementation. For direct programmatic summarization, `generateSummary()` returns the summary text and `generateSummaryWithUsage()` returns `{ text, usage }`.
168
+
169
+ ## Branch Summarization
170
+
171
+ ### When It Triggers
172
+
173
+ When you use `/tree` to navigate to a different branch, KnightCode offers to summarize the work you're leaving. `/undo` never summarizes; it only rewinds. This injects context from the left branch into the new branch.
174
+
175
+ ### How It Works
176
+
177
+ 1. **Find common ancestor**: Deepest node shared by old and new positions
178
+ 2. **Collect entries**: Walk from old leaf back to common ancestor
179
+ 3. **Prepare with budget**: Include messages up to token budget (newest first)
180
+ 4. **Generate summary**: Call LLM with structured format
181
+ 5. **Append entry**: Save `BranchSummaryEntry` at navigation point
182
+
183
+ ```
184
+ Tree before navigation:
185
+
186
+ ┌─ B ─ C ─ D (old leaf, being abandoned)
187
+ A ───┤
188
+ └─ E ─ F (target)
189
+
190
+ Common ancestor: A
191
+ Entries to summarize: B, C, D
192
+
193
+ After navigation with summary:
194
+
195
+ ┌─ B ─ C ─ D
196
+ A ───┤
197
+ └─ E ─ F ─ [summary of B,C,D] (new leaf)
198
+ ```
199
+
200
+ ### Cumulative File Tracking
201
+
202
+ Default compaction and branch summarization track files cumulatively. Both extract file operations from tool calls in the messages being summarized. Compaction also carries file lists from the previous KnightCode-generated compaction. Branch summarization carries file lists from KnightCode-generated branch summaries in the entries it summarizes.
203
+
204
+ File tracking therefore accumulates across default compactions and nested default branch summaries. KnightCode does not automatically carry file lists from extension-generated summaries whose `fromHook` field is `true`; extensions manage their own `details` format.
205
+
206
+ ### BranchSummaryEntry Structure
207
+
208
+ Defined in [`session-manager.ts`](https://github.com/KnightCodeAI/knightcode/blob/main/packages/cli/src/core/session-manager.ts):
209
+
210
+ ```typescript
211
+ interface BranchSummaryEntry<T = unknown> {
212
+ type: "branch_summary";
213
+ id: string;
214
+ parentId: string | null;
215
+ timestamp: string;
216
+ summary: string;
217
+ fromId: string; // Entry we navigated from
218
+ usage?: Usage; // LLM usage that generated the summary
219
+ fromHook?: boolean; // true if provided by extension (legacy field name)
220
+ details?: T; // implementation-specific data
221
+ }
222
+
223
+ // Default branch summarization uses this for details (from branch-summarization.ts):
224
+ interface BranchSummaryDetails {
225
+ readFiles: string[];
226
+ modifiedFiles: string[];
227
+ }
228
+ ```
229
+
230
+ Same as compaction, extensions can store custom data in `details`.
231
+
232
+ See [`collectEntriesForBranchSummary()`](https://github.com/KnightCodeAI/knightcode/blob/main/packages/cli/src/core/compaction/branch-summarization.ts), [`prepareBranchEntries()`](https://github.com/KnightCodeAI/knightcode/blob/main/packages/cli/src/core/compaction/branch-summarization.ts), and [`generateBranchSummary()`](https://github.com/KnightCodeAI/knightcode/blob/main/packages/cli/src/core/compaction/branch-summarization.ts) for the implementation.
233
+
234
+ ## Summary Format
235
+
236
+ Both formats include Goal, Constraints & Preferences, Progress, Key Decisions, and Next Steps. Compaction summaries also include Critical Context. Branch summaries stop after Next Steps. KnightCode appends file lists to either format when relevant.
237
+
238
+ Compaction summaries use this format:
239
+
240
+ ```markdown
241
+ ## Goal
242
+ [What the user is trying to accomplish]
243
+
244
+ ## Constraints & Preferences
245
+ - [Requirements mentioned by user]
246
+
247
+ ## Progress
248
+ ### Done
249
+ - [x] [Completed tasks]
250
+
251
+ ### In Progress
252
+ - [ ] [Current work]
253
+
254
+ ### Blocked
255
+ - [Issues, if any]
256
+
257
+ ## Key Decisions
258
+ - **[Decision]**: [Rationale]
259
+
260
+ ## Next Steps
261
+ 1. [What should happen next]
262
+
263
+ ## Critical Context
264
+ - [Data needed to continue]
265
+
266
+ <read-files>
267
+ path/to/file1.ts
268
+ path/to/file2.ts
269
+ </read-files>
270
+
271
+ <modified-files>
272
+ path/to/changed.ts
273
+ </modified-files>
274
+ ```
275
+
276
+ ### Message Serialization
277
+
278
+ Before summarization, messages are serialized to text via [`serializeConversation()`](https://github.com/KnightCodeAI/knightcode/blob/main/packages/cli/src/core/compaction/utils.ts):
279
+
280
+ ```
281
+ [User]: What they said
282
+ [Assistant]: Response text
283
+ [Assistant tool calls]: read(path="foo.ts"); edit(path="bar.ts", ...)
284
+ [Tool result]: Output from tool
285
+ ```
286
+
287
+ This prevents the model from treating it as a conversation to continue.
288
+
289
+ Thinking blocks are omitted. Providers return summaries of the real reasoning, and replayed thinking is often not part of the model's live context, so including it could make the summarization request larger than the context it summarizes.
290
+
291
+ Tool results are truncated to 2000 characters during serialization. Content beyond that limit is replaced with a marker indicating how many characters were truncated. This keeps summarization requests within reasonable token budgets, since tool results (especially from `read` and `bash`) are typically the largest contributors to context size.
292
+
293
+ ## Custom Summarization via Extensions
294
+
295
+ Extensions can intercept and customize both compaction and branch summarization. See [`extensions/types.ts`](https://github.com/KnightCodeAI/knightcode/blob/main/packages/cli/src/core/extensions/types.ts) for event type definitions.
296
+
297
+ ### session_before_compact
298
+
299
+ Fired before auto-compaction or `/compact`. Can cancel or provide custom summary. See `SessionBeforeCompactEvent` and `CompactionPreparation` in the types file.
300
+
301
+ ```typescript
302
+ knightcode.on("session_before_compact", async (event, ctx) => {
303
+ const { preparation, branchEntries, customInstructions, reason, willRetry, signal } = event;
304
+
305
+ // preparation.messagesToSummarize - messages to summarize
306
+ // preparation.turnPrefixMessages - user-message-span prefix (if isSplitTurn)
307
+ // preparation.previousSummary - previous compaction summary
308
+ // preparation.fileOps - extracted file operations
309
+ // preparation.tokensBefore - context tokens before compaction
310
+ // preparation.firstKeptEntryId - where kept messages start
311
+ // preparation.settings - effective settings after applying model overrides
312
+
313
+ // branchEntries - all entries on current branch (for custom state)
314
+ // reason - "manual" (/compact), "threshold", or "overflow"
315
+ // willRetry - whether the aborted turn is retried after compaction (overflow recovery)
316
+ // signal - AbortSignal (pass to LLM calls)
317
+
318
+ // Cancel:
319
+ return { cancel: true };
320
+
321
+ // Custom summary:
322
+ return {
323
+ compaction: {
324
+ summary: "Your summary...",
325
+ firstKeptEntryId: preparation.firstKeptEntryId,
326
+ tokensBefore: preparation.tokensBefore,
327
+ // usage: summaryResponse.usage, // Optional; included in session totals
328
+ details: { /* custom data */ },
329
+ }
330
+ };
331
+ });
332
+ ```
333
+
334
+ #### Converting Messages to Text
335
+
336
+ To generate a summary with your own model, convert messages to text using `serializeConversation`:
337
+
338
+ ```typescript
339
+ import { convertToLlm, serializeConversation } from "@knightcodeai/cli";
340
+
341
+ knightcode.on("session_before_compact", async (event, ctx) => {
342
+ const { preparation } = event;
343
+
344
+ // Convert AgentMessage[] to Message[], then serialize to text
345
+ const conversationText = serializeConversation(
346
+ convertToLlm(preparation.messagesToSummarize)
347
+ );
348
+ // Returns:
349
+ // [User]: message text
350
+ // [Assistant]: response text
351
+ // [Assistant tool calls]: read(path="..."); bash(command="...")
352
+ // [Tool result]: output text
353
+
354
+ // Now send to your model for summarization
355
+ const { summary, usage } = await myModel.summarize(conversationText);
356
+
357
+ return {
358
+ compaction: {
359
+ summary,
360
+ firstKeptEntryId: preparation.firstKeptEntryId,
361
+ tokensBefore: preparation.tokensBefore,
362
+ usage,
363
+ }
364
+ };
365
+ });
366
+ ```
367
+
368
+ See [custom-compaction.ts](../examples/extensions/custom-compaction.ts) for a complete example using a different model.
369
+
370
+ ### session_compact_failed
371
+
372
+ Fired when manual or automatic compaction fails or is aborted. This is useful for telemetry extensions that need to pair `session_before_compact` attempts with terminal outcomes.
373
+
374
+ ```typescript
375
+ knightcode.on("session_compact_failed", async (event, ctx) => {
376
+ const { reason, errorMessage, aborted, willRetry, fromExtension } = event;
377
+ // reason - "manual" (/compact), "threshold", or "overflow"
378
+ // errorMessage - present for non-abort failures
379
+ // aborted - true for canceled/aborted compactions
380
+ // willRetry - whether the aborted turn would have retried after compaction
381
+ // fromExtension - whether extension-provided compaction content was being used
382
+ });
383
+ ```
384
+
385
+ ### session_before_tree
386
+
387
+ Fired before `/tree` navigation. Always fires regardless of whether user chose to summarize. Can cancel navigation or provide custom summary.
388
+
389
+ ```typescript
390
+ knightcode.on("session_before_tree", async (event, ctx) => {
391
+ const { preparation, signal } = event;
392
+
393
+ // preparation.targetId - where we're navigating to
394
+ // preparation.oldLeafId - current position (being abandoned)
395
+ // preparation.commonAncestorId - shared ancestor
396
+ // preparation.entriesToSummarize - entries that would be summarized
397
+ // preparation.userWantsSummary - whether user chose to summarize
398
+
399
+ // Cancel navigation entirely:
400
+ return { cancel: true };
401
+
402
+ // Provide custom summary (only used if userWantsSummary is true):
403
+ if (preparation.userWantsSummary) {
404
+ return {
405
+ summary: {
406
+ summary: "Your summary...",
407
+ // usage: summaryResponse.usage, // Optional; included in session totals
408
+ details: { /* custom data */ },
409
+ }
410
+ };
411
+ }
412
+ });
413
+ ```
414
+
415
+ See `SessionBeforeTreeEvent` and `TreePreparation` in the types file.
416
+
417
+ ## Settings
418
+
419
+ Configure compaction in `~/.knightcode/agent/settings.json` or `<project-dir>/.knightcode/settings.json`:
420
+
421
+ ```json
422
+ {
423
+ "compaction": {
424
+ "enabled": true,
425
+ "reserveTokens": 16384,
426
+ "keepRecentTokens": 20000
427
+ }
428
+ }
429
+ ```
430
+
431
+ | Setting | Default | Description |
432
+ |---------|---------|-------------|
433
+ | `enabled` | `true` | Enable auto-compaction |
434
+ | `reserveTokens` | `16384` | Free context tokens below which auto-compaction starts |
435
+ | `keepRecentTokens` | `20000` | Recent tokens to keep (not summarized) |
436
+
437
+ Disable auto-compaction with `"enabled": false`. You can still compact manually with `/compact`.
438
+
439
+ ### Per-model overrides
440
+
441
+ Use `compaction.modelOverrides` to tune token budgets for different models:
442
+
443
+ ```json
444
+ {
445
+ "compaction": {
446
+ "reserveTokens": 16384,
447
+ "keepRecentTokens": 20000,
448
+ "modelOverrides": {
449
+ "some-provider/big-model": {
450
+ "reserveTokens": 400000
451
+ }
452
+ }
453
+ }
454
+ }
455
+ ```
456
+
457
+ For a model with a 1M context window, this override triggers compaction above 600K tokens and keeps the ordinary 20000 recent tokens. Other models retain the ordinary 16384-token reserve.
458
+
459
+ Keys are exact, case-sensitive `provider/modelId` values, including any slashes within the model ID. Each `reserveTokens` and `keepRecentTokens` value falls back independently from the model override to the ordinary setting to the built-in default. Values must be non-negative safe integers. Invalid values in the matching model override produce an error when read; only omitted fields fall back to the ordinary setting. Model override entries must be objects. Invalid ordinary token settings produce an error when read, even if the active model has a valid override. Only omitted ordinary values use built-in defaults. `enabled` remains global, not model-specific.
460
+
461
+ These resolved values are used for manual compaction, all automatic threshold checks, overflow recovery, and extension-visible `preparation.settings`. Model switches affect subsequent checks and compactions without changing ordinary settings. Compaction already in progress uses the model and settings captured for that operation. Branch summarization settings are unaffected.
462
+
463
+ Overrides work in both global and project settings. The files merge recursively before lookup, so a global model-specific value beats a project-wide fallback; a project must override that model entry to change it. See [Settings](settings.md#per-model-compaction-overrides) for details.
@@ -0,0 +1,48 @@
1
+ # Configuration
2
+
3
+ KnightCode supports user-level and project configuration. User-level configuration lives in the agent directory, which defaults to `~/.knightcode/agent`. Project configuration lives in `.knightcode` under the working directory and loads after [project trust](security.md#understand-project-trust) is granted. The only exception is `sessionDir`, which KnightCode reads before resolving trust so it can locate sessions.
4
+
5
+ In interactive mode, use `/settings` to change common preferences. For other options, ask KnightCode to update the configuration or edit the relevant files directly. Run `/reload` after manually changing settings, keybindings, instructions, or resources.
6
+
7
+ ## Agent directory
8
+
9
+ The agent directory is shown as `<agent-dir>` below. Set its location with the `KNIGHTCODE_CODING_AGENT_DIR` environment variable or the SDK's [`agentDir`](sdk.md) option.
10
+
11
+ | Path | Responsibility |
12
+ |---|---|
13
+ | `<agent-dir>/settings.json` | User-level [settings](settings.md), including preferences, defaults, resource paths, and KnightCode package declarations. |
14
+ | `<agent-dir>/keybindings.json` | Custom terminal UI and application [keybindings](keybindings.md). |
15
+ | `<agent-dir>/mcp.json` | [MCP servers](mcp.md) available in every project. |
16
+ | `<agent-dir>/models.json` | [Compatible endpoints, models, and model overrides](models.md#configure-a-compatible-endpoint). |
17
+ | `<agent-dir>/auth.json` | Saved API keys and OAuth credentials. |
18
+ | `<agent-dir>/tools.json` | [Web tool](usage.md#web-tools), scratchpad, and classifier gate settings written by `/tools`, including the Brave Search key. |
19
+ | `<agent-dir>/AGENTS.override.md`, `AGENTS.md`, `AGENTS.MD`, `CLAUDE.md`, or `CLAUDE.MD` | User instructions applied across working directories. |
20
+ | `<agent-dir>/SYSTEM.md` | Replaces KnightCode’s default system prompt. |
21
+ | `<agent-dir>/APPEND_SYSTEM.md` | Adds instructions to KnightCode’s system prompt. |
22
+ | `<agent-dir>/extensions/` | User [extensions](extensions.md). |
23
+ | `<agent-dir>/skills/` | User [skills](skills.md) and supporting files. |
24
+ | `<agent-dir>/prompts/` | User [prompt templates](prompt-templates.md) exposed as slash commands. |
25
+ | `<agent-dir>/themes/` | User [theme](themes.md) files. |
26
+
27
+ ## Project `.knightcode` directory
28
+
29
+ | Path | Responsibility |
30
+ |---|---|
31
+ | `.knightcode/settings.json` | Project-level [settings](settings.md), resource paths, and KnightCode package declarations. |
32
+ | `.knightcode/mcp.json` | Project [MCP servers](mcp.md). |
33
+ | `.knightcode/SYSTEM.md` | Replaces the system prompt for the project. |
34
+ | `.knightcode/APPEND_SYSTEM.md` | Adds project-specific instructions to the system prompt. |
35
+ | `.knightcode/extensions/` | Project extensions. |
36
+ | `.knightcode/skills/` | Project skills and supporting files. |
37
+ | `.knightcode/prompts/` | Project prompt templates exposed as slash commands. |
38
+ | `.knightcode/themes/` | Project theme files. |
39
+
40
+ For `SYSTEM.md` and `APPEND_SYSTEM.md`, the trusted project file takes precedence over the corresponding agent-directory file. Files with the same name are not combined.
41
+
42
+ ## Context files
43
+
44
+ Context files are separate from project `.knightcode` configuration. KnightCode loads them from the agent directory, the working directory, and its parent directories. A context file applies whenever KnightCode runs in its directory or anywhere below it.
45
+
46
+ An `AGENTS.override.md` replaces `AGENTS.md` or `CLAUDE.md` only in the same directory. It does not suppress context files from the agent directory or other directories.
47
+
48
+ Context-file discovery does not require project trust.
@@ -0,0 +1,143 @@
1
+ # Run KnightCode in an isolated environment
2
+
3
+ Use an isolated environment to limit the files, credentials, processes, and network services that generated commands can access or affect.
4
+
5
+ You can isolate the complete KnightCode process or keep KnightCode on the host and route selected tools into an isolated environment.
6
+
7
+ ## Choose an isolation method
8
+
9
+ | Method | Where KnightCode runs | What is isolated | Credential handling | Best for |
10
+ |---|---|---|---|---|
11
+ | Plain Docker | Container | KnightCode, built-in tools, `!` commands, and extensions | Credentials passed into the container | A straightforward local container boundary |
12
+ | OpenShell | Local or remote sandbox | KnightCode, built-in tools, `!` commands, and extensions | Policy-controlled credentials and inference routing | Filesystem, process, network, and credential policies |
13
+ | Gondolin extension | Host | Built-in tools and `!` commands | Stored KnightCode credentials remain on the host, but commands inherit host environment variables | A local micro-VM for tool execution while retaining the host interface |
14
+
15
+ The method changes where extensions run. When the complete KnightCode process runs inside an isolated environment, its extensions run there too. When host KnightCode delegates built-in tools through Gondolin, other extension tools still run on the host unless they also delegate their work.
16
+
17
+ ## Decide what KnightCode can access
18
+
19
+ An isolated process can still affect resources you expose to it:
20
+
21
+ - A read-write host mount lets KnightCode modify those host files.
22
+ - Mounting `~/.knightcode/agent` exposes your KnightCode credentials, settings, extensions, and sessions.
23
+ - Environment variables passed into a container are available to processes inside it.
24
+ - Network access may allow code or tool output to leave the environment.
25
+ - Tool-only isolation does not constrain the host KnightCode process or extension tools that do not use the isolated backend.
26
+
27
+ Expose only the working folder, credentials, and network destinations needed for the task. Use read-only mounts or copy files into and out of the environment when you do not want writes to affect the host.
28
+
29
+ ## Run KnightCode in plain Docker
30
+
31
+ Plain Docker provides the simplest whole-process container boundary.
32
+
33
+ ### Build the image
34
+
35
+ Create `Dockerfile.knightcode`:
36
+
37
+ ```dockerfile
38
+ FROM node:24-bookworm-slim
39
+
40
+ RUN apt-get update \
41
+ && apt-get install -y --no-install-recommends bash ca-certificates git ripgrep \
42
+ && rm -rf /var/lib/apt/lists/*
43
+ RUN npm install -g --ignore-scripts @knightcodeai/cli
44
+
45
+ WORKDIR /workspace
46
+ ENTRYPOINT ["knightcode"]
47
+ ```
48
+
49
+ Build it from the directory containing the file:
50
+
51
+ ```bash
52
+ docker build -t knightcode-sandbox -f Dockerfile.knightcode .
53
+ ```
54
+
55
+ ### Start KnightCode
56
+
57
+ From the working folder you want KnightCode to access, run:
58
+
59
+ ```bash
60
+ docker run --rm -it \
61
+ -e ANTHROPIC_API_KEY \
62
+ -v "$PWD:/workspace" \
63
+ -v knightcode-agent-home:/root/.knightcode/agent \
64
+ knightcode-sandbox
65
+ ```
66
+
67
+ Replace `ANTHROPIC_API_KEY` with the credential required by your provider. The named `knightcode-agent-home` volume keeps container-local settings, credentials, and sessions between runs.
68
+
69
+ Do not mount the host's `~/.knightcode/agent` unless the container should have access to your host KnightCode configuration and credentials.
70
+
71
+ ### Verify the workspace
72
+
73
+ Inside KnightCode, run:
74
+
75
+ ```text
76
+ !pwd
77
+ ```
78
+
79
+ The command should report `/workspace`. Changes under `/workspace` write through to the mounted host folder. Remove the bind mount or use a read-only mount when that is not acceptable.
80
+
81
+ ## Run KnightCode with OpenShell
82
+
83
+ [NVIDIA OpenShell](https://docs.nvidia.com/openshell/about/overview) provides local or remote sandboxes with filesystem, process, network, credential, and inference policies.
84
+
85
+ ### Select a gateway
86
+
87
+ Every sandbox requires an active gateway:
88
+
89
+ ```bash
90
+ openshell gateway add <gateway-url> --name <name>
91
+ openshell gateway select <name>
92
+ ```
93
+
94
+ ### Create the sandbox
95
+
96
+ ```bash
97
+ openshell sandbox create --name knightcode-sandbox --from knightcode -- knightcode
98
+ ```
99
+
100
+ KnightCode, its built-in tools, `!` commands, and extension tools run inside the OpenShell boundary.
101
+
102
+ ### Transfer files to a remote sandbox
103
+
104
+ A remote gateway does not bind-mount your host working folder. Clone the repository inside the sandbox or transfer files explicitly:
105
+
106
+ ```bash
107
+ openshell sandbox upload knightcode-sandbox ./working-folder /workspace
108
+ openshell sandbox download knightcode-sandbox /workspace/working-folder ./working-folder-out
109
+ ```
110
+
111
+ OpenShell inference routing can keep raw model credentials outside the sandbox. When configured, point KnightCode at the corresponding OpenAI-compatible or Anthropic-compatible endpoint exposed by the gateway.
112
+
113
+ ## Route tools through Gondolin
114
+
115
+ [Gondolin](https://github.com/KnightCodeAI/gondolin) is a local Linux micro-VM. Its example extension keeps the KnightCode process and file-based provider credentials on the host while routing the built-in tools and user `!` commands into the VM.
116
+
117
+ Commands inside the VM inherit the host process environment. Provider keys supplied through environment variables can therefore be visible inside the VM. Do not use this pattern as a credential boundary unless you remove sensitive variables or change the extension's environment handling.
118
+
119
+ Gondolin requires Node.js 23.6 or newer and QEMU installed through your operating-system package manager.
120
+
121
+ ### Install the extension
122
+
123
+ From a KnightCode source checkout:
124
+
125
+ ```bash
126
+ mkdir -p ~/.knightcode/agent/extensions
127
+ cp -R packages/cli/examples/extensions/gondolin ~/.knightcode/agent/extensions/gondolin
128
+ cd ~/.knightcode/agent/extensions/gondolin
129
+ npm install --ignore-scripts
130
+ ```
131
+
132
+ ### Start KnightCode
133
+
134
+ Run KnightCode from the working folder you want mounted:
135
+
136
+ ```bash
137
+ cd /path/to/working-folder
138
+ knightcode -e ~/.knightcode/agent/extensions/gondolin
139
+ ```
140
+
141
+ The extension mounts the host working folder at `/workspace` in the VM and overrides `read`, `write`, `edit`, `bash`, `grep`, `find`, and `ls`. File changes under `/workspace` write through to the host.
142
+
143
+ Other extension tools still run on the host unless they explicitly delegate their operations. Review the [Gondolin example](../examples/extensions/gondolin/) before adding tools that could bypass the VM boundary.