@denizokcu/haze 1.4.0 → 1.5.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 (132) hide show
  1. package/CHANGELOG.md +33 -1
  2. package/README.md +13 -8
  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 +43 -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/sessionLifecycle.d.ts +3 -1
  17. package/dist/cli/chat/sessionLifecycle.js +13 -2
  18. package/dist/cli/chat/sessionRecorder.d.ts +2 -1
  19. package/dist/cli/chat/sessionRecorder.js +8 -0
  20. package/dist/cli/chat/shutdown.d.ts +27 -0
  21. package/dist/cli/chat/shutdown.js +79 -0
  22. package/dist/cli/chat/terminalControl.d.ts +45 -0
  23. package/dist/cli/chat/terminalControl.js +107 -0
  24. package/dist/cli/chat/tips.js +1 -0
  25. package/dist/cli/chat/userInput.d.ts +43 -0
  26. package/dist/cli/chat/userInput.js +63 -0
  27. package/dist/cli/chat/wizard/sessionThemeHandlers.js +14 -6
  28. package/dist/cli/chat/wizard/types.d.ts +8 -1
  29. package/dist/cli/chat/wizardDispatch.js +1 -1
  30. package/dist/cli/commands/chat.js +251 -172
  31. package/dist/cli/commands/commandHelp.js +6 -2
  32. package/dist/cli/commands/commands.d.ts +8 -0
  33. package/dist/cli/commands/commands.js +11 -0
  34. package/dist/cli/commands/formatters.d.ts +1 -1
  35. package/dist/cli/commands/formatters.js +20 -2
  36. package/dist/cli/commands/logsCommand.js +21 -2
  37. package/dist/cli/commands/reasoningCommand.d.ts +23 -14
  38. package/dist/cli/commands/reasoningCommand.js +53 -20
  39. package/dist/cli/commands/runCommand.js +19 -11
  40. package/dist/cli/commands/streaming/attemptOutcome.d.ts +2 -0
  41. package/dist/cli/commands/streaming/attemptOutcome.js +11 -6
  42. package/dist/cli/commands/streaming/attemptSetup.d.ts +1 -0
  43. package/dist/cli/commands/streaming/attemptSetup.js +11 -5
  44. package/dist/cli/commands/streaming/goalCheckpoint.d.ts +8 -1
  45. package/dist/cli/commands/streaming/goalCheckpoint.js +3 -2
  46. package/dist/cli/commands/streaming/goalSupervisor.d.ts +4 -0
  47. package/dist/cli/commands/streaming/goalSupervisor.js +43 -7
  48. package/dist/cli/commands/streaming/prepareStep.js +7 -3
  49. package/dist/cli/commands/streaming/streamLoop.d.ts +5 -0
  50. package/dist/cli/commands/streaming/streamLoop.js +3 -0
  51. package/dist/cli/commands/streaming/toolPartHandlers.js +6 -0
  52. package/dist/cli/commands/streaming.d.ts +1 -1
  53. package/dist/cli/commands/streaming.js +23 -17
  54. package/dist/cli/commands/wizardFlow.d.ts +5 -2
  55. package/dist/cli/commands/wizardFlow.js +17 -10
  56. package/dist/cli/index.js +17 -1
  57. package/dist/config/contextFiles.d.ts +9 -0
  58. package/dist/config/contextFiles.js +21 -1
  59. package/dist/config/modelCatalog.d.ts +3 -0
  60. package/dist/config/modelCatalog.js +29 -0
  61. package/dist/config/providerPresets.d.ts +1 -1
  62. package/dist/config/providerPresets.js +42 -3
  63. package/dist/config/settings.d.ts +7 -3
  64. package/dist/config/settings.js +8 -0
  65. package/dist/core/agent/budgets.d.ts +13 -15
  66. package/dist/core/agent/budgets.js +15 -17
  67. package/dist/core/agent/completionController.d.ts +6 -2
  68. package/dist/core/agent/completionController.js +16 -3
  69. package/dist/core/agent/goalPolicy.d.ts +10 -0
  70. package/dist/core/agent/goalPolicy.js +44 -6
  71. package/dist/core/agent/projectPreflight.d.ts +2 -0
  72. package/dist/core/agent/projectPreflight.js +56 -0
  73. package/dist/core/agent/reasoningPolicy.d.ts +34 -4
  74. package/dist/core/agent/reasoningPolicy.js +27 -4
  75. package/dist/core/agent/workState.d.ts +8 -0
  76. package/dist/core/agent/workState.js +191 -8
  77. package/dist/core/providerContracts.d.ts +29 -0
  78. package/dist/core/providerContracts.js +1 -0
  79. package/dist/core/session/sessionReport.d.ts +33 -0
  80. package/dist/core/session/sessionReport.js +121 -0
  81. package/dist/core/session/sessionSlimming.js +9 -3
  82. package/dist/core/session/sessionStore.d.ts +12 -0
  83. package/dist/core/session/sessionStore.js +20 -4
  84. package/dist/core/subagent/contracts.d.ts +3 -25
  85. package/dist/core/subagent/executionProfiles.js +4 -4
  86. package/dist/core/validation/outputParser.d.ts +6 -1
  87. package/dist/core/validation/outputParser.js +6 -2
  88. package/dist/llm/client.d.ts +4 -2
  89. package/dist/llm/client.js +17 -10
  90. package/dist/llm/hazeTools.d.ts +8553 -8550
  91. package/dist/llm/hazeTools.js +6 -503
  92. package/dist/llm/lspTools.d.ts +120 -120
  93. package/dist/llm/mcp.js +3 -0
  94. package/dist/llm/requestContext.d.ts +1 -1
  95. package/dist/llm/requestContext.js +1 -1
  96. package/dist/{core/subagent → llm}/subagentRunner.d.ts +9 -9
  97. package/dist/{core/subagent → llm}/subagentRunner.js +22 -25
  98. package/dist/llm/systemPrompt.d.ts +11 -1
  99. package/dist/llm/systemPrompt.js +2 -11
  100. package/dist/llm/tools/fetchTool.d.ts +30 -30
  101. package/dist/llm/tools/fileTools.d.ts +7768 -0
  102. package/dist/llm/tools/fileTools.js +510 -0
  103. package/dist/llm/tools/processTool.d.ts +30 -30
  104. package/dist/llm/tools/shellTool.d.ts +30 -30
  105. package/dist/llm/tools/shellTool.js +8 -4
  106. package/dist/llm/tools/toolContext.d.ts +3 -32
  107. package/dist/llm/tools/toolContext.js +33 -52
  108. package/dist/llm/tools/toolContextState.d.ts +40 -0
  109. package/dist/llm/tools/toolContextState.js +34 -0
  110. package/dist/llm/workerContext.d.ts +7 -0
  111. package/dist/llm/workerContext.js +18 -1
  112. package/dist/skills/SkillLoader.js +3 -3
  113. package/dist/skills/SkillRegistry.js +3 -3
  114. package/dist/skills/builder/SkillBuilder.js +3 -3
  115. package/dist/skills/confinement.d.ts +7 -0
  116. package/dist/skills/confinement.js +15 -0
  117. package/dist/ui/codeHighlight.js +4 -4
  118. package/dist/ui/components/MarkdownText.js +7 -8
  119. package/dist/ui/components/NativeIndicators.d.ts +15 -0
  120. package/dist/ui/components/NativeIndicators.js +32 -0
  121. package/dist/ui/components/StreamingMarkdownText.d.ts +9 -0
  122. package/dist/ui/components/StreamingMarkdownText.js +38 -0
  123. package/dist/ui/components/TextInput.d.ts +7 -2
  124. package/dist/ui/components/TextInput.js +103 -46
  125. package/dist/ui/components/WizardChoices.d.ts +18 -0
  126. package/dist/ui/components/WizardChoices.js +32 -0
  127. package/dist/ui/inputBuffer.js +12 -6
  128. package/dist/ui/textGeometry.d.ts +14 -0
  129. package/dist/ui/textGeometry.js +31 -0
  130. package/package.json +14 -13
  131. /package/dist/cli/{contextReport.d.ts → contextReportCli.d.ts} +0 -0
  132. /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,13 @@ 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 { createQuarantinableCallbacks } from './streaming/attemptLifecycle.js';
