@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.
Files changed (133) hide show
  1. package/CHANGELOG.md +78 -0
  2. package/README.md +26 -15
  3. package/SECURITY.md +1 -1
  4. package/bin/haze.js +27 -7
  5. package/dist/buildInfo.json +3 -3
  6. package/dist/cli/chat/inputSuggestions.js +3 -0
  7. package/dist/cli/chat/liveMessages.d.ts +36 -0
  8. package/dist/cli/chat/liveMessages.js +64 -0
  9. package/dist/cli/chat/sessionLifecycle.d.ts +2 -1
  10. package/dist/cli/chat/sessionLifecycle.js +25 -2
  11. package/dist/cli/chat/sessionRecorder.d.ts +7 -0
  12. package/dist/cli/chat/sessionRecorder.js +6 -0
  13. package/dist/cli/chat/wizard/sessionThemeHandlers.d.ts +1 -1
  14. package/dist/cli/chat/wizard/sessionThemeHandlers.js +16 -1
  15. package/dist/cli/commands/chat.js +63 -36
  16. package/dist/cli/commands/commandHelp.js +2 -0
  17. package/dist/cli/commands/commands.js +2 -0
  18. package/dist/cli/commands/formatters.js +5 -1
  19. package/dist/cli/commands/ndjsonSink.d.ts +12 -0
  20. package/dist/cli/commands/ndjsonSink.js +29 -0
  21. package/dist/cli/commands/reasoningCommand.d.ts +35 -0
  22. package/dist/cli/commands/reasoningCommand.js +46 -0
  23. package/dist/cli/commands/runCommand.d.ts +14 -0
  24. package/dist/cli/commands/runCommand.js +43 -11
  25. package/dist/cli/commands/settingsSummary.js +2 -0
  26. package/dist/cli/commands/streaming/agentAttempt.d.ts +14 -1
  27. package/dist/cli/commands/streaming/agentAttempt.js +9 -5
  28. package/dist/cli/commands/streaming/assistantSegments.d.ts +0 -7
  29. package/dist/cli/commands/streaming/assistantSegments.js +1 -1
  30. package/dist/cli/commands/streaming/attemptLifecycle.js +13 -9
  31. package/dist/cli/commands/streaming/attemptOutcome.d.ts +23 -3
  32. package/dist/cli/commands/streaming/attemptOutcome.js +64 -11
  33. package/dist/cli/commands/streaming/attemptSetup.d.ts +13 -3
  34. package/dist/cli/commands/streaming/attemptSetup.js +40 -15
  35. package/dist/cli/commands/streaming/goalCheckpoint.d.ts +6 -0
  36. package/dist/cli/commands/streaming/goalCheckpoint.js +1 -0
  37. package/dist/cli/commands/streaming/goalSupervisor.d.ts +6 -1
  38. package/dist/cli/commands/streaming/goalSupervisor.js +18 -4
  39. package/dist/cli/commands/streaming/prepareStep.d.ts +6 -4
  40. package/dist/cli/commands/streaming/prepareStep.js +43 -22
  41. package/dist/cli/commands/streaming/stallRecovery.js +2 -2
  42. package/dist/cli/commands/streaming/streamLoop.d.ts +31 -4
  43. package/dist/cli/commands/streaming/streamLoop.js +280 -44
  44. package/dist/cli/commands/streaming/toolPartHandlers.js +13 -0
  45. package/dist/cli/commands/streaming/turnRuntime.d.ts +1 -1
  46. package/dist/cli/commands/streaming/turnRuntime.js +3 -2
  47. package/dist/cli/commands/streaming.d.ts +15 -2
  48. package/dist/cli/commands/streaming.js +37 -8
  49. package/dist/cli/commands/wizardFlow.d.ts +7 -0
  50. package/dist/cli/commands/wizardFlow.js +22 -0
  51. package/dist/cli/index.js +8 -3
  52. package/dist/config/modelCatalog.d.ts +32 -0
  53. package/dist/config/modelCatalog.js +84 -0
  54. package/dist/config/modelDiscovery.js +68 -5
  55. package/dist/config/settings.d.ts +18 -6
  56. package/dist/config/settings.js +11 -1
  57. package/dist/core/agent/budgets.d.ts +10 -2
  58. package/dist/core/agent/budgets.js +10 -2
  59. package/dist/core/agent/compaction.d.ts +42 -3
  60. package/dist/core/agent/compaction.js +53 -5
  61. package/dist/core/agent/completionController.d.ts +11 -1
  62. package/dist/core/agent/completionController.js +33 -0
  63. package/dist/core/agent/contextBudget.d.ts +56 -0
  64. package/dist/core/agent/contextBudget.js +53 -0
  65. package/dist/core/agent/errors.js +2 -2
  66. package/dist/core/agent/events.d.ts +26 -2
  67. package/dist/core/agent/goalPolicy.d.ts +7 -0
  68. package/dist/core/agent/goalPolicy.js +9 -0
  69. package/dist/core/agent/overflow.d.ts +45 -0
  70. package/dist/core/agent/overflow.js +91 -0
  71. package/dist/core/agent/reasoningPolicy.d.ts +45 -9
  72. package/dist/core/agent/reasoningPolicy.js +49 -9
  73. package/dist/core/agent/requestAssembly.d.ts +7 -0
  74. package/dist/core/agent/requestAssembly.js +15 -7
  75. package/dist/core/agent/toolCapabilities.d.ts +3 -3
  76. package/dist/core/agent/toolCapabilities.js +31 -7
  77. package/dist/core/agent/workState.d.ts +6 -4
  78. package/dist/core/agent/workState.js +53 -29
  79. package/dist/core/deadline.js +22 -24
  80. package/dist/core/safety/secretPaths.js +10 -7
  81. package/dist/core/safety/shellClassifier.d.ts +18 -0
  82. package/dist/core/safety/shellClassifier.js +39 -0
  83. package/dist/core/session/sessionSlimming.d.ts +2 -0
  84. package/dist/core/session/sessionSlimming.js +50 -1
  85. package/dist/core/session/sessionStore.d.ts +14 -8
  86. package/dist/core/session/sessionStore.js +59 -32
  87. package/dist/core/shellOutput/reducers/git.js +7 -2
  88. package/dist/core/shellOutput/reducers/validation.d.ts +1 -1
  89. package/dist/core/shellOutput/reducers/validation.js +14 -1
  90. package/dist/core/shellOutput/registry.js +3 -2
  91. package/dist/core/subagent/contracts.d.ts +8 -1
  92. package/dist/core/subagent/subagentRunner.d.ts +4 -0
  93. package/dist/core/subagent/subagentRunner.js +33 -25
  94. package/dist/core/tasks/taskStorage.js +8 -1
  95. package/dist/core/validation/outputParser.d.ts +1 -1
  96. package/dist/core/validation/outputParser.js +30 -1
  97. package/dist/llm/client.d.ts +4 -3
  98. package/dist/llm/client.js +34 -16
  99. package/dist/llm/hazeTools.d.ts +2039 -16
  100. package/dist/llm/hazeTools.js +43 -2
  101. package/dist/llm/lsp/client.d.ts +7 -1
  102. package/dist/llm/lsp/client.js +58 -9
  103. package/dist/llm/lsp/pool.d.ts +11 -0
  104. package/dist/llm/lsp/pool.js +61 -4
  105. package/dist/llm/lsp/protocol.d.ts +6 -23
  106. package/dist/llm/lsp/requests.d.ts +54 -60
  107. package/dist/llm/lsp/requests.js +152 -28
  108. package/dist/llm/lsp/symbols.d.ts +16 -0
  109. package/dist/llm/lsp/symbols.js +70 -0
  110. package/dist/llm/lsp/workspaceEdit.d.ts +43 -0
  111. package/dist/llm/lsp/workspaceEdit.js +117 -0
  112. package/dist/llm/lspTools.d.ts +7518 -2859
  113. package/dist/llm/lspTools.js +195 -110
  114. package/dist/llm/requestContext.d.ts +3 -2
  115. package/dist/llm/requestContext.js +8 -4
  116. package/dist/llm/systemPrompt.js +2 -2
  117. package/dist/llm/tools/fetchTool.d.ts +4 -0
  118. package/dist/llm/tools/processTool.d.ts +4 -0
  119. package/dist/llm/tools/replaceInFiles.d.ts +105 -0
  120. package/dist/llm/tools/replaceInFiles.js +131 -0
  121. package/dist/llm/tools/shellTool.d.ts +4 -0
  122. package/dist/llm/tools/shellTool.js +27 -8
  123. package/dist/llm/tools/storedOutputTool.d.ts +4 -0
  124. package/dist/llm/tools/taskTool.d.ts +4 -0
  125. package/dist/llm/tools/toolContext.d.ts +3 -0
  126. package/dist/llm/tools/toolContext.js +26 -4
  127. package/dist/skills/SkillLoader.js +27 -1
  128. package/dist/ui/components/TextInput.d.ts +18 -1
  129. package/dist/ui/components/TextInput.js +44 -6
  130. package/dist/ui/components/useInputSuggestions.js +18 -6
  131. package/dist/utils/buildInfo.js +29 -8
  132. package/dist/utils/fs.js +5 -1
  133. 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?.kind === 'incomplete-goal' || options.resumeFrom?.kind === 'stored-goal' ? options.resumeFrom.checkpoint : undefined;
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 { HazeToolContext } from '../../../llm/tools/toolContext.js';
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
- export declare function withScopedContextControl(messages: ModelMessage[], context: HazeToolContext): ModelMessage[];
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
- }): PrepareStepFn;
33
+ usageAnchor: {
34
+ current: ContextUsageAnchor | undefined;
35
+ };
36
+ }): (input: Parameters<PrepareStepFn>[0]) => SyncPrepareStepResult;
35
37
  export {};
