@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,6 +1,6 @@
1
1
  import { Type } from "@sinclair/typebox";
2
- import { type ModelRegistry, resolveModel } from "./model-resolver.js";
3
- import type { AgentConfig, IsolationMode, JoinMode, ThinkingLevel } from "./types.js";
2
+ import { type ModelRegistry, resolveModel } from "./model-resolver.ts";
3
+ import type { AgentConfig, IsolationMode, JoinMode, ThinkingLevel } from "./types.ts";
4
4
 
5
5
  /**
6
6
  * Agent pins are authoritative: a qualified `provider/id` pin resolves exactly
@@ -129,10 +129,40 @@ export function isolationParam(enabled: boolean): Partial<typeof isolationParamS
129
129
  return enabled ? isolationParamShape : {};
130
130
  }
131
131
 
132
+ /**
133
+ * The model-facing `max_turns` parameter, shared by the top-level `Agent` tool
134
+ * and the nested delegation tool.
135
+ *
136
+ * Like `isolationParam`, this is a `Partial` shape meant to be spread into a
137
+ * `Type.Object`: when caller caps are disabled the field is omitted entirely,
138
+ * so the model is never told a knob exists that the runtime would ignore. The
139
+ * resolver gate and the RPC filter still cover calls that bypass schema
140
+ * validation.
141
+ */
142
+ const maxTurnsParamShape = {
143
+ max_turns: Type.Optional(
144
+ Type.Number({
145
+ description: "Maximum number of agentic turns before stopping. Omit for unlimited (default).",
146
+ minimum: 1,
147
+ }),
148
+ ),
149
+ };
150
+
151
+ /** Build the `max_turns` parameter for a tool schema, or nothing when caller caps are disabled. */
152
+ export function maxTurnsParam(enabled: boolean): Partial<typeof maxTurnsParamShape> {
153
+ return enabled ? maxTurnsParamShape : {};
154
+ }
155
+
132
156
  interface AgentInvocationParams {
133
157
  model?: string;
134
158
  thinking?: string;
135
- max_turns?: number;
159
+ /**
160
+ * Untyped for the same reason as `isolation` below: the conditional schema
161
+ * spread erases TypeBox's numeric inference. The resolver narrows by runtime
162
+ * type rather than trusting the declaration, which also keeps the
163
+ * unvalidated RPC path safe.
164
+ */
165
+ max_turns?: unknown;
136
166
  run_in_background?: boolean;
137
167
  inherit_context?: boolean;
138
168
  isolated?: boolean;
@@ -166,6 +196,12 @@ interface ResolveOptions {
166
196
  * a caller that supplies no options at all, which in-tree means tests.
167
197
  */
168
198
  defaultRunInBackground?: boolean;
199
+ /**
200
+ * Whether the caller's `max_turns` parameter may set the budget. False by
201
+ * default: agent-file and project caps remain authoritative, and a caller
202
+ * limit is dropped. The agent file's own `maxTurns` always wins when set.
203
+ */
204
+ allowPerCallTurnLimits?: boolean;
169
205
  }
170
206
 
171
207
  export function resolveAgentInvocationConfig(
@@ -207,11 +243,21 @@ export function resolveAgentInvocationConfig(
207
243
  ? params.model
208
244
  : undefined;
209
245
 
246
+ // A conditional schema spread leaves `max_turns` statically unknown, and the
247
+ // RPC path can carry anything. Narrow to a finite number (`0` stays intact —
248
+ // it is the explicit "unlimited" marker) before the policy gate, so a caller
249
+ // value that is not a number is treated as no opinion rather than reaching
250
+ // normalizeMaxTurns.
251
+ const callerMaxTurns = typeof params.max_turns === "number" && Number.isFinite(params.max_turns)
252
+ ? params.max_turns
253
+ : undefined;
254
+
210
255
  return {
211
256
  modelInput: agentConfig?.model ?? params.model,
212
257
  modelFromParams: agentConfig?.model == null && params.model != null,
213
258
  thinking: (agentConfig?.thinking ?? params.thinking) as ThinkingLevel | undefined,
214
- maxTurns: agentConfig?.maxTurns ?? params.max_turns,
259
+ maxTurns: agentConfig?.maxTurns
260
+ ?? (opts?.allowPerCallTurnLimits === true ? callerMaxTurns : undefined),
215
261
  inheritContext: agentConfig?.inheritContext ?? params.inherit_context ?? false,
216
262
  runInBackground: agentConfig?.runInBackground ?? params.run_in_background ?? opts?.defaultRunInBackground ?? false,
217
263
  isolated: agentConfig?.isolated ?? params.isolated ?? false,
package/src/memory.ts CHANGED
@@ -15,7 +15,7 @@ import { existsSync, lstatSync, mkdirSync, readFileSync } from "node:fs";
15
15
  import { homedir } from "node:os";
16
16
  import { join, } from "node:path";
17
17
  import { getAgentDir } from "@earendil-works/pi-coding-agent";
18
- import type { MemoryScope } from "./types.js";
18
+ import type { MemoryScope } from "./types.ts";
19
19
 
20
20
  /** Maximum lines to read from MEMORY.md */
21
21
  const MAX_MEMORY_LINES = 200;
@@ -71,9 +71,9 @@ import {
71
71
  SessionManager,
72
72
  type ToolDefinition,
73
73
  } from "@earendil-works/pi-coding-agent";
74
- import { runAsSubagentProcess, runInChildSessionContext } from "./child-context.js";
75
- import { agentMentionReminder } from "./mention.js";
76
- import type { SubagentType, ThinkingLevel } from "./types.js";
74
+ import { runAsSubagentProcess, runInChildSessionContext } from "./child-context.ts";
75
+ import { agentMentionReminder } from "./mention.ts";
76
+ import type { SubagentType, ThinkingLevel } from "./types.ts";
77
77
 
78
78
  export interface MentionCloneOptions {
79
79
  /** The MAIN session's context — what the spawn is attributed to, and the
@@ -7,7 +7,7 @@
7
7
  * `disableDefaults` lives in agent-types.ts: both entry points need it.
8
8
  */
9
9
 
10
- import { isModelInScope, type ModelRegistryRef, readEnabledModels, resolveEnabledModels } from "./enabled-models.js";
10
+ import { isModelInScope, type ModelRegistryRef, readEnabledModels, resolveEnabledModels } from "./enabled-models.ts";
11
11
 
12
12
  /**
13
13
  * When enabled, subagent model choices are validated against `enabledModels`
@@ -7,34 +7,38 @@ import {
7
7
  type ToolDefinition,
8
8
  } from "@earendil-works/pi-coding-agent";
9
9
  import { Type } from "@sinclair/typebox";
10
- import { abortable } from "./abortable.js";
10
+ import { abortable } from "./abortable.ts";
11
+ import { getAllowPerCallTurnLimits } from "./agent-runner.ts";
11
12
  import {
12
13
  buildAgentRegistry,
14
+ cloneAgentDefinition,
13
15
  getAgentConfigIn,
14
16
  getAvailableTypesIn,
15
17
  resolveEnabledTypeIn,
16
18
  resolveTypeIn,
17
- } from "./agent-types.js";
18
- import { loadCustomAgents } from "./custom-agents.js";
19
- import { isolationParam, resolveAgentInvocationConfig } from "./invocation-config.js";
20
- import { resolveModel } from "./model-resolver.js";
21
- import { checkModelScope } from "./model-scope.js";
19
+ } from "./agent-types.ts";
20
+ import { loadCustomAgents, loadCustomAgentsAsync } from "./custom-agents.ts";
21
+ import { isForceMainModel } from "./force-main-model.ts";
22
+ import { isolationParam, maxTurnsParam, resolveAgentInvocationConfig } from "./invocation-config.ts";
23
+ import { resolveModel } from "./model-resolver.ts";
24
+ import { checkModelScope } from "./model-scope.ts";
22
25
  import {
23
26
  createOutputFilePath,
24
27
  getOutputTranscriptDefault,
25
28
  streamToOutputFile,
26
29
  writeInitialEntry,
27
- } from "./output-file.js";
28
- import { getForegroundOutcomeNote, getStatusNote, partialOutputSuffix } from "./status-note.js";
30
+ } from "./output-file.ts";
31
+ import type { ReportLookup, ReportOwnerContext, ReportSnapshot } from "./report-store.ts";
32
+ import { getForegroundOutcomeNote, getStatusNote, partialOutputSuffix } from "./status-note.ts";
29
33
  import type {
30
34
  AgentConfig,
31
35
  AgentInvocation,
32
36
  AgentRecord,
33
37
  IsolationMode,
34
38
  ThinkingLevel,
35
- } from "./types.js";
36
- import { addUsage } from "./usage.js";
37
- import { isWorktreeIsolationEnabled } from "./worktree.js";
39
+ } from "./types.ts";
40
+ import { addUsage } from "./usage.ts";
41
+ import { isWorktreeIsolationEnabled } from "./worktree.ts";
38
42
 
39
43
  /**
40
44
  * Hard ceiling on nesting for every branch: main session = 0, its subagents = 1,
@@ -49,6 +53,18 @@ export function setMaxSubagentDepth(n: number): void { maxSubagentDepth = Math.m
49
53
 
50
54
  const NESTED_TOOL_NAMES = ["Agent", "get_subagent_result", "steer_subagent"] as const;
51
55
 
56
+ /**
57
+ * Async, parent-scoped reader for durable completed reports.
58
+ *
59
+ * Injected explicitly from the surviving root manager through the runner into
60
+ * these tools. Only the owner that actually spawned an archived child may read
61
+ * it; the store enforces `parentAgentId === ownerId`, so a workflow row (which
62
+ * has `workflowId`, not a parent) and a sibling's child stay invisible.
63
+ */
64
+ export interface ArchivedReportReader {
65
+ findOwned(ref: string, owner: ReportOwnerContext): Promise<ReportLookup>;
66
+ }
67
+
52
68
  interface NestedSpawnOptions {
53
69
  description: string;
54
70
  model?: Model<any>;
@@ -67,6 +83,13 @@ interface NestedSpawnOptions {
67
83
  maxSubagentDepth: number;
68
84
  configCwd?: string;
69
85
  rootSessionId?: string;
86
+ /**
87
+ * The admitted definition, cloned from the branch's own scoped registry
88
+ * before any admission await. The runner derives prompt, tool policy and
89
+ * model/session/nesting defaults from this snapshot, so another root or
90
+ * process-wide reload cannot change what this queued child is allowed to do.
91
+ */
92
+ agentDefinition?: AgentConfig;
70
93
  }
71
94
 
72
95
  export interface NestedAgentManager {
@@ -102,6 +125,8 @@ export interface NestedToolContext {
102
125
  allowedSubagents: "all" | string[];
103
126
  /** Root used for agent/config discovery; may differ from the agent's working directory. */
104
127
  configCwd: string;
128
+ /** Optional durable-report reader; absent means archive-only reads are unavailable. */
129
+ archive?: ArchivedReportReader;
105
130
  }
106
131
 
107
132
  function textResult(text: string, isError = false) {
@@ -142,12 +167,70 @@ function formatRecord(record: AgentRecord, position: ResultPosition): string {
142
167
  return note ? `Nested agent${note}.\n\n${text}` : text;
143
168
  }
144
169
 
170
+ /**
171
+ * The durable-report shape of {@link formatRecord}. Same honesty rules: a
172
+ * failure keeps its error and the partial output before it, a non-normal
173
+ * status keeps its note, and missing metadata is never invented as zero.
174
+ */
175
+ function formatArchivedReport(report: ReportSnapshot, provenance: string): string {
176
+ const recovered = `\n\n(Recovered from the ${provenance} saved report; no live session remains.)`;
177
+ if (report.status === "error") {
178
+ const partial = report.result?.trim();
179
+ return `Agent failed: ${report.error ?? "unknown error"}${
180
+ partial ? `\n\nPartial output before the failure:\n${partial}` : ""
181
+ }${recovered}`;
182
+ }
183
+ const text = report.result?.trim() || report.error?.trim() || "No output.";
184
+ const note = getStatusNote(report.status);
185
+ return `${note ? `Nested agent${note}.\n\n` : ""}${text}${recovered}`;
186
+ }
187
+
188
+ /**
189
+ * The backend owner's contract is `parentAgentId` EXACT for nested reads;
190
+ * `ownerIds` is cleanup ancestry and must never widen read access. Enforce that
191
+ * here as well, so even a backend release that matched ancestors cannot expose
192
+ * a sibling/descendant row through this bridge.
193
+ */
194
+ function exactParentLookup(lookup: ReportLookup, parentAgentId: string, ref: string): ReportLookup {
195
+ if (lookup.status === "missing") return lookup;
196
+ if (lookup.status === "ambiguous") {
197
+ return { status: "missing", ref, reason: "ambiguous archived owner match" };
198
+ }
199
+ const owned = lookup.status === "found"
200
+ ? lookup.report.parentAgentId === parentAgentId
201
+ : lookup.entry.parentAgentId === parentAgentId;
202
+ return owned ? lookup : { status: "missing", ref, reason: "not owned by this parent" };
203
+ }
204
+
205
+ /** Honest wording for every non-found archived lookup; never a guessed result. */
206
+ function formatArchivedLookup(lookup: ReportLookup, ref: string): string {
207
+ switch (lookup.status) {
208
+ case "found":
209
+ return formatArchivedReport(lookup.report, lookup.provenance);
210
+ case "expired":
211
+ return `Nested agent ${lookup.entry.id} is no longer available: its saved report expired at ${new Date(lookup.expiredAt).toISOString()} (30-day retention).`;
212
+ case "deleted":
213
+ return `Nested agent ${lookup.entry.id}'s saved report was deliberately deleted${
214
+ lookup.reason === undefined ? "" : ` (${lookup.reason})`
215
+ } at ${new Date(lookup.deletedAt).toISOString()}. It will not be resurrected.`;
216
+ case "ambiguous":
217
+ return `Nested agent "${ref}" is ambiguous in the saved archive; no result was chosen.`;
218
+ case "missing":
219
+ return `Nested agent not found or not owned by this parent: "${ref}". ${lookup.reason}.`;
220
+ }
221
+ }
222
+
145
223
  /** Build child-safe orchestration tools scoped to one parent agent instance. */
146
224
  export function createNestedSubagentTools(context: NestedToolContext): ToolDefinition[] {
147
225
  // Agents resolve from a registry built for THIS branch's config root (under
148
226
  // worktree isolation, the copy). Never via registerAgents — that is
149
227
  // process-global state shared with the main session and every other agent.
150
228
  const loadRegistry = () => buildAgentRegistry(loadCustomAgents(context.configCwd));
229
+ // Executes use the async twin so a slow definition directory yields instead
230
+ // of blocking the child's event loop. The synchronous form stays for the
231
+ // parameter schema below, which cannot await; it is read fresh, not cached
232
+ // for admission.
233
+ const loadRegistryAsync = async () => buildAgentRegistry(await loadCustomAgentsAsync(context.configCwd));
151
234
  const allowedTypesIn = (registry: Map<string, AgentConfig>): Set<string> | undefined =>
152
235
  context.allowedSubagents === "all"
153
236
  ? undefined
@@ -169,7 +252,7 @@ export function createNestedSubagentTools(context: NestedToolContext): ToolDefin
169
252
  subagent_type: Type.String({ description: `Allowed nested agent type. Available: ${availableIn(loadRegistry()).join(", ") || "none"}.` }),
170
253
  model: Type.Optional(Type.String({ description: "Optional provider/model override." })),
171
254
  thinking: Type.Optional(Type.String({ description: "Optional thinking level." })),
172
- max_turns: Type.Optional(Type.Number({ minimum: 1 })),
255
+ ...maxTurnsParam(getAllowPerCallTurnLimits()),
173
256
  run_in_background: Type.Optional(
174
257
  Type.Boolean({
175
258
  description: "Defaults to false for nested spawns — the call blocks and returns the child's result inline. Set true only for work you will collect later with get_subagent_result; a detached child is stopped when you finish.",
@@ -200,7 +283,7 @@ export function createNestedSubagentTools(context: NestedToolContext): ToolDefin
200
283
  }
201
284
 
202
285
  // Reloaded per call so new agent files are picked up without a restart.
203
- const registry = loadRegistry();
286
+ const registry = await loadRegistryAsync();
204
287
  const rawType = params.subagent_type;
205
288
  // Strict resolve, never the fallback policy: a project-level
206
289
  // `fallbackSubagent` must not hand a nested caller an agent its allowlist
@@ -222,14 +305,23 @@ export function createNestedSubagentTools(context: NestedToolContext): ToolDefin
222
305
  }
223
306
 
224
307
  const config = getAgentConfigIn(registry, resolvedType);
308
+ // Pin what was admitted, not what the process-wide registry says later.
309
+ // The manager may queue, copy a worktree or otherwise suspend before the
310
+ // runner reads the definition; cloning now keeps prompt, tools/denylists,
311
+ // model and session/nesting policy on the values that passed admission.
312
+ const agentDefinition = config === undefined ? undefined : cloneAgentDefinition(config);
225
313
  // Foreground regardless of `backgroundByDefault` — see the reasoning on
226
314
  // ResolveOptions. An explicit `true` here still opts in.
227
315
  const invocation = resolveAgentInvocationConfig(config, params, {
228
316
  worktreeAllowed: isWorktreeIsolationEnabled(),
229
317
  defaultRunInBackground: false,
318
+ allowPerCallTurnLimits: getAllowPerCallTurnLimits(),
230
319
  });
320
+ // /subagents off: the nested spawn twins its parent's model (itself
321
+ // twinned), so caller/config model inputs and the scope check give way.
322
+ const twinForced = isForceMainModel();
231
323
  let model = ctx.model;
232
- if (invocation.modelInput) {
324
+ if (!twinForced && invocation.modelInput) {
233
325
  const resolvedModel = resolveModel(invocation.modelInput, ctx.modelRegistry);
234
326
  if (typeof resolvedModel === "string") {
235
327
  if (invocation.modelFromParams) return textResult(resolvedModel, true);
@@ -241,15 +333,17 @@ export function createNestedSubagentTools(context: NestedToolContext): ToolDefin
241
333
  // Same scopeModels policy as the top-level Agent tool — a nested spawn
242
334
  // must not escape the allowlist. A "warn" verdict proceeds silently:
243
335
  // child sessions have no UI surface to toast to.
244
- const scopeVerdict = checkModelScope({
245
- model,
246
- cwd: context.configCwd,
247
- modelRegistry: ctx.modelRegistry,
248
- callerSupplied: invocation.modelFromParams,
249
- agentLabel: config?.displayName ?? resolvedType,
250
- modelInput: invocation.modelInput,
251
- });
252
- if (scopeVerdict.kind === "error") return textResult(scopeVerdict.message, true);
336
+ if (!twinForced) {
337
+ const scopeVerdict = checkModelScope({
338
+ model,
339
+ cwd: context.configCwd,
340
+ modelRegistry: ctx.modelRegistry,
341
+ callerSupplied: invocation.modelFromParams,
342
+ agentLabel: config?.displayName ?? resolvedType,
343
+ modelInput: invocation.modelInput,
344
+ });
345
+ if (scopeVerdict.kind === "error") return textResult(scopeVerdict.message, true);
346
+ }
253
347
 
254
348
  // The whole branch shares the root session's transcript directory; read it
255
349
  // off the owning parent rather than this child session's own id.
@@ -293,6 +387,7 @@ export function createNestedSubagentTools(context: NestedToolContext): ToolDefin
293
387
  maxSubagentDepth: context.maxSubagentDepth,
294
388
  configCwd: context.configCwd,
295
389
  rootSessionId,
390
+ agentDefinition,
296
391
  };
297
392
 
298
393
  // Transcript wiring, same gate as the top-level path: the child's
@@ -371,21 +466,57 @@ export function createNestedSubagentTools(context: NestedToolContext): ToolDefin
371
466
  wait: Type.Optional(Type.Boolean()),
372
467
  }),
373
468
  execute: async (_toolCallId, params, signal) => {
374
- const record = context.manager.getRecord(params.agent_id);
375
- if (!ownsRecord(record, context.parentAgentId)) {
376
- return textResult(`Nested agent not found or not owned by this parent: "${params.agent_id}".`, true);
377
- }
378
- // Wait for completion if requested. Cancellation (e.g. the parent's tool
379
- // call is aborted) stops only this wait; the nested child keeps running and
380
- // stays unconsumed. Queued records have no promise until the manager starts
381
- // them, so poll — abortably — until they leave the queue, then await.
382
- if (params.wait && (record.status === "queued" || record.status === "running")) {
469
+ /** Wait abortably for a LIVE record; archived rows never wait. */
470
+ const waitForLive = async (record: AgentRecord): Promise<void> => {
471
+ if (!params.wait || (record.status !== "queued" && record.status !== "running")) return;
472
+ // Queued records have no promise until the manager starts them, so poll
473
+ // — abortably — until they leave the queue, then await. Cancellation
474
+ // stops only this wait; the nested child keeps running and unconsumed.
383
475
  while (record.status === "queued") {
384
476
  await abortable(new Promise<void>(resolve => setTimeout(resolve, 250)), signal);
385
477
  }
386
478
  if (record.promise) await abortable(record.promise, signal);
479
+ };
480
+
481
+ const record = context.manager.getRecord(params.agent_id);
482
+ if (record !== undefined) {
483
+ // A KNOWN but unowned live record is refused outright. Falling through
484
+ // to the archive here could surface a same-id archived row (after a
485
+ // resume) that this parent never owned.
486
+ if (!ownsRecord(record, context.parentAgentId)) {
487
+ return textResult(`Nested agent not found or not owned by this parent: "${params.agent_id}".`, true);
488
+ }
489
+ await waitForLive(record);
490
+ return textResult(formatRecord(record, "fetched"), record.status === "error");
491
+ }
492
+
493
+ // The runtime record is gone (evicted/reloaded). The root manager's
494
+ // durable store can still answer, but only for this exact parent.
495
+ if (context.archive === undefined) {
496
+ return textResult(`Nested agent not found or not owned by this parent: "${params.agent_id}".`, true);
497
+ }
498
+ const lookup = exactParentLookup(
499
+ await context.archive.findOwned(params.agent_id, {
500
+ kind: "parent",
501
+ id: context.parentAgentId,
502
+ }),
503
+ context.parentAgentId,
504
+ params.agent_id,
505
+ );
506
+ // Recheck live after the async read: a resume that started meanwhile is
507
+ // the current truth, and an older saved answer must not shadow it.
508
+ const relive = context.manager.getRecord(params.agent_id);
509
+ if (relive !== undefined) {
510
+ if (!ownsRecord(relive, context.parentAgentId)) {
511
+ return textResult(`Nested agent not found or not owned by this parent: "${params.agent_id}".`, true);
512
+ }
513
+ await waitForLive(relive);
514
+ return textResult(formatRecord(relive, "fetched"), relive.status === "error");
387
515
  }
388
- return textResult(formatRecord(record, "fetched"), record.status === "error");
516
+ return textResult(
517
+ formatArchivedLookup(lookup, params.agent_id),
518
+ lookup.status === "found" ? lookup.report.status === "error" : true,
519
+ );
389
520
  },
390
521
  });
391
522