@denizokcu/haze 0.2.0 → 0.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 (50) hide show
  1. package/CHANGELOG.md +41 -0
  2. package/README.md +38 -22
  3. package/dist/cli/commands/chat.d.ts +1 -1
  4. package/dist/cli/commands/chat.js +411 -74
  5. package/dist/cli/commands/commands.js +122 -54
  6. package/dist/cli/commands/formatters.d.ts +2 -0
  7. package/dist/cli/commands/formatters.js +34 -0
  8. package/dist/cli/commands/streaming.d.ts +36 -1
  9. package/dist/cli/commands/streaming.js +312 -103
  10. package/dist/cli/contextReport.d.ts +1 -0
  11. package/dist/cli/contextReport.js +47 -0
  12. package/dist/config/contextFiles.d.ts +25 -0
  13. package/dist/config/contextFiles.js +53 -0
  14. package/dist/config/providerPresets.d.ts +23 -0
  15. package/dist/config/providerPresets.js +230 -0
  16. package/dist/core/agent/compaction.d.ts +3 -0
  17. package/dist/core/agent/compaction.js +23 -3
  18. package/dist/core/agent/contextBudget.d.ts +33 -0
  19. package/dist/core/agent/contextBudget.js +88 -0
  20. package/dist/core/agent/requestAssembly.d.ts +22 -0
  21. package/dist/core/agent/requestAssembly.js +146 -0
  22. package/dist/core/agent/toolOutputStore.d.ts +11 -0
  23. package/dist/core/agent/toolOutputStore.js +33 -0
  24. package/dist/core/agent/workState.d.ts +38 -0
  25. package/dist/core/agent/workState.js +89 -0
  26. package/dist/core/goal/completionPolicy.js +1 -1
  27. package/dist/core/goal/sessionGoal.d.ts +2 -0
  28. package/dist/core/goal/sessionGoal.js +8 -1
  29. package/dist/core/log/llmLog.d.ts +68 -0
  30. package/dist/core/log/llmLog.js +55 -0
  31. package/dist/core/session/sessionStore.d.ts +6 -0
  32. package/dist/core/session/sessionStore.js +5 -0
  33. package/dist/core/subagent/subagentRunner.d.ts +4 -1
  34. package/dist/core/subagent/subagentRunner.js +5 -15
  35. package/dist/core/tasks/taskStorage.d.ts +13 -0
  36. package/dist/core/tasks/taskStorage.js +29 -0
  37. package/dist/core/validation/outputParser.js +15 -2
  38. package/dist/llm/client.d.ts +39 -0
  39. package/dist/llm/client.js +46 -2
  40. package/dist/llm/hazeTools.d.ts +53 -12
  41. package/dist/llm/hazeTools.js +170 -46
  42. package/dist/llm/systemPrompt.d.ts +6 -1
  43. package/dist/llm/systemPrompt.js +42 -79
  44. package/dist/skills/builder/SkillBuilder.d.ts +16 -2
  45. package/dist/skills/builder/SkillBuilder.js +68 -65
  46. package/dist/skills/skillTools.d.ts +2 -19
  47. package/dist/skills/skillTools.js +28 -19
  48. package/dist/ui/components/TextInput.d.ts +2 -1
  49. package/dist/ui/components/TextInput.js +6 -2
  50. package/package.json +2 -1
@@ -1,16 +1,21 @@
1
1
  import { stepCountIs, streamText } from 'ai';
2
- import { model } from '../../llm/client.js';
2
+ import { appendLogEntry as logAppend } from '../../core/log/llmLog.js';
3
+ import { modelWithConfig, providerRequestSettings } from '../../llm/client.js';
3
4
  import { hazeTools } from '../../llm/hazeTools.js';
4
5
  import { buildSystemPrompt } from '../../llm/systemPrompt.js';
5
6
  import { loadSkillRegistry } from '../../skills/SkillRegistry.js';
6
7
  import { buildSkillTools } from '../../skills/skillTools.js';
7
- import { compact, toolCallSummary, toolResultSummary, formatSeconds } from './formatters.js';
8
+ import { compact, toolCallSummary, toolResultSummary, formatElapsedTime, formatElapsedTimeWhole, formatSeconds } from './formatters.js';
8
9
  import { isActionRequest, isPlanImplementationRequest, isPlanOnlyRequest, isValidationRequest } from '../../core/goal/requestClassifier.js';
9
10
  import { completionDecision, looksIncomplete, noTextAfterToolPrompt, postContinuationPrompt, toolLoopBudgetPrompt } from '../../core/goal/completionPolicy.js';
10
11
  import { createSessionGoal, formatGoalStatus, observeGoalToolEvent } from '../../core/goal/sessionGoal.js';
11
12
  import { agentEvent } from '../../core/agent/events.js';
12
13
  import { isContextOverflowError, isRetryableModelError } from '../../core/agent/errors.js';
13
14
  import { createSubagentTool } from '../../core/subagent/subagentRunner.js';
15
+ import { contextBreakdown, cacheHitRatio, effectiveNonCachedInput, estimateValueTokens } from '../../core/agent/contextBudget.js';
16
+ import { compactToolHistory, stripSyntheticControls, toolRequestSettings, withSyntheticControl } from '../../core/agent/requestAssembly.js';
17
+ import { compactModelMessages } from '../../core/agent/compaction.js';
18
+ import { workStatePrompt } from '../../core/agent/workState.js';
14
19
  function stableToolKey(toolCall) {
15
20
  return `${toolCall.toolName}:${JSON.stringify(toolCall.input)}`;
16
21
  }
@@ -82,19 +87,56 @@ async function abortableDelay(milliseconds, signal) {
82
87
  }
83
88
  const DEFAULT_MAX_OUTPUT_TOKENS = 16384;
84
89
  const IDLE_TIMEOUT_MS = 5 * 60_000;
85
- const MAIN_STEP_LIMIT = 40;
90
+ const MAIN_STEP_LIMIT = 64;
86
91
  const MAIN_TOOL_CALL_LIMIT = 40;
87
- const MAIN_TOOL_ONLY_STEP_LIMIT = 12;
88
- const FOLLOW_UP_STEP_LIMIT = 30;
89
- const FOLLOW_UP_TOOL_CALL_LIMIT = 30;
90
- const FOLLOW_UP_TOOL_ONLY_STEP_LIMIT = 10;
91
- const COMPLETION_CONTINUATION_LIMIT = 30;
92
+ const MAIN_TOOL_ONLY_STEP_LIMIT = 24;
93
+ const FOLLOW_UP_STEP_LIMIT = 64;
94
+ const FOLLOW_UP_TOOL_CALL_LIMIT = 40;
95
+ const FOLLOW_UP_TOOL_ONLY_STEP_LIMIT = 24;
96
+ const COMPLETION_CONTINUATION_LIMIT = 12;
97
+ const ACTIVE_CONTEXT_TOKEN_BUDGET = 40_000;
92
98
  function toolOutputOk(output, success) {
93
99
  if (!success)
94
100
  return false;
95
101
  return !(typeof output === 'object' && output != null && 'ok' in output && output.ok === false);
96
102
  }
