@timmyjl12/pi-subagents 0.20.0 → 0.21.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.
Files changed (159) hide show
  1. package/CHANGELOG.md +862 -827
  2. package/README.md +1125 -1080
  3. package/dist/active-agents-prompt.d.ts +31 -9
  4. package/dist/active-agents-prompt.js +73 -9
  5. package/dist/agent-color.js +9 -1
  6. package/dist/agent-file-toggle.d.ts +1 -1
  7. package/dist/agent-manager.d.ts +405 -18
  8. package/dist/agent-manager.js +1661 -131
  9. package/dist/agent-runner.d.ts +45 -6
  10. package/dist/agent-runner.js +109 -18
  11. package/dist/agent-types.d.ts +30 -7
  12. package/dist/agent-types.js +38 -9
  13. package/dist/awaited-result.d.ts +37 -0
  14. package/dist/awaited-result.js +150 -0
  15. package/dist/child-session-shutdown.d.ts +19 -1
  16. package/dist/child-session-shutdown.js +60 -11
  17. package/dist/cleanup-plans.d.ts +10 -0
  18. package/dist/cleanup-plans.js +112 -0
  19. package/dist/cross-extension-rpc.d.ts +8 -1
  20. package/dist/cross-extension-rpc.js +59 -5
  21. package/dist/custom-agents.d.ts +34 -9
  22. package/dist/custom-agents.js +308 -111
  23. package/dist/default-agents.d.ts +1 -1
  24. package/dist/env.d.ts +1 -1
  25. package/dist/error-log.d.ts +6 -0
  26. package/dist/error-log.js +8 -0
  27. package/dist/force-main-model.d.ts +21 -0
  28. package/dist/force-main-model.js +28 -0
  29. package/dist/goal-bridge.d.ts +155 -0
  30. package/dist/goal-bridge.js +305 -0
  31. package/dist/group-join.d.ts +5 -1
  32. package/dist/group-join.js +52 -7
  33. package/dist/index.d.ts +5 -5
  34. package/dist/index.js +2827 -333
  35. package/dist/invocation-config.d.ts +30 -3
  36. package/dist/invocation-config.js +30 -1
  37. package/dist/memory.d.ts +1 -1
  38. package/dist/mention-clone.d.ts +1 -1
  39. package/dist/model-scope.d.ts +1 -1
  40. package/dist/nested-tools.d.ts +22 -1
  41. package/dist/nested-tools.js +120 -26
  42. package/dist/output-file.d.ts +15 -4
  43. package/dist/output-file.js +146 -43
  44. package/dist/prompts.d.ts +1 -1
  45. package/dist/recovery.d.ts +1 -1
  46. package/dist/report-cleanup.d.ts +204 -0
  47. package/dist/report-cleanup.js +1632 -0
  48. package/dist/report-store.d.ts +738 -0
  49. package/dist/report-store.js +3612 -0
  50. package/dist/schedule-store.d.ts +14 -6
  51. package/dist/schedule-store.js +88 -58
  52. package/dist/schedule.d.ts +20 -8
  53. package/dist/schedule.js +135 -74
  54. package/dist/settings.d.ts +39 -11
  55. package/dist/settings.js +22 -5
  56. package/dist/status-note.d.ts +1 -1
  57. package/dist/structured-output.d.ts +1 -1
  58. package/dist/types.d.ts +32 -3
  59. package/dist/ui/agent-mention.d.ts +2 -2
  60. package/dist/ui/agent-widget.d.ts +82 -13
  61. package/dist/ui/agent-widget.js +155 -37
  62. package/dist/ui/cleanup-preview.d.ts +59 -0
  63. package/dist/ui/cleanup-preview.js +466 -0
  64. package/dist/ui/conversation-viewer.d.ts +4 -4
  65. package/dist/ui/conversation-viewer.js +10 -6
  66. package/dist/ui/fleet-list.d.ts +3 -3
  67. package/dist/ui/fleet-list.js +3 -3
  68. package/dist/ui/fleet-overlay.d.ts +37 -6
  69. package/dist/ui/fleet-overlay.js +214 -18
  70. package/dist/ui/hub-feed.d.ts +52 -0
  71. package/dist/ui/hub-feed.js +148 -0
  72. package/dist/ui/native-transcript.js +5 -1
  73. package/dist/ui/schedule-menu.d.ts +1 -1
  74. package/dist/ui/schedule-menu.js +1 -1
  75. package/dist/ui/workflow-card.d.ts +4 -4
  76. package/dist/ui/workflow-dialog.d.ts +4 -4
  77. package/dist/ui/workflow-dialog.js +8 -3
  78. package/dist/ui/workflow-menu.d.ts +2 -2
  79. package/dist/usage.d.ts +12 -0
  80. package/dist/usage.js +28 -1
  81. package/dist/workflow/entry.d.ts +3 -3
  82. package/dist/workflow/host.d.ts +7 -4
  83. package/dist/workflow/host.js +162 -48
  84. package/dist/workflow/journal.d.ts +23 -7
  85. package/dist/workflow/journal.js +80 -23
  86. package/dist/workflow/progress.d.ts +1 -1
  87. package/dist/workflow/runtime.d.ts +45 -6
  88. package/dist/workflow/runtime.js +105 -16
  89. package/dist/workflow/task.d.ts +13 -4
  90. package/dist/workflow/task.js +7 -1
  91. package/dist/workflow/tool-description.d.ts +7 -2
  92. package/dist/workflow/tool-description.js +10 -5
  93. package/docs/{FORK.md → DEVELOPMENT.md} +4 -4
  94. package/docs/artifacts.md +93 -0
  95. package/docs/rpc.md +252 -189
  96. package/docs/runtime-performance.md +53 -0
  97. package/docs/workflows.md +48 -18
  98. package/examples/agent-tool-description.md +2 -2
  99. package/examples/workflows/review-panel.js +6 -3
  100. package/package.json +5 -5
  101. package/src/active-agents-prompt.ts +115 -39
  102. package/src/agent-color.ts +10 -2
  103. package/src/agent-file-toggle.ts +2 -2
  104. package/src/agent-manager.ts +3312 -1601
  105. package/src/agent-runner.ts +164 -36
  106. package/src/agent-types.ts +56 -11
  107. package/src/awaited-result.ts +187 -0
  108. package/src/child-session-shutdown.ts +114 -46
  109. package/src/cleanup-plans.ts +112 -0
  110. package/src/cross-extension-rpc.ts +68 -9
  111. package/src/custom-agents.ts +384 -112
  112. package/src/default-agents.ts +1 -1
  113. package/src/enabled-models.ts +1 -1
  114. package/src/env.ts +1 -1
  115. package/src/error-log.ts +10 -1
  116. package/src/force-main-model.ts +29 -0
  117. package/src/goal-bridge.ts +468 -0
  118. package/src/group-join.ts +56 -9
  119. package/src/index.ts +2987 -349
  120. package/src/invocation-config.ts +50 -4
  121. package/src/memory.ts +1 -1
  122. package/src/mention-clone.ts +3 -3
  123. package/src/model-scope.ts +1 -1
  124. package/src/nested-tools.ts +164 -33
  125. package/src/output-file.ts +168 -46
  126. package/src/prompts.ts +1 -1
  127. package/src/recovery.ts +2 -2
  128. package/src/report-cleanup.ts +2044 -0
  129. package/src/report-store.ts +4130 -0
  130. package/src/schedule-store.ts +244 -201
  131. package/src/schedule.ts +144 -80
  132. package/src/settings.ts +61 -16
  133. package/src/skill-loader.ts +1 -1
  134. package/src/standalone-fallback.ts +2 -2
  135. package/src/status-note.ts +1 -1
  136. package/src/structured-output.ts +1 -1
  137. package/src/types.ts +33 -3
  138. package/src/ui/agent-mention.ts +3 -3
  139. package/src/ui/agent-widget.ts +179 -45
  140. package/src/ui/cleanup-preview.ts +518 -0
  141. package/src/ui/conversation-viewer.ts +19 -15
  142. package/src/ui/fleet-list.ts +7 -7
  143. package/src/ui/fleet-overlay.ts +1048 -847
  144. package/src/ui/hub-feed.ts +179 -0
  145. package/src/ui/native-transcript.ts +7 -3
  146. package/src/ui/schedule-menu.ts +4 -4
  147. package/src/ui/workflow-card.ts +4 -4
  148. package/src/ui/workflow-dialog.ts +10 -6
  149. package/src/ui/workflow-menu.ts +4 -4
  150. package/src/usage.ts +53 -3
  151. package/src/workflow/collisions.ts +1 -1
  152. package/src/workflow/entry.ts +3 -3
  153. package/src/workflow/host.ts +174 -54
  154. package/src/workflow/journal.ts +80 -23
  155. package/src/workflow/progress.ts +1 -1
  156. package/src/workflow/runtime.ts +146 -23
  157. package/src/workflow/saved.ts +3 -3
  158. package/src/workflow/task.ts +18 -7
  159. package/src/workflow/tool-description.ts +10 -5
