@denizokcu/haze 1.1.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 +24 -1
- package/README.md +9 -5
- 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 +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 -815
- package/dist/cli/commands/chat.js +45 -108
- 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 +67 -4
- 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/index.js +3 -1
- package/dist/config/providerPresets.d.ts +7 -0
- package/dist/config/providerPresets.js +195 -391
- 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/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/tools/taskTool.d.ts +64 -208
- package/dist/llm/tools/taskTool.js +22 -10
- package/dist/ui/components/TextInput.js +6 -67
- 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 +1 -1
- 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;
|
|
@@ -624,6 +559,9 @@ function ChatScreen({ debug = false, version, build, continueSession = false, re
|
|
|
624
559
|
log: llmLogRef.current,
|
|
625
560
|
},
|
|
626
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) },
|
|
627
565
|
...(turnOptions.attachments || turnOptions.blessedPaths || turnOptions.ephemeralControl || turnOptions.subagentOverrides ? { turnOptions } : {})
|
|
628
566
|
});
|
|
629
567
|
await sessionRecorder.flush().catch(showPersistenceWarning);
|
|
@@ -654,14 +592,13 @@ function ChatScreen({ debug = false, version, build, continueSession = false, re
|
|
|
654
592
|
{ kind: 'header', key: 'header', subtitle: headerSubtitle },
|
|
655
593
|
...staticTranscriptItems,
|
|
656
594
|
];
|
|
657
|
-
const busyElapsed = busyElapsedLabel(turnStartedAtRef.current);
|
|
658
595
|
const contentWidth = Math.max(1, width - 2);
|
|
659
596
|
// Live-region budget: once the dynamic frame exceeds the viewport, Ink falls
|
|
660
597
|
// back to clearTerminal + full transcript replay, which wipes scrollback and
|
|
661
598
|
// jumps to the top on every render. Every dynamic section is therefore
|
|
662
599
|
// clamped so the frame stays under one screen (see chat/liveRegion.ts).
|
|
663
600
|
const busyRows = busy ? (showingTip ? 2 : 1) : 0;
|
|
664
|
-
const queuedRows =
|
|
601
|
+
const queuedRows = followUps.queued.length > 0 ? 2 + followUps.queued.length : 0;
|
|
665
602
|
const collapsedTaskRows = Math.min(visibleTasks.length, MAX_VISIBLE_TASKS);
|
|
666
603
|
const expandedTaskCap = Math.max(MAX_VISIBLE_TASKS, terminalRows - 18);
|
|
667
604
|
const expandedTaskRows = Math.min(visibleTasks.length, expandedTaskCap) + (visibleTasks.length > expandedTaskCap ? 1 : 0);
|
|
@@ -682,7 +619,7 @@ function ChatScreen({ debug = false, version, build, continueSession = false, re
|
|
|
682
619
|
// One row for the optional header plus one for the item's bottom margin.
|
|
683
620
|
const chrome = (item.showHeader === false ? 0 : 1) + 1;
|
|
684
621
|
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))] }),
|
|
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: () => {
|
|
686
623
|
if (!tasksExpanded) {
|
|
687
624
|
setTaskBarPadding(0);
|
|
688
625
|
setTasksExpanded(true);
|
|
@@ -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,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
|
|
@@ -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;
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { agentEvent } from '../../../core/agent/events.js';
|
|
2
|
+
import { assistantDisplayText, normalizeAssistantText, isHiddenAssistantFragment, isHiddenUnstartedFinalText, isShortLeadInBeforeTool, isShortUnfinishedLeadIn } from './assistantText.js';
|
|
3
|
+
import { responseCompletionMetrics } from './turnRuntime.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 function resetAssistantSegment(loopState) {
|
|
11
|
+
loopState.currentAssistantId = `assistant-${Date.now()}-${Math.random().toString(36).slice(2)}`;
|
|
12
|
+
loopState.assistantStarted = false;
|
|
13
|
+
loopState.assistantStartedAt = Date.now();
|
|
14
|
+
loopState.currentAssistantText = '';
|
|
15
|
+
}
|
|
16
|
+
export function finalizeAssistantSegment(loopState, callbacks, options = {}) {
|
|
17
|
+
const finalText = assistantDisplayText(loopState.currentAssistantText);
|
|
18
|
+
const normalized = normalizeAssistantText(finalText);
|
|
19
|
+
const hidden = (loopState.assistantStarted ? isHiddenAssistantFragment(finalText) : isHiddenUnstartedFinalText(finalText))
|
|
20
|
+
|| (options.beforeTool === true && isShortLeadInBeforeTool(finalText))
|
|
21
|
+
|| (options.beforeTool !== true && isShortUnfinishedLeadIn(finalText))
|
|
22
|
+
|| (normalized.length > 0 && loopState.visibleAssistantTexts.has(normalized));
|
|
23
|
+
if (loopState.assistantStarted) {
|
|
24
|
+
if (!hidden)
|
|
25
|
+
loopState.rememberVisibleAssistantText(finalText);
|
|
26
|
+
callbacks.onEvent?.(agentEvent({ type: 'message_end', id: loopState.currentAssistantId, text: finalText, hidden }));
|
|
27
|
+
callbacks.updateMessage(loopState.currentAssistantId, { text: finalText, streaming: false, hidden, ...responseCompletionMetrics(finalText, loopState.assistantStartedAt) });
|
|
28
|
+
}
|
|
29
|
+
else if (!hidden) {
|
|
30
|
+
if (!hidden)
|
|
31
|
+
loopState.rememberVisibleAssistantText(finalText);
|
|
32
|
+
callbacks.onEvent?.(agentEvent({ type: 'message_start', id: loopState.currentAssistantId, role: 'assistant' }));
|
|
33
|
+
callbacks.onEvent?.(agentEvent({ type: 'message_end', id: loopState.currentAssistantId, text: finalText, hidden: false }));
|
|
34
|
+
callbacks.addMessage({ id: loopState.currentAssistantId, role: 'assistant', text: finalText, streaming: false, startedAt: loopState.assistantStartedAt, ...responseCompletionMetrics(finalText, loopState.assistantStartedAt) });
|
|
35
|
+
}
|
|
36
|
+
resetAssistantSegment(loopState);
|
|
37
|
+
return !hidden;
|
|
38
|
+
}
|
|
39
|
+
/** Finalize any pending assistant text right before a tool call starts, demoting hidden lead-ins to the tool group caption. */
|
|
40
|
+
export function finalizePendingAssistantBeforeTool(deps) {
|
|
41
|
+
const { loopState, callbacks, toolDisplay } = deps;
|
|
42
|
+
if (loopState.currentAssistantText.trim().length > 0 || loopState.assistantStarted) {
|
|
43
|
+
const pending = assistantDisplayText(loopState.currentAssistantText);
|
|
44
|
+
const shown = finalizeAssistantSegment(loopState, callbacks, { beforeTool: true });
|
|
45
|
+
if (!shown && pending)
|
|
46
|
+
toolDisplay.setGroupCaption(pending);
|
|
47
|
+
}
|
|
48
|
+
}
|
|
@@ -30,9 +30,10 @@ export declare function terminalTurnStatus(input: {
|
|
|
30
30
|
mutationCount?: number;
|
|
31
31
|
validationOutcome?: ValidationOutcome;
|
|
32
32
|
taskProgress?: WorkTaskProgress;
|
|
33
|
+
redPair?: 'not-required' | 'missing' | 'satisfied';
|
|
33
34
|
}): TurnStatus;
|
|
34
35
|
/** Bounded recovery slice an attempt proposes for the next agent call. */
|
|
35
|
-
type AttemptRecovery = {
|
|
36
|
+
export type AttemptRecovery = {
|
|
36
37
|
kind: 'length' | 'rescue' | 'goal';
|
|
37
38
|
control: string;
|
|
38
39
|
slice: {
|
|
@@ -93,4 +94,3 @@ export interface AttemptFailureDeps {
|
|
|
93
94
|
* hard model-call failure. Completed-step progress is always preserved.
|
|
94
95
|
*/
|
|
95
96
|
export declare function handleAttemptFailure(deps: AttemptFailureDeps): AgentAttemptResult;
|
|
96
|
-
export {};
|
|
@@ -4,12 +4,13 @@ import { isContextOverflowError, isRetryableModelError } from '../../../core/age
|
|
|
4
4
|
import { completionRescuePrompt, goalContinuationPrompt, lengthContinuationPrompt } from '../../../core/agent/goalPolicy.js';
|
|
5
5
|
import { assessCompletionReadiness, classifyTerminalOutcome, decideGoalContinuation, decideLengthRecovery, decideRescue, describeCompletionReadiness, goalContinuationRecoverable, isBudgetExhausted, rescueEligibleRequest } from '../../../core/agent/completionController.js';
|
|
6
6
|
import { clampSlice, remainingSteps, remainingToolCalls, DEFAULT_TURN_DEADLINE_MS, IDLE_TIMEOUT_MS, DEFAULT_MODEL_RETRIES } from '../../../core/agent/budgets.js';
|
|
7
|
-
import { deriveValidationOutcome } from '../../../core/agent/workState.js';
|
|
7
|
+
import { deriveValidationOutcome, redPairStatus } from '../../../core/agent/workState.js';
|
|
8
8
|
import { withoutRejectedAssistantFinal } from '../../../core/agent/requestAssembly.js';
|
|
9
|
-
import { buildIncompleteGoalResume } from './goalCheckpoint.js';
|
|
10
|
-
import { formatSeconds } from '
|
|
9
|
+
import { buildIncompleteGoalResume, taskCountsOf } from './goalCheckpoint.js';
|
|
10
|
+
import { formatSeconds } from '../../../utils/format.js';
|
|
11
11
|
import { retryDelayMs } from './turnRuntime.js';
|
|
12
|
-
import {
|
|
12
|
+
import { salvageConversationToLastStep } from './stallRecovery.js';
|
|
13
|
+
import { formatIdleMinutes } from '../../../utils/format.js';
|
|
13
14
|
/**
|
|
14
15
|
* CLI adapter for the authoritative turn-status decision. The pure policy
|
|
15
16
|
* lives in `core/agent/completionController.ts`; this keeps the single call site
|
|
@@ -30,6 +31,7 @@ export function terminalTurnStatus(input) {
|
|
|
30
31
|
mutationCount: input.mutationCount ?? 0,
|
|
31
32
|
...(input.validationOutcome ? { validationOutcome: input.validationOutcome } : {}),
|
|
32
33
|
...(input.taskProgress ? { taskProgress: input.taskProgress } : {}),
|
|
34
|
+
...(input.redPair ? { redPair: input.redPair } : {}),
|
|
33
35
|
};
|
|
34
36
|
return decideTerminalStatus(state, {
|
|
35
37
|
sawToolCall: input.sawToolCall,
|
|
@@ -46,6 +48,8 @@ export function projectGoalEvidence(turnState, goal) {
|
|
|
46
48
|
turnState.validationKind = goal.validations.at(-1)?.kind ?? goal.carriedValidation?.kind;
|
|
47
49
|
turnState.validationAfterMutation = goal.validationSeq > 0 && goal.validationSeq >= goal.mutationSeq;
|
|
48
50
|
turnState.taskProgress = goal.taskProgress;
|
|
51
|
+
// Opportunistic red→green: only an actually observed red can gate.
|
|
52
|
+
turnState.redPair = redPairStatus(goal);
|
|
49
53
|
}
|
|
50
54
|
/**
|
|
51
55
|
* Classify the finished attempt: project work evidence onto the turn state,
|
|
@@ -64,7 +68,7 @@ export function finalizeAttemptOutcome(deps) {
|
|
|
64
68
|
const completionEvidence = { sawToolCall: stream.sawToolCall, assistantText: stream.assistantText, lastToolOk: stream.lastToolOk, unresolvedToolInputError: stream.unresolvedToolInputError };
|
|
65
69
|
const readiness = assessCompletionReadiness(turnState, completionEvidence);
|
|
66
70
|
const classification = classifyTerminalOutcome(turnState, completionEvidence);
|
|
67
|
-
const turnStatus = terminalTurnStatus({ aborted: false, assistantText: stream.assistantText, sawToolCall: stream.sawToolCall, lastToolOk: stream.lastToolOk, finishReason: stream.finishReason, budgetReached: turnState.budgetBoundary, unresolvedToolInputError: stream.unresolvedToolInputError, intent: turnState.intent, mutationCount: turnState.mutationCount, validationOutcome: turnState.validationOutcome, taskProgress: turnState.taskProgress });
|
|
71
|
+
const turnStatus = terminalTurnStatus({ aborted: false, assistantText: stream.assistantText, sawToolCall: stream.sawToolCall, lastToolOk: stream.lastToolOk, finishReason: stream.finishReason, budgetReached: turnState.budgetBoundary, unresolvedToolInputError: stream.unresolvedToolInputError, intent: turnState.intent, mutationCount: turnState.mutationCount, validationOutcome: turnState.validationOutcome, taskProgress: turnState.taskProgress, ...(turnState.redPair ? { redPair: turnState.redPair } : {}) });
|
|
68
72
|
if (stream.unresolvedMalformedToolName)
|
|
69
73
|
callbacks.addMessage({ role: 'system', text: `${stream.unresolvedMalformedToolName} did not execute because its generated input remained invalid or truncated. The requested work is incomplete.` });
|
|
70
74
|
goal.phase = 'done';
|
|
@@ -89,10 +93,16 @@ export function finalizeAttemptOutcome(deps) {
|
|
|
89
93
|
// physical turns; a bare runAgentTurn caller surfaces them as resume info.
|
|
90
94
|
const goalId = turnOptions.goalContext?.goalId ?? goal.id;
|
|
91
95
|
const goalCycle = turnOptions.goalContext?.cycle ?? 1;
|
|
96
|
+
const carriedEvidence = {
|
|
97
|
+
...(turnOptions.goalContext?.requestHash ? { requestHash: turnOptions.goalContext.requestHash } : {}),
|
|
98
|
+
// Carry red evidence until the same check passes after the mutation. This
|
|
99
|
+
// includes boundaries reached after red capture but before the first edit.
|
|
100
|
+
...(turnState.redPair !== 'satisfied' && goal.redEvidence ? { redEvidence: { ...goal.redEvidence } } : {}),
|
|
101
|
+
};
|
|
92
102
|
const discardRejectedFinal = () => callbacks.setConversation(withoutRejectedAssistantFinal(callbacks.getConversation()));
|
|
93
103
|
const checkpointResult = () => {
|
|
94
104
|
discardRejectedFinal();
|
|
95
|
-
return { status: 'failed', resume: buildIncompleteGoalResume(value, goalId, goalCycle, turnState, readiness) };
|
|
105
|
+
return { status: 'failed', resume: buildIncompleteGoalResume(value, goalId, goalCycle, turnState, readiness, carriedEvidence) };
|
|
96
106
|
};
|
|
97
107
|
if (!abortController.signal.aborted) {
|
|
98
108
|
const lengthDecision = decideLengthRecovery(turnState, turnBudget);
|
|
@@ -116,7 +126,7 @@ export function finalizeAttemptOutcome(deps) {
|
|
|
116
126
|
discardRejectedFinal();
|
|
117
127
|
if (readiness === 'validation_failed' || readiness === 'validation_stale' || readiness === 'validation_absent_after_mutation')
|
|
118
128
|
turnState.validationContinuationUsed = true;
|
|
119
|
-
return { status: turnStatus, recovery: { kind: 'goal', control: goalContinuationPrompt(describeCompletionReadiness(readiness, turnState.taskProgress)), slice: { maxSteps: goalSlice.steps, maxToolCalls: goalSlice.toolCalls } } };
|
|
129
|
+
return { status: turnStatus, recovery: { kind: 'goal', control: goalContinuationPrompt(describeCompletionReadiness(readiness, turnState.taskProgress), taskCountsOf(turnState.taskProgress)), slice: { maxSteps: goalSlice.steps, maxToolCalls: goalSlice.toolCalls } } };
|
|
120
130
|
}
|
|
121
131
|
else if (rescueSlice && rescueSlice.steps > 0) {
|
|
122
132
|
return { status: turnStatus, recovery: { kind: 'rescue', control: completionRescuePrompt(), slice: { maxSteps: rescueSlice.steps, maxToolCalls: rescueSlice.toolCalls } } };
|