97
- export async function runAgentTurn(value, displayValue, contextFiles, callbacks, retryAttempt = 0, retryingExistingRequest = false, contextOverflowRecovered = false) {
103
+ function estimateInputBreakdown(input) {
104
+ const breakdown = contextBreakdown(input);
105
+ return {
106
+ breakdown,
107
+ systemPrompt: breakdown.system,
108
+ messages: Object.values(breakdown.messagesByRole).reduce((sum, value) => sum + value, 0),
109
+ toolSchemas: breakdown.toolSchemas.reduce((sum, value) => sum + value.tokens, 0),
110
+ logicalInputEstimate: breakdown.logicalInputEstimate,
111
+ };
112
+ }
113
+ function logEntry(log, entry) {
114
+ if (log)
115
+ void logAppend(log, entry).catch(() => undefined);
116
+ }
117
+ function subagentTokenEstimate(output) {
118
+ if (typeof output !== 'object' || output == null || !('tokens' in output))
119
+ return undefined;
120
+ const tokens = output.tokens;
121
+ const input = typeof tokens?.in === 'number' ? tokens.in : 0;
122
+ const outputTokens = typeof tokens?.out === 'number' ? tokens.out : 0;
123
+ return input > 0 || outputTokens > 0 ? { input, output: outputTokens } : undefined;
124
+ }
125
+ function extractUsage(event) {
126
+ const cacheReadTokens = event.usage?.inputTokenDetails?.cacheReadTokens ?? 0;
127
+ const reportedNoCache = 'noCacheTokens' in (event.usage?.inputTokenDetails ?? {})
128
+ ? (event.usage?.inputTokenDetails).noCacheTokens
129
+ : undefined;
130
+ return {
131
+ inputTokens: event.usage?.inputTokens,
132
+ outputTokens: event.usage?.outputTokens,
133
+ cacheReadTokens,
134
+ cacheWriteTokens: event.usage?.inputTokenDetails?.cacheWriteTokens ?? 0,
135
+ noCacheTokens: reportedNoCache ?? effectiveNonCachedInput(event.usage?.inputTokens, cacheReadTokens) ?? 0,
136
+ reasoningTokens: event.usage?.outputTokenDetails?.reasoningTokens ?? 0,
137
+ };
138
+ }
139
+ export async function runAgentTurn(value, displayValue, contextFiles, callbacks, retryAttempt = 0, retryingExistingRequest = false, contextOverflowRecovered = false, session) {
98
140
  const displayVal = displayValue ?? value;
99
141
  const userMessage = { role: 'user', text: displayVal };
100
142
  callbacks.onEvent?.(agentEvent({ type: 'turn_start', request: value }));
@@ -104,39 +146,51 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
104
146
  const abortController = new AbortController();
105
147
  callbacks.setAbortController?.(abortController);
106
148
  let turnStatus = 'failed';
149
+ let turnStopReason;
107
150
  let idleTimer;
151
+ let stopActiveTimers = () => undefined;
108
152
  const resetIdleTimer = () => {
109
153
  if (idleTimer)
110
154
  clearTimeout(idleTimer);
111
- idleTimer = setTimeout(() => abortController.abort('Haze turn timed out after no model/tool activity.'), IDLE_TIMEOUT_MS);
155
+ idleTimer = setTimeout(() => {
156
+ turnStopReason = { kind: 'idle_timeout', message: `Stopped after ${Math.round(IDLE_TIMEOUT_MS / 60_000)} minutes of no activity. Type "continue" to resume — Haze will pick up where it left off.` };
157
+ abortController.abort('Haze turn timed out after no model/tool activity.');
158
+ }, IDLE_TIMEOUT_MS);
112
159
  };
113
160
  try {
114
- const m = await model();
115
- if (!m) {
161
+ const runtime = await modelWithConfig(session ? { cwd: session.cwd } : undefined);
162
+ if (!runtime.model) {
116
163
  callbacks.addMessage({ role: 'assistant', text: 'No model provider configured. Run /provider to choose or add a provider. Haze cannot hallucinate without a model. Progress.' });
117
164
  return;
118
165
  }
119
- const activeModel = m;
166
+ const activeModel = runtime.model;
167
+ const providerSettings = providerRequestSettings(runtime.config);
120
168
  const skillRegistry = await loadSkillRegistry();
121
- const subagentTool = createSubagentTool({ model: activeModel, contextFiles });
169
+ const subagentTool = createSubagentTool({ model: activeModel, contextFiles, session });
122
170
  const availableTools = { ...hazeTools, subagent: subagentTool, ...buildSkillTools(skillRegistry) };
123
171
  const goal = createSessionGoal(value);
172
+ callbacks.setWorkState?.(goal.workState);
124
173
  callbacks.setGoalStatus?.(formatGoalStatus(goal));
125
174
  const likelyPlanOnlyRequest = isPlanOnlyRequest(value);
126
175
  const likelyPlanImplementationRequest = isPlanImplementationRequest(value);
127
176
  const likelyActionRequest = isActionRequest(value);
128
177
  const likelyValidationRequest = isValidationRequest(value);
129
178
  const planImplementationGuidance = 'Haze internal guidance for implementing plan files. The original user request remains authoritative. First identify the concrete required checklist items and compare them with the current files. Do not edit source or tests when the required behavior is already present. Implement the smallest clearly required phase or required items, skip optional/design-question items unless explicitly requested, add tests rather than exploratory one-off scripts where possible, prefer file tools for source changes, run validation once after code/test edits, then update plan status with file tools if requested. Do not call unresolved optional scope a blocker.';
130
- const requestMessages = retryingExistingRequest
131
- ? callbacks.getConversation()
132
- : likelyPlanImplementationRequest
133
- ? [...callbacks.getConversation(), { role: 'user', content: value }, { role: 'user', content: planImplementationGuidance }]
134
- : [...callbacks.getConversation(), { role: 'user', content: value }];
135
- callbacks.setConversation(requestMessages);
179
+ const durableRequestMessages = compactToolHistory(retryingExistingRequest
180
+ ? stripSyntheticControls(callbacks.getConversation())
181
+ : [...stripSyntheticControls(callbacks.getConversation()), { role: 'user', content: value }]).messages;
182
+ let requestMessages = likelyPlanImplementationRequest
183
+ ? withSyntheticControl(durableRequestMessages, planImplementationGuidance)
184
+ : durableRequestMessages;
185
+ if (estimateValueTokens(requestMessages) > ACTIVE_CONTEXT_TOKEN_BUDGET) {
186
+ requestMessages = compactModelMessages(requestMessages, { tokenBudget: ACTIVE_CONTEXT_TOKEN_BUDGET, workState: goal.workState }).messages;
187
+ }
188
+ callbacks.setConversation(stripSyntheticControls(requestMessages));
136
189
  resetIdleTimer();
137
190
  let currentAssistantId = `assistant-${Date.now()}`;
138
191
  let assistantStarted = false;
139
192
  let currentAssistantStarted = false;
193
+ let currentAssistantStartedAt = Date.now();
140
194
  let currentAssistantText = '';
141
195
  let assistantText = '';
142
196
  let toolEpoch = 0;
@@ -150,6 +204,12 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
150
204
  let textAfterTool = false;
151
205
  let completionContinuationCount = 0;
152
206
  const maxCompletionContinuations = COMPLETION_CONTINUATION_LIMIT;
207
+ const recentStepTextSignatures = [];
208
+ let consecutiveTextOnlySteps = 0;
209
+ let repetitionAbortFired = false;
210
+ const toolCallSignatureCounts = new Map();
211
+ const TOOL_REPETITION_THRESHOLD = 3;
212
+ let latestAccumulatedResponseMessages = [];
153
213
  let editRecoveryPath;
154
214
  let editRecoveryReasonCode;
155
215
  let editRecoveryReadSatisfied = false;
@@ -179,6 +239,24 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
179
239
  const toolDisplayItems = [];
180
240
  let toolGroupStarted = false;
181
241
  let toolGroupFinalized = false;
242
+ let toolTimer;
243
+ function stopToolTimer() {
244
+ if (!toolTimer)
245
+ return;
246
+ clearInterval(toolTimer);
247
+ toolTimer = undefined;
248
+ }
249
+ function startToolTimer() {
250
+ if (toolTimer)
251
+ return;
252
+ toolTimer = setInterval(() => {
253
+ if (toolDisplayItems.some(item => item.status === 'running'))
254
+ updateToolGroup(true);
255
+ else
256
+ stopToolTimer();
257
+ }, 1000);
258
+ }
259
+ stopActiveTimers = stopToolTimer;
182
260
  function renderToolGroup(streaming) {
183
261
  const visibleItems = toolDisplayItems.filter(item => !item.hidden);
184
262
  const running = visibleItems.some(item => item.status === 'running');
@@ -198,9 +276,13 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
198
276
  }
199
277
  const rows = [...grouped.values()];
200
278
  const compactSuffix = !running && visibleItems.length > 12 ? ` · showing ${compactItems.length} important` : '';
279
+ const elapsedMs = visibleItems.length > 0
280
+ ? (running ? Date.now() : Math.max(...visibleItems.map(item => item.finishedAt ?? item.startedAt))) - Math.min(...visibleItems.map(item => item.startedAt))
281
+ : 0;
282
+ const elapsed = running || streaming ? formatElapsedTimeWhole(elapsedMs) : formatElapsedTime(elapsedMs);
201
283
  const header = running || streaming
202
- ? 'Running tools'
203
- : `${visibleItems.length} call${visibleItems.length === 1 ? '' : 's'} · ${changes.length} change${changes.length === 1 ? '' : 's'} · ${failures.length} failed${compactSuffix}`;
284
+ ? `Running tools · ${elapsed}`
285
+ : `${visibleItems.length} call${visibleItems.length === 1 ? '' : 's'} · ${changes.length} change${changes.length === 1 ? '' : 's'} · ${failures.length} failed · ${elapsed}${compactSuffix}`;
204
286
  const lines = [];
205
287
  for (const { item, count } of rows) {
206
288
  const icon = item.status === 'running' ? '…' : item.status === 'success' ? '✓' : '✗';
@@ -219,7 +301,7 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
219
301
  }
220
302
  if (item.subItems && item.subItems.length > 0) {
221
303
  for (const sub of item.subItems) {
222
- const subDuration = sub.durationMs > 1000 ? ` (${formatSeconds(sub.durationMs)})` : '';
304
+ const subDuration = sub.durationMs > 1000 ? ` · ${formatSeconds(sub.durationMs)}` : '';
223
305
  lines.push(` · ${sub.name} — ${sub.summary}${subDuration}`);
224
306
  }
225
307
  }
@@ -246,7 +328,8 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
246
328
  toolGroupStarted = false;
247
329
  }
248
330
  callbacks.onEvent?.(agentEvent({ type: 'tool_start', id: toolCall.toolCallId, name: toolCall.toolName, input: toolCall.input }));
249
- toolDisplayItems.push({ id: toolCall.toolCallId, summary: toolCallSummary(toolCall.toolName, toolCall.input), status: 'running' });
331
+ toolDisplayItems.push({ id: toolCall.toolCallId, summary: toolCallSummary(toolCall.toolName, toolCall.input), status: 'running', startedAt: Date.now() });
332
+ startToolTimer();
250
333
  updateToolGroup(true);
251
334
  const runningSubagents = toolDisplayItems.filter(item => item.status === 'running' && item.summary.startsWith('subagent')).length;
252
335
  if (runningSubagents > 0)
@@ -260,6 +343,7 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
260
343
  item.status = toolOutputOk(event.output, event.success) ? 'success' : 'error';
261
344
  item.result = toolResultSummary(event);
262
345
  item.durationMs = event.durationMs;
346
+ item.finishedAt = item.startedAt + event.durationMs;
263
347
  item.hidden = isDuplicateSkippedOutput(event.output);
264
348
  if (typeof event.output === 'object' && event.output != null) {
265
349
  const output = event.output;
@@ -278,7 +362,13 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
278
362
  }));
279
363
  }
