@dirgha/code 1.21.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 (282) 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 +148 -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 +45 -22
  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/health-monitor.d.ts +8 -8
  98. package/dist/intelligence/health-monitor.js +105 -74
  99. package/dist/intelligence/health-monitor.js.map +1 -1
  100. package/dist/intelligence/prices.d.ts +6 -4
  101. package/dist/intelligence/prices.js +36 -10
  102. package/dist/intelligence/prices.js.map +1 -1
  103. package/dist/kernel/agent-loop.js +60 -17
  104. package/dist/kernel/agent-loop.js.map +1 -1
  105. package/dist/kernel/types.d.ts +3 -0
  106. package/dist/lsp/client.js +29 -16
  107. package/dist/lsp/client.js.map +1 -1
  108. package/dist/lsp/detector.js +7 -6
  109. package/dist/lsp/detector.js.map +1 -1
  110. package/dist/mcp/client.d.ts +1 -1
  111. package/dist/mcp/client.js +19 -16
  112. package/dist/mcp/client.js.map +1 -1
  113. package/dist/mcp/transport.js +46 -38
  114. package/dist/mcp/transport.js.map +1 -1
  115. package/dist/providers/deepseek.js +1 -1
  116. package/dist/providers/deepseek.js.map +1 -1
  117. package/dist/providers/dispatch.js +15 -1
  118. package/dist/providers/dispatch.js.map +1 -1
  119. package/dist/providers/index.d.ts +11 -0
  120. package/dist/providers/index.js +29 -2
  121. package/dist/providers/index.js.map +1 -1
  122. package/dist/providers/nvidia.js +1 -1
  123. package/dist/providers/nvidia.js.map +1 -1
  124. package/dist/providers/openai-compat.js +4 -2
  125. package/dist/providers/openai-compat.js.map +1 -1
  126. package/dist/providers/openrouter.js +1 -1
  127. package/dist/providers/openrouter.js.map +1 -1
  128. package/dist/safety/audit-log.d.ts +15 -0
  129. package/dist/safety/audit-log.js +21 -0
  130. package/dist/safety/audit-log.js.map +1 -1
  131. package/dist/state/db-telemetry.d.ts +21 -0
  132. package/dist/state/db-telemetry.js +116 -0
  133. package/dist/state/db-telemetry.js.map +1 -0
  134. package/dist/state/db.d.ts +7 -0
  135. package/dist/state/db.js +132 -7
  136. package/dist/state/db.js.map +1 -1
  137. package/dist/state/sync-index.d.ts +74 -0
  138. package/dist/state/sync-index.js +246 -0
  139. package/dist/state/sync-index.js.map +1 -0
  140. package/dist/state/transaction.d.ts +62 -0
  141. package/dist/state/transaction.js +65 -0
  142. package/dist/state/transaction.js.map +1 -0
  143. package/dist/state/vec.d.ts +28 -0
  144. package/dist/state/vec.js +113 -0
  145. package/dist/state/vec.js.map +1 -0
  146. package/dist/telemetry/gateway-push.d.ts +17 -0
  147. package/dist/telemetry/gateway-push.js +48 -0
  148. package/dist/telemetry/gateway-push.js.map +1 -0
  149. package/dist/telemetry/index.d.ts +9 -0
  150. package/dist/telemetry/index.js +9 -0
  151. package/dist/telemetry/index.js.map +1 -0
  152. package/dist/tools/browser.js +24 -16
  153. package/dist/tools/browser.js.map +1 -1
  154. package/dist/tools/checkpoint.d.ts +6 -1
  155. package/dist/tools/checkpoint.js +79 -62
  156. package/dist/tools/checkpoint.js.map +1 -1
  157. package/dist/tools/cron.js +1 -3
  158. package/dist/tools/cron.js.map +1 -1
  159. package/dist/tools/db-workspace-info.d.ts +10 -0
  160. package/dist/tools/db-workspace-info.js +76 -0
  161. package/dist/tools/db-workspace-info.js.map +1 -0
  162. package/dist/tools/diff.js +25 -21
  163. package/dist/tools/diff.js.map +1 -1
  164. package/dist/tools/exec.d.ts +6 -1
  165. package/dist/tools/exec.js +46 -4
  166. package/dist/tools/exec.js.map +1 -1
  167. package/dist/tools/fs-edit.d.ts +3 -5
  168. package/dist/tools/fs-edit.js +8 -23
  169. package/dist/tools/fs-edit.js.map +1 -1
  170. package/dist/tools/fs-ls.js +6 -8
  171. package/dist/tools/fs-ls.js.map +1 -1
  172. package/dist/tools/fs-read.d.ts +1 -1
  173. package/dist/tools/fs-read.js +37 -28
  174. package/dist/tools/fs-read.js.map +1 -1
  175. package/dist/tools/fs-write.d.ts +1 -1
  176. package/dist/tools/fs-write.js +33 -33
  177. package/dist/tools/fs-write.js.map +1 -1
  178. package/dist/tools/git.js +12 -6
  179. package/dist/tools/git.js.map +1 -1
  180. package/dist/tools/github.d.ts +13 -0
  181. package/dist/tools/github.js +257 -0
  182. package/dist/tools/github.js.map +1 -0
  183. package/dist/tools/graph-neighbors.d.ts +9 -0
  184. package/dist/tools/graph-neighbors.js +77 -0
  185. package/dist/tools/graph-neighbors.js.map +1 -0
  186. package/dist/tools/graph-traverse.d.ts +10 -0
  187. package/dist/tools/graph-traverse.js +90 -0
  188. package/dist/tools/graph-traverse.js.map +1 -0
  189. package/dist/tools/index.d.ts +10 -2
  190. package/dist/tools/index.js +17 -4
  191. package/dist/tools/index.js.map +1 -1
  192. package/dist/tools/kb-search.d.ts +13 -0
  193. package/dist/tools/kb-search.js +113 -0
  194. package/dist/tools/kb-search.js.map +1 -0
  195. package/dist/tools/multimodal.js +11 -12
  196. package/dist/tools/multimodal.js.map +1 -1
  197. package/dist/tools/registry.d.ts +10 -0
  198. package/dist/tools/registry.js.map +1 -1
  199. package/dist/tools/rtk.js +22 -9
  200. package/dist/tools/rtk.js.map +1 -1
  201. package/dist/tools/search-glob.d.ts +1 -1
  202. package/dist/tools/search-glob.js +42 -24
  203. package/dist/tools/search-glob.js.map +1 -1
  204. package/dist/tools/search-grep.d.ts +1 -1
  205. package/dist/tools/search-grep.js +56 -32
  206. package/dist/tools/search-grep.js.map +1 -1
  207. package/dist/tools/shell.d.ts +7 -1
  208. package/dist/tools/shell.js +178 -61
  209. package/dist/tools/shell.js.map +1 -1
  210. package/dist/tools/transactional-write.d.ts +10 -0
  211. package/dist/tools/transactional-write.js +132 -0
  212. package/dist/tools/transactional-write.js.map +1 -0
  213. package/dist/tui/ink/App.d.ts +2 -1
  214. package/dist/tui/ink/App.js +319 -83
  215. package/dist/tui/ink/App.js.map +1 -1
  216. package/dist/tui/ink/components/DenseToolMessage.js +23 -8
  217. package/dist/tui/ink/components/DenseToolMessage.js.map +1 -1
  218. package/dist/tui/ink/components/InputBox.js +16 -25
  219. package/dist/tui/ink/components/InputBox.js.map +1 -1
  220. package/dist/tui/ink/components/KeySetOverlay.d.ts +1 -1
  221. package/dist/tui/ink/components/KeySetOverlay.js +18 -16
  222. package/dist/tui/ink/components/KeySetOverlay.js.map +1 -1
  223. package/dist/tui/ink/components/Logo.d.ts +20 -0
  224. package/dist/tui/ink/components/Logo.js +67 -1
  225. package/dist/tui/ink/components/Logo.js.map +1 -1
  226. package/dist/tui/ink/components/ModelPicker.d.ts +2 -2
  227. package/dist/tui/ink/components/ModelPicker.js +34 -26
  228. package/dist/tui/ink/components/ModelPicker.js.map +1 -1
  229. package/dist/tui/ink/components/PasteCollapse.d.ts +3 -1
  230. package/dist/tui/ink/components/PasteCollapse.js +11 -9
  231. package/dist/tui/ink/components/PasteCollapse.js.map +1 -1
  232. package/dist/tui/ink/components/SandboxPicker.d.ts +18 -0
  233. package/dist/tui/ink/components/SandboxPicker.js +77 -0
  234. package/dist/tui/ink/components/SandboxPicker.js.map +1 -0
  235. package/dist/tui/ink/components/SpinnerGlyph.d.ts +4 -4
  236. package/dist/tui/ink/components/SpinnerGlyph.js +34 -14
  237. package/dist/tui/ink/components/SpinnerGlyph.js.map +1 -1
  238. package/dist/tui/ink/components/StatusBar.d.ts +7 -0
  239. package/dist/tui/ink/components/StatusBar.js +11 -5
  240. package/dist/tui/ink/components/StatusBar.js.map +1 -1
  241. package/dist/tui/ink/components/ThinkingBlock.d.ts +15 -4
  242. package/dist/tui/ink/components/ThinkingBlock.js +34 -17
  243. package/dist/tui/ink/components/ThinkingBlock.js.map +1 -1
  244. package/dist/tui/ink/components/ToolBox.js +23 -13
  245. package/dist/tui/ink/components/ToolBox.js.map +1 -1
  246. package/dist/tui/ink/components/VirtualTranscript.d.ts +19 -0
  247. package/dist/tui/ink/components/VirtualTranscript.js +31 -0
  248. package/dist/tui/ink/components/VirtualTranscript.js.map +1 -0
  249. package/dist/tui/ink/index.js +17 -1
  250. package/dist/tui/ink/index.js.map +1 -1
  251. package/dist/tui/ink/markdown/syntax-highlight.d.ts +13 -0
  252. package/dist/tui/ink/markdown/syntax-highlight.js +91 -0
  253. package/dist/tui/ink/markdown/syntax-highlight.js.map +1 -0
  254. package/dist/tui/ink/theme-context.js +6 -3
  255. package/dist/tui/ink/theme-context.js.map +1 -1
  256. package/dist/tui/ink/use-declined-versions.js +6 -2
  257. package/dist/tui/ink/use-declined-versions.js.map +1 -1
  258. package/dist/tui/ink/use-elapsed.d.ts +14 -0
  259. package/dist/tui/ink/use-elapsed.js +61 -0
  260. package/dist/tui/ink/use-elapsed.js.map +1 -0
  261. package/dist/tui/ink/use-event-projection.d.ts +10 -0
  262. package/dist/tui/ink/use-event-projection.js +111 -12
  263. package/dist/tui/ink/use-event-projection.js.map +1 -1
  264. package/dist/tui/ink/use-flicker-detector.d.ts +12 -0
  265. package/dist/tui/ink/use-flicker-detector.js +37 -0
  266. package/dist/tui/ink/use-flicker-detector.js.map +1 -0
  267. package/dist/tui/ink/use-overlays.d.ts +2 -2
  268. package/dist/tui/ink/use-overlays.js +16 -17
  269. package/dist/tui/ink/use-overlays.js.map +1 -1
  270. package/dist/tui/ink/use-render-metrics.d.ts +14 -0
  271. package/dist/tui/ink/use-render-metrics.js +106 -0
  272. package/dist/tui/ink/use-render-metrics.js.map +1 -0
  273. package/dist/tui/ink/use-transcript-scroll.d.ts +19 -0
  274. package/dist/tui/ink/use-transcript-scroll.js +83 -0
  275. package/dist/tui/ink/use-transcript-scroll.js.map +1 -0
  276. package/dist/utils/env.d.ts +1 -0
  277. package/dist/utils/env.js +60 -0
  278. package/dist/utils/env.js.map +1 -0
  279. package/dist/utils/fs.d.ts +10 -0
  280. package/dist/utils/fs.js +37 -0
  281. package/dist/utils/fs.js.map +1 -0
  282. 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,8 +15,9 @@ 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
