@denizokcu/haze 0.4.0 → 0.5.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 (51) hide show
  1. package/CHANGELOG.md +28 -0
  2. package/README.md +31 -29
  3. package/dist/cli/commands/chat.js +106 -48
  4. package/dist/cli/commands/commands.js +15 -1
  5. package/dist/cli/commands/streaming.d.ts +4 -0
  6. package/dist/cli/commands/streaming.js +242 -111
  7. package/dist/config/contextFiles.d.ts +6 -0
  8. package/dist/config/contextFiles.js +47 -16
  9. package/dist/config/providers.d.ts +2 -5
  10. package/dist/config/providers.js +16 -12
  11. package/dist/core/agent/requestAssembly.js +12 -1
  12. package/dist/core/agent/toolOutputStore.d.ts +6 -1
  13. package/dist/core/agent/toolOutputStore.js +33 -1
  14. package/dist/core/bashOutput/ansi.d.ts +1 -0
  15. package/dist/core/bashOutput/ansi.js +7 -0
  16. package/dist/core/bashOutput/command.d.ts +2 -0
  17. package/dist/core/bashOutput/command.js +62 -0
  18. package/dist/core/bashOutput/lineFilter.d.ts +25 -0
  19. package/dist/core/bashOutput/lineFilter.js +62 -0
  20. package/dist/core/bashOutput/reducers/content.d.ts +3 -0
  21. package/dist/core/bashOutput/reducers/content.js +134 -0
  22. package/dist/core/bashOutput/reducers/git.d.ts +1 -0
  23. package/dist/core/bashOutput/reducers/git.js +147 -0
  24. package/dist/core/bashOutput/reducers/search.d.ts +7 -0
  25. package/dist/core/bashOutput/reducers/search.js +76 -0
  26. package/dist/core/bashOutput/reducers/validation.d.ts +2 -0
  27. package/dist/core/bashOutput/reducers/validation.js +41 -0
  28. package/dist/core/bashOutput/registry.d.ts +4 -0
  29. package/dist/core/bashOutput/registry.js +126 -0
  30. package/dist/core/bashOutput/types.d.ts +46 -0
  31. package/dist/core/bashOutput/types.js +1 -0
  32. package/dist/core/goal/completionPolicy.d.ts +1 -0
  33. package/dist/core/goal/completionPolicy.js +4 -0
  34. package/dist/core/safety/urlGuard.d.ts +37 -0
  35. package/dist/core/safety/urlGuard.js +206 -0
  36. package/dist/core/subagent/subagentRunner.d.ts +1 -1
  37. package/dist/core/subagent/subagentRunner.js +2 -2
  38. package/dist/core/toolOutput/reduction.d.ts +25 -0
  39. package/dist/core/toolOutput/reduction.js +23 -0
  40. package/dist/llm/client.d.ts +2 -2
  41. package/dist/llm/client.js +6 -4
  42. package/dist/llm/hazeTools.d.ts +133 -16
  43. package/dist/llm/hazeTools.js +205 -31
  44. package/dist/llm/initPrompt.js +2 -1
  45. package/dist/llm/systemPrompt.js +3 -1
  46. package/dist/llm/toolResultTypes.d.ts +1 -1
  47. package/dist/llm/webFetch.d.ts +57 -0
  48. package/dist/llm/webFetch.js +270 -0
  49. package/dist/ui/components/MarkdownText.d.ts +2 -0
  50. package/dist/ui/components/MarkdownText.js +116 -3
  51. package/package.json +17 -10
@@ -5,9 +5,9 @@ import { hazeTools } from '../../llm/hazeTools.js';
5
5
  import { buildSystemPrompt } from '../../llm/systemPrompt.js';
6
6
  import { loadSkillRegistry } from '../../skills/SkillRegistry.js';
7
7
  import { buildSkillTools } from '../../skills/skillTools.js';
8
- import { compact, toolCallSummary, toolResultSummary, formatElapsedTime, formatElapsedTimeWhole, formatSeconds } from './formatters.js';
8
+ import { compact, toolCallSummary, toolResultSummary, formatElapsedTimeWhole, formatSeconds } from './formatters.js';
9
9
  import { isActionRequest, isPlanImplementationRequest, isPlanOnlyRequest, isValidationRequest } from '../../core/goal/requestClassifier.js';
10
- import { completionDecision, looksIncomplete, noTextAfterToolPrompt, postContinuationPrompt, toolLoopBudgetPrompt } from '../../core/goal/completionPolicy.js';
10
+ import { completionDecision, looksIncomplete, noTextAfterToolPrompt, postContinuationPrompt, repeatedToolCallPrompt, toolLoopBudgetPrompt } from '../../core/goal/completionPolicy.js';
11
11
  import { createSessionGoal, formatGoalStatus, observeGoalToolEvent } from '../../core/goal/sessionGoal.js';
