@denizokcu/haze 0.10.0 → 0.11.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 +77 -1
- package/README.md +66 -25
- package/SECURITY.md +22 -0
- package/bin/haze.js +102 -1
- package/dist/buildInfo.json +7 -0
- package/dist/cli/chat/TaskBar.d.ts +2 -1
- package/dist/cli/chat/TaskBar.js +7 -4
- package/dist/cli/chat/contextReport.js +2 -0
- package/dist/cli/chat/fileMentionSuggestions.js +3 -2
- package/dist/cli/chat/liveRegion.d.ts +25 -0
- package/dist/cli/chat/liveRegion.js +48 -0
- package/dist/cli/chat/messages.d.ts +33 -2
- package/dist/cli/chat/messages.js +216 -33
- package/dist/cli/chat/sessionLifecycle.d.ts +9 -0
- package/dist/cli/chat/sessionLifecycle.js +64 -14
- package/dist/cli/chat/sessionRecorder.js +75 -7
- package/dist/cli/chat/startupInfo.d.ts +0 -1
- package/dist/cli/chat/startupInfo.js +11 -15
- package/dist/cli/chat/wizardDispatch.js +111 -12
- package/dist/cli/commands/chat.d.ts +5 -0
- package/dist/cli/commands/chat.js +203 -101
- package/dist/cli/commands/commands.d.ts +2 -0
- package/dist/cli/commands/commands.js +10 -5
- package/dist/cli/commands/doctor.d.ts +19 -0
- package/dist/cli/commands/doctor.js +76 -0
- package/dist/cli/commands/formatters.js +2 -0
- package/dist/cli/commands/ndjsonSink.d.ts +23 -0
- package/dist/cli/commands/ndjsonSink.js +38 -0
- package/dist/cli/commands/providerWizard.d.ts +9 -2
- package/dist/cli/commands/providerWizard.js +37 -4
- package/dist/cli/commands/runCommand.d.ts +3 -0
- package/dist/cli/commands/runCommand.js +117 -11
- package/dist/cli/commands/streaming/abortCause.d.ts +24 -0
- package/dist/cli/commands/streaming/abortCause.js +16 -0
- package/dist/cli/commands/streaming/assistantText.js +9 -2
- package/dist/cli/commands/streaming/goalCheckpoint.d.ts +65 -0
- package/dist/cli/commands/streaming/goalCheckpoint.js +23 -0
- package/dist/cli/commands/streaming/goalSupervisor.d.ts +64 -0
- package/dist/cli/commands/streaming/goalSupervisor.js +127 -0
- package/dist/cli/commands/streaming/toolCallRecovery.d.ts +2 -0
- package/dist/cli/commands/streaming/toolCallRecovery.js +24 -0
- package/dist/cli/commands/streaming/toolGroupRenderer.d.ts +29 -0
- package/dist/cli/commands/streaming/toolGroupRenderer.js +50 -4
- package/dist/cli/commands/streaming/toolResultState.d.ts +6 -1
- package/dist/cli/commands/streaming/toolResultState.js +29 -7
- package/dist/cli/commands/streaming/turnOutcome.d.ts +17 -0
- package/dist/cli/commands/streaming/turnOutcome.js +27 -11
- package/dist/cli/commands/streaming.d.ts +70 -3
- package/dist/cli/commands/streaming.js +491 -77
- package/dist/cli/commands/wizardActions.d.ts +1 -0
- package/dist/cli/commands/wizardActions.js +1 -0
- package/dist/cli/commands/wizardPrompts.js +7 -1
- package/dist/cli/commands/wizardSuggestions.js +5 -3
- package/dist/cli/index.js +68 -22
- package/dist/cli/terminalTitle.js +1 -1
- package/dist/config/modelDiscovery.d.ts +51 -0
- package/dist/config/modelDiscovery.js +164 -1
- package/dist/config/privateStorage.js +28 -2
- package/dist/config/providerAuth.d.ts +14 -0
- package/dist/config/providerAuth.js +49 -0
- package/dist/config/providerPresets.d.ts +39 -7
- package/dist/config/providerPresets.js +371 -100
- package/dist/config/providers.js +2 -0
- package/dist/config/settings.d.ts +36 -0
- package/dist/config/settings.js +9 -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 +38 -0
- package/dist/core/agent/compaction.js +92 -17
- package/dist/core/agent/completionController.d.ts +230 -0
- package/dist/core/agent/completionController.js +287 -0
- package/dist/core/agent/contextBudget.d.ts +38 -0
- package/dist/core/agent/contextBudget.js +60 -7
- package/dist/core/agent/events.d.ts +74 -0
- package/dist/core/agent/reasoningPolicy.d.ts +31 -0
- package/dist/core/agent/reasoningPolicy.js +27 -0
- package/dist/core/agent/toolCapabilities.d.ts +27 -0
- package/dist/core/agent/toolCapabilities.js +58 -0
- package/dist/core/agent/toolExecutionBudget.d.ts +35 -0
- package/dist/core/agent/toolExecutionBudget.js +49 -0
- package/dist/core/agent/toolOutputStore.d.ts +8 -0
- package/dist/core/agent/toolOutputStore.js +10 -10
- package/dist/core/agent/toolResults.d.ts +12 -0
- package/dist/core/agent/toolResults.js +38 -0
- package/dist/core/agent/turnBudget.d.ts +35 -0
- package/dist/core/agent/turnBudget.js +27 -0
- package/dist/core/agent/turnPolicy.d.ts +11 -0
- package/dist/core/agent/turnPolicy.js +19 -0
- package/dist/core/agent/workState.d.ts +75 -0
- package/dist/core/agent/workState.js +120 -9
- package/dist/core/deadline.d.ts +33 -0
- package/dist/core/deadline.js +74 -0
- package/dist/core/goal/completionPolicy.d.ts +27 -0
- package/dist/core/goal/completionPolicy.js +37 -1
- package/dist/core/limits/byteBudgets.d.ts +2 -0
- package/dist/core/limits/byteBudgets.js +2 -0
- package/dist/core/limits/textBudgets.d.ts +2 -0
- package/dist/core/limits/textBudgets.js +2 -0
- package/dist/core/log/llmLog.js +7 -0
- package/dist/core/persistence/orderedFileWriter.d.ts +10 -0
- package/dist/core/persistence/orderedFileWriter.js +16 -2
- package/dist/core/process/backgroundRegistry.js +8 -7
- package/dist/core/process/runBoundedProcess.d.ts +8 -2
- package/dist/core/process/runBoundedProcess.js +15 -6
- package/dist/core/safety/missingExecutable.d.ts +42 -0
- package/dist/core/safety/missingExecutable.js +77 -0
- package/dist/core/session/sessionStore.d.ts +37 -0
- package/dist/core/session/sessionStore.js +215 -51
- package/dist/core/subagent/contracts.d.ts +4 -0
- package/dist/core/subagent/contracts.js +1 -0
- package/dist/core/subagent/subagentCoordinator.d.ts +4 -0
- package/dist/core/subagent/subagentCoordinator.js +32 -2
- package/dist/core/subagent/subagentRunner.js +17 -37
- package/dist/llm/client.d.ts +17 -1
- package/dist/llm/client.js +82 -14
- package/dist/llm/hazeTools.d.ts +554 -80
- package/dist/llm/hazeTools.js +103 -24
- package/dist/llm/lsp.d.ts +24 -4
- package/dist/llm/lsp.js +72 -11
- package/dist/llm/lspTools.d.ts +2366 -0
- package/dist/llm/lspTools.js +87 -79
- package/dist/llm/openaiCodex.d.ts +3 -0
- package/dist/llm/openaiCodex.js +47 -0
- package/dist/llm/openaiCodexOAuth.d.ts +54 -0
- package/dist/llm/openaiCodexOAuth.js +214 -0
- package/dist/llm/requestContext.d.ts +3 -0
- package/dist/llm/requestContext.js +7 -4
- package/dist/llm/systemPrompt.d.ts +11 -0
- package/dist/llm/systemPrompt.js +12 -6
- package/dist/llm/toolResultTypes.d.ts +8 -1
- package/dist/llm/tools/bashTool.d.ts +48 -16
- package/dist/llm/tools/bashTool.js +5 -0
- package/dist/llm/tools/editMatch.d.ts +14 -0
- package/dist/llm/tools/editMatch.js +72 -0
- package/dist/llm/tools/failures.d.ts +2 -0
- package/dist/llm/tools/failures.js +1 -0
- package/dist/llm/tools/fetchTool.d.ts +16 -0
- package/dist/llm/tools/fileToolShared.d.ts +4 -3
- package/dist/llm/tools/fileToolShared.js +16 -21
- package/dist/llm/tools/gitIgnore.d.ts +49 -0
- package/dist/llm/tools/gitIgnore.js +129 -0
- package/dist/llm/tools/readRecovery.d.ts +10 -0
- package/dist/llm/tools/readRecovery.js +135 -0
- package/dist/llm/tools/toolContext.d.ts +1 -1
- package/dist/llm/tools/toolContext.js +61 -32
- package/dist/llm/webFetch.d.ts +17 -0
- package/dist/llm/webFetch.js +64 -97
- package/dist/ui/codeHighlight.d.ts +4 -0
- package/dist/ui/codeHighlight.js +31 -0
- package/dist/ui/components/Header.d.ts +1 -1
- package/dist/ui/components/MarkdownText.d.ts +16 -2
- package/dist/ui/components/MarkdownText.js +244 -34
- package/dist/ui/components/TextInput.d.ts +8 -1
- package/dist/ui/components/TextInput.js +6 -2
- package/dist/ui/theme.d.ts +4 -3
- package/dist/ui/theme.js +5 -4
- package/dist/utils/buildInfo.d.ts +104 -0
- package/dist/utils/buildInfo.js +253 -0
- package/dist/utils/fs.d.ts +9 -0
- package/dist/utils/fs.js +87 -25
- package/dist/utils/openPath.d.ts +2 -2
- package/dist/utils/openPath.js +19 -6
- package/dist/utils/path.d.ts +2 -0
- package/dist/utils/path.js +5 -1
- package/dist/utils/utf8.d.ts +22 -0
- package/dist/utils/utf8.js +54 -0
- package/dist/utils/version.d.ts +9 -3
- package/dist/utils/version.js +28 -2
- package/package.json +24 -19
|
@@ -10,23 +10,32 @@ import { agentEvent } from '../../core/agent/events.js';
|
|
|
10
10
|
import { isContextOverflowError, isRetryableModelError } from '../../core/agent/errors.js';
|
|
11
11
|
import { isPlanOnlyRequest } from '../../core/goal/requestClassifier.js';
|
|
12
12
|
import { userTurnMessage } from '../../core/attachments/imageAttachments.js';
|
|
13
|
-
import { repeatedToolCallPrompt, toolLoopBudgetPrompt } from '../../core/goal/completionPolicy.js';
|
|
14
|
-
import { estimateValueTokens } from '../../core/agent/contextBudget.js';
|
|
13
|
+
import { malformedToolCallPrompt, repeatedToolCallPrompt, toolLoopBudgetPrompt, lengthContinuationPrompt, completionRescuePrompt, goalContinuationPrompt } from '../../core/goal/completionPolicy.js';
|
|
14
|
+
import { calculateRequestTokenBudget, estimateMessagesTokens, estimateValueTokens } from '../../core/agent/contextBudget.js';
|
|
15
15
|
import { compactToolHistory, stripSyntheticControls, withSyntheticControl, withoutSystemMessages } from '../../core/agent/requestAssembly.js';
|
|
16
|
-
import { isDuplicateSkippedOutput,
|
|
17
|
-
import {
|
|
18
|
-
export { uniqueRepeatedToolNames, toolOnlyStepCount } from '../../core/agent/turnPolicy.js';
|
|
16
|
+
import { isDuplicateSkippedOutput, safeToolFailureDetails, toolOutputOk } from '../../core/agent/toolResults.js';
|
|
17
|
+
import { latestRepeatedToolNames, toolOnlyStepCount } from '../../core/agent/turnPolicy.js';
|
|
18
|
+
export { latestRepeatedToolNames, uniqueRepeatedToolNames, toolOnlyStepCount } from '../../core/agent/turnPolicy.js';
|
|
19
19
|
import { compactModelMessages } from '../../core/agent/compaction.js';
|
|
20
|
-
import {
|
|
20
|
+
import { DEFAULT_MAX_OUTPUT_TOKENS, DEFAULT_TOOL_DEADLINE_MS, DEFAULT_TURN_DEADLINE_MS, IDLE_TIMEOUT_MS, MAIN_STEP_LIMIT, MAIN_TOOL_CALL_LIMIT, SUBAGENT_TOOL_DEADLINE_MS, WRITE_FILE_CHUNK_BYTES } from '../../core/agent/budgets.js';
|
|
21
|
+
import { createTurnExecutionState, assessCompletionReadiness, classifyTerminalOutcome, decideGoalContinuation, decideLengthRecovery, decideRescue, describeCompletionReadiness, goalContinuationRecoverable, isBudgetExhausted, normalizeFinishReason, recordGoalContinuation, rescueEligibleRequest, RESCUE_BOUNDARY, toCompletionEvidence } from '../../core/agent/completionController.js';
|
|
22
|
+
import { clampSlice, mainTurnBudget, remainingSteps, remainingToolCalls } from '../../core/agent/turnBudget.js';
|
|
23
|
+
import { createToolExecutionBudget, isToolBudgetBlocked, withToolExecutionBudget } from '../../core/agent/toolExecutionBudget.js';
|
|
24
|
+
import { createAbsoluteDeadline, isToolDeadlineExceeded, withToolDeadline } from '../../core/deadline.js';
|
|
25
|
+
import { isMutatingCapability, isValidationCapable } from '../../core/agent/toolCapabilities.js';
|
|
26
|
+
import { deriveValidationOutcome, seedCarriedGoalEvidence } from '../../core/agent/workState.js';
|
|
21
27
|
import { createSessionGoal, formatGoalStatus, observeGoalToolEvent } from '../../core/goal/sessionGoal.js';
|
|
28
|
+
import { buildIncompleteGoalResume } from './streaming/goalCheckpoint.js';
|
|
22
29
|
import { sanitizeAssistantText, assistantDisplayText, normalizeAssistantText, shouldStartAssistantStream, isHiddenAssistantFragment, isHiddenUnstartedFinalText, isShortLeadInBeforeTool, isShortUnfinishedLeadIn } from './streaming/assistantText.js';
|
|
23
|
-
import { createToolGroupRenderer } from './streaming/toolGroupRenderer.js';
|
|
24
|
-
import {
|
|
30
|
+
import { createToolGroupRenderer, toolDiffFromResult } from './streaming/toolGroupRenderer.js';
|
|
31
|
+
import { applyStepToolResultState, initialToolResultState } from './streaming/toolResultState.js';
|
|
25
32
|
import { abortableDelay, estimateInputBreakdown, extractUsage, rememberContextFilesFromToolOutput, responseCompletionMetrics, retryDelayMs, stepCacheMetrics, subagentTokenEstimate } from './streaming/turnRuntime.js';
|
|
26
33
|
import { toolsContextFor } from '../../llm/tools/toolContext.js';
|
|
27
34
|
import { modelThinkingLabel } from '../../utils/modelName.js';
|
|
28
35
|
import { terminalTurnStatus } from './streaming/turnOutcome.js';
|
|
29
36
|
import { createIdleTimer } from './streaming/idleTimer.js';
|
|
37
|
+
import { abortForTurn, createUserAbortCause } from './streaming/abortCause.js';
|
|
38
|
+
import { isMalformedToolInputError } from './streaming/toolCallRecovery.js';
|
|
30
39
|
import { WorkspaceMutationPolicy } from '../../core/subagent/workspaceMutationPolicy.js';
|
|
31
40
|
function logEntry(log, entry) {
|
|
32
41
|
if (log)
|
|
@@ -39,19 +48,88 @@ function withScopedContextControl(messages, context) {
|
|
|
39
48
|
context.pendingContextFiles = [];
|
|
40
49
|
return withSyntheticControl(messages, `Additional scoped project instructions were just read for a non-root path touched by a tool call. Apply them to subsequent work in that subtree.${projectContextSection(files)}`);
|
|
41
50
|
}
|
|
42
|
-
|
|
51
|
+
/**
|
|
52
|
+
* Restrict a tool set to the capabilities permitted in a completion-rescue
|
|
53
|
+
* slice: mutation (edit/write/replace) and validation-capable (bash) built-in
|
|
54
|
+
* tools only. Discovery, read, coordinate, and all third-party (MCP) tools are
|
|
55
|
+
* dropped so the rescue cannot reopen exploration. May return an empty set
|
|
56
|
+
* when no built-in mutation/validation tools exist (only possible if builtins
|
|
57
|
+
* were removed); the caller then forces a tool-free synthesis slice instead
|
|
58
|
+
* of silently keeping the unfiltered tool set (F-08).
|
|
59
|
+
*/
|
|
60
|
+
export function restrictToRescueTools(tools) {
|
|
61
|
+
const restricted = {};
|
|
62
|
+
for (const [name, tool] of Object.entries(tools)) {
|
|
63
|
+
if (isMutatingCapability(name) || isValidationCapable(name))
|
|
64
|
+
restricted[name] = tool;
|
|
65
|
+
}
|
|
66
|
+
return restricted;
|
|
67
|
+
}
|
|
68
|
+
/** Shared bounded retry pool for transient model errors and idle-stream stalls (per turn). */
|
|
69
|
+
const MAX_MODEL_RETRIES = 2;
|
|
70
|
+
function formatIdleMinutes(milliseconds) {
|
|
71
|
+
const minutes = Math.round(milliseconds / 60_000);
|
|
72
|
+
return `${minutes} minute${minutes === 1 ? '' : 's'}`;
|
|
73
|
+
}
|
|
74
|
+
/** Auto-retry an idle stall only while the stalled step emitted nothing visible (no partial text or in-flight tool). */
|
|
75
|
+
function idleStallAutoRetryEligible(retryAttempt, stallEmission) {
|
|
76
|
+
return stallEmission === 'none' && retryAttempt < MAX_MODEL_RETRIES;
|
|
77
|
+
}
|
|
78
|
+
async function runAgentAttempt(value, contextFiles, callbacks, retryAttempt, retryingExistingRequest, contextOverflowRecovered, session, modelOverride, abortController, turnOptions, turnScope, turnState, turnBudget, globalBudget, goal, abortCause, remainingTurnDeadlineMs) {
|
|
43
79
|
let thinkingLabel = modelThinkingLabel(undefined);
|
|
44
80
|
callbacks.setBusyLabel?.(thinkingLabel);
|
|
45
81
|
let turnStatus = 'failed';
|
|
82
|
+
let recovery;
|
|
46
83
|
let loadedMcp;
|
|
84
|
+
let lspPool;
|
|
47
85
|
// Tool calls currently executing. A concurrent subagent wave can run for many
|
|
48
86
|
// minutes with no stream parts; that is activity, not a dead stream, so the
|
|
49
87
|
// idle timer defers while any tool is in flight (see streaming/idleTimer.ts).
|
|
50
88
|
const inFlightTools = new Set();
|
|
89
|
+
// Hoisted stall/abort state: the idle timer's onTimeout and the catch below
|
|
90
|
+
// must classify a stall from stream state that is otherwise scoped to the try
|
|
91
|
+
// block below. requestMessages/accumulated responses enable the salvage that
|
|
92
|
+
// lets an idle retry resume from the last fully completed step.
|
|
93
|
+
let activeProviderName;
|
|
94
|
+
let activeModelName;
|
|
95
|
+
let lastStreamEventAt;
|
|
96
|
+
let lastStreamEventType;
|
|
97
|
+
let idleStallEmission = 'none';
|
|
98
|
+
let idleStallRetryEligible = false;
|
|
99
|
+
let requestMessages = [];
|
|
100
|
+
let latestAccumulatedResponseMessages = [];
|
|
101
|
+
let currentAssistantText = '';
|
|
102
|
+
let assistantStarted = false;
|
|
51
103
|
const idleTimer = createIdleTimer({
|
|
52
104
|
timeoutMs: IDLE_TIMEOUT_MS,
|
|
53
105
|
isBusy: () => inFlightTools.size > 0,
|
|
54
|
-
onTimeout: () =>
|
|
106
|
+
onTimeout: () => {
|
|
107
|
+
if (abortController.signal.aborted)
|
|
108
|
+
return;
|
|
109
|
+
// What the stalled step had emitted when the stream went quiet. Retrying
|
|
110
|
+
// after partial output could duplicate or mangle it, so only 'none' is
|
|
111
|
+
// automatically retryable.
|
|
112
|
+
idleStallEmission = currentAssistantText.trim().length > 0 || assistantStarted ? 'text' : inFlightTools.size > 0 ? 'tool' : 'none';
|
|
113
|
+
idleStallRetryEligible = idleStallAutoRetryEligible(retryAttempt, idleStallEmission);
|
|
114
|
+
const lastEventAtIso = lastStreamEventAt != null ? new Date(lastStreamEventAt).toISOString() : undefined;
|
|
115
|
+
// Safe metadata only (names, timestamps, enums, phases): never prompt
|
|
116
|
+
// content or credentials.
|
|
117
|
+
callbacks.onEvent?.(agentEvent({
|
|
118
|
+
type: 'timeout',
|
|
119
|
+
phase: 'model-stream',
|
|
120
|
+
timeoutMs: IDLE_TIMEOUT_MS,
|
|
121
|
+
provider: activeProviderName,
|
|
122
|
+
model: activeModelName,
|
|
123
|
+
lastStreamEventAt: lastEventAtIso,
|
|
124
|
+
lastStreamEventType: lastStreamEventType,
|
|
125
|
+
stallEmission: idleStallEmission,
|
|
126
|
+
workPhase: goal.phase,
|
|
127
|
+
retryEligible: idleStallRetryEligible,
|
|
128
|
+
}));
|
|
129
|
+
logEntry(callbacks.log, { at: new Date().toISOString(), type: 'warning', stream: 'main', error: `model-stream idle ${IDLE_TIMEOUT_MS}ms: provider=${activeProviderName ?? 'unknown'} model=${activeModelName ?? 'unknown'} lastEvent=${lastStreamEventType ?? 'none'}@${lastEventAtIso ?? 'never'} stallEmission=${idleStallEmission} workPhase=${goal.phase} retryEligible=${idleStallRetryEligible} stepsUsed=${turnState.stepsUsed}` });
|
|
130
|
+
callbacks.debugLog(`model stream idle for ${IDLE_TIMEOUT_MS}ms (last event: ${lastStreamEventType ?? 'none'}); ${idleStallRetryEligible ? 'retryable stall' : 'stall not retryable'}`);
|
|
131
|
+
abortForTurn(abortCause, { kind: 'model-stream-idle', timeoutMs: IDLE_TIMEOUT_MS }, abortController, 'haze model stream was idle for the configured timeout.');
|
|
132
|
+
},
|
|
55
133
|
});
|
|
56
134
|
const toolDisplay = createToolGroupRenderer({ addMessage: callbacks.addMessage, updateMessage: callbacks.updateMessage, debugLog: callbacks.debugLog, onEvent: callbacks.onEvent, log: callbacks.log });
|
|
57
135
|
try {
|
|
@@ -65,10 +143,29 @@ async function runAgentAttempt(value, contextFiles, callbacks, retryAttempt, ret
|
|
|
65
143
|
return { status: turnStatus };
|
|
66
144
|
}
|
|
67
145
|
thinkingLabel = modelThinkingLabel(runtime.config.modelName);
|
|
146
|
+
activeProviderName = runtime.config.providerName;
|
|
147
|
+
activeModelName = runtime.config.modelName;
|
|
68
148
|
callbacks.setBusyLabel?.(thinkingLabel);
|
|
149
|
+
// Observable requested-vs-effective reasoning policy (safe: level strings + reason only).
|
|
150
|
+
const reasoningPolicy = runtime.config.reasoningPolicy;
|
|
151
|
+
if (reasoningPolicy)
|
|
152
|
+
callbacks.onEvent?.(agentEvent({ type: 'reasoning_policy', requested: reasoningPolicy.requested, effective: reasoningPolicy.effective, reason: reasoningPolicy.reason }));
|
|
153
|
+
// Make the context-budget guess observable: a stream event every turn
|
|
154
|
+
// (headless consumers can gate on it), and — interactively — a system
|
|
155
|
+
// message only when the built-in default was used for a model this session
|
|
156
|
+
// has not warned about yet (a user-set fallback setting is an intentional
|
|
157
|
+
// choice and is not warned about). The warned key is `provider:model`, so
|
|
158
|
+
// the message appears at the start of a session and once after a model
|
|
159
|
+
// switch, never on every turn.
|
|
160
|
+
callbacks.onEvent?.(agentEvent({ type: 'context_budget', contextWindowTokens: runtime.config.contextWindowTokens, source: runtime.config.contextWindowSource }));
|
|
161
|
+
const fallbackModelKey = `${runtime.config.providerName}:${runtime.config.modelName}`;
|
|
162
|
+
if (runtime.config.contextWindowSource === 'default-fallback' && session && session.contextFallbackWarned !== fallbackModelKey) {
|
|
163
|
+
session.contextFallbackWarned = fallbackModelKey;
|
|
164
|
+
callbacks.addMessage({ role: 'system', text: `No context-window data for ${runtime.config.providerName}:${runtime.config.modelName}; budgeting conservatively at ${runtime.config.contextWindowTokens.toLocaleString('en-US')} tokens. Set modelLimits for this model via /provider, or contextWindowFallbackTokens in settings, to use its real window.` });
|
|
165
|
+
}
|
|
69
166
|
let activeContextFiles = contextFiles;
|
|
70
167
|
const activeModel = runtime.model;
|
|
71
|
-
const providerSettings = providerRequestSettings(runtime.config);
|
|
168
|
+
const { omitMaxOutputTokens, ...providerSettings } = providerRequestSettings(runtime.config);
|
|
72
169
|
const assembled = await assembleRequestContext({ contextFiles: activeContextFiles, session, model: activeModel, modelRuntime: runtime, subagentOverrides: turnOptions.subagentOverrides, abortSignal: abortController.signal, executionScope: turnScope.executionScope, settings: turnSettings, onSubagentEvent: event => callbacks.onEvent?.(agentEvent(event.type === 'queued'
|
|
73
170
|
? { type: 'subagent_state', id: event.id, state: 'queued', mode: event.mode, queued: event.queued, running: event.running }
|
|
74
171
|
: event.type === 'started'
|
|
@@ -78,19 +175,29 @@ async function runAgentAttempt(value, contextFiles, callbacks, retryAttempt, ret
|
|
|
78
175
|
: { type: 'subagent_state', id: event.id, state: 'settled', mode: event.mode, queueMs: event.queueMs, durationMs: event.durationMs, termination: event.termination, execution: 'settled', running: event.running })) });
|
|
79
176
|
turnScope.executionScope ??= assembled.executionScope;
|
|
80
177
|
const availableTools = assembled.availableTools;
|
|
178
|
+
const toolCategories = assembled.toolCategories;
|
|
81
179
|
loadedMcp = assembled.loadedMcp;
|
|
180
|
+
lspPool = assembled.lspPool;
|
|
82
181
|
if (loadedMcp?.errors.length)
|
|
83
182
|
callbacks.addMessage({ role: 'system', text: `MCP: ${loadedMcp.errors.join('; ')}` });
|
|
84
|
-
const goal = createSessionGoal(value);
|
|
85
183
|
callbacks.setWorkState?.(goal);
|
|
86
184
|
callbacks.setGoalStatus?.(formatGoalStatus(goal));
|
|
87
185
|
const likelyPlanOnlyRequest = isPlanOnlyRequest(value);
|
|
88
186
|
const durableRequestMessages = compactToolHistory(retryingExistingRequest
|
|
89
187
|
? stripSyntheticControls(callbacks.getConversation())
|
|
90
188
|
: [...stripSyntheticControls(callbacks.getConversation()), userTurnMessage(value, turnOptions.attachments ?? [])]).messages;
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
189
|
+
// Model-aware request budget (RH-005): message allowance is the context
|
|
190
|
+
// window minus system prompt, tool schemas, output reserve, and a safety
|
|
191
|
+
// margin — not a fixed 40K constant. Small contexts get a safe budget; the
|
|
192
|
+
// assembled request plus output reserve stays within configured capacity.
|
|
193
|
+
const requestedOutputTokens = runtime.config.maxOutputTokens ?? DEFAULT_MAX_OUTPUT_TOKENS;
|
|
194
|
+
const requestBudget = calculateRequestTokenBudget({ contextWindowTokens: runtime.config.contextWindowTokens, requestedOutputTokens, system: assembled.systemPrompt, tools: availableTools });
|
|
195
|
+
// A context-overflow retry progressively shrinks the target so it cannot loop
|
|
196
|
+
// at an unchanged budget; further overflows get even smaller (RH-005).
|
|
197
|
+
const overflowTargetTokens = contextOverflowRecovered ? Math.floor(requestBudget.messageTokens * 0.6) : requestBudget.messageTokens;
|
|
198
|
+
requestMessages = durableRequestMessages;
|
|
199
|
+
if (estimateMessagesTokens(requestMessages) > overflowTargetTokens) {
|
|
200
|
+
requestMessages = compactModelMessages(requestMessages, { tokenBudget: overflowTargetTokens, workState: goal }).messages;
|
|
94
201
|
}
|
|
95
202
|
requestMessages = withoutSystemMessages(requestMessages);
|
|
96
203
|
callbacks.setConversation(stripSyntheticControls(requestMessages));
|
|
@@ -113,19 +220,18 @@ async function runAgentAttempt(value, contextFiles, callbacks, retryAttempt, ret
|
|
|
113
220
|
const toolExecutionContext = { inFlightToolCalls: new Map(), loadedContextFilePaths: new Set(activeContextFiles.map(file => file.path)), loadedContextFileSignatures: contextFileSignatures, onContextFileRead: path => toolDisplay.addContextFileRead(path), mutationPolicy, blessedPaths: turnOptions.blessedPaths };
|
|
114
221
|
const startedTools = new Map();
|
|
115
222
|
const latestToolCalls = new Map();
|
|
116
|
-
let latestAccumulatedResponseMessages = [];
|
|
117
223
|
let currentAssistantId = `assistant-${Date.now()}`;
|
|
118
|
-
let assistantStarted = false;
|
|
119
224
|
let assistantStartedAt = Date.now();
|
|
120
225
|
let assistantText = '';
|
|
121
|
-
let currentAssistantText = '';
|
|
122
226
|
let streamError;
|
|
123
227
|
let streamFinished = false;
|
|
124
228
|
let finishReason;
|
|
125
229
|
let lastToolOk;
|
|
126
|
-
let
|
|
127
|
-
let
|
|
128
|
-
|
|
230
|
+
let pendingMalformedToolName;
|
|
231
|
+
let unresolvedMalformedToolName;
|
|
232
|
+
// Per-attempt (not per-turn) recovery counter: a transient retry gets a
|
|
233
|
+
// fresh map. Bounded across the whole turn by MAIN_TOOL_CALL_LIMIT.
|
|
234
|
+
const malformedRecoveryAttempts = new Map();
|
|
129
235
|
let toolResultState = initialToolResultState();
|
|
130
236
|
const resetAssistantSegment = () => {
|
|
131
237
|
currentAssistantId = `assistant-${Date.now()}-${Math.random().toString(36).slice(2)}`;
|
|
@@ -156,46 +262,139 @@ async function runAgentAttempt(value, contextFiles, callbacks, retryAttempt, ret
|
|
|
156
262
|
resetAssistantSegment();
|
|
157
263
|
return !hidden;
|
|
158
264
|
};
|
|
265
|
+
const recoverySlice = turnOptions.recoverySlice;
|
|
266
|
+
const stepCap = recoverySlice?.maxSteps ?? MAIN_STEP_LIMIT;
|
|
267
|
+
// Rescue exposes only mutation + validation-capable built-in tools so
|
|
268
|
+
// discovery cannot be reopened near the boundary. Length-continuation keeps
|
|
269
|
+
// the full tool set. When no built-in mutation/validation tool qualifies,
|
|
270
|
+
// the rescue slice runs tool-free (forced synthesis) rather than keeping
|
|
271
|
+
// the unfiltered set — the "discovery must not be reopened" invariant (F-08).
|
|
272
|
+
const rescueTools = recoverySlice?.kind === 'rescue' ? restrictToRescueTools(availableTools) : availableTools;
|
|
273
|
+
const rescueWithoutTools = recoverySlice?.kind === 'rescue' && Object.keys(rescueTools).length === 0;
|
|
274
|
+
const sliceTools = rescueWithoutTools ? {} : rescueTools;
|
|
275
|
+
// Execution-boundary budgets (RH-003). The global budget is turn-wide
|
|
276
|
+
// (shared across retries and recovery slices); the slice budget is
|
|
277
|
+
// per-attempt and caps a recovery slice. Both are checked atomically at the
|
|
278
|
+
// actual execute boundary so one oversized parallel batch cannot overshoot.
|
|
279
|
+
const sliceBudget = createToolExecutionBudget();
|
|
280
|
+
const sliceToolCallCap = recoverySlice?.maxToolCalls ?? MAIN_TOOL_CALL_LIMIT;
|
|
281
|
+
const budgetedTools = withToolExecutionBudget(sliceTools, { state: globalBudget, limit: turnBudget.toolCallLimit }, { state: sliceBudget, limit: sliceToolCallCap });
|
|
282
|
+
// Layer a per-tool execution deadline on top of the budget (RH-004). The
|
|
283
|
+
// budget is checked first (cheap); a permitted call then runs under a
|
|
284
|
+
// deadline so an uncooperative tool cannot defer the turn indefinitely.
|
|
285
|
+
// Subagents legitimately run long, so their wrapper gets a larger bound.
|
|
286
|
+
const deadlineWrappedTools = Object.fromEntries(Object.entries(budgetedTools).map(([name, definition]) => {
|
|
287
|
+
if (typeof definition.execute !== 'function')
|
|
288
|
+
return [name, definition];
|
|
289
|
+
const execute = definition.execute;
|
|
290
|
+
const deadlineMs = name === 'subagent' ? SUBAGENT_TOOL_DEADLINE_MS : DEFAULT_TOOL_DEADLINE_MS;
|
|
291
|
+
return [name, { ...definition, execute: (...args) => withToolDeadline(() => execute(...args), deadlineMs, abortController.signal) }];
|
|
292
|
+
}));
|
|
159
293
|
const agent = new ToolLoopAgent({
|
|
160
294
|
id: 'haze-main',
|
|
161
295
|
model: activeModel,
|
|
162
296
|
instructions: systemPrompt,
|
|
163
|
-
tools:
|
|
164
|
-
maxOutputTokens: DEFAULT_MAX_OUTPUT_TOKENS,
|
|
297
|
+
tools: deadlineWrappedTools,
|
|
298
|
+
...(!omitMaxOutputTokens ? { maxOutputTokens: DEFAULT_MAX_OUTPUT_TOKENS } : {}),
|
|
165
299
|
...providerSettings,
|
|
166
|
-
stopWhen: isStepCount(
|
|
300
|
+
stopWhen: isStepCount(stepCap),
|
|
167
301
|
runtimeContext: toolExecutionContext,
|
|
168
|
-
toolsContext: toolsContextFor(
|
|
302
|
+
toolsContext: toolsContextFor(deadlineWrappedTools, toolExecutionContext),
|
|
303
|
+
experimental_repairToolCall: async ({ toolCall, error }) => {
|
|
304
|
+
if (isMalformedToolInputError(error)) {
|
|
305
|
+
pendingMalformedToolName = toolCall.toolName;
|
|
306
|
+
unresolvedMalformedToolName = toolCall.toolName;
|
|
307
|
+
}
|
|
308
|
+
// Truncated generated file content cannot be reconstructed safely here;
|
|
309
|
+
// let the next agent step retry under the bounded tool-choice constraint.
|
|
310
|
+
return null;
|
|
311
|
+
},
|
|
169
312
|
prepareStep({ steps, messages }) {
|
|
313
|
+
// A rescue slice with no qualifying tools must synthesize, never reopen
|
|
314
|
+
// discovery by falling back to the full tool set (F-08).
|
|
315
|
+
if (rescueWithoutTools) {
|
|
316
|
+
callbacks.debugLog('rescue slice has no mutation/validation tools; forcing tool-free synthesis');
|
|
317
|
+
return { toolChoice: 'none' };
|
|
318
|
+
}
|
|
170
319
|
const toolCalls = steps.flatMap(step => step.toolCalls);
|
|
171
|
-
const repeatedToolNames =
|
|
172
|
-
|
|
173
|
-
|
|
320
|
+
const repeatedToolNames = latestRepeatedToolNames(steps);
|
|
321
|
+
let scopedMessages = withScopedContextControl(messages, toolExecutionContext);
|
|
322
|
+
let messagesChanged = scopedMessages !== messages;
|
|
323
|
+
// Re-evaluate the accumulated request size before each provider call and
|
|
324
|
+
// compact old tool history when it exceeds the model-aware budget, so a
|
|
325
|
+
// long multi-step turn compacts before overflowing (RH-005).
|
|
326
|
+
if (estimateMessagesTokens(scopedMessages) > requestBudget.messageTokens) {
|
|
327
|
+
const compacted = compactModelMessages(stripSyntheticControls(scopedMessages), { tokenBudget: requestBudget.messageTokens, workState: goal }).messages;
|
|
328
|
+
scopedMessages = compacted;
|
|
329
|
+
messagesChanged = true;
|
|
330
|
+
}
|
|
331
|
+
// Turn-wide hard caps (shared across retries and recovery slices).
|
|
332
|
+
const turnToolCallsExhausted = turnState.toolCallsUsed >= turnBudget.toolCallLimit;
|
|
333
|
+
// Per-slice tool-call cap for a recovery slice (counts this slice's calls).
|
|
334
|
+
const sliceToolCallsExhausted = recoverySlice ? toolCalls.length >= recoverySlice.maxToolCalls : false;
|
|
335
|
+
// Reserve the final tool-only slot for rescue: normal exploration stops at
|
|
336
|
+
// the boundary; a rescue slice is exempt so it may use the reserved slot.
|
|
337
|
+
const toolOnlyBoundaryHit = !recoverySlice && toolOnlyStepCount(steps) >= RESCUE_BOUNDARY;
|
|
174
338
|
if (likelyPlanOnlyRequest && toolResultState.mutatingToolSucceeded)
|
|
175
339
|
return messagesChanged ? { toolChoice: 'none', messages: scopedMessages } : { toolChoice: 'none' };
|
|
176
|
-
if (
|
|
177
|
-
|
|
340
|
+
if (pendingMalformedToolName && pendingMalformedToolName in sliceTools) {
|
|
341
|
+
const toolName = pendingMalformedToolName;
|
|
342
|
+
const attempt = malformedRecoveryAttempts.get(String(toolName)) ?? 0;
|
|
343
|
+
pendingMalformedToolName = undefined;
|
|
344
|
+
if (attempt >= 2) {
|
|
345
|
+
callbacks.debugLog(`malformed ${String(toolName)} recovery exhausted`);
|
|
346
|
+
return { toolChoice: 'none', messages: withSyntheticControl(scopedMessages, `The ${String(toolName)} input remained invalid after two smaller retries. Report this as blocked; do not promise another retry or claim completion.`) };
|
|
347
|
+
}
|
|
348
|
+
malformedRecoveryAttempts.set(String(toolName), attempt + 1);
|
|
349
|
+
callbacks.debugLog(`forcing smaller retry after malformed ${String(toolName)} input`);
|
|
350
|
+
return { toolChoice: { type: 'tool', toolName }, messages: withSyntheticControl(scopedMessages, malformedToolCallPrompt(String(toolName), WRITE_FILE_CHUNK_BYTES)) };
|
|
351
|
+
}
|
|
352
|
+
if (toolResultState.editRecoveryPath && !toolResultState.editRecoveryReadSatisfied) {
|
|
353
|
+
if ('readFile' in sliceTools)
|
|
354
|
+
return messagesChanged ? { activeTools: ['readFile'], messages: scopedMessages } : { activeTools: ['readFile'] };
|
|
355
|
+
return { toolChoice: 'none', messages: withSyntheticControl(scopedMessages, `The failed mutation of ${toolResultState.editRecoveryPath} requires a fresh read, but readFile is unavailable in this bounded recovery slice. Report the unfinished edit as blocked; do not claim it succeeded.`) };
|
|
356
|
+
}
|
|
178
357
|
if (repeatedToolNames.length > 0) {
|
|
179
|
-
const activeTools = Object.keys(
|
|
358
|
+
const activeTools = Object.keys(sliceTools).filter(name => !repeatedToolNames.includes(name));
|
|
180
359
|
callbacks.debugLog(`disabling repeated tools for next step: ${repeatedToolNames.join(', ')}`);
|
|
181
360
|
return activeTools.length > 0
|
|
182
361
|
? { activeTools, messages: withSyntheticControl(scopedMessages, repeatedToolCallPrompt(repeatedToolNames)) }
|
|
183
362
|
: { toolChoice: 'none', messages: withSyntheticControl(scopedMessages, repeatedToolCallPrompt(repeatedToolNames)) };
|
|
184
363
|
}
|
|
185
|
-
if (
|
|
364
|
+
if (turnToolCallsExhausted || sliceToolCallsExhausted || toolOnlyBoundaryHit || toolCalls.length >= MAIN_TOOL_CALL_LIMIT) {
|
|
186
365
|
callbacks.debugLog('forcing text response to avoid tool loop');
|
|
187
366
|
return { toolChoice: 'none', messages: withSyntheticControl(scopedMessages, toolLoopBudgetPrompt()) };
|
|
188
367
|
}
|
|
189
368
|
return messagesChanged ? { messages: scopedMessages } : undefined;
|
|
190
369
|
},
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
370
|
+
onStepStart({ stepNumber }) {
|
|
371
|
+
callbacks.onEvent?.(agentEvent({ type: 'step_start', attempt: retryAttempt + 1, step: stepNumber + 1 }));
|
|
372
|
+
},
|
|
373
|
+
onStepEnd({ stepNumber, text, content = [], toolCalls, toolResults, finishReason, usage, response }) {
|
|
374
|
+
// Tool-loop control must advance from this internal callback, which the
|
|
375
|
+
// SDK awaits before prepareStep. Updating it from the public stream can
|
|
376
|
+
// lag behind fast providers and leave the next request read-only.
|
|
377
|
+
toolResultState = applyStepToolResultState(toolResultState, content);
|
|
378
|
+
// Turn-wide counters (shared across provider retries and recovery
|
|
379
|
+
// slices) so the global budget cannot reset between attempts. The
|
|
380
|
+
// execution-boundary budget (RH-003) is the authoritative count of
|
|
381
|
+
// underlying executions; sync the turn state to it so blocked calls are
|
|
382
|
+
// not double-counted and recovery math stays consistent.
|
|
383
|
+
turnState.stepsUsed += 1;
|
|
384
|
+
turnState.toolCallsUsed = globalBudget.started;
|
|
194
385
|
if (toolCalls.length > 0 && text.trim().length === 0)
|
|
195
|
-
|
|
386
|
+
turnState.toolOnlyStepsUsed += 1;
|
|
196
387
|
if (Array.isArray(response?.messages) && response.messages.length > 0)
|
|
197
388
|
latestAccumulatedResponseMessages = response.messages;
|
|
198
389
|
const stepUsage = stepCacheMetrics(usage);
|
|
390
|
+
const publicUsage = {
|
|
391
|
+
inputTokens: stepUsage.inputTokens ?? 0,
|
|
392
|
+
outputTokens: usage?.outputTokens ?? 0,
|
|
393
|
+
cacheReadTokens: stepUsage.cacheReadTokens,
|
|
394
|
+
cacheWriteTokens: stepUsage.cacheWriteTokens,
|
|
395
|
+
reasoningTokens: stepUsage.reasoningTokens,
|
|
396
|
+
};
|
|
397
|
+
callbacks.onEvent?.(agentEvent({ type: 'step_end', attempt: retryAttempt + 1, step: stepNumber + 1, finishReason, toolCallCount: toolCalls.length, usage: publicUsage }));
|
|
199
398
|
logEntry(callbacks.log, { at: new Date().toISOString(), type: 'step', stream: 'main', step: stepNumber, text, finishReason, usage: { inputTokens: stepUsage.inputTokens, outputTokens: usage?.outputTokens, cacheReadTokens: stepUsage.cacheReadTokens || undefined, cacheWriteTokens: stepUsage.cacheWriteTokens || undefined, noCacheTokens: stepUsage.noCacheTokens || undefined, reasoningTokens: stepUsage.reasoningTokens || undefined, cacheHitRatio: stepUsage.cacheHitRatio } });
|
|
200
399
|
callbacks.debugLog(`step ${stepNumber} finished: ${finishReason}; text=${text.length}; toolCalls=${toolCalls.length}; toolResults=${toolResults.length}`);
|
|
201
400
|
},
|
|
@@ -225,6 +424,8 @@ async function runAgentAttempt(value, contextFiles, callbacks, retryAttempt, ret
|
|
|
225
424
|
const result = await agent.stream({ messages: requestMessages, abortSignal: abortController.signal });
|
|
226
425
|
for await (const part of result.stream) {
|
|
227
426
|
idleTimer.reset();
|
|
427
|
+
lastStreamEventAt = Date.now();
|
|
428
|
+
lastStreamEventType = part.type;
|
|
228
429
|
switch (part.type) {
|
|
229
430
|
case 'text-delta': {
|
|
230
431
|
callbacks.setBusyLabel?.(thinkingLabel);
|
|
@@ -256,7 +457,6 @@ async function runAgentAttempt(value, contextFiles, callbacks, retryAttempt, ret
|
|
|
256
457
|
}
|
|
257
458
|
const toolCall = { toolCallId: part.id, toolName: part.toolName, input: {} };
|
|
258
459
|
latestToolCalls.set(part.id, toolCall);
|
|
259
|
-
startedTools.set(part.id, Date.now());
|
|
260
460
|
inFlightTools.add(part.id);
|
|
261
461
|
callbacks.setBusyLabel?.(busyToolLabel(part.toolName, {}));
|
|
262
462
|
toolDisplay.ensureToolItem(toolCall);
|
|
@@ -271,8 +471,8 @@ async function runAgentAttempt(value, contextFiles, callbacks, retryAttempt, ret
|
|
|
271
471
|
}
|
|
272
472
|
const toolCall = { toolCallId: part.toolCallId, toolName: part.toolName, input: part.input };
|
|
273
473
|
latestToolCalls.set(part.toolCallId, toolCall);
|
|
274
|
-
|
|
275
|
-
|
|
474
|
+
// Tool execution begins only after its complete input has parsed and validated.
|
|
475
|
+
startedTools.set(part.toolCallId, Date.now());
|
|
276
476
|
callbacks.setBusyLabel?.(busyToolLabel(part.toolName, part.input));
|
|
277
477
|
toolDisplay.ensureToolItem(toolCall).summary = toolCallSummary(part.toolName, part.input);
|
|
278
478
|
toolDisplay.updateToolGroup(true);
|
|
@@ -283,17 +483,46 @@ async function runAgentAttempt(value, contextFiles, callbacks, retryAttempt, ret
|
|
|
283
483
|
latestToolCalls.set(part.toolCallId, toolCall);
|
|
284
484
|
inFlightTools.delete(part.toolCallId);
|
|
285
485
|
const startedAt = startedTools.get(part.toolCallId) ?? Date.now();
|
|
486
|
+
// A budget-blocked call never reached the underlying implementation;
|
|
487
|
+
// record it as a bounded non-event with no goal/observal side effect (RH-003).
|
|
488
|
+
if (isToolBudgetBlocked(part.output)) {
|
|
489
|
+
const item = toolDisplay.ensureToolItem(toolCall);
|
|
490
|
+
item.status = 'error';
|
|
491
|
+
item.result = 'skipped: tool-call budget exhausted';
|
|
492
|
+
item.durationMs = Date.now() - startedAt;
|
|
493
|
+
item.finishedAt = startedAt + (item.durationMs ?? 0);
|
|
494
|
+
callbacks.onEvent?.(agentEvent({ type: 'tool_end', id: toolCall.toolCallId, name: toolCall.toolName, success: false, errorCode: 'tool_budget_blocked', durationMs: item.durationMs ?? 0 }));
|
|
495
|
+
toolDisplay.updateToolGroup(true);
|
|
496
|
+
break;
|
|
497
|
+
}
|
|
498
|
+
// A deadline-exceeded call was terminated at the wrapper boundary; the
|
|
499
|
+
// underlying work may still be settling and must not mutate goal state (RH-004).
|
|
500
|
+
if (isToolDeadlineExceeded(part.output)) {
|
|
501
|
+
const item = toolDisplay.ensureToolItem(toolCall);
|
|
502
|
+
item.status = 'error';
|
|
503
|
+
item.result = `timed out after ${DEFAULT_TOOL_DEADLINE_MS}ms`;
|
|
504
|
+
const durationMs = Date.now() - startedAt;
|
|
505
|
+
item.durationMs = durationMs;
|
|
506
|
+
item.finishedAt = startedAt + durationMs;
|
|
507
|
+
callbacks.onEvent?.(agentEvent({ type: 'tool_end', id: toolCall.toolCallId, name: toolCall.toolName, success: false, errorCode: 'tool_deadline', durationMs }));
|
|
508
|
+
callbacks.onEvent?.(agentEvent({ type: 'timeout', phase: 'tool', timeoutMs: toolCall.toolName === 'subagent' ? SUBAGENT_TOOL_DEADLINE_MS : DEFAULT_TOOL_DEADLINE_MS }));
|
|
509
|
+
toolDisplay.updateToolGroup(true);
|
|
510
|
+
break;
|
|
511
|
+
}
|
|
286
512
|
const ok = toolOutputOk(part.output, true);
|
|
287
513
|
lastToolOk = ok;
|
|
514
|
+
if (ok && part.toolName === unresolvedMalformedToolName)
|
|
515
|
+
unresolvedMalformedToolName = undefined;
|
|
288
516
|
const finish = { toolCall, success: ok, output: part.output, durationMs: Date.now() - startedAt };
|
|
289
517
|
const item = toolDisplay.ensureToolItem(toolCall);
|
|
290
518
|
item.status = ok ? 'success' : 'error';
|
|
291
519
|
item.result = toolResultSummary(finish);
|
|
520
|
+
item.diff = toolDiffFromResult(toolCall, part.output);
|
|
292
521
|
item.durationMs = finish.durationMs;
|
|
293
522
|
item.finishedAt = startedAt + finish.durationMs;
|
|
294
|
-
|
|
523
|
+
const failureDetails = ok || toolCategories.get(toolCall.toolName) !== 'builtin' ? {} : safeToolFailureDetails(part.output);
|
|
524
|
+
callbacks.onEvent?.(agentEvent({ type: 'tool_end', id: toolCall.toolCallId, name: toolCall.toolName, success: ok, output: part.output, ...failureDetails, durationMs: finish.durationMs }));
|
|
295
525
|
logEntry(callbacks.log, { at: new Date().toISOString(), type: 'tool_result', stream: 'main', toolResult: { id: toolCall.toolCallId, name: toolCall.toolName, success: ok, output: part.output, durationMs: finish.durationMs } });
|
|
296
|
-
toolResultState = applyToolResultState(toolResultState, { toolName: toolCall.toolName, input: toolCall.input, output: part.output, ok });
|
|
297
526
|
observeGoalToolEvent(goal, { ...toolCall, success: ok, output: part.output, duplicateSkipped: isDuplicateSkippedOutput(part.output) });
|
|
298
527
|
callbacks.setWorkState?.(goal);
|
|
299
528
|
callbacks.setGoalStatus?.(formatGoalStatus(goal));
|
|
@@ -312,17 +541,19 @@ async function runAgentAttempt(value, contextFiles, callbacks, retryAttempt, ret
|
|
|
312
541
|
const toolCall = { toolCallId: part.toolCallId, toolName: part.toolName, input: part.input ?? existing?.input };
|
|
313
542
|
const startedAt = startedTools.get(part.toolCallId) ?? Date.now();
|
|
314
543
|
lastToolOk = false;
|
|
544
|
+
if (isMalformedToolInputError(part.error)) {
|
|
545
|
+
pendingMalformedToolName = part.toolName;
|
|
546
|
+
unresolvedMalformedToolName = part.toolName;
|
|
547
|
+
}
|
|
315
548
|
const finish = { toolCall, success: false, error: part.error, durationMs: Date.now() - startedAt };
|
|
316
549
|
const item = toolDisplay.ensureToolItem(toolCall);
|
|
317
550
|
item.status = 'error';
|
|
318
551
|
item.result = toolResultSummary(finish);
|
|
319
552
|
item.durationMs = finish.durationMs;
|
|
320
553
|
item.finishedAt = startedAt + finish.durationMs;
|
|
321
|
-
|
|
554
|
+
const publicError = toolCategories.get(toolCall.toolName) === 'builtin' ? { error: part.error } : {};
|
|
555
|
+
callbacks.onEvent?.(agentEvent({ type: 'tool_end', id: toolCall.toolCallId, name: toolCall.toolName, success: false, errorCode: 'tool_execution_error', ...publicError, durationMs: finish.durationMs }));
|
|
322
556
|
logEntry(callbacks.log, { at: new Date().toISOString(), type: 'tool_result', stream: 'main', toolResult: { id: toolCall.toolCallId, name: toolCall.toolName, success: false, error: part.error, durationMs: finish.durationMs } });
|
|
323
|
-
if (isMutatingToolName(toolCall.toolName)) {
|
|
324
|
-
toolResultState = { ...toolResultState, editRecoveryPath: toolInputField(toolCall.input, 'path'), editRecoveryReadSatisfied: false };
|
|
325
|
-
}
|
|
326
557
|
observeGoalToolEvent(goal, { ...toolCall, success: false, output: part.error });
|
|
327
558
|
callbacks.setWorkState?.(goal);
|
|
328
559
|
callbacks.setGoalStatus?.(formatGoalStatus(goal));
|
|
@@ -367,39 +598,144 @@ async function runAgentAttempt(value, contextFiles, callbacks, retryAttempt, ret
|
|
|
367
598
|
else if (latestToolCalls.size > 0) {
|
|
368
599
|
callbacks.addMessage({ role: 'system', text: 'Tool work ended without a substantive final answer.' });
|
|
369
600
|
}
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
601
|
+
turnState.finishCause = normalizeFinishReason(finishReason);
|
|
602
|
+
// Observable work evidence (Increment 3 surfaces this additively; tracked
|
|
603
|
+
// here so the turn-wide state is the single source of runtime evidence).
|
|
604
|
+
turnState.validationOutcome = deriveValidationOutcome(goal);
|
|
605
|
+
turnState.mutationCount = goal.mutationCount;
|
|
606
|
+
turnState.validationKind = goal.validations.at(-1)?.kind ?? goal.carriedValidation?.kind;
|
|
607
|
+
turnState.validationAfterMutation = goal.validationSeq > 0 && goal.validationSeq >= goal.mutationSeq;
|
|
608
|
+
turnState.taskProgress = goal.taskProgress;
|
|
609
|
+
turnState.budgetBoundary = isBudgetExhausted(turnState, turnBudget);
|
|
610
|
+
const completionEvidence = { sawToolCall: latestToolCalls.size > 0, assistantText, lastToolOk, unresolvedToolInputError: unresolvedMalformedToolName != null };
|
|
611
|
+
const readiness = assessCompletionReadiness(turnState, completionEvidence);
|
|
612
|
+
const classification = classifyTerminalOutcome(turnState, completionEvidence);
|
|
613
|
+
turnStatus = terminalTurnStatus({ aborted: false, assistantText, sawToolCall: latestToolCalls.size > 0, lastToolOk, finishReason, budgetReached: turnState.budgetBoundary, unresolvedToolInputError: unresolvedMalformedToolName != null, intent: turnState.intent, mutationCount: turnState.mutationCount, validationOutcome: turnState.validationOutcome, taskProgress: turnState.taskProgress });
|
|
614
|
+
if (unresolvedMalformedToolName)
|
|
615
|
+
callbacks.addMessage({ role: 'system', text: `${unresolvedMalformedToolName} did not execute because its generated input remained invalid or truncated. The requested work is incomplete.` });
|
|
375
616
|
goal.phase = 'done';
|
|
376
|
-
|
|
617
|
+
// Goal status reflects completion readiness, not the shallow text status:
|
|
618
|
+
// unfinished-but-recoverable work is waiting on continuation (supervisor or
|
|
619
|
+
// the user), while tool/input failures are concrete blockers. Prose alone
|
|
620
|
+
// can never turn pending work into 'complete'.
|
|
621
|
+
goal.status = turnStatus === 'aborted' ? 'aborted'
|
|
622
|
+
: turnStatus === 'complete' ? 'complete'
|
|
623
|
+
: readiness === 'tool_failure' || readiness === 'unresolved_tool_input' ? 'blocked'
|
|
624
|
+
: goalContinuationRecoverable(readiness) ? 'needs-user'
|
|
625
|
+
: 'blocked';
|
|
377
626
|
callbacks.setWorkState?.(goal);
|
|
378
627
|
callbacks.setGoalStatus?.(undefined);
|
|
628
|
+
// Bounded recovery + the goal-level invariant. Length/rescue credits are
|
|
629
|
+
// single-use and only the main flow proposes them; goal continuation is
|
|
630
|
+
// repeatable while measurable progress continues. The invariant: when the
|
|
631
|
+
// attempt classified `recoverable-incomplete` and no same-turn recovery can
|
|
632
|
+
// run (budget/deadline boundary, exhausted slice, no-progress guard), the
|
|
633
|
+
// attempt returns an `incomplete-goal` checkpoint — never a silent failure,
|
|
634
|
+
// and never `complete`. The goal supervisor turns checkpoints into fresh
|
|
635
|
+
// physical turns; a bare runAgentTurn caller surfaces them as resume info.
|
|
636
|
+
const goalId = turnOptions.goalContext?.goalId ?? goal.id;
|
|
637
|
+
const goalCycle = turnOptions.goalContext?.cycle ?? 1;
|
|
638
|
+
const checkpointResult = () => ({ status: 'failed', resume: buildIncompleteGoalResume(value, goalId, goalCycle, turnState, readiness) });
|
|
639
|
+
if (!abortController.signal.aborted) {
|
|
640
|
+
const lengthDecision = decideLengthRecovery(turnState, turnBudget);
|
|
641
|
+
if (lengthDecision.action === 'continue') {
|
|
642
|
+
const clamped = clampSlice(lengthDecision.slice, { steps: remainingSteps(turnState.stepsUsed, turnBudget), toolCalls: remainingToolCalls(turnState.toolCallsUsed, turnBudget) });
|
|
643
|
+
if (clamped.steps > 0)
|
|
644
|
+
recovery = { kind: 'length', control: lengthContinuationPrompt(), slice: { maxSteps: clamped.steps, maxToolCalls: clamped.toolCalls } };
|
|
645
|
+
}
|
|
646
|
+
else {
|
|
647
|
+
const goalDecision = decideGoalContinuation(turnState, completionEvidence, turnBudget);
|
|
648
|
+
const rescueDecision = turnOptions.recoverySlice == null
|
|
649
|
+
? decideRescue(turnState, completionEvidence, turnBudget, rescueEligibleRequest(goal.intent))
|
|
650
|
+
: undefined;
|
|
651
|
+
const goalSlice = goalDecision.action === 'continue' && remainingTurnDeadlineMs() > 0
|
|
652
|
+
? clampSlice(goalDecision.slice, { steps: remainingSteps(turnState.stepsUsed, turnBudget), toolCalls: remainingToolCalls(turnState.toolCallsUsed, turnBudget) })
|
|
653
|
+
: undefined;
|
|
654
|
+
const rescueSlice = goalSlice && goalSlice.steps > 0 ? undefined : rescueDecision?.action === 'continue'
|
|
655
|
+
? clampSlice(rescueDecision.slice, { steps: remainingSteps(turnState.stepsUsed, turnBudget), toolCalls: remainingToolCalls(turnState.toolCallsUsed, turnBudget) })
|
|
656
|
+
: undefined;
|
|
657
|
+
if (goalSlice && goalSlice.steps > 0) {
|
|
658
|
+
recovery = { kind: 'goal', control: goalContinuationPrompt(describeCompletionReadiness(readiness, turnState.taskProgress)), slice: { maxSteps: goalSlice.steps, maxToolCalls: goalSlice.toolCalls } };
|
|
659
|
+
}
|
|
660
|
+
else if (rescueSlice && rescueSlice.steps > 0) {
|
|
661
|
+
recovery = { kind: 'rescue', control: completionRescuePrompt(), slice: { maxSteps: rescueSlice.steps, maxToolCalls: rescueSlice.toolCalls } };
|
|
662
|
+
}
|
|
663
|
+
else if (classification === 'recoverable-incomplete') {
|
|
664
|
+
// Budget boundary (`tool-calls`), exhausted slice, deadline, or no-progress
|
|
665
|
+
// guard: end the physical turn with a resumable checkpoint.
|
|
666
|
+
callbacks.debugLog(`goal checkpoint: readiness=${readiness}; goalDecision=${goalDecision.reason}; rescueDecision=${rescueDecision?.reason ?? 'not proposed from a recovery slice'}`);
|
|
667
|
+
return checkpointResult();
|
|
668
|
+
}
|
|
669
|
+
}
|
|
670
|
+
}
|
|
379
671
|
}
|
|
380
672
|
catch (error) {
|
|
381
673
|
if (abortController.signal.aborted) {
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
674
|
+
if (abortCause.kind === 'model-stream-idle') {
|
|
675
|
+
// Transport stall, not a user cancel. Preserve completed work first: the
|
|
676
|
+
// conversation is salvaged from the last fully completed step so an
|
|
677
|
+
// automatic retry (or a user-triggered resume) continues from there
|
|
678
|
+
// instead of re-running — possibly mutating — tool work.
|
|
679
|
+
if (latestAccumulatedResponseMessages.length > 0) {
|
|
680
|
+
callbacks.setConversation(compactToolHistory([...stripSyntheticControls(requestMessages), ...latestAccumulatedResponseMessages]).messages);
|
|
681
|
+
}
|
|
682
|
+
if (idleStallRetryEligible) {
|
|
683
|
+
const delay = retryDelayMs(retryAttempt);
|
|
684
|
+
callbacks.onEvent?.(agentEvent({ type: 'retry', attempt: retryAttempt + 1, maxAttempts: MAX_MODEL_RETRIES, delayMs: delay, error: `model stream idle for ${formatSeconds(IDLE_TIMEOUT_MS)}` }));
|
|
685
|
+
callbacks.addMessage({ role: 'system', text: `Model stream stalled for ${formatIdleMinutes(IDLE_TIMEOUT_MS)}; retrying attempt ${retryAttempt + 1}/${MAX_MODEL_RETRIES} in ${formatSeconds(delay)}. Completed steps are preserved.` });
|
|
686
|
+
turnStatus = 'failed';
|
|
687
|
+
// freshController: this stall aborted the controller to kill the hung
|
|
688
|
+
// stream; the retry needs a live signal.
|
|
689
|
+
return { status: turnStatus, retry: { attempt: retryAttempt + 1, contextOverflowRecovered, delayMs: delay, freshController: true } };
|
|
690
|
+
}
|
|
691
|
+
// Bounded retries exhausted, or the stalled step emitted partial output.
|
|
692
|
+
// Pause with the active goal preserved (work state is untouched by this
|
|
693
|
+
// path) instead of discarding progress; the interactive UI offers a
|
|
694
|
+
// one-key resume from TurnResult.resume.
|
|
695
|
+
turnStatus = 'failed';
|
|
696
|
+
const afterStep = turnState.stepsUsed > 0 ? ` after step ${turnState.stepsUsed}` : '';
|
|
697
|
+
callbacks.addMessage({ role: 'system', text: `Model stream stalled for ${formatIdleMinutes(IDLE_TIMEOUT_MS)}; unfinished task paused${afterStep}. Press R to retry, or send a follow-up message to continue.` });
|
|
698
|
+
return { status: turnStatus, resume: { kind: 'model-stream-idle', request: value, retryAttempt } };
|
|
699
|
+
}
|
|
700
|
+
if (abortCause.kind === 'turn-deadline') {
|
|
701
|
+
// Absolute turn budget exhausted — distinct from a user cancel: the turn
|
|
702
|
+
// ran out of time, not patience. No retry by definition (the deadline is
|
|
703
|
+
// the bound), but completed-step progress stays in the conversation.
|
|
704
|
+
turnState.aborted = true;
|
|
705
|
+
turnStatus = 'aborted';
|
|
706
|
+
callbacks.debugLog('turn exceeded the absolute deadline');
|
|
707
|
+
callbacks.addMessage({ role: 'system', text: `Turn stopped: the ${formatIdleMinutes(abortCause.timeoutMs ?? DEFAULT_TURN_DEADLINE_MS)} turn budget elapsed before the model finished. Completed steps are preserved in the conversation; send a follow-up to continue.` });
|
|
708
|
+
}
|
|
709
|
+
else {
|
|
710
|
+
turnState.aborted = true;
|
|
711
|
+
turnStatus = 'aborted';
|
|
712
|
+
callbacks.debugLog('request aborted');
|
|
713
|
+
callbacks.addMessage({ role: 'system', text: 'Thinking aborted. You can type again.' });
|
|
714
|
+
}
|
|
385
715
|
}
|
|
386
716
|
else {
|
|
387
717
|
const text = error instanceof Error ? error.message : String(error);
|
|
388
718
|
callbacks.debugLog(`error: ${text}`);
|
|
389
719
|
if (!contextOverflowRecovered && isContextOverflowError(error)) {
|
|
390
|
-
const
|
|
720
|
+
const canCompact = typeof callbacks.compactConversation === 'function';
|
|
721
|
+
const compacted = canCompact
|
|
722
|
+
? callbacks.compactConversation?.('Automatic recovery after provider context overflow. Preserve the active user request and concrete next steps.') ?? false
|
|
723
|
+
: false;
|
|
391
724
|
callbacks.onEvent?.(agentEvent({ type: 'context_overflow', recovered: compacted, error: text }));
|
|
392
725
|
if (compacted) {
|
|
393
726
|
callbacks.addMessage({ role: 'system', text: 'Context overflow detected; compacted older context and retrying the same request once.' });
|
|
394
727
|
return { status: 'failed', retry: { attempt: retryAttempt, contextOverflowRecovered: true, delayMs: 0 } };
|
|
395
728
|
}
|
|
396
|
-
callbacks.addMessage({ role: 'system', text:
|
|
729
|
+
callbacks.addMessage({ role: 'system', text: canCompact
|
|
730
|
+
? 'Context overflow detected, but there was not enough conversation history to compact automatically.'
|
|
731
|
+
: 'Context overflow detected, and this mode does not attempt automatic compaction. Resume the session interactively or retry with a smaller request.' });
|
|
397
732
|
}
|
|
398
|
-
|
|
399
|
-
|
|
733
|
+
// Transient model errors share the bounded retry pool with idle-stream
|
|
734
|
+
// stalls, so a turn can never retry more than MAX_MODEL_RETRIES times total.
|
|
735
|
+
if (retryAttempt < MAX_MODEL_RETRIES && isRetryableModelError(error)) {
|
|
400
736
|
const delay = retryDelayMs(retryAttempt);
|
|
401
|
-
callbacks.onEvent?.(agentEvent({ type: 'retry', attempt: retryAttempt + 1, maxAttempts:
|
|
402
|
-
callbacks.addMessage({ role: 'system', text: `Transient model error; retrying attempt ${retryAttempt + 1}/${
|
|
737
|
+
callbacks.onEvent?.(agentEvent({ type: 'retry', attempt: retryAttempt + 1, maxAttempts: MAX_MODEL_RETRIES, delayMs: delay, error: text }));
|
|
738
|
+
callbacks.addMessage({ role: 'system', text: `Transient model error; retrying attempt ${retryAttempt + 1}/${MAX_MODEL_RETRIES} in ${formatSeconds(delay)}: ${text}` });
|
|
403
739
|
return { status: 'failed', retry: { attempt: retryAttempt + 1, contextOverflowRecovered, delayMs: delay } };
|
|
404
740
|
}
|
|
405
741
|
callbacks.addMessage({ role: 'assistant', text: `Model call failed: ${text}` });
|
|
@@ -408,46 +744,124 @@ async function runAgentAttempt(value, contextFiles, callbacks, retryAttempt, ret
|
|
|
408
744
|
finally {
|
|
409
745
|
if (loadedMcp?.clients.length)
|
|
410
746
|
await closeMcpClients(loadedMcp.clients);
|
|
747
|
+
if (lspPool)
|
|
748
|
+
await lspPool.close();
|
|
411
749
|
idleTimer.clear();
|
|
412
750
|
toolDisplay.stopToolTimer();
|
|
413
751
|
toolDisplay.finalizeToolGroup();
|
|
414
752
|
}
|
|
415
|
-
return { status: turnStatus };
|
|
753
|
+
return { status: turnStatus, recovery };
|
|
416
754
|
}
|
|
417
755
|
export async function runAgentTurn(value, displayValue, contextFiles, callbacks, retryAttempt = 0, retryingExistingRequest = false, contextOverflowRecovered = false, session, modelOverride, turnOptions = {}) {
|
|
418
|
-
|
|
756
|
+
// The controller is replaced when an idle-stall retry needs a live signal
|
|
757
|
+
// after aborting a hung stream, so both it and the cause are mutable.
|
|
758
|
+
let abortController = new AbortController();
|
|
759
|
+
let abortCause = createUserAbortCause();
|
|
419
760
|
let status = 'failed';
|
|
761
|
+
let resume;
|
|
762
|
+
const turnState = createTurnExecutionState();
|
|
420
763
|
callbacks.onEvent?.(agentEvent({ type: 'turn_start', request: value }));
|
|
421
764
|
callbacks.setBusy(true);
|
|
422
765
|
callbacks.setAbortController?.(abortController);
|
|
423
766
|
if (!retryingExistingRequest)
|
|
424
767
|
callbacks.addMessage({ role: 'user', text: displayValue ?? value });
|
|
768
|
+
let turnDeadline;
|
|
769
|
+
const turnStartedAt = Date.now();
|
|
770
|
+
const turnDeadlineMs = turnOptions.turnDeadlineMs ?? DEFAULT_TURN_DEADLINE_MS;
|
|
425
771
|
try {
|
|
426
772
|
// Retries are one logical turn and therefore share coordinator admission and
|
|
427
|
-
// the workspace mutation lease, including quarantined lingering work.
|
|
428
|
-
|
|
773
|
+
// the workspace mutation lease, including quarantined lingering work. A
|
|
774
|
+
// goal supervisor may pass one shared scope so every physical turn of the
|
|
775
|
+
// logical goal shares the same lease.
|
|
776
|
+
const turnScope = turnOptions.sharedTurnScope ?? {};
|
|
777
|
+
const turnBudget = mainTurnBudget();
|
|
778
|
+
// Turn-wide execution budget (RH-003): one authoritative counter of
|
|
779
|
+
// underlying tool executions, shared across retries and recovery slices so
|
|
780
|
+
// the global limit cannot be reset or exceeded.
|
|
781
|
+
const globalBudget = createToolExecutionBudget();
|
|
782
|
+
// Turn-wide work state: persists across provider retries and recovery
|
|
783
|
+
// slices so mutation/validation evidence accumulates correctly. When the
|
|
784
|
+
// goal supervisor continues a logical goal, cumulative evidence (tasks,
|
|
785
|
+
// mutations, carried validation) is hydrated so a fresh physical turn
|
|
786
|
+
// cannot complete while carried work remains.
|
|
787
|
+
const goal = createSessionGoal(value);
|
|
788
|
+
if (turnOptions.goalContext)
|
|
789
|
+
seedCarriedGoalEvidence(goal, turnOptions.goalContext.carried);
|
|
790
|
+
// Completion policy is intent-sensitive (implement/fix/test expect
|
|
791
|
+
// post-mutation validation); the turn-wide state carries the classified intent.
|
|
792
|
+
turnState.intent = goal.intent;
|
|
793
|
+
let activeOptions = turnOptions;
|
|
429
794
|
let attempt = retryAttempt;
|
|
430
795
|
let overflowRecovered = contextOverflowRecovered;
|
|
431
796
|
let retrying = retryingExistingRequest;
|
|
432
797
|
while (true) {
|
|
433
|
-
|
|
798
|
+
// Absolute main-turn deadline (RH-004): distinct from the idle timer, it
|
|
799
|
+
// bounds total turn elapsed time so a stream of busy tools cannot defer
|
|
800
|
+
// it. Recreated per attempt with the remaining wall-clock budget and bound
|
|
801
|
+
// to the current attempt's controller — an idle-stall retry replaces the
|
|
802
|
+
// controller and must not trip this deadline early via the old signal.
|
|
803
|
+
turnDeadline = createAbsoluteDeadline({
|
|
804
|
+
timeoutMs: Math.max(0, turnDeadlineMs - (Date.now() - turnStartedAt)),
|
|
805
|
+
signal: abortController.signal,
|
|
806
|
+
onTimeout: () => {
|
|
807
|
+
if (abortController.signal.aborted)
|
|
808
|
+
return;
|
|
809
|
+
callbacks.onEvent?.(agentEvent({ type: 'timeout', phase: 'turn', timeoutMs: turnDeadlineMs }));
|
|
810
|
+
abortForTurn(abortCause, { kind: 'turn-deadline', timeoutMs: turnDeadlineMs }, abortController, `haze turn exceeded the ${turnDeadlineMs}ms absolute deadline.`);
|
|
811
|
+
},
|
|
812
|
+
});
|
|
813
|
+
const result = await runAgentAttempt(value, contextFiles, callbacks, attempt, retrying, overflowRecovered, session, modelOverride, abortController, activeOptions, turnScope, turnState, turnBudget, globalBudget, goal, abortCause, () => Math.max(0, turnDeadlineMs - (Date.now() - turnStartedAt)));
|
|
814
|
+
turnDeadline.clear();
|
|
815
|
+
turnDeadline = undefined;
|
|
434
816
|
status = result.status;
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
817
|
+
resume = result.resume;
|
|
818
|
+
if (result.retry) {
|
|
819
|
+
attempt = result.retry.attempt;
|
|
820
|
+
overflowRecovered = result.retry.contextOverflowRecovered;
|
|
821
|
+
retrying = true;
|
|
822
|
+
if (result.retry.freshController) {
|
|
823
|
+
// The idle stall aborted the previous controller to kill the hung
|
|
824
|
+
// stream; the retry needs a live one (and a fresh 'user' cause).
|
|
825
|
+
abortController = new AbortController();
|
|
826
|
+
abortCause = createUserAbortCause();
|
|
827
|
+
callbacks.setAbortController?.(abortController);
|
|
828
|
+
}
|
|
829
|
+
if (result.retry.delayMs > 0)
|
|
830
|
+
await abortableDelay(result.retry.delayMs, abortController.signal);
|
|
831
|
+
if (abortController.signal.aborted) {
|
|
832
|
+
status = 'aborted';
|
|
833
|
+
break;
|
|
834
|
+
}
|
|
835
|
+
continue;
|
|
836
|
+
}
|
|
837
|
+
// Bounded recovery slice (length-continuation, rescue, or goal
|
|
838
|
+
// continuation). Length/rescue credits are single-use, so a slice cannot
|
|
839
|
+
// trigger another of the same kind; goal continuation is repeatable but
|
|
840
|
+
// progress-guarded and counts against the shared turn budget. Abort is
|
|
841
|
+
// re-checked before and within the slice.
|
|
842
|
+
if (result.recovery && !abortController.signal.aborted) {
|
|
843
|
+
const rec = result.recovery;
|
|
844
|
+
if (rec.kind === 'length') {
|
|
845
|
+
turnState.lengthCreditUsed = true;
|
|
846
|
+
turnState.lengthRecoveriesAttempted += 1;
|
|
847
|
+
}
|
|
848
|
+
else if (rec.kind === 'rescue')
|
|
849
|
+
turnState.rescueUsed = true;
|
|
850
|
+
else
|
|
851
|
+
recordGoalContinuation(turnState);
|
|
852
|
+
activeOptions = { ...activeOptions, ephemeralControl: rec.control, recoverySlice: { kind: rec.kind, maxSteps: rec.slice.maxSteps, maxToolCalls: rec.slice.maxToolCalls } };
|
|
853
|
+
retrying = true;
|
|
854
|
+
callbacks.debugLog(`starting ${rec.kind} recovery slice: ${rec.slice.maxSteps} steps / ${rec.slice.maxToolCalls} tool calls`);
|
|
855
|
+
continue;
|
|
445
856
|
}
|
|
857
|
+
break;
|
|
446
858
|
}
|
|
447
|
-
|
|
859
|
+
const evidence = toCompletionEvidence(turnState);
|
|
860
|
+
return { status, evidence, ...(resume ? { resume } : {}) };
|
|
448
861
|
}
|
|
449
862
|
finally {
|
|
450
|
-
|
|
863
|
+
turnDeadline?.clear();
|
|
864
|
+
callbacks.onEvent?.(agentEvent({ type: 'turn_end', request: value, status, evidence: toCompletionEvidence(turnState) }));
|
|
451
865
|
callbacks.setAbortController?.(null);
|
|
452
866
|
callbacks.setBusyLabel?.(modelThinkingLabel(undefined));
|
|
453
867
|
callbacks.setBusy(false);
|