+ import { VirtualTranscript } from "./components/VirtualTranscript.js";
20
21
  import { appendAudit } from "../../audit/writer.js";
21
22
  import { maybeCompact } from "../../context/compaction.js";
22
23
  import { contextWindowFor } from "../../intelligence/prices.js";
@@ -26,6 +27,7 @@ import { loadProjectPrimer, composeSystemPrompt, } from "../../context/primer.js
26
27
  import { queryKb } from "../../context/kb-query.js";
27
28
  import { probeGitState, renderGitState } from "../../context/git-state.js";
28
29
  import { loadSoul } from "../../context/soul.js";
30
+ import { routeModel } from "../../providers/dispatch.js";
29
31
  import { isAutoApprove, modePreamble } from "../../context/mode.js";
30
32
  import { runAgentLoop } from "../../kernel/agent-loop.js";
31
33
  import { createErrorClassifier } from "../../intelligence/error-classifier.js";
@@ -33,10 +35,9 @@ import { createToolExecutor } from "../../tools/exec.js";
33
35
  import { createInkApprovalBus, } from "./ink-approval-bus.js";
34
36
  import { ApprovalPrompt, } from "./components/ApprovalPrompt.js";
35
37
  import { PRICES } from "../../intelligence/prices.js";
36
- import { Logo } from "./components/Logo.js";
37
38
  import { StatusBar } from "./components/StatusBar.js";
