@denizokcu/haze 1.1.0 → 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.
Files changed (149) hide show
  1. package/CHANGELOG.md +49 -1
  2. package/README.md +17 -10
  3. package/SECURITY.md +1 -1
  4. package/dist/buildInfo.json +3 -3
  5. package/dist/cli/chat/busyIndicator.d.ts +11 -0
  6. package/dist/cli/chat/busyIndicator.js +34 -0
  7. package/dist/cli/chat/chatMetrics.d.ts +0 -1
  8. package/dist/cli/chat/chatMetrics.js +1 -7
  9. package/dist/cli/chat/followUpQueue.d.ts +11 -0
  10. package/dist/cli/chat/followUpQueue.js +38 -0
  11. package/dist/cli/chat/messages.d.ts +0 -22
  12. package/dist/cli/chat/messages.js +40 -85
  13. package/dist/cli/chat/sessionLifecycle.d.ts +3 -1
  14. package/dist/cli/chat/sessionLifecycle.js +8 -1
  15. package/dist/cli/chat/sessionRecorder.d.ts +9 -0
  16. package/dist/cli/chat/sessionRecorder.js +12 -0
  17. package/dist/cli/chat/startupSequence.d.ts +29 -0
  18. package/dist/cli/chat/startupSequence.js +59 -0
  19. package/dist/cli/chat/transcriptPartition.d.ts +23 -0
  20. package/dist/cli/chat/transcriptPartition.js +78 -0
  21. package/dist/cli/chat/wizard/fieldTransitions.d.ts +38 -0
  22. package/dist/cli/chat/wizard/fieldTransitions.js +43 -0
  23. package/dist/cli/chat/wizard/lspHandlers.d.ts +4 -0
  24. package/dist/cli/chat/wizard/lspHandlers.js +85 -0
  25. package/dist/cli/chat/wizard/mcpHandlers.d.ts +8 -0
  26. package/dist/cli/chat/wizard/mcpHandlers.js +82 -0
  27. package/dist/cli/chat/wizard/providerHandlers.d.ts +12 -0
  28. package/dist/cli/chat/wizard/providerHandlers.js +420 -0
  29. package/dist/cli/chat/wizard/sessionThemeHandlers.d.ts +4 -0
  30. package/dist/cli/chat/wizard/sessionThemeHandlers.js +48 -0
  31. package/dist/cli/chat/wizard/skillsHandlers.d.ts +4 -0
  32. package/dist/cli/chat/wizard/skillsHandlers.js +125 -0
  33. package/dist/cli/chat/wizard/types.d.ts +63 -0
  34. package/dist/cli/chat/wizard/types.js +24 -0
  35. package/dist/cli/chat/wizard/uiState.d.ts +56 -0
  36. package/dist/cli/chat/wizard/uiState.js +15 -0
  37. package/dist/cli/chat/wizardDispatch.d.ts +11 -113
  38. package/dist/cli/chat/wizardDispatch.js +41 -815
  39. package/dist/cli/commands/chat.js +69 -110
  40. package/dist/cli/commands/formatters.d.ts +0 -3
  41. package/dist/cli/commands/formatters.js +0 -29
  42. package/dist/cli/commands/runCommand.d.ts +2 -0
  43. package/dist/cli/commands/runCommand.js +73 -4
  44. package/dist/cli/commands/streaming/agentAttempt.d.ts +11 -1
  45. package/dist/cli/commands/streaming/agentAttempt.js +9 -5
  46. package/dist/cli/commands/streaming/assistantSegments.d.ts +19 -0
  47. package/dist/cli/commands/streaming/assistantSegments.js +48 -0
  48. package/dist/cli/commands/streaming/attemptOutcome.d.ts +25 -5
  49. package/dist/cli/commands/streaming/attemptOutcome.js +69 -16
  50. package/dist/cli/commands/streaming/attemptSetup.d.ts +10 -3
  51. package/dist/cli/commands/streaming/attemptSetup.js +30 -13
  52. package/dist/cli/commands/streaming/goalCheckpoint.d.ts +69 -8
  53. package/dist/cli/commands/streaming/goalCheckpoint.js +36 -1
  54. package/dist/cli/commands/streaming/goalSupervisor.d.ts +18 -3
  55. package/dist/cli/commands/streaming/goalSupervisor.js +71 -12
  56. package/dist/cli/commands/streaming/prepareStep.d.ts +40 -0
  57. package/dist/cli/commands/streaming/prepareStep.js +116 -0
  58. package/dist/cli/commands/streaming/recoverySlices.d.ts +15 -0
  59. package/dist/cli/commands/streaming/recoverySlices.js +29 -0
  60. package/dist/cli/commands/streaming/stallRecovery.d.ts +0 -1
  61. package/dist/cli/commands/streaming/stallRecovery.js +2 -6
  62. package/dist/cli/commands/streaming/streamLoop.d.ts +31 -4
  63. package/dist/cli/commands/streaming/streamLoop.js +283 -268
  64. package/dist/cli/commands/streaming/toolGroupRenderer.js +2 -1
  65. package/dist/cli/commands/streaming/toolPartHandlers.d.ts +19 -0
  66. package/dist/cli/commands/streaming/toolPartHandlers.js +108 -0
  67. package/dist/cli/commands/streaming/turnRuntime.d.ts +1 -1
  68. package/dist/cli/commands/streaming/turnRuntime.js +3 -2
  69. package/dist/cli/commands/streaming.d.ts +12 -1
  70. package/dist/cli/commands/streaming.js +20 -25
  71. package/dist/cli/index.js +6 -3
  72. package/dist/config/modelCatalog.d.ts +32 -0
  73. package/dist/config/modelCatalog.js +84 -0
  74. package/dist/config/providerPresets.d.ts +7 -0
  75. package/dist/config/providerPresets.js +195 -391
  76. package/dist/config/settings.d.ts +10 -2
  77. package/dist/config/settings.js +3 -0
  78. package/dist/core/agent/budgets.d.ts +10 -0
  79. package/dist/core/agent/budgets.js +10 -0
  80. package/dist/core/agent/compaction.d.ts +42 -3
  81. package/dist/core/agent/compaction.js +53 -5
  82. package/dist/core/agent/completionController.d.ts +16 -7
  83. package/dist/core/agent/completionController.js +13 -6
  84. package/dist/core/agent/contextBudget.d.ts +56 -0
  85. package/dist/core/agent/contextBudget.js +53 -0
  86. package/dist/core/agent/errors.js +2 -2
  87. package/dist/core/agent/events.d.ts +36 -1
  88. package/dist/core/agent/goalPolicy.d.ts +4 -3
  89. package/dist/core/agent/goalPolicy.js +9 -4
  90. package/dist/core/agent/overflow.d.ts +45 -0
  91. package/dist/core/agent/overflow.js +91 -0
  92. package/dist/core/agent/requestAssembly.d.ts +7 -0
  93. package/dist/core/agent/requestAssembly.js +15 -7
  94. package/dist/core/agent/workState.d.ts +25 -15
  95. package/dist/core/agent/workState.js +84 -44
  96. package/dist/core/safety/shellClassifier.d.ts +16 -0
  97. package/dist/core/safety/shellClassifier.js +31 -0
  98. package/dist/core/session/sessionSlimming.js +8 -0
  99. package/dist/core/session/sessionStore.d.ts +71 -1
  100. package/dist/core/session/sessionStore.js +121 -6
  101. package/dist/core/validation/outputParser.d.ts +1 -1
  102. package/dist/core/validation/outputParser.js +6 -1
  103. package/dist/llm/client.d.ts +2 -2
  104. package/dist/llm/client.js +14 -6
  105. package/dist/llm/hazeTools.d.ts +64 -208
  106. package/dist/llm/tools/shellTool.js +27 -8
  107. package/dist/llm/tools/taskTool.d.ts +64 -208
  108. package/dist/llm/tools/taskTool.js +22 -10
  109. package/dist/ui/components/TextInput.d.ts +18 -1
  110. package/dist/ui/components/TextInput.js +50 -73
  111. package/dist/ui/components/useInputSuggestions.d.ts +27 -0
  112. package/dist/ui/components/useInputSuggestions.js +98 -0
  113. package/dist/ui/theme.d.ts +8 -8
  114. package/dist/ui/theme.js +11 -12
  115. package/dist/ui/themes/registry.d.ts +5 -0
  116. package/dist/ui/themes/registry.js +436 -0
  117. package/dist/utils/format.d.ts +10 -0
  118. package/dist/utils/format.js +45 -0
  119. package/package.json +16 -15
  120. package/dist/ui/themes/af-magic.d.ts +0 -7
  121. package/dist/ui/themes/af-magic.js +0 -25
  122. package/dist/ui/themes/agnoster.d.ts +0 -10
  123. package/dist/ui/themes/agnoster.js +0 -40
  124. package/dist/ui/themes/bira.d.ts +0 -10
  125. package/dist/ui/themes/bira.js +0 -28
  126. package/dist/ui/themes/bureau.d.ts +0 -10
  127. package/dist/ui/themes/bureau.js +0 -28
  128. package/dist/ui/themes/clean.d.ts +0 -9
  129. package/dist/ui/themes/clean.js +0 -27
  130. package/dist/ui/themes/cloud.d.ts +0 -6
  131. package/dist/ui/themes/cloud.js +0 -24
  132. package/dist/ui/themes/dst.d.ts +0 -10
  133. package/dist/ui/themes/dst.js +0 -28
  134. package/dist/ui/themes/fishy.d.ts +0 -7
  135. package/dist/ui/themes/fishy.js +0 -25
  136. package/dist/ui/themes/index.d.ts +0 -8
  137. package/dist/ui/themes/index.js +0 -36
  138. package/dist/ui/themes/light.d.ts +0 -3
  139. package/dist/ui/themes/light.js +0 -21
  140. package/dist/ui/themes/purple.d.ts +0 -7
  141. package/dist/ui/themes/purple.js +0 -26
  142. package/dist/ui/themes/robbyrussell.d.ts +0 -8
  143. package/dist/ui/themes/robbyrussell.js +0 -26
  144. package/dist/ui/themes/solarized-dark.d.ts +0 -16
  145. package/dist/ui/themes/solarized-dark.js +0 -44
  146. package/dist/ui/themes/solarized-light.d.ts +0 -12
  147. package/dist/ui/themes/solarized-light.js +0 -40
  148. package/dist/ui/themes/steeef.d.ts +0 -11
  149. package/dist/ui/themes/steeef.js +0 -29
