@dirgha/code 1.22.0 → 1.24.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 (321) 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 +13 -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 +61 -1
  16. package/dist/cli/interactive.js.map +1 -1
  17. package/dist/cli/main.js +82 -23
  18. package/dist/cli/main.js.map +1 -1
  19. package/dist/cli/setup.js +1 -0
  20. package/dist/cli/setup.js.map +1 -1
  21. package/dist/cli/slash/fleet.js +28 -3
  22. package/dist/cli/slash/fleet.js.map +1 -1
  23. package/dist/cli/slash/index.d.ts +2 -1
  24. package/dist/cli/slash/index.js +3 -1
  25. package/dist/cli/slash/index.js.map +1 -1
  26. package/dist/cli/slash/models.js +339 -7
  27. package/dist/cli/slash/models.js.map +1 -1
  28. package/dist/cli/slash/paste.js +4 -7
  29. package/dist/cli/slash/paste.js.map +1 -1
  30. package/dist/cli/slash/provider.d.ts +1 -0
  31. package/dist/cli/slash/provider.js +33 -1
  32. package/dist/cli/slash/provider.js.map +1 -1
  33. package/dist/cli/slash/sandbox.d.ts +21 -0
  34. package/dist/cli/slash/sandbox.js +84 -0
  35. package/dist/cli/slash/sandbox.js.map +1 -0
  36. package/dist/cli/slash.d.ts +5 -0
  37. package/dist/cli/slash.js +26 -10
  38. package/dist/cli/slash.js.map +1 -1
  39. package/dist/cli/subcommands/audit.js +28 -8
  40. package/dist/cli/subcommands/audit.js.map +1 -1
  41. package/dist/cli/subcommands/doctor.d.ts +4 -0
  42. package/dist/cli/subcommands/doctor.js +117 -21
  43. package/dist/cli/subcommands/doctor.js.map +1 -1
  44. package/dist/cli/subcommands/feature-setup.js +6 -6
  45. package/dist/cli/subcommands/feature-setup.js.map +1 -1
  46. package/dist/cli/subcommands/memory.js +23 -0
  47. package/dist/cli/subcommands/memory.js.map +1 -1
  48. package/dist/cli/subcommands/telemetry.d.ts +2 -1
  49. package/dist/cli/subcommands/telemetry.js +47 -34
  50. package/dist/cli/subcommands/telemetry.js.map +1 -1
  51. package/dist/context/_fts.js +4 -1
  52. package/dist/context/_fts.js.map +1 -1
  53. package/dist/context/branch.d.ts +2 -2
  54. package/dist/context/branch.js +40 -23
  55. package/dist/context/branch.js.map +1 -1
  56. package/dist/context/compaction.js +44 -21
  57. package/dist/context/compaction.js.map +1 -1
  58. package/dist/context/default-soul.md +1 -0
  59. package/dist/context/git-state.js +31 -18
  60. package/dist/context/git-state.js.map +1 -1
  61. package/dist/context/knowledge.js +31 -20
  62. package/dist/context/knowledge.js.map +1 -1
  63. package/dist/context/memory.js +8 -1
  64. package/dist/context/memory.js.map +1 -1
  65. package/dist/context/mode-enforcement.js +11 -1
  66. package/dist/context/mode-enforcement.js.map +1 -1
  67. package/dist/context/mode.js +67 -30
  68. package/dist/context/mode.js.map +1 -1
  69. package/dist/context/primer.d.ts +17 -0
  70. package/dist/context/primer.js +50 -3
  71. package/dist/context/primer.js.map +1 -1
  72. package/dist/context/session.d.ts +4 -0
  73. package/dist/context/session.js.map +1 -1
  74. package/dist/daemon/server.js +17 -3
  75. package/dist/daemon/server.js.map +1 -1
  76. package/dist/embeddings/iface.d.ts +26 -0
  77. package/dist/embeddings/iface.js +15 -0
  78. package/dist/embeddings/iface.js.map +1 -0
  79. package/dist/embeddings/local.d.ts +24 -0
  80. package/dist/embeddings/local.js +112 -0
  81. package/dist/embeddings/local.js.map +1 -0
  82. package/dist/embeddings/remote.d.ts +31 -0
  83. package/dist/embeddings/remote.js +88 -0
  84. package/dist/embeddings/remote.js.map +1 -0
  85. package/dist/embeddings/select.d.ts +24 -0
  86. package/dist/embeddings/select.js +39 -0
  87. package/dist/embeddings/select.js.map +1 -0
  88. package/dist/fleet/apply-back.js +5 -1
  89. package/dist/fleet/apply-back.js.map +1 -1
  90. package/dist/fleet/cli-command.d.ts +2 -0
  91. package/dist/fleet/cli-command.js +15 -1
  92. package/dist/fleet/cli-command.js.map +1 -1
  93. package/dist/fleet/runner.js +35 -2
  94. package/dist/fleet/runner.js.map +1 -1
  95. package/dist/fleet/scratchpad.js +1 -2
  96. package/dist/fleet/scratchpad.js.map +1 -1
  97. package/dist/fleet/state.d.ts +4 -0
  98. package/dist/fleet/state.js +11 -2
  99. package/dist/fleet/state.js.map +1 -1
  100. package/dist/fleet/templates.d.ts +4 -0
  101. package/dist/fleet/templates.js.map +1 -1
  102. package/dist/fleet/types.d.ts +4 -0
  103. package/dist/fleet/types.js.map +1 -1
  104. package/dist/intelligence/failover-chain.js +10 -1
  105. package/dist/intelligence/failover-chain.js.map +1 -1
  106. package/dist/intelligence/prices.d.ts +6 -4
  107. package/dist/intelligence/prices.js +45 -11
  108. package/dist/intelligence/prices.js.map +1 -1
  109. package/dist/kernel/abort-utils.d.ts +4 -0
  110. package/dist/kernel/abort-utils.js +45 -0
  111. package/dist/kernel/abort-utils.js.map +1 -0
  112. package/dist/kernel/agent-loop.js +104 -25
  113. package/dist/kernel/agent-loop.js.map +1 -1
  114. package/dist/kernel/tool-timeout.d.ts +27 -0
  115. package/dist/kernel/tool-timeout.js +53 -0
  116. package/dist/kernel/tool-timeout.js.map +1 -0
  117. package/dist/kernel/types.d.ts +3 -0
  118. package/dist/lsp/client.js +29 -16
  119. package/dist/lsp/client.js.map +1 -1
  120. package/dist/lsp/detector.js +7 -6
  121. package/dist/lsp/detector.js.map +1 -1
  122. package/dist/mcp/client.d.ts +1 -1
  123. package/dist/mcp/client.js +19 -16
  124. package/dist/mcp/client.js.map +1 -1
  125. package/dist/mcp/transport.js +46 -38
  126. package/dist/mcp/transport.js.map +1 -1
  127. package/dist/providers/custom-provider.d.ts +31 -0
  128. package/dist/providers/custom-provider.js +72 -0
  129. package/dist/providers/custom-provider.js.map +1 -0
  130. package/dist/providers/deepseek.js +1 -1
  131. package/dist/providers/deepseek.js.map +1 -1
  132. package/dist/providers/dispatch.d.ts +1 -1
  133. package/dist/providers/dispatch.js +25 -2
  134. package/dist/providers/dispatch.js.map +1 -1
  135. package/dist/providers/family-fallback.js +5 -0
  136. package/dist/providers/family-fallback.js.map +1 -1
  137. package/dist/providers/gemini.js +33 -3
  138. package/dist/providers/gemini.js.map +1 -1
  139. package/dist/providers/index.d.ts +16 -0
  140. package/dist/providers/index.js +43 -2
  141. package/dist/providers/index.js.map +1 -1
  142. package/dist/providers/machine1.d.ts +30 -0
  143. package/dist/providers/machine1.js +341 -0
  144. package/dist/providers/machine1.js.map +1 -0
  145. package/dist/providers/nvidia.js +1 -1
  146. package/dist/providers/nvidia.js.map +1 -1
  147. package/dist/providers/openai-compat.d.ts +1 -0
  148. package/dist/providers/openai-compat.js +32 -9
  149. package/dist/providers/openai-compat.js.map +1 -1
  150. package/dist/providers/openrouter.js +5 -2
  151. package/dist/providers/openrouter.js.map +1 -1
  152. package/dist/safety/audit-log.d.ts +15 -0
  153. package/dist/safety/audit-log.js +21 -0
  154. package/dist/safety/audit-log.js.map +1 -1
  155. package/dist/state/db-telemetry.js +11 -1
  156. package/dist/state/db-telemetry.js.map +1 -1
  157. package/dist/state/db.d.ts +7 -0
  158. package/dist/state/db.js +147 -3
  159. package/dist/state/db.js.map +1 -1
  160. package/dist/state/index.js +8 -4
  161. package/dist/state/index.js.map +1 -1
  162. package/dist/state/sync-index.d.ts +74 -0
  163. package/dist/state/sync-index.js +246 -0
  164. package/dist/state/sync-index.js.map +1 -0
  165. package/dist/state/transaction.d.ts +62 -0
  166. package/dist/state/transaction.js +65 -0
  167. package/dist/state/transaction.js.map +1 -0
  168. package/dist/state/vec.d.ts +28 -0
  169. package/dist/state/vec.js +113 -0
  170. package/dist/state/vec.js.map +1 -0
  171. package/dist/telemetry/gateway-push.d.ts +17 -0
  172. package/dist/telemetry/gateway-push.js +48 -0
  173. package/dist/telemetry/gateway-push.js.map +1 -0
  174. package/dist/telemetry/index.d.ts +9 -0
  175. package/dist/telemetry/index.js +9 -0
  176. package/dist/telemetry/index.js.map +1 -0
  177. package/dist/tools/browser.js +24 -16
  178. package/dist/tools/browser.js.map +1 -1
  179. package/dist/tools/checkpoint.d.ts +6 -1
  180. package/dist/tools/checkpoint.js +94 -63
  181. package/dist/tools/checkpoint.js.map +1 -1
  182. package/dist/tools/cron.js +1 -3
  183. package/dist/tools/cron.js.map +1 -1
  184. package/dist/tools/db-workspace-info.d.ts +10 -0
  185. package/dist/tools/db-workspace-info.js +76 -0
  186. package/dist/tools/db-workspace-info.js.map +1 -0
  187. package/dist/tools/diff.js +25 -21
  188. package/dist/tools/diff.js.map +1 -1
  189. package/dist/tools/exec.d.ts +6 -1
  190. package/dist/tools/exec.js +46 -4
  191. package/dist/tools/exec.js.map +1 -1
  192. package/dist/tools/fs-edit.d.ts +3 -5
  193. package/dist/tools/fs-edit.js +8 -23
  194. package/dist/tools/fs-edit.js.map +1 -1
  195. package/dist/tools/fs-ls.js +6 -8
  196. package/dist/tools/fs-ls.js.map +1 -1
  197. package/dist/tools/fs-read.d.ts +1 -1
  198. package/dist/tools/fs-read.js +37 -28
  199. package/dist/tools/fs-read.js.map +1 -1
  200. package/dist/tools/fs-write.d.ts +1 -1
  201. package/dist/tools/fs-write.js +33 -33
  202. package/dist/tools/fs-write.js.map +1 -1
  203. package/dist/tools/git.js +13 -6
  204. package/dist/tools/git.js.map +1 -1
  205. package/dist/tools/github.d.ts +13 -0
  206. package/dist/tools/github.js +257 -0
  207. package/dist/tools/github.js.map +1 -0
  208. package/dist/tools/graph-neighbors.d.ts +9 -0
  209. package/dist/tools/graph-neighbors.js +77 -0
  210. package/dist/tools/graph-neighbors.js.map +1 -0
  211. package/dist/tools/graph-traverse.d.ts +10 -0
  212. package/dist/tools/graph-traverse.js +90 -0
  213. package/dist/tools/graph-traverse.js.map +1 -0
  214. package/dist/tools/index.d.ts +10 -2
  215. package/dist/tools/index.js +17 -4
  216. package/dist/tools/index.js.map +1 -1
  217. package/dist/tools/kb-search.d.ts +13 -0
  218. package/dist/tools/kb-search.js +113 -0
  219. package/dist/tools/kb-search.js.map +1 -0
  220. package/dist/tools/multimodal.js +30 -15
  221. package/dist/tools/multimodal.js.map +1 -1
  222. package/dist/tools/permission.js +5 -4
  223. package/dist/tools/permission.js.map +1 -1
  224. package/dist/tools/registry.d.ts +10 -0
  225. package/dist/tools/registry.js.map +1 -1
  226. package/dist/tools/rtk.js +28 -9
  227. package/dist/tools/rtk.js.map +1 -1
  228. package/dist/tools/search-glob.d.ts +1 -1
  229. package/dist/tools/search-glob.js +46 -24
  230. package/dist/tools/search-glob.js.map +1 -1
  231. package/dist/tools/search-grep.d.ts +1 -1
  232. package/dist/tools/search-grep.js +56 -32
  233. package/dist/tools/search-grep.js.map +1 -1
  234. package/dist/tools/shell.d.ts +7 -1
  235. package/dist/tools/shell.js +178 -61
  236. package/dist/tools/shell.js.map +1 -1
  237. package/dist/tools/transactional-write.d.ts +10 -0
  238. package/dist/tools/transactional-write.js +132 -0
  239. package/dist/tools/transactional-write.js.map +1 -0
  240. package/dist/tui/approval.js +31 -3
  241. package/dist/tui/approval.js.map +1 -1
  242. package/dist/tui/ink/App.d.ts +2 -1
  243. package/dist/tui/ink/App.js +333 -79
  244. package/dist/tui/ink/App.js.map +1 -1
  245. package/dist/tui/ink/components/DenseToolMessage.js +20 -3
  246. package/dist/tui/ink/components/DenseToolMessage.js.map +1 -1
  247. package/dist/tui/ink/components/InputBox.d.ts +4 -0
  248. package/dist/tui/ink/components/InputBox.js +38 -21
  249. package/dist/tui/ink/components/InputBox.js.map +1 -1
  250. package/dist/tui/ink/components/KeySetOverlay.d.ts +1 -1
  251. package/dist/tui/ink/components/KeySetOverlay.js +18 -16
  252. package/dist/tui/ink/components/KeySetOverlay.js.map +1 -1
  253. package/dist/tui/ink/components/Logo.d.ts +20 -0
  254. package/dist/tui/ink/components/Logo.js +67 -1
  255. package/dist/tui/ink/components/Logo.js.map +1 -1
  256. package/dist/tui/ink/components/ModelPicker.d.ts +2 -2
  257. package/dist/tui/ink/components/ModelPicker.js +34 -26
  258. package/dist/tui/ink/components/ModelPicker.js.map +1 -1
  259. package/dist/tui/ink/components/PasteCollapse.d.ts +3 -1
  260. package/dist/tui/ink/components/PasteCollapse.js +11 -9
  261. package/dist/tui/ink/components/PasteCollapse.js.map +1 -1
  262. package/dist/tui/ink/components/PromptQueueIndicator.js +1 -1
  263. package/dist/tui/ink/components/PromptQueueIndicator.js.map +1 -1
  264. package/dist/tui/ink/components/SandboxPicker.d.ts +18 -0
  265. package/dist/tui/ink/components/SandboxPicker.js +77 -0
  266. package/dist/tui/ink/components/SandboxPicker.js.map +1 -0
  267. package/dist/tui/ink/components/SpinnerGlyph.d.ts +4 -4
  268. package/dist/tui/ink/components/SpinnerGlyph.js +34 -14
  269. package/dist/tui/ink/components/SpinnerGlyph.js.map +1 -1
  270. package/dist/tui/ink/components/StatusBar.d.ts +3 -7
  271. package/dist/tui/ink/components/StatusBar.js +2 -11
  272. package/dist/tui/ink/components/StatusBar.js.map +1 -1
  273. package/dist/tui/ink/components/ThinkingBlock.d.ts +15 -4
  274. package/dist/tui/ink/components/ThinkingBlock.js +34 -17
  275. package/dist/tui/ink/components/ThinkingBlock.js.map +1 -1
  276. package/dist/tui/ink/components/ToolBox.js +21 -13
  277. package/dist/tui/ink/components/ToolBox.js.map +1 -1
  278. package/dist/tui/ink/components/VirtualTranscript.d.ts +1 -1
  279. package/dist/tui/ink/components/VirtualTranscript.js +5 -3
  280. package/dist/tui/ink/components/VirtualTranscript.js.map +1 -1
  281. package/dist/tui/ink/index.js +36 -14
  282. package/dist/tui/ink/index.js.map +1 -1
  283. package/dist/tui/ink/ink-approval-bus.d.ts +2 -0
  284. package/dist/tui/ink/ink-approval-bus.js +10 -0
  285. package/dist/tui/ink/ink-approval-bus.js.map +1 -1
  286. package/dist/tui/ink/markdown/display.js +9 -2
  287. package/dist/tui/ink/markdown/display.js.map +1 -1
  288. package/dist/tui/ink/markdown/split-point.js +8 -13
  289. package/dist/tui/ink/markdown/split-point.js.map +1 -1
  290. package/dist/tui/ink/markdown/syntax-highlight.d.ts +13 -0
  291. package/dist/tui/ink/markdown/syntax-highlight.js +91 -0
  292. package/dist/tui/ink/markdown/syntax-highlight.js.map +1 -0
  293. package/dist/tui/ink/theme-context.js +6 -3
  294. package/dist/tui/ink/theme-context.js.map +1 -1
  295. package/dist/tui/ink/use-declined-versions.js +6 -2
  296. package/dist/tui/ink/use-declined-versions.js.map +1 -1
  297. package/dist/tui/ink/use-elapsed.d.ts +9 -1
  298. package/dist/tui/ink/use-elapsed.js +17 -2
  299. package/dist/tui/ink/use-elapsed.js.map +1 -1
  300. package/dist/tui/ink/use-event-projection.d.ts +10 -0
  301. package/dist/tui/ink/use-event-projection.js +111 -12
  302. package/dist/tui/ink/use-event-projection.js.map +1 -1
  303. package/dist/tui/ink/use-flicker-detector.js +9 -0
  304. package/dist/tui/ink/use-flicker-detector.js.map +1 -1
  305. package/dist/tui/ink/use-overlays.d.ts +2 -2
  306. package/dist/tui/ink/use-overlays.js +20 -17
  307. package/dist/tui/ink/use-overlays.js.map +1 -1
  308. package/dist/tui/ink/use-render-metrics.js +18 -5
  309. package/dist/tui/ink/use-render-metrics.js.map +1 -1
  310. package/dist/tui/ink/use-tool-progress.d.ts +7 -0
  311. package/dist/tui/ink/use-tool-progress.js +39 -0
  312. package/dist/tui/ink/use-tool-progress.js.map +1 -0
  313. package/dist/tui/ink/use-transcript-scroll.js +14 -6
  314. package/dist/tui/ink/use-transcript-scroll.js.map +1 -1
  315. package/dist/utils/env.d.ts +1 -0
  316. package/dist/utils/env.js +60 -0
  317. package/dist/utils/env.js.map +1 -0
  318. package/dist/utils/fs.d.ts +10 -0
  319. package/dist/utils/fs.js +37 -0
  320. package/dist/utils/fs.js.map +1 -0
  321. package/package.json +12 -8
