@dirgha/code 1.22.0 → 1.23.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 (272) hide show
  1. package/CHANGELOG.md +171 -0
  2. package/README.md +8 -4
  3. package/dist/auth/keypool.js +40 -26
  4. package/dist/auth/keypool.js.map +1 -1
  5. package/dist/auth/keystore.js +16 -11
  6. package/dist/auth/keystore.js.map +1 -1
  7. package/dist/cli/config.d.ts +36 -5
  8. package/dist/cli/config.js +31 -3
  9. package/dist/cli/config.js.map +1 -1
  10. package/dist/cli/first-run.js +40 -24
  11. package/dist/cli/first-run.js.map +1 -1
  12. package/dist/cli/flows/wizard.js +12 -18
  13. package/dist/cli/flows/wizard.js.map +1 -1
  14. package/dist/cli/interactive.d.ts +4 -0
  15. package/dist/cli/interactive.js +45 -1
  16. package/dist/cli/interactive.js.map +1 -1
  17. package/dist/cli/main.js +69 -18
  18. package/dist/cli/main.js.map +1 -1
  19. package/dist/cli/slash/fleet.js +19 -1
  20. package/dist/cli/slash/fleet.js.map +1 -1
  21. package/dist/cli/slash/index.d.ts +2 -1
  22. package/dist/cli/slash/index.js +3 -1
  23. package/dist/cli/slash/index.js.map +1 -1
  24. package/dist/cli/slash/models.js +4 -2
  25. package/dist/cli/slash/models.js.map +1 -1
  26. package/dist/cli/slash/paste.js +4 -7
  27. package/dist/cli/slash/paste.js.map +1 -1
  28. package/dist/cli/slash/sandbox.d.ts +21 -0
  29. package/dist/cli/slash/sandbox.js +84 -0
  30. package/dist/cli/slash/sandbox.js.map +1 -0
  31. package/dist/cli/slash.d.ts +5 -0
  32. package/dist/cli/slash.js +26 -10
  33. package/dist/cli/slash.js.map +1 -1
  34. package/dist/cli/subcommands/audit.js +28 -8
  35. package/dist/cli/subcommands/audit.js.map +1 -1
  36. package/dist/cli/subcommands/doctor.d.ts +4 -0
  37. package/dist/cli/subcommands/doctor.js +117 -21
  38. package/dist/cli/subcommands/doctor.js.map +1 -1
  39. package/dist/cli/subcommands/feature-setup.js +6 -6
  40. package/dist/cli/subcommands/feature-setup.js.map +1 -1
  41. package/dist/cli/subcommands/memory.js +23 -0
  42. package/dist/cli/subcommands/memory.js.map +1 -1
  43. package/dist/cli/subcommands/telemetry.d.ts +2 -1
  44. package/dist/cli/subcommands/telemetry.js +47 -34
  45. package/dist/cli/subcommands/telemetry.js.map +1 -1
  46. package/dist/context/branch.d.ts +2 -2
  47. package/dist/context/branch.js +40 -23
  48. package/dist/context/branch.js.map +1 -1
  49. package/dist/context/compaction.js +44 -21
  50. package/dist/context/compaction.js.map +1 -1
  51. package/dist/context/default-soul.md +1 -0
  52. package/dist/context/git-state.js +31 -18
  53. package/dist/context/git-state.js.map +1 -1
  54. package/dist/context/knowledge.js +31 -20
  55. package/dist/context/knowledge.js.map +1 -1
  56. package/dist/context/memory.js +8 -1
  57. package/dist/context/memory.js.map +1 -1
  58. package/dist/context/mode-enforcement.js +11 -1
  59. package/dist/context/mode-enforcement.js.map +1 -1
  60. package/dist/context/mode.js +67 -30
  61. package/dist/context/mode.js.map +1 -1
  62. package/dist/context/primer.d.ts +17 -0
  63. package/dist/context/primer.js +50 -3
  64. package/dist/context/primer.js.map +1 -1
  65. package/dist/context/session.d.ts +4 -0
  66. package/dist/context/session.js.map +1 -1
  67. package/dist/embeddings/iface.d.ts +26 -0
  68. package/dist/embeddings/iface.js +15 -0
  69. package/dist/embeddings/iface.js.map +1 -0
  70. package/dist/embeddings/local.d.ts +24 -0
  71. package/dist/embeddings/local.js +112 -0
  72. package/dist/embeddings/local.js.map +1 -0
  73. package/dist/embeddings/remote.d.ts +31 -0
  74. package/dist/embeddings/remote.js +88 -0
  75. package/dist/embeddings/remote.js.map +1 -0
  76. package/dist/embeddings/select.d.ts +24 -0
  77. package/dist/embeddings/select.js +39 -0
  78. package/dist/embeddings/select.js.map +1 -0
  79. package/dist/fleet/apply-back.js +5 -1
  80. package/dist/fleet/apply-back.js.map +1 -1
  81. package/dist/fleet/cli-command.d.ts +2 -0
  82. package/dist/fleet/cli-command.js +15 -1
  83. package/dist/fleet/cli-command.js.map +1 -1
  84. package/dist/fleet/runner.js +35 -2
  85. package/dist/fleet/runner.js.map +1 -1
  86. package/dist/fleet/scratchpad.js +1 -2
  87. package/dist/fleet/scratchpad.js.map +1 -1
  88. package/dist/fleet/state.d.ts +4 -0
  89. package/dist/fleet/state.js +11 -2
  90. package/dist/fleet/state.js.map +1 -1
  91. package/dist/fleet/templates.d.ts +4 -0
  92. package/dist/fleet/templates.js.map +1 -1
  93. package/dist/fleet/types.d.ts +4 -0
  94. package/dist/fleet/types.js.map +1 -1
  95. package/dist/intelligence/failover-chain.js +10 -1
  96. package/dist/intelligence/failover-chain.js.map +1 -1
  97. package/dist/intelligence/prices.d.ts +6 -4
  98. package/dist/intelligence/prices.js +36 -10
  99. package/dist/intelligence/prices.js.map +1 -1
  100. package/dist/kernel/agent-loop.js +60 -17
  101. package/dist/kernel/agent-loop.js.map +1 -1
  102. package/dist/kernel/types.d.ts +3 -0
  103. package/dist/lsp/client.js +29 -16
  104. package/dist/lsp/client.js.map +1 -1
  105. package/dist/lsp/detector.js +7 -6
  106. package/dist/lsp/detector.js.map +1 -1
  107. package/dist/mcp/client.d.ts +1 -1
  108. package/dist/mcp/client.js +19 -16
  109. package/dist/mcp/client.js.map +1 -1
  110. package/dist/mcp/transport.js +46 -38
  111. package/dist/mcp/transport.js.map +1 -1
  112. package/dist/providers/deepseek.js +1 -1
  113. package/dist/providers/deepseek.js.map +1 -1
  114. package/dist/providers/dispatch.js +15 -1
  115. package/dist/providers/dispatch.js.map +1 -1
  116. package/dist/providers/index.d.ts +11 -0
  117. package/dist/providers/index.js +29 -2
  118. package/dist/providers/index.js.map +1 -1
  119. package/dist/providers/nvidia.js +1 -1
  120. package/dist/providers/nvidia.js.map +1 -1
  121. package/dist/providers/openai-compat.js +4 -2
  122. package/dist/providers/openai-compat.js.map +1 -1
  123. package/dist/providers/openrouter.js +1 -1
  124. package/dist/providers/openrouter.js.map +1 -1
  125. package/dist/safety/audit-log.d.ts +15 -0
  126. package/dist/safety/audit-log.js +21 -0
  127. package/dist/safety/audit-log.js.map +1 -1
  128. package/dist/state/db-telemetry.js +11 -1
  129. package/dist/state/db-telemetry.js.map +1 -1
  130. package/dist/state/db.d.ts +7 -0
  131. package/dist/state/db.js +125 -3
  132. package/dist/state/db.js.map +1 -1
  133. package/dist/state/sync-index.d.ts +74 -0
  134. package/dist/state/sync-index.js +246 -0
  135. package/dist/state/sync-index.js.map +1 -0
  136. package/dist/state/transaction.d.ts +62 -0
  137. package/dist/state/transaction.js +65 -0
  138. package/dist/state/transaction.js.map +1 -0
  139. package/dist/state/vec.d.ts +28 -0
  140. package/dist/state/vec.js +113 -0
  141. package/dist/state/vec.js.map +1 -0
  142. package/dist/telemetry/gateway-push.d.ts +17 -0
  143. package/dist/telemetry/gateway-push.js +48 -0
  144. package/dist/telemetry/gateway-push.js.map +1 -0
  145. package/dist/telemetry/index.d.ts +9 -0
  146. package/dist/telemetry/index.js +9 -0
  147. package/dist/telemetry/index.js.map +1 -0
  148. package/dist/tools/browser.js +24 -16
  149. package/dist/tools/browser.js.map +1 -1
  150. package/dist/tools/checkpoint.d.ts +6 -1
  151. package/dist/tools/checkpoint.js +79 -62
  152. package/dist/tools/checkpoint.js.map +1 -1
  153. package/dist/tools/cron.js +1 -3
  154. package/dist/tools/cron.js.map +1 -1
  155. package/dist/tools/db-workspace-info.d.ts +10 -0
  156. package/dist/tools/db-workspace-info.js +76 -0
  157. package/dist/tools/db-workspace-info.js.map +1 -0
  158. package/dist/tools/diff.js +25 -21
  159. package/dist/tools/diff.js.map +1 -1
  160. package/dist/tools/exec.d.ts +6 -1
  161. package/dist/tools/exec.js +46 -4
  162. package/dist/tools/exec.js.map +1 -1
  163. package/dist/tools/fs-edit.d.ts +3 -5
  164. package/dist/tools/fs-edit.js +8 -23
  165. package/dist/tools/fs-edit.js.map +1 -1
  166. package/dist/tools/fs-ls.js +6 -8
  167. package/dist/tools/fs-ls.js.map +1 -1
  168. package/dist/tools/fs-read.d.ts +1 -1
  169. package/dist/tools/fs-read.js +37 -28
  170. package/dist/tools/fs-read.js.map +1 -1
  171. package/dist/tools/fs-write.d.ts +1 -1
  172. package/dist/tools/fs-write.js +33 -33
  173. package/dist/tools/fs-write.js.map +1 -1
  174. package/dist/tools/git.js +12 -6
  175. package/dist/tools/git.js.map +1 -1
  176. package/dist/tools/github.d.ts +13 -0
  177. package/dist/tools/github.js +257 -0
  178. package/dist/tools/github.js.map +1 -0
  179. package/dist/tools/graph-neighbors.d.ts +9 -0
  180. package/dist/tools/graph-neighbors.js +77 -0
  181. package/dist/tools/graph-neighbors.js.map +1 -0
  182. package/dist/tools/graph-traverse.d.ts +10 -0
  183. package/dist/tools/graph-traverse.js +90 -0
  184. package/dist/tools/graph-traverse.js.map +1 -0
  185. package/dist/tools/index.d.ts +10 -2
  186. package/dist/tools/index.js +17 -4
  187. package/dist/tools/index.js.map +1 -1
  188. package/dist/tools/kb-search.d.ts +13 -0
  189. package/dist/tools/kb-search.js +113 -0
  190. package/dist/tools/kb-search.js.map +1 -0
  191. package/dist/tools/multimodal.js +11 -12
  192. package/dist/tools/multimodal.js.map +1 -1
  193. package/dist/tools/registry.d.ts +10 -0
  194. package/dist/tools/registry.js.map +1 -1
  195. package/dist/tools/rtk.js +22 -9
  196. package/dist/tools/rtk.js.map +1 -1
  197. package/dist/tools/search-glob.d.ts +1 -1
  198. package/dist/tools/search-glob.js +42 -24
  199. package/dist/tools/search-glob.js.map +1 -1
  200. package/dist/tools/search-grep.d.ts +1 -1
  201. package/dist/tools/search-grep.js +56 -32
  202. package/dist/tools/search-grep.js.map +1 -1
  203. package/dist/tools/shell.d.ts +7 -1
  204. package/dist/tools/shell.js +178 -61
  205. package/dist/tools/shell.js.map +1 -1
  206. package/dist/tools/transactional-write.d.ts +10 -0
  207. package/dist/tools/transactional-write.js +132 -0
  208. package/dist/tools/transactional-write.js.map +1 -0
  209. package/dist/tui/ink/App.d.ts +2 -1
  210. package/dist/tui/ink/App.js +304 -74
  211. package/dist/tui/ink/App.js.map +1 -1
  212. package/dist/tui/ink/components/DenseToolMessage.js +20 -3
  213. package/dist/tui/ink/components/DenseToolMessage.js.map +1 -1
  214. package/dist/tui/ink/components/InputBox.js +16 -15
  215. package/dist/tui/ink/components/InputBox.js.map +1 -1
  216. package/dist/tui/ink/components/KeySetOverlay.d.ts +1 -1
  217. package/dist/tui/ink/components/KeySetOverlay.js +18 -16
  218. package/dist/tui/ink/components/KeySetOverlay.js.map +1 -1
  219. package/dist/tui/ink/components/Logo.d.ts +20 -0
  220. package/dist/tui/ink/components/Logo.js +67 -1
  221. package/dist/tui/ink/components/Logo.js.map +1 -1
  222. package/dist/tui/ink/components/ModelPicker.d.ts +2 -2
  223. package/dist/tui/ink/components/ModelPicker.js +34 -26
  224. package/dist/tui/ink/components/ModelPicker.js.map +1 -1
  225. package/dist/tui/ink/components/PasteCollapse.d.ts +3 -1
  226. package/dist/tui/ink/components/PasteCollapse.js +11 -9
  227. package/dist/tui/ink/components/PasteCollapse.js.map +1 -1
  228. package/dist/tui/ink/components/SandboxPicker.d.ts +18 -0
  229. package/dist/tui/ink/components/SandboxPicker.js +77 -0
  230. package/dist/tui/ink/components/SandboxPicker.js.map +1 -0
  231. package/dist/tui/ink/components/SpinnerGlyph.d.ts +4 -4
  232. package/dist/tui/ink/components/SpinnerGlyph.js +34 -14
  233. package/dist/tui/ink/components/SpinnerGlyph.js.map +1 -1
  234. package/dist/tui/ink/components/StatusBar.js +0 -2
  235. package/dist/tui/ink/components/StatusBar.js.map +1 -1
  236. package/dist/tui/ink/components/ThinkingBlock.d.ts +15 -4
  237. package/dist/tui/ink/components/ThinkingBlock.js +34 -17
  238. package/dist/tui/ink/components/ThinkingBlock.js.map +1 -1
  239. package/dist/tui/ink/components/ToolBox.js +21 -13
  240. package/dist/tui/ink/components/ToolBox.js.map +1 -1
  241. package/dist/tui/ink/components/VirtualTranscript.d.ts +1 -1
  242. package/dist/tui/ink/components/VirtualTranscript.js +5 -3
  243. package/dist/tui/ink/components/VirtualTranscript.js.map +1 -1
  244. package/dist/tui/ink/index.js +17 -1
  245. package/dist/tui/ink/index.js.map +1 -1
  246. package/dist/tui/ink/markdown/syntax-highlight.d.ts +13 -0
  247. package/dist/tui/ink/markdown/syntax-highlight.js +91 -0
  248. package/dist/tui/ink/markdown/syntax-highlight.js.map +1 -0
  249. package/dist/tui/ink/theme-context.js +6 -3
  250. package/dist/tui/ink/theme-context.js.map +1 -1
  251. package/dist/tui/ink/use-declined-versions.js +6 -2
  252. package/dist/tui/ink/use-declined-versions.js.map +1 -1
  253. package/dist/tui/ink/use-elapsed.d.ts +9 -1
  254. package/dist/tui/ink/use-elapsed.js +17 -2
  255. package/dist/tui/ink/use-elapsed.js.map +1 -1
  256. package/dist/tui/ink/use-event-projection.d.ts +10 -0
  257. package/dist/tui/ink/use-event-projection.js +111 -12
  258. package/dist/tui/ink/use-event-projection.js.map +1 -1
  259. package/dist/tui/ink/use-flicker-detector.js +9 -0
  260. package/dist/tui/ink/use-flicker-detector.js.map +1 -1
  261. package/dist/tui/ink/use-overlays.d.ts +2 -2
  262. package/dist/tui/ink/use-overlays.js +16 -17
  263. package/dist/tui/ink/use-overlays.js.map +1 -1
  264. package/dist/tui/ink/use-render-metrics.js +18 -5
  265. package/dist/tui/ink/use-render-metrics.js.map +1 -1
  266. package/dist/utils/env.d.ts +1 -0
  267. package/dist/utils/env.js +60 -0
  268. package/dist/utils/env.js.map +1 -0
  269. package/dist/utils/fs.d.ts +10 -0
  270. package/dist/utils/fs.js +37 -0
  271. package/dist/utils/fs.js.map +1 -0
  272. package/package.json +10 -7
