@denizokcu/haze 1.1.1 → 1.4.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 +78 -0
- package/README.md +26 -15
- package/SECURITY.md +1 -1
- package/bin/haze.js +27 -7
- package/dist/buildInfo.json +3 -3
- package/dist/cli/chat/inputSuggestions.js +3 -0
- package/dist/cli/chat/liveMessages.d.ts +36 -0
- package/dist/cli/chat/liveMessages.js +64 -0
- package/dist/cli/chat/sessionLifecycle.d.ts +2 -1
- package/dist/cli/chat/sessionLifecycle.js +25 -2
- package/dist/cli/chat/sessionRecorder.d.ts +7 -0
- package/dist/cli/chat/sessionRecorder.js +6 -0
- package/dist/cli/chat/wizard/sessionThemeHandlers.d.ts +1 -1
- package/dist/cli/chat/wizard/sessionThemeHandlers.js +16 -1
- package/dist/cli/commands/chat.js +63 -36
- package/dist/cli/commands/commandHelp.js +2 -0
- package/dist/cli/commands/commands.js +2 -0
- package/dist/cli/commands/formatters.js +5 -1
- package/dist/cli/commands/ndjsonSink.d.ts +12 -0
- package/dist/cli/commands/ndjsonSink.js +29 -0
- package/dist/cli/commands/reasoningCommand.d.ts +35 -0
- package/dist/cli/commands/reasoningCommand.js +46 -0
- package/dist/cli/commands/runCommand.d.ts +14 -0
- package/dist/cli/commands/runCommand.js +43 -11
- package/dist/cli/commands/settingsSummary.js +2 -0
- package/dist/cli/commands/streaming/agentAttempt.d.ts +14 -1
- package/dist/cli/commands/streaming/agentAttempt.js +9 -5
- package/dist/cli/commands/streaming/assistantSegments.d.ts +0 -7
- package/dist/cli/commands/streaming/assistantSegments.js +1 -1
- package/dist/cli/commands/streaming/attemptLifecycle.js +13 -9
- package/dist/cli/commands/streaming/attemptOutcome.d.ts +23 -3
- package/dist/cli/commands/streaming/attemptOutcome.js +64 -11
- package/dist/cli/commands/streaming/attemptSetup.d.ts +13 -3
- package/dist/cli/commands/streaming/attemptSetup.js +40 -15
- package/dist/cli/commands/streaming/goalCheckpoint.d.ts +6 -0
- package/dist/cli/commands/streaming/goalCheckpoint.js +1 -0
- package/dist/cli/commands/streaming/goalSupervisor.d.ts +6 -1
- package/dist/cli/commands/streaming/goalSupervisor.js +18 -4
- package/dist/cli/commands/streaming/prepareStep.d.ts +6 -4
- package/dist/cli/commands/streaming/prepareStep.js +43 -22
- package/dist/cli/commands/streaming/stallRecovery.js +2 -2
- package/dist/cli/commands/streaming/streamLoop.d.ts +31 -4
- package/dist/cli/commands/streaming/streamLoop.js +280 -44
- package/dist/cli/commands/streaming/toolPartHandlers.js +13 -0
- package/dist/cli/commands/streaming/turnRuntime.d.ts +1 -1
- package/dist/cli/commands/streaming/turnRuntime.js +3 -2
- package/dist/cli/commands/streaming.d.ts +15 -2
- package/dist/cli/commands/streaming.js +37 -8
- package/dist/cli/commands/wizardFlow.d.ts +7 -0
- package/dist/cli/commands/wizardFlow.js +22 -0
- package/dist/cli/index.js +8 -3
- package/dist/config/modelCatalog.d.ts +32 -0
- package/dist/config/modelCatalog.js +84 -0
- package/dist/config/modelDiscovery.js +68 -5
- package/dist/config/settings.d.ts +18 -6
- package/dist/config/settings.js +11 -1
- package/dist/core/agent/budgets.d.ts +10 -2
- package/dist/core/agent/budgets.js +10 -2
- package/dist/core/agent/compaction.d.ts +42 -3
- package/dist/core/agent/compaction.js +53 -5
- package/dist/core/agent/completionController.d.ts +11 -1
- package/dist/core/agent/completionController.js +33 -0
- package/dist/core/agent/contextBudget.d.ts +56 -0
- package/dist/core/agent/contextBudget.js +53 -0
- package/dist/core/agent/errors.js +2 -2
- package/dist/core/agent/events.d.ts +26 -2
- package/dist/core/agent/goalPolicy.d.ts +7 -0
- package/dist/core/agent/goalPolicy.js +9 -0
- package/dist/core/agent/overflow.d.ts +45 -0
- package/dist/core/agent/overflow.js +91 -0
- package/dist/core/agent/reasoningPolicy.d.ts +45 -9
- package/dist/core/agent/reasoningPolicy.js +49 -9
- package/dist/core/agent/requestAssembly.d.ts +7 -0
- package/dist/core/agent/requestAssembly.js +15 -7
- package/dist/core/agent/toolCapabilities.d.ts +3 -3
- package/dist/core/agent/toolCapabilities.js +31 -7
- package/dist/core/agent/workState.d.ts +6 -4
- package/dist/core/agent/workState.js +53 -29
- package/dist/core/deadline.js +22 -24
- package/dist/core/safety/secretPaths.js +10 -7
- package/dist/core/safety/shellClassifier.d.ts +18 -0
- package/dist/core/safety/shellClassifier.js +39 -0
- package/dist/core/session/sessionSlimming.d.ts +2 -0
- package/dist/core/session/sessionSlimming.js +50 -1
- package/dist/core/session/sessionStore.d.ts +14 -8
- package/dist/core/session/sessionStore.js +59 -32
- package/dist/core/shellOutput/reducers/git.js +7 -2
- package/dist/core/shellOutput/reducers/validation.d.ts +1 -1
- package/dist/core/shellOutput/reducers/validation.js +14 -1
- package/dist/core/shellOutput/registry.js +3 -2
- package/dist/core/subagent/contracts.d.ts +8 -1
- package/dist/core/subagent/subagentRunner.d.ts +4 -0
- package/dist/core/subagent/subagentRunner.js +33 -25
- package/dist/core/tasks/taskStorage.js +8 -1
- package/dist/core/validation/outputParser.d.ts +1 -1
- package/dist/core/validation/outputParser.js +30 -1
- package/dist/llm/client.d.ts +4 -3
- package/dist/llm/client.js +34 -16
- package/dist/llm/hazeTools.d.ts +2039 -16
- package/dist/llm/hazeTools.js +43 -2
- package/dist/llm/lsp/client.d.ts +7 -1
- package/dist/llm/lsp/client.js +58 -9
- package/dist/llm/lsp/pool.d.ts +11 -0
- package/dist/llm/lsp/pool.js +61 -4
- package/dist/llm/lsp/protocol.d.ts +6 -23
- package/dist/llm/lsp/requests.d.ts +54 -60
- package/dist/llm/lsp/requests.js +152 -28
- package/dist/llm/lsp/symbols.d.ts +16 -0
- package/dist/llm/lsp/symbols.js +70 -0
- package/dist/llm/lsp/workspaceEdit.d.ts +43 -0
- package/dist/llm/lsp/workspaceEdit.js +117 -0
- package/dist/llm/lspTools.d.ts +7518 -2859
- package/dist/llm/lspTools.js +195 -110
- package/dist/llm/requestContext.d.ts +3 -2
- package/dist/llm/requestContext.js +8 -4
- package/dist/llm/systemPrompt.js +2 -2
- package/dist/llm/tools/fetchTool.d.ts +4 -0
- package/dist/llm/tools/processTool.d.ts +4 -0
- package/dist/llm/tools/replaceInFiles.d.ts +105 -0
- package/dist/llm/tools/replaceInFiles.js +131 -0
- package/dist/llm/tools/shellTool.d.ts +4 -0
- package/dist/llm/tools/shellTool.js +27 -8
- package/dist/llm/tools/storedOutputTool.d.ts +4 -0
- package/dist/llm/tools/taskTool.d.ts +4 -0
- package/dist/llm/tools/toolContext.d.ts +3 -0
- package/dist/llm/tools/toolContext.js +26 -4
- package/dist/skills/SkillLoader.js +27 -1
- package/dist/ui/components/TextInput.d.ts +18 -1
- package/dist/ui/components/TextInput.js +44 -6
- package/dist/ui/components/useInputSuggestions.js +18 -6
- package/dist/utils/buildInfo.js +29 -8
- package/dist/utils/fs.js +5 -1
- package/package.json +20 -19
|
@@ -20,6 +20,7 @@ function checkpointFromResume(resume, noProgressCount) {
|
|
|
20
20
|
noProgressCount,
|
|
21
21
|
...(resume.requestHash ? { requestHash: resume.requestHash } : {}),
|
|
22
22
|
...(resume.redEvidence ? { redEvidence: { ...resume.redEvidence } } : {}),
|
|
23
|
+
...(resume.validationKind ? { validationKind: resume.validationKind } : {}),
|
|
23
24
|
};
|
|
24
25
|
}
|
|
25
26
|
function countsToTaskProgress(counts) {
|
|
@@ -38,6 +39,7 @@ function carriedOf(checkpoint) {
|
|
|
38
39
|
validationOutcome: checkpoint.validationOutcome,
|
|
39
40
|
...(checkpoint.taskCounts ? { taskProgress: countsToTaskProgress(checkpoint.taskCounts) } : {}),
|
|
40
41
|
...(checkpoint.redEvidence ? { redEvidence: { ...checkpoint.redEvidence } } : {}),
|
|
42
|
+
...(checkpoint.validationKind ? { validationKind: checkpoint.validationKind } : {}),
|
|
41
43
|
}
|
|
42
44
|
: { mutationCount: 0, validationOutcome: 'not_applicable' };
|
|
43
45
|
}
|
|
@@ -63,7 +65,7 @@ function carriedOf(checkpoint) {
|
|
|
63
65
|
export async function runAgentGoal(options) {
|
|
64
66
|
const { request, contextFiles, callbacks } = options;
|
|
65
67
|
const startedAt = Date.now();
|
|
66
|
-
const resumedCheckpoint = options.resumeFrom?.
|
|
68
|
+
const resumedCheckpoint = options.resumeFrom?.checkpoint;
|
|
67
69
|
const goalId = resumedCheckpoint?.goalId ?? `goal-${startedAt}-${Math.random().toString(36).slice(2)}`;
|
|
68
70
|
const requestHash = resumedCheckpoint?.requestHash ?? hashRequest(request);
|
|
69
71
|
const intent = resumedCheckpoint?.intent ?? classifyRequestIntent(request);
|
|
@@ -92,6 +94,7 @@ export async function runAgentGoal(options) {
|
|
|
92
94
|
// Unresolved red evidence keeps crash resumes at parity with in-process
|
|
93
95
|
// continuation; satisfied pairs are deliberately not carried.
|
|
94
96
|
...(source?.redEvidence ? { redEvidence: { ...source.redEvidence } } : {}),
|
|
97
|
+
...(source?.validationKind ? { validationKind: source.validationKind } : {}),
|
|
95
98
|
...extra,
|
|
96
99
|
});
|
|
97
100
|
};
|
|
@@ -136,10 +139,12 @@ export async function runAgentGoal(options) {
|
|
|
136
139
|
sharedTurnScope,
|
|
137
140
|
...(remainingMs != null ? { turnDeadlineMs: Math.min(remainingMs, DEFAULT_TURN_DEADLINE_MS) } : {}),
|
|
138
141
|
};
|
|
139
|
-
const result = await runAgentTurn(request, continuing ? undefined : options.displayValue, contextFiles, callbacks, initialRetryAttempt, continuing, false, options.session, options.modelOverride, turnOptions);
|
|
142
|
+
const result = await runAgentTurn(request, continuing ? undefined : options.displayValue, contextFiles, callbacks, initialRetryAttempt, continuing, false, options.session, options.modelOverride, turnOptions, options.reasoningOverride);
|
|
140
143
|
initialRetryAttempt = 0;
|
|
141
144
|
cycle += 1;
|
|
142
145
|
lastEvidence = result.evidence;
|
|
146
|
+
if (result.checkpoint)
|
|
147
|
+
checkpoint = result.checkpoint;
|
|
143
148
|
if (result.status === 'complete')
|
|
144
149
|
return finish('complete', 'completed');
|
|
145
150
|
if (result.status === 'aborted') {
|
|
@@ -152,6 +157,15 @@ export async function runAgentGoal(options) {
|
|
|
152
157
|
noProgressCount = prevSignature != null && next.progressSignature === prevSignature ? noProgressCount + 1 : 0;
|
|
153
158
|
prevSignature = next.progressSignature;
|
|
154
159
|
checkpoint = { ...next, noProgressCount };
|
|
160
|
+
// Context exhaustion is not a correctable-in-place condition: the window
|
|
161
|
+
// stayed full after the turn's bounded compact-and-retry attempts, so
|
|
162
|
+
// continuing immediately would relaunch the same oversized request.
|
|
163
|
+
// Pause with the resumable checkpoint instead (Pillar 1.4); the user
|
|
164
|
+
// compacts/clears context or switches models, then resumes.
|
|
165
|
+
if (checkpoint.readiness === 'context_exhausted') {
|
|
166
|
+
callbacks.onEvent?.(agentEvent({ type: 'goal_notice', text: `Goal paused: ${checkpointReason(checkpoint)}. Compact or clear context, or switch to a larger-context model, then resume.` }));
|
|
167
|
+
return finish('failed', 'context-exhausted', { kind: 'incomplete-goal', checkpoint });
|
|
168
|
+
}
|
|
155
169
|
appendLedger('goal_continue');
|
|
156
170
|
if (noProgressCount >= GOAL_NO_PROGRESS_LIMIT) {
|
|
157
171
|
callbacks.addMessage({ role: 'system', text: `Unfinished goal paused after ${noProgressCount} corrective cycle${noProgressCount === 1 ? '' : 's'} without measurable progress (${checkpointReason(checkpoint)}). Completed work is preserved in the conversation. Press R to resume, or send a follow-up.` });
|
|
@@ -171,10 +185,10 @@ export async function runAgentGoal(options) {
|
|
|
171
185
|
if (result.resume?.kind === 'model-stream-idle') {
|
|
172
186
|
// Bounded in-turn retries are exhausted; a transport stall is a concrete
|
|
173
187
|
// external blocker — pause with the existing one-key resume path.
|
|
174
|
-
return finish('failed', 'model-stream-idle', { kind: 'model-stream-idle', request: result.resume.request, retryAttempt: result.resume.retryAttempt });
|
|
188
|
+
return finish('failed', 'model-stream-idle', { kind: 'model-stream-idle', request: result.resume.request, retryAttempt: result.resume.retryAttempt, ...(checkpoint ? { checkpoint } : {}) });
|
|
175
189
|
}
|
|
176
190
|
// Failed without a checkpoint: hard blocker (failed tool, invalid input,
|
|
177
191
|
// provider error) or an unresolved synthesis failure.
|
|
178
|
-
return finish('failed', result.evidence?.finishCause === 'error' ? 'model-error' : 'blocked');
|
|
192
|
+
return finish('failed', result.evidence?.finishCause === 'error' ? 'model-error' : 'blocked', checkpoint ? { kind: 'incomplete-goal', checkpoint } : undefined);
|
|
179
193
|
}
|
|
180
194
|
}
|
|
@@ -1,6 +1,5 @@
|
|
|
1
|
-
import type { ModelMessage } from 'ai';
|
|
2
1
|
import { type SessionGoal } from '../../../core/agent/goalPolicy.js';
|
|
3
|
-
import type
|
|
2
|
+
import { type ContextUsageAnchor } from '../../../core/agent/contextBudget.js';
|
|
4
3
|
import type { StreamCallbacks, TurnExecutionOptions } from '../streaming.js';
|
|
5
4
|
import type { AttemptSetup } from './attemptSetup.js';
|
|
6
5
|
import type { AttemptLoopState } from './streamLoop.js';
|
|
@@ -16,7 +15,7 @@ import type { TurnExecutionState } from '../../../core/agent/completionControlle
|
|
|
16
15
|
type AgentOptions = NonNullable<ConstructorParameters<typeof import('ai').ToolLoopAgent>[0]>;
|
|
17
16
|
type RepairToolCallFn = NonNullable<AgentOptions['experimental_repairToolCall']>;
|
|
18
17
|
type PrepareStepFn = NonNullable<AgentOptions['prepareStep']>;
|
|
19
|
-
|
|
18
|
+
type SyncPrepareStepResult = Exclude<ReturnType<PrepareStepFn>, PromiseLike<unknown>>;
|
|
20
19
|
export declare function createRepairToolCall(deps: {
|
|
21
20
|
callbacks: StreamCallbacks;
|
|
22
21
|
loopState: AttemptLoopState;
|
|
@@ -31,5 +30,8 @@ export declare function createPrepareStep(deps: {
|
|
|
31
30
|
};
|
|
32
31
|
goal: SessionGoal;
|
|
33
32
|
recoverySlice: TurnExecutionOptions['recoverySlice'];
|
|
34
|
-
|
|
33
|
+
usageAnchor: {
|
|
34
|
+
current: ContextUsageAnchor | undefined;
|
|
35
|
+
};
|
|
36
|
+
}): (input: Parameters<PrepareStepFn>[0]) => SyncPrepareStepResult;
|
|
35
37
|
export {};
|
|
@@ -1,18 +1,19 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
1
|
+
import { agentEvent } from '../../../core/agent/events.js';
|
|
2
|
+
import { editRecoveryReadPrompt, malformedToolCallPrompt, repeatedToolCallPrompt, toolLoopBudgetPrompt } from '../../../core/agent/goalPolicy.js';
|
|
3
|
+
import { estimateConversationTokens } from '../../../core/agent/contextBudget.js';
|
|
3
4
|
import { compactModelMessages } from '../../../core/agent/compaction.js';
|
|
4
|
-
import {
|
|
5
|
+
import { appendSyntheticControl, stripSyntheticControls } from '../../../core/agent/requestAssembly.js';
|
|
5
6
|
import { latestRepeatedToolNames, toolOnlyStepCount } from '../../../core/agent/turnPolicy.js';
|
|
6
7
|
import { RESCUE_BOUNDARY } from '../../../core/agent/completionController.js';
|
|
7
8
|
import { MAIN_TOOL_CALL_LIMIT, WRITE_FILE_CHUNK_BYTES } from '../../../core/agent/budgets.js';
|
|
8
9
|
import { projectContextSection } from '../../../llm/systemPrompt.js';
|
|
9
10
|
import { clampOutOfBoundsToolNumbers, isMalformedToolInputError } from './toolCallRecovery.js';
|
|
10
|
-
|
|
11
|
+
function withScopedContextControl(messages, context) {
|
|
11
12
|
const files = context.pendingContextFiles ?? [];
|
|
12
13
|
if (files.length === 0)
|
|
13
14
|
return messages;
|
|
14
15
|
context.pendingContextFiles = [];
|
|
15
|
-
return
|
|
16
|
+
return appendSyntheticControl(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
|
}
|
|
17
18
|
export function createRepairToolCall(deps) {
|
|
18
19
|
const { callbacks, loopState } = deps;
|
|
@@ -32,7 +33,7 @@ export function createRepairToolCall(deps) {
|
|
|
32
33
|
};
|
|
33
34
|
}
|
|
34
35
|
export function createPrepareStep(deps) {
|
|
35
|
-
const { setup, callbacks, loopState, turnState, turnBudget, goal, recoverySlice } = deps;
|
|
36
|
+
const { setup, callbacks, loopState, turnState, turnBudget, goal, recoverySlice, usageAnchor } = deps;
|
|
36
37
|
const { sliceTools, requestBudget, toolExecutionContext, likelyPlanOnlyRequest, rescueWithoutTools } = setup;
|
|
37
38
|
return ({ steps, messages }) => {
|
|
38
39
|
// A rescue slice with no qualifying tools must synthesize, never reopen
|
|
@@ -42,24 +43,39 @@ export function createPrepareStep(deps) {
|
|
|
42
43
|
return { toolChoice: 'none' };
|
|
43
44
|
}
|
|
44
45
|
const toolCalls = steps.flatMap(step => step.toolCalls);
|
|
45
|
-
|
|
46
|
+
// ToolLoopAgent instances are intentionally one step wide. SDK `steps`
|
|
47
|
+
// therefore resets at each resource epoch; retain only bounded policy
|
|
48
|
+
// metadata in loopState instead of holding prior StepResult graphs.
|
|
49
|
+
const repeatedToolNames = steps.length > 0 ? latestRepeatedToolNames(steps) : loopState.latestRepeatedToolNames;
|
|
46
50
|
let scopedMessages = withScopedContextControl(messages, toolExecutionContext);
|
|
47
51
|
let messagesChanged = scopedMessages !== messages;
|
|
48
52
|
// Re-evaluate the accumulated request size before each provider call and
|
|
49
53
|
// compact old tool history when it exceeds the model-aware budget, so a
|
|
50
|
-
// long multi-step turn compacts before overflowing (RH-005).
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
54
|
+
// long multi-step turn compacts before overflowing (RH-005). The estimate
|
|
55
|
+
// prefers provider usage from the last completed step (Pillar 1.1); this
|
|
56
|
+
// sync path is the safety net under the epoch-boundary LLM compaction.
|
|
57
|
+
const contextEstimate = estimateConversationTokens(scopedMessages, usageAnchor.current, requestBudget.systemTokens + requestBudget.toolSchemaTokens);
|
|
58
|
+
if (contextEstimate.tokens > requestBudget.messageTokens) {
|
|
59
|
+
callbacks.onEvent?.(agentEvent({ type: 'compaction_start', reason: 'threshold', method: 'heuristic' }));
|
|
60
|
+
const compacted = compactModelMessages(stripSyntheticControls(scopedMessages), { tokenBudget: requestBudget.messageTokens, workState: goal });
|
|
61
|
+
if (compacted.compacted) {
|
|
62
|
+
scopedMessages = compacted.messages;
|
|
63
|
+
loopState.contextCompactedInEpoch = true;
|
|
64
|
+
messagesChanged = true;
|
|
65
|
+
usageAnchor.current = undefined;
|
|
66
|
+
callbacks.recordCompaction?.({ method: 'heuristic', olderCount: compacted.olderCount, keptCount: compacted.keptCount, summary: compacted.summary ?? '' });
|
|
67
|
+
}
|
|
68
|
+
callbacks.onEvent?.(agentEvent({ type: 'compaction_end', reason: 'threshold', method: compacted.compacted ? 'heuristic' : 'none', compacted: compacted.compacted, olderCount: compacted.olderCount, keptCount: compacted.keptCount }));
|
|
55
69
|
}
|
|
56
70
|
// Turn-wide hard caps (shared across retries and recovery slices).
|
|
57
71
|
const turnToolCallsExhausted = turnState.toolCallsUsed >= turnBudget.toolCallLimit;
|
|
58
72
|
// Per-slice tool-call cap for a recovery slice (counts this slice's calls).
|
|
59
|
-
const
|
|
73
|
+
const sliceToolCalls = steps.length > 0 ? toolCalls.length : loopState.generatedToolCalls;
|
|
74
|
+
const sliceToolCallsExhausted = recoverySlice ? sliceToolCalls >= recoverySlice.maxToolCalls : false;
|
|
60
75
|
// Reserve the final tool-only slot for rescue: normal exploration stops at
|
|
61
76
|
// the boundary; a rescue slice is exempt so it may use the reserved slot.
|
|
62
|
-
const
|
|
77
|
+
const consecutiveToolOnlySteps = steps.length > 0 ? toolOnlyStepCount(steps) : loopState.consecutiveToolOnlySteps;
|
|
78
|
+
const toolOnlyBoundaryHit = !recoverySlice && consecutiveToolOnlySteps >= RESCUE_BOUNDARY;
|
|
63
79
|
if (likelyPlanOnlyRequest && loopState.toolResultState.mutatingToolSucceeded)
|
|
64
80
|
return messagesChanged ? { toolChoice: 'none', messages: scopedMessages } : { toolChoice: 'none' };
|
|
65
81
|
if (loopState.pendingMalformedToolName && loopState.pendingMalformedToolName in sliceTools) {
|
|
@@ -68,7 +84,7 @@ export function createPrepareStep(deps) {
|
|
|
68
84
|
loopState.pendingMalformedToolName = undefined;
|
|
69
85
|
if (attempt >= 2) {
|
|
70
86
|
callbacks.debugLog(`malformed ${String(toolName)} recovery exhausted`);
|
|
71
|
-
return { toolChoice: 'none', messages:
|
|
87
|
+
return { toolChoice: 'none', messages: appendSyntheticControl(scopedMessages, `The ${String(toolName)} input remained invalid after two smaller retries. Report this as blocked; do not promise another retry or claim completion.`) };
|
|
72
88
|
}
|
|
73
89
|
loopState.malformedRecoveryAttempts.set(String(toolName), attempt + 1);
|
|
74
90
|
callbacks.debugLog(`forcing smaller retry after malformed ${String(toolName)} input`);
|
|
@@ -77,23 +93,28 @@ export function createPrepareStep(deps) {
|
|
|
77
93
|
// required) and reject the object form with HTTP 400. Narrowing to a
|
|
78
94
|
// single active tool plus 'required' preserves the forced-call
|
|
79
95
|
// semantics on every server.
|
|
80
|
-
return { activeTools: [toolName], toolChoice: 'required', messages:
|
|
96
|
+
return { activeTools: [toolName], toolChoice: 'required', messages: appendSyntheticControl(scopedMessages, malformedToolCallPrompt(String(toolName), WRITE_FILE_CHUNK_BYTES)) };
|
|
81
97
|
}
|
|
82
98
|
if (loopState.toolResultState.editRecoveryPath && !loopState.toolResultState.editRecoveryReadSatisfied) {
|
|
99
|
+
// Instruct, do not restrict: the execution-time gate in toolContext
|
|
100
|
+
// (failed-mutation path requires a fresh read) is the structural
|
|
101
|
+
// enforcer and returns a recoverable structured error. Narrowing the
|
|
102
|
+
// request tool set here would downgrade that to a step-fatal
|
|
103
|
+
// AI_NoSuchToolError when a model retries the edit anyway.
|
|
83
104
|
if ('readFile' in sliceTools)
|
|
84
|
-
return
|
|
85
|
-
return { toolChoice: 'none', messages:
|
|
105
|
+
return { messages: appendSyntheticControl(scopedMessages, editRecoveryReadPrompt(loopState.toolResultState.editRecoveryPath)) };
|
|
106
|
+
return { toolChoice: 'none', messages: appendSyntheticControl(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
107
|
}
|
|
87
108
|
if (repeatedToolNames.length > 0) {
|
|
88
109
|
const activeTools = Object.keys(sliceTools).filter(name => !repeatedToolNames.includes(name));
|
|
89
110
|
callbacks.debugLog(`disabling repeated tools for next step: ${repeatedToolNames.join(', ')}`);
|
|
90
111
|
return activeTools.length > 0
|
|
91
|
-
? { activeTools, messages:
|
|
92
|
-
: { toolChoice: 'none', messages:
|
|
112
|
+
? { activeTools, messages: appendSyntheticControl(scopedMessages, repeatedToolCallPrompt(repeatedToolNames)) }
|
|
113
|
+
: { toolChoice: 'none', messages: appendSyntheticControl(scopedMessages, repeatedToolCallPrompt(repeatedToolNames)) };
|
|
93
114
|
}
|
|
94
|
-
if (turnToolCallsExhausted || sliceToolCallsExhausted || toolOnlyBoundaryHit ||
|
|
115
|
+
if (turnToolCallsExhausted || sliceToolCallsExhausted || toolOnlyBoundaryHit || sliceToolCalls >= MAIN_TOOL_CALL_LIMIT) {
|
|
95
116
|
callbacks.debugLog('forcing text response to avoid tool loop');
|
|
96
|
-
return { toolChoice: 'none', messages:
|
|
117
|
+
return { toolChoice: 'none', messages: appendSyntheticControl(scopedMessages, toolLoopBudgetPrompt()) };
|
|
97
118
|
}
|
|
98
119
|
return messagesChanged ? { messages: scopedMessages } : undefined;
|
|
99
120
|
};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { agentEvent } from '../../../core/agent/events.js';
|
|
2
2
|
import { IDLE_TIMEOUT_MS, DEFAULT_MODEL_RETRIES } from '../../../core/agent/budgets.js';
|
|
3
|
-
import {
|
|
3
|
+
import { stripSyntheticControls } from '../../../core/agent/requestAssembly.js';
|
|
4
4
|
import { abortForTurn } from './abortCause.js';
|
|
5
5
|
import { logEntry } from './turnRuntime.js';
|
|
6
6
|
/** Auto-retry an idle stall only while the stalled step emitted nothing visible (no partial text or in-flight tool). */
|
|
@@ -96,6 +96,6 @@ export function createStreamStallGuard(deps) {
|
|
|
96
96
|
*/
|
|
97
97
|
export function salvageConversationToLastStep(callbacks, salvage) {
|
|
98
98
|
if (salvage.accumulated.length > 0) {
|
|
99
|
-
callbacks.setConversation(
|
|
99
|
+
callbacks.setConversation([...stripSyntheticControls(salvage.requestMessages), ...salvage.accumulated]);
|
|
100
100
|
}
|
|
101
101
|
}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { type SessionGoal } from '../../../core/agent/goalPolicy.js';
|
|
2
|
+
import { type ContextUsageAnchor } from '../../../core/agent/contextBudget.js';
|
|
2
3
|
import { type TurnExecutionState } from '../../../core/agent/completionController.js';
|
|
3
4
|
import { type ToolExecutionBudgetState, type TurnBudget } from '../../../core/agent/budgets.js';
|
|
4
5
|
import type { StreamCallbacks, TurnExecutionOptions } from '../streaming.js';
|
|
@@ -23,6 +24,7 @@ export interface AttemptLoopState {
|
|
|
23
24
|
streamFinished: boolean;
|
|
24
25
|
finishReason: string | undefined;
|
|
25
26
|
lastToolOk: boolean | undefined;
|
|
27
|
+
sawToolCall: boolean;
|
|
26
28
|
pendingMalformedToolName: string | undefined;
|
|
27
29
|
unresolvedMalformedToolName: string | undefined;
|
|
28
30
|
/** Per-attempt (not per-turn) recovery counter: a transient retry gets a fresh map. Bounded across the whole turn by MAIN_TOOL_CALL_LIMIT. */
|
|
@@ -37,6 +39,21 @@ export interface AttemptLoopState {
|
|
|
37
39
|
rememberVisibleAssistantText: (text: string) => void;
|
|
38
40
|
/** Context files active for this attempt; grows when tool outputs surface scoped instructions. */
|
|
39
41
|
contextFiles: ContextFile[];
|
|
42
|
+
/** Lightweight cross-epoch history; never retains AI SDK StepResult objects. */
|
|
43
|
+
completedSteps: number;
|
|
44
|
+
generatedToolCalls: number;
|
|
45
|
+
consecutiveToolOnlySteps: number;
|
|
46
|
+
latestRepeatedToolNames: string[];
|
|
47
|
+
seenToolCallFingerprints: Set<string>;
|
|
48
|
+
/** The current epoch rewrote history because the real context budget fired. */
|
|
49
|
+
contextCompactedInEpoch: boolean;
|
|
50
|
+
/** Last valid per-step provider usage (input/output/cache), for usage-overflow detection (Pillar 1.2). */
|
|
51
|
+
lastUsage: {
|
|
52
|
+
inputTokens: number | undefined;
|
|
53
|
+
outputTokens: number;
|
|
54
|
+
cacheReadTokens: number;
|
|
55
|
+
cacheWriteTokens: number;
|
|
56
|
+
} | undefined;
|
|
40
57
|
}
|
|
41
58
|
export declare function createAttemptLoopState(previousAssistantText: string, contextFiles: ContextFile[], callbacks: Pick<StreamCallbacks, 'setLastAssistantText'>): AttemptLoopState;
|
|
42
59
|
/** What the completed stream tells the attempt outcome (classification evidence). */
|
|
@@ -47,6 +64,13 @@ export interface AttemptStreamOutcome {
|
|
|
47
64
|
sawToolCall: boolean;
|
|
48
65
|
unresolvedMalformedToolName: string | undefined;
|
|
49
66
|
unresolvedToolInputError: boolean;
|
|
67
|
+
/**
|
|
68
|
+
* Non-error context overflow detected from usage (Pillar 1.2): `silent`
|
|
69
|
+
* (usage exceeded the window on a successful finish) or `length-stop`
|
|
70
|
+
* (truncated input filled the window leaving no output room). Routed to
|
|
71
|
+
* compact-and-retry recovery in `finalizeAttemptOutcome`.
|
|
72
|
+
*/
|
|
73
|
+
usageOverflow: 'silent' | 'length-stop' | undefined;
|
|
50
74
|
}
|
|
51
75
|
export interface AttemptStreamDeps {
|
|
52
76
|
setup: AttemptSetup;
|
|
@@ -62,11 +86,14 @@ export interface AttemptStreamDeps {
|
|
|
62
86
|
loopState: AttemptLoopState;
|
|
63
87
|
toolDisplay: ToolGroupRenderer;
|
|
64
88
|
salvage: AttemptSalvage;
|
|
89
|
+
/** Turn-scoped usage anchor for provider-usage-backed context estimation (Pillar 1.1). */
|
|
90
|
+
usageAnchor: {
|
|
91
|
+
current: ContextUsageAnchor | undefined;
|
|
92
|
+
};
|
|
65
93
|
}
|
|
66
94
|
/**
|
|
67
|
-
* Drive one attempt
|
|
68
|
-
*
|
|
69
|
-
*
|
|
70
|
-
* classifies failures (abort cause, retry pool, recovery) in one place.
|
|
95
|
+
* Drive one attempt through bounded ToolLoopAgent epochs. The provider prefix,
|
|
96
|
+
* tools, budgets, evidence, and deadline stay continuous; only the AI SDK's
|
|
97
|
+
* request-local retained graph is released at each completed step.
|
|
71
98
|
*/
|
|
72
99
|
export declare function runAttemptStream(deps: AttemptStreamDeps): Promise<AttemptStreamOutcome>;
|