@knightcodeai/cli 0.17.4 → 0.18.1

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 +1303 -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-253N4337.js +7 -0
  8. package/dist/bundle/chunks/chunk-2QIKI63P.js +108 -0
  9. package/dist/bundle/chunks/chunk-3LX7U45C.js +130 -0
  10. package/dist/bundle/chunks/chunk-4CRI7BMY.js +2 -0
  11. package/dist/bundle/chunks/chunk-57BPR4HF.js +2 -0
  12. package/dist/bundle/chunks/chunk-A5LJINMT.js +2 -0
  13. package/dist/bundle/chunks/chunk-AANBXVWQ.js +2 -0
  14. package/dist/bundle/chunks/chunk-AHB7JV5B.js +2 -0
  15. package/dist/bundle/chunks/chunk-B2FT7RH5.js +2 -0
  16. package/dist/bundle/chunks/chunk-BPNRVFVQ.js +2 -0
  17. package/dist/bundle/chunks/chunk-BRKUE2MD.js +2 -0
  18. package/dist/bundle/chunks/chunk-BXZL5C3N.js +58 -0
  19. package/dist/bundle/chunks/chunk-DGACKL4S.js +30 -0
  20. package/dist/bundle/chunks/chunk-DKOURXGU.js +2 -0
  21. package/dist/bundle/chunks/chunk-DVFCXHT4.js +2 -0
  22. package/dist/bundle/chunks/chunk-ETOMYYZC.js +2 -0
  23. package/dist/bundle/chunks/chunk-FA32X2UJ.js +7 -0
  24. package/dist/bundle/chunks/chunk-FHM6KUY3.js +44 -0
  25. package/dist/bundle/chunks/chunk-FO7CEQB3.js +11 -0
  26. package/dist/bundle/chunks/chunk-FXS5MU6B.js +2 -0
  27. package/dist/bundle/chunks/chunk-HHWP56PR.js +2 -0
  28. package/dist/bundle/chunks/chunk-HSL72VZI.js +2 -0
  29. package/dist/bundle/chunks/chunk-HUQB436V.js +2 -0
  30. package/dist/bundle/chunks/chunk-HWXGL4YB.js +2 -0
  31. package/dist/bundle/chunks/chunk-KQKUEQJA.js +6 -0
  32. package/dist/bundle/chunks/chunk-LROWZ6UF.js +1333 -0
  33. package/dist/bundle/chunks/chunk-MOALMQWH.js +9 -0
  34. package/dist/bundle/chunks/chunk-MXIWLMNT.js +8 -0
  35. package/dist/bundle/chunks/chunk-N6VDWLND.js +2 -0
  36. package/dist/bundle/chunks/chunk-NCIBB66G.js +2 -0
  37. package/dist/bundle/chunks/chunk-NDQ5OW6U.js +2 -0
  38. package/dist/bundle/chunks/chunk-O6JSP6YG.js +6 -0
  39. package/dist/bundle/chunks/chunk-OFST7FDG.js +2 -0
  40. package/dist/bundle/chunks/chunk-SPAUY3RD.js +12 -0
  41. package/dist/bundle/chunks/chunk-UZWP3NHW.js +2 -0
  42. package/dist/bundle/chunks/chunk-V5ANFNKF.js +11 -0
  43. package/dist/bundle/chunks/chunk-VJJ6J35N.js +20 -0
  44. package/dist/bundle/chunks/chunk-ZW7FVRHT.js +31 -0
  45. package/dist/bundle/chunks/cli-DFJTSQI6.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-7O2AHLAQ.js +2 -0
  50. package/dist/bundle/chunks/execute-4CLOTQIS.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-IN7ZPKFY.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-7VXI3TVN.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 +16 -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 +225 -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 +420 -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 +195 -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,1076 @@