@@ -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,18 +15,19 @@ 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";
22
22
  import { maybeCompact } from "../../context/compaction.js";
23
- import { contextWindowFor } from "../../intelligence/prices.js";
23
+ import { contextWindowFor, resolveModelAlias } from "../../intelligence/prices.js";
24
24
  import { buildAgentHooksFromConfig } from "../../hooks/config-bridge.js";
25
25
  import { enforceMode, composeHooks } from "../../context/mode-enforcement.js";
26
26
  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,13 +53,17 @@ 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";
62
65
  import { useOverlays } from "./use-overlays.js";
66
+ import { useToolProgress } from "./use-tool-progress.js";
63
67
  import { useDeclinedVersions } from "./use-declined-versions.js";
64
68
  import { useStartupHealth } from "./use-startup-health.js";
65
69
  import { useFlickerDetector } from "./use-flicker-detector.js";
@@ -69,7 +73,7 @@ import { createRequire } from "node:module";
69
73
  // Pulled from the installed package.json so the TUI title matches the
70
74
  // shipped binary version. Falls back to '0.0.0-dev' if the file isn't
71
75
  // reachable (e.g. an unusual deploy layout).
72
- const VERSION = (() => {
76
+ export const VERSION = (() => {
73
77
  try {
74
78
  const req = createRequire(import.meta.url);
75
79
  const pkg = req("../../../package.json");
@@ -79,13 +83,30 @@ const VERSION = (() => {
79
83
  return "0.0.0-dev";
80
84
  }
81
85
  })();
86
+ // Cache for initialHistory — avoids sync fs I/O in the render phase
87
+ // on re-calls (e.g. /clear). The underlying files rarely change within
88
+ // a session so a single snapshot is sufficient.
89
+ let _cachedInitialMessages = null;
82
90
  export function App(props) {
83
91
  const { exit } = useApp();
84
92
  const sessionIdRef = React.useRef(randomUUID());
85
93
  const historyRef = React.useRef(initialHistory(props));
86
94
  const abortRef = React.useRef(null);
95
+ // Stores the user-facing cancellation message so the finally block can
96
+ // inject it via appendLiveSync (avoids the React state-updater race
97
+ // where appendLive doesn't update liveItemsRef before commitLive reads it).
98
+ const interruptMsgRef = React.useRef(null);
87
99
  const pendingModelRef = React.useRef(null);
88
100
  const sessionRef = React.useRef(null);
101
+ // Tracks whether the model has produced its first response in this
102
+ // session. The system prompt includes a one-line `[session-title]`
103
+ // instruction only on the first turn; after the first agent_end the
104
+ // instruction is stripped out so it does not appear on every turn.
105
+ const firstTurnRef = React.useRef(!(props.initialMessages ?? []).some((m) => m.role === "user" || m.role === "assistant"));
106
+ // Live sandbox mode — initialised from config, mutated by /sandbox.
107
+ // Read by the executor wiring on every tool dispatch so the toggle
108
+ // takes effect on the next tool call without re-mounting the App.
109
+ const sandboxModeRef = React.useRef(props.config.sandbox ?? "off");
89
110
  React.useEffect(() => {
90
111
  const id = sessionIdRef.current;
91
112
  void props.sessions.create(id).then((s) => {
@@ -109,10 +130,16 @@ export function App(props) {
109
130
  const [transcript, setTranscript] = React.useState([]);
110
131
  const [input, setInput] = React.useState("");
111
132
  const [busy, setBusy] = React.useState(false);
133
+ const [thinkingStreaming, setThinkingStreaming] = React.useState(false);
112
134
  // Prompt queue: while a turn is streaming the user can still type and
113
135
  // press Enter. Submissions land here instead of being dropped, then
114
136
  // drain FIFO when the turn finishes (see useEffect below).
115
137
  const [promptQueue, setPromptQueue] = React.useState([]);
138
+ // Mirror promptQueue in a ref so callbacks can read the latest value
139
+ // without capturing stale closures and without causing dependency cycles.
140
+ const promptQueueRef = React.useRef([]);
141
+ promptQueueRef.current = promptQueue;
142
+ const activeTools = useToolProgress(props.events);
116
143
  const [currentModel, setCurrentModel] = React.useState(props.config.model);
117
144
  // Inline key entry: set when a provider throws "X_API_KEY is required"
118
145
  // (either at model-pick time or when a turn fires). Cleared on save/cancel.
@@ -145,9 +172,11 @@ export function App(props) {
145
172
  // turns. Replaces the legacy `createTuiApprovalBus` that wrote prompts
146
173
  // direct to stdout (overdrawn by Ink) and read stdin raw (hung on
147
174
  // Windows). See `ink-approval-bus.ts` for the full rationale.
148
- const approvalBusRef = React.useRef();
175
+ const approvalBusRef = React.useRef(null);
149
176
  if (!approvalBusRef.current) {
150
- approvalBusRef.current = createInkApprovalBus(new Set(props.config.autoApproveTools));
177
+ const autoApproveSet = new Set(props.config.autoApproveTools);
178
+ autoApproveSet.add("rtk"); // RTK is a safe shell wrapper, never needs approval
179
+ approvalBusRef.current = createInkApprovalBus(autoApproveSet);
151
180
  }
152
181
  const [pendingApproval, setPendingApproval] = React.useState(null);
153
182
  React.useEffect(() => {
@@ -166,7 +195,55 @@ export function App(props) {
166
195
  onCommitSplit: React.useCallback((item) => {
167
196
  setTranscript((prev) => [...prev, item]);
168
197
  }, []),
198
+ // First-turn `[session-title] X` marker support. The projection
199
+ // strips the marker line from the transcript; here we surface the
200
+ // captured title as: (a) the OSC 0 terminal title, (b) a persisted
201
+ // session entry, (c) React state for any future `/sessions` UI.
202
+ isFirstTurn: React.useCallback(() => firstTurnRef.current, []),
203
+ onSessionTitle: React.useCallback((title) => {
204
+ // Strip control characters from LLM-supplied title before
205
+ // injecting into an OSC sequence — a raw 0x07/0x9c would close
206
+ // the OSC string early and let the model inject arbitrary
207
+ // terminal codes. Codepoint filter avoids eslint's
208
+ // `no-control-regex` rule (which fires on both literal and
209
+ // string-constructed regexes).
210
+ const safe = Array.from(title)
211
+ .filter((c) => {
212
+ const cp = c.charCodeAt(0);
213
+ return cp >= 0x20 && cp !== 0x7f;
214
+ })
215
+ .join("")
216
+ .slice(0, 80)
217
+ .trim();
218
+ if (!safe)
219
+ return;
220
+ sessionTitleRef.current = safe;
221
+ try {
222
+ if (process.stdout.isTTY) {
223
+ process.stdout.write(`\x1b]0;Dirgha · ${safe}\x07`);
224
+ }
225
+ }
226
+ catch {
227
+ /* OSC write best-effort */
228
+ }
229
+ const s = sessionRef.current;
230
+ if (s) {
231
+ void s
232
+ .append({
233
+ type: "title",
234
+ ts: new Date().toISOString(),
235
+ title: safe,
236
+ })
237
+ .catch(() => {
238
+ /* persistence best-effort — non-blocking */
239
+ });
240
+ }
241
+ }, []),
169
242
  });
243
+ // Holds the most recent session title (set by the projection's
244
+ // `onSessionTitle` callback). Read by future surfaces (/sessions
245
+ // list, status bar, etc) — not currently displayed in v1.20.40.
246
+ const sessionTitleRef = React.useRef(null);
170
247
  const overlays = useOverlays();
171
248
  // Live counters for the in-progress turn — drive the StatusBar
172
249
  // tok/s readout. Reset at agent_start, accumulate output deltas,
@@ -292,8 +369,18 @@ export function App(props) {
292
369
  liveOutputTokensAccRef.current = 0;
293
370
  setLiveOutputTokens(0);
294
371
  setLiveDurationMs(0);
372
+ setThinkingStreaming(false);
373
+ }
374
+ else if (ev.type === "thinking_start") {
375
+ setThinkingStreaming(true);
376
+ }
377
+ else if (ev.type === "thinking_end") {
378
+ setThinkingStreaming(false);
295
379
  }
296
380
  else if (ev.type === "text_delta" || ev.type === "thinking_delta") {
381
+ // Approximate tokens as chars ÷ 4 — a common heuristic for English
382
+ // text where avg token length is ~4 characters. Not exact but keeps
383
+ // the tok/s rate plausible without an expensive tokenizer.
297
384
  liveOutputTokensAccRef.current += (ev.delta?.length ?? 0) / 4;
298
385
  }
299
386
  else if (ev.type === "usage") {
@@ -305,10 +392,36 @@ export function App(props) {
305
392
  setLiveDurationMs(0);
306
393
  setLiveOutputTokens(0);
307
394
  liveOutputTokensAccRef.current = 0;
395
+ // After the first response completes, refresh the system
396
+ // message to drop the one-line session-title instruction so
397
+ // the model does not keep emitting `[session-title]` on every
398
+ // subsequent turn. Composing here uses cached project primer
399
+ // + soul (cheap) and only runs once per session.
400
+ if (firstTurnRef.current) {
401
+ firstTurnRef.current = false;
402
+ const msgs = historyRef.current;
403
+ if (msgs.length > 0 && msgs[0].role === "system") {
404
+ const primer = loadProjectPrimer(props.cwd);
405
+ const soul = loadSoul();
406
+ const refreshedSystem = composeSystemPrompt({
407
+ soul: soul.text,
408
+ modePreamble: modePreamble(mode),
409
+ primer: primer.primer,
410
+ ledgerContext: props.ledgerContext,
411
+ gitState: renderGitState(probeGitState(props.cwd)),
412
+ userSystem: props.systemPrompt,
413
+ firstTurn: false,
414
+ });
415
+ historyRef.current = [
416
+ { role: "system", content: refreshedSystem },
417
+ ...msgs.slice(1),
418
+ ];
419
+ }
420
+ }
308
421
  }
309
422
  });
310
423
  return unsub;
311
- }, [props.events]);
424
+ }, [props.events, mode, props.cwd, props.ledgerContext, props.systemPrompt]);
312
425
  // globalSpinnerFrame removed — spinner interval now lives inside
313
426
  // SpinnerGlyph so only the glyph subtree re-renders at 80ms, not the
314
427
  // entire App tree.
@@ -396,7 +509,7 @@ export function App(props) {
396
509
  });
397
510
  // A new submission supersedes any pending failover prompt.
398
511
  setPendingFailover(null);
399
- if (value === "/exit" || value === "/quit") {
512
+ if (value === "/exit" || value === "/quit" || value === "/stop") {
400
513
  exit();
401
514
  return;
402
515
  }
@@ -412,25 +525,41 @@ export function App(props) {
412
525
  return;
413
526
  }
414
527
  if (value.startsWith("/model ")) {
415
- const id = value.slice("/model ".length).trim();
416
- if (id !== "") {
417
- const valid = PRICES.some((p) => p.model === id);
418
- if (!valid) {
528
+ const rawId = value.slice("/model ".length).trim();
529
+ if (rawId !== "") {
530
+ // Resolve aliases (e.g. "ring" → "inclusionai/ring-2.6-1t:free")
531
+ // before matching against the catalogue, mirroring the CLI flag path.
532
+ const id = resolveModelAlias(rawId);
533
+ // Exact match first, then suffix fallback — mirrors slash.ts /model handler.
534
+ const exactMatch = PRICES.find((p) => p.model === id);
535
+ if (exactMatch) {
536
+ setCurrentModel(exactMatch.model);
419
537
  const note = {
420
538
  kind: "notice",
421
539
  id: randomUUID(),
422
- text: `Invalid model: ${id}. Use /models to see the catalogue.`,
540
+ text: `Model set to ${exactMatch.model}`,
423
541
  };
424
542
  setTranscript((prev) => [...prev, note]);
425
543
  }
426
544
  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]);
545
+ const suffixMatch = PRICES.find((p) => p.model.endsWith("/" + id));
546
+ if (suffixMatch) {
547
+ setCurrentModel(suffixMatch.model);
548
+ const note = {
549
+ kind: "notice",
550
+ id: randomUUID(),
551
+ text: `Model set to ${suffixMatch.model}`,
552
+ };
553
+ setTranscript((prev) => [...prev, note]);
554
+ }
555
+ else {
556
+ const note = {
557
+ kind: "notice",
558
+ id: randomUUID(),
559
+ text: `Invalid model: ${rawId}. Use /models to see the catalogue.`,
560
+ };
561
+ setTranscript((prev) => [...prev, note]);
562
+ }
434
563
  }
435
564
  }
436
565
  return;
@@ -444,6 +573,11 @@ export function App(props) {
444
573
  overlays.openOverlay("theme");
445
574
  return;
446
575
  }
576
+ // `/sandbox` with no args opens the picker; `/sandbox <mode>` sets directly.
577
+ if (value === "/sandbox") {
578
+ overlays.openOverlay("sandbox");
579
+ return;
580
+ }
447
581
  // /upgrade and /self-update trigger npm install + restart.
448
582
  if (value === "/upgrade" ||
449
583
  value === "/self-update" ||
@@ -520,7 +654,11 @@ export function App(props) {
520
654
  exit();
521
655
  process.exit(code);
522
656
  },
523
- getToken: () => tokenRef.current,
657
+ getToken: () => {
658
+ // Token loads asynchronously after mount; return null
659
+ // gracefully so slash commands don't crash on first call.
660
+ return tokenRef.current;
661
+ },
524
662
  setToken: (newToken) => {
525
663
  tokenRef.current = newToken;
526
664
  },
@@ -542,6 +680,10 @@ export function App(props) {
542
680
  setMode: (m) => setMode(m),
543
681
  getTheme: () => props.config.theme ?? "readable",
544
682
  setTheme: () => undefined,
683
+ getSandbox: () => sandboxModeRef.current,
684
+ setSandbox: (next) => {
685
+ sandboxModeRef.current = next;
686
+ },
545
687
  getSession: () => null,
546
688
  getSessionStore: () => props.sessions,
547
689
  getProvider: () => props.providers.forModel(currentModel),
@@ -658,6 +800,7 @@ export function App(props) {
658
800
  registry: props.registry,
659
801
  cwd: props.cwd,
660
802
  sessionId: sessionIdRef.current,
803
+ sandboxMode: sandboxModeRef.current,
661
804
  onProgress: (toolId, message) => {
662
805
  props.events.emit({
663
806
  type: "tool_exec_progress",
@@ -709,7 +852,10 @@ export function App(props) {
709
852
  }
710
853
  catch (err) {
711
854
  const msg = err instanceof Error ? err.message : String(err);
712
- const keyMatch = /^([A-Z][A-Z0-9_]+_API_KEY) is required/.exec(msg);
855
+ // Only match provider-key errors, not errors from deep inside the agent
856
+ // loop that happen to contain a similar pattern. The message must start
857
+ // with the key name and end with "is required" to qualify.
858
+ const keyMatch = /^([A-Z][A-Z0-9_]+_API_KEY) is required$/.exec(msg);
713
859
  if (keyMatch?.[1]) {
714
860
  setPendingKey({
715
861
  keyName: keyMatch[1],
@@ -725,6 +871,19 @@ export function App(props) {
725
871
  }
726
872
  }
727
873
  finally {
874
+ // If the turn was cancelled via ESC / Ctrl-C, inject the notice
875
+ // synchronously into liveItemsRef before commitLive reads it — this
876
+ // avoids the React-state race where appendLive's functional updater
877
+ // hasn't flushed to the ref yet when commitLive runs.
878
+ const interruptMsg = interruptMsgRef.current;
879
+ interruptMsgRef.current = null;
880
+ if (abort.signal.aborted && interruptMsg !== null) {
881
+ projection.appendLiveSync({
882
+ kind: "notice",
883
+ id: randomUUID(),
884
+ text: interruptMsg,
885
+ });
886
+ }
728
887
  const committed = projection.commitLive();
729
888
  if (committed.length > 0)
730
889
  setTranscript((prev) => [...prev, ...committed]);
@@ -732,7 +891,12 @@ export function App(props) {
732
891
  abortRef.current = null;
733
892
  }
734
893
  };
735
- runTurnRef.current = runTurn;
894
+ // Keep runTurnRef pointed at the latest runTurn closure so
895
+ // handleSubmit always calls the current version without adding
896
+ // runTurn's deps to handleSubmit's dependency array.
897
+ React.useEffect(() => {
898
+ runTurnRef.current = runTurn;
899
+ });
736
900
  // Drain the prompt queue when a turn finishes. Pops the oldest queued
737
901
  // prompt and re-submits it through handleSubmit (which transitions
738
902
  // back into busy=true via runTurn). Guarded on `!busy` so we never
@@ -752,6 +916,8 @@ export function App(props) {
752
916
  // 2. If a turn is streaming → abort it (cancels the in-flight LLM
753
917
  // request via the AbortController plumbed through runAgentLoop).
754
918
  // 3. If the input box has draft text → clear it.
919
+ // (step 3 is skipped when vimMode is on — InputBox's own handler
920
+ // enters NORMAL mode; clearing here would destroy the text.)
755
921
  // Always active so Esc behaves like the user expects regardless of
756
922
  // which surface they're looking at. The atfile overlay handles its
757
923
  // own Esc (cancel completion) so we skip step 1 there.
@@ -763,33 +929,23 @@ export function App(props) {
763
929
  return;
764
930
  }
765
931
  if (busy && abortRef.current !== null) {
932
+ interruptMsgRef.current = "Cancelled.";
766
933
  abortRef.current.abort();
767
- projection.appendLive({
768
- kind: "notice",
769
- id: randomUUID(),
770
- text: "Cancelled.",
771
- });
772
934
  return;
773
935
  }
774
- if (input.length > 0)
936
+ if (input.length > 0 && props.config.vimMode !== true)
775
937
  setInput("");
776
938
  });
777
939
  // Ctrl-C handler: if a turn is running, abort it and show "[Interrupted]"
778
940
  // in the transcript (matching the readline path in src/cli/interactive.ts).
779
- // If idle, let the process exit normally via app.exit().
941
+ // Idle exit is handled by InputBox's own Ctrl-C handler (2-press safety
942
+ // within 1.5s) — we don't override that here.
780
943
  useInput((ch, key) => {
781
944
  if (!(key.ctrl && ch === "c"))
782
945
  return;
783
946
  if (busy && abortRef.current !== null) {
947
+ interruptMsgRef.current = "[Interrupted]";
784
948
  abortRef.current.abort();
785
- projection.appendLive({
786
- kind: "notice",
787
- id: randomUUID(),
788
- text: "[Interrupted]",
789
- });
790
- }
791
- else {
792
- exit();
793
949
  }
794
950
  });
795
951
  const handleModelPick = React.useCallback((id) => {
@@ -815,7 +971,7 @@ export function App(props) {
815
971
  }
816
972
  catch (err) {
817
973
  const msg = err instanceof Error ? err.message : String(err);
818
- const m = /([A-Z][A-Z0-9_]+_API_KEY) is required/.exec(msg);
974
+ const m = /^([A-Z][A-Z0-9_]+_API_KEY) is required$/.exec(msg);
819
975
  if (m?.[1]) {
820
976
  // Open inline key entry instead of a static hint — the user can
821
977
  // paste their key right here without leaving the REPL.
@@ -931,6 +1087,30 @@ export function App(props) {
931
1087
  // live. Initial value comes from config; subsequent changes are
932
1088
  // persisted to ~/.dirgha/config.json so future sessions pick it up.
933
1089
  const [themeName, setThemeName] = React.useState((props.config.theme ?? "readable"));
1090
+ const handleSandboxPick = React.useCallback((next) => {
1091
+ overlays.closeOverlay();
1092
+ sandboxModeRef.current = next;
1093
+ const note = {
1094
+ kind: "notice",
1095
+ id: randomUUID(),
1096
+ text: `Sandbox mode → ${next}`,
1097
+ };
1098
+ setTranscript((t) => [...t, note]);
1099
+ void (async () => {
1100
+ try {
1101
+ const dir = pathJoin(homedir(), ".dirgha");
1102
+ await mkdir(dir, { recursive: true });
1103
+ const path = pathJoin(dir, "config.json");
1104
+ const text = await readFile(path, "utf8").catch(() => "");
1105
+ const cfg = text ? JSON.parse(text) : {};
1106
+ cfg.sandbox = next;
1107
+ await writeFile(path, `${JSON.stringify(cfg, null, 2)}\n`, "utf8");
1108
+ }
1109
+ catch {
1110
+ /* best-effort persistence */
1111
+ }
1112
+ })();
1113
+ }, [overlays]);
934
1114
  const handleThemePick = React.useCallback((name) => {
935
1115
  overlays.closeOverlay();
936
1116
  setThemeName(name);
@@ -955,10 +1135,18 @@ export function App(props) {
955
1135
  }
956
1136
  })();
957
1137
  }, [overlays]);
958
- const liveJsx = React.useMemo(() => renderTranscript(projection.liveItems), [projection.liveItems]);
1138
+ const liveJsx = React.useMemo(() => renderTranscript(projection.liveItems, thinkingStreaming), [projection.liveItems, thinkingStreaming]);
959
1139
  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) => {
1140
+ const spinnerCtx = React.useMemo(() => ({ busy, frame: 0 }), [busy]);
1141
+ const renderTranscriptItem = React.useCallback((item) => _jsx(TranscriptRow, { item: item }, item.id), []);
1142
+ // Logo is emitted via process.stdout.write() before Ink mounts (see
1143
+ // tui/ink/index.ts). Keeping it out of Ink's render tree avoids the
1144
+ // re-emission flicker users hit when transcripts overflow the
1145
+ // viewport: Ink's onRender prepends `fullStaticOutput` (which includes
1146
+ // the logo) on every overflow redraw, repainting it on every chat
1147
+ // turn that fills the screen. `use-flicker-detector` already warns
1148
+ // when this is about to happen.
1149
+ 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
1150
  approvalBusRef.current?.resolve(pendingApproval.id, decision);
963
1151
  } })), pendingFailover !== null && (_jsx(ModelSwitchPrompt, { failedModel: pendingFailover.failedModel, failoverModel: pendingFailover.failoverModel, onAccept: (failover) => {
964
1152
  const lastPrompt = pendingFailover.lastPrompt;
@@ -974,6 +1162,9 @@ export function App(props) {
974
1162
  } })), _jsx(PromptQueueIndicator, { queued: promptQueue }), _jsx(InputBox, { value: input, onChange: setInput, onSubmit: handleSubmit, busy: busy, liveDurationMs: liveDurationMs, vimMode: props.config.vimMode === true, onAtQueryChange: overlays.setAtQuery, onSlashQueryChange: overlays.setSlashQuery, onRequestOverlay: overlays.openOverlay, promptHistory: promptHistory, onRequestYoloToggle: () => {
975
1163
  const next = mode === "yolo" ? "act" : "yolo";
976
1164
  setMode(next);
1165
+ // Wire the approval bus so mid-turn tool calls are immediately
1166
+ // affected — not just the next turn's autoApprove flag.
1167
+ approvalBusRef.current?.setApproveAll(next === "yolo");
977
1168
  setTranscript((prev) => [
978
1169
  ...prev,
979
1170
  {
@@ -984,7 +1175,17 @@ export function App(props) {
984
1175
  : "YOLO mode OFF — back to standard confirmation.",
985
1176
  },
986
1177
  ]);
987
- }, onRequestUpgrade: handleUpgrade, inputFocus: inputFocus }), healthResult !== null && !healthResult.allOk && (_jsx(Box, { paddingX: 1, children: _jsxs(Text, { color: "yellow", children: ["[! System check: ", healthResult.failures.length, " issue", healthResult.failures.length !== 1 ? "s" : "", " found \u2014 run 'dirgha doctor' for details]"] }) })), overlays.active === "atfile" && overlays.atQuery !== null && (_jsx(AtFileComplete, { cwd: props.cwd, query: overlays.atQuery, onPick: handleAtPick, onCancel: () => {
1178
+ }, onRequestUpgrade: handleUpgrade, inputFocus: inputFocus, queueLength: promptQueue.length, onDequeueForEdit: () => {
1179
+ // Read from ref so we get the latest queue without capturing a
1180
+ // stale closure. Calling setInput inside a setState updater would
1181
+ // violate React's purity requirement for updater functions.
1182
+ const q = promptQueueRef.current;
1183
+ if (q.length === 0)
1184
+ return;
1185
+ const last = q[q.length - 1];
1186
+ setInput(last);
1187
+ setPromptQueue((prev) => prev.slice(0, -1));
1188
+ } }), healthResult !== null && !healthResult.allOk && (_jsx(Box, { paddingX: 1, children: _jsxs(Text, { color: "yellow", children: ["[! System check: ", healthResult.failures.length, " issue", healthResult.failures.length !== 1 ? "s" : "", " found \u2014 run 'dirgha doctor' for details]"] }) })), overlays.active === "atfile" && overlays.atQuery !== null && (_jsx(AtFileComplete, { cwd: props.cwd, query: overlays.atQuery, onPick: handleAtPick, onCancel: () => {
988
1189
  overlays.setAtQuery(null);
989
1190
  overlays.setActive(null);
990
1191
  } })), overlays.active === "slash" && overlays.slashQuery !== null && (_jsx(SlashComplete, { commands: slashCommands, query: overlays.slashQuery, onPick: handleSlashPick, onCancel: () => {
@@ -1013,28 +1214,40 @@ export function App(props) {
1013
1214
  // Esc inside ModelPicker → back to ProviderPicker (NOT close).
1014
1215
  setPickerStage("provider");
1015
1216
  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 })] }) }) }));
1217
+ } })), 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, activeTool: activeTools[0] })] }) }) }));
1017
1218
  }
