@timmyjl12/pi-subagents 0.20.0 → 0.21.1

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 +3616 -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 +4133 -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,46 +1,114 @@
1
- import type { AgentSession } from "@earendil-works/pi-coding-agent";
2
- import { releaseAdvisorStatus } from "./advisor-status.js";
3
- import { disposeChildRecovery } from "./recovery.js";
4
- import { releaseToolProgress } from "./ui/tool-progress.js";
5
-
6
- const CHILD_SHUTDOWN_TIMEOUT_MS = 3_000;
7
- const childShutdowns = new WeakMap<AgentSession, Promise<void>>();
8
-
9
- /** Close the extension lifecycle opened by bindExtensions before invalidating the session. */
10
- export function shutdownChildSession(session: AgentSession | undefined): Promise<void> {
11
- if (!session) return Promise.resolve();
12
- const pending = childShutdowns.get(session);
13
- if (pending) return pending;
14
- const shutdown = closeChildSession(session);
15
- childShutdowns.set(session, shutdown);
16
- return shutdown;
17
- }
18
-
19
- async function closeChildSession(session: AgentSession): Promise<void> {
20
- disposeChildRecovery(session);
21
- releaseToolProgress(session);
22
- let timeout: ReturnType<typeof setTimeout> | undefined;
23
- try {
24
- const runner = session.extensionRunner;
25
- if (runner?.hasHandlers?.("session_shutdown")) {
26
- await Promise.race([
27
- runner.emit({ type: "session_shutdown", reason: "quit" }),
28
- new Promise<void>(resolve => {
29
- timeout = setTimeout(resolve, CHILD_SHUTDOWN_TIMEOUT_MS);
30
- timeout.unref?.();
31
- }),
32
- ]);
33
- }
34
- } catch {
35
- // A partially bound extension must not prevent child teardown.
36
- console.error("pi-subagents: child shutdown handler failed");
37
- } finally {
38
- releaseAdvisorStatus(session);
39
- if (timeout !== undefined) clearTimeout(timeout);
40
- try {
41
- session.dispose?.();
42
- } catch {
43
- console.error("pi-subagents: child session disposal failed");
44
- }
45
- }
46
- }
1
+ import type { AgentSession, ExtensionError } from "@earendil-works/pi-coding-agent";
2
+ import { releaseAdvisorStatus } from "./advisor-status.ts";
3
+ import { disposeChildRecovery } from "./recovery.ts";
4
+ import { releaseToolProgress } from "./ui/tool-progress.ts";
5
+
6
+ const CHILD_SHUTDOWN_TIMEOUT_MS = 3_000;
7
+
8
+ /**
9
+ * How a child session's teardown ended.
10
+ *
11
+ * The old `Promise<void>` contract could not answer the one question cleanup
12
+ * must ask before deleting a session's files: did every shutdown handler
13
+ * actually finish? A three-second timeout used to resolve exactly like a clean
14
+ * teardown, so "disposed" and "gave up waiting" were indistinguishable — and a
15
+ * cleanup that treated them alike could unlink a transcript a still-running
16
+ * handler was about to write.
17
+ */
18
+ export type ChildShutdownStatus = "completed" | "timed_out" | "failed";
19
+
20
+ export interface ChildShutdownOutcome {
21
+ status: ChildShutdownStatus;
22
+ /** True only when the bounded handler window expired. */
23
+ timedOut: boolean;
24
+ /** Diagnostic for `failed`/`timed_out`; never proof of quiescence. */
25
+ reason?: string;
26
+ }
27
+
28
+ const COMPLETED: ChildShutdownOutcome = Object.freeze({
29
+ status: "completed",
30
+ timedOut: false,
31
+ });
32
+
33
+ const childShutdowns = new WeakMap<AgentSession, Promise<ChildShutdownOutcome>>();
34
+
35
+ /** Close the extension lifecycle opened by bindExtensions before invalidating the session. */
36
+ export function shutdownChildSession(session: AgentSession | undefined): Promise<ChildShutdownOutcome> {
37
+ if (!session) return Promise.resolve(COMPLETED);
38
+ const pending = childShutdowns.get(session);
39
+ if (pending) return pending;
40
+ const shutdown = closeChildSession(session);
41
+ childShutdowns.set(session, shutdown);
42
+ return shutdown;
43
+ }
44
+
45
+ async function closeChildSession(session: AgentSession): Promise<ChildShutdownOutcome> {
46
+ disposeChildRecovery(session);
47
+ releaseToolProgress(session);
48
+ let timeout: ReturnType<typeof setTimeout> | undefined;
49
+ let timedOut = false;
50
+ let failure: string | undefined;
51
+ let unsubscribeError: (() => void) | undefined;
52
+ const observeError = (error: ExtensionError) => {
53
+ // The installed ExtensionRunner catches a throwing handler, publishes it
54
+ // here, and RESOLVES emit() normally. Without this subscription a failed
55
+ // real cleanup would be indistinguishable from a clean one.
56
+ if (error.event !== "session_shutdown") return;
57
+ const where = error.extensionPath ? ` (${error.extensionPath})` : "";
58
+ failure ??= `session_shutdown handler failed${where}: ${error.error}`;
59
+ };
60
+ try {
61
+ const runner = session.extensionRunner;
62
+ if (runner?.hasHandlers?.("session_shutdown")) {
63
+ if (typeof runner.onError === "function") {
64
+ unsubscribeError = runner.onError(observeError);
65
+ }
66
+ try {
67
+ await Promise.race([
68
+ runner.emit({ type: "session_shutdown", reason: "quit" }),
69
+ new Promise<void>(resolve => {
70
+ timeout = setTimeout(() => {
71
+ timedOut = true;
72
+ resolve();
73
+ }, CHILD_SHUTDOWN_TIMEOUT_MS);
74
+ timeout.unref?.();
75
+ }),
76
+ ]);
77
+ } finally {
78
+ unsubscribeError?.();
79
+ unsubscribeError = undefined;
80
+ }
81
+ }
82
+ } catch (error) {
83
+ // A partially bound extension must not prevent child teardown.
84
+ failure = error instanceof Error ? error.message : String(error);
85
+ console.error("pi-subagents: child shutdown handler failed");
86
+ } finally {
87
+ // Always drop the temporary listener, including a rejecting emit and a
88
+ // timeout that never returns through the emit promise.
89
+ unsubscribeError?.();
90
+ try {
91
+ releaseAdvisorStatus(session);
92
+ } catch (error) {
93
+ failure ??= error instanceof Error ? error.message : String(error);
94
+ }
95
+ if (timeout !== undefined) clearTimeout(timeout);
96
+ try {
97
+ session.dispose?.();
98
+ } catch (error) {
99
+ failure ??= error instanceof Error ? error.message : String(error);
100
+ console.error("pi-subagents: child session disposal failed");
101
+ }
102
+ }
103
+ if (timedOut) {
104
+ return {
105
+ status: "timed_out",
106
+ timedOut: true,
107
+ reason: `session_shutdown handler exceeded ${CHILD_SHUTDOWN_TIMEOUT_MS}ms`,
108
+ };
109
+ }
110
+ if (failure !== undefined) {
111
+ return { status: "failed", timedOut: false, reason: failure };
112
+ }
113
+ return COMPLETED;
114
+ }
@@ -0,0 +1,112 @@
1
+ /** Assemble one confirmed inventory without changing lease ownership or replanning. */
2
+ import {
3
+ type CleanupFileInventory,
4
+ type CleanupPlan,
5
+ type CleanupSkip,
6
+ cleanupCounts,
7
+ } from "./report-cleanup.ts";
8
+ import { normalizeReportPath } from "./report-store.ts";
9
+
10
+ function withFiles(plan: CleanupPlan, files: readonly CleanupFileInventory[]): CleanupPlan {
11
+ const agents = new Set<string>();
12
+ const sessions = new Set<string>();
13
+ for (const file of files) {
14
+ if (file.agentId !== undefined) agents.add(file.agentId);
15
+ if (file.kind === "child-session" && file.sessionFile !== undefined) sessions.add(file.sessionFile);
16
+ }
17
+ return { ...plan, files, counts: cleanupCounts(files), agentIds: [...agents].sort(), sessionFiles: [...sessions].sort() };
18
+ }
19
+
20
+ /**
21
+ * A base global inventory sees another local store's lease as foreign. Replace
22
+ * only that namespace with its owning store's session inventory; never relax
23
+ * nonce checks, close stores, or lose global identity evidence.
24
+ */
25
+ export function mergeCleanupPlans(base: CleanupPlan, overrides: ReadonlyMap<string, CleanupPlan>): CleanupPlan {
26
+ if (base.scope !== "global" && overrides.size > 0) {
27
+ throw new Error("Owning-store overrides require global scope");
28
+ }
29
+ const roots = new Map(base.roots.map(root => [root.rootSessionId, root]));
30
+ const files = new Map<string, CleanupFileInventory>();
31
+ const conflicts = new Set<string>();
32
+ const skipped: CleanupSkip[] = base.skipped.filter(skip => skip.rootSessionId === undefined || !overrides.has(skip.rootSessionId));
33
+ let identityUncertainty = base.identityUncertainty;
34
+
35
+ const addFile = (file: CleanupFileInventory) => {
36
+ const key = normalizeReportPath(file.path);
37
+ if (conflicts.has(key)) {
38
+ skipped.push({ path: file.path, rootSessionId: file.rootSessionId, kind: file.kind, agentId: file.agentId, workflowId: file.workflowId, reason: "conflicting-preview-ownership" });
39
+ return;
40
+ }
41
+ const previous = files.get(key);
42
+ if (previous === undefined) {
43
+ files.set(key, file);
44
+ return;
45
+ }
46
+ const same = previous.kind === file.kind && previous.rootSessionId === file.rootSessionId
47
+ && previous.agentId === file.agentId && previous.workflowId === file.workflowId
48
+ && previous.size === file.size && previous.mtimeMs === file.mtimeMs
49
+ && previous.fingerprint === file.fingerprint && previous.entryGeneration === file.entryGeneration
50
+ && previous.workflowUpdatedAt === file.workflowUpdatedAt && previous.legacy === file.legacy
51
+ && previous.shared === file.shared && previous.sessionFile === file.sessionFile;
52
+ if (same) {
53
+ if (file.readState === "unread" || (previous.readState === "read" && file.readState === "unknown")) {
54
+ files.set(key, { ...previous, readState: file.readState });
55
+ }
56
+ return;
57
+ }
58
+ files.delete(key);
59
+ conflicts.add(key);
60
+ for (const candidate of [previous, file]) {
61
+ skipped.push({ path: candidate.path, rootSessionId: candidate.rootSessionId, kind: candidate.kind, agentId: candidate.agentId, workflowId: candidate.workflowId, reason: "conflicting-preview-ownership" });
62
+ }
63
+ };
64
+ for (const file of base.files) {
65
+ if (!overrides.has(file.rootSessionId)) addFile(file);
66
+ }
67
+ for (const [rootSessionId, plan] of overrides) {
68
+ identityUncertainty ??= plan.identityUncertainty;
69
+ // Preserve all identities, not just the namespace whose candidates replace
70
+ // the base. Only its owning store may replace an existing fingerprint.
71
+ for (const root of plan.roots) {
72
+ if (root.rootSessionId === rootSessionId || !roots.has(root.rootSessionId)) roots.set(root.rootSessionId, root);
73
+ }
74
+ for (const file of plan.files) {
75
+ if (file.rootSessionId === rootSessionId) addFile(file);
76
+ }
77
+ for (const skip of plan.skipped) {
78
+ if (skip.reason !== "legacy-outside-session-scope" && skip.rootSessionId === rootSessionId) skipped.push(skip);
79
+ }
80
+ }
81
+ const uniqueSkips = new Map<string, CleanupSkip>();
82
+ for (const skip of skipped) {
83
+ const key = JSON.stringify([skip.path === undefined ? null : normalizeReportPath(skip.path), skip.kind, skip.rootSessionId, skip.agentId, skip.workflowId, skip.reason, skip.legacy]);
84
+ uniqueSkips.set(key, skip);
85
+ }
86
+ return withFiles({
87
+ ...base,
88
+ roots: [...roots.values()],
89
+ skipped: [...uniqueSkips.values()],
90
+ ...(identityUncertainty === undefined ? {} : { identityUncertainty }),
91
+ }, [...files.values()]);
92
+ }
93
+
94
+ /** Each root stays in one apply; diagnostics is a single final partition. */
95
+ export function partitionCleanupPlan(plan: CleanupPlan): CleanupPlan[] {
96
+ const groups = new Map<string, CleanupFileInventory[]>();
97
+ for (const file of plan.files) {
98
+ const key = file.kind === "diagnostics-log" ? "" : file.rootSessionId;
99
+ const group = groups.get(key);
100
+ if (group === undefined) groups.set(key, [file]);
101
+ else group.push(file);
102
+ }
103
+ const result: CleanupPlan[] = [];
104
+ const keys = [...groups.keys()].filter(key => key !== "").sort();
105
+ if (groups.has("")) 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
+ }
@@ -13,10 +13,13 @@
13
13
  * completion-notification race, and what protocol version 2 does not promise.
