@henryqw/pi-subagent 2.5.1 → 2.9.5

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/CONTEXT.md CHANGED
@@ -17,8 +17,8 @@ Provide validated user Roles, shared task-model Pi launch policy, generic manage
17
17
 
18
18
  ## Invariants
19
19
 
20
- - One Delegated Task creates one ephemeral child process and no saved session. Its soft deadline is 10 minutes; active model/tool execution or activity within the last minute grants one 5-minute grace period before a hard stop.
21
- - Up to four active ephemeral `delegate_task` children run per Main; excess calls wait FIFO. Queued calls do not start a child or consume child timeout. Managed Herdr workers are unaffected.
20
+ - One Delegated Task creates one ephemeral child process and no saved session. Default timeouts: 10-minute soft deadline; active model/tool execution or activity within the last minute grants one 5-minute grace period before a hard stop. Every value is configurable via the `timeout` object in `~/.pi/agent/config/pi-subagent.json` (`softMinutes`, `graceMinutes`, `activeWindowSeconds`).
21
+ - Up to five active ephemeral `delegate_task` children run per Main by default, configurable via `maxSubagents` in `~/.pi/agent/config/pi-subagent.json` or the `PI_SUBAGENT_MAX_SUBAGENTS` environment variable; excess calls wait FIFO. Queued calls do not start a child or consume child timeout. Managed Herdr workers are unaffected.
22
22
  - Ambient child extensions and Skills stay disabled; Role explicitly selects extension sources and named Skills. Pi loads Skills supplied by those extension packages or their resource discovery. Omitted Role tools use Pi's effective `defaultTools`; an explicit list sets base tools while loaded extension tools activate automatically.
23
23
  - Role Skill names resolve through Main's effective Pi Skill registry; unavailable names warn and skip without blocking delegation.
24
24
  - Main selects Role and may override Model Class per task; omitted class uses shared `pi-subagent/delegateTask` assignment, initially `balanced`. Library callers select Role plus their own shared task ID.
package/README.md CHANGED
@@ -27,7 +27,7 @@ An explicit `model` (`provider/modelId`) overrides `modelClass` and resolves aga
27
27
 
28
28
  `modelClass` is `fast`, `balanced`, `frontier`, or `fav`. Omitted class uses the shared `pi-subagent/delegateTask` assignment, which defaults to `balanced`. Primary route is resolved against current scoped text models; fallback is tried only before launch. If no route is usable, delegation rejects with `Run /task-models`. A started child is never retried.
29
29
 
30
- Main splits broad work into independent bounded tasks and keeps integration and cross-cutting decisions. Each `task` states its objective, exact scope and exclusions, relevant context and constraints, expected deliverable, and validation. Each call uses the least capable `modelClass` that can reliably complete its task. Independent sibling calls can run concurrently; concurrent edit tasks must own non-overlapping files. Up to four active ephemeral `delegate_task` children run per Main; excess calls wait FIFO. Queued calls do not start a child or consume child timeout. Managed Herdr workers are unaffected.
30
+ Main splits broad work into independent bounded tasks and keeps integration and cross-cutting decisions. Each `task` states its objective, exact scope and exclusions, relevant context and constraints, expected deliverable, and validation. Each call uses the least capable `modelClass` that can reliably complete its task. Independent sibling calls can run concurrently; concurrent edit tasks must own non-overlapping files. Up to five active ephemeral `delegate_task` subagents run per Main; excess calls wait FIFO. Configure the cap with `"maxSubagents"` (positive integer) in `~/.pi/agent/config/pi-subagent.json`, or override per session with the `PI_SUBAGENT_MAX_SUBAGENTS` environment variable. Child timeouts are configurable with a `"timeout"` object: `{ "softMinutes": 20, "graceMinutes": 10, "activeWindowSeconds": 90 }` (all keys optional; defaults 10/5/60). Invalid config values fall back to the default with a warning; an invalid environment variable fails fast. Queued calls do not start a child or consume child timeout. Managed Herdr workers are unaffected.
31
31
 
