@denizokcu/haze 1.1.1 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/CHANGELOG.md +25 -0
  2. package/README.md +15 -12
  3. package/SECURITY.md +1 -1
  4. package/dist/buildInfo.json +3 -3
  5. package/dist/cli/chat/sessionLifecycle.js +2 -0
  6. package/dist/cli/chat/sessionRecorder.d.ts +7 -0
  7. package/dist/cli/chat/sessionRecorder.js +6 -0
  8. package/dist/cli/commands/chat.js +24 -2
  9. package/dist/cli/commands/runCommand.js +6 -0
  10. package/dist/cli/commands/streaming/agentAttempt.d.ts +11 -1
  11. package/dist/cli/commands/streaming/agentAttempt.js +9 -5
  12. package/dist/cli/commands/streaming/attemptOutcome.d.ts +23 -3
  13. package/dist/cli/commands/streaming/attemptOutcome.js +52 -9
  14. package/dist/cli/commands/streaming/attemptSetup.d.ts +10 -3
  15. package/dist/cli/commands/streaming/attemptSetup.js +30 -13
  16. package/dist/cli/commands/streaming/goalSupervisor.d.ts +1 -1
  17. package/dist/cli/commands/streaming/goalSupervisor.js +9 -0
  18. package/dist/cli/commands/streaming/prepareStep.d.ts +6 -1
  19. package/dist/cli/commands/streaming/prepareStep.js +35 -19
  20. package/dist/cli/commands/streaming/stallRecovery.js +2 -2
  21. package/dist/cli/commands/streaming/streamLoop.d.ts +31 -4
  22. package/dist/cli/commands/streaming/streamLoop.js +280 -44
  23. package/dist/cli/commands/streaming/toolPartHandlers.js +13 -0
  24. package/dist/cli/commands/streaming/turnRuntime.d.ts +1 -1
  25. package/dist/cli/commands/streaming/turnRuntime.js +3 -2
  26. package/dist/cli/commands/streaming.d.ts +8 -0
  27. package/dist/cli/commands/streaming.js +14 -4
  28. package/dist/cli/index.js +3 -2
  29. package/dist/config/modelCatalog.d.ts +32 -0
  30. package/dist/config/modelCatalog.js +84 -0
  31. package/dist/config/settings.d.ts +10 -2
  32. package/dist/config/settings.js +3 -0
  33. package/dist/core/agent/budgets.d.ts +10 -0
  34. package/dist/core/agent/budgets.js +10 -0
  35. package/dist/core/agent/compaction.d.ts +42 -3
  36. package/dist/core/agent/compaction.js +53 -5
  37. package/dist/core/agent/completionController.d.ts +3 -1
  38. package/dist/core/agent/completionController.js +1 -0
  39. package/dist/core/agent/contextBudget.d.ts +56 -0
  40. package/dist/core/agent/contextBudget.js +53 -0
  41. package/dist/core/agent/errors.js +2 -2
  42. package/dist/core/agent/events.d.ts +24 -1
  43. package/dist/core/agent/overflow.d.ts +45 -0
  44. package/dist/core/agent/overflow.js +91 -0
  45. package/dist/core/agent/requestAssembly.d.ts +7 -0
  46. package/dist/core/agent/requestAssembly.js +15 -7
  47. package/dist/core/agent/workState.js +13 -1
  48. package/dist/core/safety/shellClassifier.d.ts +16 -0
  49. package/dist/core/safety/shellClassifier.js +31 -0
  50. package/dist/core/session/sessionStore.d.ts +10 -0
  51. package/dist/core/session/sessionStore.js +6 -0
  52. package/dist/core/validation/outputParser.d.ts +1 -1
  53. package/dist/core/validation/outputParser.js +6 -1
  54. package/dist/llm/client.d.ts +2 -2
  55. package/dist/llm/client.js +14 -6
  56. package/dist/llm/tools/shellTool.js +27 -8
  57. package/dist/ui/components/TextInput.d.ts +18 -1
  58. package/dist/ui/components/TextInput.js +44 -6
  59. package/package.json +16 -15