@@ -1,22 +1,19 @@
1
- import { ToolLoopAgent, isStepCount } from 'ai';
1
+ import { createHash } from 'node:crypto';
2
+ import { ToolLoopAgent, generateText, isStepCount } from 'ai';
2
3
  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';
4
+ import { contextTokensFromUsage, estimateConversationTokens, estimateValueTokens } from '../../../core/agent/contextBudget.js';
5
+ import { stripSyntheticControls } from '../../../core/agent/requestAssembly.js';
6
+ import { buildLlmCompactionPrompt, chooseBoundaryCompactionMethod, compactModelMessages, compactModelMessagesWithSummary, extractExistingCompactionSummary } from '../../../core/agent/compaction.js';
7
+ import { isLengthStopOverflow, isSilentContextOverflow } from '../../../core/agent/overflow.js';
8
+ import { COMPACTION_LLM_MAX_OUTPUT_TOKENS, COMPACTION_LLM_MIN_OLDER_TOKENS, DEFAULT_MAX_OUTPUT_TOKENS } from '../../../core/agent/budgets.js';
13
9
  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';
10
+ import { busyToolLabel, toolCallSummary } from '../formatters.js';
11
+ import { sanitizeAssistantText, assistantDisplayText, normalizeAssistantText, shouldStartAssistantStream } from './assistantText.js';
12
+ import { finalizeAssistantSegment, finalizePendingAssistantBeforeTool } from './assistantSegments.js';
13
+ import { handleToolErrorPart, handleToolResultPart } from './toolPartHandlers.js';
14
+ import { createPrepareStep, createRepairToolCall } from './prepareStep.js';
17
15
  import { applyStepToolResultState, initialToolResultState } from './toolResultState.js';