32
32
  Each call starts one isolated child (`pi --mode json -p --no-session`). Ambient extensions and Skills are off. Role/caller extensions load; those packages' tools and Skills auto-load, plus any extra `skills` names. Child uses the delegated working directory and Main's project approval. Abort kills the child process group. An inactive child times out after 10 minutes; current model/tool execution or activity in the last minute grants one 5-minute grace period, then the child stops. Streaming output is capped at 50 KiB. Unused JSON event types are discarded before payload buffering; consumed or unclassifiable events above 1 MiB fail delegation.
33
33
 
@@ -0,0 +1,131 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { getAgentDir } from "@earendil-works/pi-coding-agent";
4
+
5
+ export interface SubagentTimeoutConfig {
6
+ /** Soft deadline in minutes; the child is asked to stop after this. */
7
+ softMinutes?: number;
8
+ /** Extra minutes past the soft deadline before a stuck child is killed. */
9
+ graceMinutes?: number;
10
+ /** Activity window in seconds that qualifies an active child for grace. */
11
+ activeWindowSeconds?: number;
12
+ }
13
+
14
+ export interface SubagentConfig {
15
+ maxSubagents?: number;
16
+ timeout?: SubagentTimeoutConfig;
17
+ }
18
+
19
+ export interface LoadedSubagentConfig {
20
+ config: SubagentConfig;
21
+ /** Human-readable problems when the file exists but is partly unusable; the file is never rewritten. */
22
+ error?: string;
23
+ }
24
+
25
+ const positive = (value: unknown): value is number =>
26
+ typeof value === "number" && Number.isFinite(value) && value > 0;
27
+
28
+ // Node clamps setTimeout delays above 2^31 - 1 ms to 1 ms, which would kill
29
+ // every child immediately instead of applying the configured deadline.
30
+ const MAX_TIMER_DELAY_MS = 2_147_483_647;
31
+ // Defaults for fields the user left unset, used when bounding the combined
32
+ // soft + grace hard-deadline delay.
33
+ const DEFAULT_SOFT_MINUTES = 10;
34
+ const DEFAULT_GRACE_MINUTES = 5;
35
+ const TIMEOUT_FIELDS: Array<[keyof SubagentTimeoutConfig, number, string]> = [
36
+ ["softMinutes", 60_000, "minutes"],
37
+ ["graceMinutes", 60_000, "minutes"],
38
+ ["activeWindowSeconds", 1_000, "seconds"],
39
+ ];
40
+
41
+ /**
42
+ * Required single-extension config path form (AGENTS.md); agentDir is
43
+ * injectable so tests can point at a temp directory.
44
+ */
45
+ export const configPath = (agentDir = getAgentDir()): string =>
46
+ join(agentDir, "config", "pi-subagent.json");
47
+
48
+ /**
49
+ * Read the optional user config at `<agentDir>/config/pi-subagent.json`.
50
+ * Treated as untrusted user data: malformed files are preserved untouched and
51
+ * reported instead of crashing the session; callers fall back to defaults.
52
+ */
53
+ export function readSubagentConfig(agentDir = getAgentDir()): LoadedSubagentConfig {
54
+ const path = configPath(agentDir);
55
+ let raw: string;
56
+ try {
57
+ raw = readFileSync(path, "utf8");
58
+ } catch (error) {
59
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return { config: {} };
60
+ throw error;
61
+ }
62
+ let parsed: unknown;
63
+ try {
64
+ parsed = JSON.parse(raw);
65
+ } catch (error) {
66
+ return {
67
+ config: {},
68
+ error: `${path} is not valid JSON (${error instanceof Error ? error.message : String(error)}); using defaults.`,
69
+ };
70
+ }
71
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
72
+ return { config: {}, error: `${path} must contain a JSON object; using defaults.` };
73
+ }
74
+ const record = parsed as Record<string, unknown>;
75
+ const problems: string[] = [];
76
+ const config: SubagentConfig = {};
77
+ for (const key of Object.keys(record)) {
78
+ if (key !== "maxSubagents" && key !== "timeout") {
79
+ problems.push(`unknown config key ${JSON.stringify(key)}; expected maxSubagents, timeout`);
80
+ }
81
+ }
82
+
83
+ if (record.maxSubagents !== undefined) {
84
+ if (typeof record.maxSubagents === "number" && Number.isSafeInteger(record.maxSubagents) && record.maxSubagents >= 1) {
85
+ config.maxSubagents = record.maxSubagents;
86
+ } else {
87
+ problems.push(`maxSubagents must be a safe integer >= 1, got ${JSON.stringify(record.maxSubagents)}`);
88
+ }
89
+ }
90
+
91
+ if (record.timeout !== undefined) {
92
+ if (!record.timeout || typeof record.timeout !== "object" || Array.isArray(record.timeout)) {
93
+ problems.push(`timeout must be a JSON object, got ${JSON.stringify(record.timeout)}`);
94
+ } else {
95
+ const timeoutRecord = record.timeout as Record<string, unknown>;
96
+ const timeout: SubagentTimeoutConfig = {};
97
+ for (const [key, unitMs, unit] of TIMEOUT_FIELDS) {
98
+ const value = timeoutRecord[key];
99
+ if (value === undefined) continue;
100
+ if (!positive(value)) {
101
+ problems.push(`timeout.${key} must be a positive number of ${unit}, got ${JSON.stringify(value)}`);
102
+ } else if (value * unitMs > MAX_TIMER_DELAY_MS) {
103
+ problems.push(`timeout.${key} exceeds the maximum supported delay of ${MAX_TIMER_DELAY_MS} ms, got ${JSON.stringify(value)} ${unit}`);
104
+ } else {
105
+ (timeout as Record<string, number>)[key] = value;
106
+ }
107
+ }
108
+ for (const key of Object.keys(timeoutRecord)) {
109
+ if (!TIMEOUT_FIELDS.some(([known]) => known === key)) {
110
+ problems.push(`unknown timeout.${key}; expected ${TIMEOUT_FIELDS.map(([known]) => known).join(", ")}`);
111
+ }
112
+ }
113
+ if (Object.keys(timeout).length) config.timeout = timeout;
114
+ }
115
+ }
116
+
117
+ // The hard deadline schedules softMs + graceMs in one timer; the combination
118
+ // must stay inside Node's limit even when each field fits alone. Falling back
119
+ // to defaults drops the whole timeout object, matching other invalid values.
120
+ if (config.timeout) {
121
+ const hardDeadlineMinutes =
122
+ (config.timeout.softMinutes ?? DEFAULT_SOFT_MINUTES) +
123
+ (config.timeout.graceMinutes ?? DEFAULT_GRACE_MINUTES);
124
+ if (hardDeadlineMinutes * 60_000 > MAX_TIMER_DELAY_MS) {
125
+ problems.push(`timeout softMinutes + graceMinutes must stay within ${MAX_TIMER_DELAY_MS} ms combined, got ${hardDeadlineMinutes} minutes`);
126
+ delete config.timeout;
127
+ }
128
+ }
129
+
130
+ return { config, error: problems.length ? `${path}: ${problems.join("; ")}; using defaults.` : undefined };
131
+ }
@@ -4,6 +4,7 @@ import { basename } from "node:path";
4
4
  import { StringEnum } from "@earendil-works/pi-ai";
