@esso0428/pi-subagents 0.15.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 +638 -0
- package/CONTRIBUTING.md +68 -0
- package/LICENSE +21 -0
- package/README.md +745 -0
- package/SECURITY.md +95 -0
- package/dist/agent-manager.d.ts +144 -0
- package/dist/agent-manager.js +542 -0
- package/dist/agent-runner.d.ts +212 -0
- package/dist/agent-runner.js +850 -0
- package/dist/agent-types.d.ts +67 -0
- package/dist/agent-types.js +168 -0
- package/dist/context.d.ts +12 -0
- package/dist/context.js +56 -0
- package/dist/cross-extension-rpc.d.ts +46 -0
- package/dist/cross-extension-rpc.js +76 -0
- package/dist/custom-agents.d.ts +17 -0
- package/dist/custom-agents.js +156 -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 +16 -0
- package/dist/index.js +2209 -0
- package/dist/invocation-config.d.ts +22 -0
- package/dist/invocation-config.js +15 -0
- package/dist/memory.d.ts +53 -0
- package/dist/memory.js +165 -0
- package/dist/model-resolver.d.ts +19 -0
- package/dist/model-resolver.js +80 -0
- package/dist/nico-overrides.d.ts +53 -0
- package/dist/nico-overrides.js +169 -0
- package/dist/output-file.d.ts +24 -0
- package/dist/output-file.js +101 -0
- package/dist/prompts.d.ts +32 -0
- package/dist/prompts.js +73 -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 +338 -0
- package/dist/settings.d.ts +141 -0
- package/dist/settings.js +162 -0
- package/dist/skill-loader.d.ts +24 -0
- package/dist/skill-loader.js +93 -0
- package/dist/status-note.d.ts +13 -0
- package/dist/status-note.js +24 -0
- package/dist/types.d.ts +197 -0
- package/dist/types.js +5 -0
- package/dist/ui/agent-widget.d.ts +160 -0
- package/dist/ui/agent-widget.js +484 -0
- package/dist/ui/conversation-viewer.d.ts +57 -0
- package/dist/ui/conversation-viewer.js +354 -0
- package/dist/ui/fleet-list.d.ts +106 -0
- package/dist/ui/fleet-list.js +345 -0
- package/dist/ui/schedule-menu.d.ts +16 -0
- package/dist/ui/schedule-menu.js +95 -0
- package/dist/ui/viewer-keys.d.ts +20 -0
- package/dist/ui/viewer-keys.js +17 -0
- package/dist/usage.d.ts +50 -0
- package/dist/usage.js +49 -0
- package/dist/worktree.d.ts +45 -0
- package/dist/worktree.js +160 -0
- package/examples/agent-tool-description.md +42 -0
- package/package.json +56 -0
- package/src/agent-manager.ts +631 -0
- package/src/agent-runner.ts +1014 -0
- package/src/agent-types.ts +202 -0
- package/src/context.ts +58 -0
- package/src/cross-extension-rpc.ts +122 -0
- package/src/custom-agents.ts +167 -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 +2400 -0
- package/src/invocation-config.ts +40 -0
- package/src/memory.ts +179 -0
- package/src/model-resolver.ts +100 -0
- package/src/nico-overrides.ts +235 -0
- package/src/output-file.ts +110 -0
- package/src/prompts.ts +99 -0
- package/src/schedule-store.ts +153 -0
- package/src/schedule.ts +365 -0
- package/src/settings.ts +288 -0
- package/src/skill-loader.ts +102 -0
- package/src/status-note.ts +25 -0
- package/src/types.ts +208 -0
- package/src/ui/agent-widget.ts +566 -0
- package/src/ui/conversation-viewer.ts +362 -0
- package/src/ui/fleet-list.ts +380 -0
- package/src/ui/schedule-menu.ts +104 -0
- package/src/ui/viewer-keys.ts +39 -0
- package/src/usage.ts +60 -0
- package/src/worktree.ts +191 -0
- package/vitest.config.ts +18 -0
|
@@ -0,0 +1,202 @@
|
|
|
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 { applyNicoOverridesToMap, readNicoAgentOverrides } from "./nico-overrides.js";
|
|
11
|
+
import type { AgentConfig } from "./types.js";
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* All known built-in tool names, derived from pi's own tool factories rather
|
|
16
|
+
* than hardcoded so the set tracks pi-mono if it adds/renames a built-in.
|
|
17
|
+
* `createCodingTools` → read/bash/edit/write; `createReadOnlyTools` →
|
|
18
|
+
* read/grep/find/ls; their de-duplicated union is the 7 built-ins
|
|
19
|
+
* (read, bash, edit, write, grep, find, ls). The `cwd` only binds tool
|
|
20
|
+
* operations we never invoke here — we read each tool's `.name` and discard it.
|
|
21
|
+
*/
|
|
22
|
+
export const BUILTIN_TOOL_NAMES: string[] = [
|
|
23
|
+
...new Set([...createCodingTools("."), ...createReadOnlyTools(".")].map((t) => t.name)),
|
|
24
|
+
];
|
|
25
|
+
|
|
26
|
+
/** Unified runtime registry of all agents (defaults + user-defined). */
|
|
27
|
+
const agents = new Map<string, AgentConfig>();
|
|
28
|
+
|
|
29
|
+
/** When true, DEFAULT_AGENTS are skipped during registration. */
|
|
30
|
+
let disableDefaults = false;
|
|
31
|
+
|
|
32
|
+
/** Check whether default agents are disabled. */
|
|
33
|
+
export function isDefaultsDisabled(): boolean { return disableDefaults; }
|
|
34
|
+
|
|
35
|
+
/** Set whether default agents are disabled. */
|
|
36
|
+
export function setDefaultsDisabled(b: boolean): void { disableDefaults = b; }
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Register agents into the unified registry.
|
|
40
|
+
* Starts with DEFAULT_AGENTS, then overlays user agents (overrides defaults with same name).
|
|
41
|
+
* Disabled agents (enabled === false) are kept in the registry but excluded from spawning.
|
|
42
|
+
*/
|
|
43
|
+
export function registerAgents(userAgents: Map<string, AgentConfig>): void {
|
|
44
|
+
agents.clear();
|
|
45
|
+
|
|
46
|
+
// Start with defaults (unless disabled via settings)
|
|
47
|
+
if (!disableDefaults) {
|
|
48
|
+
for (const [name, config] of DEFAULT_AGENTS) {
|
|
49
|
+
agents.set(name, config);
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
// Overlay user agents (overrides defaults with same name)
|
|
54
|
+
for (const [name, config] of userAgents) {
|
|
55
|
+
agents.set(name, config);
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Apply npm:pi-subagents-style JSON overrides to the current agent registry.
|
|
61
|
+
* Reads from ~/.pi/agent/settings.json and .pi/settings.json and applies
|
|
62
|
+
* them as the highest-priority layer. Auto-registers agents that don't
|
|
63
|
+
* exist in the registry yet.
|
|
64
|
+
*/
|
|
65
|
+
export function applyNicoOverrides(): void {
|
|
66
|
+
const { overrides, defaultModel } = readNicoAgentOverrides(process.cwd());
|
|
67
|
+
applyNicoOverridesToMap(agents, overrides, defaultModel);
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** Case-insensitive key resolution. */
|
|
71
|
+
function resolveKey(name: string): string | undefined {
|
|
72
|
+
if (agents.has(name)) return name;
|
|
73
|
+
const lower = name.toLowerCase();
|
|
74
|
+
for (const key of agents.keys()) {
|
|
75
|
+
if (key.toLowerCase() === lower) return key;
|
|
76
|
+
}
|
|
77
|
+
return undefined;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** Resolve a type name case-insensitively. Returns the canonical key or undefined. */
|
|
81
|
+
export function resolveType(name: string): string | undefined {
|
|
82
|
+
return resolveKey(name);
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** Get the agent config for a type (case-insensitive). */
|
|
86
|
+
export function getAgentConfig(name: string): AgentConfig | undefined {
|
|
87
|
+
const key = resolveKey(name);
|
|
88
|
+
return key ? agents.get(key) : undefined;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** Get all enabled type names (for spawning and tool descriptions). */
|
|
92
|
+
export function getAvailableTypes(): string[] {
|
|
93
|
+
return [...agents.entries()]
|
|
94
|
+
.filter(([_, config]) => config.enabled !== false)
|
|
95
|
+
.map(([name]) => name);
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** Get all type names including disabled (for UI listing). */
|
|
99
|
+
export function getAllTypes(): string[] {
|
|
100
|
+
return [...agents.keys()];
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** Get names of default agents currently in the registry. */
|
|
104
|
+
export function getDefaultAgentNames(): string[] {
|
|
105
|
+
return [...agents.entries()]
|
|
106
|
+
.filter(([_, config]) => config.isDefault === true)
|
|
107
|
+
.map(([name]) => name);
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** Get names of user-defined agents (non-defaults) currently in the registry. */
|
|
111
|
+
export function getUserAgentNames(): string[] {
|
|
112
|
+
return [...agents.entries()]
|
|
113
|
+
.filter(([_, config]) => config.isDefault !== true)
|
|
114
|
+
.map(([name]) => name);
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** Check if a type is valid and enabled (case-insensitive). */
|
|
118
|
+
export function isValidType(type: string): boolean {
|
|
119
|
+
const key = resolveKey(type);
|
|
120
|
+
if (!key) return false;
|
|
121
|
+
return agents.get(key)?.enabled !== false;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/** Tool names required for memory management. */
|
|
125
|
+
const MEMORY_TOOL_NAMES = ["read", "write", "edit"];
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* Get memory tool names (read/write/edit) not already in the provided set.
|
|
129
|
+
*/
|
|
130
|
+
export function getMemoryToolNames(existingToolNames: Set<string>): string[] {
|
|
131
|
+
return MEMORY_TOOL_NAMES.filter(n => !existingToolNames.has(n));
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/** Tool names needed for read-only memory access. */
|
|
135
|
+
const READONLY_MEMORY_TOOL_NAMES = ["read"];
|
|
136
|
+
|
|
137
|
+
/**
|
|
138
|
+
* Get read-only memory tool names not already in the provided set.
|
|
139
|
+
*/
|
|
140
|
+
export function getReadOnlyMemoryToolNames(existingToolNames: Set<string>): string[] {
|
|
141
|
+
return READONLY_MEMORY_TOOL_NAMES.filter(n => !existingToolNames.has(n));
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** Get built-in tool names for a type (case-insensitive). */
|
|
145
|
+
export function getToolNamesForType(type: string): string[] {
|
|
146
|
+
const key = resolveKey(type);
|
|
147
|
+
const raw = key ? agents.get(key) : undefined;
|
|
148
|
+
const config = raw?.enabled !== false ? raw : undefined;
|
|
149
|
+
// `undefined` (definition omitted the field) → all built-ins; an explicit `[]`
|
|
150
|
+
// (`tools: none` or a `tools:` with only `ext:` entries) → zero built-ins.
|
|
151
|
+
return config?.builtinToolNames ?? [...BUILTIN_TOOL_NAMES];
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/** Get config for a type (case-insensitive, returns a SubagentTypeConfig-compatible object). Falls back to general-purpose. */
|
|
155
|
+
export function getConfig(type: string): {
|
|
156
|
+
displayName: string;
|
|
157
|
+
description: string;
|
|
158
|
+
builtinToolNames: string[];
|
|
159
|
+
extensions: true | string[] | false;
|
|
160
|
+
excludeExtensions?: string[];
|
|
161
|
+
skills: true | string[] | false;
|
|
162
|
+
promptMode: "replace" | "append";
|
|
163
|
+
} {
|
|
164
|
+
const key = resolveKey(type);
|
|
165
|
+
const config = key ? agents.get(key) : undefined;
|
|
166
|
+
if (config && config.enabled !== false) {
|
|
167
|
+
return {
|
|
168
|
+
displayName: config.displayName ?? config.name,
|
|
169
|
+
description: config.description,
|
|
170
|
+
builtinToolNames: config.builtinToolNames ?? BUILTIN_TOOL_NAMES,
|
|
171
|
+
extensions: config.extensions,
|
|
172
|
+
excludeExtensions: config.excludeExtensions,
|
|
173
|
+
skills: config.skills,
|
|
174
|
+
promptMode: config.promptMode,
|
|
175
|
+
};
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
// Fallback for unknown/disabled types — general-purpose config
|
|
179
|
+
const gp = agents.get("general-purpose");
|
|
180
|
+
if (gp && gp.enabled !== false) {
|
|
181
|
+
return {
|
|
182
|
+
displayName: gp.displayName ?? gp.name,
|
|
183
|
+
description: gp.description,
|
|
184
|
+
builtinToolNames: gp.builtinToolNames ?? BUILTIN_TOOL_NAMES,
|
|
185
|
+
extensions: gp.extensions,
|
|
186
|
+
excludeExtensions: gp.excludeExtensions,
|
|
187
|
+
skills: gp.skills,
|
|
188
|
+
promptMode: gp.promptMode,
|
|
189
|
+
};
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
// Absolute fallback (should never happen)
|
|
193
|
+
return {
|
|
194
|
+
displayName: "Agent",
|
|
195
|
+
description: "General-purpose agent for complex, multi-step tasks",
|
|
196
|
+
builtinToolNames: BUILTIN_TOOL_NAMES,
|
|
197
|
+
extensions: true,
|
|
198
|
+
skills: true,
|
|
199
|
+
promptMode: "append",
|
|
200
|
+
};
|
|
201
|
+
}
|
|
202
|
+
|
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,122 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Cross-extension RPC handlers for the subagents extension.
|
|
3
|
+
*
|
|
4
|
+
* Exposes ping, spawn, and stop 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
|
+
|
|
12
|
+
import { type ModelRegistry, resolveModel } from "./model-resolver.js";
|
|
13
|
+
|
|
14
|
+
/** Minimal event bus interface needed by the RPC handlers. */
|
|
15
|
+
export interface EventBus {
|
|
16
|
+
on(event: string, handler: (data: unknown) => void): () => void;
|
|
17
|
+
emit(event: string, data: unknown): void;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** RPC reply envelope — matches pi-mono's RpcResponse shape. */
|
|
21
|
+
export type RpcReply<T = void> =
|
|
22
|
+
| { success: true; data?: T }
|
|
23
|
+
| { success: false; error: string };
|
|
24
|
+
|
|
25
|
+
/** RPC protocol version — bumped when the envelope or method contracts change. */
|
|
26
|
+
export const PROTOCOL_VERSION = 2;
|
|
27
|
+
|
|
28
|
+
/** Minimal AgentManager interface needed by the spawn/stop RPCs. */
|
|
29
|
+
export interface SpawnCapable {
|
|
30
|
+
spawn(pi: unknown, ctx: unknown, type: string, prompt: string, options: any): string;
|
|
31
|
+
abort(id: string): boolean;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export interface RpcDeps {
|
|
35
|
+
events: EventBus;
|
|
36
|
+
pi: unknown; // passed through to manager.spawn
|
|
37
|
+
getCtx: () => unknown | undefined; // returns current ExtensionContext
|
|
38
|
+
manager: SpawnCapable;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export interface RpcHandle {
|
|
42
|
+
unsubPing: () => void;
|
|
43
|
+
unsubSpawn: () => void;
|
|
44
|
+
unsubStop: () => void;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* Wire a single RPC handler: listen on `channel`, run `fn(params)`,
|
|
49
|
+
* emit the reply envelope on `channel:reply:${requestId}`.
|
|
50
|
+
*/
|
|
51
|
+
function handleRpc<P extends { requestId: string }>(
|
|
52
|
+
events: EventBus,
|
|
53
|
+
channel: string,
|
|
54
|
+
fn: (params: P) => unknown | Promise<unknown>,
|
|
55
|
+
): () => void {
|
|
56
|
+
return events.on(channel, async (raw: unknown) => {
|
|
57
|
+
const params = raw as P;
|
|
58
|
+
try {
|
|
59
|
+
const data = await fn(params);
|
|
60
|
+
const reply: { success: true; data?: unknown } = { success: true };
|
|
61
|
+
if (data !== undefined) reply.data = data;
|
|
62
|
+
events.emit(`${channel}:reply:${params.requestId}`, reply);
|
|
63
|
+
} catch (err: any) {
|
|
64
|
+
events.emit(`${channel}:reply:${params.requestId}`, {
|
|
65
|
+
success: false, error: err?.message ?? String(err),
|
|
66
|
+
});
|
|
67
|
+
}
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* Register ping, spawn, and stop RPC handlers on the event bus.
|
|
73
|
+
* Returns unsub functions for cleanup.
|
|
74
|
+
*/
|
|
75
|
+
export function registerRpcHandlers(deps: RpcDeps): RpcHandle {
|
|
76
|
+
const { events, pi, getCtx, manager } = deps;
|
|
77
|
+
|
|
78
|
+
const unsubPing = handleRpc(events, "subagents:rpc:ping", () => {
|
|
79
|
+
return { version: PROTOCOL_VERSION };
|
|
80
|
+
});
|
|
81
|
+
|
|
82
|
+
const unsubSpawn = handleRpc<{ requestId: string; type: string; prompt: string; options?: any }>(
|
|
83
|
+
events, "subagents:rpc:spawn", ({ type, prompt, options }) => {
|
|
84
|
+
const ctx = getCtx();
|
|
85
|
+
if (!ctx) throw new Error("No active session");
|
|
86
|
+
|
|
87
|
+
// Cross-extension RPC callers (e.g. pi-tasks TaskExecute) naturally
|
|
88
|
+
// forward serializable values, so options.model can be a string like
|
|
89
|
+
// "openai-codex/gpt-5.5". Resolve it to a real Model instance here
|
|
90
|
+
// — same pattern the scheduler path already uses — so the spawned
|
|
91
|
+
// agent's auth lookup doesn't crash with "No API key found for
|
|
92
|
+
// undefined".
|
|
93
|
+
let normalizedOptions = options ?? {};
|
|
94
|
+
if (typeof normalizedOptions.model === "string") {
|
|
95
|
+
const registry = (ctx as { modelRegistry?: ModelRegistry }).modelRegistry;
|
|
96
|
+
if (!registry) {
|
|
97
|
+
throw new Error(
|
|
98
|
+
`Model override "${normalizedOptions.model}" provided but ctx.modelRegistry is unavailable`,
|
|
99
|
+
);
|
|
100
|
+
}
|
|
101
|
+
const resolved = resolveModel(normalizedOptions.model, registry);
|
|
102
|
+
if (typeof resolved === "string") {
|
|
103
|
+
// resolveModel returns a human-readable error string when the
|
|
104
|
+
// input doesn't match any available model. Surface it instead of
|
|
105
|
+
// silently falling back so the caller sees the auth/typo issue.
|
|
106
|
+
throw new Error(resolved);
|
|
107
|
+
}
|
|
108
|
+
normalizedOptions = { ...normalizedOptions, model: resolved };
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
return { id: manager.spawn(pi, ctx, type, prompt, normalizedOptions) };
|
|
112
|
+
},
|
|
113
|
+
);
|
|
114
|
+
|
|
115
|
+
const unsubStop = handleRpc<{ requestId: string; agentId: string }>(
|
|
116
|
+
events, "subagents:rpc:stop", ({ agentId }) => {
|
|
117
|
+
if (!manager.abort(agentId)) throw new Error("Agent not found");
|
|
118
|
+
},
|
|
119
|
+
);
|
|
120
|
+
|
|
121
|
+
return { unsubPing, unsubSpawn, unsubStop };
|
|
122
|
+
}
|
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* custom-agents.ts — Load user-defined agents from project (.pi/agents/, plus the shared .agents/agents/ workspace) and global ($PI_CODING_AGENT_DIR/agents/, default ~/.pi/agent/agents/) locations.
|
|
3
|
+
*/
|
|
4
|
+
|
|
5
|
+
import { existsSync, readdirSync, readFileSync } from "node:fs";
|
|
6
|
+
import { basename, join } from "node:path";
|
|
7
|
+
import { getAgentDir, parseFrontmatter } from "@earendil-works/pi-coding-agent";
|
|
8
|
+
import { BUILTIN_TOOL_NAMES } from "./agent-types.js";
|
|
9
|
+
import type { AgentConfig, MemoryScope, ThinkingLevel } from "./types.js";
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Scan for custom agent .md files from multiple locations.
|
|
13
|
+
* Discovery hierarchy (higher priority wins):
|
|
14
|
+
* 1. Project: <cwd>/.pi/agents/*.md (authoritative — also where /agents writes)
|
|
15
|
+
* 2. Workspace: <cwd>/.agents/agents/*.md (shared cross-tool .agents workspace, read-only)
|
|
16
|
+
* 3. Global: $PI_CODING_AGENT_DIR/agents/*.md (default: ~/.pi/agent/agents/*.md)
|
|
17
|
+
*
|
|
18
|
+
* Project-level agents override global ones with the same name. On a name clash
|
|
19
|
+
* between the two project locations, .pi/agents wins — .pi stays the project
|
|
20
|
+
* authority; .agents/agents is an additional read location.
|
|
21
|
+
* Any name is allowed — names matching defaults (e.g. "Explore") override them.
|
|
22
|
+
*/
|
|
23
|
+
export function loadCustomAgents(cwd: string): Map<string, AgentConfig> {
|
|
24
|
+
const globalDir = join(getAgentDir(), "agents");
|
|
25
|
+
const workspaceProjectDir = join(cwd, ".agents", "agents");
|
|
26
|
+
const projectDir = join(cwd, ".pi", "agents");
|
|
27
|
+
|
|
28
|
+
const agents = new Map<string, AgentConfig>();
|
|
29
|
+
loadFromDir(globalDir, agents, "global"); // lowest priority
|
|
30
|
+
loadFromDir(workspaceProjectDir, agents, "project"); // shared workspace
|
|
31
|
+
loadFromDir(projectDir, agents, "project"); // highest priority (overwrites)
|
|
32
|
+
return agents;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** Load agent configs from a directory into the map. */
|
|
36
|
+
function loadFromDir(dir: string, agents: Map<string, AgentConfig>, source: "project" | "global"): void {
|
|
37
|
+
if (!existsSync(dir)) return;
|
|
38
|
+
|
|
39
|
+
let files: string[];
|
|
40
|
+
try {
|
|
41
|
+
files = readdirSync(dir).filter(f => f.endsWith(".md"));
|
|
42
|
+
} catch {
|
|
43
|
+
return;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
for (const file of files) {
|
|
47
|
+
const name = basename(file, ".md");
|
|
48
|
+
|
|
49
|
+
let content: string;
|
|
50
|
+
try {
|
|
51
|
+
content = readFileSync(join(dir, file), "utf-8");
|
|
52
|
+
} catch {
|
|
53
|
+
continue;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
const { frontmatter: fm, body } = parseFrontmatter<Record<string, unknown>>(content);
|
|
57
|
+
|
|
58
|
+
const { builtinToolNames, extSelectors } = parseToolsField(fm.tools);
|
|
59
|
+
|
|
60
|
+
agents.set(name, {
|
|
61
|
+
name,
|
|
62
|
+
displayName: str(fm.display_name),
|
|
63
|
+
description: str(fm.description) ?? name,
|
|
64
|
+
builtinToolNames,
|
|
65
|
+
extSelectors,
|
|
66
|
+
disallowedTools: csvListOptional(fm.disallowed_tools),
|
|
67
|
+
extensions: inheritField(fm.extensions ?? fm.inherit_extensions),
|
|
68
|
+
excludeExtensions: csvListOptional(fm.exclude_extensions),
|
|
69
|
+
skills: inheritField(fm.skills ?? fm.inherit_skills),
|
|
70
|
+
model: str(fm.model),
|
|
71
|
+
thinking: str(fm.thinking) as ThinkingLevel | undefined,
|
|
72
|
+
maxTurns: nonNegativeInt(fm.max_turns),
|
|
73
|
+
persistSession: fm.persist_session != null ? fm.persist_session === true : undefined,
|
|
74
|
+
outputTranscript: fm.output_transcript != null ? fm.output_transcript !== false : undefined,
|
|
75
|
+
sessionDir: str(fm.session_dir),
|
|
76
|
+
systemPrompt: body.trim(),
|
|
77
|
+
promptMode: fm.prompt_mode === "append" ? "append" : "replace",
|
|
78
|
+
inheritContext: fm.inherit_context != null ? fm.inherit_context === true : undefined,
|
|
79
|
+
runInBackground: fm.run_in_background != null ? fm.run_in_background === true : undefined,
|
|
80
|
+
isolated: fm.isolated != null ? fm.isolated === true : undefined,
|
|
81
|
+
memory: parseMemory(fm.memory),
|
|
82
|
+
isolation: fm.isolation === "worktree" ? "worktree" : undefined,
|
|
83
|
+
enabled: fm.enabled !== false, // default true; explicitly false disables
|
|
84
|
+
source,
|
|
85
|
+
});
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
// ---- Field parsers ----
|
|
90
|
+
// All follow the same convention: omitted → default, "none"/empty → nothing, value → exact.
|
|
91
|
+
|
|
92
|
+
/** Extract a string or undefined. */
|
|
93
|
+
function str(val: unknown): string | undefined {
|
|
94
|
+
return typeof val === "string" ? val : undefined;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** Extract a non-negative integer or undefined. 0 means unlimited for max_turns. */
|
|
98
|
+
function nonNegativeInt(val: unknown): number | undefined {
|
|
99
|
+
return typeof val === "number" && val >= 0 ? val : undefined;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* Parse a raw CSV field value into items, or undefined if absent/empty/"none".
|
|
104
|
+
*/
|
|
105
|
+
function parseCsvField(val: unknown): string[] | undefined {
|
|
106
|
+
if (val === undefined || val === null) return undefined;
|
|
107
|
+
const s = String(val).trim();
|
|
108
|
+
if (!s || s === "none") return undefined;
|
|
109
|
+
const items = s.split(",").map(t => t.trim()).filter(Boolean);
|
|
110
|
+
return items.length > 0 ? items : undefined;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* Parse a comma-separated list field with defaults.
|
|
115
|
+
* omitted → defaults; "none"/empty → []; csv → listed items.
|
|
116
|
+
*/
|
|
117
|
+
function csvList(val: unknown, defaults: string[]): string[] {
|
|
118
|
+
if (val === undefined || val === null) return defaults;
|
|
119
|
+
return parseCsvField(val) ?? [];
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/**
|
|
123
|
+
* Partition the `tools:` CSV into the built-in tool allowlist and raw `ext:` selectors.
|
|
124
|
+
* `*` (and the case-insensitive alias `all`, for `tools: all`) expands to all
|
|
125
|
+
* built-ins; plain entries are built-in names; `ext:` entries are extension-tool
|
|
126
|
+
* selectors parsed later by the runner. omitted → all built-ins, no selectors.
|
|
127
|
+
* `tools:` present with only `ext:` entries → zero built-ins (use `*`).
|
|
128
|
+
*/
|
|
129
|
+
function parseToolsField(val: unknown): { builtinToolNames: string[]; extSelectors: string[] | undefined } {
|
|
130
|
+
const entries = csvList(val, BUILTIN_TOOL_NAMES);
|
|
131
|
+
const isWildcard = (e: string) => e === "*" || e.toLowerCase() === "all";
|
|
132
|
+
const hasWildcard = entries.some(isWildcard);
|
|
133
|
+
const plain = entries.filter(e => !isWildcard(e) && !e.startsWith("ext:"));
|
|
134
|
+
const extEntries = entries.filter(e => e.startsWith("ext:"));
|
|
135
|
+
return {
|
|
136
|
+
builtinToolNames: hasWildcard ? [...new Set([...BUILTIN_TOOL_NAMES, ...plain])] : plain,
|
|
137
|
+
extSelectors: extEntries.length > 0 ? extEntries : undefined,
|
|
138
|
+
};
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/**
|
|
142
|
+
* Parse an optional comma-separated list field.
|
|
143
|
+
* omitted → undefined; "none"/empty → undefined; csv → listed items.
|
|
144
|
+
*/
|
|
145
|
+
function csvListOptional(val: unknown): string[] | undefined {
|
|
146
|
+
return parseCsvField(val);
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/**
|
|
150
|
+
* Parse a memory scope field.
|
|
151
|
+
* omitted → undefined; "user"/"project"/"local" → MemoryScope.
|
|
152
|
+
*/
|
|
153
|
+
function parseMemory(val: unknown): MemoryScope | undefined {
|
|
154
|
+
if (val === "user" || val === "project" || val === "local") return val;
|
|
155
|
+
return undefined;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/**
|
|
159
|
+
* Parse an inherit field (extensions, skills).
|
|
160
|
+
* omitted/true → true (inherit all); false/"none"/empty → false; csv → listed names.
|
|
161
|
+
*/
|
|
162
|
+
function inheritField(val: unknown): true | string[] | false {
|
|
163
|
+
if (val === undefined || val === null || val === true) return true;
|
|
164
|
+
if (val === false || val === "none") return false;
|
|
165
|
+
const items = csvList(val, []);
|
|
166
|
+
return items.length > 0 ? items : false;
|
|
167
|
+
}
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* default-agents.ts — Embedded default agent configurations.
|
|
3
|
+
*
|
|
4
|
+
* These are always available but can be overridden by user .md files with the same name.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import type { AgentConfig } from "./types.js";
|
|
8
|
+
|
|
9
|
+
const READ_ONLY_TOOLS = ["read", "bash", "grep", "find", "ls"];
|
|
10
|
+
|
|
11
|
+
export const DEFAULT_AGENTS: Map<string, AgentConfig> = new Map([
|
|
12
|
+
[
|
|
13
|
+
"general-purpose",
|
|
14
|
+
{
|
|
15
|
+
name: "general-purpose",
|
|
16
|
+
displayName: "Agent",
|
|
17
|
+
description: "General-purpose agent for researching complex questions, searching for code, and executing multi-step tasks. When you are searching for a keyword or file and are not confident that you will find the right match in the first few tries use this agent to perform the search for you.",
|
|
18
|
+
// builtinToolNames omitted — means "all available tools" (resolved at lookup time)
|
|
19
|
+
// inheritContext / runInBackground / isolated omitted — strategy fields, callers decide per-call.
|
|
20
|
+
// Setting them to false would lock callsite intent (see resolveAgentInvocationConfig in invocation-config.ts).
|
|
21
|
+
extensions: true,
|
|
22
|
+
skills: true,
|
|
23
|
+
systemPrompt: "",
|
|
24
|
+
promptMode: "append",
|
|
25
|
+
isDefault: true,
|
|
26
|
+
},
|
|
27
|
+
],
|
|
28
|
+
[
|
|
29
|
+
"Explore",
|
|
30
|
+
{
|
|
31
|
+
name: "Explore",
|
|
32
|
+
displayName: "Explore",
|
|
33
|
+
description: "Fast read-only search agent for locating code. Use it to find files by pattern (eg. \"src/components/**/*.tsx\"), grep for symbols or keywords (eg. \"API endpoints\"), or answer \"where is X defined / which files reference Y.\" Do NOT use it for code review, design-doc auditing, cross-file consistency checks, or open-ended analysis — it reads excerpts rather than whole files and will miss content past its read window. When calling, specify search breadth: \"quick\" for a single targeted lookup, \"medium\" for moderate exploration, or \"very thorough\" to search across multiple locations and naming conventions.",
|
|
34
|
+
builtinToolNames: READ_ONLY_TOOLS,
|
|
35
|
+
extensions: true,
|
|
36
|
+
skills: true,
|
|
37
|
+
// Fast/cheap model for read-only search. Provider-preferred but resilient:
|
|
38
|
+
// resolveModel matches this fuzzily (date-stamp optional) and falls back to
|
|
39
|
+
// the same model under another provider if anthropic doesn't expose it.
|
|
40
|
+
model: "anthropic/claude-haiku-4-5",
|
|
41
|
+
systemPrompt: `# CRITICAL: READ-ONLY MODE - NO FILE MODIFICATIONS
|
|
42
|
+
You are a file search specialist. You excel at thoroughly navigating and exploring codebases.
|
|
43
|
+
Your role is EXCLUSIVELY to search and analyze existing code. You do NOT have access to file editing tools.
|
|
44
|
+
|
|
45
|
+
You are STRICTLY PROHIBITED from:
|
|
46
|
+
- Creating new files
|
|
47
|
+
- Modifying existing files
|
|
48
|
+
- Deleting files
|
|
49
|
+
- Moving or copying files
|
|
50
|
+
- Creating temporary files anywhere, including /tmp
|
|
51
|
+
- Using redirect operators (>, >>, |) or heredocs to write to files
|
|
52
|
+
- Running ANY commands that change system state
|
|
53
|
+
|
|
54
|
+
Use Bash ONLY for read-only operations: ls, git status, git log, git diff, find, cat, head, tail.
|
|
55
|
+
|
|
56
|
+
# Tool Usage
|
|
57
|
+
- Use the find tool for file pattern matching (NOT the bash find command)
|
|
58
|
+
- Use the grep tool for content search (NOT bash grep/rg command)
|
|
59
|
+
- Use the read tool for reading files (NOT bash cat/head/tail)
|
|
60
|
+
- Use Bash ONLY for read-only operations
|
|
61
|
+
- Make independent tool calls in parallel for efficiency
|
|
62
|
+
- Adapt search approach based on thoroughness level specified
|
|
63
|
+
|
|
64
|
+
# Output
|
|
65
|
+
- Use absolute file paths in all references
|
|
66
|
+
- Report findings as regular messages
|
|
67
|
+
- Do not use emojis
|
|
68
|
+
- Be thorough and precise`,
|
|
69
|
+
promptMode: "replace",
|
|
70
|
+
isDefault: true,
|
|
71
|
+
},
|
|
72
|
+
],
|
|
73
|
+
[
|
|
74
|
+
"Plan",
|
|
75
|
+
{
|
|
76
|
+
name: "Plan",
|
|
77
|
+
displayName: "Plan",
|
|
78
|
+
description: "Software architect agent for designing implementation plans. Use this when you need to plan the implementation strategy for a task. Returns step-by-step plans, identifies critical files, and considers architectural trade-offs.",
|
|
79
|
+
builtinToolNames: READ_ONLY_TOOLS,
|
|
80
|
+
extensions: true,
|
|
81
|
+
skills: true,
|
|
82
|
+
systemPrompt: `# CRITICAL: READ-ONLY MODE - NO FILE MODIFICATIONS
|
|
83
|
+
You are a software architect and planning specialist.
|
|
84
|
+
Your role is EXCLUSIVELY to explore the codebase and design implementation plans.
|
|
85
|
+
You do NOT have access to file editing tools — attempting to edit files will fail.
|
|
86
|
+
|
|
87
|
+
You are STRICTLY PROHIBITED from:
|
|
88
|
+
- Creating new files
|
|
89
|
+
- Modifying existing files
|
|
90
|
+
- Deleting files
|
|
91
|
+
- Moving or copying files
|
|
92
|
+
- Creating temporary files anywhere, including /tmp
|
|
93
|
+
- Using redirect operators (>, >>, |) or heredocs to write to files
|
|
94
|
+
- Running ANY commands that change system state
|
|
95
|
+
|
|
96
|
+
# Planning Process
|
|
97
|
+
1. Understand requirements
|
|
98
|
+
2. Explore thoroughly (read files, find patterns, understand architecture)
|
|
99
|
+
3. Design solution based on your assigned perspective
|
|
100
|
+
4. Detail the plan with step-by-step implementation strategy
|
|
101
|
+
|
|
102
|
+
# Requirements
|
|
103
|
+
- Consider trade-offs and architectural decisions
|
|
104
|
+
- Identify dependencies and sequencing
|
|
105
|
+
- Anticipate potential challenges
|
|
106
|
+
- Follow existing patterns where appropriate
|
|
107
|
+
|
|
108
|
+
# Tool Usage
|
|
109
|
+
- Use the find tool for file pattern matching (NOT the bash find command)
|
|
110
|
+
- Use the grep tool for content search (NOT bash grep/rg command)
|
|
111
|
+
- Use the read tool for reading files (NOT bash cat/head/tail)
|
|
112
|
+
- Use Bash ONLY for read-only operations
|
|
113
|
+
|
|
114
|
+
# Output Format
|
|
115
|
+
- Use absolute file paths
|
|
116
|
+
- Do not use emojis
|
|
117
|
+
- End your response with:
|
|
118
|
+
|
|
119
|
+
### Critical Files for Implementation
|
|
120
|
+
List 3-5 files most critical for implementing this plan:
|
|
121
|
+
- /absolute/path/to/file.ts - [Brief reason]`,
|
|
122
|
+
promptMode: "replace",
|
|
123
|
+
isDefault: true,
|
|
124
|
+
},
|
|
125
|
+
],
|
|
126
|
+
]);
|