@denizokcu/haze 1.2.0 → 1.4.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 (109) hide show
  1. package/CHANGELOG.md +53 -0
  2. package/README.md +18 -10
  3. package/SECURITY.md +1 -1
  4. package/bin/haze.js +27 -7
  5. package/dist/buildInfo.json +3 -3
  6. package/dist/cli/chat/inputSuggestions.js +3 -0
  7. package/dist/cli/chat/liveMessages.d.ts +36 -0
  8. package/dist/cli/chat/liveMessages.js +64 -0
  9. package/dist/cli/chat/sessionLifecycle.d.ts +2 -1
  10. package/dist/cli/chat/sessionLifecycle.js +23 -2
  11. package/dist/cli/chat/wizard/sessionThemeHandlers.d.ts +1 -1
  12. package/dist/cli/chat/wizard/sessionThemeHandlers.js +16 -1
  13. package/dist/cli/commands/chat.js +39 -34
  14. package/dist/cli/commands/commandHelp.js +2 -0
  15. package/dist/cli/commands/commands.js +2 -0
  16. package/dist/cli/commands/formatters.js +5 -1
  17. package/dist/cli/commands/ndjsonSink.d.ts +12 -0
  18. package/dist/cli/commands/ndjsonSink.js +29 -0
  19. package/dist/cli/commands/reasoningCommand.d.ts +35 -0
  20. package/dist/cli/commands/reasoningCommand.js +46 -0
  21. package/dist/cli/commands/runCommand.d.ts +14 -0
  22. package/dist/cli/commands/runCommand.js +37 -11
  23. package/dist/cli/commands/settingsSummary.js +2 -0
  24. package/dist/cli/commands/streaming/agentAttempt.d.ts +3 -0
  25. package/dist/cli/commands/streaming/agentAttempt.js +2 -2
  26. package/dist/cli/commands/streaming/assistantSegments.d.ts +0 -7
  27. package/dist/cli/commands/streaming/assistantSegments.js +1 -1
  28. package/dist/cli/commands/streaming/attemptLifecycle.js +13 -9
  29. package/dist/cli/commands/streaming/attemptOutcome.js +13 -3
  30. package/dist/cli/commands/streaming/attemptSetup.d.ts +3 -0
  31. package/dist/cli/commands/streaming/attemptSetup.js +11 -3
  32. package/dist/cli/commands/streaming/goalCheckpoint.d.ts +6 -0
  33. package/dist/cli/commands/streaming/goalCheckpoint.js +1 -0
  34. package/dist/cli/commands/streaming/goalSupervisor.d.ts +5 -0
  35. package/dist/cli/commands/streaming/goalSupervisor.js +9 -4
  36. package/dist/cli/commands/streaming/prepareStep.d.ts +0 -3
  37. package/dist/cli/commands/streaming/prepareStep.js +8 -3
  38. package/dist/cli/commands/streaming.d.ts +7 -2
  39. package/dist/cli/commands/streaming.js +24 -5
  40. package/dist/cli/commands/wizardFlow.d.ts +7 -0
  41. package/dist/cli/commands/wizardFlow.js +22 -0
  42. package/dist/cli/index.js +5 -1
  43. package/dist/config/modelDiscovery.js +68 -5
  44. package/dist/config/settings.d.ts +8 -4
  45. package/dist/config/settings.js +8 -1
  46. package/dist/core/agent/budgets.d.ts +0 -2
  47. package/dist/core/agent/budgets.js +0 -2
  48. package/dist/core/agent/completionController.d.ts +8 -0
  49. package/dist/core/agent/completionController.js +32 -0
  50. package/dist/core/agent/events.d.ts +2 -1
  51. package/dist/core/agent/goalPolicy.d.ts +7 -0
  52. package/dist/core/agent/goalPolicy.js +9 -0
  53. package/dist/core/agent/reasoningPolicy.d.ts +45 -9
  54. package/dist/core/agent/reasoningPolicy.js +49 -9
  55. package/dist/core/agent/toolCapabilities.d.ts +3 -3
  56. package/dist/core/agent/toolCapabilities.js +31 -7
  57. package/dist/core/agent/workState.d.ts +6 -4
  58. package/dist/core/agent/workState.js +40 -28
  59. package/dist/core/deadline.js +22 -24
  60. package/dist/core/safety/secretPaths.js +10 -7
  61. package/dist/core/safety/shellClassifier.d.ts +2 -0
  62. package/dist/core/safety/shellClassifier.js +9 -1
  63. package/dist/core/session/sessionSlimming.d.ts +2 -0
  64. package/dist/core/session/sessionSlimming.js +50 -1
  65. package/dist/core/session/sessionStore.d.ts +4 -8
  66. package/dist/core/session/sessionStore.js +53 -32
  67. package/dist/core/shellOutput/reducers/git.js +7 -2
  68. package/dist/core/shellOutput/reducers/validation.d.ts +1 -1
  69. package/dist/core/shellOutput/reducers/validation.js +14 -1
  70. package/dist/core/shellOutput/registry.js +3 -2
  71. package/dist/core/subagent/contracts.d.ts +8 -1
  72. package/dist/core/subagent/subagentRunner.d.ts +4 -0
  73. package/dist/core/subagent/subagentRunner.js +33 -25
  74. package/dist/core/tasks/taskStorage.js +8 -1
  75. package/dist/core/validation/outputParser.js +24 -0
  76. package/dist/llm/client.d.ts +2 -1
  77. package/dist/llm/client.js +20 -10
  78. package/dist/llm/hazeTools.d.ts +2039 -16
  79. package/dist/llm/hazeTools.js +43 -2
  80. package/dist/llm/lsp/client.d.ts +7 -1
  81. package/dist/llm/lsp/client.js +58 -9
  82. package/dist/llm/lsp/pool.d.ts +11 -0
  83. package/dist/llm/lsp/pool.js +61 -4
  84. package/dist/llm/lsp/protocol.d.ts +6 -23
  85. package/dist/llm/lsp/requests.d.ts +54 -60
  86. package/dist/llm/lsp/requests.js +152 -28
  87. package/dist/llm/lsp/symbols.d.ts +16 -0
  88. package/dist/llm/lsp/symbols.js +70 -0
  89. package/dist/llm/lsp/workspaceEdit.d.ts +43 -0
  90. package/dist/llm/lsp/workspaceEdit.js +117 -0
  91. package/dist/llm/lspTools.d.ts +7518 -2859
  92. package/dist/llm/lspTools.js +195 -110
  93. package/dist/llm/requestContext.d.ts +3 -2
  94. package/dist/llm/requestContext.js +8 -4
  95. package/dist/llm/systemPrompt.js +2 -2
  96. package/dist/llm/tools/fetchTool.d.ts +4 -0
  97. package/dist/llm/tools/processTool.d.ts +4 -0
  98. package/dist/llm/tools/replaceInFiles.d.ts +105 -0
  99. package/dist/llm/tools/replaceInFiles.js +131 -0
  100. package/dist/llm/tools/shellTool.d.ts +4 -0
  101. package/dist/llm/tools/storedOutputTool.d.ts +4 -0
  102. package/dist/llm/tools/taskTool.d.ts +4 -0
  103. package/dist/llm/tools/toolContext.d.ts +3 -0
  104. package/dist/llm/tools/toolContext.js +26 -4
  105. package/dist/skills/SkillLoader.js +27 -1
  106. package/dist/ui/components/useInputSuggestions.js +18 -6
  107. package/dist/utils/buildInfo.js +29 -8
  108. package/dist/utils/fs.js +5 -1
  109. package/package.json +19 -19
