@timmyjl12/pi-subagents 0.0.0-stage → 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 (218) hide show
  1. package/CHANGELOG.md +827 -0
  2. package/CONTRIBUTING.md +72 -0
  3. package/LICENSE +21 -0
  4. package/README.md +1079 -2
  5. package/SECURITY.md +97 -0
  6. package/dist/abortable.d.ts +12 -0
  7. package/dist/abortable.js +42 -0
  8. package/dist/active-agents-prompt.d.ts +18 -0
  9. package/dist/active-agents-prompt.js +34 -0
  10. package/dist/advisor-status.d.ts +16 -0
  11. package/dist/advisor-status.js +74 -0
  12. package/dist/agent-color.d.ts +35 -0
  13. package/dist/agent-color.js +123 -0
  14. package/dist/agent-file-toggle.d.ts +125 -0
  15. package/dist/agent-file-toggle.js +264 -0
  16. package/dist/agent-manager.d.ts +485 -0
  17. package/dist/agent-manager.js +1380 -0
  18. package/dist/agent-runner.d.ts +319 -0
  19. package/dist/agent-runner.js +1128 -0
  20. package/dist/agent-types.d.ts +119 -0
  21. package/dist/agent-types.js +286 -0
  22. package/dist/child-context.d.ts +15 -0
  23. package/dist/child-context.js +181 -0
  24. package/dist/child-session-shutdown.d.ts +3 -0
  25. package/dist/child-session-shutdown.js +48 -0
  26. package/dist/context.d.ts +12 -0
  27. package/dist/context.js +56 -0
  28. package/dist/cross-extension-rpc.d.ts +66 -0
  29. package/dist/cross-extension-rpc.js +138 -0
  30. package/dist/custom-agents.d.ts +54 -0
  31. package/dist/custom-agents.js +386 -0
  32. package/dist/default-agents.d.ts +7 -0
  33. package/dist/default-agents.js +125 -0
  34. package/dist/enabled-models.d.ts +49 -0
  35. package/dist/enabled-models.js +145 -0
  36. package/dist/env.d.ts +6 -0
  37. package/dist/env.js +28 -0
  38. package/dist/error-log.d.ts +58 -0
  39. package/dist/error-log.js +168 -0
  40. package/dist/group-join.d.ts +32 -0
  41. package/dist/group-join.js +116 -0
  42. package/dist/index.d.ts +52 -0
  43. package/dist/index.js +3896 -0
  44. package/dist/invocation-config.d.ts +137 -0
  45. package/dist/invocation-config.js +129 -0
  46. package/dist/memory.d.ts +53 -0
  47. package/dist/memory.js +165 -0
  48. package/dist/mention-clone.d.ts +87 -0
  49. package/dist/mention-clone.js +178 -0
  50. package/dist/mention.d.ts +81 -0
  51. package/dist/mention.js +131 -0
  52. package/dist/model-resolver.d.ts +36 -0
  53. package/dist/model-resolver.js +95 -0
  54. package/dist/model-scope.d.ts +49 -0
  55. package/dist/model-scope.js +48 -0
  56. package/dist/nested-tools.d.ts +55 -0
  57. package/dist/nested-tools.js +299 -0
  58. package/dist/output-diagnostics.d.ts +11 -0
  59. package/dist/output-diagnostics.js +64 -0
  60. package/dist/output-file.d.ts +53 -0
  61. package/dist/output-file.js +248 -0
  62. package/dist/prompts.d.ts +61 -0
  63. package/dist/prompts.js +94 -0
  64. package/dist/recovery.d.ts +56 -0
  65. package/dist/recovery.js +341 -0
  66. package/dist/schedule-store.d.ts +44 -0
  67. package/dist/schedule-store.js +210 -0
  68. package/dist/schedule.d.ts +109 -0
  69. package/dist/schedule.js +359 -0
  70. package/dist/settings.d.ts +360 -0
  71. package/dist/settings.js +251 -0
  72. package/dist/skill-loader.d.ts +24 -0
  73. package/dist/skill-loader.js +93 -0
  74. package/dist/standalone-fallback.d.ts +30 -0
  75. package/dist/standalone-fallback.js +239 -0
  76. package/dist/status-note.d.ts +61 -0
  77. package/dist/status-note.js +85 -0
  78. package/dist/structured-output.d.ts +61 -0
  79. package/dist/structured-output.js +112 -0
  80. package/dist/terminal-progress.d.ts +115 -0
  81. package/dist/terminal-progress.js +206 -0
  82. package/dist/types.d.ts +382 -0
  83. package/dist/types.js +5 -0
  84. package/dist/ui/agent-mention.d.ts +82 -0
  85. package/dist/ui/agent-mention.js +187 -0
  86. package/dist/ui/agent-widget.d.ts +235 -0
  87. package/dist/ui/agent-widget.js +652 -0
  88. package/dist/ui/conversation-viewer.d.ts +105 -0
  89. package/dist/ui/conversation-viewer.js +540 -0
  90. package/dist/ui/fleet-list.d.ts +183 -0
  91. package/dist/ui/fleet-list.js +494 -0
  92. package/dist/ui/fleet-overlay.d.ts +172 -0
  93. package/dist/ui/fleet-overlay.js +691 -0
  94. package/dist/ui/native-transcript.d.ts +33 -0
  95. package/dist/ui/native-transcript.js +230 -0
  96. package/dist/ui/schedule-menu.d.ts +16 -0
  97. package/dist/ui/schedule-menu.js +94 -0
  98. package/dist/ui/select-item.d.ts +27 -0
  99. package/dist/ui/select-item.js +34 -0
  100. package/dist/ui/tool-progress.d.ts +22 -0
  101. package/dist/ui/tool-progress.js +56 -0
  102. package/dist/ui/viewer-keys.d.ts +20 -0
  103. package/dist/ui/viewer-keys.js +17 -0
  104. package/dist/ui/workflow-card.d.ts +175 -0
  105. package/dist/ui/workflow-card.js +332 -0
  106. package/dist/ui/workflow-dialog.d.ts +305 -0
  107. package/dist/ui/workflow-dialog.js +843 -0
  108. package/dist/ui/workflow-menu.d.ts +60 -0
  109. package/dist/ui/workflow-menu.js +147 -0
  110. package/dist/usage.d.ts +135 -0
  111. package/dist/usage.js +120 -0
  112. package/dist/workflow/collisions.d.ts +95 -0
  113. package/dist/workflow/collisions.js +88 -0
  114. package/dist/workflow/entry.d.ts +32 -0
  115. package/dist/workflow/entry.js +29 -0
  116. package/dist/workflow/host.d.ts +62 -0
  117. package/dist/workflow/host.js +363 -0
  118. package/dist/workflow/journal.d.ts +97 -0
  119. package/dist/workflow/journal.js +120 -0
  120. package/dist/workflow/json-schema.d.ts +51 -0
  121. package/dist/workflow/json-schema.js +111 -0
  122. package/dist/workflow/meta.d.ts +67 -0
  123. package/dist/workflow/meta.js +317 -0
  124. package/dist/workflow/progress.d.ts +224 -0
  125. package/dist/workflow/progress.js +361 -0
  126. package/dist/workflow/runtime.d.ts +334 -0
  127. package/dist/workflow/runtime.js +830 -0
  128. package/dist/workflow/saved.d.ts +90 -0
  129. package/dist/workflow/saved.js +203 -0
  130. package/dist/workflow/task.d.ts +136 -0
  131. package/dist/workflow/task.js +207 -0
  132. package/dist/workflow/tool-description.d.ts +38 -0
  133. package/dist/workflow/tool-description.js +199 -0
  134. package/dist/workflow/worker-source.d.ts +47 -0
  135. package/dist/workflow/worker-source.js +778 -0
  136. package/dist/worktree.d.ts +52 -0
  137. package/dist/worktree.js +164 -0
  138. package/dist/xml.d.ts +10 -0
  139. package/dist/xml.js +12 -0
  140. package/docs/FORK.md +40 -0
  141. package/docs/recovery.md +62 -0
  142. package/docs/rpc.md +189 -0
  143. package/docs/workflows.md +437 -0
  144. package/examples/agent-tool-description.md +43 -0
  145. package/examples/workflows/compose.js +51 -0
  146. package/examples/workflows/fan-out-audit.js +47 -0
  147. package/examples/workflows/gated-fix.js +60 -0
  148. package/examples/workflows/lib/count-child.js +27 -0
  149. package/examples/workflows/review-panel.js +63 -0
  150. package/examples/workflows/structured-findings.js +78 -0
  151. package/package.json +75 -6
  152. package/src/abortable.ts +43 -0
  153. package/src/active-agents-prompt.ts +39 -0
  154. package/src/advisor-status.ts +74 -0
  155. package/src/agent-color.ts +161 -0
  156. package/src/agent-file-toggle.ts +273 -0
  157. package/src/agent-manager.ts +1601 -0
  158. package/src/agent-runner.ts +1372 -0
  159. package/src/agent-types.ts +345 -0
  160. package/src/child-context.ts +173 -0
  161. package/src/child-session-shutdown.ts +46 -0
  162. package/src/context.ts +58 -0
  163. package/src/cross-extension-rpc.ts +198 -0
  164. package/src/custom-agents.ts +417 -0
  165. package/src/default-agents.ts +129 -0
  166. package/src/enabled-models.ts +180 -0
  167. package/src/env.ts +33 -0
  168. package/src/error-log.ts +193 -0
  169. package/src/group-join.ts +141 -0
  170. package/src/index.ts +4218 -0
  171. package/src/invocation-config.ts +230 -0
  172. package/src/memory.ts +179 -0
  173. package/src/mention-clone.ts +221 -0
  174. package/src/mention.ts +141 -0
  175. package/src/model-resolver.ts +118 -0
  176. package/src/model-scope.ts +70 -0
  177. package/src/nested-tools.ts +422 -0
  178. package/src/output-diagnostics.ts +68 -0
  179. package/src/output-file.ts +258 -0
  180. package/src/prompts.ts +151 -0
  181. package/src/recovery.ts +320 -0
  182. package/src/schedule-store.ts +201 -0
  183. package/src/schedule.ts +386 -0
  184. package/src/settings.ts +587 -0
  185. package/src/skill-loader.ts +102 -0
  186. package/src/standalone-fallback.ts +195 -0
  187. package/src/status-note.ts +90 -0
  188. package/src/structured-output.ts +130 -0
  189. package/src/terminal-progress.ts +215 -0
  190. package/src/types.ts +394 -0
  191. package/src/ui/agent-mention.ts +216 -0
  192. package/src/ui/agent-widget.ts +732 -0
  193. package/src/ui/conversation-viewer.ts +523 -0
  194. package/src/ui/fleet-list.ts +563 -0
  195. package/src/ui/fleet-overlay.ts +847 -0
  196. package/src/ui/native-transcript.ts +220 -0
  197. package/src/ui/schedule-menu.ts +105 -0
  198. package/src/ui/select-item.ts +45 -0
  199. package/src/ui/tool-progress.ts +67 -0
  200. package/src/ui/viewer-keys.ts +39 -0
  201. package/src/ui/workflow-card.ts +470 -0
  202. package/src/ui/workflow-dialog.ts +1115 -0
  203. package/src/ui/workflow-menu.ts +193 -0
  204. package/src/usage.ts +167 -0
  205. package/src/workflow/collisions.ts +123 -0
  206. package/src/workflow/entry.ts +47 -0
  207. package/src/workflow/host.ts +404 -0
  208. package/src/workflow/journal.ts +164 -0
  209. package/src/workflow/json-schema.ts +128 -0
  210. package/src/workflow/meta.ts +325 -0
  211. package/src/workflow/progress.ts +550 -0
  212. package/src/workflow/runtime.ts +1219 -0
  213. package/src/workflow/saved.ts +217 -0
  214. package/src/workflow/task.ts +302 -0
  215. package/src/workflow/tool-description.ts +200 -0
  216. package/src/workflow/worker-source.ts +781 -0
  217. package/src/worktree.ts +205 -0
  218. package/src/xml.ts +13 -0
