pi-subagent-manager 1.15.0 → 1.16.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/dist/index.js CHANGED
@@ -341,9 +341,7 @@ export default function piSubagent(pi) {
341
341
  rootTurnTimer !== undefined)
342
342
  return;
343
343
  if (!wakeRequested &&
344
- !(limits.finalRecap &&
345
- (manager?.outstandingAsync() ?? 0) === 0 &&
346
- pendingSummaries(ctx).length > 0) &&
344
+ !((manager?.outstandingAsync() ?? 0) === 0 && pendingSummaries(ctx).length > 0) &&
347
345
  !pendingRootNotifications(ctx).some((notification) => notification.trigger === true))
348
346
  return;
349
347
  const currentGeneration = generation;
@@ -360,9 +358,7 @@ export default function piSubagent(pi) {
360
358
  return;
361
359
  }
362
360
  drainRootMailbox(ctx);
363
- const notifications = limits.finalRecap && (manager?.outstandingAsync() ?? 0) === 0
364
- ? pendingSummaries(ctx)
365
- : [];
361
+ const notifications = (manager?.outstandingAsync() ?? 0) === 0 ? pendingSummaries(ctx) : [];
366
362
  if (!notifications.length && !wakeRequested)
367
363
  return;
368
364
  const wasWakeRequested = wakeRequested;