12
12
  import { agentEvent } from '../../core/agent/events.js';
13
13
  import { isContextOverflowError, isRetryableModelError } from '../../core/agent/errors.js';
@@ -50,8 +50,70 @@ function hideSyntheticToolCallMarkup(text) {
50
50
  .replace(/(^|\n)\s*(?:```(?:xml)?\s*)?(?:xml\s*)?<tool_call>[\s\S]*?<\/tool_call>\s*(?:```)?/gi, '$1')
51
51
  .replace(/(^|\n)\s*(?:```(?:xml)?\s*)?(?:xml\s*)?<tool_call>[\s\S]*$/i, '$1');
52
52
  }
53
+ function isWordChar(char) {
54
+ return char.toLowerCase() !== char.toUpperCase() || (char >= '0' && char <= '9');
55
+ }
56
+ function wordCount(text) {
57
+ let count = 0;
58
+ let inWord = false;
59
+ for (const char of text) {
60
+ if (isWordChar(char)) {
61
+ if (!inWord)
62
+ count += 1;
63
+ inWord = true;
64
+ }
65
+ else {
66
+ inWord = false;
67
+ }
68
+ }
69
+ return count;
70
+ }
71
+ function endsWithSentenceBoundary(text) {
72
+ const trimmed = text.trim();
73
+ if (!trimmed || wordCount(trimmed) === 0)
74
+ return false;
75
+ const last = trimmed.at(-1) ?? '';
76
+ return last === '.' || last === '!' || last === '?' || last === ':' || last === ';' || last === ')';
77
+ }
53
78
  function isNonSubstantiveAssistantText(text) {
54
- return /^[`\s]*$/.test(text);
79
+ return wordCount(text) === 0;
80
+ }
81
+ function isSubstantiveAssistantText(text) {
82
+ const trimmed = text.trim();
83
+ const words = wordCount(trimmed);
84
+ if (words === 0)
85
+ return false;
86
+ if (trimmed.length >= 24)
87
+ return true;
88
+ if (endsWithSentenceBoundary(trimmed))
89
+ return true;
90
+ return words >= 4;
91
+ }
92
+ function isIncompleteAssistantFragment(text) {
93
+ const trimmed = text.trim();
94
+ return !isSubstantiveAssistantText(trimmed) && wordCount(trimmed) <= 2 && !endsWithSentenceBoundary(trimmed);
95
+ }
96
+ function isLikelyUnfinishedMarkdownFragment(text) {
97
+ const trimmed = text.trim();
98
+ if (!trimmed.includes('\n'))
99
+ return false;
100
+ const last = trimmed.at(-1) ?? '';
101
+ return last === '-' || last === '*' || last === '#' || last === '`' || last === '>';
102
+ }
103
+ function isHiddenAssistantText(text) {
104
+ return text.length === 0 || isNonSubstantiveAssistantText(text);
105
+ }
106
+ function isHiddenAssistantFragment(text) {
107
+ return isHiddenAssistantText(text) || isIncompleteAssistantFragment(text) || isLikelyUnfinishedMarkdownFragment(text);
108
+ }
109
+ export function isHiddenUnstartedFinalText(text) {
110
+ return isHiddenAssistantText(text) || isLikelyUnfinishedMarkdownFragment(text);
111
+ }
112
+ const ASSISTANT_STREAM_DEBOUNCE_MS = 200;
113
+ export function shouldStartAssistantStream(text, startedAt) {
114
+ if (isHiddenAssistantFragment(text))
115
+ return false;
116
+ return isSubstantiveAssistantText(text) || Date.now() - startedAt >= ASSISTANT_STREAM_DEBOUNCE_MS;
55
117
  }
56
118
  function assistantDisplayText(text) {
57
119
  return hideSyntheticToolCallMarkup(text).trim();
@@ -87,11 +149,16 @@ async function abortableDelay(milliseconds, signal) {
87
149
  }
88
150
  const DEFAULT_MAX_OUTPUT_TOKENS = 16384;
89
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.
90
157
  const MAIN_STEP_LIMIT = 64;
91
- const MAIN_TOOL_CALL_LIMIT = 40;
158
+ const MAIN_TOOL_CALL_LIMIT = 120;
92
159
  const MAIN_TOOL_ONLY_STEP_LIMIT = 24;
93
160
  const FOLLOW_UP_STEP_LIMIT = 64;
94
- const FOLLOW_UP_TOOL_CALL_LIMIT = 40;
161
+ const FOLLOW_UP_TOOL_CALL_LIMIT = 120;
95
162
  const FOLLOW_UP_TOOL_ONLY_STEP_LIMIT = 24;
96
163
  const COMPLETION_CONTINUATION_LIMIT = 12;
97
164
  const ACTIVE_CONTEXT_TOKEN_BUDGET = 40_000;
@@ -114,6 +181,15 @@ function logEntry(log, entry) {
114
181
  if (log)
115
182
  void logAppend(log, entry).catch(() => undefined);
116
183
  }
184
+ function responseCompletionMetrics(text, generationStartedAt) {
185
+ const finishedAt = Date.now();
186
+ const elapsedSeconds = Math.max((finishedAt - generationStartedAt) / 1000, 0.001);
187
+ const outputTokens = estimateValueTokens(text);
188
+ return {
189
+ finishedAt,
190
+ tokensPerSecond: outputTokens > 0 ? outputTokens / elapsedSeconds : undefined,
191
+ };
192
+ }
117
193
  function subagentTokenEstimate(output) {
118
194
  if (typeof output !== 'object' || output == null || !('tokens' in output))
119
195
  return undefined;
@@ -149,6 +225,7 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
149
225
  let turnStopReason;
150
226
  let idleTimer;
151
227
  let stopActiveTimers = () => undefined;
228
+ let finalizeToolGroup = () => undefined;
152
229
  const resetIdleTimer = () => {
153
230
  if (idleTimer)
154
231
  clearTimeout(idleTimer);
@@ -159,14 +236,29 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
159
236
  };
160
237
  try {
161
238
  const runtime = await modelWithConfig(session ? { cwd: session.cwd } : undefined);
162
- if (!runtime.model) {
239
+ if (!runtime?.model) {
163
240
  callbacks.addMessage({ role: 'assistant', text: 'No model provider configured. Run /provider to choose or add a provider. Haze cannot hallucinate without a model. Progress.' });
164
241
  return;
165
242
  }
166
243
  const activeModel = runtime.model;
167
244
  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
+ };
168
260
  const skillRegistry = await loadSkillRegistry();
169
- const subagentTool = createSubagentTool({ model: activeModel, contextFiles, session });
261
+ const subagentTool = createSubagentTool({ model: activeModel, contextFiles: activeContextFiles, session });
170
262
  const availableTools = { ...hazeTools, subagent: subagentTool, ...buildSkillTools(skillRegistry) };
171
263
  const goal = createSessionGoal(value);
172
264
  callbacks.setWorkState?.(goal.workState);
@@ -207,6 +299,7 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
207
299
  const recentStepTextSignatures = [];
208
300
  let consecutiveTextOnlySteps = 0;
209
301
  let repetitionAbortFired = false;
302
+ const warnedRepeatedToolSignatures = new Set();
210
303
  const toolCallSignatureCounts = new Map();
211
304
  const TOOL_REPETITION_THRESHOLD = 3;
212
305
  let latestAccumulatedResponseMessages = [];
@@ -233,12 +326,11 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
233
326
  const normalized = normalizeAssistantText(text);
234
327
  return normalized.length > 0 && [...visibleAssistantTexts].some(previous => previous.startsWith(normalized) && previous !== normalized);
235
328
  };
236
- const toolExecutionContext = { inFlightToolCalls: new Map() };
237
- let toolGroupId = `tools-${Date.now()}-${Math.random().toString(36).slice(2)}`;
329
+ const toolExecutionContext = { inFlightToolCalls: new Map(), loadedContextFilePaths: new Set(activeContextFiles.map(file => file.path)) };
238
330
  const INLINE_DIFF_LINE_LIMIT = 20;
239
- const toolDisplayItems = [];
240
- let toolGroupStarted = false;
241
- let toolGroupFinalized = false;
331
+ const createToolDisplayGroup = () => ({ id: `tools-${Date.now()}-${Math.random().toString(36).slice(2)}`, items: [], started: false });
332
+ let activeToolGroup = createToolDisplayGroup();
333
+ let assistantSinceActiveToolGroup = false;
242
334
  let toolTimer;
243
335
  function stopToolTimer() {
244
336
  if (!toolTimer)
@@ -250,45 +342,32 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
250
342
  if (toolTimer)
251
343
  return;
252
344
  toolTimer = setInterval(() => {
253
- if (toolDisplayItems.some(item => item.status === 'running'))
254
- updateToolGroup(true);
345
+ if (activeToolGroup.items.some(item => item.status === 'running'))
346
+ updateToolGroup(activeToolGroup, true);
255
347
  else
256
348
  stopToolTimer();
257
349
  }, 1000);
258
350
  }
259
351
  stopActiveTimers = stopToolTimer;
260
- function renderToolGroup(streaming) {
261
- const visibleItems = toolDisplayItems.filter(item => !item.hidden);
262
- const running = visibleItems.some(item => item.status === 'running');
263
- const failures = visibleItems.filter(item => item.status === 'error');
264
- const changes = visibleItems.filter(item => /^(editFile|replaceLines|writeFile)\b/.test(item.summary));
265
- const compactItems = !running && visibleItems.length > 12
266
- ? [...new Map([...failures, ...changes].map(item => [item.id, item])).values()]
267
- : visibleItems;
268
- const grouped = new Map();
269
- for (const item of compactItems) {
270
- const key = `${item.status}:${item.summary}:${item.result ?? ''}`;
271
- const current = grouped.get(key);
272
- if (current)
273
- current.count += 1;
274
- else
275
- grouped.set(key, { item, count: 1 });
276
- }
277
- const rows = [...grouped.values()];
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))
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))
281
358
  : 0;
