@denizokcu/haze 1.4.0 → 1.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (134) hide show
  1. package/CHANGELOG.md +48 -1
  2. package/README.md +28 -12
  3. package/SECURITY.md +1 -1
  4. package/dist/buildInfo.json +3 -3
  5. package/dist/cli/chat/BusyBar.d.ts +7 -0
  6. package/dist/cli/chat/BusyBar.js +8 -0
  7. package/dist/cli/chat/DynamicFrame.d.ts +37 -0
  8. package/dist/cli/chat/DynamicFrame.js +48 -0
  9. package/dist/cli/chat/busyIndicator.d.ts +3 -1
  10. package/dist/cli/chat/busyIndicator.js +11 -9
  11. package/dist/cli/chat/chatMetrics.d.ts +1 -1
  12. package/dist/cli/chat/chatMetrics.js +3 -3
  13. package/dist/cli/chat/inputSuggestions.js +2 -1
  14. package/dist/cli/chat/liveRegion.js +1 -1
  15. package/dist/cli/chat/messages.js +27 -16
  16. package/dist/cli/chat/resizeGuard.d.ts +20 -0
  17. package/dist/cli/chat/resizeGuard.js +25 -0
  18. package/dist/cli/chat/sessionLifecycle.d.ts +3 -1
  19. package/dist/cli/chat/sessionLifecycle.js +13 -2
  20. package/dist/cli/chat/sessionRecorder.d.ts +2 -1
  21. package/dist/cli/chat/sessionRecorder.js +8 -0
  22. package/dist/cli/chat/shutdown.d.ts +27 -0
  23. package/dist/cli/chat/shutdown.js +79 -0
  24. package/dist/cli/chat/terminalControl.d.ts +45 -0
  25. package/dist/cli/chat/terminalControl.js +107 -0
  26. package/dist/cli/chat/tips.js +1 -0
  27. package/dist/cli/chat/userInput.d.ts +43 -0
  28. package/dist/cli/chat/userInput.js +63 -0
  29. package/dist/cli/chat/wizard/sessionThemeHandlers.js +14 -6
  30. package/dist/cli/chat/wizard/types.d.ts +8 -1
  31. package/dist/cli/chat/wizardDispatch.js +1 -1
  32. package/dist/cli/commands/chat.js +258 -172
  33. package/dist/cli/commands/commandHelp.js +6 -2
  34. package/dist/cli/commands/commands.d.ts +8 -0
  35. package/dist/cli/commands/commands.js +11 -0
  36. package/dist/cli/commands/formatters.d.ts +1 -1
  37. package/dist/cli/commands/formatters.js +20 -2
  38. package/dist/cli/commands/logsCommand.js +21 -2
  39. package/dist/cli/commands/reasoningCommand.d.ts +23 -14
  40. package/dist/cli/commands/reasoningCommand.js +53 -20
  41. package/dist/cli/commands/runCommand.js +19 -11
  42. package/dist/cli/commands/streaming/attemptOutcome.d.ts +2 -0
  43. package/dist/cli/commands/streaming/attemptOutcome.js +11 -6
  44. package/dist/cli/commands/streaming/attemptSetup.d.ts +1 -0
  45. package/dist/cli/commands/streaming/attemptSetup.js +11 -5
  46. package/dist/cli/commands/streaming/goalCheckpoint.d.ts +8 -1
  47. package/dist/cli/commands/streaming/goalCheckpoint.js +3 -2
  48. package/dist/cli/commands/streaming/goalSupervisor.d.ts +4 -0
  49. package/dist/cli/commands/streaming/goalSupervisor.js +43 -7
  50. package/dist/cli/commands/streaming/prepareStep.js +7 -3
  51. package/dist/cli/commands/streaming/streamLoop.d.ts +5 -0
  52. package/dist/cli/commands/streaming/streamLoop.js +3 -0
  53. package/dist/cli/commands/streaming/toolPartHandlers.js +6 -0
  54. package/dist/cli/commands/streaming.d.ts +1 -1
  55. package/dist/cli/commands/streaming.js +23 -17
  56. package/dist/cli/commands/wizardFlow.d.ts +5 -2
  57. package/dist/cli/commands/wizardFlow.js +17 -10
  58. package/dist/cli/index.js +17 -1
  59. package/dist/config/contextFiles.d.ts +9 -0
  60. package/dist/config/contextFiles.js +21 -1
  61. package/dist/config/modelCatalog.d.ts +3 -0
  62. package/dist/config/modelCatalog.js +29 -0
  63. package/dist/config/providerPresets.d.ts +1 -1
  64. package/dist/config/providerPresets.js +42 -3
  65. package/dist/config/settings.d.ts +11 -4
  66. package/dist/config/settings.js +9 -0
  67. package/dist/core/agent/budgets.d.ts +13 -15
  68. package/dist/core/agent/budgets.js +15 -17
  69. package/dist/core/agent/completionController.d.ts +6 -2
  70. package/dist/core/agent/completionController.js +16 -3
  71. package/dist/core/agent/goalPolicy.d.ts +10 -0
  72. package/dist/core/agent/goalPolicy.js +44 -6
  73. package/dist/core/agent/projectPreflight.d.ts +2 -0
  74. package/dist/core/agent/projectPreflight.js +56 -0
  75. package/dist/core/agent/reasoningPolicy.d.ts +34 -4
  76. package/dist/core/agent/reasoningPolicy.js +27 -4
  77. package/dist/core/agent/workState.d.ts +8 -0
  78. package/dist/core/agent/workState.js +191 -8
  79. package/dist/core/providerContracts.d.ts +32 -0
  80. package/dist/core/providerContracts.js +1 -0
  81. package/dist/core/session/sessionReport.d.ts +33 -0
  82. package/dist/core/session/sessionReport.js +121 -0
  83. package/dist/core/session/sessionSlimming.js +9 -3
  84. package/dist/core/session/sessionStore.d.ts +12 -0
  85. package/dist/core/session/sessionStore.js +20 -4
  86. package/dist/core/subagent/contracts.d.ts +3 -25
  87. package/dist/core/subagent/executionProfiles.js +4 -4
  88. package/dist/core/validation/outputParser.d.ts +6 -1
  89. package/dist/core/validation/outputParser.js +6 -2
  90. package/dist/llm/client.d.ts +4 -2
  91. package/dist/llm/client.js +44 -16
  92. package/dist/llm/hazeTools.d.ts +8553 -8550
  93. package/dist/llm/hazeTools.js +6 -503
  94. package/dist/llm/lspTools.d.ts +120 -120
  95. package/dist/llm/mcp.js +3 -0
  96. package/dist/llm/requestContext.d.ts +1 -1
  97. package/dist/llm/requestContext.js +1 -1
  98. package/dist/{core/subagent → llm}/subagentRunner.d.ts +9 -9
  99. package/dist/{core/subagent → llm}/subagentRunner.js +22 -25
  100. package/dist/llm/systemPrompt.d.ts +11 -1
  101. package/dist/llm/systemPrompt.js +2 -11
  102. package/dist/llm/tools/fetchTool.d.ts +30 -30
  103. package/dist/llm/tools/fileTools.d.ts +7768 -0
  104. package/dist/llm/tools/fileTools.js +510 -0
  105. package/dist/llm/tools/processTool.d.ts +30 -30
  106. package/dist/llm/tools/shellTool.d.ts +30 -30
  107. package/dist/llm/tools/shellTool.js +8 -4
  108. package/dist/llm/tools/toolContext.d.ts +3 -32
  109. package/dist/llm/tools/toolContext.js +33 -52
  110. package/dist/llm/tools/toolContextState.d.ts +40 -0
  111. package/dist/llm/tools/toolContextState.js +34 -0
  112. package/dist/llm/workerContext.d.ts +7 -0
  113. package/dist/llm/workerContext.js +18 -1
  114. package/dist/skills/SkillLoader.js +3 -3
  115. package/dist/skills/SkillRegistry.js +3 -3
  116. package/dist/skills/builder/SkillBuilder.js +3 -3
  117. package/dist/skills/confinement.d.ts +7 -0
  118. package/dist/skills/confinement.js +15 -0
  119. package/dist/ui/codeHighlight.js +4 -4
  120. package/dist/ui/components/MarkdownText.js +7 -8
  121. package/dist/ui/components/NativeIndicators.d.ts +15 -0
  122. package/dist/ui/components/NativeIndicators.js +32 -0
  123. package/dist/ui/components/StreamingMarkdownText.d.ts +9 -0
  124. package/dist/ui/components/StreamingMarkdownText.js +38 -0
  125. package/dist/ui/components/TextInput.d.ts +7 -2
  126. package/dist/ui/components/TextInput.js +103 -46
  127. package/dist/ui/components/WizardChoices.d.ts +18 -0
  128. package/dist/ui/components/WizardChoices.js +32 -0
  129. package/dist/ui/inputBuffer.js +12 -6
  130. package/dist/ui/textGeometry.d.ts +14 -0
  131. package/dist/ui/textGeometry.js +31 -0
  132. package/package.json +14 -13
  133. /package/dist/cli/{contextReport.d.ts → contextReportCli.d.ts} +0 -0
  134. /package/dist/cli/{contextReport.js → contextReportCli.js} +0 -0