@@ -3,7 +3,7 @@ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
3
3
  * Ink root component for the dirgha TUI.
4
4
  *
5
5
  * Layout is a single vertical stack:
6
- * 1. Logo (rendered once inside <Static>, never re-renders)
6
+ * 1. Logo (emitted to stdout once before Ink mounts — see ./index.ts)
7
7
  * 2. Transcript (finalised user messages + completed turn blocks)
8
8
  * 3. LiveTurn (the currently streaming turn, if any)
9
9
  * 4. InputBox
@@ -15,7 +15,7 @@ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
15
15
  * focused on layout and lifecycle.
16
16
  */
17
17
  import * as React from "react";
18
- import { Box, Static, Text, useApp, useInput } from "ink";
18
+ import { Box, Text, useApp, useInput } from "ink";
19
19
  import { randomUUID } from "node:crypto";
20
20
  import { VirtualTranscript } from "./components/VirtualTranscript.js";
21
21
  import { appendAudit } from "../../audit/writer.js";
@@ -27,6 +27,7 @@ import { loadProjectPrimer, composeSystemPrompt, } from "../../context/primer.js
27
27
  import { queryKb } from "../../context/kb-query.js";
28
28
  import { probeGitState, renderGitState } from "../../context/git-state.js";
29
29
  import { loadSoul } from "../../context/soul.js";