1
+ import * as fs from "node:fs";
2
+ import * as path from "node:path";
3
+ import {
4
+ backgroundAnsi,
5
+ type Color,
6
+ colorToHex,
7
+ colorToOklch,
8
+ type EditorTheme,
9
+ foregroundAnsi,
10
+ getTerminalColorMode,
11
+ indexedColor,
12
+ type MarkdownTheme,
13
+ mixColors,
14
+ parseColor,
15
+ type RgbColor,
16
+ rgbColor,
17
+ type SelectListTheme,
18
+ type SettingsListTheme,
19
+ styleTextWithAnsi,
20
+ type TerminalColorMode,
21
+ type TerminalColors,
22
+ type TextAttributes,
23
+ } from "@knightcode/tui";
24
+ import chalk from "chalk";
25
+ import { getCustomThemesDir, getThemesDir } from "../../../config.ts";
26
+ import type { SourceInfo } from "../../../core/source-info.ts";
27
+ import { closeWatcher, watchWithErrorHandler } from "../../../utils/fs-watch.ts";
28
+ import { highlight, supportsLanguage } from "../../../utils/syntax-highlight.ts";
29
+ import { stripBom } from "../../../utils/text.ts";
30
+ import { generateSystemThemeColors, SYSTEM_THEME_NAME, terminalAppearance } from "./system-theme.ts";
31
+ import {
32
+ type ResolvedThemeColorValues,
33
+ THEME_TOKENS,
34
+ type ThemeBg,
35
+ type ThemeColor,
36
+ type ThemeColorValues,
37
+ type ThemeToken,
38
+ } from "./theme-tokens.ts";
39
+
40
+ export { SYSTEM_THEME_NAME } from "./system-theme.ts";
41
+
42
+ // ============================================================================
43
+ // Types & Schema
44
+ // ============================================================================
45
+
46
+ /** The schema that validates this shape lives in `theme-schema.ts`; importing the type is free. */
47
+ import type { ThemeColorValue as ColorValue, ValidatedThemeJson as ThemeJson } from "./theme-schema.ts";
48
+
49
+ export type { ValidatedThemeJson as ThemeJson } from "./theme-schema.ts";
50
+ export type { ThemeBg, ThemeColor, ThemeToken } from "./theme-tokens.ts";
51
+
52
+ /**
53
+ * Tokens are only accepted in their own slot, because "" (terminal default) means the default foreground
54
+ * or background depending on the slot. Use `theme.colors[token]` to use a token's color in the other slot.
55
+ */
56
+ export interface ThemeStyle extends TextAttributes {
57
+ fg?: ThemeColor | Color;
58
+ bg?: ThemeBg | Color;
59
+ }
60
+
61
+ export type ThemeJsonValidator = (label: string, json: unknown) => ThemeJson;
62
+
63
+ let themeJsonValidator: ThemeJsonValidator | undefined;
64
+
65
+ /**
66
+ * Install full theme validation. Without it, documents are accepted as-is, which is what built-in
67
+ * themes already do: validating user-authored JSON needs typebox, and a presentation that only uses
68
+ * built-in themes should not pay ~17 MB of module graph for it.
69
+ */
70
+ export function setThemeJsonValidator(validator: ThemeJsonValidator): void {
71
+ themeJsonValidator = validator;
72
+ }
73
+
74
+ // ============================================================================
75
+ // Color Utilities
76
+ // ============================================================================
77
+
78
+ function resolveVarRefs(
79
+ value: ColorValue,
80
+ vars: Record<string, ColorValue>,
81
+ visited = new Set<string>(),
82
+ ): string | number {
83
+ if (typeof value === "number" || value === "" || value.startsWith("#") || /^ok(lch|hsl)\(/i.test(value)) {
84
+ return value;
85
+ }
86
+ if (visited.has(value)) {
87
+ throw new Error(`Circular variable reference detected: ${value}`);
88
+ }
89
+ if (!(value in vars)) {
90
+ throw new Error(`Variable reference not found: ${value}`);
91
+ }
92
+ visited.add(value);
93
+ return resolveVarRefs(vars[value], vars, visited);
94
+ }
95
+
96
+ function resolveThemeColors<T extends Record<string, ColorValue>>(
97
+ colors: T,
98
+ vars: Record<string, ColorValue> = {},
99
+ ): Record<keyof T, string | number> {
100
+ const resolved: Record<string, string | number> = {};
101
+ for (const [key, value] of Object.entries(colors)) {
102
+ resolved[key] = resolveVarRefs(value, vars);
103
+ }
104
+ return resolved as Record<keyof T, string | number>;
105
+ }
106
+
107
+ function withThemeTokenFallbacks<Value>(values: ThemeColorValues<Value>): ResolvedThemeColorValues<Value> {
108
+ const resolved = { ...values } as Partial<ResolvedThemeColorValues<Value>>;
109
+ for (const [rawName, descriptor] of Object.entries(THEME_TOKENS)) {
110
+ if (!("fallback" in descriptor)) continue;
111
+ const name = rawName as ThemeToken;
112
+ if (resolved[name] !== undefined) continue;
113
+ const fallback = descriptor.fallback as ThemeToken;
114
+ const fallbackValue = resolved[fallback];
115
+ if (fallbackValue === undefined) {
116
+ throw new Error(`Theme token ${rawName} has unresolved fallback ${descriptor.fallback}`);
117
+ }
118
+ resolved[name] = fallbackValue;
119
+ }
120
+ return resolved as ResolvedThemeColorValues<Value>;
121
+ }
122
+
123
+ // ============================================================================
124
+ // Appearance & Terminal Default Colors
125
+ // ============================================================================
126
+
127
+ /** The background a theme is designed for. */
128
+ export type ThemeAppearance = TerminalTheme;
129
+
130
+ // The terminal's reported colors. Replaced (never mutated) on update, so themes can cache resolved colors
131
+ // by identity.
132
+ let terminalColors: TerminalColors = {};
133
+ // While the terminal color query is in flight, the system theme renders in grayscale.
134
+ let terminalColorsPending = false;
135
+ // The terminal's last light/dark report (mode 2031). Only used while it has not reported a background.
136
+ let terminalColorScheme: TerminalTheme | undefined;
137
+
138
+ /**
139
+ * Record the terminal's reported colors. Themes use the default colors for tokens set to "" (terminal
140
+ * default); the system theme is generated from all of them. Ends the pending state.
141
+ */
142
+ export function setTerminalColors(colors: TerminalColors): void {
143
+ terminalColors = { ...colors };
144
+ terminalColorsPending = false;
145
+ }
146
+
147
+ /** Record the terminal's light/dark report, the fallback for terminals that do not report their background. */
148
+ export function setTerminalColorScheme(scheme: TerminalTheme | undefined): void {
149
+ terminalColorScheme = scheme;
150
+ }
151
+
152
+ /** Render the system theme in grayscale until `setTerminalColors()` reports the terminal's colors. */
153
+ export function markTerminalColorsPending(): void {
154
+ terminalColorsPending = true;
155
+ }
156
+
157
+ /** Assumed terminal default colors when the terminal does not report them. */
158
+ const GUESSED_DEFAULT_COLORS: Record<ThemeAppearance, { foreground: Color; background: Color }> = {
159
+ dark: { foreground: parseColor("#e5e5e7"), background: parseColor("#000000") },
160
+ light: { foreground: parseColor("#000000"), background: parseColor("#ffffff") },
161
+ };
162
+
163
+ function averageLightness(colors: Color[]): number | undefined {
164
+ // Palette colors 0-15 follow the user's terminal palette, so they say nothing about the theme.
165
+ const fixed = colors.filter((color) => color.kind !== "indexed" || color.index >= 16);
166
+ if (fixed.length === 0) return undefined;
167
+ return fixed.reduce((sum, color) => sum + colorToOklch(color).l, 0) / fixed.length;
168
+ }
169
+
170
+ /** Detect the background a theme is designed for from the lightness of its own colors. */
171
+ function detectAppearance(foregrounds: Color[], backgrounds: Color[]): ThemeAppearance | undefined {
172
+ const fg = averageLightness(foregrounds);
173
+ const bg = averageLightness(backgrounds);
174
+ if (fg !== undefined && bg !== undefined) return bg < fg ? "dark" : "light";
175
+ if (bg !== undefined) return bg < 0.5 ? "dark" : "light";
176
+ if (fg !== undefined) return fg > 0.5 ? "dark" : "light";
177
+ return undefined;
178
+ }
179
+
180
+ // ============================================================================
181
+ // Theme Class
182
+ // ============================================================================
183
+
184
+ export class Theme {
185
+ readonly name?: string;
186
+ readonly sourcePath?: string;
187
+ sourceInfo?: SourceInfo;
188
+ private mode: TerminalColorMode;
189
+ // Precomputed escape sequences keep fg()/bg() on the render hot path to a lookup and concat.
190
+ private readonly fgAnsi = new Map<ThemeColor, string>();
191
+ private readonly bgAnsi = new Map<ThemeBg, string>();
192
+ // Tokens set to "" have no color of their own; `colors` fills them from the terminal defaults.
193
+ private readonly concreteColors: Partial<Record<ThemeToken, Color>> = {};
194
+ private readonly defaultForegroundTokens: ThemeToken[] = [];
195
+ private readonly defaultBackgroundTokens: ThemeToken[] = [];
196
+ // Foreground tokens rendered faint (SGR 2) on top of their color.
197
+ private readonly dimTokens: ReadonlySet<ThemeColor>;
198
+ private readonly ownAppearance: ThemeAppearance | undefined;
199
+ private resolvedColors: { terminal: TerminalColors; colors: Readonly<Record<ThemeToken, Color>> } | undefined;
200
+ private editorBorderAnsi: { colors: Readonly<Record<ThemeToken, Color>>; ansi: string } | undefined;
201
+ private readonly editorBorderColor = (str: string): string => {
202
+ const colors = this.colors;
203
+ // Terminal colour reports replace the resolved palette, invalidating this derived escape sequence.
204
+ if (this.editorBorderAnsi?.colors !== colors) {
205
+ this.editorBorderAnsi = {
206
+ colors,
207
+ ansi: foregroundAnsi(mixColors(colors.border, colors.text, 0.35), this.mode),
208
+ };
209
+ }
210
+ return `${this.editorBorderAnsi.ansi}${str}\x1b[39m`;
211
+ };
212
+
213
+ constructor(
214
+ fgColors: Pick<ThemeColorValues<string | number>, ThemeColor>,
215
+ bgColors: Pick<ThemeColorValues<string | number>, ThemeBg>,
216
+ mode: TerminalColorMode,
217
+ options: {
218
+ name?: string;
219
+ sourcePath?: string;
220
+ sourceInfo?: SourceInfo;
221
+ appearance?: ThemeAppearance;
222
+ /** Foreground tokens to render faint (SGR 2). */
223
+ dim?: readonly ThemeColor[];
224
+ } = {},
225
+ ) {
226
+ this.name = options.name;
227
+ this.sourcePath = options.sourcePath;
228
+ this.sourceInfo = options.sourceInfo;
229
+ this.mode = mode;
230
+ this.dimTokens = new Set(options.dim);
231
+ const { fgColors: foregrounds, bgColors: backgrounds } = splitThemeColors(
232
+ withThemeTokenFallbacks({ ...fgColors, ...bgColors }),
233
+ );
234
+ const concreteForegrounds: Color[] = [];
235
+ const concreteBackgrounds: Color[] = [];
236
+ // Returns the escape sequence for the token's own slot.
237
+ const addToken = (token: ThemeToken, value: string | number, isBackground: boolean): string => {
238
+ if (value === "") {
239
+ (isBackground ? this.defaultBackgroundTokens : this.defaultForegroundTokens).push(token);
240
+ return isBackground ? "\x1b[49m" : "\x1b[39m";
241
+ }
242
+ const color = parseColor(value);
243
+ this.concreteColors[token] = color;
244
+ (isBackground ? concreteBackgrounds : concreteForegrounds).push(color);
245
+ return isBackground ? backgroundAnsi(color, mode) : foregroundAnsi(color, mode);
246
+ };
247
+ for (const [token, value] of Object.entries(foregrounds) as [ThemeColor, string | number][]) {
248
+ this.fgAnsi.set(token, addToken(token, value, false));
249
+ }
250
+ for (const [token, value] of Object.entries(backgrounds) as [ThemeBg, string | number][]) {
251
+ this.bgAnsi.set(token, addToken(token, value, true));
252
+ }
253
+ this.ownAppearance = options.appearance ?? detectAppearance(concreteForegrounds, concreteBackgrounds);
254
+ }
255
+
256
+ /**
257
+ * The background the theme is designed for: declared in the theme JSON, detected from its colors,
258
+ * or, for themes without usable colors, the terminal's appearance.
259
+ */
260
+ get appearance(): ThemeAppearance {
261
+ return this.ownAppearance ?? getTerminalTheme();
262
+ }
263
+
264
+ /**
265
+ * Concrete colors for all tokens. Tokens set to "" (terminal default) use the terminal's reported
266
+ * default colors, or a guess based on `appearance` when the terminal did not report them. Faint
267
+ * tokens are approximated by mixing their color toward the background.
268
+ */
269
+ get colors(): Readonly<Record<ThemeToken, Color>> {
270
+ const terminal = terminalColors;
271
+ if (this.resolvedColors?.terminal !== terminal) {
272
+ const guess = GUESSED_DEFAULT_COLORS[this.appearance];
273
+ const toColor = (rgb: RgbColor | undefined, fallback: Color) => (rgb ? rgbColor(rgb.r, rgb.g, rgb.b) : fallback);
274
+ const foreground = toColor(terminal.foreground, guess.foreground);
275
+ const background = toColor(terminal.background, guess.background);
276
+ const colors = { ...this.concreteColors };
277
+ for (const token of this.defaultForegroundTokens) colors[token] = foreground;
278
+ for (const token of this.defaultBackgroundTokens) colors[token] = background;
279
+ for (const token of this.dimTokens) {
280
+ const color = colors[token];
281
+ if (color) colors[token] = mixColors(color, background, 0.4);
282
+ }
283
+ this.resolvedColors = { terminal, colors: Object.freeze(colors as Record<ThemeToken, Color>) };
284
+ }
285
+ return this.resolvedColors.colors;
286
+ }
287
+
288
+ style(text: string, options: ThemeStyle): string {
289
+ const { fg, bg } = options;
290
+ if (typeof fg === "string" && this.dimTokens.has(fg)) options = { ...options, dim: true };
291
+ return styleTextWithAnsi(
292
+ text,
293
+ fg === undefined
294
+ ? undefined
295
+ : typeof fg === "string"
296
+ ? this.tokenAnsi(this.fgAnsi, fg)
297
+ : foregroundAnsi(fg, this.mode),
298
+ bg === undefined
299
+ ? undefined
300
+ : typeof bg === "string"
301
+ ? this.tokenAnsi(this.bgAnsi, bg)
302
+ : backgroundAnsi(bg, this.mode),
303
+ options,
304
+ );
305
+ }
306
+
307
+ fg(color: ThemeColor, text: string): string {
308
+ const ansi = this.tokenAnsi(this.fgAnsi, color);
309
+ if (this.dimTokens.has(color)) return `${ansi}\x1b[2m${text}\x1b[22;39m`;
310
+ return `${ansi}${text}\x1b[39m`;
311
+ }
312
+
313
+ bg(color: ThemeBg, text: string): string {
314
+ const ansi = this.tokenAnsi(this.bgAnsi, color);
315
+ return `${ansi}${text}\x1b[49m`;
316
+ }
317
+
318
+ private tokenAnsi<T extends ThemeToken>(ansi: Map<T, string>, token: T): string {
319
+ const value = ansi.get(token);
320
+ if (value === undefined) throw new Error(`Unknown theme color: ${token}`);
321
+ return value;
322
+ }
323
+
324
+ bold(text: string): string {
325
+ return chalk.bold(text);
326
+ }
327
+
328
+ italic(text: string): string {
329
+ return chalk.italic(text);
330
+ }
331
+
332
+ underline(text: string): string {
333
+ return chalk.underline(text);
334
+ }
335
+
336
+ inverse(text: string): string {
337
+ return chalk.inverse(text);
338
+ }
339
+
340
+ strikethrough(text: string): string {
341
+ return chalk.strikethrough(text);
342
+ }
343
+
344
+ /** Opening escape sequence for a foreground token. Faint tokens include SGR 2, which `\x1b[22m` closes. */
345
+ getFgAnsi(color: ThemeColor): string {
346
+ const ansi = this.tokenAnsi(this.fgAnsi, color);
347
+ return this.dimTokens.has(color) ? `${ansi}\x1b[2m` : ansi;
348
+ }
349
+
350
+ getBgAnsi(color: ThemeBg): string {
351
+ return this.tokenAnsi(this.bgAnsi, color);
352
+ }
353
+
354
+ getColorMode(): TerminalColorMode {
355
+ return this.mode;
356
+ }
357
+
358
+ getEditorBorderColor(): (str: string) => string {
359
+ return this.editorBorderColor;
360
+ }
361
+
362
+ getBashModeBorderColor(): (str: string) => string {
363
+ return (str: string) => this.fg("bashMode", str);
364
+ }
365
+ }
366
+
367
+ // ============================================================================
368
+ // Theme Loading
369
+ // ============================================================================
370
+
371
+ let BUILTIN_THEMES: Record<string, ThemeJson> | undefined;
372
+
373
+ function getBuiltinThemes(): Record<string, ThemeJson> {
374
+ if (!BUILTIN_THEMES) {
375
+ const themesDir = getThemesDir();
376
+ const darkPath = path.join(themesDir, "dark.json");
377
+ const lightPath = path.join(themesDir, "light.json");
378
+ BUILTIN_THEMES = {
379
+ dark: JSON.parse(stripBom(fs.readFileSync(darkPath, "utf-8"))) as ThemeJson,
380
+ light: JSON.parse(stripBom(fs.readFileSync(lightPath, "utf-8"))) as ThemeJson,
381
+ };
382
+ }
383
+ return BUILTIN_THEMES;
384
+ }
385
+
386
+ export function getAvailableThemes(): string[] {
387
+ return getAvailableThemesWithPaths().map(({ name }) => name);
388
+ }
389
+
390
+ export interface ThemeInfo {
391
+ name: string;
392
+ path: string | undefined;
393
+ }
394
+
395
+ export function getAvailableThemesWithPaths(): ThemeInfo[] {
396
+ const themesDir = getThemesDir();
397
+ const result: ThemeInfo[] = [];
398
+ const seen = new Set<string>();
399
+ const addTheme = (themeInfo: ThemeInfo) => {
400
+ if (seen.has(themeInfo.name)) {
401
+ return;
402
+ }
403
+ seen.add(themeInfo.name);
404
+ result.push(themeInfo);
405
+ };
406
+
407
+ // Built-in themes. The system theme is generated, so it has no file.
408
+ addTheme({ name: SYSTEM_THEME_NAME, path: undefined });
409
+ for (const name of Object.keys(getBuiltinThemes())) {
410
+ addTheme({ name, path: path.join(themesDir, `${name}.json`) });
411
+ }
412
+
413
+ // Custom themes
414
+ for (const themeInfo of getCustomThemeInfos()) {
415
+ addTheme(themeInfo);
416
+ }
417
+
418
+ for (const [name, theme] of registeredThemes.entries()) {
419
+ addTheme({ name, path: theme.sourcePath });
420
+ }
421
+
422
+ // The system theme comes first: it is the default and adapts to every terminal.
423
+ return result.sort((a, b) =>
424
+ a.name === SYSTEM_THEME_NAME ? -1 : b.name === SYSTEM_THEME_NAME ? 1 : a.name.localeCompare(b.name),
425
+ );
426
+ }
427
+
428
+ function getCustomThemeInfos(): ThemeInfo[] {
429
+ const customThemesDir = getCustomThemesDir();
430
+ const result: ThemeInfo[] = [];
431
+ if (!fs.existsSync(customThemesDir)) {
432
+ return result;
433
+ }
434
+
435
+ for (const file of fs.readdirSync(customThemesDir)) {
436
+ if (!file.endsWith(".json")) {
437
+ continue;
438
+ }
439
+ const themePath = path.join(customThemesDir, file);
440
+ try {
441
+ const customTheme = loadThemeFromPath(themePath);
442
+ if (customTheme.name) {
443
+ result.push({ name: customTheme.name, path: themePath });
444
+ }
445
+ } catch {
446
+ // Invalid themes are ignored here; the resource loader reports them
447
+ // during normal startup/reload.
448
+ }
449
+ }
450
+ return result;
451
+ }
452
+
453
+ function assertThemeNameIsValid(name: string): void {
454
+ if (name.includes("/")) {
455
+ throw new Error(
456
+ `Invalid theme name "${name}": theme names cannot contain "/" because it is reserved for automatic light/dark theme settings.`,
457
+ );
458
+ }
459
+ }
460
+
461
+ function parseThemeJson(label: string, json: unknown): ThemeJson {
462
+ if (themeJsonValidator) return themeJsonValidator(label, json);
463
+ if (typeof json !== "object" || json === null || !("colors" in json)) {
464
+ throw new Error(`Invalid theme "${label}": expected an object with a "colors" map.`);
465
+ }
466
+ return json as ThemeJson;
467
+ }
468
+
469
+ function parseThemeJsonContent(label: string, content: string): ThemeJson {
470
+ let json: unknown;
471
+ try {
472
+ json = JSON.parse(stripBom(content));
473
+ } catch (error) {
474
+ throw new Error(`Failed to parse theme ${label}: ${error}`);
475
+ }
476
+ return parseThemeJson(label, json);
477
+ }
478
+
479
+ function loadThemeJson(name: string): ThemeJson {
480
+ const builtinThemes = getBuiltinThemes();
481
+ if (name in builtinThemes) {
482
+ return builtinThemes[name];
483
+ }
484
+ const registeredTheme = registeredThemes.get(name);
485
+ if (registeredTheme?.sourcePath) {
486
+ const content = fs.readFileSync(registeredTheme.sourcePath, "utf-8");
487
+ return parseThemeJsonContent(registeredTheme.sourcePath, content);
488
+ }
489
+ if (registeredTheme) {
490
+ throw new Error(`Theme "${name}" does not have a source path for export`);
491
+ }
492
+ const customThemesDir = getCustomThemesDir();
493
+ const themePath = path.join(customThemesDir, `${name}.json`);
494
+ if (!fs.existsSync(themePath)) {
495
+ throw new Error(`Theme not found: ${name}`);
496
+ }
497
+ const content = fs.readFileSync(themePath, "utf-8");
498
+ return parseThemeJsonContent(name, content);
499
+ }
500
+
501
+ function splitThemeColors(colors: ResolvedThemeColorValues<string | number>): {
502
+ fgColors: Record<ThemeColor, string | number>;
503
+ bgColors: Record<ThemeBg, string | number>;
504
+ } {
505
+ const fgColors = {} as Record<ThemeColor, string | number>;
506
+ const bgColors = {} as Record<ThemeBg, string | number>;
507
+ for (const [key, value] of Object.entries(colors)) {
508
+ if (THEME_TOKENS[key as ThemeToken].slot === "background") {
509
+ bgColors[key as ThemeBg] = value;
510
+ } else {
511
+ fgColors[key as ThemeColor] = value;
512
+ }
513
+ }
514
+ return { fgColors, bgColors };
515
+ }
516
+
517
+ function createTheme(themeJson: ThemeJson, mode?: TerminalColorMode, sourcePath?: string): Theme {
518
+ const colorMode = mode ?? getTerminalColorMode();
519
+ const resolvedColors = withThemeTokenFallbacks(resolveThemeColors(themeJson.colors, themeJson.vars));
520
+ const { fgColors, bgColors } = splitThemeColors(resolvedColors);
521
+ return new Theme(fgColors, bgColors, colorMode, {
522
+ name: themeJson.name,
523
+ sourcePath,
524
+ appearance: themeJson.appearance,
525
+ });
526
+ }
527
+
528
+ /** Generate the system theme from the terminal's reported colors (grayscale while they are pending). */
529
+ function createSystemTheme(mode?: TerminalColorMode): Theme {
530
+ const generated = generateSystemThemeColors({
531
+ ...terminalColors,
532
+ saturation: terminalColorsPending ? 0 : 1,
533
+ appearanceHint: getTerminalTheme(),
534
+ });
535
+ const { fgColors, bgColors } = splitThemeColors(withThemeTokenFallbacks(generated.colors));
536
+ return new Theme(fgColors, bgColors, mode ?? getTerminalColorMode(), {
537
+ name: SYSTEM_THEME_NAME,
538
+ appearance: generated.appearance,
539
+ dim: generated.dim,
540
+ });
541
+ }
542
+
543
+ export function loadThemeFromPath(themePath: string, mode?: TerminalColorMode): Theme {
544
+ const content = fs.readFileSync(themePath, "utf-8");
545
+ const themeJson = parseThemeJsonContent(themePath, content);
546
+ return createTheme(themeJson, mode, themePath);
547
+ }
548
+
549
+ function loadTheme(name: string, mode?: TerminalColorMode): Theme {
550
+ // The system theme name is reserved: it takes precedence over custom themes of the same name.
551
+ if (name === SYSTEM_THEME_NAME) return createSystemTheme(mode);
552
+ const registeredTheme = registeredThemes.get(name);
553
+ if (registeredTheme) {
554
+ return registeredTheme;
555
+ }
556
+ const themeJson = loadThemeJson(name);
557
+ return createTheme(themeJson, mode);
558
+ }
559
+
560
+ export function getThemeByName(name: string): Theme | undefined {
561
+ try {
562
+ return loadTheme(name);
563
+ } catch {
564
+ return undefined;
565
+ }
566
+ }
567
+
568
+ export type TerminalTheme = "dark" | "light";
569
+
570
+ export function parseAutoThemeSetting(
571
+ themeSetting: string | undefined,
572
+ ): { lightTheme: string; darkTheme: string } | undefined {
573
+ if (!themeSetting) return undefined;
574
+ const slashIndex = themeSetting.indexOf("/");
575
+ if (slashIndex === -1 || themeSetting.indexOf("/", slashIndex + 1) !== -1) {
576
+ return undefined;
577
+ }
578
+
579
+ const lightTheme = themeSetting.slice(0, slashIndex).trim();
580
+ const darkTheme = themeSetting.slice(slashIndex + 1).trim();
581
+ if (!lightTheme || !darkTheme) {
582
+ return undefined;
583
+ }
584
+ return { lightTheme, darkTheme };
585
+ }
586
+
587
+ export function resolveThemeSetting(
588
+ themeSetting: string | undefined,
589
+ terminalTheme: TerminalTheme,
590
+ ): string | undefined {
591
+ const autoTheme = parseAutoThemeSetting(themeSetting);
592
+ if (autoTheme) {
593
+ return terminalTheme === "light" ? autoTheme.lightTheme : autoTheme.darkTheme;
594
+ }
595
+ if (themeSetting?.includes("/")) return undefined;
596
+ if (typeof themeSetting === "string") return themeSetting;
597
+ return undefined;
598
+ }
599
+
600
+ /**
601
+ * Dark or light from the `COLORFGBG` environment variable some terminals set, or undefined without a
602
+ * usable background index. The value is `fg;bg` or `fg;xpm;bg` (rxvt), where a field is an ANSI color
603
+ * index or `default` when the color is not in the palette. The index refers to the terminal's own palette,
604
+ * whose colors are unknown here, so it is classified by index like Vim does: 0-6 and 8 (bright black, e.g.
605
+ * Solarized Dark's background) are dark, 7 and 9-15 are light.
606
+ */
607
+ export function detectColorFgBgTheme(env: NodeJS.ProcessEnv = process.env): TerminalTheme | undefined {
608
+ const bg = env.COLORFGBG?.split(";").at(-1)?.trim();
609
+ if (!bg || !/^\d{1,2}$/.test(bg)) return undefined;
610
+ const index = Number(bg);
611
+ if (index > 15) return undefined;
612
+ return index <= 6 || index === 8 ? "dark" : "light";
613
+ }
614
+
615
+ /**
616
+ * Whether the terminal is dark or light. The background it renders decides, classified the same way the
617
+ * system theme does. Without a reported background: the terminal's light/dark report, then COLORFGBG,
618
+ * then dark.
619
+ */
620
+ export function detectTerminalTheme(
621
+ colors: TerminalColors = {},
622
+ reportedScheme?: TerminalTheme,
623
+ env: NodeJS.ProcessEnv = process.env,
624
+ ): TerminalTheme {
625
+ const { background, foreground } = colors;
626
+ if (background) return terminalAppearance(background, foreground);
627
+ return reportedScheme ?? detectColorFgBgTheme(env) ?? "dark";
628
+ }
629
+
630
+ /** Whether the terminal is dark or light, from everything it reported so far. See `detectTerminalTheme()`. */
631
+ export function getTerminalTheme(): TerminalTheme {
632
+ return detectTerminalTheme(terminalColors, terminalColorScheme);
633
+ }
634
+
635
+ // ============================================================================
636
+ // Global Theme Instance
637
+ // ============================================================================
638
+
639
+ // Use globalThis to share theme across module loaders (node + jiti in dev mode)
640
+ const THEME_KEY = Symbol.for("@knightcodeai/cli:theme");
641
+
642
+ // Export theme as a getter that reads from globalThis
643
+ // This ensures all module instances (node, jiti) see the same theme
644
+ export const theme: Theme = new Proxy({} as Theme, {
645
+ get(_target, prop) {
646
+ const t = (globalThis as Record<symbol, Theme>)[THEME_KEY];
647
+ if (!t) throw new Error("Theme not initialized. Call initTheme() first.");
648
+ return (t as unknown as Record<string | symbol, unknown>)[prop];
649
+ },
650
+ });
651
+
652
+ function setGlobalTheme(t: Theme): void {
653
+ (globalThis as Record<symbol, Theme>)[THEME_KEY] = t;
654
+ }
655
+
656
+ let currentThemeName: string | undefined;
657
+ let themeWatcher: fs.FSWatcher | undefined;
658
+ let themeReloadTimer: NodeJS.Timeout | undefined;
659
+ let onThemeChangeCallback: (() => void) | undefined;
660
+ const registeredThemes = new Map<string, Theme>();
661
+
662
+ export function setRegisteredThemes(themes: Theme[]): void {
663
+ registeredThemes.clear();
664
+ for (const theme of themes) {
665
+ if (theme.name) {
666
+ assertThemeNameIsValid(theme.name);
667
+ registeredThemes.set(theme.name, theme);
668
+ }
669
+ }
670
+ }
671
+
672
+ export function initTheme(themeName?: string, enableWatcher: boolean = false): void {
673
+ const name = themeName ?? SYSTEM_THEME_NAME;
674
+ currentThemeName = name;
675
+ try {
676
+ setGlobalTheme(loadTheme(name));
677
+ if (enableWatcher) {
678
+ startThemeWatcher();
679
+ }
680
+ } catch (_error) {
681
+ // Theme is invalid - fall back to the system theme silently
682
+ currentThemeName = SYSTEM_THEME_NAME;
683
+ setGlobalTheme(loadTheme(SYSTEM_THEME_NAME));
684
+ // Don't start watcher for fallback theme
685
+ }
686
+ }
687
+
688
+ export function setTheme(name: string, enableWatcher: boolean = false): { success: boolean; error?: string } {
689
+ currentThemeName = name;
690
+ try {
691
+ setGlobalTheme(loadTheme(name));
692
+ if (enableWatcher) {
693
+ startThemeWatcher();
694
+ }
695
+ if (onThemeChangeCallback) {
696
+ onThemeChangeCallback();
697
+ }
698
+ return { success: true };
699
+ } catch (error) {
700
+ // Theme is invalid - fall back to the system theme
701
+ currentThemeName = SYSTEM_THEME_NAME;
702
+ setGlobalTheme(loadTheme(SYSTEM_THEME_NAME));
703
+ // Don't start watcher for fallback theme
704
+ return {
705
+ success: false,
706
+ error: error instanceof Error ? error.message : String(error),
707
+ };
708
+ }
709
+ }
710
+
711
+ export function setThemeInstance(themeInstance: Theme): void {
712
+ setGlobalTheme(themeInstance);
713
+ currentThemeName = "<in-memory>";
714
+ stopThemeWatcher(); // Can't watch a direct instance
715
+ if (onThemeChangeCallback) {
716
+ onThemeChangeCallback();
717
+ }
718
+ }
719
+
720
+ export function onThemeChange(callback: () => void): void {
721
+ onThemeChangeCallback = callback;
722
+ }
723
+
724
+ function startThemeWatcher(): void {
725
+ stopThemeWatcher();
726
+
727
+ // Only watch if it's a custom theme (not built-in)
728
+ if (
729
+ !currentThemeName ||
730
+ currentThemeName === "dark" ||
731
+ currentThemeName === "light" ||
732
+ currentThemeName === SYSTEM_THEME_NAME
733
+ ) {
734
+ return;
735
+ }
736
+
737
+ const customThemesDir = getCustomThemesDir();
738
+ const watchedThemeName = currentThemeName;
739
+ const watchedFileName = `${watchedThemeName}.json`;
740
+ const themeFile = path.join(customThemesDir, watchedFileName);
741
+
742
+ // Only watch if the file exists
743
+ if (!fs.existsSync(themeFile)) {
744
+ return;
745
+ }
746
+
747
+ const scheduleReload = () => {
748
+ if (themeReloadTimer) {
749
+ clearTimeout(themeReloadTimer);
750
+ }
751
+ themeReloadTimer = setTimeout(() => {
752
+ themeReloadTimer = undefined;
753
+
754
+ // Ignore stale timers after switching themes or stopping the watcher
755
+ if (currentThemeName !== watchedThemeName) {
756
+ return;
757
+ }
758
+
759
+ // Keep the last successfully loaded theme active if the file is temporarily missing
760
+ if (!fs.existsSync(themeFile)) {
761
+ return;
762
+ }
763
+
764
+ try {
765
+ // Reload the theme from disk and refresh the registry cache
766
+ const reloadedTheme = loadThemeFromPath(themeFile);
767
+ registeredThemes.set(watchedThemeName, reloadedTheme);
768
+ setGlobalTheme(reloadedTheme);
769
+ // Notify callback (to invalidate UI)
770
+ if (onThemeChangeCallback) {
771
+ onThemeChangeCallback();
772
+ }
773
+ } catch (_error) {
774
+ // Ignore errors (file might be in invalid state while being edited)
775
+ }
776
+ }, 100);
777
+ };
778
+
779
+ themeWatcher =
780
+ watchWithErrorHandler(
781
+ customThemesDir,
782
+ (_eventType, filename) => {
783
+ if (currentThemeName !== watchedThemeName) {
784
+ return;
785
+ }
786
+ if (!filename) {
787
+ scheduleReload();
788
+ return;
789
+ }
790
+ if (filename !== watchedFileName) {
791
+ return;
792
+ }
793
+ scheduleReload();
794
+ },
795
+ () => {
796
+ closeWatcher(themeWatcher);
797
+ themeWatcher = undefined;
798
+ },
799
+ ) ?? undefined;
800
+ }
801
+
802
+ export function stopThemeWatcher(): void {
803
+ if (themeReloadTimer) {
804
+ clearTimeout(themeReloadTimer);
805
+ themeReloadTimer = undefined;
806
+ }
807
+ closeWatcher(themeWatcher);
808
+ themeWatcher = undefined;
809
+ }
810
+
811
+ // ============================================================================
812
+ // HTML Export Helpers
813
+ // ============================================================================
814
+
815
+ /**
816
+ * Get resolved theme colors as CSS-compatible hex strings.
817
+ * Used by HTML export to generate CSS custom properties.
818
+ */
819
+ export function getResolvedThemeColors(themeName?: string): Record<string, string> {
820
+ const colors = loadTheme(themeName ?? currentThemeName ?? SYSTEM_THEME_NAME).colors;
821
+ return Object.fromEntries(Object.entries(colors).map(([token, color]) => [token, colorToHex(color)]));
822
+ }
823
+
824
+ /**
825
+ * Check if a theme is a "light" theme (for CSS that needs light/dark variants).
826
+ */
827
+ export function isLightTheme(themeName?: string): boolean {
828
+ return loadTheme(themeName ?? currentThemeName ?? SYSTEM_THEME_NAME).appearance === "light";
829
+ }
830
+
831
+ /**
832
+ * Get explicit export colors from theme JSON, if specified.
833
+ * Returns undefined for each color that isn't explicitly set.
834
+ */
835
+ export function getThemeExportColors(themeName?: string): {
836
+ pageBg?: string;
837
+ cardBg?: string;
838
+ infoBg?: string;
839
+ } {
840
+ const name = themeName ?? currentThemeName ?? SYSTEM_THEME_NAME;
841
+ if (name === SYSTEM_THEME_NAME) return {};
842
+ try {
843
+ const themeJson = loadThemeJson(name);
844
+ const exportSection = themeJson.export;
845
+ if (!exportSection) return {};
846
+
847
+ const vars = themeJson.vars ?? {};
848
+ // Export colors end up in CSS, which understands hex and oklch() values directly but not okhsl().
849
+ const resolve = (value: ColorValue | undefined): string | undefined => {
850
+ if (value === undefined) return undefined;
851
+ const resolved = resolveVarRefs(value, vars);
852
+ if (typeof resolved === "number") return colorToHex(indexedColor(resolved));
853
+ if (resolved === "") return undefined;
854
+ if (/^okhsl\(/i.test(resolved)) return colorToHex(parseColor(resolved));
855
+ return resolved;
856
+ };
857
+
858
+ return {
859
+ pageBg: resolve(exportSection.pageBg),
860
+ cardBg: resolve(exportSection.cardBg),
861
+ infoBg: resolve(exportSection.infoBg),
862
+ };
863
+ } catch {
864
+ return {};
865
+ }
866
+ }
867
+
868
+ // ============================================================================
869
+ // TUI Helpers
870
+ // ============================================================================
871
+
872
+ type CliHighlightTheme = Record<string, (s: string) => string>;
873
+
874
+ let cachedHighlightThemeFor: Theme | undefined;
875
+ let cachedCliHighlightTheme: CliHighlightTheme | undefined;
876
+
877
+ function buildCliHighlightTheme(t: Theme): CliHighlightTheme {
878
+ return {
879
+ keyword: (s: string) => t.fg("syntaxKeyword", s),
880
+ built_in: (s: string) => t.fg("syntaxType", s),
881
+ literal: (s: string) => t.fg("syntaxNumber", s),
882
+ number: (s: string) => t.fg("syntaxNumber", s),
883
+ regexp: (s: string) => t.fg("syntaxString", s),
884
+ string: (s: string) => t.fg("syntaxString", s),
885
+ subst: (s: string) => t.fg("text", s),
886
+ comment: (s: string) => t.fg("syntaxComment", s),
887
+ doctag: (s: string) => t.fg("syntaxComment", s),
888
+ meta: (s: string) => t.fg("muted", s),
889
+ function: (s: string) => t.fg("syntaxFunction", s),
890
+ title: (s: string) => t.fg("syntaxFunction", s),
891
+ class: (s: string) => t.fg("syntaxType", s),
892
+ type: (s: string) => t.fg("syntaxType", s),
893
+ tag: (s: string) => t.fg("syntaxPunctuation", s),
894
+ name: (s: string) => t.fg("syntaxKeyword", s),
895
+ attr: (s: string) => t.fg("syntaxVariable", s),
896
+ variable: (s: string) => t.fg("syntaxVariable", s),
897
+ params: (s: string) => t.fg("syntaxVariable", s),
898
+ operator: (s: string) => t.fg("syntaxOperator", s),
899
+ punctuation: (s: string) => t.fg("syntaxPunctuation", s),
900
+ emphasis: (s: string) => t.italic(s),
901
+ strong: (s: string) => t.bold(s),
902
+ link: (s: string) => t.underline(s),
903
+ addition: (s: string) => t.fg("toolDiffAdded", s),
904
+ deletion: (s: string) => t.fg("toolDiffRemoved", s),
905
+ };
906
+ }
907
+
908
+ function getCliHighlightTheme(t: Theme): CliHighlightTheme {
909
+ if (cachedHighlightThemeFor !== t || !cachedCliHighlightTheme) {
910
+ cachedHighlightThemeFor = t;
911
+ cachedCliHighlightTheme = buildCliHighlightTheme(t);
912
+ }
913
+ return cachedCliHighlightTheme;
914
+ }
915
+
916
+ /**
917
+ * Highlight code with syntax coloring based on file extension or language.
918
+ * Returns array of highlighted lines.
919
+ */
920
+ export function highlightCode(code: string, lang?: string): string[] {
921
+ // Validate language before highlighting to avoid stderr spam from cli-highlight
922
+ const validLang = lang && supportsLanguage(lang) ? lang : undefined;
923
+ // Skip highlighting when no valid language is specified. cli-highlight's
924
+ // auto-detection is unreliable and can misidentify prose as AppleScript,
925
+ // LiveCodeServer, etc., coloring random English words as keywords.
926
+ if (!validLang) {
927
+ return code.split("\n").map((line) => theme.fg("mdCodeBlock", line));
928
+ }
929
+ const opts = {
930
+ language: validLang,
931
+ ignoreIllegals: true,
932
+ theme: getCliHighlightTheme(theme),
933
+ };
934
+ try {
935
+ return highlight(code, opts).split("\n");
936
+ } catch {
937
+ return code.split("\n");
938
+ }
939
+ }
940
+
941
+ /**
942
+ * Get language identifier from file path extension.
943
+ */
944
+ export function getLanguageFromPath(filePath: string): string | undefined {
945
+ const ext = filePath.split(".").pop()?.toLowerCase();
946
+ if (!ext) return undefined;
947
+
948
+ const extToLang: Record<string, string> = {
949
+ ts: "typescript",
950
+ tsx: "typescript",
951
+ js: "javascript",
952
+ jsx: "javascript",
953
+ mjs: "javascript",
954
+ cjs: "javascript",
955
+ py: "python",
956
+ rb: "ruby",
957
+ rs: "rust",
958
+ go: "go",
959
+ java: "java",
960
+ kt: "kotlin",
961
+ swift: "swift",
962
+ c: "c",
963
+ h: "c",
964
+ cpp: "cpp",
965
+ cc: "cpp",
966
+ cxx: "cpp",
967
+ hpp: "cpp",
968
+ cs: "csharp",
969
+ php: "php",
970
+ sh: "bash",
971
+ bash: "bash",
972
+ zsh: "bash",
973
+ fish: "fish",
974
+ ps1: "powershell",
975
+ sql: "sql",
976
+ html: "html",
977
+ htm: "html",
978
+ css: "css",
979
+ scss: "scss",
980
+ sass: "sass",
981
+ less: "less",
982
+ json: "json",
983
+ yaml: "yaml",
984
+ yml: "yaml",
985
+ toml: "toml",
986
+ xml: "xml",
987
+ md: "markdown",
988
+ markdown: "markdown",
989
+ dockerfile: "dockerfile",
990
+ makefile: "makefile",
991
+ cmake: "cmake",
992
+ lua: "lua",
993
+ perl: "perl",
994
+ r: "r",
995
+ scala: "scala",
996
+ clj: "clojure",
997
+ ex: "elixir",
998
+ exs: "elixir",
999
+ erl: "erlang",
1000
+ hs: "haskell",
1001
+ ml: "ocaml",
1002
+ vim: "vim",
1003
+ graphql: "graphql",
1004
+ proto: "protobuf",
1005
+ tf: "hcl",
1006
+ hcl: "hcl",
1007
+ };
1008
+
1009
+ return extToLang[ext];
1010
+ }
1011
+
1012
+ export function getMarkdownTheme(): MarkdownTheme {
1013
+ return {
1014
+ heading: (text: string) => theme.fg("mdHeading", text),
1015
+ link: (text: string) => theme.fg("mdLink", text),
1016
+ linkUrl: (text: string) => theme.fg("mdLinkUrl", text),
1017
+ code: (text: string) => theme.fg("mdCode", text),
1018
+ codeBlock: (text: string) => theme.fg("mdCodeBlock", text),
1019
+ codeBlockBorder: (text: string) => theme.fg("mdCodeBlockBorder", text),
1020
+ quote: (text: string) => theme.fg("mdQuote", text),
1021
+ quoteBorder: (text: string) => theme.fg("mdQuoteBorder", text),
1022
+ hr: (text: string) => theme.fg("mdHr", text),
1023
+ listBullet: (text: string) => theme.fg("mdListBullet", text),
1024
+ bold: (text: string) => theme.bold(text),
1025
+ italic: (text: string) => theme.italic(text),
1026
+ underline: (text: string) => theme.underline(text),
1027
+ strikethrough: (text: string) => theme.strikethrough(text),
1028
+ highlightCode: (code: string, lang?: string): string[] => {
1029
+ // Validate language before highlighting to avoid stderr spam from cli-highlight
1030
+ const validLang = lang && supportsLanguage(lang) ? lang : undefined;
1031
+ // Skip highlighting when no valid language is specified. cli-highlight's
1032
+ // auto-detection is unreliable and can misidentify prose as AppleScript,
1033
+ // LiveCodeServer, etc., coloring random English words as keywords.
1034
+ if (!validLang) {
1035
+ return code.split("\n").map((line) => theme.fg("mdCodeBlock", line));
1036
+ }
1037
+ const opts = {
1038
+ language: validLang,
1039
+ ignoreIllegals: true,
1040
+ theme: getCliHighlightTheme(theme),
1041
+ };
1042
+ try {
1043
+ return highlight(code, opts).split("\n");
1044
+ } catch {
1045
+ return code.split("\n").map((line) => theme.fg("mdCodeBlock", line));
1046
+ }
1047
+ },
1048
+ };
1049
+ }
1050
+
1051
+ export function getSelectListTheme(): SelectListTheme {
1052
+ return {
1053
+ selectedPrefix: (text: string) => theme.fg("accent", text),
1054
+ selectedText: (text: string) => theme.fg("accent", text),
1055
+ description: (text: string) => theme.fg("muted", text),
1056
+ scrollInfo: (text: string) => theme.fg("muted", text),
1057
+ noMatch: (text: string) => theme.fg("muted", text),
1058
+ };
1059
+ }
1060
+
1061
+ export function getEditorTheme(): EditorTheme {
1062
+ return {
1063
+ borderColor: (text: string) => theme.getEditorBorderColor()(text),
1064
+ selectList: getSelectListTheme(),
1065
+ };
1066
+ }
1067
+
1068
+ export function getSettingsListTheme(): SettingsListTheme {
1069
+ return {
1070
+ label: (text: string, selected: boolean) => (selected ? theme.fg("accent", text) : text),
1071
+ value: (text: string, selected: boolean) => (selected ? theme.fg("accent", text) : theme.fg("muted", text)),
1072
+ description: (text: string) => theme.fg("dim", text),
1073
+ cursor: theme.fg("accent", "→ "),
1074
+ hint: (text: string) => theme.fg("dim", text),
1075
+ };
1076
+ }