@diousk/pi-subagents-fast 0.20.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 (183) hide show
  1. package/CHANGELOG.md +808 -0
  2. package/CONTRIBUTING.md +72 -0
  3. package/LICENSE +21 -0
  4. package/README.md +1034 -0
  5. package/SECURITY.md +95 -0
  6. package/dist/abortable.d.ts +12 -0
  7. package/dist/abortable.js +42 -0
  8. package/dist/agent-color.d.ts +35 -0
  9. package/dist/agent-color.js +123 -0
  10. package/dist/agent-file-toggle.d.ts +125 -0
  11. package/dist/agent-file-toggle.js +260 -0
  12. package/dist/agent-manager.d.ts +472 -0
  13. package/dist/agent-manager.js +1338 -0
  14. package/dist/agent-runner.d.ts +312 -0
  15. package/dist/agent-runner.js +1034 -0
  16. package/dist/agent-types.d.ts +119 -0
  17. package/dist/agent-types.js +286 -0
  18. package/dist/child-context.d.ts +2 -0
  19. package/dist/child-context.js +12 -0
  20. package/dist/context.d.ts +12 -0
  21. package/dist/context.js +56 -0
  22. package/dist/cross-extension-rpc.d.ts +66 -0
  23. package/dist/cross-extension-rpc.js +138 -0
  24. package/dist/custom-agents.d.ts +54 -0
  25. package/dist/custom-agents.js +316 -0
  26. package/dist/default-agents.d.ts +7 -0
  27. package/dist/default-agents.js +122 -0
  28. package/dist/enabled-models.d.ts +49 -0
  29. package/dist/enabled-models.js +145 -0
  30. package/dist/env.d.ts +6 -0
  31. package/dist/env.js +28 -0
  32. package/dist/group-join.d.ts +32 -0
  33. package/dist/group-join.js +116 -0
  34. package/dist/index.d.ts +50 -0
  35. package/dist/index.js +3682 -0
  36. package/dist/invocation-config.d.ts +107 -0
  37. package/dist/invocation-config.js +83 -0
  38. package/dist/memory.d.ts +53 -0
  39. package/dist/memory.js +165 -0
  40. package/dist/mention-clone.d.ts +87 -0
  41. package/dist/mention-clone.js +153 -0
  42. package/dist/mention.d.ts +81 -0
  43. package/dist/mention.js +131 -0
  44. package/dist/model-resolver.d.ts +36 -0
  45. package/dist/model-resolver.js +95 -0
  46. package/dist/model-scope.d.ts +49 -0
  47. package/dist/model-scope.js +48 -0
  48. package/dist/nested-tools.d.ts +55 -0
  49. package/dist/nested-tools.js +299 -0
  50. package/dist/output-file.d.ts +43 -0
  51. package/dist/output-file.js +142 -0
  52. package/dist/prompts.d.ts +55 -0
  53. package/dist/prompts.js +91 -0
  54. package/dist/schedule-store.d.ts +38 -0
  55. package/dist/schedule-store.js +155 -0
  56. package/dist/schedule.d.ts +109 -0
  57. package/dist/schedule.js +359 -0
  58. package/dist/settings.d.ts +360 -0
  59. package/dist/settings.js +251 -0
  60. package/dist/skill-loader.d.ts +24 -0
  61. package/dist/skill-loader.js +93 -0
  62. package/dist/status-note.d.ts +61 -0
  63. package/dist/status-note.js +85 -0
  64. package/dist/structured-output.d.ts +61 -0
  65. package/dist/structured-output.js +112 -0
  66. package/dist/types.d.ts +371 -0
  67. package/dist/types.js +5 -0
  68. package/dist/ui/agent-mention.d.ts +82 -0
  69. package/dist/ui/agent-mention.js +187 -0
  70. package/dist/ui/agent-widget.d.ts +219 -0
  71. package/dist/ui/agent-widget.js +592 -0
  72. package/dist/ui/conversation-viewer.d.ts +120 -0
  73. package/dist/ui/conversation-viewer.js +578 -0
  74. package/dist/ui/fleet-list.d.ts +195 -0
  75. package/dist/ui/fleet-list.js +471 -0
  76. package/dist/ui/schedule-menu.d.ts +16 -0
  77. package/dist/ui/schedule-menu.js +94 -0
  78. package/dist/ui/select-item.d.ts +27 -0
  79. package/dist/ui/select-item.js +34 -0
  80. package/dist/ui/viewer-keys.d.ts +20 -0
  81. package/dist/ui/viewer-keys.js +17 -0
  82. package/dist/ui/workflow-card.d.ts +175 -0
  83. package/dist/ui/workflow-card.js +332 -0
  84. package/dist/ui/workflow-dialog.d.ts +305 -0
  85. package/dist/ui/workflow-dialog.js +843 -0
  86. package/dist/ui/workflow-menu.d.ts +60 -0
  87. package/dist/ui/workflow-menu.js +147 -0
  88. package/dist/usage.d.ts +135 -0
  89. package/dist/usage.js +120 -0
  90. package/dist/workflow/collisions.d.ts +95 -0
  91. package/dist/workflow/collisions.js +88 -0
  92. package/dist/workflow/entry.d.ts +32 -0
  93. package/dist/workflow/entry.js +29 -0
  94. package/dist/workflow/host.d.ts +62 -0
  95. package/dist/workflow/host.js +362 -0
  96. package/dist/workflow/journal.d.ts +97 -0
  97. package/dist/workflow/journal.js +120 -0
  98. package/dist/workflow/json-schema.d.ts +51 -0
  99. package/dist/workflow/json-schema.js +111 -0
  100. package/dist/workflow/meta.d.ts +67 -0
  101. package/dist/workflow/meta.js +317 -0
  102. package/dist/workflow/progress.d.ts +224 -0
  103. package/dist/workflow/progress.js +361 -0
  104. package/dist/workflow/runtime.d.ts +334 -0
  105. package/dist/workflow/runtime.js +830 -0
  106. package/dist/workflow/saved.d.ts +90 -0
  107. package/dist/workflow/saved.js +203 -0
  108. package/dist/workflow/task.d.ts +136 -0
  109. package/dist/workflow/task.js +207 -0
  110. package/dist/workflow/tool-description.d.ts +38 -0
  111. package/dist/workflow/tool-description.js +199 -0
  112. package/dist/workflow/worker-source.d.ts +47 -0
  113. package/dist/workflow/worker-source.js +778 -0
  114. package/dist/worktree.d.ts +52 -0
  115. package/dist/worktree.js +164 -0
  116. package/dist/xml.d.ts +10 -0
  117. package/dist/xml.js +12 -0
  118. package/docs/rpc.md +183 -0
  119. package/docs/workflows.md +437 -0
  120. package/examples/agent-tool-description.md +42 -0
  121. package/examples/workflows/compose.js +51 -0
  122. package/examples/workflows/fan-out-audit.js +47 -0
  123. package/examples/workflows/gated-fix.js +60 -0
  124. package/examples/workflows/lib/count-child.js +27 -0
  125. package/examples/workflows/review-panel.js +63 -0
  126. package/examples/workflows/structured-findings.js +78 -0
  127. package/package.json +68 -0
  128. package/src/abortable.ts +43 -0
  129. package/src/agent-color.ts +161 -0
  130. package/src/agent-file-toggle.ts +270 -0
  131. package/src/agent-manager.ts +1581 -0
  132. package/src/agent-runner.ts +1286 -0
  133. package/src/agent-types.ts +346 -0
  134. package/src/child-context.ts +15 -0
  135. package/src/context.ts +58 -0
  136. package/src/cross-extension-rpc.ts +198 -0
  137. package/src/custom-agents.ts +333 -0
  138. package/src/default-agents.ts +126 -0
  139. package/src/enabled-models.ts +180 -0
  140. package/src/env.ts +33 -0
  141. package/src/group-join.ts +141 -0
  142. package/src/index.ts +3991 -0
  143. package/src/invocation-config.ts +155 -0
  144. package/src/memory.ts +179 -0
  145. package/src/mention-clone.ts +196 -0
  146. package/src/mention.ts +141 -0
  147. package/src/model-resolver.ts +118 -0
  148. package/src/model-scope.ts +70 -0
  149. package/src/nested-tools.ts +422 -0
  150. package/src/output-file.ts +155 -0
  151. package/src/prompts.ts +142 -0
  152. package/src/schedule-store.ts +153 -0
  153. package/src/schedule.ts +386 -0
  154. package/src/settings.ts +587 -0
  155. package/src/skill-loader.ts +102 -0
  156. package/src/status-note.ts +90 -0
  157. package/src/structured-output.ts +130 -0
  158. package/src/types.ts +384 -0
  159. package/src/ui/agent-mention.ts +216 -0
  160. package/src/ui/agent-widget.ts +664 -0
  161. package/src/ui/conversation-viewer.ts +589 -0
  162. package/src/ui/fleet-list.ts +543 -0
  163. package/src/ui/schedule-menu.ts +105 -0
  164. package/src/ui/select-item.ts +45 -0
  165. package/src/ui/viewer-keys.ts +39 -0
  166. package/src/ui/workflow-card.ts +470 -0
  167. package/src/ui/workflow-dialog.ts +1115 -0
  168. package/src/ui/workflow-menu.ts +193 -0
  169. package/src/usage.ts +167 -0
  170. package/src/workflow/collisions.ts +123 -0
  171. package/src/workflow/entry.ts +47 -0
  172. package/src/workflow/host.ts +403 -0
  173. package/src/workflow/journal.ts +164 -0
  174. package/src/workflow/json-schema.ts +128 -0
  175. package/src/workflow/meta.ts +325 -0
  176. package/src/workflow/progress.ts +550 -0
  177. package/src/workflow/runtime.ts +1219 -0
  178. package/src/workflow/saved.ts +217 -0
  179. package/src/workflow/task.ts +302 -0
  180. package/src/workflow/tool-description.ts +200 -0
  181. package/src/workflow/worker-source.ts +781 -0
  182. package/src/worktree.ts +205 -0
  183. package/src/xml.ts +13 -0