282
- const elapsed = running || streaming ? formatElapsedTimeWhole(elapsedMs) : formatElapsedTime(elapsedMs);
283
- const header = running || streaming
284
- ? `Running tools · ${elapsed}`
285
- : `${visibleItems.length} call${visibleItems.length === 1 ? '' : 's'} · ${changes.length} change${changes.length === 1 ? '' : 's'} · ${failures.length} failed · ${elapsed}${compactSuffix}`;
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;
286
366
  const lines = [];
287
- for (const { item, count } of rows) {
367
+ for (const item of group.items) {
288
368
  const icon = item.status === 'running' ? '…' : item.status === 'success' ? '✓' : '✗';
289
- const countText = count > 1 ? ` ×${count}` : '';
290
369
  const result = item.status === 'running' ? '' : ` — ${item.result ?? item.status}${item.durationMs == null ? '' : ` in ${formatSeconds(item.durationMs)}`}`;
291
- lines.push(` ${icon} ${item.summary}${countText}${result}`);
370
+ lines.push(` ${icon} ${item.summary}${result}`);
292
371
  if (item.diff && item.diff.length > 0 && (item.diffLineCount ?? item.diff.length) <= INLINE_DIFF_LINE_LIMIT) {
293
372
  for (const diffLine of item.diff) {
294
373
  const lineNumber = diffLine.type === 'add' ? diffLine.newLine : diffLine.oldLine;
@@ -308,45 +387,67 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
308
387
  }
309
388
  return [header, ...lines].join('\n');
310
389
  }
311
- function updateToolGroup(streaming = true) {
312
- const text = renderToolGroup(streaming);
313
- if (!toolGroupStarted) {
314
- toolGroupStarted = true;
315
- callbacks.addMessage({ id: toolGroupId, role: 'tool', text, streaming });
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 });
316
395
  }
317
396
  else {
318
- callbacks.updateMessage(toolGroupId, { text, streaming });
397
+ callbacks.updateMessage(group.id, { text, streaming });
319
398
  }
320
- if (!streaming)
321
- toolGroupFinalized = true;
322
399
  }