@@ -1,12 +1,13 @@
1
- import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
1
+ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
2
2
  import { useEffect, useReducer, useRef, useState } from 'react';
3
3
  import { Box, render, Static, Text, useApp, useWindowSize } from 'ink';
4
- import Spinner from 'ink-spinner';
4
+ import { StatusNotice } from '../../ui/components/NativeIndicators.js';
5
+ import { BusyBar } from '../chat/BusyBar.js';
5
6
  import { readContextFiles } from '../../config/contextFiles.js';
6
7
  import { addInputHistoryItem, readInputHistory } from '../../config/inputHistory.js';
7
8
  import { loadTasks as loadTasksFromStore, clearTasks as clearTasksFromStore } from '../../core/tasks/taskStorage.js';
8
9
  import { readSettings, updateSettings } from '../../config/settings.js';
9
- import { activeModel, activeProvider } from '../../config/providers.js';
10
+ import { activeModel } from '../../config/providers.js';
10
11
  import { isSkillEnabled } from '../../config/skillSettings.js';
11
12
  import { Header } from '../../ui/components/Header.js';
12
13
  import { TextInput } from '../../ui/components/TextInput.js';
@@ -15,13 +16,14 @@ import { applyTerminalColors, resetTerminalColors } from '../../ui/terminalColor
15
16
  import { handleSlashCommand } from './commands.js';
16
17
  import { runAgentGoal } from './streaming/goalSupervisor.js';
17
18
  import { checkpointFromGoalFrontier } from './streaming/goalCheckpoint.js';
18
- import { imageAttachmentLine } from './formatters.js';
19
- import { imageCapabilityError, IMAGE_ONLY_PROMPT_TEXT, resolveImageAttachments } from '../../core/attachments/imageAttachments.js';
20
- import { resolveReadBlessings } from '../../core/attachments/readBlessings.js';
21
19
  import { endLog as endLlmLog } from '../../core/log/llmLog.js';
22
20
  import { loadSkillRegistry } from '../../skills/SkillRegistry.js';
23
21
  import { formatSession, listSessions } from '../../core/session/sessionStore.js';
24
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';
25
+ import { installViewportResizeGuard } from '../chat/resizeGuard.js';
26
+ import { createQuarantinableCallbacks } from './streaming/attemptLifecycle.js';
25
27
  import { AssistantMarkdownChunkView, MessageView } from '../chat/messages.js';
26
28
  import { partitionDisplayMessages } from '../chat/transcriptPartition.js';
27
29
  import { useLiveMessages } from '../chat/liveMessages.js';
@@ -35,31 +37,29 @@ import { compactHomePath, statusBarMetrics } from '../chat/chatMetrics.js';
35
37
  import { formatTokenCount } from '../../utils/format.js';
36
38
  import { accumulateTokenUsage, EMPTY_TOKEN_USAGE, shouldClearCompletedTasks } from '../chat/turnState.js';
37
39
  import { MASKED_MODES, PICKER_MODES, SUBMIT_EMPTY_MODES, placeholderForMode } from './chatModes.js';
38
- import { DEFAULT_REASONING_LEVEL, isReasoningLevel } from '../../core/agent/reasoningPolicy.js';
40
+ import { contextFileSignatureMap, isPausedGoalRecoveryCommand, mergeSettingsSelection, prepareUserInput as prepareUserInputPolicy, resumeKindFor } from '../chat/userInput.js';
41
+ import { isStoredReasoning, resolveReasoningChoice } from '../../core/agent/reasoningPolicy.js';
39
42
  import { inputSuggestionsForState } from '../chat/inputSuggestions.js';
40
43
  import { currentBranchName, runStartupSequence } from '../chat/startupSequence.js';
41
44
  import { useFollowUpQueue } from '../chat/followUpQueue.js';
42
45
  import { useBusyIndicator } from '../chat/busyIndicator.js';
46
+ import { useTerminalControl } from '../chat/terminalControl.js';
43
47
  import { modelThinkingLabel } from '../../utils/modelName.js';
44
48
  import { commandParts } from './wizardFlow.js';
45
49
  import { backgroundProcessCount, subscribeBackgroundProcesses, teardownBackgroundProcesses } from '../../core/process/backgroundRegistry.js';
46
50
  import { MAX_SESSION_PICKER_RESULTS } from './sessionPicker.js';
51
+ /** Latest Ink render metrics under --debug (module-level: render options are outside React). */
52
+ let renderMetricsReader;
47
53
  function thinkingLabelForSettings(settings) {
48
54
  return modelThinkingLabel(activeModel(settings)?.model);
49
55
  }
