@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,87 @@
1
+ import type { AgentSession } from "@earendil-works/pi-coding-agent";
2
+ import type { SubagentConfig } from "../subagent-config.js";
3
+ import { DoneSubagent } from "./done-subagent.js";
4
+ import { RunningSubagent } from "./running-subagent.js";
5
+
6
+ export interface QueuedSubagentParams {
7
+ id: string;
8
+ prompt: string;
9
+ description: string;
10
+ config: SubagentConfig;
11
+ session: AgentSession;
12
+ }
13
+
14
+ export interface QueuedSubagentSessionEntry {
15
+ readonly status: "queued";
16
+ readonly id: string;
17
+ readonly prompt: string;
18
+ readonly description: string;
19
+ readonly config: SubagentConfig;
20
+ readonly sessionFile: string | undefined;
21
+ }
22
+
23
+ export interface RunSubagentParams {
24
+ onUpdate: (running: RunningSubagent) => void;
25
+ onDone: (done: DoneSubagent) => void;
26
+ }
27
+
28
+ export class QueuedSubagent {
29
+ readonly status = "queued" as const;
30
+ readonly id: string;
31
+ readonly prompt: string;
32
+ readonly description: string;
33
+ readonly config: SubagentConfig;
34
+ readonly session: AgentSession;
35
+
36
+ get name() {
37
+ return this.config.name;
38
+ }
39
+
40
+ get template() {
41
+ return this.config.template;
42
+ }
43
+
44
+ constructor({ id, prompt, description, config, session }: QueuedSubagentParams) {
45
+ this.id = id;
46
+ this.prompt = prompt;
47
+ this.description = description;
48
+ this.config = config;
49
+ this.session = session;
50
+ }
51
+
52
+ abort(): DoneSubagent {
53
+ return new DoneSubagent({ instance: this, result: { status: "aborted" } });
54
+ }
55
+
56
+ error(error: unknown): DoneSubagent {
57
+ return new DoneSubagent({
58
+ instance: this,
59
+ result: {
60
+ status: "error",
61
+ error: error instanceof Error ? error.message : String(error),
62
+ },
63
+ });
64
+ }
65
+
66
+ run({ onUpdate, onDone }: RunSubagentParams): RunningSubagent {
67
+ return RunningSubagent.start({
68
+ instance: this,
69
+ prompt: this.prompt,
70
+ description: this.description,
71
+ startedAt: Date.now(),
72
+ onUpdate,
73
+ onDone,
74
+ });
75
+ }
76
+
77
+ toEntry(): QueuedSubagentSessionEntry {
78
+ return {
79
+ status: "queued",
80
+ id: this.id,
81
+ prompt: this.prompt,
82
+ description: this.description,
83
+ config: this.config,
84
+ sessionFile: this.session.sessionFile,
85
+ };
86
+ }
87
+ }
@@ -0,0 +1,224 @@
1
+ import type { AssistantMessage } from "@earendil-works/pi-ai";
2
+ import type {
3
+ AgentSession,
4
+ AgentSessionEvent,
5
+ ContextUsage,
6
+ } from "@earendil-works/pi-coding-agent";
7
+ import type { SubagentConfig } from "../subagent-config.js";
8
+ import type { DoneResult, ExceededLimit } from "./done-subagent.js";
9
+ import { DoneSubagent } from "./done-subagent.js";
10
+ import type { QueuedSubagent } from "./queued-subagent.js";
11
+
12
+ export interface StartSubgentParams {
13
+ instance: QueuedSubagent | DoneSubagent;
14
+ prompt: string;
15
+ description: string;
16
+ startedAt: number;
17
+ onUpdate: (running: RunningSubagent) => void;
18
+ onDone: (done: DoneSubagent) => void;
19
+ }
20
+
21
+ export interface RunningAgentSessionEntry {
22
+ readonly status: "running";
23
+ readonly id: string;
24
+ readonly prompt: string;
25
+ readonly description: string;
26
+ readonly config: SubagentConfig;
27
+ readonly sessionFile: string | undefined;
28
+ readonly startedAt: number;
29
+ readonly usage: ContextUsage | undefined;
30
+ readonly turns: number;
31
+ readonly steered: boolean;
32
+ readonly aborted: boolean;
33
+ readonly lastMessage: AssistantMessage | undefined;
34
+ }
35
+
36
+ interface RunningAgentState {
37
+ turn: number;
38
+ steered: boolean;
39
+ aborted: boolean;
40
+ exceededLimit: ExceededLimit | undefined;
41
+ lastMessage: AssistantMessage | undefined;
42
+ }
43
+
44
+ export class RunningSubagent {
45
+ readonly status = "running" as const;
46
+ readonly id: string;
47
+ readonly prompt: string;
48
+ readonly description: string;
49
+ readonly config: SubagentConfig;
50
+ readonly session: AgentSession;
51
+ readonly startedAt: number;
52
+
53
+ private readonly state: RunningAgentState;
54
+
55
+ get name() {
56
+ return this.config.name;
57
+ }
58
+
59
+ get template() {
60
+ return this.config.template;
61
+ }
62
+
63
+ get turn() {
64
+ return this.state.turn;
65
+ }
66
+
67
+ get steered() {
68
+ return this.state.steered;
69
+ }
70
+
71
+ get aborted() {
72
+ return this.state.aborted;
73
+ }
74
+
75
+ private constructor({
76
+ instance,
77
+ prompt,
78
+ description,
79
+ startedAt,
80
+ }: Pick<StartSubgentParams, "instance" | "prompt" | "description" | "startedAt">) {
81
+ this.id = instance.id;
82
+ this.prompt = prompt;
83
+ this.description = description;
84
+ this.config = instance.config;
85
+ this.session = instance.session;
86
+ this.startedAt = startedAt;
87
+ this.state = {
88
+ turn: 0,
89
+ steered: false,
90
+ aborted: false,
91
+ exceededLimit: undefined,
92
+ lastMessage: undefined,
93
+ };
94
+ }
95
+
96
+ static start({
97
+ instance,
98
+ prompt,
99
+ description,
100
+ startedAt,
101
+ onUpdate,
102
+ onDone,
103
+ }: StartSubgentParams): RunningSubagent {
104
+ const running = new RunningSubagent({
105
+ instance,
106
+ prompt,
107
+ description,
108
+ startedAt,
109
+ });
110
+ void running.runSession(onUpdate, onDone);
111
+ return running;
112
+ }
113
+
114
+ get duration(): number {
115
+ return Date.now() - this.startedAt;
116
+ }
117
+
118
+ async steer(message: string): Promise<RunningSubagent> {
119
+ await this.session.steer(message);
120
+ return this;
121
+ }
122
+
123
+ async abort(): Promise<DoneSubagent> {
124
+ this.state.aborted = true;
125
+ await this.session.abort();
126
+ return this.done({ status: "aborted" });
127
+ }
128
+
129
+ toEntry(): RunningAgentSessionEntry {
130
+ return {
131
+ status: "running",
132
+ id: this.id,
133
+ prompt: this.prompt,
134
+ description: this.description,
135
+ config: this.config,
136
+ sessionFile: this.session.sessionFile,
137
+ startedAt: this.startedAt,
138
+ turns: this.turn,
139
+ steered: this.steered,
140
+ aborted: this.aborted,
141
+ lastMessage: this.state.lastMessage,
142
+ usage: this.session.getContextUsage(),
143
+ };
144
+ }
145
+
146
+ private done(result: DoneResult): DoneSubagent {
147
+ return new DoneSubagent({ instance: this, result });
148
+ }
149
+
150
+ private async runSession(
151
+ onUpdate: (running: RunningSubagent) => void,
152
+ onDone: (done: DoneSubagent) => void,
153
+ ): Promise<void> {
154
+ const { session } = this;
155
+ const unsubscribe = session.subscribe(async (event: AgentSessionEvent) => {
156
+ switch (event.type) {
157
+ case "turn_end":
158
+ this.state.turn++;
159
+
160
+ if (event.message.role === "assistant") {
161
+ this.state.lastMessage = event.message;
162
+ }
163
+ if (this.config.maxTurns) {
164
+ if (
165
+ !this.state.steered &&
166
+ this.config.graceTurns > 0 &&
167
+ this.turn >= this.config.maxTurns
168
+ ) {
169
+ this.state.steered = true;
170
+ await this.steer(
171
+ "You've reached your turn limit. Wrap up immediately — provide your final / partial answer and next steps NOW. Note that the job was interrupted by usage limit and might require follow-up.",
172
+ );
173
+ } else if (this.turn >= this.config.maxTurns + this.config.graceTurns) {
174
+ this.state.exceededLimit = {
175
+ type: "turns",
176
+ maxTurns: this.config.maxTurns,
177
+ graceTurns: this.config.graceTurns,
178
+ };
179
+ this.state.aborted = true;
180
+ this.session.abort();
181
+ return;
182
+ }
183
+ }
184
+ break;
185
+ case "message_start":
186
+ case "message_update":
187
+ case "message_end":
188
+ if (event.message.role === "assistant") {
189
+ this.state.lastMessage = event.message;
190
+ }
191
+ break;
192
+ }
193
+
194
+ onUpdate(this);
195
+ });
196
+
197
+ try {
198
+ await session.prompt(this.prompt);
199
+
200
+ if (this.state.exceededLimit) {
201
+ onDone(this.done({ status: "exceeded_limit", limit: this.state.exceededLimit }));
202
+ } else if (this.state.aborted) {
203
+ onDone(this.done({ status: "aborted" }));
204
+ } else {
205
+ onDone(
206
+ this.done({
207
+ status: "completed",
208
+ message: session.getLastAssistantText() ?? "",
209
+ steered: this.state.steered,
210
+ }),
211
+ );
212
+ }
213
+ } catch (error: unknown) {
214
+ onDone(
215
+ this.done({
216
+ status: "error",
217
+ error: error instanceof Error ? error.message : String(error),
218
+ }),
219
+ );
220
+ } finally {
221
+ unsubscribe();
222
+ }
223
+ }
224
+ }
@@ -0,0 +1,13 @@
1
+ import type { ThinkingLevel } from "@earendil-works/pi-agent-core";
2
+ import type { SubagentTemplate } from "./subagent-template.js";
3
+
4
+ export interface SubagentConfig {
5
+ readonly name: string;
6
+ readonly template: SubagentTemplate;
7
+ readonly model: string | undefined;
8
+ readonly thinkingLevel: ThinkingLevel;
9
+ readonly maxTurns?: number;
10
+ readonly graceTurns: number;
11
+ readonly includedTools: string[];
12
+ readonly includedSubagents: string[];
13
+ }
@@ -0,0 +1,248 @@
1
+ import { join, resolve } from "node:path";
2
+ import type { ThinkingLevel } from "@earendil-works/pi-agent-core";
3
+ import type { Api, Model } from "@earendil-works/pi-ai";
4
+ import {
5
+ type AgentSession,
6
+ createAgentSession,
7
+ type ExtensionContext,
8
+ getAgentDir,
9
+ type ModelRegistry,
10
+ SessionManager,
11
+ SettingsManager,
12
+ } from "@earendil-works/pi-coding-agent";
13
+ import type { DoneSubagent } from "./instance/done-subagent.js";
14
+ import { QueuedSubagent } from "./instance/queued-subagent.js";
15
+ import type { SubagentConfig } from "./subagent-config.js";
16
+ import { SubagentResourceLoader } from "./subagent-resource-loader.js";
17
+ import { SubagentStore } from "./subagent-store.js";
18
+ import type { SubagentTemplate } from "./subagent-template.js";
19
+ import type {
20
+ Subagent,
21
+ SubagentByStatus,
22
+ SubagentConfigEntry,
23
+ SubagentId,
24
+ SubagentStatus,
25
+ } from "./types.js";
26
+
27
+ const DEFAULT_THINKING_LEVEL: ThinkingLevel = "medium";
28
+ const DEFAULT_GRACE_TURNS = 5;
29
+
30
+ interface SpawnParams {
31
+ id: SubagentId;
32
+ ctx: ExtensionContext;
33
+ template: SubagentTemplate;
34
+ prompt: string;
35
+ description: string;
36
+ model?: string;
37
+ thinkingLevel?: ThinkingLevel;
38
+ maxTurns?: number;
39
+ graceTurns?: number;
40
+ availableTools: string[];
41
+ signal: AbortSignal | undefined;
42
+ onUpdate: (instance: Subagent) => void;
43
+ }
44
+ interface FollowUpParams {
45
+ id: SubagentId;
46
+ prompt: string;
47
+ description: string;
48
+ signal: AbortSignal | undefined;
49
+ onUpdate: (instance: Subagent) => void;
50
+ }
51
+
52
+ type ToolCallId = string;
53
+
54
+ export class SubagentInstancesManager {
55
+ private readonly ids = new Map<ToolCallId, SubagentId>();
56
+ private readonly store: SubagentStore;
57
+
58
+ constructor(maxConcurrent: number) {
59
+ this.store = new SubagentStore({ maxConcurrent });
60
+ }
61
+
62
+ id(toolCallId: ToolCallId): SubagentId {
63
+ const existing = this.ids.get(toolCallId);
64
+ if (existing) {
65
+ return existing;
66
+ }
67
+ const id = String(this.ids.size + 1);
68
+ this.ids.set(toolCallId, id);
69
+ return id;
70
+ }
71
+
72
+ async spawn({
73
+ id,
74
+ ctx,
75
+ template,
76
+ prompt,
77
+ description,
78
+ model,
79
+ thinkingLevel,
80
+ maxTurns,
81
+ graceTurns,
82
+ availableTools,
83
+ signal,
84
+ onUpdate,
85
+ }: SpawnParams): Promise<DoneSubagent> {
86
+ if (this.store.has(id)) {
87
+ throw new Error(`Subagent with id "${id}" already exists.`);
88
+ }
89
+
90
+ const resolvedModel =
91
+ this.resolveModel(ctx.modelRegistry, model ?? template.model) ?? ctx.model;
92
+ const includedTools = this.resolveIncludedTools(template, availableTools);
93
+ const config: SubagentConfig = {
94
+ template: template,
95
+ name: template.name,
96
+ model: resolvedModel?.name,
97
+ thinkingLevel: thinkingLevel ?? template.thinkingLevel ?? DEFAULT_THINKING_LEVEL,
98
+ maxTurns: maxTurns ?? template.maxTurns,
99
+ graceTurns: graceTurns ?? template.graceTurns ?? DEFAULT_GRACE_TURNS,
100
+ includedTools: includedTools,
101
+ includedSubagents: template.includedSubagents ?? [],
102
+ };
103
+ const session = await this.createSession(ctx.cwd, config, resolvedModel);
104
+ const queued = new QueuedSubagent({
105
+ id,
106
+ prompt,
107
+ description,
108
+ config,
109
+ session,
110
+ });
111
+ onUpdate(queued);
112
+
113
+ return new Promise((resolve) => {
114
+ this.store.enqueue({
115
+ signal,
116
+ queued,
117
+ onUpdate,
118
+ onDone: resolve,
119
+ });
120
+ });
121
+ }
122
+
123
+ async followUp({
124
+ id,
125
+ prompt,
126
+ description,
127
+ signal,
128
+ onUpdate,
129
+ }: FollowUpParams): Promise<DoneSubagent> {
130
+ const instance = this.store.get(id);
131
+ if (!instance) {
132
+ throw new Error(`Unkown subagent instance with id ${id}.`);
133
+ } else if (instance.status !== "done") {
134
+ throw new Error(`Subagent with id ${id} is not done, can't follow-up yet.`);
135
+ }
136
+ const queued = instance.followUp({
137
+ prompt,
138
+ description,
139
+ });
140
+ onUpdate(queued);
141
+
142
+ return new Promise((resolve) => {
143
+ this.store.enqueue({
144
+ signal,
145
+ queued,
146
+ onUpdate,
147
+ onDone: resolve,
148
+ });
149
+ });
150
+ }
151
+
152
+ async steer(id: string, message: string): Promise<void> {
153
+ this.store.steer(id, message);
154
+ }
155
+
156
+ getInstance<TStatus extends SubagentStatus>(
157
+ id: string,
158
+ status: TStatus,
159
+ ): SubagentByStatus<TStatus> | undefined;
160
+ getInstance(id: string): Subagent | undefined;
161
+ getInstance(id: string, status?: SubagentStatus): Subagent | undefined {
162
+ const instance = this.store.get(id);
163
+ if (status && instance?.status !== status) {
164
+ return undefined;
165
+ }
166
+ return instance;
167
+ }
168
+
169
+ listInstances<TStatus extends SubagentStatus>(status: TStatus): SubagentByStatus<TStatus>[];
170
+ listInstances(): Subagent[];
171
+ listInstances(status?: SubagentStatus): Subagent[] {
172
+ const allInstances = this.store.list();
173
+ const selectedInstances = status
174
+ ? allInstances.filter((instance) => instance.status === status)
175
+ : allInstances;
176
+
177
+ // TODO: find better sorting mechanism
178
+ return selectedInstances.sort(
179
+ (instanceA, instanceB) => Number(instanceA.id) - Number(instanceB.id),
180
+ );
181
+ }
182
+
183
+ isRunning(): boolean {
184
+ const running = this.listInstances("running");
185
+ return running.length > 0;
186
+ }
187
+
188
+ private resolveModel(registry: ModelRegistry, name: string | undefined): Model<Api> | undefined {
189
+ if (!name) {
190
+ return undefined;
191
+ }
192
+ const models = registry.getAvailable();
193
+ if (!models || models.length === 0) {
194
+ return undefined;
195
+ }
196
+
197
+ const exact = models.find(
198
+ (model) => `${model.provider} / ${model.id}` === name || model.id === name,
199
+ );
200
+ if (exact) {
201
+ return exact;
202
+ }
203
+
204
+ const lower = name.toLowerCase();
205
+ return models.find(
206
+ (model) => model.id.toLowerCase().includes(lower) || model.name.toLowerCase().includes(lower),
207
+ );
208
+ }
209
+
210
+ private resolveIncludedTools(template: SubagentTemplate, availableTools: string[]): string[] {
211
+ const canSpawn = (template.includedSubagents?.length ?? 0) > 0;
212
+ const allowedTools = new Set(template.includedTools ?? availableTools);
213
+ if (!canSpawn) {
214
+ allowedTools.delete("subagent");
215
+ }
216
+ return availableTools.filter((t) => allowedTools.has(t));
217
+ }
218
+
219
+ private resolveSessionsDir(cwd: string): string {
220
+ // ~copy-paste from pi-subagent package, no API exposed to encode cwd
221
+ const resolvedCwd = resolve(cwd);
222
+ const encodedCwd = `--${resolvedCwd.replace(/^\//, "").replace(/[/\\:]/g, "-")}--`;
223
+ return join(getAgentDir(), "sessions", "subagents", encodedCwd);
224
+ }
225
+
226
+ private async createSession(
227
+ cwd: string,
228
+ config: SubagentConfig,
229
+ model: Model<Api> | undefined,
230
+ ): Promise<AgentSession> {
231
+ const sessionManager = SessionManager.create(cwd, this.resolveSessionsDir(cwd));
232
+ const resourceLoader = new SubagentResourceLoader(cwd, config);
233
+ await resourceLoader.reload();
234
+ const { session } = await createAgentSession({
235
+ cwd,
236
+ sessionManager,
237
+ settingsManager: SettingsManager.create(cwd),
238
+ model,
239
+ tools: config.includedTools,
240
+ resourceLoader,
241
+ thinkingLevel: config.thinkingLevel,
242
+ });
243
+ sessionManager.appendCustomEntry("pi-subagents:config", {
244
+ includedSubagents: config.includedSubagents ?? [],
245
+ } satisfies SubagentConfigEntry);
246
+ return session;
247
+ }
248
+ }
@@ -0,0 +1,53 @@
1
+ import {
2
+ DefaultResourceLoader,
3
+ getAgentDir,
4
+ type PromptTemplate,
5
+ type ResourceDiagnostic,
6
+ } from "@earendil-works/pi-coding-agent";
7
+ import { escapeXmlContent } from "../xml.js";
8
+ import type { SubagentConfig } from "./subagent-config.js";
9
+
10
+ export class SubagentResourceLoader extends DefaultResourceLoader {
11
+ constructor(
12
+ cwd: string,
13
+ private readonly config: SubagentConfig,
14
+ ) {
15
+ super({
16
+ cwd,
17
+ agentDir: getAgentDir(),
18
+ });
19
+ }
20
+
21
+ override getSkills() {
22
+ const { skills, diagnostics } = super.getSkills();
23
+ if (this.config.template.includedSkills) {
24
+ const includedSkill = new Set(
25
+ this.config.template.includedSkills.map((s) => s.toLowerCase()),
26
+ );
27
+ const filteredSkills = skills.filter((skill) => includedSkill.has(skill.name.toLowerCase()));
28
+ return { skills: filteredSkills, diagnostics };
29
+ }
30
+ return { skills, diagnostics };
31
+ }
32
+
33
+ override getPrompts(): {
34
+ prompts: PromptTemplate[];
35
+ diagnostics: ResourceDiagnostic[];
36
+ } {
37
+ return {
38
+ prompts: [],
39
+ diagnostics: [],
40
+ };
41
+ }
42
+
43
+ override getAppendSystemPrompt(): string[] {
44
+ const subagentSystemPropmt = [
45
+ `You're subagent "${this.config.name}":`,
46
+ `<subagent_instructions>`,
47
+ escapeXmlContent(this.config.template.instructions.trim()),
48
+ "</subagent_instructions>",
49
+ ].join("\n");
50
+
51
+ return [...super.getAppendSystemPrompt(), subagentSystemPropmt];
52
+ }
53
+ }