280
364
  }
281
- updateToolGroup(toolDisplayItems.some(candidate => candidate.status === 'running'));
365
+ if (event.toolCall.toolName === 'writeTasks' && event.success) {
366
+ callbacks.onTasksChanged?.();
367
+ }
368
+ const hasRunningTools = toolDisplayItems.some(candidate => candidate.status === 'running');
369
+ updateToolGroup(hasRunningTools);
370
+ if (!hasRunningTools)
371
+ stopToolTimer();
282
372
  const runningSubagents = toolDisplayItems.filter(i => i.status === 'running' && i.summary.startsWith('subagent')).length;
283
373
  if (runningSubagents === 0)
284
374
  callbacks.setBusyLabel?.('Haze is thinking');
@@ -291,6 +381,7 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
291
381
  const duplicateSkipped = isDuplicateSkippedOutput(event.output);
292
382
  const ok = toolOutputOk(event.output, event.success);
293
383
  observeGoalToolEvent(goal, { ...event.toolCall, success: ok, output: event.output, duplicateSkipped });
384
+ callbacks.setWorkState?.(goal.workState);
294
385
  callbacks.setGoalStatus?.(formatGoalStatus(goal));
295
386
  if (!ok && ['editFile', 'replaceLines', 'writeFile'].includes(event.toolCall.toolName)) {
296
387
  editFileFailed = true;
@@ -322,21 +413,27 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
322
413
  async function streamAssistantResponse(messages, reason, prompt, allowTools = false) {
323
414
  callbacks.debugLog(`requesting assistant ${allowTools ? 'continuation' : 'text'}: ${reason}`);
324
415
  const responseId = `assistant-${Date.now()}-${Math.random().toString(36).slice(2)}`;
325
- let responseStarted = false;
416
+ const responseStarted = true;
417
+ const responseStartedAt = Date.now();
326
418
  let responseText = '';
327
419
  let continuationToolCalls = 0;
328
420
  let followUpStreamError;
329
- const continuationMessages = [
330
- ...messages,
331
- { role: 'user', content: prompt },
332
- ];
421
+ const prunedMessages = compactToolHistory(stripSyntheticControls(messages)).messages;
422
+ const compactedMessages = estimateValueTokens(prunedMessages) > ACTIVE_CONTEXT_TOKEN_BUDGET
423
+ ? compactModelMessages(prunedMessages, { tokenBudget: ACTIVE_CONTEXT_TOKEN_BUDGET, workState: goal.workState }).messages
424
+ : prunedMessages;
425
+ const continuationMessages = withSyntheticControl(compactedMessages, `${prompt}\n\n${workStatePrompt(goal.workState)}`);
426
+ const followUpSystemPrompt = buildSystemPrompt(contextFiles, session);
427
+ const followUpTools = allowTools ? availableTools : undefined;
428
+ const followUpInputBreakdown = estimateInputBreakdown({ system: followUpSystemPrompt, contextFiles, messages: continuationMessages, tools: followUpTools });
429
+ logEntry(callbacks.log, { at: new Date().toISOString(), type: 'request', stream: `continuation:${reason}`, system: followUpSystemPrompt, messages: continuationMessages, tools: followUpTools ? Object.keys(followUpTools) : [], context: followUpInputBreakdown.breakdown });
333
430
  const followUp = streamText({
334
431
  model: activeModel,
335
432
  maxOutputTokens: DEFAULT_MAX_OUTPUT_TOKENS,
336
- system: buildSystemPrompt(contextFiles),
433
+ system: followUpSystemPrompt,
337
434
  messages: continuationMessages,
338
- tools: availableTools,
339
- toolChoice: allowTools ? 'auto' : 'none',
435
+ ...toolRequestSettings(availableTools, allowTools),
436
+ ...providerSettings,
340
437
  stopWhen: stepCountIs(FOLLOW_UP_STEP_LIMIT),
341
438
  abortSignal: abortController.signal,
342
439
  experimental_context: toolExecutionContext,
@@ -345,32 +442,19 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
345
442
  if (continuationToolCalls >= FOLLOW_UP_TOOL_CALL_LIMIT || toolOnlyStepCount(steps) >= FOLLOW_UP_TOOL_ONLY_STEP_LIMIT) {
346
443
  return {
347
444
  toolChoice: 'none',
348
- messages: [
349
- ...messages,
350
- { role: 'user', content: toolLoopBudgetPrompt() },
351
- ],
445
+ messages: withSyntheticControl(messages, toolLoopBudgetPrompt()),
352
446
  };
353
447
  }
354
448
  if (likelyPlanOnlyRequest && mutatingToolSucceeded) {
355
449
  return {
356
450
  toolChoice: 'none',
357
- messages: [
358
- ...messages,
359
- { role: 'user', content: 'This was a planning request and the plan artifact has been created or updated. Stop using tools and summarize the plan file only; do not implement or validate it.' },
360
- ],
361
451
  };
362
452
  }
363
453
  if (editRecoveryPath && !editRecoveryReadSatisfied) {
364
454
  return {
365
455
  activeTools: ['readFile'],
366
- messages: [
367
- ...messages,
368
- { role: 'user', content: `A previous edit failed for ${editRecoveryPath}${editRecoveryReasonCode ? ` (${editRecoveryReasonCode})` : ''}. Before any further edit or bash inspection, call readFile on exactly ${editRecoveryPath}. Bash/cat does not satisfy this recovery step.` },
369
- ],
370
456
  };
371
457
  }
372
- if (editFileFailed)
373
- return { activeTools: ['listFiles', 'readFile', 'replaceLines', 'writeFile', 'bash'] };
374
458
  return undefined;
375
459
  },
376
460
  onError({ error }) {
@@ -378,18 +462,50 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
378
462
  callbacks.debugLog(`stream error: ${error instanceof Error ? error.message : String(error)}`);
379
463
  },
380
464
  onFinish(event) {
381
- callbacks.setConversation([...continuationMessages, ...event.response.messages]);
382
- callbacks.debugLog(`conversation updated to ${continuationMessages.length + event.response.messages.length} messages after follow-up`);
465
+ const providerUsage = extractUsage(event);
466
+ callbacks.recordTokenUsage?.({
467
+ inputTokens: providerUsage.inputTokens,
468
+ outputTokens: providerUsage.outputTokens,
469
+ systemPrompt: followUpInputBreakdown.systemPrompt,
470
+ messages: followUpInputBreakdown.messages,
471
+ toolSchemas: followUpInputBreakdown.toolSchemas,
472
+ outputEstimate: estimateValueTokens(event.response.messages),
473
+ cacheReadTokens: providerUsage.cacheReadTokens,
474
+ cacheWriteTokens: providerUsage.cacheWriteTokens,
475
+ noCacheTokens: providerUsage.noCacheTokens,
476
+ reasoningTokens: providerUsage.reasoningTokens,
477
+ logicalInputEstimate: followUpInputBreakdown.logicalInputEstimate,
478
+ effectiveNonCachedInput: effectiveNonCachedInput(providerUsage.inputTokens, providerUsage.cacheReadTokens),
479
+ });
480
+ const nextConversation = [...stripSyntheticControls(compactedMessages), ...event.response.messages];
481
+ callbacks.setConversation(nextConversation);
482
+ callbacks.debugLog(`conversation updated to ${nextConversation.length} messages after follow-up`);
383
483
  },
384
484
  experimental_onToolCallStart({ toolCall }) {
385
485
  sawToolCall = true;
386
486
  recordToolStart(toolCall);
387
487
  resetIdleTimer();
488
+ logEntry(callbacks.log, { at: new Date().toISOString(), type: 'tool_call', stream: `continuation:${reason}`, toolCall: { id: toolCall.toolCallId, name: toolCall.toolName, input: toolCall.input } });
388
489
  callbacks.debugLog(`follow-up tool start: ${toolCall.toolName} ${compact(toolCall.input)}`);
490
+ const sig = stableToolKey(toolCall);
491
+ const count = (toolCallSignatureCounts.get(sig) ?? 0) + 1;
492
+ toolCallSignatureCounts.set(sig, count);
493
+ if (count >= TOOL_REPETITION_THRESHOLD && !repetitionAbortFired) {
494
+ repetitionAbortFired = true;
495
+ turnStopReason = { kind: 'tool_repetition', message: `Stopped: called ${toolCall.toolName} ${count} times with identical input (tool loop). Type "continue" to try again — the next turn starts fresh.` };
496
+ const preview = sig.length > 100 ? `${sig.slice(0, 100)}…` : sig;
497
+ logEntry(callbacks.log, { at: new Date().toISOString(), type: 'warning', stream: `continuation:${reason}`, text: `tool repetition guard: "${preview}" called ${count} times with identical input this turn. Aborting to avoid tool-only loop.` });
498
+ callbacks.debugLog(`tool repetition guard abort (continuation): ${toolCall.toolName} count=${count}`);
499
+ abortController.abort(`Haze tool repetition guard: ${toolCall.toolName} called ${count} times with identical input.`);
500
+ }
389
501
  },
390
502
  experimental_onToolCallFinish(event) {
391
503
  resetIdleTimer();
392
504
  recordToolFinish(event);
505
+ logEntry(callbacks.log, { at: new Date().toISOString(), type: 'tool_result', stream: `continuation:${reason}`, toolResult: { id: event.toolCall.toolCallId, name: event.toolCall.toolName, success: event.success, output: event.output, error: event.error, durationMs: event.durationMs } });
506
+ const nestedTokens = subagentTokenEstimate(event.output);
507
+ if (nestedTokens)
508
+ 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 });
393
509
  const summary = toolResultSummary(event);
394
510
  toolSummaries.push(`${event.toolCall.toolName}: ${summary}`);
395
511
  recordToolDisplayFinish(event);
@@ -400,22 +516,17 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
400
516
  : `follow-up tool error: ${event.toolCall.toolName} after ${event.durationMs}ms ${compact(event.error)}`);
401
517
  },