50
- /**
51
- * Busy indicator isolated in its own component. The Spinner animates on its own
52
- * internal state (~10 fps) which triggers re-renders inside this subtree; keeping
53
- * the spinner out of ChatScreen's render scope means those ticks don't propagate
54
- * to the transcript tree above (where React.memo on MessageView already prevents
55
- * deep re-renders, but avoiding the reconciliation walk entirely is still cheaper).
56
- */
57
- function BusyBar({ label, elapsed, tip }) {
58
- return _jsxs(Box, { flexDirection: "column", flexShrink: 0, children: [_jsx(Box, { children: _jsxs(Text, { children: [_jsxs(Text, { color: theme.command, bold: true, children: [_jsx(Spinner, { type: "dots" }), " ", label, elapsed ? _jsxs(Text, { color: theme.muted, children: [" \u00B7 ", elapsed] }) : null] }), _jsx(Text, { color: theme.muted, children: " \u00B7 type to queue follow-up \u00B7 esc to interrupt" })] }) }), tip && (_jsx(Box, { children: _jsxs(Text, { color: theme.muted, children: [_jsx(Text, { bold: true, children: "Tip:" }), " ", tip] }) }))] });
59
- }
60
- function ChatScreen({ debug = false, version, build, continueSession = false, resumeSessionId, noSession = false }) {
56
+ function ChatScreen({ debug = false, version, build, continueSession = false, resumeSessionId, noSession = false, onShutdownReady }) {
61
57
  const { exit } = useApp();
62
58
  const { columns: width, rows: terminalRows } = useWindowSize();
59
+ const stoppingRef = useRef(false);
60
+ const sealedRef = useRef(false);
61
+ const activeGoalRef = useRef(undefined);
62
+ const quarantineRef = useRef(undefined);
63
63
  const nextDisplayOrderRef = useRef(1);
64
64
  const withDisplayOrder = (message) => {
65
65
  if (message.displayOrder != null)
@@ -69,9 +69,30 @@ function ChatScreen({ debug = false, version, build, continueSession = false, re
69
69
  const withDisplayOrders = (next) => next.map(withDisplayOrder);
70
70
  const [messages, setMessagesRaw] = useState([]);
71
71
  const setMessages = (updater) => {
72
+ if (stoppingRef.current)
73
+ return;
72
74
  setMessagesRaw(previous => withDisplayOrders(typeof updater === 'function' ? updater(previous) : updater));
73
75
  };
74
- const [settings, setSettings] = useState({});
76
+ const [settings, setSettingsRaw] = useState({});
77
+ const settingsRef = useRef({});
78
+ const defaultSelectionRef = useRef({});
79
+ function setSettings(next, patch) {
80
+ // The ref records the global default from `next` (what updateSettings
81
+ // returned) before the patch merge; unrelated settings writes must not
82
+ // replace a resumed session's model (merge policy in chat/userInput.ts).
83
+ defaultSelectionRef.current = { provider: next.provider, model: next.model };
84
+ settingsRef.current = patch ? mergeSettingsSelection(next, settingsRef.current, patch) : next;
85
+ setSettingsRaw(settingsRef.current);
86
+ if (patch && ('provider' in patch || 'model' in patch)) {
87
+ const selected = currentModelSelection();
88
+ if (selected)
89
+ sessionRecorderRef.current?.recordModelSelection(selected);
90
+ }
91
+ }
92
+ function currentModelSelection() {
93
+ const { provider, model } = settingsRef.current;
94
+ return provider && model ? { provider, model } : undefined;
95
+ }
75
96
  const [settingsError, setSettingsError] = useState();
76
97
  const conversationRef = useRef([]);
77
98
  const lastAssistantTextRef = useRef('');
@@ -82,7 +103,7 @@ function ChatScreen({ debug = false, version, build, continueSession = false, re
82
103
  sessionRecorderRef.current = createSessionRecorder(() => sessionRef.current);
83
104
  /** Finalize a formerly-live message into the append-only transcript and session record. */
84
105
  function finalizeMessage(message) {
85
- if (message.hidden)
106
+ if (message.hidden || sealedRef.current)
86
107
  return;
87
108
  const ordered = withDisplayOrder(message);
88
109
  setMessages(m => [...m, ordered]);
@@ -97,6 +118,9 @@ function ChatScreen({ debug = false, version, build, continueSession = false, re
97
118
  // detected by sessionStartRef identity (the lifecycle controller replaces
98
119
  // the Date on new/resume/continue).
99
120
  const promptSessionRef = useRef({ identity: undefined, value: { cwd: process.cwd() } });
121
+ // Session per-model reasoning overrides live on the stable PromptSession
122
+ // object; this counter only forces a re-render so the status bar updates.
123
+ const [reasoningOverrideCounter, setReasoningOverrideCounter] = useState(0);
100
124
  const workStateRef = useRef(undefined);
101
125
  const llmLogRef = useRef(undefined);
102
126
  const persistenceWarningShownRef = useRef(false);
@@ -113,6 +137,7 @@ function ChatScreen({ debug = false, version, build, continueSession = false, re
113
137
  // the developer always sees rolling activity (elapsed turn time) even when
114
138
  // the model is thinking with no streamed output and no tool is running.
115
139
  const { busy, setBusy: setBusyWithHeartbeat, elapsed: busyElapsed } = useBusyIndicator();
140
+ const terminalControl = useTerminalControl();
116
141
  const [backgroundCount, setBackgroundCount] = useState(backgroundProcessCount);
117
142
  const [busyLabel, setBusyLabel] = useState(() => thinkingLabelForSettings(settings));
118
143
  const [visibleTasks, setVisibleTasks] = useState([]);
@@ -126,6 +151,34 @@ function ChatScreen({ debug = false, version, build, continueSession = false, re
126
151
  const [pausedResume, setPausedResume] = useState(undefined);
127
152
  const [skills, setSkills] = useState([]);
128
153
  const [branchName, setBranchName] = useState();
154
+ const shutdownRef = useRef(undefined);
155
+ if (!shutdownRef.current)
156
+ shutdownRef.current = createChatShutdown({
157
+ stop: () => { stoppingRef.current = true; followUps.clear(); },
158
+ abort: () => abortControllerRef.current?.abort('Chat is exiting.'),
159
+ settle: () => activeGoalRef.current,
160
+ seal: () => {
161
+ drainLiveMessages();
162
+ sealedRef.current = true;
163
+ quarantineRef.current?.();
164
+ },
165
+ flush: () => sessionRecorderRef.current?.flush(),
166
+ endLog: () => {
167
+ const log = llmLogRef.current;
168
+ llmLogRef.current = undefined;
169
+ return log ? endLlmLog(log) : undefined;
170
+ },
171
+ cleanup: async () => {
172
+ await Promise.all([teardownBackgroundProcesses(), clearTasksFromStore()]);
173
+ },
174
+ exit,
175
+ report: message => process.stderr.write(`[haze] ${message}\n`),
176
+ });
177
+ const shutdown = shutdownRef.current;
178
+ useEffect(() => {
179
+ onShutdownReady?.(shutdown);
180
+ return () => { void shutdown(); };
181
+ }, [onShutdownReady, shutdown]);
129
182
  // Wizard flow state (selection, drafts, model discovery) in one reducer;
130
183
  // this replaced twelve individual useState hooks.
131
184
  const [wizardState, updateWizard] = useReducer(wizardUiReducer, undefined, initialWizardUiState);
@@ -160,7 +213,7 @@ function ChatScreen({ debug = false, version, build, continueSession = false, re
160
213
  const settingsThemeLoadedRef = useRef(false);
161
214
  const activeThemeName = settings.theme ?? DEFAULT_THEME_NAME;
162
215
  useEffect(() => {
163
- if (!settingsThemeLoadedRef.current)
216
+ if (!settingsThemeLoadedRef.current || stoppingRef.current)
164
217
  return;
165
218
  try {
166
219
  setActiveTheme(resolveTheme(activeThemeName));
@@ -179,7 +232,7 @@ function ChatScreen({ debug = false, version, build, continueSession = false, re
179
232
  setSettingsError(settingsError);
180
233
  setBranchName(branch);
181
234
  setContextFiles(files);
182
- contextFileSignaturesRef.current = new Map(files.flatMap(file => file.signature ? [[file.path, file.signature]] : []));
235
+ contextFileSignaturesRef.current = contextFileSignatureMap(files);
183
236
  },
184
237
  initializeSession: () => sessionLifecycle.initializeSession(),
185
238
  refreshSkills,
@@ -224,7 +277,7 @@ function ChatScreen({ debug = false, version, build, continueSession = false, re
224
277
  return skill ? { skill, args: args.join(' ') } : undefined;
225
278
  }
226
279
  function debugLog(line) {
227
- if (!debug)
280
+ if (!debug || stoppingRef.current)
228
281
  return;
229
282
  setDebugLogs(current => [...current.slice(-7), line]);
230
283
  }
@@ -245,6 +298,11 @@ function ChatScreen({ debug = false, version, build, continueSession = false, re
245
298
  noSession,
246
299
  debug,
247
300
  contextFiles: () => contextFiles,
301
+ modelSelection: currentModelSelection,
302
+ onModelSelection: selection => {
303
+ settingsRef.current = { ...settingsRef.current, ...(selection ?? defaultSelectionRef.current) };
304
+ setSettingsRaw(settingsRef.current);
305
+ },
248
306
  sessionRef,
249
307
  sessionRecorder: () => sessionRecorderRef.current,
250
308
  sessionStartRef,
@@ -301,6 +359,19 @@ function ChatScreen({ debug = false, version, build, continueSession = false, re
301
359
  if (message)
302
360
  setMessages(m => [...m, { role: 'system', text: message }]);
303
361
  }
362
+ // Session per-model reasoning overrides live on the stable PromptSession
363
+ // object; the counter only forces a re-render so the status bar updates.
364
+ function setSessionReasoningOverride(modelSelector, setting) {
365
+ const session = currentPromptSession();
366
+ if (setting === undefined) {
367
+ if (session.reasoningByModel)
368
+ delete session.reasoningByModel[modelSelector];
369
+ }
370
+ else {
371
+ session.reasoningByModel = { ...session.reasoningByModel, [modelSelector]: setting };
372
+ }
373
+ setReasoningOverrideCounter(count => count + 1);
374
+ }
304
375
  // Wizard/picker submit dispatch lives in one table-driven module with a
305
376
  // shared settings-patch applier (CR-006). Rebuilt every render so handlers
306
377
  // see current state without new React state.
@@ -313,12 +384,21 @@ function ChatScreen({ debug = false, version, build, continueSession = false, re
313
384
  forkSessionById: sessionLifecycle.forkSessionById,
314
385
  setBusyLabel, setBusy: setBusyWithHeartbeat,
315
386
  idleBusyLabel: thinkingLabelForSettings(settings),
387
+ sessionReasoning: {
388
+ modelSelector: () => { const selection = activeModel(settings); return selection ? `${selection.provider.name}:${selection.model}` : undefined; },
389
+ get: modelSelector => currentPromptSession().reasoningByModel?.[modelSelector],
390
+ set: setSessionReasoningOverride,
391
+ },
316
392
  });
317
393
  async function submit(value) {
394
+ if (stoppingRef.current)
395
+ return;
396
+ if (mode === 'chat' && /^\/(?:exit|quit)\s*$/i.test(value))
397
+ return shutdown();
318
398
  if (settingsError) {
319
399
  try {
320
400
  const repaired = await readSettings();
321
- setSettings(repaired);
401
+ setSettings(repaired, {});
322
402
  setSettingsError(undefined);
323
403
  }
324
404
  catch (error) {
@@ -339,7 +419,7 @@ function ChatScreen({ debug = false, version, build, continueSession = false, re
339
419
  // recovery/configuration commands (compact, model, provider, settings,
340
420
  // resume…) intentionally keep it — the pause notice tells the user to run
341
421
  // exactly those and then press R (SU-04).
342
- const isRecoveryCommand = mode !== 'chat' || /^(?:\/compact|\/model|\/provider|\/settings|\/themes|\/resume|\/sessions)\b/.test(value.trim());
422
+ const isRecoveryCommand = isPausedGoalRecoveryCommand(mode, value);
343
423
  if (pausedResume && !isRecoveryCommand)
344
424
  setPausedResume(undefined);
345
425
  if (await wizard.dispatch(mode, value))
@@ -374,17 +454,26 @@ function ChatScreen({ debug = false, version, build, continueSession = false, re
374
454
  compactConversation,
375
455
  compactConversationLlm: compactConversationWithModel,
376
456
  runAgentTurn: (prompt, displayValue, options) => doAgentTurn(prompt, displayValue, options),
457
+ composeInEditor: async () => {
458
+ const text = await terminalControl.composeInEditor();
459
+ if (text === undefined)
460
+ setMessages(m => [...m, { role: 'system', text: '/editor needs $EDITOR (or $VISUAL) set to an editor command.' }]);
461
+ return text;
462
+ },
463
+ viewInPager: terminalControl.viewInPager,
377
464
  refreshContextFiles: async () => {
378
465
  const files = await readContextFiles().catch(() => contextFiles);
379
466
  setContextFiles(files);
380
- contextFileSignaturesRef.current = new Map(files.flatMap(file => file.signature ? [[file.path, file.signature]] : []));
467
+ contextFileSignaturesRef.current = contextFileSignatureMap(files);
381
468
  return files;
382
469
  },
383
470
  updateSettings: async (patch) => {
384
471
  const next = await updateSettings(patch);
385
- setSettings(next);
386
- return next;
472
+ setSettings(next, patch);
473
+ return settingsRef.current;
387
474
  },
475
+ getSessionReasoning: modelSelector => currentPromptSession().reasoningByModel?.[modelSelector],
476
+ setSessionReasoning: setSessionReasoningOverride,
388
477
  getContextReport: () => buildContextReport({ sessionStart: sessionStartRef.current, contextFiles, conversation: conversationRef.current }),
389
478
  };
390
479
  let result;
@@ -396,13 +485,8 @@ function ChatScreen({ debug = false, version, build, continueSession = false, re
396
485
  setMessages(m => [...m, { role: 'system', text: `Command failed: ${text}` }]);
397
486
  return;
398
487
  }
399
- if (result === 'exit') {
400
- await teardownBackgroundProcesses().catch(showPersistenceWarning);
401
- await sessionRecorderRef.current?.flush().catch(showPersistenceWarning);
402
- if (llmLogRef.current)
403
- await endLlmLog(llmLogRef.current).catch(showPersistenceWarning);
404
- return exit();
405
- }
488
+ if (result === 'exit')
489
+ return shutdown();
406
490
  if (result === 'handled') {
407
491
  if (value === '/clear') {
408
492
  loadTasksFromStore().then(t => { setVisibleTasks(t); setTaskBarPadding(0); }).catch(() => undefined);
@@ -414,38 +498,20 @@ function ChatScreen({ debug = false, version, build, continueSession = false, re
414
498
  return;
415
499
  await doAgentTurn(prepared.value, prepared.displayValue, prepared.options);
416
500
  }
417
- // F03: resolve @image mentions in a prompt the user typed into attachments and
418
- // gate them on the active provider's explicit capability before any model call.
419
- // Applied only to genuine user input (direct chat and queued follow-ups), never
420
- // to synthetic control prompts (/init, /fleet, skill invocations). Resolution
421
- // errors and capability rejections surface an actionable system message and
422
- // return undefined instead of starting a turn.
501
+ // F03: attachment gating and read blessings live in the pure helper
502
+ // (chat/userInput.ts); this wrapper only surfaces its errors as system
503
+ // messages. Applied only to genuine user input, never synthetic control prompts.
423
504
  async function prepareUserInput(value) {
424
- let resolved;
425
- try {
426
- resolved = await resolveImageAttachments(value);
427
- }
428
- catch (error) {
429
- const text = error instanceof Error ? error.message : String(error);
430
- setMessages(m => [...m, { role: 'system', text }]);
431
- return undefined;
432
- }
433
- const blessed = await resolveReadBlessings(resolved.text);
434
- if (resolved.attachments.length === 0 && blessed.blessedPaths.length === 0)
435
- return { value, options: {} };
436
- const gateError = imageCapabilityError(activeProvider(settings));
437
- if (resolved.attachments.length > 0 && gateError) {
438
- setMessages(m => [...m, { role: 'system', text: gateError }]);
505
+ const prepared = await prepareUserInputPolicy(value, settings);
506
+ if (prepared?.error) {
507
+ setMessages(m => [...m, { role: 'system', text: prepared.error }]);
439
508
  return undefined;
440
509
  }
441
- const displayValue = [resolved.text, ...resolved.attachments.map(imageAttachmentLine)].filter(Boolean).join('\n');
442
- return {
443
- value: resolved.text || IMAGE_ONLY_PROMPT_TEXT,
444
- displayValue,
445
- options: { attachments: resolved.attachments, blessedPaths: blessed.blessedPaths },
446
- };
510
+ return prepared;
447
511
  }
448
512
  async function doAgentTurn(value, displayValue, turnOptions = {}) {
513
+ if (stoppingRef.current)
514
+ return;
449
515
  setDebugLogs([]);
450
516
  // When every task is already completed, start the new turn with a clean
451
517
  // slate: the task bar clears (nothing shown for simple questions) and the
@@ -457,24 +523,19 @@ function ChatScreen({ debug = false, version, build, continueSession = false, re
457
523
  await clearTasksFromStore().catch(() => undefined);
458
524
  }
459
525
  await runSingleAgentTurn(value, displayValue, turnOptions);
460
- for (let next = followUps.takeNext(); next !== undefined; next = followUps.takeNext()) {
526
+ for (let next = followUps.takeNext(); !stoppingRef.current && next !== undefined; next = followUps.takeNext()) {
461
527
  const preparedFollowUp = await prepareUserInput(next);
462
528
  if (!preparedFollowUp)
463
529
  continue;
464
530
  await runSingleAgentTurn(preparedFollowUp.value, preparedFollowUp.displayValue, preparedFollowUp.options);
465
531
  }
466
532
  }
467
- /**
468
- * Resume a paused turn against the preserved conversation (no re-added user
469
- * message). An idle-stall resume continues the same logical turn's bounded
470
- * retry pool; an incomplete-goal resume starts a fresh logical turn (its
471
- * budget was exhausted) nudged to pick up the remaining concrete work.
472
- */
473
533
  /**
474
534
  * Explicitly resume a genuinely paused goal (automatic continuation already
475
535
  * ran): an idle-stall resume continues the bounded retry pool; an
476
- * incomplete-goal resume restarts the supervisor from the stored checkpoint.
477
- * Both ride the preserved conversation — no completed mutations are replayed.
536
+ * incomplete-goal resume restarts the supervisor from the stored checkpoint
537
+ * (kind selection in chat/userInput.ts). Both ride the preserved
538
+ * conversation — no completed mutations are replayed.
478
539
  */
479
540
  async function resumePausedTask() {
480
541
  const resume = pausedResume;
@@ -482,10 +543,7 @@ function ChatScreen({ debug = false, version, build, continueSession = false, re
482
543
  return;
483
544
  setPausedResume(undefined);
484
545
  setMessages(m => [...m, { role: 'system', text: 'Resuming the unfinished goal; completed work is preserved in the conversation.' }]);
485
- const resumeFrom = resume.kind === 'incomplete-goal' && resume.checkpoint
486
- ? { kind: 'incomplete-goal', checkpoint: resume.checkpoint }
487
- : { kind: 'model-stream-idle', retryAttempt: resume.retryAttempt };
488
- await runSingleAgentTurn(resume.request, undefined, {}, resumeFrom);
546
+ await runSingleAgentTurn(resume.request, undefined, {}, resumeKindFor(resume));
489
547
  }
490
548
  /**
491
549
  * The PromptSession shared by every turn of the active session. Returning a
@@ -500,16 +558,26 @@ function ChatScreen({ debug = false, version, build, continueSession = false, re
500
558
  return promptSessionRef.current.value;
501
559
  }
502
560
  async function runSingleAgentTurn(value, displayValue, turnOptions = {}, resumeExisting) {
561
+ if (stoppingRef.current)
562
+ return;
503
563
  const sessionRecorder = sessionRecorderRef.current;
564
+ const selection = currentModelSelection();
565
+ if (!selection) {
566
+ setMessages(m => [...m, { role: 'system', text: 'No model selected for this session. Run /model to choose one.' }]);
567
+ return;
568
+ }
569
+ sessionRecorder.recordModelSelection(selection);
504
570
  // The logical-goal supervisor owns this submission: recoverable-incomplete
505
571
  // physical turns (including step/tool budget boundaries) continue
506
572
  // automatically; per-turn limits stay safety boundaries. An explicit
507
573
  // resumeFrom restarts a genuinely paused goal from its checkpoint/pool.
508
- const goalResult = await runAgentGoal({
574
+ const goalOptions = {
509
575
  request: value,
510
576
  displayValue,
511
577
  contextFiles,
512
578
  session: currentPromptSession(),
579
+ modelOverride: `${selection.provider}:${selection.model}`,
580
+ escalationModel: settings.escalationModel,
513
581
  callbacks: {
514
582
  addMessage: msg => {
515
583
  const ordered = withDisplayOrder(msg);
@@ -534,7 +602,11 @@ function ChatScreen({ debug = false, version, build, continueSession = false, re
534
602
  getConversation: () => conversationRef.current,
535
603
  getLastAssistantText: () => lastAssistantTextRef.current,
536
604
  setLastAssistantText: text => { lastAssistantTextRef.current = text; },
537
- setAbortController: controller => { abortControllerRef.current = controller; },
605
+ setAbortController: controller => {
606
+ abortControllerRef.current = controller;
607
+ if (stoppingRef.current)
608
+ controller?.abort('Chat is exiting.');
609
+ },
538
610
  setWorkState: state => {
539
611
  workStateRef.current = state;
540
612
  sessionRecorder.recordWorkState(state);
@@ -547,16 +619,32 @@ function ChatScreen({ debug = false, version, build, continueSession = false, re
547
619
  onEvent: event => {
548
620
  sessionRecorder.recordEvent(event);
549
621
  },
550
- onTasksChanged: () => { loadTasksFromStore().then(t => { setVisibleTasks(t); setTaskBarPadding(0); }).catch(() => undefined); },
622
+ onTasksChanged: () => {
623
+ loadTasksFromStore().then(t => {
624
+ if (stoppingRef.current)
625
+ return;
626
+ setVisibleTasks(t);
627
+ setTaskBarPadding(0);
628
+ }).catch(() => undefined);
629
+ },
551
630
  contextFileSignatures: contextFileSignaturesRef.current,
552
631
  log: llmLogRef.current,
553
632
  },
554
633
  ...(resumeExisting ? { resumeFrom: resumeExisting } : {}),
555
634
  // Durable goal ledger (P1): every supervisor boundary appends to the
556
635
  // session JSONL so a crash or restart leaves a resumable frontier.
557
- goalLedger: { append: entry => sessionRecorder.recordGoalEntry(entry) },
636
+ goalLedger: { append: entry => { if (!sealedRef.current)
637
+ sessionRecorder.recordGoalEntry(entry); } },
558
638
  ...(turnOptions.attachments || turnOptions.blessedPaths || turnOptions.ephemeralControl || turnOptions.subagentOverrides ? { turnOptions } : {})
559
- });
639
+ };
640
+ const guarded = createQuarantinableCallbacks(goalOptions.callbacks);
641
+ quarantineRef.current = guarded.quarantine;
642
+ const goalPromise = runAgentGoal({ ...goalOptions, callbacks: guarded.callbacks });
643
+ activeGoalRef.current = goalPromise;
644
+ const goalResult = await goalPromise;
645
+ activeGoalRef.current = undefined;
646
+ if (stoppingRef.current)
647
+ return goalResult;
560
648
  await sessionRecorder.flush().catch(showPersistenceWarning);
561
649
  await llmLogRef.current?.writer?.flush().catch(showPersistenceWarning);
562
650
  // Turn boundary: an aborted or forcibly-settled attempt is quarantined
@@ -579,69 +667,76 @@ function ChatScreen({ debug = false, version, build, continueSession = false, re
579
667
  const { staticItems: staticTranscriptItems, streamingItems } = partitionDisplayMessages([...visible, ...activeLiveMessages]);
580
668
  const activeSelection = activeModel(settings);
581
669
  const placeholder = placeholderForMode(mode, busy);
582
- const activeModelName = activeSelection ? `${activeSelection.provider.name}:${activeSelection.model}` : 'unconfigured';
583
- const reasoningSuffix = isReasoningLevel(settings.reasoning) || settings.reasoning === undefined
584
- ? ` (${isReasoningLevel(settings.reasoning) ? settings.reasoning : DEFAULT_REASONING_LEVEL})`
670
+ const selectedModel = currentModelSelection();
671
+ const activeModelName = selectedModel ? `${selectedModel.provider}:${selectedModel.model}${activeSelection ? '' : ' (unavailable)'}` : 'unconfigured';
672
+ const activeSelector = activeSelection ? `${activeSelection.provider.name}:${activeSelection.model}` : undefined;
673
+ // Synchronize session identity before rendering either the status or picker;
674
+ // a new/resumed/forked session must not display the previous session's map.
675
+ const sessionReasoning = currentPromptSession().reasoningByModel;
676
+ const effectiveReasoning = activeSelector
677
+ ? resolveReasoningChoice(sessionReasoning?.[activeSelector], isStoredReasoning(settings.reasoning) ? settings.reasoning : undefined)
678
+ : undefined;
679
+ // When a session override changes, the suffix below must re-render: bump a
680
+ // cheap counter from setSessionReasoning instead of threading per-turn state.
681
+ void reasoningOverrideCounter;
682
+ const reasoningSuffix = effectiveReasoning
683
+ ? effectiveReasoning.level === undefined
684
+ ? ' (no reasoning parameter)'
685
+ : ` (${effectiveReasoning.level})`
585
686
  : '';
586
687
  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.'] }));
587
688
  const workspaceLabel = `${compactHomePath(process.cwd())}${branchName ? ` (${branchName})` : ''}`;
588
689
  const enabledSkillCount = new Set(skills.filter(skill => isSkillEnabled(settings, skill.name, skill.source)).map(skill => skill.name)).size;
589
690
  const metrics = statusBarMetrics({ messages: [...messages, ...liveMessages], tokenUsage, enabledSkillCount, backgroundProcessCount: backgroundCount });
590
- const inputSuggestions = inputSuggestionsForState({ mode, settings, skills, sessions, selectedProviderName, modelProviderFilter, providerDraftName: providerDraft.name, discoveredModels, suggestedModels, selectedSkillName, selectedLspName, selectedMcpName });
691
+ const inputSuggestions = inputSuggestionsForState({ mode, settings, skills, sessions, selectedProviderName, modelProviderFilter, providerDraftName: providerDraft.name, discoveredModels, suggestedModels, selectedSkillName, selectedLspName, selectedMcpName, sessionReasoning });
591
692
  const staticItems = [
592
693
  { kind: 'header', key: 'header', subtitle: headerSubtitle },
593
694
  ...staticTranscriptItems,
594
695
  ];
595
- const contentWidth = Math.max(1, width - 2);
596
- // Live-region budget: once the dynamic frame exceeds the viewport, Ink falls
597
- // back to clearTerminal + full transcript replay, which wipes scrollback and
598
- // jumps to the top on every render. Every dynamic section is therefore
599
- // clamped so the frame stays under one screen (see chat/liveRegion.ts).
600
- const busyRows = busy ? (showingTip ? 2 : 1) : 0;
601
- const queuedRows = followUps.queued.length > 0 ? 2 + followUps.queued.length : 0;
602
- const collapsedTaskRows = Math.min(visibleTasks.length, MAX_VISIBLE_TASKS);
603
- const expandedTaskCap = Math.max(MAX_VISIBLE_TASKS, terminalRows - 18);
604
- const expandedTaskRows = Math.min(visibleTasks.length, expandedTaskCap) + (visibleTasks.length > expandedTaskCap ? 1 : 0);
605
- const taskRows = visibleTasks.length > 0 ? 2 + taskBarPadding + (tasksExpanded ? expandedTaskRows : collapsedTaskRows) : 0;
606
- // Debug-only panels are counted conservatively so debug mode cannot overflow either.
607
- const debugPanelRows = debug && debugLogs.length > 0 ? 4 + debugLogs.length : 0;
608
- const tokenPanelRows = debug && metrics.hasTokenBreakdown ? 5 : 0;
609
- // The input box is border (2) + one row; a user-pasted multiline draft can
610
- // exceed this estimate (accepted: it is transient, user-driven editing state).
611
- const fixedLiveRows = busyRows + queuedRows + taskRows + debugPanelRows + tokenPanelRows + 3 /* input */ + 2 /* status */ + 2 /* safety */;
612
- const streamingRowsBudget = Math.max(1, terminalRows - fixedLiveRows);
613
- const perStreamingItemRows = streamingItems.length > 0 ? Math.max(2, Math.floor(streamingRowsBudget / streamingItems.length)) : 0;
614
- return _jsxs(Box, { flexDirection: "column", paddingX: 1, children: [_jsx(Static, { items: staticItems, children: item => item.kind === 'header'
696
+ const horizontalPadding = width >= 12 ? 1 : 0;
697
+ const contentWidth = Math.max(1, width - horizontalPadding * 2);
698
+ return _jsxs(Box, { flexDirection: "column", paddingX: horizontalPadding, children: [_jsx(Static, { items: staticItems, children: item => item.kind === 'header'
615
699
  ? _jsx(Header, { subtitle: item.subtitle, version: version }, item.key)
616
700
  : item.kind === 'assistant-markdown'
617
701
  ? _jsx(AssistantMarkdownChunkView, { message: item.message, content: item.content, width: contentWidth, first: item.first, final: item.final }, item.key)
618
- : _jsx(MessageView, { message: item.message, width: contentWidth }, item.key) }), streamingItems.length > 0 && _jsx(Box, { flexDirection: "column", flexShrink: 0, children: streamingItems.map(item => {
619
- // One row for the optional header plus one for the item's bottom margin.
620
- const chrome = (item.showHeader === false ? 0 : 1) + 1;
621
- return _jsx(MessageView, { message: item.message, width: contentWidth, showHeader: item.showHeader, maxVisibleLines: Math.max(1, perStreamingItemRows - chrome) }, item.key);
622
- }) }), debug && debugLogs.length > 0 && _jsxs(Box, { flexDirection: "column", flexShrink: 0, marginBottom: 1, borderStyle: "round", borderColor: theme.muted, paddingX: 1, children: [_jsx(Text, { color: theme.muted, bold: true, children: "Debug" }), debugLogs.map((line, index) => _jsxs(Text, { color: theme.muted, children: ["\u2022 ", line] }, index))] }), followUps.queued.length > 0 && _jsxs(Box, { flexDirection: "column", flexShrink: 0, marginBottom: 1, children: [_jsx(Text, { color: theme.muted, children: "Queued follow-ups:" }), followUps.queued.map((item, index) => _jsxs(Text, { color: theme.muted, children: [" ", index + 1, ". ", item] }, `${index}-${item}`))] }), pausedResume && !busy && _jsxs(Box, { flexShrink: 0, marginBottom: 1, children: [_jsxs(Text, { color: theme.muted, children: [pausedResume.kind === 'incomplete-goal'
623
- ? pausedResume.pauseReason === 'context-exhausted'
624
- ? 'Unfinished goal paused (context window exhausted — compact or switch models, then resume)'
625
- : pausedResume.pauseReason === 'goal-deadline'
626
- ? 'Unfinished goal paused (goal deadline reached)'
627
- : 'Unfinished goal paused (no measurable progress)'
628
- : 'Unfinished goal paused (model stream stalled)', " \u00B7 "] }), _jsxs(Text, { color: theme.command, bold: true, children: ["Press R to ", pausedResume.kind === 'incomplete-goal' ? 'resume' : 'retry'] }), _jsx(Text, { color: theme.muted, children: " or type a follow-up" })] }), visibleTasks.length > 0 && _jsx(Box, { flexDirection: "column", flexShrink: 0, marginBottom: 1, children: _jsx(TaskBar, { tasks: visibleTasks, width: contentWidth, expanded: tasksExpanded, padding: taskBarPadding, maxRows: expandedTaskCap }) }), busy && _jsx(BusyBar, { label: busyLabel, elapsed: busyElapsed, tip: showingTip ? TIPS[tipIndex] : undefined }), _jsx(Box, { borderStyle: "round", borderColor: theme.border, paddingX: 1, flexShrink: 0, children: _jsx(Box, { flexGrow: 1, minWidth: 0, children: _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: Math.max(20, contentWidth - 4), getMentionSuggestions: fileMentionSuggestions, onHistoryAdd: persistInputHistory, onToggleTasks: () => {
629
- if (!tasksExpanded) {
630
- setTaskBarPadding(0);
631
- setTasksExpanded(true);
632
- }
633
- else {
634
- const expandedRows = visibleTasks.length + 1;
635
- const collapsedRows = Math.min(visibleTasks.length, MAX_VISIBLE_TASKS) + 1;
636
- setTaskBarPadding(Math.max(0, expandedRows - collapsedRows));
637
- setTasksExpanded(false);
638
- }
639
- }, onCancel: cancelThinking, onResumeKey: pausedResume != null && !busy ? resumePausedTask : undefined, onInterrupt: () => exit(), onEscape: () => {
640
- if (busy)
641
- cancelThinking();
642
- else
643
- closeInputList();
644
- }, onSubmit: submit }) }) }), debug && metrics.hasTokenBreakdown && _jsxs(Box, { flexShrink: 0, flexDirection: "column", paddingX: 1, children: [_jsxs(Text, { color: theme.muted, bold: true, children: ["Token usage ", metrics.inputEstimated || metrics.outputEstimated ? '(estimated)' : '(precise)'] }), _jsxs(Text, { color: theme.muted, children: [" in=", formatTokenCount(metrics.effectiveInput), " out=", formatTokenCount(metrics.effectiveOutput), tokenUsage.cacheReadTokens > 0 ? ` cached=${formatTokenCount(tokenUsage.cacheReadTokens)}` : '', tokenUsage.noCacheTokens > 0 ? ` uncached=${formatTokenCount(tokenUsage.noCacheTokens)}` : '', tokenUsage.cacheWriteTokens > 0 ? ` cache_write=${formatTokenCount(tokenUsage.cacheWriteTokens)}` : '', tokenUsage.reasoningTokens > 0 ? ` reasoning=${formatTokenCount(tokenUsage.reasoningTokens)}` : ''] }), _jsxs(Text, { color: theme.muted, children: [" logical=", formatTokenCount(tokenUsage.logicalInputEstimate), tokenUsage.effectiveNonCachedInput != null ? ` effective_non_cached=${formatTokenCount(tokenUsage.effectiveNonCachedInput)}` : ''] }), _jsxs(Text, { color: theme.muted, children: [" system=", formatTokenCount(tokenUsage.systemPrompt), " messages=", formatTokenCount(tokenUsage.messages), " tools=", formatTokenCount(tokenUsage.toolSchemas), " output=", formatTokenCount(tokenUsage.outputEstimate)] })] }), _jsxs(Box, { flexShrink: 0, justifyContent: "space-between", children: [_jsxs(Box, { flexDirection: "column", flexShrink: 1, minWidth: 0, children: [_jsx(Text, { color: theme.muted, wrap: "truncate-end", children: workspaceLabel }), _jsx(Text, { color: theme.muted, wrap: "truncate-end", children: metrics.statusDetailLabel })] }), _jsx(Box, { flexShrink: 0, marginLeft: 2, children: _jsxs(Text, { color: theme.muted, wrap: "truncate-start", children: [activeModelName, reasoningSuffix] }) })] })] });
702
+ : _jsx(MessageView, { message: item.message, width: contentWidth }, item.key) }, width), _jsx(DynamicFrame, { rows: terminalRows, columns: contentWidth, sections: {
703
+ live: streamingItems.length > 0 ? rows => {
704
+ // Allocate the sum, not a positive minimum for every pending item.
705
+ const displayed = streamingItems.slice(0, Math.floor(rows / 2));
706
+ const itemRows = displayed.length > 0 ? Math.floor(rows / displayed.length) : 0;
707
+ 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));
708
+ } : undefined,
709
+ 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 && (() => {
710
+ const renderMetrics = renderMetricsReader();
711
+ if (!renderMetrics)
712
+ return null;
713
+ const age = Date.now() - renderMetrics.at;
714
+ // Skip the reading once it is clearly stale; it refreshes on the
715
+ // next frame while anything animated keeps the debug panel alive.
716
+ return age < 5_000 ? _jsxs(Text, { color: theme.muted, wrap: "truncate-end", children: ["Ink render: ", renderMetrics.renderTime.toFixed(1), "ms"] }) : null;
717
+ })()] }) : undefined,
718
+ 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,
719
+ tasks: visibleTasks.length > 0 ? _jsx(TaskBar, { tasks: visibleTasks, width: contentWidth, expanded: tasksExpanded, padding: taskBarPadding, maxRows: Math.max(1, terminalRows - 8) }) : undefined,
720
+ activity: busy ? _jsx(BusyBar, { label: busyLabel, elapsed: busyElapsed, tip: showingTip ? TIPS[tipIndex] : undefined })
721
+ : pausedResume ? _jsxs(StatusNotice, { variant: "warning", children: ["Press R to resume \u00B7 unfinished goal paused", pausedResume.pauseReason ? ` (${pausedResume.pauseReason})` : ''] }) : undefined,
722
+ 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 })] }),
723
+ }, 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: () => {
724
+ if (!tasksExpanded) {
725
+ setTaskBarPadding(0);
726
+ setTasksExpanded(true);
727
+ }
728
+ else {
729
+ const expandedRows = visibleTasks.length + 1;
730
+ const collapsedRows = Math.min(visibleTasks.length, MAX_VISIBLE_TASKS) + 1;
731
+ setTaskBarPadding(Math.max(0, expandedRows - collapsedRows));
732
+ setTasksExpanded(false);
733
+ }
734
+ }, onCancel: cancelThinking, onResumeKey: pausedResume != null && !busy ? resumePausedTask : undefined, onInterrupt: () => { void shutdown(); }, onEscape: () => {
735
+ if (busy)
736
+ cancelThinking();
737
+ else
738
+ closeInputList();
739
+ }, onSubmit: submit }) })] });
645
740
  }
646
741
  export async function chatCommand(options = {}) {
647
742
  // Resolve the theme before any Ink output so every component renders with it.
@@ -653,47 +748,38 @@ export async function chatCommand(options = {}) {
653
748
  catch (error) {
654
749
  console.error(`[haze] ${error instanceof Error ? error.message : String(error)}; using the ${DEFAULT_THEME_NAME} theme.`);
655
750
  }
656
- if (process.stdout.isTTY) {
657
- process.stdout.write('\u001B[2J\u001B[3J\u001B[H');
658
- // Adopt the theme's foreground AND background as the terminal defaults
659
- // (OSC 10 + 11; ignored by terminals without support). Both sides must be
660
- // themed together: unstyled text inherits the terminal fg, so a light
661
- // background without a light-mode fg would be unreadable. Restored
662
- // (OSC 110 + 111) on exit below.
663
- applyTerminalColors(theme.foreground, theme.background);
664
- }
665
751
  await clearTasksFromStore().catch(() => undefined);
666
- // Incremental rendering rewrites only changed lines of the live frame, removing
667
- // the full-frame erase/rewrite flicker while streaming. The fps cap aligns with
668
- // the ~80ms spinner cadence; faster renders would only repaint unchanged lines.
669
- //
670
- // Kitty keyboard protocol (auto-detected): without opting in, terminals send a
671
- // bare \r for Shift+Enter — indistinguishable from Enter — so Shift+Enter would
672
- // submit the prompt instead of inserting a newline. With the disambiguate flag,
673
- // compliant terminals (kitty, WezTerm, Ghostty, iTerm2 >=3.5, foot, recent
674
- // Windows Terminal, tmux passthrough) report modified Enter as CSI 13;<mod>u,
675
- // which TextInput maps to a newline. Ink queries support first (CSI ? u) with a
676
- // 200ms timeout, pushes/pops the terminal's flag stack across lifecycle, and
677
- // leaves unsupporting terminals (e.g. macOS Terminal.app) untouched; Enter,
678
- // Tab, and Backspace without modifiers keep their legacy bytes.
679
- //
680
- // The protocol also re-encodes Ctrl+C as CSI 99;5u, which Ink 7.1.1's
681
- // exit-on-CtrlC (raw \x03 check) does not recognize — its useInput layer
682
- // would swallow the parsed c+ctrl without exiting. haze therefore owns the
683
- // interrupt: render with exitOnCtrlC disabled and let ChatScreen's TextInput
684
- // onInterrupt (useApp exit) terminate for both encodings.
685
- const app = render(_jsx(ChatScreen, { debug: options.debug, version: options.version, build: options.build, continueSession: options.continueSession, resumeSessionId: options.resumeSessionId, noSession: options.noSession }), {
686
- incrementalRendering: true,
687
- maxFps: 15,
688
- kittyKeyboard: { mode: 'auto', flags: ['disambiguateEscapeCodes'] },
689
- exitOnCtrlC: false,
752
+ let shutdown;
753
+ // Sampled by the --debug onRender hook; read by ChatScreen's debug panel via
754
+ // a getter so the metric never enters React state (no extra re-renders).
755
+ let lastRenderMetricsMs;
756
+ renderMetricsReader = () => lastRenderMetricsMs;
757
+ // Clear on width changes ahead of Ink's repaint; ChatScreen then replays
758
+ // its width-keyed Static transcript instead of leaving a blank viewport.
759
+ const removeResizeGuard = installViewportResizeGuard();
760
+ await runTerminalSession({
761
+ adopt: () => {
762
+ if (!process.stdout.isTTY)
763
+ return;
764
+ // Clear the viewport, not preexisting terminal scrollback.
765
+ process.stdout.write('\u001B[2J\u001B[H');
766
+ applyTerminalColors(theme.foreground, theme.background);
767
+ },
768
+ create: () => render(_jsx(ChatScreen, { ...options, onShutdownReady: owner => { shutdown = owner; } }), {
769
+ incrementalRendering: true,
770
+ maxFps: 15,
771
+ kittyKeyboard: { mode: 'auto', flags: ['disambiguateEscapeCodes'] },
772
+ exitOnCtrlC: false,
773
+ // Ink 8 render metrics: direct observability of per-frame render cost
774
+ // under --debug, alongside the estimator-based live-region clamp.
775
+ ...(options.debug ? { onRender: ({ renderTime }) => {
776
+ lastRenderMetricsMs = { at: Date.now(), renderTime };
777
+ } } : {}),
778
+ }),
779
+ shutdown: () => shutdown?.(),
780
+ restore: () => {
781
+ removeResizeGuard();
782
+ resetTerminalColors();
783
+ },
690
784
  });
691
- try {
692
- await app.waitUntilExit();
693
- await teardownBackgroundProcesses().catch(() => undefined);
694
- await clearTasksFromStore().catch(() => undefined);
695
- }
696
- finally {
697
- resetTerminalColors();
698
- }
699
785
  }