18
- import { clampOutOfBoundsToolNumbers, isMalformedToolInputError } from './toolCallRecovery.js';
19
- import { extractUsage, logEntry, rememberContextFilesFromToolOutput, responseCompletionMetrics, stepCacheMetrics, subagentTokenEstimate } from './turnRuntime.js';
16
+ import { extractUsage, logEntry, stepCacheMetrics } from './turnRuntime.js';
20
17
  export function createAttemptLoopState(previousAssistantText, contextFiles, callbacks) {
21
18
  const visibleAssistantTexts = new Set(previousAssistantText ? [previousAssistantText] : []);
22
19
  return {
@@ -29,6 +26,7 @@ export function createAttemptLoopState(previousAssistantText, contextFiles, call
29
26
  streamFinished: false,
30
27
  finishReason: undefined,
31
28
  lastToolOk: undefined,
29
+ sawToolCall: false,
32
30
  pendingMalformedToolName: undefined,
33
31
  unresolvedMalformedToolName: undefined,
34
32
  malformedRecoveryAttempts: new Map(),
@@ -45,222 +43,42 @@ export function createAttemptLoopState(previousAssistantText, contextFiles, call
45
43
  callbacks.setLastAssistantText(text);
46
44
  },
47
45
  contextFiles,
46
+ completedSteps: 0,
47
+ generatedToolCalls: 0,
48
+ consecutiveToolOnlySteps: 0,
49
+ latestRepeatedToolNames: [],
50
+ seenToolCallFingerprints: new Set(),
51
+ contextCompactedInEpoch: false,
52
+ lastUsage: undefined,
48
53
  };
49
54
  }
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)}`);
55
+ function toolCallFingerprint(value) {
56
+ if (typeof value !== 'object' || value == null)
57
+ return undefined;
58
+ const call = value;
59
+ if (typeof call.toolName !== 'string')
60
+ return undefined;
61
+ const serialized = JSON.stringify(call.input) ?? 'undefined';
62
+ const digest = createHash('sha256').update(serialized).digest('base64url');
63
+ return { fingerprint: `${call.toolName}:${digest}`, toolName: call.toolName };
56
64
  }
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) });
65
+ /** Retain only the policy metadata needed by prepareStep across SDK epochs. */
66
+ function recordCompletedStep(loopState, input) {
67
+ const repeated = new Set();
68
+ for (const toolCall of input.toolCalls) {
69
+ const keyed = toolCallFingerprint(toolCall);
70
+ if (!keyed)
71
+ continue;
72
+ if (loopState.seenToolCallFingerprints.has(keyed.fingerprint))
73
+ repeated.add(keyed.toolName);
74
+ loopState.seenToolCallFingerprints.add(keyed.fingerprint);
166
75
  }
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);
76
+ loopState.latestRepeatedToolNames = [...repeated];
77
+ loopState.completedSteps += 1;
78
+ loopState.generatedToolCalls += input.toolCalls.length;
79
+ loopState.consecutiveToolOnlySteps = input.toolCalls.length > 0 && input.text.trim().length === 0
80
+ ? loopState.consecutiveToolOnlySteps + 1
81
+ : 0;
264
82
  }
265
83
  function applyStreamPart(deps, part) {
266
84
  const { loopState, callbacks, toolDisplay, setup } = deps;
@@ -288,6 +106,7 @@ function applyStreamPart(deps, part) {
288
106
  }
289
107
  case 'tool-input-start': {
290
108
  finalizePendingAssistantBeforeTool(deps);
109
+ loopState.sawToolCall = true;
291
110
  const toolCall = { toolCallId: part.id, toolName: part.toolName, input: {} };
292
111
  loopState.latestToolCalls.set(part.id, toolCall);
293
112
  loopState.inFlightTools.add(part.id);
@@ -297,6 +116,7 @@ function applyStreamPart(deps, part) {
297
116
  }
298
117
  case 'tool-call': {
299
118
  finalizePendingAssistantBeforeTool(deps);
119
+ loopState.sawToolCall = true;
300
120
  const toolCall = { toolCallId: part.toolCallId, toolName: part.toolName, input: part.input };
301
121
  loopState.latestToolCalls.set(part.toolCallId, toolCall);
302
122
  // Tool execution begins only after its complete input has parsed and validated.
@@ -327,44 +147,62 @@ function applyStreamPart(deps, part) {
327
147
  break;
328
148
  }
329
149
  }
330
- /** Await the agent's response messages and commit the completed conversation; salvage to the last completed step on a post-stream failure. */
150
+ /** Await one bounded SDK epoch and commit its exact append-only provider history. */
331
151
  async function commitStreamResult(deps, result) {
332
- const { loopState, callbacks, salvage } = deps;
152
+ const { loopState, callbacks, salvage, abortController } = deps;
333
153
  if (loopState.streamError && !loopState.streamFinished) {
334
154
  void Promise.resolve(result.responseMessages).catch(() => undefined);
335
155
  throw loopState.streamError;
336
156
  }
337
157
  try {
338
158
  const responseMessages = await result.responseMessages;
339
- const completedConversation = [...stripSyntheticControls(salvage.requestMessages), ...responseMessages];
340
- callbacks.setConversation(compactToolHistory(completedConversation).messages);
159
+ // Some providers settle responseMessages instead of rejecting when an
160
+ // abort ends the stream. Never commit that partial response as a normal
161
+ // completion: the attempt catch must classify the recorded abort cause.
162
+ if (abortController.signal.aborted)
163
+ throw abortController.signal.reason ?? new Error('aborted');
164
+ const providerConversation = [...salvage.requestMessages, ...responseMessages];
165
+ // Synthetic controls are request-local and must not enter session state,
166
+ // but every non-control provider message remains byte-for-byte unchanged.
167
+ callbacks.setConversation(stripSyntheticControls(providerConversation));
168
+ return providerConversation;
341
169
  }
342
170
  catch (error) {
343
171
  if (salvage.accumulated.length > 0) {
344
- callbacks.setConversation(compactToolHistory([...stripSyntheticControls(salvage.requestMessages), ...salvage.accumulated]).messages);
172
+ callbacks.setConversation([...stripSyntheticControls(salvage.requestMessages), ...salvage.accumulated]);
345
173
  }
174
+ // An idle timeout commonly makes AI SDK responseMessages reject with the
175
+ // generic "terminated" error after one or more completed tool steps. That
176
+ // is not benign: propagate it so model-stream retry/pause recovery runs.
177
+ if (abortController.signal.aborted)
178
+ throw loopState.streamError ?? error;
346
179
  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);
180
+ const benignTerminatedAfterStream = text === 'terminated' && (loopState.streamFinished || loopState.assistantText.trim().length > 0 || loopState.sawToolCall);
348
181
  if (!benignTerminatedAfterStream)
349
182
  throw loopState.streamError ?? error;
350
183
  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.' });
184
+ return [...salvage.requestMessages, ...salvage.accumulated];
357
185
  }
358
186
  }
359
187
  /**
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.
188
+ * Run exactly one AI SDK step. Keeping this in a separate async frame makes the
189
+ * ToolLoopAgent, StreamTextResult, and SDK StepResult graph collectible before
190
+ * the next provider request while retaining Vercel's provider/tool machinery.
364
191
  */
365
- export async function runAttemptStream(deps) {
192
+ async function runAgentEpoch(deps, requestMessages) {
366
193
  const { setup, callbacks, loopState, turnState, globalBudget, stallGuard, salvage, retryAttempt, abortController } = deps;
367
- const { sliceTools, stepCap, systemPrompt, inputBreakdown, providerSettings, omitMaxOutputTokens, toolExecutionContext, requestMessages } = setup;
194
+ const { sliceTools, systemPrompt, inputBreakdown, providerSettings, omitMaxOutputTokens, toolExecutionContext } = setup;
195
+ const prepare = createPrepareStep(deps);
196
+ const completedBefore = loopState.completedSteps;
197
+ salvage.requestMessages = requestMessages;
198
+ salvage.accumulated = [];
199
+ loopState.streamError = undefined;
200
+ loopState.streamFinished = false;
201
+ loopState.finishReason = undefined;
202
+ loopState.contextCompactedInEpoch = false;
203
+ // Epoch-final provider usage for the usage anchor (Pillar 1.1); onEnd fires
204
+ // before the stream promise settles, so stash and commit after commitStreamResult.
205
+ let epochUsage;
368
206
  const agent = new ToolLoopAgent({
369
207
  id: 'haze-main',
370
208
  model: setup.runtime.model,
@@ -372,31 +210,61 @@ export async function runAttemptStream(deps) {
372
210
  tools: sliceTools,
373
211
  ...(!omitMaxOutputTokens ? { maxOutputTokens: DEFAULT_MAX_OUTPUT_TOKENS } : {}),
374
212
  ...providerSettings,
375
- stopWhen: isStepCount(stepCap),
213
+ // One provider request + its tool batch per SDK object graph. A normal
214
+ // ToolLoopAgent would make the same next provider request internally.
215
+ stopWhen: isStepCount(1),
376
216
  runtimeContext: toolExecutionContext,
377
217
  toolsContext: toolsContextFor(sliceTools, toolExecutionContext),
378
218
  experimental_repairToolCall: createRepairToolCall(deps),
379
- prepareStep: createPrepareStep(deps),
219
+ prepareStep(args) {
220
+ const prepared = prepare(args);
221
+ // Preserve the exact provider-facing prefix across epochs, including a
222
+ // scoped control injected for this request. Session state strips those
223
+ // controls independently when the epoch commits.
224
+ const preparedMessages = prepared?.messages ?? args.messages;
225
+ salvage.requestMessages = preparedMessages;
226
+ if (completedBefore > 0) {
227
+ const messagesPreserved = requestMessages.length <= preparedMessages.length
228
+ && requestMessages.every((message, index) => preparedMessages[index] === message);
229
+ const requestPolicyStable = prepared?.activeTools == null
230
+ && prepared?.toolChoice == null
231
+ && prepared?.model == null
232
+ && prepared?.providerOptions == null;
233
+ const prefixPreserved = messagesPreserved && requestPolicyStable;
234
+ callbacks.onEvent?.(agentEvent({
235
+ type: 'resource_rollover',
236
+ attempt: retryAttempt + 1,
237
+ completedSteps: completedBefore,
238
+ toolCalls: loopState.generatedToolCalls,
239
+ prefixPreserved,
240
+ reason: prefixPreserved ? 'sdk-step-boundary' : loopState.contextCompactedInEpoch ? 'context-compaction' : 'request-policy-change',
241
+ }));
242
+ callbacks.debugLog(`ToolLoopAgent epoch rollover after step ${completedBefore}; provider prefix ${prefixPreserved ? 'preserved' : 'reset'}`);
243
+ }
244
+ return prepared;
245
+ },
380
246
  onStepStart({ stepNumber }) {
381
- callbacks.onEvent?.(agentEvent({ type: 'step_start', attempt: retryAttempt + 1, step: stepNumber + 1 }));
247
+ callbacks.onEvent?.(agentEvent({ type: 'step_start', attempt: retryAttempt + 1, step: loopState.completedSteps + stepNumber + 1 }));
382
248
  },
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.
249
+ onStepEnd({ text, content = [], toolCalls, toolResults, finishReason, usage, response }) {
250
+ // Tool-loop control must advance from this internally ordered callback.
387
251
  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.
252
+ recordCompletedStep(loopState, { text, toolCalls });
253
+ // Remember the last valid per-step usage for usage-overflow detection
254
+ // (Pillar 1.2); empty usage objects (some gateways/tests) keep the
255
+ // previous value or stay unset.
256
+ const stepUsage = stepCacheMetrics(usage);
257
+ if (stepUsage.inputTokens != null || usage?.outputTokens != null || stepUsage.cacheReadTokens > 0 || stepUsage.cacheWriteTokens > 0) {
258
+ loopState.lastUsage = { inputTokens: stepUsage.inputTokens, outputTokens: usage?.outputTokens ?? 0, cacheReadTokens: stepUsage.cacheReadTokens, cacheWriteTokens: stepUsage.cacheWriteTokens };
259
+ }
260
+ // Turn-wide counters remain shared across bounded SDK epochs, retries,
261
+ // and recovery slices. Executions are authoritative for tool-call usage.
393
262
  turnState.stepsUsed += 1;
394
263
  turnState.toolCallsUsed = globalBudget.started;
395
264
  if (toolCalls.length > 0 && text.trim().length === 0)
396
265
  turnState.toolOnlyStepsUsed += 1;
397
266
  if (Array.isArray(response?.messages) && response.messages.length > 0)
398
267
  salvage.accumulated = response.messages;
399
- const stepUsage = stepCacheMetrics(usage);
400
268
  const publicUsage = {
401
269
  inputTokens: stepUsage.inputTokens ?? 0,
402
270
  outputTokens: usage?.outputTokens ?? 0,
@@ -404,12 +272,13 @@ export async function runAttemptStream(deps) {
404
272
  cacheWriteTokens: stepUsage.cacheWriteTokens,
405
273
  reasoningTokens: stepUsage.reasoningTokens,
406
274
  };
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}`);
275
+ callbacks.onEvent?.(agentEvent({ type: 'step_end', attempt: retryAttempt + 1, step: loopState.completedSteps, finishReason, toolCallCount: toolCalls.length, usage: publicUsage, ...(response?.modelId ? { responseModel: response.modelId } : {}) }));
276
+ logEntry(callbacks.log, { at: new Date().toISOString(), type: 'step', stream: 'main', step: loopState.completedSteps - 1, 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 } });
277
+ callbacks.debugLog(`step ${loopState.completedSteps - 1} finished: ${finishReason}; text=${text.length}; toolCalls=${toolCalls.length}; toolResults=${toolResults.length}`);
410
278
  },