@@ -1,3 +1,21 @@
1
1
  import type { AgentSession } from "@earendil-works/pi-coding-agent";
2
+ /**
3
+ * How a child session's teardown ended.
4
+ *
5
+ * The old `Promise<void>` contract could not answer the one question cleanup
6
+ * must ask before deleting a session's files: did every shutdown handler
7
+ * actually finish? A three-second timeout used to resolve exactly like a clean
8
+ * teardown, so "disposed" and "gave up waiting" were indistinguishable — and a
9
+ * cleanup that treated them alike could unlink a transcript a still-running
10
+ * handler was about to write.
11
+ */
12
+ export type ChildShutdownStatus = "completed" | "timed_out" | "failed";
13
+ export interface ChildShutdownOutcome {
14
+ status: ChildShutdownStatus;
15
+ /** True only when the bounded handler window expired. */
16
+ timedOut: boolean;
17
+ /** Diagnostic for `failed`/`timed_out`; never proof of quiescence. */
18
+ reason?: string;
19
+ }
2
20
  /** Close the extension lifecycle opened by bindExtensions before invalidating the session. */
3
- export declare function shutdownChildSession(session: AgentSession | undefined): Promise<void>;
21
+ export declare function shutdownChildSession(session: AgentSession | undefined): Promise<ChildShutdownOutcome>;
@@ -2,11 +2,15 @@ import { releaseAdvisorStatus } from "./advisor-status.js";
2
2
  import { disposeChildRecovery } from "./recovery.js";
