@esso0428/pi-subagents 0.17.6 → 0.17.8

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 (260) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/CONTRIBUTING.md +4 -0
  3. package/dist/abortable.d.ts +13 -0
  4. package/dist/abortable.d.ts.map +1 -0
  5. package/dist/abortable.js +43 -0
  6. package/dist/abortable.js.map +1 -0
  7. package/dist/agent-color.d.ts +36 -0
  8. package/dist/agent-color.d.ts.map +1 -0
  9. package/dist/agent-color.js +124 -0
  10. package/dist/agent-color.js.map +1 -0
  11. package/dist/agent-file-toggle.d.ts +126 -0
  12. package/dist/agent-file-toggle.d.ts.map +1 -0
  13. package/dist/agent-file-toggle.js +259 -0
  14. package/dist/agent-file-toggle.js.map +1 -0
  15. package/dist/agent-history.d.ts +4 -0
  16. package/dist/agent-history.d.ts.map +1 -1
  17. package/dist/agent-history.js +47 -1
  18. package/dist/agent-history.js.map +1 -1
  19. package/dist/agent-manager.d.ts +370 -56
  20. package/dist/agent-manager.d.ts.map +1 -1
  21. package/dist/agent-manager.js +1123 -409
  22. package/dist/agent-manager.js.map +1 -1
  23. package/dist/agent-runner.d.ts +100 -10
  24. package/dist/agent-runner.d.ts.map +1 -1
  25. package/dist/agent-runner.js +166 -21
  26. package/dist/agent-runner.js.map +1 -1
  27. package/dist/agent-types.d.ts +57 -5
  28. package/dist/agent-types.d.ts.map +1 -1
  29. package/dist/agent-types.js +164 -32
  30. package/dist/agent-types.js.map +1 -1
  31. package/dist/child-context.d.ts +3 -0
  32. package/dist/child-context.d.ts.map +1 -0
  33. package/dist/child-context.js +13 -0
  34. package/dist/child-context.js.map +1 -0
  35. package/dist/cross-extension-rpc.d.ts +23 -3
  36. package/dist/cross-extension-rpc.d.ts.map +1 -1
  37. package/dist/cross-extension-rpc.js +79 -17
  38. package/dist/cross-extension-rpc.js.map +1 -1
  39. package/dist/custom-agents.d.ts +38 -1
  40. package/dist/custom-agents.d.ts.map +1 -1
  41. package/dist/custom-agents.js +164 -12
  42. package/dist/custom-agents.js.map +1 -1
  43. package/dist/index.d.ts +34 -0
  44. package/dist/index.d.ts.map +1 -1
  45. package/dist/index.js +1912 -492
  46. package/dist/index.js.map +1 -1
  47. package/dist/invocation-config.d.ts +87 -2
  48. package/dist/invocation-config.d.ts.map +1 -1
  49. package/dist/invocation-config.js +71 -3
  50. package/dist/invocation-config.js.map +1 -1
  51. package/dist/mention-clone.d.ts +88 -0
  52. package/dist/mention-clone.d.ts.map +1 -0
  53. package/dist/mention-clone.js +154 -0
  54. package/dist/mention-clone.js.map +1 -0
  55. package/dist/mention.d.ts +82 -0
  56. package/dist/mention.d.ts.map +1 -0
  57. package/dist/mention.js +132 -0
  58. package/dist/mention.js.map +1 -0
  59. package/dist/model-resolver.d.ts +17 -0
  60. package/dist/model-resolver.d.ts.map +1 -1
  61. package/dist/model-resolver.js +15 -0
  62. package/dist/model-resolver.js.map +1 -1
  63. package/dist/model-scope.d.ts +50 -0
  64. package/dist/model-scope.d.ts.map +1 -0
  65. package/dist/model-scope.js +49 -0
  66. package/dist/model-scope.js.map +1 -0
  67. package/dist/nested-tools.d.ts +57 -0
  68. package/dist/nested-tools.d.ts.map +1 -0
  69. package/dist/nested-tools.js +301 -0
  70. package/dist/nested-tools.js.map +1 -0
  71. package/dist/output-file.d.ts +22 -3
  72. package/dist/output-file.d.ts.map +1 -1
  73. package/dist/output-file.js +58 -7
  74. package/dist/output-file.js.map +1 -1
  75. package/dist/prompts.d.ts +23 -0
  76. package/dist/prompts.d.ts.map +1 -1
  77. package/dist/prompts.js +20 -2
  78. package/dist/prompts.js.map +1 -1
  79. package/dist/schedule.d.ts.map +1 -1
  80. package/dist/schedule.js +36 -15
  81. package/dist/schedule.js.map +1 -1
  82. package/dist/settings.d.ts +228 -2
  83. package/dist/settings.d.ts.map +1 -1
  84. package/dist/settings.js +94 -0
  85. package/dist/settings.js.map +1 -1
  86. package/dist/status-note.d.ts +49 -1
  87. package/dist/status-note.d.ts.map +1 -1
  88. package/dist/status-note.js +62 -1
  89. package/dist/status-note.js.map +1 -1
  90. package/dist/structured-output.d.ts +62 -0
  91. package/dist/structured-output.d.ts.map +1 -0
  92. package/dist/structured-output.js +113 -0
  93. package/dist/structured-output.js.map +1 -0
  94. package/dist/types.d.ts +176 -10
  95. package/dist/types.d.ts.map +1 -1
  96. package/dist/ui/agent-mention.d.ts +83 -0
  97. package/dist/ui/agent-mention.d.ts.map +1 -0
  98. package/dist/ui/agent-mention.js +188 -0
  99. package/dist/ui/agent-mention.js.map +1 -0
  100. package/dist/ui/agent-widget.d.ts +97 -75
  101. package/dist/ui/agent-widget.d.ts.map +1 -1
  102. package/dist/ui/agent-widget.js +398 -420
  103. package/dist/ui/agent-widget.js.map +1 -1
  104. package/dist/ui/conversation-blocks.d.ts.map +1 -1
  105. package/dist/ui/conversation-blocks.js +6 -0
  106. package/dist/ui/conversation-blocks.js.map +1 -1
  107. package/dist/ui/conversation-timeline.d.ts +10 -2
  108. package/dist/ui/conversation-timeline.d.ts.map +1 -1
  109. package/dist/ui/conversation-timeline.js +130 -23
  110. package/dist/ui/conversation-timeline.js.map +1 -1
  111. package/dist/ui/conversation-viewer.d.ts +15 -5
  112. package/dist/ui/conversation-viewer.d.ts.map +1 -1
  113. package/dist/ui/conversation-viewer.js +202 -50
  114. package/dist/ui/conversation-viewer.js.map +1 -1
  115. package/dist/ui/fleet-list.d.ts +198 -0
  116. package/dist/ui/fleet-list.d.ts.map +1 -0
  117. package/dist/ui/fleet-list.js +487 -0
  118. package/dist/ui/fleet-list.js.map +1 -0
  119. package/dist/ui/schedule-menu.d.ts.map +1 -1
  120. package/dist/ui/schedule-menu.js +6 -7
  121. package/dist/ui/schedule-menu.js.map +1 -1
  122. package/dist/ui/select-item.d.ts +28 -0
  123. package/dist/ui/select-item.d.ts.map +1 -0
  124. package/dist/ui/select-item.js +35 -0
  125. package/dist/ui/select-item.js.map +1 -0
  126. package/dist/ui/workflow-card.d.ts +176 -0
  127. package/dist/ui/workflow-card.d.ts.map +1 -0
  128. package/dist/ui/workflow-card.js +333 -0
  129. package/dist/ui/workflow-card.js.map +1 -0
  130. package/dist/ui/workflow-dialog.d.ts +306 -0
  131. package/dist/ui/workflow-dialog.d.ts.map +1 -0
  132. package/dist/ui/workflow-dialog.js +844 -0
  133. package/dist/ui/workflow-dialog.js.map +1 -0
  134. package/dist/ui/workflow-menu.d.ts +61 -0
  135. package/dist/ui/workflow-menu.d.ts.map +1 -0
  136. package/dist/ui/workflow-menu.js +148 -0
  137. package/dist/ui/workflow-menu.js.map +1 -0
  138. package/dist/usage.d.ts +86 -1
  139. package/dist/usage.d.ts.map +1 -1
  140. package/dist/usage.js +72 -1
  141. package/dist/usage.js.map +1 -1
  142. package/dist/workflow/collisions.d.ts +96 -0
  143. package/dist/workflow/collisions.d.ts.map +1 -0
  144. package/dist/workflow/collisions.js +89 -0
  145. package/dist/workflow/collisions.js.map +1 -0
  146. package/dist/workflow/entry.d.ts +33 -0
  147. package/dist/workflow/entry.d.ts.map +1 -0
  148. package/dist/workflow/entry.js +30 -0
  149. package/dist/workflow/entry.js.map +1 -0
  150. package/dist/workflow/host.d.ts +63 -0
  151. package/dist/workflow/host.d.ts.map +1 -0
  152. package/dist/workflow/host.js +363 -0
  153. package/dist/workflow/host.js.map +1 -0
  154. package/dist/workflow/journal.d.ts +98 -0
  155. package/dist/workflow/journal.d.ts.map +1 -0
  156. package/dist/workflow/journal.js +121 -0
  157. package/dist/workflow/journal.js.map +1 -0
  158. package/dist/workflow/json-schema.d.ts +52 -0
  159. package/dist/workflow/json-schema.d.ts.map +1 -0
  160. package/dist/workflow/json-schema.js +112 -0
  161. package/dist/workflow/json-schema.js.map +1 -0
  162. package/dist/workflow/meta.d.ts +68 -0
  163. package/dist/workflow/meta.d.ts.map +1 -0
  164. package/dist/workflow/meta.js +318 -0
  165. package/dist/workflow/meta.js.map +1 -0
  166. package/dist/workflow/progress.d.ts +225 -0
  167. package/dist/workflow/progress.d.ts.map +1 -0
  168. package/dist/workflow/progress.js +362 -0
  169. package/dist/workflow/progress.js.map +1 -0
  170. package/dist/workflow/runtime.d.ts +335 -0
  171. package/dist/workflow/runtime.d.ts.map +1 -0
  172. package/dist/workflow/runtime.js +831 -0
  173. package/dist/workflow/runtime.js.map +1 -0
  174. package/dist/workflow/saved.d.ts +91 -0
  175. package/dist/workflow/saved.d.ts.map +1 -0
  176. package/dist/workflow/saved.js +204 -0
  177. package/dist/workflow/saved.js.map +1 -0
  178. package/dist/workflow/task.d.ts +137 -0
  179. package/dist/workflow/task.d.ts.map +1 -0
  180. package/dist/workflow/task.js +208 -0
  181. package/dist/workflow/task.js.map +1 -0
  182. package/dist/workflow/tool-description.d.ts +39 -0
  183. package/dist/workflow/tool-description.d.ts.map +1 -0
  184. package/dist/workflow/tool-description.js +200 -0
  185. package/dist/workflow/tool-description.js.map +1 -0
  186. package/dist/workflow/worker-source.d.ts +48 -0
  187. package/dist/workflow/worker-source.d.ts.map +1 -0
  188. package/dist/workflow/worker-source.js +779 -0
  189. package/dist/workflow/worker-source.js.map +1 -0
  190. package/dist/worktree.d.ts +10 -3
  191. package/dist/worktree.d.ts.map +1 -1
  192. package/dist/worktree.js +58 -54
  193. package/dist/worktree.js.map +1 -1
  194. package/dist/xml.d.ts +11 -0
  195. package/dist/xml.d.ts.map +1 -0
  196. package/dist/xml.js +13 -0
  197. package/dist/xml.js.map +1 -0
  198. package/docs/rpc.md +183 -0
  199. package/docs/superpowers/plans/2026-09-30-upstream-event-workflow-partial-history.md +195 -0
  200. package/docs/superpowers/specs/2026-09-30-upstream-event-workflow-partial-history-design.md +49 -0
  201. package/docs/workflows.md +437 -0
  202. package/examples/agent-tool-description.md +7 -7
  203. package/examples/workflows/compose.js +51 -0
  204. package/examples/workflows/fan-out-audit.js +47 -0
  205. package/examples/workflows/gated-fix.js +60 -0
  206. package/examples/workflows/lib/count-child.js +27 -0
  207. package/examples/workflows/review-panel.js +63 -0
  208. package/examples/workflows/structured-findings.js +78 -0
  209. package/package.json +1 -1
  210. package/src/abortable.ts +43 -0
  211. package/src/agent-color.ts +161 -0
  212. package/src/agent-file-toggle.ts +269 -0
  213. package/src/agent-history.ts +54 -2
  214. package/src/agent-manager.ts +1263 -402
  215. package/src/agent-runner.ts +251 -27
  216. package/src/agent-types.ts +188 -32
  217. package/src/child-context.ts +15 -0
  218. package/src/cross-extension-rpc.ts +96 -20
  219. package/src/custom-agents.ts +170 -13
  220. package/src/index.ts +2029 -536
  221. package/src/invocation-config.ts +118 -3
  222. package/src/mention-clone.ts +196 -0
  223. package/src/mention.ts +141 -0
  224. package/src/model-resolver.ts +18 -0
  225. package/src/model-scope.ts +70 -0
  226. package/src/nested-tools.ts +424 -0
  227. package/src/output-file.ts +61 -6
  228. package/src/prompts.ts +45 -2
  229. package/src/schedule.ts +35 -14
  230. package/src/settings.ts +312 -2
  231. package/src/status-note.ts +66 -1
  232. package/src/structured-output.ts +130 -0
  233. package/src/types.ts +177 -10
  234. package/src/ui/agent-mention.ts +216 -0
  235. package/src/ui/agent-widget.ts +393 -441
  236. package/src/ui/conversation-blocks.ts +6 -0
  237. package/src/ui/conversation-timeline.ts +139 -25
  238. package/src/ui/conversation-viewer.ts +212 -48
  239. package/src/ui/fleet-list.ts +558 -0
  240. package/src/ui/schedule-menu.ts +9 -8
  241. package/src/ui/select-item.ts +45 -0
  242. package/src/ui/workflow-card.ts +470 -0
  243. package/src/ui/workflow-dialog.ts +1115 -0
  244. package/src/ui/workflow-menu.ts +193 -0
  245. package/src/usage.ts +109 -2
  246. package/src/workflow/collisions.ts +123 -0
  247. package/src/workflow/entry.ts +47 -0
  248. package/src/workflow/host.ts +403 -0
  249. package/src/workflow/journal.ts +164 -0
  250. package/src/workflow/json-schema.ts +128 -0
  251. package/src/workflow/meta.ts +325 -0
  252. package/src/workflow/progress.ts +550 -0
  253. package/src/workflow/runtime.ts +1219 -0
  254. package/src/workflow/saved.ts +217 -0
  255. package/src/workflow/task.ts +302 -0
  256. package/src/workflow/tool-description.ts +200 -0
  257. package/src/workflow/worker-source.ts +781 -0
  258. package/src/worktree.ts +69 -55
  259. package/src/xml.ts +13 -0
  260. package/vitest.config.ts +0 -18