@@ -1,18 +1,19 @@
1
- import { malformedToolCallPrompt, repeatedToolCallPrompt, toolLoopBudgetPrompt } from '../../../core/agent/goalPolicy.js';
2
- import { estimateMessagesTokens } from '../../../core/agent/contextBudget.js';
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 { stripSyntheticControls, withSyntheticControl } from '../../../core/agent/requestAssembly.js';
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
- export function withScopedContextControl(messages, context) {
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 withSyntheticControl(messages, `Additional scoped project instructions were just read for a non-root path touched by a tool call. Apply them to subsequent work in that subtree.${projectContextSection(files)}`);
16
+ 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
- const repeatedToolNames = latestRepeatedToolNames(steps);
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
- if (estimateMessagesTokens(scopedMessages) > requestBudget.messageTokens) {
52
- const compacted = compactModelMessages(stripSyntheticControls(scopedMessages), { tokenBudget: requestBudget.messageTokens, workState: goal }).messages;
53
- scopedMessages = compacted;
54
- messagesChanged = true;
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 sliceToolCallsExhausted = recoverySlice ? toolCalls.length >= recoverySlice.maxToolCalls : false;
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 toolOnlyBoundaryHit = !recoverySlice && toolOnlyStepCount(steps) >= RESCUE_BOUNDARY;
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: withSyntheticControl(scopedMessages, `The ${String(toolName)} input remained invalid after two smaller retries. Report this as blocked; do not promise another retry or claim completion.`) };
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: withSyntheticControl(scopedMessages, malformedToolCallPrompt(String(toolName), WRITE_FILE_CHUNK_BYTES)) };
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 messagesChanged ? { activeTools: ['readFile'], messages: scopedMessages } : { activeTools: ['readFile'] };
85
- return { toolChoice: 'none', messages: withSyntheticControl(scopedMessages, `The failed mutation of ${loopState.toolResultState.editRecoveryPath} requires a fresh read, but readFile is unavailable in this bounded recovery slice. Report the unfinished edit as blocked; do not claim it succeeded.`) };
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: withSyntheticControl(scopedMessages, repeatedToolCallPrompt(repeatedToolNames)) }
92
- : { toolChoice: 'none', messages: withSyntheticControl(scopedMessages, repeatedToolCallPrompt(repeatedToolNames)) };
112
+ ? { activeTools, messages: appendSyntheticControl(scopedMessages, repeatedToolCallPrompt(repeatedToolNames)) }
113
+ : { toolChoice: 'none', messages: appendSyntheticControl(scopedMessages, repeatedToolCallPrompt(repeatedToolNames)) };
93
114
  }
94
- if (turnToolCallsExhausted || sliceToolCallsExhausted || toolOnlyBoundaryHit || toolCalls.length >= MAIN_TOOL_CALL_LIMIT) {
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: withSyntheticControl(scopedMessages, toolLoopBudgetPrompt()) };
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 { compactToolHistory, stripSyntheticControls } from '../../../core/agent/requestAssembly.js';
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(compactToolHistory([...stripSyntheticControls(salvage.requestMessages), ...salvage.accumulated]).messages);
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'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.
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>;