@@ -24,6 +24,7 @@ import { formatSession, listSessions } from '../../core/session/sessionStore.js'
24
24
  import { MAX_VISIBLE_TASKS, TaskBar } from '../chat/TaskBar.js';
25
25
  import { AssistantMarkdownChunkView, MessageView } from '../chat/messages.js';
26
26
  import { partitionDisplayMessages } from '../chat/transcriptPartition.js';
27
+ import { useLiveMessages } from '../chat/liveMessages.js';
27
28
  import { createSessionRecorder } from '../chat/sessionRecorder.js';
28
29
  import { createSessionLifecycle } from '../chat/sessionLifecycle.js';
29
30
  import { createWizardDispatch, initialWizardUiState, wizardUiReducer } from '../chat/wizardDispatch.js';
@@ -34,6 +35,7 @@ import { compactHomePath, statusBarMetrics } from '../chat/chatMetrics.js';
34
35
  import { formatTokenCount } from '../../utils/format.js';
35
36
  import { accumulateTokenUsage, EMPTY_TOKEN_USAGE, shouldClearCompletedTasks } from '../chat/turnState.js';
36
37
  import { MASKED_MODES, PICKER_MODES, SUBMIT_EMPTY_MODES, placeholderForMode } from './chatModes.js';
38
+ import { DEFAULT_REASONING_LEVEL, isReasoningLevel } from '../../core/agent/reasoningPolicy.js';
37
39
  import { inputSuggestionsForState } from '../chat/inputSuggestions.js';
38
40
  import { currentBranchName, runStartupSequence } from '../chat/startupSequence.js';
39
41
  import { useFollowUpQueue } from '../chat/followUpQueue.js';