30
+ import { routeModel } from "../../providers/dispatch.js";
30
31
  import { isAutoApprove, modePreamble } from "../../context/mode.js";
31
32
  import { runAgentLoop } from "../../kernel/agent-loop.js";
32
33
  import { createErrorClassifier } from "../../intelligence/error-classifier.js";
@@ -34,10 +35,9 @@ import { createToolExecutor } from "../../tools/exec.js";
34
35
  import { createInkApprovalBus, } from "./ink-approval-bus.js";
35
36
  import { ApprovalPrompt, } from "./components/ApprovalPrompt.js";
36
37
  import { PRICES } from "../../intelligence/prices.js";
37
- import { Logo } from "./components/Logo.js";
38
38
  import { StatusBar } from "./components/StatusBar.js";
39
39
  import { StreamingText } from "./components/StreamingText.js";
40
- import { ThinkingBlock } from "./components/ThinkingBlock.js";
40
+ import { ThinkingBlock, ThinkingBlockGroup, } from "./components/ThinkingBlock.js";
41
41
  import { ToolBox } from "./components/ToolBox.js";
42
42
  import { ToolGroup } from "./components/ToolGroup.js";
43
43
  import { InputBox } from "./components/InputBox.js";
@@ -53,9 +53,12 @@ import { getUpdateBannerVersion } from "../../cli/update-check.js";
53
53
  import { AtFileComplete } from "./components/AtFileComplete.js";
54
54
  import { SlashComplete } from "./components/SlashComplete.js";
55
55
  import { ThemePicker } from "./components/ThemePicker.js";
56
- import { ThemeProvider } from "./theme-context.js";
56
+ import { SandboxPicker } from "./components/SandboxPicker.js";
57
+ import { ThemeProvider, useTheme } from "./theme-context.js";
57
58
  import { SpinnerContext } from "./spinner-context.js";
59
+ import { SpinnerGlyph } from "./components/SpinnerGlyph.js";
58
60
  import { writeFile, mkdir, readFile } from "node:fs/promises";
61
+ import { readFileSync, existsSync } from "node:fs";
59
62
  import { homedir } from "node:os";
60
63
  import { join as pathJoin } from "node:path";
61
64
  import { useEventProjection, } from "./use-event-projection.js";
@@ -69,7 +72,7 @@ import { createRequire } from "node:module";
69
72
  // Pulled from the installed package.json so the TUI title matches the
