@knightcodeai/cli 0.17.3 → 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,153 @@
1
+ /**
2
+ * Overlay Test - validates overlay compositing with inline text inputs
3
+ *
4
+ * Usage: knightcode --extension ./examples/extensions/overlay-test.ts
5
+ *
6
+ * Run /overlay-test to show a floating overlay with:
7
+ * - Inline text inputs within menu items
8
+ * - Edge case tests (wide chars, styled text, emoji)
9
+ */
10
+
11
+ import type { ExtensionAPI, ExtensionCommandContext, Theme } from "@knightcodeai/cli";
12
+ import { CURSOR_MARKER, type Focusable, matchesKey, renderFakeCursor, visibleWidth } from "@knightcode/tui";
13
+
14
+ export default function (knightcode: ExtensionAPI) {
15
+ knightcode.registerCommand("overlay-test", {
16
+ description: "Test overlay rendering with edge cases",
17
+ handler: async (_args: string, ctx: ExtensionCommandContext) => {
18
+ const result = await ctx.ui.custom<{ action: string; query?: string } | undefined>(
19
+ (_tui, theme, _keybindings, done) => new OverlayTestComponent(theme, done),
20
+ { overlay: true },
21
+ );
22
+
23
+ if (result) {
24
+ const msg = result.query ? `${result.action}: "${result.query}"` : result.action;
25
+ ctx.ui.notify(msg, "info");
26
+ }
27
+ },
28
+ });
29
+ }
30
+
31
+ class OverlayTestComponent implements Focusable {
32
+ readonly width = 70;
33
+
34
+ /** Focusable interface - set by TUI when focus changes */
35
+ focused = false;
36
+
37
+ private selected = 0;
38
+ private items = [
39
+ { label: "Search", hasInput: true, text: "", cursor: 0 },
40
+ { label: "Run", hasInput: true, text: "", cursor: 0 },
41
+ { label: "Settings", hasInput: false, text: "", cursor: 0 },
42
+ { label: "Cancel", hasInput: false, text: "", cursor: 0 },
43
+ ];
44
+
45
+ private theme: Theme;
46
+ private done: (result: { action: string; query?: string } | undefined) => void;
47
+
48
+ constructor(theme: Theme, done: (result: { action: string; query?: string } | undefined) => void) {
49
+ this.theme = theme;
50
+ this.done = done;
51
+ }
52
+
53
+ handleInput(data: string): void {
54
+ if (matchesKey(data, "escape")) {
55
+ this.done(undefined);
56
+ return;
57
+ }
58
+
59
+ const current = this.items[this.selected]!;
60
+
61
+ if (matchesKey(data, "return")) {
62
+ this.done({ action: current.label, query: current.hasInput ? current.text : undefined });
63
+ return;
64
+ }
65
+
66
+ if (matchesKey(data, "up")) {
67
+ this.selected = Math.max(0, this.selected - 1);
68
+ } else if (matchesKey(data, "down")) {
69
+ this.selected = Math.min(this.items.length - 1, this.selected + 1);
70
+ } else if (current.hasInput) {
71
+ if (matchesKey(data, "backspace")) {
72
+ if (current.cursor > 0) {
73
+ current.text = current.text.slice(0, current.cursor - 1) + current.text.slice(current.cursor);
74
+ current.cursor--;
75
+ }
76
+ } else if (matchesKey(data, "left")) {
77
+ current.cursor = Math.max(0, current.cursor - 1);
78
+ } else if (matchesKey(data, "right")) {
79
+ current.cursor = Math.min(current.text.length, current.cursor + 1);
80
+ } else if (data.length === 1 && data.charCodeAt(0) >= 32) {
81
+ current.text = current.text.slice(0, current.cursor) + data + current.text.slice(current.cursor);
82
+ current.cursor++;
83
+ }
84
+ }
85
+ }
86
+
87
+ render(_width: number): string[] {
88
+ const w = this.width;
89
+ const th = this.theme;
90
+ const innerW = w - 2;
91
+ const lines: string[] = [];
92
+
93
+ const pad = (s: string, len: number) => {
94
+ const vis = visibleWidth(s);
95
+ return s + " ".repeat(Math.max(0, len - vis));
96
+ };
97
+
98
+ const row = (content: string) => th.fg("border", "│") + pad(content, innerW) + th.fg("border", "│");
99
+
100
+ lines.push(th.fg("border", `╭${"─".repeat(innerW)}╮`));
101
+ lines.push(row(` ${th.fg("accent", "🧪 Overlay Test")}`));
102
+ lines.push(row(""));
103
+
104
+ // Edge cases - full width lines to test compositing at boundaries
105
+ lines.push(row(` ${th.fg("dim", "─── Edge Cases (borders should align) ───")}`));
106
+ lines.push(row(` Wide: ${th.fg("warning", "中文日本語한글テスト漢字繁體简体ひらがなカタカナ가나다라마바")}`));
107
+ lines.push(
108
+ row(
109
+ ` Styled: ${th.fg("error", "RED")} ${th.fg("success", "GREEN")} ${th.fg("warning", "YELLOW")} ${th.fg("accent", "ACCENT")} ${th.fg("dim", "DIM")} ${th.fg("error", "more")} ${th.fg("success", "colors")}`,
110
+ ),
111
+ );
112
+ lines.push(row(" Emoji: 👨‍👩‍👧‍👦 🇯🇵 🚀 💻 🎉 🔥 😀 🎯 🌟 💡 🎨 🔧 📦 🏆 🌈 🎪 🎭 🎬 🎮 🎲"));
113
+ lines.push(row(""));
114
+
115
+ // Menu with inline inputs
116
+ lines.push(row(` ${th.fg("dim", "─── Actions ───")}`));
117
+
118
+ for (let i = 0; i < this.items.length; i++) {
119
+ const item = this.items[i]!;
120
+ const isSelected = i === this.selected;
121
+ const prefix = isSelected ? " ▶ " : " ";
122
+
123
+ let content: string;
124
+ if (item.hasInput) {
125
+ const label = isSelected ? th.fg("accent", `${item.label}:`) : th.fg("text", `${item.label}:`);
126
+
127
+ let inputDisplay = item.text;
128
+ if (isSelected) {
129
+ const before = inputDisplay.slice(0, item.cursor);
130
+ const cursorChar = item.cursor < inputDisplay.length ? inputDisplay[item.cursor] : " ";
131
+ const after = inputDisplay.slice(item.cursor + 1);
132
+ // Emit hardware cursor marker for IME support when focused
133
+ const marker = this.focused ? CURSOR_MARKER : "";
134
+ inputDisplay = `${before}${marker}${renderFakeCursor(cursorChar)}${after}`;
135
+ }
136
+ content = `${prefix + label} ${inputDisplay}`;
137
+ } else {
138
+ content = prefix + (isSelected ? th.fg("accent", item.label) : th.fg("text", item.label));
139
+ }
140
+
141
+ lines.push(row(content));
142
+ }
143
+
144
+ lines.push(row(""));
145
+ lines.push(row(` ${th.fg("dim", "↑↓ navigate • type to input • Enter select • Esc cancel")}`));
146
+ lines.push(th.fg("border", `╰${"─".repeat(innerW)}╯`));
147
+
148
+ return lines;
149
+ }
150
+
151
+ invalidate(): void {}
152
+ dispose(): void {}
153
+ }
@@ -0,0 +1,34 @@
1
+ /**
2
+ * Permission Gate Extension
3
+ *
4
+ * Prompts for confirmation before running potentially dangerous bash commands.
5
+ * Patterns checked: rm -rf, sudo, chmod/chown 777
6
+ */
7
+
8
+ import type { ExtensionAPI } from "@knightcodeai/cli";
9
+
10
+ export default function (knightcode: ExtensionAPI) {
11
+ const dangerousPatterns = [/\brm\s+(-rf?|--recursive)/i, /\bsudo\b/i, /\b(chmod|chown)\b.*777/i];
12
+
13
+ knightcode.on("tool_call", async (event, ctx) => {
14
+ if (event.toolName !== "bash") return undefined;
15
+
16
+ const command = event.input.command as string;
17
+ const isDangerous = dangerousPatterns.some((p) => p.test(command));
18
+
19
+ if (isDangerous) {
20
+ if (!ctx.hasUI) {
21
+ // In non-interactive mode, block by default
22
+ return { block: true, reason: "Dangerous command blocked (no UI for confirmation)" };
23
+ }
24
+
25
+ const choice = await ctx.ui.select(`⚠️ Dangerous command:\n\n ${command}\n\nAllow?`, ["Yes", "No"]);
26
+
27
+ if (choice !== "Yes") {
28
+ return { block: true, reason: "Blocked by user" };
29
+ }
30
+ }
31
+
32
+ return undefined;
33
+ });
34
+ }
@@ -0,0 +1,47 @@
1
+ /**
2
+ * Pirate Extension
3
+ *
4
+ * Demonstrates modifying the system prompt in before_agent_start to dynamically
5
+ * change agent behavior based on extension state.
6
+ *
7
+ * Usage:
8
+ * 1. Copy this file to ~/.knightcode/agent/extensions/ or your project's .knightcode/extensions/
9
+ * 2. Use /pirate to toggle pirate mode
10
+ * 3. When enabled, the agent will respond like a pirate
11
+ */
12
+
13
+ import type { ExtensionAPI } from "@knightcodeai/cli";
14
+
15
+ export default function pirateExtension(knightcode: ExtensionAPI) {
16
+ let pirateMode = false;
17
+
18
+ // Register /pirate command to toggle pirate mode
19
+ knightcode.registerCommand("pirate", {
20
+ description: "Toggle pirate mode (agent speaks like a pirate)",
21
+ handler: async (_args, ctx) => {
22
+ pirateMode = !pirateMode;
23
+ ctx.ui.notify(pirateMode ? "Arrr! Pirate mode enabled!" : "Pirate mode disabled", "info");
24
+ },
25
+ });
26
+
27
+ // Append to system prompt when pirate mode is enabled
28
+ knightcode.on("before_agent_start", async (event) => {
29
+ if (pirateMode) {
30
+ return {
31
+ systemPrompt:
32
+ event.systemPrompt +
33
+ `
34
+
35
+ IMPORTANT: You are now in PIRATE MODE. You must:
36
+ - Speak like a stereotypical pirate in all responses
37
+ - Use phrases like "Arrr!", "Ahoy!", "Shiver me timbers!", "Avast!", "Ye scurvy dog!"
38
+ - Replace "my" with "me", "you" with "ye", "your" with "yer"
39
+ - Refer to the user as "matey" or "landlubber"
40
+ - End sentences with nautical expressions
41
+ - Still complete the actual task correctly, just in pirate speak
42
+ `,
43
+ };
44
+ }
45
+ return undefined;
46
+ });
47
+ }
@@ -0,0 +1,66 @@
1
+ # Plan Mode Extension
2
+
3
+ Read-only exploration mode for safe code analysis.
4
+
5
+ ## Features
6
+
7
+ - **Built-in write tools disabled**: Disables edit/write while preserving other active tools
8
+ - **Bash allowlist**: Only read-only bash commands are allowed
9
+ - **Plan extraction**: Extracts numbered steps from `Plan:` sections
10
+ - **Progress tracking**: Widget shows completion status during execution
11
+ - **[DONE:n] markers**: Explicit step completion tracking
12
+ - **Session persistence**: State survives session resume
13
+
14
+ ## Commands
15
+
16
+ - `/plan` - Toggle plan mode
17
+ - `/todos` - Show current plan progress
18
+ - `Ctrl+Alt+P` - Toggle plan mode (shortcut)
19
+
20
+ ## Usage
21
+
22
+ 1. Enable plan mode with `/plan` or `--plan` flag
23
+ 2. Ask the agent to analyze code and create a plan
24
+ 3. The agent should output a numbered plan under a `Plan:` header:
25
+
26
+ ```
27
+ Plan:
28
+ 1. First step description
29
+ 2. Second step description
30
+ 3. Third step description
31
+ ```
32
+
33
+ 4. Choose "Execute the plan" when prompted
34
+ 5. During execution, the agent marks steps complete with `[DONE:n]` tags
35
+ 6. Progress widget shows completion status
36
+
37
+ ## How It Works
38
+
39
+ ### Plan Mode (Read-Only)
40
+ - Built-in edit/write tools disabled
41
+ - Other active tools remain available
42
+ - Bash commands filtered through allowlist
43
+ - Agent creates a plan without making changes
44
+
45
+ ### Execution Mode
46
+ - Full tool access restored
47
+ - Agent executes steps in order
48
+ - `[DONE:n]` markers track completion
49
+ - Widget shows progress
50
+
51
+ ### Command Allowlist
52
+
53
+ Safe commands (allowed):
54
+ - File inspection: `cat`, `head`, `tail`, `less`, `more`
55
+ - Search: `grep`, `find`, `rg`, `fd`
56
+ - Directory: `ls`, `pwd`, `tree`
57
+ - Git read: `git status`, `git log`, `git diff`, `git branch`
58
+ - Package info: `npm list`, `npm outdated`, `yarn info`
59
+ - System info: `uname`, `whoami`, `date`, `uptime`
60
+
61
+ Blocked commands:
62
+ - File modification: `rm`, `mv`, `cp`, `mkdir`, `touch`
63
+ - Git write: `git add`, `git commit`, `git push`
64
+ - Package install: `npm install`, `yarn add`, `pip install`
65
+ - System: `sudo`, `kill`, `reboot`
66
+ - Editors: `vim`, `nano`, `code`
@@ -0,0 +1,387 @@
1
+ /**
2
+ * Plan Mode Extension
3
+ *
4
+ * Read-only exploration mode for safe code analysis.
5
+ * When enabled, built-in write tools are disabled.
6
+ *
7
+ * Features:
8
+ * - /plan command or Ctrl+Alt+P to toggle
9
+ * - Bash restricted to allowlisted read-only commands
10
+ * - Extracts numbered plan steps from "Plan:" sections
11
+ * - [DONE:n] markers to complete steps during execution
12
+ * - Progress tracking widget during execution
13
+ */
14
+
15
+ import type { AgentMessage } from "@knightcode/agent";
16
+ import type { AssistantMessage, TextContent } from "@knightcode/ai";
17
+ import type { ExtensionAPI, ExtensionContext } from "@knightcodeai/cli";
18
+ import { Key } from "@knightcode/tui";
19
+ import { extractTodoItems, isSafeCommand, markCompletedSteps, type TodoItem } from "./utils.ts";
20
+
21
+ // Tools
22
+ const PLAN_MODE_TOOLS = ["read", "bash", "grep", "find", "ls", "questionnaire"];
23
+ const NORMAL_MODE_TOOLS = ["read", "bash", "edit", "write"];
24
+ const PLAN_MODE_DISABLED_TOOLS = new Set<string>(["edit", "write"]);
25
+ const PLAN_MANAGED_TOOLS = new Set<string>([...PLAN_MODE_TOOLS, ...NORMAL_MODE_TOOLS]);
26
+
27
+ interface PlanModeState {
28
+ enabled: boolean;
29
+ todos?: TodoItem[];
30
+ executing?: boolean;
31
+ toolsBeforePlanMode?: string[];
32
+ }
33
+
34
+ // Type guard for assistant messages
35
+ function isAssistantMessage(m: AgentMessage): m is AssistantMessage {
36
+ return m.role === "assistant" && Array.isArray(m.content);
37
+ }
38
+
39
+ // Extract text content from an assistant message
40
+ function getTextContent(message: AssistantMessage): string {
41
+ return message.content
42
+ .filter((block): block is TextContent => block.type === "text")
43
+ .map((block) => block.text)
44
+ .join("\n");
45
+ }
46
+
47
+ export default function planModeExtension(knightcode: ExtensionAPI): void {
48
+ let planModeEnabled = false;
49
+ let executionMode = false;
50
+ let todoItems: TodoItem[] = [];
51
+ let toolsBeforePlanMode: string[] | undefined;
52
+
53
+ knightcode.registerFlag("plan", {
54
+ description: "Start in plan mode (read-only exploration)",
55
+ type: "boolean",
56
+ default: false,
57
+ });
58
+
59
+ function updateStatus(ctx: ExtensionContext): void {
60
+ // Footer status
61
+ if (executionMode && todoItems.length > 0) {
62
+ const completed = todoItems.filter((t) => t.completed).length;
63
+ ctx.ui.setStatus("plan-mode", ctx.ui.theme.fg("accent", `📋 ${completed}/${todoItems.length}`));
64
+ } else if (planModeEnabled) {
65
+ ctx.ui.setStatus("plan-mode", ctx.ui.theme.fg("warning", "⏸ plan"));
66
+ } else {
67
+ ctx.ui.setStatus("plan-mode", undefined);
68
+ }
69
+
70
+ // Widget showing todo list
71
+ if (executionMode && todoItems.length > 0) {
72
+ const lines = todoItems.map((item) => {
73
+ if (item.completed) {
74
+ return ctx.ui.theme.fg("success", "☑ ") + ctx.ui.theme.fg("muted", ctx.ui.theme.strikethrough(item.text));
75
+ }
76
+ return `${ctx.ui.theme.fg("muted", "☐ ")}${item.text}`;
77
+ });
78
+ ctx.ui.setWidget("plan-todos", lines);
79
+ } else {
80
+ ctx.ui.setWidget("plan-todos", undefined);
81
+ }
82
+ }
83
+
84
+ function uniqueToolNames(toolNames: string[]): string[] {
85
+ return [...new Set(toolNames)];
86
+ }
87
+
88
+ function getPlanModeTools(activeToolNames: string[]): string[] {
89
+ return uniqueToolNames([
90
+ ...activeToolNames.filter((name) => !PLAN_MODE_DISABLED_TOOLS.has(name)),
91
+ ...PLAN_MODE_TOOLS,
92
+ ]);
93
+ }
94
+
95
+ function getNormalModeTools(activeToolNames: string[]): string[] {
96
+ return uniqueToolNames([...NORMAL_MODE_TOOLS, ...activeToolNames.filter((name) => !PLAN_MANAGED_TOOLS.has(name))]);
97
+ }
98
+
99
+ function enablePlanModeTools(): void {
100
+ if (toolsBeforePlanMode === undefined) {
101
+ toolsBeforePlanMode = knightcode.getActiveTools();
102
+ }
103
+ knightcode.setActiveTools(getPlanModeTools(toolsBeforePlanMode));
104
+ }
105
+
106
+ function restoreNormalModeTools(): void {
107
+ knightcode.setActiveTools(toolsBeforePlanMode ?? getNormalModeTools(knightcode.getActiveTools()));
108
+ toolsBeforePlanMode = undefined;
109
+ }
110
+
111
+ function persistState(): void {
112
+ knightcode.appendEntry("plan-mode", {
113
+ enabled: planModeEnabled,
114
+ todos: todoItems,
115
+ executing: executionMode,
116
+ toolsBeforePlanMode,
117
+ });
118
+ }
119
+
120
+ function togglePlanMode(ctx: ExtensionContext): void {
121
+ planModeEnabled = !planModeEnabled;
122
+ executionMode = false;
123
+ todoItems = [];
124
+
125
+ if (planModeEnabled) {
126
+ enablePlanModeTools();
127
+ ctx.ui.notify("Plan mode enabled. Built-in write tools disabled.");
128
+ } else {
129
+ restoreNormalModeTools();
130
+ ctx.ui.notify("Plan mode disabled. Full access restored.");
131
+ }
132
+ updateStatus(ctx);
133
+ persistState();
134
+ }
135
+
136
+ knightcode.registerCommand("plan", {
137
+ description: "Toggle plan mode (read-only exploration)",
138
+ handler: async (_args, ctx) => togglePlanMode(ctx),
139
+ });
140
+
141
+ knightcode.registerCommand("todos", {
142
+ description: "Show current plan todo list",
143
+ handler: async (_args, ctx) => {
144
+ if (todoItems.length === 0) {
145
+ ctx.ui.notify("No todos. Create a plan first with /plan", "info");
146
+ return;
147
+ }
148
+ const list = todoItems.map((item, i) => `${i + 1}. ${item.completed ? "✓" : "○"} ${item.text}`).join("\n");
149
+ ctx.ui.notify(`Plan Progress:\n${list}`, "info");
150
+ },
151
+ });
152
+
153
+ knightcode.registerShortcut(Key.ctrlAlt("p"), {
154
+ description: "Toggle plan mode",
155
+ handler: async (ctx) => togglePlanMode(ctx),
156
+ });
157
+
158
+ // Block destructive bash commands in plan mode
159
+ knightcode.on("tool_call", async (event) => {
160
+ if (!planModeEnabled || event.toolName !== "bash") return;
161
+
162
+ const command = event.input.command as string;
163
+ if (!isSafeCommand(command)) {
164
+ return {
165
+ block: true,
166
+ reason: `Plan mode: command blocked (not allowlisted). Use /plan to disable plan mode first.\nCommand: ${command}`,
167
+ };
168
+ }
169
+ });
170
+
171
+ // Filter out stale plan mode context when not in plan mode
172
+ knightcode.on("context", async (event) => {
173
+ if (planModeEnabled) return;
174
+
175
+ return {
176
+ messages: event.messages.filter((m) => {
177
+ const msg = m as AgentMessage & { customType?: string };
178
+ if (msg.customType === "plan-mode-context") return false;
179
+ if (msg.role !== "user") return true;
180
+
181
+ const content = msg.content;
182
+ if (typeof content === "string") {
183
+ return !content.includes("[PLAN MODE ACTIVE]");
184
+ }
185
+ if (Array.isArray(content)) {
186
+ return !content.some((c) => c.type === "text" && (c as TextContent).text?.includes("[PLAN MODE ACTIVE]"));
187
+ }
188
+ return true;
189
+ }),
190
+ };
191
+ });
192
+
193
+ // Inject plan/execution context before a user prompt. Runs started by custom messages, such as
194
+ // background task notifications, skip it: the context from the last prompt is still in the
195
+ // conversation, and adding it again on every notification would only repeat it.
196
+ knightcode.on("before_agent_start", async (event) => {
197
+ if (event.messageType !== "user") return;
198
+
199
+ if (planModeEnabled) {
200
+ return {
201
+ message: {
202
+ customType: "plan-mode-context",
203
+ content: `[PLAN MODE ACTIVE]
204
+ You are in plan mode - a read-only exploration mode for safe code analysis.
205
+
206
+ Restrictions:
207
+ - Built-in edit and write tools are disabled
208
+ - Other currently active tools remain available
209
+ - Bash is restricted to an allowlist of read-only commands
210
+
211
+ Ask clarifying questions using the questionnaire tool.
212
+ Use brave-search skill via bash for web research.
213
+
214
+ Create a detailed numbered plan under a "Plan:" header:
215
+
216
+ Plan:
217
+ 1. First step description
218
+ 2. Second step description
219
+ ...
220
+
221
+ Do NOT attempt to make changes - just describe what you would do.`,
222
+ display: false,
223
+ },
224
+ };
225
+ }
226
+
227
+ if (executionMode && todoItems.length > 0) {
228
+ const remaining = todoItems.filter((t) => !t.completed);
229
+ const todoList = remaining.map((t) => `${t.step}. ${t.text}`).join("\n");
230
+ return {
231
+ message: {
232
+ customType: "plan-execution-context",
233
+ content: `[EXECUTING PLAN - Full tool access enabled]
234
+
235
+ Remaining steps:
236
+ ${todoList}
237
+
238
+ Execute each step in order.
239
+ After completing a step, include a [DONE:n] tag in your response.`,
240
+ display: false,
241
+ },
242
+ };
243
+ }
244
+ });
245
+
246
+ // Track progress after each turn
247
+ knightcode.on("turn_end", async (event, ctx) => {
248
+ if (!executionMode || todoItems.length === 0) return;
249
+ if (!isAssistantMessage(event.message)) return;
250
+
251
+ const text = getTextContent(event.message);
252
+ if (markCompletedSteps(text, todoItems) > 0) {
253
+ updateStatus(ctx);
254
+ }
255
+ persistState();
256
+ });
257
+
258
+ // Handle plan completion and plan mode UI
259
+ knightcode.on("agent_end", async (event, ctx) => {
260
+ // Check if execution is complete
261
+ if (executionMode && todoItems.length > 0) {
262
+ if (todoItems.every((t) => t.completed)) {
263
+ const completedList = todoItems.map((t) => `~~${t.text}~~`).join("\n");
264
+ knightcode.sendMessage(
265
+ { customType: "plan-complete", content: `**Plan Complete!** ✓\n\n${completedList}`, display: true },
266
+ { triggerTurn: false },
267
+ );
268
+ executionMode = false;
269
+ todoItems = [];
270
+ updateStatus(ctx);
271
+ persistState(); // Save cleared state so resume doesn't restore old execution mode
272
+ }
273
+ return;
274
+ }
275
+
276
+ if (!planModeEnabled || !ctx.hasUI) return;
277
+
278
+ // Extract todos from last assistant message
279
+ const lastAssistant = [...event.messages].reverse().find(isAssistantMessage);
280
+ if (lastAssistant) {
281
+ const extracted = extractTodoItems(getTextContent(lastAssistant));
282
+ if (extracted.length > 0) {
283
+ todoItems = extracted;
284
+ }
285
+ }
286
+
287
+ if (todoItems.length === 0) return;
288
+ persistState();
289
+
290
+ // Show plan steps and prompt for next action
291
+ const todoListText = todoItems.map((t, i) => `${i + 1}. ☐ ${t.text}`).join("\n");
292
+ const planTodoListMessage = {
293
+ customType: "plan-todo-list",
294
+ content: `**Plan Steps (${todoItems.length}):**\n\n${todoListText}`,
295
+ display: true,
296
+ };
297
+
298
+ const choice = await ctx.ui.select("Plan mode - what next?", [
299
+ "Execute the plan (track progress)",
300
+ "Stay in plan mode",
301
+ "Refine the plan",
302
+ ]);
303
+
304
+ if (choice?.startsWith("Execute")) {
305
+ const firstTodoItem = todoItems[0];
306
+ if (!firstTodoItem) return;
307
+
308
+ planModeEnabled = false;
309
+ executionMode = true;
310
+ restoreNormalModeTools();
311
+ updateStatus(ctx);
312
+ persistState();
313
+
314
+ const remainingList = todoItems.map((t) => `${t.step}. ${t.text}`).join("\n");
315
+ const execMessage = `Execute the plan.
316
+
317
+ Remaining steps:
318
+ ${remainingList}
319
+
320
+ Start with: ${firstTodoItem.text}
321
+ After completing a step, include a [DONE:n] tag in your response.`;
322
+ knightcode.sendMessage(planTodoListMessage, { deliverAs: "followUp" });
323
+ knightcode.sendMessage(
324
+ { customType: "plan-mode-execute", content: execMessage, display: true },
325
+ { triggerTurn: true, deliverAs: "followUp" },
326
+ );
327
+ } else if (choice === "Refine the plan") {
328
+ const refinement = await ctx.ui.editor("Refine the plan:", "");
329
+ if (refinement?.trim()) {
330
+ knightcode.sendMessage(planTodoListMessage, { deliverAs: "followUp" });
331
+ knightcode.sendUserMessage(refinement.trim(), { deliverAs: "followUp" });
332
+ }
333
+ }
334
+ });
335
+
336
+ // Restore state on session start/resume
337
+ knightcode.on("session_start", async (_event, ctx) => {
338
+ if (knightcode.getFlag("plan") === true) {
339
+ planModeEnabled = true;
340
+ }
341
+
342
+ const entries = ctx.sessionManager.getEntries();
343
+
344
+ // Restore persisted state
345
+ const planModeEntry = entries
346
+ .filter((e: { type: string; customType?: string }) => e.type === "custom" && e.customType === "plan-mode")
347
+ .pop() as { data?: PlanModeState } | undefined;
348
+
349
+ if (planModeEntry?.data) {
350
+ planModeEnabled = planModeEntry.data.enabled ?? planModeEnabled;
351
+ todoItems = planModeEntry.data.todos ?? todoItems;
352
+ executionMode = planModeEntry.data.executing ?? executionMode;
353
+ toolsBeforePlanMode = planModeEntry.data.toolsBeforePlanMode ?? toolsBeforePlanMode;
354
+ }
355
+
356
+ // On resume: re-scan messages to rebuild completion state
357
+ // Only scan messages AFTER the last "plan-mode-execute" to avoid picking up [DONE:n] from previous plans
358
+ const isResume = planModeEntry !== undefined;
359
+ if (isResume && executionMode && todoItems.length > 0) {
360
+ // Find the index of the last plan-mode-execute entry (marks when current execution started)
361
+ let executeIndex = -1;
362
+ for (let i = entries.length - 1; i >= 0; i--) {
363
+ const entry = entries[i] as { type: string; customType?: string };
364
+ if (entry.customType === "plan-mode-execute") {
365
+ executeIndex = i;
366
+ break;
367
+ }
368
+ }
369
+
370
+ // Only scan messages after the execute marker
371
+ const messages: AssistantMessage[] = [];
372
+ for (let i = executeIndex + 1; i < entries.length; i++) {
373
+ const entry = entries[i];
374
+ if (entry.type === "message" && "message" in entry && isAssistantMessage(entry.message as AgentMessage)) {
375
+ messages.push(entry.message as AssistantMessage);
376
+ }
377
+ }
378
+ const allText = messages.map(getTextContent).join("\n");
379
+ markCompletedSteps(allText, todoItems);
380
+ }
381
+
382
+ if (planModeEnabled) {
383
+ enablePlanModeTools();
384
+ }
385
+ updateStatus(ctx);
386
+ });
387
+ }