@denizokcu/haze 0.5.0 → 0.6.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 (36) hide show
  1. package/CHANGELOG.md +18 -2
  2. package/README.md +51 -21
  3. package/dist/cli/commands/chat.d.ts +1 -1
  4. package/dist/cli/commands/chat.js +686 -61
  5. package/dist/cli/commands/commands.d.ts +2 -1
  6. package/dist/cli/commands/commands.js +62 -101
  7. package/dist/cli/commands/formatters.d.ts +27 -0
  8. package/dist/cli/commands/formatters.js +137 -0
  9. package/dist/cli/commands/streaming.d.ts +10 -13
  10. package/dist/cli/commands/streaming.js +319 -716
  11. package/dist/config/lspSettings.d.ts +16 -0
  12. package/dist/config/lspSettings.js +98 -0
  13. package/dist/config/mcpSettings.d.ts +24 -0
  14. package/dist/config/mcpSettings.js +100 -0
  15. package/dist/config/settings.d.ts +34 -0
  16. package/dist/config/skillSettings.d.ts +15 -0
  17. package/dist/config/skillSettings.js +31 -0
  18. package/dist/config/updateCheck.d.ts +44 -0
  19. package/dist/config/updateCheck.js +83 -0
  20. package/dist/llm/lsp.d.ts +64 -0
  21. package/dist/llm/lsp.js +241 -0
  22. package/dist/llm/lspTools.d.ts +122 -0
  23. package/dist/llm/lspTools.js +115 -0
  24. package/dist/llm/mcp.d.ts +19 -0
  25. package/dist/llm/mcp.js +64 -0
  26. package/dist/llm/requestContext.d.ts +28 -0
  27. package/dist/llm/requestContext.js +56 -0
  28. package/dist/llm/systemPrompt.d.ts +4 -1
  29. package/dist/llm/systemPrompt.js +8 -2
  30. package/dist/skills/builder/SkillBuilder.js +23 -44
  31. package/dist/ui/components/TextInput.d.ts +1 -1
  32. package/dist/utils/version.d.ts +20 -0
  33. package/dist/utils/version.js +72 -0
  34. package/package.json +2 -1
  35. package/dist/cli/commands/skills.d.ts +0 -4
  36. package/dist/cli/commands/skills.js +0 -38
@@ -1,25 +1,21 @@
1
- import { stepCountIs, streamText } from 'ai';
1
+ import { ToolLoopAgent, stepCountIs } from 'ai';
2
2
  import { appendLogEntry as logAppend } from '../../core/log/llmLog.js';
3
3
  import { modelWithConfig, providerRequestSettings } from '../../llm/client.js';
4
- import { hazeTools } from '../../llm/hazeTools.js';
5
- import { buildSystemPrompt } from '../../llm/systemPrompt.js';
6
- import { loadSkillRegistry } from '../../skills/SkillRegistry.js';
7
- import { buildSkillTools } from '../../skills/skillTools.js';
4
+ import { assembleRequestContext } from '../../llm/requestContext.js';
5
+ import { closeMcpClients } from '../../llm/mcp.js';
8
6
  import { compact, toolCallSummary, toolResultSummary, formatElapsedTimeWhole, formatSeconds } from './formatters.js';
9
- import { isActionRequest, isPlanImplementationRequest, isPlanOnlyRequest, isValidationRequest } from '../../core/goal/requestClassifier.js';
10
- import { completionDecision, looksIncomplete, noTextAfterToolPrompt, postContinuationPrompt, repeatedToolCallPrompt, toolLoopBudgetPrompt } from '../../core/goal/completionPolicy.js';
11
- import { createSessionGoal, formatGoalStatus, observeGoalToolEvent } from '../../core/goal/sessionGoal.js';
12
7
  import { agentEvent } from '../../core/agent/events.js';
13
8
  import { isContextOverflowError, isRetryableModelError } from '../../core/agent/errors.js';
14
- import { createSubagentTool } from '../../core/subagent/subagentRunner.js';
9
+ import { isPlanOnlyRequest } from '../../core/goal/requestClassifier.js';
10
+ import { repeatedToolCallPrompt, toolLoopBudgetPrompt } from '../../core/goal/completionPolicy.js';
15
11
  import { contextBreakdown, cacheHitRatio, effectiveNonCachedInput, estimateValueTokens } from '../../core/agent/contextBudget.js';
16
- import { compactToolHistory, stripSyntheticControls, toolRequestSettings, withSyntheticControl } from '../../core/agent/requestAssembly.js';
12
+ import { compactToolHistory, stripSyntheticControls, withSyntheticControl } from '../../core/agent/requestAssembly.js';
17
13
  import { compactModelMessages } from '../../core/agent/compaction.js';
18
- import { workStatePrompt } from '../../core/agent/workState.js';
14
+ import { createSessionGoal, formatGoalStatus, observeGoalToolEvent } from '../../core/goal/sessionGoal.js';
19
15
  function stableToolKey(toolCall) {
20
16
  return `${toolCall.toolName}:${JSON.stringify(toolCall.input)}`;
21
17
  }
