@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,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 = general-purpose. */
24
+ export declare function getFallbackSubagent(): string | undefined;
25
+ /** Set the configured fallback agent type. undefined = general-purpose. */
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` keeps the historical behavior
33
+ * (general-purpose); `NO_FALLBACK` makes dispatch fail closed. 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 = general-purpose. */
41
+ export function getFallbackSubagent() { return fallbackSubagent; }
42
+ /** Set the configured fallback agent type. undefined = general-purpose. */
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
+ registry.set(name, config);
58
+ return registry;
59
+ }
60
+ /**
61
+ * Register agents into the unified registry.
62
+ * Starts with DEFAULT_AGENTS, then overlays user agents (overrides defaults with same name).
63
+ * Disabled agents (enabled === false) are kept in the registry but excluded from spawning.
64
+ */
65
+ export function registerAgents(userAgents) {
66
+ agents.clear();
67
+ for (const [name, config] of buildAgentRegistry(userAgents)) {
68
+ agents.set(name, config);
69
+ }
70
+ }
71
+ /** Case-insensitive key resolution within a registry. */
72
+ function resolveKeyIn(registry, name) {
73
+ if (registry.has(name))
74
+ return name;
75
+ const lower = name.toLowerCase();
76
+ for (const key of registry.keys()) {
77
+ if (key.toLowerCase() === lower)
78
+ return key;
79
+ }
80
+ return undefined;
81
+ }
82
+ /** Case-insensitive key resolution. */
83
+ function resolveKey(name) {
84
+ return resolveKeyIn(agents, name);
85
+ }
86
+ /** Resolve a type name case-insensitively in a registry. Returns the canonical key or undefined. */
87
+ export function resolveTypeIn(registry, name) {
88
+ return resolveKeyIn(registry, name);
89
+ }
90
+ /** Get the agent config for a type (case-insensitive) from a registry. */
91
+ export function getAgentConfigIn(registry, name) {
92
+ const key = resolveKeyIn(registry, name);
93
+ return key ? registry.get(key) : undefined;
94
+ }
95
+ /** Check if a type is valid and enabled (case-insensitive) in a registry. */
96
+ export function isValidTypeIn(registry, type) {
97
+ const key = resolveKeyIn(registry, type);
98
+ if (!key)
99
+ return false;
100
+ return registry.get(key)?.enabled !== false;
101
+ }
102
+ /** Get all enabled type names in a registry (for spawning and tool descriptions). */
103
+ export function getAvailableTypesIn(registry) {
104
+ return [...registry.entries()]
105
+ .filter(([_, config]) => config.enabled !== false)
106
+ .map(([name]) => name);
107
+ }
108
+ /**
109
+ * Case-insensitive resolution that refuses to guess. An exact match always wins;
110
+ * otherwise the name must match exactly one key. Two agents differing only in
111
+ * case are reachable (`loadCustomAgents` keys by filename across three
112
+ * directories), and picking whichever came first would silently dispatch a
113
+ * different agent, model and tool policy than the caller meant.
114
+ */
115
+ function resolveUnambiguousKeyIn(registry, name) {
116
+ if (registry.has(name))
117
+ return name;
118
+ const lower = name.toLowerCase();
119
+ const matches = [...registry.keys()].filter(key => key.toLowerCase() === lower);
120
+ return matches.length === 1 ? matches[0] : undefined;
121
+ }
122
+ /**
123
+ * The canonical key for a caller-supplied name that identifies exactly one
124
+ * ENABLED agent, or undefined. Strict by construction: no fallback, no guessing
125
+ * between case-variants. Nested delegation resolves with this directly, since
126
+ * "unknown types are rejected rather than falling back" is its own contract.
127
+ */
128
+ export function resolveEnabledTypeIn(registry, requested) {
129
+ const raw = typeof requested === "string" ? requested.trim() : "";
130
+ if (!raw)
131
+ return undefined;
132
+ const key = resolveUnambiguousKeyIn(registry, raw);
133
+ return key !== undefined && registry.get(key)?.enabled !== false ? key : undefined;
134
+ }
135
+ /**
136
+ * Resolve a caller-supplied agent type against a registry, applying the
137
+ * `fallbackSubagent` policy. The single decision point for every caller-supplied
138
+ * spawn — the Agent tool, the scheduler, cross-extension RPC, and the nested
139
+ * tools — so a type that fails here never reaches `runAgent`, where `getConfig`
140
+ * would silently substitute general-purpose.
141
+ *
142
+ * Unknown, disabled, and case-ambiguous names are all treated the same way:
143
+ * the caller named something that doesn't identify exactly one enabled agent.
144
+ *
145
+ * Pure over `registry` — callers that need fresh agent files reload before
146
+ * calling (the Agent tool already does, per spawn). Reloading here would mean
147
+ * importing custom-agents.ts, which imports this module.
148
+ */
149
+ export function resolveSpawnTypeIn(registry, requested) {
150
+ const raw = typeof requested === "string" ? requested.trim() : "";
151
+ const available = () => getAvailableTypesIn(registry).join(", ") || "(none)";
152
+ const key = resolveEnabledTypeIn(registry, raw);
153
+ if (key !== undefined)
154
+ return { ok: true, type: key };
155
+ // A missing type follows the same policy as a wrong one rather than always
156
+ // erroring: before this setting existed an empty type fell back like any
157
+ // other unresolvable name, and only opting in should change that.
158
+ const reason = raw ? `Unknown or disabled agent type: "${raw}".` : "No agent type given.";
159
+ // Trimmed like `requested`: a padded value set programmatically would
160
+ // otherwise be reported as a missing agent.
161
+ const configured = typeof fallbackSubagent === "string" ? fallbackSubagent.trim() : undefined;
162
+ if (configured !== undefined && configured.toLowerCase() === NO_FALLBACK) {
163
+ return { ok: false, message: `${reason} Available: ${available()}.` };
164
+ }
165
+ if (configured !== undefined) {
166
+ // An explicitly configured fallback that is itself unusable is a
167
+ // misconfiguration, not a second chance to guess — say so rather than
168
+ // quietly dropping to general-purpose.
169
+ const fallbackKey = resolveUnambiguousKeyIn(registry, configured);
170
+ if (fallbackKey === undefined || registry.get(fallbackKey)?.enabled === false) {
171
+ return {
172
+ ok: false,
173
+ message: `${reason} The configured fallbackSubagent "${configured}" is itself ` +
174
+ `unknown or disabled. Available: ${available()}.`,
175
+ };
176
+ }
177
+ return { ok: true, type: fallbackKey, fellBackFrom: raw };
178
+ }
179
+ // Unset: historical behavior, deliberately unchanged. #183 asks for the
180
+ // fallback to remain the default, so the pre-existing hole it leaves — an
181
+ // unregistered general-purpose resolving to `getConfig`'s all-tools hardcoded
182
+ // tier — is what `fallbackSubagent: none` is for, not something to close
183
+ // under everyone silently.
184
+ return { ok: true, type: "general-purpose", 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,2 @@
1
+ export declare function inChildSessionContext(): boolean;
2
+ export declare function runInChildSessionContext<T>(fn: () => Promise<T>): Promise<T>;
@@ -0,0 +1,12 @@
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
+ }
@@ -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;
@@ -0,0 +1,56 @@
1
+ /**
2
+ * context.ts — Extract parent conversation context for subagent inheritance.
3
+ */
4
+ /** Extract text from a message content block array. */
5
+ export function extractText(content) {
6
+ return content
7
+ .filter((c) => c.type === "text")
8
+ .map((c) => c.text ?? "")
9
+ .join("\n");
10
+ }
11
+ /**
12
+ * Build a text representation of the parent conversation context.
13
+ * Used when inherit_context is true to give the subagent visibility
14
+ * into what has been discussed/done so far.
15
+ */
16
+ export function buildParentContext(ctx) {
17
+ const entries = ctx.sessionManager.getBranch();
18
+ if (!entries || entries.length === 0)
19
+ return "";
20
+ const parts = [];
21
+ for (const entry of entries) {
22
+ if (entry.type === "message") {
23
+ const msg = entry.message;
24
+ if (msg.role === "user") {
25
+ const text = typeof msg.content === "string"
26
+ ? msg.content
27
+ : extractText(msg.content);
28
+ if (text.trim())
29
+ parts.push(`[User]: ${text.trim()}`);
30
+ }
31
+ else if (msg.role === "assistant") {
32
+ const text = extractText(msg.content);
33
+ if (text.trim())
34
+ parts.push(`[Assistant]: ${text.trim()}`);
35
+ }
36
+ // Skip toolResult messages — too verbose for context
37
+ }
38
+ else if (entry.type === "compaction") {
39
+ // Include compaction summaries — they're already condensed
40
+ if (entry.summary) {
41
+ parts.push(`[Summary]: ${entry.summary}`);
42
+ }
43
+ }
44
+ }
45
+ if (parts.length === 0)
46
+ return "";
47
+ return `# Parent Conversation Context
48
+ The following is the conversation history from the parent session that spawned you.
49
+ Use this context to understand what has been discussed and decided so far.
50
+
51
+ ${parts.join("\n\n")}
52
+
53
+ ---
54
+ # Your Task (below)
55
+ `;
56
+ }
@@ -0,0 +1,66 @@
1
+ /**
2
+ * Cross-extension RPC handlers for the subagents extension.
3
+ *
4
+ * Exposes ping, spawn, stop, and consume RPCs over the pi.events event bus,
5
+ * using per-request scoped reply channels.
6
+ *
7
+ * Reply envelope follows pi-mono convention:
8
+ * success → { success: true, data?: T }
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.
14
+ */
15
+ import type { AgentRecord } from "./types.js";
16
+ /** Minimal event bus interface needed by the RPC handlers. */
17
+ export interface EventBus {
18
+ on(event: string, handler: (data: unknown) => void): () => void;
19
+ emit(event: string, data: unknown): void;
20
+ }
21
+ /** RPC reply envelope — matches pi-mono's RpcResponse shape. */
22
+ export type RpcReply<T = void> = {
23
+ success: true;
24
+ data?: T;
25
+ } | {
26
+ success: false;
27
+ error: string;
28
+ };
29
+ /** RPC protocol version — bumped when the envelope or method contracts change. */
30
+ export declare const PROTOCOL_VERSION = 2;
31
+ /** Minimal AgentManager interface needed by the spawn/stop/consume RPCs. */
32
+ export interface SpawnCapable {
33
+ spawn(pi: unknown, ctx: unknown, type: string, prompt: string, options: any): string;
34
+ /** Resolves once the spawned agent is running; rejects on a startup failure. */
35
+ awaitStartup(id: string): Promise<void>;
36
+ abort(id: string): boolean;
37
+ /**
38
+ * The record behind an id, for the stop handler's ownership check. Narrowed
39
+ * to the two fields `isTopLevelAgent` reads, so the RPC layer keeps its
40
+ * deliberately shallow view of the manager.
41
+ */
42
+ getRecord(id: string): Pick<AgentRecord, "parentAgentId" | "workflowId"> | undefined;
43
+ /**
44
+ * Mark a settled agent's result as read by the caller, suppressing the
45
+ * completion notification — what `get_subagent_result` does when it returns
46
+ * one. False when there is no such agent, or it has not settled yet.
47
+ */
48
+ consumeResult(id: string): boolean;
49
+ }
50
+ export interface RpcDeps {
51
+ events: EventBus;
52
+ pi: unknown;
53
+ getCtx: () => unknown | undefined;
54
+ manager: SpawnCapable;
55
+ }
56
+ export interface RpcHandle {
57
+ unsubPing: () => void;
58
+ unsubSpawn: () => void;
59
+ unsubStop: () => void;
60
+ unsubConsume: () => void;
61
+ }
62
+ /**
63
+ * Register ping, spawn, stop, and consume RPC handlers on the event bus.
64
+ * Returns unsub functions for cleanup.
65
+ */
66
+ export declare function registerRpcHandlers(deps: RpcDeps): RpcHandle;