@piotr-oles/pi-subagents 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.
@@ -0,0 +1,208 @@
1
+ import type { DoneSubagent } from "./instance/done-subagent.js";
2
+ import type { QueuedSubagent } from "./instance/queued-subagent.js";
3
+ import type { RunningSubagent } from "./instance/running-subagent.js";
4
+ import type { Subagent, SubagentId, SubagentStatus } from "./types.js";
5
+
6
+ export interface EnqueueSubagentParams {
7
+ signal: AbortSignal | undefined;
8
+ queued: QueuedSubagent;
9
+ onUpdate: (running: RunningSubagent) => void;
10
+ onDone: (done: DoneSubagent) => void;
11
+ }
12
+
13
+ interface SubagentEntry {
14
+ instance: Subagent;
15
+ start: () => void;
16
+ steer: (message: string) => Promise<void>;
17
+ abort: () => void;
18
+ }
19
+
20
+ interface SubagentStoreParams {
21
+ maxConcurrent: number;
22
+ }
23
+
24
+ export class SubagentStore {
25
+ private readonly queued: SubagentQueue = new SubagentQueue();
26
+ private readonly running: SubagentMap = new Map();
27
+ private readonly done: SubagentMap = new Map();
28
+ private readonly maxConcurrent: number;
29
+
30
+ constructor({ maxConcurrent }: SubagentStoreParams) {
31
+ this.maxConcurrent = maxConcurrent;
32
+ }
33
+
34
+ has(id: string, status?: SubagentStatus): boolean {
35
+ switch (status) {
36
+ case "queued":
37
+ return this.queued.has(id);
38
+ case "running":
39
+ return this.running.has(id);
40
+ case "done":
41
+ return this.done.has(id);
42
+ case undefined:
43
+ return this.queued.has(id) || this.running.has(id) || this.done.has(id);
44
+ default:
45
+ return false;
46
+ }
47
+ }
48
+
49
+ get(id: string): Subagent | undefined {
50
+ return (
51
+ this.queued.get(id)?.instance ?? this.running.get(id)?.instance ?? this.done.get(id)?.instance
52
+ );
53
+ }
54
+
55
+ list(): Subagent[] {
56
+ return [
57
+ ...Array.from(this.queued.values()).map((entry) => entry.instance),
58
+ ...Array.from(this.running.values()).map((entry) => entry.instance),
59
+ ...Array.from(this.done.values()).map((entry) => entry.instance),
60
+ ];
61
+ }
62
+
63
+ async steer(id: string, message: string): Promise<void> {
64
+ const running = this.running.get(id);
65
+ if (running) {
66
+ await running.steer(message);
67
+ }
68
+ }
69
+
70
+ enqueue(params: EnqueueSubagentParams): void {
71
+ const entry: SubagentEntry = {
72
+ instance: params.queued,
73
+ start: () => {
74
+ this.queued.delete(entry.instance.id);
75
+ if (entry.instance.status !== "queued") {
76
+ throw new Error(`Cannot start non-queued (${entry.instance.status}) subagent.`);
77
+ }
78
+ entry.instance = entry.instance.run({
79
+ onUpdate: (running: RunningSubagent) => {
80
+ if (entry.instance.status !== "running") {
81
+ throw new Error(`Cannot update non-running (${entry.instance.status}) subagent.`);
82
+ }
83
+ params.onUpdate(running);
84
+ entry.instance = running;
85
+ },
86
+ onDone: (done: DoneSubagent) => {
87
+ if (entry.instance.status === "done") {
88
+ return; // noop
89
+ }
90
+ if (entry.instance.status !== "running") {
91
+ throw new Error(`Cannot mark done non-running (${entry.instance.status}) subagent.`);
92
+ }
93
+ this.running.delete(entry.instance.id);
94
+ params.onDone(done);
95
+ entry.instance = done;
96
+ this.done.set(entry.instance.id, entry);
97
+ params.signal?.removeEventListener("abort", entry.abort);
98
+ this.notify();
99
+ },
100
+ });
101
+ this.running.set(entry.instance.id, entry);
102
+ },
103
+ steer: async (message: string) => {
104
+ if (entry.instance.status !== "running") {
105
+ throw new Error("Cannot steer non-running subagent.");
106
+ }
107
+ const running = await entry.instance.steer(message);
108
+ params.onUpdate(running);
109
+ entry.instance = running;
110
+ },
111
+ abort: async () => {
112
+ if (entry.instance.status === "done") {
113
+ throw new Error("Cannot abort done subagent.");
114
+ }
115
+ this.queued.delete(entry.instance.id);
116
+ this.running.delete(entry.instance.id);
117
+ const done = await entry.instance.abort();
118
+ params.onDone(done);
119
+ entry.instance = done;
120
+ this.done.set(entry.instance.id, entry);
121
+ this.notify();
122
+ },
123
+ };
124
+ if (params.signal?.aborted) {
125
+ const done = params.queued.abort();
126
+ params.onDone(done);
127
+ entry.instance = done;
128
+ this.done.set(done.id, entry);
129
+ return;
130
+ }
131
+
132
+ params.signal?.addEventListener("abort", entry.abort, { once: true });
133
+
134
+ if (this.running.size < this.maxConcurrent) {
135
+ entry.start();
136
+ } else {
137
+ this.queued.push(entry);
138
+ }
139
+ }
140
+
141
+ private notify(): void {
142
+ while (this.running.size < this.maxConcurrent) {
143
+ const entry = this.queued.pop();
144
+ if (entry === undefined) {
145
+ break;
146
+ }
147
+ entry.start();
148
+ }
149
+ }
150
+ }
151
+
152
+ type SubagentMap = Map<SubagentId, SubagentEntry>;
153
+
154
+ // simple implementation of a queue with id lookup
155
+ class SubagentQueue {
156
+ private readonly queue: Map<SubagentId, SubagentEntry> = new Map();
157
+
158
+ get size(): number {
159
+ return this.queue.size;
160
+ }
161
+
162
+ has(id: SubagentId): boolean {
163
+ return this.queue.has(id);
164
+ }
165
+
166
+ get(id: SubagentId): SubagentEntry | undefined {
167
+ return this.queue.get(id);
168
+ }
169
+
170
+ delete(id: SubagentId): void {
171
+ this.queue.delete(id);
172
+ }
173
+
174
+ keys() {
175
+ return this.queue.keys();
176
+ }
177
+
178
+ values() {
179
+ return this.queue.values();
180
+ }
181
+
182
+ entries() {
183
+ return this.queue.entries();
184
+ }
185
+
186
+ [Symbol.iterator]() {
187
+ return this.queue[Symbol.iterator]();
188
+ }
189
+
190
+ push(entry: SubagentEntry): void {
191
+ if (this.queue.has(entry.instance.id)) {
192
+ throw new Error("Cannot push the same subagent to the queue twice.");
193
+ }
194
+ this.queue.set(entry.instance.id, entry);
195
+ }
196
+
197
+ pop(): SubagentEntry | undefined {
198
+ const iterator = this.queue[Symbol.iterator]();
199
+ // map iteration order is insertion order so it behaves like queue
200
+ const result = iterator.next();
201
+ if (result.done) {
202
+ return undefined;
203
+ }
204
+ const [id, entry] = result.value;
205
+ this.queue.delete(id);
206
+ return entry;
207
+ }
208
+ }
@@ -0,0 +1,30 @@
1
+ import type { ThinkingLevel } from "@earendil-works/pi-agent-core";
2
+
3
+ export type SubagentSource = "project" | "global";
4
+
5
+ export interface SubagentTemplate {
6
+ readonly name: string;
7
+ readonly description: string;
8
+ readonly instructions: string;
9
+ readonly includedTools: string[] | undefined;
10
+ readonly includedSkills: string[] | undefined;
11
+ readonly includedSubagents?: string[];
12
+ readonly model?: string;
13
+ readonly thinkingLevel?: ThinkingLevel;
14
+ readonly maxTurns?: number;
15
+ readonly graceTurns?: number;
16
+ readonly enabled: boolean;
17
+ readonly source: SubagentSource;
18
+ readonly filePath: string | undefined;
19
+ }
20
+
21
+ export const GENERAL_PURPOSE_TEMPLATE: SubagentTemplate = {
22
+ name: "general-purpose",
23
+ description: "General-purpose agent",
24
+ instructions: "",
25
+ enabled: true,
26
+ source: "global",
27
+ includedTools: undefined,
28
+ includedSkills: undefined,
29
+ filePath: undefined,
30
+ };
@@ -0,0 +1,183 @@
1
+ import { readdir, readFile } from "node:fs/promises";
2
+ import { basename, join } from "node:path";
3
+ import type { ThinkingLevel } from "@earendil-works/pi-agent-core";
4
+ import { getAgentDir, parseFrontmatter } from "@earendil-works/pi-coding-agent";
5
+ import type { SubagentSource, SubagentTemplate } from "./subagent-template.js";
6
+ import { GENERAL_PURPOSE_TEMPLATE } from "./subagent-template.js";
7
+ import type { SubagentName } from "./types.js";
8
+
9
+ export class SubagentTemplatesManager {
10
+ static getGlobalDir(): string {
11
+ return join(getAgentDir(), "subagents");
12
+ }
13
+
14
+ static getProjectDir(cwd: string) {
15
+ return join(cwd, ".pi", "subagents");
16
+ }
17
+
18
+ private templates = new Map<SubagentName, SubagentTemplate>();
19
+
20
+ constructor(private readonly cwd: string) {}
21
+
22
+ async reload(): Promise<void> {
23
+ this.templates.clear();
24
+
25
+ for (const [file, template] of await this.loadFromDir(
26
+ SubagentTemplatesManager.getGlobalDir(),
27
+ "global",
28
+ )) {
29
+ this.templates.set(file, template);
30
+ }
31
+ for (const [file, template] of await this.loadFromDir(
32
+ SubagentTemplatesManager.getProjectDir(this.cwd),
33
+ "project",
34
+ )) {
35
+ this.templates.set(file, template);
36
+ }
37
+ }
38
+
39
+ getTemplate(name: SubagentName): SubagentTemplate | undefined {
40
+ const key = this.resolveName(name);
41
+ if (!key) {
42
+ return undefined;
43
+ }
44
+ const template = this.templates.get(key);
45
+ return template?.enabled ? template : undefined;
46
+ }
47
+
48
+ getTemplateOrDefault(name: SubagentName): SubagentTemplate {
49
+ return (
50
+ this.getTemplate(name) ?? this.getTemplate("general-purpose") ?? GENERAL_PURPOSE_TEMPLATE
51
+ );
52
+ }
53
+
54
+ listTemplates(): SubagentTemplate[] {
55
+ return Array.from(this.templates.values()).sort(
56
+ (templateA, templateB) => this.scoreTemplate(templateB) - this.scoreTemplate(templateA),
57
+ );
58
+ }
59
+
60
+ private scoreTemplate(template: SubagentTemplate): number {
61
+ if (template.enabled) {
62
+ return template.source === "project" ? 3 : 2;
63
+ } else {
64
+ return template.source === "project" ? 1 : 0;
65
+ }
66
+ }
67
+
68
+ private resolveName(name: string): SubagentName | undefined {
69
+ if (this.templates.has(name)) {
70
+ return name;
71
+ }
72
+ const lower = name.toLowerCase();
73
+ for (const key of this.templates.keys()) {
74
+ if (key.toLowerCase() === lower) {
75
+ return key;
76
+ }
77
+ }
78
+ return undefined;
79
+ }
80
+
81
+ private async loadFromDir(
82
+ dir: string,
83
+ source: SubagentSource,
84
+ ): Promise<Map<SubagentName, SubagentTemplate>> {
85
+ const templates = new Map<SubagentName, SubagentTemplate>();
86
+
87
+ let files: string[];
88
+ try {
89
+ files = (await readdir(dir)).filter((file) => file.endsWith(".md"));
90
+ } catch {
91
+ return templates;
92
+ }
93
+
94
+ const read = await Promise.all(
95
+ files.map(async (file) => {
96
+ const filePath = join(dir, file);
97
+
98
+ try {
99
+ const content = await readFile(filePath, "utf-8");
100
+ return { filePath, content };
101
+ } catch {
102
+ return { filePath, content: undefined };
103
+ }
104
+ }),
105
+ );
106
+
107
+ for (const { filePath, content } of read) {
108
+ if (!content) {
109
+ continue;
110
+ }
111
+ const name = basename(filePath, ".md");
112
+ try {
113
+ templates.set(name, parseTemplateFile(filePath, name, content, source));
114
+ } catch (error) {
115
+ // TODO: report it
116
+ }
117
+ }
118
+
119
+ return templates;
120
+ }
121
+ }
122
+
123
+ function parseTemplateFile(
124
+ filePath: string,
125
+ name: string,
126
+ content: string,
127
+ source: SubagentSource,
128
+ ): SubagentTemplate {
129
+ const { frontmatter: fm, body } = parseFrontmatter(content);
130
+ return {
131
+ name: parseString(fm.name) || name,
132
+ description: parseString(fm.description) ?? name,
133
+ includedTools: parseCsvField(fm.included_tools),
134
+ includedSkills: parseCsvField(fm.included_skills),
135
+ includedSubagents: parseCsvField(fm.included_subagents),
136
+ model: parseString(fm.model),
137
+ thinkingLevel: parseThinkingLevel(fm.thinking),
138
+ maxTurns: parseNonNegativeInt(fm.max_turns),
139
+ graceTurns: parseNonNegativeInt(fm.grace_turns),
140
+ instructions: body.trim(),
141
+ enabled: fm.enabled !== false,
142
+ source,
143
+ filePath,
144
+ };
145
+ }
146
+
147
+ const THINKING_LEVELS: ReadonlySet<ThinkingLevel> = new Set([
148
+ "off",
149
+ "minimal",
150
+ "low",
151
+ "medium",
152
+ "high",
153
+ "xhigh",
154
+ ]);
155
+
156
+ function isThinkingLevel(value: string): value is ThinkingLevel {
157
+ return THINKING_LEVELS.has(value as ThinkingLevel);
158
+ }
159
+
160
+ function parseThinkingLevel(value: unknown): ThinkingLevel | undefined {
161
+ const str = parseString(value);
162
+ return str !== undefined && isThinkingLevel(str) ? str : undefined;
163
+ }
164
+
165
+ function parseString(value: unknown): string | undefined {
166
+ return typeof value === "string" ? value : undefined;
167
+ }
168
+
169
+ function parseNonNegativeInt(value: unknown): number | undefined {
170
+ return typeof value === "number" && value >= 0 ? value : undefined;
171
+ }
172
+
173
+ function parseCsvField(value: unknown): string[] | undefined {
174
+ const str = parseString(value)?.trim();
175
+ if (!str || str === "none") {
176
+ return undefined;
177
+ }
178
+ const items = str
179
+ .split(",")
180
+ .map((item) => item.trim())
181
+ .filter(Boolean);
182
+ return items.length > 0 ? items : undefined;
183
+ }
@@ -0,0 +1,26 @@
1
+ import type { DoneSubagent, DoneSubagentSessionEntry } from "./instance/done-subagent.js";
2
+ import type { QueuedSubagent, QueuedSubagentSessionEntry } from "./instance/queued-subagent.js";
3
+ import type { RunningAgentSessionEntry, RunningSubagent } from "./instance/running-subagent.js";
4
+
5
+ export type SubagentName = string;
6
+ export type SubagentId = string;
7
+
8
+ export type Subagent = QueuedSubagent | RunningSubagent | DoneSubagent;
9
+ export type SubagentStatus = Subagent["status"];
10
+ export type SubagentByStatus<TStatus extends SubagentStatus> =
11
+ TStatus extends QueuedSubagent["status"]
12
+ ? QueuedSubagent
13
+ : TStatus extends RunningSubagent["status"]
14
+ ? RunningSubagent
15
+ : TStatus extends DoneSubagent["status"]
16
+ ? DoneSubagent
17
+ : never;
18
+
19
+ export type SubagentSessionEntry =
20
+ | QueuedSubagentSessionEntry
21
+ | RunningAgentSessionEntry
22
+ | DoneSubagentSessionEntry;
23
+
24
+ export interface SubagentConfigEntry {
25
+ includedSubagents: string[];
26
+ }
package/src/flags.ts ADDED
@@ -0,0 +1,14 @@
1
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
+
3
+ export function registerFlags(pi: ExtensionAPI): void {
4
+ pi.registerFlag("pi-subagents-max-concurrent", {
5
+ type: "string",
6
+ description: "Max subagents running concurrently (default: 4).",
7
+ default: "4",
8
+ });
9
+ }
10
+
11
+ export function getMaxConcurrent(pi: ExtensionAPI): number {
12
+ const val = Number(pi.getFlag("pi-subagents-max-concurrent"));
13
+ return Number.isInteger(val) && val >= 1 ? val : 4;
14
+ }
package/src/format.ts ADDED
@@ -0,0 +1,48 @@
1
+ import { homedir } from "node:os";
2
+ import type { ContextUsage } from "@earendil-works/pi-coding-agent";
3
+
4
+ export function formatUsage(usage: ContextUsage | undefined): string {
5
+ const formatted = formatSi(usage?.tokens ?? 0);
6
+ if (usage?.percent) {
7
+ return `${formatted} (${usage.percent.toFixed(1)}%)`;
8
+ }
9
+ return `${formatted}`;
10
+ }
11
+
12
+ const SI_THRESHOLDS: { value: number; suffix: string }[] = [
13
+ { value: 1e18, suffix: "E" },
14
+ { value: 1e15, suffix: "P" },
15
+ { value: 1e12, suffix: "T" },
16
+ { value: 1e9, suffix: "G" },
17
+ { value: 1e6, suffix: "M" },
18
+ { value: 1e3, suffix: "K" },
19
+ ];
20
+
21
+ export function formatSi(n: number, precision = 1): string {
22
+ for (const { value, suffix } of SI_THRESHOLDS) {
23
+ if (Math.abs(n) >= value) {
24
+ return `${(n / value).toFixed(precision)}${suffix}`;
25
+ }
26
+ }
27
+ return String(n);
28
+ }
29
+
30
+ export function formatDuration(ms: number): string {
31
+ return ms >= 60_000
32
+ ? `${Math.floor(ms / 60_000)}m${Math.floor((ms % 60_000) / 1000)}s`
33
+ : `${(ms / 1000).toFixed(1)}s`;
34
+ }
35
+
36
+ export function formatFilePath(absPath: string): string {
37
+ const home = homedir();
38
+ return absPath.startsWith(home) ? `~${absPath.slice(home.length)}` : absPath;
39
+ }
40
+
41
+ export function getFirstLine(text: string): string {
42
+ const trimmedText = text.trim();
43
+ const firstLineText = trimmedText.includes("\n")
44
+ ? trimmedText.slice(0, trimmedText.indexOf("\n"))
45
+ : trimmedText;
46
+
47
+ return firstLineText;
48
+ }
package/src/index.ts ADDED
@@ -0,0 +1,76 @@
1
+ import type { CustomEntry, ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
+ import { showSubagentTemplatesMenu as showSubagentTemplates } from "./commands/subagent-templates-menu.js";
3
+ import { SubagentInstancesManager } from "./domain/subagent-instances-manager.js";
4
+ import type { SubagentTemplate } from "./domain/subagent-template.js";
5
+ import { SubagentTemplatesManager } from "./domain/subagent-templates-manager.js";
6
+ import type { SubagentConfigEntry } from "./domain/types.js";
7
+ import { getMaxConcurrent, registerFlags } from "./flags.js";
8
+ import { createSubagentTool } from "./tools/subagent-tool.js";
9
+ import { escapeXmlContent } from "./xml.js";
10
+
11
+ export default async function piSubagents(pi: ExtensionAPI): Promise<void> {
12
+ registerFlags(pi);
13
+
14
+ const templatesManager = new SubagentTemplatesManager(process.cwd());
15
+ await templatesManager.reload();
16
+ const instanceManager = new SubagentInstancesManager(getMaxConcurrent(pi));
17
+
18
+ pi.registerTool(createSubagentTool({ pi, instanceManager, templatesManager }));
19
+
20
+ pi.registerCommand("subagent:templates", {
21
+ description: "List available subagent templates",
22
+ handler: async (_args, ctx) => {
23
+ await showSubagentTemplates(ctx, templatesManager);
24
+ },
25
+ });
26
+
27
+ pi.on("before_agent_start", async (event, ctx) => {
28
+ await templatesManager.reload();
29
+
30
+ const entries = ctx.sessionManager.getEntries();
31
+ const configEntry = entries.find(
32
+ (e): e is CustomEntry<SubagentConfigEntry> =>
33
+ e.type === "custom" && e.customType === "pi-subagents:config",
34
+ );
35
+
36
+ let allowedTemplates = templatesManager.listTemplates();
37
+ if (configEntry) {
38
+ const includedSubagents = new Set(configEntry.data?.includedSubagents ?? []);
39
+ allowedTemplates = allowedTemplates.filter((template) =>
40
+ includedSubagents.has(template.name),
41
+ );
42
+ }
43
+ const enabledTemplates = allowedTemplates.filter((template) => template.enabled);
44
+
45
+ if (enabledTemplates.length > 0) {
46
+ return {
47
+ systemPrompt: `${event.systemPrompt}\n\n${subagentsSystemPrompt(enabledTemplates)}`,
48
+ };
49
+ }
50
+ });
51
+ }
52
+
53
+ function subagentsSystemPrompt(templates: SubagentTemplate[]): string {
54
+ return [
55
+ "Subagents:",
56
+ "Your context window is limited, when possible delegate tasks to subagents using `subagent` tool.",
57
+ buildSubagentsXml(templates),
58
+ ].join("\n");
59
+ }
60
+
61
+ function buildSubagentsXml(templates: SubagentTemplate[]): string {
62
+ return [
63
+ "<available_subagents>",
64
+ templates
65
+ .map((template) =>
66
+ [
67
+ ` <subagent>`,
68
+ ` <name>${escapeXmlContent(template.name)}</name>`,
69
+ ` <description>${escapeXmlContent(template.description)}</description>`,
70
+ ` </subagent>`,
71
+ ].join("\n"),
72
+ )
73
+ .join("\n"),
74
+ "</available_subagents>",
75
+ ].join("\n");
76
+ }
@@ -0,0 +1,62 @@
1
+ import type { AgentSession } from "@earendil-works/pi-coding-agent";
2
+ import { type Completion, ScriptedSession, type Step } from "./scripted-session.js";
3
+
4
+ /**
5
+ * Fluent builder for ScriptedSession.
6
+ *
7
+ * The builder owns the steeringLog array so assertions can be made against
8
+ * the builder after the session has run:
9
+ *
10
+ * const builder = new ScriptedSessionBuilder().turns(5).complete("done");
11
+ * await run(builder.build(), { maxTurns: 5 });
12
+ * expect(builder.steeredMessages[0]).toContain("turn limit");
13
+ */
14
+ export class ScriptedSessionBuilder {
15
+ private readonly steps: Step[] = [];
16
+ private completion: Completion = { kind: "complete", text: "" };
17
+ private readonly steeringLog: string[] = [];
18
+
19
+ turns(n: number): this {
20
+ for (let i = 0; i < n; i++) {
21
+ this.steps.push({ kind: "turn" });
22
+ }
23
+ return this;
24
+ }
25
+
26
+ turn(): this {
27
+ this.steps.push({ kind: "turn" });
28
+ return this;
29
+ }
30
+
31
+ sideEffect(run: () => void): this {
32
+ this.steps.push({ kind: "side-effect", run });
33
+ return this;
34
+ }
35
+
36
+ event(eventType: string): this {
37
+ this.steps.push({ kind: "event", eventType });
38
+ return this;
39
+ }
40
+
41
+ complete(text = ""): this {
42
+ this.completion = { kind: "complete", text };
43
+ return this;
44
+ }
45
+
46
+ fail(message: string): this {
47
+ this.completion = { kind: "error", message };
48
+ return this;
49
+ }
50
+
51
+ build(): AgentSession {
52
+ return new ScriptedSession(
53
+ [...this.steps],
54
+ this.completion,
55
+ this.steeringLog,
56
+ ) as unknown as AgentSession;
57
+ }
58
+
59
+ get steeredMessages(): readonly string[] {
60
+ return [...this.steeringLog];
61
+ }
62
+ }