@denizokcu/haze 0.2.0 → 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) {
@@ -70,6 +74,10 @@ export function toolResultSummary(event) {
70
74
  return `${output.status}${meta}: ${preview}`;
71
75
  }
72
76
  if (typeof output?.ok === 'boolean') {
77
+ // writeTasks result
78
+ if (output.ok && typeof output.summary === 'string') {
79
+ return compact(output.summary, 120);
80
+ }
73
81
  if (output.ok) {
74
82
  if (typeof output.addedLines === 'number' || typeof output.removedLines === 'number') {
75
83
  const added = typeof output.addedLines === 'number' ? output.addedLines : 0;
@@ -86,6 +94,32 @@ export function toolResultSummary(event) {
86
94
  export function formatSeconds(milliseconds) {
87
95
  return `${(milliseconds / 1000).toFixed(1)}s`;
88
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
+ }
89
123
  export function toolOutputDetails(value) {
90
124
  if (!value || typeof value !== 'object')
91
125
  return '';
@@ -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);
@@ -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;
@@ -179,6 +213,24 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
179
213
  const toolDisplayItems = [];
180
214
  let toolGroupStarted = false;
181
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;
182
234
  function renderToolGroup(streaming) {
183
235
  const visibleItems = toolDisplayItems.filter(item => !item.hidden);
184
236
  const running = visibleItems.some(item => item.status === 'running');
@@ -198,9 +250,13 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
198
250
  }
199
251
  const rows = [...grouped.values()];
200
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);
201
257
  const header = running || streaming
202
- ? 'Running tools'
203
- : `${visibleItems.length} call${visibleItems.length === 1 ? '' : 's'} · ${changes.length} change${changes.length === 1 ? '' : 's'} · ${failures.length} failed${compactSuffix}`;
258
+ ? `Running tools · ${elapsed}`
259
+ : `${visibleItems.length} call${visibleItems.length === 1 ? '' : 's'} · ${changes.length} change${changes.length === 1 ? '' : 's'} · ${failures.length} failed · ${elapsed}${compactSuffix}`;
204
260
  const lines = [];
205
261
  for (const { item, count } of rows) {
206
262
  const icon = item.status === 'running' ? '…' : item.status === 'success' ? '✓' : '✗';
@@ -219,7 +275,7 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
219
275
  }
220
276
  if (item.subItems && item.subItems.length > 0) {
221
277
  for (const sub of item.subItems) {
222
- const subDuration = sub.durationMs > 1000 ? ` (${formatSeconds(sub.durationMs)})` : '';
278
+ const subDuration = sub.durationMs > 1000 ? ` · ${formatSeconds(sub.durationMs)}` : '';
223
279
  lines.push(` · ${sub.name} — ${sub.summary}${subDuration}`);
224
280
  }
225
281
  }
@@ -246,7 +302,8 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
246
302
  toolGroupStarted = false;
247
303
  }
248
304
  callbacks.onEvent?.(agentEvent({ type: 'tool_start', id: toolCall.toolCallId, name: toolCall.toolName, input: toolCall.input }));
249
- toolDisplayItems.push({ id: toolCall.toolCallId, summary: toolCallSummary(toolCall.toolName, toolCall.input), status: 'running' });
305
+ toolDisplayItems.push({ id: toolCall.toolCallId, summary: toolCallSummary(toolCall.toolName, toolCall.input), status: 'running', startedAt: Date.now() });
306
+ startToolTimer();
250
307
  updateToolGroup(true);
251
308
  const runningSubagents = toolDisplayItems.filter(item => item.status === 'running' && item.summary.startsWith('subagent')).length;
252
309
  if (runningSubagents > 0)
@@ -260,6 +317,7 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
260
317
  item.status = toolOutputOk(event.output, event.success) ? 'success' : 'error';
261
318
  item.result = toolResultSummary(event);
262
319
  item.durationMs = event.durationMs;
320
+ item.finishedAt = item.startedAt + event.durationMs;
263
321
  item.hidden = isDuplicateSkippedOutput(event.output);
264
322
  if (typeof event.output === 'object' && event.output != null) {
265
323
  const output = event.output;
@@ -278,7 +336,13 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
278
336
  }));
279
337
  }