1018
1219
  /**
1019
1220
  * 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.
1221
+ * <ToolGroup>. Fold 3+ consecutive `thinking` items into a single
1222
+ * <ThinkingBlockGroup>. Non-tool / non-thinking items render via
1223
+ * <TranscriptRow>.
1024
1224
  */
1025
- function renderTranscript(items) {
1225
+ function renderTranscript(items, thinkingStreaming) {
1026
1226
  const out = [];
1027
1227
  let toolBuf = [];
1228
+ let thinkBuf = [];
1028
1229
  const flushTools = () => {
1029
1230
  if (toolBuf.length === 0)
1030
1231
  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
1232
  out.push(_jsx(ToolGroup, { tools: toolBuf }, toolBuf[0].id));
1034
1233
  toolBuf = [];
1035
1234
  };
1235
+ const flushThinking = () => {
1236
+ if (thinkBuf.length === 0)
1237
+ return;
1238
+ if (thinkBuf.length >= 3) {
1239
+ out.push(_jsx(ThinkingBlockGroup, { blocks: thinkBuf }, thinkBuf[0].id));
1240
+ }
1241
+ else {
1242
+ for (const tb of thinkBuf) {
1243
+ out.push(_jsx(TranscriptRow, { item: { kind: "thinking", id: tb.id, content: tb.content }, isStreaming: thinkingStreaming }, tb.id));
1244
+ }
1245
+ }
1246
+ thinkBuf = [];
1247
+ };
1036
1248
  for (const item of items) {
1037
1249
  if (item.kind === "tool") {
1250
+ flushThinking();
1038
1251
  toolBuf.push({
1039
1252
  id: item.id,
1040
1253
  name: item.name,
@@ -1047,20 +1260,27 @@ function renderTranscript(items) {
1047
1260
  });
1048
1261
  continue;
1049
1262
  }
1263
+ if (item.kind === "thinking") {
1264
+ flushTools();
1265
+ thinkBuf.push({ id: item.id, content: item.content });
1266
+ continue;
1267
+ }
1050
1268
  flushTools();
1051
- out.push(_jsx(TranscriptRow, { item: item }, item.id));
1269
+ flushThinking();
1270
+ out.push(_jsx(TranscriptRow, { item: item, isStreaming: thinkingStreaming }, item.id));
1052
1271
  }
1053
1272
  flushTools();
1273
+ flushThinking();
1054
1274
  return out;
1055
1275
  }
1056
- function TranscriptRow({ item, }) {
1276
+ function TranscriptRow({ item, isStreaming = false, }) {
1057
1277
  switch (item.kind) {
1058
1278
  case "user":
1059
1279
  return (_jsxs(Box, { gap: 2, marginBottom: 1, children: [_jsx(Text, { color: "magenta", children: "\u276F" }), _jsx(Text, { color: "white", children: item.text })] }));
1060
1280
  case "text":
1061
1281
  return _jsx(StreamingText, { content: item.content });
1062
1282
  case "thinking":
1063
- return _jsx(ThinkingBlock, { content: item.content });
1283
+ return _jsx(ThinkingBlock, { content: item.content, isStreaming: isStreaming });
1064
1284
  case "tool":
1065
1285
  // Should not be reached — tools are folded by renderTranscript() into
1066
1286
  // <ToolGroup>. Kept as a safety net so an unexpected tool item still
@@ -1072,8 +1292,29 @@ function TranscriptRow({ item, }) {
1072
1292
  return (_jsx(Box, { marginBottom: 1, children: _jsx(Text, { color: "yellow", children: item.text }) }));
1073
1293
  }
1074
1294
  }
1295
+ function GeneratingIndicator(props) {
1296
+ const palette = useTheme();
1297
+ const [now, setNow] = React.useState(Date.now());
1298
+ React.useEffect(() => {
1299
+ const t = setInterval(() => setNow(Date.now()), 1000);
1300
+ return () => clearInterval(t);
1301
+ }, []);
1302
+ const elapsedSec = props.startedAtMs > 0 ? Math.round((now - props.startedAtMs) / 1000) : 0;
1303
+ const slow = elapsedSec >= 5 && props.liveOutputTokens === 0;
1304
+ const label = slow
1305
+ ? `warming up · ${elapsedSec}s · first token can take 10–30s on free models`
1306
+ : `generating · ${elapsedSec}s`;
1307
+ 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 })] }));
1308
+ }
1075
1309
  function initialHistory(props) {
1310
+ if (_cachedInitialMessages !== null)
1311
+ return _cachedInitialMessages;
1076
1312
  const base = props.initialMessages ? [...props.initialMessages] : [];
1313
+ // Detect resumed sessions — if the caller passed user/assistant
1314
+ // messages, the session already has history and the LLM should NOT
1315
+ // emit a session-title marker (we'd be retrofitting one onto an
1316
+ // already-named conversation).
1317
+ const isFreshSession = !base.some((m) => m.role === "user" || m.role === "assistant");
1077
1318
  // Boot context: mode preamble + project primer (DIRGHA.md) +
1078
1319
  // caller's --system. Without this, the Ink TUI starts with zero
1079
1320
  // project awareness — same parity-matrix #1 fix as the one-shot
@@ -1087,32 +1328,21 @@ function initialHistory(props) {
1087
1328
  ledgerContext: props.ledgerContext,
1088
1329
  gitState: renderGitState(probeGitState(props.cwd)),
1089
1330
  userSystem: props.systemPrompt,
1331
+ firstTurn: isFreshSession,
1090
1332
  });
