@denizokcu/haze 1.7.11 → 1.8.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 (234) hide show
  1. package/CHANGELOG.md +56 -0
  2. package/README.md +142 -102
  3. package/SECURITY.md +1 -1
  4. package/assets/graph-grammars/NOTICE.md +21 -0
  5. package/assets/graph-grammars/tree-sitter-javascript.wasm +0 -0
  6. package/assets/graph-grammars/tree-sitter-tsx.wasm +0 -0
  7. package/assets/graph-grammars/tree-sitter-typescript.wasm +0 -0
  8. package/assets/graph-grammars/web-tree-sitter.cjs +4116 -0
  9. package/assets/graph-grammars/web-tree-sitter.cjs.map +7 -0
  10. package/assets/graph-grammars/web-tree-sitter.js +4056 -0
  11. package/assets/graph-grammars/web-tree-sitter.js.map +7 -0
  12. package/assets/graph-grammars/web-tree-sitter.wasm +0 -0
  13. package/assets/graph-grammars/web-tree-sitter.wasm.map +55 -0
  14. package/bin/haze.js +47 -19
  15. package/dist/buildInfo.json +3 -3
  16. package/dist/cli/chat/BusyBar.d.ts +1 -2
  17. package/dist/cli/chat/ChatHeader.d.ts +6 -0
  18. package/dist/cli/chat/ChatHeader.js +11 -0
  19. package/dist/cli/chat/ChatScreen.d.ts +16 -0
  20. package/dist/cli/chat/ChatScreen.js +399 -0
  21. package/dist/cli/chat/ChatScreenView.d.ts +68 -0
  22. package/dist/cli/chat/ChatScreenView.js +47 -0
  23. package/dist/cli/chat/LiveTail.d.ts +11 -0
  24. package/dist/cli/chat/LiveTail.js +26 -0
  25. package/dist/cli/chat/TaskBar.d.ts +3 -2
  26. package/dist/cli/chat/TaskBar.js +4 -0
  27. package/dist/cli/chat/agentTurnRunner.d.ts +12 -0
  28. package/dist/cli/chat/agentTurnRunner.js +177 -0
  29. package/dist/cli/chat/busyIndicator.js +9 -5
  30. package/dist/cli/chat/chatMetrics.d.ts +7 -0
  31. package/dist/cli/chat/chatMetrics.js +15 -1
  32. package/dist/cli/chat/chatViewModel.d.ts +85 -0
  33. package/dist/cli/chat/chatViewModel.js +66 -0
  34. package/dist/cli/chat/fileMentionSuggestions.d.ts +0 -14
  35. package/dist/cli/chat/fileMentionSuggestions.js +4 -21
  36. package/dist/cli/chat/inputSuggestions.js +1 -0
  37. package/dist/cli/chat/liveTheme.d.ts +11 -0
  38. package/dist/cli/chat/liveTheme.js +26 -0
  39. package/dist/cli/chat/messageFinalize.d.ts +4 -0
  40. package/dist/cli/chat/messageFinalize.js +8 -0
  41. package/dist/cli/chat/messages.js +1 -1
  42. package/dist/cli/chat/pickerOpeners.d.ts +23 -0
  43. package/dist/cli/chat/pickerOpeners.js +36 -0
  44. package/dist/cli/chat/promptSessionState.d.ts +11 -0
  45. package/dist/cli/chat/promptSessionState.js +39 -0
  46. package/dist/cli/chat/renderMetrics.d.ts +8 -0
  47. package/dist/cli/chat/renderMetrics.js +14 -0
  48. package/dist/cli/chat/resizeGuard.d.ts +11 -0
  49. package/dist/cli/chat/resizeGuard.js +25 -0
  50. package/dist/cli/chat/screenDeps.d.ts +116 -0
  51. package/dist/cli/chat/screenDeps.js +1 -0
  52. package/dist/cli/chat/sessionLifecycle.d.ts +2 -0
  53. package/dist/cli/chat/sessionLifecycle.js +6 -2
  54. package/dist/cli/chat/sessionRecorder.js +4 -1
  55. package/dist/cli/chat/settingsSelection.d.ts +33 -0
  56. package/dist/cli/chat/settingsSelection.js +46 -0
  57. package/dist/cli/chat/skillNotices.d.ts +18 -0
  58. package/dist/cli/chat/skillNotices.js +26 -0
  59. package/dist/cli/chat/startupInfo.js +1 -1
  60. package/dist/cli/chat/startupSequence.d.ts +2 -0
  61. package/dist/cli/chat/startupSequence.js +6 -0
  62. package/dist/cli/chat/submitPipeline.d.ts +8 -0
  63. package/dist/cli/chat/submitPipeline.js +141 -0
  64. package/dist/cli/chat/terminalControl.js +1 -1
  65. package/dist/cli/chat/toolSummaries.d.ts +29 -0
  66. package/dist/cli/chat/toolSummaries.js +268 -0
  67. package/dist/cli/chat/turnState.d.ts +8 -0
  68. package/dist/cli/chat/turnState.js +1 -0
  69. package/dist/cli/chat/userCommandFlow.d.ts +21 -0
  70. package/dist/cli/chat/userCommandFlow.js +66 -0
  71. package/dist/cli/chat/userCommandRunner.d.ts +14 -0
  72. package/dist/cli/chat/userCommandRunner.js +56 -0
  73. package/dist/cli/chat/wizard/providerHandlers.js +19 -2
  74. package/dist/cli/chat/wizardTrail.d.ts +22 -0
  75. package/dist/cli/chat/wizardTrail.js +55 -0
  76. package/dist/cli/commands/chat.d.ts +1 -13
  77. package/dist/cli/commands/chat.js +10 -795
  78. package/dist/cli/commands/commandHelp.js +11 -6
  79. package/dist/cli/commands/commandSuggest.d.ts +2 -0
  80. package/dist/cli/commands/commandSuggest.js +35 -0
  81. package/dist/cli/commands/commands.js +12 -3
  82. package/dist/cli/commands/formatters.d.ts +1 -23
  83. package/dist/cli/commands/formatters.js +3 -224
  84. package/dist/cli/commands/graphCommand.d.ts +2 -0
  85. package/dist/cli/commands/graphCommand.js +60 -0
  86. package/dist/cli/commands/initCommand.js +14 -0
  87. package/dist/cli/commands/modelCommand.js +11 -7
  88. package/dist/cli/commands/reasoningCommand.js +3 -3
  89. package/dist/cli/commands/runCommand.js +6 -2
  90. package/dist/cli/commands/streaming/agentAttempt.js +11 -1
  91. package/dist/cli/commands/streaming/attemptLifecycle.js +1 -0
  92. package/dist/cli/commands/streaming/attemptOutcome.js +8 -3
  93. package/dist/cli/commands/streaming/attemptSetup.d.ts +4 -0
  94. package/dist/cli/commands/streaming/attemptSetup.js +34 -5
  95. package/dist/cli/commands/streaming/goalCheckpoint.d.ts +1 -1
  96. package/dist/cli/commands/streaming/goalSupervisor.js +5 -3
  97. package/dist/cli/commands/streaming/prepareStep.js +1 -0
  98. package/dist/cli/commands/streaming/stepProjection.d.ts +59 -0
  99. package/dist/cli/commands/streaming/stepProjection.js +54 -0
  100. package/dist/cli/commands/streaming/streamLoop.d.ts +2 -0
  101. package/dist/cli/commands/streaming/streamLoop.js +34 -23
  102. package/dist/cli/commands/streaming/toolGroupRenderer.js +1 -1
  103. package/dist/cli/commands/streaming/toolPartHandlers.js +8 -2
  104. package/dist/cli/commands/streaming.d.ts +3 -1
  105. package/dist/cli/commands/streaming.js +5 -0
  106. package/dist/cli/commands/wizardFlow.d.ts +2 -0
  107. package/dist/cli/commands/wizardFlow.js +3 -0
  108. package/dist/cli/index.js +8 -4
  109. package/dist/cli/terminalTitle.js +9 -3
  110. package/dist/config/contextFiles.d.ts +2 -5
  111. package/dist/config/contextFiles.js +1 -1
  112. package/dist/config/inputHistory.js +2 -2
  113. package/dist/config/providerAuth.js +2 -2
  114. package/dist/config/providerModelFacts.js +5 -0
  115. package/dist/config/providerPresets.js +1 -1
  116. package/dist/config/settings.d.ts +7 -0
  117. package/dist/config/settings.js +9 -2
  118. package/dist/config/updateCheck.js +2 -2
  119. package/dist/core/agent/compaction.d.ts +1 -0
  120. package/dist/core/agent/compaction.js +3 -0
  121. package/dist/core/agent/completionController.d.ts +1 -1
  122. package/dist/core/agent/contextBudget.d.ts +1 -1
  123. package/dist/core/agent/goalPolicy.js +8 -2
  124. package/dist/core/agent/overflow.js +5 -0
  125. package/dist/core/agent/toolCapabilities.js +14 -0
  126. package/dist/core/agent/userCommands.d.ts +53 -0
  127. package/dist/core/agent/userCommands.js +116 -0
  128. package/dist/core/agent/workState.d.ts +3 -1
  129. package/dist/core/agent/workState.js +57 -26
  130. package/dist/core/contextFileTypes.d.ts +12 -0
  131. package/dist/core/contextFileTypes.js +1 -0
  132. package/dist/core/graph/analyze.d.ts +61 -0
  133. package/dist/core/graph/analyze.js +274 -0
  134. package/dist/core/graph/buildGraph.d.ts +44 -0
  135. package/dist/core/graph/buildGraph.js +290 -0
  136. package/dist/core/graph/digest.d.ts +2 -0
  137. package/dist/core/graph/digest.js +40 -0
  138. package/dist/core/graph/extract.d.ts +58 -0
  139. package/dist/core/graph/extract.js +394 -0
  140. package/dist/core/graph/model.d.ts +63 -0
  141. package/dist/core/graph/model.js +96 -0
  142. package/dist/core/graph/query.d.ts +69 -0
  143. package/dist/core/graph/query.js +391 -0
  144. package/dist/core/graph/store.d.ts +64 -0
  145. package/dist/core/graph/store.js +171 -0
  146. package/dist/core/limits.d.ts +2 -0
  147. package/dist/core/limits.js +2 -0
  148. package/dist/core/log/llmLog.js +2 -2
  149. package/dist/{config → core/persistence}/privateStorage.js +1 -1
  150. package/dist/core/process/runBoundedProcess.d.ts +7 -4
  151. package/dist/core/process/runBoundedProcess.js +22 -11
  152. package/dist/core/safety/redaction.d.ts +2 -0
  153. package/dist/core/safety/redaction.js +26 -5
  154. package/dist/core/safety/secretPaths.js +12 -3
  155. package/dist/core/safety/untrustedEnvelopes.d.ts +6 -0
  156. package/dist/core/safety/untrustedEnvelopes.js +17 -2
  157. package/dist/core/safety/urlGuard.js +2 -0
  158. package/dist/core/session/sessionStore.d.ts +8 -1
  159. package/dist/core/session/sessionStore.js +15 -4
  160. package/dist/core/shellOutput/reducers/validation.d.ts +1 -1
  161. package/dist/core/shellOutput/types.d.ts +1 -1
  162. package/dist/core/subagent/executionProfiles.js +4 -4
  163. package/dist/core/tasks/taskStorage.js +11 -1
  164. package/dist/{llm → core}/toolResultTypes.d.ts +1 -1
  165. package/dist/core/validation/outputParser.d.ts +1 -1
  166. package/dist/core/validation/outputParser.js +16 -8
  167. package/dist/llm/hazeTools.d.ts +2 -12426
  168. package/dist/llm/hazeTools.js +4 -0
  169. package/dist/llm/lsp/pool.js +1 -1
  170. package/dist/llm/lsp/workspaceEdit.d.ts +1 -1
  171. package/dist/llm/lspTools.d.ts +3 -12622
  172. package/dist/llm/requestContext.d.ts +6 -0
  173. package/dist/llm/requestContext.js +28 -7
  174. package/dist/llm/subagentRunner.d.ts +2 -308
  175. package/dist/llm/systemPrompt.js +17 -7
  176. package/dist/llm/toolGroups.d.ts +534 -0
  177. package/dist/llm/toolGroups.js +57 -0
  178. package/dist/llm/tools/editMatch.d.ts +1 -1
  179. package/dist/llm/tools/failures.d.ts +1 -1
  180. package/dist/llm/tools/fetchTool.d.ts +2 -1221
  181. package/dist/llm/tools/fileToolShared.d.ts +1 -1
  182. package/dist/llm/tools/fileToolShared.js +1 -1
  183. package/dist/llm/tools/fileTools.d.ts +2 -7768
  184. package/dist/llm/tools/fileTools.js +1 -1
  185. package/dist/llm/tools/gitTools.d.ts +12 -0
  186. package/dist/llm/tools/gitTools.js +527 -0
  187. package/dist/llm/tools/graphAdvisory.d.ts +22 -0
  188. package/dist/llm/tools/graphAdvisory.js +68 -0
  189. package/dist/llm/tools/graphTools.d.ts +13 -0
  190. package/dist/llm/tools/graphTools.js +195 -0
  191. package/dist/llm/tools/processTool.d.ts +2 -1081
  192. package/dist/llm/tools/readRecovery.d.ts +1 -1
  193. package/dist/llm/tools/replaceInFiles.d.ts +1 -1
  194. package/dist/llm/tools/replaceInFiles.js +1 -1
  195. package/dist/llm/tools/shellTool.d.ts +2 -1513
  196. package/dist/llm/tools/storedOutputTool.d.ts +2 -355
  197. package/dist/llm/tools/taskTool.d.ts +2 -489
  198. package/dist/llm/tools/taskTool.js +4 -1
  199. package/dist/llm/tools/toolContext.js +29 -11
  200. package/dist/llm/tools/toolContextState.d.ts +4 -1
  201. package/dist/llm/tools/toolContextState.js +2 -1
  202. package/dist/llm/tools/workspaceFile.d.ts +2 -2
  203. package/dist/llm/tools/workspaceFile.js +10 -5
  204. package/dist/skills/SkillRegistry.js +1 -1
  205. package/dist/skills/builder/SkillBuilder.js +1 -1
  206. package/dist/skills/plugins/installer.js +1 -1
  207. package/dist/skills/plugins/runtime.js +1 -1
  208. package/dist/skills/skillTools.js +4 -1
  209. package/dist/ui/components/MarkdownText.d.ts +14 -0
  210. package/dist/ui/components/MarkdownText.js +77 -12
  211. package/dist/ui/components/NativeIndicators.js +5 -1
  212. package/dist/ui/components/StreamingMarkdownText.d.ts +3 -1
  213. package/dist/ui/components/StreamingMarkdownText.js +39 -11
  214. package/dist/ui/components/TextInput.d.ts +1 -2
  215. package/dist/ui/components/TextInput.js +79 -9
  216. package/dist/ui/components/WizardChoices.d.ts +1 -2
  217. package/dist/ui/components/useInputSuggestions.d.ts +1 -1
  218. package/dist/ui/components/useInputSuggestions.js +1 -1
  219. package/dist/ui/mentionDetection.d.ts +20 -0
  220. package/dist/ui/mentionDetection.js +24 -0
  221. package/dist/ui/terminalColors.d.ts +4 -4
  222. package/dist/ui/terminalColors.js +23 -6
  223. package/dist/ui/terminalSanitize.js +8 -3
  224. package/dist/ui/textGeometry.d.ts +2 -0
  225. package/dist/ui/textGeometry.js +6 -0
  226. package/dist/ui/themes/registry.js +33 -33
  227. package/dist/utils/openPath.js +7 -0
  228. package/package.json +22 -19
  229. /package/dist/{llm/tools → core/ignore}/gitIgnore.d.ts +0 -0
  230. /package/dist/{llm/tools → core/ignore}/gitIgnore.js +0 -0
  231. /package/dist/{config → core}/paths.d.ts +0 -0
  232. /package/dist/{config → core}/paths.js +0 -0
  233. /package/dist/{config → core/persistence}/privateStorage.d.ts +0 -0
  234. /package/dist/{llm → core}/toolResultTypes.js +0 -0