38
39
  import { StreamingText } from "./components/StreamingText.js";
39
- import { ThinkingBlock } from "./components/ThinkingBlock.js";
40
+ import { ThinkingBlock, ThinkingBlockGroup, } from "./components/ThinkingBlock.js";
40
41
  import { ToolBox } from "./components/ToolBox.js";
41
42
  import { ToolGroup } from "./components/ToolGroup.js";
42
43
  import { InputBox } from "./components/InputBox.js";
@@ -52,21 +53,26 @@ import { getUpdateBannerVersion } from "../../cli/update-check.js";
52
53
  import { AtFileComplete } from "./components/AtFileComplete.js";
53
54
  import { SlashComplete } from "./components/SlashComplete.js";
54
55
  import { ThemePicker } from "./components/ThemePicker.js";
55
- import { ThemeProvider } from "./theme-context.js";
56
+ import { SandboxPicker } from "./components/SandboxPicker.js";
57
+ import { ThemeProvider, useTheme } from "./theme-context.js";
56
58
  import { SpinnerContext } from "./spinner-context.js";
59
+ import { SpinnerGlyph } from "./components/SpinnerGlyph.js";
57
60
  import { writeFile, mkdir, readFile } from "node:fs/promises";
61
+ import { readFileSync, existsSync } from "node:fs";
58
62
  import { homedir } from "node:os";
