@denizokcu/haze 0.9.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 +133 -17
- package/README.md +164 -68
- 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/chatMetrics.d.ts +17 -1
- package/dist/cli/chat/chatMetrics.js +22 -5
- package/dist/cli/chat/contextReport.d.ts +11 -0
- package/dist/cli/chat/contextReport.js +46 -0
- package/dist/cli/chat/fileMentionSuggestions.d.ts +29 -0
- package/dist/cli/chat/fileMentionSuggestions.js +92 -0
- package/dist/cli/chat/inputSuggestions.d.ts +5 -0
- package/dist/cli/chat/inputSuggestions.js +17 -3
- 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 +67 -0
- package/dist/cli/chat/sessionLifecycle.js +205 -0
- package/dist/cli/chat/sessionRecorder.js +80 -14
- package/dist/cli/chat/startupInfo.js +11 -4
- package/dist/cli/chat/tips.d.ts +21 -0
- package/dist/cli/chat/tips.js +43 -0
- package/dist/cli/chat/wizardDispatch.d.ts +64 -0
- package/dist/cli/chat/wizardDispatch.js +744 -0
- package/dist/cli/commands/chat.d.ts +6 -0
- package/dist/cli/commands/chat.js +373 -790
- package/dist/cli/commands/chatModes.d.ts +1 -1
- package/dist/cli/commands/chatModes.js +7 -2
- package/dist/cli/commands/commandHelp.js +5 -3
- package/dist/cli/commands/commands.d.ts +5 -2
- package/dist/cli/commands/commands.js +22 -18
- package/dist/cli/commands/doctor.d.ts +19 -0
- package/dist/cli/commands/doctor.js +76 -0
- package/dist/cli/commands/fleetCommand.d.ts +14 -0
- package/dist/cli/commands/fleetCommand.js +46 -0
- package/dist/cli/commands/formatters.d.ts +5 -0
- package/dist/cli/commands/formatters.js +35 -6
- package/dist/cli/commands/logsCommand.js +1 -7
- package/dist/cli/commands/modelCommand.js +1 -1
- package/dist/cli/commands/ndjsonSink.d.ts +23 -0
- package/dist/cli/commands/ndjsonSink.js +38 -0
- package/dist/cli/commands/providerWizard.d.ts +10 -2
- package/dist/cli/commands/providerWizard.js +50 -4
- package/dist/cli/commands/runCommand.d.ts +4 -0
- package/dist/cli/commands/runCommand.js +142 -16
- package/dist/cli/commands/sessionPicker.d.ts +9 -0
- package/dist/cli/commands/sessionPicker.js +29 -0
- package/dist/cli/commands/settingsSummary.js +6 -4
- package/dist/cli/commands/skillConfirmRemove.js +4 -3
- package/dist/cli/commands/skillWizard.d.ts +2 -0
- package/dist/cli/commands/skillWizard.js +16 -6
- 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/idleTimer.d.ts +26 -0
- package/dist/cli/commands/streaming/idleTimer.js +24 -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 +31 -0
- package/dist/cli/commands/streaming/toolGroupRenderer.js +50 -2
- 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/turnRuntime.js +6 -4
- package/dist/cli/commands/streaming.d.ts +82 -3
- package/dist/cli/commands/streaming.js +528 -91
- package/dist/cli/commands/wizardActions.d.ts +7 -0
- package/dist/cli/commands/wizardActions.js +7 -0
- package/dist/cli/commands/wizardPrompts.js +7 -1
- package/dist/cli/commands/wizardSuggestions.d.ts +8 -0
- package/dist/cli/commands/wizardSuggestions.js +64 -14
- package/dist/cli/commands/wizardTransition.d.ts +4 -0
- package/dist/cli/commands/wizardTransition.js +1 -2
- package/dist/cli/index.js +82 -22
- package/dist/cli/terminalTitle.d.ts +6 -0
- package/dist/cli/terminalTitle.js +36 -0
- package/dist/config/inputHistory.d.ts +3 -3
- package/dist/config/inputHistory.js +12 -18
- package/dist/config/modelDiscovery.d.ts +71 -0
- package/dist/config/modelDiscovery.js +214 -0
- 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 +49 -5
- package/dist/config/providerPresets.js +573 -73
- package/dist/config/providers.d.ts +2 -0
- package/dist/config/providers.js +9 -0
- package/dist/config/settings.d.ts +58 -0
- package/dist/config/settings.js +38 -1
- package/dist/config/skillSettings.d.ts +6 -13
- package/dist/config/skillSettings.js +20 -19
- package/dist/core/agent/budgets.d.ts +36 -0
- package/dist/core/agent/budgets.js +44 -0
- package/dist/core/agent/compaction.d.ts +38 -0
- package/dist/core/agent/compaction.js +108 -19
- package/dist/core/agent/completionController.d.ts +230 -0
- package/dist/core/agent/completionController.js +287 -0
- package/dist/core/agent/contextBudget.d.ts +46 -0
- package/dist/core/agent/contextBudget.js +89 -7
- package/dist/core/agent/errors.js +6 -2
- package/dist/core/agent/events.d.ts +86 -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 +13 -0
- package/dist/core/agent/toolOutputStore.js +27 -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 +76 -1
- package/dist/core/agent/workState.js +120 -13
- package/dist/core/attachments/imageAttachments.d.ts +90 -0
- package/dist/core/attachments/imageAttachments.js +245 -0
- package/dist/core/attachments/readBlessings.d.ts +37 -0
- package/dist/core/attachments/readBlessings.js +79 -0
- 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/goal/requestClassifier.d.ts +0 -3
- package/dist/core/goal/requestClassifier.js +0 -13
- package/dist/core/io/boundedRead.js +76 -29
- package/dist/core/limits/byteBudgets.d.ts +7 -0
- package/dist/core/limits/byteBudgets.js +7 -0
- package/dist/core/limits/textBudgets.d.ts +25 -0
- package/dist/core/limits/textBudgets.js +25 -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.d.ts +35 -0
- package/dist/core/process/backgroundRegistry.js +195 -0
- package/dist/core/process/runBoundedProcess.d.ts +9 -0
- package/dist/core/process/runBoundedProcess.js +74 -29
- package/dist/core/safety/missingExecutable.d.ts +42 -0
- package/dist/core/safety/missingExecutable.js +77 -0
- package/dist/core/safety/urlGuard.d.ts +2 -1
- package/dist/core/safety/urlGuard.js +3 -2
- package/dist/core/session/sessionSlimming.js +47 -4
- package/dist/core/session/sessionStore.d.ts +74 -0
- package/dist/core/session/sessionStore.js +268 -18
- package/dist/core/subagent/contracts.d.ts +120 -0
- package/dist/core/subagent/contracts.js +55 -0
- package/dist/core/subagent/executionProfiles.d.ts +28 -0
- package/dist/core/subagent/executionProfiles.js +45 -0
- package/dist/core/subagent/subagentCoordinator.d.ts +78 -0
- package/dist/core/subagent/subagentCoordinator.js +164 -0
- package/dist/core/subagent/subagentRunner.d.ts +211 -145
- package/dist/core/subagent/subagentRunner.js +208 -98
- package/dist/core/subagent/workspaceMutationPolicy.d.ts +11 -0
- package/dist/core/subagent/workspaceMutationPolicy.js +52 -0
- package/dist/core/tasks/taskStorage.js +12 -1
- package/dist/llm/client.d.ts +36 -29
- package/dist/llm/client.js +102 -33
- package/dist/llm/hazeTools.d.ts +2559 -150
- package/dist/llm/hazeTools.js +119 -31
- package/dist/llm/lsp.d.ts +26 -4
- package/dist/llm/lsp.js +90 -14
- 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 +25 -1
- package/dist/llm/requestContext.js +51 -8
- package/dist/llm/systemPrompt.d.ts +15 -1
- package/dist/llm/systemPrompt.js +24 -8
- package/dist/llm/toolResultTypes.d.ts +8 -1
- package/dist/llm/tools/bashTool.d.ts +906 -32
- package/dist/llm/tools/bashTool.js +30 -4
- 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 +42 -26
- package/dist/llm/tools/fetchTool.js +1 -1
- package/dist/llm/tools/fileToolShared.d.ts +6 -4
- package/dist/llm/tools/fileToolShared.js +18 -23
- package/dist/llm/tools/gitIgnore.d.ts +49 -0
- package/dist/llm/tools/gitIgnore.js +129 -0
- package/dist/llm/tools/grepRunner.d.ts +5 -0
- package/dist/llm/tools/grepRunner.js +52 -71
- package/dist/llm/tools/outputCap.d.ts +2 -6
- package/dist/llm/tools/outputCap.js +2 -6
- package/dist/llm/tools/processTool.d.ts +1077 -0
- package/dist/llm/tools/processTool.js +41 -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 +9 -1
- package/dist/llm/tools/toolContext.js +83 -43
- package/dist/llm/tools/workspaceFile.d.ts +9 -1
- package/dist/llm/tools/workspaceFile.js +33 -4
- package/dist/llm/webFetch.d.ts +17 -0
- package/dist/llm/webFetch.js +66 -86
- package/dist/llm/workerContext.d.ts +18 -0
- package/dist/llm/workerContext.js +55 -0
- package/dist/skills/SkillLoader.d.ts +2 -2
- package/dist/skills/SkillRegistry.d.ts +3 -2
- package/dist/skills/SkillRegistry.js +43 -13
- package/dist/skills/builder/SkillBuilder.d.ts +3 -0
- package/dist/skills/builder/SkillBuilder.js +23 -5
- package/dist/skills/skillTools.js +11 -4
- package/dist/skills/types.d.ts +6 -1
- 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 +12 -2
- package/dist/ui/components/TextInput.js +80 -8
- 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/format.d.ts +2 -0
- package/dist/utils/format.js +8 -0
- package/dist/utils/fs.d.ts +9 -1
- package/dist/utils/fs.js +87 -29
- package/dist/utils/openPath.d.ts +2 -0
- package/dist/utils/openPath.js +22 -0
- 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
|
@@ -4,26 +4,39 @@ import { modelWithConfig, providerRequestSettings } from '../../llm/client.js';
|
|
|
4
4
|
import { assembleRequestContext } from '../../llm/requestContext.js';
|
|
5
5
|
import { projectContextSection } from '../../llm/systemPrompt.js';
|
|
6
6
|
import { closeMcpClients } from '../../llm/mcp.js';
|
|
7
|
+
import { readSettings } from '../../config/settings.js';
|
|
7
8
|
import { toolCallSummary, toolResultSummary, busyToolLabel, formatSeconds } from './formatters.js';
|
|
8
9
|
import { agentEvent } from '../../core/agent/events.js';
|
|
9
10
|
import { isContextOverflowError, isRetryableModelError } from '../../core/agent/errors.js';
|
|
10
11
|
import { isPlanOnlyRequest } from '../../core/goal/requestClassifier.js';
|
|
11
|
-
import {
|
|
12
|
-
import {
|
|
12
|
+
import { userTurnMessage } from '../../core/attachments/imageAttachments.js';
|
|
13
|
+
import { malformedToolCallPrompt, repeatedToolCallPrompt, toolLoopBudgetPrompt, lengthContinuationPrompt, completionRescuePrompt, goalContinuationPrompt } from '../../core/goal/completionPolicy.js';
|
|
14
|
+
import { calculateRequestTokenBudget, estimateMessagesTokens, estimateValueTokens } from '../../core/agent/contextBudget.js';
|
|
13
15
|
import { compactToolHistory, stripSyntheticControls, withSyntheticControl, withoutSystemMessages } from '../../core/agent/requestAssembly.js';
|
|
14
|
-
import { isDuplicateSkippedOutput,
|
|
15
|
-
import {
|
|
16
|
-
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';
|
|
17
19
|
import { compactModelMessages } from '../../core/agent/compaction.js';
|
|
18
|
-
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';
|
|
19
27
|
import { createSessionGoal, formatGoalStatus, observeGoalToolEvent } from '../../core/goal/sessionGoal.js';
|
|
28
|
+
import { buildIncompleteGoalResume } from './streaming/goalCheckpoint.js';
|
|
20
29
|
import { sanitizeAssistantText, assistantDisplayText, normalizeAssistantText, shouldStartAssistantStream, isHiddenAssistantFragment, isHiddenUnstartedFinalText, isShortLeadInBeforeTool, isShortUnfinishedLeadIn } from './streaming/assistantText.js';
|
|
21
|
-
import { createToolGroupRenderer } from './streaming/toolGroupRenderer.js';
|
|
22
|
-
import {
|
|
30
|
+
import { createToolGroupRenderer, toolDiffFromResult } from './streaming/toolGroupRenderer.js';
|
|
31
|
+
import { applyStepToolResultState, initialToolResultState } from './streaming/toolResultState.js';
|
|
23
32
|
import { abortableDelay, estimateInputBreakdown, extractUsage, rememberContextFilesFromToolOutput, responseCompletionMetrics, retryDelayMs, stepCacheMetrics, subagentTokenEstimate } from './streaming/turnRuntime.js';
|
|
24
33
|
import { toolsContextFor } from '../../llm/tools/toolContext.js';
|
|
25
34
|
import { modelThinkingLabel } from '../../utils/modelName.js';
|
|
26
35
|
import { terminalTurnStatus } from './streaming/turnOutcome.js';
|
|
36
|
+
import { createIdleTimer } from './streaming/idleTimer.js';
|
|
37
|
+
import { abortForTurn, createUserAbortCause } from './streaming/abortCause.js';
|
|
38
|
+
import { isMalformedToolInputError } from './streaming/toolCallRecovery.js';
|
|
39
|
+
import { WorkspaceMutationPolicy } from '../../core/subagent/workspaceMutationPolicy.js';
|
|
27
40
|
function logEntry(log, entry) {
|
|
28
41
|
if (log)
|
|
29
42
|
void logAppend(log, entry).catch(() => undefined);
|
|
@@ -35,50 +48,161 @@ function withScopedContextControl(messages, context) {
|
|
|
35
48
|
context.pendingContextFiles = [];
|
|
36
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)}`);
|
|
37
50
|
}
|
|
38
|
-
|
|
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) {
|
|
39
79
|
let thinkingLabel = modelThinkingLabel(undefined);
|
|
40
80
|
callbacks.setBusyLabel?.(thinkingLabel);
|
|
41
81
|
let turnStatus = 'failed';
|
|
42
|
-
let
|
|
82
|
+
let recovery;
|
|
43
83
|
let loadedMcp;
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
84
|
+
let lspPool;
|
|
85
|
+
// Tool calls currently executing. A concurrent subagent wave can run for many
|
|
86
|
+
// minutes with no stream parts; that is activity, not a dead stream, so the
|
|
87
|
+
// idle timer defers while any tool is in flight (see streaming/idleTimer.ts).
|
|
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;
|
|
103
|
+
const idleTimer = createIdleTimer({
|
|
104
|
+
timeoutMs: IDLE_TIMEOUT_MS,
|
|
105
|
+
isBusy: () => inFlightTools.size > 0,
|
|
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
|
+
},
|
|
133
|
+
});
|
|
51
134
|
const toolDisplay = createToolGroupRenderer({ addMessage: callbacks.addMessage, updateMessage: callbacks.updateMessage, debugLog: callbacks.debugLog, onEvent: callbacks.onEvent, log: callbacks.log });
|
|
52
135
|
try {
|
|
53
|
-
|
|
136
|
+
// Single choke point: one fresh settings read per turn, shared by model
|
|
137
|
+
// resolution and request assembly (CR-024).
|
|
138
|
+
const turnSettings = await readSettings();
|
|
139
|
+
const runtime = await modelWithConfig({ cwd: session?.cwd, modelSelector: modelOverride }, turnSettings);
|
|
54
140
|
if (!runtime?.model) {
|
|
55
141
|
callbacks.addMessage({ role: 'assistant', text: 'No model provider configured. Run /provider to choose or add a provider. haze cannot hallucinate without a model. Progress.' });
|
|
56
142
|
turnStatus = 'failed';
|
|
57
143
|
return { status: turnStatus };
|
|
58
144
|
}
|
|
59
145
|
thinkingLabel = modelThinkingLabel(runtime.config.modelName);
|
|
146
|
+
activeProviderName = runtime.config.providerName;
|
|
147
|
+
activeModelName = runtime.config.modelName;
|
|
60
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
|
+
}
|
|
61
166
|
let activeContextFiles = contextFiles;
|
|
62
167
|
const activeModel = runtime.model;
|
|
63
|
-
const providerSettings = providerRequestSettings(runtime.config);
|
|
64
|
-
const assembled = await assembleRequestContext({ contextFiles: activeContextFiles, session, model: activeModel, abortSignal: abortController.signal
|
|
168
|
+
const { omitMaxOutputTokens, ...providerSettings } = providerRequestSettings(runtime.config);
|
|
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'
|
|
170
|
+
? { type: 'subagent_state', id: event.id, state: 'queued', mode: event.mode, queued: event.queued, running: event.running }
|
|
171
|
+
: event.type === 'started'
|
|
172
|
+
? { type: 'subagent_state', id: event.id, state: 'started', mode: event.mode, queueMs: event.queueMs, running: event.running }
|
|
173
|
+
: event.type === 'terminal'
|
|
174
|
+
? { type: 'subagent_state', id: event.id, state: 'terminal', mode: event.mode, queueMs: event.queueMs, durationMs: event.durationMs, termination: event.termination, execution: event.execution, running: event.running }
|
|
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 })) });
|
|
176
|
+
turnScope.executionScope ??= assembled.executionScope;
|
|
65
177
|
const availableTools = assembled.availableTools;
|
|
178
|
+
const toolCategories = assembled.toolCategories;
|
|
66
179
|
loadedMcp = assembled.loadedMcp;
|
|
180
|
+
lspPool = assembled.lspPool;
|
|
67
181
|
if (loadedMcp?.errors.length)
|
|
68
182
|
callbacks.addMessage({ role: 'system', text: `MCP: ${loadedMcp.errors.join('; ')}` });
|
|
69
|
-
const goal = createSessionGoal(value);
|
|
70
183
|
callbacks.setWorkState?.(goal);
|
|
71
184
|
callbacks.setGoalStatus?.(formatGoalStatus(goal));
|
|
72
185
|
const likelyPlanOnlyRequest = isPlanOnlyRequest(value);
|
|
73
186
|
const durableRequestMessages = compactToolHistory(retryingExistingRequest
|
|
74
187
|
? stripSyntheticControls(callbacks.getConversation())
|
|
75
|
-
: [...stripSyntheticControls(callbacks.getConversation()),
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
188
|
+
: [...stripSyntheticControls(callbacks.getConversation()), userTurnMessage(value, turnOptions.attachments ?? [])]).messages;
|
|
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;
|
|
79
201
|
}
|
|
80
202
|
requestMessages = withoutSystemMessages(requestMessages);
|
|
81
203
|
callbacks.setConversation(stripSyntheticControls(requestMessages));
|
|
204
|
+
if (turnOptions.ephemeralControl)
|
|
205
|
+
requestMessages = withSyntheticControl(requestMessages, turnOptions.ephemeralControl);
|
|
82
206
|
const systemPrompt = assembled.systemPrompt;
|
|
83
207
|
const inputBreakdown = estimateInputBreakdown({ system: systemPrompt, contextFiles: activeContextFiles, messages: requestMessages, tools: availableTools });
|
|
84
208
|
logEntry(callbacks.log, { at: new Date().toISOString(), type: 'request', stream: 'main', system: systemPrompt, messages: requestMessages, tools: Object.keys(availableTools), context: inputBreakdown.breakdown });
|
|
@@ -92,22 +216,22 @@ async function runAgentAttempt(value, contextFiles, callbacks, retryAttempt, ret
|
|
|
92
216
|
callbacks.setLastAssistantText(text);
|
|
93
217
|
};
|
|
94
218
|
const contextFileSignatures = callbacks.contextFileSignatures ?? new Map(activeContextFiles.flatMap(file => file.signature ? [[file.path, file.signature]] : []));
|
|
95
|
-
const
|
|
219
|
+
const mutationPolicy = assembled.executionScope?.mutationPolicy ?? new WorkspaceMutationPolicy();
|
|
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 };
|
|
96
221
|
const startedTools = new Map();
|
|
97
222
|
const latestToolCalls = new Map();
|
|
98
|
-
let latestAccumulatedResponseMessages = [];
|
|
99
223
|
let currentAssistantId = `assistant-${Date.now()}`;
|
|
100
|
-
let assistantStarted = false;
|
|
101
224
|
let assistantStartedAt = Date.now();
|
|
102
225
|
let assistantText = '';
|
|
103
|
-
let currentAssistantText = '';
|
|
104
226
|
let streamError;
|
|
105
227
|
let streamFinished = false;
|
|
106
228
|
let finishReason;
|
|
107
229
|
let lastToolOk;
|
|
108
|
-
let
|
|
109
|
-
let
|
|
110
|
-
|
|
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();
|
|
111
235
|
let toolResultState = initialToolResultState();
|
|
112
236
|
const resetAssistantSegment = () => {
|
|
113
237
|
currentAssistantId = `assistant-${Date.now()}-${Math.random().toString(36).slice(2)}`;
|
|
@@ -138,46 +262,139 @@ async function runAgentAttempt(value, contextFiles, callbacks, retryAttempt, ret
|
|
|
138
262
|
resetAssistantSegment();
|
|
139
263
|
return !hidden;
|
|
140
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
|
+
}));
|
|
141
293
|
const agent = new ToolLoopAgent({
|
|
142
294
|
id: 'haze-main',
|
|
143
295
|
model: activeModel,
|
|
144
296
|
instructions: systemPrompt,
|
|
145
|
-
tools:
|
|
146
|
-
maxOutputTokens: DEFAULT_MAX_OUTPUT_TOKENS,
|
|
297
|
+
tools: deadlineWrappedTools,
|
|
298
|
+
...(!omitMaxOutputTokens ? { maxOutputTokens: DEFAULT_MAX_OUTPUT_TOKENS } : {}),
|
|
147
299
|
...providerSettings,
|
|
148
|
-
stopWhen: isStepCount(
|
|
300
|
+
stopWhen: isStepCount(stepCap),
|
|
149
301
|
runtimeContext: toolExecutionContext,
|
|
150
|
-
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
|
+
},
|
|
151
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
|
+
}
|
|
152
319
|
const toolCalls = steps.flatMap(step => step.toolCalls);
|
|
153
|
-
const repeatedToolNames =
|
|
154
|
-
|
|
155
|
-
|
|
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;
|
|
156
338
|
if (likelyPlanOnlyRequest && toolResultState.mutatingToolSucceeded)
|
|
157
339
|
return messagesChanged ? { toolChoice: 'none', messages: scopedMessages } : { toolChoice: 'none' };
|
|
158
|
-
if (
|
|
159
|
-
|
|
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
|
+
}
|
|
160
357
|
if (repeatedToolNames.length > 0) {
|
|
161
|
-
const activeTools = Object.keys(
|
|
358
|
+
const activeTools = Object.keys(sliceTools).filter(name => !repeatedToolNames.includes(name));
|
|
162
359
|
callbacks.debugLog(`disabling repeated tools for next step: ${repeatedToolNames.join(', ')}`);
|
|
163
360
|
return activeTools.length > 0
|
|
164
361
|
? { activeTools, messages: withSyntheticControl(scopedMessages, repeatedToolCallPrompt(repeatedToolNames)) }
|
|
165
362
|
: { toolChoice: 'none', messages: withSyntheticControl(scopedMessages, repeatedToolCallPrompt(repeatedToolNames)) };
|
|
166
363
|
}
|
|
167
|
-
if (
|
|
364
|
+
if (turnToolCallsExhausted || sliceToolCallsExhausted || toolOnlyBoundaryHit || toolCalls.length >= MAIN_TOOL_CALL_LIMIT) {
|
|
168
365
|
callbacks.debugLog('forcing text response to avoid tool loop');
|
|
169
366
|
return { toolChoice: 'none', messages: withSyntheticControl(scopedMessages, toolLoopBudgetPrompt()) };
|
|
170
367
|
}
|
|
171
368
|
return messagesChanged ? { messages: scopedMessages } : undefined;
|
|
172
369
|
},
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
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;
|
|
176
385
|
if (toolCalls.length > 0 && text.trim().length === 0)
|
|
177
|
-
|
|
386
|
+
turnState.toolOnlyStepsUsed += 1;
|
|
178
387
|
if (Array.isArray(response?.messages) && response.messages.length > 0)
|
|
179
388
|
latestAccumulatedResponseMessages = response.messages;
|
|
180
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 }));
|
|
181
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 } });
|
|
182
399
|
callbacks.debugLog(`step ${stepNumber} finished: ${finishReason}; text=${text.length}; toolCalls=${toolCalls.length}; toolResults=${toolResults.length}`);
|
|
183
400
|
},
|
|
@@ -203,10 +420,12 @@ async function runAgentAttempt(value, contextFiles, callbacks, retryAttempt, ret
|
|
|
203
420
|
callbacks.debugLog(`conversation updated to ${compacted.messages.length} messages by ToolLoopAgent`);
|
|
204
421
|
},
|
|
205
422
|
});
|
|
206
|
-
|
|
423
|
+
idleTimer.reset();
|
|
207
424
|
const result = await agent.stream({ messages: requestMessages, abortSignal: abortController.signal });
|
|
208
425
|
for await (const part of result.stream) {
|
|
209
|
-
|
|
426
|
+
idleTimer.reset();
|
|
427
|
+
lastStreamEventAt = Date.now();
|
|
428
|
+
lastStreamEventType = part.type;
|
|
210
429
|
switch (part.type) {
|
|
211
430
|
case 'text-delta': {
|
|
212
431
|
callbacks.setBusyLabel?.(thinkingLabel);
|
|
@@ -238,7 +457,7 @@ async function runAgentAttempt(value, contextFiles, callbacks, retryAttempt, ret
|
|
|
238
457
|
}
|
|
239
458
|
const toolCall = { toolCallId: part.id, toolName: part.toolName, input: {} };
|
|
240
459
|
latestToolCalls.set(part.id, toolCall);
|
|
241
|
-
|
|
460
|
+
inFlightTools.add(part.id);
|
|
242
461
|
callbacks.setBusyLabel?.(busyToolLabel(part.toolName, {}));
|
|
243
462
|
toolDisplay.ensureToolItem(toolCall);
|
|
244
463
|
break;
|
|
@@ -252,8 +471,8 @@ async function runAgentAttempt(value, contextFiles, callbacks, retryAttempt, ret
|
|
|
252
471
|
}
|
|
253
472
|
const toolCall = { toolCallId: part.toolCallId, toolName: part.toolName, input: part.input };
|
|
254
473
|
latestToolCalls.set(part.toolCallId, toolCall);
|
|
255
|
-
|
|
256
|
-
|
|
474
|
+
// Tool execution begins only after its complete input has parsed and validated.
|
|
475
|
+
startedTools.set(part.toolCallId, Date.now());
|
|
257
476
|
callbacks.setBusyLabel?.(busyToolLabel(part.toolName, part.input));
|
|
258
477
|
toolDisplay.ensureToolItem(toolCall).summary = toolCallSummary(part.toolName, part.input);
|
|
259
478
|
toolDisplay.updateToolGroup(true);
|
|
@@ -262,18 +481,48 @@ async function runAgentAttempt(value, contextFiles, callbacks, retryAttempt, ret
|
|
|
262
481
|
case 'tool-result': {
|
|
263
482
|
const toolCall = { toolCallId: part.toolCallId, toolName: part.toolName, input: part.input };
|
|
264
483
|
latestToolCalls.set(part.toolCallId, toolCall);
|
|
484
|
+
inFlightTools.delete(part.toolCallId);
|
|
265
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
|
+
}
|
|
266
512
|
const ok = toolOutputOk(part.output, true);
|
|
267
513
|
lastToolOk = ok;
|
|
514
|
+
if (ok && part.toolName === unresolvedMalformedToolName)
|
|
515
|
+
unresolvedMalformedToolName = undefined;
|
|
268
516
|
const finish = { toolCall, success: ok, output: part.output, durationMs: Date.now() - startedAt };
|
|
269
517
|
const item = toolDisplay.ensureToolItem(toolCall);
|
|
270
518
|
item.status = ok ? 'success' : 'error';
|
|
271
519
|
item.result = toolResultSummary(finish);
|
|
520
|
+
item.diff = toolDiffFromResult(toolCall, part.output);
|
|
272
521
|
item.durationMs = finish.durationMs;
|
|
273
522
|
item.finishedAt = startedAt + finish.durationMs;
|
|
274
|
-
|
|
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 }));
|
|
275
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 } });
|
|
276
|
-
toolResultState = applyToolResultState(toolResultState, { toolName: toolCall.toolName, input: toolCall.input, output: part.output, ok });
|
|
277
526
|
observeGoalToolEvent(goal, { ...toolCall, success: ok, output: part.output, duplicateSkipped: isDuplicateSkippedOutput(part.output) });
|
|
278
527
|
callbacks.setWorkState?.(goal);
|
|
279
528
|
callbacks.setGoalStatus?.(formatGoalStatus(goal));
|
|
@@ -287,21 +536,24 @@ async function runAgentAttempt(value, contextFiles, callbacks, retryAttempt, ret
|
|
|
287
536
|
break;
|
|
288
537
|
}
|
|
289
538
|
case 'tool-error': {
|
|
539
|
+
inFlightTools.delete(part.toolCallId);
|
|
290
540
|
const existing = latestToolCalls.get(part.toolCallId);
|
|
291
541
|
const toolCall = { toolCallId: part.toolCallId, toolName: part.toolName, input: part.input ?? existing?.input };
|
|
292
542
|
const startedAt = startedTools.get(part.toolCallId) ?? Date.now();
|
|
293
543
|
lastToolOk = false;
|
|
544
|
+
if (isMalformedToolInputError(part.error)) {
|
|
545
|
+
pendingMalformedToolName = part.toolName;
|
|
546
|
+
unresolvedMalformedToolName = part.toolName;
|
|
547
|
+
}
|
|
294
548
|
const finish = { toolCall, success: false, error: part.error, durationMs: Date.now() - startedAt };
|
|
295
549
|
const item = toolDisplay.ensureToolItem(toolCall);
|
|
296
550
|
item.status = 'error';
|
|
297
551
|
item.result = toolResultSummary(finish);
|
|
298
552
|
item.durationMs = finish.durationMs;
|
|
299
553
|
item.finishedAt = startedAt + finish.durationMs;
|
|
300
|
-
|
|
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 }));
|
|
301
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 } });
|
|
302
|
-
if (isMutatingToolName(toolCall.toolName)) {
|
|
303
|
-
toolResultState = { ...toolResultState, editRecoveryPath: toolInputField(toolCall.input, 'path'), editRecoveryReadSatisfied: false };
|
|
304
|
-
}
|
|
305
557
|
observeGoalToolEvent(goal, { ...toolCall, success: false, output: part.error });
|
|
306
558
|
callbacks.setWorkState?.(goal);
|
|
307
559
|
callbacks.setGoalStatus?.(formatGoalStatus(goal));
|
|
@@ -346,39 +598,144 @@ async function runAgentAttempt(value, contextFiles, callbacks, retryAttempt, ret
|
|
|
346
598
|
else if (latestToolCalls.size > 0) {
|
|
347
599
|
callbacks.addMessage({ role: 'system', text: 'Tool work ended without a substantive final answer.' });
|
|
348
600
|
}
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
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.` });
|
|
354
616
|
goal.phase = 'done';
|
|
355
|
-
|
|
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';
|
|
356
626
|
callbacks.setWorkState?.(goal);
|
|
357
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
|
+
}
|
|
358
671
|
}
|
|
359
672
|
catch (error) {
|
|
360
673
|
if (abortController.signal.aborted) {
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
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
|
+
}
|
|
364
715
|
}
|
|
365
716
|
else {
|
|
366
717
|
const text = error instanceof Error ? error.message : String(error);
|
|
367
718
|
callbacks.debugLog(`error: ${text}`);
|
|
368
719
|
if (!contextOverflowRecovered && isContextOverflowError(error)) {
|
|
369
|
-
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;
|
|
370
724
|
callbacks.onEvent?.(agentEvent({ type: 'context_overflow', recovered: compacted, error: text }));
|
|
371
725
|
if (compacted) {
|
|
372
726
|
callbacks.addMessage({ role: 'system', text: 'Context overflow detected; compacted older context and retrying the same request once.' });
|
|
373
727
|
return { status: 'failed', retry: { attempt: retryAttempt, contextOverflowRecovered: true, delayMs: 0 } };
|
|
374
728
|
}
|
|
375
|
-
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.' });
|
|
376
732
|
}
|
|
377
|
-
|
|
378
|
-
|
|
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)) {
|
|
379
736
|
const delay = retryDelayMs(retryAttempt);
|
|
380
|
-
callbacks.onEvent?.(agentEvent({ type: 'retry', attempt: retryAttempt + 1, maxAttempts:
|
|
381
|
-
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}` });
|
|
382
739
|
return { status: 'failed', retry: { attempt: retryAttempt + 1, contextOverflowRecovered, delayMs: delay } };
|
|
383
740
|
}
|
|
384
741
|
callbacks.addMessage({ role: 'assistant', text: `Model call failed: ${text}` });
|
|
@@ -387,44 +744,124 @@ async function runAgentAttempt(value, contextFiles, callbacks, retryAttempt, ret
|
|
|
387
744
|
finally {
|
|
388
745
|
if (loadedMcp?.clients.length)
|
|
389
746
|
await closeMcpClients(loadedMcp.clients);
|
|
390
|
-
if (
|
|
391
|
-
|
|
747
|
+
if (lspPool)
|
|
748
|
+
await lspPool.close();
|
|
749
|
+
idleTimer.clear();
|
|
392
750
|
toolDisplay.stopToolTimer();
|
|
393
751
|
toolDisplay.finalizeToolGroup();
|
|
394
752
|
}
|
|
395
|
-
return { status: turnStatus };
|
|
753
|
+
return { status: turnStatus, recovery };
|
|
396
754
|
}
|
|
397
|
-
export async function runAgentTurn(value, displayValue, contextFiles, callbacks, retryAttempt = 0, retryingExistingRequest = false, contextOverflowRecovered = false, session, modelOverride) {
|
|
398
|
-
|
|
755
|
+
export async function runAgentTurn(value, displayValue, contextFiles, callbacks, retryAttempt = 0, retryingExistingRequest = false, contextOverflowRecovered = false, session, modelOverride, turnOptions = {}) {
|
|
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();
|
|
399
760
|
let status = 'failed';
|
|
761
|
+
let resume;
|
|
762
|
+
const turnState = createTurnExecutionState();
|
|
400
763
|
callbacks.onEvent?.(agentEvent({ type: 'turn_start', request: value }));
|
|
401
764
|
callbacks.setBusy(true);
|
|
402
765
|
callbacks.setAbortController?.(abortController);
|
|
403
766
|
if (!retryingExistingRequest)
|
|
404
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;
|
|
405
771
|
try {
|
|
772
|
+
// Retries are one logical turn and therefore share coordinator admission and
|
|
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;
|
|
406
794
|
let attempt = retryAttempt;
|
|
407
795
|
let overflowRecovered = contextOverflowRecovered;
|
|
408
796
|
let retrying = retryingExistingRequest;
|
|
409
797
|
while (true) {
|
|
410
|
-
|
|
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;
|
|
411
816
|
status = result.status;
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
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;
|
|
422
856
|
}
|
|
857
|
+
break;
|
|
423
858
|
}
|
|
424
|
-
|
|
859
|
+
const evidence = toCompletionEvidence(turnState);
|
|
860
|
+
return { status, evidence, ...(resume ? { resume } : {}) };
|
|
425
861
|
}
|
|
426
862
|
finally {
|
|
427
|
-
|
|
863
|
+
turnDeadline?.clear();
|
|
864
|
+
callbacks.onEvent?.(agentEvent({ type: 'turn_end', request: value, status, evidence: toCompletionEvidence(turnState) }));
|
|
428
865
|
callbacks.setAbortController?.(null);
|
|
429
866
|
callbacks.setBusyLabel?.(modelThinkingLabel(undefined));
|
|
430
867
|
callbacks.setBusy(false);
|