323
- function recordToolStart(toolCall) {
324
- if (toolGroupFinalized) {
325
- toolDisplayItems.length = 0;
326
- toolGroupId = `tools-${Date.now()}-${Math.random().toString(36).slice(2)}`;
327
- toolGroupFinalized = false;
328
- toolGroupStarted = false;
400
+ finalizeToolGroup = () => {
401
+ if (activeToolGroup.started)
402
+ updateToolGroup(activeToolGroup, false);
403
+ };
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;
329
419
  }
330
- callbacks.onEvent?.(agentEvent({ type: 'tool_start', id: toolCall.toolCallId, name: toolCall.toolName, input: toolCall.input }));
331
- toolDisplayItems.push({ id: toolCall.toolCallId, summary: toolCallSummary(toolCall.toolName, toolCall.input), status: 'running', startedAt: Date.now() });
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);
332
429
  startToolTimer();
333
- updateToolGroup(true);
334
- const runningSubagents = toolDisplayItems.filter(item => item.status === 'running' && item.summary.startsWith('subagent')).length;
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;
335
437
  if (runningSubagents > 0)
336
438
  callbacks.setBusyLabel?.(`Running ${runningSubagents} subagent${runningSubagents === 1 ? '' : 's'}`);
337
439
  }
338
440
  function recordToolDisplayFinish(event) {
339
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 }));
340
- const item = toolDisplayItems.find(candidate => candidate.id === event.toolCall.toolCallId);
341
- if (!item)
342
- return;
442
+ const item = ensureToolDisplayItem(event.toolCall);
443
+ item.startedAt = Math.min(item.startedAt, Date.now() - event.durationMs);
343
444
  item.status = toolOutputOk(event.output, event.success) ? 'success' : 'error';