@@ -1,799 +1,13 @@
1
- import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
2
- import { useEffect, useReducer, useRef, useState } from 'react';
3
- import { Box, render, Static, Text, useApp, useWindowSize } from 'ink';
4
- import { StatusNotice } from '../../ui/components/NativeIndicators.js';
5
- import { BusyBar } from '../chat/BusyBar.js';
6
- import { readContextFiles } from '../../config/contextFiles.js';
7
- import { addInputHistoryItem, readInputHistory } from '../../config/inputHistory.js';
8
- import { loadTasks as loadTasksFromStore, clearTasks as clearTasksFromStore } from '../../core/tasks/taskStorage.js';
9
- import { readSettings, updateSettings } from '../../config/settings.js';
10
- import { activeModel, providerEndpointFingerprint, resolveModelSelector } from '../../config/providers.js';
11
- import { isSkillEnabled } from '../../config/skillSettings.js';
12
- import { Header } from '../../ui/components/Header.js';
13
- import { TextInput } from '../../ui/components/TextInput.js';
14
- import { setActiveTheme, resolveTheme, theme, DEFAULT_THEME_NAME } from '../../ui/theme.js';
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
+ import { render } from 'ink';
3
+ import { readSettings } from '../../config/settings.js';
4
+ import { clearTasks as clearTasksFromStore } from '../../core/tasks/taskStorage.js';
5
+ import { DEFAULT_THEME_NAME, resolveTheme, setActiveTheme, theme } from '../../ui/theme.js';
15
6
  import { applyTerminalColors, resetTerminalColors } from '../../ui/terminalColors.js';
