@denizokcu/haze 1.0.0 → 1.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +33 -0
- package/README.md +17 -8
- package/SECURITY.md +3 -1
- package/dist/buildInfo.json +3 -3
- package/dist/cli/chat/TaskBar.js +1 -1
- package/dist/cli/chat/busyIndicator.d.ts +11 -0
- package/dist/cli/chat/busyIndicator.js +34 -0
- package/dist/cli/chat/chatMetrics.d.ts +0 -1
- package/dist/cli/chat/chatMetrics.js +1 -7
- package/dist/cli/chat/followUpQueue.d.ts +11 -0
- package/dist/cli/chat/followUpQueue.js +38 -0
- package/dist/cli/chat/inputSuggestions.js +1 -0
- package/dist/cli/chat/messages.d.ts +0 -22
- package/dist/cli/chat/messages.js +42 -87
- package/dist/cli/chat/sessionLifecycle.d.ts +3 -1
- package/dist/cli/chat/sessionLifecycle.js +6 -1
- package/dist/cli/chat/sessionRecorder.d.ts +2 -0
- package/dist/cli/chat/sessionRecorder.js +6 -0
- package/dist/cli/chat/startupSequence.d.ts +29 -0
- package/dist/cli/chat/startupSequence.js +59 -0
- package/dist/cli/chat/transcriptPartition.d.ts +23 -0
- package/dist/cli/chat/transcriptPartition.js +78 -0
- package/dist/cli/chat/wizard/fieldTransitions.d.ts +38 -0
- package/dist/cli/chat/wizard/fieldTransitions.js +43 -0
- package/dist/cli/chat/wizard/lspHandlers.d.ts +4 -0
- package/dist/cli/chat/wizard/lspHandlers.js +85 -0
- package/dist/cli/chat/wizard/mcpHandlers.d.ts +8 -0
- package/dist/cli/chat/wizard/mcpHandlers.js +82 -0
- package/dist/cli/chat/wizard/providerHandlers.d.ts +12 -0
- package/dist/cli/chat/wizard/providerHandlers.js +420 -0
- package/dist/cli/chat/wizard/sessionThemeHandlers.d.ts +4 -0
- package/dist/cli/chat/wizard/sessionThemeHandlers.js +48 -0
- package/dist/cli/chat/wizard/skillsHandlers.d.ts +4 -0
- package/dist/cli/chat/wizard/skillsHandlers.js +125 -0
- package/dist/cli/chat/wizard/types.d.ts +63 -0
- package/dist/cli/chat/wizard/types.js +24 -0
- package/dist/cli/chat/wizard/uiState.d.ts +56 -0
- package/dist/cli/chat/wizard/uiState.js +15 -0
- package/dist/cli/chat/wizardDispatch.d.ts +11 -113
- package/dist/cli/chat/wizardDispatch.js +41 -805
- package/dist/cli/commands/chat.js +89 -110
- package/dist/cli/commands/commandHelp.js +2 -0
- package/dist/cli/commands/commands.js +2 -0
- package/dist/cli/commands/formatters.d.ts +0 -3
- package/dist/cli/commands/formatters.js +6 -29
- package/dist/cli/commands/runCommand.d.ts +2 -0
- package/dist/cli/commands/runCommand.js +67 -4
- package/dist/cli/commands/settingsSummary.js +2 -0
- package/dist/cli/commands/streaming/assistantSegments.d.ts +19 -0
- package/dist/cli/commands/streaming/assistantSegments.js +48 -0
- package/dist/cli/commands/streaming/attemptOutcome.d.ts +2 -2
- package/dist/cli/commands/streaming/attemptOutcome.js +17 -7
- package/dist/cli/commands/streaming/goalCheckpoint.d.ts +69 -8
- package/dist/cli/commands/streaming/goalCheckpoint.js +36 -1
- package/dist/cli/commands/streaming/goalSupervisor.d.ts +17 -2
- package/dist/cli/commands/streaming/goalSupervisor.js +62 -12
- package/dist/cli/commands/streaming/prepareStep.d.ts +35 -0
- package/dist/cli/commands/streaming/prepareStep.js +100 -0
- package/dist/cli/commands/streaming/recoverySlices.d.ts +15 -0
- package/dist/cli/commands/streaming/recoverySlices.js +29 -0
- package/dist/cli/commands/streaming/stallRecovery.d.ts +0 -1
- package/dist/cli/commands/streaming/stallRecovery.js +0 -4
- package/dist/cli/commands/streaming/streamLoop.js +9 -230
- package/dist/cli/commands/streaming/toolGroupRenderer.js +2 -1
- package/dist/cli/commands/streaming/toolPartHandlers.d.ts +19 -0
- package/dist/cli/commands/streaming/toolPartHandlers.js +95 -0
- package/dist/cli/commands/streaming.d.ts +4 -1
- package/dist/cli/commands/streaming.js +6 -21
- package/dist/cli/commands/themesCommand.d.ts +17 -0
- package/dist/cli/commands/themesCommand.js +24 -0
- package/dist/cli/commands/wizardFlow.d.ts +7 -0
- package/dist/cli/commands/wizardFlow.js +20 -0
- package/dist/cli/index.js +3 -1
- package/dist/config/providerPresets.d.ts +7 -0
- package/dist/config/providerPresets.js +195 -391
- package/dist/config/settings.d.ts +2 -0
- package/dist/config/settings.js +1 -0
- package/dist/core/agent/completionController.d.ts +14 -7
- package/dist/core/agent/completionController.js +12 -6
- package/dist/core/agent/events.d.ts +12 -0
- package/dist/core/agent/goalPolicy.d.ts +4 -3
- package/dist/core/agent/goalPolicy.js +9 -4
- package/dist/core/agent/workState.d.ts +25 -15
- package/dist/core/agent/workState.js +71 -43
- package/dist/core/safety/secretPaths.d.ts +18 -0
- package/dist/core/safety/secretPaths.js +115 -0
- package/dist/core/session/sessionSlimming.js +8 -0
- package/dist/core/session/sessionStore.d.ts +61 -1
- package/dist/core/session/sessionStore.js +115 -6
- package/dist/llm/hazeTools.d.ts +64 -208
- package/dist/llm/hazeTools.js +6 -0
- package/dist/llm/systemPrompt.js +3 -1
- package/dist/llm/toolResultTypes.d.ts +1 -1
- package/dist/llm/tools/failures.d.ts +6 -0
- package/dist/llm/tools/failures.js +8 -2
- package/dist/llm/tools/readRecovery.js +2 -0
- package/dist/llm/tools/shellTool.js +3 -0
- package/dist/llm/tools/taskTool.d.ts +64 -208
- package/dist/llm/tools/taskTool.js +22 -10
- package/dist/llm/tools/workspaceFile.d.ts +4 -3
- package/dist/llm/tools/workspaceFile.js +30 -13
- 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 +8 -69
- package/dist/ui/components/useInputSuggestions.d.ts +27 -0
- package/dist/ui/components/useInputSuggestions.js +98 -0
- 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 +125 -15
- package/dist/ui/themes/registry.d.ts +5 -0
- package/dist/ui/themes/registry.js +436 -0
- package/dist/utils/format.d.ts +10 -0
- package/dist/utils/format.js +45 -0
- package/package.json +1 -1
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
import { malformedToolCallPrompt, repeatedToolCallPrompt, toolLoopBudgetPrompt } from '../../../core/agent/goalPolicy.js';
|
|
2
|
+
import { estimateMessagesTokens } from '../../../core/agent/contextBudget.js';
|
|
3
|
+
import { compactModelMessages } from '../../../core/agent/compaction.js';
|
|
4
|
+
import { stripSyntheticControls, withSyntheticControl } from '../../../core/agent/requestAssembly.js';
|
|
5
|
+
import { latestRepeatedToolNames, toolOnlyStepCount } from '../../../core/agent/turnPolicy.js';
|
|
6
|
+
import { RESCUE_BOUNDARY } from '../../../core/agent/completionController.js';
|
|
7
|
+
import { MAIN_TOOL_CALL_LIMIT, WRITE_FILE_CHUNK_BYTES } from '../../../core/agent/budgets.js';
|
|
8
|
+
import { projectContextSection } from '../../../llm/systemPrompt.js';
|
|
9
|
+
import { clampOutOfBoundsToolNumbers, isMalformedToolInputError } from './toolCallRecovery.js';
|
|
10
|
+
export function withScopedContextControl(messages, context) {
|
|
11
|
+
const files = context.pendingContextFiles ?? [];
|
|
12
|
+
if (files.length === 0)
|
|
13
|
+
return messages;
|
|
14
|
+
context.pendingContextFiles = [];
|
|
15
|
+
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)}`);
|
|
16
|
+
}
|
|
17
|
+
export function createRepairToolCall(deps) {
|
|
18
|
+
const { callbacks, loopState } = deps;
|
|
19
|
+
return async ({ toolCall, error, inputSchema }) => {
|
|
20
|
+
if (isMalformedToolInputError(error)) {
|
|
21
|
+
const clamped = await clampOutOfBoundsToolNumbers(toolCall.input, toolCall.toolName, inputSchema);
|
|
22
|
+
if (clamped != null) {
|
|
23
|
+
callbacks.debugLog(`clamped out-of-range numeric input for ${toolCall.toolName}; executing repaired call`);
|
|
24
|
+
return { type: 'tool-call', toolCallId: toolCall.toolCallId, toolName: toolCall.toolName, input: JSON.stringify(clamped) };
|
|
25
|
+
}
|
|
26
|
+
loopState.pendingMalformedToolName = toolCall.toolName;
|
|
27
|
+
loopState.unresolvedMalformedToolName = toolCall.toolName;
|
|
28
|
+
}
|
|
29
|
+
// Truncated generated file content cannot be reconstructed safely here;
|
|
30
|
+
// let the next agent step retry under the bounded tool-choice constraint.
|
|
31
|
+
return null;
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
export function createPrepareStep(deps) {
|
|
35
|
+
const { setup, callbacks, loopState, turnState, turnBudget, goal, recoverySlice } = deps;
|
|
36
|
+
const { sliceTools, requestBudget, toolExecutionContext, likelyPlanOnlyRequest, rescueWithoutTools } = setup;
|
|
37
|
+
return ({ steps, messages }) => {
|
|
38
|
+
// A rescue slice with no qualifying tools must synthesize, never reopen
|
|
39
|
+
// discovery by falling back to the full tool set (F-08).
|
|
40
|
+
if (rescueWithoutTools) {
|
|
41
|
+
callbacks.debugLog('rescue slice has no mutation/validation tools; forcing tool-free synthesis');
|
|
42
|
+
return { toolChoice: 'none' };
|
|
43
|
+
}
|
|
44
|
+
const toolCalls = steps.flatMap(step => step.toolCalls);
|
|
45
|
+
const repeatedToolNames = latestRepeatedToolNames(steps);
|
|
46
|
+
let scopedMessages = withScopedContextControl(messages, toolExecutionContext);
|
|
47
|
+
let messagesChanged = scopedMessages !== messages;
|
|
48
|
+
// Re-evaluate the accumulated request size before each provider call and
|
|
49
|
+
// compact old tool history when it exceeds the model-aware budget, so a
|
|
50
|
+
// long multi-step turn compacts before overflowing (RH-005).
|
|
51
|
+
if (estimateMessagesTokens(scopedMessages) > requestBudget.messageTokens) {
|
|
52
|
+
const compacted = compactModelMessages(stripSyntheticControls(scopedMessages), { tokenBudget: requestBudget.messageTokens, workState: goal }).messages;
|
|
53
|
+
scopedMessages = compacted;
|
|
54
|
+
messagesChanged = true;
|
|
55
|
+
}
|
|
56
|
+
// Turn-wide hard caps (shared across retries and recovery slices).
|
|
57
|
+
const turnToolCallsExhausted = turnState.toolCallsUsed >= turnBudget.toolCallLimit;
|
|
58
|
+
// Per-slice tool-call cap for a recovery slice (counts this slice's calls).
|
|
59
|
+
const sliceToolCallsExhausted = recoverySlice ? toolCalls.length >= recoverySlice.maxToolCalls : false;
|
|
60
|
+
// Reserve the final tool-only slot for rescue: normal exploration stops at
|
|
61
|
+
// the boundary; a rescue slice is exempt so it may use the reserved slot.
|
|
62
|
+
const toolOnlyBoundaryHit = !recoverySlice && toolOnlyStepCount(steps) >= RESCUE_BOUNDARY;
|
|
63
|
+
if (likelyPlanOnlyRequest && loopState.toolResultState.mutatingToolSucceeded)
|
|
64
|
+
return messagesChanged ? { toolChoice: 'none', messages: scopedMessages } : { toolChoice: 'none' };
|
|
65
|
+
if (loopState.pendingMalformedToolName && loopState.pendingMalformedToolName in sliceTools) {
|
|
66
|
+
const toolName = loopState.pendingMalformedToolName;
|
|
67
|
+
const attempt = loopState.malformedRecoveryAttempts.get(String(toolName)) ?? 0;
|
|
68
|
+
loopState.pendingMalformedToolName = undefined;
|
|
69
|
+
if (attempt >= 2) {
|
|
70
|
+
callbacks.debugLog(`malformed ${String(toolName)} recovery exhausted`);
|
|
71
|
+
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.`) };
|
|
72
|
+
}
|
|
73
|
+
loopState.malformedRecoveryAttempts.set(String(toolName), attempt + 1);
|
|
74
|
+
callbacks.debugLog(`forcing smaller retry after malformed ${String(toolName)} input`);
|
|
75
|
+
// OpenAI-compatible servers differ in tool_choice support: several
|
|
76
|
+
// (LM Studio, llama.cpp) accept only the string form (none/auto/
|
|
77
|
+
// required) and reject the object form with HTTP 400. Narrowing to a
|
|
78
|
+
// single active tool plus 'required' preserves the forced-call
|
|
79
|
+
// semantics on every server.
|
|
80
|
+
return { activeTools: [toolName], toolChoice: 'required', messages: withSyntheticControl(scopedMessages, malformedToolCallPrompt(String(toolName), WRITE_FILE_CHUNK_BYTES)) };
|
|
81
|
+
}
|
|
82
|
+
if (loopState.toolResultState.editRecoveryPath && !loopState.toolResultState.editRecoveryReadSatisfied) {
|
|
83
|
+
if ('readFile' in sliceTools)
|
|
84
|
+
return messagesChanged ? { activeTools: ['readFile'], messages: scopedMessages } : { activeTools: ['readFile'] };
|
|
85
|
+
return { toolChoice: 'none', messages: withSyntheticControl(scopedMessages, `The failed mutation of ${loopState.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.`) };
|
|
86
|
+
}
|
|
87
|
+
if (repeatedToolNames.length > 0) {
|
|
88
|
+
const activeTools = Object.keys(sliceTools).filter(name => !repeatedToolNames.includes(name));
|
|
89
|
+
callbacks.debugLog(`disabling repeated tools for next step: ${repeatedToolNames.join(', ')}`);
|
|
90
|
+
return activeTools.length > 0
|
|
91
|
+
? { activeTools, messages: withSyntheticControl(scopedMessages, repeatedToolCallPrompt(repeatedToolNames)) }
|
|
92
|
+
: { toolChoice: 'none', messages: withSyntheticControl(scopedMessages, repeatedToolCallPrompt(repeatedToolNames)) };
|
|
93
|
+
}
|
|
94
|
+
if (turnToolCallsExhausted || sliceToolCallsExhausted || toolOnlyBoundaryHit || toolCalls.length >= MAIN_TOOL_CALL_LIMIT) {
|
|
95
|
+
callbacks.debugLog('forcing text response to avoid tool loop');
|
|
96
|
+
return { toolChoice: 'none', messages: withSyntheticControl(scopedMessages, toolLoopBudgetPrompt()) };
|
|
97
|
+
}
|
|
98
|
+
return messagesChanged ? { messages: scopedMessages } : undefined;
|
|
99
|
+
};
|
|
100
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { type TurnExecutionState } from '../../../core/agent/completionController.js';
|
|
2
|
+
import type { ToolExecutionBudgetState } from '../../../core/agent/budgets.js';
|
|
3
|
+
import type { AttemptRecovery } from './attemptOutcome.js';
|
|
4
|
+
import type { TurnExecutionOptions } from '../streaming.js';
|
|
5
|
+
/**
|
|
6
|
+
* Recovery-slice admission for the turn loop (extracted from
|
|
7
|
+
* `runAgentTurn`). Length/rescue credits are single-use, so a slice cannot
|
|
8
|
+
* trigger another of the same kind; goal continuation is repeatable but
|
|
9
|
+
* progress-guarded and counts against the shared turn budget.
|
|
10
|
+
*/
|
|
11
|
+
export declare function startRecoverySlice(recovery: AttemptRecovery, state: {
|
|
12
|
+
turnState: TurnExecutionState;
|
|
13
|
+
sliceBudget: ToolExecutionBudgetState;
|
|
14
|
+
options: TurnExecutionOptions;
|
|
15
|
+
}, debugLog: (line: string) => void): TurnExecutionOptions;
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { recordGoalContinuation } from '../../../core/agent/completionController.js';
|
|
2
|
+
/**
|
|
3
|
+
* Recovery-slice admission for the turn loop (extracted from
|
|
4
|
+
* `runAgentTurn`). Length/rescue credits are single-use, so a slice cannot
|
|
5
|
+
* trigger another of the same kind; goal continuation is repeatable but
|
|
6
|
+
* progress-guarded and counts against the shared turn budget.
|
|
7
|
+
*/
|
|
8
|
+
export function startRecoverySlice(recovery, state, debugLog) {
|
|
9
|
+
if (recovery.kind === 'length') {
|
|
10
|
+
state.turnState.lengthCreditUsed = true;
|
|
11
|
+
state.turnState.lengthRecoveriesAttempted += 1;
|
|
12
|
+
}
|
|
13
|
+
else if (recovery.kind === 'rescue') {
|
|
14
|
+
state.turnState.rescueUsed = true;
|
|
15
|
+
}
|
|
16
|
+
else {
|
|
17
|
+
recordGoalContinuation(state.turnState);
|
|
18
|
+
}
|
|
19
|
+
// A new slice gets a fresh execution allowance, clamped once here; the
|
|
20
|
+
// slice budget persists across provider retries within the slice (C2).
|
|
21
|
+
state.sliceBudget.started = 0;
|
|
22
|
+
state.sliceBudget.exceeded = false;
|
|
23
|
+
debugLog(`starting ${recovery.kind} recovery slice: ${recovery.slice.maxSteps} steps / ${recovery.slice.maxToolCalls} tool calls`);
|
|
24
|
+
return {
|
|
25
|
+
...state.options,
|
|
26
|
+
ephemeralControl: recovery.control,
|
|
27
|
+
recoverySlice: { kind: recovery.kind, maxSteps: recovery.slice.maxSteps, maxToolCalls: recovery.slice.maxToolCalls },
|
|
28
|
+
};
|
|
29
|
+
}
|
|
@@ -4,7 +4,6 @@ import type { ModelMessage } from 'ai';
|
|
|
4
4
|
import { type TurnAbortCause } from './abortCause.js';
|
|
5
5
|
/** What the stalled step had emitted when the stream went quiet. Only 'none' is auto-retryable. */
|
|
6
6
|
type StallEmission = 'none' | 'text' | 'tool';
|
|
7
|
-
export declare function formatIdleMinutes(milliseconds: number): string;
|
|
8
7
|
/**
|
|
9
8
|
* An idle timer for the main agent turn.
|
|
10
9
|
*
|
|
@@ -3,10 +3,6 @@ import { IDLE_TIMEOUT_MS, DEFAULT_MODEL_RETRIES } from '../../../core/agent/budg
|
|
|
3
3
|
import { compactToolHistory, stripSyntheticControls } from '../../../core/agent/requestAssembly.js';
|
|
4
4
|
import { abortForTurn } from './abortCause.js';
|
|
5
5
|
import { logEntry } from './turnRuntime.js';
|
|
6
|
-
export function formatIdleMinutes(milliseconds) {
|
|
7
|
-
const minutes = Math.round(milliseconds / 60_000);
|
|
8
|
-
return `${minutes} minute${minutes === 1 ? '' : 's'}`;
|
|
9
|
-
}
|
|
10
6
|
/** Auto-retry an idle stall only while the stalled step emitted nothing visible (no partial text or in-flight tool). */
|
|
11
7
|
function idleStallAutoRetryEligible(retryAttempt, stallEmission, maxRetries) {
|
|
12
8
|
return stallEmission === 'none' && retryAttempt < maxRetries;
|
|
@@ -1,22 +1,16 @@
|
|
|
1
1
|
import { ToolLoopAgent, isStepCount } from 'ai';
|
|
2
2
|
import { agentEvent } from '../../../core/agent/events.js';
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
6
|
-
import { compactModelMessages } from '../../../core/agent/compaction.js';
|
|
7
|
-
import { latestRepeatedToolNames, toolOnlyStepCount } from '../../../core/agent/turnPolicy.js';
|
|
8
|
-
import { RESCUE_BOUNDARY } from '../../../core/agent/completionController.js';
|
|
9
|
-
import { MAIN_TOOL_CALL_LIMIT, DEFAULT_MAX_OUTPUT_TOKENS, DEFAULT_TOOL_DEADLINE_MS, SUBAGENT_TOOL_DEADLINE_MS, WRITE_FILE_CHUNK_BYTES, isToolBudgetBlocked } from '../../../core/agent/budgets.js';
|
|
10
|
-
import { isToolDeadlineExceeded } from '../../../core/deadline.js';
|
|
11
|
-
import { isDuplicateSkippedOutput, safeToolFailureDetails, toolOutputOk } from '../../../core/agent/toolResults.js';
|
|
12
|
-
import { projectContextSection } from '../../../llm/systemPrompt.js';
|
|
3
|
+
import { estimateValueTokens } from '../../../core/agent/contextBudget.js';
|
|
4
|
+
import { compactToolHistory, stripSyntheticControls } from '../../../core/agent/requestAssembly.js';
|
|
5
|
+
import { DEFAULT_MAX_OUTPUT_TOKENS } from '../../../core/agent/budgets.js';
|
|
13
6
|
import { toolsContextFor } from '../../../llm/tools/toolContext.js';
|
|
14
|
-
import { busyToolLabel, toolCallSummary
|
|
15
|
-
import { sanitizeAssistantText, assistantDisplayText, normalizeAssistantText, shouldStartAssistantStream
|
|
16
|
-
import {
|
|
7
|
+
import { busyToolLabel, toolCallSummary } from '../formatters.js';
|
|
8
|
+
import { sanitizeAssistantText, assistantDisplayText, normalizeAssistantText, shouldStartAssistantStream } from './assistantText.js';
|
|
9
|
+
import { finalizeAssistantSegment, finalizePendingAssistantBeforeTool } from './assistantSegments.js';
|
|
10
|
+
import { handleToolErrorPart, handleToolResultPart } from './toolPartHandlers.js';
|
|
11
|
+
import { createPrepareStep, createRepairToolCall } from './prepareStep.js';
|
|
17
12
|
import { applyStepToolResultState, initialToolResultState } from './toolResultState.js';
|
|
18
|
-
import {
|
|
19
|
-
import { extractUsage, logEntry, rememberContextFilesFromToolOutput, responseCompletionMetrics, stepCacheMetrics, subagentTokenEstimate } from './turnRuntime.js';
|
|
13
|
+
import { extractUsage, logEntry, stepCacheMetrics } from './turnRuntime.js';
|
|
20
14
|
export function createAttemptLoopState(previousAssistantText, contextFiles, callbacks) {
|
|
21
15
|
const visibleAssistantTexts = new Set(previousAssistantText ? [previousAssistantText] : []);
|
|
22
16
|
return {
|
|
@@ -47,221 +41,6 @@ export function createAttemptLoopState(previousAssistantText, contextFiles, call
|
|
|
47
41
|
contextFiles,
|
|
48
42
|
};
|
|
49
43
|
}
|
|
50
|
-
function withScopedContextControl(messages, context) {
|
|
51
|
-
const files = context.pendingContextFiles ?? [];
|
|
52
|
-
if (files.length === 0)
|
|
53
|
-
return messages;
|
|
54
|
-
context.pendingContextFiles = [];
|
|
55
|
-
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)}`);
|
|
56
|
-
}
|
|
57
|
-
function createRepairToolCall(deps) {
|
|
58
|
-
const { callbacks, loopState } = deps;
|
|
59
|
-
return async ({ toolCall, error, inputSchema }) => {
|
|
60
|
-
if (isMalformedToolInputError(error)) {
|
|
61
|
-
const clamped = await clampOutOfBoundsToolNumbers(toolCall.input, toolCall.toolName, inputSchema);
|
|
62
|
-
if (clamped != null) {
|
|
63
|
-
callbacks.debugLog(`clamped out-of-range numeric input for ${toolCall.toolName}; executing repaired call`);
|
|
64
|
-
return { type: 'tool-call', toolCallId: toolCall.toolCallId, toolName: toolCall.toolName, input: JSON.stringify(clamped) };
|
|
65
|
-
}
|
|
66
|
-
loopState.pendingMalformedToolName = toolCall.toolName;
|
|
67
|
-
loopState.unresolvedMalformedToolName = toolCall.toolName;
|
|
68
|
-
}
|
|
69
|
-
// Truncated generated file content cannot be reconstructed safely here;
|
|
70
|
-
// let the next agent step retry under the bounded tool-choice constraint.
|
|
71
|
-
return null;
|
|
72
|
-
};
|
|
73
|
-
}
|
|
74
|
-
function createPrepareStep(deps) {
|
|
75
|
-
const { setup, callbacks, loopState, turnState, turnBudget, goal, recoverySlice } = deps;
|
|
76
|
-
const { sliceTools, requestBudget, toolExecutionContext, likelyPlanOnlyRequest, rescueWithoutTools } = setup;
|
|
77
|
-
return ({ steps, messages }) => {
|
|
78
|
-
// A rescue slice with no qualifying tools must synthesize, never reopen
|
|
79
|
-
// discovery by falling back to the full tool set (F-08).
|
|
80
|
-
if (rescueWithoutTools) {
|
|
81
|
-
callbacks.debugLog('rescue slice has no mutation/validation tools; forcing tool-free synthesis');
|
|
82
|
-
return { toolChoice: 'none' };
|
|
83
|
-
}
|
|
84
|
-
const toolCalls = steps.flatMap(step => step.toolCalls);
|
|
85
|
-
const repeatedToolNames = latestRepeatedToolNames(steps);
|
|
86
|
-
let scopedMessages = withScopedContextControl(messages, toolExecutionContext);
|
|
87
|
-
let messagesChanged = scopedMessages !== messages;
|
|
88
|
-
// Re-evaluate the accumulated request size before each provider call and
|
|
89
|
-
// compact old tool history when it exceeds the model-aware budget, so a
|
|
90
|
-
// long multi-step turn compacts before overflowing (RH-005).
|
|
91
|
-
if (estimateMessagesTokens(scopedMessages) > requestBudget.messageTokens) {
|
|
92
|
-
const compacted = compactModelMessages(stripSyntheticControls(scopedMessages), { tokenBudget: requestBudget.messageTokens, workState: goal }).messages;
|
|
93
|
-
scopedMessages = compacted;
|
|
94
|
-
messagesChanged = true;
|
|
95
|
-
}
|
|
96
|
-
// Turn-wide hard caps (shared across retries and recovery slices).
|
|
97
|
-
const turnToolCallsExhausted = turnState.toolCallsUsed >= turnBudget.toolCallLimit;
|
|
98
|
-
// Per-slice tool-call cap for a recovery slice (counts this slice's calls).
|
|
99
|
-
const sliceToolCallsExhausted = recoverySlice ? toolCalls.length >= recoverySlice.maxToolCalls : false;
|
|
100
|
-
// Reserve the final tool-only slot for rescue: normal exploration stops at
|
|
101
|
-
// the boundary; a rescue slice is exempt so it may use the reserved slot.
|
|
102
|
-
const toolOnlyBoundaryHit = !recoverySlice && toolOnlyStepCount(steps) >= RESCUE_BOUNDARY;
|
|
103
|
-
if (likelyPlanOnlyRequest && loopState.toolResultState.mutatingToolSucceeded)
|
|
104
|
-
return messagesChanged ? { toolChoice: 'none', messages: scopedMessages } : { toolChoice: 'none' };
|
|
105
|
-
if (loopState.pendingMalformedToolName && loopState.pendingMalformedToolName in sliceTools) {
|
|
106
|
-
const toolName = loopState.pendingMalformedToolName;
|
|
107
|
-
const attempt = loopState.malformedRecoveryAttempts.get(String(toolName)) ?? 0;
|
|
108
|
-
loopState.pendingMalformedToolName = undefined;
|
|
109
|
-
if (attempt >= 2) {
|
|
110
|
-
callbacks.debugLog(`malformed ${String(toolName)} recovery exhausted`);
|
|
111
|
-
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.`) };
|
|
112
|
-
}
|
|
113
|
-
loopState.malformedRecoveryAttempts.set(String(toolName), attempt + 1);
|
|
114
|
-
callbacks.debugLog(`forcing smaller retry after malformed ${String(toolName)} input`);
|
|
115
|
-
// OpenAI-compatible servers differ in tool_choice support: several
|
|
116
|
-
// (LM Studio, llama.cpp) accept only the string form (none/auto/
|
|
117
|
-
// required) and reject the object form with HTTP 400. Narrowing to a
|
|
118
|
-
// single active tool plus 'required' preserves the forced-call
|
|
119
|
-
// semantics on every server.
|
|
120
|
-
return { activeTools: [toolName], toolChoice: 'required', messages: withSyntheticControl(scopedMessages, malformedToolCallPrompt(String(toolName), WRITE_FILE_CHUNK_BYTES)) };
|
|
121
|
-
}
|
|
122
|
-
if (loopState.toolResultState.editRecoveryPath && !loopState.toolResultState.editRecoveryReadSatisfied) {
|
|
123
|
-
if ('readFile' in sliceTools)
|
|
124
|
-
return messagesChanged ? { activeTools: ['readFile'], messages: scopedMessages } : { activeTools: ['readFile'] };
|
|
125
|
-
return { toolChoice: 'none', messages: withSyntheticControl(scopedMessages, `The failed mutation of ${loopState.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.`) };
|
|
126
|
-
}
|
|
127
|
-
if (repeatedToolNames.length > 0) {
|
|
128
|
-
const activeTools = Object.keys(sliceTools).filter(name => !repeatedToolNames.includes(name));
|
|
129
|
-
callbacks.debugLog(`disabling repeated tools for next step: ${repeatedToolNames.join(', ')}`);
|
|
130
|
-
return activeTools.length > 0
|
|
131
|
-
? { activeTools, messages: withSyntheticControl(scopedMessages, repeatedToolCallPrompt(repeatedToolNames)) }
|
|
132
|
-
: { toolChoice: 'none', messages: withSyntheticControl(scopedMessages, repeatedToolCallPrompt(repeatedToolNames)) };
|
|
133
|
-
}
|
|
134
|
-
if (turnToolCallsExhausted || sliceToolCallsExhausted || toolOnlyBoundaryHit || toolCalls.length >= MAIN_TOOL_CALL_LIMIT) {
|
|
135
|
-
callbacks.debugLog('forcing text response to avoid tool loop');
|
|
136
|
-
return { toolChoice: 'none', messages: withSyntheticControl(scopedMessages, toolLoopBudgetPrompt()) };
|
|
137
|
-
}
|
|
138
|
-
return messagesChanged ? { messages: scopedMessages } : undefined;
|
|
139
|
-
};
|
|
140
|
-
}
|
|
141
|
-
function resetAssistantSegment(loopState) {
|
|
142
|
-
loopState.currentAssistantId = `assistant-${Date.now()}-${Math.random().toString(36).slice(2)}`;
|
|
143
|
-
loopState.assistantStarted = false;
|
|
144
|
-
loopState.assistantStartedAt = Date.now();
|
|
145
|
-
loopState.currentAssistantText = '';
|
|
146
|
-
}
|
|
147
|
-
function finalizeAssistantSegment(loopState, callbacks, options = {}) {
|
|
148
|
-
const finalText = assistantDisplayText(loopState.currentAssistantText);
|
|
149
|
-
const normalized = normalizeAssistantText(finalText);
|
|
150
|
-
const hidden = (loopState.assistantStarted ? isHiddenAssistantFragment(finalText) : isHiddenUnstartedFinalText(finalText))
|
|
151
|
-
|| (options.beforeTool === true && isShortLeadInBeforeTool(finalText))
|
|
152
|
-
|| (options.beforeTool !== true && isShortUnfinishedLeadIn(finalText))
|
|
153
|
-
|| (normalized.length > 0 && loopState.visibleAssistantTexts.has(normalized));
|
|
154
|
-
if (loopState.assistantStarted) {
|
|
155
|
-
if (!hidden)
|
|
156
|
-
loopState.rememberVisibleAssistantText(finalText);
|
|
157
|
-
callbacks.onEvent?.(agentEvent({ type: 'message_end', id: loopState.currentAssistantId, text: finalText, hidden }));
|
|
158
|
-
callbacks.updateMessage(loopState.currentAssistantId, { text: finalText, streaming: false, hidden, ...responseCompletionMetrics(finalText, loopState.assistantStartedAt) });
|
|
159
|
-
}
|
|
160
|
-
else if (!hidden) {
|
|
161
|
-
if (!hidden)
|
|
162
|
-
loopState.rememberVisibleAssistantText(finalText);
|
|
163
|
-
callbacks.onEvent?.(agentEvent({ type: 'message_start', id: loopState.currentAssistantId, role: 'assistant' }));
|
|
164
|
-
callbacks.onEvent?.(agentEvent({ type: 'message_end', id: loopState.currentAssistantId, text: finalText, hidden: false }));
|
|
165
|
-
callbacks.addMessage({ id: loopState.currentAssistantId, role: 'assistant', text: finalText, streaming: false, startedAt: loopState.assistantStartedAt, ...responseCompletionMetrics(finalText, loopState.assistantStartedAt) });
|
|
166
|
-
}
|
|
167
|
-
resetAssistantSegment(loopState);
|
|
168
|
-
return !hidden;
|
|
169
|
-
}
|
|
170
|
-
function finalizePendingAssistantBeforeTool(deps) {
|
|
171
|
-
const { loopState, callbacks, toolDisplay } = deps;
|
|
172
|
-
if (loopState.currentAssistantText.trim().length > 0 || loopState.assistantStarted) {
|
|
173
|
-
const pending = assistantDisplayText(loopState.currentAssistantText);
|
|
174
|
-
const shown = finalizeAssistantSegment(loopState, callbacks, { beforeTool: true });
|
|
175
|
-
if (!shown && pending)
|
|
176
|
-
toolDisplay.setGroupCaption(pending);
|
|
177
|
-
}
|
|
178
|
-
}
|
|
179
|
-
function handleToolResultPart(deps, part) {
|
|
180
|
-
const { loopState, callbacks, toolDisplay, setup, goal } = deps;
|
|
181
|
-
const toolCallId = part.toolCallId;
|
|
182
|
-
const toolName = part.toolName;
|
|
183
|
-
const toolCall = { toolCallId, toolName, input: part.input };
|
|
184
|
-
loopState.latestToolCalls.set(toolCallId, toolCall);
|
|
185
|
-
loopState.inFlightTools.delete(toolCallId);
|
|
186
|
-
const startedAt = loopState.startedTools.get(toolCallId) ?? Date.now();
|
|
187
|
-
// A budget-blocked call never reached the underlying implementation;
|
|
188
|
-
// record it as a bounded non-event with no goal/observal side effect (RH-003).
|
|
189
|
-
if (isToolBudgetBlocked(part.output)) {
|
|
190
|
-
const item = toolDisplay.ensureToolItem(toolCall);
|
|
191
|
-
item.status = 'error';
|
|
192
|
-
item.result = 'skipped: tool-call budget exhausted';
|
|
193
|
-
item.durationMs = Date.now() - startedAt;
|
|
194
|
-
item.finishedAt = startedAt + (item.durationMs ?? 0);
|
|
195
|
-
callbacks.onEvent?.(agentEvent({ type: 'tool_end', id: toolCall.toolCallId, name: toolCall.toolName, success: false, errorCode: 'tool_budget_blocked', durationMs: item.durationMs ?? 0 }));
|
|
196
|
-
toolDisplay.updateToolGroup(true);
|
|
197
|
-
return;
|
|
198
|
-
}
|
|
199
|
-
// A deadline-exceeded call was terminated at the wrapper boundary; the
|
|
200
|
-
// underlying work may still be settling and must not mutate goal state (RH-004).
|
|
201
|
-
if (isToolDeadlineExceeded(part.output)) {
|
|
202
|
-
const item = toolDisplay.ensureToolItem(toolCall);
|
|
203
|
-
item.status = 'error';
|
|
204
|
-
item.result = `timed out after ${DEFAULT_TOOL_DEADLINE_MS}ms`;
|
|
205
|
-
const durationMs = Date.now() - startedAt;
|
|
206
|
-
item.durationMs = durationMs;
|
|
207
|
-
item.finishedAt = startedAt + durationMs;
|
|
208
|
-
callbacks.onEvent?.(agentEvent({ type: 'tool_end', id: toolCall.toolCallId, name: toolCall.toolName, success: false, errorCode: 'tool_deadline', durationMs }));
|
|
209
|
-
callbacks.onEvent?.(agentEvent({ type: 'timeout', phase: 'tool', timeoutMs: toolName === 'subagent' ? SUBAGENT_TOOL_DEADLINE_MS : DEFAULT_TOOL_DEADLINE_MS }));
|
|
210
|
-
toolDisplay.updateToolGroup(true);
|
|
211
|
-
return;
|
|
212
|
-
}
|
|
213
|
-
const ok = toolOutputOk(part.output, true);
|
|
214
|
-
loopState.lastToolOk = ok;
|
|
215
|
-
if (ok && part.toolName === loopState.unresolvedMalformedToolName)
|
|
216
|
-
loopState.unresolvedMalformedToolName = undefined;
|
|
217
|
-
const finish = { toolCall, success: ok, output: part.output, durationMs: Date.now() - startedAt };
|
|
218
|
-
const item = toolDisplay.ensureToolItem(toolCall);
|
|
219
|
-
item.status = ok ? 'success' : 'error';
|
|
220
|
-
item.result = toolResultSummary(finish);
|
|
221
|
-
item.diff = toolDiffFromResult(toolCall, part.output);
|
|
222
|
-
item.durationMs = finish.durationMs;
|
|
223
|
-
item.finishedAt = startedAt + finish.durationMs;
|
|
224
|
-
const failureDetails = ok || setup.toolCategories.get(toolCall.toolName) !== 'builtin' ? {} : safeToolFailureDetails(part.output);
|
|
225
|
-
callbacks.onEvent?.(agentEvent({ type: 'tool_end', id: toolCall.toolCallId, name: toolCall.toolName, success: ok, output: part.output, ...failureDetails, durationMs: finish.durationMs }));
|
|
226
|
-
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 } });
|
|
227
|
-
observeGoalToolEvent(goal, { ...toolCall, success: ok, output: part.output, duplicateSkipped: isDuplicateSkippedOutput(part.output) });
|
|
228
|
-
callbacks.setWorkState?.(goal);
|
|
229
|
-
callbacks.setGoalStatus?.(formatGoalStatus(goal));
|
|
230
|
-
loopState.contextFiles = rememberContextFilesFromToolOutput(loopState.contextFiles, part.output);
|
|
231
|
-
if (toolCall.toolName === 'writeTasks')
|
|
232
|
-
callbacks.onTasksChanged?.();
|
|
233
|
-
const nestedTokens = subagentTokenEstimate(part.output);
|
|
234
|
-
if (nestedTokens)
|
|
235
|
-
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 });
|
|
236
|
-
toolDisplay.updateToolGroup(true);
|
|
237
|
-
}
|
|
238
|
-
function handleToolErrorPart(deps, part) {
|
|
239
|
-
const { loopState, callbacks, toolDisplay, setup, goal } = deps;
|
|
240
|
-
const toolCallId = part.toolCallId;
|
|
241
|
-
const toolName = part.toolName;
|
|
242
|
-
loopState.inFlightTools.delete(toolCallId);
|
|
243
|
-
const existing = loopState.latestToolCalls.get(toolCallId);
|
|
244
|
-
const toolCall = { toolCallId, toolName, input: part.input ?? existing?.input };
|
|
245
|
-
const startedAt = loopState.startedTools.get(toolCallId) ?? Date.now();
|
|
246
|
-
loopState.lastToolOk = false;
|
|
247
|
-
if (isMalformedToolInputError(part.error)) {
|
|
248
|
-
loopState.pendingMalformedToolName = toolName;
|
|
249
|
-
loopState.unresolvedMalformedToolName = toolName;
|
|
250
|
-
}
|
|
251
|
-
const finish = { toolCall, success: false, error: part.error, durationMs: Date.now() - startedAt };
|
|
252
|
-
const item = toolDisplay.ensureToolItem(toolCall);
|
|
253
|
-
item.status = 'error';
|
|
254
|
-
item.result = toolResultSummary(finish);
|
|
255
|
-
item.durationMs = finish.durationMs;
|
|
256
|
-
item.finishedAt = startedAt + finish.durationMs;
|
|
257
|
-
const publicError = setup.toolCategories.get(toolCall.toolName) === 'builtin' ? { error: part.error } : {};
|
|
258
|
-
callbacks.onEvent?.(agentEvent({ type: 'tool_end', id: toolCall.toolCallId, name: toolCall.toolName, success: false, errorCode: 'tool_execution_error', ...publicError, durationMs: finish.durationMs }));
|
|
259
|
-
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 } });
|
|
260
|
-
observeGoalToolEvent(goal, { ...toolCall, success: false, output: part.error });
|
|
261
|
-
callbacks.setWorkState?.(goal);
|
|
262
|
-
callbacks.setGoalStatus?.(formatGoalStatus(goal));
|
|
263
|
-
toolDisplay.updateToolGroup(true);
|
|
264
|
-
}
|
|
265
44
|
function applyStreamPart(deps, part) {
|
|
266
45
|
const { loopState, callbacks, toolDisplay, setup } = deps;
|
|
267
46
|
switch (part.type) {
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { agentEvent } from '../../../core/agent/events.js';
|
|
2
2
|
import { appendLogEntry as logAppend } from '../../../core/log/llmLog.js';
|
|
3
|
-
import { toolCallSummary, compact
|
|
3
|
+
import { toolCallSummary, compact } from '../formatters.js';
|
|
4
|
+
import { formatElapsedTimeWhole, formatSeconds } from '../../../utils/format.js';
|
|
4
5
|
function logEntry(log, entry) {
|
|
5
6
|
if (log)
|
|
6
7
|
void logAppend(log, entry).catch(() => undefined);
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { type SessionGoal } from '../../../core/agent/goalPolicy.js';
|
|
2
|
+
import { type ToolGroupRenderer } from './toolGroupRenderer.js';
|
|
3
|
+
import type { StreamCallbacks } from '../streaming.js';
|
|
4
|
+
import type { AttemptSetup } from './attemptSetup.js';
|
|
5
|
+
import type { AttemptLoopState } from './streamLoop.js';
|
|
6
|
+
/** One consumed public stream part, keyed by `type` (see the AI SDK's full-stream parts). */
|
|
7
|
+
export type AttemptStreamPart = {
|
|
8
|
+
type: string;
|
|
9
|
+
} & Record<string, unknown>;
|
|
10
|
+
type ToolPartHandlerDeps = {
|
|
11
|
+
loopState: AttemptLoopState;
|
|
12
|
+
callbacks: StreamCallbacks;
|
|
13
|
+
toolDisplay: ToolGroupRenderer;
|
|
14
|
+
setup: AttemptSetup;
|
|
15
|
+
goal: SessionGoal;
|
|
16
|
+
};
|
|
17
|
+
export declare function handleToolResultPart(deps: ToolPartHandlerDeps, part: AttemptStreamPart): void;
|
|
18
|
+
export declare function handleToolErrorPart(deps: ToolPartHandlerDeps, part: AttemptStreamPart): void;
|
|
19
|
+
export {};
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
import { agentEvent } from '../../../core/agent/events.js';
|
|
2
|
+
import { formatGoalStatus, observeGoalToolEvent } from '../../../core/agent/goalPolicy.js';
|
|
3
|
+
import { DEFAULT_TOOL_DEADLINE_MS, SUBAGENT_TOOL_DEADLINE_MS, isToolBudgetBlocked } from '../../../core/agent/budgets.js';
|
|
4
|
+
import { isToolDeadlineExceeded } from '../../../core/deadline.js';
|
|
5
|
+
import { isDuplicateSkippedOutput, safeToolFailureDetails, toolOutputOk } from '../../../core/agent/toolResults.js';
|
|
6
|
+
import { toolResultSummary } from '../formatters.js';
|
|
7
|
+
import { toolDiffFromResult } from './toolGroupRenderer.js';
|
|
8
|
+
import { isMalformedToolInputError } from './toolCallRecovery.js';
|
|
9
|
+
import { logEntry, rememberContextFilesFromToolOutput, subagentTokenEstimate } from './turnRuntime.js';
|
|
10
|
+
export function handleToolResultPart(deps, part) {
|
|
11
|
+
const { loopState, callbacks, toolDisplay, setup, goal } = deps;
|
|
12
|
+
const toolCallId = part.toolCallId;
|
|
13
|
+
const toolName = part.toolName;
|
|
14
|
+
const toolCall = { toolCallId, toolName, input: part.input };
|
|
15
|
+
loopState.latestToolCalls.set(toolCallId, toolCall);
|
|
16
|
+
loopState.inFlightTools.delete(toolCallId);
|
|
17
|
+
const startedAt = loopState.startedTools.get(toolCallId) ?? Date.now();
|
|
18
|
+
// A budget-blocked call never reached the underlying implementation;
|
|
19
|
+
// record it as a bounded non-event with no goal/observal side effect (RH-003).
|
|
20
|
+
if (isToolBudgetBlocked(part.output)) {
|
|
21
|
+
const item = toolDisplay.ensureToolItem(toolCall);
|
|
22
|
+
item.status = 'error';
|
|
23
|
+
item.result = 'skipped: tool-call budget exhausted';
|
|
24
|
+
item.durationMs = Date.now() - startedAt;
|
|
25
|
+
item.finishedAt = startedAt + (item.durationMs ?? 0);
|
|
26
|
+
callbacks.onEvent?.(agentEvent({ type: 'tool_end', id: toolCall.toolCallId, name: toolCall.toolName, success: false, errorCode: 'tool_budget_blocked', durationMs: item.durationMs ?? 0 }));
|
|
27
|
+
toolDisplay.updateToolGroup(true);
|
|
28
|
+
return;
|
|
29
|
+
}
|
|
30
|
+
// A deadline-exceeded call was terminated at the wrapper boundary; the
|
|
31
|
+
// underlying work may still be settling and must not mutate goal state (RH-004).
|
|
32
|
+
if (isToolDeadlineExceeded(part.output)) {
|
|
33
|
+
const item = toolDisplay.ensureToolItem(toolCall);
|
|
34
|
+
item.status = 'error';
|
|
35
|
+
item.result = `timed out after ${DEFAULT_TOOL_DEADLINE_MS}ms`;
|
|
36
|
+
const durationMs = Date.now() - startedAt;
|
|
37
|
+
item.durationMs = durationMs;
|
|
38
|
+
item.finishedAt = startedAt + durationMs;
|
|
39
|
+
callbacks.onEvent?.(agentEvent({ type: 'tool_end', id: toolCall.toolCallId, name: toolCall.toolName, success: false, errorCode: 'tool_deadline', durationMs }));
|
|
40
|
+
callbacks.onEvent?.(agentEvent({ type: 'timeout', phase: 'tool', timeoutMs: toolName === 'subagent' ? SUBAGENT_TOOL_DEADLINE_MS : DEFAULT_TOOL_DEADLINE_MS }));
|
|
41
|
+
toolDisplay.updateToolGroup(true);
|
|
42
|
+
return;
|
|
43
|
+
}
|
|
44
|
+
const ok = toolOutputOk(part.output, true);
|
|
45
|
+
loopState.lastToolOk = ok;
|
|
46
|
+
if (ok && part.toolName === loopState.unresolvedMalformedToolName)
|
|
47
|
+
loopState.unresolvedMalformedToolName = undefined;
|
|
48
|
+
const finish = { toolCall, success: ok, output: part.output, durationMs: Date.now() - startedAt };
|
|
49
|
+
const item = toolDisplay.ensureToolItem(toolCall);
|
|
50
|
+
item.status = ok ? 'success' : 'error';
|
|
51
|
+
item.result = toolResultSummary(finish);
|
|
52
|
+
item.diff = toolDiffFromResult(toolCall, part.output);
|
|
53
|
+
item.durationMs = finish.durationMs;
|
|
54
|
+
item.finishedAt = startedAt + finish.durationMs;
|
|
55
|
+
const failureDetails = ok || setup.toolCategories.get(toolCall.toolName) !== 'builtin' ? {} : safeToolFailureDetails(part.output);
|
|
56
|
+
callbacks.onEvent?.(agentEvent({ type: 'tool_end', id: toolCall.toolCallId, name: toolCall.toolName, success: ok, output: part.output, ...failureDetails, durationMs: finish.durationMs }));
|
|
57
|
+
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 } });
|
|
58
|
+
observeGoalToolEvent(goal, { ...toolCall, success: ok, output: part.output, duplicateSkipped: isDuplicateSkippedOutput(part.output) });
|
|
59
|
+
callbacks.setWorkState?.(goal);
|
|
60
|
+
callbacks.setGoalStatus?.(formatGoalStatus(goal));
|
|
61
|
+
loopState.contextFiles = rememberContextFilesFromToolOutput(loopState.contextFiles, part.output);
|
|
62
|
+
if (toolCall.toolName === 'writeTasks')
|
|
63
|
+
callbacks.onTasksChanged?.();
|
|
64
|
+
const nestedTokens = subagentTokenEstimate(part.output);
|
|
65
|
+
if (nestedTokens)
|
|
66
|
+
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 });
|
|
67
|
+
toolDisplay.updateToolGroup(true);
|
|
68
|
+
}
|
|
69
|
+
export function handleToolErrorPart(deps, part) {
|
|
70
|
+
const { loopState, callbacks, toolDisplay, setup, goal } = deps;
|
|
71
|
+
const toolCallId = part.toolCallId;
|
|
72
|
+
const toolName = part.toolName;
|
|
73
|
+
loopState.inFlightTools.delete(toolCallId);
|
|
74
|
+
const existing = loopState.latestToolCalls.get(toolCallId);
|
|
75
|
+
const toolCall = { toolCallId, toolName, input: part.input ?? existing?.input };
|
|
76
|
+
const startedAt = loopState.startedTools.get(toolCallId) ?? Date.now();
|
|
77
|
+
loopState.lastToolOk = false;
|
|
78
|
+
if (isMalformedToolInputError(part.error)) {
|
|
79
|
+
loopState.pendingMalformedToolName = toolName;
|
|
80
|
+
loopState.unresolvedMalformedToolName = toolName;
|
|
81
|
+
}
|
|
82
|
+
const finish = { toolCall, success: false, error: part.error, durationMs: Date.now() - startedAt };
|
|
83
|
+
const item = toolDisplay.ensureToolItem(toolCall);
|
|
84
|
+
item.status = 'error';
|
|
85
|
+
item.result = toolResultSummary(finish);
|
|
86
|
+
item.durationMs = finish.durationMs;
|
|
87
|
+
item.finishedAt = startedAt + finish.durationMs;
|
|
88
|
+
const publicError = setup.toolCategories.get(toolCall.toolName) === 'builtin' ? { error: part.error } : {};
|
|
89
|
+
callbacks.onEvent?.(agentEvent({ type: 'tool_end', id: toolCall.toolCallId, name: toolCall.toolName, success: false, errorCode: 'tool_execution_error', ...publicError, durationMs: finish.durationMs }));
|
|
90
|
+
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 } });
|
|
91
|
+
observeGoalToolEvent(goal, { ...toolCall, success: false, output: part.error });
|
|
92
|
+
callbacks.setWorkState?.(goal);
|
|
93
|
+
callbacks.setGoalStatus?.(formatGoalStatus(goal));
|
|
94
|
+
toolDisplay.updateToolGroup(true);
|
|
95
|
+
}
|
|
@@ -4,7 +4,7 @@ import { type AgentEventSink } from '../../core/agent/events.js';
|
|
|
4
4
|
import type { ImageAttachment } from '../../core/attachments/imageAttachments.js';
|
|
5
5
|
import { type BlessedPath } from '../../core/attachments/readBlessings.js';
|
|
6
6
|
import type { TurnCompletionEvidence } from '../../core/agent/completionController.js';
|
|
7
|
-
import type { ValidationOutcome, WorkTaskProgress, WorkState } from '../../core/agent/workState.js';
|
|
7
|
+
import type { RedEvidence, ValidationOutcome, WorkTaskProgress, WorkState } from '../../core/agent/workState.js';
|
|
8
8
|
import type { SubagentOverrides, TurnExecutionScope } from '../../llm/requestContext.js';
|
|
9
9
|
import type { PromptSession } from '../../llm/systemPrompt.js';
|
|
10
10
|
import type { ContextFile } from '../../config/contextFiles.js';
|
|
@@ -64,9 +64,12 @@ interface TurnGoalContext {
|
|
|
64
64
|
mutationCount: number;
|
|
65
65
|
validationOutcome: ValidationOutcome;
|
|
66
66
|
taskProgress?: WorkTaskProgress;
|
|
67
|
+
redEvidence?: RedEvidence;
|
|
67
68
|
};
|
|
68
69
|
/** Consecutive no-progress physical turns at goal level (diagnostics). */
|
|
69
70
|
noProgressCount: number;
|
|
71
|
+
/** Hash binding of the exact mission bytes (P1); rides every checkpoint downstream. */
|
|
72
|
+
requestHash?: string;
|
|
70
73
|
}
|
|
71
74
|
export interface TurnExecutionOptions {
|
|
72
75
|
ephemeralControl?: string;
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { agentEvent } from '../../core/agent/events.js';
|
|
2
|
-
import { createTurnExecutionState,
|
|
2
|
+
import { createTurnExecutionState, toCompletionEvidence } from '../../core/agent/completionController.js';
|
|
3
3
|
import { createSessionGoal } from '../../core/agent/goalPolicy.js';
|
|
4
4
|
import { seedCarriedGoalEvidence } from '../../core/agent/workState.js';
|
|
5
5
|
import { createToolExecutionBudget, mainTurnBudget, DEFAULT_TURN_DEADLINE_MS } from '../../core/agent/budgets.js';
|
|
@@ -10,7 +10,8 @@ import { abortForTurn, createUserAbortCause } from './streaming/abortCause.js';
|
|
|
10
10
|
import { runAgentAttempt } from './streaming/agentAttempt.js';
|
|
11
11
|
import { projectGoalEvidence } from './streaming/attemptOutcome.js';
|
|
12
12
|
import { awaitAttemptWithForcedSettlement, createAttemptCleanupRegistry, createQuarantinableCallbacks } from './streaming/attemptLifecycle.js';
|
|
13
|
-
import {
|
|
13
|
+
import { startRecoverySlice } from './streaming/recoverySlices.js';
|
|
14
|
+
import { formatIdleMinutes } from '../../utils/format.js';
|
|
14
15
|
export async function runAgentTurn(value, displayValue, contextFiles, callbacks, retryAttempt = 0, retryingExistingRequest = false, contextOverflowRecovered = false, session, modelOverride, turnOptions = {}) {
|
|
15
16
|
// The controller is replaced when an idle-stall retry needs a live signal
|
|
16
17
|
// after aborting a hung stream, so both it and the cause are mutable.
|
|
@@ -119,27 +120,11 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
|
|
|
119
120
|
continue;
|
|
120
121
|
}
|
|
121
122
|
// Bounded recovery slice (length-continuation, rescue, or goal
|
|
122
|
-
// continuation).
|
|
123
|
-
//
|
|
124
|
-
// progress-guarded and counts against the shared turn budget. Abort is
|
|
125
|
-
// re-checked before and within the slice.
|
|
123
|
+
// continuation); see recoverySlices.ts. Abort is re-checked before and
|
|
124
|
+
// within the slice.
|
|
126
125
|
if (result.recovery && !abortController.signal.aborted) {
|
|
127
|
-
|
|
128
|
-
if (rec.kind === 'length') {
|
|
129
|
-
turnState.lengthCreditUsed = true;
|
|
130
|
-
turnState.lengthRecoveriesAttempted += 1;
|
|
131
|
-
}
|
|
132
|
-
else if (rec.kind === 'rescue')
|
|
133
|
-
turnState.rescueUsed = true;
|
|
134
|
-
else
|
|
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;
|
|
140
|
-
activeOptions = { ...activeOptions, ephemeralControl: rec.control, recoverySlice: { kind: rec.kind, maxSteps: rec.slice.maxSteps, maxToolCalls: rec.slice.maxToolCalls } };
|
|
126
|
+
activeOptions = startRecoverySlice(result.recovery, { turnState, sliceBudget, options: activeOptions }, callbacks.debugLog);
|
|
141
127
|
retrying = true;
|
|
142
|
-
callbacks.debugLog(`starting ${rec.kind} recovery slice: ${rec.slice.maxSteps} steps / ${rec.slice.maxToolCalls} tool calls`);
|
|
143
128
|
continue;
|
|
144
129
|
}
|
|
145
130
|
break;
|