344
445
  item.result = toolResultSummary(event);
345
446
  item.durationMs = event.durationMs;
346
447
  item.finishedAt = item.startedAt + event.durationMs;
347
- item.hidden = isDuplicateSkippedOutput(event.output);
348
448
  if (typeof event.output === 'object' && event.output != null) {
349
449
  const output = event.output;
450
+ rememberContextFiles(output.applicableProjectInstructions);
350
451
  if (typeof output.diffLineCount === 'number')
351
452
  item.diffLineCount = output.diffLineCount;
352
453
  if (Array.isArray(output.diff))
@@ -365,11 +466,11 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
365
466
  if (event.toolCall.toolName === 'writeTasks' && event.success) {
366
467
  callbacks.onTasksChanged?.();
367
468
  }
368
- const hasRunningTools = toolDisplayItems.some(candidate => candidate.status === 'running');
369
- updateToolGroup(hasRunningTools);
469
+ const hasRunningTools = activeToolGroup.items.some(candidate => candidate.status === 'running');
470
+ updateToolGroup(activeToolGroup, !assistantSinceActiveToolGroup);
370
471
  if (!hasRunningTools)
371
472
  stopToolTimer();
372
- const runningSubagents = toolDisplayItems.filter(i => i.status === 'running' && i.summary.startsWith('subagent')).length;
473
+ const runningSubagents = activeToolGroup.items.filter(i => i.status === 'running' && i.summary.startsWith('subagent')).length;
373
474
  if (runningSubagents === 0)
374
475
  callbacks.setBusyLabel?.('Haze is thinking');
375
476
  else
@@ -413,8 +514,8 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
413
514
  async function streamAssistantResponse(messages, reason, prompt, allowTools = false) {
414
515
  callbacks.debugLog(`requesting assistant ${allowTools ? 'continuation' : 'text'}: ${reason}`);
415
516
  const responseId = `assistant-${Date.now()}-${Math.random().toString(36).slice(2)}`;
416
- const responseStarted = true;
417
- const responseStartedAt = Date.now();
517
+ let responseStarted = false;
518
+ let responseStartedAt = Date.now();
418
519
  let responseText = '';
419
520
  let continuationToolCalls = 0;
420
521
  let followUpStreamError;
@@ -423,9 +524,9 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
423
524
  ? compactModelMessages(prunedMessages, { tokenBudget: ACTIVE_CONTEXT_TOKEN_BUDGET, workState: goal.workState }).messages
424
525
  : prunedMessages;
425
526
  const continuationMessages = withSyntheticControl(compactedMessages, `${prompt}\n\n${workStatePrompt(goal.workState)}`);
426
- const followUpSystemPrompt = buildSystemPrompt(contextFiles, session);
527
+ const followUpSystemPrompt = buildSystemPrompt(activeContextFiles, session);
427
528
  const followUpTools = allowTools ? availableTools : undefined;
428
- const followUpInputBreakdown = estimateInputBreakdown({ system: followUpSystemPrompt, contextFiles, messages: continuationMessages, tools: followUpTools });
529
+ const followUpInputBreakdown = estimateInputBreakdown({ system: followUpSystemPrompt, contextFiles: activeContextFiles, messages: continuationMessages, tools: followUpTools });
429
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 });
430
531
  const followUp = streamText({
431
532
  model: activeModel,
@@ -438,13 +539,22 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
438
539
  abortSignal: abortController.signal,
439
540
  experimental_context: toolExecutionContext,
440
541
  prepareStep({ steps, messages }) {
441
- continuationToolCalls = steps.flatMap(step => step.toolCalls).length;
542
+ const toolCalls = steps.flatMap(step => step.toolCalls);
543
+ continuationToolCalls = toolCalls.length;
544
+ const repeatedToolNames = uniqueRepeatedToolNames(toolCalls);
442
545
  if (continuationToolCalls >= FOLLOW_UP_TOOL_CALL_LIMIT || toolOnlyStepCount(steps) >= FOLLOW_UP_TOOL_ONLY_STEP_LIMIT) {
443
546
  return {
444
547
  toolChoice: 'none',
445
548
  messages: withSyntheticControl(messages, toolLoopBudgetPrompt()),
446
549
  };
447
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
+ }
448
558
  if (likelyPlanOnlyRequest && mutatingToolSucceeded) {
449
559
  return {
450
560
  toolChoice: 'none',
@@ -490,13 +600,11 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
490
600
  const sig = stableToolKey(toolCall);
491
601
  const count = (toolCallSignatureCounts.get(sig) ?? 0) + 1;
492
602
  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.` };
603
+ if (count >= TOOL_REPETITION_THRESHOLD && !warnedRepeatedToolSignatures.has(sig)) {
604
+ warnedRepeatedToolSignatures.add(sig);
496
605
  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.`);
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}`);
500
608
  }
501
609
  },
502
610
  experimental_onToolCallFinish(event) {
@@ -516,17 +624,24 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
516
624
  : `follow-up tool error: ${event.toolCall.toolName} after ${event.durationMs}ms ${compact(event.error)}`);
517
625
  },
518
626
  });
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 });
521
627
  for await (const rawDelta of followUp.textStream) {
522
628
  resetIdleTimer();
523
629
  const delta = sanitizeAssistantText(rawDelta);
524
630
  responseText += delta;
525
631
  const displayText = assistantDisplayText(responseText);
526
- if (!displayText || isNonSubstantiveAssistantText(displayText) || isPrefixOfVisibleAssistantText(displayText))
632
+ if ((!shouldStartAssistantStream(displayText, responseStartedAt) || isPrefixOfVisibleAssistantText(displayText)) && !responseStarted)
527
633
  continue;
528
- callbacks.onEvent?.(agentEvent({ type: 'message_update', id: responseId, text: displayText }));
529
- callbacks.updateMessage(responseId, { text: displayText });
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
+ }
530
645
  }
531
646
  try {
532
647
  await followUp.response;
@@ -536,19 +651,25 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
536
651
  }
537
652
  const finalText = assistantDisplayText(responseText);
538
653
  const visibleFinalText = finalText;
539
- const hidden = visibleFinalText.length === 0 || isNonSubstantiveAssistantText(visibleFinalText) || isDuplicateVisibleAssistantText(visibleFinalText);
654
+ const hidden = (responseStarted ? isHiddenAssistantFragment(visibleFinalText) : isHiddenUnstartedFinalText(visibleFinalText)) || isDuplicateVisibleAssistantText(visibleFinalText);
540
655
  if (responseStarted) {
541
656
  if (!hidden)
542
657
  rememberVisibleAssistantText(visibleFinalText);
543
658
  callbacks.onEvent?.(agentEvent({ type: 'message_end', id: responseId, text: visibleFinalText, hidden }));
544
- callbacks.updateMessage(responseId, { text: visibleFinalText, streaming: false, hidden, finishedAt: Date.now() });
659
+ callbacks.updateMessage(responseId, { text: visibleFinalText, streaming: false, hidden, ...responseCompletionMetrics(visibleFinalText, responseStartedAt) });
660
+ }
661
+ 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) });
545
666
  }
546
667
  return { text: finalText, id: responseId, started: responseStarted };
547
668
  }
548
669
  let streamError;
549
670
  let lastFinishReason;
550
- const mainSystemPrompt = buildSystemPrompt(contextFiles, session);
551
- const mainInputBreakdown = estimateInputBreakdown({ system: mainSystemPrompt, contextFiles, messages: requestMessages, tools: availableTools });
671
+ const mainSystemPrompt = buildSystemPrompt(activeContextFiles, session);
672
+ const mainInputBreakdown = estimateInputBreakdown({ system: mainSystemPrompt, contextFiles: activeContextFiles, messages: requestMessages, tools: availableTools });
552
673
  logEntry(callbacks.log, { at: new Date().toISOString(), type: 'request', stream: 'main', system: mainSystemPrompt, messages: requestMessages, tools: Object.keys(availableTools), context: mainInputBreakdown.breakdown });
553
674
  const result = streamText({
554
675
  model: activeModel,
@@ -582,9 +703,9 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
582
703
  if (repeatedToolCall) {
583
704
  const activeTools = Object.keys(availableTools).filter(name => !repeatedToolNames.includes(name));
584
705
  callbacks.debugLog(`disabling repeated tools for next step: ${repeatedToolNames.join(', ')}`);
585
- return {
586
- activeTools,
587
- };
706
+ return activeTools.length > 0
707
+ ? { activeTools, messages: withSyntheticControl(messages, repeatedToolCallPrompt(repeatedToolNames)) }
708
+ : { toolChoice: 'none', messages: withSyntheticControl(messages, repeatedToolCallPrompt(repeatedToolNames)) };
588
709
  }
589
710
  if (toolCalls.length >= MAIN_TOOL_CALL_LIMIT || consecutiveToolOnlySteps >= MAIN_TOOL_ONLY_STEP_LIMIT) {
590
711
  callbacks.debugLog('forcing text response to avoid tool loop');
@@ -599,6 +720,8 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
599
720
  return undefined;
600
721
  },
601
722
  onStepFinish({ stepNumber, text, toolCalls, toolResults, finishReason, usage, response }) {
723
+ for (const toolCall of toolCalls)
724
+ ensureToolDisplayItem(toolCall);
602
725
  if (Array.isArray(response?.messages) && response.messages.length > 0) {
603
726
  latestAccumulatedResponseMessages = response.messages;
604
727
  }
@@ -684,18 +807,16 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
684
807
  logEntry(callbacks.log, { at: new Date().toISOString(), type: 'tool_call', stream: 'main', toolCall: { id: toolCall.toolCallId, name: toolCall.toolName, input: toolCall.input } });
685
808
  callbacks.debugLog(`tool start: ${toolCall.toolName} ${compact(toolCall.input)}`);
686
809
  // 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.
810
+ // TOOL_REPETITION_THRESHOLD times this turn, log once. prepareStep then
811
+ // disables that repeated tool and injects a model-facing correction.
689
812
  const sig = stableToolKey(toolCall);
690
813
  const count = (toolCallSignatureCounts.get(sig) ?? 0) + 1;
691
814
  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.` };
815
+ if (count >= TOOL_REPETITION_THRESHOLD && !warnedRepeatedToolSignatures.has(sig)) {
816
+ warnedRepeatedToolSignatures.add(sig);
695
817
  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.`);
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}`);
699
820
  }
700
821
  },
