@xzzpig/pi-subagents 0.5.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,6 +1,9 @@
1
1
  # Changelog
2
2
 
3
- ## [Unreleased]
3
+ ## [0.6.0] - 2026-08-23
4
+
5
+ ### Added
6
+ - Context injection: agents that opt in with `injectToContext: true` frontmatter, plus names listed under the new `subagents.injectAgents` setting, are pre-declared to the parent agent in a compact `<available_subagents>` system-prompt block. The union resolves once per session (canonical names or aliases; builtins allowed), stays byte-identical across turns to preserve provider prompt caching, skips disabled and capability-ceiling-restricted agents and spawned child sessions, ignores unknown setting names (reported by `/subagents-doctor`), and never duplicates itself on forked or resumed sessions.
4
7
 
5
8
  ## [0.5.0] - 2026-08-22
6
9
 
package/README.md CHANGED
@@ -50,6 +50,10 @@ Installing the extension does not start an automatic reviewer in the background.
50
50
  When you finish implementing, run a reviewer subagent before summarizing.
51
51
  ```
52
52
 
53
+ ### Pre-declaring agents in context (context injection)
54
+
55
+ By default Pi discovers agents by calling `subagent({ action: "list" })`. You can pre-declare selected agents in the parent system prompt so routing happens without that round trip: set `injectToContext: true` in an agent's frontmatter, or list names under `subagents.injectAgents` in settings. The union is injected once per session as a compact block — byte-stable across turns, so prompt caching stays effective. Disabled and capability-restricted agents are never advertised; unknown setting names are ignored and reported by `/subagents-doctor`. See [docs/agents.md](docs/agents.md#context-injection).
56
+
53
57
  ## Builtin agents
54
58
 
55
59
  The extension ships with agents you can use immediately:
package/docs/agents.md CHANGED
@@ -178,6 +178,7 @@ acceptanceRole: read-only
178
178
  completionGuard: false
179
179
  interactive: true
180
180
  maxSubagentDepth: 1
181
+ injectToContext: true
181
182
  ---
182
183
 
183
184
  Your system prompt goes here.
@@ -224,8 +225,46 @@ Field notes:
224
225
  | `completionGuard` | Set `false` only for non-implementation agents that may mention implementation words while using mutation-capable tools such as `bash`. |
225
226
  | `interactive` | Parsed for compatibility but not currently enforced. |
226
227
  | `maxSubagentDepth` | Tightens nested delegation for this agent's children. |
228
+ | `injectToContext` | Advertise this agent in the parent system prompt at session start so the main agent can select it without calling `{ action: "list" }` first. See [Context injection](#context-injection). |
227
229
  | `memory` | Opt-in role-specific persistent memory. See below. |
228
230
 
231
+ ## Context injection
232
+
233
+ By default the parent agent learns which agents exist only by calling `subagent({ action: "list" })`. Context injection pre-declares selected agents in the parent system prompt through a compact `<available_subagents>` block, so routing decisions can happen without a discovery round trip.
234
+
235
+ Two sources contribute, and the union is advertised:
236
+
237
+ 1. Agent files that opt in with `injectToContext: true` in their frontmatter.
238
+ 2. The `subagents.injectAgents` setting, which lists agent names (canonical names or aliases; builtins allowed):
239
+
240
+ ```json
241
+ {
242
+ "subagents": {
243
+ "injectAgents": ["worker", "reviewer", "security-reviewer"]
244
+ }
245
+ }
246
+ ```
247
+
248
+ Rendered block shape:
249
+
250
+ ```text
251
+ <available_subagents>
252
+ The following pre-declared subagents are available.
253
+ Launch them with the subagent tool when a task matches their description.
254
+
255
+ - security-reviewer: Security review specialist
256
+ - worker: Implementation work, including approved oracle handoffs.
257
+ </available_subagents>
258
+ ```
259
+
260
+ Semantics and guarantees:
261
+
262
+ - **Snapshot per session.** The list resolves once at session start (and on reload) and stays byte-identical for every turn, so provider prompt caching is never invalidated mid-session. Edits to agent files or settings take effect in a new session, not the current one; `{ action: "list" }` remains the runtime source of truth.
263
+ - **Only executable agents are advertised.** Disabled agents and agents restricted by the session capability ceiling are never injected.
264
+ - **Children never see it.** Spawned child sessions do not load the parent injection; fanout children can still call `{ action: "list" }`.
265
+ - **Unknown setting names are ignored** and reported by `/subagents-doctor` instead of failing startup.
266
+ - The block is appended only when it is not already present, so forked or resumed sessions never duplicate it.
267
+
229
268
  ## Per-agent persistent memory
230
269
 
231
270
  A recurring custom agent can opt into a durable, role-specific memory scope with the `memory` frontmatter field:
@@ -2,7 +2,7 @@
2
2
 
3
3
  `pi-subagents` reads optional JSON config from `~/.pi/agent/extensions/subagent/config.json`. This page lists every key, plus the environment variables and the settings-file keys that affect config resolution.
4
4
 
5
- Settings-level keys (`subagents.defaultModel`, `defaultThinking`, `defaultExtensions`, `agentOverrides`, `modelScope`, `disableThinking`, `disableBuiltins`, watchdog settings) live in Pi settings files, not this config file. See [models.md](models.md), [agents.md](agents.md), and [watchdog.md](watchdog.md).
5
+ Settings-level keys (`subagents.defaultModel`, `defaultThinking`, `defaultExtensions`, `agentOverrides`, `modelScope`, `disableThinking`, `disableBuiltins`, `injectAgents`, watchdog settings) live in Pi settings files, not this config file. See [models.md](models.md), [agents.md](agents.md), and [watchdog.md](watchdog.md).
6
6
 
7
7
  ## Project root resolution (settings)
8
8
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@xzzpig/pi-subagents",
3
- "version": "0.5.0",
3
+ "version": "0.6.0",
4
4
  "description": "Pi extension for single-agent delegation and scripted multi-agent workflows",
5
5
  "author": "Nico Bailon",
6
6
  "license": "MIT",
@@ -31,6 +31,7 @@ export const KNOWN_FIELDS = new Set([
31
31
  "outputMode",
32
32
  "defaultReads",
33
33
  "defaultProgress",
34
+ "injectToContext",
34
35
  "interactive",
35
36
  "maxSubagentDepth",
36
37
  "completionGuard",
@@ -120,6 +121,7 @@ export function serializeAgent(config: AgentConfig, options: SerializeAgentOptio
120
121
  if (readsValue) lines.push(`defaultReads: ${readsValue}`);
121
122
 
122
123
  if (config.defaultProgress) lines.push("defaultProgress: true");
124
+ if (config.injectToContext) lines.push("injectToContext: true");
123
125
  if (config.interactive) lines.push("interactive: true");
124
126
  const maxSubagentDepth = config.maxSubagentDepth;
125
127
  if (typeof maxSubagentDepth === "number" && Number.isInteger(maxSubagentDepth) && maxSubagentDepth >= 0) {
@@ -140,6 +140,7 @@ export interface AgentConfig {
140
140
  outputMode?: OutputMode;
141
141
  defaultReads?: string[];
142
142
  defaultProgress?: boolean;
143
+ injectToContext?: boolean;
143
144
  interactive?: boolean;
144
145
  maxSubagentDepth?: number;
145
146
  completionGuard?: boolean;
@@ -162,6 +163,7 @@ interface SubagentSettings {
162
163
  disableBuiltins?: boolean;
163
164
  disableThinking?: boolean;
164
165
  modelScope?: ModelScopeConfig;
166
+ injectAgents?: string[];
165
167
  }
166
168
 
167
169
  const EMPTY_SUBAGENT_SETTINGS: SubagentSettings = { overrides: {} };
@@ -249,6 +251,7 @@ interface AgentDiscoveryResult {
249
251
  agentDiagnostics?: AgentDiscoveryDiagnostic[];
250
252
  projectAgentsDir: string | null;
251
253
  modelScope?: ModelScopeConfig;
254
+ injectAgents?: string[];
252
255
  }
253
256
 
254
257
  function getUserChainDir(): string {
@@ -262,9 +265,19 @@ interface PackageSubagentPaths {
262
265
 
263
266
  let cachedGlobalNpmRoot: string | null = null;
264
267
 
265
- function readJsonFileBestEffort(filePath: string): unknown {
268
+ /** Parsed JSON object record from a manifest/settings-style file. */
269
+ interface JsonObjectFile {
270
+ [key: string]: unknown;
271
+ }
272
+
273
+ function isJsonObjectRecord(value: unknown): value is JsonObjectFile {
274
+ return value !== null && typeof value === "object" && !Array.isArray(value);
275
+ }
276
+
277
+ function readJsonFileBestEffort(filePath: string): JsonObjectFile | null {
266
278
  try {
267
- return JSON.parse(fs.readFileSync(filePath, "utf-8"));
279
+ const parsed: unknown = JSON.parse(fs.readFileSync(filePath, "utf-8"));
280
+ return isJsonObjectRecord(parsed) ? parsed : null;
268
281
  } catch {
269
282
  // Installed package scans are opportunistic; bad third-party manifests
270
283
  // should not break local agent discovery.
@@ -272,9 +285,10 @@ function readJsonFileBestEffort(filePath: string): unknown {
272
285
  }
273
286
  }
274
287
 
275
- function readOptionalJsonFile(filePath: string): unknown {
288
+ function readOptionalJsonFile(filePath: string): JsonObjectFile | null {
289
+ let parsed: unknown;
276
290
  try {
277
- return JSON.parse(fs.readFileSync(filePath, "utf-8"));
291
+ parsed = JSON.parse(fs.readFileSync(filePath, "utf-8"));
278
292
  } catch (error) {
279
293
  const code = typeof error === "object" && error !== null && "code" in error
280
294
  ? (error as { code?: unknown }).code
@@ -282,6 +296,7 @@ function readOptionalJsonFile(filePath: string): unknown {
282
296
  if (code === "ENOENT") return null;
283
297
  throw error;
284
298
  }
299
+ return isJsonObjectRecord(parsed) ? parsed : null;
285
300
  }
286
301
 
287
302
  function isSafePackagePath(value: string): boolean {
@@ -394,15 +409,15 @@ function stringArray(value: unknown): string[] {
394
409
  function extractSubagentPathsFromPackageRoot(packageRoot: string): PackageSubagentPaths {
395
410
  const packageJsonPath = path.join(packageRoot, "package.json");
396
411
  const pkg = readJsonFileBestEffort(packageJsonPath);
397
- if (!pkg || typeof pkg !== "object" || Array.isArray(pkg)) return { agents: [], chains: [] };
412
+ if (!pkg) return { agents: [], chains: [] };
398
413
 
399
414
  const roots: Record<string, unknown>[] = [];
400
- const piSubagents = (pkg as { "pi-subagents"?: unknown })["pi-subagents"];
415
+ const piSubagents = pkg["pi-subagents"];
401
416
  if (piSubagents && typeof piSubagents === "object" && !Array.isArray(piSubagents)) {
402
417
  roots.push(piSubagents as Record<string, unknown>);
403
418
  }
404
419
 
405
- const pi = (pkg as { pi?: unknown }).pi;
420
+ const pi = pkg.pi;
406
421
  if (pi && typeof pi === "object" && !Array.isArray(pi)) {
407
422
  const subagents = (pi as { subagents?: unknown }).subagents;
408
423
  if (subagents && typeof subagents === "object" && !Array.isArray(subagents)) {
@@ -457,8 +472,8 @@ function collectPackageRootsFromNodeModules(nodeModulesDir: string): string[] {
457
472
 
458
473
  function collectSettingsPackageRoots(settingsFile: string, baseDir: string): string[] {
459
474
  const settings = readOptionalJsonFile(settingsFile);
460
- if (!settings || typeof settings !== "object" || Array.isArray(settings)) return [];
461
- const packages = (settings as { packages?: unknown }).packages;
475
+ if (!settings) return [];
476
+ const packages = settings.packages;
462
477
  if (!Array.isArray(packages)) return [];
463
478
 
464
479
  const roots: string[] = [];
@@ -959,6 +974,14 @@ function readSubagentSettings(filePath: string | null): SubagentSettings {
959
974
  }
960
975
  defaultExtensions = subagentsObject.defaultExtensions.map((item) => item.trim());
961
976
  }
977
+ let injectAgents: string[] | undefined;
978
+ if ("injectAgents" in subagentsObject) {
979
+ if (!Array.isArray(subagentsObject.injectAgents)
980
+ || subagentsObject.injectAgents.some((item) => typeof item !== "string" || !item.trim())) {
981
+ throw new Error(`Subagent settings in '${filePath}' have invalid 'injectAgents'; expected an array of non-empty agent names.`);
982
+ }
983
+ injectAgents = subagentsObject.injectAgents.map((item) => item.trim());
984
+ }
962
985
  const modelScope = parseModelScopeConfig(subagentsObject.modelScope, { filePath });
963
986
 
964
987
  const parsed: Record<string, BuiltinAgentOverrideConfig> = {};
@@ -971,6 +994,7 @@ function readSubagentSettings(filePath: string | null): SubagentSettings {
971
994
  ...(disableBuiltins !== undefined ? { disableBuiltins } : {}),
972
995
  ...(disableThinking !== undefined ? { disableThinking } : {}),
973
996
  ...(modelScope !== undefined ? { modelScope } : {}),
997
+ ...(injectAgents !== undefined ? { injectAgents } : {}),
974
998
  };
975
999
  if (!agentOverrides || typeof agentOverrides !== "object" || Array.isArray(agentOverrides)) {
976
1000
  return parsedSettings;
@@ -1779,6 +1803,7 @@ function loadAgentsFromDefinitionFiles(files: AgentDefinitionFile[], source: Age
1779
1803
  ...(outputMode !== undefined ? { outputMode } : {}),
1780
1804
  ...(defaultReads?.length ? { defaultReads } : {}),
1781
1805
  defaultProgress: frontmatter.defaultProgress === "true",
1806
+ injectToContext: frontmatter.injectToContext === "true",
1782
1807
  interactive: frontmatter.interactive === "true",
1783
1808
  ...(maxSubagentDepth !== undefined ? { maxSubagentDepth } : {}),
1784
1809
  ...(completionGuard !== undefined ? { completionGuard } : {}),
@@ -1891,6 +1916,9 @@ export function discoverAgents(cwd: string, scope: AgentScope): AgentDiscoveryRe
1891
1916
  const defaultModel = resolveSubagentDefaultModel(userSettings, projectSettings, userSettingsPath, projectSettingsPath);
1892
1917
  const defaultThinking = resolveSubagentDefaultThinking(userSettings, projectSettings, projectSettingsPath);
1893
1918
  const defaultExtensions = resolveSubagentDefaultExtensions(userSettings, projectSettings, projectSettingsPath);
1919
+ const injectAgents = projectSettingsPath && projectSettings.injectAgents !== undefined
1920
+ ? projectSettings.injectAgents
1921
+ : userSettings.injectAgents;
1894
1922
  const modelScope = projectSettings.modelScope ?? userSettings.modelScope;
1895
1923
  const packageSubagentPaths = collectPackageSubagentPaths(cwd, {
1896
1924
  includeUser: scope !== "project",
@@ -1947,7 +1975,7 @@ export function discoverAgents(cwd: string, scope: AgentScope): AgentDiscoveryRe
1947
1975
  ...projectLoaded.flatMap((loaded) => loaded.diagnostics),
1948
1976
  ...packageLoaded.flatMap((loaded) => loaded.diagnostics),
1949
1977
  ];
1950
- return { agents, agentDiagnostics, projectAgentsDir, ...(modelScope !== undefined ? { modelScope } : {}) };
1978
+ return { agents, agentDiagnostics, projectAgentsDir, ...(modelScope !== undefined ? { modelScope } : {}), ...(injectAgents?.length ? { injectAgents } : {}) };
1951
1979
  }
1952
1980
 
1953
1981
  export function discoverAgentsAll(cwd: string): {
@@ -1956,6 +1984,7 @@ export function discoverAgentsAll(cwd: string): {
1956
1984
  user: AgentConfig[];
1957
1985
  project: AgentConfig[];
1958
1986
  agentDiagnostics?: AgentDiscoveryDiagnostic[];
1987
+ injectAgents?: string[];
1959
1988
  chains: ChainConfig[];
1960
1989
  chainDiagnostics: ChainDiscoveryDiagnostic[];
1961
1990
  userDir: string;
@@ -1977,6 +2006,9 @@ export function discoverAgentsAll(cwd: string): {
1977
2006
  const defaultModel = resolveSubagentDefaultModel(userSettings, projectSettings, userSettingsPath, projectSettingsPath);
1978
2007
  const defaultThinking = resolveSubagentDefaultThinking(userSettings, projectSettings, projectSettingsPath);
1979
2008
  const defaultExtensions = resolveSubagentDefaultExtensions(userSettings, projectSettings, projectSettingsPath);
2009
+ const injectAgents = projectSettingsPath && projectSettings.injectAgents !== undefined
2010
+ ? projectSettings.injectAgents
2011
+ : userSettings.injectAgents;
1980
2012
  const packageSubagentPaths = collectPackageSubagentPaths(cwd);
1981
2013
 
1982
2014
  const builtinLoaded = loadAgentsFromDefinitionFiles(BUILTIN_AGENT_DEFINITION_FILES, "builtin");
@@ -2067,5 +2099,5 @@ export function discoverAgentsAll(cwd: string): {
2067
2099
 
2068
2100
  const userDir = process.env.PI_CODING_AGENT_DIR ? userDirOld : fs.existsSync(userDirNew) ? userDirNew : userDirOld;
2069
2101
 
2070
- return { builtin, package: packageAgents, user, project, agentDiagnostics, chains, chainDiagnostics, userDir, projectDir, userChainDir, projectChainDir, userSettingsPath, projectSettingsPath };
2102
+ return { builtin, package: packageAgents, user, project, agentDiagnostics, chains, chainDiagnostics, userDir, projectDir, userChainDir, projectChainDir, userSettingsPath, projectSettingsPath, ...(injectAgents?.length ? { injectAgents } : {}) };
2071
2103
  }
@@ -43,6 +43,7 @@ export interface RuntimeAgentDefinition {
43
43
  outputMode?: OutputMode;
44
44
  defaultReads?: readonly string[];
45
45
  defaultProgress?: boolean;
46
+ injectToContext?: boolean;
46
47
  interactive?: boolean;
47
48
  maxSubagentDepth?: number;
48
49
  completionGuard?: boolean;
@@ -202,7 +203,7 @@ function validateDefinition(value: unknown): RuntimeAgentDefinition {
202
203
  "description", "systemPrompt", "aliases", "tools", "mcpDirectTools", "model", "fallbackModels", "thinking",
203
204
  "systemPromptMode", "inheritProjectContext", "inheritSkills", "defaultContext", "defaultAsync", "defaultTimeoutMs",
204
205
  "defaultToolTimeoutMs", "defaultTurnBudget", "defaultAcceptance", "acceptanceRole", "runner", "skills", "skillPath",
205
- "extensions", "subagentOnlyExtensions", "output", "outputMode", "defaultReads", "defaultProgress", "interactive",
206
+ "extensions", "subagentOnlyExtensions", "output", "outputMode", "defaultReads", "defaultProgress", "injectToContext", "interactive",
206
207
  "maxSubagentDepth", "completionGuard", "toolBudget", "permissions",
207
208
  ]);
208
209
  const unknown = Object.keys(definition).filter((key) => !supported.has(key));
@@ -237,6 +238,7 @@ function validateDefinition(value: unknown): RuntimeAgentDefinition {
237
238
  const output = validateOptionalString(definition.output, "Runtime agent definition output");
238
239
  const defaultReads = validateStringList(definition.defaultReads, "Runtime agent definition defaultReads");
239
240
  const defaultProgress = validateBoolean(definition.defaultProgress, "Runtime agent definition defaultProgress");
241
+ const injectToContext = validateBoolean(definition.injectToContext, "Runtime agent definition injectToContext");
240
242
  const interactive = validateBoolean(definition.interactive, "Runtime agent definition interactive");
241
243
  const maxSubagentDepth = validatePositiveInteger(definition.maxSubagentDepth, "Runtime agent definition maxSubagentDepth");
242
244
  const completionGuard = validateBoolean(definition.completionGuard, "Runtime agent definition completionGuard");
@@ -270,6 +272,7 @@ function validateDefinition(value: unknown): RuntimeAgentDefinition {
270
272
  ...(outputMode !== undefined ? { outputMode: outputMode as OutputMode } : {}),
271
273
  ...(defaultReads ? { defaultReads } : {}),
272
274
  ...(defaultProgress !== undefined ? { defaultProgress } : {}),
275
+ ...(injectToContext !== undefined ? { injectToContext } : {}),
273
276
  ...(interactive !== undefined ? { interactive } : {}),
274
277
  ...(maxSubagentDepth !== undefined ? { maxSubagentDepth } : {}),
275
278
  ...(completionGuard !== undefined ? { completionGuard } : {}),
@@ -349,6 +352,7 @@ function toAgentConfig(name: string, definition: RuntimeAgentDefinition): AgentC
349
352
  ...(definition.outputMode !== undefined ? { outputMode: definition.outputMode } : {}),
350
353
  ...(definition.defaultReads !== undefined ? { defaultReads: [...definition.defaultReads] } : {}),
351
354
  ...(definition.defaultProgress !== undefined ? { defaultProgress: definition.defaultProgress } : {}),
355
+ ...(definition.injectToContext !== undefined ? { injectToContext: definition.injectToContext } : {}),
352
356
  ...(definition.interactive !== undefined ? { interactive: definition.interactive } : {}),
353
357
  ...(definition.maxSubagentDepth !== undefined ? { maxSubagentDepth: definition.maxSubagentDepth } : {}),
354
358
  ...(definition.completionGuard !== undefined ? { completionGuard: definition.completionGuard } : {}),
@@ -0,0 +1,118 @@
1
+ import type { AgentConfig } from "../agents/agents.ts";
2
+ import { isAgentAllowedByCapabilityCeiling, type ResolvedSubagentCapabilityCeiling } from "../runs/shared/capability-ceiling.ts";
3
+
4
+ /**
5
+ * Marker used to detect an already-injected block so repeated injections
6
+ * (forked or resumed sessions replaying chained system prompts) stay idempotent.
7
+ */
8
+ export const SUBAGENT_INJECTION_MARKER = "<available_subagents>";
9
+
10
+ /** One compact line per advertised agent inside the injected block. */
11
+ export interface InjectableAgentSummary {
12
+ name: string;
13
+ description: string;
14
+ }
15
+
16
+ export interface ResolveInjectableAgentsInput {
17
+ /** Merged discovered agents across scopes (builtin, package, user, project). */
18
+ agents: readonly AgentConfig[];
19
+ /** Names (canonical or alias) listed by the `subagents.injectAgents` setting. */
20
+ injectAgents?: readonly string[];
21
+ /** Current session capability ceiling; restricted agents are never advertised. */
22
+ capabilityCeiling?: ResolvedSubagentCapabilityCeiling | undefined;
23
+ }
24
+
25
+ export interface ResolveInjectableAgentsResult {
26
+ agents: InjectableAgentSummary[];
27
+ /** Setting entries that matched no discovered agent, trimmed, discovery order preserved. */
28
+ unknownNames: string[];
29
+ }
30
+
31
+ function normalizeDescription(description: string): string {
32
+ return description.replace(/\s+/g, " ").trim();
33
+ }
34
+
35
+ function buildNameLookup(agents: readonly AgentConfig[]): Map<string, AgentConfig> {
36
+ const lookup = new Map<string, AgentConfig>();
37
+ for (const agent of agents) {
38
+ if (!lookup.has(agent.name)) lookup.set(agent.name, agent);
39
+ for (const alias of agent.aliases ?? []) {
40
+ if (!lookup.has(alias)) lookup.set(alias, agent);
41
+ }
42
+ }
43
+ return lookup;
44
+ }
45
+
46
+ /**
47
+ * Union of settings-listed agents (`subagents.injectAgents`) and agents whose
48
+ * frontmatter opts in with `injectToContext: true`. Settings names resolve
49
+ * against canonical names and aliases; unresolved entries are reported through
50
+ * `unknownNames` instead of failing discovery. Disabled agents and agents
51
+ * restricted by the session capability ceiling are never advertised.
52
+ */
53
+ export function resolveInjectableAgents(input: ResolveInjectableAgentsInput): ResolveInjectableAgentsResult {
54
+ const { agents, injectAgents, capabilityCeiling } = input;
55
+ const lookup = buildNameLookup(agents);
56
+ const selected = new Map<string, InjectableAgentSummary>();
57
+ const unknownNames: string[] = [];
58
+
59
+ const advertise = (agent: AgentConfig): void => {
60
+ if (agent.disabled === true) return;
61
+ if (!isAgentAllowedByCapabilityCeiling(agent.name, capabilityCeiling)) return;
62
+ if (selected.has(agent.name)) return;
63
+ selected.set(agent.name, { name: agent.name, description: normalizeDescription(agent.description) });
64
+ };
65
+
66
+ for (const rawName of injectAgents ?? []) {
67
+ const name = rawName.trim();
68
+ if (!name) continue;
69
+ const resolved = lookup.get(name);
70
+ if (!resolved) {
71
+ if (!unknownNames.includes(name)) unknownNames.push(name);
72
+ continue;
73
+ }
74
+ advertise(resolved);
75
+ }
76
+
77
+ for (const agent of agents) {
78
+ if (agent.injectToContext === true) advertise(agent);
79
+ }
80
+
81
+ return {
82
+ agents: Array.from(selected.values()).sort((a, b) => a.name.localeCompare(b.name)),
83
+ unknownNames,
84
+ };
85
+ }
86
+
87
+ /**
88
+ * Append the session-snapshot block to this turn's system prompt.
89
+ * Returns `undefined` when nothing should change: empty block, or a prompt
90
+ * that already carries the marker (forked/resumed chains replaying history).
91
+ */
92
+ export function applyInjectionBlock(input: { systemPrompt: string; block: string }): string | undefined {
93
+ const { systemPrompt, block } = input;
94
+ if (!block) return undefined;
95
+ if (systemPrompt.includes(SUBAGENT_INJECTION_MARKER)) return undefined;
96
+ return `${systemPrompt}\n\n${block}`;
97
+ }
98
+
99
+ /**
100
+ * Render the deterministic `<available_subagents>` block appended to the parent
101
+ * system prompt. Pure function of its input: stable sort order and a fixed
102
+ * template guarantee byte-identical output across turns so provider prompt
103
+ * caching stays effective. Descriptions are collapsed to a single line so a
104
+ * multi-line frontmatter description cannot break the compact format. Returns
105
+ * an empty string when nothing is advertised.
106
+ */
107
+ export function renderInjectionBlock(agents: readonly InjectableAgentSummary[]): string {
108
+ if (agents.length === 0) return "";
109
+ const lines = [
110
+ SUBAGENT_INJECTION_MARKER,
111
+ "The following pre-declared subagents are available.",
112
+ "Launch them with the subagent tool when a task matches their description.",
113
+ "",
114
+ ...agents.map((agent) => `- ${agent.name}: ${normalizeDescription(agent.description)}`),
115
+ "</available_subagents>",
116
+ ];
117
+ return lines.join("\n");
118
+ }
@@ -1,6 +1,8 @@
1
1
  import * as fs from "node:fs";
2
2
  import * as path from "node:path";
3
3
  import { discoverAgentsAll, type AgentSource } from "../agents/agents.ts";
4
+ import { mergeAgentsForScope } from "../agents/agent-selection.ts";
5
+ import { resolveInjectableAgents } from "./context-injection.ts";
4
6
  import { isAsyncAvailable } from "../runs/background/async-execution.ts";
5
7
  import { formatSpawnBudgetSummary, getSpawnBudgetSnapshot } from "../runs/shared/spawn-budget.ts";
6
8
  import { getActiveAsyncCapacitySnapshot, resolveMaxActiveAsyncRunsPerSession } from "../runs/background/active-async-capacity.ts";
@@ -144,8 +146,17 @@ function formatDiscovery(input: DoctorReportInput, deps: DoctorDeps): string[] {
144
146
  runtime: 0,
145
147
  };
146
148
  const diagnostics = discovered.agentDiagnostics ?? [];
149
+ const injectable = resolveInjectableAgents({
150
+ agents: mergeAgentsForScope("both", discovered.user, discovered.project, discovered.builtin, discovered.package),
151
+ injectAgents: discovered.injectAgents,
152
+ });
153
+ const snapshot = input.state.contextInjectionBlock;
147
154
  return [
148
155
  `- agents: total ${agentCounts.builtin + agentCounts.package + agentCounts.user + agentCounts.project} (${formatSourceCounts(agentCounts)})`,
156
+ injectable.agents.length
157
+ ? `- context injection: ${injectable.agents.length} advertised (${injectable.agents.map((agent) => agent.name).join(", ")}); session snapshot ${snapshot ? "present" : "absent"}`
158
+ : "- context injection: none",
159
+ ...(injectable.unknownNames.length ? [`- context injection unknown names (ignored): ${injectable.unknownNames.join(", ")}`] : []),
149
160
  ...diagnostics.map((diagnostic) => `- invalid agent ${diagnostic.name ?? diagnostic.filePath} (${diagnostic.source}): ${diagnostic.error}`),
150
161
  ].join("\n");
151
162
  }),
@@ -20,6 +20,7 @@ import type { AgentToolResult } from "@earendil-works/pi-agent-core";
20
20
  import { keyText, type ExtensionAPI, type ExtensionContext, type ToolDefinition } from "@earendil-works/pi-coding-agent";
21
21
  import { Box, Container, Spacer, Text, truncateToWidth, visibleWidth, wrapTextWithAnsi, type Component } from "@earendil-works/pi-tui";
22
22
  import { discoverAgents, discoverAgentsAll, type AgentConfig, type AgentScope } from "../agents/agents.ts";
23
+ import { mergeAgentsForScope } from "../agents/agent-selection.ts";
23
24
  import { clearRuntimeAgentsForPi, listRuntimeAgentConfigs, mergeRuntimeAgents } from "../agents/runtime-agent-registry.ts";
24
25
  import { ensureAccessibleDir } from "../shared/accessible-dir.ts";
25
26
  import { cleanupAllArtifactDirs, cleanupOldArtifacts, getArtifactsDir } from "../shared/artifacts.ts";
@@ -56,6 +57,7 @@ import { SUBAGENT_CHILD_ENV, SUBAGENT_PARENT_SESSION_ENV } from "../runs/shared/
56
57
  import { resolveCurrentSubagentCapabilityCeiling } from "../runs/shared/capability-ceiling.ts";
57
58
  import { formatDuration, shortenPath } from "../shared/formatters.ts";
58
59
  import { loadConfig, resolveAsyncByDefault, resolveScheduledStoreRoot } from "./config.ts";
60
+ import { applyInjectionBlock, renderInjectionBlock, resolveInjectableAgents, SUBAGENT_INJECTION_MARKER } from "./context-injection.ts";
59
61
  import { buildSubagentToolDescription, buildSubagentToolPromptMetadata } from "./tool-description.ts";
60
62
  import { collectGoalContinuationNotices } from "../missions/goal-driver.ts";
61
63
  import { restoreForegroundRunHistory } from "../runs/foreground/foreground-history.ts";
@@ -887,6 +889,35 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
887
889
  fleetStatus?.setContext(ctx);
888
890
  };
889
891
 
892
+ // Snapshot the injectable-agent advertisement once per session so the
893
+ // appended `<available_subagents>` block stays byte-identical across turns
894
+ // and provider prompt caching is never invalidated mid-session.
895
+ const refreshContextInjectionSnapshot = (ctx: ExtensionContext) => {
896
+ if (process.env[SUBAGENT_CHILD_ENV] === "1") return;
897
+ try {
898
+ const cwd = ctx.cwd || state.baseCwd;
899
+ if (!cwd) {
900
+ state.contextInjectionBlock = "";
901
+ state.contextInjectionUnknownNames = [];
902
+ return;
903
+ }
904
+ const discovery = discoverAgentsAll(cwd);
905
+ const mergedAgents = mergeAgentsForScope("both", discovery.user, discovery.project, discovery.builtin, discovery.package);
906
+ const resolved = resolveInjectableAgents({
907
+ agents: mergedAgents,
908
+ injectAgents: discovery.injectAgents,
909
+ capabilityCeiling: resolveCurrentSubagentCapabilityCeiling(state.currentSessionId ?? undefined),
910
+ });
911
+ state.contextInjectionBlock = renderInjectionBlock(resolved.agents);
912
+ state.contextInjectionUnknownNames = resolved.unknownNames;
913
+ } catch (error) {
914
+ // Injection is a best-effort convenience; never break session startup.
915
+ state.contextInjectionBlock = "";
916
+ state.contextInjectionUnknownNames = [];
917
+ console.error("Failed to snapshot injectable subagents:", error);
918
+ }
919
+ };
920
+
890
921
  let runtimeCleaned = false;
891
922
  const runtimeEntry: SubagentRuntimeEntry = {
892
923
  sessionManager: null,
@@ -1001,6 +1032,7 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
1001
1032
  installRuntime(ctx);
1002
1033
  const recovering = event.reason === "startup" || event.reason === "reload" || event.reason === "resume";
1003
1034
  resetSessionState(ctx, recovering);
1035
+ refreshContextInjectionSnapshot(ctx);
1004
1036
  herdrStatusBridge.sessionStarted({
1005
1037
  hasUI: ctx.hasUI === true,
1006
1038
  runs: activeHerdrRuns(),
@@ -1010,6 +1042,15 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
1010
1042
  supervisorChannel.activateTransport();
1011
1043
  });
1012
1044
 
1045
+ pi.on("before_agent_start", (event) => {
1046
+ if (process.env[SUBAGENT_CHILD_ENV] === "1") return undefined;
1047
+ const next = applyInjectionBlock({
1048
+ systemPrompt: event.systemPrompt,
1049
+ block: state.contextInjectionBlock ?? "",
1050
+ });
1051
+ return next ? { systemPrompt: next } : undefined;
1052
+ });
1053
+
1013
1054
  pi.on("session_shutdown", async () => {
1014
1055
  runtimeEntry.cleanup();
1015
1056
  await herdrStatusBridge.flush();
@@ -1780,6 +1780,10 @@ export interface SubagentState {
1780
1780
  waitSubscriptions?: Map<string, WaitSubscriptionRecord>;
1781
1781
  /** Live in-process workflow controllers. Durable status remains on disk after settlement. */
1782
1782
  workflowControllers?: Map<string, AbortController>;
1783
+ /** Session-snapshot `<available_subagents>` block appended to the parent system prompt; empty when nothing is advertised. */
1784
+ contextInjectionBlock?: string;
1785
+ /** `subagents.injectAgents` entries that matched no discovered agent at snapshot time. */
1786
+ contextInjectionUnknownNames?: string[];
1783
1787
  }
1784
1788
 
1785
1789
  // ============================================================================