@denizokcu/haze 1.1.0 → 1.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +49 -1
- package/README.md +17 -10
- package/SECURITY.md +1 -1
- package/dist/buildInfo.json +3 -3
- 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/messages.d.ts +0 -22
- package/dist/cli/chat/messages.js +40 -85
- package/dist/cli/chat/sessionLifecycle.d.ts +3 -1
- package/dist/cli/chat/sessionLifecycle.js +8 -1
- package/dist/cli/chat/sessionRecorder.d.ts +9 -0
- package/dist/cli/chat/sessionRecorder.js +12 -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 -815
- package/dist/cli/commands/chat.js +69 -110
- package/dist/cli/commands/formatters.d.ts +0 -3
- package/dist/cli/commands/formatters.js +0 -29
- package/dist/cli/commands/runCommand.d.ts +2 -0
- package/dist/cli/commands/runCommand.js +73 -4
- package/dist/cli/commands/streaming/agentAttempt.d.ts +11 -1
- package/dist/cli/commands/streaming/agentAttempt.js +9 -5
- 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 +25 -5
- package/dist/cli/commands/streaming/attemptOutcome.js +69 -16
- package/dist/cli/commands/streaming/attemptSetup.d.ts +10 -3
- package/dist/cli/commands/streaming/attemptSetup.js +30 -13
- 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 +18 -3
- package/dist/cli/commands/streaming/goalSupervisor.js +71 -12
- package/dist/cli/commands/streaming/prepareStep.d.ts +40 -0
- package/dist/cli/commands/streaming/prepareStep.js +116 -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 +2 -6
- package/dist/cli/commands/streaming/streamLoop.d.ts +31 -4
- package/dist/cli/commands/streaming/streamLoop.js +283 -268
- 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 +108 -0
- package/dist/cli/commands/streaming/turnRuntime.d.ts +1 -1
- package/dist/cli/commands/streaming/turnRuntime.js +3 -2
- package/dist/cli/commands/streaming.d.ts +12 -1
- package/dist/cli/commands/streaming.js +20 -25
- package/dist/cli/index.js +6 -3
- package/dist/config/modelCatalog.d.ts +32 -0
- package/dist/config/modelCatalog.js +84 -0
- package/dist/config/providerPresets.d.ts +7 -0
- package/dist/config/providerPresets.js +195 -391
- package/dist/config/settings.d.ts +10 -2
- package/dist/config/settings.js +3 -0
- package/dist/core/agent/budgets.d.ts +10 -0
- package/dist/core/agent/budgets.js +10 -0
- package/dist/core/agent/compaction.d.ts +42 -3
- package/dist/core/agent/compaction.js +53 -5
- package/dist/core/agent/completionController.d.ts +16 -7
- package/dist/core/agent/completionController.js +13 -6
- package/dist/core/agent/contextBudget.d.ts +56 -0
- package/dist/core/agent/contextBudget.js +53 -0
- package/dist/core/agent/errors.js +2 -2
- package/dist/core/agent/events.d.ts +36 -1
- package/dist/core/agent/goalPolicy.d.ts +4 -3
- package/dist/core/agent/goalPolicy.js +9 -4
- package/dist/core/agent/overflow.d.ts +45 -0
- package/dist/core/agent/overflow.js +91 -0
- package/dist/core/agent/requestAssembly.d.ts +7 -0
- package/dist/core/agent/requestAssembly.js +15 -7
- package/dist/core/agent/workState.d.ts +25 -15
- package/dist/core/agent/workState.js +84 -44
- package/dist/core/safety/shellClassifier.d.ts +16 -0
- package/dist/core/safety/shellClassifier.js +31 -0
- package/dist/core/session/sessionSlimming.js +8 -0
- package/dist/core/session/sessionStore.d.ts +71 -1
- package/dist/core/session/sessionStore.js +121 -6
- package/dist/core/validation/outputParser.d.ts +1 -1
- package/dist/core/validation/outputParser.js +6 -1
- package/dist/llm/client.d.ts +2 -2
- package/dist/llm/client.js +14 -6
- package/dist/llm/hazeTools.d.ts +64 -208
- package/dist/llm/tools/shellTool.js +27 -8
- package/dist/llm/tools/taskTool.d.ts +64 -208
- package/dist/llm/tools/taskTool.js +22 -10
- package/dist/ui/components/TextInput.d.ts +18 -1
- package/dist/ui/components/TextInput.js +50 -73
- package/dist/ui/components/useInputSuggestions.d.ts +27 -0
- package/dist/ui/components/useInputSuggestions.js +98 -0
- package/dist/ui/theme.d.ts +8 -8
- package/dist/ui/theme.js +11 -12
- 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 +16 -15
- package/dist/ui/themes/af-magic.d.ts +0 -7
- package/dist/ui/themes/af-magic.js +0 -25
- package/dist/ui/themes/agnoster.d.ts +0 -10
- package/dist/ui/themes/agnoster.js +0 -40
- package/dist/ui/themes/bira.d.ts +0 -10
- package/dist/ui/themes/bira.js +0 -28
- package/dist/ui/themes/bureau.d.ts +0 -10
- package/dist/ui/themes/bureau.js +0 -28
- package/dist/ui/themes/clean.d.ts +0 -9
- package/dist/ui/themes/clean.js +0 -27
- package/dist/ui/themes/cloud.d.ts +0 -6
- package/dist/ui/themes/cloud.js +0 -24
- package/dist/ui/themes/dst.d.ts +0 -10
- package/dist/ui/themes/dst.js +0 -28
- package/dist/ui/themes/fishy.d.ts +0 -7
- package/dist/ui/themes/fishy.js +0 -25
- package/dist/ui/themes/index.d.ts +0 -8
- package/dist/ui/themes/index.js +0 -36
- package/dist/ui/themes/light.d.ts +0 -3
- package/dist/ui/themes/light.js +0 -21
- package/dist/ui/themes/purple.d.ts +0 -7
- package/dist/ui/themes/purple.js +0 -26
- package/dist/ui/themes/robbyrussell.d.ts +0 -8
- package/dist/ui/themes/robbyrussell.js +0 -26
- package/dist/ui/themes/solarized-dark.d.ts +0 -16
- package/dist/ui/themes/solarized-dark.js +0 -44
- package/dist/ui/themes/solarized-light.d.ts +0 -12
- package/dist/ui/themes/solarized-light.js +0 -40
- package/dist/ui/themes/steeef.d.ts +0 -11
- package/dist/ui/themes/steeef.js +0 -29
|
@@ -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';
|
|
@@ -17,47 +14,34 @@ import { setActiveTheme, resolveTheme, theme, DEFAULT_THEME_NAME } from '../../u
|
|
|
17
14
|
import { applyTerminalColors, resetTerminalColors } from '../../ui/terminalColors.js';
|
|
18
15
|
import { handleSlashCommand } from './commands.js';
|
|
19
16
|
import { runAgentGoal } from './streaming/goalSupervisor.js';
|
|
20
|
-
import {
|
|
17
|
+
import { checkpointFromGoalFrontier } from './streaming/goalCheckpoint.js';
|
|
18
|
+
import { imageAttachmentLine } from './formatters.js';
|
|
21
19
|
import { imageCapabilityError, IMAGE_ONLY_PROMPT_TEXT, resolveImageAttachments } from '../../core/attachments/imageAttachments.js';
|
|
22
20
|
import { resolveReadBlessings } from '../../core/attachments/readBlessings.js';
|
|
23
21
|
import { endLog as endLlmLog } from '../../core/log/llmLog.js';
|
|
24
22
|
import { loadSkillRegistry } from '../../skills/SkillRegistry.js';
|
|
25
23
|
import { formatSession, listSessions } from '../../core/session/sessionStore.js';
|
|
26
24
|
import { MAX_VISIBLE_TASKS, TaskBar } from '../chat/TaskBar.js';
|
|
27
|
-
import { AssistantMarkdownChunkView, MessageView
|
|
25
|
+
import { AssistantMarkdownChunkView, MessageView } from '../chat/messages.js';
|
|
26
|
+
import { partitionDisplayMessages } from '../chat/transcriptPartition.js';
|
|
28
27
|
import { createSessionRecorder } from '../chat/sessionRecorder.js';
|
|
29
28
|
import { createSessionLifecycle } from '../chat/sessionLifecycle.js';
|
|
30
29
|
import { createWizardDispatch, initialWizardUiState, wizardUiReducer } from '../chat/wizardDispatch.js';
|
|
31
30
|
import { buildContextReport } from '../chat/contextReport.js';
|
|
32
|
-
import { startupContextInfo, startupProviderInfo } from '../chat/startupInfo.js';
|
|
33
31
|
import { TIPS, randomTipIndex, tipsEnabled } from '../chat/tips.js';
|
|
34
32
|
import { fileMentionSuggestions } from '../chat/fileMentionSuggestions.js';
|
|
35
|
-
import { compactHomePath,
|
|
33
|
+
import { compactHomePath, statusBarMetrics } from '../chat/chatMetrics.js';
|
|
34
|
+
import { formatTokenCount } from '../../utils/format.js';
|
|
36
35
|
import { accumulateTokenUsage, EMPTY_TOKEN_USAGE, shouldClearCompletedTasks } from '../chat/turnState.js';
|
|
37
36
|
import { MASKED_MODES, PICKER_MODES, SUBMIT_EMPTY_MODES, placeholderForMode } from './chatModes.js';
|
|
38
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';
|
|
39
41
|
import { modelThinkingLabel } from '../../utils/modelName.js';
|
|
40
|
-
import { detectCheckoutMismatch, formatMismatchWarning, runtimeCapabilities } from '../../utils/buildInfo.js';
|
|
41
42
|
import { commandParts } from './wizardFlow.js';
|
|
42
43
|
import { backgroundProcessCount, subscribeBackgroundProcesses, teardownBackgroundProcesses } from '../../core/process/backgroundRegistry.js';
|
|
43
44
|
import { MAX_SESSION_PICKER_RESULTS } from './sessionPicker.js';
|
|
44
|
-
const execFile = promisify(execFileCallback);
|
|
45
|
-
async function currentBranchName() {
|
|
46
|
-
try {
|
|
47
|
-
const { stdout } = await execFile('git', ['branch', '--show-current'], { cwd: process.cwd() });
|
|
48
|
-
return stdout.trim() || undefined;
|
|
49
|
-
}
|
|
50
|
-
catch {
|
|
51
|
-
return undefined;
|
|
52
|
-
}
|
|
53
|
-
}
|
|
54
|
-
/** Elapsed-time label for the busy indicator heartbeat, or '' when no turn is active. */
|
|
55
|
-
function busyElapsedLabel(startedAt) {
|
|
56
|
-
if (startedAt == null)
|
|
57
|
-
return '';
|
|
58
|
-
const elapsed = Date.now() - startedAt;
|
|
59
|
-
return elapsed > 0 ? formatElapsedTimeWhole(elapsed) : '';
|
|
60
|
-
}
|
|
61
45
|
function thinkingLabelForSettings(settings) {
|
|
62
46
|
return modelThinkingLabel(activeModel(settings)?.model);
|
|
63
47
|
}
|
|
@@ -115,25 +99,22 @@ function ChatScreen({ debug = false, version, build, continueSession = false, re
|
|
|
115
99
|
const skillErrorSignatureRef = useRef('');
|
|
116
100
|
const projectSkillSignatureRef = useRef('');
|
|
117
101
|
const contextFileSignaturesRef = useRef(new Map());
|
|
118
|
-
const
|
|
102
|
+
const followUps = useFollowUpQueue(text => setMessages(m => [...m, { role: 'system', text }]));
|
|
119
103
|
const [inputHistory, setInputHistory] = useState([]);
|
|
120
104
|
const [debugLogs, setDebugLogs] = useState([]);
|
|
121
105
|
const [contextFiles, setContextFiles] = useState([]);
|
|
122
106
|
const [mode, setMode] = useState('chat');
|
|
123
107
|
const [sessions, setSessions] = useState([]);
|
|
124
|
-
|
|
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();
|
|
125
112
|
const [backgroundCount, setBackgroundCount] = useState(backgroundProcessCount);
|
|
126
113
|
const [busyLabel, setBusyLabel] = useState(() => thinkingLabelForSettings(settings));
|
|
127
|
-
// Heartbeat for the busy indicator: ticks every second while haze is working
|
|
128
|
-
// so the developer always sees rolling activity (elapsed turn time) even when
|
|
129
|
-
// the model is thinking with no streamed output and no tool is running.
|
|
130
|
-
const turnStartedAtRef = useRef(undefined);
|
|
131
|
-
const [, setBusyTick] = useState(0);
|
|
132
114
|
const [visibleTasks, setVisibleTasks] = useState([]);
|
|
133
115
|
const [tasksExpanded, setTasksExpanded] = useState(false);
|
|
134
116
|
const [taskBarPadding, setTaskBarPadding] = useState(0);
|
|
135
117
|
const [tokenUsage, setTokenUsage] = useState({ ...EMPTY_TOKEN_USAGE });
|
|
136
|
-
const [queuedFollowUps, setQueuedFollowUps] = useState([]);
|
|
137
118
|
// A genuinely paused goal (no measurable progress, deadline, or a stalled
|
|
138
119
|
// model stream) — automatic continuation has already been attempted by the
|
|
139
120
|
// goal supervisor. Carries what a one-key resume needs; any new submission
|
|
@@ -145,24 +126,7 @@ function ChatScreen({ debug = false, version, build, continueSession = false, re
|
|
|
145
126
|
// this replaced twelve individual useState hooks.
|
|
146
127
|
const [wizardState, updateWizard] = useReducer(wizardUiReducer, undefined, initialWizardUiState);
|
|
147
128
|
const { modelProviderFilter, discoveredModels, suggestedModels, selectedProviderName, providerDraft, selectedSkillName, selectedLspName, selectedMcpName } = wizardState;
|
|
148
|
-
// Wrap setBusy so the busy indicator knows when the turn started, and tick a
|
|
149
|
-
// heartbeat every second while busy so elapsed time keeps rolling. This keeps
|
|
150
|
-
// the UI visibly alive during long model thinking / blocked tool runs where
|
|
151
|
-
// otherwise no streamed output is produced (the "looks stuck" problem).
|
|
152
|
-
const setBusyWithHeartbeat = (nextBusy) => {
|
|
153
|
-
if (nextBusy && !busy)
|
|
154
|
-
turnStartedAtRef.current = Date.now();
|
|
155
|
-
if (!nextBusy)
|
|
156
|
-
turnStartedAtRef.current = undefined;
|
|
157
|
-
setBusy(nextBusy);
|
|
158
|
-
};
|
|
159
129
|
useEffect(() => subscribeBackgroundProcesses(() => setBackgroundCount(backgroundProcessCount())), []);
|
|
160
|
-
useEffect(() => {
|
|
161
|
-
if (!busy)
|
|
162
|
-
return;
|
|
163
|
-
const heartbeat = setInterval(() => setBusyTick(tick => tick + 1), 1000);
|
|
164
|
-
return () => clearInterval(heartbeat);
|
|
165
|
-
}, [busy]);
|
|
166
130
|
// One tip per thinking section, shown under the busy label while the model
|
|
167
131
|
// is purely thinking (no tool running) and the user has not disabled tips.
|
|
168
132
|
// A fresh tip is picked each time the model enters thinking mode; no
|
|
@@ -182,7 +146,7 @@ function ChatScreen({ debug = false, version, build, continueSession = false, re
|
|
|
182
146
|
return;
|
|
183
147
|
currentBranchName().then(setBranchName).catch(() => setBranchName(undefined));
|
|
184
148
|
}, [busy]);
|
|
185
|
-
// Live theme switching
|
|
149
|
+
// Live theme switching: whenever the settings'
|
|
186
150
|
// theme name changes (/themes), re-resolve and adopt it so the whole UI
|
|
187
151
|
// repaints without a restart. Ink <Static> history stays as-rendered, so
|
|
188
152
|
// already-printed text keeps its old colors; the terminal defaults (OSC
|
|
@@ -203,41 +167,20 @@ function ChatScreen({ debug = false, version, build, continueSession = false, re
|
|
|
203
167
|
}
|
|
204
168
|
}, [activeThemeName]);
|
|
205
169
|
useEffect(() => {
|
|
206
|
-
void (
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
await sessionLifecycle.initializeSession().catch(error => {
|
|
221
|
-
const text = error instanceof Error ? error.message : String(error);
|
|
222
|
-
setMessages(m => [...m, { role: 'system', text: `Session disabled: ${text}` }]);
|
|
223
|
-
});
|
|
224
|
-
await refreshSkills().catch(() => undefined);
|
|
225
|
-
if (version) {
|
|
226
|
-
const result = await checkForUpdate({ currentVersion: version, packageName: '@denizokcu/haze' }).catch(() => undefined);
|
|
227
|
-
if (result?.isOutdated) {
|
|
228
|
-
setMessages(m => [...m, { role: 'system', text: `A new version of haze is available: ${result.latestVersion} (you have ${version}). Update with: npm i -g @denizokcu/haze` }]);
|
|
229
|
-
}
|
|
230
|
-
}
|
|
231
|
-
// Runtime/installation diagnostics: never switch runtimes silently, but
|
|
232
|
-
// make a stale binary serving a workspace with a newer checkout unmistakable.
|
|
233
|
-
const mismatch = detectCheckoutMismatch();
|
|
234
|
-
if (mismatch) {
|
|
235
|
-
setMessages(m => [...m, { role: 'system', text: formatMismatchWarning(mismatch) }]);
|
|
236
|
-
}
|
|
237
|
-
else if (!runtimeCapabilities().goalSupervisorAvailable) {
|
|
238
|
-
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).' }]);
|
|
239
|
-
}
|
|
240
|
-
})().catch(() => undefined);
|
|
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);
|
|
241
184
|
readInputHistory().then(setInputHistory).catch(() => undefined);
|
|
242
185
|
loadTasksFromStore().then(setVisibleTasks).catch(() => undefined);
|
|
243
186
|
const branchTimer = setInterval(() => {
|
|
@@ -310,6 +253,14 @@ function ChatScreen({ debug = false, version, build, continueSession = false, re
|
|
|
310
253
|
setLiveMessagesState,
|
|
311
254
|
setTokenUsage,
|
|
312
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
|
+
},
|
|
313
264
|
debugLog,
|
|
314
265
|
showPersistenceWarning,
|
|
315
266
|
});
|
|
@@ -332,21 +283,9 @@ function ChatScreen({ debug = false, version, build, continueSession = false, re
|
|
|
332
283
|
if (!busy)
|
|
333
284
|
return;
|
|
334
285
|
abortControllerRef.current?.abort('User pressed Esc.');
|
|
335
|
-
|
|
336
|
-
followUpQueueRef.current = [];
|
|
337
|
-
setQueuedFollowUps([]);
|
|
338
|
-
setMessages(m => [...m, { role: 'system', text: 'Cleared queued follow-ups after interrupt.' }]);
|
|
339
|
-
}
|
|
286
|
+
followUps.clear();
|
|
340
287
|
setBusyWithHeartbeat(false);
|
|
341
288
|
}
|
|
342
|
-
function queueFollowUp(value) {
|
|
343
|
-
const trimmed = value.trim();
|
|
344
|
-
if (!trimmed)
|
|
345
|
-
return;
|
|
346
|
-
followUpQueueRef.current = [...followUpQueueRef.current, trimmed];
|
|
347
|
-
setQueuedFollowUps(followUpQueueRef.current);
|
|
348
|
-
setMessages(m => [...m, { role: 'system', text: `Queued follow-up (${followUpQueueRef.current.length}): ${trimmed}` }]);
|
|
349
|
-
}
|
|
350
289
|
function closeInputList() {
|
|
351
290
|
if (mode !== 'chat') {
|
|
352
291
|
setMode('chat');
|
|
@@ -389,7 +328,7 @@ function ChatScreen({ debug = false, version, build, continueSession = false, re
|
|
|
389
328
|
}
|
|
390
329
|
if (busy) {
|
|
391
330
|
if (mode === 'chat')
|
|
392
|
-
|
|
331
|
+
followUps.queue(value);
|
|
393
332
|
return;
|
|
394
333
|
}
|
|
395
334
|
// Any new submission supersedes a paused-task resume affordance.
|
|
@@ -510,11 +449,7 @@ function ChatScreen({ debug = false, version, build, continueSession = false, re
|
|
|
510
449
|
await clearTasksFromStore().catch(() => undefined);
|
|
511
450
|
}
|
|
512
451
|
await runSingleAgentTurn(value, displayValue, turnOptions);
|
|
513
|
-
|
|
514
|
-
const next = followUpQueueRef.current[0];
|
|
515
|
-
followUpQueueRef.current = followUpQueueRef.current.slice(1);
|
|
516
|
-
setQueuedFollowUps(followUpQueueRef.current);
|
|
517
|
-
setMessages(m => [...m, { role: 'system', text: `Running queued follow-up: ${next}` }]);
|
|
452
|
+
for (let next = followUps.takeNext(); next !== undefined; next = followUps.takeNext()) {
|
|
518
453
|
const preparedFollowUp = await prepareUserInput(next);
|
|
519
454
|
if (!preparedFollowUp)
|
|
520
455
|
continue;
|
|
@@ -613,6 +548,7 @@ function ChatScreen({ debug = false, version, build, continueSession = false, re
|
|
|
613
548
|
sessionRecorder.recordWorkState(state);
|
|
614
549
|
},
|
|
615
550
|
compactConversation,
|
|
551
|
+
recordCompaction: entry => sessionRecorder.recordCompactEntry(entry),
|
|
616
552
|
recordTokenUsage: usage => {
|
|
617
553
|
setTokenUsage(current => accumulateTokenUsage(current, usage));
|
|
618
554
|
},
|
|
@@ -624,6 +560,9 @@ function ChatScreen({ debug = false, version, build, continueSession = false, re
|
|
|
624
560
|
log: llmLogRef.current,
|
|
625
561
|
},
|
|
626
562
|
...(resumeExisting ? { resumeFrom: resumeExisting } : {}),
|
|
563
|
+
// Durable goal ledger (P1): every supervisor boundary appends to the
|
|
564
|
+
// session JSONL so a crash or restart leaves a resumable frontier.
|
|
565
|
+
goalLedger: { append: entry => sessionRecorder.recordGoalEntry(entry) },
|
|
627
566
|
...(turnOptions.attachments || turnOptions.blessedPaths || turnOptions.ephemeralControl || turnOptions.subagentOverrides ? { turnOptions } : {})
|
|
628
567
|
});
|
|
629
568
|
await sessionRecorder.flush().catch(showPersistenceWarning);
|
|
@@ -654,14 +593,13 @@ function ChatScreen({ debug = false, version, build, continueSession = false, re
|
|
|
654
593
|
{ kind: 'header', key: 'header', subtitle: headerSubtitle },
|
|
655
594
|
...staticTranscriptItems,
|
|
656
595
|
];
|
|
657
|
-
const busyElapsed = busyElapsedLabel(turnStartedAtRef.current);
|
|
658
596
|
const contentWidth = Math.max(1, width - 2);
|
|
659
597
|
// Live-region budget: once the dynamic frame exceeds the viewport, Ink falls
|
|
660
598
|
// back to clearTerminal + full transcript replay, which wipes scrollback and
|
|
661
599
|
// jumps to the top on every render. Every dynamic section is therefore
|
|
662
600
|
// clamped so the frame stays under one screen (see chat/liveRegion.ts).
|
|
663
601
|
const busyRows = busy ? (showingTip ? 2 : 1) : 0;
|
|
664
|
-
const queuedRows =
|
|
602
|
+
const queuedRows = followUps.queued.length > 0 ? 2 + followUps.queued.length : 0;
|
|
665
603
|
const collapsedTaskRows = Math.min(visibleTasks.length, MAX_VISIBLE_TASKS);
|
|
666
604
|
const expandedTaskCap = Math.max(MAX_VISIBLE_TASKS, terminalRows - 18);
|
|
667
605
|
const expandedTaskRows = Math.min(visibleTasks.length, expandedTaskCap) + (visibleTasks.length > expandedTaskCap ? 1 : 0);
|
|
@@ -682,7 +620,7 @@ function ChatScreen({ debug = false, version, build, continueSession = false, re
|
|
|
682
620
|
// One row for the optional header plus one for the item's bottom margin.
|
|
683
621
|
const chrome = (item.showHeader === false ? 0 : 1) + 1;
|
|
684
622
|
return _jsx(MessageView, { message: item.message, width: contentWidth, showHeader: item.showHeader, maxVisibleLines: Math.max(1, perStreamingItemRows - chrome) }, item.key);
|
|
685
|
-
}) }), 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))] }),
|
|
623
|
+
}) }), debug && debugLogs.length > 0 && _jsxs(Box, { flexDirection: "column", flexShrink: 0, marginBottom: 1, borderStyle: "round", borderColor: theme.muted, paddingX: 1, children: [_jsx(Text, { color: theme.muted, bold: true, children: "Debug" }), debugLogs.map((line, index) => _jsxs(Text, { color: theme.muted, children: ["\u2022 ", line] }, index))] }), followUps.queued.length > 0 && _jsxs(Box, { flexDirection: "column", flexShrink: 0, marginBottom: 1, children: [_jsx(Text, { color: theme.muted, children: "Queued follow-ups:" }), followUps.queued.map((item, index) => _jsxs(Text, { color: theme.muted, children: [" ", index + 1, ". ", item] }, `${index}-${item}`))] }), pausedResume && !busy && _jsxs(Box, { flexShrink: 0, marginBottom: 1, children: [_jsxs(Text, { color: theme.muted, children: [pausedResume.kind === 'incomplete-goal' ? 'Unfinished goal paused (no measurable progress)' : 'Unfinished goal paused (model stream stalled)', " \u00B7 "] }), _jsxs(Text, { color: theme.command, bold: true, children: ["Press R to ", pausedResume.kind === 'incomplete-goal' ? 'resume' : 'retry'] }), _jsx(Text, { color: theme.muted, children: " or type a follow-up" })] }), visibleTasks.length > 0 && _jsx(Box, { flexDirection: "column", flexShrink: 0, marginBottom: 1, children: _jsx(TaskBar, { tasks: visibleTasks, width: contentWidth, expanded: tasksExpanded, padding: taskBarPadding, maxRows: expandedTaskCap }) }), busy && _jsx(BusyBar, { label: busyLabel, elapsed: busyElapsed, tip: showingTip ? TIPS[tipIndex] : undefined }), _jsx(Box, { borderStyle: "round", borderColor: theme.border, paddingX: 1, flexShrink: 0, children: _jsx(Box, { flexGrow: 1, minWidth: 0, children: _jsx(TextInput, { placeholder: placeholder, disabled: busy && mode !== 'chat', mask: MASKED_MODES.has(mode), historyItems: inputHistory, recordHistory: mode === 'chat', suggestions: inputSuggestions, suggestionMode: PICKER_MODES.has(mode) ? 'always' : 'slash', submitOnEmpty: SUBMIT_EMPTY_MODES.has(mode), width: Math.max(20, contentWidth - 4), getMentionSuggestions: fileMentionSuggestions, onHistoryAdd: persistInputHistory, onToggleTasks: () => {
|
|
686
624
|
if (!tasksExpanded) {
|
|
687
625
|
setTaskBarPadding(0);
|
|
688
626
|
setTasksExpanded(true);
|
|
@@ -693,7 +631,7 @@ function ChatScreen({ debug = false, version, build, continueSession = false, re
|
|
|
693
631
|
setTaskBarPadding(Math.max(0, expandedRows - collapsedRows));
|
|
694
632
|
setTasksExpanded(false);
|
|
695
633
|
}
|
|
696
|
-
}, onCancel: cancelThinking, onResumeKey: pausedResume != null && !busy ? resumePausedTask : undefined, onEscape: () => {
|
|
634
|
+
}, onCancel: cancelThinking, onResumeKey: pausedResume != null && !busy ? resumePausedTask : undefined, onInterrupt: () => exit(), onEscape: () => {
|
|
697
635
|
if (busy)
|
|
698
636
|
cancelThinking();
|
|
699
637
|
else
|
|
@@ -723,7 +661,28 @@ export async function chatCommand(options = {}) {
|
|
|
723
661
|
// Incremental rendering rewrites only changed lines of the live frame, removing
|
|
724
662
|
// the full-frame erase/rewrite flicker while streaming. The fps cap aligns with
|
|
725
663
|
// the ~80ms spinner cadence; faster renders would only repaint unchanged lines.
|
|
726
|
-
|
|
664
|
+
//
|
|
665
|
+
// Kitty keyboard protocol (auto-detected): without opting in, terminals send a
|
|
666
|
+
// bare \r for Shift+Enter — indistinguishable from Enter — so Shift+Enter would
|
|
667
|
+
// submit the prompt instead of inserting a newline. With the disambiguate flag,
|
|
668
|
+
// compliant terminals (kitty, WezTerm, Ghostty, iTerm2 >=3.5, foot, recent
|
|
669
|
+
// Windows Terminal, tmux passthrough) report modified Enter as CSI 13;<mod>u,
|
|
670
|
+
// which TextInput maps to a newline. Ink queries support first (CSI ? u) with a
|
|
671
|
+
// 200ms timeout, pushes/pops the terminal's flag stack across lifecycle, and
|
|
672
|
+
// leaves unsupporting terminals (e.g. macOS Terminal.app) untouched; Enter,
|
|
673
|
+
// Tab, and Backspace without modifiers keep their legacy bytes.
|
|
674
|
+
//
|
|
675
|
+
// The protocol also re-encodes Ctrl+C as CSI 99;5u, which Ink 7.1.1's
|
|
676
|
+
// exit-on-CtrlC (raw \x03 check) does not recognize — its useInput layer
|
|
677
|
+
// would swallow the parsed c+ctrl without exiting. haze therefore owns the
|
|
678
|
+
// interrupt: render with exitOnCtrlC disabled and let ChatScreen's TextInput
|
|
679
|
+
// onInterrupt (useApp exit) terminate for both encodings.
|
|
680
|
+
const app = render(_jsx(ChatScreen, { debug: options.debug, version: options.version, build: options.build, continueSession: options.continueSession, resumeSessionId: options.resumeSessionId, noSession: options.noSession }), {
|
|
681
|
+
incrementalRendering: true,
|
|
682
|
+
maxFps: 15,
|
|
683
|
+
kittyKeyboard: { mode: 'auto', flags: ['disambiguateEscapeCodes'] },
|
|
684
|
+
exitOnCtrlC: false,
|
|
685
|
+
});
|
|
727
686
|
try {
|
|
728
687
|
await app.waitUntilExit();
|
|
729
688
|
await teardownBackgroundProcesses().catch(() => undefined);
|
|
@@ -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;
|
|
@@ -184,39 +184,10 @@ export function busyToolLabel(toolName, input) {
|
|
|
184
184
|
return `Running ${toolName}`;
|
|
185
185
|
}
|
|
186
186
|
}
|
|
187
|
-
export function formatSeconds(milliseconds) {
|
|
188
|
-
return `${(milliseconds / 1000).toFixed(1)}s`;
|
|
189
|
-
}
|
|
190
187
|
/** Compact transcript row for a user-attached image (F03); never dumps bytes. */
|
|
191
188
|
export function imageAttachmentLine(attachment) {
|
|
192
189
|
return `🖼 ${attachment.fileName} (${formatBytes(attachment.bytes)})`;
|
|
193
190
|
}
|
|
194
|
-
export function formatElapsedTime(milliseconds) {
|
|
195
|
-
const totalSeconds = Math.max(0, milliseconds / 1000);
|
|
196
|
-
const wholeSeconds = Math.floor(totalSeconds);
|
|
197
|
-
const seconds = totalSeconds - Math.floor(wholeSeconds / 60) * 60;
|
|
198
|
-
const totalMinutes = Math.floor(wholeSeconds / 60);
|
|
199
|
-
const minutes = totalMinutes % 60;
|
|
200
|
-
const hours = Math.floor(totalMinutes / 60);
|
|
201
|
-
const secondsLabel = `${seconds.toFixed(1)}s`;
|
|
202
|
-
if (hours > 0)
|
|
203
|
-
return `${hours}h ${minutes}m ${secondsLabel}`;
|
|
204
|
-
if (minutes > 0)
|
|
205
|
-
return `${minutes}m ${secondsLabel}`;
|
|
206
|
-
return secondsLabel;
|
|
207
|
-
}
|
|
208
|
-
export function formatElapsedTimeWhole(milliseconds) {
|
|
209
|
-
const totalSeconds = Math.max(0, Math.floor(milliseconds / 1000));
|
|
210
|
-
const seconds = totalSeconds % 60;
|
|
211
|
-
const totalMinutes = Math.floor(totalSeconds / 60);
|
|
212
|
-
const minutes = totalMinutes % 60;
|
|
213
|
-
const hours = Math.floor(totalMinutes / 60);
|
|
214
|
-
if (hours > 0)
|
|
215
|
-
return `${hours}h ${minutes}m ${seconds}s`;
|
|
216
|
-
if (minutes > 0)
|
|
217
|
-
return `${minutes}m ${seconds}s`;
|
|
218
|
-
return `${seconds}s`;
|
|
219
|
-
}
|
|
220
191
|
const CONTEXT_CATEGORY_LABEL = {
|
|
221
192
|
builtin: 'Built-in',
|
|
222
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,13 +54,19 @@ 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':
|
|
62
67
|
return { type: 'step_end', attempt: event.attempt, step: event.step, finishReason: event.finishReason, toolCallCount: event.toolCallCount, usage: event.usage, ...(event.responseModel ? { responseModel: event.responseModel } : {}), at: event.at };
|
|
68
|
+
case 'resource_rollover':
|
|
69
|
+
return { type: 'resource_rollover', attempt: event.attempt, completedSteps: event.completedSteps, toolCalls: event.toolCalls, prefixPreserved: event.prefixPreserved, reason: event.reason, at: event.at };
|
|
63
70
|
case 'message_start':
|
|
64
71
|
return { type: 'message_start', id: event.id, role: event.role, at: event.at };
|
|
65
72
|
case 'message_update':
|
|
@@ -83,6 +90,10 @@ function toHeadlessStreamEvent(event) {
|
|
|
83
90
|
return { ...(event.requested ? { requested: event.requested } : {}), type: 'reasoning_policy', effective: event.effective, reason: event.reason, at: event.at };
|
|
84
91
|
case 'context_budget':
|
|
85
92
|
return { type: 'context_budget', contextWindowTokens: event.contextWindowTokens, source: event.source, at: event.at };
|
|
93
|
+
case 'compaction_start':
|
|
94
|
+
return { type: 'compaction_start', reason: event.reason, method: event.method, at: event.at };
|
|
95
|
+
case 'compaction_end':
|
|
96
|
+
return { ...(event.olderCount === undefined ? {} : { olderCount: event.olderCount }), ...(event.keptCount === undefined ? {} : { keptCount: event.keptCount }), ...(event.willRetry === undefined ? {} : { willRetry: event.willRetry }), ...(event.error === undefined ? {} : { error: event.error }), type: 'compaction_end', reason: event.reason, method: event.method, compacted: event.compacted, at: event.at };
|
|
86
97
|
}
|
|
87
98
|
}
|
|
88
99
|
function writeNdjson(value) {
|
|
@@ -184,6 +195,16 @@ export async function runHeadless(options) {
|
|
|
184
195
|
void streamSink.write(headlessEvent);
|
|
185
196
|
}
|
|
186
197
|
: undefined;
|
|
198
|
+
// Bounded, cross-output-mode collection of gate decisions and pauses so
|
|
199
|
+
// `--output json` consumers see *why* a goal continued or paused, not only
|
|
200
|
+
// that it did. The same events stream live in
|
|
201
|
+
// stream-json mode.
|
|
202
|
+
const goalNotices = [];
|
|
203
|
+
const recordEvent = (event) => {
|
|
204
|
+
if (event.type === 'goal_notice' && goalNotices.length < 20)
|
|
205
|
+
goalNotices.push(event.text);
|
|
206
|
+
emitStreamEvent?.(event);
|
|
207
|
+
};
|
|
187
208
|
const callbacks = {
|
|
188
209
|
addMessage: (msg) => {
|
|
189
210
|
if (msg.role === 'assistant')
|
|
@@ -222,7 +243,7 @@ export async function runHeadless(options) {
|
|
|
222
243
|
conversation = result.messages;
|
|
223
244
|
return true;
|
|
224
245
|
},
|
|
225
|
-
onEvent:
|
|
246
|
+
onEvent: recordEvent,
|
|
226
247
|
log,
|
|
227
248
|
};
|
|
228
249
|
let status;
|
|
@@ -235,7 +256,55 @@ export async function runHeadless(options) {
|
|
|
235
256
|
// The logical-goal supervisor owns the whole request: `--timeout` bounds
|
|
236
257
|
// the entire goal, and per-turn budgets merely end physical turns that
|
|
237
258
|
// continue automatically while recoverable work and progress remain.
|
|
238
|
-
|
|
259
|
+
// `--until-done` (P6) adds a bounded in-process relaunch loop on top:
|
|
260
|
+
// transient model failures (model-error, idle-stall exhaustion) with a
|
|
261
|
+
// live frontier re-enter the supervisor with backoff, until structural
|
|
262
|
+
// completion, the goal deadline, or the poison guard (repeated relaunches
|
|
263
|
+
// with no frontier progress). Unattendedness never grants authority: the
|
|
264
|
+
// supervisor resumes work, not permissions.
|
|
265
|
+
const deadlineAt = turnDeadlineMs != null ? Date.now() + turnDeadlineMs : undefined;
|
|
266
|
+
const runOnce = async (relaunchOptions) => runAgentGoal({
|
|
267
|
+
request: options.prompt,
|
|
268
|
+
displayValue: options.prompt,
|
|
269
|
+
contextFiles,
|
|
270
|
+
callbacks,
|
|
271
|
+
session,
|
|
272
|
+
modelOverride: options.modelOverride,
|
|
273
|
+
...(turnDeadlineMs != null ? { goalDeadlineMs: Math.max(1, deadlineAt - Date.now()) } : {}),
|
|
274
|
+
...(relaunchOptions.resumeFrom ? { resumeFrom: relaunchOptions.resumeFrom } : {}),
|
|
275
|
+
...(relaunchOptions.conversationCarriesRequest ? { conversationCarriesRequest: true } : {}),
|
|
276
|
+
});
|
|
277
|
+
let goalResult = await runOnce({});
|
|
278
|
+
if (options.untilDone) {
|
|
279
|
+
const poisonLimit = 3;
|
|
280
|
+
let relaunches = 0;
|
|
281
|
+
let noProgressRelaunches = 0;
|
|
282
|
+
let lastSignature;
|
|
283
|
+
while (goalResult.status === 'failed'
|
|
284
|
+
&& (goalResult.stopReason === 'model-error' || goalResult.stopReason === 'model-stream-idle')) {
|
|
285
|
+
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);
|
|
286
|
+
noProgressRelaunches = lastSignature != null && signature === lastSignature ? noProgressRelaunches + 1 : 0;
|
|
287
|
+
lastSignature = signature;
|
|
288
|
+
if (noProgressRelaunches >= poisonLimit) {
|
|
289
|
+
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`);
|
|
290
|
+
break;
|
|
291
|
+
}
|
|
292
|
+
if (deadlineAt != null && Date.now() >= deadlineAt)
|
|
293
|
+
break;
|
|
294
|
+
relaunches += 1;
|
|
295
|
+
const delayMs = Math.min(30_000, 1_000 * 2 ** Math.min(relaunches, 5));
|
|
296
|
+
callbacks.onEvent?.(agentEvent({ type: 'goal_resume', goalId: `relaunch-${relaunches}`, relaunch: relaunches, stopReason: goalResult.stopReason, reason: `transient ${goalResult.stopReason}; relaunching with ${delayMs}ms backoff` }));
|
|
297
|
+
process.stderr.write(`haze --until-done: ${goalResult.stopReason} on cycle ${goalResult.cycles}; relaunching (attempt ${relaunches}, backoff ${delayMs}ms).\n`);
|
|
298
|
+
await new Promise(resolve => setTimeout(resolve, delayMs));
|
|
299
|
+
// A paused checkpoint (idle stall) resumes it; a hard model error has
|
|
300
|
+
// no checkpoint, but the conversation is preserved — re-enter against
|
|
301
|
+
// it without duplicating the user request.
|
|
302
|
+
goalResult = await runOnce({
|
|
303
|
+
...(goalResult.resume?.kind === 'incomplete-goal' ? { resumeFrom: goalResult.resume } : {}),
|
|
304
|
+
...(goalResult.resume ? {} : { conversationCarriesRequest: conversation.length > 0 }),
|
|
305
|
+
});
|
|
306
|
+
}
|
|
307
|
+
}
|
|
239
308
|
status = goalResult.status;
|
|
240
309
|
evidence = goalResult.evidence;
|
|
241
310
|
goal = {
|
|
@@ -270,7 +339,7 @@ export async function runHeadless(options) {
|
|
|
270
339
|
if (streamSink)
|
|
271
340
|
await streamSink.flush().catch(() => undefined);
|
|
272
341
|
// 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 } : {}) };
|
|
342
|
+
const resultLine = { type: 'result', status, result, usage: pinnedUsage(usage), ...(evidence ? { evidence } : {}), ...(goal ? { goal } : {}), ...(goalNotices.length > 0 ? { notices: goalNotices.slice(-5) } : {}) };
|
|
274
343
|
if (streamSink)
|
|
275
344
|
await streamSink.write(resultLine).catch(() => undefined);
|
|
276
345
|
else
|
|
@@ -2,6 +2,7 @@ import type { ContextFile } from '../../../config/contextFiles.js';
|
|
|
2
2
|
import type { PromptSession } from '../../../llm/systemPrompt.js';
|
|
3
3
|
import type { TurnExecutionScope } from '../../../llm/requestContext.js';
|
|
4
4
|
import type { ToolExecutionBudgetState, TurnBudget } from '../../../core/agent/budgets.js';
|
|
5
|
+
import type { ContextUsageAnchor } from '../../../core/agent/contextBudget.js';
|
|
5
6
|
import type { TurnExecutionState } from '../../../core/agent/completionController.js';
|
|
6
7
|
import type { SessionGoal } from '../../../core/agent/goalPolicy.js';
|
|
7
8
|
import { type AgentAttemptResult } from './attemptOutcome.js';
|
|
@@ -14,7 +15,12 @@ export interface AgentAttemptInput {
|
|
|
14
15
|
callbacks: StreamCallbacks;
|
|
15
16
|
retryAttempt: number;
|
|
16
17
|
retryingExistingRequest: boolean;
|
|
17
|
-
|
|
18
|
+
/** Multiplier for the message-token budget after context-overflow retries (1 = none; Pillar 1.4). */
|
|
19
|
+
overflowShrinkFactor: number;
|
|
20
|
+
/** Context-overflow retries already consumed by this turn (Pillar 1.4). */
|
|
21
|
+
overflowRetries: number;
|
|
22
|
+
/** Whether this attempt runs after progress since the previous retry (Pillar 1.3 pool reset). */
|
|
23
|
+
progressSinceLastRetry: boolean;
|
|
18
24
|
session: PromptSession | undefined;
|
|
19
25
|
modelOverride: string | undefined;
|
|
20
26
|
abortController: AbortController;
|
|
@@ -32,6 +38,10 @@ export interface AgentAttemptInput {
|
|
|
32
38
|
/** Exactly-once teardown registry; shared with the turn's forced-settlement path. */
|
|
33
39
|
cleanup: AttemptCleanupRegistry;
|
|
34
40
|
remainingTurnDeadlineMs: () => number;
|
|
41
|
+
/** Turn-scoped usage anchor for provider-usage-backed context estimation (Pillar 1.1). */
|
|
42
|
+
usageAnchor: {
|
|
43
|
+
current: ContextUsageAnchor | undefined;
|
|
44
|
+
};
|
|
35
45
|
}
|
|
36
46
|
/**
|
|
37
47
|
* Run one agent attempt end to end: setup (`attemptSetup`), the stream loop
|
|
@@ -15,7 +15,11 @@ import { ATTEMPT_TEARDOWN_BOUND_MS } from './attemptLifecycle.js';
|
|
|
15
15
|
* display are always torn down.
|
|
16
16
|
*/
|
|
17
17
|
export async function runAgentAttempt(input) {
|
|
18
|
-
const { value, contextFiles, callbacks,
|
|
18
|
+
const { value, contextFiles, callbacks, retryingExistingRequest, session, modelOverride, abortController, turnOptions, turnScope, turnState, turnBudget, globalBudget, sliceBudget, goal, abortCause, cleanup, remainingTurnDeadlineMs, usageAnchor } = input;
|
|
19
|
+
// Pillar 1.3: progress since the previous retry resets the shared retry pool
|
|
20
|
+
// (mirrors a per-burst budget), applied to both the stall guard's retry
|
|
21
|
+
// eligibility and the failure classification below.
|
|
22
|
+
const retryAttempt = input.progressSinceLastRetry && input.retryAttempt > 0 ? 0 : input.retryAttempt;
|
|
19
23
|
callbacks.setBusyLabel?.(modelThinkingLabel(undefined));
|
|
20
24
|
let loadedMcp;
|
|
21
25
|
let lspPool;
|
|
@@ -43,7 +47,7 @@ export async function runAgentAttempt(input) {
|
|
|
43
47
|
let stallGuard;
|
|
44
48
|
let setup;
|
|
45
49
|
try {
|
|
46
|
-
setup = await prepareAttempt({ value, contextFiles, callbacks, retryingExistingRequest,
|
|
50
|
+
setup = await prepareAttempt({ value, contextFiles, callbacks, retryingExistingRequest, overflowShrinkFactor: input.overflowShrinkFactor, session, modelOverride, abortController, turnOptions, turnScope, turnBudget, globalBudget, sliceBudget, goal, onContextFileRead: path => toolDisplay.addContextFileRead(path), usageAnchor });
|
|
47
51
|
if (!setup)
|
|
48
52
|
return { status: 'failed' };
|
|
49
53
|
const attemptSetupResult = setup;
|
|
@@ -66,11 +70,11 @@ export async function runAgentAttempt(input) {
|
|
|
66
70
|
log: callbacks.log,
|
|
67
71
|
debugLog: callbacks.debugLog,
|
|
68
72
|
});
|
|
69
|
-
const stream = await runAttemptStream({ setup, callbacks, abortController, retryAttempt, recoverySlice: turnOptions.recoverySlice, turnState, turnBudget, globalBudget, goal, stallGuard, loopState, toolDisplay, salvage });
|
|
70
|
-
return finalizeAttemptOutcome({ value, callbacks, abortController, turnOptions, turnState, turnBudget, goal, remainingTurnDeadlineMs, stream });
|
|
73
|
+
const stream = await runAttemptStream({ setup, callbacks, abortController, retryAttempt, recoverySlice: turnOptions.recoverySlice, turnState, turnBudget, globalBudget, goal, stallGuard, loopState, toolDisplay, salvage, usageAnchor });
|
|
74
|
+
return finalizeAttemptOutcome({ value, callbacks, abortController, turnOptions, turnState, turnBudget, goal, remainingTurnDeadlineMs, stream, retryAttempt, overflowRetries: input.overflowRetries });
|
|
71
75
|
}
|
|
72
76
|
catch (error) {
|
|
73
|
-
return handleAttemptFailure({ value, callbacks, abortController, turnState, retryAttempt,
|
|
77
|
+
return handleAttemptFailure({ value, callbacks, abortController, turnState, retryAttempt, progressSinceLastRetry: input.progressSinceLastRetry, overflowRetries: input.overflowRetries, abortCause, stallGuard, salvage, error, maxRetries: setup?.modelRetries, retryBaseDelayMs: setup?.retryBaseDelayMs, goal, turnOptions });
|
|
74
78
|
}
|
|
75
79
|
finally {
|
|
76
80
|
await cleanup.closeOnce(ATTEMPT_TEARDOWN_BOUND_MS);
|
|
@@ -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;
|