5
5
  import { type ExtensionAPI, type ExtensionContext, type Theme } from "@earendil-works/pi-coding-agent";
6
6
  import { type Component, truncateToWidth, type TUI, visibleWidth } from "@earendil-works/pi-tui";
7
+ import { readSubagentConfig, type SubagentTimeoutConfig } from "./config.ts";
7
8
  import {
8
9
  availableTaskModels,
9
10
  modelReference,
@@ -20,7 +21,6 @@ const MODEL_CLASSES = PROFILE_NAMES;
20
21
  const SUBAGENT_TASK = "pi-subagent/delegateTask";
21
22
  const MAX_OUTPUT_BYTES = 50 * 1024;
22
23
  const MAX_JSON_EVENT_BYTES = 1024 * 1024;
23
- const MAX_ACTIVE_CHILDREN = 4;
24
24
  const CONSUMED_JSON_EVENTS = new Set(["message_start", "message_update", "message_end"]);
25
25
  const JSON_EVENT_TYPE = /^\s*\{\s*"type"\s*:\s*"([^"\\]+)"/;
26
26
  const WIDGET_KEY = "subagent-status";
@@ -35,6 +35,16 @@ const DEFAULT_TIMEOUT_POLICY = {
35
35
  const SPINNER_FRAMES = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
36
36
 
37
37
  type TimeoutPolicy = typeof DEFAULT_TIMEOUT_POLICY;
38
+
39
+ /** Merge validated config-file timeout fields over defaults; absent keys keep defaults. */
40
+ export function resolveTimeoutPolicy(partial: SubagentTimeoutConfig | undefined): TimeoutPolicy {
41
+ const policy: TimeoutPolicy = { ...DEFAULT_TIMEOUT_POLICY };
42
+ if (!partial) return policy;
43
+ if (partial.softMinutes !== undefined) policy.softMs = partial.softMinutes * 60_000;
44
+ if (partial.graceMinutes !== undefined) policy.graceMs = partial.graceMinutes * 60_000;
45
+ if (partial.activeWindowSeconds !== undefined) policy.activeWindowMs = partial.activeWindowSeconds * 1_000;
46
+ return policy;
47
+ }
38
48
  type ModelClass = ProfileName;
39
49
  class SubagentTimeoutError extends Error {}
40
50
  type ChildResult = {
@@ -429,6 +439,9 @@ const Parameters = Type.Object({
429
439
  modelClass: Type.Optional(StringEnum(MODEL_CLASSES, {
430
440
  description: "Classify task complexity: fast for narrow lookups or mechanical edits; balanced for normal bounded work; frontier for ambiguous, cross-cutting, or high-risk reasoning; fav for the user's favorite model when they ask for it. Defaults to the shared pi-subagent/delegateTask assignment.",
431
441
  })),
442
+ background: Type.Optional(Type.Boolean({
443
+ description: "Run without blocking: returns a task ID immediately and delivers the outcome as a message when the Subagent settles. Prefer blocking delegation whenever the parent needs the result to continue.",
444
+ })),
432
445
  });
433
446
 
434
447
  function resolveDesignatedRoute(ctx: ExtensionContext, reference: string): ResolvedTaskRoute {
@@ -441,6 +454,8 @@ function resolveDesignatedRoute(ctx: ExtensionContext, reference: string): Resol
441
454
  return { model, thinkingLevel: levels.includes("medium") ? "medium" : levels.at(-1)! };
442
455
  }
443
456
 
457
+ const BACKGROUND_RESULT_TYPE = "subagent-background-result";
458
+
444
459
  const roleSummary = (): string => {
445
460
  try {
446
461
  const roles = loadRoles();
@@ -452,14 +467,47 @@ const roleSummary = (): string => {
452
467
 
453
468
  export default function subagentExtension(
454
469
  pi: ExtensionAPI,
455
- timeoutPolicy: TimeoutPolicy = DEFAULT_TIMEOUT_POLICY,
470
+ overrideTimeoutPolicy?: TimeoutPolicy,
456
471
  ): void {
457
472
  const widgetItems = new Map<string, WidgetItem>();
473
+ // Each child is a full Pi process issuing its own model calls; cap parallel
474
+ // spend. Precedence: PI_SUBAGENT_MAX_SUBAGENTS env > config/pi-subagent.json
475
+ // maxSubagents > default 5. Invalid config falls back to the default and is
476
+ // reported once the UI exists; an invalid env value fails fast.
477
+ const loadedConfig = readSubagentConfig();
478
+ const startupWarnings = [loadedConfig.error].filter((message): message is string => message !== undefined);
479
+ let maxActiveSubagents = loadedConfig.config.maxSubagents ?? 5;
480
+ const maxSubagentsRaw = process.env.PI_SUBAGENT_MAX_SUBAGENTS;
481
+ if (maxSubagentsRaw !== undefined) {
482
+ // Reject "2workers", "1.5", "1e3" — parseInt would silently accept prefixes —
483
+ // and digit strings that overflow to Infinity, which would disable the cap.
484
+ if (!/^\d+$/.test(maxSubagentsRaw) || !/^[1-9]\d*$/.test(maxSubagentsRaw)) {
485
+ throw new Error(`PI_SUBAGENT_MAX_SUBAGENTS must be a positive integer, got ${JSON.stringify(maxSubagentsRaw)}.`);
486
+ }
487
+ const parsed = Number.parseInt(maxSubagentsRaw, 10);
488
+ if (!Number.isSafeInteger(parsed)) {
489
+ throw new Error(`PI_SUBAGENT_MAX_SUBAGENTS exceeds the supported range, got ${JSON.stringify(maxSubagentsRaw)}.`);
490
+ }
491
+ maxActiveSubagents = parsed;
492
+ }
493
+ let backgroundSequence = 0;
494
+ // Explicit policy argument (tests/embedders) wins; otherwise resolve from
495
+ // config file over defaults.
496
+ const timeoutPolicy: TimeoutPolicy = overrideTimeoutPolicy ?? resolveTimeoutPolicy(loadedConfig.config.timeout);
497
+ // Background children outlive the launching tool call, so they get their own
498
+ // abort signal: tied to the session, not to the turn that started them.
499
+ const backgroundTasks = new Map<string, AbortController>();
500
+ // Latest known session context; refreshed on session lifecycle and model
501
+ // changes so queued background launches resolve against effective state.
502
+ let latestCtx: ExtensionContext | undefined;
503
+ // Bumped by session_start and session_shutdown; background tasks may only
504
+ // deliver into the exact session that launched them.
505
+ let sessionEpoch = 0;
458
506
  let activeChildren = 0;
459
507
  const queuedChildren: Array<() => void> = [];
460
508
  const acquireChildPermit = (signal: AbortSignal | undefined): Promise<void> => {
461
509
  if (signal?.aborted) return Promise.reject(new Error("Subagent was aborted."));
462
- if (activeChildren < MAX_ACTIVE_CHILDREN) {
510
+ if (activeChildren < maxActiveSubagents) {
463
511
  activeChildren++;
464
512
  return Promise.resolve();
465
513
  }
@@ -561,7 +609,10 @@ export default function subagentExtension(
561
609
  };
562
610
 
563
611
  pi.on("session_start", (_event, ctx) => {
612
+ sessionEpoch += 1;
613
+ latestCtx = ctx;
564
614
  ensureWidget(ctx);
615
+ for (const warning of startupWarnings.splice(0)) ctx.ui.notify(warning, "warning");
565
616
  });
566
617
  pi.on("session_shutdown", (_event, ctx) => {
567
618
  stopWidgetTimer();
@@ -569,18 +620,54 @@ export default function subagentExtension(
569
620
  activeTui = undefined;
570
621
  widgetInstalled = false;
571
622
  if (ctx.hasUI) ctx.ui.setWidget(WIDGET_KEY, undefined);
623
+ // Invalidate every outstanding background delivery: the aborting session
624
+ // is gone, and a later-settling child must not reach the next session.
625
+ sessionEpoch += 1;
626
+ for (const controller of backgroundTasks.values()) controller.abort();
627
+ backgroundTasks.clear();
628
+ });
629
+ // btw-style context refresh: model_select carries the new model on the event,
630
+ // agent_settled delivers the freshest full context after each turn.
631
+ pi.on("model_select", (event, ctx) => {
632
+ latestCtx = { ...ctx, model: event.model } as ExtensionContext;
572
633
  });
634
+ pi.on("agent_settled", (_event, ctx) => {
635
+ latestCtx = ctx;
636
+ });
637
+
638
+ const reportBackground = async (
639
+ launchEpoch: number,
640
+ taskId: string,
641
+ details: { role: string; model?: string; thinkingLevel?: string },
642
+ outcome: "completed" | "failed" | "aborted",
643
+ text: string,
644
+ ): Promise<void> => {
645
+ if (launchEpoch !== sessionEpoch) return;
646
+ // Custom messages convert to user-role LLM messages, so the parent agent
647
+ // sees the outcome on its next turn without a forced turn now.
648
+ try {
649
+ pi.sendMessage({
650
+ customType: BACKGROUND_RESULT_TYPE,
651
+ content: `Background subagent ${taskId} (${details.role}) ${outcome}.\n\n${capOutput(text)}`,
652
+ display: true,
653
+ details: { ...details, taskId, outcome },
654
+ }, { triggerTurn: false });
655
+ } catch {
656
+ // Session may already be gone; the widget row still shows the outcome.
657
+ }
658
+ };
573
659
 
574
660
  pi.registerTool({
575
661
  name: "delegate_task",
576
662
  label: "Subagent",
577
- description: `Delegate one bounded, independently executable task to one isolated Pi Subagent. Roles: ${roleSummary()}. Choose fast for narrow work, balanced for normal work, frontier for ambiguous and high-risk work, or fav when the user asks for their favorite model; omit modelClass to use shared task-model settings. When the user designates a specific model, pass it as provider/modelId in model.`,
663
+ description: `Delegate one bounded, independently executable task to one isolated Pi Subagent. Roles: ${roleSummary()}. Choose fast for narrow work, balanced for normal work, frontier for ambiguous and high-risk work, or fav when the user asks for their favorite model; omit modelClass to use shared task-model settings. When the user designates a specific model, pass it as provider/modelId in model. Set background only when the user explicitly wants the task to run without blocking; background tasks report results later and cannot be waited on.`,
578
664
  promptSnippet: "Delegate one bounded, independently executable task to an isolated role",
579
665
  promptGuidelines: [
580
666
  "Before calling delegate_task, split broad work into the smallest independent bounded tasks; keep integration and cross-cutting decisions in Main.",
581
667
  "Each delegate_task task must state its objective, exact scope and exclusions, relevant context and constraints, expected deliverable, and validation; never pass the parent request unchanged.",
582
668
  "Use fav when the user explicitly asks for their favorite model. Otherwise, choose the least capable modelClass that can reliably complete the task: fast for narrow work, balanced for normal work, and frontier only for ambiguous, cross-cutting, or high-risk work.",
583
669
  "Submit independent delegate_task calls together for parallel execution. Parallel edits must own non-overlapping files; otherwise sequence them. Use the minimum number of Subagents needed.",
670
+ "Use background: true only when the user explicitly asks for non-blocking delegation (for example \"keep working while this runs\"); the result arrives as a message after the current turn and the parent must not assume it is available yet.",
584
671
  ],
585
672
  parameters: Parameters,
586
673
  async execute(toolCallId, params, signal, onUpdate, ctx) {
@@ -594,28 +681,99 @@ export default function subagentExtension(
594
681
  if (params.modelClass !== undefined && !isModelClass(params.modelClass)) {
595
682
  throw new Error("delegate_task modelClass must be fast, balanced, frontier, or fav.");
596
683
  }
597
- const launch = params.model !== undefined
598
- ? createRoleLaunch(pi, ctx, { role, route: resolveDesignatedRoute(ctx, cleanText(params.model, "model", "delegate_task")) })
684
+ // Resolve against the latest known session context: a task queued past
685
+ // the cap must pick up model or Codex account changes that happened
686
+ // while it waited.
687
+ const launchCtx = () => latestCtx ?? ctx;
688
+ const resolveLaunch = () => params.model !== undefined
689
+ ? createRoleLaunch(pi, launchCtx(), { role, route: resolveDesignatedRoute(launchCtx(), cleanText(params.model, "model", "delegate_task")) })
599
690
  : params.modelClass === undefined
600
- ? resolveRoleLaunch(pi, ctx, { role, taskId: SUBAGENT_TASK })
601
- : createRoleLaunch(pi, ctx, { role, route: resolveTaskRoute(ctx, params.modelClass) });
602
- const modelReferenceValue = modelReference(launch.model);
603
- const thinkingLevel = launch.thinkingLevel;
604
- if (launch.missingSkills.length) {
605
- ctx.ui.notify(
606
- `Subagent role ${role.name} skipped unavailable Pi skills: ${launch.missingSkills.join(", ")}.`,
607
- "warning",
608
- );
691
+ ? resolveRoleLaunch(pi, launchCtx(), { role, taskId: SUBAGENT_TASK })
692
+ : createRoleLaunch(pi, launchCtx(), { role, route: resolveTaskRoute(launchCtx(), params.modelClass) });
693
+ const notifyMissingSkills = (launch: ReturnType<typeof resolveLaunch>) => {
694
+ if (launch.missingSkills.length) {
695
+ ctx.ui.notify(
696
+ `Subagent role ${role.name} skipped unavailable Pi skills: ${launch.missingSkills.join(", ")}.`,
697
+ "warning",
698
+ );
699
+ }
700
+ };
701
+
702
+ if (params.background) {
703
+ const taskId = `bg-${++backgroundSequence}-${Date.now().toString(36)}`;
704
+ const controller = new AbortController();
705
+ backgroundTasks.set(taskId, controller);
706
+ // Freeze the launching session now: a task that settles after a
707
+ // reload must not deliver into whichever session is active then.
708
+ const launchEpoch = sessionEpoch;
709
+ void (async () => {
710
+ let acquired = false;
711
+ let widgetStatus: Exclude<WidgetStatus, "working"> = "failure";
712
+ // Role is known up front; model/thinking join after launch resolution.
713
+ let details: { role: string; model?: string; thinkingLevel?: string } = { role: role.name };
714
+ try {
715
+ await acquireChildPermit(controller.signal);
716
+ acquired = true;
717
+ // Resolve resources only once launched: a task queued past the
718
+ // cap must not start with model routes or skills resolved before
719
+ // registries or accounts changed while it waited.
720
+ const launch = resolveLaunch();
721
+ notifyMissingSkills(launch);
722
+ details = { role: role.name, model: modelReference(launch.model), thinkingLevel: launch.thinkingLevel };
723
+ startWidgetItem(taskId, role.name, launch.model.id, launch.thinkingLevel, task, ctx);
724
+ const result = await runPi(
725
+ ["--mode", "json", "-p", ...launch.args, `Task: ${task}`],
726
+ ctx.cwd,
727
+ controller.signal,
728
+ undefined,
729
+ (tokens) => updateWidgetTokens(taskId, tokens),
730
+ timeoutPolicy,
731
+ );
732
+ const failed = result.exitCode !== 0 || result.stopReason === "error" || result.stopReason === "aborted";
733
+ widgetStatus = result.stopReason === "aborted" ? "aborted" : failed ? "failure" : "success";
734
+ const text = capOutput(failed
735
+ ? result.errorMessage || result.stderr.trim() || result.output || `Subagent exited with code ${result.exitCode}.`
736
+ : result.output || "(no output)");
737
+ await reportBackground(
738
+ launchEpoch,
739
+ taskId,
740
+ details,
741
+ result.stopReason === "aborted" ? "aborted" : failed ? "failed" : "completed",
742
+ text,
743
+ );
744
+ } catch (error) {
745
+ const aborted = controller.signal.aborted && !(error instanceof SubagentTimeoutError);
746
+ widgetStatus = aborted ? "aborted" : "failure";
747
+ await reportBackground(
748
+ launchEpoch,
749
+ taskId,
750
+ details,
751
+ aborted ? "aborted" : "failed",
752
+ capOutput(error instanceof Error ? error.message : String(error)),
753
+ );
754
+ } finally {
755
+ if (acquired) releaseChildPermit();
756
+ finishWidgetItem(taskId, widgetStatus);
757
+ backgroundTasks.delete(taskId);
758
+ }
759
+ })();
760
+ return {
761
+ content: [{ type: "text" as const, text: `Background subagent ${taskId} started (${role.name}). The outcome arrives as a message when the task settles; keep working or end your turn.` }],
762
+ details: { role: role.name, taskId, background: true },
763
+ };
609
764
  }
610
765
 
611
- const args = ["--mode", "json", "-p", ...launch.args, `Task: ${task}`];
766
+ const launch = resolveLaunch();
767
+ notifyMissingSkills(launch);
768
+ const modelReferenceValue = modelReference(launch.model);
769
+ const details = { role: role.name, model: modelReferenceValue, thinkingLevel: launch.thinkingLevel };
770
+
612
771
  await acquireChildPermit(signal);
613
772
  let widgetStatus: Exclude<WidgetStatus, "working"> = "failure";
614
773
  try {
615
- startWidgetItem(toolCallId, role.name, launch.model.id, thinkingLevel, task, ctx);
616
- const details = { role: role.name, model: modelReferenceValue, thinkingLevel };
774
+ startWidgetItem(toolCallId, role.name, launch.model.id, launch.thinkingLevel, task, ctx);
617
775
  const result = await runPi(
618
- args,
776
+ ["--mode", "json", "-p", ...launch.args, `Task: ${task}`],
619
777
  ctx.cwd,
620
778
  signal,
621
779
  (text) => onUpdate?.({ content: [{ type: "text", text }], details }),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@henryqw/pi-subagent",
3
- "version": "2.5.1",
3
+ "version": "2.9.5",
4
4
  "description": "Delegate one task to an isolated Pi role with explicit extensions and skills.",
5
5
  "keywords": [
6
6
  "pi-package",