pi-subagent-manager 0.16.0 → 0.18.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.
@@ -1,3 +1,4 @@
1
+ import { randomUUID } from "node:crypto";
1
2
  import type { AgentMessage } from "@earendil-works/pi-agent-core";
2
3
  import type {
3
4
  AgentDriver,
@@ -30,10 +31,14 @@ interface Record {
30
31
  started?: Promise<void>;
31
32
  sessionLeafId?: string | null;
32
33
  /** Last authoritative cumulative usage applied from the current driver. */
33
- usageCursor?: { input: number; output: number };
34
+ usageCursor?: { input: number; output: number; costUsd?: number };
34
35
  /** In-progress message usage. Shown live, never persisted. */
35
36
  liveInputTokens?: number;
36
37
  liveOutputTokens?: number;
38
+ liveCostUsd?: number;
39
+ /** Detached (spawned with wait:false): completion is reported as an event. */
40
+ async?: boolean;
41
+ timeoutTimer?: ReturnType<typeof setTimeout>;
37
42
  pauseRequested: boolean;
38
43
  stopRequested: boolean;
39
44
  observationRevision?: number;
@@ -45,6 +50,18 @@ interface Record {
45
50
  }
46
51
  const active = (view: Pick<ThreadView, "state">) =>
47
52
  view.state === "starting" || view.state === "running";
53
+ export const MIN_SPAWN_TIMEOUT_MS = 30_000;
54
+ export const MAX_SPAWN_TIMEOUT_MS = 300_000;
55
+ function assertSpawnTimeout(timeoutMs: number): void {
56
+ if (
57
+ !Number.isInteger(timeoutMs) ||
58
+ timeoutMs < MIN_SPAWN_TIMEOUT_MS ||
59
+ timeoutMs > MAX_SPAWN_TIMEOUT_MS
60
+ )
61
+ throw new Error(
62
+ `timeoutMs must be an integer between ${MIN_SPAWN_TIMEOUT_MS} (30s) and ${MAX_SPAWN_TIMEOUT_MS} (5min)`,
63
+ );
64
+ }
48
65
  const errorText = (error: unknown) => (error instanceof Error ? error.message : String(error));
49
66
 
50
67
  function abortable<T>(work: Promise<T>, signal: AbortSignal): Promise<T> {
@@ -91,11 +108,14 @@ export class ThreadManager {
91
108
  const eligible = new Set(
92
109
  records
93
110
  .filter((record) => !only || only.includes(record.view.path))
94
- .filter((record) => record.view.state === "completed" && (!record.initializing || record.driver))
95
- .filter((record) =>
96
- !records.some(
97
- (other) => active(other.view) && isDescendant(record.view.path, other.view.path),
98
- ),
111
+ .filter(
112
+ (record) => record.view.state === "completed" && (!record.initializing || record.driver),
113
+ )
114
+ .filter(
115
+ (record) =>
116
+ !records.some(
117
+ (other) => active(other.view) && isDescendant(record.view.path, other.view.path),
118
+ ),
99
119
  )
100
120
  .map((record) => record.view.path),
101
121
  );
@@ -119,6 +139,7 @@ export class ThreadManager {
119
139
  const reaped: string[] = [];
120
140
  for (const path of this.reapCandidates(only)) {
121
141
  const record = this.records.get(path)!;
142
+ this.clearTimeout(record);
122
143
  record.detachTranscript?.();
123
144
  record.transcriptListeners?.clear();
124
145
  record.driver?.dispose();
@@ -142,7 +163,7 @@ export class ThreadManager {
142
163
  transcript: (path) => this.transcript(caller, path),
143
164
  observeTranscript: (path, listener) => this.observeTranscript(caller, path, listener),
144
165
  spawn: (args, signal) => this.spawn(caller, args, signal),
145
- steer: (path, message) => this.steer(caller, path, message),
166
+ steer: (path, message, timeoutMs) => this.steer(caller, path, message, timeoutMs),
146
167
  wait: (path, timeoutMs, signal) => this.wait(caller, path, timeoutMs, signal),
147
168
  update: (message) => this.update(caller, message),
148
169
  pause: (reason) => this.pause(caller, reason),
@@ -182,6 +203,8 @@ export class ThreadManager {
182
203
  type: current.type,
183
204
  color: current.color,
184
205
  icon: current.icon,
206
+ model: current.model,
207
+ thinkingLevel: current.thinkingLevel,
185
208
  state: current.state,
186
209
  task: current.task,
187
210
  status: current.status,
@@ -194,6 +217,8 @@ export class ThreadManager {
194
217
  elapsedMs: record.view.elapsedMs ?? 0,
195
218
  inputTokens: record.view.inputTokens ?? 0,
196
219
  outputTokens: record.view.outputTokens ?? 0,
220
+ costUsd: record.view.costUsd,
221
+ costId: record.view.costId,
197
222
  };
198
223
  const sessionLeafId = this.sessionLeafId(record);
199
224
  if (sessionLeafId !== undefined) view.sessionLeafId = sessionLeafId;
@@ -224,6 +249,9 @@ export class ThreadManager {
224
249
  const { sessionLeafId, ...storedView } = savedView;
225
250
  const view: ThreadView = {
226
251
  ...storedView,
252
+ costId:
253
+ storedView.costId ??
254
+ `legacy:${storedView.sessionFile ?? `${storedView.path}:${storedView.createdAt}`}`,
227
255
  icon: storedView.icon ?? item.definition.icon,
228
256
  updatedAt: Date.now(),
229
257
  elapsedMs: storedView.elapsedMs ?? 0,
@@ -260,10 +288,11 @@ export class ThreadManager {
260
288
 
261
289
  async spawn(
262
290
  caller: string,
263
- args: { path: string; type: string; task: string; wait?: boolean },
291
+ args: { path: string; type: string; task: string; wait?: boolean; timeoutMs?: number },
264
292
  signal?: AbortSignal,
265
293
  ): Promise<ThreadView> {
266
294
  this.assertLive();
295
+ if (args.timeoutMs !== undefined) assertSpawnTimeout(args.timeoutMs);
267
296
  caller = canonicalPath(caller);
268
297
  if (
269
298
  caller !== "/root" &&
@@ -316,6 +345,7 @@ export class ThreadManager {
316
345
  task: args.task,
317
346
  status: "Starting",
318
347
  createdAt: now,
348
+ costId: randomUUID(),
319
349
  updatedAt: now,
320
350
  elapsedMs: 0,
321
351
  inputTokens: 0,
@@ -330,17 +360,37 @@ export class ThreadManager {
330
360
  };
331
361
  this.records.set(path, record);
332
362
  if (record.contextPending) this.prepareInheritedContext(record);
363
+ record.async = args.wait === false;
333
364
  this.start(record, args.task);
365
+ if (args.timeoutMs !== undefined) this.armTimeout(record, args.timeoutMs);
334
366
  return args.wait === false ? this.view(record) : this.wait(caller, path, undefined, signal);
335
367
  }
336
368
 
337
- async steer(caller: string, path: string, message: string): Promise<ThreadView> {
369
+ /**
370
+ * Steer/resume a thread and/or re-arm its report-only timeout.
371
+ * timeoutMs without message only re-arms (the child must be running); both does steer then re-arm.
372
+ */
373
+ async steer(
374
+ caller: string,
375
+ path: string,
376
+ message?: string,
377
+ timeoutMs?: number,
378
+ ): Promise<ThreadView> {
338
379
  this.assertLive();
339
380
  caller = canonicalPath(caller);
340
381
  path = canonicalPath(path, caller);
341
382
  this.assertAccess(caller, path);
383
+ if (message === undefined && timeoutMs === undefined)
384
+ throw new Error("Provide message, timeoutMs, or both");
385
+ if (timeoutMs !== undefined) assertSpawnTimeout(timeoutMs);
386
+ if (message === undefined) return this.extendTimeout(caller, path, timeoutMs!);
342
387
  if (!message.trim()) throw new Error("Steering message must not be empty");
343
388
  const record = this.record(path);
389
+ const rearm = (): ThreadView => {
390
+ if (timeoutMs !== undefined && active(record.view) && !record.stopRequested)
391
+ this.armTimeout(record, timeoutMs);
392
+ return this.view(record);
393
+ };
344
394
  for (;;) {
345
395
  this.assertLive();
346
396
  this.assertCallerMaySteer(caller);
@@ -356,11 +406,11 @@ export class ThreadManager {
356
406
  if (record.view.state === "running") {
357
407
  await record.driver!.steer(message);
358
408
  this.touch(record);
359
- return this.view(record);
409
+ return rearm();
360
410
  }
361
411
  this.assertCapacity();
362
412
  this.start(record, message);
363
- return this.view(record);
413
+ return rearm();
364
414
  }
365
415
  }
366
416
  async wait(
@@ -430,6 +480,7 @@ export class ThreadManager {
430
480
  for (const item of targets) {
431
481
  item.stopRequested = true;
432
482
  item.startup.abort();
483
+ this.clearTimeout(item);
433
484
  }
434
485
  await Promise.all(
435
486
  targets.map(async (item) => {
@@ -486,6 +537,63 @@ export class ThreadManager {
486
537
  },
487
538
  };
488
539
  }
540
+ /** Re-arm a running child's report-only timeout from now (replaces any pending timer). */
541
+ extendTimeout(caller: string, path: string, timeoutMs: number): ThreadView {
542
+ this.assertLive();
543
+ path = canonicalPath(path, caller);
544
+ this.assertAccess(caller, path);
545
+ assertSpawnTimeout(timeoutMs);
546
+ const record = this.record(path);
547
+ if (!active(record.view) || record.stopRequested)
548
+ throw new Error("Only a working agent has a timeout to extend");
549
+ this.armTimeout(record, timeoutMs);
550
+ return this.view(record);
551
+ }
552
+ /** Number of detached agents still working; recap waits for this to reach zero. */
553
+ outstandingAsync(): number {
554
+ return [...this.records.values()].filter((r) => r.async && active(r.view)).length;
555
+ }
556
+ private clearTimeout(record: Record): void {
557
+ if (record.timeoutTimer !== undefined) clearTimeout(record.timeoutTimer);
558
+ record.timeoutTimer = undefined;
559
+ }
560
+ private armTimeout(record: Record, timeoutMs: number): void {
561
+ this.clearTimeout(record);
562
+ record.timeoutTimer = setTimeout(() => {
563
+ record.timeoutTimer = undefined;
564
+ if (this.disposed || !active(record.view) || record.stopRequested) return;
565
+ this.emit({
566
+ kind: "timeout",
567
+ thread: this.view(record),
568
+ recipient: record.view.parent ?? record.view.owner,
569
+ timeoutMs,
570
+ recentOutput: this.recentOutput(record),
571
+ });
572
+ }, timeoutMs);
573
+ record.timeoutTimer.unref?.();
574
+ }
575
+ private recentOutput(record: Record): string {
576
+ const parts: string[] = [];
577
+ try {
578
+ const messages = record.driver?.snapshot() ?? [];
579
+ for (const message of messages.slice(-6)) {
580
+ if (message.role !== "assistant") continue;
581
+ const content = message.content as unknown;
582
+ const text = Array.isArray(content)
583
+ ? content
584
+ .filter((c: any) => c?.type === "text" && typeof c.text === "string")
585
+ .map((c: any) => c.text)
586
+ .join("\n")
587
+ : typeof content === "string"
588
+ ? content
589
+ : "";
590
+ if (text.trim()) parts.push(text.trim());
591
+ }
592
+ } catch {
593
+ /* best effort */
594
+ }
595
+ return parts.slice(-2).join("\n---\n").slice(-2000);
596
+ }
489
597
  async deliver(path: string, content: string): Promise<void> {
490
598
  // Restored parents may be idle and unopened; reports still belong in their retained transcript.
491
599
  const driver = await this.ensureDriver(this.record(path), true);
@@ -502,6 +610,7 @@ export class ThreadManager {
502
610
  record.transcriptListeners?.clear();
503
611
  record.stopRequested = true;
504
612
  record.startup.abort();
613
+ this.clearTimeout(record);
505
614
  }
506
615
  await Promise.all(
507
616
  records.map(async (record) => {
@@ -560,9 +669,11 @@ export class ThreadManager {
560
669
  record.view.error = errorText(error);
561
670
  record.view.status = record.stopRequested ? "Stopped; session retained" : record.view.error;
562
671
  } finally {
672
+ this.clearTimeout(record);
563
673
  this.freezeElapsed(record);
564
674
  record.liveInputTokens = 0;
565
675
  record.liveOutputTokens = 0;
676
+ record.liveCostUsd = undefined;
566
677
  markStarted(); // Failed/cancelled initialization must also release callers waiting to steer.
567
678
  this.touch(record);
568
679
  if (!this.disposed && epoch === this.epoch)
@@ -570,6 +681,7 @@ export class ThreadManager {
570
681
  kind: "settled",
571
682
  thread: this.view(record),
572
683
  recipient: record.view.parent ?? record.view.owner,
684
+ async: record.async === true,
573
685
  });
574
686
  }
575
687
  });
@@ -601,6 +713,17 @@ export class ThreadManager {
601
713
  signal,
602
714
  shouldPause: () => record.pauseRequested,
603
715
  onEvent: (event) => {
716
+ if (event.kind === "settings") {
717
+ if (
718
+ record.view.model !== event.model ||
719
+ record.view.thinkingLevel !== event.thinkingLevel
720
+ ) {
721
+ record.view.model = event.model;
722
+ record.view.thinkingLevel = event.thinkingLevel;
723
+ this.touch(record);
724
+ }
725
+ return;
726
+ }
604
727
  if (event.kind === "usage") {
605
728
  this.applyUsage(record, event);
606
729
  return;
@@ -632,6 +755,7 @@ export class ThreadManager {
632
755
  record.usageCursor = { input: 0, output: 0 };
633
756
  record.liveInputTokens = 0;
634
757
  record.liveOutputTokens = 0;
758
+ record.liveCostUsd = undefined;
635
759
  record.view.sessionFile = driver.sessionFile;
636
760
  if (driver.sessionLeafId !== undefined) record.sessionLeafId = driver.sessionLeafId;
637
761
  this.touch(record);
@@ -708,15 +832,25 @@ export class ThreadManager {
708
832
  /** Fold driver-cumulative usage into persisted totals. Partials only refresh the live view. */
709
833
  private applyUsage(
710
834
  record: Record,
711
- event: { inputTokens: number; outputTokens: number; partial?: boolean },
835
+ event: { inputTokens: number; outputTokens: number; costUsd?: number; partial?: boolean },
712
836
  ): void {
713
837
  const cursor = record.usageCursor ?? { input: 0, output: 0 };
838
+ const costUsd =
839
+ event.costUsd !== undefined && Number.isFinite(event.costUsd) && event.costUsd >= 0
840
+ ? Math.max(0, event.costUsd - (cursor.costUsd ?? 0))
841
+ : undefined;
714
842
  if (event.partial) {
715
843
  const input = Math.max(0, event.inputTokens - cursor.input);
716
844
  const output = Math.max(0, event.outputTokens - cursor.output);
717
- if (input === record.liveInputTokens && output === record.liveOutputTokens) return;
845
+ if (
846
+ input === record.liveInputTokens &&
847
+ output === record.liveOutputTokens &&
848
+ costUsd === record.liveCostUsd
849
+ )
850
+ return;
718
851
  record.liveInputTokens = input;
719
852
  record.liveOutputTokens = output;
853
+ record.liveCostUsd = costUsd;
720
854
  if (!this.disposed) this.emit({ kind: "metrics", thread: this.view(record) });
721
855
  return;
722
856
  }
@@ -724,9 +858,15 @@ export class ThreadManager {
724
858
  (record.view.inputTokens ?? 0) + Math.max(0, event.inputTokens - cursor.input);
725
859
  record.view.outputTokens =
726
860
  (record.view.outputTokens ?? 0) + Math.max(0, event.outputTokens - cursor.output);
727
- record.usageCursor = { input: event.inputTokens, output: event.outputTokens };
861
+ if (costUsd !== undefined) record.view.costUsd = (record.view.costUsd ?? 0) + costUsd;
862
+ record.usageCursor = {
863
+ input: event.inputTokens,
864
+ output: event.outputTokens,
865
+ costUsd: event.costUsd ?? cursor.costUsd,
866
+ };
728
867
  record.liveInputTokens = 0;
729
868
  record.liveOutputTokens = 0;
869
+ record.liveCostUsd = undefined;
730
870
  this.touch(record);
731
871
  }
732
872
  private freezeElapsed(record: Record): void {
@@ -780,6 +920,7 @@ export class ThreadManager {
780
920
  if (record.liveInputTokens) view.inputTokens = (view.inputTokens ?? 0) + record.liveInputTokens;
781
921
  if (record.liveOutputTokens)
782
922
  view.outputTokens = (view.outputTokens ?? 0) + record.liveOutputTokens;
923
+ if (record.liveCostUsd !== undefined) view.costUsd = (view.costUsd ?? 0) + record.liveCostUsd;
783
924
  return view;
784
925
  }
785
926
  private record(path: string): Record {
@@ -17,7 +17,7 @@ export function subagentPrompt(settings: ManagerSettings): string | undefined {
17
17
  policy,
18
18
  "Call agent_types before choosing a type. Use task-based kebab-case paths, not type names. Choose context via agent_spawn path: /root/task forks the lexical parent's conversation; /task starts fresh with no inherited history. Use fresh agents for adversarial review or clean-slate research; give them a self-contained task without the current thread's conclusions.",
19
19
  waitingPolicy,
20
- "Use agent_status to inspect and agent_output for full results. Detached notifications do not resume your turn.",
20
+ "Use agent_status to inspect and agent_output for full results. Completion, failure or stop of a wait:false agent is delivered to you as a message event that starts a new turn when you are idle (with Final Recap on, once after all outstanding async agents have finished). Pass timeoutMs to agent_spawn to get a status event if a child runs long; the child is not killed. Valid range 30000–300000 ms; omit for no timeout. When a timeout event shows a child still progressing, call agent_steer with only timeoutMs (no message; re-arms without steering) to re-arm it, or agent_wait/agent_steer/agent_stop.",
21
21
  "Use agent_steer to send input or resume retained sessions. Paused agents have no final answer; completed agents hand back results. Both retain their session.",
22
22
  `Maximum depth: ${settings.maxLevels} levels including L1. Shared concurrency: ${settings.maxConcurrent} active threads; waiting parents count.`,
23
23
  ].join("\n");
@@ -388,7 +388,10 @@ export function createDriverFactory(
388
388
  const rootActive = new Set(inherited.activeNames);
389
389
  // Preserve deferred/codemode exposure rather than flooding model declarations with MCP tools.
390
390
  const activeToolNames = toolNames.filter(
391
- (name) => localNames.has(name) || rootActive.has(name) || options.type.tools?.allow?.includes(name) && toolFiltering === "allowed",
391
+ (name) =>
392
+ localNames.has(name) ||
393
+ rootActive.has(name) ||
394
+ (options.type.tools?.allow?.includes(name) && toolFiltering === "allowed"),
392
395
  );
393
396
  const customTools = [...options.tools, ...externalTools].filter(
394
397
  (tool) => allowed.has(tool.name) && tool.name !== "codemode" && tool.name !== "tool_search",
@@ -467,6 +470,11 @@ export function createDriverFactory(
467
470
  id: currentModel.id,
468
471
  thinking: session.thinkingLevel,
469
472
  });
473
+ options.onEvent({
474
+ kind: "settings",
475
+ model: modelIdentity(currentModel),
476
+ thinkingLevel: session.thinkingLevel,
477
+ });
470
478
  };
471
479
  const assertScopedRequestAuthorized = (
472
480
  currentIdentity: string | undefined,
@@ -606,6 +614,7 @@ export function createDriverFactory(
606
614
  // Subscribe after inherited/restored history is loaded; only new assistant events are counted.
607
615
  let settledInput = 0;
608
616
  let settledOutput = 0;
617
+ let settledCost: number | undefined;
609
618
  const countedUsage = new WeakSet<object>();
610
619
  let finalOutput = "";
611
620
  let abortPromise: Promise<void> | undefined;
@@ -616,7 +625,14 @@ export function createDriverFactory(
616
625
  const input = usage.input + usage.cacheRead + usage.cacheWrite;
617
626
  const output = usage.output;
618
627
  if (!Number.isFinite(input) || !Number.isFinite(output)) return;
619
- return { input, output, reported: input + output + usage.totalTokens > 0 };
628
+ const total = usage.cost?.total;
629
+ const costUsd = Number.isFinite(total) && total >= 0 ? total : undefined;
630
+ return {
631
+ input,
632
+ output,
633
+ costUsd,
634
+ reported: input + output + usage.totalTokens > 0 || (costUsd ?? 0) > 0,
635
+ };
620
636
  };
621
637
 
622
638
  const ownership = sessionManager
@@ -657,6 +673,8 @@ export function createDriverFactory(
657
673
  kind: "usage",
658
674
  inputTokens: settledInput + usage.input,
659
675
  outputTokens: settledOutput + usage.output,
676
+ costUsd:
677
+ usage.costUsd === undefined ? settledCost : (settledCost ?? 0) + usage.costUsd,
660
678
  partial: true,
661
679
  });
662
680
  } else {
@@ -664,11 +682,13 @@ export function createDriverFactory(
664
682
  if (usage) {
665
683
  settledInput += usage.input;
666
684
  settledOutput += usage.output;
685
+ if (usage.costUsd !== undefined) settledCost = (settledCost ?? 0) + usage.costUsd;
667
686
  }
668
687
  options.onEvent({
669
688
  kind: "usage",
670
689
  inputTokens: settledInput,
671
690
  outputTokens: settledOutput,
691
+ costUsd: settledCost,
672
692
  });
673
693
  const text = event.message.content
674
694
  .filter((block) => block.type === "text")
package/src/orch/tools.ts CHANGED
@@ -81,7 +81,7 @@ export function agentTools(
81
81
  ),
82
82
  make(
83
83
  "agent_spawn",
84
- "Spawn a named child. The lexical parent, NOT the caller, supplies a context snapshot. /root is the main thread; independent roots have no inherited context. Foreground waits by default; wait:false runs detached. For parallel work, spawn every independent sibling with wait:false before calling agent_wait; child agents with delegation tools should do the same. Existing paths are retained and can be resumed with agent_steer. Use agent_types to discover current types.",
84
+ "Spawn a named child. The lexical parent, NOT the caller, supplies a context snapshot. /root is the main thread; independent roots have no inherited context. Foreground waits by default; wait:false runs detached: when it completes, fails or is stopped, you receive a message event that wakes you, so do not poll. Optional timeoutMs (30000–300000; none if unset): if the child is still running after that many ms you receive an event with its status, elapsed time, tokens and recent output (the child is NOT stopped; you decide whether to wait, steer, stop it or re-arm with agent_steer timeoutMs). For parallel work, spawn every independent sibling with wait:false before calling agent_wait; child agents with delegation tools should do the same. Existing paths are retained and can be resumed with agent_steer. Use agent_types to discover current types.",
85
85
  Type.Object({
86
86
  path: Type.String({
87
87
  description:
@@ -90,6 +90,14 @@ export function agentTools(
90
90
  type: text,
91
91
  task: text,
92
92
  wait: Type.Optional(Type.Boolean()),
93
+ timeoutMs: Type.Optional(
94
+ Type.Integer({
95
+ minimum: 30000,
96
+ maximum: 300000,
97
+ description:
98
+ "Optional report-only timeout, 30000–300000 ms (30s–5min). If the child is still running after this many ms, a status event is sent to you; the child keeps running.",
99
+ }),
100
+ ),
93
101
  }),
94
102
  async (params, signal) => result(compact(await threads().spawn(params, signal))),
95
103
  ),
@@ -105,9 +113,14 @@ export function agentTools(
105
113
  ),
106
114
  make(
107
115
  "agent_steer",
108
- "Send input to a descendant. Working threads receive queued steering; completed, stopped and paused threads resume the SAME session with its previous context. Returns immediately; use agent_wait for the result.",
109
- Type.Object({ path, message: text }),
110
- async (params) => result(compact(await threads().steer(params.path, params.message))),
116
+ "Send input to a descendant and/or re-arm its report-only timeout. With message: working threads receive queued steering; completed, stopped and paused threads resume the SAME session with its previous context. With timeoutMs (30000–300000): the timeout fires that many ms from now, replacing any pending timer. timeoutMs WITHOUT message only re-arms the timeout of a running child (error if not running) and does not steer or resume it; with both, steer and re-arm. At least one is required. Returns immediately; use agent_wait for the result.",
117
+ Type.Object({
118
+ path,
119
+ message: Type.Optional(text),
120
+ timeoutMs: Type.Optional(Type.Integer({ minimum: 30000, maximum: 300000 })),
121
+ }),
122
+ async (params) =>
123
+ result(compact(await threads().steer(params.path, params.message, params.timeoutMs))),
111
124
  ),
112
125
  make(
113
126
  "agent_status",
package/src/types.ts CHANGED
@@ -49,6 +49,9 @@ export interface ThreadView {
49
49
  type: string;
50
50
  color?: string;
51
51
  icon?: string;
52
+ /** Actual runtime selection, not the type's model preferences. */
53
+ model?: string;
54
+ thinkingLevel?: ThinkingLevel;
52
55
  state: ThreadState;
53
56
  task: string;
54
57
  status: string;
@@ -67,8 +70,13 @@ export interface ThreadView {
67
70
  inputTokens?: number;
68
71
  /** Cumulative output tokens. Live views include the in-progress message. */
69
72
  outputTokens?: number;
73
+ /** Cumulative estimated USD cost for this agent's own messages. */
74
+ costUsd?: number;
75
+ /** Stable lifetime identity for cost accounting, retained across resumes/reloads. */
76
+ costId?: string;
70
77
  }
71
78
  export type DriverEvent =
79
+ | { kind: "settings"; model: string; thinkingLevel: ThinkingLevel }
72
80
  | { kind: "activity" | "error"; text: string }
73
81
  | {
74
82
  kind: "checkpoint";
@@ -81,6 +89,8 @@ export type DriverEvent =
81
89
  /** Cumulative own-assistant tokens for this driver instance, excluding inherited history. */
82
90
  inputTokens: number;
83
91
  outputTokens: number;
92
+ /** Cumulative estimated USD cost, when reported by the runtime. */
93
+ costUsd?: number;
84
94
  /** Streaming message_update snapshot. Omit for authoritative message_end. */
85
95
  partial?: boolean;
86
96
  };
@@ -144,6 +154,8 @@ export interface SavedThreadView {
144
154
  type: string;
145
155
  color?: string;
146
156
  icon?: string;
157
+ model?: string;
158
+ thinkingLevel?: ThinkingLevel;
147
159
  state: ThreadState;
148
160
  task: string;
149
161
  status: string;
@@ -157,6 +169,8 @@ export interface SavedThreadView {
157
169
  lastStartedAt?: number;
158
170
  inputTokens?: number;
159
171
  outputTokens?: number;
172
+ costUsd?: number;
173
+ costId?: string;
160
174
  }
161
175
  export interface SavedThread {
162
176
  view: SavedThreadView;
@@ -172,10 +186,11 @@ export interface ThreadService {
172
186
  /** Optional for portable adapters; the runtime manager always implements this. */
173
187
  observeTranscript?(path: string, listener: TranscriptListener): Promise<TranscriptObservation>;
174
188
  spawn(
175
- args: { path: string; type: string; task: string; wait?: boolean },
189
+ args: { path: string; type: string; task: string; wait?: boolean; timeoutMs?: number },
176
190
  signal?: AbortSignal,
177
191
  ): Promise<ThreadView>;
178
- steer(path: string, message: string): Promise<ThreadView>;
192
+ /** message and/or timeoutMs (30s–5min). timeoutMs alone only re-arms a running child's report-only timeout. */
193
+ steer(path: string, message?: string, timeoutMs?: number): Promise<ThreadView>;
179
194
  wait(path: string, timeoutMs?: number, signal?: AbortSignal): Promise<ThreadView>;
180
195
  update(message: string): ThreadView;
181
196
  pause(reason: string): ThreadView;
@@ -186,7 +201,15 @@ export type ThreadEvent =
186
201
  | { kind: "change"; thread: ThreadView }
187
202
  | { kind: "metrics"; thread: ThreadView }
188
203
  | { kind: "update"; thread: ThreadView; message: string; recipient: string }
189
- | { kind: "settled"; thread: ThreadView; recipient: string };
204
+ | { kind: "settled"; thread: ThreadView; recipient: string; async: boolean }
205
+ /** A spawn timeout elapsed while the child is still running. The child is NOT stopped. */
206
+ | {
207
+ kind: "timeout";
208
+ thread: ThreadView;
209
+ recipient: string;
210
+ timeoutMs: number;
211
+ recentOutput: string;
212
+ };
190
213
  export interface ManagerOptions {
191
214
  createDriver: DriverFactory;
192
215
  rootSnapshot(): AgentMessage[];