402
518
  });
519
+ callbacks.onEvent?.(agentEvent({ type: 'message_start', id: responseId, role: 'assistant' }));
520
+ callbacks.addMessage({ id: responseId, role: 'assistant', text: 'Awaiting response…', streaming: true, startedAt: responseStartedAt });
403
521
  for await (const rawDelta of followUp.textStream) {
404
522
  resetIdleTimer();
405
523
  const delta = sanitizeAssistantText(rawDelta);
406
524
  responseText += delta;
407
525
  const displayText = assistantDisplayText(responseText);
408
- if ((!displayText || isNonSubstantiveAssistantText(displayText) || isPrefixOfVisibleAssistantText(displayText)) && !responseStarted)
526
+ if (!displayText || isNonSubstantiveAssistantText(displayText) || isPrefixOfVisibleAssistantText(displayText))
409
527
  continue;
410
- if (!responseStarted) {
411
- responseStarted = true;
412
- callbacks.onEvent?.(agentEvent({ type: 'message_start', id: responseId, role: 'assistant' }));
413
- callbacks.addMessage({ id: responseId, role: 'assistant', text: displayText, streaming: true });
414
- }
415
- else {
416
- callbacks.onEvent?.(agentEvent({ type: 'message_update', id: responseId, text: displayText }));
417
- callbacks.updateMessage(responseId, { text: displayText });
418
- }
528
+ callbacks.onEvent?.(agentEvent({ type: 'message_update', id: responseId, text: displayText }));
529
+ callbacks.updateMessage(responseId, { text: displayText });
419
530
  }
