@denizokcu/haze 0.11.0 → 1.1.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 +33 -0
- package/README.md +28 -14
- package/SECURITY.md +5 -3
- package/dist/buildInfo.json +3 -3
- package/dist/cli/chat/TaskBar.js +1 -1
- package/dist/cli/chat/chatMetrics.d.ts +2 -2
- package/dist/cli/chat/chatMetrics.js +1 -1
- package/dist/cli/chat/fileMentionSuggestions.js +1 -1
- package/dist/cli/chat/inputSuggestions.d.ts +8 -16
- package/dist/cli/chat/inputSuggestions.js +10 -41
- package/dist/cli/chat/messages.d.ts +0 -2
- package/dist/cli/chat/messages.js +5 -5
- package/dist/cli/chat/sessionLifecycle.d.ts +2 -1
- package/dist/cli/chat/turnState.d.ts +1 -1
- package/dist/cli/chat/wizardDispatch.d.ts +90 -28
- package/dist/cli/chat/wizardDispatch.js +257 -130
- package/dist/cli/commands/chat.js +61 -77
- package/dist/cli/commands/chatModes.d.ts +8 -1
- package/dist/cli/commands/chatModes.js +9 -44
- package/dist/cli/commands/commandHelp.js +2 -0
- package/dist/cli/commands/commands.js +2 -0
- package/dist/cli/commands/doctor.js +1 -1
- package/dist/cli/commands/formatters.d.ts +3 -3
- package/dist/cli/commands/formatters.js +12 -25
- package/dist/cli/commands/providerWizard.js +2 -3
- package/dist/cli/commands/runCommand.js +1 -1
- package/dist/cli/commands/serverWizard.d.ts +34 -0
- package/dist/cli/commands/{mcpWizard.js → serverWizard.js} +44 -2
- package/dist/cli/commands/settingsSummary.js +2 -0
- package/dist/cli/commands/skillsWizard.d.ts +41 -0
- package/dist/cli/commands/{skillWizard.js → skillsWizard.js} +33 -11
- package/dist/cli/commands/streaming/abortCause.d.ts +2 -1
- package/dist/cli/commands/streaming/agentAttempt.d.ts +43 -0
- package/dist/cli/commands/streaming/agentAttempt.js +79 -0
- package/dist/cli/commands/streaming/attemptLifecycle.d.ts +56 -0
- package/dist/cli/commands/streaming/attemptLifecycle.js +110 -0
- package/dist/cli/commands/streaming/attemptOutcome.d.ts +96 -0
- package/dist/cli/commands/streaming/attemptOutcome.js +206 -0
- package/dist/cli/commands/streaming/attemptSetup.d.ts +78 -0
- package/dist/cli/commands/streaming/attemptSetup.js +167 -0
- package/dist/cli/commands/streaming/goalCheckpoint.d.ts +1 -1
- package/dist/cli/commands/streaming/goalCheckpoint.js +2 -2
- package/dist/cli/commands/streaming/goalSupervisor.js +9 -6
- package/dist/cli/commands/streaming/stallRecovery.d.ts +94 -0
- package/dist/cli/commands/streaming/stallRecovery.js +105 -0
- package/dist/cli/commands/streaming/streamLoop.d.ts +72 -0
- package/dist/cli/commands/streaming/streamLoop.js +448 -0
- package/dist/cli/commands/streaming/toolCallRecovery.d.ts +14 -0
- package/dist/cli/commands/streaming/toolCallRecovery.js +56 -0
- package/dist/cli/commands/streaming/toolGroupRenderer.d.ts +2 -1
- package/dist/cli/commands/streaming/turnRuntime.d.ts +4 -0
- package/dist/cli/commands/streaming/turnRuntime.js +6 -0
- package/dist/cli/commands/streaming.d.ts +14 -25
- package/dist/cli/commands/streaming.js +43 -754
- package/dist/cli/commands/themesCommand.d.ts +17 -0
- package/dist/cli/commands/themesCommand.js +24 -0
- package/dist/cli/commands/wizardFlow.d.ts +341 -0
- package/dist/cli/commands/wizardFlow.js +397 -0
- package/dist/cli/contextReport.js +3 -0
- package/dist/cli/index.js +1 -1
- package/dist/config/contextFiles.js +9 -3
- package/dist/config/inputHistory.d.ts +0 -1
- package/dist/config/inputHistory.js +1 -1
- package/dist/config/modelDiscovery.d.ts +0 -15
- package/dist/config/modelDiscovery.js +1 -1
- package/dist/config/settings.d.ts +9 -0
- package/dist/config/settings.js +4 -0
- package/dist/config/skillSettings.js +4 -4
- package/dist/config/updateCheck.d.ts +0 -1
- package/dist/config/updateCheck.js +1 -1
- package/dist/core/agent/budgets.d.ts +63 -1
- package/dist/core/agent/budgets.js +84 -1
- package/dist/core/agent/compaction.js +1 -1
- package/dist/core/agent/completionController.d.ts +7 -13
- package/dist/core/agent/completionController.js +17 -8
- package/dist/core/agent/contextBudget.d.ts +0 -4
- package/dist/core/agent/contextBudget.js +3 -3
- package/dist/core/agent/errors.d.ts +0 -1
- package/dist/core/agent/errors.js +1 -1
- package/dist/core/agent/events.d.ts +5 -1
- package/dist/core/{goal/completionPolicy.d.ts → agent/goalPolicy.d.ts} +18 -0
- package/dist/core/agent/goalPolicy.js +106 -0
- package/dist/core/agent/requestAssembly.d.ts +2 -2
- package/dist/core/agent/requestAssembly.js +16 -4
- package/dist/core/agent/toolCapabilities.d.ts +2 -2
- package/dist/core/agent/toolCapabilities.js +5 -5
- package/dist/core/agent/toolOutputStore.js +1 -1
- package/dist/core/agent/toolResults.js +1 -1
- package/dist/core/agent/workState.d.ts +6 -3
- package/dist/core/agent/workState.js +62 -7
- package/dist/core/attachments/imageAttachments.js +90 -42
- package/dist/core/deadline.d.ts +0 -6
- package/dist/core/deadline.js +1 -1
- package/dist/core/io/boundedRead.js +1 -1
- package/dist/core/limits.d.ts +51 -0
- package/dist/core/limits.js +51 -0
- package/dist/core/log/llmLog.js +1 -1
- package/dist/core/process/backgroundRegistry.d.ts +2 -3
- package/dist/core/process/backgroundRegistry.js +10 -6
- package/dist/core/process/userShell.d.ts +16 -0
- package/dist/core/process/userShell.js +59 -0
- package/dist/core/safety/secretPaths.d.ts +18 -0
- package/dist/core/safety/secretPaths.js +115 -0
- package/dist/core/safety/shellClassifier.d.ts +11 -0
- package/dist/core/safety/{bashClassifier.js → shellClassifier.js} +5 -3
- package/dist/core/safety/urlGuard.d.ts +1 -1
- package/dist/core/session/sessionSlimming.d.ts +0 -3
- package/dist/core/session/sessionSlimming.js +2 -3
- package/dist/core/session/sessionStore.d.ts +1 -0
- package/dist/core/session/sessionStore.js +39 -20
- package/dist/core/{bashOutput → shellOutput}/lineFilter.js +8 -2
- package/dist/core/{bashOutput → shellOutput}/reducers/search.d.ts +0 -1
- package/dist/core/{bashOutput → shellOutput}/reducers/search.js +1 -1
- package/dist/core/shellOutput/registry.d.ts +2 -0
- package/dist/core/{bashOutput → shellOutput}/registry.js +3 -3
- package/dist/core/{bashOutput → shellOutput}/types.d.ts +6 -5
- package/dist/core/subagent/contracts.d.ts +2 -14
- package/dist/core/subagent/contracts.js +3 -3
- package/dist/core/subagent/executionProfiles.js +2 -2
- package/dist/core/subagent/subagentRunner.js +3 -4
- package/dist/core/toolOutput/reduction.d.ts +0 -12
- package/dist/core/toolOutput/reduction.js +1 -1
- package/dist/core/validation/outputParser.d.ts +2 -2
- package/dist/llm/client.js +5 -1
- package/dist/llm/hazeTools.d.ts +139 -124
- package/dist/llm/hazeTools.js +20 -11
- package/dist/llm/initPrompt.js +1 -1
- package/dist/llm/lsp/client.d.ts +45 -0
- package/dist/llm/lsp/client.js +195 -0
- package/dist/llm/lsp/pool.d.ts +23 -0
- package/dist/llm/lsp/pool.js +86 -0
- package/dist/llm/lsp/protocol.d.ts +64 -0
- package/dist/llm/lsp/protocol.js +128 -0
- package/dist/llm/lsp/requests.d.ts +94 -0
- package/dist/llm/lsp/requests.js +119 -0
- package/dist/llm/lspTools.d.ts +3824 -570
- package/dist/llm/lspTools.js +65 -1
- package/dist/llm/openaiCodex.d.ts +0 -2
- package/dist/llm/openaiCodex.js +0 -4
- package/dist/llm/openaiCodexOAuth.d.ts +0 -3
- package/dist/llm/openaiCodexOAuth.js +6 -3
- package/dist/llm/requestContext.d.ts +5 -1
- package/dist/llm/requestContext.js +25 -2
- package/dist/llm/systemPrompt.d.ts +1 -0
- package/dist/llm/systemPrompt.js +16 -7
- package/dist/llm/toolResultTypes.d.ts +1 -15
- package/dist/llm/toolResultTypes.js +1 -4
- package/dist/llm/tools/editMatch.d.ts +0 -9
- package/dist/llm/tools/editMatch.js +1 -1
- package/dist/llm/tools/failures.d.ts +6 -0
- package/dist/llm/tools/failures.js +8 -2
- package/dist/llm/tools/fetchTool.js +1 -1
- package/dist/llm/tools/fileToolShared.d.ts +4 -2
- package/dist/llm/tools/fileToolShared.js +9 -5
- package/dist/llm/tools/gitIgnore.d.ts +25 -32
- package/dist/llm/tools/gitIgnore.js +216 -98
- package/dist/llm/tools/grepParse.d.ts +2 -1
- package/dist/llm/tools/grepRunner.d.ts +1 -1
- package/dist/llm/tools/grepRunner.js +2 -2
- package/dist/llm/tools/outputCap.d.ts +2 -7
- package/dist/llm/tools/outputCap.js +3 -3
- package/dist/llm/tools/processTool.d.ts +16 -16
- package/dist/llm/tools/processTool.js +1 -1
- package/dist/llm/tools/readRecovery.d.ts +0 -2
- package/dist/llm/tools/readRecovery.js +4 -2
- package/dist/llm/tools/{bashTool.d.ts → shellTool.d.ts} +123 -107
- package/dist/llm/tools/{bashTool.js → shellTool.js} +18 -14
- package/dist/llm/tools/toolContext.js +5 -5
- package/dist/llm/tools/workspaceFile.d.ts +4 -4
- package/dist/llm/tools/workspaceFile.js +29 -17
- package/dist/llm/webFetch.d.ts +1 -1
- package/dist/skills/SkillLoader.d.ts +1 -11
- package/dist/skills/SkillLoader.js +1 -2
- package/dist/skills/types.d.ts +2 -1
- package/dist/ui/components/Header.js +1 -1
- package/dist/ui/components/MarkdownText.js +10 -10
- package/dist/ui/components/TextInput.d.ts +1 -1
- package/dist/ui/components/TextInput.js +2 -2
- package/dist/ui/terminalColors.d.ts +29 -0
- package/dist/ui/terminalColors.js +47 -0
- package/dist/ui/theme.d.ts +105 -10
- package/dist/ui/theme.js +126 -15
- package/dist/ui/themes/af-magic.d.ts +7 -0
- package/dist/ui/themes/af-magic.js +25 -0
- package/dist/ui/themes/agnoster.d.ts +10 -0
- package/dist/ui/themes/agnoster.js +40 -0
- package/dist/ui/themes/bira.d.ts +10 -0
- package/dist/ui/themes/bira.js +28 -0
- package/dist/ui/themes/bureau.d.ts +10 -0
- package/dist/ui/themes/bureau.js +28 -0
- package/dist/ui/themes/clean.d.ts +9 -0
- package/dist/ui/themes/clean.js +27 -0
- package/dist/ui/themes/cloud.d.ts +6 -0
- package/dist/ui/themes/cloud.js +24 -0
- package/dist/ui/themes/dst.d.ts +10 -0
- package/dist/ui/themes/dst.js +28 -0
- package/dist/ui/themes/fishy.d.ts +7 -0
- package/dist/ui/themes/fishy.js +25 -0
- package/dist/ui/themes/index.d.ts +8 -0
- package/dist/ui/themes/index.js +36 -0
- package/dist/ui/themes/light.d.ts +3 -0
- package/dist/ui/themes/light.js +21 -0
- package/dist/ui/themes/purple.d.ts +7 -0
- package/dist/ui/themes/purple.js +26 -0
- package/dist/ui/themes/robbyrussell.d.ts +8 -0
- package/dist/ui/themes/robbyrussell.js +26 -0
- package/dist/ui/themes/solarized-dark.d.ts +16 -0
- package/dist/ui/themes/solarized-dark.js +44 -0
- package/dist/ui/themes/solarized-light.d.ts +12 -0
- package/dist/ui/themes/solarized-light.js +40 -0
- package/dist/ui/themes/steeef.d.ts +11 -0
- package/dist/ui/themes/steeef.js +29 -0
- package/dist/utils/buildInfo.d.ts +6 -13
- package/dist/utils/buildInfo.js +6 -15
- package/dist/utils/fs.d.ts +7 -5
- package/dist/utils/fs.js +5 -2
- package/dist/utils/path.d.ts +0 -1
- package/dist/utils/path.js +1 -1
- package/package.json +6 -4
- package/dist/cli/commands/lspWizard.d.ts +0 -14
- package/dist/cli/commands/lspWizard.js +0 -44
- package/dist/cli/commands/mcpWizard.d.ts +0 -15
- package/dist/cli/commands/skillConfirmRemove.d.ts +0 -11
- package/dist/cli/commands/skillConfirmRemove.js +0 -20
- package/dist/cli/commands/skillCreation.d.ts +0 -12
- package/dist/cli/commands/skillCreation.js +0 -14
- package/dist/cli/commands/skillWizard.d.ts +0 -17
- package/dist/cli/commands/streaming/idleTimer.d.ts +0 -26
- package/dist/cli/commands/streaming/idleTimer.js +0 -24
- package/dist/cli/commands/streaming/turnOutcome.d.ts +0 -27
- package/dist/cli/commands/streaming/turnOutcome.js +0 -29
- package/dist/cli/commands/wizardActions.d.ts +0 -47
- package/dist/cli/commands/wizardActions.js +0 -47
- package/dist/cli/commands/wizardInput.d.ts +0 -4
- package/dist/cli/commands/wizardInput.js +0 -19
- package/dist/cli/commands/wizardPrompts.d.ts +0 -22
- package/dist/cli/commands/wizardPrompts.js +0 -58
- package/dist/cli/commands/wizardSuggestions.d.ts +0 -31
- package/dist/cli/commands/wizardSuggestions.js +0 -190
- package/dist/cli/commands/wizardTransition.d.ts +0 -37
- package/dist/cli/commands/wizardTransition.js +0 -43
- package/dist/core/agent/toolExecutionBudget.d.ts +0 -35
- package/dist/core/agent/toolExecutionBudget.js +0 -49
- package/dist/core/agent/turnBudget.d.ts +0 -35
- package/dist/core/agent/turnBudget.js +0 -27
- package/dist/core/bashOutput/ansi.d.ts +0 -1
- package/dist/core/bashOutput/ansi.js +0 -7
- package/dist/core/bashOutput/registry.d.ts +0 -4
- package/dist/core/goal/completionPolicy.js +0 -43
- package/dist/core/goal/requestClassifier.d.ts +0 -3
- package/dist/core/goal/requestClassifier.js +0 -18
- package/dist/core/goal/sessionGoal.d.ts +0 -8
- package/dist/core/goal/sessionGoal.js +0 -30
- package/dist/core/limits/byteBudgets.d.ts +0 -20
- package/dist/core/limits/byteBudgets.js +0 -20
- package/dist/core/limits/textBudgets.d.ts +0 -25
- package/dist/core/limits/textBudgets.js +0 -25
- package/dist/core/safety/bashClassifier.d.ts +0 -10
- package/dist/llm/lsp.d.ts +0 -149
- package/dist/llm/lsp.js +0 -368
- package/dist/ui/components/ErrorView.d.ts +0 -4
- package/dist/ui/components/ErrorView.js +0 -7
- package/dist/utils/yaml.d.ts +0 -2
- package/dist/utils/yaml.js +0 -8
- package/examples/skills/files/SKILL.md +0 -16
- package/examples/skills/files/examples/file-editing.md +0 -3
- /package/dist/core/{bashOutput → shellOutput}/command.d.ts +0 -0
- /package/dist/core/{bashOutput → shellOutput}/command.js +0 -0
- /package/dist/core/{bashOutput → shellOutput}/lineFilter.d.ts +0 -0
- /package/dist/core/{bashOutput → shellOutput}/reducers/content.d.ts +0 -0
- /package/dist/core/{bashOutput → shellOutput}/reducers/content.js +0 -0
- /package/dist/core/{bashOutput → shellOutput}/reducers/gh.d.ts +0 -0
- /package/dist/core/{bashOutput → shellOutput}/reducers/gh.js +0 -0
- /package/dist/core/{bashOutput → shellOutput}/reducers/git.d.ts +0 -0
- /package/dist/core/{bashOutput → shellOutput}/reducers/git.js +0 -0
- /package/dist/core/{bashOutput → shellOutput}/reducers/validation.d.ts +0 -0
- /package/dist/core/{bashOutput → shellOutput}/reducers/validation.js +0 -0
- /package/dist/core/{bashOutput → shellOutput}/types.js +0 -0
|
@@ -1,763 +1,23 @@
|
|
|
1
|
-
import { ToolLoopAgent, isStepCount } from 'ai';
|
|
2
|
-
import { appendLogEntry as logAppend } from '../../core/log/llmLog.js';
|
|
3
|
-
import { modelWithConfig, providerRequestSettings } from '../../llm/client.js';
|
|
4
|
-
import { assembleRequestContext } from '../../llm/requestContext.js';
|
|
5
|
-
import { projectContextSection } from '../../llm/systemPrompt.js';
|
|
6
|
-
import { closeMcpClients } from '../../llm/mcp.js';
|
|
7
|
-
import { readSettings } from '../../config/settings.js';
|
|
8
|
-
import { toolCallSummary, toolResultSummary, busyToolLabel, formatSeconds } from './formatters.js';
|
|
9
1
|
import { agentEvent } from '../../core/agent/events.js';
|
|
10
|
-
import {
|
|
11
|
-
import {
|
|
12
|
-
import {
|
|
13
|
-
import {
|
|
14
|
-
import {
|
|
15
|
-
import { compactToolHistory, stripSyntheticControls, withSyntheticControl, withoutSystemMessages } from '../../core/agent/requestAssembly.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
|
-
import { compactModelMessages } from '../../core/agent/compaction.js';
|
|
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';
|
|
27
|
-
import { createSessionGoal, formatGoalStatus, observeGoalToolEvent } from '../../core/goal/sessionGoal.js';
|
|
28
|
-
import { buildIncompleteGoalResume } from './streaming/goalCheckpoint.js';
|
|
29
|
-
import { sanitizeAssistantText, assistantDisplayText, normalizeAssistantText, shouldStartAssistantStream, isHiddenAssistantFragment, isHiddenUnstartedFinalText, isShortLeadInBeforeTool, isShortUnfinishedLeadIn } from './streaming/assistantText.js';
|
|
30
|
-
import { createToolGroupRenderer, toolDiffFromResult } from './streaming/toolGroupRenderer.js';
|
|
31
|
-
import { applyStepToolResultState, initialToolResultState } from './streaming/toolResultState.js';
|
|
32
|
-
import { abortableDelay, estimateInputBreakdown, extractUsage, rememberContextFilesFromToolOutput, responseCompletionMetrics, retryDelayMs, stepCacheMetrics, subagentTokenEstimate } from './streaming/turnRuntime.js';
|
|
33
|
-
import { toolsContextFor } from '../../llm/tools/toolContext.js';
|
|
2
|
+
import { createTurnExecutionState, recordGoalContinuation, toCompletionEvidence } from '../../core/agent/completionController.js';
|
|
3
|
+
import { createSessionGoal } from '../../core/agent/goalPolicy.js';
|
|
4
|
+
import { seedCarriedGoalEvidence } from '../../core/agent/workState.js';
|
|
5
|
+
import { createToolExecutionBudget, mainTurnBudget, DEFAULT_TURN_DEADLINE_MS } from '../../core/agent/budgets.js';
|
|
6
|
+
import { createAbsoluteDeadline } from '../../core/deadline.js';
|
|
34
7
|
import { modelThinkingLabel } from '../../utils/modelName.js';
|
|
35
|
-
import {
|
|
36
|
-
import { createIdleTimer } from './streaming/idleTimer.js';
|
|
8
|
+
import { abortableDelay } from './streaming/turnRuntime.js';
|
|
37
9
|
import { abortForTurn, createUserAbortCause } from './streaming/abortCause.js';
|
|
38
|
-
import {
|
|
39
|
-
import {
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
void logAppend(log, entry).catch(() => undefined);
|
|
43
|
-
}
|
|
44
|
-
function withScopedContextControl(messages, context) {
|
|
45
|
-
const files = context.pendingContextFiles ?? [];
|
|
46
|
-
if (files.length === 0)
|
|
47
|
-
return messages;
|
|
48
|
-
context.pendingContextFiles = [];
|
|
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)}`);
|
|
50
|
-
}
|
|
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) {
|
|
79
|
-
let thinkingLabel = modelThinkingLabel(undefined);
|
|
80
|
-
callbacks.setBusyLabel?.(thinkingLabel);
|
|
81
|
-
let turnStatus = 'failed';
|
|
82
|
-
let recovery;
|
|
83
|
-
let loadedMcp;
|
|
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
|
-
});
|
|
134
|
-
const toolDisplay = createToolGroupRenderer({ addMessage: callbacks.addMessage, updateMessage: callbacks.updateMessage, debugLog: callbacks.debugLog, onEvent: callbacks.onEvent, log: callbacks.log });
|
|
135
|
-
try {
|
|
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);
|
|
140
|
-
if (!runtime?.model) {
|
|
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.' });
|
|
142
|
-
turnStatus = 'failed';
|
|
143
|
-
return { status: turnStatus };
|
|
144
|
-
}
|
|
145
|
-
thinkingLabel = modelThinkingLabel(runtime.config.modelName);
|
|
146
|
-
activeProviderName = runtime.config.providerName;
|
|
147
|
-
activeModelName = runtime.config.modelName;
|
|
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
|
-
}
|
|
166
|
-
let activeContextFiles = contextFiles;
|
|
167
|
-
const activeModel = runtime.model;
|
|
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;
|
|
177
|
-
const availableTools = assembled.availableTools;
|
|
178
|
-
const toolCategories = assembled.toolCategories;
|
|
179
|
-
loadedMcp = assembled.loadedMcp;
|
|
180
|
-
lspPool = assembled.lspPool;
|
|
181
|
-
if (loadedMcp?.errors.length)
|
|
182
|
-
callbacks.addMessage({ role: 'system', text: `MCP: ${loadedMcp.errors.join('; ')}` });
|
|
183
|
-
callbacks.setWorkState?.(goal);
|
|
184
|
-
callbacks.setGoalStatus?.(formatGoalStatus(goal));
|
|
185
|
-
const likelyPlanOnlyRequest = isPlanOnlyRequest(value);
|
|
186
|
-
const durableRequestMessages = compactToolHistory(retryingExistingRequest
|
|
187
|
-
? stripSyntheticControls(callbacks.getConversation())
|
|
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;
|
|
201
|
-
}
|
|
202
|
-
requestMessages = withoutSystemMessages(requestMessages);
|
|
203
|
-
callbacks.setConversation(stripSyntheticControls(requestMessages));
|
|
204
|
-
if (turnOptions.ephemeralControl)
|
|
205
|
-
requestMessages = withSyntheticControl(requestMessages, turnOptions.ephemeralControl);
|
|
206
|
-
const systemPrompt = assembled.systemPrompt;
|
|
207
|
-
const inputBreakdown = estimateInputBreakdown({ system: systemPrompt, contextFiles: activeContextFiles, messages: requestMessages, tools: availableTools });
|
|
208
|
-
logEntry(callbacks.log, { at: new Date().toISOString(), type: 'request', stream: 'main', system: systemPrompt, messages: requestMessages, tools: Object.keys(availableTools), context: inputBreakdown.breakdown });
|
|
209
|
-
const previousAssistantText = normalizeAssistantText(callbacks.getLastAssistantText());
|
|
210
|
-
const visibleAssistantTexts = new Set(previousAssistantText ? [previousAssistantText] : []);
|
|
211
|
-
const rememberVisibleAssistantText = (text) => {
|
|
212
|
-
const normalized = normalizeAssistantText(text);
|
|
213
|
-
if (!normalized)
|
|
214
|
-
return;
|
|
215
|
-
visibleAssistantTexts.add(normalized);
|
|
216
|
-
callbacks.setLastAssistantText(text);
|
|
217
|
-
};
|
|
218
|
-
const contextFileSignatures = callbacks.contextFileSignatures ?? new Map(activeContextFiles.flatMap(file => file.signature ? [[file.path, file.signature]] : []));
|
|
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 };
|
|
221
|
-
const startedTools = new Map();
|
|
222
|
-
const latestToolCalls = new Map();
|
|
223
|
-
let currentAssistantId = `assistant-${Date.now()}`;
|
|
224
|
-
let assistantStartedAt = Date.now();
|
|
225
|
-
let assistantText = '';
|
|
226
|
-
let streamError;
|
|
227
|
-
let streamFinished = false;
|
|
228
|
-
let finishReason;
|
|
229
|
-
let lastToolOk;
|
|
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();
|
|
235
|
-
let toolResultState = initialToolResultState();
|
|
236
|
-
const resetAssistantSegment = () => {
|
|
237
|
-
currentAssistantId = `assistant-${Date.now()}-${Math.random().toString(36).slice(2)}`;
|
|
238
|
-
assistantStarted = false;
|
|
239
|
-
assistantStartedAt = Date.now();
|
|
240
|
-
currentAssistantText = '';
|
|
241
|
-
};
|
|
242
|
-
const finalizeAssistantSegment = (options = {}) => {
|
|
243
|
-
const finalText = assistantDisplayText(currentAssistantText);
|
|
244
|
-
const normalized = normalizeAssistantText(finalText);
|
|
245
|
-
const hidden = (assistantStarted ? isHiddenAssistantFragment(finalText) : isHiddenUnstartedFinalText(finalText))
|
|
246
|
-
|| (options.beforeTool === true && isShortLeadInBeforeTool(finalText))
|
|
247
|
-
|| (options.beforeTool !== true && isShortUnfinishedLeadIn(finalText))
|
|
248
|
-
|| (normalized.length > 0 && visibleAssistantTexts.has(normalized));
|
|
249
|
-
if (assistantStarted) {
|
|
250
|
-
if (!hidden)
|
|
251
|
-
rememberVisibleAssistantText(finalText);
|
|
252
|
-
callbacks.onEvent?.(agentEvent({ type: 'message_end', id: currentAssistantId, text: finalText, hidden }));
|
|
253
|
-
callbacks.updateMessage(currentAssistantId, { text: finalText, streaming: false, hidden, ...responseCompletionMetrics(finalText, assistantStartedAt) });
|
|
254
|
-
}
|
|
255
|
-
else if (!hidden) {
|
|
256
|
-
if (!hidden)
|
|
257
|
-
rememberVisibleAssistantText(finalText);
|
|
258
|
-
callbacks.onEvent?.(agentEvent({ type: 'message_start', id: currentAssistantId, role: 'assistant' }));
|
|
259
|
-
callbacks.onEvent?.(agentEvent({ type: 'message_end', id: currentAssistantId, text: finalText, hidden: false }));
|
|
260
|
-
callbacks.addMessage({ id: currentAssistantId, role: 'assistant', text: finalText, streaming: false, startedAt: assistantStartedAt, ...responseCompletionMetrics(finalText, assistantStartedAt) });
|
|
261
|
-
}
|
|
262
|
-
resetAssistantSegment();
|
|
263
|
-
return !hidden;
|
|
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
|
-
}));
|
|
293
|
-
const agent = new ToolLoopAgent({
|
|
294
|
-
id: 'haze-main',
|
|
295
|
-
model: activeModel,
|
|
296
|
-
instructions: systemPrompt,
|
|
297
|
-
tools: deadlineWrappedTools,
|
|
298
|
-
...(!omitMaxOutputTokens ? { maxOutputTokens: DEFAULT_MAX_OUTPUT_TOKENS } : {}),
|
|
299
|
-
...providerSettings,
|
|
300
|
-
stopWhen: isStepCount(stepCap),
|
|
301
|
-
runtimeContext: toolExecutionContext,
|
|
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
|
-
},
|
|
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
|
-
}
|
|
319
|
-
const toolCalls = steps.flatMap(step => step.toolCalls);
|
|
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;
|
|
338
|
-
if (likelyPlanOnlyRequest && toolResultState.mutatingToolSucceeded)
|
|
339
|
-
return messagesChanged ? { toolChoice: 'none', messages: scopedMessages } : { toolChoice: 'none' };
|
|
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
|
-
}
|
|
357
|
-
if (repeatedToolNames.length > 0) {
|
|
358
|
-
const activeTools = Object.keys(sliceTools).filter(name => !repeatedToolNames.includes(name));
|
|
359
|
-
callbacks.debugLog(`disabling repeated tools for next step: ${repeatedToolNames.join(', ')}`);
|
|
360
|
-
return activeTools.length > 0
|
|
361
|
-
? { activeTools, messages: withSyntheticControl(scopedMessages, repeatedToolCallPrompt(repeatedToolNames)) }
|
|
362
|
-
: { toolChoice: 'none', messages: withSyntheticControl(scopedMessages, repeatedToolCallPrompt(repeatedToolNames)) };
|
|
363
|
-
}
|
|
364
|
-
if (turnToolCallsExhausted || sliceToolCallsExhausted || toolOnlyBoundaryHit || toolCalls.length >= MAIN_TOOL_CALL_LIMIT) {
|
|
365
|
-
callbacks.debugLog('forcing text response to avoid tool loop');
|
|
366
|
-
return { toolChoice: 'none', messages: withSyntheticControl(scopedMessages, toolLoopBudgetPrompt()) };
|
|
367
|
-
}
|
|
368
|
-
return messagesChanged ? { messages: scopedMessages } : undefined;
|
|
369
|
-
},
|
|
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;
|
|
385
|
-
if (toolCalls.length > 0 && text.trim().length === 0)
|
|
386
|
-
turnState.toolOnlyStepsUsed += 1;
|
|
387
|
-
if (Array.isArray(response?.messages) && response.messages.length > 0)
|
|
388
|
-
latestAccumulatedResponseMessages = response.messages;
|
|
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 }));
|
|
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 } });
|
|
399
|
-
callbacks.debugLog(`step ${stepNumber} finished: ${finishReason}; text=${text.length}; toolCalls=${toolCalls.length}; toolResults=${toolResults.length}`);
|
|
400
|
-
},
|
|
401
|
-
onEnd(event) {
|
|
402
|
-
const providerUsage = extractUsage({ usage: event.usage });
|
|
403
|
-
callbacks.recordTokenUsage?.({
|
|
404
|
-
inputTokens: providerUsage.inputTokens,
|
|
405
|
-
outputTokens: providerUsage.outputTokens,
|
|
406
|
-
systemPrompt: inputBreakdown.systemPrompt,
|
|
407
|
-
messages: inputBreakdown.messages,
|
|
408
|
-
toolSchemas: inputBreakdown.toolSchemas,
|
|
409
|
-
outputEstimate: estimateValueTokens(event.responseMessages),
|
|
410
|
-
cacheReadTokens: providerUsage.cacheReadTokens,
|
|
411
|
-
cacheWriteTokens: providerUsage.cacheWriteTokens,
|
|
412
|
-
noCacheTokens: providerUsage.noCacheTokens,
|
|
413
|
-
reasoningTokens: providerUsage.reasoningTokens,
|
|
414
|
-
logicalInputEstimate: inputBreakdown.logicalInputEstimate,
|
|
415
|
-
effectiveNonCachedInput: providerUsage.effectiveNonCachedInput,
|
|
416
|
-
});
|
|
417
|
-
const accumulated = [...stripSyntheticControls(requestMessages), ...event.responseMessages];
|
|
418
|
-
const compacted = compactToolHistory(accumulated);
|
|
419
|
-
callbacks.setConversation(compacted.messages);
|
|
420
|
-
callbacks.debugLog(`conversation updated to ${compacted.messages.length} messages by ToolLoopAgent`);
|
|
421
|
-
},
|
|
422
|
-
});
|
|
423
|
-
idleTimer.reset();
|
|
424
|
-
const result = await agent.stream({ messages: requestMessages, abortSignal: abortController.signal });
|
|
425
|
-
for await (const part of result.stream) {
|
|
426
|
-
idleTimer.reset();
|
|
427
|
-
lastStreamEventAt = Date.now();
|
|
428
|
-
lastStreamEventType = part.type;
|
|
429
|
-
switch (part.type) {
|
|
430
|
-
case 'text-delta': {
|
|
431
|
-
callbacks.setBusyLabel?.(thinkingLabel);
|
|
432
|
-
toolDisplay.startFreshToolGroup();
|
|
433
|
-
const delta = sanitizeAssistantText(part.text);
|
|
434
|
-
assistantText += delta;
|
|
435
|
-
currentAssistantText += delta;
|
|
436
|
-
const displayText = assistantDisplayText(currentAssistantText);
|
|
437
|
-
if (!assistantStarted && !shouldStartAssistantStream(displayText, assistantStartedAt))
|
|
438
|
-
break;
|
|
439
|
-
if (!assistantStarted) {
|
|
440
|
-
assistantStarted = true;
|
|
441
|
-
assistantStartedAt = Date.now();
|
|
442
|
-
callbacks.onEvent?.(agentEvent({ type: 'message_start', id: currentAssistantId, role: 'assistant' }));
|
|
443
|
-
callbacks.addMessage({ id: currentAssistantId, role: 'assistant', text: displayText, streaming: true, startedAt: assistantStartedAt });
|
|
444
|
-
}
|
|
445
|
-
else {
|
|
446
|
-
callbacks.onEvent?.(agentEvent({ type: 'message_update', id: currentAssistantId, text: displayText }));
|
|
447
|
-
callbacks.updateMessage(currentAssistantId, { text: displayText });
|
|
448
|
-
}
|
|
449
|
-
break;
|
|
450
|
-
}
|
|
451
|
-
case 'tool-input-start': {
|
|
452
|
-
if (currentAssistantText.trim().length > 0 || assistantStarted) {
|
|
453
|
-
const pending = assistantDisplayText(currentAssistantText);
|
|
454
|
-
const shown = finalizeAssistantSegment({ beforeTool: true });
|
|
455
|
-
if (!shown && pending)
|
|
456
|
-
toolDisplay.setGroupCaption(pending);
|
|
457
|
-
}
|
|
458
|
-
const toolCall = { toolCallId: part.id, toolName: part.toolName, input: {} };
|
|
459
|
-
latestToolCalls.set(part.id, toolCall);
|
|
460
|
-
inFlightTools.add(part.id);
|
|
461
|
-
callbacks.setBusyLabel?.(busyToolLabel(part.toolName, {}));
|
|
462
|
-
toolDisplay.ensureToolItem(toolCall);
|
|
463
|
-
break;
|
|
464
|
-
}
|
|
465
|
-
case 'tool-call': {
|
|
466
|
-
if (currentAssistantText.trim().length > 0 || assistantStarted) {
|
|
467
|
-
const pending = assistantDisplayText(currentAssistantText);
|
|
468
|
-
const shown = finalizeAssistantSegment({ beforeTool: true });
|
|
469
|
-
if (!shown && pending)
|
|
470
|
-
toolDisplay.setGroupCaption(pending);
|
|
471
|
-
}
|
|
472
|
-
const toolCall = { toolCallId: part.toolCallId, toolName: part.toolName, input: part.input };
|
|
473
|
-
latestToolCalls.set(part.toolCallId, toolCall);
|
|
474
|
-
// Tool execution begins only after its complete input has parsed and validated.
|
|
475
|
-
startedTools.set(part.toolCallId, Date.now());
|
|
476
|
-
callbacks.setBusyLabel?.(busyToolLabel(part.toolName, part.input));
|
|
477
|
-
toolDisplay.ensureToolItem(toolCall).summary = toolCallSummary(part.toolName, part.input);
|
|
478
|
-
toolDisplay.updateToolGroup(true);
|
|
479
|
-
break;
|
|
480
|
-
}
|
|
481
|
-
case 'tool-result': {
|
|
482
|
-
const toolCall = { toolCallId: part.toolCallId, toolName: part.toolName, input: part.input };
|
|
483
|
-
latestToolCalls.set(part.toolCallId, toolCall);
|
|
484
|
-
inFlightTools.delete(part.toolCallId);
|
|
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
|
-
}
|
|
512
|
-
const ok = toolOutputOk(part.output, true);
|
|
513
|
-
lastToolOk = ok;
|
|
514
|
-
if (ok && part.toolName === unresolvedMalformedToolName)
|
|
515
|
-
unresolvedMalformedToolName = undefined;
|
|
516
|
-
const finish = { toolCall, success: ok, output: part.output, durationMs: Date.now() - startedAt };
|
|
517
|
-
const item = toolDisplay.ensureToolItem(toolCall);
|
|
518
|
-
item.status = ok ? 'success' : 'error';
|
|
519
|
-
item.result = toolResultSummary(finish);
|
|
520
|
-
item.diff = toolDiffFromResult(toolCall, part.output);
|
|
521
|
-
item.durationMs = finish.durationMs;
|
|
522
|
-
item.finishedAt = startedAt + finish.durationMs;
|
|
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 }));
|
|
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 } });
|
|
526
|
-
observeGoalToolEvent(goal, { ...toolCall, success: ok, output: part.output, duplicateSkipped: isDuplicateSkippedOutput(part.output) });
|
|
527
|
-
callbacks.setWorkState?.(goal);
|
|
528
|
-
callbacks.setGoalStatus?.(formatGoalStatus(goal));
|
|
529
|
-
activeContextFiles = rememberContextFilesFromToolOutput(activeContextFiles, part.output);
|
|
530
|
-
if (toolCall.toolName === 'writeTasks')
|
|
531
|
-
callbacks.onTasksChanged?.();
|
|
532
|
-
const nestedTokens = subagentTokenEstimate(part.output);
|
|
533
|
-
if (nestedTokens)
|
|
534
|
-
callbacks.recordTokenUsage?.({ inputTokens: nestedTokens.input, outputTokens: nestedTokens.output, systemPrompt: 0, messages: 0, toolSchemas: 0, outputEstimate: 0, cacheReadTokens: 0, cacheWriteTokens: 0, noCacheTokens: nestedTokens.input, reasoningTokens: 0, logicalInputEstimate: nestedTokens.input, effectiveNonCachedInput: nestedTokens.input });
|
|
535
|
-
toolDisplay.updateToolGroup(true);
|
|
536
|
-
break;
|
|
537
|
-
}
|
|
538
|
-
case 'tool-error': {
|
|
539
|
-
inFlightTools.delete(part.toolCallId);
|
|
540
|
-
const existing = latestToolCalls.get(part.toolCallId);
|
|
541
|
-
const toolCall = { toolCallId: part.toolCallId, toolName: part.toolName, input: part.input ?? existing?.input };
|
|
542
|
-
const startedAt = startedTools.get(part.toolCallId) ?? Date.now();
|
|
543
|
-
lastToolOk = false;
|
|
544
|
-
if (isMalformedToolInputError(part.error)) {
|
|
545
|
-
pendingMalformedToolName = part.toolName;
|
|
546
|
-
unresolvedMalformedToolName = part.toolName;
|
|
547
|
-
}
|
|
548
|
-
const finish = { toolCall, success: false, error: part.error, durationMs: Date.now() - startedAt };
|
|
549
|
-
const item = toolDisplay.ensureToolItem(toolCall);
|
|
550
|
-
item.status = 'error';
|
|
551
|
-
item.result = toolResultSummary(finish);
|
|
552
|
-
item.durationMs = finish.durationMs;
|
|
553
|
-
item.finishedAt = startedAt + finish.durationMs;
|
|
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 }));
|
|
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 } });
|
|
557
|
-
observeGoalToolEvent(goal, { ...toolCall, success: false, output: part.error });
|
|
558
|
-
callbacks.setWorkState?.(goal);
|
|
559
|
-
callbacks.setGoalStatus?.(formatGoalStatus(goal));
|
|
560
|
-
toolDisplay.updateToolGroup(true);
|
|
561
|
-
break;
|
|
562
|
-
}
|
|
563
|
-
case 'error':
|
|
564
|
-
streamError = part.error;
|
|
565
|
-
callbacks.debugLog(`stream error: ${part.error instanceof Error ? part.error.message : String(part.error)}`);
|
|
566
|
-
break;
|
|
567
|
-
case 'finish':
|
|
568
|
-
streamFinished = true;
|
|
569
|
-
finishReason = part.finishReason;
|
|
570
|
-
callbacks.debugLog(`ToolLoopAgent finished: ${part.finishReason}`);
|
|
571
|
-
break;
|
|
572
|
-
default:
|
|
573
|
-
break;
|
|
574
|
-
}
|
|
575
|
-
}
|
|
576
|
-
if (streamError && !streamFinished) {
|
|
577
|
-
void Promise.resolve(result.responseMessages).catch(() => undefined);
|
|
578
|
-
throw streamError;
|
|
579
|
-
}
|
|
580
|
-
try {
|
|
581
|
-
const responseMessages = await result.responseMessages;
|
|
582
|
-
const completedConversation = [...stripSyntheticControls(requestMessages), ...responseMessages];
|
|
583
|
-
callbacks.setConversation(compactToolHistory(completedConversation).messages);
|
|
584
|
-
}
|
|
585
|
-
catch (error) {
|
|
586
|
-
if (latestAccumulatedResponseMessages.length > 0) {
|
|
587
|
-
callbacks.setConversation(compactToolHistory([...stripSyntheticControls(requestMessages), ...latestAccumulatedResponseMessages]).messages);
|
|
588
|
-
}
|
|
589
|
-
const text = error instanceof Error ? error.message : String(error);
|
|
590
|
-
const benignTerminatedAfterStream = text === 'terminated' && (streamFinished || assistantText.trim().length > 0 || latestToolCalls.size > 0);
|
|
591
|
-
if (!benignTerminatedAfterStream)
|
|
592
|
-
throw streamError ?? error;
|
|
593
|
-
callbacks.debugLog(`ignored post-stream response error: ${text}`);
|
|
594
|
-
}
|
|
595
|
-
if (currentAssistantText.trim().length > 0 || assistantStarted) {
|
|
596
|
-
finalizeAssistantSegment();
|
|
597
|
-
}
|
|
598
|
-
else if (latestToolCalls.size > 0) {
|
|
599
|
-
callbacks.addMessage({ role: 'system', text: 'Tool work ended without a substantive final answer.' });
|
|
600
|
-
}
|
|
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.` });
|
|
616
|
-
goal.phase = 'done';
|
|
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';
|
|
626
|
-
callbacks.setWorkState?.(goal);
|
|
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
|
-
}
|
|
671
|
-
}
|
|
672
|
-
catch (error) {
|
|
673
|
-
if (abortController.signal.aborted) {
|
|
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
|
-
}
|
|
715
|
-
}
|
|
716
|
-
else {
|
|
717
|
-
const text = error instanceof Error ? error.message : String(error);
|
|
718
|
-
callbacks.debugLog(`error: ${text}`);
|
|
719
|
-
if (!contextOverflowRecovered && isContextOverflowError(error)) {
|
|
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;
|
|
724
|
-
callbacks.onEvent?.(agentEvent({ type: 'context_overflow', recovered: compacted, error: text }));
|
|
725
|
-
if (compacted) {
|
|
726
|
-
callbacks.addMessage({ role: 'system', text: 'Context overflow detected; compacted older context and retrying the same request once.' });
|
|
727
|
-
return { status: 'failed', retry: { attempt: retryAttempt, contextOverflowRecovered: true, delayMs: 0 } };
|
|
728
|
-
}
|
|
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.' });
|
|
732
|
-
}
|
|
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)) {
|
|
736
|
-
const delay = retryDelayMs(retryAttempt);
|
|
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}` });
|
|
739
|
-
return { status: 'failed', retry: { attempt: retryAttempt + 1, contextOverflowRecovered, delayMs: delay } };
|
|
740
|
-
}
|
|
741
|
-
callbacks.addMessage({ role: 'assistant', text: `Model call failed: ${text}` });
|
|
742
|
-
}
|
|
743
|
-
}
|
|
744
|
-
finally {
|
|
745
|
-
if (loadedMcp?.clients.length)
|
|
746
|
-
await closeMcpClients(loadedMcp.clients);
|
|
747
|
-
if (lspPool)
|
|
748
|
-
await lspPool.close();
|
|
749
|
-
idleTimer.clear();
|
|
750
|
-
toolDisplay.stopToolTimer();
|
|
751
|
-
toolDisplay.finalizeToolGroup();
|
|
752
|
-
}
|
|
753
|
-
return { status: turnStatus, recovery };
|
|
754
|
-
}
|
|
10
|
+
import { runAgentAttempt } from './streaming/agentAttempt.js';
|
|
11
|
+
import { projectGoalEvidence } from './streaming/attemptOutcome.js';
|
|
12
|
+
import { awaitAttemptWithForcedSettlement, createAttemptCleanupRegistry, createQuarantinableCallbacks } from './streaming/attemptLifecycle.js';
|
|
13
|
+
import { formatIdleMinutes } from './streaming/stallRecovery.js';
|
|
755
14
|
export async function runAgentTurn(value, displayValue, contextFiles, callbacks, retryAttempt = 0, retryingExistingRequest = false, contextOverflowRecovered = false, session, modelOverride, turnOptions = {}) {
|
|
756
15
|
// The controller is replaced when an idle-stall retry needs a live signal
|
|
757
16
|
// after aborting a hung stream, so both it and the cause are mutable.
|
|
758
17
|
let abortController = new AbortController();
|
|
759
18
|
let abortCause = createUserAbortCause();
|
|
760
19
|
let status = 'failed';
|
|
20
|
+
let abortReason;
|
|
761
21
|
let resume;
|
|
762
22
|
const turnState = createTurnExecutionState();
|
|
763
23
|
callbacks.onEvent?.(agentEvent({ type: 'turn_start', request: value }));
|
|
@@ -777,8 +37,12 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
|
|
|
777
37
|
const turnBudget = mainTurnBudget();
|
|
778
38
|
// Turn-wide execution budget (RH-003): one authoritative counter of
|
|
779
39
|
// underlying tool executions, shared across retries and recovery slices so
|
|
780
|
-
// the global limit cannot be reset or exceeded.
|
|
40
|
+
// the global limit cannot be reset or exceeded. The slice budget caps the
|
|
41
|
+
// current slice (main phase or one recovery slice): it is shared by every
|
|
42
|
+
// attempt in that slice and reset only when a new slice is admitted, so a
|
|
43
|
+
// provider retry inside a rescue can never re-arm the slice cap (C2).
|
|
781
44
|
const globalBudget = createToolExecutionBudget();
|
|
45
|
+
const sliceBudget = createToolExecutionBudget();
|
|
782
46
|
// Turn-wide work state: persists across provider retries and recovery
|
|
783
47
|
// slices so mutation/validation evidence accumulates correctly. When the
|
|
784
48
|
// goal supervisor continues a logical goal, cumulative evidence (tasks,
|
|
@@ -794,6 +58,10 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
|
|
|
794
58
|
let attempt = retryAttempt;
|
|
795
59
|
let overflowRecovered = contextOverflowRecovered;
|
|
796
60
|
let retrying = retryingExistingRequest;
|
|
61
|
+
// The attempt machinery runs against quarantinable callbacks so an
|
|
62
|
+
// abort-ignoring stream that outlives forced settlement cannot mutate the
|
|
63
|
+
// finished turn's UI, conversation, or session state.
|
|
64
|
+
const { callbacks: attemptCallbacks, quarantine } = createQuarantinableCallbacks(callbacks);
|
|
797
65
|
while (true) {
|
|
798
66
|
// Absolute main-turn deadline (RH-004): distinct from the idle timer, it
|
|
799
67
|
// bounds total turn elapsed time so a stream of busy tools cannot defer
|
|
@@ -810,10 +78,26 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
|
|
|
810
78
|
abortForTurn(abortCause, { kind: 'turn-deadline', timeoutMs: turnDeadlineMs }, abortController, `haze turn exceeded the ${turnDeadlineMs}ms absolute deadline.`);
|
|
811
79
|
},
|
|
812
80
|
});
|
|
813
|
-
const
|
|
81
|
+
const cleanup = createAttemptCleanupRegistry();
|
|
82
|
+
const result = await awaitAttemptWithForcedSettlement(runAgentAttempt({ value, contextFiles, callbacks: attemptCallbacks, retryAttempt: attempt, retryingExistingRequest: retrying, contextOverflowRecovered: overflowRecovered, session, modelOverride, abortController, turnOptions: activeOptions, turnScope, turnState, turnBudget, globalBudget, sliceBudget, goal, abortCause, cleanup, remainingTurnDeadlineMs: () => Math.max(0, turnDeadlineMs - (Date.now() - turnStartedAt)) }), {
|
|
83
|
+
abortController,
|
|
84
|
+
cleanup,
|
|
85
|
+
quarantine,
|
|
86
|
+
onForced: tornDown => {
|
|
87
|
+
// The attempt ignored cancellation past the grace window: settle the
|
|
88
|
+
// turn ourselves, truthfully reporting whether teardown completed.
|
|
89
|
+
turnState.aborted = true;
|
|
90
|
+
callbacks.debugLog(`attempt ignored cancellation; forced settlement after grace (teardown ${tornDown ? 'completed' : 'still settling'})`);
|
|
91
|
+
callbacks.addMessage({ role: 'system', text: abortCause.kind === 'turn-deadline'
|
|
92
|
+
? `Turn stopped: the ${formatIdleMinutes(abortCause.timeoutMs ?? turnDeadlineMs)} turn budget elapsed before the model finished.${tornDown ? '' : ' Some background teardown is still settling.'} Completed steps are preserved in the conversation; send a follow-up to continue.`
|
|
93
|
+
: 'Thinking aborted. You can type again.' });
|
|
94
|
+
return { status: 'aborted', abortReason: abortCause.kind === 'turn-deadline' ? 'turn-deadline' : 'user' };
|
|
95
|
+
},
|
|
96
|
+
});
|
|
814
97
|
turnDeadline.clear();
|
|
815
98
|
turnDeadline = undefined;
|
|
816
99
|
status = result.status;
|
|
100
|
+
abortReason = result.abortReason;
|
|
817
101
|
resume = result.resume;
|
|
818
102
|
if (result.retry) {
|
|
819
103
|
attempt = result.retry.attempt;
|
|
@@ -849,6 +133,10 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
|
|
|
849
133
|
turnState.rescueUsed = true;
|
|
850
134
|
else
|
|
851
135
|
recordGoalContinuation(turnState);
|
|
136
|
+
// A new slice gets a fresh execution allowance, clamped once here; the
|
|
137
|
+
// slice budget persists across provider retries within the slice (C2).
|
|
138
|
+
sliceBudget.started = 0;
|
|
139
|
+
sliceBudget.exceeded = false;
|
|
852
140
|
activeOptions = { ...activeOptions, ephemeralControl: rec.control, recoverySlice: { kind: rec.kind, maxSteps: rec.slice.maxSteps, maxToolCalls: rec.slice.maxToolCalls } };
|
|
853
141
|
retrying = true;
|
|
854
142
|
callbacks.debugLog(`starting ${rec.kind} recovery slice: ${rec.slice.maxSteps} steps / ${rec.slice.maxToolCalls} tool calls`);
|
|
@@ -856,8 +144,9 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
|
|
|
856
144
|
}
|
|
857
145
|
break;
|
|
858
146
|
}
|
|
147
|
+
projectGoalEvidence(turnState, goal);
|
|
859
148
|
const evidence = toCompletionEvidence(turnState);
|
|
860
|
-
return { status, evidence, ...(resume ? { resume } : {}) };
|
|
149
|
+
return { status, evidence, ...(abortReason ? { abortReason } : {}), ...(resume ? { resume } : {}) };
|
|
861
150
|
}
|
|
862
151
|
finally {
|
|
863
152
|
turnDeadline?.clear();
|