@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,5 +1,5 @@
1
- import { type ModelRegistry, resolveModel } from "./model-resolver.js";
2
- import type { AgentConfig, IsolationMode, JoinMode, ThinkingLevel } from "./types.js";
1
+ import { type ModelRegistry, resolveModel } from "./model-resolver.ts";
2
+ import type { AgentConfig, IsolationMode, JoinMode, ThinkingLevel } from "./types.ts";
3
3
  /**
4
4
  * Agent pins are authoritative: a qualified `provider/id` pin resolves exactly
5
5
  * first, then — via model-resolver's normalization — to the same model id on
@@ -73,10 +73,31 @@ declare const isolationParamShape: {
73
73
  * setting needs a new pi session for the schema to change.
74
74
  */
75
75
  export declare function isolationParam(enabled: boolean): Partial<typeof isolationParamShape>;
76
+ /**
77
+ * The model-facing `max_turns` parameter, shared by the top-level `Agent` tool
78
+ * and the nested delegation tool.
79
+ *
80
+ * Like `isolationParam`, this is a `Partial` shape meant to be spread into a
81
+ * `Type.Object`: when caller caps are disabled the field is omitted entirely,
82
+ * so the model is never told a knob exists that the runtime would ignore. The
83
+ * resolver gate and the RPC filter still cover calls that bypass schema
84
+ * validation.
85
+ */
86
+ declare const maxTurnsParamShape: {
87
+ max_turns: import("@sinclair/typebox").TOptional<import("@sinclair/typebox").TNumber>;
88
+ };
89
+ /** Build the `max_turns` parameter for a tool schema, or nothing when caller caps are disabled. */
90
+ export declare function maxTurnsParam(enabled: boolean): Partial<typeof maxTurnsParamShape>;
76
91
  interface AgentInvocationParams {
77
92
  model?: string;
78
93
  thinking?: string;
79
- max_turns?: number;
94
+ /**
95
+ * Untyped for the same reason as `isolation` below: the conditional schema
96
+ * spread erases TypeBox's numeric inference. The resolver narrows by runtime
97
+ * type rather than trusting the declaration, which also keeps the
98
+ * unvalidated RPC path safe.
99
+ */
100
+ max_turns?: unknown;
80
101
  run_in_background?: boolean;
81
102
  inherit_context?: boolean;
82
103
  isolated?: boolean;
@@ -109,6 +130,12 @@ interface ResolveOptions {
109
130
  * a caller that supplies no options at all, which in-tree means tests.
110
131
  */
111
132
  defaultRunInBackground?: boolean;
133
+ /**
134
+ * Whether the caller's `max_turns` parameter may set the budget. False by
135
+ * default: agent-file and project caps remain authoritative, and a caller
136
+ * limit is dropped. The agent file's own `maxTurns` always wins when set.
137
+ */
138
+ allowPerCallTurnLimits?: boolean;
112
139
  }
113
140
  export declare function resolveAgentInvocationConfig(agentConfig: AgentConfig | undefined, params: AgentInvocationParams, opts?: ResolveOptions): {
114
141
  modelInput?: string;
@@ -93,6 +93,26 @@ const isolationParamShape = {
93
93
  export function isolationParam(enabled) {
94
94
  return enabled ? isolationParamShape : {};
95
95
  }
96
+ /**
97
+ * The model-facing `max_turns` parameter, shared by the top-level `Agent` tool
98
+ * and the nested delegation tool.
99
+ *
100
+ * Like `isolationParam`, this is a `Partial` shape meant to be spread into a
101
+ * `Type.Object`: when caller caps are disabled the field is omitted entirely,
102
+ * so the model is never told a knob exists that the runtime would ignore. The
103
+ * resolver gate and the RPC filter still cover calls that bypass schema
104
+ * validation.
105
+ */
106
+ const maxTurnsParamShape = {
107
+ max_turns: Type.Optional(Type.Number({
108
+ description: "Maximum number of agentic turns before stopping. Omit for unlimited (default).",
109
+ minimum: 1,
110
+ })),
111
+ };
112
+ /** Build the `max_turns` parameter for a tool schema, or nothing when caller caps are disabled. */
113
+ export function maxTurnsParam(enabled) {
114
+ return enabled ? maxTurnsParamShape : {};
115
+ }
96
116
  export function resolveAgentInvocationConfig(agentConfig, params, opts) {
97
117
  // Precedence first, collapse second — reversing these loses the veto, since
98
118
  // an agent file's "off" only outranks a caller's "worktree" while it is still
@@ -107,11 +127,20 @@ export function resolveAgentInvocationConfig(agentConfig, params, opts) {
107
127
  && agentConfig.model !== params.model
108
128
  ? params.model
109
129
  : undefined;
130
+ // A conditional schema spread leaves `max_turns` statically unknown, and the
131
+ // RPC path can carry anything. Narrow to a finite number (`0` stays intact —
132
+ // it is the explicit "unlimited" marker) before the policy gate, so a caller
133
+ // value that is not a number is treated as no opinion rather than reaching
134
+ // normalizeMaxTurns.
135
+ const callerMaxTurns = typeof params.max_turns === "number" && Number.isFinite(params.max_turns)
136
+ ? params.max_turns
137
+ : undefined;
110
138
  return {
111
139
  modelInput: agentConfig?.model ?? params.model,
112
140
  modelFromParams: agentConfig?.model == null && params.model != null,
113
141
  thinking: (agentConfig?.thinking ?? params.thinking),
114
- maxTurns: agentConfig?.maxTurns ?? params.max_turns,
142
+ maxTurns: agentConfig?.maxTurns
143
+ ?? (opts?.allowPerCallTurnLimits === true ? callerMaxTurns : undefined),
115
144
  inheritContext: agentConfig?.inheritContext ?? params.inherit_context ?? false,
116
145
  runInBackground: agentConfig?.runInBackground ?? params.run_in_background ?? opts?.defaultRunInBackground ?? false,
117
146
  isolated: agentConfig?.isolated ?? params.isolated ?? false,
package/dist/memory.d.ts CHANGED
@@ -10,7 +10,7 @@
10
10
  * is still honored (read + write) when it exists and the new location doesn't,
11
11
  * so existing memories aren't orphaned.
12
12
  */
13
- import type { MemoryScope } from "./types.js";
13
+ import type { MemoryScope } from "./types.ts";
14
14
  /**
15
15
  * Returns true if a name contains characters not allowed in agent/skill names.
16
16
  * Uses a whitelist: only alphanumeric, hyphens, underscores, and dots (no leading dot).
@@ -61,7 +61,7 @@
61
61
  * an invisible turn with the full toolset could do invisible work.
62
62
  */
63
63
  import { type ExtensionContext, type ToolDefinition } from "@earendil-works/pi-coding-agent";
64
- import type { SubagentType } from "./types.js";
64
+ import type { SubagentType } from "./types.ts";
65
65
  export interface MentionCloneOptions {
66
66
  /** The MAIN session's context — what the spawn is attributed to, and the
67
67
  * source of both the conversation and the live system prompt. */
@@ -6,7 +6,7 @@
6
6
  * State lives here (rather than in an index.ts closure) for the same reason
7
7
  * `disableDefaults` lives in agent-types.ts: both entry points need it.
8
8
  */
9
- import { type ModelRegistryRef } from "./enabled-models.js";
9
+ import { type ModelRegistryRef } from "./enabled-models.ts";
10
10
  export declare function isScopeModelsEnabled(): boolean;
11
11
  export declare function setScopeModelsEnabled(enabled: boolean): void;
12
12
  export type ModelScopeVerdict =
@@ -1,8 +1,20 @@
1
1
  import type { Model } from "@earendil-works/pi-ai";
2
2
  import { type AgentSession, type ExtensionAPI, type ExtensionContext, type ToolDefinition } from "@earendil-works/pi-coding-agent";
3
- import type { AgentInvocation, AgentRecord, IsolationMode, ThinkingLevel } from "./types.js";
3
+ import type { ReportLookup, ReportOwnerContext } from "./report-store.ts";
4
+ import type { AgentConfig, AgentInvocation, AgentRecord, IsolationMode, ThinkingLevel } from "./types.ts";
4
5
  export declare function getMaxSubagentDepth(): number;
5
6
  export declare function setMaxSubagentDepth(n: number): void;
7
+ /**
8
+ * Async, parent-scoped reader for durable completed reports.
9
+ *
10
+ * Injected explicitly from the surviving root manager through the runner into
11
+ * these tools. Only the owner that actually spawned an archived child may read
12
+ * it; the store enforces `parentAgentId === ownerId`, so a workflow row (which
13
+ * has `workflowId`, not a parent) and a sibling's child stay invisible.
14
+ */
15
+ export interface ArchivedReportReader {
16
+ findOwned(ref: string, owner: ReportOwnerContext): Promise<ReportLookup>;
17
+ }
6
18
  interface NestedSpawnOptions {
7
19
  description: string;
8
20
  model?: Model<any>;
@@ -25,6 +37,13 @@ interface NestedSpawnOptions {
25
37
  maxSubagentDepth: number;
26
38
  configCwd?: string;
27
39
  rootSessionId?: string;
40
+ /**
41
+ * The admitted definition, cloned from the branch's own scoped registry
42
+ * before any admission await. The runner derives prompt, tool policy and
43
+ * model/session/nesting defaults from this snapshot, so another root or
44
+ * process-wide reload cannot change what this queued child is allowed to do.
45
+ */
46
+ agentDefinition?: AgentConfig;
28
47
  }
29
48
  export interface NestedAgentManager {
30
49
  spawn(pi: ExtensionAPI, ctx: ExtensionContext, type: string, prompt: string, options: NestedSpawnOptions): string;
@@ -49,6 +68,8 @@ export interface NestedToolContext {
49
68
  allowedSubagents: "all" | string[];
50
69
  /** Root used for agent/config discovery; may differ from the agent's working directory. */
51
70
  configCwd: string;
71
+ /** Optional durable-report reader; absent means archive-only reads are unavailable. */
72
+ archive?: ArchivedReportReader;
52
73
  }
53
74
  /** Build child-safe orchestration tools scoped to one parent agent instance. */
54
75
  export declare function createNestedSubagentTools(context: NestedToolContext): ToolDefinition[];
@@ -1,9 +1,11 @@
1
1
  import { defineTool, } from "@earendil-works/pi-coding-agent";
2
2
  import { Type } from "@sinclair/typebox";
3
3
  import { abortable } from "./abortable.js";
4
- import { buildAgentRegistry, getAgentConfigIn, getAvailableTypesIn, resolveEnabledTypeIn, resolveTypeIn, } from "./agent-types.js";
5
- import { loadCustomAgents } from "./custom-agents.js";
6
- import { isolationParam, resolveAgentInvocationConfig } from "./invocation-config.js";
4
+ import { getAllowPerCallTurnLimits } from "./agent-runner.js";
5
+ import { buildAgentRegistry, cloneAgentDefinition, getAgentConfigIn, getAvailableTypesIn, resolveEnabledTypeIn, resolveTypeIn, } from "./agent-types.js";
6
+ import { loadCustomAgents, loadCustomAgentsAsync } from "./custom-agents.js";
7
+ import { isForceMainModel } from "./force-main-model.js";
8
+ import { isolationParam, maxTurnsParam, resolveAgentInvocationConfig } from "./invocation-config.js";
7
9
  import { resolveModel } from "./model-resolver.js";
8
10
  import { checkModelScope } from "./model-scope.js";
9
11
  import { createOutputFilePath, getOutputTranscriptDefault, streamToOutputFile, writeInitialEntry, } from "./output-file.js";
@@ -42,12 +44,64 @@ function formatRecord(record, position) {
42
44
  : getStatusNote(record.status);
43
45
  return note ? `Nested agent${note}.\n\n${text}` : text;
44
46
  }
47
+ /**
48
+ * The durable-report shape of {@link formatRecord}. Same honesty rules: a
49
+ * failure keeps its error and the partial output before it, a non-normal
50
+ * status keeps its note, and missing metadata is never invented as zero.
51
+ */
52
+ function formatArchivedReport(report, provenance) {
53
+ const recovered = `\n\n(Recovered from the ${provenance} saved report; no live session remains.)`;
54
+ if (report.status === "error") {
55
+ const partial = report.result?.trim();
56
+ return `Agent failed: ${report.error ?? "unknown error"}${partial ? `\n\nPartial output before the failure:\n${partial}` : ""}${recovered}`;
57
+ }
58
+ const text = report.result?.trim() || report.error?.trim() || "No output.";
59
+ const note = getStatusNote(report.status);
60
+ return `${note ? `Nested agent${note}.\n\n` : ""}${text}${recovered}`;
61
+ }
62
+ /**
63
+ * The backend owner's contract is `parentAgentId` EXACT for nested reads;
64
+ * `ownerIds` is cleanup ancestry and must never widen read access. Enforce that
65
+ * here as well, so even a backend release that matched ancestors cannot expose
66
+ * a sibling/descendant row through this bridge.
67
+ */
68
+ function exactParentLookup(lookup, parentAgentId, ref) {
69
+ if (lookup.status === "missing")
70
+ return lookup;
71
+ if (lookup.status === "ambiguous") {
72
+ return { status: "missing", ref, reason: "ambiguous archived owner match" };
73
+ }
74
+ const owned = lookup.status === "found"
75
+ ? lookup.report.parentAgentId === parentAgentId
76
+ : lookup.entry.parentAgentId === parentAgentId;
77
+ return owned ? lookup : { status: "missing", ref, reason: "not owned by this parent" };
78
+ }
79
+ /** Honest wording for every non-found archived lookup; never a guessed result. */
80
+ function formatArchivedLookup(lookup, ref) {
81
+ switch (lookup.status) {
82
+ case "found":
83
+ return formatArchivedReport(lookup.report, lookup.provenance);
84
+ case "expired":
85
+ return `Nested agent ${lookup.entry.id} is no longer available: its saved report expired at ${new Date(lookup.expiredAt).toISOString()} (30-day retention).`;
86
+ case "deleted":
87
+ return `Nested agent ${lookup.entry.id}'s saved report was deliberately deleted${lookup.reason === undefined ? "" : ` (${lookup.reason})`} at ${new Date(lookup.deletedAt).toISOString()}. It will not be resurrected.`;
88
+ case "ambiguous":
89
+ return `Nested agent "${ref}" is ambiguous in the saved archive; no result was chosen.`;
90
+ case "missing":
91
+ return `Nested agent not found or not owned by this parent: "${ref}". ${lookup.reason}.`;
92
+ }
93
+ }
45
94
  /** Build child-safe orchestration tools scoped to one parent agent instance. */
46
95
  export function createNestedSubagentTools(context) {
47
96
  // Agents resolve from a registry built for THIS branch's config root (under
48
97
  // worktree isolation, the copy). Never via registerAgents — that is
49
98
  // process-global state shared with the main session and every other agent.
50
99
  const loadRegistry = () => buildAgentRegistry(loadCustomAgents(context.configCwd));
100
+ // Executes use the async twin so a slow definition directory yields instead
101
+ // of blocking the child's event loop. The synchronous form stays for the
102
+ // parameter schema below, which cannot await; it is read fresh, not cached
103
+ // for admission.
104
+ const loadRegistryAsync = async () => buildAgentRegistry(await loadCustomAgentsAsync(context.configCwd));
51
105
  const allowedTypesIn = (registry) => context.allowedSubagents === "all"
52
106
  ? undefined
53
107
  : new Set(context.allowedSubagents.map(name => resolveTypeIn(registry, name) ?? name));
@@ -66,7 +120,7 @@ export function createNestedSubagentTools(context) {
66
120
  subagent_type: Type.String({ description: `Allowed nested agent type. Available: ${availableIn(loadRegistry()).join(", ") || "none"}.` }),
67
121
  model: Type.Optional(Type.String({ description: "Optional provider/model override." })),
68
122
  thinking: Type.Optional(Type.String({ description: "Optional thinking level." })),
69
- max_turns: Type.Optional(Type.Number({ minimum: 1 })),
123
+ ...maxTurnsParam(getAllowPerCallTurnLimits()),
70
124
  run_in_background: Type.Optional(Type.Boolean({
71
125
  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.",
72
126
  })),
@@ -90,7 +144,7 @@ export function createNestedSubagentTools(context) {
90
144
  return textResult(`Nested subagent call blocked (depth=${context.depth}, max=${context.maxSubagentDepth}). Complete the task directly.`, true);
91
145
  }
92
146
  // Reloaded per call so new agent files are picked up without a restart.
93
- const registry = loadRegistry();
147
+ const registry = await loadRegistryAsync();
94
148
  const rawType = params.subagent_type;
95
149
  // Strict resolve, never the fallback policy: a project-level
96
150
  // `fallbackSubagent` must not hand a nested caller an agent its allowlist
@@ -105,14 +159,23 @@ export function createNestedSubagentTools(context) {
105
159
  return textResult(`Nested agent type "${resolvedType}" is not allowed for this parent. Allowed: ${[...allowed].join(", ")}.`, true);
106
160
  }
107
161
  const config = getAgentConfigIn(registry, resolvedType);
162
+ // Pin what was admitted, not what the process-wide registry says later.
163
+ // The manager may queue, copy a worktree or otherwise suspend before the
164
+ // runner reads the definition; cloning now keeps prompt, tools/denylists,
165
+ // model and session/nesting policy on the values that passed admission.
166
+ const agentDefinition = config === undefined ? undefined : cloneAgentDefinition(config);
108
167
  // Foreground regardless of `backgroundByDefault` — see the reasoning on
109
168
  // ResolveOptions. An explicit `true` here still opts in.
110
169
  const invocation = resolveAgentInvocationConfig(config, params, {
111
170
  worktreeAllowed: isWorktreeIsolationEnabled(),
112
171
  defaultRunInBackground: false,
172
+ allowPerCallTurnLimits: getAllowPerCallTurnLimits(),
113
173
  });
174
+ // /subagents off: the nested spawn twins its parent's model (itself
175
+ // twinned), so caller/config model inputs and the scope check give way.
176
+ const twinForced = isForceMainModel();
114
177
  let model = ctx.model;
115
- if (invocation.modelInput) {
178
+ if (!twinForced && invocation.modelInput) {
116
179
  const resolvedModel = resolveModel(invocation.modelInput, ctx.modelRegistry);
117
180
  if (typeof resolvedModel === "string") {
118
181
  if (invocation.modelFromParams)
@@ -125,16 +188,18 @@ export function createNestedSubagentTools(context) {
125
188
  // Same scopeModels policy as the top-level Agent tool — a nested spawn
126
189
  // must not escape the allowlist. A "warn" verdict proceeds silently:
127
190
  // child sessions have no UI surface to toast to.
128
- const scopeVerdict = checkModelScope({
129
- model,
130
- cwd: context.configCwd,
131
- modelRegistry: ctx.modelRegistry,
132
- callerSupplied: invocation.modelFromParams,
133
- agentLabel: config?.displayName ?? resolvedType,
134
- modelInput: invocation.modelInput,
135
- });
136
- if (scopeVerdict.kind === "error")
137
- return textResult(scopeVerdict.message, true);
191
+ if (!twinForced) {
192
+ const scopeVerdict = checkModelScope({
193
+ model,
194
+ cwd: context.configCwd,
195
+ modelRegistry: ctx.modelRegistry,
196
+ callerSupplied: invocation.modelFromParams,
197
+ agentLabel: config?.displayName ?? resolvedType,
198
+ modelInput: invocation.modelInput,
199
+ });
200
+ if (scopeVerdict.kind === "error")
201
+ return textResult(scopeVerdict.message, true);
202
+ }
138
203
  // The whole branch shares the root session's transcript directory; read it
139
204
  // off the owning parent rather than this child session's own id.
140
205
  const rootSessionId = context.manager.getRecord(context.parentAgentId)?.rootSessionId;
@@ -178,6 +243,7 @@ export function createNestedSubagentTools(context) {
178
243
  maxSubagentDepth: context.maxSubagentDepth,
179
244
  configCwd: context.configCwd,
180
245
  rootSessionId,
246
+ agentDefinition,
181
247
  };
182
248
  // Transcript wiring, same gate as the top-level path: the child's
183
249
  // `output_transcript` frontmatter wins, else the project default. Without
@@ -247,22 +313,50 @@ export function createNestedSubagentTools(context) {
247
313
  wait: Type.Optional(Type.Boolean()),
248
314
  }),
249
315
  execute: async (_toolCallId, params, signal) => {
250
- const record = context.manager.getRecord(params.agent_id);
251
- if (!ownsRecord(record, context.parentAgentId)) {
252
- return textResult(`Nested agent not found or not owned by this parent: "${params.agent_id}".`, true);
253
- }
254
- // Wait for completion if requested. Cancellation (e.g. the parent's tool
255
- // call is aborted) stops only this wait; the nested child keeps running and
256
- // stays unconsumed. Queued records have no promise until the manager starts
257
- // them, so poll — abortably — until they leave the queue, then await.
258
- if (params.wait && (record.status === "queued" || record.status === "running")) {
316
+ /** Wait abortably for a LIVE record; archived rows never wait. */
317
+ const waitForLive = async (record) => {
318
+ if (!params.wait || (record.status !== "queued" && record.status !== "running"))
319
+ return;
320
+ // Queued records have no promise until the manager starts them, so poll
321
+ // — abortably — until they leave the queue, then await. Cancellation
322
+ // stops only this wait; the nested child keeps running and unconsumed.
259
323
  while (record.status === "queued") {
260
324
  await abortable(new Promise(resolve => setTimeout(resolve, 250)), signal);
261
325
  }
262
326
  if (record.promise)
263
327
  await abortable(record.promise, signal);
328
+ };
329
+ const record = context.manager.getRecord(params.agent_id);
330
+ if (record !== undefined) {
331
+ // A KNOWN but unowned live record is refused outright. Falling through
332
+ // to the archive here could surface a same-id archived row (after a
333
+ // resume) that this parent never owned.
334
+ if (!ownsRecord(record, context.parentAgentId)) {
335
+ return textResult(`Nested agent not found or not owned by this parent: "${params.agent_id}".`, true);
336
+ }
337
+ await waitForLive(record);
338
+ return textResult(formatRecord(record, "fetched"), record.status === "error");
339
+ }
340
+ // The runtime record is gone (evicted/reloaded). The root manager's
341
+ // durable store can still answer, but only for this exact parent.
342
+ if (context.archive === undefined) {
343
+ return textResult(`Nested agent not found or not owned by this parent: "${params.agent_id}".`, true);
344
+ }
345
+ const lookup = exactParentLookup(await context.archive.findOwned(params.agent_id, {
346
+ kind: "parent",
347
+ id: context.parentAgentId,
348
+ }), context.parentAgentId, params.agent_id);
349
+ // Recheck live after the async read: a resume that started meanwhile is
350
+ // the current truth, and an older saved answer must not shadow it.
351
+ const relive = context.manager.getRecord(params.agent_id);
352
+ if (relive !== undefined) {
353
+ if (!ownsRecord(relive, context.parentAgentId)) {
354
+ return textResult(`Nested agent not found or not owned by this parent: "${params.agent_id}".`, true);
355
+ }
356
+ await waitForLive(relive);
357
+ return textResult(formatRecord(relive, "fetched"), relive.status === "error");
264
358
  }
265
- return textResult(formatRecord(record, "fetched"), record.status === "error");
359
+ return textResult(formatArchivedLookup(lookup, params.agent_id), lookup.status === "found" ? lookup.report.status === "error" : true);
266
360
  },
267
361
  });
268
362
  const steerTool = defineTool({
@@ -42,12 +42,23 @@ export declare function writeInitialEntry(path: string, agentId: string, prompt:
42
42
  * so a caller can await the final flush.
43
43
  */
44
44
  export declare function drainOutputFile(path: string): Promise<void>;
45
+ /** Diagnostic only: serialized bytes accepted for a path but not yet written. */
46
+ export declare function pendingOutputBytes(path: string): number;
47
+ type OutputSession = Pick<AgentSession, "messages" | "retryAttempt" | "subscribe"> & {
48
+ agent?: Pick<AgentSession["agent"], "subscribe">;
49
+ };
45
50
  /**
46
51
  * Persist finalized events before retries can remove them from session.messages.
47
52
  * Snapshot flushes also preserve eventless SDK additions (e.g. bashExecution).
48
53
  * Lines are stringified at event time but written through an async per-file
49
- * queue (see chainWrite), so message-sized JSON work never blocks the loop.
50
- * Returns an idempotent final flush/unsubscribe that resolves once the flushed
51
- * writes are on disk; never changes retry policy.
54
+ * queue (see drainQueue). JSON serialization remains synchronous; disk waits
55
+ * and bounded producer checkpoints are asynchronous.
56
+ * A real Agent session also gets a producer listener registered after the
57
+ * session observer: it waits below the high-water mark at message_end and
58
+ * forces a drain at turn/run settlement, so slow disk stops the producer
59
+ * instead of growing an unbounded in-memory queue. Returns an idempotent final
60
+ * flush/unsubscribe that resolves once the flushed writes are on disk; never
61
+ * changes retry policy.
52
62
  */
53
- export declare function streamToOutputFile(session: AgentSession, path: string, agentId: string, cwd: string, startIndex?: number, agentType?: string): () => void;
63
+ export declare function streamToOutputFile(session: OutputSession, path: string, agentId: string, cwd: string, startIndex?: number, agentType?: string): () => Promise<void>;
64
+ export {};