@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
@@ -1,8 +1,11 @@
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 { estimateValueTokens } from '../../../core/agent/contextBudget.js';
4
- import { compactToolHistory, stripSyntheticControls } from '../../../core/agent/requestAssembly.js';
5
- import { DEFAULT_MAX_OUTPUT_TOKENS } from '../../../core/agent/budgets.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';
6
9
  import { toolsContextFor } from '../../../llm/tools/toolContext.js';
7
10
  import { busyToolLabel, toolCallSummary } from '../formatters.js';
8
11
  import { sanitizeAssistantText, assistantDisplayText, normalizeAssistantText, shouldStartAssistantStream } from './assistantText.js';
@@ -23,6 +26,7 @@ export function createAttemptLoopState(previousAssistantText, contextFiles, call
23
26
  streamFinished: false,
24
27
  finishReason: undefined,
25
28
  lastToolOk: undefined,
29
+ sawToolCall: false,
26
30
  pendingMalformedToolName: undefined,
27
31
  unresolvedMalformedToolName: undefined,
28
32
  malformedRecoveryAttempts: new Map(),
@@ -39,8 +43,43 @@ export function createAttemptLoopState(previousAssistantText, contextFiles, call
39
43
  callbacks.setLastAssistantText(text);
40
44
  },
41
45
  contextFiles,
46
+ completedSteps: 0,
47
+ generatedToolCalls: 0,
48
+ consecutiveToolOnlySteps: 0,
49
+ latestRepeatedToolNames: [],
50
+ seenToolCallFingerprints: new Set(),
51
+ contextCompactedInEpoch: false,
52
+ lastUsage: undefined,
42
53
  };