14
14
  */
15
15
 
16
- import { isTopLevelAgent } from "./agent-manager.js";
17
- import { type ModelRegistry, resolveModel } from "./model-resolver.js";
18
- import { checkModelScope } from "./model-scope.js";
19
- import type { AgentRecord } from "./types.js";
16
+ import { isTopLevelAgent } from "./agent-manager.ts";
17
+ import { getAllowPerCallTurnLimits, resolveEffectiveMaxTurns } from "./agent-runner.ts";
18
+ import { cloneAgentDefinition, getAgentConfigIn, resolveSpawnTypeIn } from "./agent-types.ts";
19
+ import { isForceMainModel } from "./force-main-model.ts";
20
+ import { type ModelRegistry, resolveModel } from "./model-resolver.ts";
21
+ import { checkModelScope } from "./model-scope.ts";
22
+ import type { AgentConfig, AgentRecord } from "./types.ts";
20
23
 
21
24
  /** Minimal event bus interface needed by the RPC handlers. */
22
25
  export interface EventBus {
@@ -57,6 +60,13 @@ export interface RpcDeps {
57
60
  pi: unknown; // passed through to manager.spawn
58
61
  getCtx: () => unknown | undefined; // returns current ExtensionContext
59
62
  manager: SpawnCapable;
63
+ /**
64
+ * Refreshes the caller's scoped registry for an ordinary spawn admission.
65
+ * When present, the requested type is resolved against this map and the
66
+ * admitted definition is cloned into the spawn options. Absent keeps the
67
+ * legacy pass-through behaviour for callers that wire no async preparation.
68
+ */
69
+ prepare?: () => Promise<Map<string, AgentConfig>>;
60
70
  }
61
71
 
62
72
  export interface RpcHandle {
@@ -106,18 +116,58 @@ export function registerRpcHandlers(deps: RpcDeps): RpcHandle {
106
116
  const ctx = getCtx();
107
117
  if (!ctx) throw new Error("No active session");
108
118
 
119
+ // Refresh and resolve against the caller's OWN scoped registry before
120
+ // anything can suspend. The clone freezes prompt, tool permissions and
121
+ // model/session/nesting policy through queueing, worktree setup and the
122
+ // runner; a later process-wide reload cannot widen or narrow this child.
123
+ // No `prepare` means the legacy path: the manager receives the requested
124
+ // type and no definition snapshot, exactly as before.
125
+ const registry = deps.prepare === undefined ? undefined : await deps.prepare();
126
+ let spawnType = type;
127
+ let agentDefinition: AgentConfig | undefined;
128
+ if (registry !== undefined) {
129
+ const dispatch = resolveSpawnTypeIn(registry, type);
130
+ if (!dispatch.ok) throw new Error(dispatch.message);
131
+ spawnType = dispatch.type;
132
+ const config = getAgentConfigIn(registry, spawnType);
133
+ agentDefinition = config === undefined ? undefined : cloneAgentDefinition(config);
134
+ }
135
+
109
136
  // Cross-extension RPC callers (e.g. pi-tasks TaskExecute) naturally
110
137
  // forward serializable values, so options.model can be a string like
111
138
  // "openai-codex/gpt-5.5". Resolve it to a real Model instance here
112
139
  // — same pattern the scheduler path already uses — so the spawned
113
140
  // agent's auth lookup doesn't crash with "No API key found for
114
141
  // undefined".
115
- let normalizedOptions = options ?? {};
142
+ // Own caller options only: inherited admission fields must not reach a
143
+ // legacy manager when no other normalization happens to copy the object.
144
+ let normalizedOptions = { ...(options ?? {}) };
145
+ // Admission state comes only from this handler's prepared scoped registry.
146
+ // Never mutate the caller or trust its own/non-enumerable definition.
147
+ delete normalizedOptions.agentDefinition;
148
+ // Caller caps are a policy opt-in, and an RPC payload is unvalidated: a
149
+ // caller that bypasses the tool schema can still send `maxTurns`. Strip
150
+ // it here so the runner's low-level option contract cannot be reached
151
+ // around the switch. Copy first — never mutate the caller's own object.
152
+ if (!getAllowPerCallTurnLimits()) {
153
+ normalizedOptions = { ...normalizedOptions };
154
+ delete normalizedOptions.maxTurns;
155
+ const invocation = normalizedOptions.invocation;
156
+ if (invocation !== null && typeof invocation === "object") {
157
+ normalizedOptions.invocation = { ...invocation, maxTurns: resolveEffectiveMaxTurns(spawnType) };
158
+ }
159
+ }
116
160
  // `!= null` on purpose: a JSON-forwarding caller can serialize an unset
117
161
  // field as null, and the runner reads `options.model ?? default`, so null
118
162
  // means "inherit" — not an override to resolve or scope-check.
119
163
  const override = normalizedOptions.model;
120
- if (override != null) {
164
+ if (override != null && isForceMainModel()) {
165
+ // Dropped, not deferred: a queued spawn reads the switch when it
166
+ // STARTS, and a raw string that reaches the runner after a mid-queue
167
+ // `/subagents on` is the "No API key found for undefined" crash this
168
+ // resolution exists to prevent.
169
+ normalizedOptions = { ...normalizedOptions, model: undefined };
170
+ } else if (override != null) {
121
171
  const { modelRegistry, cwd } = ctx as { modelRegistry?: ModelRegistry; cwd?: string };
122
172
  // Names the override the same way in both messages below; an object
123
173
  // override would otherwise interpolate as "[object Object]".
@@ -149,17 +199,26 @@ export function registerRpcHandlers(deps: RpcDeps): RpcHandle {
149
199
  cwd: cwd ?? process.cwd(),
150
200
  modelRegistry,
151
201
  callerSupplied: true,
152
- agentLabel: type,
202
+ agentLabel: spawnType,
153
203
  modelInput: label,
154
204
  });
155
205
  if (verdict.kind === "error") throw new Error(verdict.message);
156
206
  }
157
207
 
158
- const id = manager.spawn(pi, ctx, type, prompt, normalizedOptions);
208
+ const spawnOptions = agentDefinition === undefined
209
+ ? normalizedOptions
210
+ : { ...normalizedOptions, agentDefinition };
211
+ const id = manager.spawn(pi, ctx, spawnType, prompt, spawnOptions);
159
212
  // With isolation: "worktree" the agent starts asynchronously — wait for
160
213
  // it, so a strict-isolation failure is still an error envelope rather
161
214
  // than an id for an agent that never ran.
162
- await manager.awaitStartup(id);
215
+ try {
216
+ await manager.awaitStartup(id);
217
+ } catch (error) {
218
+ // The error envelope is the result; do not also wake the main model.
219
+ manager.consumeResult(id);
220
+ throw error;
221
+ }
163
222
  return { id };
164
223
  },
165
224
  );