pi-subagent-manager 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.
package/src/manager.ts CHANGED
@@ -10,6 +10,7 @@ import type {
10
10
  ThreadView,
11
11
  } from "./types.ts";
12
12
  import { canonicalPath, inheritContext, isDescendant, parentPath } from "./paths.ts";
13
+ import { DEFAULT_MANAGER_SETTINGS, type ManagerSettings } from "./settings.ts";
13
14
 
14
15
  interface Record {
15
16
  view: ThreadView;
@@ -23,6 +24,11 @@ interface Record {
23
24
  run?: Promise<void>;
24
25
  started?: Promise<void>;
25
26
  sessionLeafId?: string | null;
27
+ /** Last authoritative cumulative usage applied from the current driver. */
28
+ usageCursor?: { input: number; output: number };
29
+ /** In-progress message usage. Shown live, never persisted. */
30
+ liveInputTokens?: number;
31
+ liveOutputTokens?: number;
26
32
  pauseRequested: boolean;
27
33
  stopRequested: boolean;
28
34
  }
@@ -58,6 +64,11 @@ export class ThreadManager {
58
64
  private epoch = 0;
59
65
  constructor(private options: ManagerOptions) {}
60
66
 
67
+ /** New limits affect future launches/resumes, never cancel existing work. */
68
+ setLimits(limits: ManagerSettings): void {
69
+ this.options = { ...this.options, ...limits };
70
+ }
71
+
61
72
  list(): ThreadView[] {
62
73
  return [...this.records.values()].map((record) => this.view(record));
63
74
  }
@@ -121,6 +132,10 @@ export class ThreadManager {
121
132
  error: current.error,
122
133
  createdAt: current.createdAt,
123
134
  sessionFile: current.sessionFile,
135
+ // Settled totals only. startedAt and partial usage must not churn persistence.
136
+ elapsedMs: record.view.elapsedMs ?? 0,
137
+ inputTokens: record.view.inputTokens ?? 0,
138
+ outputTokens: record.view.outputTokens ?? 0,
124
139
  };
125
140
  const sessionLeafId = this.sessionLeafId(record);
126
141
  if (sessionLeafId !== undefined) view.sessionLeafId = sessionLeafId;
@@ -149,7 +164,14 @@ export class ThreadManager {
149
164
  )
150
165
  throw new Error("Invalid saved thread registry");
151
166
  const { sessionLeafId, ...storedView } = savedView;
152
- const view: ThreadView = { ...storedView, updatedAt: Date.now() };
167
+ const view: ThreadView = {
168
+ ...storedView,
169
+ updatedAt: Date.now(),
170
+ elapsedMs: storedView.elapsedMs ?? 0,
171
+ inputTokens: storedView.inputTokens ?? 0,
172
+ outputTokens: storedView.outputTokens ?? 0,
173
+ };
174
+ delete view.startedAt;
153
175
  if (view.parent !== parentPath(path)) throw new Error(`Invalid saved parent for ${path}`);
154
176
  if (active(view)) {
155
177
  view.state = "paused";
@@ -199,9 +221,17 @@ export class ThreadManager {
199
221
  if (caller !== "/root" && parent !== caller)
200
222
  throw new Error("An agent may spawn only its immediate children");
201
223
  if (!args.task.trim()) throw new Error("Task must not be empty");
202
- if (path.slice(1).split("/").length - 1 > (this.options.maxDepth ?? 8))
224
+ const segments = path.slice(1).split("/");
225
+ // Independent roots still represent agents launched by the main L1 conversation.
226
+ const level = segments.length + (segments[0] === "root" ? 0 : 1);
227
+ const maxLevels = this.options.maxLevels ?? DEFAULT_MANAGER_SETTINGS.maxLevels;
228
+ if (
229
+ this.options.maxLevels === undefined && this.options.maxDepth !== undefined
230
+ ? segments.length - 1 > this.options.maxDepth
231
+ : level > maxLevels
232
+ )
203
233
  throw new Error("Agent depth limit reached");
204
- if (this.records.size >= (this.options.maxThreads ?? 64))
234
+ if (this.records.size >= (this.options.maxThreads ?? DEFAULT_MANAGER_SETTINGS.maxThreads))
205
235
  throw new Error("Total thread limit reached");
206
236
  this.assertCapacity();
207
237
  const type = structuredClone(this.options.getType(args.type));
@@ -227,6 +257,9 @@ export class ThreadManager {
227
257
  status: "Starting",
228
258
  createdAt: now,
229
259
  updatedAt: now,
260
+ elapsedMs: 0,
261
+ inputTokens: 0,
262
+ outputTokens: 0,
230
263
  },
231
264
  definition: type,
232
265
  inherited,
@@ -380,11 +413,13 @@ export class ThreadManager {
380
413
  }
381
414
 
382
415
  private start(record: Record, message: string): void {
416
+ this.freezeElapsed(record);
383
417
  record.pauseRequested = false;
384
418
  record.stopRequested = false;
385
419
  record.startup = new AbortController();
386
420
  record.view.state = "starting";
387
421
  record.view.status = "Starting";
422
+ record.view.startedAt = Date.now();
388
423
  delete record.view.output;
389
424
  delete record.view.error;
390
425
  const epoch = this.epoch;
@@ -423,6 +458,9 @@ export class ThreadManager {
423
458
  record.view.error = errorText(error);
424
459
  record.view.status = record.stopRequested ? "Stopped; session retained" : record.view.error;
425
460
  } finally {
461
+ this.freezeElapsed(record);
462
+ record.liveInputTokens = 0;
463
+ record.liveOutputTokens = 0;
426
464
  markStarted(); // Failed/cancelled initialization must also release callers waiting to steer.
427
465
  this.touch(record);
428
466
  if (!this.disposed && epoch === this.epoch)
@@ -450,6 +488,7 @@ export class ThreadManager {
450
488
  const parentRecord = this.record(record.view.parent);
451
489
  if (!parentRecord.driver) await this.ensureDriver(parentRecord, readOnly);
452
490
  }
491
+ const parentSessionFile = this.lexicalParentSessionFile(record);
453
492
  const options: DriverOptions = {
454
493
  path: record.view.path,
455
494
  type: record.definition,
@@ -460,6 +499,10 @@ export class ThreadManager {
460
499
  signal,
461
500
  shouldPause: () => record.pauseRequested,
462
501
  onEvent: (event) => {
502
+ if (event.kind === "usage") {
503
+ this.applyUsage(record, event);
504
+ return;
505
+ }
463
506
  if (event.kind === "checkpoint") {
464
507
  this.touch(record);
465
508
  return;
@@ -469,6 +512,7 @@ export class ThreadManager {
469
512
  this.touch(record);
470
513
  }
471
514
  },
515
+ ...(parentSessionFile ? { parentSessionFile } : {}),
472
516
  ...(record.sessionLeafId !== undefined ? { sessionLeafId: record.sessionLeafId } : {}),
473
517
  };
474
518
  return this.options.createDriver(options);
@@ -480,6 +524,9 @@ export class ThreadManager {
480
524
  throw new Error("Driver startup cancelled");
481
525
  }
482
526
  record.driver = driver;
527
+ record.usageCursor = { input: 0, output: 0 };
528
+ record.liveInputTokens = 0;
529
+ record.liveOutputTokens = 0;
483
530
  record.view.sessionFile = driver.sessionFile;
484
531
  if (driver.sessionLeafId !== undefined) record.sessionLeafId = driver.sessionLeafId;
485
532
  this.touch(record);
@@ -498,6 +545,36 @@ export class ThreadManager {
498
545
  record.view.updatedAt = Date.now();
499
546
  if (!this.disposed) this.options.onEvent?.({ kind: "change", thread: this.view(record) });
500
547
  }
548
+ /** Fold driver-cumulative usage into persisted totals. Partials only refresh the live view. */
549
+ private applyUsage(
550
+ record: Record,
551
+ event: { inputTokens: number; outputTokens: number; partial?: boolean },
552
+ ): void {
553
+ const cursor = record.usageCursor ?? { input: 0, output: 0 };
554
+ if (event.partial) {
555
+ const input = Math.max(0, event.inputTokens - cursor.input);
556
+ const output = Math.max(0, event.outputTokens - cursor.output);
557
+ if (input === record.liveInputTokens && output === record.liveOutputTokens) return;
558
+ record.liveInputTokens = input;
559
+ record.liveOutputTokens = output;
560
+ if (!this.disposed) this.options.onEvent?.({ kind: "metrics", thread: this.view(record) });
561
+ return;
562
+ }
563
+ record.view.inputTokens =
564
+ (record.view.inputTokens ?? 0) + Math.max(0, event.inputTokens - cursor.input);
565
+ record.view.outputTokens =
566
+ (record.view.outputTokens ?? 0) + Math.max(0, event.outputTokens - cursor.output);
567
+ record.usageCursor = { input: event.inputTokens, output: event.outputTokens };
568
+ record.liveInputTokens = 0;
569
+ record.liveOutputTokens = 0;
570
+ this.touch(record);
571
+ }
572
+ private freezeElapsed(record: Record): void {
573
+ const startedAt = record.view.startedAt;
574
+ if (startedAt === undefined) return;
575
+ record.view.elapsedMs = (record.view.elapsedMs ?? 0) + Math.max(0, Date.now() - startedAt);
576
+ delete record.view.startedAt;
577
+ }
501
578
  private prepareInheritedContext(record: Record, readOnly = false): Promise<void> | undefined {
502
579
  if (!record.contextPending) return record.contextReady;
503
580
  if (record.contextReady) return record.contextReady;
@@ -527,11 +604,23 @@ export class ThreadManager {
527
604
  const leaf = record.driver?.sessionLeafId;
528
605
  return leaf !== undefined ? leaf : record.sessionLeafId;
529
606
  }
607
+ /** Live persisted file, else the saved file of a restored parent that has not been opened. */
608
+ private lexicalParentSessionFile(record: Record): string | undefined {
609
+ const parent = record.view.parent;
610
+ if (!parent || parent === "/root") return undefined;
611
+ const parentRecord = this.records.get(parent);
612
+ if (!parentRecord) return undefined;
613
+ return parentRecord.driver?.sessionFile ?? parentRecord.view.sessionFile;
614
+ }
530
615
  private view(record: Record): ThreadView {
531
- return structuredClone({
616
+ const view = structuredClone({
532
617
  ...record.view,
533
618
  sessionFile: record.driver ? record.driver.sessionFile : record.view.sessionFile,
534
619
  });
620
+ if (record.liveInputTokens) view.inputTokens = (view.inputTokens ?? 0) + record.liveInputTokens;
621
+ if (record.liveOutputTokens)
622
+ view.outputTokens = (view.outputTokens ?? 0) + record.liveOutputTokens;
623
+ return view;
535
624
  }
536
625
  private record(path: string): Record {
537
626
  const record = this.records.get(path);
@@ -560,7 +649,7 @@ export class ThreadManager {
560
649
  private assertCapacity(): void {
561
650
  if (
562
651
  [...this.records.values()].filter((record) => active(record.view)).length >=
563
- (this.options.maxConcurrent ?? 16)
652
+ (this.options.maxConcurrent ?? DEFAULT_MANAGER_SETTINGS.maxConcurrent)
564
653
  )
565
654
  throw new Error("Concurrent thread limit reached; wait for a thread to settle");
566
655
  }