420
531
  try {
421
532
  await followUp.response;
@@ -430,18 +541,22 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
430
541
  if (!hidden)
431
542
  rememberVisibleAssistantText(visibleFinalText);
432
543
  callbacks.onEvent?.(agentEvent({ type: 'message_end', id: responseId, text: visibleFinalText, hidden }));
433
- callbacks.updateMessage(responseId, { text: visibleFinalText, streaming: false, hidden });
544
+ callbacks.updateMessage(responseId, { text: visibleFinalText, streaming: false, hidden, finishedAt: Date.now() });
434
545
  }
435
546
  return { text: finalText, id: responseId, started: responseStarted };
436
547
  }
437
548
  let streamError;
438
549
  let lastFinishReason;
550
+ const mainSystemPrompt = buildSystemPrompt(contextFiles, session);
551
+ const mainInputBreakdown = estimateInputBreakdown({ system: mainSystemPrompt, contextFiles, messages: requestMessages, tools: availableTools });
552
+ logEntry(callbacks.log, { at: new Date().toISOString(), type: 'request', stream: 'main', system: mainSystemPrompt, messages: requestMessages, tools: Object.keys(availableTools), context: mainInputBreakdown.breakdown });
439
553
  const result = streamText({
440
554
  model: activeModel,
441
555
  maxOutputTokens: DEFAULT_MAX_OUTPUT_TOKENS,
442
- system: buildSystemPrompt(contextFiles),
556
+ system: mainSystemPrompt,
443
557
  messages: requestMessages,
444
558
  tools: availableTools,
559
+ ...providerSettings,
445
560
  stopWhen: stepCountIs(MAIN_STEP_LIMIT),
446
561
  abortSignal: abortController.signal,
447
562
  experimental_context: toolExecutionContext,
@@ -457,19 +572,11 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
457
572
  if (likelyPlanOnlyRequest && mutatingToolSucceeded) {
458
573
  return {
459
574
  toolChoice: 'none',
460
- messages: [
461
- ...messages,
462
- { role: 'user', content: 'This was a planning request and the plan artifact has been created or updated. Stop using tools and summarize the plan file only; do not implement or validate it.' },
463
- ],
464
575
  };
465
576
  }
466
577
  if (editRecoveryPath && !editRecoveryReadSatisfied) {
467
578
  return {
468
579
  activeTools: ['readFile'],
469
- messages: [
470
- ...messages,
471
- { role: 'user', content: `A previous edit failed for ${editRecoveryPath}${editRecoveryReasonCode ? ` (${editRecoveryReasonCode})` : ''}. Before any further edit or bash inspection, call readFile on exactly ${editRecoveryPath}. Bash/cat does not satisfy this recovery step.` },
472
- ],
473
580
  };
474
581
  }
475
582
  if (repeatedToolCall) {
@@ -477,54 +584,128 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
477
584
  callbacks.debugLog(`disabling repeated tools for next step: ${repeatedToolNames.join(', ')}`);
478
585
  return {
479
586
  activeTools,
480
- messages: [
481
- ...messages,
482
- { role: 'user', content: `You already called ${repeatedToolNames.join(', ')} with the same input. Do not repeat that tool call. Use a different relevant tool. If this is an action request and no file change has been made yet, continue with edit/write tools rather than summarizing.` },
483
- ],
484
- };
485
- }
486
- if (likelyActionRequest && !mutatingToolSucceeded && consecutiveToolOnlySteps >= 3 && toolCalls.length < MAIN_TOOL_CALL_LIMIT) {
487
- callbacks.debugLog('nudging action request toward mutation after read-only steps');
488
- return {
489
- messages: [
490
- ...messages,
491
- { role: 'user', content: 'You have inspected enough for now. This is an action request; make the requested change with editFile, replaceLines, or writeFile instead of saying tools are unavailable or summarizing.' },
492
- ],
493
587
  };
494
588
  }
495
589
  if (toolCalls.length >= MAIN_TOOL_CALL_LIMIT || consecutiveToolOnlySteps >= MAIN_TOOL_ONLY_STEP_LIMIT) {
496
590
  callbacks.debugLog('forcing text response to avoid tool loop');
591
+ turnStopReason = toolCalls.length >= MAIN_TOOL_CALL_LIMIT
592
+ ? { kind: 'tool_budget', message: `Reached the per-turn tool-call limit (${MAIN_TOOL_CALL_LIMIT}). Type "continue" to resume — Haze will pick up where it left off.` }
593
+ : { kind: 'tool_only_limit', message: `Made ${MAIN_TOOL_ONLY_STEP_LIMIT} consecutive inspection-only steps without making changes. Type "continue" to resume.` };
497
594
  return {
498
595
  toolChoice: 'none',
499
- messages: [
500
- ...messages,
501
- { role: 'user', content: toolLoopBudgetPrompt() },
502
- ],
596
+ messages: withSyntheticControl(messages, toolLoopBudgetPrompt()),
503
597
  };
504
598
  }
505
- if (editFileFailed)
506
- return { activeTools: ['listFiles', 'readFile', 'replaceLines', 'writeFile', 'bash'] };
507
599
  return undefined;
508
600
  },
509
- onStepFinish({ stepNumber, text, toolCalls, toolResults, finishReason }) {
601
+ onStepFinish({ stepNumber, text, toolCalls, toolResults, finishReason, usage, response }) {
602
+ if (Array.isArray(response?.messages) && response.messages.length > 0) {
603
+ latestAccumulatedResponseMessages = response.messages;
604
+ }
605
+ if (!turnStopReason && stepNumber >= MAIN_STEP_LIMIT - 1) {
606
+ turnStopReason = { kind: 'step_limit', message: `Reached the per-turn step limit (${MAIN_STEP_LIMIT}). Type "continue" to resume — Haze will pick up where it left off.` };
607
+ }
510
608
  lastFinishReason = finishReason;
511
- callbacks.debugLog(`step ${stepNumber} finished: ${finishReason}; text=${text.length}; toolCalls=${toolCalls.length}; toolResults=${toolResults.length}`);
609
+ const stepInputTokens = usage?.inputTokens;
610
+ const stepOutputTokens = usage?.outputTokens;
611
+ const stepCacheRead = usage?.inputTokenDetails?.cacheReadTokens ?? 0;
612
+ const stepCacheWrite = usage?.inputTokenDetails?.cacheWriteTokens ?? 0;
613
+ const stepReasoning = usage?.outputTokenDetails?.reasoningTokens ?? 0;
614
+ const stepNoCache = effectiveNonCachedInput(stepInputTokens, stepCacheRead) ?? 0;
615
+ const stepCacheHitRatio = cacheHitRatio(stepInputTokens, stepCacheRead || undefined);
616
+ logEntry(callbacks.log, { at: new Date().toISOString(), type: 'step', stream: 'main', step: stepNumber, text, finishReason, usage: { inputTokens: stepInputTokens, outputTokens: stepOutputTokens, cacheReadTokens: stepCacheRead || undefined, cacheWriteTokens: stepCacheWrite || undefined, noCacheTokens: stepNoCache || undefined, reasoningTokens: stepReasoning || undefined, cacheHitRatio: stepCacheHitRatio } });
617
+ if (stepCacheHitRatio !== undefined && stepCacheHitRatio < 0.5 && stepNoCache > 2000) {
618
+ logEntry(callbacks.log, { at: new Date().toISOString(), type: 'warning', stream: 'main', step: stepNumber, text: `low cache hit: ${(stepCacheHitRatio * 100).toFixed(1)}% (${stepCacheRead}/${stepInputTokens}), ${stepNoCache} no-cache tokens. Likely prompt prefix changed mid-turn.` });
619
+ }
620
+ callbacks.debugLog(`step ${stepNumber} finished: ${finishReason}; text=${text.length}; toolCalls=${toolCalls.length}; toolResults=${toolResults.length}; usage=${stepInputTokens != null ? `in=${stepInputTokens} out=${stepOutputTokens}` : 'not reported'}${stepCacheRead ? ` cached=${stepCacheRead}` : ''}${stepCacheWrite ? ` cache_write=${stepCacheWrite}` : ''}${stepReasoning ? ` reasoning=${stepReasoning}` : ''}${stepCacheHitRatio !== undefined ? ` cache_hit=${(stepCacheHitRatio * 100).toFixed(0)}%` : ''}`);
621
+ // Repetition guard: when a constrained (no-tools) step emits short text
622
+ // that matches the prior two short-text steps, the model is stuck in a
623
+ // "Let me X" loop. Abort the whole turn so we don't burn maxOutputTokens
624
+ // on every remaining step in the limit. The secondary consecutive-text-only
625
+ // check catches varied-phrasing loops (e.g. "Let me install" → "I'll install
626
+ // dependencies now" → "Now let me run npm install") that the exact-signature
627
+ // check would miss.
628
+ if (finishReason === 'stop' && toolCalls.length === 0) {
629
+ consecutiveTextOnlySteps += 1;
630
+ const signature = text.trim().toLowerCase().replace(/[^a-z0-9 ]/g, '').replace(/\s+/g, ' ').slice(0, 120);
631
+ if (signature.length >= 8) {
632
+ recentStepTextSignatures.push(signature);
633
+ const last3 = recentStepTextSignatures.slice(-3);
634
+ if (last3.length === 3 && last3[0] === last3[1] && last3[1] === last3[2] && !repetitionAbortFired) {
635
+ repetitionAbortFired = true;
636
+ turnStopReason = { kind: 'text_repetition', message: 'Stopped: the model emitted the same response 3 times in a row (text loop). Type "continue" to try again — the next turn starts fresh.' };
637
+ logEntry(callbacks.log, { at: new Date().toISOString(), type: 'warning', stream: 'main', step: stepNumber, text: `repetition guard: 3 consecutive identical text-only steps. Aborting turn to avoid loop. Last signature: "${signature.slice(0, 60)}"` });
638
+ callbacks.debugLog(`repetition guard abort at step ${stepNumber}; signature="${signature.slice(0, 60)}"`);
639
+ abortController.abort('Haze repetition guard: 3 consecutive identical text-only steps.');
640
+ }
641
+ }
642
+ if (consecutiveTextOnlySteps >= 4 && !repetitionAbortFired) {
643
+ repetitionAbortFired = true;
644
+ turnStopReason = { kind: 'text_repetition', message: 'Stopped: the model emitted several text responses in a row without making progress (likely a varied-phrasing loop). Type "continue" to try again — the next turn starts fresh.' };
645
+ logEntry(callbacks.log, { at: new Date().toISOString(), type: 'warning', stream: 'main', step: stepNumber, text: `repetition guard: ${consecutiveTextOnlySteps} consecutive text-only steps with no tool calls. Aborting turn to avoid varied-phrasing loop.` });
646
+ callbacks.debugLog(`repetition guard abort at step ${stepNumber}; consecutiveTextOnlySteps=${consecutiveTextOnlySteps}`);
647
+ abortController.abort(`Haze repetition guard: ${consecutiveTextOnlySteps} consecutive text-only steps without progress.`);
648
+ }
649
+ }
650
+ else {
651
+ consecutiveTextOnlySteps = 0;
652
+ }
512
653
  },
513
654
  onFinish(event) {
514
- const nextConversation = [...requestMessages, ...event.response.messages];
655
+ const providerUsage = extractUsage(event);
656
+ callbacks.recordTokenUsage?.({
657
+ inputTokens: providerUsage.inputTokens,
658
+ outputTokens: providerUsage.outputTokens,
659
+ systemPrompt: mainInputBreakdown.systemPrompt,
660
+ messages: mainInputBreakdown.messages,
661
+ toolSchemas: mainInputBreakdown.toolSchemas,
662
+ outputEstimate: estimateValueTokens(event.response.messages),
663
+ cacheReadTokens: providerUsage.cacheReadTokens,
664
+ cacheWriteTokens: providerUsage.cacheWriteTokens,
665
+ noCacheTokens: providerUsage.noCacheTokens,
666
+ reasoningTokens: providerUsage.reasoningTokens,
667
+ logicalInputEstimate: mainInputBreakdown.logicalInputEstimate,
668
+ effectiveNonCachedInput: effectiveNonCachedInput(providerUsage.inputTokens, providerUsage.cacheReadTokens),
669
+ });
670
+ const accumulated = [...stripSyntheticControls(requestMessages), ...event.response.messages];
671
+ const compacted = compactToolHistory(accumulated);
672
+ const nextConversation = compacted.messages;
515
673
  callbacks.setConversation(nextConversation);
674
+ if (compacted.compactedResults > 0 || compacted.compactedCalls > 0) {
675
+ callbacks.debugLog(`end-of-turn compaction: ${compacted.compactedResults} results, ${compacted.compactedCalls} tool-call inputs compacted`);
676
+ logEntry(callbacks.log, { at: new Date().toISOString(), type: 'warning', stream: 'main', text: `end-of-turn compaction: ${compacted.compactedResults} old results, ${compacted.compactedCalls} old tool-call inputs compacted before next turn.` });
677
+ }
516
678
  callbacks.debugLog(`conversation updated to ${nextConversation.length} messages`);
517
679
  },
518
680
  experimental_onToolCallStart({ toolCall }) {
519
681
  sawToolCall = true;
520
682
  recordToolStart(toolCall);
521
683
  resetIdleTimer();
684
+ logEntry(callbacks.log, { at: new Date().toISOString(), type: 'tool_call', stream: 'main', toolCall: { id: toolCall.toolCallId, name: toolCall.toolName, input: toolCall.input } });
522
685
  callbacks.debugLog(`tool start: ${toolCall.toolName} ${compact(toolCall.input)}`);
686
+ // Tool-repetition guard: if the same (toolName, input) has been called
687
+ // TOOL_REPETITION_THRESHOLD times this turn, the model is stuck in a
688
+ // tool-only loop. Abort the turn rather than letting it burn more calls.
689
+ const sig = stableToolKey(toolCall);
690
+ const count = (toolCallSignatureCounts.get(sig) ?? 0) + 1;
691
+ toolCallSignatureCounts.set(sig, count);
692
+ if (count >= TOOL_REPETITION_THRESHOLD && !repetitionAbortFired) {
693
+ repetitionAbortFired = true;
694
+ turnStopReason = { kind: 'tool_repetition', message: `Stopped: called ${toolCall.toolName} ${count} times with identical input (tool loop). Type "continue" to try again — the next turn starts fresh.` };
695
+ const preview = sig.length > 100 ? `${sig.slice(0, 100)}…` : sig;
696
+ logEntry(callbacks.log, { at: new Date().toISOString(), type: 'warning', stream: 'main', text: `tool repetition guard: "${preview}" called ${count} times with identical input this turn. Aborting to avoid tool-only loop.` });
697
+ callbacks.debugLog(`tool repetition guard abort: ${toolCall.toolName} count=${count} sig=${preview}`);
698
+ abortController.abort(`Haze tool repetition guard: ${toolCall.toolName} called ${count} times with identical input.`);
699
+ }
523
700
  },
524
701
  experimental_onToolCallFinish(event) {
525
702
  resetIdleTimer();
526
703
  const summary = toolResultSummary(event);
527
704
  recordToolFinish(event);
705
+ logEntry(callbacks.log, { at: new Date().toISOString(), type: 'tool_result', stream: 'main', toolResult: { id: event.toolCall.toolCallId, name: event.toolCall.toolName, success: event.success, output: event.output, error: event.error, durationMs: event.durationMs } });
706
+ const nestedTokens = subagentTokenEstimate(event.output);
707
+ if (nestedTokens)
708
+ 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 });
528
709
  toolSummaries.push(`${event.toolCall.toolName}: ${summary}`);
529
710
  recordToolDisplayFinish(event);
530
711
  if (!isDuplicateSkippedOutput(event.output))
@@ -534,6 +715,10 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
534
715
  : `tool error: ${event.toolCall.toolName} after ${event.durationMs}ms ${compact(event.error)}`);