59
63
  import { join as pathJoin } from "node:path";
60
64
  import { useEventProjection, } from "./use-event-projection.js";
61
65
  import { useOverlays } from "./use-overlays.js";
62
66
  import { useDeclinedVersions } from "./use-declined-versions.js";
63
67
  import { useStartupHealth } from "./use-startup-health.js";
68
+ import { useFlickerDetector } from "./use-flicker-detector.js";
69
+ import { useRenderMetrics, } from "./use-render-metrics.js";
64
70
  import { getRemoteConfig, isVersionBelowMin, } from "../../intelligence/remote-config.js";
65
71
  import { createRequire } from "node:module";
66
72
  // Pulled from the installed package.json so the TUI title matches the
67
73
  // shipped binary version. Falls back to '0.0.0-dev' if the file isn't
68
74
  // reachable (e.g. an unusual deploy layout).
69
- const VERSION = (() => {
75
+ export const VERSION = (() => {
70
76
  try {
71
77
  const req = createRequire(import.meta.url);
72
78
  const pkg = req("../../../package.json");
@@ -76,13 +82,30 @@ const VERSION = (() => {
76
82
  return "0.0.0-dev";
77
83
  }
78
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;
79
89
  export function App(props) {
80
90
  const { exit } = useApp();
81
91
  const sessionIdRef = React.useRef(randomUUID());
82
92
  const historyRef = React.useRef(initialHistory(props));
83
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);
84
98
  const pendingModelRef = React.useRef(null);
85
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");
86
109
  React.useEffect(() => {
87
110
  const id = sessionIdRef.current;
88
111
  void props.sessions.create(id).then((s) => {
@@ -106,6 +129,7 @@ export function App(props) {
106
129
  const [transcript, setTranscript] = React.useState([]);
107
130
  const [input, setInput] = React.useState("");
108
131
  const [busy, setBusy] = React.useState(false);
132
+ const [thinkingStreaming, setThinkingStreaming] = React.useState(false);
109
133
  // Prompt queue: while a turn is streaming the user can still type and
110
134
  // press Enter. Submissions land here instead of being dropped, then
111
135
  // drain FIFO when the turn finishes (see useEffect below).
@@ -142,7 +166,7 @@ export function App(props) {
142
166
  // turns. Replaces the legacy `createTuiApprovalBus` that wrote prompts
143
167
  // direct to stdout (overdrawn by Ink) and read stdin raw (hung on
144
168
  // Windows). See `ink-approval-bus.ts` for the full rationale.
145
- const approvalBusRef = React.useRef();
169
+ const approvalBusRef = React.useRef(null);
146
170
  if (!approvalBusRef.current) {
147
171
  approvalBusRef.current = createInkApprovalBus(new Set(props.config.autoApproveTools));
148
172
  }
@@ -163,7 +187,55 @@ export function App(props) {
163
187
  onCommitSplit: React.useCallback((item) => {
164
188
  setTranscript((prev) => [...prev, item]);
165
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
+ }, []),
166
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);
167
239
  const overlays = useOverlays();
168
240
  // Live counters for the in-progress turn — drive the StatusBar
169
241
  // tok/s readout. Reset at agent_start, accumulate output deltas,
@@ -186,6 +258,18 @@ export function App(props) {
186
258
  }, [declined]);
187
259
  // Startup health check — non-blocking, cached for 24h.
188
260
  const healthResult = useStartupHealth();
261
+ // Flicker detector — compares estimated tree height to terminal rows.
262
+ const estimatedLineCount = (transcript.length + projection.liveItems.length) * 2 + 15;
263
+ const flicker = useFlickerDetector(estimatedLineCount);
264
+ // Render performance metrics — track frame timing, expose for StatusBar.
265
+ const renderMetrics = useRenderMetrics();
266
+ const [showRenderMetrics, setShowRenderMetrics] = React.useState(false);
267
+ // Alt+M toggles the render-metrics display in the StatusBar.
268
+ useInput((ch, key) => {
269
+ if (key.meta && ch === "m") {
270
+ setShowRenderMetrics((v) => !v);
271
+ }
272
+ });
189
273
  // Remote config: fetch once on mount, set model default, show MOTD.
190
274
  const [remoteConfig, setRemoteConfig] = React.useState(null);
191
275
  const [motdShown, setMotdShown] = React.useState(false);
@@ -277,8 +361,18 @@ export function App(props) {
277
361
  liveOutputTokensAccRef.current = 0;
278
362
  setLiveOutputTokens(0);
279
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);
280
371
  }
281
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.
282
376
  liveOutputTokensAccRef.current += (ev.delta?.length ?? 0) / 4;
283
377
  }
284
378
  else if (ev.type === "usage") {
@@ -290,10 +384,36 @@ export function App(props) {
290
384
  setLiveDurationMs(0);
291
385
  setLiveOutputTokens(0);
292
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
+ }
293
413
  }
294
414
  });
295
415
  return unsub;
296
- }, [props.events]);
416
+ }, [props.events, mode, props.cwd, props.ledgerContext, props.systemPrompt]);
297
417
  // globalSpinnerFrame removed — spinner interval now lives inside
298
418
  // SpinnerGlyph so only the glyph subtree re-renders at 80ms, not the
299
419
  // entire App tree.
@@ -381,7 +501,7 @@ export function App(props) {
381
501
  });
382
502
  // A new submission supersedes any pending failover prompt.
383
503
  setPendingFailover(null);
384
- if (value === "/exit" || value === "/quit") {
504
+ if (value === "/exit" || value === "/quit" || value === "/stop") {
385
505
  exit();
386
506
  return;
387
507
  }
@@ -399,23 +519,36 @@ export function App(props) {
399
519
  if (value.startsWith("/model ")) {
400
520
  const id = value.slice("/model ".length).trim();
401
521
  if (id !== "") {
402
- const valid = PRICES.some((p) => p.model === id);
403
- 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);
404
526
  const note = {
405
527
  kind: "notice",
406
528
  id: randomUUID(),
407
- text: `Invalid model: ${id}. Use /models to see the catalogue.`,
529
+ text: `Model set to ${exactMatch.model}`,
408
530
  };
409
531
  setTranscript((prev) => [...prev, note]);
410
532
  }
411
533
  else {
412
- setCurrentModel(id);
413
- const note = {
414
- kind: "notice",
415
- id: randomUUID(),
416
- text: `Model set to ${id}`,
417
- };
418
- 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
+ }
419
552
  }
420
553
  }
421
554
  return;
@@ -429,6 +562,11 @@ export function App(props) {
429
562
  overlays.openOverlay("theme");
430
563
  return;
431
564
  }
565
+ // `/sandbox` with no args opens the picker; `/sandbox <mode>` sets directly.
566
+ if (value === "/sandbox") {
567
+ overlays.openOverlay("sandbox");
568
+ return;
569
+ }
432
570
  // /upgrade and /self-update trigger npm install + restart.
433
571
  if (value === "/upgrade" ||
434
572
  value === "/self-update" ||
@@ -505,7 +643,11 @@ export function App(props) {
505
643
  exit();
506
644
  process.exit(code);
507
645
  },
508
- 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
+ },
509
651
  setToken: (newToken) => {
510
652
  tokenRef.current = newToken;
511
653
  },
@@ -527,6 +669,10 @@ export function App(props) {
527
669
  setMode: (m) => setMode(m),
528
670
  getTheme: () => props.config.theme ?? "readable",
529
671
  setTheme: () => undefined,
672
+ getSandbox: () => sandboxModeRef.current,
673
+ setSandbox: (next) => {
674
+ sandboxModeRef.current = next;
675
+ },
530
676
  getSession: () => null,
531
677
  getSessionStore: () => props.sessions,
532
678
  getProvider: () => props.providers.forModel(currentModel),
@@ -643,6 +789,7 @@ export function App(props) {
643
789
  registry: props.registry,
644
790
  cwd: props.cwd,
645
791
  sessionId: sessionIdRef.current,
792
+ sandboxMode: sandboxModeRef.current,
646
793
  onProgress: (toolId, message) => {
647
794
  props.events.emit({
648
795
  type: "tool_exec_progress",
@@ -694,7 +841,10 @@ export function App(props) {
694
841
  }
695
842
  catch (err) {
696
843
  const msg = err instanceof Error ? err.message : String(err);
697
- 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);
698
848
  if (keyMatch?.[1]) {
699
849
  setPendingKey({
700
850
  keyName: keyMatch[1],
@@ -710,6 +860,19 @@ export function App(props) {
710
860
  }
711
861
  }
712
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
+ }
713
876
  const committed = projection.commitLive();
714
877
  if (committed.length > 0)
715
878
  setTranscript((prev) => [...prev, ...committed]);
@@ -717,7 +880,12 @@ export function App(props) {
717
880
  abortRef.current = null;
718
881
  }
719
882
  };
720
- 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
+ });
721
889
  // Drain the prompt queue when a turn finishes. Pops the oldest queued
722
890
  // prompt and re-submits it through handleSubmit (which transitions
723
891
  // back into busy=true via runTurn). Guarded on `!busy` so we never
@@ -737,6 +905,8 @@ export function App(props) {
737
905
  // 2. If a turn is streaming → abort it (cancels the in-flight LLM
738
906
  // request via the AbortController plumbed through runAgentLoop).
739
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.)
740
910
  // Always active so Esc behaves like the user expects regardless of
741
911
  // which surface they're looking at. The atfile overlay handles its
742
912
  // own Esc (cancel completion) so we skip step 1 there.
@@ -748,33 +918,23 @@ export function App(props) {
748
918
  return;
749
919
  }
750
920
  if (busy && abortRef.current !== null) {
921
+ interruptMsgRef.current = "Cancelled.";
751
922
  abortRef.current.abort();
752
- projection.appendLive({
753
- kind: "notice",
754
- id: randomUUID(),
755
- text: "Cancelled.",
756
- });
757
923
  return;
758
924
  }
759
- if (input.length > 0)
925
+ if (input.length > 0 && props.config.vimMode !== true)
760
926
  setInput("");
761
927
  });
762
928
  // Ctrl-C handler: if a turn is running, abort it and show "[Interrupted]"
763
929
  // in the transcript (matching the readline path in src/cli/interactive.ts).
764
- // 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.
765
932
  useInput((ch, key) => {
766
933
  if (!(key.ctrl && ch === "c"))
767
934
  return;
768
935
  if (busy && abortRef.current !== null) {
936
+ interruptMsgRef.current = "[Interrupted]";
769
937
  abortRef.current.abort();
770
- projection.appendLive({
771
- kind: "notice",
772
- id: randomUUID(),
773
- text: "[Interrupted]",
774
- });
775
- }
776
- else {
777
- exit();
778
938
  }
779
939
  });
780
940
  const handleModelPick = React.useCallback((id) => {
@@ -800,7 +960,7 @@ export function App(props) {
800
960
  }
801
961
  catch (err) {
802
962
  const msg = err instanceof Error ? err.message : String(err);
803
- 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);
804
964
  if (m?.[1]) {
805
965
  // Open inline key entry instead of a static hint — the user can
806
966
  // paste their key right here without leaving the REPL.
@@ -916,6 +1076,30 @@ export function App(props) {
916
1076
  // live. Initial value comes from config; subsequent changes are
917
1077
  // persisted to ~/.dirgha/config.json so future sessions pick it up.
918
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]);
919
1103
  const handleThemePick = React.useCallback((name) => {
920
1104
  overlays.closeOverlay();
921
1105
  setThemeName(name);
@@ -940,19 +1124,18 @@ export function App(props) {
940
1124
  }
941
1125
  })();
942
1126
  }, [overlays]);
943
- const committedJsx = React.useMemo(() => renderTranscript(transcript), [transcript]);
944
- // Gemini CLI approach: freeze committed history inside <Static>
945
- // so Ink caches the output and never re-renders it. Without this,
946
- // every streaming flush tick re-conciles the entire transcript
947
- // against the terminal — causing visible flicker/jitter.
948
- const committedStaticItems = React.useMemo(() => committedJsx.map((el, i) => ({
949
- key: el?.key ?? `c-${i}`,
950
- el,
951
- })), [committedJsx]);
952
- const liveJsx = React.useMemo(() => renderTranscript(projection.liveItems), [projection.liveItems]);
1127
+ const liveJsx = React.useMemo(() => renderTranscript(projection.liveItems, thinkingStreaming), [projection.liveItems, thinkingStreaming]);
953
1128
  const providerEntries = React.useMemo(() => buildProviderEntries(models, currentModel), [models, currentModel]);
954
- const LOGO_ITEMS = React.useMemo(() => [{ key: "logo" }], []);
955
- 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(Static, { items: committedStaticItems, children: ({ el }) => el }), _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) => {
956
1139
  approvalBusRef.current?.resolve(pendingApproval.id, decision);
957
1140
  } })), pendingFailover !== null && (_jsx(ModelSwitchPrompt, { failedModel: pendingFailover.failedModel, failoverModel: pendingFailover.failoverModel, onAccept: (failover) => {
958
1141
  const lastPrompt = pendingFailover.lastPrompt;
@@ -1007,28 +1190,40 @@ export function App(props) {
1007
1190
  // Esc inside ModelPicker → back to ProviderPicker (NOT close).
1008
1191
  setPickerStage("provider");
1009
1192
  setPickerProvider(null);
1010
- } })), 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 })] }) }) }));
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 })] }) }) }));
1011
1194
  }