@@ -439,17 +435,18 @@ export default function piSubagent(pi) {
439
435
  : `Agent ${thread.path} is ${thread.state}: ${thread.status}. ${thread.state === "paused" ? "No answer handback; send input to resume the same session." : "Session retained for further input."}`;
440
436
  try {
441
437
  if (event.recipient === "/root") {
442
- const recap = limits.finalRecap &&
443
- !suspendingSummaries &&
438
+ const recap = !suspendingSummaries &&
444
439
  event.kind === "settled" &&
445
440
  event.async &&
441
+ event.recipient === "/root" &&
446
442
  ["completed", "failed", "stopped"].includes(thread.state);
447
443
  const notification = {
448
444
  rootSessionId: requireContext().sessionManager.getSessionId(),
449
445
  content: message,
450
446
  finalRecap: recap,
451
447
  trigger: !suspendingSummaries &&
452
- (event.kind === "timeout" || (event.kind === "settled" && event.async && !recap)),
448
+ (event.kind === "timeout" ||
449
+ (event.kind === "settled" && (event.wakeParent || (event.async && !recap)))),
453
450
  details: {
454
451
  mailboxId: randomUUID(),
455
452
  path: thread.path,
@@ -459,15 +456,25 @@ export default function piSubagent(pi) {
459
456
  pi.appendEntry(ROOT_MAILBOX_ENTRY, notification);
460
457
  restoreRootMailbox(requireContext());
461
458
  }
462
- else {
463
- void requireManager().deliver(event.recipient, message).catch(warnDelivery);
464
- if (event.kind === "settled")
465
- restoreRootMailbox(requireContext());
466
- }
467
459
  }
468
460
  catch (error) {
469
461
  warnDelivery(error);
470
462
  }
463
+ if (event.recipient !== "/root") {
464
+ try {
465
+ void requireManager()
466
+ .deliver(event.recipient, message, !suspendingSummaries &&
467
+ limits.subagentMode !== "off" &&
468
+ event.kind === "settled" &&
469
+ event.wakeParent === true)
470
+ .catch(warnDelivery);
471
+ if (event.kind === "settled")
472
+ restoreRootMailbox(requireContext());
473
+ }
474
+ catch (error) {
475
+ warnDelivery(error);
476
+ }
477
+ }
471
478
  };
472
479
  const makeDriverFactory = () => createDriverFactory(requireContext, () => limits.modelSelection, () => limits.toolFiltering, () => inheritedTools.snapshot(), () => limits.subagentExtensions);
473
480
  let driverFactory = makeDriverFactory();
@@ -562,7 +569,8 @@ export default function piSubagent(pi) {
562
569
  syncTools();
563
570
  pi.on("before_agent_start", async (event, ctx) => {
564
571
  rootTask =
565
- (typeof event.prompt === "string" && event.prompt.replace(/\s+/g, " ").trim().slice(0, 500)) ||
572
+ (typeof event.prompt === "string" &&
573
+ event.prompt.replace(/\s+/g, " ").trim().slice(0, 500)) ||
566
574
  "Main Pi session";
567
575
  const prompt = subagentPrompt(limits, limits.checklistIntegration &&
568
576
  limits.subagentMode !== "off" &&
@@ -92,8 +92,8 @@ export class ThreadManager {
92
92
  steer: (path, message, timeoutMs) => this.steer(caller, path, message, timeoutMs),
93
93
  wait: (path, timeoutMs, signal) => this.wait(caller, path, timeoutMs, signal),
94
94
  update: (message) => this.update(caller, message),
95
- pause: (reason) => this.pause(caller, reason),
96
- stop: (path) => this.stop(caller, path),
95
+ pause: (reason, wakeParent) => this.pause(caller, reason, wakeParent),
96
+ stop: (path, wakeParent) => this.stop(caller, path, wakeParent),
97
97
  };
98
98
  }
99
99
  get(path, caller = "/root") {
@@ -387,21 +387,26 @@ export class ThreadManager {
387
387
  });
388
388
  return this.view(record);
389
389
  }
390
- pause(caller, reason) {
390
+ pause(caller, reason, wakeParent = false) {
391
391
  const record = this.record(caller);
392
392
  if (!active(record.view))
393
393
  throw new Error("Only a working child may pause itself");
394
394
  record.pauseRequested = true;
395
+ if (wakeParent)
396
+ record.wakeParentRequested = true;
395
397
  record.view.status = reason.trim() || "Awaiting further input";
396
398
  delete record.view.summary;
397
399
  this.touch(record);
398
400
  return this.view(record);
399
401
  }
400
- async stop(caller, path) {
402
+ async stop(caller, path, wakeParent = false) {
401
403
  path = canonicalPath(path, caller);
402
404
  this.assertAccess(caller, path);
403
405
  const record = this.record(path);
404
406
  const targets = [...this.records.values()].filter((item) => item === record || (isDescendant(item.view.path, path) && active(item.view)));
407
+ if (wakeParent && active(record.view))
408
+ record.wakeParentRequested = true;
409
+ const runs = new Map(targets.map((item) => [item, { id: item.runId, run: item.run }]));
405
410
  for (const item of targets) {
406
411
  item.stopRequested = true;
407
412
  item.startup.abort();
@@ -410,7 +415,9 @@ export class ThreadManager {
410
415
  await Promise.all(targets.map(async (item) => {
411
416
  if (item.driver)
412
417
  await item.driver.abort();
413
- await item.run;
418
+ await runs.get(item).run;
419
+ if (item.runId !== runs.get(item).id)
420
+ return;
414
421
  item.view.state = "stopped";
415
422
  item.view.status = "Stopped; session retained";
416
423
  delete item.view.output;
@@ -518,9 +525,27 @@ export class ThreadManager {
518
525
  }
519
526
  return parts.slice(-2).join("\n---\n").slice(-2000);
520
527
  }
521
- async deliver(path, content) {
522
- const driver = await this.ensureDriver(this.record(path), true);
528
+ async deliver(path, content, wakeParent = false) {
529
+ const record = this.record(path);
530
+ const driver = await this.ensureDriver(record, true);
531
+ const admission = wakeParent && active(record.view) && !record.pauseRequested && !record.stopRequested
532
+ ? { driver, runId: record.runId, run: record.run }
533
+ : undefined;
523
534
  await driver.sendUpdate(content);
535
+ if (!admission)
536
+ return;
537
+ if (record.driver !== admission.driver ||
538
+ record.runId !== admission.runId ||
539
+ record.run !== admission.run ||
540
+ !active(record.view) ||
541
+ record.pauseRequested ||
542
+ record.stopRequested)
543
+ return;
544
+ const wake = "A child settlement requested your attention (see the preceding subagent update). " +
545
+ "Inspect it and continue or recap the work as appropriate.";
546
+ if (!driver.followUp)
547
+ throw new Error("The parent driver does not support safe follow-up wake");
548
+ await driver.followUp(wake);
524
549
  }
525
550
  async shutdown() {
526
551
  this.disposed = true;
@@ -546,6 +571,7 @@ export class ThreadManager {
546
571
  this.freezeElapsed(record);
547
572
  record.pauseRequested = false;
548
573
  record.stopRequested = false;
574
+ record.wakeParentRequested = false;
549
575
  record.startup = new AbortController();
550
576
  record.view.state = "starting";
551
577
  record.view.status = "Starting";
@@ -610,6 +636,7 @@ export class ThreadManager {
610
636
  thread: this.view(record),
611
637
  recipient: record.view.parent ?? record.view.owner,
612
638
  async: record.async === true,
639
+ ...(record.wakeParentRequested ? { wakeParent: true } : {}),
613
640
  });
614
641
  }
615
642
  });
@@ -19,7 +19,7 @@ export function subagentPrompt(settings, checklistEligible = false) {
19
19
  policy,
20
20
  "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.",
21
21
  waitingPolicy,
22
- '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. To extend a running background agent\'s reporting timer, before or after a timeout event, call agent_steer({path: "/root/task", timeoutMs: 120000}) with message omitted entirely. This resets the timer from now (replacing any pending timer), without sending input, interrupting or resuming the agent; it requires the agent to still be running. After re-arming, end your turn to remain available while it works. For other timeout responses, follow the waiting policy above, send steering input or stop the agent.',
22
+ '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, 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. To extend a running background agent\'s reporting timer, before or after a timeout event, call agent_steer({path: "/root/task", timeoutMs: 120000}) with message omitted entirely. This resets the timer from now (replacing any pending timer), without sending input, interrupting or resuming the agent; it requires the agent to still be running. After re-arming, end your turn to remain available while it works. For other timeout responses, follow the waiting policy above, send steering input or stop the agent.',
23
23
  "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.",
24
24
  `Maximum depth: ${settings.maxLevels} levels including L1. Shared concurrency: ${settings.maxConcurrent} active threads; waiting parents count.`,
25
25
  delegationGuidance(settings.maxLevels > 1),
@@ -597,7 +597,15 @@ export function createDriverFactory(getRootContext, getModelSelection = () => "p
597
597
  sessionManager.appendMessage(buildBootstrapMessage());
598
598
  emit("activity", BOOTSTRAP_MESSAGE);
599
599
  };
600
+ let acceptingFollowUps = true;
601
+ const continueAgent = session.agent.continue.bind(session.agent);
602
+ session.agent.continue = async () => {
603
+ acceptingFollowUps = true;
604
+ await continueAgent();
605
+ };
600
606
  const queueAccepted = async (kind, content) => {
607
+ if (kind === "followUp" && !acceptingFollowUps)
608
+ return false;
601
609
  assertCurrentModelAuthorized();
602
610
  ensurePersistedSession();
603
611
  const accepted = mailbox.accept(kind, content);
@@ -607,6 +615,7 @@ export function createDriverFactory(getRootContext, getModelSelection = () => "p
607
615
  else
608
616
  session.agent.steer(buildQueuedUserMessage(accepted));
609
617
  mailbox.markEnqueued(accepted.id);
618
+ return true;
610
619
  };
611
620
  const resumePending = async () => {
612
621
  for (const accepted of mailbox.replayablePending()) {
@@ -682,6 +691,10 @@ export function createDriverFactory(getRootContext, getModelSelection = () => "p
682
691
  : options.inherited.length;
683
692
  const transcript = new TranscriptChannel(() => session.messages, session.messages.some((message) => message.role === "compactionSummary") ? 0 : inheritedCount);
684
693
  const unsubscribe = session.subscribe((event) => {
694
+ if (event.type === "agent_start")
695
+ acceptingFollowUps = true;
696
+ else if (event.type === "agent_end")
697
+ acceptingFollowUps = false;
685
698
  transcript.accept(event);
686
699
  if (running && event.type === "message_end" && event.message.role === "assistant")
687
700
  promptResult.lastAssistant = event.message;
@@ -743,6 +756,7 @@ export function createDriverFactory(getRootContext, getModelSelection = () => "p
743
756
  if (running)
744
757
  throw new Error("Subagent is already running; use steer instead");
745
758
  running = true;
759
+ acceptingFollowUps = true;
746
760
  aborted = false;
747
761
  promptResult.lastAssistant = undefined;
748
762
  finalOutput = "";
@@ -768,6 +782,7 @@ export function createDriverFactory(getRootContext, getModelSelection = () => "p
768
782
  }
769
783
  finally {
770
784
  updateResolved();
785
+ acceptingFollowUps = false;
771
786
  running = false;
772
787
  }
773
788
  },
@@ -775,6 +790,10 @@ export function createDriverFactory(getRootContext, getModelSelection = () => "p
775
790
  assertOpen();
776
791
  await queueAccepted("steer", message);
777
792
  },
793
+ async followUp(message) {
794
+ assertOpen();
795
+ return queueAccepted("followUp", message);
796
+ },
778
797
  snapshot() {
779
798
  return structuredClone(session.messages);
780
799
  },
@@ -86,15 +86,15 @@ export function agentTools(getManager, caller, getTypes, resolveSettings) {
86
86
  }), async (params) => result(compact(await threads().steer(params.path, params.message, params.timeoutMs)))),
87
87
  make("agent_status", "Read a thread's status, including bounded child extension diagnostics, or list visible descendants. Root can inspect all trees. Completion retains the session; pause retains it without final answer handback.", Type.Object({ path: Type.Optional(path) }), (params) => result(params.path ? compact(threads().get(params.path)) : threads().list().map(compact))),
88
88
  make("agent_update", "Child-only: send progress to the parent without ending this task. Delivery is recorded and displayed but does not interrupt or automatically restart the parent model.", Type.Object({ message: Type.String({ minLength: 1, maxLength: 8000 }) }), (params) => result(compact(threads().update(params.message)))),
89
- make("agent_pause", "Child-only: stop at this turn boundary WITHOUT returning a final answer. Keep the SAME session for user/parent input via agent_steer. To finish and hand back an answer instead, simply return your final assistant answer. Both states can be resumed.", Type.Object({ reason: text }), (params) => ({
89
+ make("agent_pause", "Child-only: stop at this turn boundary WITHOUT returning a final answer. Keep the SAME session for user/parent input via agent_steer. To finish and hand back an answer instead, simply return your final assistant answer. Both states can be resumed. Set wakeParent:true to request a turn on your immediate parent after settlement, even while siblings work. A busy parent receives a safe follow-up; an already-settled parent is never auto-resumed.", Type.Object({ reason: text, wakeParent: Type.Optional(Type.Boolean()) }), (params) => ({
90
90
  ...result({
91
91
  path: caller,
92
92
  pauseRequested: true,
93
- status: threads().pause(params.reason).status,
93
+ status: threads().pause(params.reason, params.wakeParent).status,
94
94
  }),
95
95
  terminate: true,
96
96
  })),
97
- make("agent_stop", "Stop a descendant and its working children. Session history is retained; resume with agent_steer. This is cooperative cancellation, not sandbox process termination.", Type.Object({ path }), async (params) => result(compact(await threads().stop(params.path)))),
97
+ make("agent_stop", "Stop a descendant and its working children. Session history is retained; resume with agent_steer. This is cooperative cancellation, not sandbox process termination. Set wakeParent:true to request a turn on the addressed thread's immediate parent when that active thread settles; descendants do not inherit it. Busy parents receive a safe follow-up; an already-settled parent is never auto-resumed.", Type.Object({ path, wakeParent: Type.Optional(Type.Boolean()) }), async (params) => result(compact(await threads().stop(params.path, params.wakeParent)))),
98
98
  make("agent_output", "Read completed thread output in character pages. Paused threads deliberately have no final answer handback. All sessions can be viewed by the user with /agents tree; select a thread and press Enter to inspect it.", Type.Object({
99
99
  path,
100
100
  offset: Type.Optional(Type.Integer({ minimum: 0 })),
@@ -37,7 +37,6 @@ export const DEFAULT_MANAGER_SETTINGS = {
37
37
  costIcon: "money",
38
38
  nerdFontIcons: false,
39
39
  loaderStyle: "circle",
40
- finalRecap: false,
41
40
  subagentExtensions: false,
42
41
  checklistIntegration: false,
43
42
  housekeepingEnabled: false,
@@ -59,7 +58,6 @@ const KEYS = [
59
58
  "costIcon",
60
59
  "nerdFontIcons",
61
60
  "loaderStyle",
62
- "finalRecap",
63
61
  "subagentExtensions",
64
62
  "checklistIntegration",
65
63
  "housekeepingEnabled",
@@ -99,21 +97,23 @@ function isExtensionSelectionPath(entry) {
99
97
  return false;
100
98
  if (entry.startsWith(AGENT_DIR_EXTENSION_PREFIX)) {
101
99
  const suffix = entry.slice(AGENT_DIR_EXTENSION_PREFIX.length);
102
- return !suffix.includes("\\") &&
103
- suffix.split("/").every((part) => part && part !== "." && part !== "..");
100
+ return (!suffix.includes("\\") &&
101
+ suffix.split("/").every((part) => part && part !== "." && part !== ".."));
104
102
  }
105
103
  if (entry === AGENT_DIR_EXTENSION_PREFIX.slice(0, -1))
106
104
  return false;
107
105
  if (isAbsolute(entry))
108
106
  return resolve(entry) === entry;
109
- return normalize(entry) === entry &&
110
- entry !== "." && entry !== ".." && !entry.startsWith(`..${sep}`) && !entry.endsWith(sep);
107
+ return (normalize(entry) === entry &&
108
+ entry !== "." &&
109
+ entry !== ".." &&
110
+ !entry.startsWith(`..${sep}`) &&
111
+ !entry.endsWith(sep));
111
112
  }
112
113
  function requirement(key) {
113
114
  if (key === "subagentExtensions")
114
115
  return "subagentExtensions must be a boolean or an array of absolute, project-relative, or $PI_CODING_AGENT_DIR paths";
115
116
  if (key === "nerdFontIcons" ||
116
- key === "finalRecap" ||
117
117
  key === "checklistIntegration" ||
118
118
  key === "housekeepingEnabled" ||
119
119
  key === "forkHistorySummaries")
@@ -152,7 +152,7 @@ function parseSettings(content) {
152
152
  }
153
153
  const record = parsed;
154
154
  for (const key of Object.keys(record)) {
155
- if (!isSupportedKey(key) && key !== "scopedModelFiltering")
155
+ if (!isSupportedKey(key) && key !== "scopedModelFiltering" && key !== "finalRecap")
156
156
  throw new Error(`Unknown settings key: ${key}`);
157
157
  }
158
158
  const layer = {};
@@ -169,7 +169,6 @@ function parseSettings(content) {
169
169
  continue;
170
170
  const value = record[key];
171
171
  if (key === "nerdFontIcons" ||
172
- key === "finalRecap" ||
173
172
  key === "checklistIntegration" ||
174
173
  key === "housekeepingEnabled" ||
175
174
  key === "forkHistorySummaries") {
@@ -440,12 +440,6 @@ async function configureAgentsDialog(ctx, options) {
440
440
  help: "Experimental: reload selected user/trusted-project extension hooks, including auto-discovered .ts/.js files and subdirectory entry points, in separate subagent sessions (not CLI-only or inline extensions). Bugs and unintended consequences may occur if hooks assume main-session state.\nRead limitations: https://github.com/championswimmer/pi-subagent-manager/blob/main/docs/subagent-extension-limitations.md\nSelect individual extensions in the submenu. None by default. Save and apply affects newly opened sessions, not already-open agents.",
441
441
  },
442
442
  checklistRow(draft.checklistIntegration, checklistStatus()),
443
- {
444
- id: "finalRecap",
445
- label: "[lab] Final Recap",
446
- value: draft.finalRecap ? "On" : "Off",
447
- help: "Experimental: when detached agents finish or fail and the main agent is idle, automatically ask the main agent to summarize their results.\nEnabling this may cause extra model turns and uses more tokens and context.\nOff by default. Subagent Mode Off suppresses automatic summaries.",
448
- },
449
443
  {
450
444
  id: "scope",
451
445
  label: "Save scope",
@@ -563,9 +557,6 @@ async function configureAgentsDialog(ctx, options) {
563
557
  else
564
558
  draft.checklistIntegration = !draft.checklistIntegration;
565
559
  }
566
- else if (action === "finalRecap") {
567
- draft.finalRecap = !draft.finalRecap;
568
- }
569
560
  else if (action === "scope") {
570
561
  if (!ctx.isProjectTrusted())
571
562
  ctx.ui.notify("Project settings require a trusted project; saving globally.", "warning");
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-subagent-manager",
3
- "version": "1.15.0",
3
+ "version": "1.16.0",
4
4
  "description": "Hierarchical, steerable subagent threads for pi",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",