@piotr-oles/pi-subagents 0.2.0 → 1.0.1

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@piotr-oles/pi-subagents",
3
- "version": "0.2.0",
3
+ "version": "1.0.1",
4
4
  "description": "Pi Agent extension: spawn specialized subagents with isolated sessions",
5
5
  "repository": {
6
6
  "type": "git",
@@ -24,6 +24,14 @@
24
24
  "./src/index.ts"
25
25
  ]
26
26
  },
27
+ "scripts": {
28
+ "test": "vitest run",
29
+ "test:watch": "vitest",
30
+ "typecheck": "tsc --noEmit",
31
+ "check": "biome ci src/",
32
+ "fix": "biome check --write src/",
33
+ "release": "semantic-release -e semantic-release-monorepo"
34
+ },
27
35
  "peerDependencies": {
28
36
  "@earendil-works/pi-agent-core": "*",
29
37
  "@earendil-works/pi-coding-agent": "*"
@@ -38,12 +46,5 @@
38
46
  "typebox": "^1.1.38",
39
47
  "typescript": "^5.8.3",
40
48
  "vitest": "^3.2.1"
41
- },
42
- "scripts": {
43
- "test": "vitest run",
44
- "test:watch": "vitest",
45
- "typecheck": "tsc --noEmit",
46
- "check": "biome ci src/",
47
- "fix": "biome check --write src/"
48
49
  }