280
338
  }
281
- 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();
282
346
  const runningSubagents = toolDisplayItems.filter(i => i.status === 'running' && i.summary.startsWith('subagent')).length;
283
347
  if (runningSubagents === 0)
284
348
  callbacks.setBusyLabel?.('Haze is thinking');
@@ -322,7 +386,8 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
322
386
  async function streamAssistantResponse(messages, reason, prompt, allowTools = false) {
323
387
  callbacks.debugLog(`requesting assistant ${allowTools ? 'continuation' : 'text'}: ${reason}`);
324
388
  const responseId = `assistant-${Date.now()}-${Math.random().toString(36).slice(2)}`;
325
- let responseStarted = false;
389
+ const responseStarted = true;
390
+ const responseStartedAt = Date.now();
326
391
  let responseText = '';
327
392
  let continuationToolCalls = 0;
328
393
  let followUpStreamError;
@@ -330,10 +395,12 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
330
395
  ...messages,
331
396
  { role: 'user', content: prompt },
332
397
  ];
398
+ const followUpSystemPrompt = buildSystemPrompt(contextFiles);
399
+ const followUpInputEstimate = estimateLlmInputTokens({ system: followUpSystemPrompt, messages: continuationMessages, tools: availableTools });
333
400
  const followUp = streamText({
334
401
  model: activeModel,
335
402
  maxOutputTokens: DEFAULT_MAX_OUTPUT_TOKENS,
336
- system: buildSystemPrompt(contextFiles),
403
+ system: followUpSystemPrompt,
337
404
  messages: continuationMessages,
338
405
  tools: availableTools,
339
406
  toolChoice: allowTools ? 'auto' : 'none',
@@ -378,6 +445,7 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
378
445
  callbacks.debugLog(`stream error: ${error instanceof Error ? error.message : String(error)}`);
379
446
  },
380
447
  onFinish(event) {
448
+ callbacks.recordTokenEstimate?.(usageTokenEstimate(event, { input: followUpInputEstimate, output: estimateLlmOutputTokens(event.response.messages) }));
381
449
  callbacks.setConversation([...continuationMessages, ...event.response.messages]);
382
450
  callbacks.debugLog(`conversation updated to ${continuationMessages.length + event.response.messages.length} messages after follow-up`);
383
451
  },
@@ -390,6 +458,9 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
390
458
  experimental_onToolCallFinish(event) {
391
459
  resetIdleTimer();
392
460
  recordToolFinish(event);
461
+ const nestedTokens = subagentTokenEstimate(event.output);
462
+ if (nestedTokens)
463
+ callbacks.recordTokenEstimate?.(nestedTokens);
393
464
  const summary = toolResultSummary(event);
394
465
  toolSummaries.push(`${event.toolCall.toolName}: ${summary}`);
395
466
  recordToolDisplayFinish(event);
@@ -400,22 +471,17 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
400
471
  : `follow-up tool error: ${event.toolCall.toolName} after ${event.durationMs}ms ${compact(event.error)}`);
401
472
  },
402
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 });
403
476
  for await (const rawDelta of followUp.textStream) {
404
477
  resetIdleTimer();
405
478
  const delta = sanitizeAssistantText(rawDelta);
406
479
  responseText += delta;
407
480
  const displayText = assistantDisplayText(responseText);
408
- if ((!displayText || isNonSubstantiveAssistantText(displayText) || isPrefixOfVisibleAssistantText(displayText)) && !responseStarted)
481
+ if (!displayText || isNonSubstantiveAssistantText(displayText) || isPrefixOfVisibleAssistantText(displayText))
409
482
  continue;
410
- if (!responseStarted) {
411
- responseStarted = true;
412
- callbacks.onEvent?.(agentEvent({ type: 'message_start', id: responseId, role: 'assistant' }));
413
- callbacks.addMessage({ id: responseId, role: 'assistant', text: displayText, streaming: true });
414
- }
415
- else {
416
- callbacks.onEvent?.(agentEvent({ type: 'message_update', id: responseId, text: displayText }));
417
- callbacks.updateMessage(responseId, { text: displayText });
418
- }
483
+ callbacks.onEvent?.(agentEvent({ type: 'message_update', id: responseId, text: displayText }));
484
+ callbacks.updateMessage(responseId, { text: displayText });
419
485
  }