@@ -69,15 +71,6 @@ function ChatScreen({ debug = false, version, build, continueSession = false, re
69
71
  const setMessages = (updater) => {
70
72
  setMessagesRaw(previous => withDisplayOrders(typeof updater === 'function' ? updater(previous) : updater));
71
73
  };
72
- const [liveMessages, setLiveMessages] = useState([]);
73
- const liveMessagesRef = useRef([]);
74
- const setLiveMessagesState = (updater) => {
75
- setLiveMessages(previous => {
76
- const next = withDisplayOrders(updater(previous));
77
- liveMessagesRef.current = next;
78
- return next;
79
- });
80
- };
81
74
  const [settings, setSettings] = useState({});
82
75
  const [settingsError, setSettingsError] = useState();
83
76
  const conversationRef = useRef([]);
@@ -87,6 +80,17 @@ function ChatScreen({ debug = false, version, build, continueSession = false, re
87
80
  const sessionRecorderRef = useRef(undefined);
88
81
  if (!sessionRecorderRef.current)
89
82
  sessionRecorderRef.current = createSessionRecorder(() => sessionRef.current);
83
+ /** Finalize a formerly-live message into the append-only transcript and session record. */
84
+ function finalizeMessage(message) {
85
+ if (message.hidden)
86
+ return;
87
+ const ordered = withDisplayOrder(message);
88
+ setMessages(m => [...m, ordered]);
89
+ sessionRecorderRef.current?.recordUiMessage(ordered);
90
+ }
91
+ // Synchronous live-tail store (see chat/liveMessages.ts): stream callbacks
92
+ // that land inside one React batch window must route against fresh state.
93
+ const { liveMessages, addStreaming, patch: patchLiveMessage, drain: drainLiveMessages, clear: clearLiveMessages } = useLiveMessages(finalizeMessage);
90
94
  const sessionStartRef = useRef(new Date());
91
95
  // Stable PromptSession object across turns so per-session flags (the
92
96
  // context-fallback warning key) persist; rebuilt when a new session starts,
@@ -250,7 +254,7 @@ function ChatScreen({ debug = false, version, build, continueSession = false, re
250
254
  llmLogRef,
251
255
  contextFileSignaturesRef,
252
256
  setMessages,
253
- setLiveMessagesState,
257
+ clearLiveMessages,
254
258
  setTokenUsage,
255
259
  manualCompaction: () => settings.manualCompaction ?? 'llm-summary',
256
260
  // P1 resume path: an unterminated goal frontier detected on resume becomes
@@ -331,8 +335,12 @@ function ChatScreen({ debug = false, version, build, continueSession = false, re
331
335
  followUps.queue(value);
332
336
  return;
333
337
  }
334
- // Any new submission supersedes a paused-task resume affordance.
335
- if (pausedResume)
338
+ // A new goal or session reset supersedes the paused-goal resume affordance;
339
+ // recovery/configuration commands (compact, model, provider, settings,
340
+ // resume…) intentionally keep it — the pause notice tells the user to run
341
+ // exactly those and then press R (SU-04).
342
+ const isRecoveryCommand = mode !== 'chat' || /^(?:\/compact|\/model|\/provider|\/settings|\/themes|\/resume|\/sessions)\b/.test(value.trim());
343
+ if (pausedResume && !isRecoveryCommand)
336
344
  setPausedResume(undefined);
337
345
  if (await wizard.dispatch(mode, value))
338
346
  return;
@@ -352,7 +360,7 @@ function ChatScreen({ debug = false, version, build, continueSession = false, re
352
360
  newSession: async () => {
353
361
  conversationRef.current = [];
354
362
  lastAssistantTextRef.current = '';
355
- setLiveMessagesState(() => []);
363
+ clearLiveMessages();
356
364
  setMessages([{ role: 'system', text: 'Started fresh. The fog parts.' }]);
357
365
  await sessionLifecycle.startNewSession('New session started.');
358
366
  },
@@ -493,13 +501,6 @@ function ChatScreen({ debug = false, version, build, continueSession = false, re
493
501
  }
494
502
  async function runSingleAgentTurn(value, displayValue, turnOptions = {}, resumeExisting) {
495
503
  const sessionRecorder = sessionRecorderRef.current;
496
- const finalizeMessage = (msg) => {
497
- if (msg.hidden)
498
- return;
499
- const ordered = withDisplayOrder(msg);
500
- setMessages(m => [...m, ordered]);
501
- sessionRecorder.recordUiMessage(ordered);
502
- };
503
504
  // The logical-goal supervisor owns this submission: recoverable-incomplete
504
505
  // physical turns (including step/tool budget boundaries) continue
505
506
  // automatically; per-turn limits stay safety boundaries. An explicit
@@ -513,23 +514,14 @@ function ChatScreen({ debug = false, version, build, continueSession = false, re
513
514
  addMessage: msg => {
514
515
  const ordered = withDisplayOrder(msg);
515
516
  if (ordered.streaming) {
516
- setLiveMessagesState(m => [...m, ordered]);
517
+ addStreaming(ordered);
517
518
  return;
518
519
  }
519
520
  finalizeMessage(ordered);
520
521
  },
521
522
  updateMessage: (id, update) => {
522
- const liveMessage = liveMessagesRef.current.find(msg => msg.id === id);
523
- if (liveMessage) {
524
- const updated = { ...liveMessage, ...update };
525
- if (updated.streaming === false) {
526
- setLiveMessagesState(m => m.filter(msg => msg.id !== id));
527
- finalizeMessage(updated);
528
- return;
529
- }
530
- setLiveMessagesState(m => m.map(msg => msg.id === id ? { ...msg, ...update } : msg));
523
+ if (patchLiveMessage(id, update))
531
524
  return;
532
- }
533
525
  setMessages(m => m.map(msg => msg.id === id ? { ...msg, ...update } : msg));
534
526
  },
535
527
  setConversation: msgs => {
@@ -567,13 +559,17 @@ function ChatScreen({ debug = false, version, build, continueSession = false, re
567
559
  });
568
560
  await sessionRecorder.flush().catch(showPersistenceWarning);
569
561
  await llmLogRef.current?.writer?.flush().catch(showPersistenceWarning);
562
+ // Turn boundary: an aborted or forcibly-settled attempt is quarantined
563
+ // before it can emit the finalizing update, so settle anything still in
564
+ // the live tail now; the streamed text is preserved verbatim in <Static>.
565
+ drainLiveMessages();
570
566
  // Only a genuinely paused goal (supervisor already attempted automatic
571
567
  // continuation) exposes the one-key resume affordance; it stays until the
572
568
  // user submits something else.
573
569
  if (goalResult.resume?.kind === 'model-stream-idle')
574
570
  setPausedResume({ kind: 'model-stream-idle', request: goalResult.resume.request, retryAttempt: goalResult.resume.retryAttempt });
575
571
  else if (goalResult.resume?.kind === 'incomplete-goal')
576
- setPausedResume({ kind: 'incomplete-goal', request: goalResult.resume.checkpoint.request, retryAttempt: 0, checkpoint: goalResult.resume.checkpoint });
572
+ setPausedResume({ kind: 'incomplete-goal', request: goalResult.resume.checkpoint.request, retryAttempt: 0, checkpoint: goalResult.resume.checkpoint, pauseReason: goalResult.stopReason === 'context-exhausted' || goalResult.stopReason === 'goal-deadline' || goalResult.stopReason === 'no-progress' ? goalResult.stopReason : undefined });
577
573
  else
578
574
  setPausedResume(undefined);
579
575
  return goalResult;
@@ -584,6 +580,9 @@ function ChatScreen({ debug = false, version, build, continueSession = false, re
584
580
  const activeSelection = activeModel(settings);
585
581
  const placeholder = placeholderForMode(mode, busy);
586
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})`
585
+ : '';
587
586
  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.'] }));
588
587
  const workspaceLabel = `${compactHomePath(process.cwd())}${branchName ? ` (${branchName})` : ''}`;
589
588
  const enabledSkillCount = new Set(skills.filter(skill => isSkillEnabled(settings, skill.name, skill.source)).map(skill => skill.name)).size;
@@ -620,7 +619,13 @@ function ChatScreen({ debug = false, version, build, continueSession = false, re
620
619
  // One row for the optional header plus one for the item's bottom margin.
621
620
  const chrome = (item.showHeader === false ? 0 : 1) + 1;
622
621
  return _jsx(MessageView, { message: item.message, width: contentWidth, showHeader: item.showHeader, maxVisibleLines: Math.max(1, perStreamingItemRows - chrome) }, item.key);
623
- }) }), 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' ? 'Unfinished goal paused (no measurable progress)' : '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: () => {
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: () => {
624
629
  if (!tasksExpanded) {
625
630
  setTaskBarPadding(0);
626
631
  setTasksExpanded(true);
@@ -636,7 +641,7 @@ function ChatScreen({ debug = false, version, build, continueSession = false, re
636
641
  cancelThinking();
637
642
  else
638
643
  closeInputList();
639
- }, 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: _jsx(Text, { color: theme.muted, wrap: "truncate-start", children: activeModelName }) })] })] });
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] }) })] })] });
640
645
  }
641
646
  export async function chatCommand(options = {}) {
642
647
  // Resolve the theme before any Ink output so every component renders with it.
@@ -7,6 +7,8 @@ export const COMMAND_HELP_ENTRIES = [
7
7
  { usage: '/settings open', description: 'Open ~/.haze/settings.json with the OS default app.' },
8
8
  { usage: '/themes', description: 'Choose a terminal theme from the built-in registry (light palettes and oh-my-zsh ports included); applies immediately.' },
9
9
  { usage: '/themes <name>', description: 'Set the theme directly, e.g. /themes robbyrussell. Saved to ~/.haze/settings.json; text already on screen keeps its old colors.' },
10
+ { usage: '/reasoning', description: 'Choose a reasoning effort level (none, minimal, low, medium, high, xhigh) or unset; high is the default and applies from the next turn.' },
11
+ { usage: '/reasoning <level|unset|status>', description: 'Set the reasoning effort directly, clear it with unset (no parameter sent), or show the current level with status. Endpoints without native support ignore the parameter.' },
10
12
  { usage: '/skills', description: 'Manage Markdown skills: generate a custom skill, show info, enable/disable, validate, or remove.' },
11
13
  { usage: '/tips', description: 'Toggle the rotating tips shown under the busy label while the model is thinking.' },
12
14
  { usage: '/fleet [--review] [--profile <name>] [--workers <provider:model>] [--concurrency <n>] [--] <prompt>', description: 'Run genuinely independent tasks through disposable contexts. Runtime enforces profile concurrency, deadlines, and mutation serialization; control guidance is not persisted. Declines non-parallel work.' },
@@ -7,6 +7,7 @@ import { handleFleetCommand } from './fleetCommand.js';
7
7
  import { handleInitCommand } from './initCommand.js';
8
8
  import { handleLogsCommand } from './logsCommand.js';
9
9
  import { handleModelCommand } from './modelCommand.js';
10
+ import { handleReasoningCommand } from './reasoningCommand.js';
10
11
  import { handleThemesCommand } from './themesCommand.js';
11
12
  import { formatSettingsSummary } from './settingsSummary.js';
12
13
  async function ensureSettingsFile(settings) {
@@ -59,6 +60,7 @@ const SLASH_COMMANDS = [
59
60
  return HANDLED;
60
61
  } },
61
62
  { match: exactOrArgs('/themes'), run: async (args, ctx) => await handleThemesCommand(args, ctx) },
63
+ { match: exactOrArgs('/reasoning'), run: async (args, ctx) => await handleReasoningCommand(args, ctx) },
62
64
  { match: exactOrArgs('/fleet'), run: (args, ctx) => handleFleetCommand(args, ctx) },
63
65
  ];
64
66
  export async function handleSlashCommand(value, ctx) {
@@ -41,9 +41,11 @@ export function toolCallSummary(toolName, input) {
41
41
  const edits = Array.isArray(data.edits) ? ` (${data.edits.length} edit${data.edits.length === 1 ? '' : 's'})` : '';
42
42
  return `${toolName} ${data.path}${edits}`;
43
43
  }
44
+ if (toolName === 'replaceInFiles' && typeof data?.needle === 'string')
45
+ return `replaceInFiles "${compact(data.needle, 60)}"${typeof data.path === 'string' && data.path !== '.' ? ` in ${data.path}` : ''}${data.dryRun === false ? '' : ' (dry run)'}`;
44
46
  if (toolName === 'replaceLines' && typeof data?.path === 'string')
45
47
  return `replaceLines ${data.path}:${data.startLine}-${data.endLine}`;
46
- if ((toolName === 'editFile' || toolName === 'replaceLines') && (data == null || (typeof data === 'object' && Object.keys(data).length === 0)))
48
+ if ((toolName === 'editFile' || toolName === 'replaceInFiles' || toolName === 'replaceLines') && (data == null || (typeof data === 'object' && Object.keys(data).length === 0)))
47
49
  return toolName;
48
50
  if (toolName === 'subagent') {
49
51
  const task = typeof data?.objective === 'string' ? data.objective : typeof data?.task === 'string' ? data.task : undefined;
@@ -60,6 +62,8 @@ export function toolCallSummary(toolName, input) {
60
62
  return `lspWorkspaceSymbols "${data.query}"`;
61
63
  if (toolName === 'lspSymbols' && typeof data?.path === 'string')
62
64
  return `lspSymbols ${data.path}`;
65
+ if ((toolName === 'lspFindSymbol' || toolName === 'lspRenameSymbol' || toolName === 'lspSafeDeleteSymbol' || toolName === 'lspDiagnosticsForSymbol') && typeof data?.namePath === 'string')
66
+ return `${toolName} ${typeof data.path === 'string' ? `${data.path}:` : ''}${data.namePath}`;
63
67
  if (toolName === 'lspDiagnostics' && typeof data?.path === 'string')
64
68
  return `lspDiagnostics ${data.path}`;
65
69
  if ((toolName === 'lspDefinition' || toolName === 'lspTypeDefinition' || toolName === 'lspImplementation' || toolName === 'lspReferences') && typeof data?.path === 'string')
@@ -4,16 +4,28 @@
4
4
  * drain when the stream returns false, so a slow/redirected consumer cannot
5
5
  * reorder or lose events and the final result line always lands after all
6
6
  * streamed events.
7
+ *
8
+ * SU-05: stream errors are captured permanently (an asynchronous error after a
9
+ * `true` return has a listener here), so `flush()` rejects and the caller can
10
+ * report an output-delivery failure instead of exiting 0 with a broken stream.
7
11
  */
8
12
  export interface WritableSink {
9
13
  write(chunk: string): boolean;
10
14
  once(event: 'drain' | 'error', listener: () => void): unknown;
11
15
  off?(event: 'drain' | 'error', listener: () => void): unknown;
12
16
  }
17
+ /**
18
+ * Queue a best-effort event write without creating an unhandled rejection.
19
+ * NdjsonSink retains the first delivery error, so the caller's final flush still
20
+ * reports failure and can return a non-zero exit code.
21
+ */
22
+ export declare function queueNdjsonWrite(sink: NdjsonSink, value: unknown): void;
13
23
  export declare class NdjsonSink {
14
24
  private readonly stream;
15
25
  private tail;
16
26
  private firstError;
27
+ private pendingLines;
28
+ private permanentError;
17
29
  constructor(stream: WritableSink);
18
30
  /** Serialize one value as an NDJSON line, preserving order and awaiting drain. */
19
31
  write(value: unknown): Promise<void>;
@@ -1,17 +1,44 @@
1
+ /** Upper bound on queued lines: an unbounded producer would grow without limit under a stalled consumer. */
2
+ const MAX_PENDING_LINES = 1000;
3
+ /**
4
+ * Queue a best-effort event write without creating an unhandled rejection.
5
+ * NdjsonSink retains the first delivery error, so the caller's final flush still
6
+ * reports failure and can return a non-zero exit code.
7
+ */
8
+ export function queueNdjsonWrite(sink, value) {
9
+ void sink.write(value).catch(() => undefined);
10
+ }
1
11
  export class NdjsonSink {
2
12
  stream;
3
13
  tail = Promise.resolve();
4
14
  firstError;
15
+ pendingLines = 0;
16
+ permanentError;
5
17
  constructor(stream) {
6
18
  this.stream = stream;
19
+ // Permanent stream-error capture: errors between writes (true returns) or
20
+ // after close also fail the flush instead of vanishing (SU-05).
21
+ stream.once('error', () => {
22
+ this.permanentError ??= new Error('output stream failed');
23
+ });
7
24
  }
8
25
  /** Serialize one value as an NDJSON line, preserving order and awaiting drain. */
9
26
  write(value) {
10
27
  const line = `${JSON.stringify(value)}\n`;
28
+ if (this.permanentError)
29
+ return Promise.reject(this.permanentError);
30
+ if (this.pendingLines >= MAX_PENDING_LINES) {
31
+ const error = new Error(`output stream stalled; more than ${MAX_PENDING_LINES} lines are waiting to drain`);
32
+ this.permanentError ??= error;
33
+ return Promise.reject(error);
34
+ }
35
+ this.pendingLines += 1;
11
36
  const next = this.tail.then(() => this.writeLine(line));
12
37
  // Keep the chain draining even if one line fails; surface the first error on flush.
13
38
  this.tail = next.catch(error => {
14
39
  this.firstError ??= error instanceof Error ? error : new Error(String(error));
40
+ }).finally(() => {
41
+ this.pendingLines -= 1;
15
42
  });
16
43
  return next;
17
44
  }
@@ -32,6 +59,8 @@ export class NdjsonSink {
32
59
  /** Wait for every queued line to finish writing. Rejects on the first error. */
33
60
  async flush() {
34
61
  await this.tail;
62
+ if (this.permanentError)
63
+ throw this.permanentError;
35
64
  if (this.firstError)
36
65
  throw this.firstError;
37
66
  }
@@ -0,0 +1,35 @@
1
+ import type { HazeSettings } from '../../config/settings.js';
2
+ import type { CommandContext, CommandResult } from './commands.js';
3
+ /**
4
+ * `/reasoning` — reasoning-effort picker and direct set, modeled on
5
+ * `/themes`. The picker is one step in the `wizardFlow.ts` table (mode
6
+ * `reasoning`); this module holds the pure result function shared by the
7
+ * slash path and the wizard submit handler. The setting applies from the next
8
+ * turn (reasoning is resolved once per attempt in `attemptSetup`).
9
+ */
10
+ /** Picker value that clears the setting (also accepted as `off` on the slash path). */
11
+ export declare const REASONING_UNSET = "unset";
12
+ export type ReasoningCommandResult = {
13
+ action: 'status';
14
+ message: string;
15
+ } | {
16
+ action: 'set';
17
+ settingsPatch: HazeSettings;
18
+ message: string;
19
+ } | {
20
+ action: 'clear';
21
+ settingsPatch: HazeSettings;
22
+ message: string;
23
+ } | {
24
+ action: 'error';
25
+ message: string;
26
+ } | {
27
+ action: 'open-picker';
28
+ };
29
+ /**
30
+ * Resolve a `/reasoning` invocation against the current setting. Pure: the
31
+ * caller applies `settingsPatch` (a `reasoning: undefined` clear drops the
32
+ * key, because settings writes serialize with `JSON.stringify`).
33
+ */
34
+ export declare function resolveReasoningCommand(args: string, current: unknown): ReasoningCommandResult;
35
+ export declare function handleReasoningCommand(args: string, ctx: CommandContext): Promise<CommandResult>;
@@ -0,0 +1,46 @@
1
+ import { DEFAULT_REASONING_LEVEL, REASONING_LEVELS, REASONING_PROVIDER_DEFAULT, isReasoningLevel, isReasoningUnsetAlias } from '../../core/agent/reasoningPolicy.js';
2
+ /**
3
+ * `/reasoning` — reasoning-effort picker and direct set, modeled on
4
+ * `/themes`. The picker is one step in the `wizardFlow.ts` table (mode
5
+ * `reasoning`); this module holds the pure result function shared by the
6
+ * slash path and the wizard submit handler. The setting applies from the next
7
+ * turn (reasoning is resolved once per attempt in `attemptSetup`).
8
+ */
9
+ /** Picker value that clears the setting (also accepted as `off` on the slash path). */
10
+ export const REASONING_UNSET = 'unset';
11
+ const LEVELS_LIST = REASONING_LEVELS.join(', ');
12
+ /**
13
+ * Resolve a `/reasoning` invocation against the current setting. Pure: the
14
+ * caller applies `settingsPatch` (a `reasoning: undefined` clear drops the
15
+ * key, because settings writes serialize with `JSON.stringify`).
16
+ */
17
+ export function resolveReasoningCommand(args, current) {
18
+ const value = args.trim().toLowerCase();
19
+ if (!value)
20
+ return { action: 'open-picker' };
21
+ if (value === 'status') {
22
+ const level = isReasoningLevel(current) ? current : DEFAULT_REASONING_LEVEL;
23
+ return { action: 'status', message: `Reasoning effort: ${level}${current === level ? '' : ` (default ${DEFAULT_REASONING_LEVEL})`}. Sent as the model's reasoning parameter. Change with /reasoning <level>, /reasoning unset for the provider default, or /reasoning none to turn reasoning off. Levels: ${LEVELS_LIST}.` };
24
+ }
25
+ if (isReasoningUnsetAlias(value)) {
26
+ return { action: 'clear', settingsPatch: { reasoning: REASONING_PROVIDER_DEFAULT }, message: `Reasoning effort unset. No reasoning parameter is sent from the next turn; the provider default applies.` };
27
+ }
28
+ if (!isReasoningLevel(value)) {
29
+ return { action: 'error', message: `Unknown reasoning level "${value}". Valid levels: ${LEVELS_LIST} — or ${REASONING_UNSET} for the provider default.` };
30
+ }
31
+ return { action: 'set', settingsPatch: { reasoning: value }, message: `Reasoning effort set to ${value}. Saved to ~/.haze/settings.json; applies from the next turn. Endpoints without native support ignore the parameter.` };
32
+ }
33
+ export async function handleReasoningCommand(args, ctx) {
34
+ if (!args.trim()) {
35
+ ctx.setMode('reasoning');
36
+ ctx.addSystemMessage('Choose a reasoning effort level. Selecting one saves it to ~/.haze/settings.json and applies from the next turn; unset sends no reasoning parameter (provider default).');
37
+ return 'handled';
38
+ }
39
+ const result = resolveReasoningCommand(args, ctx.settings.reasoning);
40
+ if (result.action === 'set' || result.action === 'clear')
41
+ await ctx.updateSettings(result.settingsPatch);
42
+ // Unreachable (args are non-empty here) but narrows the open-picker variant away.
43
+ if (result.action !== 'open-picker')
44
+ ctx.addSystemMessage(result.message);
45
+ return 'handled';
46
+ }
@@ -1,7 +1,10 @@
1
+ import { type StoredReasoningSetting } from '../../core/agent/reasoningPolicy.js';
1
2
  export type HeadlessOutput = 'text' | 'json' | 'stream-json';
2
3
  export interface HeadlessOptions {
3
4
  prompt: string;
4
5
  modelOverride?: string;
6
+ /** Raw `--reasoning` value (level or unset alias); validated in `runHeadless` so the error path is testable. */
7
+ reasoning?: string;
5
8
  resumeSessionId?: string;
6
9
  output: HeadlessOutput;
7
10
  debug?: boolean;
@@ -19,4 +22,15 @@ export interface HeadlessUsage {
19
22
  }
20
23
  /** Parse a `--timeout` duration like `30s`, `10m`, `2h`, or raw ms. Throws on invalid input. */
21
24
  export declare function parseTurnTimeoutMs(raw: string | undefined): number | undefined;
25
+ /**
26
+ * Resolve the model the run will use *before* invoking the agent, so a bad `--model`
27
+ * selector or a missing provider produces a precise error (not the generic no-provider
28
+ * message) with a non-zero exit. Returns an error string when the run cannot proceed.
29
+ */
30
+ /** Parse a `--reasoning` value into the run-scoped override. Returns an error string when invalid. */
31
+ export declare function parseHeadlessReasoning(raw: string | undefined): {
32
+ setting: StoredReasoningSetting | undefined;
33
+ } | {
34
+ error: string;
35
+ };
22
36
  export declare function runHeadless(options: HeadlessOptions): Promise<number>;
@@ -1,5 +1,6 @@
1
1
  import { readContextFiles } from '../../config/contextFiles.js';
2
2
  import { runAgentGoal } from './streaming/goalSupervisor.js';
3
+ import { parseReasoningOverride } from '../../core/agent/reasoningPolicy.js';
3
4
  import { EMPTY_TOKEN_USAGE, accumulateTokenUsage } from '../chat/turnState.js';
4
5
  import { readSettings } from '../../config/settings.js';
5
6
  import { activeModel, modelSelector, resolveModelSelector } from '../../config/providers.js';
@@ -10,7 +11,7 @@ import { compactModelMessages } from '../../core/agent/compaction.js';
10
11
  import { FALLBACK_CONTEXT_WINDOW_TOKENS } from '../../core/agent/contextBudget.js';
11
12
  import { teardownBackgroundProcesses } from '../../core/process/backgroundRegistry.js';
12
13
  import { MAX_TURN_DEADLINE_MS } from '../../core/agent/budgets.js';
13
- import { NdjsonSink } from './ndjsonSink.js';
14
+ import { NdjsonSink, queueNdjsonWrite } from './ndjsonSink.js';
14
15
  function pinnedUsage(usage) {
15
16
  // Normalize every field to a number: TokenUsage seeds most fields to 0 but
16
17
  // inputTokens/outputTokens may be undefined until the first report. A uniform ?? 0
@@ -116,6 +117,13 @@ function messageUpdateDelta(event, emitted) {
116
117
  * selector or a missing provider produces a precise error (not the generic no-provider
117
118
  * message) with a non-zero exit. Returns an error string when the run cannot proceed.
118
119
  */
120
+ /** Parse a `--reasoning` value into the run-scoped override. Returns an error string when invalid. */
121
+ export function parseHeadlessReasoning(raw) {
122
+ if (raw === undefined || raw.trim() === '')
123
+ return { setting: undefined };
124
+ const parsed = parseReasoningOverride(raw);
125
+ return parsed.ok ? { setting: parsed.setting } : { error: parsed.error };
126
+ }
119
127
  async function resolveModelOrError(modelOverride) {
120
128
  const settings = await readSettings();
121
129
  const override = modelOverride?.trim();
@@ -148,6 +156,11 @@ export async function runHeadless(options) {
148
156
  process.stderr.write(`No session named ${options.resumeSessionId} exists for this workspace.\n`);
149
157
  return 1;
150
158
  }
159
+ const reasoning = parseHeadlessReasoning(options.reasoning);
160
+ if ('error' in reasoning) {
161
+ process.stderr.write(`${reasoning.error}\n`);
162
+ return 2;
163
+ }
151
164
  const modelError = await resolveModelOrError(options.modelOverride);
152
165
  if (modelError) {
153
166
  process.stderr.write(`${modelError}\n`);
@@ -185,14 +198,14 @@ export async function runHeadless(options) {
185
198
  if (event.type === 'message_update') {
186
199
  const delta = messageUpdateDelta(event, emittedSegmentText);
187
200
  if (delta)
188
- void streamSink.write(delta);
201
+ queueNdjsonWrite(streamSink, delta);
189
202
  return;
190
203
  }
191
204
  if (event.type === 'message_end')
192
205
  emittedSegmentText.delete(event.id);
193
206
  const headlessEvent = toHeadlessStreamEvent(event);
194
207
  if (headlessEvent)
195
- void streamSink.write(headlessEvent);
208
+ queueNdjsonWrite(streamSink, headlessEvent);
196
209
  }
197
210
  : undefined;
198
211
  // Bounded, cross-output-mode collection of gate decisions and pauses so
@@ -270,6 +283,7 @@ export async function runHeadless(options) {
270
283
  callbacks,
271
284
  session,
272
285
  modelOverride: options.modelOverride,
286
+ ...(reasoning.setting !== undefined ? { reasoningOverride: reasoning.setting } : {}),
273
287
  ...(turnDeadlineMs != null ? { goalDeadlineMs: Math.max(1, deadlineAt - Date.now()) } : {}),
274
288
  ...(relaunchOptions.resumeFrom ? { resumeFrom: relaunchOptions.resumeFrom } : {}),
275
289
  ...(relaunchOptions.conversationCarriesRequest ? { conversationCarriesRequest: true } : {}),
@@ -296,12 +310,11 @@ export async function runHeadless(options) {
296
310
  callbacks.onEvent?.(agentEvent({ type: 'goal_resume', goalId: `relaunch-${relaunches}`, relaunch: relaunches, stopReason: goalResult.stopReason, reason: `transient ${goalResult.stopReason}; relaunching with ${delayMs}ms backoff` }));
297
311
  process.stderr.write(`haze --until-done: ${goalResult.stopReason} on cycle ${goalResult.cycles}; relaunching (attempt ${relaunches}, backoff ${delayMs}ms).\n`);
298
312
  await new Promise(resolve => setTimeout(resolve, delayMs));
299
- // A paused checkpoint (idle stall) resumes it; a hard model error has
300
- // no checkpoint, but the conversation is preserved — re-enter against
301
- // it without duplicating the user request.
313
+ // Relaunch with the same obligations and history. A new bounded retry
314
+ // pool is intentional after headless backoff, not a new user request.
302
315
  goalResult = await runOnce({
303
- ...(goalResult.resume?.kind === 'incomplete-goal' ? { resumeFrom: goalResult.resume } : {}),
304
- ...(goalResult.resume ? {} : { conversationCarriesRequest: conversation.length > 0 }),
316
+ ...(goalResult.resume ? { resumeFrom: goalResult.resume.kind === 'model-stream-idle' ? { ...goalResult.resume, retryAttempt: 0 } : goalResult.resume } : {}),
317
+ conversationCarriesRequest: conversation.length > 0,
305
318
  });
306
319
  }
307
320
  }
@@ -336,16 +349,29 @@ export async function runHeadless(options) {
336
349
  if (options.output === 'json' || options.output === 'stream-json') {
337
350
  // For stream-json the authoritative agent events have already streamed; flush
338
351
  // them before the terminal result so ordering is preserved under backpressure.
352
+ // A broken output stream is a delivery failure: report it and exit non-zero
353
+ // instead of claiming success with an unusable stream (SU-05).
354
+ let outputError;
339
355
  if (streamSink)
340
- await streamSink.flush().catch(() => undefined);
356
+ await streamSink.flush().catch(error => {
357
+ outputError = error instanceof Error ? error.message : String(error);
358
+ });
341
359
  // This terminal line is byte-identical to the --output json envelope, so harnesses can parse the last line the same way.
342
360
  const resultLine = { type: 'result', status, result, usage: pinnedUsage(usage), ...(evidence ? { evidence } : {}), ...(goal ? { goal } : {}), ...(goalNotices.length > 0 ? { notices: goalNotices.slice(-5) } : {}) };
343
361
  if (streamSink)
344
- await streamSink.write(resultLine).catch(() => undefined);
362
+ await streamSink.write(resultLine).catch(error => {
363
+ outputError ??= error instanceof Error ? error.message : String(error);
364
+ });
345
365
  else
346
366
  writeNdjson(resultLine);
347
367
  if (streamSink)
348
- await streamSink.flush().catch(() => undefined);
368
+ await streamSink.flush().catch(error => {
369
+ outputError ??= error instanceof Error ? error.message : String(error);
370
+ });
371
+ if (outputError) {
372
+ process.stderr.write(`haze output error: failed to deliver stream-json output (${outputError}).\n`);
373
+ return 1;
374
+ }
349
375
  }
350
376
  else if (status === 'complete') {
351
377
  process.stdout.write(result + (result.endsWith('\n') ? '' : '\n'));
@@ -3,6 +3,7 @@ import { configuredLspServers } from '../../config/lspSettings.js';
3
3
  import { configuredMcpServers } from '../../config/mcpSettings.js';
4
4
  import { activeProvider as resolveActiveProvider, configuredProviders, providerHasKey, providerImageCapable } from '../../config/providers.js';
5
5
  import { isSkillEnabled } from '../../config/skillSettings.js';
6
+ import { DEFAULT_REASONING_LEVEL, isReasoningLevel, REASONING_PROVIDER_DEFAULT } from '../../core/agent/reasoningPolicy.js';
6
7
  import { DEFAULT_THEME_NAME } from '../../ui/theme.js';
7
8
  import { loadSkillRegistry } from '../../skills/SkillRegistry.js';
8
9
  export async function formatSettingsSummary(settings, contextFiles) {
@@ -32,6 +33,7 @@ export async function formatSettingsSummary(settings, contextFiles) {
32
33
  `Base URL: ${activeProvider?.url ?? settings.baseURL ?? 'not configured'}`,
33
34
  `API key: ${activeProvider && providerHasKey(settings, activeProvider) ? 'saved' : 'missing'}`,
34
35
  `Theme: ${settings.theme ?? `${DEFAULT_THEME_NAME} (default)`}`,
36
+ `Reasoning: ${isReasoningLevel(settings.reasoning) ? settings.reasoning : settings.reasoning === REASONING_PROVIDER_DEFAULT ? 'provider default (no parameter sent)' : `${DEFAULT_REASONING_LEVEL} (default)`}`,
35
37
  `Configured providers: ${providers.map(provider => `${provider.name}${providerImageCapable(provider) ? ' (images)' : ''}`).join(', ') || 'none'}`,
36
38
  `LSP servers: ${lspServers.map(server => `${server.name}${server.enabled === false ? ' (disabled)' : ''}`).join(', ') || 'none'}`,
37
39
  `MCP servers: ${configuredMcpServers(settings).map(server => `${server.name}${server.enabled === false ? ' (disabled)' : ''}`).join(', ') || 'none'}`,
@@ -8,6 +8,7 @@ import type { SessionGoal } from '../../../core/agent/goalPolicy.js';
8
8
  import { type AgentAttemptResult } from './attemptOutcome.js';
9
9
  import type { AttemptCleanupRegistry } from './attemptLifecycle.js';
10
10
  import type { TurnAbortCause } from './abortCause.js';
11
+ import type { StoredReasoningSetting } from '../../../core/agent/reasoningPolicy.js';
11
12
  import type { StreamCallbacks, TurnExecutionOptions } from '../streaming.js';
12
13
  export interface AgentAttemptInput {
13
14
  value: string;
@@ -23,6 +24,8 @@ export interface AgentAttemptInput {
23
24
  progressSinceLastRetry: boolean;
24
25
  session: PromptSession | undefined;
25
26
  modelOverride: string | undefined;
27
+ /** Run-scoped reasoning level/sentinel (CLI `--reasoning`); overrides the stored setting for this run. */
28
+ reasoningOverride: StoredReasoningSetting | undefined;
26
29
  abortController: AbortController;
27
30
  turnOptions: TurnExecutionOptions;
28
31
  turnScope: {
@@ -15,7 +15,7 @@ import { ATTEMPT_TEARDOWN_BOUND_MS } from './attemptLifecycle.js';
15
15
  * display are always torn down.
16
16
  */
17
17
  export async function runAgentAttempt(input) {
18
- const { value, contextFiles, callbacks, retryingExistingRequest, session, modelOverride, abortController, turnOptions, turnScope, turnState, turnBudget, globalBudget, sliceBudget, goal, abortCause, cleanup, remainingTurnDeadlineMs, usageAnchor } = input;
18
+ const { value, contextFiles, callbacks, retryingExistingRequest, session, modelOverride, reasoningOverride, abortController, turnOptions, turnScope, turnState, turnBudget, globalBudget, sliceBudget, goal, abortCause, cleanup, remainingTurnDeadlineMs, usageAnchor } = input;
19
19
  // Pillar 1.3: progress since the previous retry resets the shared retry pool
20
20
  // (mirrors a per-burst budget), applied to both the stall guard's retry
21
21
  // eligibility and the failure classification below.
@@ -47,7 +47,7 @@ export async function runAgentAttempt(input) {
47
47
  let stallGuard;
48
48
  let setup;
49
49
  try {
50
- setup = await prepareAttempt({ value, contextFiles, callbacks, retryingExistingRequest, overflowShrinkFactor: input.overflowShrinkFactor, session, modelOverride, abortController, turnOptions, turnScope, turnBudget, globalBudget, sliceBudget, goal, onContextFileRead: path => toolDisplay.addContextFileRead(path), usageAnchor });
50
+ setup = await prepareAttempt({ value, contextFiles, callbacks, retryingExistingRequest, overflowShrinkFactor: input.overflowShrinkFactor, session, modelOverride, reasoningOverride, abortController, turnOptions, turnScope, turnBudget, globalBudget, sliceBudget, goal, onContextFileRead: path => toolDisplay.addContextFileRead(path), usageAnchor });
51
51
  if (!setup)
52
52
  return { status: 'failed' };
53
53
  const attemptSetupResult = setup;
@@ -1,13 +1,6 @@
1
1
  import type { StreamCallbacks } from '../streaming.js';
2
2
  import type { ToolGroupRenderer } from './toolGroupRenderer.js';
3
3
  import type { AttemptLoopState } from './streamLoop.js';
4
- /**
5
- * Assistant segment lifecycle (extracted from streamLoop.ts): one segment is
6
- * the text between tool calls (or the final answer). Segments start lazily
7
- * (gated by `shouldStartAssistantStream`), finalize with duplicate/lead-in
8
- * suppression, and reset for the next segment.
9
- */
10
- export declare function resetAssistantSegment(loopState: AttemptLoopState): void;
11
4
  export declare function finalizeAssistantSegment(loopState: AttemptLoopState, callbacks: StreamCallbacks, options?: {
12
5
  beforeTool?: boolean;
13
6
  }): boolean;
@@ -7,7 +7,7 @@ import { responseCompletionMetrics } from './turnRuntime.js';
7
7
  * (gated by `shouldStartAssistantStream`), finalize with duplicate/lead-in
8
8
  * suppression, and reset for the next segment.
9
9
  */
10
- export function resetAssistantSegment(loopState) {
10
+ function resetAssistantSegment(loopState) {
11
11
  loopState.currentAssistantId = `assistant-${Date.now()}-${Math.random().toString(36).slice(2)}`;
12
12
  loopState.assistantStarted = false;
13
13
  loopState.assistantStartedAt = Date.now();