@denizokcu/haze 1.1.1 → 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.
- package/CHANGELOG.md +78 -0
- package/README.md +26 -15
- package/SECURITY.md +1 -1
- package/bin/haze.js +27 -7
- package/dist/buildInfo.json +3 -3
- package/dist/cli/chat/inputSuggestions.js +3 -0
- package/dist/cli/chat/liveMessages.d.ts +36 -0
- package/dist/cli/chat/liveMessages.js +64 -0
- package/dist/cli/chat/sessionLifecycle.d.ts +2 -1
- package/dist/cli/chat/sessionLifecycle.js +25 -2
- package/dist/cli/chat/sessionRecorder.d.ts +7 -0
- package/dist/cli/chat/sessionRecorder.js +6 -0
- package/dist/cli/chat/wizard/sessionThemeHandlers.d.ts +1 -1
- package/dist/cli/chat/wizard/sessionThemeHandlers.js +16 -1
- package/dist/cli/commands/chat.js +63 -36
- package/dist/cli/commands/commandHelp.js +2 -0
- package/dist/cli/commands/commands.js +2 -0
- package/dist/cli/commands/formatters.js +5 -1
- package/dist/cli/commands/ndjsonSink.d.ts +12 -0
- package/dist/cli/commands/ndjsonSink.js +29 -0
- package/dist/cli/commands/reasoningCommand.d.ts +35 -0
- package/dist/cli/commands/reasoningCommand.js +46 -0
- package/dist/cli/commands/runCommand.d.ts +14 -0
- package/dist/cli/commands/runCommand.js +43 -11
- package/dist/cli/commands/settingsSummary.js +2 -0
- package/dist/cli/commands/streaming/agentAttempt.d.ts +14 -1
- package/dist/cli/commands/streaming/agentAttempt.js +9 -5
- package/dist/cli/commands/streaming/assistantSegments.d.ts +0 -7
- package/dist/cli/commands/streaming/assistantSegments.js +1 -1
- package/dist/cli/commands/streaming/attemptLifecycle.js +13 -9
- package/dist/cli/commands/streaming/attemptOutcome.d.ts +23 -3
- package/dist/cli/commands/streaming/attemptOutcome.js +64 -11
- package/dist/cli/commands/streaming/attemptSetup.d.ts +13 -3
- package/dist/cli/commands/streaming/attemptSetup.js +40 -15
- package/dist/cli/commands/streaming/goalCheckpoint.d.ts +6 -0
- package/dist/cli/commands/streaming/goalCheckpoint.js +1 -0
- package/dist/cli/commands/streaming/goalSupervisor.d.ts +6 -1
- package/dist/cli/commands/streaming/goalSupervisor.js +18 -4
- package/dist/cli/commands/streaming/prepareStep.d.ts +6 -4
- package/dist/cli/commands/streaming/prepareStep.js +43 -22
- package/dist/cli/commands/streaming/stallRecovery.js +2 -2
- package/dist/cli/commands/streaming/streamLoop.d.ts +31 -4
- package/dist/cli/commands/streaming/streamLoop.js +280 -44
- package/dist/cli/commands/streaming/toolPartHandlers.js +13 -0
- package/dist/cli/commands/streaming/turnRuntime.d.ts +1 -1
- package/dist/cli/commands/streaming/turnRuntime.js +3 -2
- package/dist/cli/commands/streaming.d.ts +15 -2
- package/dist/cli/commands/streaming.js +37 -8
- package/dist/cli/commands/wizardFlow.d.ts +7 -0
- package/dist/cli/commands/wizardFlow.js +22 -0
- package/dist/cli/index.js +8 -3
- package/dist/config/modelCatalog.d.ts +32 -0
- package/dist/config/modelCatalog.js +84 -0
- package/dist/config/modelDiscovery.js +68 -5
- package/dist/config/settings.d.ts +18 -6
- package/dist/config/settings.js +11 -1
- package/dist/core/agent/budgets.d.ts +10 -2
- package/dist/core/agent/budgets.js +10 -2
- package/dist/core/agent/compaction.d.ts +42 -3
- package/dist/core/agent/compaction.js +53 -5
- package/dist/core/agent/completionController.d.ts +11 -1
- package/dist/core/agent/completionController.js +33 -0
- package/dist/core/agent/contextBudget.d.ts +56 -0
- package/dist/core/agent/contextBudget.js +53 -0
- package/dist/core/agent/errors.js +2 -2
- package/dist/core/agent/events.d.ts +26 -2
- package/dist/core/agent/goalPolicy.d.ts +7 -0
- package/dist/core/agent/goalPolicy.js +9 -0
- package/dist/core/agent/overflow.d.ts +45 -0
- package/dist/core/agent/overflow.js +91 -0
- package/dist/core/agent/reasoningPolicy.d.ts +45 -9
- package/dist/core/agent/reasoningPolicy.js +49 -9
- package/dist/core/agent/requestAssembly.d.ts +7 -0
- package/dist/core/agent/requestAssembly.js +15 -7
- package/dist/core/agent/toolCapabilities.d.ts +3 -3
- package/dist/core/agent/toolCapabilities.js +31 -7
- package/dist/core/agent/workState.d.ts +6 -4
- package/dist/core/agent/workState.js +53 -29
- package/dist/core/deadline.js +22 -24
- package/dist/core/safety/secretPaths.js +10 -7
- package/dist/core/safety/shellClassifier.d.ts +18 -0
- package/dist/core/safety/shellClassifier.js +39 -0
- package/dist/core/session/sessionSlimming.d.ts +2 -0
- package/dist/core/session/sessionSlimming.js +50 -1
- package/dist/core/session/sessionStore.d.ts +14 -8
- package/dist/core/session/sessionStore.js +59 -32
- package/dist/core/shellOutput/reducers/git.js +7 -2
- package/dist/core/shellOutput/reducers/validation.d.ts +1 -1
- package/dist/core/shellOutput/reducers/validation.js +14 -1
- package/dist/core/shellOutput/registry.js +3 -2
- package/dist/core/subagent/contracts.d.ts +8 -1
- package/dist/core/subagent/subagentRunner.d.ts +4 -0
- package/dist/core/subagent/subagentRunner.js +33 -25
- package/dist/core/tasks/taskStorage.js +8 -1
- package/dist/core/validation/outputParser.d.ts +1 -1
- package/dist/core/validation/outputParser.js +30 -1
- package/dist/llm/client.d.ts +4 -3
- package/dist/llm/client.js +34 -16
- package/dist/llm/hazeTools.d.ts +2039 -16
- package/dist/llm/hazeTools.js +43 -2
- package/dist/llm/lsp/client.d.ts +7 -1
- package/dist/llm/lsp/client.js +58 -9
- package/dist/llm/lsp/pool.d.ts +11 -0
- package/dist/llm/lsp/pool.js +61 -4
- package/dist/llm/lsp/protocol.d.ts +6 -23
- package/dist/llm/lsp/requests.d.ts +54 -60
- package/dist/llm/lsp/requests.js +152 -28
- package/dist/llm/lsp/symbols.d.ts +16 -0
- package/dist/llm/lsp/symbols.js +70 -0
- package/dist/llm/lsp/workspaceEdit.d.ts +43 -0
- package/dist/llm/lsp/workspaceEdit.js +117 -0
- package/dist/llm/lspTools.d.ts +7518 -2859
- package/dist/llm/lspTools.js +195 -110
- package/dist/llm/requestContext.d.ts +3 -2
- package/dist/llm/requestContext.js +8 -4
- package/dist/llm/systemPrompt.js +2 -2
- package/dist/llm/tools/fetchTool.d.ts +4 -0
- package/dist/llm/tools/processTool.d.ts +4 -0
- package/dist/llm/tools/replaceInFiles.d.ts +105 -0
- package/dist/llm/tools/replaceInFiles.js +131 -0
- package/dist/llm/tools/shellTool.d.ts +4 -0
- package/dist/llm/tools/shellTool.js +27 -8
- package/dist/llm/tools/storedOutputTool.d.ts +4 -0
- package/dist/llm/tools/taskTool.d.ts +4 -0
- package/dist/llm/tools/toolContext.d.ts +3 -0
- package/dist/llm/tools/toolContext.js +26 -4
- package/dist/skills/SkillLoader.js +27 -1
- package/dist/ui/components/TextInput.d.ts +18 -1
- package/dist/ui/components/TextInput.js +44 -6
- package/dist/ui/components/useInputSuggestions.js +18 -6
- package/dist/utils/buildInfo.js +29 -8
- package/dist/utils/fs.js +5 -1
- package/package.json +20 -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
|
-
|
|
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
|
-
//
|
|
335
|
-
|
|
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
|
-
|
|
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
|
-
|
|
517
|
+
addStreaming(ordered);
|
|
517
518
|
return;
|
|
518
519
|
}
|
|
519
520
|
finalizeMessage(ordered);
|
|
520
521
|
},
|
|
521
522
|
updateMessage: (id, update) => {
|
|
522
|
-
|
|
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 => {
|
|
@@ -548,6 +540,7 @@ function ChatScreen({ debug = false, version, build, continueSession = false, re
|
|
|
548
540
|
sessionRecorder.recordWorkState(state);
|
|
549
541
|
},
|
|
550
542
|
compactConversation,
|
|
543
|
+
recordCompaction: entry => sessionRecorder.recordCompactEntry(entry),
|
|
551
544
|
recordTokenUsage: usage => {
|
|
552
545
|
setTokenUsage(current => accumulateTokenUsage(current, usage));
|
|
553
546
|
},
|
|
@@ -566,13 +559,17 @@ function ChatScreen({ debug = false, version, build, continueSession = false, re
|
|
|
566
559
|
});
|
|
567
560
|
await sessionRecorder.flush().catch(showPersistenceWarning);
|
|
568
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();
|
|
569
566
|
// Only a genuinely paused goal (supervisor already attempted automatic
|
|
570
567
|
// continuation) exposes the one-key resume affordance; it stays until the
|
|
571
568
|
// user submits something else.
|
|
572
569
|
if (goalResult.resume?.kind === 'model-stream-idle')
|
|
573
570
|
setPausedResume({ kind: 'model-stream-idle', request: goalResult.resume.request, retryAttempt: goalResult.resume.retryAttempt });
|
|
574
571
|
else if (goalResult.resume?.kind === 'incomplete-goal')
|
|
575
|
-
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 });
|
|
576
573
|
else
|
|
577
574
|
setPausedResume(undefined);
|
|
578
575
|
return goalResult;
|
|
@@ -583,6 +580,9 @@ function ChatScreen({ debug = false, version, build, continueSession = false, re
|
|
|
583
580
|
const activeSelection = activeModel(settings);
|
|
584
581
|
const placeholder = placeholderForMode(mode, busy);
|
|
585
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
|
+
: '';
|
|
586
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.'] }));
|
|
587
587
|
const workspaceLabel = `${compactHomePath(process.cwd())}${branchName ? ` (${branchName})` : ''}`;
|
|
588
588
|
const enabledSkillCount = new Set(skills.filter(skill => isSkillEnabled(settings, skill.name, skill.source)).map(skill => skill.name)).size;
|
|
@@ -619,7 +619,13 @@ function ChatScreen({ debug = false, version, build, continueSession = false, re
|
|
|
619
619
|
// One row for the optional header plus one for the item's bottom margin.
|
|
620
620
|
const chrome = (item.showHeader === false ? 0 : 1) + 1;
|
|
621
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'
|
|
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: () => {
|
|
623
629
|
if (!tasksExpanded) {
|
|
624
630
|
setTaskBarPadding(0);
|
|
625
631
|
setTasksExpanded(true);
|
|
@@ -630,12 +636,12 @@ function ChatScreen({ debug = false, version, build, continueSession = false, re
|
|
|
630
636
|
setTaskBarPadding(Math.max(0, expandedRows - collapsedRows));
|
|
631
637
|
setTasksExpanded(false);
|
|
632
638
|
}
|
|
633
|
-
}, onCancel: cancelThinking, onResumeKey: pausedResume != null && !busy ? resumePausedTask : undefined, onEscape: () => {
|
|
639
|
+
}, onCancel: cancelThinking, onResumeKey: pausedResume != null && !busy ? resumePausedTask : undefined, onInterrupt: () => exit(), onEscape: () => {
|
|
634
640
|
if (busy)
|
|
635
641
|
cancelThinking();
|
|
636
642
|
else
|
|
637
643
|
closeInputList();
|
|
638
|
-
}, 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:
|
|
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] }) })] })] });
|
|
639
645
|
}
|
|
640
646
|
export async function chatCommand(options = {}) {
|
|
641
647
|
// Resolve the theme before any Ink output so every component renders with it.
|
|
@@ -660,7 +666,28 @@ export async function chatCommand(options = {}) {
|
|
|
660
666
|
// Incremental rendering rewrites only changed lines of the live frame, removing
|
|
661
667
|
// the full-frame erase/rewrite flicker while streaming. The fps cap aligns with
|
|
662
668
|
// the ~80ms spinner cadence; faster renders would only repaint unchanged lines.
|
|
663
|
-
|
|
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,
|
|
690
|
+
});
|
|
664
691
|
try {
|
|
665
692
|
await app.waitUntilExit();
|
|
666
693
|
await teardownBackgroundProcesses().catch(() => undefined);
|
|
@@ -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
|
|
@@ -65,6 +66,8 @@ function toHeadlessStreamEvent(event) {
|
|
|
65
66
|
return { type: 'step_start', attempt: event.attempt, step: event.step, at: event.at };
|
|
66
67
|
case 'step_end':
|
|
67
68
|
return { type: 'step_end', attempt: event.attempt, step: event.step, finishReason: event.finishReason, toolCallCount: event.toolCallCount, usage: event.usage, ...(event.responseModel ? { responseModel: event.responseModel } : {}), at: event.at };
|
|
69
|
+
case 'resource_rollover':
|
|
70
|
+
return { type: 'resource_rollover', attempt: event.attempt, completedSteps: event.completedSteps, toolCalls: event.toolCalls, prefixPreserved: event.prefixPreserved, reason: event.reason, at: event.at };
|
|
68
71
|
case 'message_start':
|
|
69
72
|
return { type: 'message_start', id: event.id, role: event.role, at: event.at };
|
|
70
73
|
case 'message_update':
|
|
@@ -88,6 +91,10 @@ function toHeadlessStreamEvent(event) {
|
|
|
88
91
|
return { ...(event.requested ? { requested: event.requested } : {}), type: 'reasoning_policy', effective: event.effective, reason: event.reason, at: event.at };
|
|
89
92
|
case 'context_budget':
|
|
90
93
|
return { type: 'context_budget', contextWindowTokens: event.contextWindowTokens, source: event.source, at: event.at };
|
|
94
|
+
case 'compaction_start':
|
|
95
|
+
return { type: 'compaction_start', reason: event.reason, method: event.method, at: event.at };
|
|
96
|
+
case 'compaction_end':
|
|
97
|
+
return { ...(event.olderCount === undefined ? {} : { olderCount: event.olderCount }), ...(event.keptCount === undefined ? {} : { keptCount: event.keptCount }), ...(event.willRetry === undefined ? {} : { willRetry: event.willRetry }), ...(event.error === undefined ? {} : { error: event.error }), type: 'compaction_end', reason: event.reason, method: event.method, compacted: event.compacted, at: event.at };
|
|
91
98
|
}
|
|
92
99
|
}
|
|
93
100
|
function writeNdjson(value) {
|
|
@@ -110,6 +117,13 @@ function messageUpdateDelta(event, emitted) {
|
|
|
110
117
|
* selector or a missing provider produces a precise error (not the generic no-provider
|
|
111
118
|
* message) with a non-zero exit. Returns an error string when the run cannot proceed.
|
|
112
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
|
+
}
|
|
113
127
|
async function resolveModelOrError(modelOverride) {
|
|
114
128
|
const settings = await readSettings();
|
|
115
129
|
const override = modelOverride?.trim();
|
|
@@ -142,6 +156,11 @@ export async function runHeadless(options) {
|
|
|
142
156
|
process.stderr.write(`No session named ${options.resumeSessionId} exists for this workspace.\n`);
|
|
143
157
|
return 1;
|
|
144
158
|
}
|
|
159
|
+
const reasoning = parseHeadlessReasoning(options.reasoning);
|
|
160
|
+
if ('error' in reasoning) {
|
|
161
|
+
process.stderr.write(`${reasoning.error}\n`);
|
|
162
|
+
return 2;
|
|
163
|
+
}
|
|
145
164
|
const modelError = await resolveModelOrError(options.modelOverride);
|
|
146
165
|
if (modelError) {
|
|
147
166
|
process.stderr.write(`${modelError}\n`);
|
|
@@ -179,14 +198,14 @@ export async function runHeadless(options) {
|
|
|
179
198
|
if (event.type === 'message_update') {
|
|
180
199
|
const delta = messageUpdateDelta(event, emittedSegmentText);
|
|
181
200
|
if (delta)
|
|
182
|
-
|
|
201
|
+
queueNdjsonWrite(streamSink, delta);
|
|
183
202
|
return;
|
|
184
203
|
}
|
|
185
204
|
if (event.type === 'message_end')
|
|
186
205
|
emittedSegmentText.delete(event.id);
|
|
187
206
|
const headlessEvent = toHeadlessStreamEvent(event);
|
|
188
207
|
if (headlessEvent)
|
|
189
|
-
|
|
208
|
+
queueNdjsonWrite(streamSink, headlessEvent);
|
|
190
209
|
}
|
|
191
210
|
: undefined;
|
|
192
211
|
// Bounded, cross-output-mode collection of gate decisions and pauses so
|
|
@@ -264,6 +283,7 @@ export async function runHeadless(options) {
|
|
|
264
283
|
callbacks,
|
|
265
284
|
session,
|
|
266
285
|
modelOverride: options.modelOverride,
|
|
286
|
+
...(reasoning.setting !== undefined ? { reasoningOverride: reasoning.setting } : {}),
|
|
267
287
|
...(turnDeadlineMs != null ? { goalDeadlineMs: Math.max(1, deadlineAt - Date.now()) } : {}),
|
|
268
288
|
...(relaunchOptions.resumeFrom ? { resumeFrom: relaunchOptions.resumeFrom } : {}),
|
|
269
289
|
...(relaunchOptions.conversationCarriesRequest ? { conversationCarriesRequest: true } : {}),
|
|
@@ -290,12 +310,11 @@ export async function runHeadless(options) {
|
|
|
290
310
|
callbacks.onEvent?.(agentEvent({ type: 'goal_resume', goalId: `relaunch-${relaunches}`, relaunch: relaunches, stopReason: goalResult.stopReason, reason: `transient ${goalResult.stopReason}; relaunching with ${delayMs}ms backoff` }));
|
|
291
311
|
process.stderr.write(`haze --until-done: ${goalResult.stopReason} on cycle ${goalResult.cycles}; relaunching (attempt ${relaunches}, backoff ${delayMs}ms).\n`);
|
|
292
312
|
await new Promise(resolve => setTimeout(resolve, delayMs));
|
|
293
|
-
//
|
|
294
|
-
//
|
|
295
|
-
// 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.
|
|
296
315
|
goalResult = await runOnce({
|
|
297
|
-
...(goalResult.resume
|
|
298
|
-
|
|
316
|
+
...(goalResult.resume ? { resumeFrom: goalResult.resume.kind === 'model-stream-idle' ? { ...goalResult.resume, retryAttempt: 0 } : goalResult.resume } : {}),
|
|
317
|
+
conversationCarriesRequest: conversation.length > 0,
|
|
299
318
|
});
|
|
300
319
|
}
|
|
301
320
|
}
|
|
@@ -330,16 +349,29 @@ export async function runHeadless(options) {
|
|
|
330
349
|
if (options.output === 'json' || options.output === 'stream-json') {
|
|
331
350
|
// For stream-json the authoritative agent events have already streamed; flush
|
|
332
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;
|
|
333
355
|
if (streamSink)
|
|
334
|
-
await streamSink.flush().catch(
|
|
356
|
+
await streamSink.flush().catch(error => {
|
|
357
|
+
outputError = error instanceof Error ? error.message : String(error);
|
|
358
|
+
});
|
|
335
359
|
// This terminal line is byte-identical to the --output json envelope, so harnesses can parse the last line the same way.
|
|
336
360
|
const resultLine = { type: 'result', status, result, usage: pinnedUsage(usage), ...(evidence ? { evidence } : {}), ...(goal ? { goal } : {}), ...(goalNotices.length > 0 ? { notices: goalNotices.slice(-5) } : {}) };
|
|
337
361
|
if (streamSink)
|
|
338
|
-
await streamSink.write(resultLine).catch(
|
|
362
|
+
await streamSink.write(resultLine).catch(error => {
|
|
363
|
+
outputError ??= error instanceof Error ? error.message : String(error);
|
|
364
|
+
});
|
|
339
365
|
else
|
|
340
366
|
writeNdjson(resultLine);
|
|
341
367
|
if (streamSink)
|
|
342
|
-
await streamSink.flush().catch(
|
|
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
|
+
}
|
|
343
375
|
}
|
|
344
376
|
else if (status === 'complete') {
|
|
345
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'}`,
|