@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.
- package/CHANGELOG.md +808 -0
- package/CONTRIBUTING.md +72 -0
- package/LICENSE +21 -0
- package/README.md +1034 -0
- package/SECURITY.md +95 -0
- package/dist/abortable.d.ts +12 -0
- package/dist/abortable.js +42 -0
- package/dist/agent-color.d.ts +35 -0
- package/dist/agent-color.js +123 -0
- package/dist/agent-file-toggle.d.ts +125 -0
- package/dist/agent-file-toggle.js +260 -0
- package/dist/agent-manager.d.ts +472 -0
- package/dist/agent-manager.js +1338 -0
- package/dist/agent-runner.d.ts +312 -0
- package/dist/agent-runner.js +1034 -0
- package/dist/agent-types.d.ts +119 -0
- package/dist/agent-types.js +286 -0
- package/dist/child-context.d.ts +2 -0
- package/dist/child-context.js +12 -0
- package/dist/context.d.ts +12 -0
- package/dist/context.js +56 -0
- package/dist/cross-extension-rpc.d.ts +66 -0
- package/dist/cross-extension-rpc.js +138 -0
- package/dist/custom-agents.d.ts +54 -0
- package/dist/custom-agents.js +316 -0
- package/dist/default-agents.d.ts +7 -0
- package/dist/default-agents.js +122 -0
- package/dist/enabled-models.d.ts +49 -0
- package/dist/enabled-models.js +145 -0
- package/dist/env.d.ts +6 -0
- package/dist/env.js +28 -0
- package/dist/group-join.d.ts +32 -0
- package/dist/group-join.js +116 -0
- package/dist/index.d.ts +50 -0
- package/dist/index.js +3682 -0
- package/dist/invocation-config.d.ts +107 -0
- package/dist/invocation-config.js +83 -0
- package/dist/memory.d.ts +53 -0
- package/dist/memory.js +165 -0
- package/dist/mention-clone.d.ts +87 -0
- package/dist/mention-clone.js +153 -0
- package/dist/mention.d.ts +81 -0
- package/dist/mention.js +131 -0
- package/dist/model-resolver.d.ts +36 -0
- package/dist/model-resolver.js +95 -0
- package/dist/model-scope.d.ts +49 -0
- package/dist/model-scope.js +48 -0
- package/dist/nested-tools.d.ts +55 -0
- package/dist/nested-tools.js +299 -0
- package/dist/output-file.d.ts +43 -0
- package/dist/output-file.js +142 -0
- package/dist/prompts.d.ts +55 -0
- package/dist/prompts.js +91 -0
- package/dist/schedule-store.d.ts +38 -0
- package/dist/schedule-store.js +155 -0
- package/dist/schedule.d.ts +109 -0
- package/dist/schedule.js +359 -0
- package/dist/settings.d.ts +360 -0
- package/dist/settings.js +251 -0
- package/dist/skill-loader.d.ts +24 -0
- package/dist/skill-loader.js +93 -0
- package/dist/status-note.d.ts +61 -0
- package/dist/status-note.js +85 -0
- package/dist/structured-output.d.ts +61 -0
- package/dist/structured-output.js +112 -0
- package/dist/types.d.ts +371 -0
- package/dist/types.js +5 -0
- package/dist/ui/agent-mention.d.ts +82 -0
- package/dist/ui/agent-mention.js +187 -0
- package/dist/ui/agent-widget.d.ts +219 -0
- package/dist/ui/agent-widget.js +592 -0
- package/dist/ui/conversation-viewer.d.ts +120 -0
- package/dist/ui/conversation-viewer.js +578 -0
- package/dist/ui/fleet-list.d.ts +195 -0
- package/dist/ui/fleet-list.js +471 -0
- package/dist/ui/schedule-menu.d.ts +16 -0
- package/dist/ui/schedule-menu.js +94 -0
- package/dist/ui/select-item.d.ts +27 -0
- package/dist/ui/select-item.js +34 -0
- package/dist/ui/viewer-keys.d.ts +20 -0
- package/dist/ui/viewer-keys.js +17 -0
- package/dist/ui/workflow-card.d.ts +175 -0
- package/dist/ui/workflow-card.js +332 -0
- package/dist/ui/workflow-dialog.d.ts +305 -0
- package/dist/ui/workflow-dialog.js +843 -0
- package/dist/ui/workflow-menu.d.ts +60 -0
- package/dist/ui/workflow-menu.js +147 -0
- package/dist/usage.d.ts +135 -0
- package/dist/usage.js +120 -0
- package/dist/workflow/collisions.d.ts +95 -0
- package/dist/workflow/collisions.js +88 -0
- package/dist/workflow/entry.d.ts +32 -0
- package/dist/workflow/entry.js +29 -0
- package/dist/workflow/host.d.ts +62 -0
- package/dist/workflow/host.js +362 -0
- package/dist/workflow/journal.d.ts +97 -0
- package/dist/workflow/journal.js +120 -0
- package/dist/workflow/json-schema.d.ts +51 -0
- package/dist/workflow/json-schema.js +111 -0
- package/dist/workflow/meta.d.ts +67 -0
- package/dist/workflow/meta.js +317 -0
- package/dist/workflow/progress.d.ts +224 -0
- package/dist/workflow/progress.js +361 -0
- package/dist/workflow/runtime.d.ts +334 -0
- package/dist/workflow/runtime.js +830 -0
- package/dist/workflow/saved.d.ts +90 -0
- package/dist/workflow/saved.js +203 -0
- package/dist/workflow/task.d.ts +136 -0
- package/dist/workflow/task.js +207 -0
- package/dist/workflow/tool-description.d.ts +38 -0
- package/dist/workflow/tool-description.js +199 -0
- package/dist/workflow/worker-source.d.ts +47 -0
- package/dist/workflow/worker-source.js +778 -0
- package/dist/worktree.d.ts +52 -0
- package/dist/worktree.js +164 -0
- package/dist/xml.d.ts +10 -0
- package/dist/xml.js +12 -0
- package/docs/rpc.md +183 -0
- package/docs/workflows.md +437 -0
- package/examples/agent-tool-description.md +42 -0
- package/examples/workflows/compose.js +51 -0
- package/examples/workflows/fan-out-audit.js +47 -0
- package/examples/workflows/gated-fix.js +60 -0
- package/examples/workflows/lib/count-child.js +27 -0
- package/examples/workflows/review-panel.js +63 -0
- package/examples/workflows/structured-findings.js +78 -0
- package/package.json +68 -0
- package/src/abortable.ts +43 -0
- package/src/agent-color.ts +161 -0
- package/src/agent-file-toggle.ts +270 -0
- package/src/agent-manager.ts +1581 -0
- package/src/agent-runner.ts +1286 -0
- package/src/agent-types.ts +346 -0
- package/src/child-context.ts +15 -0
- package/src/context.ts +58 -0
- package/src/cross-extension-rpc.ts +198 -0
- package/src/custom-agents.ts +333 -0
- package/src/default-agents.ts +126 -0
- package/src/enabled-models.ts +180 -0
- package/src/env.ts +33 -0
- package/src/group-join.ts +141 -0
- package/src/index.ts +3991 -0
- package/src/invocation-config.ts +155 -0
- package/src/memory.ts +179 -0
- package/src/mention-clone.ts +196 -0
- package/src/mention.ts +141 -0
- package/src/model-resolver.ts +118 -0
- package/src/model-scope.ts +70 -0
- package/src/nested-tools.ts +422 -0
- package/src/output-file.ts +155 -0
- package/src/prompts.ts +142 -0
- package/src/schedule-store.ts +153 -0
- package/src/schedule.ts +386 -0
- package/src/settings.ts +587 -0
- package/src/skill-loader.ts +102 -0
- package/src/status-note.ts +90 -0
- package/src/structured-output.ts +130 -0
- package/src/types.ts +384 -0
- package/src/ui/agent-mention.ts +216 -0
- package/src/ui/agent-widget.ts +664 -0
- package/src/ui/conversation-viewer.ts +589 -0
- package/src/ui/fleet-list.ts +543 -0
- package/src/ui/schedule-menu.ts +105 -0
- package/src/ui/select-item.ts +45 -0
- package/src/ui/viewer-keys.ts +39 -0
- package/src/ui/workflow-card.ts +470 -0
- package/src/ui/workflow-dialog.ts +1115 -0
- package/src/ui/workflow-menu.ts +193 -0
- package/src/usage.ts +167 -0
- package/src/workflow/collisions.ts +123 -0
- package/src/workflow/entry.ts +47 -0
- package/src/workflow/host.ts +403 -0
- package/src/workflow/journal.ts +164 -0
- package/src/workflow/json-schema.ts +128 -0
- package/src/workflow/meta.ts +325 -0
- package/src/workflow/progress.ts +550 -0
- package/src/workflow/runtime.ts +1219 -0
- package/src/workflow/saved.ts +217 -0
- package/src/workflow/task.ts +302 -0
- package/src/workflow/tool-description.ts +200 -0
- package/src/workflow/worker-source.ts +781 -0
- package/src/worktree.ts +205 -0
- package/src/xml.ts +13 -0
|
@@ -0,0 +1,346 @@
|
|
|
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
|
+
|
|
8
|
+
import { createCodingTools, createReadOnlyTools } from "@earendil-works/pi-coding-agent";
|
|
9
|
+
import { DEFAULT_AGENTS } from "./default-agents.js";
|
|
10
|
+
import type { AgentConfig } from "./types.js";
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* All known built-in tool names, derived from pi's own tool factories rather
|
|
14
|
+
* than hardcoded so the set tracks pi-mono if it adds/renames a built-in.
|
|
15
|
+
* `createCodingTools` → read/bash/edit/write; `createReadOnlyTools` →
|
|
16
|
+
* read/grep/find/ls; their de-duplicated union is the 7 built-ins
|
|
17
|
+
* (read, bash, edit, write, grep, find, ls). The `cwd` only binds tool
|
|
18
|
+
* operations we never invoke here — we read each tool's `.name` and discard it.
|
|
19
|
+
*/
|
|
20
|
+
export const BUILTIN_TOOL_NAMES: string[] = [
|
|
21
|
+
...new Set([...createCodingTools("."), ...createReadOnlyTools(".")].map((t) => t.name)),
|
|
22
|
+
];
|
|
23
|
+
|
|
24
|
+
/** Unified runtime registry of all agents (defaults + user-defined). */
|
|
25
|
+
const agents = new Map<string, AgentConfig>();
|
|
26
|
+
|
|
27
|
+
/** When true, DEFAULT_AGENTS are skipped during registration. */
|
|
28
|
+
let disableDefaults = false;
|
|
29
|
+
|
|
30
|
+
/** Check whether default agents are disabled. */
|
|
31
|
+
export function isDefaultsDisabled(): boolean { return disableDefaults; }
|
|
32
|
+
|
|
33
|
+
/** Set whether default agents are disabled. */
|
|
34
|
+
export function setDefaultsDisabled(b: boolean): void { disableDefaults = b; }
|
|
35
|
+
|
|
36
|
+
/** `fallbackSubagent` value that disables the fallback entirely (strict dispatch). */
|
|
37
|
+
export const NO_FALLBACK = "none";
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Agent type substituted when a caller-supplied `subagent_type` doesn't resolve
|
|
41
|
+
* to exactly one enabled agent. `undefined` keeps the historical behavior
|
|
42
|
+
* (general-purpose); `NO_FALLBACK` makes dispatch fail closed. Set from
|
|
43
|
+
* `subagents.json` (`fallbackSubagent`).
|
|
44
|
+
*
|
|
45
|
+
* Module state rather than an index.ts closure because every caller-supplied
|
|
46
|
+
* spawn path needs it — the Agent tool, the scheduler, and cross-extension RPC.
|
|
47
|
+
*/
|
|
48
|
+
let fallbackSubagent: string | undefined;
|
|
49
|
+
|
|
50
|
+
/** Get the configured fallback agent type. undefined = general-purpose. */
|
|
51
|
+
export function getFallbackSubagent(): string | undefined { return fallbackSubagent; }
|
|
52
|
+
|
|
53
|
+
/** Set the configured fallback agent type. undefined = general-purpose. */
|
|
54
|
+
export function setFallbackSubagent(v: string | undefined): void { fallbackSubagent = v; }
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Build a registry map: DEFAULT_AGENTS first (unless disabled via settings),
|
|
58
|
+
* then user agents overlaid on top (same name overrides the default).
|
|
59
|
+
* Pure — callers that must not disturb the process-wide registry (nested
|
|
60
|
+
* delegation resolving agents from its own config root) build their own map.
|
|
61
|
+
*/
|
|
62
|
+
export function buildAgentRegistry(userAgents: Map<string, AgentConfig>): Map<string, AgentConfig> {
|
|
63
|
+
const registry = new Map<string, AgentConfig>();
|
|
64
|
+
if (!disableDefaults) {
|
|
65
|
+
for (const [name, config] of DEFAULT_AGENTS) registry.set(name, config);
|
|
66
|
+
}
|
|
67
|
+
for (const [name, config] of userAgents) registry.set(name, config);
|
|
68
|
+
return registry;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* Register agents into the unified registry.
|
|
73
|
+
* Starts with DEFAULT_AGENTS, then overlays user agents (overrides defaults with same name).
|
|
74
|
+
* Disabled agents (enabled === false) are kept in the registry but excluded from spawning.
|
|
75
|
+
*/
|
|
76
|
+
export function registerAgents(userAgents: Map<string, AgentConfig>): void {
|
|
77
|
+
agents.clear();
|
|
78
|
+
for (const [name, config] of buildAgentRegistry(userAgents)) {
|
|
79
|
+
agents.set(name, config);
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** Case-insensitive key resolution within a registry. */
|
|
84
|
+
function resolveKeyIn(registry: Map<string, AgentConfig>, name: string): string | undefined {
|
|
85
|
+
if (registry.has(name)) return name;
|
|
86
|
+
const lower = name.toLowerCase();
|
|
87
|
+
for (const key of registry.keys()) {
|
|
88
|
+
if (key.toLowerCase() === lower) return key;
|
|
89
|
+
}
|
|
90
|
+
return undefined;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** Case-insensitive key resolution. */
|
|
94
|
+
function resolveKey(name: string): string | undefined {
|
|
95
|
+
return resolveKeyIn(agents, name);
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** Resolve a type name case-insensitively in a registry. Returns the canonical key or undefined. */
|
|
99
|
+
export function resolveTypeIn(registry: Map<string, AgentConfig>, name: string): string | undefined {
|
|
100
|
+
return resolveKeyIn(registry, name);
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** Get the agent config for a type (case-insensitive) from a registry. */
|
|
104
|
+
export function getAgentConfigIn(registry: Map<string, AgentConfig>, name: string): AgentConfig | undefined {
|
|
105
|
+
const key = resolveKeyIn(registry, name);
|
|
106
|
+
return key ? registry.get(key) : undefined;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** Check if a type is valid and enabled (case-insensitive) in a registry. */
|
|
110
|
+
export function isValidTypeIn(registry: Map<string, AgentConfig>, type: string): boolean {
|
|
111
|
+
const key = resolveKeyIn(registry, type);
|
|
112
|
+
if (!key) return false;
|
|
113
|
+
return registry.get(key)?.enabled !== false;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/** Get all enabled type names in a registry (for spawning and tool descriptions). */
|
|
117
|
+
export function getAvailableTypesIn(registry: Map<string, AgentConfig>): string[] {
|
|
118
|
+
return [...registry.entries()]
|
|
119
|
+
.filter(([_, config]) => config.enabled !== false)
|
|
120
|
+
.map(([name]) => name);
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/**
|
|
124
|
+
* Case-insensitive resolution that refuses to guess. An exact match always wins;
|
|
125
|
+
* otherwise the name must match exactly one key. Two agents differing only in
|
|
126
|
+
* case are reachable (`loadCustomAgents` keys by filename across three
|
|
127
|
+
* directories), and picking whichever came first would silently dispatch a
|
|
128
|
+
* different agent, model and tool policy than the caller meant.
|
|
129
|
+
*/
|
|
130
|
+
function resolveUnambiguousKeyIn(registry: Map<string, AgentConfig>, name: string): string | undefined {
|
|
131
|
+
if (registry.has(name)) return name;
|
|
132
|
+
const lower = name.toLowerCase();
|
|
133
|
+
const matches = [...registry.keys()].filter(key => key.toLowerCase() === lower);
|
|
134
|
+
return matches.length === 1 ? matches[0] : undefined;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/**
|
|
138
|
+
* The canonical key for a caller-supplied name that identifies exactly one
|
|
139
|
+
* ENABLED agent, or undefined. Strict by construction: no fallback, no guessing
|
|
140
|
+
* between case-variants. Nested delegation resolves with this directly, since
|
|
141
|
+
* "unknown types are rejected rather than falling back" is its own contract.
|
|
142
|
+
*/
|
|
143
|
+
export function resolveEnabledTypeIn(
|
|
144
|
+
registry: Map<string, AgentConfig>,
|
|
145
|
+
requested: unknown,
|
|
146
|
+
): string | undefined {
|
|
147
|
+
const raw = typeof requested === "string" ? requested.trim() : "";
|
|
148
|
+
if (!raw) return undefined;
|
|
149
|
+
const key = resolveUnambiguousKeyIn(registry, raw);
|
|
150
|
+
return key !== undefined && registry.get(key)?.enabled !== false ? key : undefined;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/** Outcome of resolving a caller-supplied `subagent_type` into a spawnable type. */
|
|
154
|
+
export type SpawnTypeResolution =
|
|
155
|
+
/** Spawn this type. `fellBackFrom` is set when it isn't what the caller asked for. */
|
|
156
|
+
| { ok: true; type: string; fellBackFrom?: string }
|
|
157
|
+
/** Refuse the spawn and return this message to the caller. */
|
|
158
|
+
| { ok: false; message: string };
|
|
159
|
+
|
|
160
|
+
/**
|
|
161
|
+
* Resolve a caller-supplied agent type against a registry, applying the
|
|
162
|
+
* `fallbackSubagent` policy. The single decision point for every caller-supplied
|
|
163
|
+
* spawn — the Agent tool, the scheduler, cross-extension RPC, and the nested
|
|
164
|
+
* tools — so a type that fails here never reaches `runAgent`, where `getConfig`
|
|
165
|
+
* would silently substitute general-purpose.
|
|
166
|
+
*
|
|
167
|
+
* Unknown, disabled, and case-ambiguous names are all treated the same way:
|
|
168
|
+
* the caller named something that doesn't identify exactly one enabled agent.
|
|
169
|
+
*
|
|
170
|
+
* Pure over `registry` — callers that need fresh agent files reload before
|
|
171
|
+
* calling (the Agent tool already does, per spawn). Reloading here would mean
|
|
172
|
+
* importing custom-agents.ts, which imports this module.
|
|
173
|
+
*/
|
|
174
|
+
export function resolveSpawnTypeIn(
|
|
175
|
+
registry: Map<string, AgentConfig>,
|
|
176
|
+
requested: unknown,
|
|
177
|
+
): SpawnTypeResolution {
|
|
178
|
+
const raw = typeof requested === "string" ? requested.trim() : "";
|
|
179
|
+
const available = () => getAvailableTypesIn(registry).join(", ") || "(none)";
|
|
180
|
+
|
|
181
|
+
const key = resolveEnabledTypeIn(registry, raw);
|
|
182
|
+
if (key !== undefined) return { ok: true, type: key };
|
|
183
|
+
|
|
184
|
+
// A missing type follows the same policy as a wrong one rather than always
|
|
185
|
+
// erroring: before this setting existed an empty type fell back like any
|
|
186
|
+
// other unresolvable name, and only opting in should change that.
|
|
187
|
+
const reason = raw ? `Unknown or disabled agent type: "${raw}".` : "No agent type given.";
|
|
188
|
+
|
|
189
|
+
// Trimmed like `requested`: a padded value set programmatically would
|
|
190
|
+
// otherwise be reported as a missing agent.
|
|
191
|
+
const configured = typeof fallbackSubagent === "string" ? fallbackSubagent.trim() : undefined;
|
|
192
|
+
|
|
193
|
+
if (configured !== undefined && configured.toLowerCase() === NO_FALLBACK) {
|
|
194
|
+
return { ok: false, message: `${reason} Available: ${available()}.` };
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
if (configured !== undefined) {
|
|
198
|
+
// An explicitly configured fallback that is itself unusable is a
|
|
199
|
+
// misconfiguration, not a second chance to guess — say so rather than
|
|
200
|
+
// quietly dropping to general-purpose.
|
|
201
|
+
const fallbackKey = resolveUnambiguousKeyIn(registry, configured);
|
|
202
|
+
if (fallbackKey === undefined || registry.get(fallbackKey)?.enabled === false) {
|
|
203
|
+
return {
|
|
204
|
+
ok: false,
|
|
205
|
+
message:
|
|
206
|
+
`${reason} The configured fallbackSubagent "${configured}" is itself ` +
|
|
207
|
+
`unknown or disabled. Available: ${available()}.`,
|
|
208
|
+
};
|
|
209
|
+
}
|
|
210
|
+
return { ok: true, type: fallbackKey, fellBackFrom: raw };
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
// Unset: historical behavior, deliberately unchanged. #183 asks for the
|
|
214
|
+
// fallback to remain the default, so the pre-existing hole it leaves — an
|
|
215
|
+
// unregistered general-purpose resolving to `getConfig`'s all-tools hardcoded
|
|
216
|
+
// tier — is what `fallbackSubagent: none` is for, not something to close
|
|
217
|
+
// under everyone silently.
|
|
218
|
+
return { ok: true, type: "general-purpose", fellBackFrom: raw };
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
/** Resolve a caller-supplied agent type against the process-wide registry. */
|
|
222
|
+
export function resolveSpawnType(requested: unknown): SpawnTypeResolution {
|
|
223
|
+
return resolveSpawnTypeIn(agents, requested);
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
/** Resolve a type name case-insensitively. Returns the canonical key or undefined. */
|
|
227
|
+
export function resolveType(name: string): string | undefined {
|
|
228
|
+
return resolveKey(name);
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
/** Get the agent config for a type (case-insensitive). */
|
|
232
|
+
export function getAgentConfig(name: string): AgentConfig | undefined {
|
|
233
|
+
return getAgentConfigIn(agents, name);
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/** Get all enabled type names (for spawning and tool descriptions). */
|
|
237
|
+
export function getAvailableTypes(): string[] {
|
|
238
|
+
return getAvailableTypesIn(agents);
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
/** Get all type names including disabled (for UI listing). */
|
|
242
|
+
export function getAllTypes(): string[] {
|
|
243
|
+
return [...agents.keys()];
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
/** Get names of default agents currently in the registry. */
|
|
247
|
+
export function getDefaultAgentNames(): string[] {
|
|
248
|
+
return [...agents.entries()]
|
|
249
|
+
.filter(([_, config]) => config.isDefault === true)
|
|
250
|
+
.map(([name]) => name);
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
/** Get names of user-defined agents (non-defaults) currently in the registry. */
|
|
254
|
+
export function getUserAgentNames(): string[] {
|
|
255
|
+
return [...agents.entries()]
|
|
256
|
+
.filter(([_, config]) => config.isDefault !== true)
|
|
257
|
+
.map(([name]) => name);
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
/** Check if a type is valid and enabled (case-insensitive). */
|
|
261
|
+
export function isValidType(type: string): boolean {
|
|
262
|
+
return isValidTypeIn(agents, type);
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
/** Tool names required for memory management. */
|
|
266
|
+
const MEMORY_TOOL_NAMES = ["read", "write", "edit"];
|
|
267
|
+
|
|
268
|
+
/**
|
|
269
|
+
* Get memory tool names (read/write/edit) not already in the provided set.
|
|
270
|
+
*/
|
|
271
|
+
export function getMemoryToolNames(existingToolNames: Set<string>): string[] {
|
|
272
|
+
return MEMORY_TOOL_NAMES.filter(n => !existingToolNames.has(n));
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
/** Tool names needed for read-only memory access. */
|
|
276
|
+
const READONLY_MEMORY_TOOL_NAMES = ["read"];
|
|
277
|
+
|
|
278
|
+
/**
|
|
279
|
+
* Get read-only memory tool names not already in the provided set.
|
|
280
|
+
*/
|
|
281
|
+
export function getReadOnlyMemoryToolNames(existingToolNames: Set<string>): string[] {
|
|
282
|
+
return READONLY_MEMORY_TOOL_NAMES.filter(n => !existingToolNames.has(n));
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
/** Get built-in tool names for a type (case-insensitive). */
|
|
286
|
+
export function getToolNamesForType(type: string): string[] {
|
|
287
|
+
const key = resolveKey(type);
|
|
288
|
+
const raw = key ? agents.get(key) : undefined;
|
|
289
|
+
const config = raw?.enabled !== false ? raw : undefined;
|
|
290
|
+
// `undefined` (definition omitted the field) → all built-ins; an explicit `[]`
|
|
291
|
+
// (`tools: none` or a `tools:` with only `ext:` entries) → zero built-ins.
|
|
292
|
+
return config?.builtinToolNames ?? [...BUILTIN_TOOL_NAMES];
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
/** Get config for a type (case-insensitive, returns a SubagentTypeConfig-compatible object). Falls back to general-purpose. */
|
|
296
|
+
export function getConfig(type: string): {
|
|
297
|
+
displayName: string;
|
|
298
|
+
color?: string;
|
|
299
|
+
description: string;
|
|
300
|
+
builtinToolNames: string[];
|
|
301
|
+
extensions: true | string[] | false;
|
|
302
|
+
excludeExtensions?: string[];
|
|
303
|
+
skills: true | string[] | false;
|
|
304
|
+
promptMode: "replace" | "append";
|
|
305
|
+
} {
|
|
306
|
+
const key = resolveKey(type);
|
|
307
|
+
const config = key ? agents.get(key) : undefined;
|
|
308
|
+
if (config && config.enabled !== false) {
|
|
309
|
+
return {
|
|
310
|
+
displayName: config.displayName ?? config.name,
|
|
311
|
+
color: config.color,
|
|
312
|
+
description: config.description,
|
|
313
|
+
builtinToolNames: config.builtinToolNames ?? BUILTIN_TOOL_NAMES,
|
|
314
|
+
extensions: config.extensions,
|
|
315
|
+
excludeExtensions: config.excludeExtensions,
|
|
316
|
+
skills: config.skills,
|
|
317
|
+
promptMode: config.promptMode,
|
|
318
|
+
};
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
// Fallback for unknown/disabled types — general-purpose config
|
|
322
|
+
const gp = agents.get("general-purpose");
|
|
323
|
+
if (gp && gp.enabled !== false) {
|
|
324
|
+
return {
|
|
325
|
+
displayName: gp.displayName ?? gp.name,
|
|
326
|
+
color: gp.color,
|
|
327
|
+
description: gp.description,
|
|
328
|
+
builtinToolNames: gp.builtinToolNames ?? BUILTIN_TOOL_NAMES,
|
|
329
|
+
extensions: gp.extensions,
|
|
330
|
+
excludeExtensions: gp.excludeExtensions,
|
|
331
|
+
skills: gp.skills,
|
|
332
|
+
promptMode: gp.promptMode,
|
|
333
|
+
};
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
// Absolute fallback (should never happen)
|
|
337
|
+
return {
|
|
338
|
+
displayName: "Agent",
|
|
339
|
+
description: "General-purpose agent for complex, multi-step tasks",
|
|
340
|
+
builtinToolNames: BUILTIN_TOOL_NAMES,
|
|
341
|
+
extensions: true,
|
|
342
|
+
skills: true,
|
|
343
|
+
promptMode: "append",
|
|
344
|
+
};
|
|
345
|
+
}
|
|
346
|
+
|
|
@@ -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
|
+
}
|
package/src/context.ts
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* context.ts — Extract parent conversation context for subagent inheritance.
|
|
3
|
+
*/
|
|
4
|
+
|
|
5
|
+
import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
6
|
+
|
|
7
|
+
/** Extract text from a message content block array. */
|
|
8
|
+
export function extractText(content: unknown[]): string {
|
|
9
|
+
return content
|
|
10
|
+
.filter((c: any) => c.type === "text")
|
|
11
|
+
.map((c: any) => c.text ?? "")
|
|
12
|
+
.join("\n");
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Build a text representation of the parent conversation context.
|
|
17
|
+
* Used when inherit_context is true to give the subagent visibility
|
|
18
|
+
* into what has been discussed/done so far.
|
|
19
|
+
*/
|
|
20
|
+
export function buildParentContext(ctx: ExtensionContext): string {
|
|
21
|
+
const entries = ctx.sessionManager.getBranch();
|
|
22
|
+
if (!entries || entries.length === 0) return "";
|
|
23
|
+
|
|
24
|
+
const parts: string[] = [];
|
|
25
|
+
|
|
26
|
+
for (const entry of entries) {
|
|
27
|
+
if (entry.type === "message") {
|
|
28
|
+
const msg = entry.message;
|
|
29
|
+
if (msg.role === "user") {
|
|
30
|
+
const text = typeof msg.content === "string"
|
|
31
|
+
? msg.content
|
|
32
|
+
: extractText(msg.content);
|
|
33
|
+
if (text.trim()) parts.push(`[User]: ${text.trim()}`);
|
|
34
|
+
} else if (msg.role === "assistant") {
|
|
35
|
+
const text = extractText(msg.content);
|
|
36
|
+
if (text.trim()) parts.push(`[Assistant]: ${text.trim()}`);
|
|
37
|
+
}
|
|
38
|
+
// Skip toolResult messages — too verbose for context
|
|
39
|
+
} else if (entry.type === "compaction") {
|
|
40
|
+
// Include compaction summaries — they're already condensed
|
|
41
|
+
if (entry.summary) {
|
|
42
|
+
parts.push(`[Summary]: ${entry.summary}`);
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
if (parts.length === 0) return "";
|
|
48
|
+
|
|
49
|
+
return `# Parent Conversation Context
|
|
50
|
+
The following is the conversation history from the parent session that spawned you.
|
|
51
|
+
Use this context to understand what has been discussed and decided so far.
|
|
52
|
+
|
|
53
|
+
${parts.join("\n\n")}
|
|
54
|
+
|
|
55
|
+
---
|
|
56
|
+
# Your Task (below)
|
|
57
|
+
`;
|
|
58
|
+
}
|
|
@@ -0,0 +1,198 @@
|
|
|
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
|
+
|
|
16
|
+
import { isTopLevelAgent } from "./agent-manager.js";
|
|
17
|
+
import { type ModelRegistry, resolveModel } from "./model-resolver.js";
|
|
18
|
+
import { checkModelScope } from "./model-scope.js";
|
|
19
|
+
import type { AgentRecord } from "./types.js";
|
|
20
|
+
|
|
21
|
+
/** Minimal event bus interface needed by the RPC handlers. */
|
|
22
|
+
export interface EventBus {
|
|
23
|
+
on(event: string, handler: (data: unknown) => void): () => void;
|
|
24
|
+
emit(event: string, data: unknown): void;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** RPC reply envelope — matches pi-mono's RpcResponse shape. */
|
|
28
|
+
export type RpcReply<T = void> =
|
|
29
|
+
| { success: true; data?: T }
|
|
30
|
+
| { success: false; error: string };
|
|
31
|
+
|
|
32
|
+
/** RPC protocol version — bumped when the envelope or method contracts change. */
|
|
33
|
+
export const PROTOCOL_VERSION = 2;
|
|
34
|
+
|
|
35
|
+
/** Minimal AgentManager interface needed by the spawn/stop/consume RPCs. */
|
|
36
|
+
export interface SpawnCapable {
|
|
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>;
|
|
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;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export interface RpcDeps {
|
|
56
|
+
events: EventBus;
|
|
57
|
+
pi: unknown; // passed through to manager.spawn
|
|
58
|
+
getCtx: () => unknown | undefined; // returns current ExtensionContext
|
|
59
|
+
manager: SpawnCapable;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export interface RpcHandle {
|
|
63
|
+
unsubPing: () => void;
|
|
64
|
+
unsubSpawn: () => void;
|
|
65
|
+
unsubStop: () => void;
|
|
66
|
+
unsubConsume: () => void;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* Wire a single RPC handler: listen on `channel`, run `fn(params)`,
|
|
71
|
+
* emit the reply envelope on `channel:reply:${requestId}`.
|
|
72
|
+
*/
|
|
73
|
+
function handleRpc<P extends { requestId: string }>(
|
|
74
|
+
events: EventBus,
|
|
75
|
+
channel: string,
|
|
76
|
+
fn: (params: P) => unknown | Promise<unknown>,
|
|
77
|
+
): () => void {
|
|
78
|
+
return events.on(channel, async (raw: unknown) => {
|
|
79
|
+
const params = raw as P;
|
|
80
|
+
try {
|
|
81
|
+
const data = await fn(params);
|
|
82
|
+
const reply: { success: true; data?: unknown } = { success: true };
|
|
83
|
+
if (data !== undefined) reply.data = data;
|
|
84
|
+
events.emit(`${channel}:reply:${params.requestId}`, reply);
|
|
85
|
+
} catch (err: any) {
|
|
86
|
+
events.emit(`${channel}:reply:${params.requestId}`, {
|
|
87
|
+
success: false, error: err?.message ?? String(err),
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
});
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* Register ping, spawn, stop, and consume RPC handlers on the event bus.
|
|
95
|
+
* Returns unsub functions for cleanup.
|
|
96
|
+
*/
|
|
97
|
+
export function registerRpcHandlers(deps: RpcDeps): RpcHandle {
|
|
98
|
+
const { events, pi, getCtx, manager } = deps;
|
|
99
|
+
|
|
100
|
+
const unsubPing = handleRpc(events, "subagents:rpc:ping", () => {
|
|
101
|
+
return { version: PROTOCOL_VERSION };
|
|
102
|
+
});
|
|
103
|
+
|
|
104
|
+
const unsubSpawn = handleRpc<{ requestId: string; type: string; prompt: string; options?: any }>(
|
|
105
|
+
events, "subagents:rpc:spawn", async ({ type, prompt, options }) => {
|
|
106
|
+
const ctx = getCtx();
|
|
107
|
+
if (!ctx) throw new Error("No active session");
|
|
108
|
+
|
|
109
|
+
// Cross-extension RPC callers (e.g. pi-tasks TaskExecute) naturally
|
|
110
|
+
// forward serializable values, so options.model can be a string like
|
|
111
|
+
// "openai-codex/gpt-5.5". Resolve it to a real Model instance here
|
|
112
|
+
// — same pattern the scheduler path already uses — so the spawned
|
|
113
|
+
// agent's auth lookup doesn't crash with "No API key found for
|
|
114
|
+
// undefined".
|
|
115
|
+
let normalizedOptions = options ?? {};
|
|
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`);
|
|
127
|
+
}
|
|
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 };
|
|
139
|
+
}
|
|
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);
|
|
156
|
+
}
|
|
157
|
+
|
|
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 };
|
|
164
|
+
},
|
|
165
|
+
);
|
|
166
|
+
|
|
167
|
+
const unsubStop = handleRpc<{ requestId: string; agentId: string }>(
|
|
168
|
+
events, "subagents:rpc:stop", ({ agentId }) => {
|
|
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");
|
|
194
|
+
},
|
|
195
|
+
);
|
|
196
|
+
|
|
197
|
+
return { unsubPing, unsubSpawn, unsubStop, unsubConsume };
|
|
198
|
+
}
|