535
716
  }
536
717
  });
718
+ callbacks.onEvent?.(agentEvent({ type: 'message_start', id: currentAssistantId, role: 'assistant' }));
719
+ callbacks.addMessage({ id: currentAssistantId, role: 'assistant', text: 'Awaiting response…', streaming: true, startedAt: currentAssistantStartedAt });
720
+ assistantStarted = true;
721
+ currentAssistantStarted = true;
537
722
  for await (const rawDelta of result.textStream) {
538
723
  resetIdleTimer();
539
724
  const delta = sanitizeAssistantText(rawDelta);
@@ -541,13 +726,12 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
541
726
  textAfterTool = true;
542
727
  if (currentAssistantStarted && currentAssistantText.length > 0 && toolEpoch > currentAssistantToolEpoch) {
543
728
  const intermediateText = assistantDisplayText(currentAssistantText);
544
- const hidden = intermediateText.length === 0 || isNonSubstantiveAssistantText(intermediateText) || isDuplicateVisibleAssistantText(intermediateText);
545
- if (!hidden)
546
- rememberVisibleAssistantText(intermediateText);
729
+ const hidden = true;
547
730
  callbacks.onEvent?.(agentEvent({ type: 'message_end', id: currentAssistantId, text: intermediateText, hidden }));
548
- callbacks.updateMessage(currentAssistantId, { text: intermediateText, streaming: false, hidden });
731
+ callbacks.updateMessage(currentAssistantId, { text: intermediateText, streaming: false, hidden, finishedAt: Date.now() });
549
732
  currentAssistantId = `assistant-${Date.now()}-${Math.random().toString(36).slice(2)}`;
550
733
  currentAssistantStarted = false;
734
+ currentAssistantStartedAt = Date.now();
551
735
  currentAssistantText = '';
552
736
  currentAssistantToolEpoch = toolEpoch;
553
737
  }
@@ -560,7 +744,8 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
560
744
  assistantStarted = true;
561
745
  currentAssistantStarted = true;
562
746
  callbacks.onEvent?.(agentEvent({ type: 'message_start', id: currentAssistantId, role: 'assistant' }));
563
- callbacks.addMessage({ id: currentAssistantId, role: 'assistant', text: displayText, streaming: true });
747
+ currentAssistantStartedAt = Date.now();
748
+ callbacks.addMessage({ id: currentAssistantId, role: 'assistant', text: displayText, streaming: true, startedAt: currentAssistantStartedAt });
564
749
  }