22
- function uniqueRepeatedToolNames(toolCalls) {
18
+ export function uniqueRepeatedToolNames(toolCalls) {
23
19
  const seen = new Set();
24
20
  const repeated = new Set();
25
21
  for (const toolCall of toolCalls) {
@@ -30,7 +26,7 @@ function uniqueRepeatedToolNames(toolCalls) {
30
26
  }
31
27
  return [...repeated];
32
28
  }
33
- function toolOnlyStepCount(steps) {
29
+ export function toolOnlyStepCount(steps) {
34
30
  let count = 0;
35
31
  for (const step of [...steps].reverse()) {
36
32
  if (step.toolCalls.length === 0 || step.text.trim().length > 0)
@@ -100,6 +96,10 @@ function isLikelyUnfinishedMarkdownFragment(text) {
100
96
  const last = trimmed.at(-1) ?? '';
101
97
  return last === '-' || last === '*' || last === '#' || last === '`' || last === '>';
102
98
  }
99
+ export function isShortUnfinishedBridgeBeforeTool(text) {
100
+ const trimmed = text.trim();
101
+ return trimmed.length > 0 && wordCount(trimmed) <= 12 && !endsWithSentenceBoundary(trimmed) && !isLikelyUnfinishedMarkdownFragment(trimmed);
102
+ }
103
103
  function isHiddenAssistantText(text) {
104
104
  return text.length === 0 || isNonSubstantiveAssistantText(text);
105
105
  }
@@ -149,18 +149,9 @@ async function abortableDelay(milliseconds, signal) {
149
149
  }
150
150
  const DEFAULT_MAX_OUTPUT_TOKENS = 16384;
151
151
  const IDLE_TIMEOUT_MS = 5 * 60_000;
152
- // The step limit is the primary per-turn cost ceiling. The tool-call limits sit
153
- // above it so healthy autonomous runs (read -> edit -> validate per todo item)
154
- // complete in one turn instead of being interrupted by a blunt count ceiling.
155
- // True tool loops are steered by duplicate-call nudges and the tool-only-step
156
- // guard below, not by these count limits.
157
152
  const MAIN_STEP_LIMIT = 64;
158
153
  const MAIN_TOOL_CALL_LIMIT = 120;
159
154
  const MAIN_TOOL_ONLY_STEP_LIMIT = 24;
160
- const FOLLOW_UP_STEP_LIMIT = 64;
161
- const FOLLOW_UP_TOOL_CALL_LIMIT = 120;
162
- const FOLLOW_UP_TOOL_ONLY_STEP_LIMIT = 24;
163
- const COMPLETION_CONTINUATION_LIMIT = 12;
164
155
  const ACTIVE_CONTEXT_TOKEN_BUDGET = 40_000;
165
156
  function toolOutputOk(output, success) {
166
157
  if (!success)
@@ -190,127 +181,169 @@ function responseCompletionMetrics(text, generationStartedAt) {
190
181
  tokensPerSecond: outputTokens > 0 ? outputTokens / elapsedSeconds : undefined,
191
182
  };
192
183
  }
193
- function subagentTokenEstimate(output) {
194
- if (typeof output !== 'object' || output == null || !('tokens' in output))
195
- return undefined;
196
- const tokens = output.tokens;
197
- const input = typeof tokens?.in === 'number' ? tokens.in : 0;
198
- const outputTokens = typeof tokens?.out === 'number' ? tokens.out : 0;
199
- return input > 0 || outputTokens > 0 ? { input, output: outputTokens } : undefined;
200
- }
201
184
  function extractUsage(event) {
202
185
  const cacheReadTokens = event.usage?.inputTokenDetails?.cacheReadTokens ?? 0;
203
- const reportedNoCache = 'noCacheTokens' in (event.usage?.inputTokenDetails ?? {})
204
- ? (event.usage?.inputTokenDetails).noCacheTokens
205
- : undefined;
206
186
  return {
207
187
  inputTokens: event.usage?.inputTokens,
208
188
  outputTokens: event.usage?.outputTokens,
209
189
  cacheReadTokens,
210
190
  cacheWriteTokens: event.usage?.inputTokenDetails?.cacheWriteTokens ?? 0,
211
- noCacheTokens: reportedNoCache ?? effectiveNonCachedInput(event.usage?.inputTokens, cacheReadTokens) ?? 0,
191
+ noCacheTokens: event.usage?.inputTokenDetails?.noCacheTokens ?? effectiveNonCachedInput(event.usage?.inputTokens, cacheReadTokens) ?? 0,
212
192
  reasoningTokens: event.usage?.outputTokenDetails?.reasoningTokens ?? 0,
213
193
  };
214
194
  }
195
+ function subagentTokenEstimate(output) {
196
+ if (typeof output !== 'object' || output == null || !('tokens' in output))
197
+ return undefined;
198
+ const tokens = output.tokens;
199
+ const input = typeof tokens?.in === 'number' ? tokens.in : 0;
200
+ const outputTokens = typeof tokens?.out === 'number' ? tokens.out : 0;
201
+ return input > 0 || outputTokens > 0 ? { input, output: outputTokens } : undefined;
202
+ }
203
+ function rememberContextFilesFromToolOutput(activeContextFiles, output) {
204
+ if (typeof output !== 'object' || output == null)
205
+ return activeContextFiles;
206
+ const files = output.applicableProjectInstructions;
207
+ if (!Array.isArray(files))
208
+ return activeContextFiles;
209
+ const seen = new Set(activeContextFiles.map(file => file.path));
210
+ const next = [...activeContextFiles];
211
+ for (const file of files) {
212
+ if (typeof file !== 'object' || file == null)
213
+ continue;
214
+ const candidate = file;
215
+ if (typeof candidate.path !== 'string' || typeof candidate.content !== 'string' || seen.has(candidate.path))
216
+ continue;
217
+ next.push({ path: candidate.path, content: candidate.content });
218
+ seen.add(candidate.path);
219
+ }
220
+ return next;
221
+ }
215
222
  export async function runAgentTurn(value, displayValue, contextFiles, callbacks, retryAttempt = 0, retryingExistingRequest = false, contextOverflowRecovered = false, session) {
216
223
  const displayVal = displayValue ?? value;
217
- const userMessage = { role: 'user', text: displayVal };
218
224
  callbacks.onEvent?.(agentEvent({ type: 'turn_start', request: value }));
219
225
  callbacks.setBusy(true);
226
+ callbacks.setBusyLabel?.('Haze is thinking');
220
227
  if (!retryingExistingRequest)
221
- callbacks.addMessage(userMessage);
228
+ callbacks.addMessage({ role: 'user', text: displayVal });
222
229
  const abortController = new AbortController();
223
230
  callbacks.setAbortController?.(abortController);
224
231
  let turnStatus = 'failed';
225
- let turnStopReason;
226
232
  let idleTimer;
227
- let stopActiveTimers = () => undefined;
228
- let finalizeToolGroup = () => undefined;
233
+ let loadedMcp;
229
234
  const resetIdleTimer = () => {
230
235
  if (idleTimer)
231
236
  clearTimeout(idleTimer);
232
237
  idleTimer = setTimeout(() => {
233
- 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.` };
234
238
  abortController.abort('Haze turn timed out after no model/tool activity.');
235
239
  }, IDLE_TIMEOUT_MS);
236
240
  };
241
+ const createToolGroup = () => ({ id: `tools-${Date.now()}-${Math.random().toString(36).slice(2)}`, items: [], started: false, finalized: false });
242
+ let toolGroup = createToolGroup();
243
+ let toolTimer;
244
+ const renderToolGroup = (group = toolGroup) => {
245
+ const running = group.items.some(item => item.status === 'running');
246
+ const failures = group.items.filter(item => item.status === 'error').length;
247
+ const changes = group.items.filter(item => /^(editFile|replaceLines|writeFile)\b/.test(item.summary)).length;
248
+ const elapsedMs = group.items.length > 0
249
+ ? (running ? Date.now() : Math.max(...group.items.map(item => item.finishedAt ?? item.startedAt))) - Math.min(...group.items.map(item => item.startedAt))
250
+ : 0;
251
+ const summaryParts = [`${group.items.length} calls`, `${changes} changes`];
252
+ if (failures > 0)
253
+ summaryParts.push(`${failures} failed`);
254
+ summaryParts.push(formatElapsedTimeWhole(elapsedMs));
255
+ return [summaryParts.join(' · '), ...group.items.map(item => {
256
+ const icon = item.status === 'running' ? '…' : item.status === 'success' ? '✓' : '✗';
257
+ const result = item.status === 'running' ? '' : ` — ${item.result ?? item.status}${item.durationMs == null ? '' : ` in ${formatSeconds(item.durationMs)}`}`;
258
+ return ` ${icon} ${item.summary}${result}`;
259
+ })].join('\n');
260
+ };
261
+ const updateToolGroup = (streaming = true, group = toolGroup) => {
262
+ const text = renderToolGroup(group);
263
+ if (!group.started) {
264
+ group.started = true;
265
+ group.finalized = !streaming;
266
+ callbacks.addMessage({ id: group.id, role: 'tool', text, streaming });
267
+ }
268
+ else {
269
+ group.finalized = !streaming;
270
+ callbacks.updateMessage(group.id, { text, streaming });
271
+ }
272
+ };
273
+ const finalizeToolGroup = (group = toolGroup) => {
274
+ if (!group.started || group.finalized)
275
+ return;
276
+ updateToolGroup(false, group);
277
+ };
278
+ const startFreshToolGroup = () => {
279
+ if (!toolGroup.started || toolGroup.items.some(item => item.status === 'running'))
280
+ return;
281
+ finalizeToolGroup(toolGroup);
282
+ toolGroup = createToolGroup();
283
+ };
284
+ const stopToolTimer = () => {
285
+ if (!toolTimer)
286
+ return;
287
+ clearInterval(toolTimer);
288
+ toolTimer = undefined;
289
+ };
290
+ const startToolTimer = () => {
291
+ if (toolTimer)
292
+ return;
293
+ toolTimer = setInterval(() => {
294
+ if (toolGroup.items.some(item => item.status === 'running'))
295
+ updateToolGroup(true);
296
+ else
297
+ stopToolTimer();
298
+ }, 1000);
299
+ };
300
+ const ensureToolItem = (toolCall) => {
301
+ if (toolGroup.finalized)
302
+ toolGroup = createToolGroup();
303
+ let item = toolGroup.items.find(candidate => candidate.id === toolCall.toolCallId);
304
+ if (!item) {
305
+ item = { id: toolCall.toolCallId, summary: toolCallSummary(toolCall.toolName, toolCall.input), status: 'running', startedAt: Date.now() };
306
+ toolGroup.items.push(item);
307
+ callbacks.onEvent?.(agentEvent({ type: 'tool_start', id: toolCall.toolCallId, name: toolCall.toolName, input: toolCall.input }));
308
+ logEntry(callbacks.log, { at: new Date().toISOString(), type: 'tool_call', stream: 'main', toolCall: { id: toolCall.toolCallId, name: toolCall.toolName, input: toolCall.input } });
309
+ callbacks.debugLog(`tool start: ${toolCall.toolName} ${compact(toolCall.input)}`);
310
+ startToolTimer();
311
+ updateToolGroup(true);
312
+ }
313
+ return item;
314
+ };
237
315
  try {
238
316
  const runtime = await modelWithConfig(session ? { cwd: session.cwd } : undefined);
239
317
  if (!runtime?.model) {
240
318
  callbacks.addMessage({ role: 'assistant', text: 'No model provider configured. Run /provider to choose or add a provider. Haze cannot hallucinate without a model. Progress.' });
319
+ turnStatus = 'complete';
241
320
  return;
242
321
  }
322
+ let activeContextFiles = contextFiles;
243
323
  const activeModel = runtime.model;
244
324
  const providerSettings = providerRequestSettings(runtime.config);
245
- let activeContextFiles = [...contextFiles];
246
- const rememberContextFiles = (files) => {
247
- if (!Array.isArray(files))
248
- return;
249
- const seen = new Set(activeContextFiles.map(file => file.path));
250
- for (const file of files) {
251
- if (typeof file !== 'object' || file == null)
252
- continue;
253
- const candidate = file;
254
- if (typeof candidate.path !== 'string' || typeof candidate.content !== 'string' || seen.has(candidate.path))
255
- continue;
256
- activeContextFiles = [...activeContextFiles, { path: candidate.path, content: candidate.content }];
257
- seen.add(candidate.path);
258
- }
259
- };
260
- const skillRegistry = await loadSkillRegistry();
261
- const subagentTool = createSubagentTool({ model: activeModel, contextFiles: activeContextFiles, session });
262
- const availableTools = { ...hazeTools, subagent: subagentTool, ...buildSkillTools(skillRegistry) };
325
+ const assembled = await assembleRequestContext({ contextFiles: activeContextFiles, session, model: activeModel });
326
+ const availableTools = assembled.availableTools;
327
+ loadedMcp = assembled.loadedMcp;
328
+ if (loadedMcp?.errors.length)
329
+ callbacks.addMessage({ role: 'system', text: `MCP: ${loadedMcp.errors.join('; ')}` });
263
330
  const goal = createSessionGoal(value);
264
331
  callbacks.setWorkState?.(goal.workState);
265
332
  callbacks.setGoalStatus?.(formatGoalStatus(goal));
266
333
  const likelyPlanOnlyRequest = isPlanOnlyRequest(value);
267
- const likelyPlanImplementationRequest = isPlanImplementationRequest(value);
268
- const likelyActionRequest = isActionRequest(value);
269
- const likelyValidationRequest = isValidationRequest(value);
270
- 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.';
271
334
  const durableRequestMessages = compactToolHistory(retryingExistingRequest
272
335
  ? stripSyntheticControls(callbacks.getConversation())
273
336
  : [...stripSyntheticControls(callbacks.getConversation()), { role: 'user', content: value }]).messages;
274
- let requestMessages = likelyPlanImplementationRequest
275
- ? withSyntheticControl(durableRequestMessages, planImplementationGuidance)
276
- : durableRequestMessages;
337
+ let requestMessages = durableRequestMessages;
277
338
  if (estimateValueTokens(requestMessages) > ACTIVE_CONTEXT_TOKEN_BUDGET) {
278
339
  requestMessages = compactModelMessages(requestMessages, { tokenBudget: ACTIVE_CONTEXT_TOKEN_BUDGET, workState: goal.workState }).messages;
279
340
  }
280
341
  callbacks.setConversation(stripSyntheticControls(requestMessages));
281
- resetIdleTimer();
282
- let currentAssistantId = `assistant-${Date.now()}`;
283
- let assistantStarted = false;
284
- let currentAssistantStarted = false;
285
- let currentAssistantStartedAt = Date.now();
286
- let currentAssistantText = '';
287
- let assistantText = '';
288
- let toolEpoch = 0;
289
- let currentAssistantToolEpoch = 0;
290
- let editFileFailed = false;
291
- let mutatingToolSucceeded = false;
292
- let validationToolSucceeded = false;
293
- let validationToolFailed = false;
294
- let sawReadOnlyTool = false;
295
- let sawToolCall = false;
296
- let textAfterTool = false;
297
- let completionContinuationCount = 0;
298
- const maxCompletionContinuations = COMPLETION_CONTINUATION_LIMIT;
299
- const recentStepTextSignatures = [];
300
- let consecutiveTextOnlySteps = 0;
301
- let repetitionAbortFired = false;
302
- const warnedRepeatedToolSignatures = new Set();
303
- const toolCallSignatureCounts = new Map();
304
- const TOOL_REPETITION_THRESHOLD = 3;
305
- let latestAccumulatedResponseMessages = [];
306
- let editRecoveryPath;
307
- let editRecoveryReasonCode;
308
- let editRecoveryReadSatisfied = false;
309
- const toolSummaries = [];
310
- const visibleAssistantTexts = new Set();
342
+ const systemPrompt = assembled.systemPrompt;
343
+ const inputBreakdown = estimateInputBreakdown({ system: systemPrompt, contextFiles: activeContextFiles, messages: requestMessages, tools: availableTools });
344
+ logEntry(callbacks.log, { at: new Date().toISOString(), type: 'request', stream: 'main', system: systemPrompt, messages: requestMessages, tools: Object.keys(availableTools), context: inputBreakdown.breakdown });
311
345
  const previousAssistantText = normalizeAssistantText(callbacks.getLastAssistantText());
312
- if (previousAssistantText)
313
- visibleAssistantTexts.add(previousAssistantText);
346
+ const visibleAssistantTexts = new Set(previousAssistantText ? [previousAssistantText] : []);
314
347
  const rememberVisibleAssistantText = (text) => {
315
348
  const normalized = normalizeAssistantText(text);
316
349
  if (!normalized)
@@ -318,417 +351,78 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
318
351
  visibleAssistantTexts.add(normalized);
319
352
  callbacks.setLastAssistantText(text);
320
353
  };
321
- const isDuplicateVisibleAssistantText = (text) => {
322
- const normalized = normalizeAssistantText(text);
323
- return normalized.length > 0 && visibleAssistantTexts.has(normalized);
324
- };
325
- const isPrefixOfVisibleAssistantText = (text) => {
326
- const normalized = normalizeAssistantText(text);
327
- return normalized.length > 0 && [...visibleAssistantTexts].some(previous => previous.startsWith(normalized) && previous !== normalized);
328
- };
329
354
  const toolExecutionContext = { inFlightToolCalls: new Map(), loadedContextFilePaths: new Set(activeContextFiles.map(file => file.path)) };
330
- const INLINE_DIFF_LINE_LIMIT = 20;
331
- const createToolDisplayGroup = () => ({ id: `tools-${Date.now()}-${Math.random().toString(36).slice(2)}`, items: [], started: false });
332
- let activeToolGroup = createToolDisplayGroup();
333
- let assistantSinceActiveToolGroup = false;
334
- let toolTimer;
335
- function stopToolTimer() {
336
- if (!toolTimer)
337
- return;
338
- clearInterval(toolTimer);
339
- toolTimer = undefined;
340
- }
341
- function startToolTimer() {
342
- if (toolTimer)
343
- return;
344
- toolTimer = setInterval(() => {
345
- if (activeToolGroup.items.some(item => item.status === 'running'))
346
- updateToolGroup(activeToolGroup, true);
347
- else
348
- stopToolTimer();
349
- }, 1000);
350
- }
351
- stopActiveTimers = stopToolTimer;
352
- function renderToolGroup(group, _streaming) {
353
- const running = group.items.some(item => item.status === 'running');
354
- const failures = group.items.filter(item => item.status === 'error');
355
- const changes = group.items.filter(item => /^(editFile|replaceLines|writeFile)\b/.test(item.summary));
356
- const elapsedMs = group.items.length > 0
357
- ? (running ? Date.now() : Math.max(...group.items.map(item => item.finishedAt ?? item.startedAt))) - Math.min(...group.items.map(item => item.startedAt))
358
- : 0;
359
- const elapsed = formatElapsedTimeWhole(elapsedMs);
360
- const summaryParts = [`${group.items.length} calls`, `${changes.length} changes`];
361
- if (failures.length > 0)
362
- summaryParts.push(`${failures.length} failed`);
363
- summaryParts.push(elapsed);
364
- const summary = summaryParts.join(' · ');
365
- const header = summary;
366
- const lines = [];
367
- for (const item of group.items) {
368
- const icon = item.status === 'running' ? '…' : item.status === 'success' ? '✓' : '✗';
369
- const result = item.status === 'running' ? '' : ` — ${item.result ?? item.status}${item.durationMs == null ? '' : ` in ${formatSeconds(item.durationMs)}`}`;
370
- lines.push(` ${icon} ${item.summary}${result}`);
371
- if (item.diff && item.diff.length > 0 && (item.diffLineCount ?? item.diff.length) <= INLINE_DIFF_LINE_LIMIT) {
372
- for (const diffLine of item.diff) {
373
- const lineNumber = diffLine.type === 'add' ? diffLine.newLine : diffLine.oldLine;
374
- const marker = diffLine.type === 'add' ? '+' : diffLine.type === 'remove' ? '-' : ' ';
375
- lines.push(` ${String(lineNumber ?? '').padStart(5)} ${marker} ${diffLine.text}`);
376
- }
377
- }
378
- else if ((item.diffLineCount ?? 0) > INLINE_DIFF_LINE_LIMIT) {
379
- lines.push(` diff hidden (${item.diffLineCount} changed lines; run git diff to inspect)`);
380
- }
381
- if (item.subItems && item.subItems.length > 0) {
382
- for (const sub of item.subItems) {
383
- const subDuration = sub.durationMs > 1000 ? ` · ${formatSeconds(sub.durationMs)}` : '';
384
- lines.push(` · ${sub.name} — ${sub.summary}${subDuration}`);
385
- }
386
- }
387
- }
388
- return [header, ...lines].join('\n');
389
- }
390
- function updateToolGroup(group = activeToolGroup, streaming = true) {
391
- const text = renderToolGroup(group, streaming);
392
- if (!group.started) {
393
- group.started = true;
394
- callbacks.addMessage({ id: group.id, role: 'tool', text, streaming });
395
- }
396
- else {
397
- callbacks.updateMessage(group.id, { text, streaming });
398
- }
399
- }
400
- finalizeToolGroup = () => {
401
- if (activeToolGroup.started)
402
- updateToolGroup(activeToolGroup, false);
355
+ const startedTools = new Map();
356
+ const latestToolCalls = new Map();
357
+ let latestAccumulatedResponseMessages = [];
358
+ let currentAssistantId = `assistant-${Date.now()}`;
359
+ let assistantStarted = false;
360
+ let assistantStartedAt = Date.now();
361
+ let assistantText = '';
362
+ let currentAssistantText = '';
363
+ let streamError;
364
+ let streamFinished = false;
365
+ let mutatingToolSucceeded = false;
366
+ let editRecoveryPath;
367
+ let editRecoveryReadSatisfied = false;
368
+ const resetAssistantSegment = () => {
369
+ currentAssistantId = `assistant-${Date.now()}-${Math.random().toString(36).slice(2)}`;
370
+ assistantStarted = false;
371
+ assistantStartedAt = Date.now();
372
+ currentAssistantText = '';
403
373
  };
404
- function closeToolGroupBeforeAssistantMessage() {
405
- if (!activeToolGroup.started)
406
- return undefined;
407
- const relatedToolStartedAt = activeToolGroup.items.length > 0
408
- ? Math.min(...activeToolGroup.items.map(item => item.startedAt))
409
- : undefined;
410
- updateToolGroup(activeToolGroup, false);
411
- assistantSinceActiveToolGroup = true;
412
- return relatedToolStartedAt;
413
- }
414
- function toolGroupForNextCall() {
415
- const hasRunningTools = activeToolGroup.items.some(item => item.status === 'running');
416
- if (assistantSinceActiveToolGroup && activeToolGroup.started && !hasRunningTools) {
417
- activeToolGroup = createToolDisplayGroup();
418
- assistantSinceActiveToolGroup = false;
419
- }
420
- return activeToolGroup;
421
- }
422
- function ensureToolDisplayItem(toolCall) {
423
- let item = activeToolGroup.items.find(candidate => candidate.id === toolCall.toolCallId);
424
- if (item)
425
- return item;
426
- const group = toolGroupForNextCall();
427
- item = { id: toolCall.toolCallId, summary: toolCallSummary(toolCall.toolName, toolCall.input), status: 'running', startedAt: Date.now() };
428
- group.items.push(item);
429
- startToolTimer();
430
- updateToolGroup(group, true);
431
- return item;
432
- }
433
- function recordToolStart(toolCall) {
434
- callbacks.onEvent?.(agentEvent({ type: 'tool_start', id: toolCall.toolCallId, name: toolCall.toolName, input: toolCall.input }));
435
- ensureToolDisplayItem(toolCall);
436
- const runningSubagents = activeToolGroup.items.filter(item => item.status === 'running' && item.summary.startsWith('subagent')).length;
437
- if (runningSubagents > 0)
438
- callbacks.setBusyLabel?.(`Running ${runningSubagents} subagent${runningSubagents === 1 ? '' : 's'}`);
439
- }
440
- function recordToolDisplayFinish(event) {
441
- callbacks.onEvent?.(agentEvent({ type: 'tool_end', id: event.toolCall.toolCallId, name: event.toolCall.toolName, success: event.success, output: event.output, error: event.error, durationMs: event.durationMs }));
442
- const item = ensureToolDisplayItem(event.toolCall);
443
- item.startedAt = Math.min(item.startedAt, Date.now() - event.durationMs);
444
- item.status = toolOutputOk(event.output, event.success) ? 'success' : 'error';
445
- item.result = toolResultSummary(event);
446
- item.durationMs = event.durationMs;
447
- item.finishedAt = item.startedAt + event.durationMs;
448
- if (typeof event.output === 'object' && event.output != null) {
449
- const output = event.output;
450
- rememberContextFiles(output.applicableProjectInstructions);
451
- if (typeof output.diffLineCount === 'number')
452
- item.diffLineCount = output.diffLineCount;
453
- if (Array.isArray(output.diff))
454
- item.diff = output.diff;
455
- }
456
- if (event.toolCall.toolName === 'subagent' && typeof event.output === 'object' && event.output != null) {
457
- const out = event.output;
458
- if (Array.isArray(out.toolCalls)) {
459
- item.subItems = out.toolCalls.map(tc => ({
460
- name: tc.name,
461
- summary: tc.summary,
462
- durationMs: tc.durationMs,
463
- }));
464
- }
465
- }
466
- if (event.toolCall.toolName === 'writeTasks' && event.success) {
467
- callbacks.onTasksChanged?.();
468
- }
469
- const hasRunningTools = activeToolGroup.items.some(candidate => candidate.status === 'running');
470
- updateToolGroup(activeToolGroup, !assistantSinceActiveToolGroup);
471
- if (!hasRunningTools)
472
- stopToolTimer();
473
- const runningSubagents = activeToolGroup.items.filter(i => i.status === 'running' && i.summary.startsWith('subagent')).length;
474
- if (runningSubagents === 0)
475
- callbacks.setBusyLabel?.('Haze is thinking');
476
- else
477
- callbacks.setBusyLabel?.(`Running ${runningSubagents} subagent${runningSubagents === 1 ? '' : 's'}`);
478
- }
479
- callbacks.debugLog(`request started with ${requestMessages.length} conversation messages; intent=${goal.normalizedIntent}; action=${likelyActionRequest}`);
480
- function recordToolFinish(event) {
481
- const path = toolInputPath(event.toolCall.input);
482
- const duplicateSkipped = isDuplicateSkippedOutput(event.output);
483
- const ok = toolOutputOk(event.output, event.success);
484
- observeGoalToolEvent(goal, { ...event.toolCall, success: ok, output: event.output, duplicateSkipped });
485
- callbacks.setWorkState?.(goal.workState);
486
- callbacks.setGoalStatus?.(formatGoalStatus(goal));
487
- if (!ok && ['editFile', 'replaceLines', 'writeFile'].includes(event.toolCall.toolName)) {
488
- editFileFailed = true;
489
- editRecoveryPath = path;
490
- editRecoveryReasonCode = typeof event.output === 'object' && event.output != null && 'reasonCode' in event.output && typeof event.output.reasonCode === 'string' ? event.output.reasonCode : undefined;
491
- editRecoveryReadSatisfied = false;
492
- }
493
- if (ok && ['listFiles', 'readFile'].includes(event.toolCall.toolName))
494
- sawReadOnlyTool = true;
495
- if (ok && event.toolCall.toolName === 'readFile' && path && path === editRecoveryPath && !duplicateSkipped) {
496
- editRecoveryReadSatisfied = true;
497
- }
498
- if (ok && !duplicateSkipped && ['editFile', 'replaceLines', 'writeFile'].includes(event.toolCall.toolName)) {
499
- mutatingToolSucceeded = true;
500
- if (!path || path === editRecoveryPath) {
501
- editRecoveryPath = undefined;
502
- editRecoveryReasonCode = undefined;
503
- editRecoveryReadSatisfied = false;
504
- editFileFailed = false;
505
- }
506
- }
507
- if (event.success && event.toolCall.toolName === 'bash') {
508
- if (ok)
509
- validationToolSucceeded = true;
510
- else
511
- validationToolFailed = true;
512
- }
513
- }
514
- async function streamAssistantResponse(messages, reason, prompt, allowTools = false) {
515
- callbacks.debugLog(`requesting assistant ${allowTools ? 'continuation' : 'text'}: ${reason}`);
516
- const responseId = `assistant-${Date.now()}-${Math.random().toString(36).slice(2)}`;
517
- let responseStarted = false;
518
- let responseStartedAt = Date.now();
519
- let responseText = '';
520
- let continuationToolCalls = 0;
521
- let followUpStreamError;
522
- const prunedMessages = compactToolHistory(stripSyntheticControls(messages)).messages;
523
- const compactedMessages = estimateValueTokens(prunedMessages) > ACTIVE_CONTEXT_TOKEN_BUDGET
524
- ? compactModelMessages(prunedMessages, { tokenBudget: ACTIVE_CONTEXT_TOKEN_BUDGET, workState: goal.workState }).messages
525
- : prunedMessages;
526
- const continuationMessages = withSyntheticControl(compactedMessages, `${prompt}\n\n${workStatePrompt(goal.workState)}`);
527
- const followUpSystemPrompt = buildSystemPrompt(activeContextFiles, session);
528
- const followUpTools = allowTools ? availableTools : undefined;
529
- const followUpInputBreakdown = estimateInputBreakdown({ system: followUpSystemPrompt, contextFiles: activeContextFiles, messages: continuationMessages, tools: followUpTools });
530
- logEntry(callbacks.log, { at: new Date().toISOString(), type: 'request', stream: `continuation:${reason}`, system: followUpSystemPrompt, messages: continuationMessages, tools: followUpTools ? Object.keys(followUpTools) : [], context: followUpInputBreakdown.breakdown });
531
- const followUp = streamText({
532
- model: activeModel,
533
- maxOutputTokens: DEFAULT_MAX_OUTPUT_TOKENS,
534
- system: followUpSystemPrompt,
535
- messages: continuationMessages,
536
- ...toolRequestSettings(availableTools, allowTools),
537
- ...providerSettings,
538
- stopWhen: stepCountIs(FOLLOW_UP_STEP_LIMIT),
539
- abortSignal: abortController.signal,
540
- experimental_context: toolExecutionContext,
541
- prepareStep({ steps, messages }) {
542
- const toolCalls = steps.flatMap(step => step.toolCalls);
543
- continuationToolCalls = toolCalls.length;
544
- const repeatedToolNames = uniqueRepeatedToolNames(toolCalls);
545
- if (continuationToolCalls >= FOLLOW_UP_TOOL_CALL_LIMIT || toolOnlyStepCount(steps) >= FOLLOW_UP_TOOL_ONLY_STEP_LIMIT) {
546
- return {
547
- toolChoice: 'none',
548
- messages: withSyntheticControl(messages, toolLoopBudgetPrompt()),
549
- };
550
- }
551
- if (repeatedToolNames.length > 0) {
552
- const activeTools = Object.keys(availableTools).filter(name => !repeatedToolNames.includes(name));
553
- callbacks.debugLog(`disabling repeated tools for follow-up step: ${repeatedToolNames.join(', ')}`);
554
- return activeTools.length > 0
555
- ? { activeTools, messages: withSyntheticControl(messages, repeatedToolCallPrompt(repeatedToolNames)) }
556
- : { toolChoice: 'none', messages: withSyntheticControl(messages, repeatedToolCallPrompt(repeatedToolNames)) };
557
- }
558
- if (likelyPlanOnlyRequest && mutatingToolSucceeded) {
559
- return {
560
- toolChoice: 'none',
561
- };
562
- }
563
- if (editRecoveryPath && !editRecoveryReadSatisfied) {
564
- return {
565
- activeTools: ['readFile'],
566
- };
567
- }
568
- return undefined;
569
- },
570
- onError({ error }) {
571
- followUpStreamError = error;
572
- callbacks.debugLog(`stream error: ${error instanceof Error ? error.message : String(error)}`);
573
- },
574
- onFinish(event) {
575
- const providerUsage = extractUsage(event);
576
- callbacks.recordTokenUsage?.({
577
- inputTokens: providerUsage.inputTokens,
578
- outputTokens: providerUsage.outputTokens,
579
- systemPrompt: followUpInputBreakdown.systemPrompt,
580
- messages: followUpInputBreakdown.messages,
581
- toolSchemas: followUpInputBreakdown.toolSchemas,
582
- outputEstimate: estimateValueTokens(event.response.messages),
583
- cacheReadTokens: providerUsage.cacheReadTokens,
584
- cacheWriteTokens: providerUsage.cacheWriteTokens,
585
- noCacheTokens: providerUsage.noCacheTokens,
586
- reasoningTokens: providerUsage.reasoningTokens,
587
- logicalInputEstimate: followUpInputBreakdown.logicalInputEstimate,
588
- effectiveNonCachedInput: effectiveNonCachedInput(providerUsage.inputTokens, providerUsage.cacheReadTokens),
589
- });
590
- const nextConversation = [...stripSyntheticControls(compactedMessages), ...event.response.messages];
591
- callbacks.setConversation(nextConversation);
592
- callbacks.debugLog(`conversation updated to ${nextConversation.length} messages after follow-up`);
593
- },
594
- experimental_onToolCallStart({ toolCall }) {
595
- sawToolCall = true;
596
- recordToolStart(toolCall);
597
- resetIdleTimer();
598
- logEntry(callbacks.log, { at: new Date().toISOString(), type: 'tool_call', stream: `continuation:${reason}`, toolCall: { id: toolCall.toolCallId, name: toolCall.toolName, input: toolCall.input } });
599
- callbacks.debugLog(`follow-up tool start: ${toolCall.toolName} ${compact(toolCall.input)}`);
600
- const sig = stableToolKey(toolCall);
601
- const count = (toolCallSignatureCounts.get(sig) ?? 0) + 1;
602
- toolCallSignatureCounts.set(sig, count);
603
- if (count >= TOOL_REPETITION_THRESHOLD && !warnedRepeatedToolSignatures.has(sig)) {
604
- warnedRepeatedToolSignatures.add(sig);
605
- const preview = sig.length > 100 ? `${sig.slice(0, 100)}…` : sig;
606
- 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. Steering the model away from this repeated call.` });
607
- callbacks.debugLog(`tool repetition guard steering (continuation): ${toolCall.toolName} count=${count}`);
608
- }
609
- },
610
- experimental_onToolCallFinish(event) {
611
- resetIdleTimer();
612
- recordToolFinish(event);
613
- 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 } });
614
- const nestedTokens = subagentTokenEstimate(event.output);
615
- if (nestedTokens)
616
- 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 });
617
- const summary = toolResultSummary(event);
618
- toolSummaries.push(`${event.toolCall.toolName}: ${summary}`);
619
- recordToolDisplayFinish(event);
620
- if (!isDuplicateSkippedOutput(event.output))
621
- toolEpoch += 1;
622
- callbacks.debugLog(event.success
623
- ? `follow-up tool done: ${event.toolCall.toolName} after ${event.durationMs}ms ${compact(event.output)}`
624
- : `follow-up tool error: ${event.toolCall.toolName} after ${event.durationMs}ms ${compact(event.error)}`);
625
- },
626
- });
627
- for await (const rawDelta of followUp.textStream) {
628
- resetIdleTimer();
629
- const delta = sanitizeAssistantText(rawDelta);
630
- responseText += delta;
631
- const displayText = assistantDisplayText(responseText);
632
- if ((!shouldStartAssistantStream(displayText, responseStartedAt) || isPrefixOfVisibleAssistantText(displayText)) && !responseStarted)
633
- continue;
634
- if (!responseStarted) {
635
- responseStarted = true;
636
- responseStartedAt = Date.now();
637
- callbacks.onEvent?.(agentEvent({ type: 'message_start', id: responseId, role: 'assistant' }));
638
- const displayedStartedAt = closeToolGroupBeforeAssistantMessage() ?? responseStartedAt;
639
- callbacks.addMessage({ id: responseId, role: 'assistant', text: displayText, streaming: true, startedAt: displayedStartedAt });
640
- }
641
- else {
642
- callbacks.onEvent?.(agentEvent({ type: 'message_update', id: responseId, text: displayText }));
643
- callbacks.updateMessage(responseId, { text: displayText });
644
- }
645
- }
646
- try {
647
- await followUp.response;
648
- }
649
- catch (error) {
650
- throw followUpStreamError ?? error;
651
- }
652
- const finalText = assistantDisplayText(responseText);
653
- const visibleFinalText = finalText;
654
- const hidden = (responseStarted ? isHiddenAssistantFragment(visibleFinalText) : isHiddenUnstartedFinalText(visibleFinalText)) || isDuplicateVisibleAssistantText(visibleFinalText);
655
- if (responseStarted) {
374
+ const finalizeAssistantSegment = (options = {}) => {
375
+ const finalText = assistantDisplayText(currentAssistantText);
376
+ const normalized = normalizeAssistantText(finalText);
377
+ const hidden = (assistantStarted ? isHiddenAssistantFragment(finalText) : isHiddenUnstartedFinalText(finalText)) || (options.beforeTool === true && isShortUnfinishedBridgeBeforeTool(finalText)) || (normalized.length > 0 && visibleAssistantTexts.has(normalized));
378
+ if (assistantStarted) {
656
379
  if (!hidden)
657
- rememberVisibleAssistantText(visibleFinalText);
658
- callbacks.onEvent?.(agentEvent({ type: 'message_end', id: responseId, text: visibleFinalText, hidden }));
659
- callbacks.updateMessage(responseId, { text: visibleFinalText, streaming: false, hidden, ...responseCompletionMetrics(visibleFinalText, responseStartedAt) });
380
+ rememberVisibleAssistantText(finalText);
381
+ callbacks.onEvent?.(agentEvent({ type: 'message_end', id: currentAssistantId, text: finalText, hidden }));
382
+ callbacks.updateMessage(currentAssistantId, { text: finalText, streaming: false, hidden, ...responseCompletionMetrics(finalText, assistantStartedAt) });
660
383
  }
661
384
  else if (!hidden) {
662
- rememberVisibleAssistantText(visibleFinalText);
663
- callbacks.onEvent?.(agentEvent({ type: 'message_start', id: responseId, role: 'assistant' }));
664
- callbacks.onEvent?.(agentEvent({ type: 'message_end', id: responseId, text: visibleFinalText, hidden: false }));
665
- callbacks.addMessage({ id: responseId, role: 'assistant', text: visibleFinalText, streaming: false, startedAt: responseStartedAt, ...responseCompletionMetrics(visibleFinalText, responseStartedAt) });
385
+ if (!hidden)
386
+ rememberVisibleAssistantText(finalText);
387
+ callbacks.onEvent?.(agentEvent({ type: 'message_start', id: currentAssistantId, role: 'assistant' }));
388
+ callbacks.onEvent?.(agentEvent({ type: 'message_end', id: currentAssistantId, text: finalText, hidden: false }));
389
+ callbacks.addMessage({ id: currentAssistantId, role: 'assistant', text: finalText, streaming: false, startedAt: assistantStartedAt, ...responseCompletionMetrics(finalText, assistantStartedAt) });
666
390
  }
667
- return { text: finalText, id: responseId, started: responseStarted };
668
- }
669
- let streamError;
670
- let lastFinishReason;
671
- const mainSystemPrompt = buildSystemPrompt(activeContextFiles, session);
672
- const mainInputBreakdown = estimateInputBreakdown({ system: mainSystemPrompt, contextFiles: activeContextFiles, messages: requestMessages, tools: availableTools });
673
- logEntry(callbacks.log, { at: new Date().toISOString(), type: 'request', stream: 'main', system: mainSystemPrompt, messages: requestMessages, tools: Object.keys(availableTools), context: mainInputBreakdown.breakdown });
674
- const result = streamText({
391
+ resetAssistantSegment();
392
+ return !hidden;
393
+ };
394
+ const agent = new ToolLoopAgent({
395
+ id: 'haze-main',
675
396
  model: activeModel,
676
- maxOutputTokens: DEFAULT_MAX_OUTPUT_TOKENS,
677
- system: mainSystemPrompt,
678
- messages: requestMessages,
397
+ instructions: systemPrompt,
679
398
  tools: availableTools,
399
+ maxOutputTokens: DEFAULT_MAX_OUTPUT_TOKENS,
680
400
  ...providerSettings,
681
401
  stopWhen: stepCountIs(MAIN_STEP_LIMIT),
682
- abortSignal: abortController.signal,
683
402
  experimental_context: toolExecutionContext,
684
- onError({ error }) {
685
- streamError = error;
686
- callbacks.debugLog(`stream error: ${error instanceof Error ? error.message : String(error)}`);
687
- },
688
403
  prepareStep({ steps, messages }) {
689
404
  const toolCalls = steps.flatMap(step => step.toolCalls);
690
405
  const repeatedToolNames = uniqueRepeatedToolNames(toolCalls);
691
- const repeatedToolCall = repeatedToolNames.length > 0;
692
- const consecutiveToolOnlySteps = toolOnlyStepCount(steps);
693
- if (likelyPlanOnlyRequest && mutatingToolSucceeded) {
694
- return {
695
- toolChoice: 'none',
696
- };
697
- }
698
- if (editRecoveryPath && !editRecoveryReadSatisfied) {
699
- return {
700
- activeTools: ['readFile'],
701
- };
702
- }
703
- if (repeatedToolCall) {
406
+ if (likelyPlanOnlyRequest && mutatingToolSucceeded)
407
+ return { toolChoice: 'none' };
408
+ if (editRecoveryPath && !editRecoveryReadSatisfied)
409
+ return { activeTools: ['readFile'] };
410
+ if (repeatedToolNames.length > 0) {
704
411
  const activeTools = Object.keys(availableTools).filter(name => !repeatedToolNames.includes(name));
705
412
  callbacks.debugLog(`disabling repeated tools for next step: ${repeatedToolNames.join(', ')}`);
706
413
  return activeTools.length > 0
707
414
  ? { activeTools, messages: withSyntheticControl(messages, repeatedToolCallPrompt(repeatedToolNames)) }
708
415
  : { toolChoice: 'none', messages: withSyntheticControl(messages, repeatedToolCallPrompt(repeatedToolNames)) };
709
416
  }
710
- if (toolCalls.length >= MAIN_TOOL_CALL_LIMIT || consecutiveToolOnlySteps >= MAIN_TOOL_ONLY_STEP_LIMIT) {
417
+ if (toolCalls.length >= MAIN_TOOL_CALL_LIMIT || toolOnlyStepCount(steps) >= MAIN_TOOL_ONLY_STEP_LIMIT) {
711
418
  callbacks.debugLog('forcing text response to avoid tool loop');
712
- turnStopReason = toolCalls.length >= MAIN_TOOL_CALL_LIMIT
713
- ? { 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.` }
714
- : { kind: 'tool_only_limit', message: `Made ${MAIN_TOOL_ONLY_STEP_LIMIT} consecutive inspection-only steps without making changes. Type "continue" to resume.` };
715
- return {
716
- toolChoice: 'none',
717
- messages: withSyntheticControl(messages, toolLoopBudgetPrompt()),
718
- };
419
+ return { toolChoice: 'none', messages: withSyntheticControl(messages, toolLoopBudgetPrompt()) };
719
420
  }
720
421
  return undefined;
721
422
  },
722
423
  onStepFinish({ stepNumber, text, toolCalls, toolResults, finishReason, usage, response }) {
723
- for (const toolCall of toolCalls)
724
- ensureToolDisplayItem(toolCall);
725
- if (Array.isArray(response?.messages) && response.messages.length > 0) {
424
+ if (Array.isArray(response?.messages) && response.messages.length > 0)
726
425
  latestAccumulatedResponseMessages = response.messages;
727
- }
728
- if (!turnStopReason && stepNumber >= MAIN_STEP_LIMIT - 1) {
729
- 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.` };
730
- }
731
- lastFinishReason = finishReason;
732
426
  const stepInputTokens = usage?.inputTokens;
733
427
  const stepOutputTokens = usage?.outputTokens;
734
428
  const stepCacheRead = usage?.inputTokenDetails?.cacheReadTokens ?? 0;
@@ -737,275 +431,181 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
737
431
  const stepNoCache = effectiveNonCachedInput(stepInputTokens, stepCacheRead) ?? 0;
738
432
  const stepCacheHitRatio = cacheHitRatio(stepInputTokens, stepCacheRead || undefined);
739
433
  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 } });
740
- if (stepCacheHitRatio !== undefined && stepCacheHitRatio < 0.5 && stepNoCache > 2000) {
741
- 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.` });
742
- }
743
- 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)}%` : ''}`);
744
- // Repetition guard: when a constrained (no-tools) step emits short text
745
- // that matches the prior two short-text steps, the model is stuck in a
746
- // "Let me X" loop. Abort the whole turn so we don't burn maxOutputTokens
747
- // on every remaining step in the limit. The secondary consecutive-text-only
748
- // check catches varied-phrasing loops (e.g. "Let me install" → "I'll install
749
- // dependencies now" → "Now let me run npm install") that the exact-signature
750
- // check would miss.
751
- if (finishReason === 'stop' && toolCalls.length === 0) {
752
- consecutiveTextOnlySteps += 1;
753
- const signature = text.trim().toLowerCase().replace(/[^a-z0-9 ]/g, '').replace(/\s+/g, ' ').slice(0, 120);
754
- if (signature.length >= 8) {
755
- recentStepTextSignatures.push(signature);
756
- const last3 = recentStepTextSignatures.slice(-3);
757
- if (last3.length === 3 && last3[0] === last3[1] && last3[1] === last3[2] && !repetitionAbortFired) {
758
- repetitionAbortFired = true;
759
- 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.' };
760
- 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)}"` });
761
- callbacks.debugLog(`repetition guard abort at step ${stepNumber}; signature="${signature.slice(0, 60)}"`);
762
- abortController.abort('Haze repetition guard: 3 consecutive identical text-only steps.');
763
- }
764
- }
765
- if (consecutiveTextOnlySteps >= 4 && !repetitionAbortFired) {
766
- repetitionAbortFired = true;
767
- 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.' };
768
- 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.` });
769
- callbacks.debugLog(`repetition guard abort at step ${stepNumber}; consecutiveTextOnlySteps=${consecutiveTextOnlySteps}`);
770
- abortController.abort(`Haze repetition guard: ${consecutiveTextOnlySteps} consecutive text-only steps without progress.`);
771
- }
772
- }
773
- else {
774
- consecutiveTextOnlySteps = 0;
775
- }
434
+ callbacks.debugLog(`step ${stepNumber} finished: ${finishReason}; text=${text.length}; toolCalls=${toolCalls.length}; toolResults=${toolResults.length}`);
776
435
  },
777
436
  onFinish(event) {
778
- const providerUsage = extractUsage(event);
437
+ const providerUsage = extractUsage({ usage: event.totalUsage ?? event.usage });
779
438
  callbacks.recordTokenUsage?.({
780
439
  inputTokens: providerUsage.inputTokens,
781
440
  outputTokens: providerUsage.outputTokens,
782
- systemPrompt: mainInputBreakdown.systemPrompt,
783
- messages: mainInputBreakdown.messages,
784
- toolSchemas: mainInputBreakdown.toolSchemas,
441
+ systemPrompt: inputBreakdown.systemPrompt,
442
+ messages: inputBreakdown.messages,
443
+ toolSchemas: inputBreakdown.toolSchemas,
785
444
  outputEstimate: estimateValueTokens(event.response.messages),
786
445
  cacheReadTokens: providerUsage.cacheReadTokens,
787
446
  cacheWriteTokens: providerUsage.cacheWriteTokens,
788
447
  noCacheTokens: providerUsage.noCacheTokens,
789
448
  reasoningTokens: providerUsage.reasoningTokens,
790
- logicalInputEstimate: mainInputBreakdown.logicalInputEstimate,
449
+ logicalInputEstimate: inputBreakdown.logicalInputEstimate,
791
450
  effectiveNonCachedInput: effectiveNonCachedInput(providerUsage.inputTokens, providerUsage.cacheReadTokens),
792
451
  });
793
452
  const accumulated = [...stripSyntheticControls(requestMessages), ...event.response.messages];
794
453
  const compacted = compactToolHistory(accumulated);
795
- const nextConversation = compacted.messages;
796
- callbacks.setConversation(nextConversation);
797
- if (compacted.compactedResults > 0 || compacted.compactedCalls > 0) {
798
- callbacks.debugLog(`end-of-turn compaction: ${compacted.compactedResults} results, ${compacted.compactedCalls} tool-call inputs compacted`);
799
- 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.` });
800
- }
801
- callbacks.debugLog(`conversation updated to ${nextConversation.length} messages`);
802
- },
803
- experimental_onToolCallStart({ toolCall }) {
804
- sawToolCall = true;
805
- recordToolStart(toolCall);
806
- resetIdleTimer();
807
- logEntry(callbacks.log, { at: new Date().toISOString(), type: 'tool_call', stream: 'main', toolCall: { id: toolCall.toolCallId, name: toolCall.toolName, input: toolCall.input } });
808
- callbacks.debugLog(`tool start: ${toolCall.toolName} ${compact(toolCall.input)}`);
809
- // Tool-repetition guard: if the same (toolName, input) has been called
810
- // TOOL_REPETITION_THRESHOLD times this turn, log once. prepareStep then
811
- // disables that repeated tool and injects a model-facing correction.
812
- const sig = stableToolKey(toolCall);
813
- const count = (toolCallSignatureCounts.get(sig) ?? 0) + 1;
814
- toolCallSignatureCounts.set(sig, count);
815
- if (count >= TOOL_REPETITION_THRESHOLD && !warnedRepeatedToolSignatures.has(sig)) {
816
- warnedRepeatedToolSignatures.add(sig);
817
- const preview = sig.length > 100 ? `${sig.slice(0, 100)}…` : sig;
818
- logEntry(callbacks.log, { at: new Date().toISOString(), type: 'warning', stream: 'main', text: `tool repetition guard: "${preview}" called ${count} times with identical input this turn. Steering the model away from this repeated call.` });
819
- callbacks.debugLog(`tool repetition guard steering: ${toolCall.toolName} count=${count} sig=${preview}`);
820
- }
454
+ callbacks.setConversation(compacted.messages);
455
+ callbacks.debugLog(`conversation updated to ${compacted.messages.length} messages by ToolLoopAgent`);
821
456
  },