43
54
  }
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 };
64
+ }
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);
75
+ }
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;
82
+ }
44
83
  function applyStreamPart(deps, part) {
45
84
  const { loopState, callbacks, toolDisplay, setup } = deps;
46
85
  switch (part.type) {
@@ -67,6 +106,7 @@ function applyStreamPart(deps, part) {
67
106
  }
68
107
  case 'tool-input-start': {
69
108
  finalizePendingAssistantBeforeTool(deps);
109
+ loopState.sawToolCall = true;
70
110
  const toolCall = { toolCallId: part.id, toolName: part.toolName, input: {} };
71
111
  loopState.latestToolCalls.set(part.id, toolCall);
72
112
  loopState.inFlightTools.add(part.id);
@@ -76,6 +116,7 @@ function applyStreamPart(deps, part) {
76
116
  }
77
117
  case 'tool-call': {
78
118
  finalizePendingAssistantBeforeTool(deps);
119
+ loopState.sawToolCall = true;
79
120
  const toolCall = { toolCallId: part.toolCallId, toolName: part.toolName, input: part.input };
80
121
  loopState.latestToolCalls.set(part.toolCallId, toolCall);
81
122
  // Tool execution begins only after its complete input has parsed and validated.
@@ -106,44 +147,62 @@ function applyStreamPart(deps, part) {
106
147
  break;
107
148
  }
108
149
  }
109
- /** 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. */
110
151
  async function commitStreamResult(deps, result) {
111
- const { loopState, callbacks, salvage } = deps;
152
+ const { loopState, callbacks, salvage, abortController } = deps;
112
153
  if (loopState.streamError && !loopState.streamFinished) {
113
154
  void Promise.resolve(result.responseMessages).catch(() => undefined);
114
155
  throw loopState.streamError;
115
156
  }
116
157
  try {
117
158
  const responseMessages = await result.responseMessages;
118
- const completedConversation = [...stripSyntheticControls(salvage.requestMessages), ...responseMessages];
119
- 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;
120
169
  }
121
170
  catch (error) {
122
171
  if (salvage.accumulated.length > 0) {
123
- callbacks.setConversation(compactToolHistory([...stripSyntheticControls(salvage.requestMessages), ...salvage.accumulated]).messages);
172
+ callbacks.setConversation([...stripSyntheticControls(salvage.requestMessages), ...salvage.accumulated]);
124
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;
125
179
  const text = error instanceof Error ? error.message : String(error);
126
- 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);
127
181
  if (!benignTerminatedAfterStream)
128
182
  throw loopState.streamError ?? error;
129
183
  callbacks.debugLog(`ignored post-stream response error: ${text}`);
130
- }
131
- if (loopState.currentAssistantText.trim().length > 0 || loopState.assistantStarted) {
132
- finalizeAssistantSegment(loopState, callbacks);
133
- }
134
- else if (loopState.latestToolCalls.size > 0) {
135
- callbacks.addMessage({ role: 'system', text: 'Tool work ended without a substantive final answer.' });
184
+ return [...salvage.requestMessages, ...salvage.accumulated];
136
185
  }
137
186
  }
138
187
  /**
139
- * Drive one attempt's `ToolLoopAgent` stream: construct the agent (repair,
140
- * prepareStep, step observers), consume every stream part, and commit the
141
- * completed conversation. Throws the stream error so the attempt orchestrator
142
- * 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.
143
191
  */
144
- export async function runAttemptStream(deps) {
192
+ async function runAgentEpoch(deps, requestMessages) {
145
193
  const { setup, callbacks, loopState, turnState, globalBudget, stallGuard, salvage, retryAttempt, abortController } = deps;
146
- 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;
147
206
  const agent = new ToolLoopAgent({
148
207
  id: 'haze-main',
149
208
  model: setup.runtime.model,
@@ -151,31 +210,61 @@ export async function runAttemptStream(deps) {
151
210
  tools: sliceTools,
152
211
  ...(!omitMaxOutputTokens ? { maxOutputTokens: DEFAULT_MAX_OUTPUT_TOKENS } : {}),
153
212
  ...providerSettings,
154
- 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),
155
216
  runtimeContext: toolExecutionContext,
156
217
  toolsContext: toolsContextFor(sliceTools, toolExecutionContext),
157
218
  experimental_repairToolCall: createRepairToolCall(deps),
158
- 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
+ },
159
246
  onStepStart({ stepNumber }) {
160
- 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 }));
161
248
  },
162
- onStepEnd({ stepNumber, text, content = [], toolCalls, toolResults, finishReason, usage, response }) {
163
- // Tool-loop control must advance from this internal callback, which the
164
- // SDK awaits before prepareStep. Updating it from the public stream can
165
- // 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.
166
251
  loopState.toolResultState = applyStepToolResultState(loopState.toolResultState, content);
167
- // Turn-wide counters (shared across provider retries and recovery
168
- // slices) so the global budget cannot reset between attempts. The
169
- // execution-boundary budget (RH-003) is the authoritative count of
170
- // underlying executions; sync the turn state to it so blocked calls are
171
- // 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.
172
262
  turnState.stepsUsed += 1;
173
263
  turnState.toolCallsUsed = globalBudget.started;
174
264
  if (toolCalls.length > 0 && text.trim().length === 0)
175
265
  turnState.toolOnlyStepsUsed += 1;
176
266
  if (Array.isArray(response?.messages) && response.messages.length > 0)
177
267
  salvage.accumulated = response.messages;
178
- const stepUsage = stepCacheMetrics(usage);
179
268
  const publicUsage = {
180
269
  inputTokens: stepUsage.inputTokens ?? 0,
181
270
  outputTokens: usage?.outputTokens ?? 0,
@@ -183,12 +272,13 @@ export async function runAttemptStream(deps) {
183
272
  cacheWriteTokens: stepUsage.cacheWriteTokens,
184
273
  reasoningTokens: stepUsage.reasoningTokens,
185
274
  };
186
- callbacks.onEvent?.(agentEvent({ type: 'step_end', attempt: retryAttempt + 1, step: stepNumber + 1, finishReason, toolCallCount: toolCalls.length, usage: publicUsage, ...(response?.modelId ? { responseModel: response.modelId } : {}) }));
187
- 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 } });
188
- 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}`);
189
278
  },
190
279
  onEnd(event) {
191
280
  const providerUsage = extractUsage({ usage: event.usage });
281
+ epochUsage = { inputTokens: providerUsage.inputTokens, outputTokens: providerUsage.outputTokens, cacheReadTokens: providerUsage.cacheReadTokens, cacheWriteTokens: providerUsage.cacheWriteTokens };
192
282
  callbacks.recordTokenUsage?.({
193
283
  inputTokens: providerUsage.inputTokens,
194
284
  outputTokens: providerUsage.outputTokens,
@@ -203,10 +293,9 @@ export async function runAttemptStream(deps) {
203
293
  logicalInputEstimate: inputBreakdown.logicalInputEstimate,
204
294
  effectiveNonCachedInput: providerUsage.effectiveNonCachedInput,
205
295
  });
206
- const accumulated = [...stripSyntheticControls(requestMessages), ...event.responseMessages];
207
- const compacted = compactToolHistory(accumulated);
208
- callbacks.setConversation(compacted.messages);
209
- 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`);
210
299
  },