25
26
  import { AssistantMarkdownChunkView, MessageView } from '../chat/messages.js';
26
27
  import { partitionDisplayMessages } from '../chat/transcriptPartition.js';
27
28
  import { useLiveMessages } from '../chat/liveMessages.js';
@@ -35,31 +36,29 @@ import { compactHomePath, statusBarMetrics } from '../chat/chatMetrics.js';
35
36
  import { formatTokenCount } from '../../utils/format.js';
36
37
  import { accumulateTokenUsage, EMPTY_TOKEN_USAGE, shouldClearCompletedTasks } from '../chat/turnState.js';
37
38
  import { MASKED_MODES, PICKER_MODES, SUBMIT_EMPTY_MODES, placeholderForMode } from './chatModes.js';
38
- import { DEFAULT_REASONING_LEVEL, isReasoningLevel } from '../../core/agent/reasoningPolicy.js';
39
+ import { contextFileSignatureMap, isPausedGoalRecoveryCommand, mergeSettingsSelection, prepareUserInput as prepareUserInputPolicy, resumeKindFor } from '../chat/userInput.js';
40
+ import { isStoredReasoning, resolveReasoningChoice } from '../../core/agent/reasoningPolicy.js';
39
41
  import { inputSuggestionsForState } from '../chat/inputSuggestions.js';
40
42
  import { currentBranchName, runStartupSequence } from '../chat/startupSequence.js';