@@ -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) {
@@ -107,6 +107,14 @@ export interface StreamCallbacks {
107
107
  setGoalStatus?: (status: string | undefined) => void;
108
108
  onEvent?: AgentEventSink;
109
109
  compactConversation?: (instructions?: string) => boolean;
110
+ /** Durable compaction audit hook (Pillar 1.7): fired for every automatic compaction that rewrites the conversation, mirroring the session `compact` entry shape. */
111
+ recordCompaction?: (entry: {
112
+ method: 'heuristic' | 'llm';
113
+ olderCount: number;
114
+ keptCount: number;
115
+ instructions?: string;
116
+ summary: string;
117
+ }) => void;
110
118
  recordTokenUsage?: (usage: TokenUsage) => void;
111
119
  setWorkState?: (state: WorkState) => void;
112
120
  onTasksChanged?: () => void;
@@ -2,7 +2,7 @@ import { agentEvent } from '../../core/agent/events.js';
2
2
  import { createTurnExecutionState, toCompletionEvidence } from '../../core/agent/completionController.js';
3
3
  import { createSessionGoal } from '../../core/agent/goalPolicy.js';
4
4
  import { seedCarriedGoalEvidence } from '../../core/agent/workState.js';
5
- import { createToolExecutionBudget, mainTurnBudget, DEFAULT_TURN_DEADLINE_MS } from '../../core/agent/budgets.js';
5
+ import { createToolExecutionBudget, mainTurnBudget, DEFAULT_TURN_DEADLINE_MS, OVERFLOW_SHRINK_FACTOR } from '../../core/agent/budgets.js';
6
6
  import { createAbsoluteDeadline } from '../../core/deadline.js';
7
7
  import { modelThinkingLabel } from '../../utils/modelName.js';
8
8
  import { abortableDelay } from './streaming/turnRuntime.js';
@@ -36,6 +36,10 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
36
36
  // logical goal shares the same lease.
37
37
  const turnScope = turnOptions.sharedTurnScope ?? {};
38
38
  const turnBudget = mainTurnBudget();
39
+ // Turn-scoped provider-usage anchor (Pillar 1.1): context estimation prefers
40
+ // real usage from the last completed step, with chars/4 estimates only for
41
+ // trailing messages. Shared across attempts and invalidated by compaction.
42
+ const usageAnchor = { current: undefined };
39
43
  // Turn-wide execution budget (RH-003): one authoritative counter of
40
44
  // underlying tool executions, shared across retries and recovery slices so
41
45
  // the global limit cannot be reset or exceeded. The slice budget caps the
@@ -57,7 +61,9 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
57
61
  turnState.intent = goal.intent;
58
62
  let activeOptions = turnOptions;
59
63
  let attempt = retryAttempt;
60
- let overflowRecovered = contextOverflowRecovered;
64
+ let overflowRetries = contextOverflowRecovered ? 1 : 0;
65
+ let overflowShrinkFactor = contextOverflowRecovered ? OVERFLOW_SHRINK_FACTOR : 1;
66
+ let stepsUsedAtLastRetry = 0;
61
67
  let retrying = retryingExistingRequest;
62
68
  // The attempt machinery runs against quarantinable callbacks so an
63
69
  // abort-ignoring stream that outlives forced settlement cannot mutate the
@@ -80,7 +86,7 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
80
86
  },
81
87
  });
82
88
  const cleanup = createAttemptCleanupRegistry();