16
- import { handleSlashCommand } from './commands.js';
17
- import { runAgentGoal } from './streaming/goalSupervisor.js';
18
- import { checkpointFromGoalFrontier } from './streaming/goalCheckpoint.js';
19
- import { endLog as endLlmLog } from '../../core/log/llmLog.js';
20
- import { loadSkillRegistry } from '../../skills/SkillRegistry.js';
21
- import { formatSession, listSessions } from '../../core/session/sessionStore.js';
22
- import { MAX_VISIBLE_TASKS, TaskBar } from '../chat/TaskBar.js';
23
- import { DynamicFrame } from '../chat/DynamicFrame.js';
24
- import { createChatShutdown, runTerminalSession } from '../chat/shutdown.js';
7
+ import { runTerminalSession } from '../chat/shutdown.js';
25
8
  import { installViewportResizeGuard } from '../chat/resizeGuard.js';
26
- import { createQuarantinableCallbacks } from './streaming/attemptLifecycle.js';
27
- import { AssistantMarkdownChunkView, MessageView } from '../chat/messages.js';
28
- import { partitionDisplayMessages } from '../chat/transcriptPartition.js';
29
- import { useLiveMessages } from '../chat/liveMessages.js';
30
- import { createSessionRecorder } from '../chat/sessionRecorder.js';
31
- import { createSessionLifecycle } from '../chat/sessionLifecycle.js';
32
- import { createWizardDispatch, initialWizardUiState, wizardUiReducer } from '../chat/wizardDispatch.js';
33
- import { buildContextReport } from '../chat/contextReport.js';
34
- import { TIPS, randomTipIndex, tipsEnabled } from '../chat/tips.js';
35
- import { fileMentionSuggestions } from '../chat/fileMentionSuggestions.js';
36
- import { busyDetailLabel, compactHomePath, nextFleetStatus, statusBarMetrics } from '../chat/chatMetrics.js';
37
- import { formatTokenCount } from '../../utils/format.js';
38
- import { accumulateTokenUsage, EMPTY_TOKEN_USAGE, shouldClearCompletedTasks } from '../chat/turnState.js';
39
- import { MASKED_MODES, PICKER_MODES, SUBMIT_EMPTY_MODES, placeholderForMode } from './chatModes.js';
40
- import { contextFileSignatureMap, isPausedGoalRecoveryCommand, mergeSettingsSelection, prepareUserInput as prepareUserInputPolicy, resumeKindFor } from '../chat/userInput.js';
41
- import { isStoredReasoning, resolveReasoningChoice } from '../../core/agent/reasoningPolicy.js';
42
- import { resolveProviderReasoning } from '../../config/providerReasoning.js';
43
- import { inputSuggestionsForState } from '../chat/inputSuggestions.js';
44
- import { currentBranchName, runStartupSequence } from '../chat/startupSequence.js';
45
- import { useFollowUpQueue } from '../chat/followUpQueue.js';
46
- import { useBusyIndicator } from '../chat/busyIndicator.js';
47
- import { useTerminalControl } from '../chat/terminalControl.js';
48
- import { modelThinkingLabel } from '../../utils/modelName.js';
49
- import { transitionProviderConversation } from '../../core/agent/providerTransition.js';
50
- import { commandParts } from './wizardFlow.js';
51
- import { backgroundProcessCount, subscribeBackgroundProcesses, teardownBackgroundProcesses } from '../../core/process/backgroundRegistry.js';
52
- import { MAX_SESSION_PICKER_RESULTS } from './sessionPicker.js';
53
- import { listInstalledPlugins } from './pluginCommand.js';
54
- /** Latest Ink render metrics under --debug (module-level: render options are outside React). */
55
- let renderMetricsReader;
56
- function thinkingLabelForSettings(settings) {
57
- return modelThinkingLabel(activeModel(settings)?.model);
58
- }
59
- function ChatScreen({ debug = false, version, build, continueSession = false, resumeSessionId, noSession = false, onShutdownReady }) {
60
- const { exit } = useApp();
61
- const { columns: width, rows: terminalRows } = useWindowSize();
62
- const stoppingRef = useRef(false);
63
- const sealedRef = useRef(false);
64
- const activeGoalRef = useRef(undefined);
65
- const quarantineRef = useRef(undefined);
66
- const nextDisplayOrderRef = useRef(1);
67
- const withDisplayOrder = (message) => {
68
- if (message.displayOrder != null)
69
- return message;
70
- return { ...message, displayOrder: nextDisplayOrderRef.current++ };
71
- };
72
- const withDisplayOrders = (next) => next.map(withDisplayOrder);
73
- const [messages, setMessagesRaw] = useState([]);
74
- const setMessages = (updater) => {
75
- if (stoppingRef.current)
76
- return;
77
- setMessagesRaw(previous => withDisplayOrders(typeof updater === 'function' ? updater(previous) : updater));
78
- };
79
- const [settings, setSettingsRaw] = useState({});
80
- const settingsRef = useRef({});
81
- const defaultSelectionRef = useRef({});
82
- function setSettings(next, patch) {
83
- const previousSelection = currentModelSelection();
84
- const previousProvider = activeModel(settingsRef.current)?.provider;
85
- // The ref records the global default from `next` (what updateSettings
86
- // returned) before the patch merge; unrelated settings writes must not
87
- // replace a resumed session's model (merge policy in chat/userInput.ts).
88
- defaultSelectionRef.current = { provider: next.provider, model: next.model };
89
- settingsRef.current = patch ? mergeSettingsSelection(next, settingsRef.current, patch) : next;
90
- const selected = currentModelSelection();
91
- const selectedProvider = activeModel(settingsRef.current)?.provider;
92
- const changedEndpoint = selectedProvider && (!previousProvider || previousProvider.url !== selectedProvider.url || previousProvider.kind !== selectedProvider.kind);
93
- if (patch && previousSelection && selected && (previousSelection.provider !== selected.provider || previousSelection.model !== selected.model || changedEndpoint) && conversationRef.current.length) {
94
- conversationRef.current = transitionProviderConversation(conversationRef.current);
95
- sessionRecorderRef.current?.recordModelTransition(conversationRef.current, selected);
96
- setMessages(messages => [...messages, { role: 'system', text: 'Model changed: previous tool history was converted to text and provider reasoning state was cleared.' }]);
97
- }
98
- setSettingsRaw(settingsRef.current);
99
- if (patch && ('provider' in patch || 'model' in patch)) {
100
- if (selected)
101
- sessionRecorderRef.current?.recordModelSelection(selected);
102
- }
103
- }
104
- function currentModelSelection() {
105
- const { provider, model } = settingsRef.current;
106
- const selected = activeModel(settingsRef.current);
107
- return provider && model ? { provider, model, ...(selected ? { endpointFingerprint: providerEndpointFingerprint(selected.provider) } : {}) } : undefined;
108
- }
109
- const [settingsError, setSettingsError] = useState();
110
- const conversationRef = useRef([]);
111
- const lastAssistantTextRef = useRef('');
112
- const abortControllerRef = useRef(null);
113
- const sessionRef = useRef(undefined);
114
- const sessionRecorderRef = useRef(undefined);
115
- if (!sessionRecorderRef.current)
116
- sessionRecorderRef.current = createSessionRecorder(() => sessionRef.current);
117
- /** Finalize a formerly-live message into the append-only transcript and session record. */
118
- function finalizeMessage(message) {
119
- if (message.hidden || sealedRef.current)
120
- return;
121
- const ordered = withDisplayOrder(message);
122
- setMessages(m => [...m, ordered]);
123
- sessionRecorderRef.current?.recordUiMessage(ordered);
124
- }
125
- // Synchronous live-tail store (see chat/liveMessages.ts): stream callbacks
126
- // that land inside one React batch window must route against fresh state.
127
- const { liveMessages, addStreaming, patch: patchLiveMessage, drain: drainLiveMessages, clear: clearLiveMessages } = useLiveMessages(finalizeMessage);
128
- const sessionStartRef = useRef(new Date());
129
- // Stable PromptSession object across turns so per-session flags (the
130
- // context-fallback warning key) persist; rebuilt when a new session starts,
131
- // detected by sessionStartRef identity (the lifecycle controller replaces
132
- // the Date on new/resume/continue).
133
- const promptSessionRef = useRef({ identity: undefined, value: { cwd: process.cwd() } });
134
- // Session per-model reasoning overrides live on the stable PromptSession
135
- // object; this counter only forces a re-render so the status bar updates.
136
- const [reasoningOverrideCounter, setReasoningOverrideCounter] = useState(0);
137
- const workStateRef = useRef(undefined);
138
- const llmLogRef = useRef(undefined);
139
- const persistenceWarningShownRef = useRef(false);
140
- const skillErrorSignatureRef = useRef('');
141
- const skillNoticeSignatureRef = useRef('');
142
- const projectSkillSignatureRef = useRef('');
143
- const contextFileSignaturesRef = useRef(new Map());
144
- const followUps = useFollowUpQueue(text => setMessages(m => [...m, { role: 'system', text }]));
145
- const [inputHistory, setInputHistory] = useState([]);
146
- const [debugLogs, setDebugLogs] = useState([]);
147
- const [contextFiles, setContextFiles] = useState([]);
148
- const [mode, setMode] = useState('chat');
149
- const [sessions, setSessions] = useState([]);
150
- // Busy indicator with a one-second heartbeat: ticks while haze is working so
151
- // the developer always sees rolling activity (elapsed turn time) even when
152
- // the model is thinking with no streamed output and no tool is running.
153
- const { busy, setBusy: setBusyWithHeartbeat, elapsed: busyElapsed } = useBusyIndicator();
154
- // Fleet depth for the busy row; folded from coordinator events so a
155
- // minutes-long fan-out turn visibly progresses (workers running/queued).
156
- const [fleet, setFleet] = useState(undefined);
157
- const terminalControl = useTerminalControl();
158
- const [backgroundCount, setBackgroundCount] = useState(backgroundProcessCount);
159
- const [busyLabel, setBusyLabel] = useState(() => thinkingLabelForSettings(settings));
160
- const [visibleTasks, setVisibleTasks] = useState([]);
161
- const [tasksExpanded, setTasksExpanded] = useState(false);
162
- const [taskBarPadding, setTaskBarPadding] = useState(0);
163
- const [tokenUsage, setTokenUsage] = useState({ ...EMPTY_TOKEN_USAGE });
164
- // A genuinely paused goal (no measurable progress, deadline, or a stalled
165
- // model stream) — automatic continuation has already been attempted by the
166
- // goal supervisor. Carries what a one-key resume needs; any new submission
167
- // clears it.
168
- const [pausedResume, setPausedResume] = useState(undefined);
169
- const [skills, setSkills] = useState([]);
170
- const [branchName, setBranchName] = useState();
171
- const shutdownRef = useRef(undefined);
172
- if (!shutdownRef.current)
173
- shutdownRef.current = createChatShutdown({
174
- stop: () => { stoppingRef.current = true; followUps.clear(); },
175
- abort: () => abortControllerRef.current?.abort('Chat is exiting.'),
176
- settle: () => activeGoalRef.current,
177
- seal: () => {
178
- drainLiveMessages();
179
- sealedRef.current = true;
180
- quarantineRef.current?.();
181
- },
182
- flush: () => sessionRecorderRef.current?.flush(),
183
- endLog: () => {
184
- const log = llmLogRef.current;
185
- llmLogRef.current = undefined;
186
- return log ? endLlmLog(log) : undefined;
187
- },
188
- cleanup: async () => {
189
- await Promise.all([teardownBackgroundProcesses(), clearTasksFromStore()]);
190
- },
191
- exit,
192
- report: message => process.stderr.write(`[haze] ${message}\n`),
193
- });
194
- const shutdown = shutdownRef.current;
195
- useEffect(() => {
196
- onShutdownReady?.(shutdown);
197
- return () => { void shutdown(); };
198
- }, [onShutdownReady, shutdown]);
199
- // Wizard flow state (selection, drafts, model discovery) in one reducer;
200
- // this replaced twelve individual useState hooks.
201
- const [wizardState, updateWizard] = useReducer(wizardUiReducer, undefined, initialWizardUiState);
202
- const { modelProviderFilter, discoveredModels, suggestedModels, selectedProviderName, providerDraft, selectedSkillName, selectedLspName, selectedMcpName, plugins, selectedPluginName, pluginCollectionEntries } = wizardState;
203
- useEffect(() => subscribeBackgroundProcesses(() => setBackgroundCount(backgroundProcessCount())), []);
204
- // One tip per thinking section, shown under the busy label while the model
205
- // is purely thinking (no tool running) and the user has not disabled tips.
206
- // A fresh tip is picked each time the model enters thinking mode; no
207
- // rotation during a single thinking section.
208
- const [tipIndex, setTipIndex] = useState(() => randomTipIndex());
209
- const thinkingLabel = thinkingLabelForSettings(settings);
210
- const showingTip = busy && busyLabel === thinkingLabel && tipsEnabled(settings);
211
- useEffect(() => {
212
- if (!showingTip)
213
- return;
214
- setTipIndex(current => randomTipIndex(current));
215
- }, [showingTip]);
216
- // Refresh the branch at turn boundaries so switching branches during a turn
217
- // shows up promptly without tight idle polling (CR-026).
218
- useEffect(() => {
219
- if (busy)
220
- return;
221
- currentBranchName().then(setBranchName).catch(() => setBranchName(undefined));
222
- }, [busy]);
223
- // Live theme switching: whenever the settings'
224
- // theme name changes (/themes), re-resolve and adopt it so the whole UI
225
- // repaints without a restart. Ink <Static> history stays as-rendered, so
226
- // already-printed text keeps its old colors; the terminal defaults (OSC
227
- // 10/11) follow the new theme. Skipped until settings have loaded once —
228
- // chatCommand() already resolved the theme before the first render, and the
229
- // pre-load {} state would briefly flash the default theme.
230
- const settingsThemeLoadedRef = useRef(false);
231
- const activeThemeName = settings.theme ?? DEFAULT_THEME_NAME;
232
- useEffect(() => {
233
- if (!settingsThemeLoadedRef.current || stoppingRef.current)
234
- return;
235
- try {
236
- setActiveTheme(resolveTheme(activeThemeName));
237
- applyTerminalColors(theme.foreground, theme.background);
238
- }
239
- catch {
240
- // Malformed theme names were reported at startup; keep the resolved default.
241
- }
242
- }, [activeThemeName]);
243
- useEffect(() => {
244
- void runStartupSequence({
245
- version,
246
- onLoaded({ settings: next, settingsError, branchName: branch, contextFiles: files }) {
247
- setSettings(next);
248
- settingsThemeLoadedRef.current = true;
249
- setSettingsError(settingsError);
250
- setBranchName(branch);
251
- setContextFiles(files);
252
- contextFileSignaturesRef.current = contextFileSignatureMap(files);
253
- },
254
- initializeSession: () => sessionLifecycle.initializeSession(),
255
- refreshSkills,
256
- addSystemMessage: text => setMessages(m => [...m, { role: 'system', text }]),
257
- }).catch(() => undefined);
258
- readInputHistory().then(setInputHistory).catch(() => undefined);
259
- loadTasksFromStore().then(setVisibleTasks).catch(() => undefined);
260
- const branchTimer = setInterval(() => {
261
- currentBranchName().then(setBranchName).catch(() => setBranchName(undefined));
262
- }, 15_000);
263
- return () => clearInterval(branchTimer);
264
- }, []);
265
- function persistInputHistory(value) {
266
- addInputHistoryItem(value).then(setInputHistory).catch(() => undefined);
267
- }
268
- async function refreshSkills() {
269
- const registry = await loadSkillRegistry();
270
- const nextSkills = registry.candidates ?? [...registry.skills.values()];
271
- setSkills(nextSkills);
272
- const projectSkills = nextSkills.filter(skill => skill.source === 'project');
273
- const projectSignature = projectSkills.map(skill => `${skill.name}:${skill.path}`).join('\n');
274
- if (projectSignature && projectSignature !== projectSkillSignatureRef.current) {
275
- setMessages(messages => [...messages, { role: 'system', text: `Project skills discovered (repository-provided, untrusted content): ${projectSkills.map(skill => skill.name).join(', ')}` }]);
276
- }
277
- projectSkillSignatureRef.current = projectSignature;
278
- const errorSignature = registry.errors.map(error => `${error.source ? `${error.source}/` : ''}${error.directory}: ${error.message}`).join('\n');
279
- if (errorSignature && errorSignature !== skillErrorSignatureRef.current) {
280
- setMessages(messages => [...messages, { role: 'system', text: `Invalid skills were isolated:\n${errorSignature}` }]);
281
- }
282
- skillErrorSignatureRef.current = errorSignature;
283
- // Visible load-time shadow notices (HZA-6): a project skill silently
284
- // overriding a same-named user skill is something the user should see.
285
- const noticeSignature = (registry.notices ?? []).join('\n');
286
- if (noticeSignature && noticeSignature !== skillNoticeSignatureRef.current) {
287
- setMessages(messages => [...messages, { role: 'system', text: noticeSignature }]);
288
- }
289
- skillNoticeSignatureRef.current = noticeSignature;
290
- return nextSkills;
291
- }
292
- function skillInvocation(value) {
293
- if (!value.startsWith('/'))
294
- return undefined;
295
- const [name, ...args] = commandParts(value.slice(1));
296
- if (!name)
297
- return undefined;
298
- const skill = skills.find(candidate => candidate.name === name && isSkillEnabled(settings, candidate.name, candidate.source));
299
- // Candidates are ordered project-first, so disabling a project collision
300
- // automatically re-surfaces the enabled global skill.
301
- return skill ? { skill, args: args.join(' ') } : undefined;
302
- }
303
- function debugLog(line) {
304
- if (!debug || stoppingRef.current)
305
- return;
306
- setDebugLogs(current => [...current.slice(-7), line]);
307
- }
308
- function showPersistenceWarning(error) {
309
- if (persistenceWarningShownRef.current)
310
- return;
311
- persistenceWarningShownRef.current = true;
312
- const text = error instanceof Error ? error.message : String(error);
313
- setMessages(messages => [...messages, { role: 'system', text: `Persistence warning: ${text}` }]);
314
- }
315
- // Session lifecycle (init/continue/resume/new/clear/compact) lives in a
316
- // dedicated controller so this component stays orchestration glue (CR-006).
317
- const sessionLifecycle = createSessionLifecycle({
318
- version,
319
- build,
320
- continueSession,
321
- resumeSessionId,
322
- noSession,
323
- debug,
324
- contextFiles: () => contextFiles,
325
- modelSelection: currentModelSelection,
326
- reasoningByModel: () => currentPromptSession().reasoningByModel,
327
- onModelSelection: selection => {
328
- const model = selection ? { provider: selection.provider, model: selection.model } : defaultSelectionRef.current;
329
- settingsRef.current = { ...settingsRef.current, ...model };
330
- setSettingsRaw(settingsRef.current);
331
- },
332
- sessionRef,
333
- sessionRecorder: () => sessionRecorderRef.current,
334
- sessionStartRef,
335
- conversationRef,
336
- workStateRef,
337
- lastAssistantTextRef,
338
- llmLogRef,
339
- contextFileSignaturesRef,
340
- setMessages,
341
- clearLiveMessages,
342
- setTokenUsage,
343
- manualCompaction: () => settings.manualCompaction ?? 'llm-summary',
344
- redactSessionSecrets: () => settings.redactSessionSecrets === true,
345
- // P1 resume path: an unterminated goal frontier detected on resume becomes
346
- // the same one-key continue affordance the in-process pause uses — the
347
- // goal continues from the stored frontier without re-sending the request.
348
- onGoalFrontier: frontier => {
349
- const checkpoint = checkpointFromGoalFrontier(frontier);
350
- setPausedResume({ kind: 'incomplete-goal', request: frontier.request, retryAttempt: 0, checkpoint });
351
- setMessages(m => [...m, { role: 'system', text: `This session ended with an unfinished goal (cycle ${frontier.cycle}, ${frontier.mutationCount} change${frontier.mutationCount === 1 ? '' : 's'} so far). Press R to resume it from where it stopped.` }]);
352
- },
353
- debugLog,
354
- showPersistenceWarning,
355
- });
356
- const { clearConversation, compactConversation, compactConversationWithModel } = sessionLifecycle;
357
- async function openSessionPicker() {
358
- await sessionRecorderRef.current?.flush().catch(showPersistenceWarning);
359
- const next = await listSessions();
360
- setSessions(next);
361
- updateWizard({ type: 'set', key: 'selectedSessionId', value: undefined });
362
- if (next.length === 0) {
363
- setMessages(m => [...m, { role: 'system', text: 'No saved sessions found for this workspace.' }]);
364
- setMode('chat');
365
- return;
366
- }
367
- setMode('sessions');
368
- const hidden = Math.max(0, next.length - MAX_SESSION_PICKER_RESULTS);
369
- setMessages(m => [...m, { role: 'system', text: `Choose a saved session (newest first)${hidden ? `. Showing ${MAX_SESSION_PICKER_RESULTS} of ${next.length}; ${hidden} older sessions are hidden.` : '.'}` }]);
370
- }
371
- async function openPluginPicker() {
372
- try {
373
- updateWizard({ type: 'plugins', value: await listInstalledPlugins() });
374
- }
375
- catch (error) {
376
- setMessages(m => [...m, { role: 'system', text: `Could not list installed plugins: ${error instanceof Error ? error.message : String(error)}` }]);
377
- return;
378
- }
379
- setMode('plugins');
380
- setMessages(m => [...m, { role: 'system', text: 'Choose install plugin, inspect plugin, or an installed plugin to manage. Only skills activate; no scripts, hooks, or MCP servers run.' }]);
381
- }
382
- function cancelThinking() {
383
- if (!busy)
384
- return;
385
- abortControllerRef.current?.abort('User pressed Esc.');
386
- followUps.clear();
387
- setBusyWithHeartbeat(false);
388
- }
389
- function closeInputList() {
390
- if (mode !== 'chat') {
391
- setMode('chat');
392
- setSessions([]);
393
- updateWizard({ type: 'reset' });
394
- }
395
- }
396
- function showWizardMessage(message) {
397
- if (message)
398
- setMessages(m => [...m, { role: 'system', text: message }]);
399
- }
400
- // Session per-model reasoning overrides live on the stable PromptSession
401
- // object; the counter only forces a re-render so the status bar updates.
402
- function setSessionReasoningOverride(modelSelector, setting) {
403
- const session = currentPromptSession();
404
- if (setting === undefined) {
405
- if (session.reasoningByModel)
406
- delete session.reasoningByModel[modelSelector];
407
- }
408
- else {
409
- session.reasoningByModel = { ...session.reasoningByModel, [modelSelector]: setting };
410
- }
411
- setReasoningOverrideCounter(count => count + 1);
412
- }
413
- // Wizard/picker submit dispatch lives in one table-driven module with a
414
- // shared settings-patch applier (CR-006). Rebuilt every render so handlers
415
- // see current state without new React state.
416
- const wizard = createWizardDispatch({
417
- settings, skills, sessions,
418
- wizard: wizardState, updateWizard,
419
- setMode, setSettings,
420
- showMessage: showWizardMessage, refreshSkills,
421
- resumeSessionById: sessionLifecycle.resumeSessionById,
422
- forkSessionById: sessionLifecycle.forkSessionById,
423
- setBusyLabel, setBusy: setBusyWithHeartbeat,
424
- idleBusyLabel: thinkingLabelForSettings(settings),
425
- sessionReasoning: {
426
- modelSelector: () => { const selection = activeModel(settings); return selection ? `${selection.provider.name}:${selection.model}` : undefined; },
427
- get: modelSelector => currentPromptSession().reasoningByModel?.[modelSelector],
428
- set: setSessionReasoningOverride,
429
- },
430
- });
431
- async function submit(value) {
432
- if (stoppingRef.current)
433
- return;
434
- if (mode === 'chat' && /^\/(?:exit|quit)\s*$/i.test(value))
435
- return shutdown();
436
- if (settingsError) {
437
- try {
438
- const repaired = await readSettings();
439
- setSettings(repaired, {});
440
- setSettingsError(undefined);
441
- }
442
- catch (error) {
443
- const message = error instanceof Error ? error.message : String(error);
444
- setSettingsError(message);
445
- if (!/^\/(?:settings\s+(?:open|edit)|help|exit|quit)\b/i.test(value.trim())) {
446
- setMessages(messages => [...messages, { role: 'system', text: `${message}\nRepair settings, then retry. /settings edit (or /settings open), /help, and /exit remain available.` }]);
447
- return;
448
- }
449
- }
450
- }
451
- if (busy) {
452
- if (mode === 'chat')
453
- followUps.queue(value);
454
- return;
455
- }
456
- // A new goal or session reset supersedes the paused-goal resume affordance;
457
- // recovery/configuration commands (compact, model, provider, settings,
458
- // resume…) intentionally keep it — the pause notice tells the user to run
459
- // exactly those and then press R (SU-04).
460
- const isRecoveryCommand = isPausedGoalRecoveryCommand(mode, value);
461
- if (pausedResume && !isRecoveryCommand)
462
- setPausedResume(undefined);
463
- if (await wizard.dispatch(mode, value))
464
- return;
465
- const invokedSkill = skillInvocation(value);
466
- if (invokedSkill) {
467
- const argumentText = invokedSkill.args ? `\nUser-provided skill arguments: ${invokedSkill.args}` : '';
468
- await doAgentTurn(`The user explicitly invoked the "${invokedSkill.skill.name}" skill. Call skill with name="${invokedSkill.skill.name}" and follow its returned instructions.${argumentText}`, value);
469
- return;
470
- }
471
- const ctx = {
472
- settings,
473
- contextFiles,
474
- setMode,
475
- setModelProviderFilter: (filter) => updateWizard({ type: 'set', key: 'modelProviderFilter', value: filter }),
476
- addSystemMessage: text => setMessages(m => [...m, { role: 'system', text }]),
477
- clearConversation,
478
- newSession: async () => {
479
- conversationRef.current = [];
480
- lastAssistantTextRef.current = '';
481
- clearLiveMessages();
482
- setMessages([{ role: 'system', text: 'Started fresh. The fog parts.' }]);
483
- await sessionLifecycle.startNewSession('New session started.');
484
- },
485
- resumeSession: noSession ? undefined : async (id) => {
486
- if (id)
487
- await sessionLifecycle.resumeSessionById(id);
488
- else
489
- await openSessionPicker();
490
- },
491
- sessionInfo: () => sessionRef.current ? formatSession(sessionRef.current) : 'Session persistence is off.',
492
- compactConversation,
493
- compactConversationLlm: compactConversationWithModel,
494
- runAgentTurn: (prompt, displayValue, options) => doAgentTurn(prompt, displayValue, options),
495
- composeInEditor: async () => {
496
- const text = await terminalControl.composeInEditor();
497
- if (text === undefined)
498
- setMessages(m => [...m, { role: 'system', text: '/editor needs $EDITOR (or $VISUAL) set to an editor command.' }]);
499
- return text;
500
- },
501
- viewInPager: terminalControl.viewInPager,
502
- editFileInEditor: terminalControl.editFileInEditor,
503
- refreshSkills,
504
- openPluginPicker,
505
- refreshContextFiles: async () => {
506
- const files = await readContextFiles().catch(() => contextFiles);
507
- setContextFiles(files);
508
- contextFileSignaturesRef.current = contextFileSignatureMap(files);
509
- return files;
510
- },
511
- updateSettings: async (patch) => {
512
- const next = await updateSettings(patch);
513
- setSettings(next, patch);
514
- return settingsRef.current;
515
- },
516
- getSessionReasoning: modelSelector => currentPromptSession().reasoningByModel?.[modelSelector],
517
- setSessionReasoning: setSessionReasoningOverride,
518
- getContextReport: () => buildContextReport({ sessionStart: sessionStartRef.current, contextFiles, conversation: conversationRef.current }),
519
- };
520
- let result;
521
- try {
522
- result = await handleSlashCommand(value, ctx);
523
- }
524
- catch (error) {
525
- const text = error instanceof Error ? error.message : String(error);
526
- setMessages(m => [...m, { role: 'system', text: `Command failed: ${text}` }]);
527
- return;
528
- }
529
- if (result === 'exit')
530
- return shutdown();
531
- if (result === 'handled') {
532
- if (value === '/clear') {
533
- loadTasksFromStore().then(t => { setVisibleTasks(t); setTaskBarPadding(0); }).catch(() => undefined);
534
- }
535
- return;
536
- }
537
- const prepared = await prepareUserInput(value);
538
- if (!prepared)
539
- return;
540
- await doAgentTurn(prepared.value, prepared.displayValue, prepared.options);
541
- }
542
- // F03: attachment gating and read blessings live in the pure helper
543
- // (chat/userInput.ts); this wrapper only surfaces its errors as system
544
- // messages. Applied only to genuine user input, never synthetic control prompts.
545
- async function prepareUserInput(value) {
546
- const prepared = await prepareUserInputPolicy(value, settings);
547
- if (prepared?.error) {
548
- setMessages(m => [...m, { role: 'system', text: prepared.error }]);
549
- return undefined;
550
- }
551
- return prepared;
552
- }
553
- async function doAgentTurn(value, displayValue, turnOptions = {}) {
554
- if (stoppingRef.current)
555
- return;
556
- setDebugLogs([]);
557
- // When every task is already completed, start the new turn with a clean
558
- // slate: the task bar clears (nothing shown for simple questions) and the
559
- // model may create fresh todos via writeTasks if the new question warrants.
560
- if (shouldClearCompletedTasks(visibleTasks)) {
561
- setVisibleTasks([]);
562
- setTasksExpanded(false);
563
- setTaskBarPadding(0);
564
- await clearTasksFromStore().catch(() => undefined);
565
- }
566
- await runSingleAgentTurn(value, displayValue, turnOptions);
567
- for (let next = followUps.takeNext(); !stoppingRef.current && next !== undefined; next = followUps.takeNext()) {
568
- const preparedFollowUp = await prepareUserInput(next);
569
- if (!preparedFollowUp)
570
- continue;
571
- await runSingleAgentTurn(preparedFollowUp.value, preparedFollowUp.displayValue, preparedFollowUp.options);
572
- }
573
- }
574
- /**
575
- * Explicitly resume a genuinely paused goal (automatic continuation already
576
- * ran): an idle-stall resume continues the bounded retry pool; an
577
- * incomplete-goal resume restarts the supervisor from the stored checkpoint
578
- * (kind selection in chat/userInput.ts). Both ride the preserved
579
- * conversation — no completed mutations are replayed.
580
- */
581
- async function resumePausedTask() {
582
- const resume = pausedResume;
583
- if (!resume || busy)
584
- return;
585
- setPausedResume(undefined);
586
- setMessages(m => [...m, { role: 'system', text: 'Resuming the unfinished goal; completed work is preserved in the conversation.' }]);
587
- await runSingleAgentTurn(resume.request, undefined, {}, resumeKindFor(resume));
588
- }
589
- /**
590
- * The PromptSession shared by every turn of the active session. Returning a
591
- * stable object (not a fresh literal per turn) is what makes once-per-session
592
- * affordances actually once-per-session; a new session identity yields a
593
- * fresh object so they fire again at its start.
594
- */
595
- function currentPromptSession() {
596
- if (promptSessionRef.current.identity !== sessionStartRef.current) {
597
- promptSessionRef.current = { identity: sessionStartRef.current, value: { start: sessionStartRef.current, cwd: process.cwd() } };
598
- }
599
- return promptSessionRef.current.value;
600
- }
601
- async function runSingleAgentTurn(value, displayValue, turnOptions = {}, resumeExisting) {
602
- if (stoppingRef.current)
603
- return;
604
- const sessionRecorder = sessionRecorderRef.current;
605
- const selection = currentModelSelection();
606
- if (!selection) {
607
- setMessages(m => [...m, { role: 'system', text: 'No model selected for this session. Run /model to choose one.' }]);
608
- return;
609
- }
610
- sessionRecorder.recordModelSelection(selection);
611
- // The logical-goal supervisor owns this submission: recoverable-incomplete
612
- // physical turns (including step/tool budget boundaries) continue
613
- // automatically; per-turn limits stay safety boundaries. An explicit
614
- // resumeFrom restarts a genuinely paused goal from its checkpoint/pool.
615
- const goalOptions = {
616
- request: value,
617
- displayValue,
618
- contextFiles,
619
- session: currentPromptSession(),
620
- modelOverride: `${selection.provider}:${selection.model}`,
621
- escalationModel: settings.escalationModel,
622
- callbacks: {
623
- addMessage: msg => {
624
- const ordered = withDisplayOrder(msg);
625
- if (ordered.streaming) {
626
- addStreaming(ordered);
627
- return;
628
- }
629
- finalizeMessage(ordered);
630
- },
631
- updateMessage: (id, update) => {
632
- if (patchLiveMessage(id, update))
633
- return;
634
- setMessages(m => m.map(msg => msg.id === id ? { ...msg, ...update } : msg));
635
- },
636
- setConversation: msgs => {
637
- conversationRef.current = msgs;
638
- sessionRecorder.recordConversation(msgs);
639
- },
640
- onModelTransition: (selector, msgs) => {
641
- const resolved = resolveModelSelector(settingsRef.current, selector);
642
- if (resolved.status === 'found')
643
- sessionRecorder.recordModelTransition(msgs, { provider: resolved.provider.name, model: resolved.model, endpointFingerprint: providerEndpointFingerprint(resolved.provider) });
644
- },
645
- setBusy: setBusyWithHeartbeat,
646
- setBusyLabel,
647
- debugLog,
648
- getConversation: () => conversationRef.current,
649
- getLastAssistantText: () => lastAssistantTextRef.current,
650
- setLastAssistantText: text => { lastAssistantTextRef.current = text; },
651
- setAbortController: controller => {
652
- abortControllerRef.current = controller;
653
- if (stoppingRef.current)
654
- controller?.abort('Chat is exiting.');
655
- },
656
- setWorkState: state => {
657
- workStateRef.current = state;
658
- sessionRecorder.recordWorkState(state);
659
- },
660
- compactConversation,
661
- recordCompaction: entry => sessionRecorder.recordCompactEntry(entry),
662
- recordTokenUsage: usage => {
663
- setTokenUsage(current => accumulateTokenUsage(current, usage));
664
- },
665
- onEvent: event => {
666
- sessionRecorder.recordEvent(event);
667
- if (event.type === 'subagent_state')
668
- setFleet(current => nextFleetStatus(current, event));
669
- else if (event.type === 'goal_end')
670
- setFleet(undefined);
671
- },
672
- onTasksChanged: () => {
673
- loadTasksFromStore().then(t => {
674
- if (stoppingRef.current)
675
- return;
676
- setVisibleTasks(t);
677
- setTaskBarPadding(0);
678
- }).catch(() => undefined);
679
- },
680
- contextFileSignatures: contextFileSignaturesRef.current,
681
- log: llmLogRef.current,
682
- },
683
- ...(resumeExisting ? { resumeFrom: resumeExisting } : {}),
684
- // Durable goal ledger (P1): every supervisor boundary appends to the
685
- // session JSONL so a crash or restart leaves a resumable frontier.
686
- goalLedger: { append: entry => { if (!sealedRef.current)
687
- sessionRecorder.recordGoalEntry(entry); } },
688
- ...(turnOptions.attachments || turnOptions.blessedPaths || turnOptions.ephemeralControl || turnOptions.subagentOverrides ? { turnOptions } : {})
689
- };
690
- const guarded = createQuarantinableCallbacks(goalOptions.callbacks);
691
- quarantineRef.current = guarded.quarantine;
692
- const goalPromise = runAgentGoal({ ...goalOptions, callbacks: guarded.callbacks });
693
- activeGoalRef.current = goalPromise;
694
- const goalResult = await goalPromise;
695
- activeGoalRef.current = undefined;
696
- if (stoppingRef.current)
697
- return goalResult;
698
- await sessionRecorder.flush().catch(showPersistenceWarning);
699
- await llmLogRef.current?.writer?.flush().catch(showPersistenceWarning);
700
- // Turn boundary: an aborted or forcibly-settled attempt is quarantined
701
- // before it can emit the finalizing update, so settle anything still in
702
- // the live tail now; the streamed text is preserved verbatim in <Static>.
703
- drainLiveMessages();
704
- // Only a genuinely paused goal (supervisor already attempted automatic
705
- // continuation) exposes the one-key resume affordance; it stays until the
706
- // user submits something else.
707
- if (goalResult.resume?.kind === 'model-stream-idle')
708
- setPausedResume({ kind: 'model-stream-idle', request: goalResult.resume.request, retryAttempt: goalResult.resume.retryAttempt });
709
- else if (goalResult.resume?.kind === 'incomplete-goal')
710
- setPausedResume({ kind: 'incomplete-goal', request: goalResult.resume.checkpoint.request, retryAttempt: 0, checkpoint: goalResult.resume.checkpoint, pauseReason: goalResult.stopReason === 'context-exhausted' || goalResult.stopReason === 'goal-deadline' || goalResult.stopReason === 'no-progress' ? goalResult.stopReason : undefined });
711
- else
712
- setPausedResume(undefined);
713
- return goalResult;
714
- }
715
- const visible = messages.filter(message => !message.hidden);
716
- const activeLiveMessages = liveMessages.filter(message => !message.hidden);
717
- // Recomputed each busy heartbeat (1 Hz) alongside the elapsed label; the
718
- // streaming-rate estimate rides the already-live message text, so no extra
719
- // timer or token bookkeeping is introduced.
720
- const busyDetail = busy ? busyDetailLabel({ messages: activeLiveMessages, fleet }) : undefined;
721
- const { staticItems: staticTranscriptItems, streamingItems } = partitionDisplayMessages([...visible, ...activeLiveMessages]);
722
- const activeSelection = activeModel(settings);
723
- const placeholder = placeholderForMode(mode, busy);
724
- const selectedModel = currentModelSelection();
725
- const activeModelName = selectedModel ? `${selectedModel.provider}:${selectedModel.model}${activeSelection ? '' : ' (unavailable)'}` : 'unconfigured';
726
- const activeSelector = activeSelection ? `${activeSelection.provider.name}:${activeSelection.model}` : undefined;
727
- // Synchronize session identity before rendering either the status or picker;
728
- // a new/resumed/forked session must not display the previous session's map.
729
- const sessionReasoning = currentPromptSession().reasoningByModel;
730
- const effectiveReasoning = activeSelector
731
- ? resolveReasoningChoice(sessionReasoning?.[activeSelector], isStoredReasoning(settings.reasoning) ? settings.reasoning : undefined)
732
- : undefined;
733
- // When a session override changes, the suffix below must re-render: bump a
734
- // cheap counter from setSessionReasoning instead of threading per-turn state.
735
- void reasoningOverrideCounter;
736
- const reasoningSuffix = effectiveReasoning
737
- ? effectiveReasoning.level === undefined
738
- ? ' (no reasoning parameter)'
739
- : activeSelection && resolveProviderReasoning(activeSelection.provider, activeSelection.model, effectiveReasoning.level).effective === 'disabled'
740
- ? ' (provider default)'
741
- : ` (${effectiveReasoning.level})`
742
- : '';
743
- const headerSubtitle = (_jsxs(Text, { children: ['A minimal coding agent for your terminal.\n\nStart with chat. Turn repeated work into Markdown skills:\n', _jsx(Text, { color: theme.command, children: "/skills" }), ' — create, enable, disable, validate, or remove skills.\n\nType ', _jsx(Text, { color: theme.command, children: "@" }), ' to browse workspace files. To grant read-only access to a file or directory outside the workspace for this turn, mention a path containing ', _jsx(Text, { color: theme.command, children: "/" }), ' (for example, ', _jsx(Text, { color: theme.command, children: "@../shared/file.ts" }), ' or ', _jsx(Text, { color: theme.command, children: "/tmp/reference.md" }), ').\n\nImage mentions require a vision-capable model. File edits and writes stay inside the workspace.\n\nhaze runs tool calls without confirmation gates. Supervise consequential work as you would any shell session.\n\nShape haze around your workflow as you go.\n\nUse ', _jsx(Text, { color: theme.command, children: "/help" }), ' for commands.'] }));
744
- const workspaceLabel = `${compactHomePath(process.cwd())}${branchName ? ` (${branchName})` : ''}`;
745
- const enabledSkillCount = new Set(skills.filter(skill => isSkillEnabled(settings, skill.name, skill.source)).map(skill => skill.name)).size;
746
- const metrics = statusBarMetrics({ messages: [...messages, ...liveMessages], tokenUsage, enabledSkillCount, backgroundProcessCount: backgroundCount });
747
- const inputSuggestions = inputSuggestionsForState({ mode, settings, skills, sessions, selectedProviderName, modelProviderFilter, providerDraftName: providerDraft.name, discoveredModels, suggestedModels, selectedSkillName, selectedLspName, selectedMcpName, plugins, selectedPluginName, pluginCollectionEntries, sessionReasoning });
748
- const staticItems = [
749
- { kind: 'header', key: 'header', subtitle: headerSubtitle },
750
- ...staticTranscriptItems,
751
- ];
752
- const horizontalPadding = width >= 12 ? 1 : 0;
753
- const contentWidth = Math.max(1, width - horizontalPadding * 2);
754
- return _jsxs(Box, { flexDirection: "column", paddingX: horizontalPadding, children: [_jsx(Static, { items: staticItems, children: item => item.kind === 'header'
755
- ? _jsx(Header, { subtitle: item.subtitle, version: version }, item.key)
756
- : item.kind === 'assistant-markdown'
757
- ? _jsx(AssistantMarkdownChunkView, { message: item.message, content: item.content, width: contentWidth, first: item.first, final: item.final }, item.key)
758
- : _jsx(MessageView, { message: item.message, width: contentWidth }, item.key) }, width), _jsx(DynamicFrame, { rows: terminalRows, columns: contentWidth, sections: {
759
- live: streamingItems.length > 0 ? rows => {
760
- // Allocate the sum, not a positive minimum for every pending item.
761
- const displayed = streamingItems.slice(0, Math.floor(rows / 2));
762
- const itemRows = displayed.length > 0 ? Math.floor(rows / displayed.length) : 0;
763
- return displayed.map(item => _jsx(Box, { maxHeight: itemRows, flexShrink: 0, overflow: "hidden", children: _jsx(MessageView, { message: item.message, width: contentWidth, showHeader: item.showHeader, maxVisibleLines: itemRows - 1 }) }, item.key));
764
- } : undefined,
765
- debug: debug ? _jsxs(_Fragment, { children: [debugLogs.map((line, index) => _jsxs(Text, { color: theme.muted, wrap: "truncate-end", children: ["\u2022 ", line] }, index)), metrics.hasTokenBreakdown && _jsxs(Text, { color: theme.muted, wrap: "truncate-end", children: ["Tokens: in=", formatTokenCount(metrics.effectiveInput), " out=", formatTokenCount(metrics.effectiveOutput), " logical=", formatTokenCount(tokenUsage.logicalInputEstimate)] }), renderMetricsReader && (() => {
766
- const renderMetrics = renderMetricsReader();
767
- if (!renderMetrics)
768
- return null;
769
- const age = Date.now() - renderMetrics.at;
770
- // Skip the reading once it is clearly stale; it refreshes on the
771
- // next frame while anything animated keeps the debug panel alive.
772
- return age < 5_000 ? _jsxs(Text, { color: theme.muted, wrap: "truncate-end", children: ["Ink render: ", renderMetrics.renderTime.toFixed(1), "ms"] }) : null;
773
- })()] }) : undefined,
774
- queue: followUps.queued.length > 0 ? _jsxs(_Fragment, { children: [_jsxs(Text, { color: theme.muted, wrap: "truncate-end", children: ["Queued follow-ups: ", followUps.queued.length] }), followUps.queued.map((item, index) => _jsxs(Text, { color: theme.muted, wrap: "truncate-end", children: [index + 1, ". ", item] }, `${index}-${item}`))] }) : undefined,
775
- tasks: visibleTasks.length > 0 ? _jsx(TaskBar, { tasks: visibleTasks, width: contentWidth, expanded: tasksExpanded, padding: taskBarPadding, maxRows: Math.max(1, terminalRows - 8) }) : undefined,
776
- activity: busy ? _jsx(BusyBar, { label: busyLabel, elapsed: busyElapsed, detail: busyDetail, tip: showingTip ? TIPS[tipIndex] : undefined })
777
- : pausedResume ? _jsxs(StatusNotice, { variant: "warning", children: ["Press R to resume \u00B7 unfinished goal paused", pausedResume.pauseReason ? ` (${pausedResume.pauseReason})` : ''] }) : undefined,
778
- status: _jsxs(_Fragment, { children: [_jsxs(Box, { width: "100%", flexDirection: "row", justifyContent: "space-between", flexShrink: 0, children: [_jsx(Text, { color: theme.muted, wrap: "truncate-end", children: workspaceLabel }), _jsxs(Text, { color: theme.muted, wrap: "truncate-start", children: [activeModelName, reasoningSuffix] })] }), _jsx(Text, { color: theme.muted, wrap: "truncate-end", children: metrics.statusDetailLabel })] }),
779
- }, input: ({ width: inputWidth, inputRows, suggestionRows, onRowsChange }) => _jsx(TextInput, { placeholder: placeholder, disabled: busy && mode !== 'chat', mask: MASKED_MODES.has(mode), historyItems: inputHistory, recordHistory: mode === 'chat', suggestions: inputSuggestions, suggestionMode: PICKER_MODES.has(mode) ? 'always' : 'slash', submitOnEmpty: SUBMIT_EMPTY_MODES.has(mode), width: inputWidth, inputRows: inputRows, suggestionRows: suggestionRows, onRowsChange: onRowsChange, getMentionSuggestions: fileMentionSuggestions, onHistoryAdd: persistInputHistory, onToggleTasks: () => {
780
- if (!tasksExpanded) {
781
- setTaskBarPadding(0);
782
- setTasksExpanded(true);
783
- }
784
- else {
785
- const expandedRows = visibleTasks.length + 1;
786
- const collapsedRows = Math.min(visibleTasks.length, MAX_VISIBLE_TASKS) + 1;
787
- setTaskBarPadding(Math.max(0, expandedRows - collapsedRows));
788
- setTasksExpanded(false);
789
- }
790
- }, onCancel: cancelThinking, onResumeKey: pausedResume != null && !busy ? resumePausedTask : undefined, onInterrupt: () => { void shutdown(); }, onEscape: () => {
791
- if (busy)
792
- cancelThinking();
793
- else
794
- closeInputList();
795
- }, onSubmit: submit }) })] });
796
- }
9
+ import { clearRenderMetricsReader, setRenderMetricsReader } from '../chat/renderMetrics.js';
10
+ import { ChatScreen } from '../chat/ChatScreen.js';
797
11
  export async function chatCommand(options = {}) {
798
12
  // Resolve the theme before any Ink output so every component renders with it.
799
13
  // Settings failures must not block startup (the in-app banner already reports
@@ -809,7 +23,7 @@ export async function chatCommand(options = {}) {
809
23
  // Sampled by the --debug onRender hook; read by ChatScreen's debug panel via
810
24
  // a getter so the metric never enters React state (no extra re-renders).
811
25
  let lastRenderMetricsMs;
812
- renderMetricsReader = () => lastRenderMetricsMs;
26
+ setRenderMetricsReader(() => lastRenderMetricsMs);
813
27
  // Clear on width changes ahead of Ink's repaint; ChatScreen then replays
814
28
  // its width-keyed Static transcript instead of leaving a blank viewport.
815
29
  const removeResizeGuard = installViewportResizeGuard();
@@ -835,6 +49,7 @@ export async function chatCommand(options = {}) {
835
49
  shutdown: () => shutdown?.(),
836
50
  restore: () => {
837
51
  removeResizeGuard();
52
+ clearRenderMetricsReader();
838
53
  resetTerminalColors();
839
54
  },
840
55
  });