41
43
  import { useFollowUpQueue } from '../chat/followUpQueue.js';
42
44
  import { useBusyIndicator } from '../chat/busyIndicator.js';
45
+ import { useTerminalControl } from '../chat/terminalControl.js';
43
46
  import { modelThinkingLabel } from '../../utils/modelName.js';
44
47
  import { commandParts } from './wizardFlow.js';
45
48
  import { backgroundProcessCount, subscribeBackgroundProcesses, teardownBackgroundProcesses } from '../../core/process/backgroundRegistry.js';
46
49
  import { MAX_SESSION_PICKER_RESULTS } from './sessionPicker.js';
50
+ /** Latest Ink render metrics under --debug (module-level: render options are outside React). */
51
+ let renderMetricsReader;
47
52
  function thinkingLabelForSettings(settings) {
48
53
  return modelThinkingLabel(activeModel(settings)?.model);
49
54
  }
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 }) {
55
+ function ChatScreen({ debug = false, version, build, continueSession = false, resumeSessionId, noSession = false, onShutdownReady }) {
61
56
  const { exit } = useApp();
62
57
  const { columns: width, rows: terminalRows } = useWindowSize();
58
+ const stoppingRef = useRef(false);
59
+ const sealedRef = useRef(false);
60
+ const activeGoalRef = useRef(undefined);
61
+ const quarantineRef = useRef(undefined);
63
62
  const nextDisplayOrderRef = useRef(1);
64
63
  const withDisplayOrder = (message) => {
65
64
  if (message.displayOrder != null)
@@ -69,9 +68,30 @@ function ChatScreen({ debug = false, version, build, continueSession = false, re
69
68
  const withDisplayOrders = (next) => next.map(withDisplayOrder);
70
69
  const [messages, setMessagesRaw] = useState([]);
71
70
  const setMessages = (updater) => {
71
+ if (stoppingRef.current)
72
+ return;
72
73
  setMessagesRaw(previous => withDisplayOrders(typeof updater === 'function' ? updater(previous) : updater));
73
74
  };
74
- const [settings, setSettings] = useState({});
75
+ const [settings, setSettingsRaw] = useState({});
76
+ const settingsRef = useRef({});
77
+ const defaultSelectionRef = useRef({});
78
+ function setSettings(next, patch) {
79
+ // The ref records the global default from `next` (what updateSettings
80
+ // returned) before the patch merge; unrelated settings writes must not
81
+ // replace a resumed session's model (merge policy in chat/userInput.ts).
82
+ defaultSelectionRef.current = { provider: next.provider, model: next.model };
83
+ settingsRef.current = patch ? mergeSettingsSelection(next, settingsRef.current, patch) : next;
84
+ setSettingsRaw(settingsRef.current);
85
+ if (patch && ('provider' in patch || 'model' in patch)) {
86
+ const selected = currentModelSelection();
87
+ if (selected)
88
+ sessionRecorderRef.current?.recordModelSelection(selected);
89
+ }
90
+ }
91
+ function currentModelSelection() {
92
+ const { provider, model } = settingsRef.current;
93
+ return provider && model ? { provider, model } : undefined;
94
+ }
75
95
  const [settingsError, setSettingsError] = useState();
76
96
  const conversationRef = useRef([]);
77
97
  const lastAssistantTextRef = useRef('');
@@ -82,7 +102,7 @@ function ChatScreen({ debug = false, version, build, continueSession = false, re
82
102
  sessionRecorderRef.current = createSessionRecorder(() => sessionRef.current);
83
103
  /** Finalize a formerly-live message into the append-only transcript and session record. */
84
104
  function finalizeMessage(message) {
85
- if (message.hidden)
105
+ if (message.hidden || sealedRef.current)
86
106
  return;
87
107
  const ordered = withDisplayOrder(message);
88
108
  setMessages(m => [...m, ordered]);
@@ -97,6 +117,9 @@ function ChatScreen({ debug = false, version, build, continueSession = false, re
97
117
  // detected by sessionStartRef identity (the lifecycle controller replaces
98
118
  // the Date on new/resume/continue).
99
119
  const promptSessionRef = useRef({ identity: undefined, value: { cwd: process.cwd() } });
120
+ // Session per-model reasoning overrides live on the stable PromptSession
121
+ // object; this counter only forces a re-render so the status bar updates.
122
+ const [reasoningOverrideCounter, setReasoningOverrideCounter] = useState(0);
100
123
  const workStateRef = useRef(undefined);
101
124
  const llmLogRef = useRef(undefined);
102
125
  const persistenceWarningShownRef = useRef(false);
@@ -113,6 +136,7 @@ function ChatScreen({ debug = false, version, build, continueSession = false, re
113
136
  // the developer always sees rolling activity (elapsed turn time) even when
114
137
  // the model is thinking with no streamed output and no tool is running.
115
138
  const { busy, setBusy: setBusyWithHeartbeat, elapsed: busyElapsed } = useBusyIndicator();
139
+ const terminalControl = useTerminalControl();
116
140
  const [backgroundCount, setBackgroundCount] = useState(backgroundProcessCount);
117
141
  const [busyLabel, setBusyLabel] = useState(() => thinkingLabelForSettings(settings));
118
142
  const [visibleTasks, setVisibleTasks] = useState([]);
@@ -126,6 +150,34 @@ function ChatScreen({ debug = false, version, build, continueSession = false, re
126
150
  const [pausedResume, setPausedResume] = useState(undefined);
127
151
  const [skills, setSkills] = useState([]);
128
152
  const [branchName, setBranchName] = useState();
153
+ const shutdownRef = useRef(undefined);
154
+ if (!shutdownRef.current)
155
+ shutdownRef.current = createChatShutdown({
156
+ stop: () => { stoppingRef.current = true; followUps.clear(); },
157
+ abort: () => abortControllerRef.current?.abort('Chat is exiting.'),
158
+ settle: () => activeGoalRef.current,
159
+ seal: () => {
160
+ drainLiveMessages();
161
+ sealedRef.current = true;
162
+ quarantineRef.current?.();
163
+ },
164
+ flush: () => sessionRecorderRef.current?.flush(),
165
+ endLog: () => {
166
+ const log = llmLogRef.current;
167
+ llmLogRef.current = undefined;
168
+ return log ? endLlmLog(log) : undefined;
169
+ },
170
+ cleanup: async () => {
171
+ await Promise.all([teardownBackgroundProcesses(), clearTasksFromStore()]);
172
+ },
173
+ exit,
174
+ report: message => process.stderr.write(`[haze] ${message}\n`),
175
+ });
176
+ const shutdown = shutdownRef.current;
177
+ useEffect(() => {
178
+ onShutdownReady?.(shutdown);
179
+ return () => { void shutdown(); };
180
+ }, [onShutdownReady, shutdown]);
129
181
  // Wizard flow state (selection, drafts, model discovery) in one reducer;
130
182
  // this replaced twelve individual useState hooks.
131
183
  const [wizardState, updateWizard] = useReducer(wizardUiReducer, undefined, initialWizardUiState);
@@ -160,7 +212,7 @@ function ChatScreen({ debug = false, version, build, continueSession = false, re
160
212
  const settingsThemeLoadedRef = useRef(false);
161
213
  const activeThemeName = settings.theme ?? DEFAULT_THEME_NAME;
162
214
  useEffect(() => {
163
- if (!settingsThemeLoadedRef.current)
215
+ if (!settingsThemeLoadedRef.current || stoppingRef.current)
164
216
  return;
165
217
  try {
166
218
  setActiveTheme(resolveTheme(activeThemeName));
@@ -179,7 +231,7 @@ function ChatScreen({ debug = false, version, build, continueSession = false, re
179
231
  setSettingsError(settingsError);
180
232
  setBranchName(branch);
181
233
  setContextFiles(files);
182
- contextFileSignaturesRef.current = new Map(files.flatMap(file => file.signature ? [[file.path, file.signature]] : []));
234
+ contextFileSignaturesRef.current = contextFileSignatureMap(files);
183
235
  },
184
236
  initializeSession: () => sessionLifecycle.initializeSession(),
185
237
  refreshSkills,
@@ -224,7 +276,7 @@ function ChatScreen({ debug = false, version, build, continueSession = false, re
224
276
  return skill ? { skill, args: args.join(' ') } : undefined;
225
277
  }
226
278
  function debugLog(line) {
227
- if (!debug)
279
+ if (!debug || stoppingRef.current)
228
280
  return;
229
281
  setDebugLogs(current => [...current.slice(-7), line]);
230
282
  }
@@ -245,6 +297,11 @@ function ChatScreen({ debug = false, version, build, continueSession = false, re
245
297
  noSession,
246
298
  debug,
247
299
  contextFiles: () => contextFiles,
300
+ modelSelection: currentModelSelection,
301
+ onModelSelection: selection => {
302
+ settingsRef.current = { ...settingsRef.current, ...(selection ?? defaultSelectionRef.current) };
303
+ setSettingsRaw(settingsRef.current);
304
+ },
248
305
  sessionRef,
249
306
  sessionRecorder: () => sessionRecorderRef.current,
250
307
  sessionStartRef,
@@ -301,6 +358,19 @@ function ChatScreen({ debug = false, version, build, continueSession = false, re
301
358
  if (message)
302
359
  setMessages(m => [...m, { role: 'system', text: message }]);
303
360
  }
361
+ // Session per-model reasoning overrides live on the stable PromptSession
362
+ // object; the counter only forces a re-render so the status bar updates.
363
+ function setSessionReasoningOverride(modelSelector, setting) {
364
+ const session = currentPromptSession();
365
+ if (setting === undefined) {
366
+ if (session.reasoningByModel)
367
+ delete session.reasoningByModel[modelSelector];
368
+ }
369
+ else {
370
+ session.reasoningByModel = { ...session.reasoningByModel, [modelSelector]: setting };
371
+ }
372
+ setReasoningOverrideCounter(count => count + 1);
373
+ }
304
374
  // Wizard/picker submit dispatch lives in one table-driven module with a
305
375
  // shared settings-patch applier (CR-006). Rebuilt every render so handlers
306
376
  // see current state without new React state.
@@ -313,12 +383,21 @@ function ChatScreen({ debug = false, version, build, continueSession = false, re
313
383
  forkSessionById: sessionLifecycle.forkSessionById,
314
384
  setBusyLabel, setBusy: setBusyWithHeartbeat,
315
385
  idleBusyLabel: thinkingLabelForSettings(settings),
386
+ sessionReasoning: {
387
+ modelSelector: () => { const selection = activeModel(settings); return selection ? `${selection.provider.name}:${selection.model}` : undefined; },
388
+ get: modelSelector => currentPromptSession().reasoningByModel?.[modelSelector],
389
+ set: setSessionReasoningOverride,
390
+ },
316
391
  });
317
392
  async function submit(value) {
393
+ if (stoppingRef.current)
394
+ return;
395
+ if (mode === 'chat' && /^\/(?:exit|quit)\s*$/i.test(value))
396
+ return shutdown();
318
397
  if (settingsError) {
319
398
  try {
320
399
  const repaired = await readSettings();
321
- setSettings(repaired);
400
+ setSettings(repaired, {});
322
401
  setSettingsError(undefined);
323
402
  }
324
403
  catch (error) {
@@ -339,7 +418,7 @@ function ChatScreen({ debug = false, version, build, continueSession = false, re
339
418
  // recovery/configuration commands (compact, model, provider, settings,
340
419
  // resume…) intentionally keep it — the pause notice tells the user to run
341
420
  // exactly those and then press R (SU-04).
342
- const isRecoveryCommand = mode !== 'chat' || /^(?:\/compact|\/model|\/provider|\/settings|\/themes|\/resume|\/sessions)\b/.test(value.trim());
421
+ const isRecoveryCommand = isPausedGoalRecoveryCommand(mode, value);
343
422
  if (pausedResume && !isRecoveryCommand)
344
423
  setPausedResume(undefined);
345
424
  if (await wizard.dispatch(mode, value))
@@ -374,17 +453,26 @@ function ChatScreen({ debug = false, version, build, continueSession = false, re
374
453
  compactConversation,
375
454
  compactConversationLlm: compactConversationWithModel,
376
455
  runAgentTurn: (prompt, displayValue, options) => doAgentTurn(prompt, displayValue, options),
456
+ composeInEditor: async () => {
457
+ const text = await terminalControl.composeInEditor();
458
+ if (text === undefined)
459
+ setMessages(m => [...m, { role: 'system', text: '/editor needs $EDITOR (or $VISUAL) set to an editor command.' }]);
460
+ return text;
461
+ },
462
+ viewInPager: terminalControl.viewInPager,
377
463
  refreshContextFiles: async () => {
378
464
  const files = await readContextFiles().catch(() => contextFiles);
379
465
  setContextFiles(files);
380
- contextFileSignaturesRef.current = new Map(files.flatMap(file => file.signature ? [[file.path, file.signature]] : []));
466
+ contextFileSignaturesRef.current = contextFileSignatureMap(files);
381
467
  return files;
382
468
  },
383
469
  updateSettings: async (patch) => {
384
470
  const next = await updateSettings(patch);
385
- setSettings(next);
386
- return next;
471
+ setSettings(next, patch);
472
+ return settingsRef.current;
387
473
  },
474
+ getSessionReasoning: modelSelector => currentPromptSession().reasoningByModel?.[modelSelector],
475
+ setSessionReasoning: setSessionReasoningOverride,
388
476
  getContextReport: () => buildContextReport({ sessionStart: sessionStartRef.current, contextFiles, conversation: conversationRef.current }),
389
477
  };
390
478
  let result;
@@ -396,13 +484,8 @@ function ChatScreen({ debug = false, version, build, continueSession = false, re
396
484
  setMessages(m => [...m, { role: 'system', text: `Command failed: ${text}` }]);
397
485
  return;
398
486
  }
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
- }
487
+ if (result === 'exit')
488
+ return shutdown();
406
489
  if (result === 'handled') {
407
490
  if (value === '/clear') {
408
491
  loadTasksFromStore().then(t => { setVisibleTasks(t); setTaskBarPadding(0); }).catch(() => undefined);
@@ -414,38 +497,20 @@ function ChatScreen({ debug = false, version, build, continueSession = false, re
414
497
  return;
415
498
  await doAgentTurn(prepared.value, prepared.displayValue, prepared.options);
416
499
  }
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.
500
+ // F03: attachment gating and read blessings live in the pure helper
501
+ // (chat/userInput.ts); this wrapper only surfaces its errors as system
502
+ // messages. Applied only to genuine user input, never synthetic control prompts.
423
503
  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 }]);
504
+ const prepared = await prepareUserInputPolicy(value, settings);
505
+ if (prepared?.error) {
506
+ setMessages(m => [...m, { role: 'system', text: prepared.error }]);
439
507
  return undefined;
440
508
  }
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
- };
509
+ return prepared;
447
510
  }
448
511
  async function doAgentTurn(value, displayValue, turnOptions = {}) {
512
+ if (stoppingRef.current)
513
+ return;
449
514
  setDebugLogs([]);
450
515
  // When every task is already completed, start the new turn with a clean
451
516
  // slate: the task bar clears (nothing shown for simple questions) and the
@@ -457,24 +522,19 @@ function ChatScreen({ debug = false, version, build, continueSession = false, re
457
522
  await clearTasksFromStore().catch(() => undefined);
458
523
  }
459
524
  await runSingleAgentTurn(value, displayValue, turnOptions);
460
- for (let next = followUps.takeNext(); next !== undefined; next = followUps.takeNext()) {
525
+ for (let next = followUps.takeNext(); !stoppingRef.current && next !== undefined; next = followUps.takeNext()) {
461
526
  const preparedFollowUp = await prepareUserInput(next);
462
527
  if (!preparedFollowUp)
463
528
  continue;
464
529
  await runSingleAgentTurn(preparedFollowUp.value, preparedFollowUp.displayValue, preparedFollowUp.options);
465
530
  }
466
531
  }
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
532
  /**
474
533
  * Explicitly resume a genuinely paused goal (automatic continuation already
475
534
  * 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.
535
+ * incomplete-goal resume restarts the supervisor from the stored checkpoint
536
+ * (kind selection in chat/userInput.ts). Both ride the preserved
537
+ * conversation — no completed mutations are replayed.
478
538
  */
479
539
  async function resumePausedTask() {
480
540
  const resume = pausedResume;
@@ -482,10 +542,7 @@ function ChatScreen({ debug = false, version, build, continueSession = false, re
482
542
  return;
483
543
  setPausedResume(undefined);
484
544
  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);
545
+ await runSingleAgentTurn(resume.request, undefined, {}, resumeKindFor(resume));
489
546
  }
490
547
  /**
491
548
  * The PromptSession shared by every turn of the active session. Returning a
@@ -500,16 +557,26 @@ function ChatScreen({ debug = false, version, build, continueSession = false, re
500
557
  return promptSessionRef.current.value;
501
558
  }
502
559
  async function runSingleAgentTurn(value, displayValue, turnOptions = {}, resumeExisting) {
560
+ if (stoppingRef.current)
561
+ return;
503
562
  const sessionRecorder = sessionRecorderRef.current;
563
+ const selection = currentModelSelection();
564
+ if (!selection) {
565
+ setMessages(m => [...m, { role: 'system', text: 'No model selected for this session. Run /model to choose one.' }]);
566
+ return;
567
+ }
568
+ sessionRecorder.recordModelSelection(selection);
504
569
  // The logical-goal supervisor owns this submission: recoverable-incomplete
505
570
  // physical turns (including step/tool budget boundaries) continue
506
571
  // automatically; per-turn limits stay safety boundaries. An explicit
507
572
  // resumeFrom restarts a genuinely paused goal from its checkpoint/pool.
508
- const goalResult = await runAgentGoal({
573
+ const goalOptions = {
509
574
  request: value,
510
575
  displayValue,
511
576
  contextFiles,
512
577
  session: currentPromptSession(),
578
+ modelOverride: `${selection.provider}:${selection.model}`,
579
+ escalationModel: settings.escalationModel,
513
580
  callbacks: {
514
581
  addMessage: msg => {
515
582
  const ordered = withDisplayOrder(msg);
@@ -534,7 +601,11 @@ function ChatScreen({ debug = false, version, build, continueSession = false, re
534
601
  getConversation: () => conversationRef.current,
535
602
  getLastAssistantText: () => lastAssistantTextRef.current,
536
603
  setLastAssistantText: text => { lastAssistantTextRef.current = text; },
537
- setAbortController: controller => { abortControllerRef.current = controller; },
604
+ setAbortController: controller => {
605
+ abortControllerRef.current = controller;
606
+ if (stoppingRef.current)
607
+ controller?.abort('Chat is exiting.');
608
+ },
538
609
  setWorkState: state => {
539
610
  workStateRef.current = state;
540
611
  sessionRecorder.recordWorkState(state);
@@ -547,16 +618,32 @@ function ChatScreen({ debug = false, version, build, continueSession = false, re
547
618
  onEvent: event => {
548
619
  sessionRecorder.recordEvent(event);
549
620
  },
550
- onTasksChanged: () => { loadTasksFromStore().then(t => { setVisibleTasks(t); setTaskBarPadding(0); }).catch(() => undefined); },
621
+ onTasksChanged: () => {
622
+ loadTasksFromStore().then(t => {
623
+ if (stoppingRef.current)
624
+ return;
625
+ setVisibleTasks(t);
626
+ setTaskBarPadding(0);
627
+ }).catch(() => undefined);
628
+ },
551
629
  contextFileSignatures: contextFileSignaturesRef.current,
552
630
  log: llmLogRef.current,
553
631
  },
554
632
  ...(resumeExisting ? { resumeFrom: resumeExisting } : {}),
555
633
  // Durable goal ledger (P1): every supervisor boundary appends to the
556
634
  // session JSONL so a crash or restart leaves a resumable frontier.
557
- goalLedger: { append: entry => sessionRecorder.recordGoalEntry(entry) },
635
+ goalLedger: { append: entry => { if (!sealedRef.current)
636
+ sessionRecorder.recordGoalEntry(entry); } },
558
637
  ...(turnOptions.attachments || turnOptions.blessedPaths || turnOptions.ephemeralControl || turnOptions.subagentOverrides ? { turnOptions } : {})
559
- });
638
+ };
639
+ const guarded = createQuarantinableCallbacks(goalOptions.callbacks);
640
+ quarantineRef.current = guarded.quarantine;
641
+ const goalPromise = runAgentGoal({ ...goalOptions, callbacks: guarded.callbacks });
642
+ activeGoalRef.current = goalPromise;
643
+ const goalResult = await goalPromise;
644
+ activeGoalRef.current = undefined;
645
+ if (stoppingRef.current)
646
+ return goalResult;
560
647
  await sessionRecorder.flush().catch(showPersistenceWarning);
561
648
  await llmLogRef.current?.writer?.flush().catch(showPersistenceWarning);
562
649
  // Turn boundary: an aborted or forcibly-settled attempt is quarantined
@@ -579,69 +666,76 @@ function ChatScreen({ debug = false, version, build, continueSession = false, re
579
666
  const { staticItems: staticTranscriptItems, streamingItems } = partitionDisplayMessages([...visible, ...activeLiveMessages]);
580
667
  const activeSelection = activeModel(settings);
581
668
  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})`
669
+ const selectedModel = currentModelSelection();
670
+ const activeModelName = selectedModel ? `${selectedModel.provider}:${selectedModel.model}${activeSelection ? '' : ' (unavailable)'}` : 'unconfigured';
671
+ const activeSelector = activeSelection ? `${activeSelection.provider.name}:${activeSelection.model}` : undefined;
672
+ // Synchronize session identity before rendering either the status or picker;
673
+ // a new/resumed/forked session must not display the previous session's map.
674
+ const sessionReasoning = currentPromptSession().reasoningByModel;
675
+ const effectiveReasoning = activeSelector
676
+ ? resolveReasoningChoice(sessionReasoning?.[activeSelector], isStoredReasoning(settings.reasoning) ? settings.reasoning : undefined)
677
+ : undefined;
678
+ // When a session override changes, the suffix below must re-render: bump a
679
+ // cheap counter from setSessionReasoning instead of threading per-turn state.
680
+ void reasoningOverrideCounter;
681
+ const reasoningSuffix = effectiveReasoning
682
+ ? effectiveReasoning.level === undefined
683
+ ? ' (no reasoning parameter)'
684
+ : ` (${effectiveReasoning.level})`
585
685
  : '';
586
686
  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
687
  const workspaceLabel = `${compactHomePath(process.cwd())}${branchName ? ` (${branchName})` : ''}`;
588
688
  const enabledSkillCount = new Set(skills.filter(skill => isSkillEnabled(settings, skill.name, skill.source)).map(skill => skill.name)).size;
589
689
  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 });
690
+ const inputSuggestions = inputSuggestionsForState({ mode, settings, skills, sessions, selectedProviderName, modelProviderFilter, providerDraftName: providerDraft.name, discoveredModels, suggestedModels, selectedSkillName, selectedLspName, selectedMcpName, sessionReasoning });
591
691
  const staticItems = [
592
692
  { kind: 'header', key: 'header', subtitle: headerSubtitle },
593
693
  ...staticTranscriptItems,
594
694
  ];
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'
695
+ const horizontalPadding = width >= 12 ? 1 : 0;
696
+ const contentWidth = Math.max(1, width - horizontalPadding * 2);
697
+ return _jsxs(Box, { flexDirection: "column", paddingX: horizontalPadding, children: [_jsx(Static, { items: staticItems, children: item => item.kind === 'header'
615
698
  ? _jsx(Header, { subtitle: item.subtitle, version: version }, item.key)
616
699
  : item.kind === 'assistant-markdown'
617
700
  ? _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] }) })] })] });
701
+ : _jsx(MessageView, { message: item.message, width: contentWidth }, item.key) }), _jsx(DynamicFrame, { rows: terminalRows, columns: contentWidth, sections: {
702
+ live: streamingItems.length > 0 ? rows => {
703
+ // Allocate the sum, not a positive minimum for every pending item.
704
+ const displayed = streamingItems.slice(0, Math.floor(rows / 2));
705
+ const itemRows = displayed.length > 0 ? Math.floor(rows / displayed.length) : 0;
706
+ 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));
707
+ } : undefined,
708
+ 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 && (() => {
709
+ const renderMetrics = renderMetricsReader();
710
+ if (!renderMetrics)
711
+ return null;
712
+ const age = Date.now() - renderMetrics.at;
713
+ // Skip the reading once it is clearly stale; it refreshes on the
714
+ // next frame while anything animated keeps the debug panel alive.
715
+ return age < 5_000 ? _jsxs(Text, { color: theme.muted, wrap: "truncate-end", children: ["Ink render: ", renderMetrics.renderTime.toFixed(1), "ms"] }) : null;
716
+ })()] }) : undefined,
717
+ 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,
718
+ tasks: visibleTasks.length > 0 ? _jsx(TaskBar, { tasks: visibleTasks, width: contentWidth, expanded: tasksExpanded, padding: taskBarPadding, maxRows: Math.max(1, terminalRows - 8) }) : undefined,
719
+ activity: busy ? _jsx(BusyBar, { label: busyLabel, elapsed: busyElapsed, tip: showingTip ? TIPS[tipIndex] : undefined })
720
+ : pausedResume ? _jsxs(StatusNotice, { variant: "warning", children: ["Press R to resume \u00B7 unfinished goal paused", pausedResume.pauseReason ? ` (${pausedResume.pauseReason})` : ''] }) : undefined,
721
+ 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 })] }),
722
+ }, 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: () => {
723
+ if (!tasksExpanded) {
724
+ setTaskBarPadding(0);
725
+ setTasksExpanded(true);
726
+ }
727
+ else {
728
+ const expandedRows = visibleTasks.length + 1;
729
+ const collapsedRows = Math.min(visibleTasks.length, MAX_VISIBLE_TASKS) + 1;
730
+ setTaskBarPadding(Math.max(0, expandedRows - collapsedRows));
731
+ setTasksExpanded(false);
732
+ }
733
+ }, onCancel: cancelThinking, onResumeKey: pausedResume != null && !busy ? resumePausedTask : undefined, onInterrupt: () => { void shutdown(); }, onEscape: () => {
734
+ if (busy)
735
+ cancelThinking();
736
+ else
737
+ closeInputList();
738
+ }, onSubmit: submit }) })] });
645
739
  }
646
740
  export async function chatCommand(options = {}) {
647
741
  // Resolve the theme before any Ink output so every component renders with it.
@@ -653,47 +747,32 @@ export async function chatCommand(options = {}) {
653
747
  catch (error) {
654
748
  console.error(`[haze] ${error instanceof Error ? error.message : String(error)}; using the ${DEFAULT_THEME_NAME} theme.`);
655
749
  }
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
750
  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,
751
+ let shutdown;
752
+ // Sampled by the --debug onRender hook; read by ChatScreen's debug panel via
753
+ // a getter so the metric never enters React state (no extra re-renders).
754
+ let lastRenderMetricsMs;
755
+ renderMetricsReader = () => lastRenderMetricsMs;
756
+ await runTerminalSession({
757
+ adopt: () => {
758
+ if (!process.stdout.isTTY)
759
+ return;
760
+ // Clear the viewport, not preexisting terminal scrollback.
761
+ process.stdout.write('\u001B[2J\u001B[H');
762
+ applyTerminalColors(theme.foreground, theme.background);
763
+ },
764
+ create: () => render(_jsx(ChatScreen, { ...options, onShutdownReady: owner => { shutdown = owner; } }), {
765
+ incrementalRendering: true,
766
+ maxFps: 15,
767
+ kittyKeyboard: { mode: 'auto', flags: ['disambiguateEscapeCodes'] },
768
+ exitOnCtrlC: false,
769
+ // Ink 8 render metrics: direct observability of per-frame render cost
770
+ // under --debug, alongside the estimator-based live-region clamp.
771
+ ...(options.debug ? { onRender: ({ renderTime }) => {
772
+ lastRenderMetricsMs = { at: Date.now(), renderTime };
773
+ } } : {}),
774
+ }),
775
+ shutdown: () => shutdown?.(),
776
+ restore: resetTerminalColors,
690
777
  });
691
- try {
692
- await app.waitUntilExit();
693
- await teardownBackgroundProcesses().catch(() => undefined);
694
- await clearTasksFromStore().catch(() => undefined);
695
- }
696
- finally {
697
- resetTerminalColors();
698
- }
699
778
  }