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