@denizokcu/haze 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/CHANGELOG.md +34 -0
  2. package/README.md +31 -19
  3. package/dist/cli/commands/chat.d.ts +1 -1
  4. package/dist/cli/commands/chat.js +144 -52
  5. package/dist/cli/commands/commands.js +105 -114
  6. package/dist/cli/commands/streaming.d.ts +33 -5
  7. package/dist/cli/commands/streaming.js +235 -103
  8. package/dist/cli/contextReport.d.ts +1 -0
  9. package/dist/cli/contextReport.js +47 -0
  10. package/dist/config/contextFiles.d.ts +25 -0
  11. package/dist/config/contextFiles.js +53 -0
  12. package/dist/core/agent/compaction.d.ts +3 -0
  13. package/dist/core/agent/compaction.js +23 -3
  14. package/dist/core/agent/contextBudget.d.ts +33 -0
  15. package/dist/core/agent/contextBudget.js +88 -0
  16. package/dist/core/agent/requestAssembly.d.ts +22 -0
  17. package/dist/core/agent/requestAssembly.js +146 -0
  18. package/dist/core/agent/toolOutputStore.d.ts +11 -0
  19. package/dist/core/agent/toolOutputStore.js +33 -0
  20. package/dist/core/agent/workState.d.ts +38 -0
  21. package/dist/core/agent/workState.js +89 -0
  22. package/dist/core/goal/completionPolicy.js +1 -1
  23. package/dist/core/goal/sessionGoal.d.ts +2 -0
  24. package/dist/core/goal/sessionGoal.js +8 -1
  25. package/dist/core/log/llmLog.d.ts +68 -0
  26. package/dist/core/log/llmLog.js +55 -0
  27. package/dist/core/session/sessionStore.d.ts +6 -0
  28. package/dist/core/session/sessionStore.js +5 -0
  29. package/dist/core/subagent/subagentRunner.d.ts +4 -1
  30. package/dist/core/subagent/subagentRunner.js +5 -15
  31. package/dist/core/validation/outputParser.js +15 -2
  32. package/dist/llm/client.d.ts +39 -0
  33. package/dist/llm/client.js +46 -2
  34. package/dist/llm/hazeTools.d.ts +37 -12
  35. package/dist/llm/hazeTools.js +133 -55
  36. package/dist/llm/systemPrompt.d.ts +6 -1
  37. package/dist/llm/systemPrompt.js +42 -81
  38. package/dist/skills/builder/SkillBuilder.d.ts +16 -2
  39. package/dist/skills/builder/SkillBuilder.js +68 -65
  40. package/dist/skills/skillTools.d.ts +2 -19
  41. package/dist/skills/skillTools.js +28 -19
  42. package/package.json +2 -1
@@ -1,5 +1,6 @@
1
1
  import { stepCountIs, streamText } from 'ai';
2
- import { model } from '../../llm/client.js';
2
+ import { appendLogEntry as logAppend } from '../../core/log/llmLog.js';
3
+ import { modelWithConfig, providerRequestSettings } from '../../llm/client.js';
3
4
  import { hazeTools } from '../../llm/hazeTools.js';
4
5
  import { buildSystemPrompt } from '../../llm/systemPrompt.js';
5
6
  import { loadSkillRegistry } from '../../skills/SkillRegistry.js';
@@ -11,6 +12,10 @@ import { createSessionGoal, formatGoalStatus, observeGoalToolEvent } from '../..
11
12
  import { agentEvent } from '../../core/agent/events.js';
12
13
  import { isContextOverflowError, isRetryableModelError } from '../../core/agent/errors.js';
13
14
  import { createSubagentTool } from '../../core/subagent/subagentRunner.js';
15
+ import { contextBreakdown, cacheHitRatio, effectiveNonCachedInput, estimateValueTokens } from '../../core/agent/contextBudget.js';
16
+ import { compactToolHistory, stripSyntheticControls, toolRequestSettings, withSyntheticControl } from '../../core/agent/requestAssembly.js';
17
+ import { compactModelMessages } from '../../core/agent/compaction.js';
18
+ import { workStatePrompt } from '../../core/agent/workState.js';
14
19
  function stableToolKey(toolCall) {
15
20
  return `${toolCall.toolName}:${JSON.stringify(toolCall.input)}`;
16
21
  }
@@ -82,33 +87,32 @@ async function abortableDelay(milliseconds, signal) {
82
87
  }
83
88
  const DEFAULT_MAX_OUTPUT_TOKENS = 16384;
84
89
  const IDLE_TIMEOUT_MS = 5 * 60_000;
85
- const MAIN_STEP_LIMIT = 40;
90
+ const MAIN_STEP_LIMIT = 64;
86
91
  const MAIN_TOOL_CALL_LIMIT = 40;
87
- const MAIN_TOOL_ONLY_STEP_LIMIT = 12;
88
- const FOLLOW_UP_STEP_LIMIT = 30;
89
- const FOLLOW_UP_TOOL_CALL_LIMIT = 30;
90
- const FOLLOW_UP_TOOL_ONLY_STEP_LIMIT = 10;
91
- const COMPLETION_CONTINUATION_LIMIT = 30;
92
+ const MAIN_TOOL_ONLY_STEP_LIMIT = 24;
93
+ const FOLLOW_UP_STEP_LIMIT = 64;
94
+ const FOLLOW_UP_TOOL_CALL_LIMIT = 40;
95
+ const FOLLOW_UP_TOOL_ONLY_STEP_LIMIT = 24;
96
+ const COMPLETION_CONTINUATION_LIMIT = 12;
97
+ const ACTIVE_CONTEXT_TOKEN_BUDGET = 40_000;
92
98
  function toolOutputOk(output, success) {
93
99
  if (!success)
94
100
  return false;
95
101
  return !(typeof output === 'object' && output != null && 'ok' in output && output.ok === false);
96
102
  }