411
279
  onEnd(event) {
412
280
  const providerUsage = extractUsage({ usage: event.usage });
281
+ epochUsage = { inputTokens: providerUsage.inputTokens, outputTokens: providerUsage.outputTokens, cacheReadTokens: providerUsage.cacheReadTokens, cacheWriteTokens: providerUsage.cacheWriteTokens };
413
282
  callbacks.recordTokenUsage?.({
414
283
  inputTokens: providerUsage.inputTokens,
415
284
  outputTokens: providerUsage.outputTokens,
@@ -424,10 +293,9 @@ export async function runAttemptStream(deps) {
424
293
  logicalInputEstimate: inputBreakdown.logicalInputEstimate,
425
294
  effectiveNonCachedInput: providerUsage.effectiveNonCachedInput,
426
295
  });
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`);
296
+ const accumulated = [...salvage.requestMessages, ...event.responseMessages];
297
+ callbacks.setConversation(stripSyntheticControls(accumulated));
298
+ callbacks.debugLog(`conversation updated to ${accumulated.length} exact messages by ToolLoopAgent epoch`);
431
299
  },
432
300
  });
433
301
  stallGuard.rearm();
@@ -436,13 +304,160 @@ export async function runAttemptStream(deps) {
436
304
  stallGuard.noteStreamEvent(part.type);
437
305
  applyStreamPart(deps, part);
438
306
  }
439
- await commitStreamResult(deps, result);
307
+ const providerMessages = await commitStreamResult(deps, result);
308
+ // Re-anchor context estimation on the provider's own accounting for the
309
+ // committed history (Pillar 1.1). The anchor indexes the control-free
310
+ // message sequence so it stays aligned with durable conversation state.
311
+ const anchorTokens = contextTokensFromUsage(epochUsage ?? {});
312
+ if (anchorTokens != null)
313
+ deps.usageAnchor.current = { messageCount: stripSyntheticControls(providerMessages).length, contextTokens: anchorTokens };
314
+ return { providerMessages, completedSteps: loopState.completedSteps - completedBefore };
315
+ }
316
+ /**
317
+ * Mid-turn compaction at an epoch boundary (Pillar 1.5/1.6): before the next
318
+ * provider request, shrink the history when the (usage-anchored) estimate
319
+ * exceeds the message budget — the anchored total drives the decision, so
320
+ * token-dense history the chars/4 estimate undercounts still compacts. Large
321
+ * older halves get an LLM-written summary —
322
+ * chained from any previous compaction summary and split-turn aware — while
323
+ * small trims keep the deterministic heuristic excerpt. Any summarization
324
+ * failure falls back to the heuristic excerpt. Rewrites the provider prefix
325
+ * exactly once and invalidates the usage anchor (the next step re-anchors on
326
+ * fresh provider usage).
327
+ */
328
+ async function compactAtEpochBoundary(deps, providerMessages) {
329
+ const { setup, callbacks, loopState, goal, abortController, usageAnchor } = deps;
330
+ const overhead = setup.requestBudget.systemTokens + setup.requestBudget.toolSchemaTokens;
331
+ const estimate = estimateConversationTokens(providerMessages, usageAnchor.current, overhead);
332
+ const decision = chooseBoundaryCompactionMethod({ messages: providerMessages, messageTokenBudget: setup.requestBudget.messageTokens, olderTokenThreshold: COMPACTION_LLM_MIN_OLDER_TOKENS, totalTokens: estimate.tokens });
333
+ if (decision.method === 'none' || !decision.split)
334
+ return providerMessages;
335
+ const split = decision.split;
336
+ const tokenBudget = setup.requestBudget.messageTokens;
337
+ if (decision.method === 'heuristic') {
338
+ callbacks.onEvent?.(agentEvent({ type: 'compaction_start', reason: 'threshold', method: 'heuristic' }));
339
+ const result = compactModelMessages(providerMessages, { tokenBudget, workState: goal });
340
+ if (!result.compacted) {
341
+ // Nothing older qualified; close the opened event truthfully.
342
+ callbacks.onEvent?.(agentEvent({ type: 'compaction_end', reason: 'threshold', method: 'none', compacted: false }));
343
+ return providerMessages;
344
+ }
345
+ callbacks.onEvent?.(agentEvent({ type: 'compaction_end', reason: 'threshold', method: 'heuristic', compacted: true, olderCount: result.olderCount, keptCount: result.keptCount }));
346
+ callbacks.debugLog(`mid-turn compaction (heuristic): condensed ${result.olderCount} messages (${estimate.basis}-backed estimate ${estimate.tokens} > budget ${tokenBudget})`);
347
+ loopState.contextCompactedInEpoch = true;
348
+ usageAnchor.current = undefined;
349
+ callbacks.recordCompaction?.({ method: 'heuristic', olderCount: result.olderCount, keptCount: result.keptCount, summary: result.summary ?? '' });
350
+ callbacks.setConversation(result.messages);
351
+ return result.messages;
352
+ }
353
+ callbacks.onEvent?.(agentEvent({ type: 'compaction_start', reason: 'threshold', method: 'llm' }));
354
+ try {
355
+ const prompt = buildLlmCompactionPrompt({
356
+ older: split.older,
357
+ previousSummary: extractExistingCompactionSummary(providerMessages),
358
+ splitTurn: split.splitTurn,
359
+ });
360
+ const summarization = await generateText({
361
+ model: setup.runtime.model,
362
+ prompt,
363
+ maxOutputTokens: COMPACTION_LLM_MAX_OUTPUT_TOKENS,
364
+ abortSignal: abortController.signal,
365
+ });
366
+ const summaryText = summarization.text.trim();
367
+ if (!summaryText)
368
+ throw new Error('model returned an empty summary');
369
+ const result = compactModelMessagesWithSummary(providerMessages, { summaryText, tokenBudget, workState: goal });
370
+ if (!result.compacted)
371
+ throw new Error('nothing older to compact');
372
+ callbacks.onEvent?.(agentEvent({ type: 'compaction_end', reason: 'threshold', method: 'llm', compacted: true, olderCount: result.olderCount, keptCount: result.keptCount }));
373
+ callbacks.recordTokenUsage?.({
374
+ inputTokens: summarization.usage?.inputTokens,
375
+ outputTokens: summarization.usage?.outputTokens,
376
+ systemPrompt: 0,
377
+ messages: 0,
378
+ toolSchemas: 0,
379
+ outputEstimate: 0,
380
+ cacheReadTokens: summarization.usage?.inputTokenDetails?.cacheReadTokens ?? 0,
381
+ cacheWriteTokens: summarization.usage?.inputTokenDetails?.cacheWriteTokens ?? 0,
382
+ noCacheTokens: 0,
383
+ reasoningTokens: summarization.usage?.outputTokenDetails?.reasoningTokens ?? 0,
384
+ logicalInputEstimate: 0,
385
+ effectiveNonCachedInput: undefined,
386
+ });
387
+ callbacks.debugLog(`mid-turn compaction (llm summary${split.splitTurn ? ', split turn' : ''}${extractExistingCompactionSummary(providerMessages) ? ', chained' : ''}): condensed ${result.olderCount} messages (${estimate.basis}-backed estimate ${estimate.tokens} > budget ${tokenBudget})`);
388
+ loopState.contextCompactedInEpoch = true;
389
+ usageAnchor.current = undefined;
390
+ callbacks.recordCompaction?.({ method: 'llm', olderCount: result.olderCount, keptCount: result.keptCount, summary: result.summary ?? '' });
391
+ callbacks.setConversation(result.messages);
392
+ return result.messages;
393
+ }
394
+ catch (error) {
395
+ const message = error instanceof Error ? error.message : String(error);
396
+ callbacks.debugLog(`mid-turn LLM compaction failed (${message}); falling back to the heuristic excerpt`);
397
+ const fallback = compactModelMessages(providerMessages, { tokenBudget, workState: goal });
398
+ // One truthful end event: the heuristic excerpt's actual outcome, with the
399
+ // LLM failure attached for diagnosis.
400
+ callbacks.onEvent?.(agentEvent({ type: 'compaction_end', reason: 'threshold', method: fallback.compacted ? 'heuristic' : 'none', compacted: fallback.compacted, olderCount: fallback.olderCount, keptCount: fallback.keptCount, error: `llm summary failed: ${message}` }));
401
+ if (!fallback.compacted)
402
+ return providerMessages;
403
+ loopState.contextCompactedInEpoch = true;
404
+ usageAnchor.current = undefined;
405
+ callbacks.recordCompaction?.({ method: 'heuristic', olderCount: fallback.olderCount, keptCount: fallback.keptCount, summary: fallback.summary ?? '' });
406
+ callbacks.setConversation(fallback.messages);
407
+ return fallback.messages;
408
+ }
409
+ }
410
+ /**
411
+ * Drive one attempt through bounded ToolLoopAgent epochs. The provider prefix,
412
+ * tools, budgets, evidence, and deadline stay continuous; only the AI SDK's
413
+ * request-local retained graph is released at each completed step.
414
+ */
415
+ export async function runAttemptStream(deps) {
416
+ const { setup, callbacks, loopState, stallGuard, abortController } = deps;
417
+ let providerMessages = setup.requestMessages;
418
+ const attemptStartStep = loopState.completedSteps;
419
+ while (!abortController.signal.aborted) {
420
+ const epoch = await runAgentEpoch(deps, providerMessages);
421
+ providerMessages = epoch.providerMessages;
422
+ const attemptSteps = loopState.completedSteps - attemptStartStep;
423
+ const continueAfterTools = loopState.finishReason === 'tool-calls'
424
+ && epoch.completedSteps > 0
425
+ && attemptSteps < setup.stepCap;
426
+ if (!continueAfterTools)
427
+ break;
428
+ // Budget-aware mid-turn compaction before the next provider request
429
+ // (Pillar 1.5); a no-op while the conversation fits.
430
+ providerMessages = await compactAtEpochBoundary(deps, providerMessages);
431
+ }
432
+ if (loopState.currentAssistantText.trim().length > 0 || loopState.assistantStarted) {
433
+ finalizeAssistantSegment(loopState, callbacks);
434
+ }
435
+ else if (loopState.sawToolCall && loopState.assistantText.trim().length === 0) {
436
+ callbacks.addMessage({ role: 'system', text: 'Tool work ended without a substantive final answer.' });
437
+ }
438
+ stallGuard.clear();
439
+ // Non-error overflow detection from the last valid usage (Pillar 1.2):
440
+ // silent overflow (successful finish, usage over the window) and
441
+ // length-stop overflow (length finish, zero output, input filling the
442
+ // window). Both route to compact-and-retry in the attempt outcome.
443
+ const window = setup.runtime.config.contextWindowTokens;
444
+ const usage = loopState.lastUsage;
445
+ let usageOverflow;
446
+ if (usage && loopState.finishReason === 'stop' && isSilentContextOverflow({ inputTokens: usage.inputTokens, cacheReadTokens: usage.cacheReadTokens, contextWindowTokens: window })) {
447
+ usageOverflow = 'silent';
448
+ }
449
+ else if (usage && isLengthStopOverflow({ finishReason: loopState.finishReason, outputTokens: usage.outputTokens, inputTokens: usage.inputTokens, cacheReadTokens: usage.cacheReadTokens, contextWindowTokens: window })) {
450
+ usageOverflow = 'length-stop';
451
+ }
452
+ if (usageOverflow)
453
+ callbacks.debugLog(`detected ${usageOverflow} context overflow from provider usage (window ${window})`);
440
454
  return {
441
455
  finishReason: loopState.finishReason,
442
456
  lastToolOk: loopState.lastToolOk,
443
457
  assistantText: loopState.assistantText,
444
- sawToolCall: loopState.latestToolCalls.size > 0,
458
+ sawToolCall: loopState.sawToolCall,
445
459
  unresolvedMalformedToolName: loopState.unresolvedMalformedToolName,
446
460
  unresolvedToolInputError: loopState.unresolvedMalformedToolName != null,
461
+ usageOverflow,
447
462
  };
448
463
  }