@denizokcu/haze 1.1.1 → 1.2.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 +25 -0
- package/README.md +15 -12
- package/SECURITY.md +1 -1
- package/dist/buildInfo.json +3 -3
- package/dist/cli/chat/sessionLifecycle.js +2 -0
- package/dist/cli/chat/sessionRecorder.d.ts +7 -0
- package/dist/cli/chat/sessionRecorder.js +6 -0
- package/dist/cli/commands/chat.js +24 -2
- package/dist/cli/commands/runCommand.js +6 -0
- package/dist/cli/commands/streaming/agentAttempt.d.ts +11 -1
- package/dist/cli/commands/streaming/agentAttempt.js +9 -5
- package/dist/cli/commands/streaming/attemptOutcome.d.ts +23 -3
- package/dist/cli/commands/streaming/attemptOutcome.js +52 -9
- package/dist/cli/commands/streaming/attemptSetup.d.ts +10 -3
- package/dist/cli/commands/streaming/attemptSetup.js +30 -13
- package/dist/cli/commands/streaming/goalSupervisor.d.ts +1 -1
- package/dist/cli/commands/streaming/goalSupervisor.js +9 -0
- package/dist/cli/commands/streaming/prepareStep.d.ts +6 -1
- package/dist/cli/commands/streaming/prepareStep.js +35 -19
- 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 +8 -0
- package/dist/cli/commands/streaming.js +14 -4
- package/dist/cli/index.js +3 -2
- package/dist/config/modelCatalog.d.ts +32 -0
- package/dist/config/modelCatalog.js +84 -0
- package/dist/config/settings.d.ts +10 -2
- package/dist/config/settings.js +3 -0
- package/dist/core/agent/budgets.d.ts +10 -0
- package/dist/core/agent/budgets.js +10 -0
- package/dist/core/agent/compaction.d.ts +42 -3
- package/dist/core/agent/compaction.js +53 -5
- package/dist/core/agent/completionController.d.ts +3 -1
- package/dist/core/agent/completionController.js +1 -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 +24 -1
- package/dist/core/agent/overflow.d.ts +45 -0
- package/dist/core/agent/overflow.js +91 -0
- package/dist/core/agent/requestAssembly.d.ts +7 -0
- package/dist/core/agent/requestAssembly.js +15 -7
- package/dist/core/agent/workState.js +13 -1
- package/dist/core/safety/shellClassifier.d.ts +16 -0
- package/dist/core/safety/shellClassifier.js +31 -0
- package/dist/core/session/sessionStore.d.ts +10 -0
- package/dist/core/session/sessionStore.js +6 -0
- package/dist/core/validation/outputParser.d.ts +1 -1
- package/dist/core/validation/outputParser.js +6 -1
- package/dist/llm/client.d.ts +2 -2
- package/dist/llm/client.js +14 -6
- package/dist/llm/tools/shellTool.js +27 -8
- package/dist/ui/components/TextInput.d.ts +18 -1
- package/dist/ui/components/TextInput.js +44 -6
- package/package.json +16 -15
|
@@ -1,12 +1,11 @@
|
|
|
1
1
|
import { readSettings } from '../../../config/settings.js';
|
|
2
|
-
import { DEFAULT_MODEL_RETRIES } from '../../../core/agent/budgets.js';
|
|
2
|
+
import { DEFAULT_MAX_OUTPUT_TOKENS, DEFAULT_RETRY_BASE_DELAY_MS, MAIN_STEP_LIMIT, MAIN_TOOL_CALL_LIMIT, SUBAGENT_TOOL_DEADLINE_MS, DEFAULT_TOOL_DEADLINE_MS, DEFAULT_MODEL_RETRIES, withToolExecutionBudget } from '../../../core/agent/budgets.js';
|
|
3
3
|
import { agentEvent } from '../../../core/agent/events.js';
|
|
4
4
|
import { isPlanOnlyRequest } from '../../../core/agent/goalPolicy.js';
|
|
5
5
|
import { formatGoalStatus } from '../../../core/agent/goalPolicy.js';
|
|
6
|
-
import { calculateRequestTokenBudget,
|
|
7
|
-
import {
|
|
6
|
+
import { calculateRequestTokenBudget, estimateConversationTokens } from '../../../core/agent/contextBudget.js';
|
|
7
|
+
import { stripSyntheticControls, withSyntheticControl, withoutSystemMessages } from '../../../core/agent/requestAssembly.js';
|
|
8
8
|
import { compactModelMessages } from '../../../core/agent/compaction.js';
|
|
9
|
-
import { DEFAULT_MAX_OUTPUT_TOKENS, MAIN_STEP_LIMIT, MAIN_TOOL_CALL_LIMIT, SUBAGENT_TOOL_DEADLINE_MS, DEFAULT_TOOL_DEADLINE_MS, withToolExecutionBudget } from '../../../core/agent/budgets.js';
|
|
10
9
|
import { withToolDeadline } from '../../../core/deadline.js';
|
|
11
10
|
import { isMutatingCapability, isValidationCapable } from '../../../core/agent/toolCapabilities.js';
|
|
12
11
|
import { userTurnMessage } from '../../../core/attachments/imageAttachments.js';
|
|
@@ -40,9 +39,11 @@ export function restrictToRescueTools(tools) {
|
|
|
40
39
|
* configured (the caller-reported failure path).
|
|
41
40
|
*/
|
|
42
41
|
export async function prepareAttempt(deps) {
|
|
43
|
-
const { value, contextFiles, callbacks, retryingExistingRequest,
|
|
44
|
-
// Single choke point: one fresh settings read per
|
|
45
|
-
// resolution and request assembly (CR-024
|
|
42
|
+
const { value, contextFiles, callbacks, retryingExistingRequest, session, modelOverride, abortController, turnOptions, turnScope, turnBudget, goal, globalBudget, sliceBudget, onContextFileRead, usageAnchor } = deps;
|
|
43
|
+
// Single choke point: one fresh settings read per attempt, shared by model
|
|
44
|
+
// resolution and request assembly (CR-024, relaxed in Pillar 1.9 so a
|
|
45
|
+
// provider/model switch mid-goal applies from the next attempt — the first
|
|
46
|
+
// attempt of each physical turn keeps the original read).
|
|
46
47
|
const turnSettings = await readSettings();
|
|
47
48
|
const runtime = await modelWithConfig({ cwd: session?.cwd, modelSelector: modelOverride }, turnSettings);
|
|
48
49
|
if (!runtime?.model) {
|
|
@@ -88,9 +89,14 @@ export async function prepareAttempt(deps) {
|
|
|
88
89
|
callbacks.setWorkState?.(goal);
|
|
89
90
|
callbacks.setGoalStatus?.(formatGoalStatus(goal));
|
|
90
91
|
const likelyPlanOnlyRequest = isPlanOnlyRequest(value);
|
|
91
|
-
|
|
92
|
+
// Keep the active provider history exact. Routine tool-history slimming used
|
|
93
|
+
// to rewrite older successful calls/results here, invalidating provider
|
|
94
|
+
// prompt-cache prefixes before the context budget required compaction.
|
|
95
|
+
// Durable session snapshots are slimmed independently at the persistence
|
|
96
|
+
// boundary; only the model-aware compaction below may rewrite active history.
|
|
97
|
+
const durableRequestMessages = retryingExistingRequest
|
|
92
98
|
? stripSyntheticControls(callbacks.getConversation())
|
|
93
|
-
: [...stripSyntheticControls(callbacks.getConversation()), userTurnMessage(value, turnOptions.attachments ?? [])]
|
|
99
|
+
: [...stripSyntheticControls(callbacks.getConversation()), userTurnMessage(value, turnOptions.attachments ?? [])];
|
|
94
100
|
// Model-aware request budget (RH-005): message allowance is the context
|
|
95
101
|
// window minus system prompt, tool schemas, output reserve, and a safety
|
|
96
102
|
// margin — not a fixed 40K constant. Small contexts get a safe budget; the
|
|
@@ -98,11 +104,21 @@ export async function prepareAttempt(deps) {
|
|
|
98
104
|
const requestedOutputTokens = runtime.config.maxOutputTokens ?? DEFAULT_MAX_OUTPUT_TOKENS;
|
|
99
105
|
const requestBudget = calculateRequestTokenBudget({ contextWindowTokens: runtime.config.contextWindowTokens, requestedOutputTokens, system: assembled.systemPrompt, tools: availableTools });
|
|
100
106
|
// A context-overflow retry progressively shrinks the target so it cannot loop
|
|
101
|
-
// at an unchanged budget; further overflows get even smaller (RH-005
|
|
102
|
-
|
|
107
|
+
// at an unchanged budget; further overflows get even smaller (RH-005, Pillar
|
|
108
|
+
// 1.4: 0.6 after the first, 0.36 after the second).
|
|
109
|
+
const overflowShrinkFactor = deps.overflowShrinkFactor;
|
|
110
|
+
const overflowTargetTokens = overflowShrinkFactor < 1 ? Math.floor(requestBudget.messageTokens * overflowShrinkFactor) : requestBudget.messageTokens;
|
|
111
|
+
const overheadTokens = requestBudget.systemTokens + requestBudget.toolSchemaTokens;
|
|
103
112
|
let requestMessages = durableRequestMessages;
|
|
104
|
-
if (
|
|
105
|
-
|
|
113
|
+
if (estimateConversationTokens(requestMessages, usageAnchor.current, overheadTokens).tokens > overflowTargetTokens) {
|
|
114
|
+
callbacks.onEvent?.(agentEvent({ type: 'compaction_start', reason: 'threshold', method: 'heuristic' }));
|
|
115
|
+
const compacted = compactModelMessages(requestMessages, { tokenBudget: overflowTargetTokens, workState: goal });
|
|
116
|
+
requestMessages = compacted.messages;
|
|
117
|
+
if (compacted.compacted) {
|
|
118
|
+
usageAnchor.current = undefined;
|
|
119
|
+
callbacks.recordCompaction?.({ method: 'heuristic', olderCount: compacted.olderCount, keptCount: compacted.keptCount, summary: compacted.summary ?? '' });
|
|
120
|
+
}
|
|
121
|
+
callbacks.onEvent?.(agentEvent({ type: 'compaction_end', reason: 'threshold', method: compacted.compacted ? 'heuristic' : 'none', compacted: compacted.compacted, olderCount: compacted.olderCount, keptCount: compacted.keptCount }));
|
|
106
122
|
}
|
|
107
123
|
requestMessages = withoutSystemMessages(requestMessages);
|
|
108
124
|
callbacks.setConversation(stripSyntheticControls(requestMessages));
|
|
@@ -163,5 +179,6 @@ export async function prepareAttempt(deps) {
|
|
|
163
179
|
contextFiles: activeContextFiles,
|
|
164
180
|
toolCategories,
|
|
165
181
|
modelRetries: typeof turnSettings.modelRetries === 'number' ? turnSettings.modelRetries : DEFAULT_MODEL_RETRIES,
|
|
182
|
+
retryBaseDelayMs: typeof turnSettings.retryBaseDelayMs === 'number' ? turnSettings.retryBaseDelayMs : DEFAULT_RETRY_BASE_DELAY_MS,
|
|
166
183
|
};
|
|
167
184
|
}
|
|
@@ -4,7 +4,7 @@ import type { PromptSession } from '../../../llm/systemPrompt.js';
|
|
|
4
4
|
import { type StreamCallbacks, type TurnExecutionOptions } from '../streaming.js';
|
|
5
5
|
import { type GoalCheckpoint, type GoalLedgerAppend } from './goalCheckpoint.js';
|
|
6
6
|
/** Why a logical goal stopped. `completed` is the only success. */
|
|
7
|
-
export type GoalStopReason = 'completed' | 'no-progress' | 'goal-deadline' | 'blocked' | 'model-error' | 'model-stream-idle' | 'user-aborted';
|
|
7
|
+
export type GoalStopReason = 'completed' | 'no-progress' | 'goal-deadline' | 'blocked' | 'model-error' | 'model-stream-idle' | 'user-aborted' | 'context-exhausted';
|
|
8
8
|
export type { GoalLedgerAppend };
|
|
9
9
|
/** Authoritative outcome of a logical goal (one or more physical turns). */
|
|
10
10
|
export interface GoalRunResult {
|
|
@@ -152,6 +152,15 @@ export async function runAgentGoal(options) {
|
|
|
152
152
|
noProgressCount = prevSignature != null && next.progressSignature === prevSignature ? noProgressCount + 1 : 0;
|
|
153
153
|
prevSignature = next.progressSignature;
|
|
154
154
|
checkpoint = { ...next, noProgressCount };
|
|
155
|
+
// Context exhaustion is not a correctable-in-place condition: the window
|
|
156
|
+
// stayed full after the turn's bounded compact-and-retry attempts, so
|
|
157
|
+
// continuing immediately would relaunch the same oversized request.
|
|
158
|
+
// Pause with the resumable checkpoint instead (Pillar 1.4); the user
|
|
159
|
+
// compacts/clears context or switches models, then resumes.
|
|
160
|
+
if (checkpoint.readiness === 'context_exhausted') {
|
|
161
|
+
callbacks.onEvent?.(agentEvent({ type: 'goal_notice', text: `Goal paused: ${checkpointReason(checkpoint)}. Compact or clear context, or switch to a larger-context model, then resume.` }));
|
|
162
|
+
return finish('failed', 'context-exhausted', { kind: 'incomplete-goal', checkpoint });
|
|
163
|
+
}
|
|
155
164
|
appendLedger('goal_continue');
|
|
156
165
|
if (noProgressCount >= GOAL_NO_PROGRESS_LIMIT) {
|
|
157
166
|
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.` });
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import type { ModelMessage } from 'ai';
|
|
2
2
|
import { type SessionGoal } from '../../../core/agent/goalPolicy.js';
|
|
3
|
+
import { type ContextUsageAnchor } from '../../../core/agent/contextBudget.js';
|
|
3
4
|
import type { HazeToolContext } from '../../../llm/tools/toolContext.js';
|
|
4
5
|
import type { StreamCallbacks, TurnExecutionOptions } from '../streaming.js';
|
|
5
6
|
import type { AttemptSetup } from './attemptSetup.js';
|
|
@@ -16,6 +17,7 @@ import type { TurnExecutionState } from '../../../core/agent/completionControlle
|
|
|
16
17
|
type AgentOptions = NonNullable<ConstructorParameters<typeof import('ai').ToolLoopAgent>[0]>;
|
|
17
18
|
type RepairToolCallFn = NonNullable<AgentOptions['experimental_repairToolCall']>;
|
|
18
19
|
type PrepareStepFn = NonNullable<AgentOptions['prepareStep']>;
|
|
20
|
+
type SyncPrepareStepResult = Exclude<ReturnType<PrepareStepFn>, PromiseLike<unknown>>;
|
|
19
21
|
export declare function withScopedContextControl(messages: ModelMessage[], context: HazeToolContext): ModelMessage[];
|
|
20
22
|
export declare function createRepairToolCall(deps: {
|
|
21
23
|
callbacks: StreamCallbacks;
|
|
@@ -31,5 +33,8 @@ export declare function createPrepareStep(deps: {
|
|
|
31
33
|
};
|
|
32
34
|
goal: SessionGoal;
|
|
33
35
|
recoverySlice: TurnExecutionOptions['recoverySlice'];
|
|
34
|
-
|
|
36
|
+
usageAnchor: {
|
|
37
|
+
current: ContextUsageAnchor | undefined;
|
|
38
|
+
};
|
|
39
|
+
}): (input: Parameters<PrepareStepFn>[0]) => SyncPrepareStepResult;
|
|
35
40
|
export {};
|
|
@@ -1,7 +1,8 @@
|
|
|
1
|
+
import { agentEvent } from '../../../core/agent/events.js';
|
|
1
2
|
import { malformedToolCallPrompt, repeatedToolCallPrompt, toolLoopBudgetPrompt } from '../../../core/agent/goalPolicy.js';
|
|
2
|
-
import {
|
|
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';
|
|
@@ -12,7 +13,7 @@ export function withScopedContextControl(messages, context) {
|
|
|
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,23 @@ 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) {
|
|
83
99
|
if ('readFile' in sliceTools)
|
|
84
100
|
return messagesChanged ? { activeTools: ['readFile'], messages: scopedMessages } : { activeTools: ['readFile'] };
|
|
85
|
-
return { toolChoice: 'none', messages:
|
|
101
|
+
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
102
|
}
|
|
87
103
|
if (repeatedToolNames.length > 0) {
|
|
88
104
|
const activeTools = Object.keys(sliceTools).filter(name => !repeatedToolNames.includes(name));
|
|
89
105
|
callbacks.debugLog(`disabling repeated tools for next step: ${repeatedToolNames.join(', ')}`);
|
|
90
106
|
return activeTools.length > 0
|
|
91
|
-
? { activeTools, messages:
|
|
92
|
-
: { toolChoice: 'none', messages:
|
|
107
|
+
? { activeTools, messages: appendSyntheticControl(scopedMessages, repeatedToolCallPrompt(repeatedToolNames)) }
|
|
108
|
+
: { toolChoice: 'none', messages: appendSyntheticControl(scopedMessages, repeatedToolCallPrompt(repeatedToolNames)) };
|
|
93
109
|
}
|
|
94
|
-
if (turnToolCallsExhausted || sliceToolCallsExhausted || toolOnlyBoundaryHit ||
|
|
110
|
+
if (turnToolCallsExhausted || sliceToolCallsExhausted || toolOnlyBoundaryHit || sliceToolCalls >= MAIN_TOOL_CALL_LIMIT) {
|
|
95
111
|
callbacks.debugLog('forcing text response to avoid tool loop');
|
|
96
|
-
return { toolChoice: 'none', messages:
|
|
112
|
+
return { toolChoice: 'none', messages: appendSyntheticControl(scopedMessages, toolLoopBudgetPrompt()) };
|
|
97
113
|
}
|
|
98
114
|
return messagesChanged ? { messages: scopedMessages } : undefined;
|
|
99
115
|
};
|
|
@@ -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>;
|