1091
1333
  base.unshift({ role: "system", content: composedSystem });
1334
+ _cachedInitialMessages = base;
1092
1335
  return base;
1093
1336
  }
1094
1337
  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";
1338
+ // Delegate to providers/dispatch.ts so the StatusBar readout
1339
+ // matches the actual runtime routing at all times.
1340
+ try {
1341
+ return routeModel(model);
1342
+ }
1343
+ catch {
1344
+ return "local";
1345
+ }
1116
1346
  }
1117
1347
  const PROVIDER_BLURB = {
1118
1348
  anthropic: "Claude — Opus, Sonnet, Haiku",
@@ -1171,6 +1401,24 @@ const PROVIDER_LABEL = {
1171
1401
  zai: "Z.AI / GLM",
1172
1402
  local: "Local",
1173
1403
  };
1404
+ /**
1405
+ * Synchronously check whether an env var exists in ~/.dirgha/keys.json.
1406
+ * Used by buildProviderEntries as a fallback when process.env doesn't
1407
+ * contain the key yet (race with startup hydration).
1408
+ */
1409
+ function tryReadKeyFromStore(envVar) {
1410
+ try {
1411
+ const path = pathJoin(homedir(), ".dirgha", "keys.json");
1412
+ if (!existsSync(path))
1413
+ return false;
1414
+ const raw = readFileSync(path, "utf8");
1415
+ const store = JSON.parse(raw);
1416
+ return typeof store[envVar] === "string" && store[envVar].length > 0;
1417
+ }
1418
+ catch {
1419
+ return false;
1420
+ }
1421
+ }
1174
1422
  /**
1175
1423
  * Group the flat model catalogue into per-provider entries for stage 1
1176
1424
  * of the picker. Skips providers with zero models in the catalogue.
@@ -1186,7 +1434,13 @@ function buildProviderEntries(models, currentModel) {
1186
1434
  const out = [];
1187
1435
  for (const [id, items] of buckets) {
1188
1436
  const env = PROVIDER_ENV[id];
1189
- const hasKey = env ? !!process.env[env] : true; // local providers don't need keys
1437
+ // Check env vars AND keys.json (env vars win). keys.json is hydrated
1438
+ // into process.env by hydrateEnvFromKeyStore at startup, but this
1439
+ // synchronous fallback handles the edge case where hydration hasn't
1440
+ // run yet (e.g. TUI mounts before startup hydration completes).
1441
+ const hasKey = env
1442
+ ? !!process.env[env] || !!tryReadKeyFromStore(env)
1443
+ : true; // local providers don't need keys
1190
1444
  out.push({
1191
1445
  id,
1192
1446
  label: PROVIDER_LABEL[id] ?? id,