211
300
  });
212
301
  stallGuard.rearm();
@@ -215,13 +304,160 @@ export async function runAttemptStream(deps) {
215
304
  stallGuard.noteStreamEvent(part.type);
216
305
  applyStreamPart(deps, part);
217
306
  }
218
- 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})`);
219
454
  return {
220
455
  finishReason: loopState.finishReason,
221
456
  lastToolOk: loopState.lastToolOk,
222
457
  assistantText: loopState.assistantText,
223
- sawToolCall: loopState.latestToolCalls.size > 0,
458
+ sawToolCall: loopState.sawToolCall,
224
459
  unresolvedMalformedToolName: loopState.unresolvedMalformedToolName,
225
460
  unresolvedToolInputError: loopState.unresolvedMalformedToolName != null,
461
+ usageOverflow,
226
462
  };
227
463
  }
@@ -7,10 +7,18 @@ import { toolResultSummary } from '../formatters.js';
7
7
  import { toolDiffFromResult } from './toolGroupRenderer.js';
8
8
  import { isMalformedToolInputError } from './toolCallRecovery.js';
9
9
  import { logEntry, rememberContextFilesFromToolOutput, subagentTokenEstimate } from './turnRuntime.js';
10
+ function releaseCompletedToolCall(loopState, toolCallId) {
11
+ // The exact protocol message remains in provider history; display state has
12
+ // already reduced the input to a summary, so do not retain a second copy in
13
+ // per-attempt bookkeeping after the result/error is consumed.
14
+ loopState.latestToolCalls.delete(toolCallId);
15
+ loopState.startedTools.delete(toolCallId);
16
+ }
10
17
  export function handleToolResultPart(deps, part) {
11
18
  const { loopState, callbacks, toolDisplay, setup, goal } = deps;
12
19
  const toolCallId = part.toolCallId;
13
20
  const toolName = part.toolName;
21
+ loopState.sawToolCall = true;
14
22
  const toolCall = { toolCallId, toolName, input: part.input };
15
23
  loopState.latestToolCalls.set(toolCallId, toolCall);
16
24
  loopState.inFlightTools.delete(toolCallId);
@@ -25,6 +33,7 @@ export function handleToolResultPart(deps, part) {
25
33
  item.finishedAt = startedAt + (item.durationMs ?? 0);
26
34
  callbacks.onEvent?.(agentEvent({ type: 'tool_end', id: toolCall.toolCallId, name: toolCall.toolName, success: false, errorCode: 'tool_budget_blocked', durationMs: item.durationMs ?? 0 }));
27
35
  toolDisplay.updateToolGroup(true);
36
+ releaseCompletedToolCall(loopState, toolCallId);
28
37
  return;
29
38
  }
30
39
  // A deadline-exceeded call was terminated at the wrapper boundary; the
@@ -39,6 +48,7 @@ export function handleToolResultPart(deps, part) {
39
48
  callbacks.onEvent?.(agentEvent({ type: 'tool_end', id: toolCall.toolCallId, name: toolCall.toolName, success: false, errorCode: 'tool_deadline', durationMs }));
40
49
  callbacks.onEvent?.(agentEvent({ type: 'timeout', phase: 'tool', timeoutMs: toolName === 'subagent' ? SUBAGENT_TOOL_DEADLINE_MS : DEFAULT_TOOL_DEADLINE_MS }));
41
50
  toolDisplay.updateToolGroup(true);
51
+ releaseCompletedToolCall(loopState, toolCallId);
42
52
  return;
43
53
  }
44
54
  const ok = toolOutputOk(part.output, true);
@@ -65,11 +75,13 @@ export function handleToolResultPart(deps, part) {
65
75
  if (nestedTokens)
66
76
  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 });
67
77
  toolDisplay.updateToolGroup(true);
78
+ releaseCompletedToolCall(loopState, toolCallId);
68
79
  }
69
80
  export function handleToolErrorPart(deps, part) {
70
81
  const { loopState, callbacks, toolDisplay, setup, goal } = deps;
71
82
  const toolCallId = part.toolCallId;
72
83
  const toolName = part.toolName;
84
+ loopState.sawToolCall = true;
73
85
  loopState.inFlightTools.delete(toolCallId);
74
86
  const existing = loopState.latestToolCalls.get(toolCallId);
75
87
  const toolCall = { toolCallId, toolName, input: part.input ?? existing?.input };
@@ -92,4 +104,5 @@ export function handleToolErrorPart(deps, part) {
92
104
  callbacks.setWorkState?.(goal);
93
105
  callbacks.setGoalStatus?.(formatGoalStatus(goal));
94
106
  toolDisplay.updateToolGroup(true);
107
+ releaseCompletedToolCall(loopState, toolCallId);
95
108
  }
@@ -16,7 +16,7 @@ export interface TokenUsage {
16
16
  logicalInputEstimate: number;
17
17
  effectiveNonCachedInput: number | undefined;
18
18
  }
19
- export declare function retryDelayMs(attempt: number): number;
19
+ export declare function retryDelayMs(attempt: number, baseDelayMs?: number): number;
20
20
  /** Append one entry to the per-turn LLM log when file logging is enabled; never blocks the turn. */
21
21
  export declare function logEntry(log: LlmLog | undefined, entry: LlmLogEntry): void;
22
22
  export declare function abortableDelay(milliseconds: number, signal: AbortSignal): Promise<void>;
@@ -1,7 +1,8 @@
1
1
  import { appendLogEntry as logAppend } from '../../../core/log/llmLog.js';
2
2
  import { cacheHitRatio, contextBreakdown, effectiveNonCachedInput, estimateValueTokens } from '../../../core/agent/contextBudget.js';
3
- export function retryDelayMs(attempt) {
4
- return Math.min(4000, 1000 * 2 ** attempt);
3
+ import { DEFAULT_RETRY_BASE_DELAY_MS } from '../../../core/agent/budgets.js';
4
+ export function retryDelayMs(attempt, baseDelayMs = DEFAULT_RETRY_BASE_DELAY_MS) {
5
+ return Math.min(baseDelayMs * 4, baseDelayMs * 2 ** attempt);
5
6
  }
6
7
  /** Append one entry to the per-turn LLM log when file logging is enabled; never blocks the turn. */
7
8
  export function logEntry(log, entry) {
@@ -5,10 +5,12 @@ import type { ImageAttachment } from '../../core/attachments/imageAttachments.js
5
5
  import { type BlessedPath } from '../../core/attachments/readBlessings.js';
6
6
  import type { TurnCompletionEvidence } from '../../core/agent/completionController.js';
7
7
  import type { RedEvidence, ValidationOutcome, WorkTaskProgress, WorkState } from '../../core/agent/workState.js';
8
+ import type { ValidationKind } from '../../llm/toolResultTypes.js';
8
9
  import type { SubagentOverrides, TurnExecutionScope } from '../../llm/requestContext.js';
9
10
  import type { PromptSession } from '../../llm/systemPrompt.js';
11
+ import type { StoredReasoningSetting } from '../../core/agent/reasoningPolicy.js';
10
12
  import type { ContextFile } from '../../config/contextFiles.js';
11
- import type { IncompleteGoalResume } from './streaming/goalCheckpoint.js';
13
+ import { type GoalCheckpoint, type IncompleteGoalResume } from './streaming/goalCheckpoint.js';
12
14
  import { type TokenUsage } from './streaming/turnRuntime.js';
13
15
  import type { ToolDisplayDiff } from './streaming/toolGroupRenderer.js';
14
16
  export type Message = {
@@ -32,6 +34,8 @@ export interface TurnResult {
32
34
  abortReason?: 'user' | 'turn-deadline';
33
35
  /** Bounded, safe completion evidence (no raw commands/output). Additive. */
34
36
  evidence?: TurnCompletionEvidence;
37
+ /** Goal-scoped obligations survive every failed exit, including transport failures. */
38
+ checkpoint?: GoalCheckpoint;
35
39
  /**
36
40
  * The turn paused with recoverable work unfinished; this carries what a
37
41
  * one-key/automatic resume needs instead of forcing the user to restate the
@@ -65,6 +69,7 @@ interface TurnGoalContext {
65
69
  validationOutcome: ValidationOutcome;
66
70
  taskProgress?: WorkTaskProgress;
67
71
  redEvidence?: RedEvidence;
72
+ validationKind?: ValidationKind;
68
73
  };
69
74
  /** Consecutive no-progress physical turns at goal level (diagnostics). */
70
75
  noProgressCount: number;
@@ -107,11 +112,19 @@ export interface StreamCallbacks {
107
112
  setGoalStatus?: (status: string | undefined) => void;
108
113
  onEvent?: AgentEventSink;
109
114
  compactConversation?: (instructions?: string) => boolean;
115
+ /** Durable compaction audit hook (Pillar 1.7): fired for every automatic compaction that rewrites the conversation, mirroring the session `compact` entry shape. */
116
+ recordCompaction?: (entry: {
117
+ method: 'heuristic' | 'llm';
118
+ olderCount: number;
119
+ keptCount: number;
120
+ instructions?: string;
121
+ summary: string;
122
+ }) => void;
110
123
  recordTokenUsage?: (usage: TokenUsage) => void;
111
124
  setWorkState?: (state: WorkState) => void;
112
125
  onTasksChanged?: () => void;
113
126
  log?: LlmLog;
114
127
  contextFileSignatures?: Map<string, string>;
115
128
  }
116
- export declare function runAgentTurn(value: string, displayValue: string | undefined, contextFiles: ContextFile[], callbacks: StreamCallbacks, retryAttempt?: number, retryingExistingRequest?: boolean, contextOverflowRecovered?: boolean, session?: PromptSession, modelOverride?: string, turnOptions?: TurnExecutionOptions): Promise<TurnResult>;
129
+ export declare function runAgentTurn(value: string, displayValue: string | undefined, contextFiles: ContextFile[], callbacks: StreamCallbacks, retryAttempt?: number, retryingExistingRequest?: boolean, contextOverflowRecovered?: boolean, session?: PromptSession, modelOverride?: string, turnOptions?: TurnExecutionOptions, reasoningOverride?: StoredReasoningSetting): Promise<TurnResult>;
117
130
  export {};