565
750
  else {
566
751
  callbacks.onEvent?.(agentEvent({ type: 'message_update', id: currentAssistantId, text: displayText }));
@@ -570,10 +755,22 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
570
755
  let completedConversation = callbacks.getConversation();
571
756
  try {
572
757
  const response = await result.response;
573
- completedConversation = [...requestMessages, ...response.messages];
758
+ completedConversation = [...stripSyntheticControls(requestMessages), ...response.messages];
574
759
  callbacks.setConversation(completedConversation);
575
760
  }
576
761
  catch (error) {
762
+ // The turn was aborted or errored mid-stream. If we have any accumulated
763
+ // response messages from completed steps (tracked in onStepFinish), persist
764
+ // them so the next turn inherits the partial work instead of losing it.
765
+ if (latestAccumulatedResponseMessages.length > 0) {
766
+ const accumulated = [...stripSyntheticControls(requestMessages), ...latestAccumulatedResponseMessages];
767
+ const compacted = compactToolHistory(accumulated);
768
+ callbacks.setConversation(compacted.messages);
769
+ if (compacted.compactedResults > 0 || compacted.compactedCalls > 0) {
770
+ logEntry(callbacks.log, { at: new Date().toISOString(), type: 'warning', stream: 'main', text: `abort recovery: persisted ${latestAccumulatedResponseMessages.length} response messages, compacted ${compacted.compactedResults} results and ${compacted.compactedCalls} tool-call inputs.` });
771
+ }
772
+ callbacks.debugLog(`abort recovery: persisted ${latestAccumulatedResponseMessages.length} response messages before re-throwing`);
773
+ }
577
774
  throw streamError ?? error;
578
775
  }
579
776
  callbacks.debugLog(`response stream finished; session has ${completedConversation.length} model messages`);
@@ -604,8 +801,10 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
604
801
  async function runCompletionLoop(seedConversation, seedText) {
605
802
  let loopConversation = seedConversation;
606
803
  let latestText = seedText;
804
+ let noProgressSlices = 0;
607
805
  while ((decision.needsActionContinuation || decision.needsValidationContinuation) && completionContinuationCount < maxCompletionContinuations) {
608
806
  completionContinuationCount += 1;
807
+ const revisionBefore = goal.workState.revision;
609
808
  const prompt = decision.continuationPrompt
610
809
  ?? (looksIncomplete(latestText) ? postContinuationPrompt() : 'Continue the same user goal until it is complete, blocked by a concrete issue, or needs a user decision. Focus on the concrete blocker, not a generic plan.');
611
810
  const continuation = await streamAssistantResponse(loopConversation, `completion gate ${completionContinuationCount}`, prompt, true);
@@ -613,6 +812,12 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
613
812
  if (continuation.text)
614
813
  latestText = continuation.text;
615
814
  decision = decideCompletion(latestText);
815
+ noProgressSlices = goal.workState.revision === revisionBefore ? noProgressSlices + 1 : 0;
816
+ if (noProgressSlices >= 2)
817
+ break;
818
+ }
819
+ if ((decision.needsActionContinuation || decision.needsValidationContinuation) && noProgressSlices >= 2) {
820
+ callbacks.addMessage({ role: 'assistant', text: 'Status: partial. Two continuation slices made no tool progress; the latest work state and blocker evidence were preserved.' });
616
821
  }
617
822
  if ((decision.needsActionContinuation || decision.needsValidationContinuation) && completionContinuationCount >= maxCompletionContinuations) {
618
823
  callbacks.addMessage({ role: 'assistant', text: 'Stopped after the autonomous safety limit. The current goal may still need work; ask me to continue and I will resume from the latest tool results.' });
@@ -630,7 +835,7 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
630
835
  if (!hidden)
631
836
  rememberVisibleAssistantText(visibleFinalAssistantText);
632
837
  callbacks.onEvent?.(agentEvent({ type: 'message_end', id: currentAssistantId, text: visibleFinalAssistantText, hidden }));
633
- callbacks.updateMessage(currentAssistantId, { text: visibleFinalAssistantText, streaming: false, hidden });
838
+ callbacks.updateMessage(currentAssistantId, { text: visibleFinalAssistantText, streaming: false, hidden, finishedAt: Date.now() });
634
839
  if (decision.needsActionContinuation || decision.needsValidationContinuation) {
635
840
  await runCompletionLoop(completedConversation, combinedAssistantText);
636
841
  }
@@ -652,22 +857,25 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
652
857
  const fallback = toolSummaries.length > 0
653
858
  ? `Finished tool work but the model did not produce a final response. Last tool result: ${toolSummaries.at(-1)}.`
654
859
  : 'Finished without a text response.';
655
- callbacks.addMessage({ id: currentAssistantId, role: 'assistant', text: fallback, streaming: false });
860
+ callbacks.addMessage({ id: currentAssistantId, role: 'assistant', text: fallback, streaming: false, startedAt: currentAssistantStartedAt, finishedAt: Date.now() });
656
861
  }
657
862
  }
658
863
  else {
659
- callbacks.addMessage({ id: currentAssistantId, role: 'assistant', text: 'Finished without a text response.', streaming: false });
864
+ callbacks.addMessage({ id: currentAssistantId, role: 'assistant', text: 'Finished without a text response.', streaming: false, startedAt: currentAssistantStartedAt, finishedAt: Date.now() });
660
865
  }
661
866
  goal.phase = 'done';
662
867
  goal.status = 'complete';
663
868
  turnStatus = 'complete';
869
+ if (turnStopReason) {
870
+ callbacks.addMessage({ role: 'system', text: turnStopReason.message });
871
+ }
664
872
  callbacks.setGoalStatus?.(undefined);
665
873
  }