83
- const result = await awaitAttemptWithForcedSettlement(runAgentAttempt({ value, contextFiles, callbacks: attemptCallbacks, retryAttempt: attempt, retryingExistingRequest: retrying, contextOverflowRecovered: overflowRecovered, session, modelOverride, abortController, turnOptions: activeOptions, turnScope, turnState, turnBudget, globalBudget, sliceBudget, goal, abortCause, cleanup, remainingTurnDeadlineMs: () => Math.max(0, turnDeadlineMs - (Date.now() - turnStartedAt)) }), {
89
+ const result = await awaitAttemptWithForcedSettlement(runAgentAttempt({ value, contextFiles, callbacks: attemptCallbacks, retryAttempt: attempt, retryingExistingRequest: retrying, overflowShrinkFactor, overflowRetries, progressSinceLastRetry: turnState.stepsUsed > stepsUsedAtLastRetry, session, modelOverride, abortController, turnOptions: activeOptions, turnScope, turnState, turnBudget, globalBudget, sliceBudget, goal, abortCause, cleanup, remainingTurnDeadlineMs: () => Math.max(0, turnDeadlineMs - (Date.now() - turnStartedAt)), usageAnchor }), {
84
90
  abortController,
85
91
  cleanup,
86
92
  quarantine,
@@ -102,7 +108,11 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
102
108
  resume = result.resume;
103
109
  if (result.retry) {
104
110
  attempt = result.retry.attempt;
105
- overflowRecovered = result.retry.contextOverflowRecovered;
111
+ if (result.retry.overflowShrinkFactor != null) {
112
+ overflowRetries += 1;
113
+ overflowShrinkFactor = result.retry.overflowShrinkFactor;
114
+ }
115
+ stepsUsedAtLastRetry = turnState.stepsUsed;
106
116
  retrying = true;
107
117
  if (result.retry.freshController) {
108
118
  // The idle stall aborted the previous controller to kill the hung
package/dist/cli/index.js CHANGED
@@ -50,8 +50,9 @@ Print mode (-p):
50
50
  run only (no settings change) and must already be registered under a provider (add it once via
51
51
  the /provider picker). Print-mode runs are non-durable: --continue is ignored and no session is
52
52
  saved. --resume <id> loads saved context for the turn without changing that session. On a
53
- provider context overflow, haze compacts the conversation and retries the request once; when
54
- compaction is unavailable, the error says so explicitly.
53
+ provider context overflow, haze compacts the conversation and retries at a progressively smaller
54
+ message budget (up to twice); exhausted retries pause with a context_exhausted checkpoint, and
55
+ when compaction is unavailable, the error says so explicitly.
55
56
  `);
56
57
  async function readStdinPrompt() {
57
58
  // Only read stdin when it is piped (non-TTY); never hang waiting on an interactive terminal.
@@ -0,0 +1,32 @@
1
+ /**
2
+ * Curated model metadata catalog (Pillar 1.8 of the Pi learning roadmap).
3
+ *
4
+ * Keys are **model-name patterns** (not provider names) because haze reaches
5
+ * most models through user-configured OpenAI-compatible gateways where the
6
+ * provider name is arbitrary — the model id is the only stable identity.
7
+ *
8
+ * Precedence (enforced in `llm/client.ts`): per-model `modelLimits` settings →
9
+ * this catalog → user-set context-window fallback → built-in default fallback.
10
+ * Values are deliberately conservative (input-safe): when a family differs
11
+ * between variants, the smaller window wins — under-budgeting only compacts a
12
+ * little earlier, over-budgeting hard-fails the request. First match wins, so
13
+ * keep more specific patterns before broader family prefixes.
14
+ *
15
+ * Local inference servers (localhost URLs) never consult the catalog: their
16
+ * effective window is set by server configuration (often far below the model's
17
+ * nominal window) and silent truncation there is undetectable.
18
+ */
19
+ export interface CatalogModelLimits {
20
+ contextWindowTokens: number;
21
+ maxOutputTokens?: number;
22
+ }
23
+ interface CatalogEntry extends CatalogModelLimits {
24
+ /** Lower-cased model-name pattern; matched with `startsWith` unless it contains '*', then prefix-before-'*' match. */
25
+ match: string;
26
+ note?: string;
27
+ }
28
+ /** Look up catalog limits for a model name (case-insensitive prefix families). Gateway-style `vendor/model` and `vendor:model` identifiers match on their final segment. */
29
+ export declare function catalogLimitsFor(modelName: string): CatalogModelLimits | undefined;
30
+ /** Catalog entries exposed for pinning tests (like the theme registry). */
31
+ export declare function getModelCatalog(): readonly CatalogEntry[];
32
+ export {};