@@ -7,10 +7,9 @@
7
7
 
8
8
  import { createCodingTools, createReadOnlyTools } from "@earendil-works/pi-coding-agent";
9
9
  import { DEFAULT_AGENTS } from "./default-agents.js";
10
- import { applyNicoOverridesToMap, readNicoAgentOverrides } from "./nico-overrides.js";
10
+ import { applyNicoOverride, applyNicoOverridesToMap, readNicoAgentOverrides } from "./nico-overrides.js";
11
11
  import type { AgentConfig } from "./types.js";
12
12
 
13
-
14
13
  /**
15
14
  * All known built-in tool names, derived from pi's own tool factories rather
16
15
  * than hardcoded so the set tracks pi-mono if it adds/renames a built-in.
@@ -35,6 +34,41 @@ export function isDefaultsDisabled(): boolean { return disableDefaults; }
35
34
  /** Set whether default agents are disabled. */
36
35
  export function setDefaultsDisabled(b: boolean): void { disableDefaults = b; }
37
36
 
37
+ /** `fallbackSubagent` value that disables the fallback entirely (strict dispatch). */
38
+ export const NO_FALLBACK = "none";
39
+
40
+ /**
41
+ * Agent type substituted when a caller-supplied `subagent_type` doesn't resolve
42
+ * to exactly one enabled agent. `undefined` keeps the historical behavior
43
+ * (general-purpose); `NO_FALLBACK` makes dispatch fail closed. Set from
44
+ * `subagents.json` (`fallbackSubagent`).
45
+ *
46
+ * Module state rather than an index.ts closure because every caller-supplied
47
+ * spawn path needs it — the Agent tool, the scheduler, and cross-extension RPC.
48
+ */
49
+ let fallbackSubagent: string | undefined;
50
+
51
+ /** Get the configured fallback agent type. undefined = general-purpose. */
52
+ export function getFallbackSubagent(): string | undefined { return fallbackSubagent; }
53
+
54
+ /** Set the configured fallback agent type. undefined = general-purpose. */
55
+ export function setFallbackSubagent(v: string | undefined): void { fallbackSubagent = v; }
56
+
57
+ /**
58
+ * Build a registry map: DEFAULT_AGENTS first (unless disabled via settings),
59
+ * then user agents overlaid on top (same name overrides the default).
60
+ * Pure — callers that must not disturb the process-wide registry (nested
61
+ * delegation resolving agents from its own config root) build their own map.
62
+ */
63
+ export function buildAgentRegistry(userAgents: Map<string, AgentConfig>): Map<string, AgentConfig> {
64
+ const registry = new Map<string, AgentConfig>();
65
+ if (!disableDefaults) {
66
+ for (const [name, config] of DEFAULT_AGENTS) registry.set(name, config);
67
+ }
68
+ for (const [name, config] of userAgents) registry.set(name, config);
69
+ return registry;
70
+ }
71
+
38
72
  /**
39
73
  * Register agents into the unified registry.
40
74
  * Starts with DEFAULT_AGENTS, then overlays user agents (overrides defaults with same name).
@@ -42,39 +76,163 @@ export function setDefaultsDisabled(b: boolean): void { disableDefaults = b; }
42
76
  */