@@ -0,0 +1,118 @@
1
+ /**
2
+ * Model resolution: exact match ("provider/modelId") with fuzzy fallback.
3
+ */
4
+
5
+ export interface ModelEntry {
6
+ id: string;
7
+ name: string;
8
+ provider: string;
9
+ }
10
+
11
+ export interface ModelRegistry {
12
+ find(provider: string, modelId: string): any;
13
+ getAll(): any[];
14
+ getAvailable?(): any[];
15
+ }
16
+
17
+ /**
18
+ * Both display forms of a model. The short one goes on tight rows (the widget,
19
+ * the Agent tool result), the canonical one where there is room to disambiguate
20
+ * two providers serving a similarly-named model (the conversation viewer).
21
+ *
22
+ * One function, because `index.ts` labels the model it resolved before the run
23
+ * and `agent-manager.ts` relabels it from the live session afterwards — the two
24
+ * must agree or the label would visibly change the moment the session starts.
25
+ */
26
+ export function describeModel(
27
+ model: { provider: string; id: string; name?: string },
28
+ ): { modelName: string; modelId: string } {
29
+ return {
30
+ modelName: (model.name ?? model.id).replace(/^Claude\s+/i, "").toLowerCase(),
31
+ modelId: `${model.provider}/${model.id}`,
32
+ };
33
+ }
34
+
35
+ /**
36
+ * Resolve a model string to a Model instance.
37
+ * Tries exact match first ("provider/modelId"), then fuzzy match against all available models.
38
+ * Returns the Model on success, or an error message string on failure.
39
+ */
40
+ export function resolveModel(
41
+ input: string,
42
+ registry: ModelRegistry,
43
+ ): any | string {
44
+ // Available models (those with auth configured)
45
+ const all = (registry.getAvailable?.() ?? registry.getAll()) as ModelEntry[];
46
+ const availableSet = new Set(all.map(m => `${m.provider}/${m.id}`.toLowerCase()));
47
+
48
+ // 1. Exact match: "provider/modelId" — only if available (has auth)
49
+ const slashIdx = input.indexOf("/");
50
+ if (slashIdx !== -1) {
51
+ const provider = input.slice(0, slashIdx);
52
+ const modelId = input.slice(slashIdx + 1);
53
+ if (availableSet.has(input.toLowerCase())) {
54
+ const found = registry.find(provider, modelId);
55
+ if (found) return found;
56
+ }
57
+ }
58
+
59
+ // 2. Fuzzy match against available models. Normalize separators so cosmetic
60
+ // punctuation differences still match — e.g. "claude-haiku-4.5" and
61
+ // "claude-haiku-4-5" (dot vs dash in the version) resolve to the same model.
62
+ const normalize = (s: string) => s.toLowerCase().replace(/\./g, "-");
63
+ const query = normalize(input);
64
+
65
+ // Score each model: prefer exact id match > id contains > name contains > provider+id contains
66
+ let bestMatch: ModelEntry | undefined;
67
+ let bestScore = 0;
68
+
69
+ for (const m of all) {
70
+ const id = normalize(m.id);
71
+ const name = normalize(m.name);
72
+ const full = normalize(`${m.provider}/${m.id}`);
73
+
74
+ let score = 0;
75
+ if (id === query || full === query) {
76
+ score = 100; // exact
77
+ } else if (id.includes(query) || full.includes(query)) {
78
+ score = 60 + (query.length / id.length) * 30; // substring, prefer tighter matches
79
+ } else if (name.includes(query)) {
80
+ score = 40 + (query.length / name.length) * 20;
81
+ } else if (
82
+ // A trailing date-stamp token (e.g. "20251001") is optional, so a
83
+ // date-pinned config like "claude-haiku-4-5-20251001" still matches an
84
+ // undated registry id like "claude-haiku-4-5".
85
+ query
86
+ .split(/[\s\-/]+/)
87
+ .every(part => /^\d{8}$/.test(part) || id.includes(part) || name.includes(part) || m.provider.toLowerCase().includes(part))
88
+ ) {
89
+ score = 20; // all parts present somewhere
90
+ }
91
+
92
+ if (score > bestScore) {
93
+ bestScore = score;
94
+ bestMatch = m;
95
+ }
96
+ }
97
+
98
+ if (bestMatch && bestScore >= 20) {
99
+ const found = registry.find(bestMatch.provider, bestMatch.id);
100
+ if (found) return found;
101
+ }
102
+
103
+ // 3. Provider fallback: a "provider/modelId" query that didn't match under the
104
+ // named provider (exact or fuzzy above) retries against all providers. The
105
+ // named provider is preferred when present; this only kicks in when it isn't,
106
+ // so the same model from another provider beats falling back to "inherit".
107
+ if (slashIdx !== -1) {
108
+ const bare = resolveModel(input.slice(slashIdx + 1), registry);
109
+ if (typeof bare !== "string") return bare;
110
+ }
111
+
112
+ // 4. No match — list available models
113
+ const modelList = all
114
+ .map(m => ` ${m.provider}/${m.id}`)
115
+ .sort()
116
+ .join("\n");
117
+ return `Model not found: "${input}".\n\nAvailable models:\n${modelList}`;
118
+ }
@@ -0,0 +1,70 @@
1
+ /**
2
+ * model-scope.ts — `scopeModels` policy, shared by the top-level Agent tool and
3
+ * the nested delegation tools so a nested spawn can't escape the allowlist the
4
+ * top-level path enforces.
5
+ *
6
+ * State lives here (rather than in an index.ts closure) for the same reason
7
+ * `disableDefaults` lives in agent-types.ts: both entry points need it.
8
+ */
9
+
10
+ import { isModelInScope, type ModelRegistryRef, readEnabledModels, resolveEnabledModels } from "./enabled-models.js";
11
+
12
+ /**
13
+ * When enabled, subagent model choices are validated against `enabledModels`
14
+ * from pi's settings — both global `<agentDir>/settings.json` and project-local
15
+ * `<cwd>/.pi/settings.json` (project overrides global). Off by default; opt-in
16
+ * via `/agents → Settings`. See the SubagentsSettings.scopeModels docstring for
17
+ * the hard-error vs warn-and-proceed policy and its rationale.
18
+ */
19
+ let scopeModelsEnabled = false;
20
+
21
+ export function isScopeModelsEnabled(): boolean { return scopeModelsEnabled; }
22
+ export function setScopeModelsEnabled(enabled: boolean): void { scopeModelsEnabled = enabled; }
23
+
24
+ export type ModelScopeVerdict =
25
+ /** In scope, or nothing to validate against (feature off / no allowlist). */
26
+ | { kind: "ok" }
27
+ /** Caller-supplied out-of-scope choice — refuse the spawn with this message. */
28
+ | { kind: "error"; message: string }
29
+ /** Frontmatter-pinned or parent-inherited — proceed, but tell the user. */
30
+ | { kind: "warn"; message: string };
31
+
32
+ /**
33
+ * Check the effective resolved model against the user's enabledModels list.
34
+ *
35
+ * scopeModels guards against *runtime* LLM choices, not user-level config:
36
+ * - Caller-supplied out-of-scope → hard error (the orchestrator made an explicit
37
+ * out-of-scope choice; surface it so it picks differently).
38
+ * - Frontmatter-pinned or parent-inherited out-of-scope → warn but proceed (the
39
+ * user authored/installed this agent or chose the parent's model; trust it).
40
+ */
41
+ export function checkModelScope(args: {
42
+ model: { provider: string; id: string } | undefined;
43
+ cwd: string;
44
+ modelRegistry: ModelRegistryRef;
45
+ /** True when the model came from the tool call rather than frontmatter. */
46
+ callerSupplied: boolean;
47
+ /** Display name used in the warning toast. */
48
+ agentLabel: string;
49
+ /** The raw `model:` input, when there was one. */
50
+ modelInput?: string;
51
+ }): ModelScopeVerdict {
52
+ const { model, cwd, modelRegistry, callerSupplied, agentLabel, modelInput } = args;
53
+ if (!scopeModelsEnabled || !model) return { kind: "ok" };
54
+
55
+ const allowed = resolveEnabledModels(readEnabledModels(cwd), modelRegistry, cwd);
56
+ if (!allowed || isModelInScope(model, allowed)) return { kind: "ok" };
57
+
58
+ if (callerSupplied) {
59
+ const list = [...allowed].sort().map(m => ` ${m}`).join("\n");
60
+ return {
61
+ kind: "error",
62
+ message: `Model not in scope: "${modelInput}".\n\nAllowed models (from enabledModels):\n${list}`,
63
+ };
64
+ }
65
+ const modelLabel = modelInput ?? `${model.provider}/${model.id}`;
66
+ return {
67
+ kind: "warn",
68
+ message: `Agent "${agentLabel}" using out-of-scope model "${modelLabel}"`,
69
+ };
70
+ }
@@ -0,0 +1,422 @@
1
+ import type { Model } from "@earendil-works/pi-ai";
2
+ import {
3
+ type AgentSession,
4
+ defineTool,
5
+ type ExtensionAPI,
6
+ type ExtensionContext,
7
+ type ToolDefinition,
8
+ } from "@earendil-works/pi-coding-agent";
9
+ import { Type } from "@sinclair/typebox";
10
+ import { abortable } from "./abortable.js";
11
+ import {
12
+ buildAgentRegistry,
13
+ getAgentConfigIn,
14
+ getAvailableTypesIn,
15
+ resolveEnabledTypeIn,
16
+ 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";
22
+ import {
23
+ createOutputFilePath,
24
+ getOutputTranscriptDefault,
25
+ streamToOutputFile,
26
+ writeInitialEntry,
27
+ } from "./output-file.js";
28
+ import { getForegroundOutcomeNote, getStatusNote, partialOutputSuffix } from "./status-note.js";
29
+ import type {
30
+ AgentConfig,
31
+ AgentInvocation,
32
+ AgentRecord,
33
+ IsolationMode,
34
+ ThinkingLevel,
35
+ } from "./types.js";
36
+ import { addUsage } from "./usage.js";
37
+ import { isWorktreeIsolationEnabled } from "./worktree.js";
38
+
39
+ /**
40
+ * Hard ceiling on nesting for every branch: main session = 0, its subagents = 1,
41
+ * their children = 2. `0`/`1` disables nesting entirely. Set from
42
+ * `subagents.json` (`maxSubagentDepth`). Read when a subagent session is built,
43
+ * so a change applies to sessions started after it.
44
+ */
45
+ let maxSubagentDepth = 2;
46
+
47
+ export function getMaxSubagentDepth(): number { return maxSubagentDepth; }
48
+ export function setMaxSubagentDepth(n: number): void { maxSubagentDepth = Math.max(0, Math.floor(n)); }
49
+
50
+ const NESTED_TOOL_NAMES = ["Agent", "get_subagent_result", "steer_subagent"] as const;
51
+
52
+ interface NestedSpawnOptions {
53
+ description: string;
54
+ model?: Model<any>;
55
+ maxTurns?: number;
56
+ isolated?: boolean;
57
+ inheritContext?: boolean;
58
+ thinkingLevel?: ThinkingLevel;
59
+ isBackground?: boolean;
60
+ isolation?: IsolationMode;
61
+ invocation?: AgentInvocation;
62
+ signal?: AbortSignal;
63
+ onAssistantUsage?: (usage: { input: number; output: number; cacheWrite: number }) => void;
64
+ onSessionCreated?: (session: AgentSession) => void;
65
+ depth: number;
66
+ parentAgentId: string;
67
+ maxSubagentDepth: number;
68
+ configCwd?: string;
69
+ rootSessionId?: string;
70
+ }
71
+
72
+ export interface NestedAgentManager {
73
+ spawn(
74
+ pi: ExtensionAPI,
75
+ ctx: ExtensionContext,
76
+ type: string,
77
+ prompt: string,
78
+ options: NestedSpawnOptions,
79
+ ): string;
80
+ /** Resolves once the spawned agent is running; rejects on a startup failure. */
81
+ awaitStartup(id: string): Promise<void>;
82
+ spawnAndWait(
83
+ pi: ExtensionAPI,
84
+ ctx: ExtensionContext,
85
+ type: string,
86
+ prompt: string,
87
+ options: Omit<NestedSpawnOptions, "isBackground">,
88
+ /** Fires synchronously after spawn, before the session exists — where the transcript is attached. */
89
+ onSpawned?: (id: string) => void,
90
+ ): Promise<{ id: string; record: AgentRecord }>;
91
+ getRecord(id: string): AgentRecord | undefined;
92
+ resume(id: string, prompt: string, signal?: AbortSignal): Promise<AgentRecord | undefined>;
93
+ }
94
+
95
+ export interface NestedToolContext {
96
+ manager: NestedAgentManager;
97
+ pi: ExtensionAPI;
98
+ parentAgentId: string;
99
+ depth: number;
100
+ maxSubagentDepth: number;
101
+ /** "all" = any enabled agent; string[] = only those types. Never empty. */
102
+ allowedSubagents: "all" | string[];
103
+ /** Root used for agent/config discovery; may differ from the agent's working directory. */
104
+ configCwd: string;
105
+ }
106
+
107
+ function textResult(text: string, isError = false) {
108
+ return { content: [{ type: "text" as const, text }], isError, details: {} };
109
+ }
110
+
111
+ function ownsRecord(record: AgentRecord | undefined, parentAgentId: string): record is AgentRecord {
112
+ return record?.parentAgentId === parentAgentId;
113
+ }
114
+
115
+ /**
116
+ * How the caller received this record, which decides the outcome wording.
117
+ *
118
+ * - "inline": a foreground spawn or a resume. The full output is in this very
119
+ * result and no agent id was handed back, so the note must say there is
120
+ * nothing left to fetch — otherwise the parent invents an id, calls
121
+ * `get_subagent_result`, and hits "not owned by this parent" (#174, the same
122
+ * trap the top-level foreground path fell into).
123
+ * - "fetched": `get_subagent_result` on a background child. The parent holds a
124
+ * valid id and can poll again, so the background wording applies.
125
+ */
126
+ type ResultPosition = "inline" | "fetched";
127
+
128
+ function formatRecord(record: AgentRecord, position: ResultPosition): string {
129
+ if (record.status === "error") {
130
+ return `Agent failed: ${record.error ?? "unknown error"}${partialOutputSuffix(record)}`;
131
+ }
132
+ if (record.status === "queued" || record.status === "running") {
133
+ return `Agent ${record.id} is ${record.status}.`;
134
+ }
135
+ // A truncated run must not read as a finished one. The top-level path carries
136
+ // this in its result headline; a nested result has no headline, so the note
137
+ // leads — appended, it would look like part of the child's own output.
138
+ const text = record.result?.trim() || record.error?.trim() || "No output.";
139
+ const note = position === "inline"
140
+ ? getForegroundOutcomeNote(record.status)
141
+ : getStatusNote(record.status);
142
+ return note ? `Nested agent${note}.\n\n${text}` : text;
143
+ }
144
+
145
+ /** Build child-safe orchestration tools scoped to one parent agent instance. */
146
+ export function createNestedSubagentTools(context: NestedToolContext): ToolDefinition[] {
147
+ // Agents resolve from a registry built for THIS branch's config root (under
148
+ // worktree isolation, the copy). Never via registerAgents — that is
149
+ // process-global state shared with the main session and every other agent.
150
+ const loadRegistry = () => buildAgentRegistry(loadCustomAgents(context.configCwd));
151
+ const allowedTypesIn = (registry: Map<string, AgentConfig>): Set<string> | undefined =>
152
+ context.allowedSubagents === "all"
153
+ ? undefined
154
+ : new Set(context.allowedSubagents.map(name => resolveTypeIn(registry, name) ?? name));
155
+ const availableIn = (registry: Map<string, AgentConfig>): string[] => {
156
+ const allowed = allowedTypesIn(registry);
157
+ return getAvailableTypesIn(registry).filter(name => allowed === undefined || allowed.has(name));
158
+ };
159
+
160
+ const agentTool = defineTool({
161
+ name: NESTED_TOOL_NAMES[0],
162
+ label: "Agent",
163
+ description:
164
+ "Launch a child-safe nested subagent for bounded delegated work. " +
165
+ "Only use agent types allowed by this parent agent; nesting is depth-limited.",
166
+ parameters: Type.Object({
167
+ prompt: Type.String({ description: "Self-contained task for the nested agent." }),
168
+ description: Type.String({ description: "Short 3-5 word task description." }),
169
+ subagent_type: Type.String({ description: `Allowed nested agent type. Available: ${availableIn(loadRegistry()).join(", ") || "none"}.` }),
170
+ model: Type.Optional(Type.String({ description: "Optional provider/model override." })),
171
+ thinking: Type.Optional(Type.String({ description: "Optional thinking level." })),
172
+ max_turns: Type.Optional(Type.Number({ minimum: 1 })),
173
+ run_in_background: Type.Optional(
174
+ Type.Boolean({
175
+ 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.",
176
+ }),
177
+ ),
178
+ resume: Type.Optional(Type.String({ description: "Resume a nested agent owned by this parent." })),
179
+ isolated: Type.Optional(Type.Boolean()),
180
+ inherit_context: Type.Optional(Type.Boolean()),
181
+ ...isolationParam(isWorktreeIsolationEnabled()),
182
+ }),
183
+ execute: async (_toolCallId, params, signal, _onUpdate, ctx) => {
184
+ if (params.resume) {
185
+ const existing = context.manager.getRecord(params.resume);
186
+ if (!ownsRecord(existing, context.parentAgentId)) {
187
+ return textResult(`Nested agent not found or not owned by this parent: "${params.resume}".`, true);
188
+ }
189
+ const resumed = await context.manager.resume(params.resume, params.prompt, signal);
190
+ return resumed
191
+ ? textResult(formatRecord(resumed, "inline"), resumed.status === "error")
192
+ : textResult(`Failed to resume nested agent "${params.resume}".`, true);
193
+ }
194
+
195
+ if (context.depth >= context.maxSubagentDepth) {
196
+ return textResult(
197
+ `Nested subagent call blocked (depth=${context.depth}, max=${context.maxSubagentDepth}). Complete the task directly.`,
198
+ true,
199
+ );
200
+ }
201
+
202
+ // Reloaded per call so new agent files are picked up without a restart.
203
+ const registry = loadRegistry();
204
+ const rawType = params.subagent_type;
205
+ // Strict resolve, never the fallback policy: a project-level
206
+ // `fallbackSubagent` must not hand a nested caller an agent its allowlist
207
+ // never named. The list stays allowlist-filtered so a typo can't enumerate
208
+ // agents this parent may not reach.
209
+ const resolvedType = resolveEnabledTypeIn(registry, rawType);
210
+ if (resolvedType === undefined) {
211
+ return textResult(
212
+ `Unknown or disabled nested agent type: "${rawType}". Allowed: ${availableIn(registry).join(", ") || "none"}.`,
213
+ true,
214
+ );
215
+ }
216
+ const allowed = allowedTypesIn(registry);
217
+ if (allowed !== undefined && !allowed.has(resolvedType)) {
218
+ return textResult(
219
+ `Nested agent type "${resolvedType}" is not allowed for this parent. Allowed: ${[...allowed].join(", ")}.`,
220
+ true,
221
+ );
222
+ }
223
+
224
+ const config = getAgentConfigIn(registry, resolvedType);
225
+ // Foreground regardless of `backgroundByDefault` — see the reasoning on
226
+ // ResolveOptions. An explicit `true` here still opts in.
227
+ const invocation = resolveAgentInvocationConfig(config, params, {
228
+ worktreeAllowed: isWorktreeIsolationEnabled(),
229
+ defaultRunInBackground: false,
230
+ });
231
+ let model = ctx.model;
232
+ if (invocation.modelInput) {
233
+ const resolvedModel = resolveModel(invocation.modelInput, ctx.modelRegistry);
234
+ if (typeof resolvedModel === "string") {
235
+ if (invocation.modelFromParams) return textResult(resolvedModel, true);
236
+ } else {
237
+ model = resolvedModel;
238
+ }
239
+ }
240
+
241
+ // Same scopeModels policy as the top-level Agent tool — a nested spawn
242
+ // must not escape the allowlist. A "warn" verdict proceeds silently:
243
+ // 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);
253
+
254
+ // The whole branch shares the root session's transcript directory; read it
255
+ // off the owning parent rather than this child session's own id.
256
+ const rootSessionId = context.manager.getRecord(context.parentAgentId)?.rootSessionId;
257
+ const childDepth = context.depth + 1;
258
+ const options: NestedSpawnOptions = {
259
+ description: params.description,
260
+ model,
261
+ maxTurns: invocation.maxTurns,
262
+ isolated: invocation.isolated,
263
+ inheritContext: invocation.inheritContext,
264
+ thinkingLevel: invocation.thinking,
265
+ isolation: invocation.isolation,
266
+ invocation: {
267
+ thinking: invocation.thinking,
268
+ maxTurns: invocation.maxTurns,
269
+ isolated: invocation.isolated,
270
+ inheritContext: invocation.inheritContext,
271
+ runInBackground: invocation.runInBackground,
272
+ isolation: invocation.isolation,
273
+ },
274
+ // Nested children are hidden from every reporting surface, so their spend
275
+ // would otherwise be unattributable. Fold it into every ancestor's record:
276
+ // the top-level one appears in lifecycle events, completion notifications,
277
+ // and `/agents`, and those all read `lifetimeUsage`. The whole chain is
278
+ // walked, not just the immediate parent — a spawn callback only fires for
279
+ // that child's OWN turns, so stopping at one level would hide a
280
+ // great-grandchild from the only record anyone can see. (The live
281
+ // widget/fleet counters read their own per-agent activity tracker, which
282
+ // still sees only the top-level agent's own turns.)
283
+ onAssistantUsage: (usage) => {
284
+ for (let id: string | undefined = context.parentAgentId; id !== undefined; ) {
285
+ const ancestor = context.manager.getRecord(id);
286
+ if (!ancestor) break;
287
+ addUsage(ancestor.lifetimeUsage, usage);
288
+ id = ancestor.parentAgentId;
289
+ }
290
+ },
291
+ depth: childDepth,
292
+ parentAgentId: context.parentAgentId,
293
+ maxSubagentDepth: context.maxSubagentDepth,
294
+ configCwd: context.configCwd,
295
+ rootSessionId,
296
+ };
297
+
298
+ // Transcript wiring, same gate as the top-level path: the child's
299
+ // `output_transcript` frontmatter wins, else the project default. Without
300
+ // it a nested run leaves no artifact but the string it returned — the
301
+ // parent's own transcript records the call and the answer, never the tool
302
+ // calls in between, which is exactly what a misbehaving child needs to
303
+ // explain itself. Filed under the ROOT session and this branch's config
304
+ // root, so a nested transcript lands in the same `tasks/` directory as its
305
+ // ancestors' rather than in a directory of its own.
306
+ const transcriptSessionId =
307
+ rootSessionId !== undefined && (config?.outputTranscript ?? getOutputTranscriptDefault())
308
+ ? rootSessionId
309
+ : undefined;
310
+ let childId: string | undefined;
311
+ const attachTranscript = (id: string): void => {
312
+ childId = id;
313
+ if (transcriptSessionId === undefined) return;
314
+ const rec = context.manager.getRecord(id);
315
+ if (!rec) return;
316
+ rec.outputFile = createOutputFilePath(context.configCwd, id, transcriptSessionId);
317
+ writeInitialEntry(rec.outputFile, id, params.prompt, ctx.cwd);
318
+ };
319
+ options.onSessionCreated = (session) => {
320
+ const rec = childId === undefined ? undefined : context.manager.getRecord(childId);
321
+ if (rec?.outputFile && childId !== undefined) {
322
+ rec.outputCleanup = streamToOutputFile(session, rec.outputFile, childId, ctx.cwd);
323
+ }
324
+ };
325
+
326
+ // `ctx` is forwarded to the manager unmodified, never captured at tool-build
327
+ // time: each AgentSession builds its own ExtensionRunner from that session's
328
+ // cwd/sessionManager/modelRegistry, so this is the CHILD's context. Capturing
329
+ // one earlier would silently give a grandchild the wrong worktree base, the
330
+ // wrong conversation under inherit_context, and the wrong inherited model.
331
+ //
332
+ // spawn() throws on strict worktree-isolation failure and cwd validation —
333
+ // report it as a tool error, like the top-level Agent tool does, instead of
334
+ // letting it escape into the child's turn.
335
+ try {
336
+ if (invocation.runInBackground) {
337
+ const id = context.manager.spawn(context.pi, ctx, resolvedType, params.prompt, {
338
+ ...options,
339
+ isBackground: true,
340
+ });
341
+ // Synchronous, before the event loop yields — onSessionCreated fires
342
+ // asynchronously inside runAgent, so the file is attached in time.
343
+ attachTranscript(id);
344
+ // Worktree isolation starts the agent asynchronously; surface its
345
+ // failure as a tool error, like the synchronous throw used to.
346
+ await context.manager.awaitStartup(id);
347
+ return textResult(`Nested agent started in background. Agent ID: ${id}`);
348
+ }
349
+
350
+ const { record } = await context.manager.spawnAndWait(
351
+ context.pi,
352
+ ctx,
353
+ resolvedType,
354
+ params.prompt,
355
+ { ...options, signal },
356
+ attachTranscript,
357
+ );
358
+ return textResult(formatRecord(record, "inline"), record.status === "error");
359
+ } catch (err) {
360
+ return textResult(err instanceof Error ? err.message : String(err), true);
361
+ }
362
+ },
363
+ });
364
+
365
+ const resultTool = defineTool({
366
+ name: NESTED_TOOL_NAMES[1],
367
+ label: "Get Nested Agent Result",
368
+ description: "Check or wait for a background nested agent owned by this parent.",
369
+ parameters: Type.Object({
370
+ agent_id: Type.String(),
371
+ wait: Type.Optional(Type.Boolean()),
372
+ }),
373
+ 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")) {
383
+ while (record.status === "queued") {
384
+ await abortable(new Promise<void>(resolve => setTimeout(resolve, 250)), signal);
385
+ }
386
+ if (record.promise) await abortable(record.promise, signal);
387
+ }
388
+ return textResult(formatRecord(record, "fetched"), record.status === "error");
389
+ },
390
+ });
391
+
392
+ const steerTool = defineTool({
393
+ name: NESTED_TOOL_NAMES[2],
394
+ label: "Steer Nested Agent",
395
+ description: "Send guidance to a running nested agent owned by this parent.",
396
+ parameters: Type.Object({
397
+ agent_id: Type.String(),
398
+ message: Type.String(),
399
+ }),
400
+ execute: async (_toolCallId, params) => {
401
+ const record = context.manager.getRecord(params.agent_id);
402
+ if (!ownsRecord(record, context.parentAgentId) || record.status !== "running") {
403
+ return textResult(`Running nested agent not found or not owned by this parent: "${params.agent_id}".`, true);
404
+ }
405
+ // Session not ready yet — queue the steer. The manager flushes pending
406
+ // steers when the session is created (same contract as the top-level tool).
407
+ if (!record.session) {
408
+ if (!record.pendingSteers) record.pendingSteers = [];
409
+ record.pendingSteers.push(params.message);
410
+ return textResult(`Steering message queued for nested agent ${params.agent_id}.`);
411
+ }
412
+ try {
413
+ await record.session.steer(params.message);
414
+ } catch (err) {
415
+ return textResult(`Failed to steer nested agent: ${err instanceof Error ? err.message : String(err)}`, true);
416
+ }
417
+ return textResult(`Steering message sent to nested agent ${params.agent_id}.`);
418
+ },
419
+ });
420
+
421
+ return [agentTool, resultTool, steerTool];
422
+ }