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