822
- experimental_onToolCallFinish(event) {
823
- resetIdleTimer();
824
- const summary = toolResultSummary(event);
825
- recordToolFinish(event);
826
- 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 } });
827
- const nestedTokens = subagentTokenEstimate(event.output);
828
- if (nestedTokens)
829
- 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 });
830
- toolSummaries.push(`${event.toolCall.toolName}: ${summary}`);
831
- recordToolDisplayFinish(event);
832
- if (!isDuplicateSkippedOutput(event.output))
833
- toolEpoch += 1;
834
- callbacks.debugLog(event.success
835
- ? `tool done: ${event.toolCall.toolName} after ${event.durationMs}ms ${compact(event.output)}`
836
- : `tool error: ${event.toolCall.toolName} after ${event.durationMs}ms ${compact(event.error)}`);
837
- }
838
457
  });
839
- for await (const rawDelta of result.textStream) {
458
+ resetIdleTimer();
459
+ const result = await agent.stream({ messages: requestMessages, abortSignal: abortController.signal });
460
+ for await (const part of result.fullStream) {
840
461
  resetIdleTimer();
841
- const delta = sanitizeAssistantText(rawDelta);
842
- if (sawToolCall)
843
- textAfterTool = true;
844
- if (currentAssistantStarted && currentAssistantText.length > 0 && toolEpoch > currentAssistantToolEpoch) {
845
- const intermediateText = assistantDisplayText(currentAssistantText);
846
- const hidden = isHiddenAssistantFragment(intermediateText) || isDuplicateVisibleAssistantText(intermediateText);
847
- if (!hidden)
848
- rememberVisibleAssistantText(intermediateText);
849
- callbacks.onEvent?.(agentEvent({ type: 'message_end', id: currentAssistantId, text: intermediateText, hidden }));
850
- callbacks.updateMessage(currentAssistantId, { text: intermediateText, streaming: false, hidden, ...responseCompletionMetrics(intermediateText, currentAssistantStartedAt) });
851
- currentAssistantId = `assistant-${Date.now()}-${Math.random().toString(36).slice(2)}`;
852
- currentAssistantStarted = false;
853
- currentAssistantStartedAt = Date.now();
854
- currentAssistantText = '';
855
- currentAssistantToolEpoch = toolEpoch;
856
- }
857
- assistantText += delta;
858
- currentAssistantText += delta;
859
- const displayText = assistantDisplayText(currentAssistantText);
860
- if ((!shouldStartAssistantStream(displayText, currentAssistantStartedAt) || isPrefixOfVisibleAssistantText(displayText)) && !currentAssistantStarted)
861
- continue;
862
- if (!currentAssistantStarted) {
863
- assistantStarted = true;
864
- currentAssistantStarted = true;
865
- callbacks.onEvent?.(agentEvent({ type: 'message_start', id: currentAssistantId, role: 'assistant' }));
866
- currentAssistantStartedAt = Date.now();
867
- const displayedStartedAt = closeToolGroupBeforeAssistantMessage() ?? currentAssistantStartedAt;
868
- callbacks.addMessage({ id: currentAssistantId, role: 'assistant', text: displayText, streaming: true, startedAt: displayedStartedAt });
869
- }
870
- else {
871
- callbacks.onEvent?.(agentEvent({ type: 'message_update', id: currentAssistantId, text: displayText }));
872
- callbacks.updateMessage(currentAssistantId, { text: displayText });
462
+ switch (part.type) {
463
+ case 'text-delta': {
464
+ startFreshToolGroup();
465
+ const delta = sanitizeAssistantText(part.text);
466
+ assistantText += delta;
467
+ currentAssistantText += delta;
468
+ const displayText = assistantDisplayText(currentAssistantText);
469
+ if (!assistantStarted && !shouldStartAssistantStream(displayText, assistantStartedAt))
470
+ break;
471
+ if (!assistantStarted) {
472
+ assistantStarted = true;
473
+ assistantStartedAt = Date.now();
474
+ callbacks.onEvent?.(agentEvent({ type: 'message_start', id: currentAssistantId, role: 'assistant' }));
475
+ callbacks.addMessage({ id: currentAssistantId, role: 'assistant', text: displayText, streaming: true, startedAt: assistantStartedAt });
476
+ }
477
+ else {
478
+ callbacks.onEvent?.(agentEvent({ type: 'message_update', id: currentAssistantId, text: displayText }));
479
+ callbacks.updateMessage(currentAssistantId, { text: displayText });
480
+ }
481
+ break;
482
+ }
483
+ case 'tool-input-start': {
484
+ if (currentAssistantText.trim().length > 0 || assistantStarted)
485
+ finalizeAssistantSegment({ beforeTool: true });
486
+ const toolCall = { toolCallId: part.id, toolName: part.toolName, input: {} };
487
+ latestToolCalls.set(part.id, toolCall);
488
+ startedTools.set(part.id, Date.now());
489
+ ensureToolItem(toolCall);
490
+ break;
491
+ }
492
+ case 'tool-call': {
493
+ if (currentAssistantText.trim().length > 0 || assistantStarted)
494
+ finalizeAssistantSegment({ beforeTool: true });
495
+ const toolCall = { toolCallId: part.toolCallId, toolName: part.toolName, input: part.input };
496
+ latestToolCalls.set(part.toolCallId, toolCall);
497
+ if (!startedTools.has(part.toolCallId))
498
+ startedTools.set(part.toolCallId, Date.now());
499
+ ensureToolItem(toolCall).summary = toolCallSummary(part.toolName, part.input);
500
+ updateToolGroup(true);
501
+ break;
502
+ }
503
+ case 'tool-result': {
504
+ const toolCall = { toolCallId: part.toolCallId, toolName: part.toolName, input: part.input };
505
+ latestToolCalls.set(part.toolCallId, toolCall);
506
+ const startedAt = startedTools.get(part.toolCallId) ?? Date.now();
507
+ const finish = { toolCall, success: true, output: part.output, durationMs: Date.now() - startedAt };
508
+ const item = ensureToolItem(toolCall);
509
+ item.status = toolOutputOk(part.output, true) ? 'success' : 'error';
510
+ item.result = toolResultSummary(finish);
511
+ item.durationMs = finish.durationMs;
512
+ item.finishedAt = startedAt + finish.durationMs;
513
+ callbacks.onEvent?.(agentEvent({ type: 'tool_end', id: toolCall.toolCallId, name: toolCall.toolName, success: true, output: part.output, durationMs: finish.durationMs }));
514
+ logEntry(callbacks.log, { at: new Date().toISOString(), type: 'tool_result', stream: 'main', toolResult: { id: toolCall.toolCallId, name: toolCall.toolName, success: true, output: part.output, durationMs: finish.durationMs } });
515
+ const ok = toolOutputOk(part.output, true);
516
+ const path = toolInputPath(toolCall.input);
517
+ if (!ok && ['editFile', 'replaceLines', 'writeFile'].includes(toolCall.toolName)) {
518
+ editRecoveryPath = path;
519
+ editRecoveryReadSatisfied = false;
520
+ }
521
+ if (ok && toolCall.toolName === 'readFile' && path && path === editRecoveryPath && !isDuplicateSkippedOutput(part.output)) {
522
+ editRecoveryReadSatisfied = true;
523
+ }
524
+ if (ok && !isDuplicateSkippedOutput(part.output) && ['editFile', 'replaceLines', 'writeFile'].includes(toolCall.toolName)) {
525
+ mutatingToolSucceeded = true;
526
+ if (!path || path === editRecoveryPath) {
527
+ editRecoveryPath = undefined;
528
+ editRecoveryReadSatisfied = false;
529
+ }
530
+ }
531
+ observeGoalToolEvent(goal, { ...toolCall, success: ok, output: part.output, duplicateSkipped: isDuplicateSkippedOutput(part.output) });
532
+ callbacks.setWorkState?.(goal.workState);
533
+ callbacks.setGoalStatus?.(formatGoalStatus(goal));
534
+ activeContextFiles = rememberContextFilesFromToolOutput(activeContextFiles, part.output);
535
+ if (toolCall.toolName === 'writeTasks')
536
+ callbacks.onTasksChanged?.();
537
+ const nestedTokens = subagentTokenEstimate(part.output);
538
+ if (nestedTokens)
539
+ 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 });
540
+ updateToolGroup(true);
541
+ break;
542
+ }
543
+ case 'tool-error': {
544
+ const existing = latestToolCalls.get(part.toolCallId);
545
+ const toolCall = { toolCallId: part.toolCallId, toolName: part.toolName, input: part.input ?? existing?.input };
546
+ const startedAt = startedTools.get(part.toolCallId) ?? Date.now();
547
+ const finish = { toolCall, success: false, error: part.error, durationMs: Date.now() - startedAt };
548
+ const item = ensureToolItem(toolCall);
549
+ item.status = 'error';
550
+ item.result = toolResultSummary(finish);
551
+ item.durationMs = finish.durationMs;
552
+ item.finishedAt = startedAt + finish.durationMs;
553
+ callbacks.onEvent?.(agentEvent({ type: 'tool_end', id: toolCall.toolCallId, name: toolCall.toolName, success: false, error: part.error, durationMs: finish.durationMs }));
554
+ logEntry(callbacks.log, { at: new Date().toISOString(), type: 'tool_result', stream: 'main', toolResult: { id: toolCall.toolCallId, name: toolCall.toolName, success: false, error: part.error, durationMs: finish.durationMs } });
555
+ if (['editFile', 'replaceLines', 'writeFile'].includes(toolCall.toolName)) {
556
+ editRecoveryPath = toolInputPath(toolCall.input);
557
+ editRecoveryReadSatisfied = false;
558
+ }
559
+ observeGoalToolEvent(goal, { ...toolCall, success: false, error: part.error });
560
+ callbacks.setWorkState?.(goal.workState);
561
+ callbacks.setGoalStatus?.(formatGoalStatus(goal));
562
+ updateToolGroup(true);
563
+ break;
564
+ }
565
+ case 'error':
566
+ streamError = part.error;
567
+ callbacks.debugLog(`stream error: ${part.error instanceof Error ? part.error.message : String(part.error)}`);
568
+ break;
569
+ case 'finish':
570
+ streamFinished = true;
571
+ callbacks.debugLog(`ToolLoopAgent finished: ${part.finishReason}`);
572
+ break;
573
+ default:
574
+ break;
873
575
  }
874
576
  }