1012
1195
  /**
1013
1196
  * Walk the transcript and fold consecutive `tool` items into a single
1014
- * <ToolGroup>. Non-tool items render via <TranscriptRow>. The grouping
1015
- * is intentionally simple — we look at adjacency, not assistant-turn
1016
- * boundaries, because the projection emits tools contiguously between
1017
- * `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>.
1018
1200
  */
1019
- function renderTranscript(items) {
1201
+ function renderTranscript(items, thinkingStreaming) {
1020
1202
  const out = [];
1021
1203
  let toolBuf = [];
1204
+ let thinkBuf = [];
1022
1205
  const flushTools = () => {
1023
1206
  if (toolBuf.length === 0)
1024
1207
  return;
1025
- // Key on the stable ID of the first tool so React never unmounts/remounts
1026
- // the ToolGroup subtree when the counter resets (which caused flicker).
1027
1208
  out.push(_jsx(ToolGroup, { tools: toolBuf }, toolBuf[0].id));
1028
1209
  toolBuf = [];
1029
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
+ };
1030
1224
  for (const item of items) {
1031
1225
  if (item.kind === "tool") {
1226
+ flushThinking();
1032
1227
  toolBuf.push({
1033
1228
  id: item.id,
1034
1229
  name: item.name,
@@ -1041,20 +1236,27 @@ function renderTranscript(items) {
1041
1236
  });
1042
1237
  continue;
1043
1238
  }
1239
+ if (item.kind === "thinking") {
1240
+ flushTools();
1241
+ thinkBuf.push({ id: item.id, content: item.content });
1242
+ continue;
1243
+ }
1044
1244
  flushTools();
1045
- out.push(_jsx(TranscriptRow, { item: item }, item.id));
1245
+ flushThinking();
1246
+ out.push(_jsx(TranscriptRow, { item: item, isStreaming: thinkingStreaming }, item.id));
1046
1247
  }
1047
1248
  flushTools();
1249
+ flushThinking();
1048
1250
  return out;
1049
1251
  }
1050
- function TranscriptRow({ item, }) {
1252
+ function TranscriptRow({ item, isStreaming = false, }) {
1051
1253
  switch (item.kind) {
1052
1254
  case "user":
1053
1255
  return (_jsxs(Box, { gap: 2, marginBottom: 1, children: [_jsx(Text, { color: "magenta", children: "\u276F" }), _jsx(Text, { color: "white", children: item.text })] }));
1054
1256
  case "text":
1055
1257
  return _jsx(StreamingText, { content: item.content });
1056
1258
  case "thinking":
1057
- return _jsx(ThinkingBlock, { content: item.content });
1259
+ return _jsx(ThinkingBlock, { content: item.content, isStreaming: isStreaming });
1058
1260
  case "tool":
1059
1261
  // Should not be reached — tools are folded by renderTranscript() into
1060
1262
  // <ToolGroup>. Kept as a safety net so an unexpected tool item still
@@ -1066,8 +1268,29 @@ function TranscriptRow({ item, }) {
1066
1268
  return (_jsx(Box, { marginBottom: 1, children: _jsx(Text, { color: "yellow", children: item.text }) }));
1067
1269
  }
1068
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
+ }
1069
1285
  function initialHistory(props) {
1286
+ if (_cachedInitialMessages !== null)
1287
+ return _cachedInitialMessages;
1070
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");
1071
1294
  // Boot context: mode preamble + project primer (DIRGHA.md) +
1072
1295
  // caller's --system. Without this, the Ink TUI starts with zero
1073
1296
  // project awareness — same parity-matrix #1 fix as the one-shot
@@ -1081,32 +1304,21 @@ function initialHistory(props) {
1081
1304
  ledgerContext: props.ledgerContext,
1082
1305
  gitState: renderGitState(probeGitState(props.cwd)),
1083
1306
  userSystem: props.systemPrompt,
1307
+ firstTurn: isFreshSession,
1084
1308
  });
1085
1309
  base.unshift({ role: "system", content: composedSystem });
1310
+ _cachedInitialMessages = base;
1086
1311
  return base;
1087
1312
  }
1088
1313
  function providerIdForModel(model) {
1089
- // Light heuristic so StatusBar has a hint without importing dispatch.
1090
- // Real routing still lives in providers/dispatch.ts at run time.
1091
- if (model.includes("claude"))
1092
- return "anthropic";
1093
- if (model.includes("gpt") || model.startsWith("o1") || model.startsWith("o3"))
1094
- return "openai";
1095
- if (model.includes("gemini"))
1096
- return "gemini";
1097
- if (model.includes("deepseek"))
1098
- return "deepseek";
1099
- if (model.includes("kimi") || model.includes("moonshot"))
1100
- return "nvidia";
1101
- if (model.includes("llama") ||
1102
- model.includes("nvidia") ||
1103
- model.includes("minimax"))
1104
- return "nvidia";
1105
- if (model.includes("fireworks"))
1106
- return "fireworks";
1107
- if (model.includes("/"))
1108
- return "openrouter";
1109
- 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
+ }
1110
1322
  }
1111
1323
  const PROVIDER_BLURB = {
1112
1324
  anthropic: "Claude — Opus, Sonnet, Haiku",
@@ -1165,6 +1377,24 @@ const PROVIDER_LABEL = {
1165
1377
  zai: "Z.AI / GLM",
1166
1378
  local: "Local",
1167
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
+ }
1168
1398
  /**
1169
1399
  * Group the flat model catalogue into per-provider entries for stage 1
1170
1400
  * of the picker. Skips providers with zero models in the catalogue.
@@ -1180,7 +1410,13 @@ function buildProviderEntries(models, currentModel) {
1180
1410
  const out = [];
1181
1411
  for (const [id, items] of buckets) {
1182
1412
  const env = PROVIDER_ENV[id];
1183
- 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
1184
1420
  out.push({
1185
1421
  id,
1186
1422
  label: PROVIDER_LABEL[id] ?? id,