666
874
  catch (error) {
667
875
  if (abortController.signal.aborted) {
668
876
  turnStatus = 'aborted';
669
877
  callbacks.debugLog('request aborted');
670
- callbacks.addMessage({ role: 'system', text: 'Thinking aborted. You can type again.' });
878
+ callbacks.addMessage({ role: 'system', text: turnStopReason?.message ?? 'Thinking aborted. You can type again.' });
671
879
  }
672
880
  else {
673
881
  const text = error instanceof Error ? error.message : String(error);
@@ -677,7 +885,7 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
677
885
  callbacks.onEvent?.(agentEvent({ type: 'context_overflow', recovered: compacted, error: text }));
678
886
  if (compacted) {
679
887
  callbacks.addMessage({ role: 'system', text: 'Context overflow detected; compacted older context and retrying the same request once.' });
680
- await runAgentTurn(value, displayValue, contextFiles, callbacks, retryAttempt, true, true);
888
+ await runAgentTurn(value, displayValue, contextFiles, callbacks, retryAttempt, true, true, session);
681
889
  return;
682
890
  }
683
891
  callbacks.addMessage({ role: 'system', text: 'Context overflow detected, but there was not enough conversation history to compact automatically.' });
@@ -690,7 +898,7 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
690
898
  await abortableDelay(delay, abortController.signal);
691
899
  if (abortController.signal.aborted)
692
900
  return;
693
- await runAgentTurn(value, displayValue, contextFiles, callbacks, retryAttempt + 1, true, contextOverflowRecovered);
901
+ await runAgentTurn(value, displayValue, contextFiles, callbacks, retryAttempt + 1, true, contextOverflowRecovered, session);
694
902
  return;
695
903
  }
696
904
  callbacks.addMessage({ role: 'assistant', text: `Model call failed: ${text}` });
@@ -699,6 +907,7 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
699
907
  finally {
700
908
  if (idleTimer)
701
909
  clearTimeout(idleTimer);
910
+ stopActiveTimers();
702
911
  callbacks.onEvent?.(agentEvent({ type: 'turn_end', request: value, status: turnStatus }));
703
912
  callbacks.setAbortController?.(null);
704
913
  callbacks.setBusy(false);