701
822
  experimental_onToolCallFinish(event) {
@@ -715,10 +836,6 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
715
836
  : `tool error: ${event.toolCall.toolName} after ${event.durationMs}ms ${compact(event.error)}`);
716
837
  }
717
838
  });
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;
722
839
  for await (const rawDelta of result.textStream) {
723
840
  resetIdleTimer();
724
841
  const delta = sanitizeAssistantText(rawDelta);
@@ -726,9 +843,11 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
726
843
  textAfterTool = true;
727
844
  if (currentAssistantStarted && currentAssistantText.length > 0 && toolEpoch > currentAssistantToolEpoch) {
728
845
  const intermediateText = assistantDisplayText(currentAssistantText);
729
- const hidden = true;
846
+ const hidden = isHiddenAssistantFragment(intermediateText) || isDuplicateVisibleAssistantText(intermediateText);
847
+ if (!hidden)
848
+ rememberVisibleAssistantText(intermediateText);
730
849
  callbacks.onEvent?.(agentEvent({ type: 'message_end', id: currentAssistantId, text: intermediateText, hidden }));
731
- callbacks.updateMessage(currentAssistantId, { text: intermediateText, streaming: false, hidden, finishedAt: Date.now() });
850
+ callbacks.updateMessage(currentAssistantId, { text: intermediateText, streaming: false, hidden, ...responseCompletionMetrics(intermediateText, currentAssistantStartedAt) });
732
851
  currentAssistantId = `assistant-${Date.now()}-${Math.random().toString(36).slice(2)}`;
733
852
  currentAssistantStarted = false;
734
853
  currentAssistantStartedAt = Date.now();
@@ -738,14 +857,15 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
738
857
  assistantText += delta;
739
858
  currentAssistantText += delta;
740
859
  const displayText = assistantDisplayText(currentAssistantText);
741
- if ((!displayText || isNonSubstantiveAssistantText(displayText) || isPrefixOfVisibleAssistantText(displayText)) && !currentAssistantStarted)
860
+ if ((!shouldStartAssistantStream(displayText, currentAssistantStartedAt) || isPrefixOfVisibleAssistantText(displayText)) && !currentAssistantStarted)
742
861
  continue;
743
862
  if (!currentAssistantStarted) {
744
863
  assistantStarted = true;
745
864
  currentAssistantStarted = true;
746
865
  callbacks.onEvent?.(agentEvent({ type: 'message_start', id: currentAssistantId, role: 'assistant' }));
747
866
  currentAssistantStartedAt = Date.now();
748
- callbacks.addMessage({ id: currentAssistantId, role: 'assistant', text: displayText, streaming: true, startedAt: currentAssistantStartedAt });
867
+ const displayedStartedAt = closeToolGroupBeforeAssistantMessage() ?? currentAssistantStartedAt;
868
+ callbacks.addMessage({ id: currentAssistantId, role: 'assistant', text: displayText, streaming: true, startedAt: displayedStartedAt });
749
869
  }
750
870
  else {
751
871
  callbacks.onEvent?.(agentEvent({ type: 'message_update', id: currentAssistantId, text: displayText }));
@@ -828,14 +948,23 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
828
948
  callbacks.addMessage({ role: 'assistant', text: `Finished tool work but the model did not produce a final response. Last tool result: ${toolSummaries.at(-1)}.` });
829
949
  }
830
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
+ }
831
961
  if (assistantStarted) {
832
- const hidePreToolFragment = sawToolCall && !textAfterTool;
833
962
  const visibleFinalAssistantText = assistantDisplayText(currentAssistantText);
834
- const hidden = visibleFinalAssistantText.length === 0 || isNonSubstantiveAssistantText(visibleFinalAssistantText) || isDuplicateVisibleAssistantText(visibleFinalAssistantText) || hidePreToolFragment;
963
+ const hidden = isHiddenAssistantFragment(visibleFinalAssistantText) || isDuplicateVisibleAssistantText(visibleFinalAssistantText);
835
964
  if (!hidden)
836
965
  rememberVisibleAssistantText(visibleFinalAssistantText);
837
966
  callbacks.onEvent?.(agentEvent({ type: 'message_end', id: currentAssistantId, text: visibleFinalAssistantText, hidden }));
838
- callbacks.updateMessage(currentAssistantId, { text: visibleFinalAssistantText, streaming: false, hidden, finishedAt: Date.now() });
967
+ callbacks.updateMessage(currentAssistantId, { text: visibleFinalAssistantText, streaming: false, hidden, ...responseCompletionMetrics(visibleFinalAssistantText, currentAssistantStartedAt) });
839
968
  if (decision.needsActionContinuation || decision.needsValidationContinuation) {
840
969
  await runCompletionLoop(completedConversation, combinedAssistantText);
841
970
  }
@@ -857,11 +986,12 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
857
986
  const fallback = toolSummaries.length > 0
858
987
  ? `Finished tool work but the model did not produce a final response. Last tool result: ${toolSummaries.at(-1)}.`
859
988
  : 'Finished without a text response.';
860
- callbacks.addMessage({ id: currentAssistantId, role: 'assistant', text: fallback, streaming: false, startedAt: currentAssistantStartedAt, finishedAt: Date.now() });
989
+ callbacks.addMessage({ id: currentAssistantId, role: 'assistant', text: fallback, streaming: false, startedAt: currentAssistantStartedAt, ...responseCompletionMetrics(fallback, currentAssistantStartedAt) });
861
990
  }
862
991
  }