70
73
  // shipped binary version. Falls back to '0.0.0-dev' if the file isn't
71
74
  // reachable (e.g. an unusual deploy layout).
72
- const VERSION = (() => {
75
+ export const VERSION = (() => {
73
76
  try {
74
77
  const req = createRequire(import.meta.url);
75
78
  const pkg = req("../../../package.json");
@@ -79,13 +82,30 @@ const VERSION = (() => {
79
82
  return "0.0.0-dev";
80
83
  }
81
84
  })();
85
+ // Cache for initialHistory — avoids sync fs I/O in the render phase
86
+ // on re-calls (e.g. /clear). The underlying files rarely change within
87
+ // a session so a single snapshot is sufficient.
88
+ let _cachedInitialMessages = null;
82
89
  export function App(props) {
83
90
  const { exit } = useApp();
84
91
  const sessionIdRef = React.useRef(randomUUID());
85
92
  const historyRef = React.useRef(initialHistory(props));
86
93
  const abortRef = React.useRef(null);
94
+ // Stores the user-facing cancellation message so the finally block can
95
+ // inject it via appendLiveSync (avoids the React state-updater race
96
+ // where appendLive doesn't update liveItemsRef before commitLive reads it).
97
+ const interruptMsgRef = React.useRef(null);
87
98
  const pendingModelRef = React.useRef(null);
88
99
  const sessionRef = React.useRef(null);
100
+ // Tracks whether the model has produced its first response in this
101
+ // session. The system prompt includes a one-line `[session-title]`
102
+ // instruction only on the first turn; after the first agent_end the
103
+ // instruction is stripped out so it does not appear on every turn.
104
+ const firstTurnRef = React.useRef(!(props.initialMessages ?? []).some((m) => m.role === "user" || m.role === "assistant"));
105
+ // Live sandbox mode — initialised from config, mutated by /sandbox.
106
+ // Read by the executor wiring on every tool dispatch so the toggle
107
+ // takes effect on the next tool call without re-mounting the App.
108
+ const sandboxModeRef = React.useRef(props.config.sandbox ?? "off");
89
109
  React.useEffect(() => {
90
110
  const id = sessionIdRef.current;
91
111
  void props.sessions.create(id).then((s) => {
@@ -109,6 +129,7 @@ export function App(props) {
109
129
  const [transcript, setTranscript] = React.useState([]);
110
130
  const [input, setInput] = React.useState("");
111
131
  const [busy, setBusy] = React.useState(false);
132
+ const [thinkingStreaming, setThinkingStreaming] = React.useState(false);
112
133
  // Prompt queue: while a turn is streaming the user can still type and
113
134
  // press Enter. Submissions land here instead of being dropped, then
114
135
  // drain FIFO when the turn finishes (see useEffect below).
@@ -145,7 +166,7 @@ export function App(props) {
145
166
  // turns. Replaces the legacy `createTuiApprovalBus` that wrote prompts
146
167
  // direct to stdout (overdrawn by Ink) and read stdin raw (hung on
147
168
  // Windows). See `ink-approval-bus.ts` for the full rationale.
148
- const approvalBusRef = React.useRef();
169
+ const approvalBusRef = React.useRef(null);
149
170
  if (!approvalBusRef.current) {
150
171
  approvalBusRef.current = createInkApprovalBus(new Set(props.config.autoApproveTools));
151
172
  }
@@ -166,7 +187,55 @@ export function App(props) {
166
187
  onCommitSplit: React.useCallback((item) => {
167
188
  setTranscript((prev) => [...prev, item]);
168
189
  }, []),
190
+ // First-turn `[session-title] X` marker support. The projection
191
+ // strips the marker line from the transcript; here we surface the
192
+ // captured title as: (a) the OSC 0 terminal title, (b) a persisted
193
+ // session entry, (c) React state for any future `/sessions` UI.
194
+ isFirstTurn: React.useCallback(() => firstTurnRef.current, []),
195
+ onSessionTitle: React.useCallback((title) => {
196
+ // Strip control characters from LLM-supplied title before
197
+ // injecting into an OSC sequence — a raw 0x07/0x9c would close
198
+ // the OSC string early and let the model inject arbitrary
199
+ // terminal codes. Codepoint filter avoids eslint's
200
+ // `no-control-regex` rule (which fires on both literal and
201
+ // string-constructed regexes).
202
+ const safe = Array.from(title)
203
+ .filter((c) => {
204
+ const cp = c.charCodeAt(0);
205
+ return cp >= 0x20 && cp !== 0x7f;
206
+ })
207
+ .join("")
208
+ .slice(0, 80)
209
+ .trim();
210
+ if (!safe)
211
+ return;
212
+ sessionTitleRef.current = safe;
213
+ try {
214
+ if (process.stdout.isTTY) {
215
+ process.stdout.write(`\x1b]0;Dirgha · ${safe}\x07`);
216
+ }
217
+ }
218
+ catch {
219
+ /* OSC write best-effort */
220
+ }
221
+ const s = sessionRef.current;
222
+ if (s) {
223
+ void s
224
+ .append({
225
+ type: "title",
226
+ ts: new Date().toISOString(),
227
+ title: safe,
228
+ })
229
+ .catch(() => {
230
+ /* persistence best-effort — non-blocking */
231
+ });
232
+ }
233
+ }, []),
169
234
  });
235
+ // Holds the most recent session title (set by the projection's
236
+ // `onSessionTitle` callback). Read by future surfaces (/sessions
237
+ // list, status bar, etc) — not currently displayed in v1.20.40.
238
+ const sessionTitleRef = React.useRef(null);
170
239
  const overlays = useOverlays();
171
240
  // Live counters for the in-progress turn — drive the StatusBar
172
241
  // tok/s readout. Reset at agent_start, accumulate output deltas,
@@ -292,8 +361,18 @@ export function App(props) {
292
361
  liveOutputTokensAccRef.current = 0;
293
362
  setLiveOutputTokens(0);
294
363
  setLiveDurationMs(0);
364
+ setThinkingStreaming(false);
365
+ }
366
+ else if (ev.type === "thinking_start") {
367
+ setThinkingStreaming(true);
368
+ }
369
+ else if (ev.type === "thinking_end") {
370
+ setThinkingStreaming(false);
295
371
  }
296
372
  else if (ev.type === "text_delta" || ev.type === "thinking_delta") {
373
+ // Approximate tokens as chars ÷ 4 — a common heuristic for English
374
+ // text where avg token length is ~4 characters. Not exact but keeps
375
+ // the tok/s rate plausible without an expensive tokenizer.
297
376
  liveOutputTokensAccRef.current += (ev.delta?.length ?? 0) / 4;
298
377
  }
299
378
  else if (ev.type === "usage") {
@@ -305,10 +384,36 @@ export function App(props) {
305
384
  setLiveDurationMs(0);
306
385
  setLiveOutputTokens(0);
307
386
  liveOutputTokensAccRef.current = 0;
387
+ // After the first response completes, refresh the system
388
+ // message to drop the one-line session-title instruction so
389
+ // the model does not keep emitting `[session-title]` on every
390
+ // subsequent turn. Composing here uses cached project primer
391
+ // + soul (cheap) and only runs once per session.
392
+ if (firstTurnRef.current) {
393
+ firstTurnRef.current = false;
394
+ const msgs = historyRef.current;
395
+ if (msgs.length > 0 && msgs[0].role === "system") {
396
+ const primer = loadProjectPrimer(props.cwd);
397
+ const soul = loadSoul();
398
+ const refreshedSystem = composeSystemPrompt({
399
+ soul: soul.text,
400
+ modePreamble: modePreamble(mode),
401
+ primer: primer.primer,
402
+ ledgerContext: props.ledgerContext,
403
+ gitState: renderGitState(probeGitState(props.cwd)),
404
+ userSystem: props.systemPrompt,
405
+ firstTurn: false,
406
+ });
407
+ historyRef.current = [
408
+ { role: "system", content: refreshedSystem },
409
+ ...msgs.slice(1),
410
+ ];
411
+ }
412
+ }
308
413
  }
309
414
  });
310
415
  return unsub;
311
- }, [props.events]);
416
+ }, [props.events, mode, props.cwd, props.ledgerContext, props.systemPrompt]);
312
417
  // globalSpinnerFrame removed — spinner interval now lives inside
313
418
  // SpinnerGlyph so only the glyph subtree re-renders at 80ms, not the
314
419
  // entire App tree.
@@ -396,7 +501,7 @@ export function App(props) {
396
501
  });
397
502
  // A new submission supersedes any pending failover prompt.
398
503
  setPendingFailover(null);
399
- if (value === "/exit" || value === "/quit") {
504
+ if (value === "/exit" || value === "/quit" || value === "/stop") {
400
505
  exit();
401
506
  return;
402
507
  }
@@ -414,23 +519,36 @@ export function App(props) {
414
519
  if (value.startsWith("/model ")) {
415
520
  const id = value.slice("/model ".length).trim();
416
521
  if (id !== "") {
417
- const valid = PRICES.some((p) => p.model === id);
418
- if (!valid) {
522
+ // Exact match first, then suffix fallback — mirrors slash.ts /model handler.
523
+ const exactMatch = PRICES.find((p) => p.model === id);
524
+ if (exactMatch) {
525
+ setCurrentModel(exactMatch.model);
419
526
  const note = {
420
527
  kind: "notice",
421
528
  id: randomUUID(),
422
- text: `Invalid model: ${id}. Use /models to see the catalogue.`,
529
+ text: `Model set to ${exactMatch.model}`,
423
530
  };
424
531
  setTranscript((prev) => [...prev, note]);
425
532
  }
426
533
  else {
427
- setCurrentModel(id);
428
- const note = {
429
- kind: "notice",
430
- id: randomUUID(),
431
- text: `Model set to ${id}`,
432
- };
433
- setTranscript((prev) => [...prev, note]);
534
+ const suffixMatch = PRICES.find((p) => p.model.endsWith("/" + id));
535
+ if (suffixMatch) {
536
+ setCurrentModel(suffixMatch.model);
537
+ const note = {
538
+ kind: "notice",
539
+ id: randomUUID(),
540
+ text: `Model set to ${suffixMatch.model}`,
541
+ };
542
+ setTranscript((prev) => [...prev, note]);
543
+ }
544
+ else {
545
+ const note = {
546
+ kind: "notice",
547
+ id: randomUUID(),
548
+ text: `Invalid model: ${id}. Use /models to see the catalogue.`,
549
+ };
550
+ setTranscript((prev) => [...prev, note]);
551
+ }
434
552
  }
435
553
  }
436
554
  return;
@@ -444,6 +562,11 @@ export function App(props) {
444
562
  overlays.openOverlay("theme");
445
563
  return;
446
564
  }
565
+ // `/sandbox` with no args opens the picker; `/sandbox <mode>` sets directly.
566
+ if (value === "/sandbox") {
567
+ overlays.openOverlay("sandbox");
568
+ return;
569
+ }
447
570
  // /upgrade and /self-update trigger npm install + restart.
448
571
  if (value === "/upgrade" ||
449
572
  value === "/self-update" ||
@@ -520,7 +643,11 @@ export function App(props) {
520
643
  exit();
521
644
  process.exit(code);
522
645
  },
523
- getToken: () => tokenRef.current,
646
+ getToken: () => {
647
+ // Token loads asynchronously after mount; return null
648
+ // gracefully so slash commands don't crash on first call.
649
+ return tokenRef.current;
650
+ },
524
651
  setToken: (newToken) => {
525
652
  tokenRef.current = newToken;
526
653
  },
@@ -542,6 +669,10 @@ export function App(props) {
542
669
  setMode: (m) => setMode(m),
543
670
  getTheme: () => props.config.theme ?? "readable",
544
671
  setTheme: () => undefined,
672
+ getSandbox: () => sandboxModeRef.current,
673
+ setSandbox: (next) => {
674
+ sandboxModeRef.current = next;
675
+ },
545
676
  getSession: () => null,
546
677
  getSessionStore: () => props.sessions,
547
678
  getProvider: () => props.providers.forModel(currentModel),
@@ -658,6 +789,7 @@ export function App(props) {
658
789
  registry: props.registry,
659
790
  cwd: props.cwd,
660
791
  sessionId: sessionIdRef.current,
792
+ sandboxMode: sandboxModeRef.current,
661
793
  onProgress: (toolId, message) => {
662
794
  props.events.emit({
663
795
  type: "tool_exec_progress",
@@ -709,7 +841,10 @@ export function App(props) {
709
841
  }
710
842
  catch (err) {
711
843
  const msg = err instanceof Error ? err.message : String(err);
712
- const keyMatch = /^([A-Z][A-Z0-9_]+_API_KEY) is required/.exec(msg);
844
+ // Only match provider-key errors, not errors from deep inside the agent
845
+ // loop that happen to contain a similar pattern. The message must start
846
+ // with the key name and end with "is required" to qualify.
847
+ const keyMatch = /^([A-Z][A-Z0-9_]+_API_KEY) is required$/.exec(msg);
713
848
  if (keyMatch?.[1]) {
714
849
  setPendingKey({
715
850
  keyName: keyMatch[1],
@@ -725,6 +860,19 @@ export function App(props) {
725
860
  }
726
861
  }
727
862
  finally {
863
+ // If the turn was cancelled via ESC / Ctrl-C, inject the notice
864
+ // synchronously into liveItemsRef before commitLive reads it — this
865
+ // avoids the React-state race where appendLive's functional updater
866
+ // hasn't flushed to the ref yet when commitLive runs.
867
+ const interruptMsg = interruptMsgRef.current;
868
+ interruptMsgRef.current = null;
869
+ if (abort.signal.aborted && interruptMsg !== null) {
870
+ projection.appendLiveSync({
871
+ kind: "notice",
872
+ id: randomUUID(),
873
+ text: interruptMsg,
874
+ });
875
+ }
728
876
  const committed = projection.commitLive();
729
877
  if (committed.length > 0)
730
878
  setTranscript((prev) => [...prev, ...committed]);
@@ -732,7 +880,12 @@ export function App(props) {
732
880
  abortRef.current = null;
733
881
  }
734
882
  };
735
- runTurnRef.current = runTurn;
883
+ // Keep runTurnRef pointed at the latest runTurn closure so
884
+ // handleSubmit always calls the current version without adding
885
+ // runTurn's deps to handleSubmit's dependency array.
886
+ React.useEffect(() => {
887
+ runTurnRef.current = runTurn;
888
+ });
736
889
  // Drain the prompt queue when a turn finishes. Pops the oldest queued
737
890
  // prompt and re-submits it through handleSubmit (which transitions
738
891
  // back into busy=true via runTurn). Guarded on `!busy` so we never
@@ -752,6 +905,8 @@ export function App(props) {
752
905
  // 2. If a turn is streaming → abort it (cancels the in-flight LLM
753
906
  // request via the AbortController plumbed through runAgentLoop).
754
907
  // 3. If the input box has draft text → clear it.
908
+ // (step 3 is skipped when vimMode is on — InputBox's own handler
909
+ // enters NORMAL mode; clearing here would destroy the text.)
755
910
  // Always active so Esc behaves like the user expects regardless of
756
911
  // which surface they're looking at. The atfile overlay handles its
757
912
  // own Esc (cancel completion) so we skip step 1 there.
@@ -763,33 +918,23 @@ export function App(props) {
763
918
  return;
764
919
  }
765
920
  if (busy && abortRef.current !== null) {
921
+ interruptMsgRef.current = "Cancelled.";
766
922
  abortRef.current.abort();
767
- projection.appendLive({
768
- kind: "notice",
769
- id: randomUUID(),
770
- text: "Cancelled.",
771
- });
772
923
  return;
773
924
  }
774
- if (input.length > 0)
925
+ if (input.length > 0 && props.config.vimMode !== true)
775
926
  setInput("");
776
927
  });
777
928
  // Ctrl-C handler: if a turn is running, abort it and show "[Interrupted]"
778
929
  // in the transcript (matching the readline path in src/cli/interactive.ts).
779
- // If idle, let the process exit normally via app.exit().
930
+ // Idle exit is handled by InputBox's own Ctrl-C handler (2-press safety
931
+ // within 1.5s) — we don't override that here.
780
932
  useInput((ch, key) => {
781
933
  if (!(key.ctrl && ch === "c"))
782
934
  return;
783
935
  if (busy && abortRef.current !== null) {
936
+ interruptMsgRef.current = "[Interrupted]";
784
937
  abortRef.current.abort();
785
- projection.appendLive({
786
- kind: "notice",
787
- id: randomUUID(),
788
- text: "[Interrupted]",
789
- });
790
- }
791
- else {
792
- exit();
793
938
  }
794
939
  });
795
940
  const handleModelPick = React.useCallback((id) => {
@@ -815,7 +960,7 @@ export function App(props) {
815
960
  }
816
961
  catch (err) {
817
962
  const msg = err instanceof Error ? err.message : String(err);
818
- const m = /([A-Z][A-Z0-9_]+_API_KEY) is required/.exec(msg);
963
+ const m = /^([A-Z][A-Z0-9_]+_API_KEY) is required$/.exec(msg);
819
964
  if (m?.[1]) {
820
965
  // Open inline key entry instead of a static hint — the user can
821
966
  // paste their key right here without leaving the REPL.
@@ -931,6 +1076,30 @@ export function App(props) {
931
1076
  // live. Initial value comes from config; subsequent changes are
932
1077
  // persisted to ~/.dirgha/config.json so future sessions pick it up.
933
1078
  const [themeName, setThemeName] = React.useState((props.config.theme ?? "readable"));
1079
+ const handleSandboxPick = React.useCallback((next) => {
1080
+ overlays.closeOverlay();
1081
+ sandboxModeRef.current = next;
1082
+ const note = {
1083
+ kind: "notice",
1084
+ id: randomUUID(),
1085
+ text: `Sandbox mode → ${next}`,
1086
+ };
1087
+ setTranscript((t) => [...t, note]);
1088
+ void (async () => {
1089
+ try {
1090
+ const dir = pathJoin(homedir(), ".dirgha");
1091
+ await mkdir(dir, { recursive: true });
1092
+ const path = pathJoin(dir, "config.json");
1093
+ const text = await readFile(path, "utf8").catch(() => "");
1094
+ const cfg = text ? JSON.parse(text) : {};
1095
+ cfg.sandbox = next;
1096
+ await writeFile(path, `${JSON.stringify(cfg, null, 2)}\n`, "utf8");
1097
+ }
1098
+ catch {
1099
+ /* best-effort persistence */
1100
+ }
1101
+ })();
1102
+ }, [overlays]);
934
1103
  const handleThemePick = React.useCallback((name) => {
935
1104
  overlays.closeOverlay();
936
1105
  setThemeName(name);
@@ -955,10 +1124,18 @@ export function App(props) {
955
1124
  }
956
1125
  })();
957
1126
  }, [overlays]);
958
- const liveJsx = React.useMemo(() => renderTranscript(projection.liveItems), [projection.liveItems]);
1127
+ const liveJsx = React.useMemo(() => renderTranscript(projection.liveItems, thinkingStreaming), [projection.liveItems, thinkingStreaming]);
959
1128
  const providerEntries = React.useMemo(() => buildProviderEntries(models, currentModel), [models, currentModel]);
960
- const LOGO_ITEMS = React.useMemo(() => [{ key: "logo" }], []);
961
- return (_jsx(ThemeProvider, { activeTheme: themeName, children: _jsx(SpinnerContext.Provider, { value: { busy, frame: 0 }, children: _jsxs(Box, { flexDirection: "column", children: [_jsx(Static, { items: LOGO_ITEMS, children: () => _jsx(Logo, { version: VERSION }, "logo") }), _jsx(VirtualTranscript, { items: transcript, renderItem: (item) => _jsx(TranscriptRow, { item: item }, item.id), autoScroll: true, inputFocus: inputFocus }), _jsx(Box, { flexDirection: "column", children: liveJsx }), pendingApproval !== null && approvalBusRef.current && (_jsx(ApprovalPrompt, { request: pendingApproval, onResolve: (decision) => {
1129
+ const spinnerCtx = React.useMemo(() => ({ busy, frame: 0 }), [busy]);
1130
+ const renderTranscriptItem = React.useCallback((item) => _jsx(TranscriptRow, { item: item }, item.id), []);
1131
+ // Logo is emitted via process.stdout.write() before Ink mounts (see
1132
+ // tui/ink/index.ts). Keeping it out of Ink's render tree avoids the
1133
+ // re-emission flicker users hit when transcripts overflow the
1134
+ // viewport: Ink's onRender prepends `fullStaticOutput` (which includes
1135
+ // the logo) on every overflow redraw, repainting it on every chat
1136
+ // turn that fills the screen. `use-flicker-detector` already warns
1137
+ // when this is about to happen.
1138
+ return (_jsx(ThemeProvider, { activeTheme: themeName, children: _jsx(SpinnerContext.Provider, { value: spinnerCtx, children: _jsxs(Box, { flexDirection: "column", children: [_jsx(VirtualTranscript, { items: transcript, renderItem: renderTranscriptItem, autoScroll: true, inputFocus: inputFocus }), _jsx(Box, { flexDirection: "column", children: liveJsx }), busy && projection.liveItems.length === 0 && _jsx(GeneratingIndicator, { startedAtMs: turnStartRef.current, liveOutputTokens: liveOutputTokens }), pendingApproval !== null && approvalBusRef.current && (_jsx(ApprovalPrompt, { request: pendingApproval, onResolve: (decision) => {
962
1139
  approvalBusRef.current?.resolve(pendingApproval.id, decision);
963
1140
  } })), pendingFailover !== null && (_jsx(ModelSwitchPrompt, { failedModel: pendingFailover.failedModel, failoverModel: pendingFailover.failoverModel, onAccept: (failover) => {
964
1141
  const lastPrompt = pendingFailover.lastPrompt;
@@ -1013,28 +1190,40 @@ export function App(props) {
1013
1190
  // Esc inside ModelPicker → back to ProviderPicker (NOT close).
1014
1191
  setPickerStage("provider");
1015
1192
  setPickerProvider(null);
1016
- } })), overlays.active === "help" && (_jsx(HelpOverlay, { slashCommands: slashCommands, onClose: overlays.closeOverlay })), overlays.active === "theme" && (_jsx(ThemePicker, { current: themeName, onPick: handleThemePick, onCancel: overlays.closeOverlay })), pendingKey && (_jsx(KeySetOverlay, { keyName: pendingKey.keyName, onSave: handleKeySetSave, onCancel: () => setPendingKey(null) })), updateVersion !== null && (_jsx(Box, { paddingX: 1, children: _jsxs(Text, { color: "yellow", children: ["[v", updateVersion, " available \u2014 press Ctrl+U or /upgrade to upgrade]"] }) })), _jsx(StatusBar, { model: currentModel, provider: providerIdForModel(currentModel), inputTokens: projection.totals.inputTokens, outputTokens: projection.totals.outputTokens, costUsd: projection.totals.costUsd, cwd: props.cwd, busy: busy, mode: mode, contextWindow: contextWindowFor(currentModel), liveOutputTokens: liveOutputTokens, liveDurationMs: liveDurationMs, overflowDetected: flicker.overflowDetected, showMetrics: showRenderMetrics, renderMetrics: renderMetrics })] }) }) }));
1193
+ } })), overlays.active === "help" && (_jsx(HelpOverlay, { slashCommands: slashCommands, onClose: overlays.closeOverlay })), overlays.active === "theme" && (_jsx(ThemePicker, { current: themeName, onPick: handleThemePick, onCancel: overlays.closeOverlay })), overlays.active === "sandbox" && (_jsx(SandboxPicker, { current: sandboxModeRef.current, onPick: handleSandboxPick, onCancel: overlays.closeOverlay })), pendingKey && (_jsx(KeySetOverlay, { keyName: pendingKey.keyName, onSave: handleKeySetSave, onCancel: () => setPendingKey(null) })), updateVersion !== null && (_jsx(Box, { paddingX: 1, children: _jsxs(Text, { color: "yellow", children: ["[v", updateVersion, " available \u2014 press Ctrl+U or /upgrade to upgrade]"] }) })), _jsx(StatusBar, { model: currentModel, provider: providerIdForModel(currentModel), inputTokens: projection.totals.inputTokens, outputTokens: projection.totals.outputTokens, costUsd: projection.totals.costUsd, cwd: props.cwd, busy: busy, mode: mode, contextWindow: contextWindowFor(currentModel), liveOutputTokens: liveOutputTokens, liveDurationMs: liveDurationMs, overflowDetected: flicker.overflowDetected, showMetrics: showRenderMetrics, renderMetrics: renderMetrics })] }) }) }));
1017
1194
  }
1018
1195
  /**
1019
1196
  * Walk the transcript and fold consecutive `tool` items into a single
1020
- * <ToolGroup>. Non-tool items render via <TranscriptRow>. The grouping
1021
- * is intentionally simple — we look at adjacency, not assistant-turn
1022
- * boundaries, because the projection emits tools contiguously between
1023
- * `text` spans of the same turn.
1197
+ * <ToolGroup>. Fold 3+ consecutive `thinking` items into a single
1198
+ * <ThinkingBlockGroup>. Non-tool / non-thinking items render via
1199
+ * <TranscriptRow>.
1024
1200
  */
1025
- function renderTranscript(items) {
1201
+ function renderTranscript(items, thinkingStreaming) {
1026
1202
  const out = [];
1027
1203
  let toolBuf = [];
1204
+ let thinkBuf = [];
1028
1205
  const flushTools = () => {
1029
1206
  if (toolBuf.length === 0)
1030
1207
  return;
1031
- // Key on the stable ID of the first tool so React never unmounts/remounts
1032
- // the ToolGroup subtree when the counter resets (which caused flicker).
1033
1208
  out.push(_jsx(ToolGroup, { tools: toolBuf }, toolBuf[0].id));
1034
1209
  toolBuf = [];
1035
1210
  };
1211
+ const flushThinking = () => {
1212
+ if (thinkBuf.length === 0)
1213
+ return;
1214
+ if (thinkBuf.length >= 3) {
1215
+ out.push(_jsx(ThinkingBlockGroup, { blocks: thinkBuf }, thinkBuf[0].id));
1216
+ }
1217
+ else {
1218
+ for (const tb of thinkBuf) {
1219
+ out.push(_jsx(TranscriptRow, { item: { kind: "thinking", id: tb.id, content: tb.content }, isStreaming: thinkingStreaming }, tb.id));
1220
+ }
1221
+ }
1222
+ thinkBuf = [];
1223
+ };
1036
1224
  for (const item of items) {
1037
1225
  if (item.kind === "tool") {
1226
+ flushThinking();
1038
1227
  toolBuf.push({
1039
1228
  id: item.id,
1040
1229
  name: item.name,
@@ -1047,20 +1236,27 @@ function renderTranscript(items) {
1047
1236
  });
1048
1237
  continue;
1049
1238
  }
1239
+ if (item.kind === "thinking") {
1240
+ flushTools();
1241
+ thinkBuf.push({ id: item.id, content: item.content });
1242
+ continue;
1243
+ }
1050
1244
  flushTools();
1051
- out.push(_jsx(TranscriptRow, { item: item }, item.id));
1245
+ flushThinking();
1246
+ out.push(_jsx(TranscriptRow, { item: item, isStreaming: thinkingStreaming }, item.id));
1052
1247
  }
1053
1248
  flushTools();
1249
+ flushThinking();
1054
1250
  return out;
1055
1251
  }
1056
- function TranscriptRow({ item, }) {
1252
+ function TranscriptRow({ item, isStreaming = false, }) {
1057
1253
  switch (item.kind) {
1058
1254
  case "user":
1059
1255
  return (_jsxs(Box, { gap: 2, marginBottom: 1, children: [_jsx(Text, { color: "magenta", children: "\u276F" }), _jsx(Text, { color: "white", children: item.text })] }));
1060
1256
  case "text":
1061
1257
  return _jsx(StreamingText, { content: item.content });
1062
1258
  case "thinking":
1063
- return _jsx(ThinkingBlock, { content: item.content });
1259
+ return _jsx(ThinkingBlock, { content: item.content, isStreaming: isStreaming });
1064
1260
  case "tool":
1065
1261
  // Should not be reached — tools are folded by renderTranscript() into
1066
1262
  // <ToolGroup>. Kept as a safety net so an unexpected tool item still
@@ -1072,8 +1268,29 @@ function TranscriptRow({ item, }) {
1072
1268
  return (_jsx(Box, { marginBottom: 1, children: _jsx(Text, { color: "yellow", children: item.text }) }));
1073
1269
  }
1074
1270
  }
1271
+ function GeneratingIndicator(props) {
1272
+ const palette = useTheme();
1273
+ const [now, setNow] = React.useState(Date.now());
1274
+ React.useEffect(() => {
1275
+ const t = setInterval(() => setNow(Date.now()), 1000);
1276
+ return () => clearInterval(t);
1277
+ }, []);
1278
+ const elapsedSec = props.startedAtMs > 0 ? Math.round((now - props.startedAtMs) / 1000) : 0;
1279
+ const slow = elapsedSec >= 5 && props.liveOutputTokens === 0;
1280
+ const label = slow
1281
+ ? `warming up · ${elapsedSec}s · first token can take 10–30s on free models`
1282
+ : `generating · ${elapsedSec}s`;
1283
+ return (_jsxs(Box, { gap: 1, marginBottom: 1, children: [_jsx(SpinnerGlyph, { isActive: true, color: palette.text.secondary }), _jsx(Text, { color: palette.text.secondary, dimColor: true, children: label })] }));
1284
+ }
1075
1285
  function initialHistory(props) {
1286
+ if (_cachedInitialMessages !== null)
1287
+ return _cachedInitialMessages;
1076
1288
  const base = props.initialMessages ? [...props.initialMessages] : [];
1289
+ // Detect resumed sessions — if the caller passed user/assistant
1290
+ // messages, the session already has history and the LLM should NOT
1291
+ // emit a session-title marker (we'd be retrofitting one onto an
1292
+ // already-named conversation).
1293
+ const isFreshSession = !base.some((m) => m.role === "user" || m.role === "assistant");
1077
1294
  // Boot context: mode preamble + project primer (DIRGHA.md) +
1078
1295
  // caller's --system. Without this, the Ink TUI starts with zero
1079
1296
  // project awareness — same parity-matrix #1 fix as the one-shot
@@ -1087,32 +1304,21 @@ function initialHistory(props) {
1087
1304
  ledgerContext: props.ledgerContext,
1088
1305
  gitState: renderGitState(probeGitState(props.cwd)),
1089
1306
  userSystem: props.systemPrompt,
1307
+ firstTurn: isFreshSession,
1090
1308
  });
1091
1309
  base.unshift({ role: "system", content: composedSystem });
1310
+ _cachedInitialMessages = base;
1092
1311
  return base;
1093
1312
  }
1094
1313
  function providerIdForModel(model) {
1095
- // Light heuristic so StatusBar has a hint without importing dispatch.
1096
- // Real routing still lives in providers/dispatch.ts at run time.
1097
- if (model.includes("claude"))
1098
- return "anthropic";
1099
- if (model.includes("gpt") || model.startsWith("o1") || model.startsWith("o3"))
1100
- return "openai";
1101
- if (model.includes("gemini"))
1102
- return "gemini";
1103
- if (model.includes("deepseek"))
1104
- return "deepseek";
1105
- if (model.includes("kimi") || model.includes("moonshot"))
1106
- return "nvidia";
1107
- if (model.includes("llama") ||
1108
- model.includes("nvidia") ||
1109
- model.includes("minimax"))
1110
- return "nvidia";
1111
- if (model.includes("fireworks"))
1112
- return "fireworks";
1113
- if (model.includes("/"))
1114
- return "openrouter";
1115
- return "local";
1314
+ // Delegate to providers/dispatch.ts so the StatusBar readout
1315
+ // matches the actual runtime routing at all times.
1316
+ try {
1317
+ return routeModel(model);
1318
+ }
1319
+ catch {
1320
+ return "local";
1321
+ }
1116
1322
  }
1117
1323
  const PROVIDER_BLURB = {
1118
1324
  anthropic: "Claude — Opus, Sonnet, Haiku",
@@ -1171,6 +1377,24 @@ const PROVIDER_LABEL = {
1171
1377
  zai: "Z.AI / GLM",
1172
1378
  local: "Local",
1173
1379
  };
1380
+ /**
1381
+ * Synchronously check whether an env var exists in ~/.dirgha/keys.json.
1382
+ * Used by buildProviderEntries as a fallback when process.env doesn't
1383
+ * contain the key yet (race with startup hydration).
1384
+ */
1385
+ function tryReadKeyFromStore(envVar) {
1386
+ try {
1387
+ const path = pathJoin(homedir(), ".dirgha", "keys.json");
1388
+ if (!existsSync(path))
1389
+ return false;
1390
+ const raw = readFileSync(path, "utf8");
1391
+ const store = JSON.parse(raw);
1392
+ return typeof store[envVar] === "string" && store[envVar].length > 0;
1393
+ }
1394
+ catch {
1395
+ return false;
1396
+ }
1397
+ }
1174
1398
  /**
1175
1399
  * Group the flat model catalogue into per-provider entries for stage 1
1176
1400
  * of the picker. Skips providers with zero models in the catalogue.
@@ -1186,7 +1410,13 @@ function buildProviderEntries(models, currentModel) {
1186
1410
  const out = [];
1187
1411
  for (const [id, items] of buckets) {
1188
1412
  const env = PROVIDER_ENV[id];
1189
- const hasKey = env ? !!process.env[env] : true; // local providers don't need keys
1413
+ // Check env vars AND keys.json (env vars win). keys.json is hydrated
1414
+ // into process.env by hydrateEnvFromKeyStore at startup, but this
1415
+ // synchronous fallback handles the edge case where hydration hasn't
1416
+ // run yet (e.g. TUI mounts before startup hydration completes).
1417
+ const hasKey = env
1418
+ ? !!process.env[env] || !!tryReadKeyFromStore(env)
1419
+ : true; // local providers don't need keys
1190
1420
  out.push({
1191
1421
  id,
1192
1422
  label: PROVIDER_LABEL[id] ?? id,