@denizokcu/haze 0.10.0 → 1.0.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 +100 -1
- package/README.md +77 -27
- package/SECURITY.md +22 -0
- package/bin/haze.js +102 -1
- package/dist/buildInfo.json +7 -0
- package/dist/cli/chat/TaskBar.d.ts +2 -1
- package/dist/cli/chat/TaskBar.js +7 -4
- package/dist/cli/chat/chatMetrics.d.ts +2 -2
- package/dist/cli/chat/chatMetrics.js +1 -1
- package/dist/cli/chat/contextReport.js +2 -0
- package/dist/cli/chat/fileMentionSuggestions.js +3 -2
- package/dist/cli/chat/inputSuggestions.d.ts +8 -16
- package/dist/cli/chat/inputSuggestions.js +9 -41
- package/dist/cli/chat/liveRegion.d.ts +25 -0
- package/dist/cli/chat/liveRegion.js +48 -0
- package/dist/cli/chat/messages.d.ts +33 -4
- package/dist/cli/chat/messages.js +218 -35
- package/dist/cli/chat/sessionLifecycle.d.ts +11 -1
- package/dist/cli/chat/sessionLifecycle.js +64 -14
- package/dist/cli/chat/sessionRecorder.js +75 -7
- package/dist/cli/chat/startupInfo.d.ts +0 -1
- package/dist/cli/chat/startupInfo.js +11 -15
- package/dist/cli/chat/turnState.d.ts +1 -1
- package/dist/cli/chat/wizardDispatch.d.ts +90 -28
- package/dist/cli/chat/wizardDispatch.js +349 -133
- package/dist/cli/commands/chat.d.ts +5 -0
- package/dist/cli/commands/chat.js +216 -172
- package/dist/cli/commands/chatModes.d.ts +8 -1
- package/dist/cli/commands/chatModes.js +9 -44
- package/dist/cli/commands/commands.d.ts +2 -0
- package/dist/cli/commands/commands.js +10 -5
- package/dist/cli/commands/doctor.d.ts +19 -0
- package/dist/cli/commands/doctor.js +76 -0
- package/dist/cli/commands/formatters.d.ts +3 -3
- package/dist/cli/commands/formatters.js +8 -25
- package/dist/cli/commands/ndjsonSink.d.ts +23 -0
- package/dist/cli/commands/ndjsonSink.js +38 -0
- package/dist/cli/commands/providerWizard.d.ts +9 -2
- package/dist/cli/commands/providerWizard.js +39 -7
- package/dist/cli/commands/runCommand.d.ts +3 -0
- package/dist/cli/commands/runCommand.js +117 -11
- package/dist/cli/commands/serverWizard.d.ts +34 -0
- package/dist/cli/commands/{mcpWizard.js → serverWizard.js} +44 -2
- 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 +25 -0
- package/dist/cli/commands/streaming/abortCause.js +16 -0
- package/dist/cli/commands/streaming/agentAttempt.d.ts +43 -0
- package/dist/cli/commands/streaming/agentAttempt.js +79 -0
- package/dist/cli/commands/streaming/assistantText.js +9 -2
- 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 +65 -0
- package/dist/cli/commands/streaming/goalCheckpoint.js +23 -0
- package/dist/cli/commands/streaming/goalSupervisor.d.ts +64 -0
- package/dist/cli/commands/streaming/goalSupervisor.js +130 -0
- 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 +16 -0
- package/dist/cli/commands/streaming/toolCallRecovery.js +80 -0
- package/dist/cli/commands/streaming/toolGroupRenderer.d.ts +31 -1
- package/dist/cli/commands/streaming/toolGroupRenderer.js +50 -4
- package/dist/cli/commands/streaming/toolResultState.d.ts +6 -1
- package/dist/cli/commands/streaming/toolResultState.js +29 -7
- package/dist/cli/commands/streaming/turnRuntime.d.ts +4 -0
- package/dist/cli/commands/streaming/turnRuntime.js +6 -0
- package/dist/cli/commands/streaming.d.ts +65 -9
- package/dist/cli/commands/streaming.js +133 -430
- package/dist/cli/commands/wizardFlow.d.ts +334 -0
- package/dist/cli/commands/wizardFlow.js +377 -0
- package/dist/cli/contextReport.js +3 -0
- package/dist/cli/index.js +68 -22
- package/dist/cli/terminalTitle.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 +36 -0
- package/dist/config/modelDiscovery.js +164 -1
- package/dist/config/privateStorage.js +28 -2
- package/dist/config/providerAuth.d.ts +14 -0
- package/dist/config/providerAuth.js +49 -0
- package/dist/config/providerPresets.d.ts +39 -7
- package/dist/config/providerPresets.js +371 -100
- package/dist/config/providers.js +2 -0
- package/dist/config/settings.d.ts +43 -0
- package/dist/config/settings.js +12 -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 +73 -1
- package/dist/core/agent/budgets.js +94 -1
- package/dist/core/agent/compaction.d.ts +38 -0
- package/dist/core/agent/compaction.js +92 -17
- package/dist/core/agent/completionController.d.ts +224 -0
- package/dist/core/agent/completionController.js +296 -0
- package/dist/core/agent/contextBudget.d.ts +36 -2
- package/dist/core/agent/contextBudget.js +62 -9
- package/dist/core/agent/errors.d.ts +0 -1
- package/dist/core/agent/errors.js +1 -1
- package/dist/core/agent/events.d.ts +78 -0
- package/dist/core/agent/goalPolicy.d.ts +47 -0
- package/dist/core/agent/goalPolicy.js +106 -0
- package/dist/core/agent/reasoningPolicy.d.ts +31 -0
- package/dist/core/agent/reasoningPolicy.js +27 -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 +27 -0
- package/dist/core/agent/toolCapabilities.js +58 -0
- package/dist/core/agent/toolOutputStore.d.ts +8 -0
- package/dist/core/agent/toolOutputStore.js +11 -11
- package/dist/core/agent/toolResults.d.ts +12 -0
- package/dist/core/agent/toolResults.js +38 -0
- package/dist/core/agent/turnPolicy.d.ts +11 -0
- package/dist/core/agent/turnPolicy.js +19 -0
- package/dist/core/agent/workState.d.ts +81 -3
- package/dist/core/agent/workState.js +176 -10
- package/dist/core/attachments/imageAttachments.js +90 -42
- package/dist/core/deadline.d.ts +27 -0
- package/dist/core/deadline.js +74 -0
- 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 +8 -1
- package/dist/core/persistence/orderedFileWriter.d.ts +10 -0
- package/dist/core/persistence/orderedFileWriter.js +16 -2
- package/dist/core/process/backgroundRegistry.d.ts +2 -3
- package/dist/core/process/backgroundRegistry.js +15 -10
- package/dist/core/process/runBoundedProcess.d.ts +8 -2
- package/dist/core/process/runBoundedProcess.js +15 -6
- package/dist/core/process/userShell.d.ts +16 -0
- package/dist/core/process/userShell.js +59 -0
- package/dist/core/safety/missingExecutable.d.ts +42 -0
- package/dist/core/safety/missingExecutable.js +77 -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 +38 -0
- package/dist/core/session/sessionStore.js +242 -59
- 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 +6 -14
- package/dist/core/subagent/contracts.js +4 -3
- package/dist/core/subagent/executionProfiles.js +2 -2
- package/dist/core/subagent/subagentCoordinator.d.ts +4 -0
- package/dist/core/subagent/subagentCoordinator.js +32 -2
- package/dist/core/subagent/subagentRunner.js +19 -40
- 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.d.ts +17 -1
- package/dist/llm/client.js +86 -14
- package/dist/llm/hazeTools.d.ts +693 -204
- package/dist/llm/hazeTools.js +110 -28
- 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 +5653 -33
- package/dist/llm/lspTools.js +152 -80
- package/dist/llm/openaiCodex.d.ts +1 -0
- package/dist/llm/openaiCodex.js +43 -0
- package/dist/llm/openaiCodexOAuth.d.ts +51 -0
- package/dist/llm/openaiCodexOAuth.js +217 -0
- package/dist/llm/requestContext.d.ts +7 -0
- package/dist/llm/requestContext.js +30 -4
- package/dist/llm/systemPrompt.d.ts +12 -0
- package/dist/llm/systemPrompt.js +24 -11
- package/dist/llm/toolResultTypes.d.ts +7 -14
- package/dist/llm/toolResultTypes.js +1 -4
- package/dist/llm/tools/editMatch.d.ts +14 -9
- package/dist/llm/tools/editMatch.js +73 -1
- package/dist/llm/tools/failures.d.ts +2 -0
- package/dist/llm/tools/failures.js +1 -0
- package/dist/llm/tools/fetchTool.d.ts +16 -0
- package/dist/llm/tools/fetchTool.js +1 -1
- package/dist/llm/tools/fileToolShared.d.ts +8 -5
- package/dist/llm/tools/fileToolShared.js +22 -23
- package/dist/llm/tools/gitIgnore.d.ts +42 -0
- package/dist/llm/tools/gitIgnore.js +247 -0
- 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 +8 -0
- package/dist/llm/tools/readRecovery.js +135 -0
- package/dist/llm/tools/{bashTool.d.ts → shellTool.d.ts} +171 -123
- package/dist/llm/tools/{bashTool.js → shellTool.js} +20 -14
- package/dist/llm/tools/toolContext.d.ts +1 -1
- package/dist/llm/tools/toolContext.js +66 -37
- package/dist/llm/tools/workspaceFile.d.ts +0 -1
- package/dist/llm/tools/workspaceFile.js +1 -6
- package/dist/llm/webFetch.d.ts +18 -1
- package/dist/llm/webFetch.js +64 -97
- 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/codeHighlight.d.ts +4 -0
- package/dist/ui/codeHighlight.js +31 -0
- package/dist/ui/components/Header.d.ts +1 -1
- package/dist/ui/components/MarkdownText.d.ts +16 -2
- package/dist/ui/components/MarkdownText.js +244 -34
- package/dist/ui/components/TextInput.d.ts +8 -1
- package/dist/ui/components/TextInput.js +6 -2
- package/dist/ui/theme.d.ts +4 -3
- package/dist/ui/theme.js +5 -4
- package/dist/utils/buildInfo.d.ts +97 -0
- package/dist/utils/buildInfo.js +244 -0
- package/dist/utils/fs.d.ts +11 -0
- package/dist/utils/fs.js +91 -26
- package/dist/utils/openPath.d.ts +2 -2
- package/dist/utils/openPath.js +19 -6
- package/dist/utils/path.d.ts +2 -1
- package/dist/utils/path.js +6 -2
- package/dist/utils/utf8.d.ts +22 -0
- package/dist/utils/utf8.js +54 -0
- package/dist/utils/version.d.ts +9 -3
- package/dist/utils/version.js +28 -2
- package/package.json +28 -21
- 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 -10
- package/dist/cli/commands/streaming/turnOutcome.js +0 -13
- package/dist/cli/commands/wizardActions.d.ts +0 -46
- package/dist/cli/commands/wizardActions.js +0 -46
- 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 -52
- package/dist/cli/commands/wizardSuggestions.d.ts +0 -31
- package/dist/cli/commands/wizardSuggestions.js +0 -188
- package/dist/cli/commands/wizardTransition.d.ts +0 -37
- package/dist/cli/commands/wizardTransition.js +0 -43
- 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.d.ts +0 -2
- package/dist/core/goal/completionPolicy.js +0 -7
- 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 -18
- package/dist/core/limits/byteBudgets.js +0 -18
- package/dist/core/limits/textBudgets.d.ts +0 -23
- package/dist/core/limits/textBudgets.js +0 -23
- package/dist/core/safety/bashClassifier.d.ts +0 -10
- package/dist/llm/lsp.d.ts +0 -129
- package/dist/llm/lsp.js +0 -307
- 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
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import { type SessionGoal } from '../../../core/agent/goalPolicy.js';
|
|
2
|
+
import { type TurnExecutionState } from '../../../core/agent/completionController.js';
|
|
3
|
+
import { type ToolExecutionBudgetState, type TurnBudget } from '../../../core/agent/budgets.js';
|
|
4
|
+
import type { StreamCallbacks, TurnExecutionOptions } from '../streaming.js';
|
|
5
|
+
import { type NativeToolCall, type ToolGroupRenderer } from './toolGroupRenderer.js';
|
|
6
|
+
import { type ToolResultState } from './toolResultState.js';
|
|
7
|
+
import type { AttemptSalvage, StreamStallGuard } from './stallRecovery.js';
|
|
8
|
+
import type { AttemptSetup } from './attemptSetup.js';
|
|
9
|
+
import type { ContextFile } from '../../../config/contextFiles.js';
|
|
10
|
+
/**
|
|
11
|
+
* Mutable per-attempt loop state. Created before the stall guard so its
|
|
12
|
+
* `classifyEmission` can read what the stalled step emitted, and consumed by
|
|
13
|
+
* the stream part handlers, `prepareStep`, and the attempt outcome.
|
|
14
|
+
*/
|
|
15
|
+
export interface AttemptLoopState {
|
|
16
|
+
/** Cumulative assistant text across all segments of this attempt. */
|
|
17
|
+
assistantText: string;
|
|
18
|
+
currentAssistantText: string;
|
|
19
|
+
assistantStarted: boolean;
|
|
20
|
+
currentAssistantId: string;
|
|
21
|
+
assistantStartedAt: number;
|
|
22
|
+
streamError: unknown;
|
|
23
|
+
streamFinished: boolean;
|
|
24
|
+
finishReason: string | undefined;
|
|
25
|
+
lastToolOk: boolean | undefined;
|
|
26
|
+
pendingMalformedToolName: string | undefined;
|
|
27
|
+
unresolvedMalformedToolName: string | undefined;
|
|
28
|
+
/** Per-attempt (not per-turn) recovery counter: a transient retry gets a fresh map. Bounded across the whole turn by MAIN_TOOL_CALL_LIMIT. */
|
|
29
|
+
malformedRecoveryAttempts: Map<string, number>;
|
|
30
|
+
toolResultState: ToolResultState;
|
|
31
|
+
/** Tool calls currently executing; a busy tool wave defers the idle timer. */
|
|
32
|
+
inFlightTools: Set<string>;
|
|
33
|
+
startedTools: Map<string, number>;
|
|
34
|
+
latestToolCalls: Map<string, NativeToolCall>;
|
|
35
|
+
/** Normalized assistant texts already shown this session (duplicate suppression). */
|
|
36
|
+
visibleAssistantTexts: Set<string>;
|
|
37
|
+
rememberVisibleAssistantText: (text: string) => void;
|
|
38
|
+
/** Context files active for this attempt; grows when tool outputs surface scoped instructions. */
|
|
39
|
+
contextFiles: ContextFile[];
|
|
40
|
+
}
|
|
41
|
+
export declare function createAttemptLoopState(previousAssistantText: string, contextFiles: ContextFile[], callbacks: Pick<StreamCallbacks, 'setLastAssistantText'>): AttemptLoopState;
|
|
42
|
+
/** What the completed stream tells the attempt outcome (classification evidence). */
|
|
43
|
+
export interface AttemptStreamOutcome {
|
|
44
|
+
finishReason: string | undefined;
|
|
45
|
+
lastToolOk: boolean | undefined;
|
|
46
|
+
assistantText: string;
|
|
47
|
+
sawToolCall: boolean;
|
|
48
|
+
unresolvedMalformedToolName: string | undefined;
|
|
49
|
+
unresolvedToolInputError: boolean;
|
|
50
|
+
}
|
|
51
|
+
export interface AttemptStreamDeps {
|
|
52
|
+
setup: AttemptSetup;
|
|
53
|
+
callbacks: StreamCallbacks;
|
|
54
|
+
abortController: AbortController;
|
|
55
|
+
retryAttempt: number;
|
|
56
|
+
recoverySlice: TurnExecutionOptions['recoverySlice'];
|
|
57
|
+
turnState: TurnExecutionState;
|
|
58
|
+
turnBudget: TurnBudget;
|
|
59
|
+
globalBudget: ToolExecutionBudgetState;
|
|
60
|
+
goal: SessionGoal;
|
|
61
|
+
stallGuard: StreamStallGuard;
|
|
62
|
+
loopState: AttemptLoopState;
|
|
63
|
+
toolDisplay: ToolGroupRenderer;
|
|
64
|
+
salvage: AttemptSalvage;
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* Drive one attempt's `ToolLoopAgent` stream: construct the agent (repair,
|
|
68
|
+
* prepareStep, step observers), consume every stream part, and commit the
|
|
69
|
+
* completed conversation. Throws the stream error so the attempt orchestrator
|
|
70
|
+
* classifies failures (abort cause, retry pool, recovery) in one place.
|
|
71
|
+
*/
|
|
72
|
+
export declare function runAttemptStream(deps: AttemptStreamDeps): Promise<AttemptStreamOutcome>;
|
|
@@ -0,0 +1,448 @@
|
|
|
1
|
+
import { ToolLoopAgent, isStepCount } from 'ai';
|
|
2
|
+
import { agentEvent } from '../../../core/agent/events.js';
|
|
3
|
+
import { malformedToolCallPrompt, repeatedToolCallPrompt, toolLoopBudgetPrompt, formatGoalStatus, observeGoalToolEvent } from '../../../core/agent/goalPolicy.js';
|
|
4
|
+
import { estimateMessagesTokens, estimateValueTokens } from '../../../core/agent/contextBudget.js';
|
|
5
|
+
import { compactToolHistory, stripSyntheticControls, withSyntheticControl } from '../../../core/agent/requestAssembly.js';
|
|
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';
|
|
13
|
+
import { toolsContextFor } from '../../../llm/tools/toolContext.js';
|
|
14
|
+
import { busyToolLabel, toolCallSummary, toolResultSummary } from '../formatters.js';
|
|
15
|
+
import { sanitizeAssistantText, assistantDisplayText, normalizeAssistantText, shouldStartAssistantStream, isHiddenAssistantFragment, isHiddenUnstartedFinalText, isShortLeadInBeforeTool, isShortUnfinishedLeadIn } from './assistantText.js';
|
|
16
|
+
import { toolDiffFromResult } from './toolGroupRenderer.js';
|
|
17
|
+
import { applyStepToolResultState, initialToolResultState } from './toolResultState.js';
|
|
18
|
+
import { clampOutOfBoundsToolNumbers, isMalformedToolInputError } from './toolCallRecovery.js';
|
|
19
|
+
import { extractUsage, logEntry, rememberContextFilesFromToolOutput, responseCompletionMetrics, stepCacheMetrics, subagentTokenEstimate } from './turnRuntime.js';
|
|
20
|
+
export function createAttemptLoopState(previousAssistantText, contextFiles, callbacks) {
|
|
21
|
+
const visibleAssistantTexts = new Set(previousAssistantText ? [previousAssistantText] : []);
|
|
22
|
+
return {
|
|
23
|
+
assistantText: '',
|
|
24
|
+
currentAssistantText: '',
|
|
25
|
+
assistantStarted: false,
|
|
26
|
+
currentAssistantId: `assistant-${Date.now()}`,
|
|
27
|
+
assistantStartedAt: Date.now(),
|
|
28
|
+
streamError: undefined,
|
|
29
|
+
streamFinished: false,
|
|
30
|
+
finishReason: undefined,
|
|
31
|
+
lastToolOk: undefined,
|
|
32
|
+
pendingMalformedToolName: undefined,
|
|
33
|
+
unresolvedMalformedToolName: undefined,
|
|
34
|
+
malformedRecoveryAttempts: new Map(),
|
|
35
|
+
toolResultState: initialToolResultState(),
|
|
36
|
+
inFlightTools: new Set(),
|
|
37
|
+
startedTools: new Map(),
|
|
38
|
+
latestToolCalls: new Map(),
|
|
39
|
+
visibleAssistantTexts,
|
|
40
|
+
rememberVisibleAssistantText: (text) => {
|
|
41
|
+
const normalized = normalizeAssistantText(text);
|
|
42
|
+
if (!normalized)
|
|
43
|
+
return;
|
|
44
|
+
visibleAssistantTexts.add(normalized);
|
|
45
|
+
callbacks.setLastAssistantText(text);
|
|
46
|
+
},
|
|
47
|
+
contextFiles,
|
|
48
|
+
};
|
|
49
|
+
}
|
|
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
|
+
function applyStreamPart(deps, part) {
|
|
266
|
+
const { loopState, callbacks, toolDisplay, setup } = deps;
|
|
267
|
+
switch (part.type) {
|
|
268
|
+
case 'text-delta': {
|
|
269
|
+
callbacks.setBusyLabel?.(setup.thinkingLabel);
|
|
270
|
+
toolDisplay.startFreshToolGroup();
|
|
271
|
+
const delta = sanitizeAssistantText(part.text);
|
|
272
|
+
loopState.assistantText += delta;
|
|
273
|
+
loopState.currentAssistantText += delta;
|
|
274
|
+
const displayText = assistantDisplayText(loopState.currentAssistantText);
|
|
275
|
+
if (!loopState.assistantStarted && !shouldStartAssistantStream(displayText, loopState.assistantStartedAt))
|
|
276
|
+
break;
|
|
277
|
+
if (!loopState.assistantStarted) {
|
|
278
|
+
loopState.assistantStarted = true;
|
|
279
|
+
loopState.assistantStartedAt = Date.now();
|
|
280
|
+
callbacks.onEvent?.(agentEvent({ type: 'message_start', id: loopState.currentAssistantId, role: 'assistant' }));
|
|
281
|
+
callbacks.addMessage({ id: loopState.currentAssistantId, role: 'assistant', text: displayText, streaming: true, startedAt: loopState.assistantStartedAt });
|
|
282
|
+
}
|
|
283
|
+
else {
|
|
284
|
+
callbacks.onEvent?.(agentEvent({ type: 'message_update', id: loopState.currentAssistantId, text: displayText }));
|
|
285
|
+
callbacks.updateMessage(loopState.currentAssistantId, { text: displayText });
|
|
286
|
+
}
|
|
287
|
+
break;
|
|
288
|
+
}
|
|
289
|
+
case 'tool-input-start': {
|
|
290
|
+
finalizePendingAssistantBeforeTool(deps);
|
|
291
|
+
const toolCall = { toolCallId: part.id, toolName: part.toolName, input: {} };
|
|
292
|
+
loopState.latestToolCalls.set(part.id, toolCall);
|
|
293
|
+
loopState.inFlightTools.add(part.id);
|
|
294
|
+
callbacks.setBusyLabel?.(busyToolLabel(part.toolName, {}));
|
|
295
|
+
toolDisplay.ensureToolItem(toolCall);
|
|
296
|
+
break;
|
|
297
|
+
}
|
|
298
|
+
case 'tool-call': {
|
|
299
|
+
finalizePendingAssistantBeforeTool(deps);
|
|
300
|
+
const toolCall = { toolCallId: part.toolCallId, toolName: part.toolName, input: part.input };
|
|
301
|
+
loopState.latestToolCalls.set(part.toolCallId, toolCall);
|
|
302
|
+
// Tool execution begins only after its complete input has parsed and validated.
|
|
303
|
+
loopState.startedTools.set(part.toolCallId, Date.now());
|
|
304
|
+
callbacks.setBusyLabel?.(busyToolLabel(part.toolName, part.input));
|
|
305
|
+
toolDisplay.ensureToolItem(toolCall).summary = toolCallSummary(part.toolName, part.input);
|
|
306
|
+
toolDisplay.updateToolGroup(true);
|
|
307
|
+
break;
|
|
308
|
+
}
|
|
309
|
+
case 'tool-result': {
|
|
310
|
+
handleToolResultPart(deps, part);
|
|
311
|
+
break;
|
|
312
|
+
}
|
|
313
|
+
case 'tool-error': {
|
|
314
|
+
handleToolErrorPart(deps, part);
|
|
315
|
+
break;
|
|
316
|
+
}
|
|
317
|
+
case 'error':
|
|
318
|
+
loopState.streamError = part.error;
|
|
319
|
+
callbacks.debugLog(`stream error: ${part.error instanceof Error ? part.error.message : String(part.error)}`);
|
|
320
|
+
break;
|
|
321
|
+
case 'finish':
|
|
322
|
+
loopState.streamFinished = true;
|
|
323
|
+
loopState.finishReason = part.finishReason;
|
|
324
|
+
callbacks.debugLog(`ToolLoopAgent finished: ${part.finishReason}`);
|
|
325
|
+
break;
|
|
326
|
+
default:
|
|
327
|
+
break;
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
/** Await the agent's response messages and commit the completed conversation; salvage to the last completed step on a post-stream failure. */
|
|
331
|
+
async function commitStreamResult(deps, result) {
|
|
332
|
+
const { loopState, callbacks, salvage } = deps;
|
|
333
|
+
if (loopState.streamError && !loopState.streamFinished) {
|
|
334
|
+
void Promise.resolve(result.responseMessages).catch(() => undefined);
|
|
335
|
+
throw loopState.streamError;
|
|
336
|
+
}
|
|
337
|
+
try {
|
|
338
|
+
const responseMessages = await result.responseMessages;
|
|
339
|
+
const completedConversation = [...stripSyntheticControls(salvage.requestMessages), ...responseMessages];
|
|
340
|
+
callbacks.setConversation(compactToolHistory(completedConversation).messages);
|
|
341
|
+
}
|
|
342
|
+
catch (error) {
|
|
343
|
+
if (salvage.accumulated.length > 0) {
|
|
344
|
+
callbacks.setConversation(compactToolHistory([...stripSyntheticControls(salvage.requestMessages), ...salvage.accumulated]).messages);
|
|
345
|
+
}
|
|
346
|
+
const text = error instanceof Error ? error.message : String(error);
|
|
347
|
+
const benignTerminatedAfterStream = text === 'terminated' && (loopState.streamFinished || loopState.assistantText.trim().length > 0 || loopState.latestToolCalls.size > 0);
|
|
348
|
+
if (!benignTerminatedAfterStream)
|
|
349
|
+
throw loopState.streamError ?? error;
|
|
350
|
+
callbacks.debugLog(`ignored post-stream response error: ${text}`);
|
|
351
|
+
}
|
|
352
|
+
if (loopState.currentAssistantText.trim().length > 0 || loopState.assistantStarted) {
|
|
353
|
+
finalizeAssistantSegment(loopState, callbacks);
|
|
354
|
+
}
|
|
355
|
+
else if (loopState.latestToolCalls.size > 0) {
|
|
356
|
+
callbacks.addMessage({ role: 'system', text: 'Tool work ended without a substantive final answer.' });
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
/**
|
|
360
|
+
* Drive one attempt's `ToolLoopAgent` stream: construct the agent (repair,
|
|
361
|
+
* prepareStep, step observers), consume every stream part, and commit the
|
|
362
|
+
* completed conversation. Throws the stream error so the attempt orchestrator
|
|
363
|
+
* classifies failures (abort cause, retry pool, recovery) in one place.
|
|
364
|
+
*/
|
|
365
|
+
export async function runAttemptStream(deps) {
|
|
366
|
+
const { setup, callbacks, loopState, turnState, globalBudget, stallGuard, salvage, retryAttempt, abortController } = deps;
|
|
367
|
+
const { sliceTools, stepCap, systemPrompt, inputBreakdown, providerSettings, omitMaxOutputTokens, toolExecutionContext, requestMessages } = setup;
|
|
368
|
+
const agent = new ToolLoopAgent({
|
|
369
|
+
id: 'haze-main',
|
|
370
|
+
model: setup.runtime.model,
|
|
371
|
+
instructions: systemPrompt,
|
|
372
|
+
tools: sliceTools,
|
|
373
|
+
...(!omitMaxOutputTokens ? { maxOutputTokens: DEFAULT_MAX_OUTPUT_TOKENS } : {}),
|
|
374
|
+
...providerSettings,
|
|
375
|
+
stopWhen: isStepCount(stepCap),
|
|
376
|
+
runtimeContext: toolExecutionContext,
|
|
377
|
+
toolsContext: toolsContextFor(sliceTools, toolExecutionContext),
|
|
378
|
+
experimental_repairToolCall: createRepairToolCall(deps),
|
|
379
|
+
prepareStep: createPrepareStep(deps),
|
|
380
|
+
onStepStart({ stepNumber }) {
|
|
381
|
+
callbacks.onEvent?.(agentEvent({ type: 'step_start', attempt: retryAttempt + 1, step: stepNumber + 1 }));
|
|
382
|
+
},
|
|
383
|
+
onStepEnd({ stepNumber, text, content = [], toolCalls, toolResults, finishReason, usage, response }) {
|
|
384
|
+
// Tool-loop control must advance from this internal callback, which the
|
|
385
|
+
// SDK awaits before prepareStep. Updating it from the public stream can
|
|
386
|
+
// lag behind fast providers and leave the next request read-only.
|
|
387
|
+
loopState.toolResultState = applyStepToolResultState(loopState.toolResultState, content);
|
|
388
|
+
// Turn-wide counters (shared across provider retries and recovery
|
|
389
|
+
// slices) so the global budget cannot reset between attempts. The
|
|
390
|
+
// execution-boundary budget (RH-003) is the authoritative count of
|
|
391
|
+
// underlying executions; sync the turn state to it so blocked calls are
|
|
392
|
+
// not double-counted and recovery math stays consistent.
|
|
393
|
+
turnState.stepsUsed += 1;
|
|
394
|
+
turnState.toolCallsUsed = globalBudget.started;
|
|
395
|
+
if (toolCalls.length > 0 && text.trim().length === 0)
|
|
396
|
+
turnState.toolOnlyStepsUsed += 1;
|
|
397
|
+
if (Array.isArray(response?.messages) && response.messages.length > 0)
|
|
398
|
+
salvage.accumulated = response.messages;
|
|
399
|
+
const stepUsage = stepCacheMetrics(usage);
|
|
400
|
+
const publicUsage = {
|
|
401
|
+
inputTokens: stepUsage.inputTokens ?? 0,
|
|
402
|
+
outputTokens: usage?.outputTokens ?? 0,
|
|
403
|
+
cacheReadTokens: stepUsage.cacheReadTokens,
|
|
404
|
+
cacheWriteTokens: stepUsage.cacheWriteTokens,
|
|
405
|
+
reasoningTokens: stepUsage.reasoningTokens,
|
|
406
|
+
};
|
|
407
|
+
callbacks.onEvent?.(agentEvent({ type: 'step_end', attempt: retryAttempt + 1, step: stepNumber + 1, finishReason, toolCallCount: toolCalls.length, usage: publicUsage, ...(response?.modelId ? { responseModel: response.modelId } : {}) }));
|
|
408
|
+
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 } });
|
|
409
|
+
callbacks.debugLog(`step ${stepNumber} finished: ${finishReason}; text=${text.length}; toolCalls=${toolCalls.length}; toolResults=${toolResults.length}`);
|
|
410
|
+
},
|
|
411
|
+
onEnd(event) {
|
|
412
|
+
const providerUsage = extractUsage({ usage: event.usage });
|
|
413
|
+
callbacks.recordTokenUsage?.({
|
|
414
|
+
inputTokens: providerUsage.inputTokens,
|
|
415
|
+
outputTokens: providerUsage.outputTokens,
|
|
416
|
+
systemPrompt: inputBreakdown.systemPrompt,
|
|
417
|
+
messages: inputBreakdown.messages,
|
|
418
|
+
toolSchemas: inputBreakdown.toolSchemas,
|
|
419
|
+
outputEstimate: estimateValueTokens(event.responseMessages),
|
|
420
|
+
cacheReadTokens: providerUsage.cacheReadTokens,
|
|
421
|
+
cacheWriteTokens: providerUsage.cacheWriteTokens,
|
|
422
|
+
noCacheTokens: providerUsage.noCacheTokens,
|
|
423
|
+
reasoningTokens: providerUsage.reasoningTokens,
|
|
424
|
+
logicalInputEstimate: inputBreakdown.logicalInputEstimate,
|
|
425
|
+
effectiveNonCachedInput: providerUsage.effectiveNonCachedInput,
|
|
426
|
+
});
|
|
427
|
+
const accumulated = [...stripSyntheticControls(requestMessages), ...event.responseMessages];
|
|
428
|
+
const compacted = compactToolHistory(accumulated);
|
|
429
|
+
callbacks.setConversation(compacted.messages);
|
|
430
|
+
callbacks.debugLog(`conversation updated to ${compacted.messages.length} messages by ToolLoopAgent`);
|
|
431
|
+
},
|
|
432
|
+
});
|
|
433
|
+
stallGuard.rearm();
|
|
434
|
+
const result = await agent.stream({ messages: requestMessages, abortSignal: abortController.signal });
|
|
435
|
+
for await (const part of result.stream) {
|
|
436
|
+
stallGuard.noteStreamEvent(part.type);
|
|
437
|
+
applyStreamPart(deps, part);
|
|
438
|
+
}
|
|
439
|
+
await commitStreamResult(deps, result);
|
|
440
|
+
return {
|
|
441
|
+
finishReason: loopState.finishReason,
|
|
442
|
+
lastToolOk: loopState.lastToolOk,
|
|
443
|
+
assistantText: loopState.assistantText,
|
|
444
|
+
sawToolCall: loopState.latestToolCalls.size > 0,
|
|
445
|
+
unresolvedMalformedToolName: loopState.unresolvedMalformedToolName,
|
|
446
|
+
unresolvedToolInputError: loopState.unresolvedMalformedToolName != null,
|
|
447
|
+
};
|
|
448
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/** Resolves a tool's public JSON Schema, as provided by the AI SDK repair hook. */
|
|
2
|
+
export type ToolInputSchemaResolver = (options: {
|
|
3
|
+
toolName: string;
|
|
4
|
+
}) => PromiseLike<unknown>;
|
|
5
|
+
/**
|
|
6
|
+
* Clamps top-level numeric arguments that exceed a tool schema's declared
|
|
7
|
+
* inclusive bounds (for example grep's maxMatches: 9999 against maximum: 200).
|
|
8
|
+
* Small local models frequently invent out-of-range values; clamping keeps the
|
|
9
|
+
* call executable without a model round-trip. Returns the repaired input
|
|
10
|
+
* object, or null when the input is not a JSON object or nothing is out of
|
|
11
|
+
* range. Exclusive bounds, nested objects, and non-numeric fields are left
|
|
12
|
+
* untouched so genuinely malformed input still takes the forced-retry path.
|
|
13
|
+
*/
|
|
14
|
+
export declare function clampOutOfBoundsToolNumbers(input: unknown, toolName: string, resolveSchema: ToolInputSchemaResolver): Promise<Record<string, unknown> | null>;
|
|
15
|
+
/** Identifies tool-input failures that are safe to send back to the model for a smaller retry. */
|
|
16
|
+
export declare function isMalformedToolInputError(error: unknown): boolean;
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
function errorFragments(error, depth = 0) {
|
|
2
|
+
if (depth > 4 || error == null)
|
|
3
|
+
return [];
|
|
4
|
+
if (typeof error === 'string')
|
|
5
|
+
return [error];
|
|
6
|
+
if (error instanceof Error) {
|
|
7
|
+
const cause = 'cause' in error ? error.cause : undefined;
|
|
8
|
+
return [error.name, error.message, ...errorFragments(cause, depth + 1)];
|
|
9
|
+
}
|
|
10
|
+
if (typeof error !== 'object')
|
|
11
|
+
return [String(error)];
|
|
12
|
+
const record = error;
|
|
13
|
+
return [
|
|
14
|
+
...errorFragments(record.name, depth + 1),
|
|
15
|
+
...errorFragments(record.message, depth + 1),
|
|
16
|
+
...errorFragments(record.cause, depth + 1),
|
|
17
|
+
...errorFragments(record.error, depth + 1),
|
|
18
|
+
];
|
|
19
|
+
}
|
|
20
|
+
function numericBoundsFor(schema, key) {
|
|
21
|
+
const properties = schema?.properties;
|
|
22
|
+
const property = properties?.[key];
|
|
23
|
+
if (property == null)
|
|
24
|
+
return {};
|
|
25
|
+
const { maximum, minimum } = property;
|
|
26
|
+
return {
|
|
27
|
+
maximum: typeof maximum === 'number' ? maximum : undefined,
|
|
28
|
+
minimum: typeof minimum === 'number' ? minimum : undefined,
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Clamps top-level numeric arguments that exceed a tool schema's declared
|
|
33
|
+
* inclusive bounds (for example grep's maxMatches: 9999 against maximum: 200).
|
|
34
|
+
* Small local models frequently invent out-of-range values; clamping keeps the
|
|
35
|
+
* call executable without a model round-trip. Returns the repaired input
|
|
36
|
+
* object, or null when the input is not a JSON object or nothing is out of
|
|
37
|
+
* range. Exclusive bounds, nested objects, and non-numeric fields are left
|
|
38
|
+
* untouched so genuinely malformed input still takes the forced-retry path.
|
|
39
|
+
*/
|
|
40
|
+
export async function clampOutOfBoundsToolNumbers(input, toolName, resolveSchema) {
|
|
41
|
+
let value = input;
|
|
42
|
+
if (typeof value === 'string') {
|
|
43
|
+
try {
|
|
44
|
+
value = JSON.parse(value);
|
|
45
|
+
}
|
|
46
|
+
catch {
|
|
47
|
+
return null;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
if (value == null || typeof value !== 'object' || Array.isArray(value))
|
|
51
|
+
return null;
|
|
52
|
+
let schema;
|
|
53
|
+
try {
|
|
54
|
+
schema = await resolveSchema({ toolName });
|
|
55
|
+
}
|
|
56
|
+
catch {
|
|
57
|
+
return null;
|
|
58
|
+
}
|
|
59
|
+
const repaired = { ...value };
|
|
60
|
+
let changed = false;
|
|
61
|
+
for (const [key, entry] of Object.entries(repaired)) {
|
|
62
|
+
if (typeof entry !== 'number' || !Number.isFinite(entry))
|
|
63
|
+
continue;
|
|
64
|
+
const { maximum, minimum } = numericBoundsFor(schema, key);
|
|
65
|
+
if (maximum !== undefined && entry > maximum) {
|
|
66
|
+
repaired[key] = maximum;
|
|
67
|
+
changed = true;
|
|
68
|
+
}
|
|
69
|
+
else if (minimum !== undefined && entry < minimum) {
|
|
70
|
+
repaired[key] = minimum;
|
|
71
|
+
changed = true;
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
return changed ? repaired : null;
|
|
75
|
+
}
|
|
76
|
+
/** Identifies tool-input failures that are safe to send back to the model for a smaller retry. */
|
|
77
|
+
export function isMalformedToolInputError(error) {
|
|
78
|
+
const text = errorFragments(error).join(' ');
|
|
79
|
+
return /AI_(?:JSONParse|InvalidToolInput)Error|JSON parsing failed|Invalid input for tool|invalid tool input/i.test(text);
|
|
80
|
+
}
|