97
- function estimateTokens(text) {
98
- return Math.ceil(text.length / 4);
99
- }
100
- function estimateModelMessageTokens(messages) {
101
- return estimateTokens(JSON.stringify(messages));
102
- }
103
- function estimateToolSchemaTokens(tools) {
104
- const names = Object.keys(tools);
105
- return estimateTokens(names.join('\n')) + names.length * 250;
106
- }
107
- function estimateLlmInputTokens(input) {
108
- return estimateTokens(input.system) + estimateModelMessageTokens(input.messages) + (input.tools ? estimateToolSchemaTokens(input.tools) : 0);
103
+ function estimateInputBreakdown(input) {
104
+ const breakdown = contextBreakdown(input);
105
+ return {
106
+ breakdown,
107
+ systemPrompt: breakdown.system,
108
+ messages: Object.values(breakdown.messagesByRole).reduce((sum, value) => sum + value, 0),
109
+ toolSchemas: breakdown.toolSchemas.reduce((sum, value) => sum + value.tokens, 0),
110
+ logicalInputEstimate: breakdown.logicalInputEstimate,
111
+ };
109
112
  }
110
- function estimateLlmOutputTokens(messages) {
111
- return estimateModelMessageTokens(messages);
113
+ function logEntry(log, entry) {
114
+ if (log)
115
+ void logAppend(log, entry).catch(() => undefined);
112
116
  }
113
117
  function subagentTokenEstimate(output) {
114
118
  if (typeof output !== 'object' || output == null || !('tokens' in output))
@@ -118,15 +122,21 @@ function subagentTokenEstimate(output) {
118
122
  const outputTokens = typeof tokens?.out === 'number' ? tokens.out : 0;
119
123
  return input > 0 || outputTokens > 0 ? { input, output: outputTokens } : undefined;
120
124
  }
121
- function usageTokenEstimate(event, fallback) {
122
- const usage = typeof event === 'object' && event != null && 'usage' in event
123
- ? event.usage
125
+ function extractUsage(event) {
126
+ const cacheReadTokens = event.usage?.inputTokenDetails?.cacheReadTokens ?? 0;
127
+ const reportedNoCache = 'noCacheTokens' in (event.usage?.inputTokenDetails ?? {})
128
+ ? (event.usage?.inputTokenDetails).noCacheTokens
124
129
  : undefined;
125
- const input = typeof usage?.inputTokens === 'number' ? usage.inputTokens : fallback.input;
126
- const output = typeof usage?.outputTokens === 'number' ? usage.outputTokens : fallback.output;
127
- return { input, output };
130
+ return {
131
+ inputTokens: event.usage?.inputTokens,
132
+ outputTokens: event.usage?.outputTokens,
133
+ cacheReadTokens,
134
+ cacheWriteTokens: event.usage?.inputTokenDetails?.cacheWriteTokens ?? 0,
135
+ noCacheTokens: reportedNoCache ?? effectiveNonCachedInput(event.usage?.inputTokens, cacheReadTokens) ?? 0,
136
+ reasoningTokens: event.usage?.outputTokenDetails?.reasoningTokens ?? 0,
137
+ };
128
138
  }
129
- export async function runAgentTurn(value, displayValue, contextFiles, callbacks, retryAttempt = 0, retryingExistingRequest = false, contextOverflowRecovered = false) {
139
+ export async function runAgentTurn(value, displayValue, contextFiles, callbacks, retryAttempt = 0, retryingExistingRequest = false, contextOverflowRecovered = false, session) {
130
140
  const displayVal = displayValue ?? value;
131
141
  const userMessage = { role: 'user', text: displayVal };
132
142
  callbacks.onEvent?.(agentEvent({ type: 'turn_start', request: value }));
@@ -136,36 +146,46 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
136
146
  const abortController = new AbortController();
137
147
  callbacks.setAbortController?.(abortController);
138
148
  let turnStatus = 'failed';
149
+ let turnStopReason;
139
150
  let idleTimer;
140
151
  let stopActiveTimers = () => undefined;
141
152
  const resetIdleTimer = () => {
142
153
  if (idleTimer)
143
154
  clearTimeout(idleTimer);
144
- idleTimer = setTimeout(() => abortController.abort('Haze turn timed out after no model/tool activity.'), IDLE_TIMEOUT_MS);
155
+ idleTimer = setTimeout(() => {
156
+ turnStopReason = { kind: 'idle_timeout', message: `Stopped after ${Math.round(IDLE_TIMEOUT_MS / 60_000)} minutes of no activity. Type "continue" to resume — Haze will pick up where it left off.` };
157
+ abortController.abort('Haze turn timed out after no model/tool activity.');
158
+ }, IDLE_TIMEOUT_MS);
145
159
  };
146
160
  try {
147
- const m = await model();
148
- if (!m) {
161
+ const runtime = await modelWithConfig(session ? { cwd: session.cwd } : undefined);
162
+ if (!runtime.model) {
149
163
  callbacks.addMessage({ role: 'assistant', text: 'No model provider configured. Run /provider to choose or add a provider. Haze cannot hallucinate without a model. Progress.' });
150
164
  return;
151
165
  }
152
- const activeModel = m;
166
+ const activeModel = runtime.model;
167
+ const providerSettings = providerRequestSettings(runtime.config);
153
168
  const skillRegistry = await loadSkillRegistry();
154
- const subagentTool = createSubagentTool({ model: activeModel, contextFiles });
169
+ const subagentTool = createSubagentTool({ model: activeModel, contextFiles, session });
155
170
  const availableTools = { ...hazeTools, subagent: subagentTool, ...buildSkillTools(skillRegistry) };
156
171
  const goal = createSessionGoal(value);
172
+ callbacks.setWorkState?.(goal.workState);
157
173
  callbacks.setGoalStatus?.(formatGoalStatus(goal));
158
174
  const likelyPlanOnlyRequest = isPlanOnlyRequest(value);
159
175
  const likelyPlanImplementationRequest = isPlanImplementationRequest(value);
160
176
  const likelyActionRequest = isActionRequest(value);
161
177
  const likelyValidationRequest = isValidationRequest(value);
162
178
  const planImplementationGuidance = 'Haze internal guidance for implementing plan files. The original user request remains authoritative. First identify the concrete required checklist items and compare them with the current files. Do not edit source or tests when the required behavior is already present. Implement the smallest clearly required phase or required items, skip optional/design-question items unless explicitly requested, add tests rather than exploratory one-off scripts where possible, prefer file tools for source changes, run validation once after code/test edits, then update plan status with file tools if requested. Do not call unresolved optional scope a blocker.';
163
- const requestMessages = retryingExistingRequest
164
- ? callbacks.getConversation()
165
- : likelyPlanImplementationRequest
166
- ? [...callbacks.getConversation(), { role: 'user', content: value }, { role: 'user', content: planImplementationGuidance }]
167
- : [...callbacks.getConversation(), { role: 'user', content: value }];
168
- callbacks.setConversation(requestMessages);
179
+ const durableRequestMessages = compactToolHistory(retryingExistingRequest
180
+ ? stripSyntheticControls(callbacks.getConversation())
181
+ : [...stripSyntheticControls(callbacks.getConversation()), { role: 'user', content: value }]).messages;
182
+ let requestMessages = likelyPlanImplementationRequest
183
+ ? withSyntheticControl(durableRequestMessages, planImplementationGuidance)
184
+ : durableRequestMessages;
185
+ if (estimateValueTokens(requestMessages) > ACTIVE_CONTEXT_TOKEN_BUDGET) {
186
+ requestMessages = compactModelMessages(requestMessages, { tokenBudget: ACTIVE_CONTEXT_TOKEN_BUDGET, workState: goal.workState }).messages;
187
+ }
188
+ callbacks.setConversation(stripSyntheticControls(requestMessages));
169
189
  resetIdleTimer();
170
190
  let currentAssistantId = `assistant-${Date.now()}`;
171
191
  let assistantStarted = false;
@@ -184,6 +204,12 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
184
204
  let textAfterTool = false;
185
205
  let completionContinuationCount = 0;
186
206
  const maxCompletionContinuations = COMPLETION_CONTINUATION_LIMIT;
207
+ const recentStepTextSignatures = [];
208
+ let consecutiveTextOnlySteps = 0;
209
+ let repetitionAbortFired = false;
210
+ const toolCallSignatureCounts = new Map();
211
+ const TOOL_REPETITION_THRESHOLD = 3;
212
+ let latestAccumulatedResponseMessages = [];
187
213
  let editRecoveryPath;
188
214
  let editRecoveryReasonCode;
189
215
  let editRecoveryReadSatisfied = false;
@@ -355,6 +381,7 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
355
381
  const duplicateSkipped = isDuplicateSkippedOutput(event.output);
356
382
  const ok = toolOutputOk(event.output, event.success);
357
383
  observeGoalToolEvent(goal, { ...event.toolCall, success: ok, output: event.output, duplicateSkipped });
384
+ callbacks.setWorkState?.(goal.workState);
358
385
  callbacks.setGoalStatus?.(formatGoalStatus(goal));
359
386
  if (!ok && ['editFile', 'replaceLines', 'writeFile'].includes(event.toolCall.toolName)) {
360
387
  editFileFailed = true;
@@ -391,19 +418,22 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
391
418
  let responseText = '';
392
419
  let continuationToolCalls = 0;
393
420
  let followUpStreamError;
394
- const continuationMessages = [
395
- ...messages,
396
- { role: 'user', content: prompt },
397
- ];
398
- const followUpSystemPrompt = buildSystemPrompt(contextFiles);
399
- const followUpInputEstimate = estimateLlmInputTokens({ system: followUpSystemPrompt, messages: continuationMessages, tools: availableTools });
421
+ const prunedMessages = compactToolHistory(stripSyntheticControls(messages)).messages;
422
+ const compactedMessages = estimateValueTokens(prunedMessages) > ACTIVE_CONTEXT_TOKEN_BUDGET
423
+ ? compactModelMessages(prunedMessages, { tokenBudget: ACTIVE_CONTEXT_TOKEN_BUDGET, workState: goal.workState }).messages
424
+ : prunedMessages;
425
+ const continuationMessages = withSyntheticControl(compactedMessages, `${prompt}\n\n${workStatePrompt(goal.workState)}`);
426
+ const followUpSystemPrompt = buildSystemPrompt(contextFiles, session);
427
+ const followUpTools = allowTools ? availableTools : undefined;
428
+ const followUpInputBreakdown = estimateInputBreakdown({ system: followUpSystemPrompt, contextFiles, messages: continuationMessages, tools: followUpTools });
429
+ logEntry(callbacks.log, { at: new Date().toISOString(), type: 'request', stream: `continuation:${reason}`, system: followUpSystemPrompt, messages: continuationMessages, tools: followUpTools ? Object.keys(followUpTools) : [], context: followUpInputBreakdown.breakdown });
400
430
  const followUp = streamText({
401
431
  model: activeModel,
402
432
  maxOutputTokens: DEFAULT_MAX_OUTPUT_TOKENS,
403
433
  system: followUpSystemPrompt,
404
434
  messages: continuationMessages,
405
- tools: availableTools,
406
- toolChoice: allowTools ? 'auto' : 'none',
435
+ ...toolRequestSettings(availableTools, allowTools),
436
+ ...providerSettings,
407
437
  stopWhen: stepCountIs(FOLLOW_UP_STEP_LIMIT),
408
438
  abortSignal: abortController.signal,
409
439
  experimental_context: toolExecutionContext,
@@ -412,32 +442,19 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
412
442
  if (continuationToolCalls >= FOLLOW_UP_TOOL_CALL_LIMIT || toolOnlyStepCount(steps) >= FOLLOW_UP_TOOL_ONLY_STEP_LIMIT) {
413
443
  return {
414
444
  toolChoice: 'none',
415
- messages: [
416
- ...messages,
417
- { role: 'user', content: toolLoopBudgetPrompt() },
418
- ],
445
+ messages: withSyntheticControl(messages, toolLoopBudgetPrompt()),
419
446
  };
420
447
  }
421
448
  if (likelyPlanOnlyRequest && mutatingToolSucceeded) {
422
449
  return {
423
450
  toolChoice: 'none',
424
- messages: [
425
- ...messages,
426
- { role: 'user', content: 'This was a planning request and the plan artifact has been created or updated. Stop using tools and summarize the plan file only; do not implement or validate it.' },
427
- ],
428
451
  };
429
452
  }
430
453
  if (editRecoveryPath && !editRecoveryReadSatisfied) {
431
454
  return {
432
455
  activeTools: ['readFile'],
433
- messages: [
434
- ...messages,
435
- { role: 'user', content: `A previous edit failed for ${editRecoveryPath}${editRecoveryReasonCode ? ` (${editRecoveryReasonCode})` : ''}. Before any further edit or bash inspection, call readFile on exactly ${editRecoveryPath}. Bash/cat does not satisfy this recovery step.` },
436
- ],
437
456
  };
438
457
  }
439
- if (editFileFailed)
440
- return { activeTools: ['listFiles', 'readFile', 'replaceLines', 'writeFile', 'bash'] };
441
458
  return undefined;
442
459
  },
443
460
  onError({ error }) {
@@ -445,22 +462,50 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
445
462
  callbacks.debugLog(`stream error: ${error instanceof Error ? error.message : String(error)}`);
446
463
  },
447
464
  onFinish(event) {
448
- callbacks.recordTokenEstimate?.(usageTokenEstimate(event, { input: followUpInputEstimate, output: estimateLlmOutputTokens(event.response.messages) }));
449
- callbacks.setConversation([...continuationMessages, ...event.response.messages]);
450
- callbacks.debugLog(`conversation updated to ${continuationMessages.length + event.response.messages.length} messages after follow-up`);
465
+ const providerUsage = extractUsage(event);
466
+ callbacks.recordTokenUsage?.({
467
+ inputTokens: providerUsage.inputTokens,
468
+ outputTokens: providerUsage.outputTokens,
469
+ systemPrompt: followUpInputBreakdown.systemPrompt,
470
+ messages: followUpInputBreakdown.messages,
471
+ toolSchemas: followUpInputBreakdown.toolSchemas,
472
+ outputEstimate: estimateValueTokens(event.response.messages),
473
+ cacheReadTokens: providerUsage.cacheReadTokens,
474
+ cacheWriteTokens: providerUsage.cacheWriteTokens,
475
+ noCacheTokens: providerUsage.noCacheTokens,
476
+ reasoningTokens: providerUsage.reasoningTokens,
477
+ logicalInputEstimate: followUpInputBreakdown.logicalInputEstimate,
478
+ effectiveNonCachedInput: effectiveNonCachedInput(providerUsage.inputTokens, providerUsage.cacheReadTokens),
479
+ });
480
+ const nextConversation = [...stripSyntheticControls(compactedMessages), ...event.response.messages];
481
+ callbacks.setConversation(nextConversation);
482
+ callbacks.debugLog(`conversation updated to ${nextConversation.length} messages after follow-up`);
451
483
  },
452
484
  experimental_onToolCallStart({ toolCall }) {
453
485
  sawToolCall = true;
454
486
  recordToolStart(toolCall);
455
487
  resetIdleTimer();
488
+ logEntry(callbacks.log, { at: new Date().toISOString(), type: 'tool_call', stream: `continuation:${reason}`, toolCall: { id: toolCall.toolCallId, name: toolCall.toolName, input: toolCall.input } });
456
489
  callbacks.debugLog(`follow-up tool start: ${toolCall.toolName} ${compact(toolCall.input)}`);
490
+ const sig = stableToolKey(toolCall);
491
+ const count = (toolCallSignatureCounts.get(sig) ?? 0) + 1;
492
+ toolCallSignatureCounts.set(sig, count);
493
+ if (count >= TOOL_REPETITION_THRESHOLD && !repetitionAbortFired) {
494
+ repetitionAbortFired = true;
495
+ turnStopReason = { kind: 'tool_repetition', message: `Stopped: called ${toolCall.toolName} ${count} times with identical input (tool loop). Type "continue" to try again — the next turn starts fresh.` };
496
+ const preview = sig.length > 100 ? `${sig.slice(0, 100)}…` : sig;
497
+ logEntry(callbacks.log, { at: new Date().toISOString(), type: 'warning', stream: `continuation:${reason}`, text: `tool repetition guard: "${preview}" called ${count} times with identical input this turn. Aborting to avoid tool-only loop.` });
498
+ callbacks.debugLog(`tool repetition guard abort (continuation): ${toolCall.toolName} count=${count}`);
499
+ abortController.abort(`Haze tool repetition guard: ${toolCall.toolName} called ${count} times with identical input.`);
500
+ }
457
501
  },
458
502
  experimental_onToolCallFinish(event) {
459
503
  resetIdleTimer();
460
504
  recordToolFinish(event);
505
+ logEntry(callbacks.log, { at: new Date().toISOString(), type: 'tool_result', stream: `continuation:${reason}`, toolResult: { id: event.toolCall.toolCallId, name: event.toolCall.toolName, success: event.success, output: event.output, error: event.error, durationMs: event.durationMs } });
461
506
  const nestedTokens = subagentTokenEstimate(event.output);
462
507
  if (nestedTokens)
463
- callbacks.recordTokenEstimate?.(nestedTokens);
508
+ callbacks.recordTokenUsage?.({ inputTokens: nestedTokens.input, outputTokens: nestedTokens.output, systemPrompt: 0, messages: 0, toolSchemas: 0, outputEstimate: 0, cacheReadTokens: 0, cacheWriteTokens: 0, noCacheTokens: nestedTokens.input, reasoningTokens: 0, logicalInputEstimate: nestedTokens.input, effectiveNonCachedInput: nestedTokens.input });
464
509
  const summary = toolResultSummary(event);
465
510
  toolSummaries.push(`${event.toolCall.toolName}: ${summary}`);
466
511
  recordToolDisplayFinish(event);
@@ -502,14 +547,16 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
502
547
  }
503
548
  let streamError;
504
549
  let lastFinishReason;
505
- const mainSystemPrompt = buildSystemPrompt(contextFiles);
506
- const mainInputEstimate = estimateLlmInputTokens({ system: mainSystemPrompt, messages: requestMessages, tools: availableTools });
550
+ const mainSystemPrompt = buildSystemPrompt(contextFiles, session);
551
+ const mainInputBreakdown = estimateInputBreakdown({ system: mainSystemPrompt, contextFiles, messages: requestMessages, tools: availableTools });
552
+ logEntry(callbacks.log, { at: new Date().toISOString(), type: 'request', stream: 'main', system: mainSystemPrompt, messages: requestMessages, tools: Object.keys(availableTools), context: mainInputBreakdown.breakdown });
507
553
  const result = streamText({
508
554
  model: activeModel,
509
555
  maxOutputTokens: DEFAULT_MAX_OUTPUT_TOKENS,
510
556
  system: mainSystemPrompt,
511
557
  messages: requestMessages,
512
558
  tools: availableTools,
559
+ ...providerSettings,
513
560
  stopWhen: stepCountIs(MAIN_STEP_LIMIT),
514
561
  abortSignal: abortController.signal,
515
562
  experimental_context: toolExecutionContext,
@@ -525,19 +572,11 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
525
572
  if (likelyPlanOnlyRequest && mutatingToolSucceeded) {
526
573
  return {
527
574
  toolChoice: 'none',
528
- messages: [
529
- ...messages,
530
- { role: 'user', content: 'This was a planning request and the plan artifact has been created or updated. Stop using tools and summarize the plan file only; do not implement or validate it.' },
531
- ],
532
575
  };
533
576
  }
534
577
  if (editRecoveryPath && !editRecoveryReadSatisfied) {
535
578
  return {
536
579
  activeTools: ['readFile'],
537
- messages: [
538
- ...messages,
539
- { role: 'user', content: `A previous edit failed for ${editRecoveryPath}${editRecoveryReasonCode ? ` (${editRecoveryReasonCode})` : ''}. Before any further edit or bash inspection, call readFile on exactly ${editRecoveryPath}. Bash/cat does not satisfy this recovery step.` },
540
- ],
541
580
  };
542
581
  }
543
582
  if (repeatedToolCall) {
@@ -545,58 +584,128 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
545
584
  callbacks.debugLog(`disabling repeated tools for next step: ${repeatedToolNames.join(', ')}`);
546
585
  return {
547
586
  activeTools,
548
- messages: [
549
- ...messages,
550
- { role: 'user', content: `You already called ${repeatedToolNames.join(', ')} with the same input. Do not repeat that tool call. Use a different relevant tool. If this is an action request and no file change has been made yet, continue with edit/write tools rather than summarizing.` },
551
- ],
552
- };
553
- }
554
- if (likelyActionRequest && !mutatingToolSucceeded && consecutiveToolOnlySteps >= 3 && toolCalls.length < MAIN_TOOL_CALL_LIMIT) {
555
- callbacks.debugLog('nudging action request toward mutation after read-only steps');
556
- return {
557
- messages: [
558
- ...messages,
559
- { role: 'user', content: 'You have inspected enough for now. This is an action request; make the requested change with editFile, replaceLines, or writeFile instead of saying tools are unavailable or summarizing.' },
560
- ],
561
587
  };
562
588
  }
563
589
  if (toolCalls.length >= MAIN_TOOL_CALL_LIMIT || consecutiveToolOnlySteps >= MAIN_TOOL_ONLY_STEP_LIMIT) {
564
590
  callbacks.debugLog('forcing text response to avoid tool loop');
591
+ turnStopReason = toolCalls.length >= MAIN_TOOL_CALL_LIMIT
592
+ ? { kind: 'tool_budget', message: `Reached the per-turn tool-call limit (${MAIN_TOOL_CALL_LIMIT}). Type "continue" to resume — Haze will pick up where it left off.` }
593
+ : { kind: 'tool_only_limit', message: `Made ${MAIN_TOOL_ONLY_STEP_LIMIT} consecutive inspection-only steps without making changes. Type "continue" to resume.` };
565
594
  return {
566
595
  toolChoice: 'none',
567
- messages: [
568
- ...messages,
569
- { role: 'user', content: toolLoopBudgetPrompt() },
570
- ],
596
+ messages: withSyntheticControl(messages, toolLoopBudgetPrompt()),
571
597
  };
572
598
  }
573
- if (editFileFailed)
574
- return { activeTools: ['listFiles', 'readFile', 'replaceLines', 'writeFile', 'bash'] };
575
599
  return undefined;
576
600
  },
577
- onStepFinish({ stepNumber, text, toolCalls, toolResults, finishReason }) {
601
+ onStepFinish({ stepNumber, text, toolCalls, toolResults, finishReason, usage, response }) {
602
+ if (Array.isArray(response?.messages) && response.messages.length > 0) {
603
+ latestAccumulatedResponseMessages = response.messages;
604
+ }
605
+ if (!turnStopReason && stepNumber >= MAIN_STEP_LIMIT - 1) {
606
+ turnStopReason = { kind: 'step_limit', message: `Reached the per-turn step limit (${MAIN_STEP_LIMIT}). Type "continue" to resume — Haze will pick up where it left off.` };
607
+ }
578
608
  lastFinishReason = finishReason;
579
- callbacks.debugLog(`step ${stepNumber} finished: ${finishReason}; text=${text.length}; toolCalls=${toolCalls.length}; toolResults=${toolResults.length}`);
609
+ const stepInputTokens = usage?.inputTokens;
610
+ const stepOutputTokens = usage?.outputTokens;
611
+ const stepCacheRead = usage?.inputTokenDetails?.cacheReadTokens ?? 0;
612
+ const stepCacheWrite = usage?.inputTokenDetails?.cacheWriteTokens ?? 0;
613
+ const stepReasoning = usage?.outputTokenDetails?.reasoningTokens ?? 0;
614
+ const stepNoCache = effectiveNonCachedInput(stepInputTokens, stepCacheRead) ?? 0;
615
+ const stepCacheHitRatio = cacheHitRatio(stepInputTokens, stepCacheRead || undefined);
616
+ logEntry(callbacks.log, { at: new Date().toISOString(), type: 'step', stream: 'main', step: stepNumber, text, finishReason, usage: { inputTokens: stepInputTokens, outputTokens: stepOutputTokens, cacheReadTokens: stepCacheRead || undefined, cacheWriteTokens: stepCacheWrite || undefined, noCacheTokens: stepNoCache || undefined, reasoningTokens: stepReasoning || undefined, cacheHitRatio: stepCacheHitRatio } });
617
+ if (stepCacheHitRatio !== undefined && stepCacheHitRatio < 0.5 && stepNoCache > 2000) {
618
+ logEntry(callbacks.log, { at: new Date().toISOString(), type: 'warning', stream: 'main', step: stepNumber, text: `low cache hit: ${(stepCacheHitRatio * 100).toFixed(1)}% (${stepCacheRead}/${stepInputTokens}), ${stepNoCache} no-cache tokens. Likely prompt prefix changed mid-turn.` });
619
+ }
620
+ callbacks.debugLog(`step ${stepNumber} finished: ${finishReason}; text=${text.length}; toolCalls=${toolCalls.length}; toolResults=${toolResults.length}; usage=${stepInputTokens != null ? `in=${stepInputTokens} out=${stepOutputTokens}` : 'not reported'}${stepCacheRead ? ` cached=${stepCacheRead}` : ''}${stepCacheWrite ? ` cache_write=${stepCacheWrite}` : ''}${stepReasoning ? ` reasoning=${stepReasoning}` : ''}${stepCacheHitRatio !== undefined ? ` cache_hit=${(stepCacheHitRatio * 100).toFixed(0)}%` : ''}`);
621
+ // Repetition guard: when a constrained (no-tools) step emits short text
622
+ // that matches the prior two short-text steps, the model is stuck in a
623
+ // "Let me X" loop. Abort the whole turn so we don't burn maxOutputTokens
624
+ // on every remaining step in the limit. The secondary consecutive-text-only
625
+ // check catches varied-phrasing loops (e.g. "Let me install" → "I'll install
626
+ // dependencies now" → "Now let me run npm install") that the exact-signature
627
+ // check would miss.
628
+ if (finishReason === 'stop' && toolCalls.length === 0) {
629
+ consecutiveTextOnlySteps += 1;
630
+ const signature = text.trim().toLowerCase().replace(/[^a-z0-9 ]/g, '').replace(/\s+/g, ' ').slice(0, 120);
631
+ if (signature.length >= 8) {
632
+ recentStepTextSignatures.push(signature);
633
+ const last3 = recentStepTextSignatures.slice(-3);
634
+ if (last3.length === 3 && last3[0] === last3[1] && last3[1] === last3[2] && !repetitionAbortFired) {
635
+ repetitionAbortFired = true;
636
+ turnStopReason = { kind: 'text_repetition', message: 'Stopped: the model emitted the same response 3 times in a row (text loop). Type "continue" to try again — the next turn starts fresh.' };
637
+ logEntry(callbacks.log, { at: new Date().toISOString(), type: 'warning', stream: 'main', step: stepNumber, text: `repetition guard: 3 consecutive identical text-only steps. Aborting turn to avoid loop. Last signature: "${signature.slice(0, 60)}"` });
638
+ callbacks.debugLog(`repetition guard abort at step ${stepNumber}; signature="${signature.slice(0, 60)}"`);
639
+ abortController.abort('Haze repetition guard: 3 consecutive identical text-only steps.');
640
+ }
641
+ }
642
+ if (consecutiveTextOnlySteps >= 4 && !repetitionAbortFired) {
643
+ repetitionAbortFired = true;
644
+ turnStopReason = { kind: 'text_repetition', message: 'Stopped: the model emitted several text responses in a row without making progress (likely a varied-phrasing loop). Type "continue" to try again — the next turn starts fresh.' };
645
+ logEntry(callbacks.log, { at: new Date().toISOString(), type: 'warning', stream: 'main', step: stepNumber, text: `repetition guard: ${consecutiveTextOnlySteps} consecutive text-only steps with no tool calls. Aborting turn to avoid varied-phrasing loop.` });
646
+ callbacks.debugLog(`repetition guard abort at step ${stepNumber}; consecutiveTextOnlySteps=${consecutiveTextOnlySteps}`);
647
+ abortController.abort(`Haze repetition guard: ${consecutiveTextOnlySteps} consecutive text-only steps without progress.`);
648
+ }
649
+ }
650
+ else {
651
+ consecutiveTextOnlySteps = 0;
652
+ }
580
653
  },
581
654
  onFinish(event) {
582
- callbacks.recordTokenEstimate?.(usageTokenEstimate(event, { input: mainInputEstimate, output: estimateLlmOutputTokens(event.response.messages) }));
583
- const nextConversation = [...requestMessages, ...event.response.messages];
655
+ const providerUsage = extractUsage(event);
656
+ callbacks.recordTokenUsage?.({
657
+ inputTokens: providerUsage.inputTokens,
658
+ outputTokens: providerUsage.outputTokens,
659
+ systemPrompt: mainInputBreakdown.systemPrompt,
660
+ messages: mainInputBreakdown.messages,
661
+ toolSchemas: mainInputBreakdown.toolSchemas,
662
+ outputEstimate: estimateValueTokens(event.response.messages),
663
+ cacheReadTokens: providerUsage.cacheReadTokens,
664
+ cacheWriteTokens: providerUsage.cacheWriteTokens,
665
+ noCacheTokens: providerUsage.noCacheTokens,
666
+ reasoningTokens: providerUsage.reasoningTokens,
667
+ logicalInputEstimate: mainInputBreakdown.logicalInputEstimate,
668
+ effectiveNonCachedInput: effectiveNonCachedInput(providerUsage.inputTokens, providerUsage.cacheReadTokens),
669
+ });
670
+ const accumulated = [...stripSyntheticControls(requestMessages), ...event.response.messages];
671
+ const compacted = compactToolHistory(accumulated);
672
+ const nextConversation = compacted.messages;
584
673
  callbacks.setConversation(nextConversation);
674
+ if (compacted.compactedResults > 0 || compacted.compactedCalls > 0) {
675
+ callbacks.debugLog(`end-of-turn compaction: ${compacted.compactedResults} results, ${compacted.compactedCalls} tool-call inputs compacted`);
676
+ logEntry(callbacks.log, { at: new Date().toISOString(), type: 'warning', stream: 'main', text: `end-of-turn compaction: ${compacted.compactedResults} old results, ${compacted.compactedCalls} old tool-call inputs compacted before next turn.` });
677
+ }
585
678
  callbacks.debugLog(`conversation updated to ${nextConversation.length} messages`);
586
679
  },
587
680
  experimental_onToolCallStart({ toolCall }) {
588
681
  sawToolCall = true;
589
682
  recordToolStart(toolCall);
590
683
  resetIdleTimer();
684
+ logEntry(callbacks.log, { at: new Date().toISOString(), type: 'tool_call', stream: 'main', toolCall: { id: toolCall.toolCallId, name: toolCall.toolName, input: toolCall.input } });
591
685
  callbacks.debugLog(`tool start: ${toolCall.toolName} ${compact(toolCall.input)}`);
686
+ // Tool-repetition guard: if the same (toolName, input) has been called
687
+ // TOOL_REPETITION_THRESHOLD times this turn, the model is stuck in a
688
+ // tool-only loop. Abort the turn rather than letting it burn more calls.
689
+ const sig = stableToolKey(toolCall);
690
+ const count = (toolCallSignatureCounts.get(sig) ?? 0) + 1;
691
+ toolCallSignatureCounts.set(sig, count);
692
+ if (count >= TOOL_REPETITION_THRESHOLD && !repetitionAbortFired) {
693
+ repetitionAbortFired = true;
694
+ turnStopReason = { kind: 'tool_repetition', message: `Stopped: called ${toolCall.toolName} ${count} times with identical input (tool loop). Type "continue" to try again — the next turn starts fresh.` };
695
+ const preview = sig.length > 100 ? `${sig.slice(0, 100)}…` : sig;
696
+ logEntry(callbacks.log, { at: new Date().toISOString(), type: 'warning', stream: 'main', text: `tool repetition guard: "${preview}" called ${count} times with identical input this turn. Aborting to avoid tool-only loop.` });
697
+ callbacks.debugLog(`tool repetition guard abort: ${toolCall.toolName} count=${count} sig=${preview}`);
698
+ abortController.abort(`Haze tool repetition guard: ${toolCall.toolName} called ${count} times with identical input.`);
699
+ }
592
700
  },
593
701
  experimental_onToolCallFinish(event) {
594
702
  resetIdleTimer();
595
703
  const summary = toolResultSummary(event);
596
704
  recordToolFinish(event);
705
+ logEntry(callbacks.log, { at: new Date().toISOString(), type: 'tool_result', stream: 'main', toolResult: { id: event.toolCall.toolCallId, name: event.toolCall.toolName, success: event.success, output: event.output, error: event.error, durationMs: event.durationMs } });
597
706
  const nestedTokens = subagentTokenEstimate(event.output);
598
707
  if (nestedTokens)
599
- callbacks.recordTokenEstimate?.(nestedTokens);
708
+ callbacks.recordTokenUsage?.({ inputTokens: nestedTokens.input, outputTokens: nestedTokens.output, systemPrompt: 0, messages: 0, toolSchemas: 0, outputEstimate: 0, cacheReadTokens: 0, cacheWriteTokens: 0, noCacheTokens: nestedTokens.input, reasoningTokens: 0, logicalInputEstimate: nestedTokens.input, effectiveNonCachedInput: nestedTokens.input });
600
709
  toolSummaries.push(`${event.toolCall.toolName}: ${summary}`);
601
710
  recordToolDisplayFinish(event);
602
711
  if (!isDuplicateSkippedOutput(event.output))
@@ -646,10 +755,22 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
646
755
  let completedConversation = callbacks.getConversation();
647
756
  try {
648
757
  const response = await result.response;
649
- completedConversation = [...requestMessages, ...response.messages];
758
+ completedConversation = [...stripSyntheticControls(requestMessages), ...response.messages];
650
759
  callbacks.setConversation(completedConversation);
651
760
  }
652
761
  catch (error) {
762
+ // The turn was aborted or errored mid-stream. If we have any accumulated
763
+ // response messages from completed steps (tracked in onStepFinish), persist
764
+ // them so the next turn inherits the partial work instead of losing it.
765
+ if (latestAccumulatedResponseMessages.length > 0) {
766
+ const accumulated = [...stripSyntheticControls(requestMessages), ...latestAccumulatedResponseMessages];
767
+ const compacted = compactToolHistory(accumulated);
768
+ callbacks.setConversation(compacted.messages);
769
+ if (compacted.compactedResults > 0 || compacted.compactedCalls > 0) {
770
+ logEntry(callbacks.log, { at: new Date().toISOString(), type: 'warning', stream: 'main', text: `abort recovery: persisted ${latestAccumulatedResponseMessages.length} response messages, compacted ${compacted.compactedResults} results and ${compacted.compactedCalls} tool-call inputs.` });
771
+ }
772
+ callbacks.debugLog(`abort recovery: persisted ${latestAccumulatedResponseMessages.length} response messages before re-throwing`);
773
+ }
653
774
  throw streamError ?? error;
654
775
  }
655
776
  callbacks.debugLog(`response stream finished; session has ${completedConversation.length} model messages`);
@@ -680,8 +801,10 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
680
801
  async function runCompletionLoop(seedConversation, seedText) {
681
802
  let loopConversation = seedConversation;
682
803
  let latestText = seedText;
804
+ let noProgressSlices = 0;
683
805
  while ((decision.needsActionContinuation || decision.needsValidationContinuation) && completionContinuationCount < maxCompletionContinuations) {
684
806
  completionContinuationCount += 1;
807
+ const revisionBefore = goal.workState.revision;
685
808
  const prompt = decision.continuationPrompt
686
809
  ?? (looksIncomplete(latestText) ? postContinuationPrompt() : 'Continue the same user goal until it is complete, blocked by a concrete issue, or needs a user decision. Focus on the concrete blocker, not a generic plan.');
687
810
  const continuation = await streamAssistantResponse(loopConversation, `completion gate ${completionContinuationCount}`, prompt, true);
@@ -689,6 +812,12 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
689
812
  if (continuation.text)
690
813
  latestText = continuation.text;
691
814
  decision = decideCompletion(latestText);
815
+ noProgressSlices = goal.workState.revision === revisionBefore ? noProgressSlices + 1 : 0;
816
+ if (noProgressSlices >= 2)
817
+ break;
818
+ }
819
+ if ((decision.needsActionContinuation || decision.needsValidationContinuation) && noProgressSlices >= 2) {
820
+ callbacks.addMessage({ role: 'assistant', text: 'Status: partial. Two continuation slices made no tool progress; the latest work state and blocker evidence were preserved.' });
692
821
  }
693
822
  if ((decision.needsActionContinuation || decision.needsValidationContinuation) && completionContinuationCount >= maxCompletionContinuations) {
694
823
  callbacks.addMessage({ role: 'assistant', text: 'Stopped after the autonomous safety limit. The current goal may still need work; ask me to continue and I will resume from the latest tool results.' });
@@ -737,13 +866,16 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
737
866
  goal.phase = 'done';
738
867
  goal.status = 'complete';
739
868
  turnStatus = 'complete';
869
+ if (turnStopReason) {
870
+ callbacks.addMessage({ role: 'system', text: turnStopReason.message });
871
+ }
740
872
  callbacks.setGoalStatus?.(undefined);
741
873
  }
742
874
  catch (error) {
743
875
  if (abortController.signal.aborted) {
744
876
  turnStatus = 'aborted';
745
877
  callbacks.debugLog('request aborted');
746
- callbacks.addMessage({ role: 'system', text: 'Thinking aborted. You can type again.' });
878
+ callbacks.addMessage({ role: 'system', text: turnStopReason?.message ?? 'Thinking aborted. You can type again.' });
747
879
  }
748
880
  else {
749
881
  const text = error instanceof Error ? error.message : String(error);
@@ -753,7 +885,7 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
753
885
  callbacks.onEvent?.(agentEvent({ type: 'context_overflow', recovered: compacted, error: text }));
754
886
  if (compacted) {
755
887
  callbacks.addMessage({ role: 'system', text: 'Context overflow detected; compacted older context and retrying the same request once.' });
756
- await runAgentTurn(value, displayValue, contextFiles, callbacks, retryAttempt, true, true);
888
+ await runAgentTurn(value, displayValue, contextFiles, callbacks, retryAttempt, true, true, session);
757
889
  return;
758
890
  }
759
891
  callbacks.addMessage({ role: 'system', text: 'Context overflow detected, but there was not enough conversation history to compact automatically.' });
@@ -766,7 +898,7 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
766
898
  await abortableDelay(delay, abortController.signal);
767
899
  if (abortController.signal.aborted)
768
900
  return;
769
- await runAgentTurn(value, displayValue, contextFiles, callbacks, retryAttempt + 1, true, contextOverflowRecovered);
901
+ await runAgentTurn(value, displayValue, contextFiles, callbacks, retryAttempt + 1, true, contextOverflowRecovered, session);
770
902
  return;
771
903
  }
772
904
  callbacks.addMessage({ role: 'assistant', text: `Model call failed: ${text}` });
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,47 @@
1
+ import fs from 'fs-extra';
2
+ import path from 'node:path';
3
+ import { buildSystemPrompt } from '../llm/systemPrompt.js';
4
+ import { hazeTools } from '../llm/hazeTools.js';
5
+ import { contextBreakdown } from '../core/agent/contextBudget.js';
6
+ import { compactToolHistory } from '../core/agent/requestAssembly.js';
7
+ import { compactModelMessages } from '../core/agent/compaction.js';
8
+ import { summarizeContextDiagnostics } from '../config/contextFiles.js';
9
+ const reportSession = { start: new Date(0), cwd: process.cwd() };
10
+ async function loadFiles(paths) {
11
+ const candidates = paths.length > 0 ? paths : ['AGENTS.md', 'CLAUDE.md'];
12
+ const files = [];
13
+ for (const candidate of candidates) {
14
+ const absolute = path.resolve(candidate);
15
+ if (!await fs.pathExists(absolute) || !(await fs.stat(absolute)).isFile())
16
+ continue;
17
+ files.push({ path: path.relative(process.cwd(), absolute) || path.basename(absolute), content: await fs.readFile(absolute, 'utf8') });
18
+ }
19
+ return files;
20
+ }
21
+ const args = process.argv.slice(2);
22
+ const traceIndex = args.indexOf('--trace');
23
+ if (traceIndex >= 0) {
24
+ const tracePath = args[traceIndex + 1];
25
+ if (!tracePath)
26
+ throw new Error('--trace requires a JSON fixture path');
27
+ const raw = await fs.readJson(path.resolve(tracePath));
28
+ const messages = raw.messages ?? [];
29
+ const pruned = compactToolHistory(messages);
30
+ const compacted = compactModelMessages(pruned.messages, { tokenBudget: 4_000 });
31
+ const system = buildSystemPrompt([], reportSession);
32
+ process.stdout.write(`${JSON.stringify({
33
+ trace: tracePath,
34
+ before: contextBreakdown({ system, messages, tools: hazeTools }),
35
+ after: contextBreakdown({ system, messages: compacted.messages, tools: hazeTools }),
36
+ compactedToolResults: pruned.compactedResults,
37
+ compactedToolCalls: pruned.compactedCalls,
38
+ compactedMessages: compacted.compacted,
39
+ olderMessagesRemoved: compacted.olderCount,
40
+ }, null, 2)}\n`);
41
+ process.exit(0);
42
+ }
43
+ const files = await loadFiles(args);
44
+ const system = buildSystemPrompt(files, reportSession);
45
+ const breakdown = contextBreakdown({ system, contextFiles: files, messages: [], tools: hazeTools });
46
+ const summary = summarizeContextDiagnostics(files);
47
+ process.stdout.write(`${JSON.stringify({ breakdown, summary }, null, 2)}\n`);