875
- let completedConversation = callbacks.getConversation();
876
577
  try {
877
578
  const response = await result.response;
878
- completedConversation = [...stripSyntheticControls(requestMessages), ...response.messages];
879
- callbacks.setConversation(completedConversation);
579
+ const completedConversation = [...stripSyntheticControls(requestMessages), ...response.messages];
580
+ callbacks.setConversation(compactToolHistory(completedConversation).messages);
880
581
  }
881
582
  catch (error) {
882
- // The turn was aborted or errored mid-stream. If we have any accumulated
883
- // response messages from completed steps (tracked in onStepFinish), persist
884
- // them so the next turn inherits the partial work instead of losing it.
885
583
  if (latestAccumulatedResponseMessages.length > 0) {
886
- const accumulated = [...stripSyntheticControls(requestMessages), ...latestAccumulatedResponseMessages];
887
- const compacted = compactToolHistory(accumulated);
888
- callbacks.setConversation(compacted.messages);
889
- if (compacted.compactedResults > 0 || compacted.compactedCalls > 0) {
890
- 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.` });
891
- }
892
- callbacks.debugLog(`abort recovery: persisted ${latestAccumulatedResponseMessages.length} response messages before re-throwing`);
893
- }
894
- throw streamError ?? error;
895
- }
896
- callbacks.debugLog(`response stream finished; session has ${completedConversation.length} model messages`);
897
- if (lastFinishReason === 'length' && !sawToolCall && completionContinuationCount < maxCompletionContinuations) {
898
- completionContinuationCount += 1;
899
- callbacks.debugLog('output token limit reached, auto-continuing');
900
- const continuation = await streamAssistantResponse(completedConversation, 'output token limit reached', 'Your response was cut off because you hit the output token limit. Continue from where you left off — do not repeat what you already said, just pick up exactly where you stopped.', true);
901
- completedConversation = callbacks.getConversation();
902
- if (continuation.text) {
903
- assistantText += '\n' + continuation.text;
904
- }
905
- }
906
- const combinedAssistantText = assistantDisplayText(assistantText);
907
- const decideCompletion = (text) => completionDecision({
908
- request: value,
909
- goal,
910
- assistantText: text,
911
- sawReadOnlyTool,
912
- sawToolCall,
913
- mutatingToolSucceeded,
914
- validationToolSucceeded,
915
- validationToolFailed,
916
- editFileFailed,
917
- editRecoveryPath,
918
- editRecoveryReasonCode,
919
- });
920
- let decision = decideCompletion(combinedAssistantText);
921
- async function runCompletionLoop(seedConversation, seedText) {
922
- let loopConversation = seedConversation;
923
- let latestText = seedText;
924
- let noProgressSlices = 0;
925
- while ((decision.needsActionContinuation || decision.needsValidationContinuation) && completionContinuationCount < maxCompletionContinuations) {
926
- completionContinuationCount += 1;
927
- const revisionBefore = goal.workState.revision;
928
- const prompt = decision.continuationPrompt
929
- ?? (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.');
930
- const continuation = await streamAssistantResponse(loopConversation, `completion gate ${completionContinuationCount}`, prompt, true);
931
- loopConversation = callbacks.getConversation();
932
- if (continuation.text)
933
- latestText = continuation.text;
934
- decision = decideCompletion(latestText);
935
- noProgressSlices = goal.workState.revision === revisionBefore ? noProgressSlices + 1 : 0;
936
- if (noProgressSlices >= 2)
937
- break;
938
- }
939
- if ((decision.needsActionContinuation || decision.needsValidationContinuation) && noProgressSlices >= 2) {
940
- callbacks.addMessage({ role: 'assistant', text: 'Status: partial. Two continuation slices made no tool progress; the latest work state and blocker evidence were preserved.' });
941
- }
942
- if ((decision.needsActionContinuation || decision.needsValidationContinuation) && completionContinuationCount >= maxCompletionContinuations) {
943
- 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.' });
944
- }
945
- if (!latestText && toolSummaries.length > 0) {
946
- const followUp = await streamAssistantResponse(loopConversation, 'completion loop ended without text', noTextAfterToolPrompt(false), false);
947
- if (!followUp.text)
948
- callbacks.addMessage({ role: 'assistant', text: `Finished tool work but the model did not produce a final response. Last tool result: ${toolSummaries.at(-1)}.` });
949
- }
950
- }
951
- if (!assistantStarted) {
952
- const hidden = isHiddenUnstartedFinalText(combinedAssistantText) || isDuplicateVisibleAssistantText(combinedAssistantText);
953
- if (!hidden) {
954
- assistantStarted = true;
955
- currentAssistantStarted = true;
956
- currentAssistantText = combinedAssistantText;
957
- callbacks.onEvent?.(agentEvent({ type: 'message_start', id: currentAssistantId, role: 'assistant' }));
958
- callbacks.addMessage({ id: currentAssistantId, role: 'assistant', text: combinedAssistantText, streaming: true, startedAt: currentAssistantStartedAt });
959
- }
960
- }
961
- if (assistantStarted) {
962
- const visibleFinalAssistantText = assistantDisplayText(currentAssistantText);
963
- const hidden = isHiddenAssistantFragment(visibleFinalAssistantText) || isDuplicateVisibleAssistantText(visibleFinalAssistantText);
964
- if (!hidden)
965
- rememberVisibleAssistantText(visibleFinalAssistantText);
966
- callbacks.onEvent?.(agentEvent({ type: 'message_end', id: currentAssistantId, text: visibleFinalAssistantText, hidden }));
967
- callbacks.updateMessage(currentAssistantId, { text: visibleFinalAssistantText, streaming: false, hidden, ...responseCompletionMetrics(visibleFinalAssistantText, currentAssistantStartedAt) });
968
- if (decision.needsActionContinuation || decision.needsValidationContinuation) {
969
- await runCompletionLoop(completedConversation, combinedAssistantText);
970
- }
971
- else if (sawToolCall && !textAfterTool) {
972
- const followUp = await streamAssistantResponse(completedConversation, 'tool use completed without follow-up text', noTextAfterToolPrompt(false), false);
973
- if (!followUp.text) {
974
- callbacks.addMessage({ role: 'assistant', text: 'Stopped after tool use without a follow-up response. You can ask me to continue if the task is not complete.' });
975
- }
584
+ callbacks.setConversation(compactToolHistory([...stripSyntheticControls(requestMessages), ...latestAccumulatedResponseMessages]).messages);
976
585
  }
586
+ const text = error instanceof Error ? error.message : String(error);
587
+ const benignTerminatedAfterStream = text === 'terminated' && (streamFinished || assistantText.trim().length > 0 || latestToolCalls.size > 0);
588
+ if (!benignTerminatedAfterStream)
589
+ throw streamError ?? error;
590
+ callbacks.debugLog(`ignored post-stream response error: ${text}`);
977
591
  }
978
- else if (sawToolCall) {
979
- const allowTools = (likelyActionRequest && (!mutatingToolSucceeded || editFileFailed)) || (likelyValidationRequest && !validationToolSucceeded);
980
- const prompt = noTextAfterToolPrompt(allowTools);
981
- const followUp = await streamAssistantResponse(completedConversation, 'tool-only turn completed without text', prompt, allowTools);
982
- decision = decideCompletion(followUp.text);
983
- if (allowTools)
984
- await runCompletionLoop(callbacks.getConversation(), followUp.text);
985
- if (!followUp.text && completionContinuationCount === 0) {
986
- const fallback = toolSummaries.length > 0
987
- ? `Finished tool work but the model did not produce a final response. Last tool result: ${toolSummaries.at(-1)}.`
988
- : 'Finished without a text response.';
989
- callbacks.addMessage({ id: currentAssistantId, role: 'assistant', text: fallback, streaming: false, startedAt: currentAssistantStartedAt, ...responseCompletionMetrics(fallback, currentAssistantStartedAt) });
990
- }
592
+ if (currentAssistantText.trim().length > 0 || assistantStarted) {
593
+ finalizeAssistantSegment();
991
594
  }
992
- else {
993
- const fallback = 'Finished without a text response.';
994
- callbacks.addMessage({ id: currentAssistantId, role: 'assistant', text: fallback, streaming: false, startedAt: currentAssistantStartedAt, ...responseCompletionMetrics(fallback, currentAssistantStartedAt) });
595
+ else if (latestToolCalls.size > 0) {
596
+ const fallback = `Finished tool work.${toolInputPath([...latestToolCalls.values()].at(-1)?.input) ? '' : ''}`;
597
+ callbacks.addMessage({ id: currentAssistantId, role: 'assistant', text: fallback, streaming: false, startedAt: assistantStartedAt, ...responseCompletionMetrics(fallback, assistantStartedAt) });
995
598
  }
996
599
  goal.phase = 'done';
997
600
  goal.status = 'complete';
998
- turnStatus = 'complete';
999
- if (turnStopReason) {
1000
- callbacks.addMessage({ role: 'system', text: turnStopReason.message });
1001
- }
1002
601
  callbacks.setGoalStatus?.(undefined);
602
+ turnStatus = 'complete';
1003
603
  }
1004
604
  catch (error) {
1005
605
  if (abortController.signal.aborted) {
1006
606
  turnStatus = 'aborted';
1007
607
  callbacks.debugLog('request aborted');
1008
- callbacks.addMessage({ role: 'system', text: turnStopReason?.message ?? 'Thinking aborted. You can type again.' });
608
+ callbacks.addMessage({ role: 'system', text: 'Thinking aborted. You can type again.' });
1009
609
  }
1010
610
  else {
1011
611
  const text = error instanceof Error ? error.message : String(error);
@@ -1035,12 +635,15 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
1035
635
  }
1036
636
  }
1037
637
  finally {
638
+ if (loadedMcp?.clients.length)
639
+ await closeMcpClients(loadedMcp.clients);
1038
640
  if (idleTimer)
1039
641
  clearTimeout(idleTimer);
642
+ stopToolTimer();
1040
643
  finalizeToolGroup();
1041
- stopActiveTimers();
1042
644
  callbacks.onEvent?.(agentEvent({ type: 'turn_end', request: value, status: turnStatus }));
1043
645
  callbacks.setAbortController?.(null);
646
+ callbacks.setBusyLabel?.('Haze is thinking');
1044
647
  callbacks.setBusy(false);
1045
648
  }
1046
649
  }