420
486
  try {
421
487
  await followUp.response;
@@ -430,16 +496,18 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
430
496
  if (!hidden)
431
497
  rememberVisibleAssistantText(visibleFinalText);
432
498
  callbacks.onEvent?.(agentEvent({ type: 'message_end', id: responseId, text: visibleFinalText, hidden }));
433
- callbacks.updateMessage(responseId, { text: visibleFinalText, streaming: false, hidden });
499
+ callbacks.updateMessage(responseId, { text: visibleFinalText, streaming: false, hidden, finishedAt: Date.now() });
434
500
  }
435
501
  return { text: finalText, id: responseId, started: responseStarted };
436
502
  }
437
503
  let streamError;
438
504
  let lastFinishReason;
505
+ const mainSystemPrompt = buildSystemPrompt(contextFiles);
506
+ const mainInputEstimate = estimateLlmInputTokens({ system: mainSystemPrompt, messages: requestMessages, tools: availableTools });
439
507
  const result = streamText({
440
508
  model: activeModel,
441
509
  maxOutputTokens: DEFAULT_MAX_OUTPUT_TOKENS,
442
- system: buildSystemPrompt(contextFiles),
510
+ system: mainSystemPrompt,
443
511
  messages: requestMessages,
444
512
  tools: availableTools,
445
513
  stopWhen: stepCountIs(MAIN_STEP_LIMIT),
@@ -511,6 +579,7 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
511
579
  callbacks.debugLog(`step ${stepNumber} finished: ${finishReason}; text=${text.length}; toolCalls=${toolCalls.length}; toolResults=${toolResults.length}`);
512
580
  },
513
581
  onFinish(event) {
582
+ callbacks.recordTokenEstimate?.(usageTokenEstimate(event, { input: mainInputEstimate, output: estimateLlmOutputTokens(event.response.messages) }));
514
583
  const nextConversation = [...requestMessages, ...event.response.messages];
515
584
  callbacks.setConversation(nextConversation);
516
585
  callbacks.debugLog(`conversation updated to ${nextConversation.length} messages`);
@@ -525,6 +594,9 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
525
594
  resetIdleTimer();
526
595
  const summary = toolResultSummary(event);
527
596
  recordToolFinish(event);
597
+ const nestedTokens = subagentTokenEstimate(event.output);
598
+ if (nestedTokens)
599
+ callbacks.recordTokenEstimate?.(nestedTokens);
528
600
  toolSummaries.push(`${event.toolCall.toolName}: ${summary}`);
529
601
  recordToolDisplayFinish(event);
530
602
  if (!isDuplicateSkippedOutput(event.output))
@@ -534,6 +606,10 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
534
606
  : `tool error: ${event.toolCall.toolName} after ${event.durationMs}ms ${compact(event.error)}`);
535
607
  }