@@ -0,0 +1,119 @@
1
+ /**
2
+ * agent-types.ts — Unified agent type registry.
3
+ *
4
+ * Merges embedded default agents with user-defined agents from .pi/agents/*.md, .agents/agents/*.md, and global agents.
5
+ * User agents override defaults with the same name. Disabled agents are kept but excluded from spawning.
6
+ */
7
+ import type { AgentConfig } from "./types.js";
8
+ /**
9
+ * All known built-in tool names, derived from pi's own tool factories rather
10
+ * than hardcoded so the set tracks pi-mono if it adds/renames a built-in.
11
+ * `createCodingTools` → read/bash/edit/write; `createReadOnlyTools` →
12
+ * read/grep/find/ls; their de-duplicated union is the 7 built-ins
13
+ * (read, bash, edit, write, grep, find, ls). The `cwd` only binds tool
14
+ * operations we never invoke here — we read each tool's `.name` and discard it.
15
+ */
16
+ export declare const BUILTIN_TOOL_NAMES: string[];
17
+ /** Check whether default agents are disabled. */
18
+ export declare function isDefaultsDisabled(): boolean;
19
+ /** Set whether default agents are disabled. */
20
+ export declare function setDefaultsDisabled(b: boolean): void;
21
+ /** `fallbackSubagent` value that disables the fallback entirely (strict dispatch). */
22
+ export declare const NO_FALLBACK = "none";
23
+ /** Get the configured fallback agent type. undefined = strict dispatch. */
24
+ export declare function getFallbackSubagent(): string | undefined;
25
+ /** Set the configured fallback agent type. undefined = strict dispatch. */
26
+ export declare function setFallbackSubagent(v: string | undefined): void;
27
+ /**
28
+ * Build a registry map: DEFAULT_AGENTS first (unless disabled via settings),
29
+ * then user agents overlaid on top (same name overrides the default).
30
+ * Pure — callers that must not disturb the process-wide registry (nested
31
+ * delegation resolving agents from its own config root) build their own map.
32
+ */
33
+ export declare function buildAgentRegistry(userAgents: Map<string, AgentConfig>): Map<string, AgentConfig>;
34
+ /**
35
+ * Register agents into the unified registry.
36
+ * Starts with DEFAULT_AGENTS, then overlays user agents (overrides defaults with same name).
37
+ * Disabled agents (enabled === false) are kept in the registry but excluded from spawning.
38
+ */
39
+ export declare function registerAgents(userAgents: Map<string, AgentConfig>): void;
40
+ /** Resolve a type name case-insensitively in a registry. Returns the canonical key or undefined. */
41
+ export declare function resolveTypeIn(registry: Map<string, AgentConfig>, name: string): string | undefined;
42
+ /** Get the agent config for a type (case-insensitive) from a registry. */
43
+ export declare function getAgentConfigIn(registry: Map<string, AgentConfig>, name: string): AgentConfig | undefined;
44
+ /** Check if a type is valid and enabled (case-insensitive) in a registry. */
45
+ export declare function isValidTypeIn(registry: Map<string, AgentConfig>, type: string): boolean;
46
+ /** Get all enabled type names in a registry (for spawning and tool descriptions). */
47
+ export declare function getAvailableTypesIn(registry: Map<string, AgentConfig>): string[];
48
+ /**
49
+ * The canonical key for a caller-supplied name that identifies exactly one
50
+ * ENABLED agent, or undefined. Strict by construction: no fallback, no guessing
51
+ * between case-variants. Nested delegation resolves with this directly, since
52
+ * "unknown types are rejected rather than falling back" is its own contract.
53
+ */
54
+ export declare function resolveEnabledTypeIn(registry: Map<string, AgentConfig>, requested: unknown): string | undefined;
55
+ /** Outcome of resolving a caller-supplied `subagent_type` into a spawnable type. */
56
+ export type SpawnTypeResolution =
57
+ /** Spawn this type. `fellBackFrom` is set when it isn't what the caller asked for. */
58
+ {
59
+ ok: true;
60
+ type: string;
61
+ fellBackFrom?: string;
62
+ }
63
+ /** Refuse the spawn and return this message to the caller. */
64
+ | {
65
+ ok: false;
66
+ message: string;
67
+ };
68
+ /**
69
+ * Resolve a caller-supplied agent type against a registry, applying the
70
+ * `fallbackSubagent` policy. The single decision point for every caller-supplied
71
+ * spawn — the Agent tool, the scheduler, cross-extension RPC, and the nested
72
+ * tools — so a type that fails here never reaches `runAgent`, where `getConfig`
73
+ * would silently substitute general-purpose.
74
+ *
75
+ * Unknown, disabled, and case-ambiguous names are all treated the same way:
76
+ * the caller named something that doesn't identify exactly one enabled agent.
77
+ *
78
+ * Pure over `registry` — callers that need fresh agent files reload before
79
+ * calling (the Agent tool already does, per spawn). Reloading here would mean
80
+ * importing custom-agents.ts, which imports this module.
81
+ */
82
+ export declare function resolveSpawnTypeIn(registry: Map<string, AgentConfig>, requested: unknown): SpawnTypeResolution;
83
+ /** Resolve a caller-supplied agent type against the process-wide registry. */
84
+ export declare function resolveSpawnType(requested: unknown): SpawnTypeResolution;
85
+ /** Resolve a type name case-insensitively. Returns the canonical key or undefined. */
86
+ export declare function resolveType(name: string): string | undefined;
87
+ /** Get the agent config for a type (case-insensitive). */
88
+ export declare function getAgentConfig(name: string): AgentConfig | undefined;
89
+ /** Get all enabled type names (for spawning and tool descriptions). */
90
+ export declare function getAvailableTypes(): string[];
91
+ /** Get all type names including disabled (for UI listing). */
92
+ export declare function getAllTypes(): string[];
93
+ /** Get names of default agents currently in the registry. */
94
+ export declare function getDefaultAgentNames(): string[];
95
+ /** Get names of user-defined agents (non-defaults) currently in the registry. */
96
+ export declare function getUserAgentNames(): string[];
97
+ /** Check if a type is valid and enabled (case-insensitive). */
98
+ export declare function isValidType(type: string): boolean;
99
+ /**
100
+ * Get memory tool names (read/write/edit) not already in the provided set.
101
+ */
102
+ export declare function getMemoryToolNames(existingToolNames: Set<string>): string[];
103
+ /**
104
+ * Get read-only memory tool names not already in the provided set.
105
+ */
106
+ export declare function getReadOnlyMemoryToolNames(existingToolNames: Set<string>): string[];
107
+ /** Get built-in tool names for a type (case-insensitive). */
108
+ export declare function getToolNamesForType(type: string): string[];
109
+ /** Get config for a type (case-insensitive, returns a SubagentTypeConfig-compatible object). Falls back to general-purpose. */
110
+ export declare function getConfig(type: string): {
111
+ displayName: string;
112
+ color?: string;
113
+ description: string;
114
+ builtinToolNames: string[];
115
+ extensions: true | string[] | false;
116
+ excludeExtensions?: string[];
117
+ skills: true | string[] | false;
118
+ promptMode: "replace" | "append";
119
+ };
@@ -0,0 +1,286 @@
1
+ /**
2
+ * agent-types.ts — Unified agent type registry.
3
+ *
4
+ * Merges embedded default agents with user-defined agents from .pi/agents/*.md, .agents/agents/*.md, and global agents.
5
+ * User agents override defaults with the same name. Disabled agents are kept but excluded from spawning.
6
+ */
7
+ import { createCodingTools, createReadOnlyTools } from "@earendil-works/pi-coding-agent";
8
+ import { DEFAULT_AGENTS } from "./default-agents.js";
9
+ /**
10
+ * All known built-in tool names, derived from pi's own tool factories rather
11
+ * than hardcoded so the set tracks pi-mono if it adds/renames a built-in.
12
+ * `createCodingTools` → read/bash/edit/write; `createReadOnlyTools` →
13
+ * read/grep/find/ls; their de-duplicated union is the 7 built-ins
14
+ * (read, bash, edit, write, grep, find, ls). The `cwd` only binds tool
15
+ * operations we never invoke here — we read each tool's `.name` and discard it.
16
+ */
17
+ export const BUILTIN_TOOL_NAMES = [
18
+ ...new Set([...createCodingTools("."), ...createReadOnlyTools(".")].map((t) => t.name)),
19
+ ];
20
+ /** Unified runtime registry of all agents (defaults + user-defined). */
21
+ const agents = new Map();
22
+ /** When true, DEFAULT_AGENTS are skipped during registration. */
23
+ let disableDefaults = false;
24
+ /** Check whether default agents are disabled. */
25
+ export function isDefaultsDisabled() { return disableDefaults; }
26
+ /** Set whether default agents are disabled. */
27
+ export function setDefaultsDisabled(b) { disableDefaults = b; }
28
+ /** `fallbackSubagent` value that disables the fallback entirely (strict dispatch). */
29
+ export const NO_FALLBACK = "none";
30
+ /**
31
+ * Agent type substituted when a caller-supplied `subagent_type` doesn't resolve
32
+ * to exactly one enabled agent. `undefined` and `NO_FALLBACK` both fail closed;
33
+ * a named fallback must be explicitly configured. Set from
34
+ * `subagents.json` (`fallbackSubagent`).
35
+ *
36
+ * Module state rather than an index.ts closure because every caller-supplied
37
+ * spawn path needs it — the Agent tool, the scheduler, and cross-extension RPC.
38
+ */
39
+ let fallbackSubagent;
40
+ /** Get the configured fallback agent type. undefined = strict dispatch. */
41
+ export function getFallbackSubagent() { return fallbackSubagent; }
42
+ /** Set the configured fallback agent type. undefined = strict dispatch. */
43
+ export function setFallbackSubagent(v) { fallbackSubagent = v; }
44
+ /**
45
+ * Build a registry map: DEFAULT_AGENTS first (unless disabled via settings),
46
+ * then user agents overlaid on top (same name overrides the default).
47
+ * Pure — callers that must not disturb the process-wide registry (nested
48
+ * delegation resolving agents from its own config root) build their own map.
49
+ */
50
+ export function buildAgentRegistry(userAgents) {
51
+ const registry = new Map();
52
+ if (!disableDefaults) {
53
+ for (const [name, config] of DEFAULT_AGENTS)
54
+ registry.set(name, config);
55
+ }
56
+ for (const [name, config] of userAgents) {
57
+ // A user file overrides a default of the same name regardless of case:
58
+ // `explore.md` (name: explore) must replace built-in `Explore`, not sit
59
+ // beside it while `subagent_type: "Explore"` still hits the default.
60
+ const lower = name.toLowerCase();
61
+ for (const [key, existing] of registry) {
62
+ if (existing.isDefault === true && key !== name && key.toLowerCase() === lower)
63
+ registry.delete(key);
64
+ }
65
+ registry.set(name, config);
66
+ }
67
+ return registry;
68
+ }
69
+ /**
70
+ * Register agents into the unified registry.
71
+ * Starts with DEFAULT_AGENTS, then overlays user agents (overrides defaults with same name).
72
+ * Disabled agents (enabled === false) are kept in the registry but excluded from spawning.
73
+ */
74
+ export function registerAgents(userAgents) {
75
+ agents.clear();
76
+ for (const [name, config] of buildAgentRegistry(userAgents)) {
77
+ agents.set(name, config);
78
+ }
79
+ }
80
+ /** Case-insensitive key resolution within a registry. */
81
+ function resolveKeyIn(registry, name) {
82
+ if (registry.has(name))
83
+ return name;
84
+ const lower = name.toLowerCase();
85
+ for (const key of registry.keys()) {
86
+ if (key.toLowerCase() === lower)
87
+ return key;
88
+ }
89
+ return undefined;
90
+ }
91
+ /** Case-insensitive key resolution. */
92
+ function resolveKey(name) {
93
+ return resolveKeyIn(agents, name);
94
+ }
95
+ /** Resolve a type name case-insensitively in a registry. Returns the canonical key or undefined. */
96
+ export function resolveTypeIn(registry, name) {
97
+ return resolveKeyIn(registry, name);
98
+ }
99
+ /** Get the agent config for a type (case-insensitive) from a registry. */
100
+ export function getAgentConfigIn(registry, name) {
101
+ const key = resolveKeyIn(registry, name);
102
+ return key ? registry.get(key) : undefined;
103
+ }
104
+ /** Check if a type is valid and enabled (case-insensitive) in a registry. */
105
+ export function isValidTypeIn(registry, type) {
106
+ const key = resolveKeyIn(registry, type);
107
+ if (!key)
108
+ return false;
109
+ return registry.get(key)?.enabled !== false;
110
+ }
111
+ /** Get all enabled type names in a registry (for spawning and tool descriptions). */
112
+ export function getAvailableTypesIn(registry) {
113
+ return [...registry.entries()]
114
+ .filter(([_, config]) => config.enabled !== false)
115
+ .map(([name]) => name);
116
+ }
117
+ /**
118
+ * Case-insensitive resolution that refuses to guess. An exact match always wins;
119
+ * otherwise the name must match exactly one key. Two agents differing only in
120
+ * case are reachable (`loadCustomAgents` keys by filename across three
121
+ * directories), and picking whichever came first would silently dispatch a
122
+ * different agent, model and tool policy than the caller meant.
123
+ */
124
+ function resolveUnambiguousKeyIn(registry, name) {
125
+ if (registry.has(name))
126
+ return name;
127
+ const lower = name.toLowerCase();
128
+ const matches = [...registry.keys()].filter(key => key.toLowerCase() === lower);
129
+ return matches.length === 1 ? matches[0] : undefined;
130
+ }
131
+ /**
132
+ * The canonical key for a caller-supplied name that identifies exactly one
133
+ * ENABLED agent, or undefined. Strict by construction: no fallback, no guessing
134
+ * between case-variants. Nested delegation resolves with this directly, since
135
+ * "unknown types are rejected rather than falling back" is its own contract.
136
+ */
137
+ export function resolveEnabledTypeIn(registry, requested) {
138
+ const raw = typeof requested === "string" ? requested.trim() : "";
139
+ if (!raw)
140
+ return undefined;
141
+ const key = resolveUnambiguousKeyIn(registry, raw);
142
+ return key !== undefined && registry.get(key)?.enabled !== false ? key : undefined;
143
+ }
144
+ /**
145
+ * Resolve a caller-supplied agent type against a registry, applying the
146
+ * `fallbackSubagent` policy. The single decision point for every caller-supplied
147
+ * spawn — the Agent tool, the scheduler, cross-extension RPC, and the nested
148
+ * tools — so a type that fails here never reaches `runAgent`, where `getConfig`
149
+ * would silently substitute general-purpose.
150
+ *
151
+ * Unknown, disabled, and case-ambiguous names are all treated the same way:
152
+ * the caller named something that doesn't identify exactly one enabled agent.
153
+ *
154
+ * Pure over `registry` — callers that need fresh agent files reload before
155
+ * calling (the Agent tool already does, per spawn). Reloading here would mean
156
+ * importing custom-agents.ts, which imports this module.
157
+ */
158
+ export function resolveSpawnTypeIn(registry, requested) {
159
+ const raw = typeof requested === "string" ? requested.trim() : "";
160
+ const available = () => getAvailableTypesIn(registry).join(", ") || "(none)";
161
+ const key = resolveEnabledTypeIn(registry, raw);
162
+ if (key !== undefined)
163
+ return { ok: true, type: key };
164
+ const ambiguous = raw && !registry.has(raw)
165
+ && [...registry.keys()].filter(name => name.toLowerCase() === raw.toLowerCase()).length > 1;
166
+ const reason = !raw ? "No agent type given."
167
+ : ambiguous ? `Ambiguous agent type: "${raw}". Use an exact name.`
168
+ : `Unknown or disabled agent type: "${raw}".`;
169
+ // Trimmed like `requested`: a padded value set programmatically would
170
+ // otherwise be reported as a missing agent.
171
+ const configured = typeof fallbackSubagent === "string" ? fallbackSubagent.trim() : undefined;
172
+ if (configured === undefined || configured.toLowerCase() === NO_FALLBACK) {
173
+ return { ok: false, message: `${reason} Choose an enabled subagent_type. Available: ${available()}.` };
174
+ }
175
+ // An unusable explicit fallback is a configuration error, not permission to guess.
176
+ const fallbackKey = resolveUnambiguousKeyIn(registry, configured);
177
+ if (fallbackKey === undefined || registry.get(fallbackKey)?.enabled === false) {
178
+ return {
179
+ ok: false,
180
+ message: `${reason} The configured fallbackSubagent "${configured}" is itself ` +
181
+ `unknown, disabled or ambiguous. Available: ${available()}.`,
182
+ };
183
+ }
184
+ return { ok: true, type: fallbackKey, fellBackFrom: raw };
185
+ }
186
+ /** Resolve a caller-supplied agent type against the process-wide registry. */
187
+ export function resolveSpawnType(requested) {
188
+ return resolveSpawnTypeIn(agents, requested);
189
+ }
190
+ /** Resolve a type name case-insensitively. Returns the canonical key or undefined. */
191
+ export function resolveType(name) {
192
+ return resolveKey(name);
193
+ }
194
+ /** Get the agent config for a type (case-insensitive). */
195
+ export function getAgentConfig(name) {
196
+ return getAgentConfigIn(agents, name);
197
+ }
198
+ /** Get all enabled type names (for spawning and tool descriptions). */
199
+ export function getAvailableTypes() {
200
+ return getAvailableTypesIn(agents);
201
+ }
202
+ /** Get all type names including disabled (for UI listing). */
203
+ export function getAllTypes() {
204
+ return [...agents.keys()];
205
+ }
206
+ /** Get names of default agents currently in the registry. */
207
+ export function getDefaultAgentNames() {
208
+ return [...agents.entries()]
209
+ .filter(([_, config]) => config.isDefault === true)
210
+ .map(([name]) => name);
211
+ }
212
+ /** Get names of user-defined agents (non-defaults) currently in the registry. */
213
+ export function getUserAgentNames() {
214
+ return [...agents.entries()]
215
+ .filter(([_, config]) => config.isDefault !== true)
216
+ .map(([name]) => name);
217
+ }
218
+ /** Check if a type is valid and enabled (case-insensitive). */
219
+ export function isValidType(type) {
220
+ return isValidTypeIn(agents, type);
221
+ }
222
+ /** Tool names required for memory management. */
223
+ const MEMORY_TOOL_NAMES = ["read", "write", "edit"];
224
+ /**
225
+ * Get memory tool names (read/write/edit) not already in the provided set.
226
+ */
227
+ export function getMemoryToolNames(existingToolNames) {
228
+ return MEMORY_TOOL_NAMES.filter(n => !existingToolNames.has(n));
229
+ }
230
+ /** Tool names needed for read-only memory access. */
231
+ const READONLY_MEMORY_TOOL_NAMES = ["read"];
232
+ /**
233
+ * Get read-only memory tool names not already in the provided set.
234
+ */
235
+ export function getReadOnlyMemoryToolNames(existingToolNames) {
236
+ return READONLY_MEMORY_TOOL_NAMES.filter(n => !existingToolNames.has(n));
237
+ }
238
+ /** Get built-in tool names for a type (case-insensitive). */
239
+ export function getToolNamesForType(type) {
240
+ const key = resolveKey(type);
241
+ const raw = key ? agents.get(key) : undefined;
242
+ const config = raw?.enabled !== false ? raw : undefined;
243
+ // `undefined` (definition omitted the field) → all built-ins; an explicit `[]`
244
+ // (`tools: none` or a `tools:` with only `ext:` entries) → zero built-ins.
245
+ return config?.builtinToolNames ?? [...BUILTIN_TOOL_NAMES];
246
+ }
247
+ /** Get config for a type (case-insensitive, returns a SubagentTypeConfig-compatible object). Falls back to general-purpose. */
248
+ export function getConfig(type) {
249
+ const key = resolveKey(type);
250
+ const config = key ? agents.get(key) : undefined;
251
+ if (config && config.enabled !== false) {
252
+ return {
253
+ displayName: config.displayName ?? config.name,
254
+ color: config.color,
255
+ description: config.description,
256
+ builtinToolNames: config.builtinToolNames ?? BUILTIN_TOOL_NAMES,
257
+ extensions: config.extensions,
258
+ excludeExtensions: config.excludeExtensions,
259
+ skills: config.skills,
260
+ promptMode: config.promptMode,
261
+ };
262
+ }
263
+ // Fallback for unknown/disabled types — general-purpose config
264
+ const gp = agents.get("general-purpose");
265
+ if (gp && gp.enabled !== false) {
266
+ return {
267
+ displayName: gp.displayName ?? gp.name,
268
+ color: gp.color,
269
+ description: gp.description,
270
+ builtinToolNames: gp.builtinToolNames ?? BUILTIN_TOOL_NAMES,
271
+ extensions: gp.extensions,
272
+ excludeExtensions: gp.excludeExtensions,
273
+ skills: gp.skills,
274
+ promptMode: gp.promptMode,
275
+ };
276
+ }
277
+ // Absolute fallback (should never happen)
278
+ return {
279
+ displayName: "Agent",
280
+ description: "General-purpose agent for complex, multi-step tasks",
281
+ builtinToolNames: BUILTIN_TOOL_NAMES,
282
+ extensions: true,
283
+ skills: true,
284
+ promptMode: "append",
285
+ };
286
+ }
@@ -0,0 +1,15 @@
1
+ export declare function inChildSessionContext(): boolean;
2
+ export declare function runInChildSessionContext<T>(fn: () => Promise<T>): Promise<T>;
3
+ /**
4
+ * Run `fn` with `process.env.PI_SUBAGENT_CHILD === "1"`, the way a genuinely
5
+ * forked child process would inherit it. Restores the previous state when the
6
+ * outermost overlapping region exits: the variable is deleted again when it
7
+ * was unset, otherwise its prior value is put back.
8
+ */
9
+ export declare function runAsSubagentProcess<T>(fn: () => Promise<T>): Promise<T>;
10
+ /**
11
+ * Bind with pi-advisor's explicit child override, held exclusively only while
12
+ * fn runs. Queued binds may abort or time out without poisoning the gate.
13
+ * An operator's concurrent subagent toggle outlives our temporary "1".
14
+ */
15
+ export declare function runWithAdvisorBind<T>(override: boolean | undefined, fn: () => Promise<T>, signal?: AbortSignal): Promise<T>;
@@ -0,0 +1,181 @@
1
+ import { AsyncLocalStorage } from "node:async_hooks";
2
+ /**
3
+ * Marks resource loading/session construction performed for a subagent. This is
4
+ * async-context-local so concurrent top-level extension work is unaffected.
5
+ */
6
+ const childSessionContext = new AsyncLocalStorage();
7
+ export function inChildSessionContext() {
8
+ return childSessionContext.getStore() === true;
9
+ }
10
+ export function runInChildSessionContext(fn) {
11
+ return childSessionContext.run(true, fn);
12
+ }
13
+ // The env half of the child marker. The ALS half above is how OUR OWN code
14
+ // knows it is inside child construction; other extensions never see it — they
15
+ // read `process.env.PI_SUBAGENT_CHILD`, the marker the spawner side of the
16
+ // pi-advisor contract is responsible for raising (pi core never sets it).
17
+ // pi-advisor consults it when deciding a session's default enabled state,
18
+ // which happens inside its `session_start` handler — i.e. while a child
19
+ // session's `bindExtensions` runs.
20
+ //
21
+ // Depth-refcounted because the env var is process-global while child
22
+ // spawns are not serial: two overlapping constructions must hold "1" until the
23
+ // LAST one exits, or the early finisher would expose the sibling still
24
+ // binding extensions as a main session.
25
+ let subagentProcessGuardDepth = 0;
26
+ let subagentProcessHadMarker = false;
27
+ let subagentProcessPriorMarker;
28
+ /**
29
+ * Run `fn` with `process.env.PI_SUBAGENT_CHILD === "1"`, the way a genuinely
30
+ * forked child process would inherit it. Restores the previous state when the
31
+ * outermost overlapping region exits: the variable is deleted again when it
32
+ * was unset, otherwise its prior value is put back.
33
+ */
34
+ export async function runAsSubagentProcess(fn) {
35
+ if (subagentProcessGuardDepth === 0) {
36
+ subagentProcessHadMarker = "PI_SUBAGENT_CHILD" in process.env;
37
+ subagentProcessPriorMarker = process.env.PI_SUBAGENT_CHILD;
38
+ }
39
+ subagentProcessGuardDepth++;
40
+ process.env.PI_SUBAGENT_CHILD = "1";
41
+ try {
42
+ return await fn();
43
+ }
44
+ finally {
45
+ subagentProcessGuardDepth--;
46
+ if (subagentProcessGuardDepth === 0) {
47
+ if (subagentProcessHadMarker && subagentProcessPriorMarker !== undefined) {
48
+ process.env.PI_SUBAGENT_CHILD = subagentProcessPriorMarker;
49
+ }
50
+ else {
51
+ delete process.env.PI_SUBAGENT_CHILD;
52
+ }
53
+ }
54
+ }
55
+ }
56
+ // The OTHER marker pi-advisor consults: `PI_ADVISOR_SUBAGENTS` is its
57
+ // per-process override for the subagent default, read by
58
+ // `configDefaultEnabled`. Verified against pi-advisor's index.ts: that
59
+ // function has a single call site inside `startOrchestrator`, which fires at
60
+ // `session_start` inside a child's `bindExtensions`; every later rebuild path
61
+ // (config saves, `/advisor main on|off`, severity edits) sits behind a UI
62
+ // command a headless child can never trigger, and `/advisor on` forces
63
+ // enablement without re-reading the env. So the value only has to be right
64
+ // for the bind itself, not for the session's lifetime.
65
+ //
66
+ // The env var is process-global while children spawn concurrently in one pi
67
+ // process, so SOME mutual exclusion is unavoidable: a sibling binding while an
68
+ // `advisor: true` child holds "1" would inherit that child's enablement. But
69
+ // only an override bind needs exclusivity — the gate below is a reader/writer
70
+ // lock, NOT a serial queue. `advisor: true` binds are writers (mutually
71
+ // exclusive with everything); deferred and `advisor: false` binds are readers
72
+ // that never touch the env and run CONCURRENTLY with each other, so a slow or
73
+ // hanging `session_start` — pi-mcp connects MCP servers from there — blocks
74
+ // only while an advisor override bind is actually in flight. A queued writer
75
+ // cannot hold every later spawn forever behind a hung reader: waits have an
76
+ // abort signal and a deadline. FIFO hand-off still prevents writer starvation.
77
+ const ADVISOR_BIND_WAIT_MS = 30_000;
78
+ let advisorWriterActive = false;
79
+ let advisorReaderCount = 0;
80
+ const advisorGateWaiters = [];
81
+ function cancelledBindError() {
82
+ const error = new Error("Advisor bind cancelled");
83
+ error.name = "AbortError";
84
+ return error;
85
+ }
86
+ function advisorGateDrain() {
87
+ // Admit consecutive readers, or one writer only after all readers finish.
88
+ while (advisorGateWaiters.length > 0 && !advisorWriterActive) {
89
+ const next = advisorGateWaiters[0];
90
+ if (next.exclusive && advisorReaderCount > 0)
91
+ break;
92
+ advisorGateWaiters.shift();
93
+ next.resume();
94
+ }
95
+ }
96
+ function advisorGateAcquire(exclusive, signal) {
97
+ if (signal?.aborted)
98
+ return Promise.reject(cancelledBindError());
99
+ if (!advisorWriterActive && advisorGateWaiters.length === 0 && (!exclusive || advisorReaderCount === 0)) {
100
+ if (exclusive)
101
+ advisorWriterActive = true;
102
+ else
103
+ advisorReaderCount++;
104
+ return Promise.resolve();
105
+ }
106
+ return new Promise((resolve, reject) => {
107
+ let timer;
108
+ const cleanup = () => {
109
+ if (timer !== undefined)
110
+ clearTimeout(timer);
111
+ signal?.removeEventListener("abort", onAbort);
112
+ };
113
+ const rejectWaiting = (error) => {
114
+ const index = advisorGateWaiters.indexOf(waiter);
115
+ if (index < 0)
116
+ return;
117
+ advisorGateWaiters.splice(index, 1);
118
+ cleanup();
119
+ advisorGateDrain();
120
+ reject(error);
121
+ };
122
+ const onAbort = () => rejectWaiting(cancelledBindError());
123
+ const waiter = {
124
+ exclusive,
125
+ resume: () => {
126
+ cleanup();
127
+ if (exclusive)
128
+ advisorWriterActive = true;
129
+ else
130
+ advisorReaderCount++;
131
+ resolve();
132
+ },
133
+ };
134
+ advisorGateWaiters.push(waiter);
135
+ signal?.addEventListener("abort", onAbort, { once: true });
136
+ timer = setTimeout(() => rejectWaiting(new Error(`Advisor bind wait timed out after ${ADVISOR_BIND_WAIT_MS}ms`)), ADVISOR_BIND_WAIT_MS);
137
+ if (signal?.aborted)
138
+ onAbort();
139
+ });
140
+ }
141
+ function advisorGateRelease(exclusive) {
142
+ if (exclusive)
143
+ advisorWriterActive = false;
144
+ else
145
+ advisorReaderCount--;
146
+ advisorGateDrain();
147
+ }
148
+ /**
149
+ * Bind with pi-advisor's explicit child override, held exclusively only while
150
+ * fn runs. Queued binds may abort or time out without poisoning the gate.
151
+ * An operator's concurrent subagent toggle outlives our temporary "1".
152
+ */
153
+ export function runWithAdvisorBind(override, fn, signal) {
154
+ const exclusive = override === true;
155
+ return (async () => {
156
+ await advisorGateAcquire(exclusive, signal);
157
+ try {
158
+ if (signal?.aborted)
159
+ throw cancelledBindError();
160
+ if (!exclusive)
161
+ return await fn();
162
+ const hadEnv = "PI_ADVISOR_SUBAGENTS" in process.env;
163
+ const priorEnv = process.env.PI_ADVISOR_SUBAGENTS;
164
+ process.env.PI_ADVISOR_SUBAGENTS = "1";
165
+ try {
166
+ return await fn();
167
+ }
168
+ finally {
169
+ if (process.env.PI_ADVISOR_SUBAGENTS === "1") {
170
+ if (hadEnv && priorEnv !== undefined)
171
+ process.env.PI_ADVISOR_SUBAGENTS = priorEnv;
172
+ else
173
+ delete process.env.PI_ADVISOR_SUBAGENTS;
174
+ }
175
+ }
176
+ }
177
+ finally {
178
+ advisorGateRelease(exclusive);
179
+ }
180
+ })();
181
+ }
@@ -0,0 +1,3 @@
1
+ import type { AgentSession } from "@earendil-works/pi-coding-agent";
2
+ /** Close the extension lifecycle opened by bindExtensions before invalidating the session. */
3
+ export declare function shutdownChildSession(session: AgentSession | undefined): Promise<void>;
@@ -0,0 +1,48 @@
1
+ import { releaseAdvisorStatus } from "./advisor-status.js";
2
+ import { disposeChildRecovery } from "./recovery.js";
3
+ import { releaseToolProgress } from "./ui/tool-progress.js";
4
+ const CHILD_SHUTDOWN_TIMEOUT_MS = 3_000;
5
+ const childShutdowns = new WeakMap();
6
+ /** Close the extension lifecycle opened by bindExtensions before invalidating the session. */
7
+ export function shutdownChildSession(session) {
8
+ if (!session)
9
+ return Promise.resolve();
10
+ const pending = childShutdowns.get(session);
11
+ if (pending)
12
+ return pending;
13
+ const shutdown = closeChildSession(session);
14
+ childShutdowns.set(session, shutdown);
15
+ return shutdown;
16
+ }
17
+ async function closeChildSession(session) {
18
+ disposeChildRecovery(session);
19
+ releaseToolProgress(session);
20
+ let timeout;
21
+ try {
22
+ const runner = session.extensionRunner;
23
+ if (runner?.hasHandlers?.("session_shutdown")) {
24
+ await Promise.race([
25
+ runner.emit({ type: "session_shutdown", reason: "quit" }),
26
+ new Promise(resolve => {
27
+ timeout = setTimeout(resolve, CHILD_SHUTDOWN_TIMEOUT_MS);
28
+ timeout.unref?.();
29
+ }),
30
+ ]);
31
+ }
32
+ }
33
+ catch {
34
+ // A partially bound extension must not prevent child teardown.
35
+ console.error("pi-subagents: child shutdown handler failed");
36
+ }
37
+ finally {
38
+ releaseAdvisorStatus(session);
39
+ if (timeout !== undefined)
40
+ clearTimeout(timeout);
41
+ try {
42
+ session.dispose?.();
43
+ }
44
+ catch {
45
+ console.error("pi-subagents: child session disposal failed");
46
+ }
47
+ }
48
+ }
@@ -0,0 +1,12 @@
1
+ /**
2
+ * context.ts — Extract parent conversation context for subagent inheritance.
3
+ */
4
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
5
+ /** Extract text from a message content block array. */
6
+ export declare function extractText(content: unknown[]): string;
7
+ /**
8
+ * Build a text representation of the parent conversation context.
9
+ * Used when inherit_context is true to give the subagent visibility
10
+ * into what has been discussed/done so far.
11
+ */
12
+ export declare function buildParentContext(ctx: ExtensionContext): string;