863
992
  else {
864
- callbacks.addMessage({ id: currentAssistantId, role: 'assistant', text: 'Finished without a text response.', streaming: false, startedAt: currentAssistantStartedAt, finishedAt: Date.now() });
993
+ const fallback = 'Finished without a text response.';
994
+ callbacks.addMessage({ id: currentAssistantId, role: 'assistant', text: fallback, streaming: false, startedAt: currentAssistantStartedAt, ...responseCompletionMetrics(fallback, currentAssistantStartedAt) });
865
995
  }
866
996
  goal.phase = 'done';
867
997
  goal.status = 'complete';
@@ -907,6 +1037,7 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
907
1037
  finally {
908
1038
  if (idleTimer)
909
1039
  clearTimeout(idleTimer);
1040
+ finalizeToolGroup();
910
1041
  stopActiveTimers();
911
1042
  callbacks.onEvent?.(agentEvent({ type: 'turn_end', request: value, status: turnStatus }));
912
1043
  callbacks.setAbortController?.(null);
@@ -22,7 +22,13 @@ export interface ContextFileDiagnosticsSummary {
22
22
  exceedsBudget: boolean | undefined;
23
23
  budgetThreshold: number;
24
24
  }
25
+ /** Maximum characters of a context file included in every request's system context. */
26
+ export declare const MAX_CONTEXT_FILE_CHARS = 20000;
25
27
  export declare function readContextFiles(cwd?: string): Promise<ContextFile[]>;
28
+ export declare function readScopedContextFilesForPath(targetPath: string, options?: {
29
+ cwd?: string;
30
+ alreadyLoadedPaths?: Iterable<string>;
31
+ }): Promise<ContextFile[]>;
26
32
  export declare function contextFileDiagnostics(files: ContextFile[]): ContextFileDiagnostic[];
27
33
  export declare function summarizeContextDiagnostics(files: ContextFile[], options?: {
28
34
  windowSize?: number;