536
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;
537
613
  for await (const rawDelta of result.textStream) {
538
614
  resetIdleTimer();
539
615
  const delta = sanitizeAssistantText(rawDelta);
@@ -541,13 +617,12 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
541
617
  textAfterTool = true;
542
618
  if (currentAssistantStarted && currentAssistantText.length > 0 && toolEpoch > currentAssistantToolEpoch) {
543
619
  const intermediateText = assistantDisplayText(currentAssistantText);
544
- const hidden = intermediateText.length === 0 || isNonSubstantiveAssistantText(intermediateText) || isDuplicateVisibleAssistantText(intermediateText);
545
- if (!hidden)
546
- rememberVisibleAssistantText(intermediateText);
620
+ const hidden = true;
547
621
  callbacks.onEvent?.(agentEvent({ type: 'message_end', id: currentAssistantId, text: intermediateText, hidden }));
548
- callbacks.updateMessage(currentAssistantId, { text: intermediateText, streaming: false, hidden });
622
+ callbacks.updateMessage(currentAssistantId, { text: intermediateText, streaming: false, hidden, finishedAt: Date.now() });
549
623
  currentAssistantId = `assistant-${Date.now()}-${Math.random().toString(36).slice(2)}`;
550
624
  currentAssistantStarted = false;
625
+ currentAssistantStartedAt = Date.now();
551
626
  currentAssistantText = '';
552
627
  currentAssistantToolEpoch = toolEpoch;
553
628
  }
@@ -560,7 +635,8 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
560
635
  assistantStarted = true;
561
636
  currentAssistantStarted = true;
562
637
  callbacks.onEvent?.(agentEvent({ type: 'message_start', id: currentAssistantId, role: 'assistant' }));
563
- 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 });
564
640
  }
565
641
  else {
566
642
  callbacks.onEvent?.(agentEvent({ type: 'message_update', id: currentAssistantId, text: displayText }));
@@ -630,7 +706,7 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
630
706
  if (!hidden)
631
707
  rememberVisibleAssistantText(visibleFinalAssistantText);
632
708
  callbacks.onEvent?.(agentEvent({ type: 'message_end', id: currentAssistantId, text: visibleFinalAssistantText, hidden }));
633
- callbacks.updateMessage(currentAssistantId, { text: visibleFinalAssistantText, streaming: false, hidden });
709
+ callbacks.updateMessage(currentAssistantId, { text: visibleFinalAssistantText, streaming: false, hidden, finishedAt: Date.now() });
634
710
  if (decision.needsActionContinuation || decision.needsValidationContinuation) {
635
711
  await runCompletionLoop(completedConversation, combinedAssistantText);
636
712
  }
@@ -652,11 +728,11 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
652
728
  const fallback = toolSummaries.length > 0
653
729
  ? `Finished tool work but the model did not produce a final response. Last tool result: ${toolSummaries.at(-1)}.`
654
730
  : 'Finished without a text response.';
655
- 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() });
656
732
  }
657
733
  }
658
734
  else {
659
- 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() });
660
736
  }
661
737
  goal.phase = 'done';
662
738
  goal.status = 'complete';
@@ -699,6 +775,7 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
699
775
  finally {
700
776
  if (idleTimer)
701
777
  clearTimeout(idleTimer);
778
+ stopActiveTimers();
702
779
  callbacks.onEvent?.(agentEvent({ type: 'turn_end', request: value, status: turnStatus }));
703
780
  callbacks.setAbortController?.(null);
704
781
  callbacks.setBusy(false);
@@ -0,0 +1,23 @@
1
+ /**
2
+ * Known provider presets derived from community conventions (nanocoder, OpenRouter docs, etc.).
3
+ * Each preset carries a pre-configured base URL so users only need to supply an API key and model names.
4
+ * Local/keyless providers have sensible localhost defaults.
5
+ */
6
+ export interface ProviderPreset {
7
+ /** Unique identifier used as the selection value. */
8
+ id: string;
9
+ /** Human-readable name shown in the picker. */
10
+ name: string;
11
+ /** Pre-configured OpenAI-compatible base URL. */
12
+ baseUrl: string;
13
+ /** Whether an API key is typically required. Local providers default to false. */
14
+ needsApiKey: boolean;
15
+ /** Hint shown when prompting for the API key. */
16
+ apiKeyHint?: string;
17
+ /** Optional suggested default model(s). */
18
+ suggestedModels?: string[];
19
+ /** Category for grouping in the picker. */
20
+ category: 'cloud' | 'local';
21
+ }
22
+ export declare const PROVIDER_PRESETS: ProviderPreset[];
23
+ export declare function findPreset(id: string): ProviderPreset | undefined;