3
3
  import { releaseToolProgress } from "./ui/tool-progress.js";
4
4
  const CHILD_SHUTDOWN_TIMEOUT_MS = 3_000;
5
+ const COMPLETED = Object.freeze({
6
+ status: "completed",
7
+ timedOut: false,
8
+ });
5
9
  const childShutdowns = new WeakMap();
6
10
  /** Close the extension lifecycle opened by bindExtensions before invalidating the session. */
7
11
  export function shutdownChildSession(session) {
8
12
  if (!session)
9
- return Promise.resolve();
13
+ return Promise.resolve(COMPLETED);
10
14
  const pending = childShutdowns.get(session);
11
15
  if (pending)
12
16
  return pending;
@@ -18,31 +22,76 @@ async function closeChildSession(session) {
18
22
  disposeChildRecovery(session);
19
23
  releaseToolProgress(session);
20
24
  let timeout;
25
+ let timedOut = false;
26
+ let failure;
27
+ let unsubscribeError;
28
+ const observeError = (error) => {
29
+ // The installed ExtensionRunner catches a throwing handler, publishes it
30
+ // here, and RESOLVES emit() normally. Without this subscription a failed
31
+ // real cleanup would be indistinguishable from a clean one.
32
+ if (error.event !== "session_shutdown")
33
+ return;
34
+ const where = error.extensionPath ? ` (${error.extensionPath})` : "";
35
+ failure ??= `session_shutdown handler failed${where}: ${error.error}`;
36
+ };
21
37
  try {
22
38
  const runner = session.extensionRunner;
23
39
  if (runner?.hasHandlers?.("session_shutdown")) {
24
- await Promise.race([
25
- runner.emit({ type: "session_shutdown", reason: "quit" }),
26
- new Promise(resolve => {
27
- timeout = setTimeout(resolve, CHILD_SHUTDOWN_TIMEOUT_MS);
28
- timeout.unref?.();
29
- }),
30
- ]);
40
+ if (typeof runner.onError === "function") {
41
+ unsubscribeError = runner.onError(observeError);
42
+ }
43
+ try {
44
+ await Promise.race([
45
+ runner.emit({ type: "session_shutdown", reason: "quit" }),
46
+ new Promise(resolve => {
47
+ timeout = setTimeout(() => {
48
+ timedOut = true;
49
+ resolve();
50
+ }, CHILD_SHUTDOWN_TIMEOUT_MS);
51
+ timeout.unref?.();
52
+ }),
53
+ ]);
54
+ }
55
+ finally {
56
+ unsubscribeError?.();
57
+ unsubscribeError = undefined;
58
+ }
31
59
  }
32
60
  }
33
- catch {
61
+ catch (error) {
34
62
  // A partially bound extension must not prevent child teardown.
63
+ failure = error instanceof Error ? error.message : String(error);
35
64
  console.error("pi-subagents: child shutdown handler failed");
36
65
  }
37
66
  finally {
38
- releaseAdvisorStatus(session);
67
+ // Always drop the temporary listener, including a rejecting emit and a
68
+ // timeout that never returns through the emit promise.
69
+ unsubscribeError?.();
70
+ try {
71
+ releaseAdvisorStatus(session);
72
+ }
73
+ catch (error) {
74
+ failure ??= error instanceof Error ? error.message : String(error);
75
+ }
39
76
  if (timeout !== undefined)
40
77
  clearTimeout(timeout);
41
78
  try {
42
79
  session.dispose?.();
43
80
  }
44
- catch {
81
+ catch (error) {
82
+ failure ??= error instanceof Error ? error.message : String(error);
45
83
  console.error("pi-subagents: child session disposal failed");
46
84
  }
47
85
  }
86
+ if (timedOut) {
87
+ return {
88
+ status: "timed_out",
89
+ timedOut: true,
90
+ reason: `session_shutdown handler exceeded ${CHILD_SHUTDOWN_TIMEOUT_MS}ms`,
91
+ };
92
+ }
93
+ if (failure !== undefined) {
94
+ return { status: "failed", timedOut: false, reason: failure };
95
+ }
96
+ return COMPLETED;
48
97
  }
@@ -0,0 +1,10 @@
1
+ /** Assemble one confirmed inventory without changing lease ownership or replanning. */
2
+ import { type CleanupPlan } from "./report-cleanup.ts";
3
+ /**
4
+ * A base global inventory sees another local store's lease as foreign. Replace
5
+ * only that namespace with its owning store's session inventory; never relax
6
+ * nonce checks, close stores, or lose global identity evidence.
7
+ */
8
+ export declare function mergeCleanupPlans(base: CleanupPlan, overrides: ReadonlyMap<string, CleanupPlan>): CleanupPlan;
9
+ /** Each root stays in one apply; diagnostics is a single final partition. */
10
+ export declare function partitionCleanupPlan(plan: CleanupPlan): CleanupPlan[];
@@ -0,0 +1,112 @@
1
+ /** Assemble one confirmed inventory without changing lease ownership or replanning. */
2
+ import { cleanupCounts, } from "./report-cleanup.js";
3
+ import { normalizeReportPath } from "./report-store.js";
4
+ function withFiles(plan, files) {
5
+ const agents = new Set();
6
+ const sessions = new Set();
7
+ for (const file of files) {
8
+ if (file.agentId !== undefined)
9
+ agents.add(file.agentId);
10
+ if (file.kind === "child-session" && file.sessionFile !== undefined)
11
+ sessions.add(file.sessionFile);
12
+ }
13
+ return { ...plan, files, counts: cleanupCounts(files), agentIds: [...agents].sort(), sessionFiles: [...sessions].sort() };
14
+ }
15
+ /**
16
+ * A base global inventory sees another local store's lease as foreign. Replace
17
+ * only that namespace with its owning store's session inventory; never relax
18
+ * nonce checks, close stores, or lose global identity evidence.
19
+ */
20
+ export function mergeCleanupPlans(base, overrides) {
21
+ if (base.scope !== "global" && overrides.size > 0) {
22
+ throw new Error("Owning-store overrides require global scope");
23
+ }
24
+ const roots = new Map(base.roots.map(root => [root.rootSessionId, root]));
25
+ const files = new Map();
26
+ const conflicts = new Set();
27
+ const skipped = base.skipped.filter(skip => skip.rootSessionId === undefined || !overrides.has(skip.rootSessionId));
28
+ let identityUncertainty = base.identityUncertainty;
29
+ const addFile = (file) => {
30
+ const key = normalizeReportPath(file.path);
31
+ if (conflicts.has(key)) {
32
+ skipped.push({ path: file.path, rootSessionId: file.rootSessionId, kind: file.kind, agentId: file.agentId, workflowId: file.workflowId, reason: "conflicting-preview-ownership" });
33
+ return;
34
+ }
35
+ const previous = files.get(key);
36
+ if (previous === undefined) {
37
+ files.set(key, file);
38
+ return;
39
+ }
40
+ const same = previous.kind === file.kind && previous.rootSessionId === file.rootSessionId
41
+ && previous.agentId === file.agentId && previous.workflowId === file.workflowId
42
+ && previous.size === file.size && previous.mtimeMs === file.mtimeMs
43
+ && previous.fingerprint === file.fingerprint && previous.entryGeneration === file.entryGeneration
44
+ && previous.workflowUpdatedAt === file.workflowUpdatedAt && previous.legacy === file.legacy
45
+ && previous.shared === file.shared && previous.sessionFile === file.sessionFile;
46
+ if (same) {
47
+ if (file.readState === "unread" || (previous.readState === "read" && file.readState === "unknown")) {
48
+ files.set(key, { ...previous, readState: file.readState });
49
+ }
50
+ return;
51
+ }
52
+ files.delete(key);
53
+ conflicts.add(key);
54
+ for (const candidate of [previous, file]) {
55
+ skipped.push({ path: candidate.path, rootSessionId: candidate.rootSessionId, kind: candidate.kind, agentId: candidate.agentId, workflowId: candidate.workflowId, reason: "conflicting-preview-ownership" });
56
+ }
57
+ };
58
+ for (const file of base.files) {
59
+ if (!overrides.has(file.rootSessionId))
60
+ addFile(file);
61
+ }
62
+ for (const [rootSessionId, plan] of overrides) {
63
+ identityUncertainty ??= plan.identityUncertainty;
64
+ // Preserve all identities, not just the namespace whose candidates replace
65
+ // the base. Only its owning store may replace an existing fingerprint.
66
+ for (const root of plan.roots) {
67
+ if (root.rootSessionId === rootSessionId || !roots.has(root.rootSessionId))
68
+ roots.set(root.rootSessionId, root);
69
+ }
70
+ for (const file of plan.files) {
71
+ if (file.rootSessionId === rootSessionId)
72
+ addFile(file);
73
+ }
74
+ for (const skip of plan.skipped) {
75
+ if (skip.reason !== "legacy-outside-session-scope" && skip.rootSessionId === rootSessionId)
76
+ skipped.push(skip);
77
+ }
78
+ }
79
+ const uniqueSkips = new Map();
80
+ for (const skip of skipped) {
81
+ const key = JSON.stringify([skip.path === undefined ? null : normalizeReportPath(skip.path), skip.kind, skip.rootSessionId, skip.agentId, skip.workflowId, skip.reason, skip.legacy]);
82
+ uniqueSkips.set(key, skip);
83
+ }
84
+ return withFiles({
85
+ ...base,
86
+ roots: [...roots.values()],
87
+ skipped: [...uniqueSkips.values()],
88
+ ...(identityUncertainty === undefined ? {} : { identityUncertainty }),
89
+ }, [...files.values()]);
90
+ }
91
+ /** Each root stays in one apply; diagnostics is a single final partition. */
92
+ export function partitionCleanupPlan(plan) {
93
+ const groups = new Map();
94
+ for (const file of plan.files) {
95
+ const key = file.kind === "diagnostics-log" ? "" : file.rootSessionId;
96
+ const group = groups.get(key);
97
+ if (group === undefined)
98
+ groups.set(key, [file]);
99
+ else
100
+ group.push(file);
101
+ }
102
+ const result = [];
103
+ const keys = [...groups.keys()].filter(key => key !== "").sort();
104
+ if (groups.has(""))
105
+ keys.push("");
106
+ for (const key of keys) {
107
+ // Keep ALL confirmed identity fingerprints and uncertainty in each part.
108
+ // The caller aggregates original preview skips exactly once.
109
+ result.push(withFiles({ ...plan, skipped: [] }, groups.get(key) ?? []));
110
+ }
111
+ return result;
112
+ }
@@ -12,7 +12,7 @@
12
12
  * (including the fields spawnTopLevel strips), every error string, the
13
13
  * completion-notification race, and what protocol version 2 does not promise.
14
14
  */
15
- import type { AgentRecord } from "./types.js";
15
+ import type { AgentConfig, AgentRecord } from "./types.ts";
16
16
  /** Minimal event bus interface needed by the RPC handlers. */
17
17
  export interface EventBus {
18
18
  on(event: string, handler: (data: unknown) => void): () => void;
@@ -52,6 +52,13 @@ export interface RpcDeps {
52
52
  pi: unknown;
53
53
  getCtx: () => unknown | undefined;
54
54
  manager: SpawnCapable;
55
+ /**
56
+ * Refreshes the caller's scoped registry for an ordinary spawn admission.
57
+ * When present, the requested type is resolved against this map and the
58
+ * admitted definition is cloned into the spawn options. Absent keeps the
59
+ * legacy pass-through behaviour for callers that wire no async preparation.
60
+ */
61
+ prepare?: () => Promise<Map<string, AgentConfig>>;
55
62
  }
56
63
  export interface RpcHandle {
57
64
  unsubPing: () => void;
@@ -13,6 +13,9 @@
13
13
  * completion-notification race, and what protocol version 2 does not promise.
14
14
  */
15
15
  import { isTopLevelAgent } from "./agent-manager.js";
16
+ import { getAllowPerCallTurnLimits, resolveEffectiveMaxTurns } from "./agent-runner.js";
17
+ import { cloneAgentDefinition, getAgentConfigIn, resolveSpawnTypeIn } from "./agent-types.js";
18
+ import { isForceMainModel } from "./force-main-model.js";
16
19
  import { resolveModel } from "./model-resolver.js";
17
20
  import { checkModelScope } from "./model-scope.js";
18
21
  /** RPC protocol version — bumped when the envelope or method contracts change. */
@@ -51,18 +54,59 @@ export function registerRpcHandlers(deps) {
51
54
  const ctx = getCtx();
52
55
  if (!ctx)
53
56
  throw new Error("No active session");
57
+ // Refresh and resolve against the caller's OWN scoped registry before
58
+ // anything can suspend. The clone freezes prompt, tool permissions and
59
+ // model/session/nesting policy through queueing, worktree setup and the
60
+ // runner; a later process-wide reload cannot widen or narrow this child.
61
+ // No `prepare` means the legacy path: the manager receives the requested
62
+ // type and no definition snapshot, exactly as before.
63
+ const registry = deps.prepare === undefined ? undefined : await deps.prepare();
64
+ let spawnType = type;
65
+ let agentDefinition;
66
+ if (registry !== undefined) {
67
+ const dispatch = resolveSpawnTypeIn(registry, type);
68
+ if (!dispatch.ok)
69
+ throw new Error(dispatch.message);
70
+ spawnType = dispatch.type;
71
+ const config = getAgentConfigIn(registry, spawnType);
72
+ agentDefinition = config === undefined ? undefined : cloneAgentDefinition(config);
73
+ }
54
74
  // Cross-extension RPC callers (e.g. pi-tasks TaskExecute) naturally
55
75
  // forward serializable values, so options.model can be a string like
56
76
  // "openai-codex/gpt-5.5". Resolve it to a real Model instance here
57
77
  // — same pattern the scheduler path already uses — so the spawned
58
78
  // agent's auth lookup doesn't crash with "No API key found for
59
79
  // undefined".
60
- let normalizedOptions = options ?? {};
80
+ // Own caller options only: inherited admission fields must not reach a
81
+ // legacy manager when no other normalization happens to copy the object.
82
+ let normalizedOptions = { ...(options ?? {}) };
83
+ // Admission state comes only from this handler's prepared scoped registry.
84
+ // Never mutate the caller or trust its own/non-enumerable definition.
85
+ delete normalizedOptions.agentDefinition;
86
+ // Caller caps are a policy opt-in, and an RPC payload is unvalidated: a
87
+ // caller that bypasses the tool schema can still send `maxTurns`. Strip
88
+ // it here so the runner's low-level option contract cannot be reached
89
+ // around the switch. Copy first — never mutate the caller's own object.
90
+ if (!getAllowPerCallTurnLimits()) {
91
+ normalizedOptions = { ...normalizedOptions };
92
+ delete normalizedOptions.maxTurns;
93
+ const invocation = normalizedOptions.invocation;
94
+ if (invocation !== null && typeof invocation === "object") {
95
+ normalizedOptions.invocation = { ...invocation, maxTurns: resolveEffectiveMaxTurns(spawnType) };
96
+ }
97
+ }
61
98
  // `!= null` on purpose: a JSON-forwarding caller can serialize an unset
62
99
  // field as null, and the runner reads `options.model ?? default`, so null
63
100
  // means "inherit" — not an override to resolve or scope-check.
64
101
  const override = normalizedOptions.model;
65
- if (override != null) {
102
+ if (override != null && isForceMainModel()) {
103
+ // Dropped, not deferred: a queued spawn reads the switch when it
104
+ // STARTS, and a raw string that reaches the runner after a mid-queue
105
+ // `/subagents on` is the "No API key found for undefined" crash this
106
+ // resolution exists to prevent.
107
+ normalizedOptions = { ...normalizedOptions, model: undefined };
108
+ }
109
+ else if (override != null) {
66
110
  const { modelRegistry, cwd } = ctx;
67
111
  // Names the override the same way in both messages below; an object
68
112
  // override would otherwise interpolate as "[object Object]".
@@ -93,17 +137,27 @@ export function registerRpcHandlers(deps) {
93
137
  cwd: cwd ?? process.cwd(),
94
138
  modelRegistry,
95
139
  callerSupplied: true,
96
- agentLabel: type,
140
+ agentLabel: spawnType,
97
141
  modelInput: label,
98
142
  });
99
143
  if (verdict.kind === "error")
100
144
  throw new Error(verdict.message);
101
145
  }
102
- const id = manager.spawn(pi, ctx, type, prompt, normalizedOptions);
146
+ const spawnOptions = agentDefinition === undefined
147
+ ? normalizedOptions
148
+ : { ...normalizedOptions, agentDefinition };
149
+ const id = manager.spawn(pi, ctx, spawnType, prompt, spawnOptions);
103
150
  // With isolation: "worktree" the agent starts asynchronously — wait for
104
151
  // it, so a strict-isolation failure is still an error envelope rather
105
152
  // than an id for an agent that never ran.
106
- await manager.awaitStartup(id);
153
+ try {
154
+ await manager.awaitStartup(id);
155
+ }
156
+ catch (error) {
157
+ // The error envelope is the result; do not also wake the main model.
158
+ manager.consumeResult(id);
159
+ throw error;
160
+ }
107
161
  return { id };
108
162
  });
109
163
  const unsubStop = handleRpc(events, "subagents:rpc:stop", ({ agentId }) => {
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * custom-agents.ts — Load user-defined agents from project (.pi/agents/, plus the shared .agents/agents/ workspace) and global ($PI_CODING_AGENT_DIR/agents/, default ~/.pi/agent/agents/) locations.
3
3
  */
4
- import type { AgentConfig } from "./types.js";
4
+ import type { AgentConfig } from "./types.ts";
5
5
  /**
6
6
  * Scan for custom agent .md files from multiple locations.
7
7
  * Discovery hierarchy (higher priority wins):
@@ -22,17 +22,22 @@ import type { AgentConfig } from "./types.js";
22
22
  */
23
23
  export declare function loadCustomAgents(cwd: string, strict?: boolean): Map<string, AgentConfig>;
24
24
  /**
25
- * Read and parse one agent file, or warn and return undefined for the caller to
26
- * skip. One bad file must not take the whole extension down with it — an
27
- * unparseable `.md` used to abort activation, so pi exited before the TUI.
25
+ * Async twin of {@link loadCustomAgents} for ordinary awaitable admission.
28
26
  *
29
- * The path is as much of the fix as the recovery: a bare YAML error ("line 2,
30
- * column 14") is unactionable when agents come from three directories at once,
31
- * and the only other symptom is `Unknown agent type`, which reads like a typo.
27
+ * Discovery and content reads are fresh every call; only the raw YAML parse is
28
+ * reused, and only when the bytes just read are identical. That distinction is
29
+ * deliberate: caching a size/mtime stamp would let a same-size edit through,
30
+ * and caching a validated AgentConfig would make a lenient load's skipped or
31
+ * coerced field authorize a strict request. Cache entries are bounded by both
32
+ * entry count and retained bytes, so a pathological directory cannot pin
33
+ * arbitrary content for the process lifetime.
32
34
  *
33
- * Under `strict` the same failure rethrows, still naming the path, so callers
34
- * that opted into failing closed stop rather than run a substituted agent.
35
+ * Concurrent callers for the same three-directory scope and strictness share
36
+ * one refresh. Each gets its own Map so a caller mutating its result cannot
37
+ * rewrite another caller's registry; warnings are collected per load and
38
+ * committed atomically when the shared load finishes.
35
39
  */
40
+ export declare function loadCustomAgentsAsync(cwd: string, strict?: boolean): Promise<Map<string, AgentConfig>>;
36
41
  /**
37
42
  * Parse an agent file's frontmatter, tolerating a leading UTF-8 BOM.
38
43
  *
@@ -52,3 +57,23 @@ export declare function parseAgentFrontmatter<T extends Record<string, unknown>>
52
57
  frontmatter: T;
53
58
  body: string;
54
59
  };
60
+ /**
61
+ * Bounds for the raw parse cache. `bytes` counts both the content used for
62
+ * exact equality and the parsed body retained beside it; it is a storage bound,
63
+ * not a limit on file size (a file larger than the cap simply is not cached).
64
+ */
65
+ export declare const AGENT_PARSE_CACHE_MAX_ENTRIES = 64;
66
+ export declare const AGENT_PARSE_CACHE_MAX_BYTES: number;
67
+ export interface AgentParseCacheStats {
68
+ entries: number;
69
+ bytes: number;
70
+ parses: number;
71
+ hits: number;
72
+ evictions: number;
73
+ syncReads: number;
74
+ asyncReads: number;
75
+ }
76
+ /** Operation counts used by the definition-refresh tests. */
77
+ export declare function getAgentParseCacheStats(): AgentParseCacheStats;
78
+ /** Drop retained parses and counters so tests start from a known cache. */
79
+ export declare function resetAgentParseCache(): void;