43
77
  export function registerAgents(userAgents: Map<string, AgentConfig>): void {
44
78
  agents.clear();
45
-
46
- // Start with defaults (unless disabled via settings)
79
+ for (const [name, config] of buildAgentRegistry(userAgents)) {
80
+ agents.set(name, config);
81
+ }
82
+ const { overrides, defaultModel } = readNicoAgentOverrides(process.cwd());
47
83
  if (!disableDefaults) {
48
- for (const [name, config] of DEFAULT_AGENTS) {
49
- agents.set(name, config);
84
+ applyNicoOverridesToMap(agents, overrides, defaultModel);
85
+ } else {
86
+ // Disabling built-ins must also prevent JSON-only built-ins from being
87
+ // synthesized; explicit user agents remain eligible for their overrides.
88
+ for (const [name, config] of agents) {
89
+ const override = overrides[name];
90
+ if (override) agents.set(name, applyNicoOverride(config, override, defaultModel));
50
91
  }
51
92
  }
93
+ }
52
94
 
53
- // Overlay user agents (overrides defaults with same name)
54
- for (const [name, config] of userAgents) {
55
- agents.set(name, config);
95
+ /** Case-insensitive key resolution within a registry. */
96
+ function resolveKeyIn(registry: Map<string, AgentConfig>, name: string): string | undefined {
97
+ if (registry.has(name)) return name;
98
+ const lower = name.toLowerCase();
99
+ for (const key of registry.keys()) {
100
+ if (key.toLowerCase() === lower) return key;
56
101
  }
102
+ return undefined;
103
+ }
104
+
105
+ /** Case-insensitive key resolution. */
106
+ function resolveKey(name: string): string | undefined {
107
+ return resolveKeyIn(agents, name);
108
+ }
109
+
110
+ /** Resolve a type name case-insensitively in a registry. Returns the canonical key or undefined. */
111
+ export function resolveTypeIn(registry: Map<string, AgentConfig>, name: string): string | undefined {
112
+ return resolveKeyIn(registry, name);
113
+ }
114
+
115
+ /** Get the agent config for a type (case-insensitive) from a registry. */
116
+ export function getAgentConfigIn(registry: Map<string, AgentConfig>, name: string): AgentConfig | undefined {
117
+ const key = resolveKeyIn(registry, name);
118
+ return key ? registry.get(key) : undefined;
119
+ }
120
+
121
+ /** Check if a type is valid and enabled (case-insensitive) in a registry. */
122
+ export function isValidTypeIn(registry: Map<string, AgentConfig>, type: string): boolean {
123
+ const key = resolveKeyIn(registry, type);
124
+ if (!key) return false;
125
+ return registry.get(key)?.enabled !== false;
126
+ }
127
+
128
+ /** Get all enabled type names in a registry (for spawning and tool descriptions). */
129
+ export function getAvailableTypesIn(registry: Map<string, AgentConfig>): string[] {
130
+ return [...registry.entries()]
131
+ .filter(([_, config]) => config.enabled !== false)
132
+ .map(([name]) => name);
57
133
  }
58
134
 
59
135
  /**
60
- * Apply npm:pi-subagents-style JSON overrides to the current agent registry.
61
- * Reads from ~/.pi/agent/settings.json and .pi/settings.json and applies
62
- * them as the highest-priority layer. Auto-registers agents that don't
63
- * exist in the registry yet.
136
+ * Case-insensitive resolution that refuses to guess. An exact match always wins;
137
+ * otherwise the name must match exactly one key. Two agents differing only in
138
+ * case are reachable (`loadCustomAgents` keys by filename across three
139
+ * directories), and picking whichever came first would silently dispatch a
140
+ * different agent, model and tool policy than the caller meant.
64
141
  */
65
- export function applyNicoOverrides(): void {
66
- const { overrides, defaultModel } = readNicoAgentOverrides(process.cwd());
67
- applyNicoOverridesToMap(agents, overrides, defaultModel);
142
+ function resolveUnambiguousKeyIn(registry: Map<string, AgentConfig>, name: string): string | undefined {
143
+ if (registry.has(name)) return name;
144
+ const lower = name.toLowerCase();
145
+ const matches = [...registry.keys()].filter(key => key.toLowerCase() === lower);
146
+ return matches.length === 1 ? matches[0] : undefined;
68
147
  }
69
148
 
70
- /** Case-insensitive key resolution. */
71
- function resolveKey(name: string): string | undefined {
72
- if (agents.has(name)) return name;
73
- const lower = name.toLowerCase();
74
- for (const key of agents.keys()) {
75
- if (key.toLowerCase() === lower) return key;
149
+ /**
150
+ * The canonical key for a caller-supplied name that identifies exactly one
151
+ * ENABLED agent, or undefined. Strict by construction: no fallback, no guessing
152
+ * between case-variants. Nested delegation resolves with this directly, since
153
+ * "unknown types are rejected rather than falling back" is its own contract.
154
+ */
155
+ export function resolveEnabledTypeIn(
156
+ registry: Map<string, AgentConfig>,
157
+ requested: unknown,
158
+ ): string | undefined {
159
+ const raw = typeof requested === "string" ? requested.trim() : "";
160
+ if (!raw) return undefined;
161
+ const key = resolveUnambiguousKeyIn(registry, raw);
162
+ return key !== undefined && registry.get(key)?.enabled !== false ? key : undefined;
163
+ }
164
+
165
+ /** Outcome of resolving a caller-supplied `subagent_type` into a spawnable type. */
166
+ export type SpawnTypeResolution =
167
+ /** Spawn this type. `fellBackFrom` is set when it isn't what the caller asked for. */
168
+ | { ok: true; type: string; fellBackFrom?: string }
169
+ /** Refuse the spawn and return this message to the caller. */
170
+ | { ok: false; message: string };
171
+
172
+ /**
173
+ * Resolve a caller-supplied agent type against a registry, applying the
174
+ * `fallbackSubagent` policy. The single decision point for every caller-supplied
175
+ * spawn — the Agent tool, the scheduler, cross-extension RPC, and the nested
176
+ * tools — so a type that fails here never reaches `runAgent`, where `getConfig`
177
+ * would silently substitute general-purpose.
178
+ *
179
+ * Unknown, disabled, and case-ambiguous names are all treated the same way:
180
+ * the caller named something that doesn't identify exactly one enabled agent.
181
+ *
182
+ * Pure over `registry` — callers that need fresh agent files reload before
183
+ * calling (the Agent tool already does, per spawn). Reloading here would mean
184
+ * importing custom-agents.ts, which imports this module.
185
+ */
186
+ export function resolveSpawnTypeIn(
187
+ registry: Map<string, AgentConfig>,
188
+ requested: unknown,
189
+ ): SpawnTypeResolution {
190
+ const raw = typeof requested === "string" ? requested.trim() : "";
191
+ const available = () => getAvailableTypesIn(registry).join(", ") || "(none)";
192
+
193
+ const key = resolveEnabledTypeIn(registry, raw);
194
+ if (key !== undefined) return { ok: true, type: key };
195
+
196
+ // A missing type follows the same policy as a wrong one rather than always
197
+ // erroring: before this setting existed an empty type fell back like any
198
+ // other unresolvable name, and only opting in should change that.
199
+ const reason = raw ? `Unknown or disabled agent type: "${raw}".` : "No agent type given.";
200
+
201
+ // Trimmed like `requested`: a padded value set programmatically would
202
+ // otherwise be reported as a missing agent.
203
+ const configured = typeof fallbackSubagent === "string" ? fallbackSubagent.trim() : undefined;
204
+
205
+ if (configured !== undefined && configured.toLowerCase() === NO_FALLBACK) {
206
+ return { ok: false, message: `${reason} Available: ${available()}.` };
76
207
  }
77
- return undefined;
208
+
209
+ if (configured !== undefined) {
210
+ // An explicitly configured fallback that is itself unusable is a
211
+ // misconfiguration, not a second chance to guess — say so rather than
212
+ // quietly dropping to general-purpose.
213
+ const fallbackKey = resolveUnambiguousKeyIn(registry, configured);
214
+ if (fallbackKey === undefined || registry.get(fallbackKey)?.enabled === false) {
215
+ return {
216
+ ok: false,
217
+ message:
218
+ `${reason} The configured fallbackSubagent "${configured}" is itself ` +
219
+ `unknown or disabled. Available: ${available()}.`,
220
+ };
221
+ }
222
+ return { ok: true, type: fallbackKey, fellBackFrom: raw };
223
+ }
224
+
225
+ // Unset: historical behavior, deliberately unchanged. #183 asks for the
226
+ // fallback to remain the default, so the pre-existing hole it leaves — an
227
+ // unregistered general-purpose resolving to `getConfig`'s all-tools hardcoded
228
+ // tier — is what `fallbackSubagent: none` is for, not something to close
229
+ // under everyone silently.
230
+ return { ok: true, type: "general-purpose", fellBackFrom: raw };
231
+ }
232
+
233
+ /** Resolve a caller-supplied agent type against the process-wide registry. */
234
+ export function resolveSpawnType(requested: unknown): SpawnTypeResolution {
235
+ return resolveSpawnTypeIn(agents, requested);
78
236
  }
79
237
 
80
238
  /** Resolve a type name case-insensitively. Returns the canonical key or undefined. */
@@ -84,15 +242,12 @@ export function resolveType(name: string): string | undefined {
84
242
 
85
243
  /** Get the agent config for a type (case-insensitive). */
86
244
  export function getAgentConfig(name: string): AgentConfig | undefined {
87
- const key = resolveKey(name);
88
- return key ? agents.get(key) : undefined;
245
+ return getAgentConfigIn(agents, name);
89
246
  }
90
247
 
91
248
  /** Get all enabled type names (for spawning and tool descriptions). */
92
249
  export function getAvailableTypes(): string[] {
93
- return [...agents.entries()]
94
- .filter(([_, config]) => config.enabled !== false)
95
- .map(([name]) => name);
250
+ return getAvailableTypesIn(agents);
96
251
  }
97
252
 
98
253
  /** Get all type names including disabled (for UI listing). */
@@ -110,15 +265,13 @@ export function getDefaultAgentNames(): string[] {
110
265
  /** Get names of user-defined agents (non-defaults) currently in the registry. */
111
266
  export function getUserAgentNames(): string[] {
112
267
  return [...agents.entries()]
113
- .filter(([_, config]) => config.isDefault !== true)
268
+ .filter(([_, config]) => config.isDefault !== true && !config.description.startsWith("Auto-registered from npm:pi-subagents JSON settings"))
114
269
  .map(([name]) => name);
115
270
  }
116
271
 
117
272
  /** Check if a type is valid and enabled (case-insensitive). */
118
273
  export function isValidType(type: string): boolean {
119
- const key = resolveKey(type);
120
- if (!key) return false;
121
- return agents.get(key)?.enabled !== false;
274
+ return isValidTypeIn(agents, type);
122
275
  }
123
276
 
124
277
  /** Tool names required for memory management. */
@@ -154,6 +307,7 @@ export function getToolNamesForType(type: string): string[] {
154
307
  /** Get config for a type (case-insensitive, returns a SubagentTypeConfig-compatible object). Falls back to general-purpose. */
155
308
  export function getConfig(type: string): {
156
309
  displayName: string;
310
+ color?: string;
157
311
  description: string;
158
312
  builtinToolNames: string[];
159
313
  extensions: true | string[] | false;
@@ -166,6 +320,7 @@ export function getConfig(type: string): {
166
320
  if (config && config.enabled !== false) {
167
321
  return {
168
322
  displayName: config.displayName ?? config.name,
323
+ color: config.color,
169
324
  description: config.description,
170
325
  builtinToolNames: config.builtinToolNames ?? BUILTIN_TOOL_NAMES,
171
326
  extensions: config.extensions,
@@ -180,6 +335,7 @@ export function getConfig(type: string): {
180
335
  if (gp && gp.enabled !== false) {
181
336
  return {
182
337
  displayName: gp.displayName ?? gp.name,
338
+ color: gp.color,
183
339
  description: gp.description,
184
340
  builtinToolNames: gp.builtinToolNames ?? BUILTIN_TOOL_NAMES,
185
341
  extensions: gp.extensions,
@@ -0,0 +1,15 @@
1
+ import { AsyncLocalStorage } from "node:async_hooks";
2
+
3
+ /**
4
+ * Marks resource loading/session construction performed for a subagent. This is
5
+ * async-context-local so concurrent top-level extension work is unaffected.
6
+ */
7
+ const childSessionContext = new AsyncLocalStorage<boolean>();
8
+
9
+ export function inChildSessionContext(): boolean {
10
+ return childSessionContext.getStore() === true;
11
+ }
12
+
13
+ export function runInChildSessionContext<T>(fn: () => Promise<T>): Promise<T> {
14
+ return childSessionContext.run(true, fn);
15
+ }
@@ -1,15 +1,22 @@
1
1
  /**
2
2
  * Cross-extension RPC handlers for the subagents extension.
3
3
  *
4
- * Exposes ping, spawn, and stop RPCs over the pi.events event bus,
4
+ * Exposes ping, spawn, stop, and consume RPCs over the pi.events event bus,
5
5
  * using per-request scoped reply channels.
6
6
  *
7
7
  * Reply envelope follows pi-mono convention:
8
8
  * success → { success: true, data?: T }
9
9
  * error → { success: false, error: string }
10
+ *
11
+ * @see docs/rpc.md — the caller-facing integration reference: spawn options
12
+ * (including the fields spawnTopLevel strips), every error string, the
13
+ * completion-notification race, and what protocol version 2 does not promise.
10
14
  */
11
15
 
16
+ import { isTopLevelAgent } from "./agent-manager.js";
12
17
  import { type ModelRegistry, resolveModel } from "./model-resolver.js";
18
+ import { checkModelScope } from "./model-scope.js";
19
+ import type { AgentRecord } from "./types.js";
13
20
 
14
21
  /** Minimal event bus interface needed by the RPC handlers. */
15
22
  export interface EventBus {
@@ -25,10 +32,24 @@ export type RpcReply<T = void> =
25
32
  /** RPC protocol version — bumped when the envelope or method contracts change. */
26
33
  export const PROTOCOL_VERSION = 2;
27
34
 
28
- /** Minimal AgentManager interface needed by the spawn/stop RPCs. */
35
+ /** Minimal AgentManager interface needed by the spawn/stop/consume RPCs. */
29
36
  export interface SpawnCapable {
30
37
  spawn(pi: unknown, ctx: unknown, type: string, prompt: string, options: any): string;
38
+ /** Resolves once the spawned agent is running; rejects on a startup failure. */
39
+ awaitStartup(id: string): Promise<void>;
31
40
  abort(id: string): boolean;
41
+ /**
42
+ * The record behind an id, for the stop handler's ownership check. Narrowed
43
+ * to the two fields `isTopLevelAgent` reads, so the RPC layer keeps its
44
+ * deliberately shallow view of the manager.
45
+ */
46
+ getRecord(id: string): Pick<AgentRecord, "parentAgentId" | "workflowId"> | undefined;
47
+ /**
48
+ * Mark a settled agent's result as read by the caller, suppressing the
49
+ * completion notification — what `get_subagent_result` does when it returns
50
+ * one. False when there is no such agent, or it has not settled yet.
51
+ */
52
+ consumeResult(id: string): boolean;
32
53
  }
33
54
 
34
55
  export interface RpcDeps {
@@ -42,6 +63,7 @@ export interface RpcHandle {
42
63
  unsubPing: () => void;
43
64
  unsubSpawn: () => void;
44
65
  unsubStop: () => void;
66
+ unsubConsume: () => void;
45
67
  }
46
68
 
47
69
  /**
@@ -69,7 +91,7 @@ function handleRpc<P extends { requestId: string }>(
69
91
  }
70
92
 
71
93
  /**
72
- * Register ping, spawn, and stop RPC handlers on the event bus.
94
+ * Register ping, spawn, stop, and consume RPC handlers on the event bus.
73
95
  * Returns unsub functions for cleanup.
74
96
  */
75
97
  export function registerRpcHandlers(deps: RpcDeps): RpcHandle {
@@ -80,7 +102,7 @@ export function registerRpcHandlers(deps: RpcDeps): RpcHandle {
80
102
  });
81
103
 
82
104
  const unsubSpawn = handleRpc<{ requestId: string; type: string; prompt: string; options?: any }>(
83
- events, "subagents:rpc:spawn", ({ type, prompt, options }) => {
105
+ events, "subagents:rpc:spawn", async ({ type, prompt, options }) => {
84
106
  const ctx = getCtx();
85
107
  if (!ctx) throw new Error("No active session");
86
108
 
@@ -91,32 +113,86 @@ export function registerRpcHandlers(deps: RpcDeps): RpcHandle {
91
113
  // agent's auth lookup doesn't crash with "No API key found for
92
114
  // undefined".
93
115
  let normalizedOptions = options ?? {};
94
- if (typeof normalizedOptions.model === "string") {
95
- const registry = (ctx as { modelRegistry?: ModelRegistry }).modelRegistry;
96
- if (!registry) {
97
- throw new Error(
98
- `Model override "${normalizedOptions.model}" provided but ctx.modelRegistry is unavailable`,
99
- );
116
+ // `!= null` on purpose: a JSON-forwarding caller can serialize an unset
117
+ // field as null, and the runner reads `options.model ?? default`, so null
118
+ // means "inherit" — not an override to resolve or scope-check.
119
+ const override = normalizedOptions.model;
120
+ if (override != null) {
121
+ const { modelRegistry, cwd } = ctx as { modelRegistry?: ModelRegistry; cwd?: string };
122
+ // Names the override the same way in both messages below; an object
123
+ // override would otherwise interpolate as "[object Object]".
124
+ const label = typeof override === "string" ? override : `${override.provider}/${override.id}`;
125
+ if (!modelRegistry) {
126
+ throw new Error(`Model override "${label}" provided but ctx.modelRegistry is unavailable`);
100
127
  }
101
- const resolved = resolveModel(normalizedOptions.model, registry);
102
- if (typeof resolved === "string") {
103
- // resolveModel returns a human-readable error string when the
104
- // input doesn't match any available model. Surface it instead of
105
- // silently falling back so the caller sees the auth/typo issue.
106
- throw new Error(resolved);
128
+ let model = override;
129
+ if (typeof override === "string") {
130
+ const resolved = resolveModel(override, modelRegistry);
131
+ if (typeof resolved === "string") {
132
+ // resolveModel returns a human-readable error string when the
133
+ // input doesn't match any available model. Surface it instead of
134
+ // silently falling back so the caller sees the auth/typo issue.
135
+ throw new Error(resolved);
136
+ }
137
+ model = resolved;
138
+ normalizedOptions = { ...normalizedOptions, model: resolved };
107
139
  }
108
- normalizedOptions = { ...normalizedOptions, model: resolved };
140
+
141
+ // A model on the RPC payload is an orchestrator-level choice, exactly
142
+ // like Agent({ model }) — so it gets the Agent tool's hard error, never
143
+ // the frontmatter warn (#240). The check reads the RESOLVED model:
144
+ // resolveModel is fuzzy, so a bare "sonnet" can land on a provider the
145
+ // caller never named. Frontmatter-pinned and parent-inherited models are
146
+ // resolved later, in agent-runner, and keep warn-and-proceed.
147
+ const verdict = checkModelScope({
148
+ model,
149
+ cwd: cwd ?? process.cwd(),
150
+ modelRegistry,
151
+ callerSupplied: true,
152
+ agentLabel: type,
153
+ modelInput: label,
154
+ });
155
+ if (verdict.kind === "error") throw new Error(verdict.message);
109
156
  }
110
157
 
111
- return { id: manager.spawn(pi, ctx, type, prompt, normalizedOptions) };
158
+ const id = manager.spawn(pi, ctx, type, prompt, normalizedOptions);
159
+ // With isolation: "worktree" the agent starts asynchronously — wait for
160
+ // it, so a strict-isolation failure is still an error envelope rather
161
+ // than an id for an agent that never ran.
162
+ await manager.awaitStartup(id);
163
+ return { id };
112
164
  },
113
165
  );
114
166
 
115
167
  const unsubStop = handleRpc<{ requestId: string; agentId: string }>(
116
168
  events, "subagents:rpc:stop", ({ agentId }) => {
117
- if (!manager.abort(agentId)) throw new Error("Agent not found");
169
+ const record = manager.getRecord(agentId);
170
+ if (!record) throw new Error("Agent not found");
171
+ // Only the session's own agents are this RPC's to stop. A nested child or
172
+ // a workflow's agent is owned by something that is *waiting on it*, and
173
+ // aborting it out from under that owner turns another extension's stop
174
+ // into a failed step here. Defence in depth rather than a live hole: no
175
+ // RPC hands out agent ids, so a caller has no ordinary way to name one it
176
+ // does not own — but the guard is cheap and the id may leak some other
177
+ // way. Same refuse-what-we-should-not-touch stance as `consume` below.
178
+ if (!isTopLevelAgent(record)) throw new Error("Agent is owned by another agent or workflow");
179
+ // Not "not found" — the lookup above already proved it exists. `abort`
180
+ // returns false only for a record that is neither running nor queued,
181
+ // which is an agent that has already finished.
182
+ if (!manager.abort(agentId)) throw new Error("Agent is not running");
183
+ },
184
+ );
185
+
186
+ // A caller that has already shown the model an agent's result — pi-tasks'
187
+ // TaskOutput is the one in practice — says so here, so the completion
188
+ // notification for that same result is not delivered on top of it and does
189
+ // not cost the parent a turn. Deliberately outside the ping version
190
+ // handshake: an extension built against protocol v2 simply never calls it.
191
+ const unsubConsume = handleRpc<{ requestId: string; agentId: string }>(
192
+ events, "subagents:rpc:consume", ({ agentId }) => {
193
+ if (!manager.consumeResult(agentId)) throw new Error("Agent not found or still running");
118
194
  },
119
195
  );
120
196
 
121
- return { unsubPing, unsubSpawn, unsubStop };
197
+ return { unsubPing, unsubSpawn, unsubStop, unsubConsume };
122
198
  }