@aoshizuku/pi-subagent 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.md +173 -2
- package/agents/explore.md +20 -0
- package/agents/general.md +17 -0
- package/package.json +55 -5
- package/src/batcher.ts +77 -0
- package/src/child.ts +212 -0
- package/src/cleanup.ts +40 -0
- package/src/config.ts +181 -0
- package/src/detail.ts +408 -0
- package/src/focus.ts +240 -0
- package/src/hud-state.ts +183 -0
- package/src/index.ts +1013 -0
- package/src/list.ts +223 -0
- package/src/manager.ts +588 -0
- package/src/models.ts +80 -0
- package/src/observer.ts +275 -0
- package/src/prompts.ts +103 -0
- package/src/render.ts +592 -0
- package/src/result.ts +226 -0
- package/src/run.ts +204 -0
- package/src/settings.ts +140 -0
- package/src/shizuku-settings.ts +92 -0
- package/src/stop-confirm.ts +47 -0
- package/src/test-helpers.ts +194 -0
- package/src/tool-line.ts +85 -0
- package/src/types.ts +257 -0
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
// Two-step stop (docs/07 §4.4): the first x arms the selected agent, a second x on it stops it. Shared by
|
|
2
|
+
// the /agents list, the detail overlay and HUD focus mode, each with its own instance.
|
|
3
|
+
//
|
|
4
|
+
// The arm belongs to an agent id, never to a row index: the lists re-sort every second, and a second x must
|
|
5
|
+
// not land on whatever agent moved into the armed row. It is dropped as soon as that agent is no longer the
|
|
6
|
+
// selected, stoppable one.
|
|
7
|
+
|
|
8
|
+
export const ARMED_HINT = "press x again to stop · any other key cancels";
|
|
9
|
+
|
|
10
|
+
export class StopConfirm {
|
|
11
|
+
private armed: string | undefined;
|
|
12
|
+
|
|
13
|
+
/** `enabled` is read on every press, so turning the option off applies to the next x. */
|
|
14
|
+
constructor(private readonly enabled: () => boolean) {}
|
|
15
|
+
|
|
16
|
+
get armedId(): string | undefined {
|
|
17
|
+
return this.armed;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
isArmed(id: string | undefined): boolean {
|
|
21
|
+
return id !== undefined && this.armed === id;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** x on a stoppable agent. True: stop it now. False: it is armed and waits for the second x. */
|
|
25
|
+
press(id: string): boolean {
|
|
26
|
+
if (!this.enabled() || this.armed === id) {
|
|
27
|
+
this.armed = undefined;
|
|
28
|
+
return true;
|
|
29
|
+
}
|
|
30
|
+
this.armed = id;
|
|
31
|
+
return false;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** Disarm; true when something was armed. */
|
|
35
|
+
cancel(): boolean {
|
|
36
|
+
if (this.armed === undefined) return false;
|
|
37
|
+
this.armed = undefined;
|
|
38
|
+
return true;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** Keep the arm only while `selectedId` is the armed agent and it can still be stopped. True when it disarmed. */
|
|
42
|
+
keep(selectedId: string | undefined, stoppable: boolean): boolean {
|
|
43
|
+
if (this.armed === undefined || (this.armed === selectedId && stoppable)) return false;
|
|
44
|
+
this.armed = undefined;
|
|
45
|
+
return true;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
// Test doubles: a scriptable child session and factory, so no test calls a model.
|
|
2
|
+
|
|
3
|
+
import type { AgentSessionEvent } from "@earendil-works/pi-coding-agent";
|
|
4
|
+
|
|
5
|
+
import type { ContextUsageLike } from "./observer.js";
|
|
6
|
+
import type { ChildSession, ChildSessionFactory, ChildSpec } from "./run.js";
|
|
7
|
+
import type { AgentType } from "./types.js";
|
|
8
|
+
|
|
9
|
+
type Listener = (event: AgentSessionEvent) => void;
|
|
10
|
+
|
|
11
|
+
export interface FakeTurn {
|
|
12
|
+
text?: string;
|
|
13
|
+
/** Tool calls made in this turn; the turn then ends with stopReason "toolUse". */
|
|
14
|
+
tools?: Array<{ name: string; args?: Record<string, unknown> }>;
|
|
15
|
+
stopReason?: "stop" | "length" | "error" | "aborted";
|
|
16
|
+
errorMessage?: string;
|
|
17
|
+
usage?: { input: number; output: number; cacheRead?: number; cacheWrite?: number; cost?: number };
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export type FakeScript = (session: FakeSession, task: string) => Promise<void>;
|
|
21
|
+
|
|
22
|
+
export function assistantMessage(turn: FakeTurn): Record<string, unknown> {
|
|
23
|
+
const content: Array<Record<string, unknown>> = [];
|
|
24
|
+
if (turn.text) content.push({ type: "text", text: turn.text });
|
|
25
|
+
for (const [index, tool] of (turn.tools ?? []).entries()) {
|
|
26
|
+
content.push({ type: "toolCall", id: `call-${index}`, name: tool.name, arguments: tool.args ?? {} });
|
|
27
|
+
}
|
|
28
|
+
const usage = turn.usage ?? { input: 10, output: 5 };
|
|
29
|
+
return {
|
|
30
|
+
role: "assistant",
|
|
31
|
+
content,
|
|
32
|
+
stopReason: turn.tools?.length ? "toolUse" : (turn.stopReason ?? "stop"),
|
|
33
|
+
errorMessage: turn.errorMessage,
|
|
34
|
+
usage: {
|
|
35
|
+
input: usage.input,
|
|
36
|
+
output: usage.output,
|
|
37
|
+
cacheRead: usage.cacheRead ?? 0,
|
|
38
|
+
cacheWrite: usage.cacheWrite ?? 0,
|
|
39
|
+
cost: { total: usage.cost ?? 0 },
|
|
40
|
+
},
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export class FakeSession implements ChildSession {
|
|
45
|
+
sessionFile: string | undefined;
|
|
46
|
+
model: string | undefined = "faux/faux-1";
|
|
47
|
+
readonly messages: unknown[] = [];
|
|
48
|
+
readonly steered: Array<{ customType: string; content: string }> = [];
|
|
49
|
+
readonly userSteers: string[] = [];
|
|
50
|
+
aborts = 0;
|
|
51
|
+
disposed = false;
|
|
52
|
+
prompts: string[] = [];
|
|
53
|
+
private listeners: Listener[] = [];
|
|
54
|
+
private abortWaiters: Array<() => void> = [];
|
|
55
|
+
private abortRequested = false;
|
|
56
|
+
/** When true, abort() never resolves (a hung provider request). */
|
|
57
|
+
hangOnAbort = false;
|
|
58
|
+
/** What contextUsage() returns; undefined like a model without a known context window. */
|
|
59
|
+
context: ContextUsageLike | undefined;
|
|
60
|
+
|
|
61
|
+
constructor(
|
|
62
|
+
private readonly script: FakeScript = async (session) => session.turn({ text: "done" }),
|
|
63
|
+
sessionFile?: string,
|
|
64
|
+
) {
|
|
65
|
+
this.sessionFile = sessionFile;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
contextUsage(): ContextUsageLike | undefined {
|
|
69
|
+
return this.context;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
subscribe(listener: Listener): () => void {
|
|
73
|
+
this.listeners.push(listener);
|
|
74
|
+
return () => {
|
|
75
|
+
this.listeners = this.listeners.filter((entry) => entry !== listener);
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
emit(event: Record<string, unknown>): void {
|
|
80
|
+
for (const listener of [...this.listeners]) listener(event as unknown as AgentSessionEvent);
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
async prompt(text: string): Promise<void> {
|
|
84
|
+
this.prompts.push(text);
|
|
85
|
+
this.messages.push({ role: "user", content: [{ type: "text", text }] });
|
|
86
|
+
this.emit({ type: "agent_start" });
|
|
87
|
+
await this.script(this, text);
|
|
88
|
+
this.emit({ type: "agent_end", messages: this.messages, willRetry: false });
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** One full turn: message events, tool execution events, turn_end. */
|
|
92
|
+
async turn(turn: FakeTurn): Promise<void> {
|
|
93
|
+
this.emit({ type: "turn_start" });
|
|
94
|
+
const message = assistantMessage(turn);
|
|
95
|
+
this.emit({ type: "message_start", message: { role: "assistant", content: [] } });
|
|
96
|
+
if (turn.text) {
|
|
97
|
+
this.emit({ type: "message_update", message, assistantMessageEvent: { type: "text_delta", delta: turn.text } });
|
|
98
|
+
}
|
|
99
|
+
this.messages.push(message);
|
|
100
|
+
this.emit({ type: "message_end", message });
|
|
101
|
+
for (const [index, tool] of (turn.tools ?? []).entries()) {
|
|
102
|
+
this.emit({ type: "tool_execution_start", toolCallId: `call-${index}`, toolName: tool.name, args: tool.args ?? {} });
|
|
103
|
+
this.emit({ type: "tool_execution_end", toolCallId: `call-${index}`, toolName: tool.name, result: {}, isError: false });
|
|
104
|
+
}
|
|
105
|
+
this.emit({ type: "turn_end", message, toolResults: [] });
|
|
106
|
+
await Promise.resolve();
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** Resolves once abort() is called; then records an aborted, empty assistant message like pi does. */
|
|
110
|
+
waitForAbort(): Promise<void> {
|
|
111
|
+
if (this.abortRequested) return Promise.resolve();
|
|
112
|
+
return new Promise((resolve) => this.abortWaiters.push(resolve));
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
get isAbortRequested(): boolean {
|
|
116
|
+
return this.abortRequested;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
async abort(): Promise<void> {
|
|
120
|
+
this.aborts += 1;
|
|
121
|
+
this.abortRequested = true;
|
|
122
|
+
for (const resolve of this.abortWaiters.splice(0)) resolve();
|
|
123
|
+
if (this.hangOnAbort) await new Promise(() => {});
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
steer(customType: string, content: string): void {
|
|
127
|
+
this.steered.push({ customType, content });
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
async steerUser(text: string): Promise<void> {
|
|
131
|
+
this.userSteers.push(text);
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
dispose(): void {
|
|
135
|
+
this.disposed = true;
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/** Script: keep making tool calls until aborted, then leave pi's aborted stub. */
|
|
140
|
+
export const runUntilAborted: FakeScript = async (session) => {
|
|
141
|
+
while (!session.isAbortRequested) {
|
|
142
|
+
await session.turn({ text: "still working", tools: [{ name: "read", args: { path: "a.ts" } }] });
|
|
143
|
+
await new Promise((resolve) => setTimeout(resolve, 1));
|
|
144
|
+
}
|
|
145
|
+
session.messages.push(assistantMessage({ stopReason: "aborted" }));
|
|
146
|
+
};
|
|
147
|
+
|
|
148
|
+
/** Script: block until aborted. */
|
|
149
|
+
export const blockUntilAborted: FakeScript = async (session) => {
|
|
150
|
+
await session.waitForAbort();
|
|
151
|
+
session.messages.push(assistantMessage({ stopReason: "aborted" }));
|
|
152
|
+
};
|
|
153
|
+
|
|
154
|
+
export class FakeFactory implements ChildSessionFactory {
|
|
155
|
+
readonly specs: ChildSpec[] = [];
|
|
156
|
+
readonly sessions: FakeSession[] = [];
|
|
157
|
+
failWith: Error | undefined;
|
|
158
|
+
|
|
159
|
+
constructor(private readonly makeScript: (spec: ChildSpec) => FakeScript = () => async (session) => session.turn({ text: "done" })) {}
|
|
160
|
+
|
|
161
|
+
async create(spec: ChildSpec): Promise<FakeSession> {
|
|
162
|
+
this.specs.push(spec);
|
|
163
|
+
if (this.failWith) throw this.failWith;
|
|
164
|
+
const file = spec.resumeFile ?? (spec.sessionDir ? `${spec.sessionDir}/child-${spec.agentId}.jsonl` : undefined);
|
|
165
|
+
const session = new FakeSession(this.makeScript(spec), file);
|
|
166
|
+
this.sessions.push(session);
|
|
167
|
+
return session;
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
export function testType(overrides: Partial<AgentType> = {}): AgentType {
|
|
172
|
+
return {
|
|
173
|
+
name: "general",
|
|
174
|
+
description: "General",
|
|
175
|
+
tools: ["read", "bash"],
|
|
176
|
+
maxTurns: 60,
|
|
177
|
+
contextLimit: 70,
|
|
178
|
+
contextFiles: true,
|
|
179
|
+
skills: false,
|
|
180
|
+
background: false,
|
|
181
|
+
body: "",
|
|
182
|
+
source: "builtin",
|
|
183
|
+
path: "general.md",
|
|
184
|
+
...overrides,
|
|
185
|
+
};
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
export function testSpec(overrides: Partial<ChildSpec> = {}): ChildSpec {
|
|
189
|
+
return { agentId: "ag-1", description: "test", type: testType(), cwd: process.cwd(), ...overrides };
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
export async function flush(times = 5): Promise<void> {
|
|
193
|
+
for (let i = 0; i < times; i++) await new Promise((resolve) => setTimeout(resolve, 0));
|
|
194
|
+
}
|
package/src/tool-line.ts
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
// One-line summary of a child tool call, e.g. `Read (src/auth.ts:40-120)` (docs/07 §1.2, §8).
|
|
2
|
+
// Mirrors pi-bettertui's tool rows (pi-bettertui src/tool-summary.ts callDetail).
|
|
3
|
+
|
|
4
|
+
import { isAbsolute, relative } from "node:path";
|
|
5
|
+
|
|
6
|
+
const LABELS: Record<string, string> = {
|
|
7
|
+
read: "Read",
|
|
8
|
+
bash: "Bash",
|
|
9
|
+
powershell: "PowerShell",
|
|
10
|
+
edit: "Edit",
|
|
11
|
+
write: "Write",
|
|
12
|
+
grep: "Grep",
|
|
13
|
+
find: "Find",
|
|
14
|
+
ls: "LS",
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
const SHELL_MAX = 40;
|
|
18
|
+
const DETAIL_MAX = 60;
|
|
19
|
+
|
|
20
|
+
export function toolLabel(name: string): string {
|
|
21
|
+
return LABELS[name] ?? name;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export function toolLine(name: string, args: unknown, cwd?: string): string {
|
|
25
|
+
const detail = toolDetail(name, isRecord(args) ? args : {}, cwd);
|
|
26
|
+
return detail ? `${toolLabel(name)} (${detail})` : toolLabel(name);
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export function toolDetail(name: string, args: Record<string, unknown>, cwd?: string): string {
|
|
30
|
+
const path = displayPath(str(args.file_path ?? args.path), cwd);
|
|
31
|
+
switch (name) {
|
|
32
|
+
case "read": {
|
|
33
|
+
const offset = num(args.offset);
|
|
34
|
+
const limit = num(args.limit);
|
|
35
|
+
if (offset === undefined) return path;
|
|
36
|
+
return `${path}:${offset}${limit !== undefined ? `-${offset + limit - 1}` : ""}`;
|
|
37
|
+
}
|
|
38
|
+
case "edit":
|
|
39
|
+
case "write":
|
|
40
|
+
return path;
|
|
41
|
+
case "bash":
|
|
42
|
+
case "powershell":
|
|
43
|
+
return clip(oneLine(str(args.command)), SHELL_MAX);
|
|
44
|
+
case "grep": {
|
|
45
|
+
const pattern = str(args.pattern);
|
|
46
|
+
return pattern ? clip(`/${pattern}/${path ? ` in ${path}` : ""}`, DETAIL_MAX) : path;
|
|
47
|
+
}
|
|
48
|
+
case "find": {
|
|
49
|
+
const pattern = str(args.pattern);
|
|
50
|
+
return clip(pattern && path ? `${pattern} in ${path}` : pattern || path, DETAIL_MAX);
|
|
51
|
+
}
|
|
52
|
+
case "ls":
|
|
53
|
+
return path || ".";
|
|
54
|
+
default:
|
|
55
|
+
return "";
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function displayPath(path: string, cwd: string | undefined): string {
|
|
60
|
+
if (!path || !cwd || !isAbsolute(path)) return path;
|
|
61
|
+
const rel = relative(cwd, path);
|
|
62
|
+
return rel && !rel.startsWith("..") && !isAbsolute(rel) ? rel.replace(/\\/g, "/") : path;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function oneLine(text: string): string {
|
|
66
|
+
const lines = text.replace(/\r\n?/g, "\n").trim().split("\n");
|
|
67
|
+
const head = (lines[0] ?? "").trim();
|
|
68
|
+
return lines.length > 1 ? `${head} …` : head;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export function clip(text: string, max: number): string {
|
|
72
|
+
return text.length > max ? `${text.slice(0, max - 1)}…` : text;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function str(value: unknown): string {
|
|
76
|
+
return typeof value === "string" ? value : "";
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function num(value: unknown): number | undefined {
|
|
80
|
+
return typeof value === "number" && Number.isFinite(value) ? value : undefined;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
84
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
85
|
+
}
|
package/src/types.ts
ADDED
|
@@ -0,0 +1,257 @@
|
|
|
1
|
+
// Agent type discovery: built-in, user and project markdown files with YAML frontmatter (docs/04).
|
|
2
|
+
|
|
3
|
+
import { readdirSync, readFileSync } from "node:fs";
|
|
4
|
+
import { basename, join } from "node:path";
|
|
5
|
+
import { fileURLToPath } from "node:url";
|
|
6
|
+
|
|
7
|
+
import { parseFrontmatter } from "@earendil-works/pi-coding-agent";
|
|
8
|
+
|
|
9
|
+
import {
|
|
10
|
+
CONTEXT_LIMIT_MAX,
|
|
11
|
+
CONTEXT_LIMIT_MIN,
|
|
12
|
+
isContextLimit,
|
|
13
|
+
isMaxTurns,
|
|
14
|
+
isThinkingLevel,
|
|
15
|
+
type SubagentConfig,
|
|
16
|
+
type ThinkingLevel,
|
|
17
|
+
} from "./config.js";
|
|
18
|
+
|
|
19
|
+
/** pi's built-in tools (pi/packages/coding-agent/src/core/tools/index.ts:95). Types may only pick from these. */
|
|
20
|
+
export const BUILTIN_TOOLS = ["read", "bash", "powershell", "edit", "write", "grep", "find", "ls"] as const;
|
|
21
|
+
export const DEFAULT_TYPE_TOOLS = ["read", "bash", "edit", "write", "grep", "find", "ls"];
|
|
22
|
+
/** A safeguard against runaway loops; the context limit is what normally ends a long run (docs/02 §9). */
|
|
23
|
+
export const DEFAULT_MAX_TURNS = 300;
|
|
24
|
+
/** Percent of the context window at which the subagent is told to write its report (docs/02 §9). */
|
|
25
|
+
export const DEFAULT_CONTEXT_LIMIT = 70;
|
|
26
|
+
export const DEFAULT_TYPE = "general";
|
|
27
|
+
|
|
28
|
+
const NAME_PATTERN = /^[a-z0-9][a-z0-9_-]*$/;
|
|
29
|
+
|
|
30
|
+
export type TypeSource = "builtin" | "user" | "project";
|
|
31
|
+
|
|
32
|
+
export interface AgentType {
|
|
33
|
+
/** Lower-case name; lookups are case-insensitive. */
|
|
34
|
+
name: string;
|
|
35
|
+
description: string;
|
|
36
|
+
tools: string[];
|
|
37
|
+
model?: string;
|
|
38
|
+
thinking?: ThinkingLevel;
|
|
39
|
+
maxTurns: number;
|
|
40
|
+
/** Percent of the context window that starts the wrap-up. */
|
|
41
|
+
contextLimit: number;
|
|
42
|
+
contextFiles: boolean;
|
|
43
|
+
skills: boolean;
|
|
44
|
+
/** Default for the `background` call parameter (docs/04 §2). */
|
|
45
|
+
background: boolean;
|
|
46
|
+
/** Role text appended to the child's system prompt (may be empty). */
|
|
47
|
+
body: string;
|
|
48
|
+
source: TypeSource;
|
|
49
|
+
path: string;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export interface TypeDirs {
|
|
53
|
+
builtinDir: string;
|
|
54
|
+
userDir: string;
|
|
55
|
+
/** `<cwd>/.pi/agents`; read only when the project is trusted. */
|
|
56
|
+
projectDir: string;
|
|
57
|
+
projectTrusted: boolean;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export interface LoadedTypes {
|
|
61
|
+
types: Map<string, AgentType>;
|
|
62
|
+
warnings: string[];
|
|
63
|
+
/** Project type files skipped because the project is not trusted. */
|
|
64
|
+
skippedProject: number;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export function builtinAgentsDir(): string {
|
|
68
|
+
return fileURLToPath(new URL("../agents/", import.meta.url));
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** Load all layers (built-in < user < project) and apply the config overrides. */
|
|
72
|
+
export function loadAgentTypes(dirs: TypeDirs, config?: SubagentConfig): LoadedTypes {
|
|
73
|
+
const types = new Map<string, AgentType>();
|
|
74
|
+
const warnings: string[] = [];
|
|
75
|
+
let skippedProject = 0;
|
|
76
|
+
|
|
77
|
+
const layers: Array<[TypeSource, string]> = [
|
|
78
|
+
["builtin", dirs.builtinDir],
|
|
79
|
+
["user", dirs.userDir],
|
|
80
|
+
];
|
|
81
|
+
if (dirs.projectTrusted) layers.push(["project", dirs.projectDir]);
|
|
82
|
+
else skippedProject = listMarkdown(dirs.projectDir).length;
|
|
83
|
+
|
|
84
|
+
for (const [source, dir] of layers) {
|
|
85
|
+
for (const path of listMarkdown(dir)) {
|
|
86
|
+
const result = parseTypeFile(path, source);
|
|
87
|
+
for (const warning of result.warnings) warnings.push(`${path}: ${warning}`);
|
|
88
|
+
if (result.kind === "skip") continue;
|
|
89
|
+
if (result.kind === "disable") {
|
|
90
|
+
types.delete(result.name);
|
|
91
|
+
continue;
|
|
92
|
+
}
|
|
93
|
+
types.set(result.type.name, result.type);
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
if (config) {
|
|
98
|
+
for (const [name, override] of Object.entries(config.types)) {
|
|
99
|
+
const type = types.get(name);
|
|
100
|
+
if (!type) {
|
|
101
|
+
warnings.push(`pi-subagent.json: types.${name} does not match any loaded agent type`);
|
|
102
|
+
continue;
|
|
103
|
+
}
|
|
104
|
+
types.set(name, {
|
|
105
|
+
...type,
|
|
106
|
+
model: override.model ?? type.model,
|
|
107
|
+
thinking: override.thinking ?? type.thinking,
|
|
108
|
+
maxTurns: override.maxTurns ?? type.maxTurns,
|
|
109
|
+
contextLimit: override.contextLimit ?? type.contextLimit,
|
|
110
|
+
});
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
return { types, warnings, skippedProject };
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
export function lookupType(types: ReadonlyMap<string, AgentType>, name: string | undefined): AgentType | undefined {
|
|
118
|
+
return types.get((name?.trim() || DEFAULT_TYPE).toLowerCase());
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
type ParseResult =
|
|
122
|
+
| { kind: "type"; type: AgentType; warnings: string[] }
|
|
123
|
+
| { kind: "disable"; name: string; warnings: string[] }
|
|
124
|
+
| { kind: "skip"; warnings: string[] };
|
|
125
|
+
|
|
126
|
+
export function parseTypeFile(path: string, source: TypeSource): ParseResult {
|
|
127
|
+
let content: string;
|
|
128
|
+
try {
|
|
129
|
+
content = readFileSync(path, "utf8");
|
|
130
|
+
} catch (error) {
|
|
131
|
+
return { kind: "skip", warnings: [`cannot read file (${(error as Error).message}); skipped`] };
|
|
132
|
+
}
|
|
133
|
+
return parseTypeContent(content, path, source);
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
export function parseTypeContent(content: string, path: string, source: TypeSource): ParseResult {
|
|
137
|
+
const warnings: string[] = [];
|
|
138
|
+
let frontmatter: Record<string, unknown>;
|
|
139
|
+
let body: string;
|
|
140
|
+
try {
|
|
141
|
+
({ frontmatter, body } = parseFrontmatter<Record<string, unknown>>(content));
|
|
142
|
+
} catch (error) {
|
|
143
|
+
return { kind: "skip", warnings: [`invalid frontmatter (${(error as Error).message}); skipped`] };
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
const rawName = typeof frontmatter.name === "string" && frontmatter.name.trim() ? frontmatter.name : basename(path, ".md");
|
|
147
|
+
const name = rawName.trim().toLowerCase();
|
|
148
|
+
if (!NAME_PATTERN.test(name)) {
|
|
149
|
+
return { kind: "skip", warnings: [`invalid name "${rawName}" (allowed: [a-z0-9][a-z0-9_-]*); skipped`] };
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
const enabled = optionalBoolean(frontmatter, "enabled", warnings);
|
|
153
|
+
if (enabled === false) return { kind: "disable", name, warnings };
|
|
154
|
+
|
|
155
|
+
const description = typeof frontmatter.description === "string" ? frontmatter.description.replace(/\s+/g, " ").trim() : "";
|
|
156
|
+
if (!description) return { kind: "skip", warnings: [...warnings, "missing description; skipped"] };
|
|
157
|
+
|
|
158
|
+
let tools = DEFAULT_TYPE_TOOLS;
|
|
159
|
+
if (frontmatter.tools !== undefined) {
|
|
160
|
+
const parsed = parseTools(frontmatter.tools);
|
|
161
|
+
if (typeof parsed === "string") return { kind: "skip", warnings: [...warnings, `${parsed}; skipped`] };
|
|
162
|
+
tools = parsed;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
let model: string | undefined;
|
|
166
|
+
if (frontmatter.model !== undefined) {
|
|
167
|
+
if (typeof frontmatter.model === "string" && frontmatter.model.trim()) model = frontmatter.model.trim();
|
|
168
|
+
else warnings.push("model must be a non-empty string; ignored");
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
let thinking: ThinkingLevel | undefined;
|
|
172
|
+
if (frontmatter.thinking !== undefined) {
|
|
173
|
+
if (isThinkingLevel(frontmatter.thinking)) thinking = frontmatter.thinking;
|
|
174
|
+
else warnings.push(`invalid thinking "${String(frontmatter.thinking)}"; ignored`);
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
let maxTurns = DEFAULT_MAX_TURNS;
|
|
178
|
+
if (frontmatter.max_turns !== undefined) {
|
|
179
|
+
if (isMaxTurns(frontmatter.max_turns)) maxTurns = frontmatter.max_turns;
|
|
180
|
+
else warnings.push(`max_turns must be an integer >= 2; using ${DEFAULT_MAX_TURNS}`);
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
let contextLimit = DEFAULT_CONTEXT_LIMIT;
|
|
184
|
+
if (frontmatter.context_limit !== undefined) {
|
|
185
|
+
if (isContextLimit(frontmatter.context_limit)) contextLimit = frontmatter.context_limit;
|
|
186
|
+
else warnings.push(`context_limit must be an integer from ${CONTEXT_LIMIT_MIN} to ${CONTEXT_LIMIT_MAX}; using ${DEFAULT_CONTEXT_LIMIT}`);
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
const type: AgentType = {
|
|
190
|
+
name,
|
|
191
|
+
description,
|
|
192
|
+
tools,
|
|
193
|
+
model,
|
|
194
|
+
thinking,
|
|
195
|
+
maxTurns,
|
|
196
|
+
contextLimit,
|
|
197
|
+
contextFiles: optionalBoolean(frontmatter, "context_files", warnings) ?? true,
|
|
198
|
+
skills: optionalBoolean(frontmatter, "skills", warnings) ?? false,
|
|
199
|
+
background: optionalBoolean(frontmatter, "background", warnings) ?? false,
|
|
200
|
+
body: body.trim(),
|
|
201
|
+
source,
|
|
202
|
+
path,
|
|
203
|
+
};
|
|
204
|
+
return { kind: "type", type, warnings };
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
const TOOL_NAME = /^[a-z][a-z0-9_]*$/;
|
|
208
|
+
|
|
209
|
+
/**
|
|
210
|
+
* Comma-separated string or YAML list; "none" means no tools. Names other than pi's built-in tools are
|
|
211
|
+
* extension tools: they become active only when an extension in `childExtensions` registers them
|
|
212
|
+
* (docs/04 §4), so listing one never loads code by itself.
|
|
213
|
+
*/
|
|
214
|
+
function parseTools(value: unknown): string[] | string {
|
|
215
|
+
let entries: string[];
|
|
216
|
+
if (typeof value === "string") entries = value.split(",");
|
|
217
|
+
else if (Array.isArray(value) && value.every((item) => typeof item === "string")) entries = value as string[];
|
|
218
|
+
else return "tools must be a comma-separated string or a list";
|
|
219
|
+
const names = entries.map((entry) => entry.trim().toLowerCase()).filter(Boolean);
|
|
220
|
+
if (names.length === 1 && names[0] === "none") return [];
|
|
221
|
+
const invalid = names.filter((name) => !TOOL_NAME.test(name));
|
|
222
|
+
if (invalid.length > 0) return `invalid tool names: ${invalid.join(", ")}`;
|
|
223
|
+
return [...new Set(names)];
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
/** Tools a child actually gets: built-ins, plus extension tools that an allowlisted extension registered. */
|
|
227
|
+
export function activeChildTools(typeTools: readonly string[], extensionTools: readonly string[]): string[] {
|
|
228
|
+
return typeTools.filter((name) => (BUILTIN_TOOLS as readonly string[]).includes(name) || extensionTools.includes(name));
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
function optionalBoolean(frontmatter: Record<string, unknown>, key: string, warnings: string[]): boolean | undefined {
|
|
232
|
+
const value = frontmatter[key];
|
|
233
|
+
if (value === undefined) return undefined;
|
|
234
|
+
if (typeof value === "boolean") return value;
|
|
235
|
+
warnings.push(`${key} must be true or false; ignored`);
|
|
236
|
+
return undefined;
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
function listMarkdown(dir: string): string[] {
|
|
240
|
+
try {
|
|
241
|
+
return readdirSync(dir, { withFileTypes: true })
|
|
242
|
+
.filter((entry) => entry.isFile() && entry.name.toLowerCase().endsWith(".md"))
|
|
243
|
+
.map((entry) => join(dir, entry.name))
|
|
244
|
+
.sort();
|
|
245
|
+
} catch {
|
|
246
|
+
return [];
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
/**
|
|
251
|
+
* Windows: `general` follows the parent's shell. When the parent has `powershell` active, the built-in
|
|
252
|
+
* `general` gets `powershell` in place of `bash` (docs/04 §3.2).
|
|
253
|
+
*/
|
|
254
|
+
export function effectiveTools(type: AgentType, parentActiveTools: readonly string[]): string[] {
|
|
255
|
+
if (type.name !== "general" || type.source !== "builtin" || !parentActiveTools.includes("powershell")) return type.tools;
|
|
256
|
+
return [...new Set(type.tools.map((tool) => (tool === "bash" ? "powershell" : tool)))];
|
|
257
|
+
}
|