@denizokcu/haze 0.1.1 → 0.3.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.
@@ -2,6 +2,7 @@ import fs from 'fs-extra';
2
2
  import path from 'node:path';
3
3
  import { buildInitPrompt } from '../../llm/initPrompt.js';
4
4
  import { activeProvider, configuredProviders, modelSelector, providerHasKey, resolveModelSelector, upsertProvider } from '../../config/providers.js';
5
+ import { clearTasks, generateTaskId, loadTasks, saveTasks } from '../../core/tasks/taskStorage.js';
5
6
  function skillHelp() {
6
7
  return [
7
8
  'Skill commands:',
@@ -23,7 +24,7 @@ async function skillOverview() {
23
24
  const skills = [...registry.skills.values()];
24
25
  const installed = skills.length === 0
25
26
  ? ['Installed skills:', '- None yet. Create one with /create-skill <description>.']
26
- : ['Installed skills:', ...skills.map(s => `- /${s.name} — ${s.description}`)];
27
+ : ['Installed skills:', ...skills.map(s => `- /${s.name} - ${s.description}`)];
27
28
  return `${skillHelp()}\n\n${installed.join('\n')}`;
28
29
  }
29
30
  async function handleSkillCommand(value, ctx) {
@@ -50,7 +51,7 @@ async function handleSkillCommand(value, ctx) {
50
51
  const skills = [...registry.skills.values()];
51
52
  ctx.addSystemMessage(skills.length === 0
52
53
  ? 'No installed skills found. Create one with /create-skill <description>.'
53
- : ['Installed skills:', ...skills.map(s => `- /${s.name} — ${s.description}`)].join('\n'));
54
+ : ['Installed skills:', ...skills.map(s => `- /${s.name} - ${s.description}`)].join('\n'));
54
55
  return 'handled';
55
56
  }
56
57
  if (subcommand === 'info') {
@@ -109,6 +110,73 @@ async function handleSkillCommand(value, ctx) {
109
110
  ctx.addSystemMessage(`Unknown skill command: ${parts[0]} ${subcommand}\n\n${skillHelp()}`);
110
111
  return 'handled';
111
112
  }
113
+ const STATUS_ICON = {
114
+ pending: '○',
115
+ in_progress: '◐',
116
+ completed: '✓',
117
+ };
118
+ async function handleTasksCommand(args, ctx) {
119
+ const parts = args.split(/\s+/).filter(Boolean);
120
+ const subcommand = parts[0]?.toLowerCase();
121
+ if (!subcommand || subcommand === 'help') {
122
+ const tasks = await loadTasks();
123
+ if (tasks.length === 0) {
124
+ ctx.addSystemMessage('No tasks. Add one with /tasks add <title>.');
125
+ }
126
+ else {
127
+ const list = tasks.map((t, i) => ` ${STATUS_ICON[t.status] ?? '○'} ${i + 1}. ${t.title}`).join('\n');
128
+ ctx.addSystemMessage(`Tasks:\n${list}`);
129
+ }
130
+ return 'handled';
131
+ }
132
+ if (subcommand === 'add') {
133
+ const title = parts.slice(1).join(' ').trim();
134
+ if (!title) {
135
+ ctx.addSystemMessage('Usage: /tasks add <title>');
136
+ return 'handled';
137
+ }
138
+ const tasks = await loadTasks();
139
+ const now = new Date().toISOString();
140
+ tasks.push({ id: generateTaskId(), title, status: 'pending', createdAt: now, updatedAt: now });
141
+ await saveTasks(tasks);
142
+ ctx.addSystemMessage(`Added: ${title}`);
143
+ return 'handled';
144
+ }
145
+ if (subcommand === 'remove' || subcommand === 'rm') {
146
+ const numStr = parts[1];
147
+ if (!numStr) {
148
+ ctx.addSystemMessage('Usage: /tasks remove <number>');
149
+ return 'handled';
150
+ }
151
+ const num = parseInt(numStr, 10);
152
+ if (isNaN(num) || num < 1) {
153
+ ctx.addSystemMessage('Provide a valid task number (e.g., /tasks remove 1).');
154
+ return 'handled';
155
+ }
156
+ const tasks = await loadTasks();
157
+ if (num > tasks.length) {
158
+ ctx.addSystemMessage(`Task ${num} not found. You have ${tasks.length} task(s).`);
159
+ return 'handled';
160
+ }
161
+ const removed = tasks.splice(num - 1, 1)[0];
162
+ await saveTasks(tasks);
163
+ ctx.addSystemMessage(`Removed: ${removed.title}`);
164
+ return 'handled';
165
+ }
166
+ if (subcommand === 'clear') {
167
+ await clearTasks();
168
+ ctx.addSystemMessage('All tasks cleared.');
169
+ return 'handled';
170
+ }
171
+ // Unknown subcommand → treat as task title
172
+ const title = args.trim();
173
+ const tasks = await loadTasks();
174
+ const now = new Date().toISOString();
175
+ tasks.push({ id: generateTaskId(), title, status: 'pending', createdAt: now, updatedAt: now });
176
+ await saveTasks(tasks);
177
+ ctx.addSystemMessage(`Added: ${title}`);
178
+ return 'handled';
179
+ }
112
180
  export async function handleSlashCommand(value, ctx) {
113
181
  if (value === '/exit' || value === '/quit')
114
182
  return 'exit';
@@ -118,7 +186,7 @@ export async function handleSlashCommand(value, ctx) {
118
186
  '/help',
119
187
  ' Show all available slash commands and what they do.',
120
188
  '/provider',
121
- ' Choose a provider, then use it or add models; choose add provider at the bottom to create one.',
189
+ ' Choose a provider, then use it, add/remove models, set API key, or remove it.',
122
190
  '/model',
123
191
  ' Choose a model from all configured providers.',
124
192
  '/model <name-or-provider:name>',
@@ -137,6 +205,10 @@ export async function handleSlashCommand(value, ctx) {
137
205
  ' Resume the latest saved session for this workspace.',
138
206
  '/new',
139
207
  ' Start a fresh durable session.',
208
+ '/tasks',
209
+ ' Manage your task list. Subcommands: add <title>, remove <number>, clear.',
210
+ '/tasks',
211
+ ' Show current task list.',
140
212
  '/compact [instructions]',
141
213
  ' Summarize older model context and keep recent messages.',
142
214
  '/clear',
@@ -175,9 +247,14 @@ export async function handleSlashCommand(value, ctx) {
175
247
  }
176
248
  if (value === '/clear') {
177
249
  ctx.clearConversation();
250
+ await clearTasks();
178
251
  ctx.addSystemMessage('Cleared. The void is productive.');
179
252
  return 'handled';
180
253
  }
254
+ if (value === '/tasks' || value.startsWith('/tasks ')) {
255
+ const args = value.slice('/tasks'.length).trim();
256
+ return await handleTasksCommand(args, ctx);
257
+ }
181
258
  if (value === '/settings') {
182
259
  const providers = configuredProviders(ctx.settings);
183
260
  const activeProvider = providers.find(provider => provider.name === ctx.settings.provider) ?? providers[0];
@@ -194,7 +271,7 @@ export async function handleSlashCommand(value, ctx) {
194
271
  if (value === '/provider') {
195
272
  ctx.setModelProviderFilter?.(undefined);
196
273
  ctx.setMode('provider');
197
- ctx.addSystemMessage('Choose a provider. Selecting one opens provider actions. Choose “add provider” at the bottom to add a new provider.');
274
+ ctx.addSystemMessage('Choose a provider. Selecting one opens provider actions. Choose "add provider" to pick from presets or enter custom details.');
198
275
  return 'handled';
199
276
  }
200
277
  if (value === '/model') {
@@ -205,7 +282,7 @@ export async function handleSlashCommand(value, ctx) {
205
282
  }
206
283
  if (value === '/model list') {
207
284
  const providers = configuredProviders(ctx.settings);
208
- ctx.addSystemMessage(['Configured models:', ...providers.flatMap(provider => provider.models.map(model => `- ${modelSelector(provider, model)} — ${provider.name}`))].join('\n'));
285
+ ctx.addSystemMessage(['Configured models:', ...providers.flatMap(provider => provider.models.map(model => `- ${modelSelector(provider, model)} - ${provider.name}`))].join('\n'));
209
286
  return 'handled';
210
287
  }
211
288
  if (value.startsWith('/model ')) {
@@ -6,4 +6,6 @@ export declare function toolResultSummary(event: {
6
6
  error?: unknown;
7
7
  }): string;
8
8
  export declare function formatSeconds(milliseconds: number): string;
9
+ export declare function formatElapsedTime(milliseconds: number): string;
10
+ export declare function formatElapsedTimeWhole(milliseconds: number): string;
9
11
  export declare function toolOutputDetails(value: unknown): string;
@@ -38,6 +38,10 @@ export function toolCallSummary(toolName, input) {
38
38
  const taskPreview = data.task.length > 60 ? `${data.task.slice(0, 60).trimEnd()}…` : data.task;
39
39
  return `subagent "${taskPreview}"`;
40
40
  }
41
+ if (toolName === 'writeTasks') {
42
+ const tasks = Array.isArray(data?.tasks) ? data.tasks : [];
43
+ return `writeTasks (${tasks.length} task${tasks.length === 1 ? '' : 's'})`;
44
+ }
41
45
  return `${toolName} ${compact(input)}`;
42
46
  }
43
47
  export function toolResultSummary(event) {
@@ -50,8 +54,17 @@ export function toolResultSummary(event) {
50
54
  const count = output.totalMatches;
51
55
  return count === 0 ? 'no matches' : `${count} match${count === 1 ? '' : 'es'}`;
52
56
  }
53
- if (typeof output?.code === 'number')
54
- return `exited with code ${output.code}`;
57
+ if (typeof output?.validationSummary === 'object' && output.validationSummary != null && 'summaryText' in output.validationSummary) {
58
+ const summary = output.validationSummary;
59
+ const next = typeof summary.suggestedNextStep === 'string' ? `; next: ${summary.suggestedNextStep}` : '';
60
+ return `${String(summary.summaryText)}${next}`;
61
+ }
62
+ if (typeof output?.code === 'number') {
63
+ const risk = typeof output.classification?.riskLevel === 'string'
64
+ ? ` (${output.classification.riskLevel})`
65
+ : '';
66
+ return `exited with code ${output.code}${risk}`;
67
+ }
55
68
  if (typeof output?.status === 'string' && typeof output?.summary === 'string') {
56
69
  const summary = output.summary.split('\n')[0] ?? '';
57
70
  const preview = summary.length > 120 ? `${summary.slice(0, 120).trimEnd()}…` : summary;
@@ -61,6 +74,10 @@ export function toolResultSummary(event) {
61
74
  return `${output.status}${meta}: ${preview}`;
62
75
  }
63
76
  if (typeof output?.ok === 'boolean') {
77
+ // writeTasks result
78
+ if (output.ok && typeof output.summary === 'string') {
79
+ return compact(output.summary, 120);
80
+ }
64
81
  if (output.ok) {
65
82
  if (typeof output.addedLines === 'number' || typeof output.removedLines === 'number') {
66
83
  const added = typeof output.addedLines === 'number' ? output.addedLines : 0;
@@ -69,20 +86,53 @@ export function toolResultSummary(event) {
69
86
  }
70
87
  return 'completed';
71
88
  }
72
- return typeof output.error === 'string' ? `failed: ${compact(output.error)}` : 'failed';
89
+ const reason = typeof output.reasonCode === 'string' ? ` (${output.reasonCode})` : '';
90
+ return typeof output.error === 'string' ? `failed${reason}: ${compact(output.error)}` : `failed${reason}`;
73
91
  }
74
92
  return 'completed';
75
93
  }
76
94
  export function formatSeconds(milliseconds) {
77
95
  return `${(milliseconds / 1000).toFixed(1)}s`;
78
96
  }
97
+ export function formatElapsedTime(milliseconds) {
98
+ const totalSeconds = Math.max(0, milliseconds / 1000);
99
+ const wholeSeconds = Math.floor(totalSeconds);
100
+ const seconds = totalSeconds - Math.floor(wholeSeconds / 60) * 60;
101
+ const totalMinutes = Math.floor(wholeSeconds / 60);
102
+ const minutes = totalMinutes % 60;
103
+ const hours = Math.floor(totalMinutes / 60);
104
+ const secondsLabel = `${seconds.toFixed(1)}s`;
105
+ if (hours > 0)
106
+ return `${hours}h ${minutes}m ${secondsLabel}`;
107
+ if (minutes > 0)
108
+ return `${minutes}m ${secondsLabel}`;
109
+ return secondsLabel;
110
+ }
111
+ export function formatElapsedTimeWhole(milliseconds) {
112
+ const totalSeconds = Math.max(0, Math.floor(milliseconds / 1000));
113
+ const seconds = totalSeconds % 60;
114
+ const totalMinutes = Math.floor(totalSeconds / 60);
115
+ const minutes = totalMinutes % 60;
116
+ const hours = Math.floor(totalMinutes / 60);
117
+ if (hours > 0)
118
+ return `${hours}h ${minutes}m ${seconds}s`;
119
+ if (minutes > 0)
120
+ return `${minutes}m ${seconds}s`;
121
+ return `${seconds}s`;
122
+ }
79
123
  export function toolOutputDetails(value) {
80
124
  if (!value || typeof value !== 'object')
81
125
  return '';
82
126
  const output = value;
83
127
  const stdout = output.stdout?.text?.trim();
84
128
  const stderr = output.stderr?.text?.trim();
129
+ const meta = [
130
+ output.cwd ? `cwd: ${output.cwd}` : '',
131
+ output.classification?.riskLevel ? `classification: ${output.classification.riskLevel}${output.classification.reason ? ` — ${output.classification.reason}` : ''}` : '',
132
+ output.validationSummary?.summaryText ? `validation: ${output.validationSummary.summaryText}${output.validationSummary.suggestedNextStep ? `\nnext: ${output.validationSummary.suggestedNextStep}` : ''}` : '',
133
+ ].filter(Boolean).join('\n');
85
134
  const parts = [
135
+ meta,
86
136
  stdout ? `stdout:\n${compact(stdout, 1200)}` : '',
87
137
  stderr ? `stderr:\n${compact(stderr, 1200)}` : '',
88
138
  ].filter(Boolean);
@@ -7,6 +7,8 @@ export type Message = {
7
7
  text: string;
8
8
  streaming?: boolean;
9
9
  hidden?: boolean;
10
+ startedAt?: number;
11
+ finishedAt?: number;
10
12
  };
11
13
  export interface StreamCallbacks {
12
14
  addMessage: (msg: Message) => void;
@@ -22,5 +24,10 @@ export interface StreamCallbacks {
22
24
  setGoalStatus?: (status: string | undefined) => void;
23
25
  onEvent?: AgentEventSink;
24
26
  compactConversation?: (instructions?: string) => boolean;
27
+ recordTokenEstimate?: (tokens: {
28
+ input: number;
29
+ output: number;
30
+ }) => void;
31
+ onTasksChanged?: () => void;
25
32
  }
26
33
  export declare function runAgentTurn(value: string, displayValue: string | undefined, contextFiles: ContextFile[], callbacks: StreamCallbacks, retryAttempt?: number, retryingExistingRequest?: boolean, contextOverflowRecovered?: boolean): Promise<void>;
@@ -4,7 +4,7 @@ import { hazeTools } from '../../llm/hazeTools.js';
4
4
  import { buildSystemPrompt } from '../../llm/systemPrompt.js';
5
5
  import { loadSkillRegistry } from '../../skills/SkillRegistry.js';
6
6
  import { buildSkillTools } from '../../skills/skillTools.js';
7
- import { compact, toolCallSummary, toolResultSummary, formatSeconds } from './formatters.js';
7
+ import { compact, toolCallSummary, toolResultSummary, formatElapsedTime, formatElapsedTimeWhole, formatSeconds } from './formatters.js';
8
8
  import { isActionRequest, isPlanImplementationRequest, isPlanOnlyRequest, isValidationRequest } from '../../core/goal/requestClassifier.js';
9
9
  import { completionDecision, looksIncomplete, noTextAfterToolPrompt, postContinuationPrompt, toolLoopBudgetPrompt } from '../../core/goal/completionPolicy.js';
10
10
  import { createSessionGoal, formatGoalStatus, observeGoalToolEvent } from '../../core/goal/sessionGoal.js';
@@ -94,6 +94,38 @@ function toolOutputOk(output, success) {
94
94
  return false;
95
95
  return !(typeof output === 'object' && output != null && 'ok' in output && output.ok === false);
96
96
  }
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);
109
+ }
110
+ function estimateLlmOutputTokens(messages) {
111
+ return estimateModelMessageTokens(messages);
112
+ }
113
+ function subagentTokenEstimate(output) {
114
+ if (typeof output !== 'object' || output == null || !('tokens' in output))
115
+ return undefined;
116
+ const tokens = output.tokens;
117
+ const input = typeof tokens?.in === 'number' ? tokens.in : 0;
118
+ const outputTokens = typeof tokens?.out === 'number' ? tokens.out : 0;
119
+ return input > 0 || outputTokens > 0 ? { input, output: outputTokens } : undefined;
120
+ }
121
+ function usageTokenEstimate(event, fallback) {
122
+ const usage = typeof event === 'object' && event != null && 'usage' in event
123
+ ? event.usage
124
+ : 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 };
128
+ }
97
129
  export async function runAgentTurn(value, displayValue, contextFiles, callbacks, retryAttempt = 0, retryingExistingRequest = false, contextOverflowRecovered = false) {
98
130
  const displayVal = displayValue ?? value;
99
131
  const userMessage = { role: 'user', text: displayVal };
@@ -105,6 +137,7 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
105
137
  callbacks.setAbortController?.(abortController);
106
138
  let turnStatus = 'failed';
107
139
  let idleTimer;
140
+ let stopActiveTimers = () => undefined;
108
141
  const resetIdleTimer = () => {
109
142
  if (idleTimer)
110
143
  clearTimeout(idleTimer);
@@ -126,7 +159,7 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
126
159
  const likelyPlanImplementationRequest = isPlanImplementationRequest(value);
127
160
  const likelyActionRequest = isActionRequest(value);
128
161
  const likelyValidationRequest = isValidationRequest(value);
129
- const planImplementationGuidance = 'When implementing a plan file, 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, use file tools (not bash) for any file 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.';
162
+ const planImplementationGuidance = 'Haze internal guidance for implementing plan files. The original user request remains authoritative. First identify the concrete required checklist items and compare them with the current files. Do not edit source or tests when the required behavior is already present. Implement the smallest clearly required phase or required items, skip optional/design-question items unless explicitly requested, add tests rather than exploratory one-off scripts where possible, prefer file tools for source changes, run validation once after code/test edits, then update plan status with file tools if requested. Do not call unresolved optional scope a blocker.';
130
163
  const requestMessages = retryingExistingRequest
131
164
  ? callbacks.getConversation()
132
165
  : likelyPlanImplementationRequest
@@ -137,6 +170,7 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
137
170
  let currentAssistantId = `assistant-${Date.now()}`;
138
171
  let assistantStarted = false;
139
172
  let currentAssistantStarted = false;
173
+ let currentAssistantStartedAt = Date.now();
140
174
  let currentAssistantText = '';
141
175
  let assistantText = '';
142
176
  let toolEpoch = 0;
@@ -151,6 +185,7 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
151
185
  let completionContinuationCount = 0;
152
186
  const maxCompletionContinuations = COMPLETION_CONTINUATION_LIMIT;
153
187
  let editRecoveryPath;
188
+ let editRecoveryReasonCode;
154
189
  let editRecoveryReadSatisfied = false;
155
190
  const toolSummaries = [];
156
191
  const visibleAssistantTexts = new Set();
@@ -178,6 +213,24 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
178
213
  const toolDisplayItems = [];
179
214
  let toolGroupStarted = false;
180
215
  let toolGroupFinalized = false;
216
+ let toolTimer;
217
+ function stopToolTimer() {
218
+ if (!toolTimer)
219
+ return;
220
+ clearInterval(toolTimer);
221
+ toolTimer = undefined;
222
+ }
223
+ function startToolTimer() {
224
+ if (toolTimer)
225
+ return;
226
+ toolTimer = setInterval(() => {
227
+ if (toolDisplayItems.some(item => item.status === 'running'))
228
+ updateToolGroup(true);
229
+ else
230
+ stopToolTimer();
231
+ }, 1000);
232
+ }
233
+ stopActiveTimers = stopToolTimer;
181
234
  function renderToolGroup(streaming) {
182
235
  const visibleItems = toolDisplayItems.filter(item => !item.hidden);
183
236
  const running = visibleItems.some(item => item.status === 'running');
@@ -197,9 +250,13 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
197
250
  }
198
251
  const rows = [...grouped.values()];
199
252
  const compactSuffix = !running && visibleItems.length > 12 ? ` · showing ${compactItems.length} important` : '';
253
+ const elapsedMs = visibleItems.length > 0
254
+ ? (running ? Date.now() : Math.max(...visibleItems.map(item => item.finishedAt ?? item.startedAt))) - Math.min(...visibleItems.map(item => item.startedAt))
255
+ : 0;
256
+ const elapsed = running || streaming ? formatElapsedTimeWhole(elapsedMs) : formatElapsedTime(elapsedMs);
200
257
  const header = running || streaming
201
- ? 'Running tools'
202
- : `${visibleItems.length} call${visibleItems.length === 1 ? '' : 's'} · ${changes.length} change${changes.length === 1 ? '' : 's'} · ${failures.length} failed${compactSuffix}`;
258
+ ? `Running tools · ${elapsed}`
259
+ : `${visibleItems.length} call${visibleItems.length === 1 ? '' : 's'} · ${changes.length} change${changes.length === 1 ? '' : 's'} · ${failures.length} failed · ${elapsed}${compactSuffix}`;
203
260
  const lines = [];
204
261
  for (const { item, count } of rows) {
205
262
  const icon = item.status === 'running' ? '…' : item.status === 'success' ? '✓' : '✗';
@@ -218,7 +275,7 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
218
275
  }
219
276
  if (item.subItems && item.subItems.length > 0) {
220
277
  for (const sub of item.subItems) {
221
- const subDuration = sub.durationMs > 1000 ? ` (${formatSeconds(sub.durationMs)})` : '';
278
+ const subDuration = sub.durationMs > 1000 ? ` · ${formatSeconds(sub.durationMs)}` : '';
222
279
  lines.push(` · ${sub.name} — ${sub.summary}${subDuration}`);
223
280
  }
224
281
  }
@@ -245,7 +302,8 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
245
302
  toolGroupStarted = false;
246
303
  }
247
304
  callbacks.onEvent?.(agentEvent({ type: 'tool_start', id: toolCall.toolCallId, name: toolCall.toolName, input: toolCall.input }));
248
- toolDisplayItems.push({ id: toolCall.toolCallId, summary: toolCallSummary(toolCall.toolName, toolCall.input), status: 'running' });
305
+ toolDisplayItems.push({ id: toolCall.toolCallId, summary: toolCallSummary(toolCall.toolName, toolCall.input), status: 'running', startedAt: Date.now() });
306
+ startToolTimer();
249
307
  updateToolGroup(true);
250
308
  const runningSubagents = toolDisplayItems.filter(item => item.status === 'running' && item.summary.startsWith('subagent')).length;
251
309
  if (runningSubagents > 0)
@@ -259,6 +317,7 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
259
317
  item.status = toolOutputOk(event.output, event.success) ? 'success' : 'error';
260
318
  item.result = toolResultSummary(event);
261
319
  item.durationMs = event.durationMs;
320
+ item.finishedAt = item.startedAt + event.durationMs;
262
321
  item.hidden = isDuplicateSkippedOutput(event.output);
263
322
  if (typeof event.output === 'object' && event.output != null) {
264
323
  const output = event.output;
@@ -277,7 +336,13 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
277
336
  }));
278
337
  }
279
338
  }
280
- updateToolGroup(toolDisplayItems.some(candidate => candidate.status === 'running'));
339
+ if (event.toolCall.toolName === 'writeTasks' && event.success) {
340
+ callbacks.onTasksChanged?.();
341
+ }
342
+ const hasRunningTools = toolDisplayItems.some(candidate => candidate.status === 'running');
343
+ updateToolGroup(hasRunningTools);
344
+ if (!hasRunningTools)
345
+ stopToolTimer();
281
346
  const runningSubagents = toolDisplayItems.filter(i => i.status === 'running' && i.summary.startsWith('subagent')).length;
282
347
  if (runningSubagents === 0)
283
348
  callbacks.setBusyLabel?.('Haze is thinking');
@@ -294,6 +359,7 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
294
359
  if (!ok && ['editFile', 'replaceLines', 'writeFile'].includes(event.toolCall.toolName)) {
295
360
  editFileFailed = true;
296
361
  editRecoveryPath = path;
362
+ editRecoveryReasonCode = typeof event.output === 'object' && event.output != null && 'reasonCode' in event.output && typeof event.output.reasonCode === 'string' ? event.output.reasonCode : undefined;
297
363
  editRecoveryReadSatisfied = false;
298
364
  }
299
365
  if (ok && ['listFiles', 'readFile'].includes(event.toolCall.toolName))
@@ -305,6 +371,7 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
305
371
  mutatingToolSucceeded = true;
306
372
  if (!path || path === editRecoveryPath) {
307
373
  editRecoveryPath = undefined;
374
+ editRecoveryReasonCode = undefined;
308
375
  editRecoveryReadSatisfied = false;
309
376
  editFileFailed = false;
310
377
  }
@@ -319,7 +386,8 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
319
386
  async function streamAssistantResponse(messages, reason, prompt, allowTools = false) {
320
387
  callbacks.debugLog(`requesting assistant ${allowTools ? 'continuation' : 'text'}: ${reason}`);
321
388
  const responseId = `assistant-${Date.now()}-${Math.random().toString(36).slice(2)}`;
322
- let responseStarted = false;
389
+ const responseStarted = true;
390
+ const responseStartedAt = Date.now();
323
391
  let responseText = '';
324
392
  let continuationToolCalls = 0;
325
393
  let followUpStreamError;
@@ -327,11 +395,12 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
327
395
  ...messages,
328
396
  { role: 'user', content: prompt },
329
397
  ];
398
+ const followUpSystemPrompt = buildSystemPrompt(contextFiles);
399
+ const followUpInputEstimate = estimateLlmInputTokens({ system: followUpSystemPrompt, messages: continuationMessages, tools: availableTools });
330
400
  const followUp = streamText({
331
401
  model: activeModel,
332
- temperature: 0,
333
402
  maxOutputTokens: DEFAULT_MAX_OUTPUT_TOKENS,
334
- system: buildSystemPrompt(contextFiles),
403
+ system: followUpSystemPrompt,
335
404
  messages: continuationMessages,
336
405
  tools: availableTools,
337
406
  toolChoice: allowTools ? 'auto' : 'none',
@@ -363,7 +432,7 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
363
432
  activeTools: ['readFile'],
364
433
  messages: [
365
434
  ...messages,
366
- { role: 'user', content: `A previous edit failed for ${editRecoveryPath}. Before any further edit or bash inspection, call readFile on exactly ${editRecoveryPath}. Bash/cat does not satisfy this recovery step.` },
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.` },
367
436
  ],
368
437
  };
369
438
  }
@@ -376,6 +445,7 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
376
445
  callbacks.debugLog(`stream error: ${error instanceof Error ? error.message : String(error)}`);
377
446
  },
378
447
  onFinish(event) {
448
+ callbacks.recordTokenEstimate?.(usageTokenEstimate(event, { input: followUpInputEstimate, output: estimateLlmOutputTokens(event.response.messages) }));
379
449
  callbacks.setConversation([...continuationMessages, ...event.response.messages]);
380
450
  callbacks.debugLog(`conversation updated to ${continuationMessages.length + event.response.messages.length} messages after follow-up`);
381
451
  },
@@ -388,6 +458,9 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
388
458
  experimental_onToolCallFinish(event) {
389
459
  resetIdleTimer();
390
460
  recordToolFinish(event);
461
+ const nestedTokens = subagentTokenEstimate(event.output);
462
+ if (nestedTokens)
463
+ callbacks.recordTokenEstimate?.(nestedTokens);
391
464
  const summary = toolResultSummary(event);
392
465
  toolSummaries.push(`${event.toolCall.toolName}: ${summary}`);
393
466
  recordToolDisplayFinish(event);
@@ -398,22 +471,17 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
398
471
  : `follow-up tool error: ${event.toolCall.toolName} after ${event.durationMs}ms ${compact(event.error)}`);
399
472
  },
400
473
  });
474
+ callbacks.onEvent?.(agentEvent({ type: 'message_start', id: responseId, role: 'assistant' }));
475
+ callbacks.addMessage({ id: responseId, role: 'assistant', text: 'Awaiting response…', streaming: true, startedAt: responseStartedAt });
401
476
  for await (const rawDelta of followUp.textStream) {
402
477
  resetIdleTimer();
403
478
  const delta = sanitizeAssistantText(rawDelta);
404
479
  responseText += delta;
405
480
  const displayText = assistantDisplayText(responseText);
406
- if ((!displayText || isNonSubstantiveAssistantText(displayText) || isPrefixOfVisibleAssistantText(displayText)) && !responseStarted)
481
+ if (!displayText || isNonSubstantiveAssistantText(displayText) || isPrefixOfVisibleAssistantText(displayText))
407
482
  continue;
408
- if (!responseStarted) {
409
- responseStarted = true;
410
- callbacks.onEvent?.(agentEvent({ type: 'message_start', id: responseId, role: 'assistant' }));
411
- callbacks.addMessage({ id: responseId, role: 'assistant', text: displayText, streaming: true });
412
- }
413
- else {
414
- callbacks.onEvent?.(agentEvent({ type: 'message_update', id: responseId, text: displayText }));
415
- callbacks.updateMessage(responseId, { text: displayText });
416
- }
483
+ callbacks.onEvent?.(agentEvent({ type: 'message_update', id: responseId, text: displayText }));
484
+ callbacks.updateMessage(responseId, { text: displayText });
417
485
  }
418
486
  try {
419
487
  await followUp.response;
@@ -428,17 +496,18 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
428
496
  if (!hidden)
429
497
  rememberVisibleAssistantText(visibleFinalText);
430
498
  callbacks.onEvent?.(agentEvent({ type: 'message_end', id: responseId, text: visibleFinalText, hidden }));
431
- callbacks.updateMessage(responseId, { text: visibleFinalText, streaming: false, hidden });
499
+ callbacks.updateMessage(responseId, { text: visibleFinalText, streaming: false, hidden, finishedAt: Date.now() });
432
500
  }
433
501
  return { text: finalText, id: responseId, started: responseStarted };
434
502
  }
435
503
  let streamError;
436
504
  let lastFinishReason;
505
+ const mainSystemPrompt = buildSystemPrompt(contextFiles);
506
+ const mainInputEstimate = estimateLlmInputTokens({ system: mainSystemPrompt, messages: requestMessages, tools: availableTools });
437
507
  const result = streamText({
438
508
  model: activeModel,
439
- temperature: 0,
440
509
  maxOutputTokens: DEFAULT_MAX_OUTPUT_TOKENS,
441
- system: buildSystemPrompt(contextFiles),
510
+ system: mainSystemPrompt,
442
511
  messages: requestMessages,
443
512
  tools: availableTools,
444
513
  stopWhen: stepCountIs(MAIN_STEP_LIMIT),
@@ -467,7 +536,7 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
467
536
  activeTools: ['readFile'],
468
537
  messages: [
469
538
  ...messages,
470
- { role: 'user', content: `A previous edit failed for ${editRecoveryPath}. Before any further edit or bash inspection, call readFile on exactly ${editRecoveryPath}. Bash/cat does not satisfy this recovery step.` },
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.` },
471
540
  ],
472
541
  };
473
542
  }
@@ -510,6 +579,7 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
510
579
  callbacks.debugLog(`step ${stepNumber} finished: ${finishReason}; text=${text.length}; toolCalls=${toolCalls.length}; toolResults=${toolResults.length}`);
511
580
  },
512
581
  onFinish(event) {
582
+ callbacks.recordTokenEstimate?.(usageTokenEstimate(event, { input: mainInputEstimate, output: estimateLlmOutputTokens(event.response.messages) }));
513
583
  const nextConversation = [...requestMessages, ...event.response.messages];
514
584
  callbacks.setConversation(nextConversation);
515
585
  callbacks.debugLog(`conversation updated to ${nextConversation.length} messages`);
@@ -524,6 +594,9 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
524
594
  resetIdleTimer();
525
595
  const summary = toolResultSummary(event);
526
596
  recordToolFinish(event);
597
+ const nestedTokens = subagentTokenEstimate(event.output);
598
+ if (nestedTokens)
599
+ callbacks.recordTokenEstimate?.(nestedTokens);
527
600
  toolSummaries.push(`${event.toolCall.toolName}: ${summary}`);
528
601
  recordToolDisplayFinish(event);
529
602
  if (!isDuplicateSkippedOutput(event.output))
@@ -533,6 +606,10 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
533
606
  : `tool error: ${event.toolCall.toolName} after ${event.durationMs}ms ${compact(event.error)}`);
534
607
  }
535
608
  });
609
+ callbacks.onEvent?.(agentEvent({ type: 'message_start', id: currentAssistantId, role: 'assistant' }));
610
+ callbacks.addMessage({ id: currentAssistantId, role: 'assistant', text: 'Awaiting response…', streaming: true, startedAt: currentAssistantStartedAt });
611
+ assistantStarted = true;
612
+ currentAssistantStarted = true;
536
613
  for await (const rawDelta of result.textStream) {
537
614
  resetIdleTimer();
538
615
  const delta = sanitizeAssistantText(rawDelta);
@@ -540,13 +617,12 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
540
617
  textAfterTool = true;
541
618
  if (currentAssistantStarted && currentAssistantText.length > 0 && toolEpoch > currentAssistantToolEpoch) {
542
619
  const intermediateText = assistantDisplayText(currentAssistantText);
543
- const hidden = intermediateText.length === 0 || isNonSubstantiveAssistantText(intermediateText) || isDuplicateVisibleAssistantText(intermediateText);
544
- if (!hidden)
545
- rememberVisibleAssistantText(intermediateText);
620
+ const hidden = true;
546
621
  callbacks.onEvent?.(agentEvent({ type: 'message_end', id: currentAssistantId, text: intermediateText, hidden }));
547
- callbacks.updateMessage(currentAssistantId, { text: intermediateText, streaming: false, hidden });
622
+ callbacks.updateMessage(currentAssistantId, { text: intermediateText, streaming: false, hidden, finishedAt: Date.now() });
548
623
  currentAssistantId = `assistant-${Date.now()}-${Math.random().toString(36).slice(2)}`;
549
624
  currentAssistantStarted = false;
625
+ currentAssistantStartedAt = Date.now();
550
626
  currentAssistantText = '';
551
627
  currentAssistantToolEpoch = toolEpoch;
552
628
  }
@@ -559,7 +635,8 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
559
635
  assistantStarted = true;
560
636
  currentAssistantStarted = true;
561
637
  callbacks.onEvent?.(agentEvent({ type: 'message_start', id: currentAssistantId, role: 'assistant' }));
562
- callbacks.addMessage({ id: currentAssistantId, role: 'assistant', text: displayText, streaming: true });
638
+ currentAssistantStartedAt = Date.now();
639
+ callbacks.addMessage({ id: currentAssistantId, role: 'assistant', text: displayText, streaming: true, startedAt: currentAssistantStartedAt });
563
640
  }
564
641
  else {
565
642
  callbacks.onEvent?.(agentEvent({ type: 'message_update', id: currentAssistantId, text: displayText }));
@@ -597,6 +674,7 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
597
674
  validationToolFailed,
598
675
  editFileFailed,
599
676
  editRecoveryPath,
677
+ editRecoveryReasonCode,
600
678
  });
601
679
  let decision = decideCompletion(combinedAssistantText);
602
680
  async function runCompletionLoop(seedConversation, seedText) {
@@ -628,7 +706,7 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
628
706
  if (!hidden)
629
707
  rememberVisibleAssistantText(visibleFinalAssistantText);
630
708
  callbacks.onEvent?.(agentEvent({ type: 'message_end', id: currentAssistantId, text: visibleFinalAssistantText, hidden }));
631
- callbacks.updateMessage(currentAssistantId, { text: visibleFinalAssistantText, streaming: false, hidden });
709
+ callbacks.updateMessage(currentAssistantId, { text: visibleFinalAssistantText, streaming: false, hidden, finishedAt: Date.now() });
632
710
  if (decision.needsActionContinuation || decision.needsValidationContinuation) {
633
711
  await runCompletionLoop(completedConversation, combinedAssistantText);
634
712
  }
@@ -650,11 +728,11 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
650
728
  const fallback = toolSummaries.length > 0
651
729
  ? `Finished tool work but the model did not produce a final response. Last tool result: ${toolSummaries.at(-1)}.`
652
730
  : 'Finished without a text response.';
653
- callbacks.addMessage({ id: currentAssistantId, role: 'assistant', text: fallback, streaming: false });
731
+ callbacks.addMessage({ id: currentAssistantId, role: 'assistant', text: fallback, streaming: false, startedAt: currentAssistantStartedAt, finishedAt: Date.now() });
654
732
  }
655
733
  }
656
734
  else {
657
- callbacks.addMessage({ id: currentAssistantId, role: 'assistant', text: 'Finished without a text response.', streaming: false });
735
+ callbacks.addMessage({ id: currentAssistantId, role: 'assistant', text: 'Finished without a text response.', streaming: false, startedAt: currentAssistantStartedAt, finishedAt: Date.now() });
658
736
  }
659
737
  goal.phase = 'done';
660
738
  goal.status = 'complete';
@@ -697,6 +775,7 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
697
775
  finally {
698
776
  if (idleTimer)
699
777
  clearTimeout(idleTimer);
778
+ stopActiveTimers();
700
779
  callbacks.onEvent?.(agentEvent({ type: 'turn_end', request: value, status: turnStatus }));
701
780
  callbacks.setAbortController?.(null);
702
781
  callbacks.setBusy(false);