@denizokcu/haze 1.0.0 → 1.1.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 +33 -0
- package/README.md +17 -8
- package/SECURITY.md +3 -1
- package/dist/buildInfo.json +3 -3
- package/dist/cli/chat/TaskBar.js +1 -1
- package/dist/cli/chat/busyIndicator.d.ts +11 -0
- package/dist/cli/chat/busyIndicator.js +34 -0
- package/dist/cli/chat/chatMetrics.d.ts +0 -1
- package/dist/cli/chat/chatMetrics.js +1 -7
- package/dist/cli/chat/followUpQueue.d.ts +11 -0
- package/dist/cli/chat/followUpQueue.js +38 -0
- package/dist/cli/chat/inputSuggestions.js +1 -0
- package/dist/cli/chat/messages.d.ts +0 -22
- package/dist/cli/chat/messages.js +42 -87
- package/dist/cli/chat/sessionLifecycle.d.ts +3 -1
- package/dist/cli/chat/sessionLifecycle.js +6 -1
- package/dist/cli/chat/sessionRecorder.d.ts +2 -0
- package/dist/cli/chat/sessionRecorder.js +6 -0
- package/dist/cli/chat/startupSequence.d.ts +29 -0
- package/dist/cli/chat/startupSequence.js +59 -0
- package/dist/cli/chat/transcriptPartition.d.ts +23 -0
- package/dist/cli/chat/transcriptPartition.js +78 -0
- package/dist/cli/chat/wizard/fieldTransitions.d.ts +38 -0
- package/dist/cli/chat/wizard/fieldTransitions.js +43 -0
- package/dist/cli/chat/wizard/lspHandlers.d.ts +4 -0
- package/dist/cli/chat/wizard/lspHandlers.js +85 -0
- package/dist/cli/chat/wizard/mcpHandlers.d.ts +8 -0
- package/dist/cli/chat/wizard/mcpHandlers.js +82 -0
- package/dist/cli/chat/wizard/providerHandlers.d.ts +12 -0
- package/dist/cli/chat/wizard/providerHandlers.js +420 -0
- package/dist/cli/chat/wizard/sessionThemeHandlers.d.ts +4 -0
- package/dist/cli/chat/wizard/sessionThemeHandlers.js +48 -0
- package/dist/cli/chat/wizard/skillsHandlers.d.ts +4 -0
- package/dist/cli/chat/wizard/skillsHandlers.js +125 -0
- package/dist/cli/chat/wizard/types.d.ts +63 -0
- package/dist/cli/chat/wizard/types.js +24 -0
- package/dist/cli/chat/wizard/uiState.d.ts +56 -0
- package/dist/cli/chat/wizard/uiState.js +15 -0
- package/dist/cli/chat/wizardDispatch.d.ts +11 -113
- package/dist/cli/chat/wizardDispatch.js +41 -805
- package/dist/cli/commands/chat.js +89 -110
- package/dist/cli/commands/commandHelp.js +2 -0
- package/dist/cli/commands/commands.js +2 -0
- package/dist/cli/commands/formatters.d.ts +0 -3
- package/dist/cli/commands/formatters.js +6 -29
- package/dist/cli/commands/runCommand.d.ts +2 -0
- package/dist/cli/commands/runCommand.js +67 -4
- package/dist/cli/commands/settingsSummary.js +2 -0
- package/dist/cli/commands/streaming/assistantSegments.d.ts +19 -0
- package/dist/cli/commands/streaming/assistantSegments.js +48 -0
- package/dist/cli/commands/streaming/attemptOutcome.d.ts +2 -2
- package/dist/cli/commands/streaming/attemptOutcome.js +17 -7
- package/dist/cli/commands/streaming/goalCheckpoint.d.ts +69 -8
- package/dist/cli/commands/streaming/goalCheckpoint.js +36 -1
- package/dist/cli/commands/streaming/goalSupervisor.d.ts +17 -2
- package/dist/cli/commands/streaming/goalSupervisor.js +62 -12
- package/dist/cli/commands/streaming/prepareStep.d.ts +35 -0
- package/dist/cli/commands/streaming/prepareStep.js +100 -0
- package/dist/cli/commands/streaming/recoverySlices.d.ts +15 -0
- package/dist/cli/commands/streaming/recoverySlices.js +29 -0
- package/dist/cli/commands/streaming/stallRecovery.d.ts +0 -1
- package/dist/cli/commands/streaming/stallRecovery.js +0 -4
- package/dist/cli/commands/streaming/streamLoop.js +9 -230
- package/dist/cli/commands/streaming/toolGroupRenderer.js +2 -1
- package/dist/cli/commands/streaming/toolPartHandlers.d.ts +19 -0
- package/dist/cli/commands/streaming/toolPartHandlers.js +95 -0
- package/dist/cli/commands/streaming.d.ts +4 -1
- package/dist/cli/commands/streaming.js +6 -21
- package/dist/cli/commands/themesCommand.d.ts +17 -0
- package/dist/cli/commands/themesCommand.js +24 -0
- package/dist/cli/commands/wizardFlow.d.ts +7 -0
- package/dist/cli/commands/wizardFlow.js +20 -0
- package/dist/cli/index.js +3 -1
- package/dist/config/providerPresets.d.ts +7 -0
- package/dist/config/providerPresets.js +195 -391
- package/dist/config/settings.d.ts +2 -0
- package/dist/config/settings.js +1 -0
- package/dist/core/agent/completionController.d.ts +14 -7
- package/dist/core/agent/completionController.js +12 -6
- package/dist/core/agent/events.d.ts +12 -0
- package/dist/core/agent/goalPolicy.d.ts +4 -3
- package/dist/core/agent/goalPolicy.js +9 -4
- package/dist/core/agent/workState.d.ts +25 -15
- package/dist/core/agent/workState.js +71 -43
- package/dist/core/safety/secretPaths.d.ts +18 -0
- package/dist/core/safety/secretPaths.js +115 -0
- package/dist/core/session/sessionSlimming.js +8 -0
- package/dist/core/session/sessionStore.d.ts +61 -1
- package/dist/core/session/sessionStore.js +115 -6
- package/dist/llm/hazeTools.d.ts +64 -208
- package/dist/llm/hazeTools.js +6 -0
- package/dist/llm/systemPrompt.js +3 -1
- package/dist/llm/toolResultTypes.d.ts +1 -1
- package/dist/llm/tools/failures.d.ts +6 -0
- package/dist/llm/tools/failures.js +8 -2
- package/dist/llm/tools/readRecovery.js +2 -0
- package/dist/llm/tools/shellTool.js +3 -0
- package/dist/llm/tools/taskTool.d.ts +64 -208
- package/dist/llm/tools/taskTool.js +22 -10
- package/dist/llm/tools/workspaceFile.d.ts +4 -3
- package/dist/llm/tools/workspaceFile.js +30 -13
- package/dist/ui/components/Header.js +1 -1
- package/dist/ui/components/MarkdownText.js +10 -10
- package/dist/ui/components/TextInput.d.ts +1 -1
- package/dist/ui/components/TextInput.js +8 -69
- package/dist/ui/components/useInputSuggestions.d.ts +27 -0
- package/dist/ui/components/useInputSuggestions.js +98 -0
- package/dist/ui/terminalColors.d.ts +29 -0
- package/dist/ui/terminalColors.js +47 -0
- package/dist/ui/theme.d.ts +105 -10
- package/dist/ui/theme.js +125 -15
- package/dist/ui/themes/registry.d.ts +5 -0
- package/dist/ui/themes/registry.js +436 -0
- package/dist/utils/format.d.ts +10 -0
- package/dist/utils/format.js +45 -0
- package/package.json +1 -1
|
@@ -1,11 +1,8 @@
|
|
|
1
1
|
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
2
2
|
import { useEffect, useReducer, useRef, useState } from 'react';
|
|
3
|
-
import { execFile as execFileCallback } from 'node:child_process';
|
|
4
|
-
import { promisify } from 'node:util';
|
|
5
3
|
import { Box, render, Static, Text, useApp, useWindowSize } from 'ink';
|
|
6
4
|
import Spinner from 'ink-spinner';
|
|
7
5
|
import { readContextFiles } from '../../config/contextFiles.js';
|
|
8
|
-
import { checkForUpdate } from '../../config/updateCheck.js';
|
|
9
6
|
import { addInputHistoryItem, readInputHistory } from '../../config/inputHistory.js';
|
|
10
7
|
import { loadTasks as loadTasksFromStore, clearTasks as clearTasksFromStore } from '../../core/tasks/taskStorage.js';
|
|
11
8
|
import { readSettings, updateSettings } from '../../config/settings.js';
|
|
@@ -13,50 +10,38 @@ import { activeModel, activeProvider } from '../../config/providers.js';
|
|
|
13
10
|
import { isSkillEnabled } from '../../config/skillSettings.js';
|
|
14
11
|
import { Header } from '../../ui/components/Header.js';
|
|
15
12
|
import { TextInput } from '../../ui/components/TextInput.js';
|
|
16
|
-
import { theme } from '../../ui/theme.js';
|
|
13
|
+
import { setActiveTheme, resolveTheme, theme, DEFAULT_THEME_NAME } from '../../ui/theme.js';
|
|
14
|
+
import { applyTerminalColors, resetTerminalColors } from '../../ui/terminalColors.js';
|
|
17
15
|
import { handleSlashCommand } from './commands.js';
|
|
18
16
|
import { runAgentGoal } from './streaming/goalSupervisor.js';
|
|
19
|
-
import {
|
|
17
|
+
import { checkpointFromGoalFrontier } from './streaming/goalCheckpoint.js';
|
|
18
|
+
import { imageAttachmentLine } from './formatters.js';
|
|
20
19
|
import { imageCapabilityError, IMAGE_ONLY_PROMPT_TEXT, resolveImageAttachments } from '../../core/attachments/imageAttachments.js';
|
|
21
20
|
import { resolveReadBlessings } from '../../core/attachments/readBlessings.js';
|
|
22
21
|
import { endLog as endLlmLog } from '../../core/log/llmLog.js';
|
|
23
22
|
import { loadSkillRegistry } from '../../skills/SkillRegistry.js';
|
|
24
23
|
import { formatSession, listSessions } from '../../core/session/sessionStore.js';
|
|
25
24
|
import { MAX_VISIBLE_TASKS, TaskBar } from '../chat/TaskBar.js';
|
|
26
|
-
import { AssistantMarkdownChunkView, MessageView
|
|
25
|
+
import { AssistantMarkdownChunkView, MessageView } from '../chat/messages.js';
|
|
26
|
+
import { partitionDisplayMessages } from '../chat/transcriptPartition.js';
|
|
27
27
|
import { createSessionRecorder } from '../chat/sessionRecorder.js';
|
|
28
28
|
import { createSessionLifecycle } from '../chat/sessionLifecycle.js';
|
|
29
29
|
import { createWizardDispatch, initialWizardUiState, wizardUiReducer } from '../chat/wizardDispatch.js';
|
|
30
30
|
import { buildContextReport } from '../chat/contextReport.js';
|
|
31
|
-
import { startupContextInfo, startupProviderInfo } from '../chat/startupInfo.js';
|
|
32
31
|
import { TIPS, randomTipIndex, tipsEnabled } from '../chat/tips.js';
|
|
33
32
|
import { fileMentionSuggestions } from '../chat/fileMentionSuggestions.js';
|
|
34
|
-
import { compactHomePath,
|
|
33
|
+
import { compactHomePath, statusBarMetrics } from '../chat/chatMetrics.js';
|
|
34
|
+
import { formatTokenCount } from '../../utils/format.js';
|
|
35
35
|
import { accumulateTokenUsage, EMPTY_TOKEN_USAGE, shouldClearCompletedTasks } from '../chat/turnState.js';
|
|
36
36
|
import { MASKED_MODES, PICKER_MODES, SUBMIT_EMPTY_MODES, placeholderForMode } from './chatModes.js';
|
|
37
37
|
import { inputSuggestionsForState } from '../chat/inputSuggestions.js';
|
|
38
|
+
import { currentBranchName, runStartupSequence } from '../chat/startupSequence.js';
|
|
39
|
+
import { useFollowUpQueue } from '../chat/followUpQueue.js';
|
|
40
|
+
import { useBusyIndicator } from '../chat/busyIndicator.js';
|
|
38
41
|
import { modelThinkingLabel } from '../../utils/modelName.js';
|
|
39
|
-
import { detectCheckoutMismatch, formatMismatchWarning, runtimeCapabilities } from '../../utils/buildInfo.js';
|
|
40
42
|
import { commandParts } from './wizardFlow.js';
|
|
41
43
|
import { backgroundProcessCount, subscribeBackgroundProcesses, teardownBackgroundProcesses } from '../../core/process/backgroundRegistry.js';
|
|
42
44
|
import { MAX_SESSION_PICKER_RESULTS } from './sessionPicker.js';
|
|
43
|
-
const execFile = promisify(execFileCallback);
|
|
44
|
-
async function currentBranchName() {
|
|
45
|
-
try {
|
|
46
|
-
const { stdout } = await execFile('git', ['branch', '--show-current'], { cwd: process.cwd() });
|
|
47
|
-
return stdout.trim() || undefined;
|
|
48
|
-
}
|
|
49
|
-
catch {
|
|
50
|
-
return undefined;
|
|
51
|
-
}
|
|
52
|
-
}
|
|
53
|
-
/** Elapsed-time label for the busy indicator heartbeat, or '' when no turn is active. */
|
|
54
|
-
function busyElapsedLabel(startedAt) {
|
|
55
|
-
if (startedAt == null)
|
|
56
|
-
return '';
|
|
57
|
-
const elapsed = Date.now() - startedAt;
|
|
58
|
-
return elapsed > 0 ? formatElapsedTimeWhole(elapsed) : '';
|
|
59
|
-
}
|
|
60
45
|
function thinkingLabelForSettings(settings) {
|
|
61
46
|
return modelThinkingLabel(activeModel(settings)?.model);
|
|
62
47
|
}
|
|
@@ -114,25 +99,22 @@ function ChatScreen({ debug = false, version, build, continueSession = false, re
|
|
|
114
99
|
const skillErrorSignatureRef = useRef('');
|
|
115
100
|
const projectSkillSignatureRef = useRef('');
|
|
116
101
|
const contextFileSignaturesRef = useRef(new Map());
|
|
117
|
-
const
|
|
102
|
+
const followUps = useFollowUpQueue(text => setMessages(m => [...m, { role: 'system', text }]));
|
|
118
103
|
const [inputHistory, setInputHistory] = useState([]);
|
|
119
104
|
const [debugLogs, setDebugLogs] = useState([]);
|
|
120
105
|
const [contextFiles, setContextFiles] = useState([]);
|
|
121
106
|
const [mode, setMode] = useState('chat');
|
|
122
107
|
const [sessions, setSessions] = useState([]);
|
|
123
|
-
|
|
108
|
+
// Busy indicator with a one-second heartbeat: ticks while haze is working so
|
|
109
|
+
// the developer always sees rolling activity (elapsed turn time) even when
|
|
110
|
+
// the model is thinking with no streamed output and no tool is running.
|
|
111
|
+
const { busy, setBusy: setBusyWithHeartbeat, elapsed: busyElapsed } = useBusyIndicator();
|
|
124
112
|
const [backgroundCount, setBackgroundCount] = useState(backgroundProcessCount);
|
|
125
113
|
const [busyLabel, setBusyLabel] = useState(() => thinkingLabelForSettings(settings));
|
|
126
|
-
// Heartbeat for the busy indicator: ticks every second while haze is working
|
|
127
|
-
// so the developer always sees rolling activity (elapsed turn time) even when
|
|
128
|
-
// the model is thinking with no streamed output and no tool is running.
|
|
129
|
-
const turnStartedAtRef = useRef(undefined);
|
|
130
|
-
const [, setBusyTick] = useState(0);
|
|
131
114
|
const [visibleTasks, setVisibleTasks] = useState([]);
|
|
132
115
|
const [tasksExpanded, setTasksExpanded] = useState(false);
|
|
133
116
|
const [taskBarPadding, setTaskBarPadding] = useState(0);
|
|
134
117
|
const [tokenUsage, setTokenUsage] = useState({ ...EMPTY_TOKEN_USAGE });
|
|
135
|
-
const [queuedFollowUps, setQueuedFollowUps] = useState([]);
|
|
136
118
|
// A genuinely paused goal (no measurable progress, deadline, or a stalled
|
|
137
119
|
// model stream) — automatic continuation has already been attempted by the
|
|
138
120
|
// goal supervisor. Carries what a one-key resume needs; any new submission
|
|
@@ -144,24 +126,7 @@ function ChatScreen({ debug = false, version, build, continueSession = false, re
|
|
|
144
126
|
// this replaced twelve individual useState hooks.
|
|
145
127
|
const [wizardState, updateWizard] = useReducer(wizardUiReducer, undefined, initialWizardUiState);
|
|
146
128
|
const { modelProviderFilter, discoveredModels, suggestedModels, selectedProviderName, providerDraft, selectedSkillName, selectedLspName, selectedMcpName } = wizardState;
|
|
147
|
-
// Wrap setBusy so the busy indicator knows when the turn started, and tick a
|
|
148
|
-
// heartbeat every second while busy so elapsed time keeps rolling. This keeps
|
|
149
|
-
// the UI visibly alive during long model thinking / blocked tool runs where
|
|
150
|
-
// otherwise no streamed output is produced (the "looks stuck" problem).
|
|
151
|
-
const setBusyWithHeartbeat = (nextBusy) => {
|
|
152
|
-
if (nextBusy && !busy)
|
|
153
|
-
turnStartedAtRef.current = Date.now();
|
|
154
|
-
if (!nextBusy)
|
|
155
|
-
turnStartedAtRef.current = undefined;
|
|
156
|
-
setBusy(nextBusy);
|
|
157
|
-
};
|
|
158
129
|
useEffect(() => subscribeBackgroundProcesses(() => setBackgroundCount(backgroundProcessCount())), []);
|
|
159
|
-
useEffect(() => {
|
|
160
|
-
if (!busy)
|
|
161
|
-
return;
|
|
162
|
-
const heartbeat = setInterval(() => setBusyTick(tick => tick + 1), 1000);
|
|
163
|
-
return () => clearInterval(heartbeat);
|
|
164
|
-
}, [busy]);
|
|
165
130
|
// One tip per thinking section, shown under the busy label while the model
|
|
166
131
|
// is purely thinking (no tool running) and the user has not disabled tips.
|
|
167
132
|
// A fresh tip is picked each time the model enters thinking mode; no
|
|
@@ -181,41 +146,41 @@ function ChatScreen({ debug = false, version, build, continueSession = false, re
|
|
|
181
146
|
return;
|
|
182
147
|
currentBranchName().then(setBranchName).catch(() => setBranchName(undefined));
|
|
183
148
|
}, [busy]);
|
|
149
|
+
// Live theme switching: whenever the settings'
|
|
150
|
+
// theme name changes (/themes), re-resolve and adopt it so the whole UI
|
|
151
|
+
// repaints without a restart. Ink <Static> history stays as-rendered, so
|
|
152
|
+
// already-printed text keeps its old colors; the terminal defaults (OSC
|
|
153
|
+
// 10/11) follow the new theme. Skipped until settings have loaded once —
|
|
154
|
+
// chatCommand() already resolved the theme before the first render, and the
|
|
155
|
+
// pre-load {} state would briefly flash the default theme.
|
|
156
|
+
const settingsThemeLoadedRef = useRef(false);
|
|
157
|
+
const activeThemeName = settings.theme ?? DEFAULT_THEME_NAME;
|
|
184
158
|
useEffect(() => {
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
}
|
|
209
|
-
|
|
210
|
-
// make a stale binary serving a workspace with a newer checkout unmistakable.
|
|
211
|
-
const mismatch = detectCheckoutMismatch();
|
|
212
|
-
if (mismatch) {
|
|
213
|
-
setMessages(m => [...m, { role: 'system', text: formatMismatchWarning(mismatch) }]);
|
|
214
|
-
}
|
|
215
|
-
else if (!runtimeCapabilities().goalSupervisorAvailable) {
|
|
216
|
-
setMessages(m => [...m, { role: 'system', text: 'Warning: this haze build lacks the goal supervisor module; exhausting a turn step/tool budget may pause the goal instead of continuing automatically. Reinstall or relink haze (npm run dev:link in the checkout).' }]);
|
|
217
|
-
}
|
|
218
|
-
})().catch(() => undefined);
|
|
159
|
+
if (!settingsThemeLoadedRef.current)
|
|
160
|
+
return;
|
|
161
|
+
try {
|
|
162
|
+
setActiveTheme(resolveTheme(activeThemeName));
|
|
163
|
+
applyTerminalColors(theme.foreground, theme.background);
|
|
164
|
+
}
|
|
165
|
+
catch {
|
|
166
|
+
// Malformed theme names were reported at startup; keep the resolved default.
|
|
167
|
+
}
|
|
168
|
+
}, [activeThemeName]);
|
|
169
|
+
useEffect(() => {
|
|
170
|
+
void runStartupSequence({
|
|
171
|
+
version,
|
|
172
|
+
onLoaded({ settings: next, settingsError, branchName: branch, contextFiles: files }) {
|
|
173
|
+
setSettings(next);
|
|
174
|
+
settingsThemeLoadedRef.current = true;
|
|
175
|
+
setSettingsError(settingsError);
|
|
176
|
+
setBranchName(branch);
|
|
177
|
+
setContextFiles(files);
|
|
178
|
+
contextFileSignaturesRef.current = new Map(files.flatMap(file => file.signature ? [[file.path, file.signature]] : []));
|
|
179
|
+
},
|
|
180
|
+
initializeSession: () => sessionLifecycle.initializeSession(),
|
|
181
|
+
refreshSkills,
|
|
182
|
+
addSystemMessage: text => setMessages(m => [...m, { role: 'system', text }]),
|
|
183
|
+
}).catch(() => undefined);
|
|
219
184
|
readInputHistory().then(setInputHistory).catch(() => undefined);
|
|
220
185
|
loadTasksFromStore().then(setVisibleTasks).catch(() => undefined);
|
|
221
186
|
const branchTimer = setInterval(() => {
|
|
@@ -288,6 +253,14 @@ function ChatScreen({ debug = false, version, build, continueSession = false, re
|
|
|
288
253
|
setLiveMessagesState,
|
|
289
254
|
setTokenUsage,
|
|
290
255
|
manualCompaction: () => settings.manualCompaction ?? 'llm-summary',
|
|
256
|
+
// P1 resume path: an unterminated goal frontier detected on resume becomes
|
|
257
|
+
// the same one-key continue affordance the in-process pause uses — the
|
|
258
|
+
// goal continues from the stored frontier without re-sending the request.
|
|
259
|
+
onGoalFrontier: frontier => {
|
|
260
|
+
const checkpoint = checkpointFromGoalFrontier(frontier);
|
|
261
|
+
setPausedResume({ kind: 'incomplete-goal', request: frontier.request, retryAttempt: 0, checkpoint });
|
|
262
|
+
setMessages(m => [...m, { role: 'system', text: `This session ended with an unfinished goal (cycle ${frontier.cycle}, ${frontier.mutationCount} change${frontier.mutationCount === 1 ? '' : 's'} so far). Press R to resume it from where it stopped.` }]);
|
|
263
|
+
},
|
|
291
264
|
debugLog,
|
|
292
265
|
showPersistenceWarning,
|
|
293
266
|
});
|
|
@@ -310,21 +283,9 @@ function ChatScreen({ debug = false, version, build, continueSession = false, re
|
|
|
310
283
|
if (!busy)
|
|
311
284
|
return;
|
|
312
285
|
abortControllerRef.current?.abort('User pressed Esc.');
|
|
313
|
-
|
|
314
|
-
followUpQueueRef.current = [];
|
|
315
|
-
setQueuedFollowUps([]);
|
|
316
|
-
setMessages(m => [...m, { role: 'system', text: 'Cleared queued follow-ups after interrupt.' }]);
|
|
317
|
-
}
|
|
286
|
+
followUps.clear();
|
|
318
287
|
setBusyWithHeartbeat(false);
|
|
319
288
|
}
|
|
320
|
-
function queueFollowUp(value) {
|
|
321
|
-
const trimmed = value.trim();
|
|
322
|
-
if (!trimmed)
|
|
323
|
-
return;
|
|
324
|
-
followUpQueueRef.current = [...followUpQueueRef.current, trimmed];
|
|
325
|
-
setQueuedFollowUps(followUpQueueRef.current);
|
|
326
|
-
setMessages(m => [...m, { role: 'system', text: `Queued follow-up (${followUpQueueRef.current.length}): ${trimmed}` }]);
|
|
327
|
-
}
|
|
328
289
|
function closeInputList() {
|
|
329
290
|
if (mode !== 'chat') {
|
|
330
291
|
setMode('chat');
|
|
@@ -367,7 +328,7 @@ function ChatScreen({ debug = false, version, build, continueSession = false, re
|
|
|
367
328
|
}
|
|
368
329
|
if (busy) {
|
|
369
330
|
if (mode === 'chat')
|
|
370
|
-
|
|
331
|
+
followUps.queue(value);
|
|
371
332
|
return;
|
|
372
333
|
}
|
|
373
334
|
// Any new submission supersedes a paused-task resume affordance.
|
|
@@ -488,11 +449,7 @@ function ChatScreen({ debug = false, version, build, continueSession = false, re
|
|
|
488
449
|
await clearTasksFromStore().catch(() => undefined);
|
|
489
450
|
}
|
|
490
451
|
await runSingleAgentTurn(value, displayValue, turnOptions);
|
|
491
|
-
|
|
492
|
-
const next = followUpQueueRef.current[0];
|
|
493
|
-
followUpQueueRef.current = followUpQueueRef.current.slice(1);
|
|
494
|
-
setQueuedFollowUps(followUpQueueRef.current);
|
|
495
|
-
setMessages(m => [...m, { role: 'system', text: `Running queued follow-up: ${next}` }]);
|
|
452
|
+
for (let next = followUps.takeNext(); next !== undefined; next = followUps.takeNext()) {
|
|
496
453
|
const preparedFollowUp = await prepareUserInput(next);
|
|
497
454
|
if (!preparedFollowUp)
|
|
498
455
|
continue;
|
|
@@ -602,6 +559,9 @@ function ChatScreen({ debug = false, version, build, continueSession = false, re
|
|
|
602
559
|
log: llmLogRef.current,
|
|
603
560
|
},
|
|
604
561
|
...(resumeExisting ? { resumeFrom: resumeExisting } : {}),
|
|
562
|
+
// Durable goal ledger (P1): every supervisor boundary appends to the
|
|
563
|
+
// session JSONL so a crash or restart leaves a resumable frontier.
|
|
564
|
+
goalLedger: { append: entry => sessionRecorder.recordGoalEntry(entry) },
|
|
605
565
|
...(turnOptions.attachments || turnOptions.blessedPaths || turnOptions.ephemeralControl || turnOptions.subagentOverrides ? { turnOptions } : {})
|
|
606
566
|
});
|
|
607
567
|
await sessionRecorder.flush().catch(showPersistenceWarning);
|
|
@@ -632,14 +592,13 @@ function ChatScreen({ debug = false, version, build, continueSession = false, re
|
|
|
632
592
|
{ kind: 'header', key: 'header', subtitle: headerSubtitle },
|
|
633
593
|
...staticTranscriptItems,
|
|
634
594
|
];
|
|
635
|
-
const busyElapsed = busyElapsedLabel(turnStartedAtRef.current);
|
|
636
595
|
const contentWidth = Math.max(1, width - 2);
|
|
637
596
|
// Live-region budget: once the dynamic frame exceeds the viewport, Ink falls
|
|
638
597
|
// back to clearTerminal + full transcript replay, which wipes scrollback and
|
|
639
598
|
// jumps to the top on every render. Every dynamic section is therefore
|
|
640
599
|
// clamped so the frame stays under one screen (see chat/liveRegion.ts).
|
|
641
600
|
const busyRows = busy ? (showingTip ? 2 : 1) : 0;
|
|
642
|
-
const queuedRows =
|
|
601
|
+
const queuedRows = followUps.queued.length > 0 ? 2 + followUps.queued.length : 0;
|
|
643
602
|
const collapsedTaskRows = Math.min(visibleTasks.length, MAX_VISIBLE_TASKS);
|
|
644
603
|
const expandedTaskCap = Math.max(MAX_VISIBLE_TASKS, terminalRows - 18);
|
|
645
604
|
const expandedTaskRows = Math.min(visibleTasks.length, expandedTaskCap) + (visibleTasks.length > expandedTaskCap ? 1 : 0);
|
|
@@ -660,7 +619,7 @@ function ChatScreen({ debug = false, version, build, continueSession = false, re
|
|
|
660
619
|
// One row for the optional header plus one for the item's bottom margin.
|
|
661
620
|
const chrome = (item.showHeader === false ? 0 : 1) + 1;
|
|
662
621
|
return _jsx(MessageView, { message: item.message, width: contentWidth, showHeader: item.showHeader, maxVisibleLines: Math.max(1, perStreamingItemRows - chrome) }, item.key);
|
|
663
|
-
}) }), debug && debugLogs.length > 0 && _jsxs(Box, { flexDirection: "column", flexShrink: 0, marginBottom: 1, borderStyle: "round", borderColor: theme.muted, paddingX: 1, children: [_jsx(Text, { color: theme.muted, bold: true, children: "Debug" }), debugLogs.map((line, index) => _jsxs(Text, { color: theme.muted, children: ["\u2022 ", line] }, index))] }),
|
|
622
|
+
}) }), debug && debugLogs.length > 0 && _jsxs(Box, { flexDirection: "column", flexShrink: 0, marginBottom: 1, borderStyle: "round", borderColor: theme.muted, paddingX: 1, children: [_jsx(Text, { color: theme.muted, bold: true, children: "Debug" }), debugLogs.map((line, index) => _jsxs(Text, { color: theme.muted, children: ["\u2022 ", line] }, index))] }), followUps.queued.length > 0 && _jsxs(Box, { flexDirection: "column", flexShrink: 0, marginBottom: 1, children: [_jsx(Text, { color: theme.muted, children: "Queued follow-ups:" }), followUps.queued.map((item, index) => _jsxs(Text, { color: theme.muted, children: [" ", index + 1, ". ", item] }, `${index}-${item}`))] }), pausedResume && !busy && _jsxs(Box, { flexShrink: 0, marginBottom: 1, children: [_jsxs(Text, { color: theme.muted, children: [pausedResume.kind === 'incomplete-goal' ? 'Unfinished goal paused (no measurable progress)' : 'Unfinished goal paused (model stream stalled)', " \u00B7 "] }), _jsxs(Text, { color: theme.command, bold: true, children: ["Press R to ", pausedResume.kind === 'incomplete-goal' ? 'resume' : 'retry'] }), _jsx(Text, { color: theme.muted, children: " or type a follow-up" })] }), visibleTasks.length > 0 && _jsx(Box, { flexDirection: "column", flexShrink: 0, marginBottom: 1, children: _jsx(TaskBar, { tasks: visibleTasks, width: contentWidth, expanded: tasksExpanded, padding: taskBarPadding, maxRows: expandedTaskCap }) }), busy && _jsx(BusyBar, { label: busyLabel, elapsed: busyElapsed, tip: showingTip ? TIPS[tipIndex] : undefined }), _jsx(Box, { borderStyle: "round", borderColor: theme.border, paddingX: 1, flexShrink: 0, children: _jsx(Box, { flexGrow: 1, minWidth: 0, children: _jsx(TextInput, { placeholder: placeholder, disabled: busy && mode !== 'chat', mask: MASKED_MODES.has(mode), historyItems: inputHistory, recordHistory: mode === 'chat', suggestions: inputSuggestions, suggestionMode: PICKER_MODES.has(mode) ? 'always' : 'slash', submitOnEmpty: SUBMIT_EMPTY_MODES.has(mode), width: Math.max(20, contentWidth - 4), getMentionSuggestions: fileMentionSuggestions, onHistoryAdd: persistInputHistory, onToggleTasks: () => {
|
|
664
623
|
if (!tasksExpanded) {
|
|
665
624
|
setTaskBarPadding(0);
|
|
666
625
|
setTasksExpanded(true);
|
|
@@ -679,15 +638,35 @@ function ChatScreen({ debug = false, version, build, continueSession = false, re
|
|
|
679
638
|
}, onSubmit: submit }) }) }), debug && metrics.hasTokenBreakdown && _jsxs(Box, { flexShrink: 0, flexDirection: "column", paddingX: 1, children: [_jsxs(Text, { color: theme.muted, bold: true, children: ["Token usage ", metrics.inputEstimated || metrics.outputEstimated ? '(estimated)' : '(precise)'] }), _jsxs(Text, { color: theme.muted, children: [" in=", formatTokenCount(metrics.effectiveInput), " out=", formatTokenCount(metrics.effectiveOutput), tokenUsage.cacheReadTokens > 0 ? ` cached=${formatTokenCount(tokenUsage.cacheReadTokens)}` : '', tokenUsage.noCacheTokens > 0 ? ` uncached=${formatTokenCount(tokenUsage.noCacheTokens)}` : '', tokenUsage.cacheWriteTokens > 0 ? ` cache_write=${formatTokenCount(tokenUsage.cacheWriteTokens)}` : '', tokenUsage.reasoningTokens > 0 ? ` reasoning=${formatTokenCount(tokenUsage.reasoningTokens)}` : ''] }), _jsxs(Text, { color: theme.muted, children: [" logical=", formatTokenCount(tokenUsage.logicalInputEstimate), tokenUsage.effectiveNonCachedInput != null ? ` effective_non_cached=${formatTokenCount(tokenUsage.effectiveNonCachedInput)}` : ''] }), _jsxs(Text, { color: theme.muted, children: [" system=", formatTokenCount(tokenUsage.systemPrompt), " messages=", formatTokenCount(tokenUsage.messages), " tools=", formatTokenCount(tokenUsage.toolSchemas), " output=", formatTokenCount(tokenUsage.outputEstimate)] })] }), _jsxs(Box, { flexShrink: 0, justifyContent: "space-between", children: [_jsxs(Box, { flexDirection: "column", flexShrink: 1, minWidth: 0, children: [_jsx(Text, { color: theme.muted, wrap: "truncate-end", children: workspaceLabel }), _jsx(Text, { color: theme.muted, wrap: "truncate-end", children: metrics.statusDetailLabel })] }), _jsx(Box, { flexShrink: 0, marginLeft: 2, children: _jsx(Text, { color: theme.muted, wrap: "truncate-start", children: activeModelName }) })] })] });
|
|
680
639
|
}
|
|
681
640
|
export async function chatCommand(options = {}) {
|
|
641
|
+
// Resolve the theme before any Ink output so every component renders with it.
|
|
642
|
+
// Settings failures must not block startup (the in-app banner already reports
|
|
643
|
+
// them), but an unknown theme name fails loudly with the valid names listed.
|
|
644
|
+
try {
|
|
645
|
+
setActiveTheme(resolveTheme((await readSettings()).theme));
|
|
646
|
+
}
|
|
647
|
+
catch (error) {
|
|
648
|
+
console.error(`[haze] ${error instanceof Error ? error.message : String(error)}; using the ${DEFAULT_THEME_NAME} theme.`);
|
|
649
|
+
}
|
|
682
650
|
if (process.stdout.isTTY) {
|
|
683
651
|
process.stdout.write('\u001B[2J\u001B[3J\u001B[H');
|
|
652
|
+
// Adopt the theme's foreground AND background as the terminal defaults
|
|
653
|
+
// (OSC 10 + 11; ignored by terminals without support). Both sides must be
|
|
654
|
+
// themed together: unstyled text inherits the terminal fg, so a light
|
|
655
|
+
// background without a light-mode fg would be unreadable. Restored
|
|
656
|
+
// (OSC 110 + 111) on exit below.
|
|
657
|
+
applyTerminalColors(theme.foreground, theme.background);
|
|
684
658
|
}
|
|
685
659
|
await clearTasksFromStore().catch(() => undefined);
|
|
686
660
|
// Incremental rendering rewrites only changed lines of the live frame, removing
|
|
687
661
|
// the full-frame erase/rewrite flicker while streaming. The fps cap aligns with
|
|
688
662
|
// the ~80ms spinner cadence; faster renders would only repaint unchanged lines.
|
|
689
663
|
const app = render(_jsx(ChatScreen, { debug: options.debug, version: options.version, build: options.build, continueSession: options.continueSession, resumeSessionId: options.resumeSessionId, noSession: options.noSession }), { incrementalRendering: true, maxFps: 15 });
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
664
|
+
try {
|
|
665
|
+
await app.waitUntilExit();
|
|
666
|
+
await teardownBackgroundProcesses().catch(() => undefined);
|
|
667
|
+
await clearTasksFromStore().catch(() => undefined);
|
|
668
|
+
}
|
|
669
|
+
finally {
|
|
670
|
+
resetTerminalColors();
|
|
671
|
+
}
|
|
693
672
|
}
|
|
@@ -5,6 +5,8 @@ export const COMMAND_HELP_ENTRIES = [
|
|
|
5
5
|
{ usage: '/model <name-or-provider:name>', description: 'Set a model directly. Selecting a model also sets its provider.' },
|
|
6
6
|
{ usage: '/settings', description: 'Show the configured provider, model, API key status, LSP/MCP servers, skills, and loaded context files.' },
|
|
7
7
|
{ usage: '/settings open', description: 'Open ~/.haze/settings.json with the OS default app.' },
|
|
8
|
+
{ usage: '/themes', description: 'Choose a terminal theme from the built-in registry (light palettes and oh-my-zsh ports included); applies immediately.' },
|
|
9
|
+
{ usage: '/themes <name>', description: 'Set the theme directly, e.g. /themes robbyrussell. Saved to ~/.haze/settings.json; text already on screen keeps its old colors.' },
|
|
8
10
|
{ usage: '/skills', description: 'Manage Markdown skills: generate a custom skill, show info, enable/disable, validate, or remove.' },
|
|
9
11
|
{ usage: '/tips', description: 'Toggle the rotating tips shown under the busy label while the model is thinking.' },
|
|
10
12
|
{ usage: '/fleet [--review] [--profile <name>] [--workers <provider:model>] [--concurrency <n>] [--] <prompt>', description: 'Run genuinely independent tasks through disposable contexts. Runtime enforces profile concurrency, deadlines, and mutation serialization; control guidance is not persisted. Declines non-parallel work.' },
|
|
@@ -7,6 +7,7 @@ import { handleFleetCommand } from './fleetCommand.js';
|
|
|
7
7
|
import { handleInitCommand } from './initCommand.js';
|
|
8
8
|
import { handleLogsCommand } from './logsCommand.js';
|
|
9
9
|
import { handleModelCommand } from './modelCommand.js';
|
|
10
|
+
import { handleThemesCommand } from './themesCommand.js';
|
|
10
11
|
import { formatSettingsSummary } from './settingsSummary.js';
|
|
11
12
|
async function ensureSettingsFile(settings) {
|
|
12
13
|
if (!await fs.pathExists(SETTINGS_FILE))
|
|
@@ -57,6 +58,7 @@ const SLASH_COMMANDS = [
|
|
|
57
58
|
ctx.addSystemMessage(`Tips rotation ${currentlyEnabled ? 'disabled' : 'enabled'}.`);
|
|
58
59
|
return HANDLED;
|
|
59
60
|
} },
|
|
61
|
+
{ match: exactOrArgs('/themes'), run: async (args, ctx) => await handleThemesCommand(args, ctx) },
|
|
60
62
|
{ match: exactOrArgs('/fleet'), run: (args, ctx) => handleFleetCommand(args, ctx) },
|
|
61
63
|
];
|
|
62
64
|
export async function handleSlashCommand(value, ctx) {
|
|
@@ -11,14 +11,11 @@ export declare function toolResultSummary(event: {
|
|
|
11
11
|
* Lets the developer see *what* is happening, not just that something is.
|
|
12
12
|
*/
|
|
13
13
|
export declare function busyToolLabel(toolName: string, input: unknown): string;
|
|
14
|
-
export declare function formatSeconds(milliseconds: number): string;
|
|
15
14
|
/** Compact transcript row for a user-attached image (F03); never dumps bytes. */
|
|
16
15
|
export declare function imageAttachmentLine(attachment: {
|
|
17
16
|
fileName: string;
|
|
18
17
|
bytes: number;
|
|
19
18
|
}): string;
|
|
20
|
-
export declare function formatElapsedTime(milliseconds: number): string;
|
|
21
|
-
export declare function formatElapsedTimeWhole(milliseconds: number): string;
|
|
22
19
|
type ContextReportCategory = 'builtin' | 'lsp' | 'skill' | 'subagent' | 'mcp';
|
|
23
20
|
interface ContextReportTool {
|
|
24
21
|
name: string;
|
|
@@ -133,6 +133,12 @@ export function toolResultSummary(event) {
|
|
|
133
133
|
}
|
|
134
134
|
return 'completed';
|
|
135
135
|
}
|
|
136
|
+
if (output.reasonCode === 'secret_file_protected') {
|
|
137
|
+
// Protection events are visible but distinct from ordinary failures so
|
|
138
|
+
// the developer can audit them at a glance; never print file contents.
|
|
139
|
+
const protectedPath = typeof output.path === 'string' && output.path ? ` (${compact(output.path, 80)})` : '';
|
|
140
|
+
return `blocked: protected secret file${protectedPath}`;
|
|
141
|
+
}
|
|
136
142
|
const reason = typeof output.reasonCode === 'string' ? ` (${output.reasonCode})` : '';
|
|
137
143
|
return typeof output.error === 'string' ? `failed${reason}: ${compact(output.error)}` : `failed${reason}`;
|
|
138
144
|
}
|
|
@@ -178,39 +184,10 @@ export function busyToolLabel(toolName, input) {
|
|
|
178
184
|
return `Running ${toolName}`;
|
|
179
185
|
}
|
|
180
186
|
}
|
|
181
|
-
export function formatSeconds(milliseconds) {
|
|
182
|
-
return `${(milliseconds / 1000).toFixed(1)}s`;
|
|
183
|
-
}
|
|
184
187
|
/** Compact transcript row for a user-attached image (F03); never dumps bytes. */
|
|
185
188
|
export function imageAttachmentLine(attachment) {
|
|
186
189
|
return `🖼 ${attachment.fileName} (${formatBytes(attachment.bytes)})`;
|
|
187
190
|
}
|
|
188
|
-
export function formatElapsedTime(milliseconds) {
|
|
189
|
-
const totalSeconds = Math.max(0, milliseconds / 1000);
|
|
190
|
-
const wholeSeconds = Math.floor(totalSeconds);
|
|
191
|
-
const seconds = totalSeconds - Math.floor(wholeSeconds / 60) * 60;
|
|
192
|
-
const totalMinutes = Math.floor(wholeSeconds / 60);
|
|
193
|
-
const minutes = totalMinutes % 60;
|
|
194
|
-
const hours = Math.floor(totalMinutes / 60);
|
|
195
|
-
const secondsLabel = `${seconds.toFixed(1)}s`;
|
|
196
|
-
if (hours > 0)
|
|
197
|
-
return `${hours}h ${minutes}m ${secondsLabel}`;
|
|
198
|
-
if (minutes > 0)
|
|
199
|
-
return `${minutes}m ${secondsLabel}`;
|
|
200
|
-
return secondsLabel;
|
|
201
|
-
}
|
|
202
|
-
export function formatElapsedTimeWhole(milliseconds) {
|
|
203
|
-
const totalSeconds = Math.max(0, Math.floor(milliseconds / 1000));
|
|
204
|
-
const seconds = totalSeconds % 60;
|
|
205
|
-
const totalMinutes = Math.floor(totalSeconds / 60);
|
|
206
|
-
const minutes = totalMinutes % 60;
|
|
207
|
-
const hours = Math.floor(totalMinutes / 60);
|
|
208
|
-
if (hours > 0)
|
|
209
|
-
return `${hours}h ${minutes}m ${seconds}s`;
|
|
210
|
-
if (minutes > 0)
|
|
211
|
-
return `${minutes}m ${seconds}s`;
|
|
212
|
-
return `${seconds}s`;
|
|
213
|
-
}
|
|
214
191
|
const CONTEXT_CATEGORY_LABEL = {
|
|
215
192
|
builtin: 'Built-in',
|
|
216
193
|
lsp: 'LSP',
|
|
@@ -6,6 +6,8 @@ export interface HeadlessOptions {
|
|
|
6
6
|
output: HeadlessOutput;
|
|
7
7
|
debug?: boolean;
|
|
8
8
|
timeout?: string;
|
|
9
|
+
/** `--until-done` (P6): relaunch the goal after transient model failures until structural completion, a deadline, or the poison guard. */
|
|
10
|
+
untilDone?: boolean;
|
|
9
11
|
}
|
|
10
12
|
/** Pinned, documented usage shape emitted in `--output json` (avoids leaking internal estimates). */
|
|
11
13
|
export interface HeadlessUsage {
|
|
@@ -4,6 +4,7 @@ import { EMPTY_TOKEN_USAGE, accumulateTokenUsage } from '../chat/turnState.js';
|
|
|
4
4
|
import { readSettings } from '../../config/settings.js';
|
|
5
5
|
import { activeModel, modelSelector, resolveModelSelector } from '../../config/providers.js';
|
|
6
6
|
import { createLog, endLog } from '../../core/log/llmLog.js';
|
|
7
|
+
import { agentEvent } from '../../core/agent/events.js';
|
|
7
8
|
import { findSession, restoreSessionState } from '../../core/session/sessionStore.js';
|
|
8
9
|
import { compactModelMessages } from '../../core/agent/compaction.js';
|
|
9
10
|
import { FALLBACK_CONTEXT_WINDOW_TOKENS } from '../../core/agent/contextBudget.js';
|
|
@@ -53,9 +54,13 @@ function toHeadlessStreamEvent(event) {
|
|
|
53
54
|
case 'goal_start':
|
|
54
55
|
return { type: 'goal_start', goalId: event.goalId, request: event.request, at: event.at };
|
|
55
56
|
case 'goal_continue':
|
|
56
|
-
return { type: 'goal_continue', goalId: event.goalId, cycle: event.cycle, reason: event.reason, at: event.at };
|
|
57
|
+
return { ...(event.text ? { text: event.text } : {}), type: 'goal_continue', goalId: event.goalId, cycle: event.cycle, reason: event.reason, at: event.at };
|
|
58
|
+
case 'goal_notice':
|
|
59
|
+
return { type: 'goal_notice', text: event.text, at: event.at };
|
|
57
60
|
case 'goal_end':
|
|
58
61
|
return { ...(event.stopReason ? { stopReason: event.stopReason } : {}), ...(event.evidence ? { evidence: event.evidence } : {}), type: 'goal_end', goalId: event.goalId, status: event.status, cycles: event.cycles, at: event.at };
|
|
62
|
+
case 'goal_resume':
|
|
63
|
+
return { type: 'goal_resume', goalId: event.goalId, relaunch: event.relaunch, stopReason: event.stopReason, reason: event.reason, at: event.at };
|
|
59
64
|
case 'step_start':
|
|
60
65
|
return { type: 'step_start', attempt: event.attempt, step: event.step, at: event.at };
|
|
61
66
|
case 'step_end':
|
|
@@ -184,6 +189,16 @@ export async function runHeadless(options) {
|
|
|
184
189
|
void streamSink.write(headlessEvent);
|
|
185
190
|
}
|
|
186
191
|
: undefined;
|
|
192
|
+
// Bounded, cross-output-mode collection of gate decisions and pauses so
|
|
193
|
+
// `--output json` consumers see *why* a goal continued or paused, not only
|
|
194
|
+
// that it did. The same events stream live in
|
|
195
|
+
// stream-json mode.
|
|
196
|
+
const goalNotices = [];
|
|
197
|
+
const recordEvent = (event) => {
|
|
198
|
+
if (event.type === 'goal_notice' && goalNotices.length < 20)
|
|
199
|
+
goalNotices.push(event.text);
|
|
200
|
+
emitStreamEvent?.(event);
|
|
201
|
+
};
|
|
187
202
|
const callbacks = {
|
|
188
203
|
addMessage: (msg) => {
|
|
189
204
|
if (msg.role === 'assistant')
|
|
@@ -222,7 +237,7 @@ export async function runHeadless(options) {
|
|
|
222
237
|
conversation = result.messages;
|
|
223
238
|
return true;
|
|
224
239
|
},
|
|
225
|
-
onEvent:
|
|
240
|
+
onEvent: recordEvent,
|
|
226
241
|
log,
|
|
227
242
|
};
|
|
228
243
|
let status;
|
|
@@ -235,7 +250,55 @@ export async function runHeadless(options) {
|
|
|
235
250
|
// The logical-goal supervisor owns the whole request: `--timeout` bounds
|
|
236
251
|
// the entire goal, and per-turn budgets merely end physical turns that
|
|
237
252
|
// continue automatically while recoverable work and progress remain.
|
|
238
|
-
|
|
253
|
+
// `--until-done` (P6) adds a bounded in-process relaunch loop on top:
|
|
254
|
+
// transient model failures (model-error, idle-stall exhaustion) with a
|
|
255
|
+
// live frontier re-enter the supervisor with backoff, until structural
|
|
256
|
+
// completion, the goal deadline, or the poison guard (repeated relaunches
|
|
257
|
+
// with no frontier progress). Unattendedness never grants authority: the
|
|
258
|
+
// supervisor resumes work, not permissions.
|
|
259
|
+
const deadlineAt = turnDeadlineMs != null ? Date.now() + turnDeadlineMs : undefined;
|
|
260
|
+
const runOnce = async (relaunchOptions) => runAgentGoal({
|
|
261
|
+
request: options.prompt,
|
|
262
|
+
displayValue: options.prompt,
|
|
263
|
+
contextFiles,
|
|
264
|
+
callbacks,
|
|
265
|
+
session,
|
|
266
|
+
modelOverride: options.modelOverride,
|
|
267
|
+
...(turnDeadlineMs != null ? { goalDeadlineMs: Math.max(1, deadlineAt - Date.now()) } : {}),
|
|
268
|
+
...(relaunchOptions.resumeFrom ? { resumeFrom: relaunchOptions.resumeFrom } : {}),
|
|
269
|
+
...(relaunchOptions.conversationCarriesRequest ? { conversationCarriesRequest: true } : {}),
|
|
270
|
+
});
|
|
271
|
+
let goalResult = await runOnce({});
|
|
272
|
+
if (options.untilDone) {
|
|
273
|
+
const poisonLimit = 3;
|
|
274
|
+
let relaunches = 0;
|
|
275
|
+
let noProgressRelaunches = 0;
|
|
276
|
+
let lastSignature;
|
|
277
|
+
while (goalResult.status === 'failed'
|
|
278
|
+
&& (goalResult.stopReason === 'model-error' || goalResult.stopReason === 'model-stream-idle')) {
|
|
279
|
+
const signature = JSON.stringify(goalResult.evidence ? [goalResult.evidence.mutationCount > 0, goalResult.evidence.validationOutcome, goalResult.evidence.taskProgress ? [goalResult.evidence.taskProgress.total, goalResult.evidence.taskProgress.pending, goalResult.evidence.taskProgress.inProgress, goalResult.evidence.taskProgress.completed] : null] : null);
|
|
280
|
+
noProgressRelaunches = lastSignature != null && signature === lastSignature ? noProgressRelaunches + 1 : 0;
|
|
281
|
+
lastSignature = signature;
|
|
282
|
+
if (noProgressRelaunches >= poisonLimit) {
|
|
283
|
+
process.stderr.write(`haze --until-done: stopping after ${noProgressRelaunches} relaunch${noProgressRelaunches === 1 ? '' : 'es'} without measurable progress (truly stuck). The frontier is preserved; the truthful goal status follows.\n`);
|
|
284
|
+
break;
|
|
285
|
+
}
|
|
286
|
+
if (deadlineAt != null && Date.now() >= deadlineAt)
|
|
287
|
+
break;
|
|
288
|
+
relaunches += 1;
|
|
289
|
+
const delayMs = Math.min(30_000, 1_000 * 2 ** Math.min(relaunches, 5));
|
|
290
|
+
callbacks.onEvent?.(agentEvent({ type: 'goal_resume', goalId: `relaunch-${relaunches}`, relaunch: relaunches, stopReason: goalResult.stopReason, reason: `transient ${goalResult.stopReason}; relaunching with ${delayMs}ms backoff` }));
|
|
291
|
+
process.stderr.write(`haze --until-done: ${goalResult.stopReason} on cycle ${goalResult.cycles}; relaunching (attempt ${relaunches}, backoff ${delayMs}ms).\n`);
|
|
292
|
+
await new Promise(resolve => setTimeout(resolve, delayMs));
|
|
293
|
+
// A paused checkpoint (idle stall) resumes it; a hard model error has
|
|
294
|
+
// no checkpoint, but the conversation is preserved — re-enter against
|
|
295
|
+
// it without duplicating the user request.
|
|
296
|
+
goalResult = await runOnce({
|
|
297
|
+
...(goalResult.resume?.kind === 'incomplete-goal' ? { resumeFrom: goalResult.resume } : {}),
|
|
298
|
+
...(goalResult.resume ? {} : { conversationCarriesRequest: conversation.length > 0 }),
|
|
299
|
+
});
|
|
300
|
+
}
|
|
301
|
+
}
|
|
239
302
|
status = goalResult.status;
|
|
240
303
|
evidence = goalResult.evidence;
|
|
241
304
|
goal = {
|
|
@@ -270,7 +333,7 @@ export async function runHeadless(options) {
|
|
|
270
333
|
if (streamSink)
|
|
271
334
|
await streamSink.flush().catch(() => undefined);
|
|
272
335
|
// This terminal line is byte-identical to the --output json envelope, so harnesses can parse the last line the same way.
|
|
273
|
-
const resultLine = { type: 'result', status, result, usage: pinnedUsage(usage), ...(evidence ? { evidence } : {}), ...(goal ? { goal } : {}) };
|
|
336
|
+
const resultLine = { type: 'result', status, result, usage: pinnedUsage(usage), ...(evidence ? { evidence } : {}), ...(goal ? { goal } : {}), ...(goalNotices.length > 0 ? { notices: goalNotices.slice(-5) } : {}) };
|
|
274
337
|
if (streamSink)
|
|
275
338
|
await streamSink.write(resultLine).catch(() => undefined);
|
|
276
339
|
else
|
|
@@ -3,6 +3,7 @@ import { configuredLspServers } from '../../config/lspSettings.js';
|
|
|
3
3
|
import { configuredMcpServers } from '../../config/mcpSettings.js';
|
|
4
4
|
import { activeProvider as resolveActiveProvider, configuredProviders, providerHasKey, providerImageCapable } from '../../config/providers.js';
|
|
5
5
|
import { isSkillEnabled } from '../../config/skillSettings.js';
|
|
6
|
+
import { DEFAULT_THEME_NAME } from '../../ui/theme.js';
|
|
6
7
|
import { loadSkillRegistry } from '../../skills/SkillRegistry.js';
|
|
7
8
|
export async function formatSettingsSummary(settings, contextFiles) {
|
|
8
9
|
const providers = configuredProviders(settings);
|
|
@@ -30,6 +31,7 @@ export async function formatSettingsSummary(settings, contextFiles) {
|
|
|
30
31
|
`Model: ${settings.model ?? 'not set'}`,
|
|
31
32
|
`Base URL: ${activeProvider?.url ?? settings.baseURL ?? 'not configured'}`,
|
|
32
33
|
`API key: ${activeProvider && providerHasKey(settings, activeProvider) ? 'saved' : 'missing'}`,
|
|
34
|
+
`Theme: ${settings.theme ?? `${DEFAULT_THEME_NAME} (default)`}`,
|
|
33
35
|
`Configured providers: ${providers.map(provider => `${provider.name}${providerImageCapable(provider) ? ' (images)' : ''}`).join(', ') || 'none'}`,
|
|
34
36
|
`LSP servers: ${lspServers.map(server => `${server.name}${server.enabled === false ? ' (disabled)' : ''}`).join(', ') || 'none'}`,
|
|
35
37
|
`MCP servers: ${configuredMcpServers(settings).map(server => `${server.name}${server.enabled === false ? ' (disabled)' : ''}`).join(', ') || 'none'}`,
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import type { StreamCallbacks } from '../streaming.js';
|
|
2
|
+
import type { ToolGroupRenderer } from './toolGroupRenderer.js';
|
|
3
|
+
import type { AttemptLoopState } from './streamLoop.js';
|
|
4
|
+
/**
|
|
5
|
+
* Assistant segment lifecycle (extracted from streamLoop.ts): one segment is
|
|
6
|
+
* the text between tool calls (or the final answer). Segments start lazily
|
|
7
|
+
* (gated by `shouldStartAssistantStream`), finalize with duplicate/lead-in
|
|
8
|
+
* suppression, and reset for the next segment.
|
|
9
|
+
*/
|
|
10
|
+
export declare function resetAssistantSegment(loopState: AttemptLoopState): void;
|
|
11
|
+
export declare function finalizeAssistantSegment(loopState: AttemptLoopState, callbacks: StreamCallbacks, options?: {
|
|
12
|
+
beforeTool?: boolean;
|
|
13
|
+
}): boolean;
|
|
14
|
+
/** Finalize any pending assistant text right before a tool call starts, demoting hidden lead-ins to the tool group caption. */
|
|
15
|
+
export declare function finalizePendingAssistantBeforeTool(deps: {
|
|
16
|
+
loopState: AttemptLoopState;
|
|
17
|
+
callbacks: StreamCallbacks;
|
|
18
|
+
toolDisplay: ToolGroupRenderer;
|
|
19
|
+
}): void;
|