49
- }
50
+ }
@@ -25,7 +25,7 @@ export class SubagentTemplatesListComponent implements Component {
25
25
 
26
26
  handleInput(data: string): void {
27
27
  const kb = getKeybindings();
28
- const { rows } = this;
28
+ const rows = this.rows;
29
29
 
30
30
  if (kb.matches(data, "tui.select.up")) {
31
31
  rows[this.selectedIndex]?.setSelected(false);
@@ -47,13 +47,13 @@ export class SubagentTemplatesListComponent implements Component {
47
47
 
48
48
  render(width: number): string[] {
49
49
  const lines: string[] = [];
50
- const { rows, maxVisible } = this;
50
+ const rows = this.rows;
51
51
 
52
52
  const startIndex = Math.max(
53
53
  0,
54
- Math.min(this.selectedIndex - Math.floor(maxVisible / 2), rows.length - maxVisible),
54
+ Math.min(this.selectedIndex - Math.floor(this.maxVisible / 2), rows.length - this.maxVisible),
55
55
  );
56
- const endIndex = Math.min(startIndex + maxVisible, rows.length);
56
+ const endIndex = Math.min(startIndex + this.maxVisible, rows.length);
57
57
 
58
58
  for (let i = startIndex; i < endIndex; i++) {
59
59
  const row = rows[i];
@@ -0,0 +1 @@
1
+ export const SUBAGENT_INIT_ENTRY_TYPE = "pi-subagents:init";
@@ -48,12 +48,8 @@ export class DoneSubagent {
48
48
  readonly session: AgentSession;
49
49
  readonly turns: number;
50
50
 
51
- get name() {
52
- return this.config.name;
53
- }
54
-
55
- get template() {
56
- return this.config.template;
51
+ get name(): string {
52
+ return this.config.template.name;
57
53
  }
58
54
 
59
55
  get duration(): number {
@@ -34,11 +34,7 @@ export class QueuedSubagent {
34
34
  readonly session: AgentSession;
35
35
 
36
36
  get name() {
37
- return this.config.name;
38
- }
39
-
40
- get template() {
41
- return this.config.template;
37
+ return this.config.template.name;
42
38
  }
43
39
 
44
40
  constructor({ id, prompt, description, config, session }: QueuedSubagentParams) {
@@ -9,7 +9,7 @@ import type { DoneResult, ExceededLimit } from "./done-subagent.js";
9
9
  import { DoneSubagent } from "./done-subagent.js";
10
10
  import type { QueuedSubagent } from "./queued-subagent.js";
11
11
 
12
- export interface StartSubgentParams {
12
+ export interface StartSubagentParams {
13
13
  instance: QueuedSubagent | DoneSubagent;
14
14
  prompt: string;
15
15
  description: string;
@@ -53,11 +53,7 @@ export class RunningSubagent {
53
53
  private readonly state: RunningAgentState;
54
54
 
55
55
  get name() {
56
- return this.config.name;
57
- }
58
-
59
- get template() {
60
- return this.config.template;
56
+ return this.config.template.name;
61
57
  }
62
58
 
63
59
  get turn() {
@@ -77,7 +73,7 @@ export class RunningSubagent {
77
73
  prompt,
78
74
  description,
79
75
  startedAt,
80
- }: Pick<StartSubgentParams, "instance" | "prompt" | "description" | "startedAt">) {
76
+ }: Pick<StartSubagentParams, "instance" | "prompt" | "description" | "startedAt">) {
81
77
  this.id = instance.id;
82
78
  this.prompt = prompt;
83
79
  this.description = description;
@@ -100,7 +96,7 @@ export class RunningSubagent {
100
96
  startedAt,
101
97
  onUpdate,
102
98
  onDone,
103
- }: StartSubgentParams): RunningSubagent {
99
+ }: StartSubagentParams): RunningSubagent {
104
100
  const running = new RunningSubagent({
105
101
  instance,
106
102
  prompt,
@@ -151,8 +147,12 @@ export class RunningSubagent {
151
147
  onUpdate: (running: RunningSubagent) => void,
152
148
  onDone: (done: DoneSubagent) => void,
153
149
  ): Promise<void> {
154
- const { session } = this;
150
+ const session = this.session;
155
151
  const unsubscribe = session.subscribe(async (event: AgentSessionEvent) => {
152
+ if (this.state.aborted) {
153
+ return;
154
+ }
155
+
156
156
  switch (event.type) {
157
157
  case "turn_end":
158
158
  this.state.turn++;
@@ -1,8 +1,11 @@
1
1
  import type { ThinkingLevel } from "@earendil-works/pi-agent-core";
2
2
  import type { SubagentTemplate } from "./subagent-template.js";
3
3
 
4
+ export interface SubagentEntry {
5
+ readonly config: SubagentConfig;
6
+ }
7
+
4
8
  export interface SubagentConfig {
5
- readonly name: string;
6
9
  readonly template: SubagentTemplate;
7
10
  readonly model: string | undefined;
8
11
  readonly thinkingLevel: ThinkingLevel;
@@ -6,23 +6,18 @@ import {
6
6
  createAgentSession,
7
7
  type ExtensionContext,
8
8
  getAgentDir,
9
- type ModelRegistry,
10
9
  SessionManager,
11
10
  SettingsManager,
12
11
  } from "@earendil-works/pi-coding-agent";
12
+ import { SUBAGENT_INIT_ENTRY_TYPE } from "../constants.js";
13
13
  import type { DoneSubagent } from "./instance/done-subagent.js";
14
14
  import { QueuedSubagent } from "./instance/queued-subagent.js";
15
- import type { SubagentConfig } from "./subagent-config.js";
15
+ import type { SubagentConfig, SubagentEntry } from "./subagent-config.js";
16
+ import { buildModelKey, findModel } from "./subagent-model.js";
16
17
  import { SubagentResourceLoader } from "./subagent-resource-loader.js";
17
18
  import { SubagentStore } from "./subagent-store.js";
18
19
  import type { SubagentTemplate } from "./subagent-template.js";
19
- import type {
20
- Subagent,
21
- SubagentByStatus,
22
- SubagentConfigEntry,
23
- SubagentId,
24
- SubagentStatus,
25
- } from "./types.js";
20
+ import type { Subagent, SubagentByStatus, SubagentId, SubagentStatus } from "./types.js";
26
21
 
27
22
  const DEFAULT_THINKING_LEVEL: ThinkingLevel = "medium";
28
23
  const DEFAULT_GRACE_TURNS = 5;
@@ -87,13 +82,11 @@ export class SubagentInstancesManager {
87
82
  throw new Error(`Subagent with id "${id}" already exists.`);
88
83
  }
89
84
 
90
- const resolvedModel =
91
- this.resolveModel(ctx.modelRegistry, model ?? template.model) ?? ctx.model;
85
+ const resolvedModel = findModel(ctx.modelRegistry, model ?? template.model) ?? ctx.model;
92
86
  const includedTools = this.resolveIncludedTools(template, availableTools);
93
87
  const config: SubagentConfig = {
94
88
  template: template,
95
- name: template.name,
96
- model: resolvedModel?.name,
89
+ model: resolvedModel ? buildModelKey(resolvedModel.provider, resolvedModel.id) : undefined,
97
90
  thinkingLevel: thinkingLevel ?? template.thinkingLevel ?? DEFAULT_THINKING_LEVEL,
98
91
  maxTurns: maxTurns ?? template.maxTurns,
99
92
  graceTurns: graceTurns ?? template.graceTurns ?? DEFAULT_GRACE_TURNS,
@@ -129,7 +122,7 @@ export class SubagentInstancesManager {
129
122
  }: FollowUpParams): Promise<DoneSubagent> {
130
123
  const instance = this.store.get(id);
131
124
  if (!instance) {
132
- throw new Error(`Unkown subagent instance with id ${id}.`);
125
+ throw new Error(`Unknown subagent instance with id ${id}.`);
133
126
  } else if (instance.status !== "done") {
134
127
  throw new Error(`Subagent with id ${id} is not done, can't follow-up yet.`);
135
128
  }
@@ -185,28 +178,6 @@ export class SubagentInstancesManager {
185
178
  return running.length > 0;
186
179
  }
187
180
 
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
181
  private resolveIncludedTools(template: SubagentTemplate, availableTools: string[]): string[] {
211
182
  const canSpawn = (template.includedSubagents?.length ?? 0) > 0;
212
183
  const allowedTools = new Set(template.includedTools ?? availableTools);
@@ -217,7 +188,9 @@ export class SubagentInstancesManager {
217
188
  }
218
189
 
219
190
  private resolveSessionsDir(cwd: string): string {
220
- // ~copy-paste from pi-subagent package, no API exposed to encode cwd
191
+ // TODO: pi-coding-agent doesn't expose a public API for cwd encoding.
192
+ // This mirrors the internal implementation. If that changes, subagent sessions become orphaned.
193
+ // Track: expose a stable encodeSessionCwd() API upstream.
221
194
  const resolvedCwd = resolve(cwd);
222
195
  const encodedCwd = `--${resolvedCwd.replace(/^\//, "").replace(/[/\\:]/g, "-")}--`;
223
196
  return join(getAgentDir(), "sessions", "subagents", encodedCwd);
@@ -240,9 +213,9 @@ export class SubagentInstancesManager {
240
213
  resourceLoader,
241
214
  thinkingLevel: config.thinkingLevel,
242
215
  });
243
- sessionManager.appendCustomEntry("pi-subagents:config", {
244
- includedSubagents: config.includedSubagents ?? [],
245
- } satisfies SubagentConfigEntry);
216
+ sessionManager.appendCustomEntry(SUBAGENT_INIT_ENTRY_TYPE, {
217
+ config,
218
+ } satisfies SubagentEntry);
246
219
  return session;
247
220
  }
248
221
  }
@@ -0,0 +1,31 @@
1
+ import type { Api, Model } from "@earendil-works/pi-ai";
2
+ import type { ModelRegistry } from "@earendil-works/pi-coding-agent";
3
+
4
+ export function buildModelKey(provider: string, id: string): string {
5
+ return `${provider} / ${id}`;
6
+ }
7
+
8
+ export function findModel(
9
+ registry: ModelRegistry,
10
+ name: string | undefined,
11
+ ): Model<Api> | undefined {
12
+ if (!name) {
13
+ return undefined;
14
+ }
15
+ const models = registry.getAvailable();
16
+ if (!models || models.length === 0) {
17
+ return undefined;
18
+ }
19
+
20
+ const exact = models.find(
21
+ (model) => buildModelKey(model.provider, model.id) === name || model.id === name,
22
+ );
23
+ if (exact) {
24
+ return exact;
25
+ }
26
+
27
+ const lower = name.toLowerCase();
28
+ return models.find(
29
+ (model) => model.id.toLowerCase().includes(lower) || model.name.toLowerCase().includes(lower),
30
+ );
31
+ }
@@ -4,7 +4,6 @@ import {
4
4
  type PromptTemplate,
5
5
  type ResourceDiagnostic,
6
6
  } from "@earendil-works/pi-coding-agent";
7
- import { escapeXmlContent } from "../xml.js";
8
7
  import type { SubagentConfig } from "./subagent-config.js";
9
8
 
10
9
  export class SubagentResourceLoader extends DefaultResourceLoader {
@@ -39,15 +38,4 @@ export class SubagentResourceLoader extends DefaultResourceLoader {
39
38
  diagnostics: [],
40
39
  };
41
40
  }
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
41
  }
@@ -78,17 +78,14 @@ export class SubagentStore {
78
78
  entry.instance = entry.instance.run({
79
79
  onUpdate: (running: RunningSubagent) => {
80
80
  if (entry.instance.status !== "running") {
81
- throw new Error(`Cannot update non-running (${entry.instance.status}) subagent.`);
81
+ return;
82
82
  }
83
83
  params.onUpdate(running);
84
84
  entry.instance = running;
85
85
  },
86
86
  onDone: (done: DoneSubagent) => {
87
- if (entry.instance.status === "done") {
88
- return; // noop
89
- }
90
87
  if (entry.instance.status !== "running") {
91
- throw new Error(`Cannot mark done non-running (${entry.instance.status}) subagent.`);
88
+ return;
92
89
  }
93
90
  this.running.delete(entry.instance.id);
94
91
  params.onDone(done);
@@ -8,23 +8,12 @@ export interface SubagentTemplate {
8
8
  readonly instructions: string;
9
9
  readonly includedTools: string[] | undefined;
10
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;
11
+ readonly includedSubagents: string[] | undefined;
12
+ readonly model: string | undefined;
13
+ readonly thinkingLevel: ThinkingLevel | undefined;
14
+ readonly maxTurns: number | undefined;
15
+ readonly graceTurns: number | undefined;
16
16
  readonly enabled: boolean;
17
17
  readonly source: SubagentSource;
18
18
  readonly filePath: string | undefined;
19
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
- };
@@ -3,7 +3,6 @@ import { basename, join } from "node:path";
3
3
  import type { ThinkingLevel } from "@earendil-works/pi-agent-core";
4
4
  import { getAgentDir, parseFrontmatter } from "@earendil-works/pi-coding-agent";
5
5
  import type { SubagentSource, SubagentTemplate } from "./subagent-template.js";
6
- import { GENERAL_PURPOSE_TEMPLATE } from "./subagent-template.js";
7
6
  import type { SubagentName } from "./types.js";
8
7
 
9
8
  export class SubagentTemplatesManager {
@@ -16,6 +15,7 @@ export class SubagentTemplatesManager {
16
15
  }
17
16
 
18
17
  private templates = new Map<SubagentName, SubagentTemplate>();
18
+ private enabled: Set<SubagentName> | null = null;
19
19
 
20
20
  constructor(private readonly cwd: string) {}
21
21
 
@@ -36,19 +36,23 @@ export class SubagentTemplatesManager {
36
36
  }
37
37
  }
38
38
 
39
+ setEnabledTemplates(names: SubagentName[] | null): void {
40
+ this.enabled = names ? new Set(names) : null;
41
+ }
42
+
39
43
  getTemplate(name: SubagentName): SubagentTemplate | undefined {
40
44
  const key = this.resolveName(name);
41
45
  if (!key) {
42
46
  return undefined;
43
47
  }
44
48
  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
- );
49
+ if (!template?.enabled) {
50
+ return undefined;
51
+ }
52
+ if (this.enabled !== null && !this.enabled.has(template.name)) {
53
+ return undefined;
54
+ }
55
+ return template;
52
56
  }
53
57
 
54
58
  listTemplates(): SubagentTemplate[] {
@@ -57,6 +61,12 @@ export class SubagentTemplatesManager {
57
61
  );
58
62
  }
59
63
 
64
+ listEnabledTemplates(): SubagentTemplate[] {
65
+ return this.listTemplates().filter(
66
+ (t) => t.enabled && (this.enabled === null || this.enabled.has(t.name)),
67
+ );
68
+ }
69
+
60
70
  private scoreTemplate(template: SubagentTemplate): number {
61
71
  if (template.enabled) {
62
72
  return template.source === "project" ? 3 : 2;
@@ -111,7 +121,7 @@ export class SubagentTemplatesManager {
111
121
  const name = basename(filePath, ".md");
112
122
  try {
113
123
  templates.set(name, parseTemplateFile(filePath, name, content, source));
114
- } catch (error) {
124
+ } catch (_error) {
115
125
  // TODO: report it
116
126
  }
117
127
  }
@@ -130,9 +140,9 @@ function parseTemplateFile(
130
140
  return {
131
141
  name: parseString(fm.name) || name,
132
142
  description: parseString(fm.description) ?? name,
133
- includedTools: parseCsvField(fm.included_tools),
134
- includedSkills: parseCsvField(fm.included_skills),
135
- includedSubagents: parseCsvField(fm.included_subagents),
143
+ includedTools: parseStringsArrayField(fm.included_tools),
144
+ includedSkills: parseStringsArrayField(fm.included_skills),
145
+ includedSubagents: parseStringsArrayField(fm.included_subagents),
136
146
  model: parseString(fm.model),
137
147
  thinkingLevel: parseThinkingLevel(fm.thinking),
138
148
  maxTurns: parseNonNegativeInt(fm.max_turns),
@@ -167,10 +177,25 @@ function parseString(value: unknown): string | undefined {
167
177
  }
168
178
 
169
179
  function parseNonNegativeInt(value: unknown): number | undefined {
170
- return typeof value === "number" && value >= 0 ? value : undefined;
180
+ if (typeof value === "number" && value >= 0) {
181
+ return value;
182
+ }
183
+ if (typeof value === "string") {
184
+ const n = Number(value.trim());
185
+ if (Number.isInteger(n) && n >= 0) {
186
+ return n;
187
+ }
188
+ }
189
+ return undefined;
171
190
  }
172
191
 
173
- function parseCsvField(value: unknown): string[] | undefined {
192
+ function parseStringsArrayField(value: unknown): string[] | undefined {
193
+ if (Array.isArray(value)) {
194
+ const items = value
195
+ .map((item) => (typeof item === "string" ? item.trim() : ""))
196
+ .filter(Boolean);
197
+ return items.length > 0 ? items : undefined;
198
+ }
174
199
  const str = parseString(value)?.trim();
175
200
  if (!str || str === "none") {
176
201
  return undefined;
@@ -20,7 +20,3 @@ export type SubagentSessionEntry =
20
20
  | QueuedSubagentSessionEntry
21
21
  | RunningAgentSessionEntry
22
22
  | DoneSubagentSessionEntry;
23
-
24
- export interface SubagentConfigEntry {
25
- includedSubagents: string[];
26
- }
package/src/index.ts CHANGED
@@ -1,12 +1,13 @@
1
- import type { CustomEntry, ExtensionAPI } from "@earendil-works/pi-coding-agent";
1
+ import type { CustomEntry, ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
2
2
  import { showSubagentTemplatesMenu as showSubagentTemplates } from "./commands/subagent-templates-menu.js";
3
+ import { SUBAGENT_INIT_ENTRY_TYPE } from "./constants.js";
4
+ import type { SubagentConfig, SubagentEntry } from "./domain/subagent-config.js";
3
5
  import { SubagentInstancesManager } from "./domain/subagent-instances-manager.js";
4
- import type { SubagentTemplate } from "./domain/subagent-template.js";
6
+ import { buildModelKey } from "./domain/subagent-model.js";
5
7
  import { SubagentTemplatesManager } from "./domain/subagent-templates-manager.js";
6
- import type { SubagentConfigEntry } from "./domain/types.js";
7
8
  import { getMaxConcurrent, registerFlags } from "./flags.js";
9
+ import { updateAgentSystemPropmt, updateSubagentSystemPrompt } from "./system-prompt.js";
8
10
  import { createSubagentTool } from "./tools/subagent-tool.js";
9
- import { escapeXmlContent } from "./xml.js";
10
11
 
11
12
  export default async function piSubagents(pi: ExtensionAPI): Promise<void> {
12
13
  registerFlags(pi);
@@ -24,53 +25,85 @@ export default async function piSubagents(pi: ExtensionAPI): Promise<void> {
24
25
  },
25
26
  });
26
27
 
28
+ pi.on("session_start", async (_event, ctx) => {
29
+ const config = readSubagentConfig(ctx);
30
+ if (config) {
31
+ await applySubagentConfig(pi, ctx, templatesManager, config);
32
+ }
33
+ });
34
+
27
35
  pi.on("before_agent_start", async (event, ctx) => {
28
36
  await templatesManager.reload();
29
37
 
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);
38
+ const config = readSubagentConfig(ctx);
44
39
 
45
- if (enabledTemplates.length > 0) {
40
+ if (config) {
41
+ await applySubagentConfig(pi, ctx, templatesManager, config);
42
+ const enabledTemplates = templatesManager.listEnabledTemplates();
46
43
  return {
47
- systemPrompt: `${event.systemPrompt}\n\n${subagentsSystemPrompt(enabledTemplates)}`,
44
+ systemPrompt: updateSubagentSystemPrompt(
45
+ event.systemPrompt,
46
+ enabledTemplates,
47
+ config.template,
48
+ ),
48
49
  };
49
50
  }
51
+
52
+ const enabledTemplates = templatesManager.listEnabledTemplates();
53
+ if (enabledTemplates.length === 0) {
54
+ return undefined;
55
+ }
56
+ return {
57
+ systemPrompt: updateAgentSystemPropmt(event.systemPrompt, enabledTemplates),
58
+ };
50
59
  });
51
60
  }
52
61
 
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");
62
+ function readSubagentConfig(ctx: ExtensionContext): SubagentConfig | undefined {
63
+ const entries = ctx.sessionManager.getEntries();
64
+ const initEntry = entries.find(
65
+ (e): e is CustomEntry<SubagentEntry> =>
66
+ e.type === "custom" && e.customType === SUBAGENT_INIT_ENTRY_TYPE,
67
+ );
68
+ return initEntry?.data?.config;
69
+ }
70
+
71
+ async function applySubagentConfig(
72
+ pi: ExtensionAPI,
73
+ ctx: ExtensionContext,
74
+ templatesManager: SubagentTemplatesManager,
75
+ config: SubagentConfig,
76
+ ): Promise<void> {
77
+ const currentTools = pi.getActiveTools();
78
+ const desiredTools = config.includedTools;
79
+ if (!areSetsEqual(currentTools, desiredTools)) {
80
+ pi.setActiveTools(desiredTools);
81
+ }
82
+
83
+ if (pi.getThinkingLevel() !== config.thinkingLevel) {
84
+ pi.setThinkingLevel(config.thinkingLevel);
85
+ }
86
+
87
+ if (config.model) {
88
+ const currentModelKey = ctx.model ? buildModelKey(ctx.model.provider, ctx.model.id) : undefined;
89
+ if (currentModelKey !== config.model) {
90
+ const models = ctx.modelRegistry.getAvailable();
91
+ const model = models?.find(
92
+ (m) => buildModelKey(m.provider, m.id) === config.model || m.id === config.model,
93
+ );
94
+ if (model) {
95
+ await pi.setModel(model);
96
+ }
97
+ }
98
+ }
99
+
100
+ templatesManager.setEnabledTemplates(config.includedSubagents);
59
101
  }
60
102
 
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");
103
+ function areSetsEqual(a: string[], b: string[]): boolean {
104
+ if (a.length !== b.length) {
105
+ return false;
106
+ }
107
+ const setA = new Set(a);
108
+ return b.every((item) => setA.has(item));
76
109
  }
@@ -0,0 +1,89 @@
1
+ import type { SubagentTemplate } from "./domain/subagent-template.js";
2
+ import { escapeXmlContent } from "./xml.js";
3
+
4
+ /**
5
+ * Update system prompt if current agent is not a subagent.
6
+ */
7
+ export function updateAgentSystemPropmt(
8
+ baseSystemPrompt: string,
9
+ templates: SubagentTemplate[],
10
+ ): string {
11
+ if (templates.length > 0) {
12
+ return `${baseSystemPrompt}\n\n${buildAvailableSubagentsSystemPrompt(templates)}`;
13
+ }
14
+ return baseSystemPrompt;
15
+ }
16
+
17
+ const STANDARD_PREAMBLE =
18
+ "You are an expert coding assistant operating inside pi, a coding agent harness. You help users by reading files, executing commands, editing code, and writing new files.\n";
19
+
20
+ /**
21
+ * Update system prompt if current agent is a subagent.
22
+ */
23
+ export function updateSubagentSystemPrompt(
24
+ baseSystemPrompt: string,
25
+ templates: SubagentTemplate[],
26
+ template: SubagentTemplate,
27
+ ): string {
28
+ if (baseSystemPrompt.startsWith(STANDARD_PREAMBLE)) {
29
+ // modify the preamble
30
+ const baseSystemPromptWithoutPreamble = baseSystemPrompt.slice(STANDARD_PREAMBLE.length);
31
+
32
+ if (templates.length > 0) {
33
+ return [
34
+ buildCurrentSubagentSystemPropmtPreamble(template),
35
+ baseSystemPromptWithoutPreamble,
36
+ buildAvailableSubagentsSystemPrompt(templates),
37
+ ].join("\n\n");
38
+ }
39
+ return [
40
+ buildCurrentSubagentSystemPropmtPreamble(template),
41
+ baseSystemPromptWithoutPreamble,
42
+ ].join("\n\n");
43
+ } else {
44
+ // preamble is different - safe path, add at the end
45
+ if (templates.length > 0) {
46
+ return [
47
+ baseSystemPrompt,
48
+ buildCurrentSubagentSystemPrompt(template),
49
+ buildAvailableSubagentsSystemPrompt(templates),
50
+ ].join("\n\n");
51
+ }
52
+ return [baseSystemPrompt, buildCurrentSubagentSystemPrompt(template)].join("\n\n");
53
+ }
54
+ }
55
+
56
+ function buildCurrentSubagentSystemPropmtPreamble(template: SubagentTemplate) {
57
+ return [
58
+ `You are ${template.name} subagent - an expert coding assistant operating inside pi, a coding agent harness. You help other agents by reading files, executing commands, editing code, and writing new files.`,
59
+ "",
60
+ `<subagent_instructions>`,
61
+ escapeXmlContent(template.instructions.trim()),
62
+ "</subagent_instructions>",
63
+ "",
64
+ ].join("\n");
65
+ }
66
+
67
+ function buildCurrentSubagentSystemPrompt(template: SubagentTemplate) {
68
+ return [
69
+ `You're subagent "${template.name}":`,
70
+ `<subagent_instructions>`,
71
+ escapeXmlContent(template.instructions.trim()),
72
+ "</subagent_instructions>",
73
+ ].join("\n");
74
+ }
75
+
76
+ function buildAvailableSubagentsSystemPrompt(templates: SubagentTemplate[]): string {
77
+ return [
78
+ "Subagents:",
79
+ "Your context window is limited, when possible delegate tasks to subagents using `subagent` tool.",
80
+ "<available_subagents>",
81
+ ...templates.flatMap((template) => [
82
+ ` <subagent>`,
83
+ ` <name>${escapeXmlContent(template.name)}</name>`,
84
+ ` <description>${escapeXmlContent(template.description)}</description>`,
85
+ ` </subagent>`,
86
+ ]),
87
+ "</available_subagents>",
88
+ ].join("\n");
89
+ }
@@ -84,6 +84,11 @@ export function makeAgentTemplate(overrides: Partial<SubagentTemplate> = {}): Su
84
84
  source: "global",
85
85
  includedTools: undefined,
86
86
  includedSkills: undefined,
87
+ includedSubagents: undefined,
88
+ graceTurns: undefined,
89
+ maxTurns: undefined,
90
+ model: undefined,
91
+ thinkingLevel: undefined,
87
92
  enabled: true,
88
93
  filePath: undefined,
89
94
  ...overrides,
@@ -92,8 +97,7 @@ export function makeAgentTemplate(overrides: Partial<SubagentTemplate> = {}): Su
92
97
 
93
98
  export function makeAgentConfig(overrides: Partial<SubagentConfig> = {}): SubagentConfig {
94
99
  return {
95
- name: "my-agent",
96
- model: "claude-haiku",
100
+ model: undefined,
97
101
  thinkingLevel: "medium",
98
102
  graceTurns: 5,
99
103
  template: makeAgentTemplate(),
@@ -16,7 +16,9 @@ export class SubagentToolCallComponent implements Component {
16
16
  }
17
17
 
18
18
  render(width: number): string[] {
19
- const { theme, expanded, params } = this;
19
+ const theme = this.theme;
20
+ const expanded = this.expanded;
21
+ const params = this.params;
20
22
  const toolTitle = theme.fg("toolTitle", "subagent");
21
23
  const id = params.id ? theme.fg("syntaxNumber", `#${params.id}`) : undefined;
22
24
  const name = params.name ? theme.fg("accent", params.name) : undefined;
@@ -41,7 +41,7 @@ export class SubagentToolResultComponent implements Component {
41
41
  }
42
42
 
43
43
  render(width: number): string[] {
44
- const { expanded } = this;
44
+ const expanded = this.expanded;
45
45
  if (expanded) {
46
46
  return [
47
47
  ...this.border.render(width),
@@ -115,7 +115,7 @@ class SubagentDetailsComponent implements Component {
115
115
  }
116
116
 
117
117
  render(width: number): string[] {
118
- const { entry } = this;
118
+ const entry = this.entry;
119
119
 
120
120
  switch (entry.status) {
121
121
  case "queued":
@@ -131,7 +131,8 @@ class SubagentDetailsComponent implements Component {
131
131
  }
132
132
 
133
133
  private footerText(): string {
134
- const { entry, theme } = this;
134
+ const entry = this.entry;
135
+ const theme = this.theme;
135
136
  if (entry.sessionFile) {
136
137
  return `${theme.fg("muted", `To open this session:`)} pi --session ${formatFilePath(entry.sessionFile)}`;
137
138
  }
@@ -186,7 +187,7 @@ class SubagentSummaryTextComponent implements Component {
186
187
  invalidate() {}
187
188
 
188
189
  private text(): string {
189
- const { entry } = this;
190
+ const entry = this.entry;
190
191
  switch (entry.status) {
191
192
  case "queued":
192
193
  return this.queuedText();
@@ -194,16 +195,18 @@ class SubagentSummaryTextComponent implements Component {
194
195
  return this.runningText(entry);
195
196
  case "done":
196
197
  return this.doneText(entry);
198
+ default:
199
+ return "";
197
200
  }
198
201
  }
199
202
 
200
203
  private queuedText(): string {
201
- const { theme } = this;
204
+ const theme = this.theme;
202
205
  return theme.fg("dim", "queued");
203
206
  }
204
207
 
205
208
  private runningText(running: RunningAgentSessionEntry): string {
206
- const { theme } = this;
209
+ const theme = this.theme;
207
210
  const parts: string[] = [];
208
211
  parts.push(theme.fg("dim", formatUsage(running.usage)));
209
212
  if (running.lastMessage) {
@@ -216,7 +219,7 @@ class SubagentSummaryTextComponent implements Component {
216
219
  }
217
220
 
218
221
  private lastActivity(message: AssistantMessage): string | undefined {
219
- const { theme } = this;
222
+ const theme = this.theme;
220
223
  const tail = message.content.at(-1);
221
224
  if (!tail) {
222
225
  return undefined;
@@ -234,7 +237,7 @@ class SubagentSummaryTextComponent implements Component {
234
237
  }
235
238
 
236
239
  private toolActivity(call: ToolCall): string | undefined {
237
- const { theme } = this;
240
+ const theme = this.theme;
238
241
  switch (call.name) {
239
242
  case "bash":
240
243
  return theme.fg("dim", getFirstLine(call.arguments.command || "bash"));
@@ -262,7 +265,7 @@ class SubagentSummaryTextComponent implements Component {
262
265
  }
263
266
 
264
267
  private doneText(done: DoneSubagentSessionEntry): string {
265
- const { theme } = this;
268
+ const theme = this.theme;
266
269
  const parts: string[] = [];
267
270
  if (done.result.status === "error") {
268
271
  parts.push(theme.fg("error", done.result.error));
@@ -334,7 +337,8 @@ class SubagentIconComponent implements Component {
334
337
  }
335
338
 
336
339
  private icon(): string {
337
- const { theme, entry } = this;
340
+ const theme = this.theme;
341
+ const entry = this.entry;
338
342
 
339
343
  switch (entry.status) {
340
344
  case "queued":
@@ -357,6 +361,8 @@ class SubagentIconComponent implements Component {
357
361
  return theme.fg("error", "✗");
358
362
  }
359
363
  }
364
+ default:
365
+ return "";
360
366
  }
361
367
  }
362
368
  }
@@ -27,6 +27,7 @@ export function createSubagentTool(deps: SubagentToolDeps) {
27
27
  "Use subagent tool to delegate self-contained tasks that don't require back-and-forth.",
28
28
  "If asked to spawn multiple subagents, spawn all of them in the same turn, as they will block next turn until done.",
29
29
  "You can follow-up on subagent that finished by calling subagent tool again, but this time with returned id and follow-up prompt.",
30
+ "If user ask you to build/modify subagent, you can find definitions in `~/.pi/agent/subagents` and `.pi/subagents`.",
30
31
  ],
31
32
  parameters: SubagentToolParams,
32
33
  executionMode: "parallel",
@@ -48,10 +49,20 @@ export function createSubagentTool(deps: SubagentToolDeps) {
48
49
  },
49
50
  });
50
51
  } else {
52
+ const template = templatesManager.getTemplate(params.name);
53
+ if (!template) {
54
+ const availableSubagents = templatesManager
55
+ .listEnabledTemplates()
56
+ .map((template) => template.name)
57
+ .join(", ");
58
+ throw new Error(
59
+ `Subagent ${params.name} is not defined. Available subagents: ${availableSubagents}.`,
60
+ );
61
+ }
51
62
  promise = instanceManager.spawn({
52
63
  id: resolvedId,
53
64
  ctx,
54
- template: templatesManager.getTemplateOrDefault(params.name),
65
+ template,
55
66
  prompt: params.prompt,
56
67
  description: params.description,
57
68
  availableTools,
@@ -79,9 +90,10 @@ export function createSubagentTool(deps: SubagentToolDeps) {
79
90
  },
80
91
  /** Custom rendering for tool call display */
81
92
  renderCall(params, theme, context): Component {
82
- const resolvedParams = params.id
83
- ? params
84
- : { ...params, id: instanceManager.id(context.toolCallId) };
93
+ const resolvedParams =
94
+ params.id || context.isPartial
95
+ ? params
96
+ : { ...params, id: instanceManager.id(context.toolCallId) };
85
97
  if (!(context.lastComponent instanceof SubagentToolCallComponent)) {
86
98
  return new SubagentToolCallComponent(resolvedParams, theme, context.expanded);
87
99
  }
@@ -105,7 +117,7 @@ export function createSubagentTool(deps: SubagentToolDeps) {
105
117
  }
106
118
 
107
119
  function buildSubagentResponse(done: DoneSubagent): TextContent[] {
108
- const subagent = `Subagent "${done.config.name}" with id ${done.id}`;
120
+ const subagent = `Subagent "${done.name}" with id ${done.id}`;
109
121
 
110
122
  switch (done.result.status) {
111
123
  case "completed":