@xzzpig/pi-subagents 0.4.2 → 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.
Files changed (128) hide show
  1. package/CHANGELOG.md +172 -1
  2. package/README.md +8 -0
  3. package/agents/oracle.md +3 -1
  4. package/agents/reviewer.md +1 -0
  5. package/agents/scout.md +2 -2
  6. package/agents/worker.md +2 -1
  7. package/async-retention-discovery-worker.mjs +180 -0
  8. package/docs/agents.md +79 -2
  9. package/docs/configuration.md +42 -14
  10. package/docs/extension-api.md +45 -2
  11. package/docs/models.md +2 -0
  12. package/docs/observability.md +41 -5
  13. package/docs/tool-reference.md +38 -39
  14. package/docs/workflows.md +173 -3
  15. package/package.json +13 -10
  16. package/prompts/council.md +48 -0
  17. package/skills/council-mode/SKILL.md +230 -0
  18. package/skills/pi-subagents/SKILL.md +8 -4
  19. package/skills/pi-subagents/references/constraints-and-recipes.md +13 -6
  20. package/skills/pi-subagents/references/execution-controls.md +40 -15
  21. package/skills/pi-subagents/references/management-authoring-rpc.md +3 -3
  22. package/skills/pi-subagents/references/multi-lane-orchestration.md +39 -0
  23. package/skills/pi-subagents/references/prompting-and-roles.md +4 -2
  24. package/src/agents/agent-management.ts +158 -357
  25. package/src/agents/agent-serializer.ts +4 -0
  26. package/src/agents/agents.ts +227 -53
  27. package/src/agents/builtin-names.ts +9 -0
  28. package/src/agents/runtime-agent-registry.ts +422 -0
  29. package/src/agents/skills.ts +1 -1
  30. package/src/api/agents.ts +7 -0
  31. package/src/api/external-job-provider.ts +186 -0
  32. package/src/api/preflight.ts +37 -9
  33. package/src/api/shared-types.ts +2 -0
  34. package/src/extension/config.ts +6 -3
  35. package/src/extension/context-injection.ts +118 -0
  36. package/src/extension/doctor.ts +15 -6
  37. package/src/extension/fanout-child.ts +2 -2
  38. package/src/extension/index.ts +224 -90
  39. package/src/extension/public-execution.ts +31 -2
  40. package/src/extension/rpc.ts +41 -1
  41. package/src/extension/schemas.ts +17 -37
  42. package/src/extension/tool-description.ts +35 -24
  43. package/src/inspectors/herdr/actions.ts +2 -2
  44. package/src/inspectors/herdr/inspector-runner.ts +2 -1
  45. package/src/inspectors/herdr/project-panes.ts +2 -2
  46. package/src/intercom/native-supervisor-channel.ts +32 -10
  47. package/src/missions/lifecycle.ts +6 -1
  48. package/src/missions/store.ts +4 -9
  49. package/src/missions/workflow-state.ts +2 -2
  50. package/src/profiles/profiles.ts +3 -1
  51. package/src/runs/background/active-run-index.ts +31 -8
  52. package/src/runs/background/async-execution.ts +70 -41
  53. package/src/runs/background/async-job-tracker.ts +24 -7
  54. package/src/runs/background/async-resume.ts +49 -16
  55. package/src/runs/background/async-retention.ts +886 -0
  56. package/src/runs/background/async-status-snapshot.ts +14 -5
  57. package/src/runs/background/async-status.ts +39 -53
  58. package/src/runs/background/auto-drain.ts +1 -0
  59. package/src/runs/background/chain-append.ts +3 -33
  60. package/src/runs/background/completion-dedupe.ts +5 -1
  61. package/src/runs/background/completion-replay.ts +22 -12
  62. package/src/runs/background/control-channel.ts +14 -68
  63. package/src/runs/background/fleet-view.ts +68 -19
  64. package/src/runs/background/index-segment.ts +59 -0
  65. package/src/runs/background/inspect-rpc.ts +443 -0
  66. package/src/runs/background/notify.ts +31 -5
  67. package/src/runs/background/result-files.ts +158 -90
  68. package/src/runs/background/result-watcher.ts +124 -20
  69. package/src/runs/background/resume-guidance.ts +8 -5
  70. package/src/runs/background/retained-children.ts +13 -3
  71. package/src/runs/background/run-id-query.ts +7 -0
  72. package/src/runs/background/run-id-resolver.ts +11 -9
  73. package/src/runs/background/run-status.ts +27 -18
  74. package/src/runs/background/scheduled-runs.ts +24 -4
  75. package/src/runs/background/stale-run-reconciler.ts +6 -3
  76. package/src/runs/background/steering.ts +11 -1
  77. package/src/runs/background/subagent-runner.ts +260 -144
  78. package/src/runs/background/subagent-wait.ts +17 -13
  79. package/src/runs/background/terminal-run-index.ts +138 -0
  80. package/src/runs/background/wait-completions.ts +21 -4
  81. package/src/runs/background/wait-subscriptions.ts +81 -2
  82. package/src/runs/background/wait-tool.ts +1 -0
  83. package/src/runs/foreground/async-steering-action.ts +21 -14
  84. package/src/runs/foreground/execution.ts +8 -2
  85. package/src/runs/foreground/subagent-executor.ts +816 -1593
  86. package/src/runs/foreground/workflow-detach-reconcile.ts +262 -0
  87. package/src/runs/foreground/workflow-foreground-steering.ts +6 -5
  88. package/src/runs/shared/acceptance.ts +48 -5
  89. package/src/runs/shared/chain-outputs.ts +1 -3
  90. package/src/runs/shared/external-job-bridge.ts +444 -0
  91. package/src/runs/shared/external-job-runner.ts +286 -0
  92. package/src/runs/shared/mcp-direct-tool-allowlist.ts +14 -0
  93. package/src/runs/shared/model-exclusions.ts +242 -0
  94. package/src/runs/shared/model-fallback.ts +153 -40
  95. package/src/runs/shared/orca-progress-tabs.ts +84 -22
  96. package/src/runs/shared/parallel-handoff.ts +46 -4
  97. package/src/runs/shared/parallel-utils.ts +4 -15
  98. package/src/runs/shared/permissions.ts +5 -1
  99. package/src/runs/shared/pi-args.ts +8 -1
  100. package/src/runs/shared/session-lease.ts +0 -6
  101. package/src/runs/shared/subagent-control.ts +51 -7
  102. package/src/runs/shared/subagent-prompt-runtime.ts +12 -6
  103. package/src/runs/shared/workflow-graph.ts +1 -23
  104. package/src/runs/shared/worktree.ts +14 -2
  105. package/src/shared/atomic-json.ts +22 -2
  106. package/src/shared/capacity-resilient-json.ts +102 -0
  107. package/src/shared/completion-owner.ts +14 -0
  108. package/src/shared/file-system-retry.ts +49 -1
  109. package/src/shared/fork-context.ts +59 -1
  110. package/src/shared/model-info.ts +20 -0
  111. package/src/shared/prompt-resources.ts +0 -40
  112. package/src/shared/settings.ts +5 -29
  113. package/src/shared/types.ts +110 -26
  114. package/src/shared/utils.ts +8 -0
  115. package/src/shared/watch-strategy.ts +10 -0
  116. package/src/slash/slash-bridge.ts +2 -1
  117. package/src/slash/slash-commands.ts +47 -7
  118. package/src/slash/slash-live-state.ts +3 -3
  119. package/src/tui/fleet-status.ts +86 -1
  120. package/src/tui/fleet.ts +117 -16
  121. package/src/tui/render.ts +73 -3
  122. package/src/watchdog/change-signature.ts +1 -1
  123. package/src/watchdog/lsp-diagnostics.ts +1 -0
  124. package/src/workflows/chat-progress.ts +2 -2
  125. package/src/workflows/scripted-workflow.ts +320 -79
  126. package/src/workflows/workflow-receipt.ts +140 -0
  127. package/src/runs/foreground/chain-clarify.ts +0 -1354
  128. package/src/runs/foreground/chain-execution.ts +0 -1581
@@ -28,8 +28,10 @@ export const KNOWN_FIELDS = new Set([
28
28
  "extensions",
29
29
  "subagentOnlyExtensions",
30
30
  "output",
31
+ "outputMode",
31
32
  "defaultReads",
32
33
  "defaultProgress",
34
+ "injectToContext",
33
35
  "interactive",
34
36
  "maxSubagentDepth",
35
37
  "completionGuard",
@@ -113,11 +115,13 @@ export function serializeAgent(config: AgentConfig, options: SerializeAgentOptio
113
115
  }
114
116
 
115
117
  if (config.output) lines.push(`output: ${config.output}`);
118
+ if (config.outputMode || preserve("outputMode")) lines.push(`outputMode: ${config.outputMode ?? ""}`);
116
119
 
117
120
  const readsValue = joinComma(config.defaultReads);
118
121
  if (readsValue) lines.push(`defaultReads: ${readsValue}`);
119
122
 
120
123
  if (config.defaultProgress) lines.push("defaultProgress: true");
124
+ if (config.injectToContext) lines.push("injectToContext: true");
121
125
  if (config.interactive) lines.push("interactive: true");
122
126
  const maxSubagentDepth = config.maxSubagentDepth;
123
127
  if (typeof maxSubagentDepth === "number" && Number.isInteger(maxSubagentDepth) && maxSubagentDepth >= 0) {
@@ -16,6 +16,7 @@ import { mergeAgentsForScope } from "./agent-selection.ts";
16
16
  import { parseFrontmatter, parseFrontmatterList } from "./frontmatter.ts";
17
17
  import { buildRuntimeName, parsePackageName } from "./identity.ts";
18
18
  import { parseModelScopeConfig, type ModelScopeConfig } from "../runs/shared/model-scope.ts";
19
+ export { BUILTIN_AGENT_NAMES } from "./builtin-names.ts";
19
20
  export { buildRuntimeName, frontmatterNameForConfig, parsePackageName } from "./identity.ts";
20
21
  import { parseMemoryFrontmatter } from "./agent-memory.ts";
21
22
  import { resolveTurnBudgetConfig } from "../runs/shared/turn-budget.ts";
@@ -24,7 +25,7 @@ import { validatePermissionRules, type PermissionRules } from "../runs/shared/pe
24
25
 
25
26
  export type AgentScope = "user" | "project" | "both";
26
27
 
27
- export type AgentSource = "builtin" | "package" | "user" | "project";
28
+ export type AgentSource = "builtin" | "package" | "user" | "project" | "runtime";
28
29
  type SystemPromptMode = "append" | "replace";
29
30
  export type AgentDefaultContext = "fresh" | "fork";
30
31
 
@@ -35,16 +36,6 @@ export interface AgentMemoryConfig {
35
36
  path: string;
36
37
  }
37
38
 
38
- export const BUILTIN_AGENT_NAMES = [
39
- "advisor",
40
- "delegate",
41
- "oracle",
42
- "researcher",
43
- "reviewer",
44
- "scout",
45
- "worker",
46
- ] as const;
47
-
48
39
  export function defaultSystemPromptMode(name: string): SystemPromptMode {
49
40
  return name === "delegate" ? "append" : "replace";
50
41
  }
@@ -59,6 +50,7 @@ export function defaultInheritSkills(): boolean {
59
50
 
60
51
  export interface BuiltinAgentOverrideBase {
61
52
  description?: string;
53
+ outputMode?: OutputMode;
62
54
  model?: string;
63
55
  fallbackModels?: string[];
64
56
  thinking?: string | false;
@@ -81,6 +73,7 @@ export interface BuiltinAgentOverrideBase {
81
73
 
82
74
  interface BuiltinAgentOverrideConfig {
83
75
  description?: string;
76
+ outputMode?: OutputMode;
84
77
  model?: string | false;
85
78
  fallbackModels?: string[] | false;
86
79
  thinking?: string | false;
@@ -137,14 +130,17 @@ export interface AgentConfig {
137
130
  systemPrompt: string;
138
131
  source: AgentSource;
139
132
  filePath: string;
133
+ discoveryPriority?: number;
140
134
  skills?: string[];
141
135
  skillPath?: string[];
142
136
  extensions?: string[];
143
137
  extensionsFromDefault?: boolean;
144
138
  subagentOnlyExtensions?: string[];
145
139
  output?: string;
140
+ outputMode?: OutputMode;
146
141
  defaultReads?: string[];
147
142
  defaultProgress?: boolean;
143
+ injectToContext?: boolean;
148
144
  interactive?: boolean;
149
145
  maxSubagentDepth?: number;
150
146
  completionGuard?: boolean;
@@ -167,6 +163,7 @@ interface SubagentSettings {
167
163
  disableBuiltins?: boolean;
168
164
  disableThinking?: boolean;
169
165
  modelScope?: ModelScopeConfig;
166
+ injectAgents?: string[];
170
167
  }
171
168
 
172
169
  const EMPTY_SUBAGENT_SETTINGS: SubagentSettings = { overrides: {} };
@@ -212,10 +209,49 @@ export interface ChainDiscoveryDiagnostic {
212
209
  error: string;
213
210
  }
214
211
 
212
+ export interface AgentDiscoveryDiagnostic extends ChainDiscoveryDiagnostic {
213
+ name?: string;
214
+ runtimeName?: string;
215
+ packageSpecified?: boolean;
216
+ discoveryPriority?: number;
217
+ }
218
+
219
+ const AGENT_SOURCE_PRIORITY: Record<AgentSource, number> = {
220
+ builtin: 0,
221
+ package: 1,
222
+ user: 2,
223
+ project: 3,
224
+ runtime: 4,
225
+ };
226
+
227
+ function agentDefinitionPriority(definition: Pick<AgentConfig | AgentDiscoveryDiagnostic, "source" | "discoveryPriority">): number {
228
+ return AGENT_SOURCE_PRIORITY[definition.source] * 1_000_000
229
+ + (definition.discoveryPriority ?? 0);
230
+ }
231
+
232
+ export function findBlockingAgentDiagnostic(name: string, agent: AgentConfig | readonly AgentConfig[] | undefined, diagnostics: AgentDiscoveryDiagnostic[] | undefined): AgentDiscoveryDiagnostic | undefined {
233
+ const normalizedName = name.trim();
234
+ const agents = Array.isArray(agent) ? agent : agent ? [agent] : [];
235
+ let match: AgentDiscoveryDiagnostic | undefined;
236
+ for (const diagnostic of diagnostics ?? []) {
237
+ if ((diagnostic.runtimeName === normalizedName
238
+ || (diagnostic.name === normalizedName && (!diagnostic.packageSpecified
239
+ || diagnostic.runtimeName === undefined
240
+ || agents.some((agent) => agent.name === diagnostic.runtimeName && agent.localName === diagnostic.name))))
241
+ && (!match || agentDefinitionPriority(diagnostic) > agentDefinitionPriority(match))) {
242
+ match = diagnostic;
243
+ }
244
+ }
245
+ const highestPriority = Math.max(...agents.map(agentDefinitionPriority), -Infinity);
246
+ return !agents.length || (match && agentDefinitionPriority(match) > highestPriority) ? match : undefined;
247
+ }
248
+
215
249
  interface AgentDiscoveryResult {
216
250
  agents: AgentConfig[];
251
+ agentDiagnostics?: AgentDiscoveryDiagnostic[];
217
252
  projectAgentsDir: string | null;
218
253
  modelScope?: ModelScopeConfig;
254
+ injectAgents?: string[];
219
255
  }
220
256
 
221
257
  function getUserChainDir(): string {
@@ -229,9 +265,19 @@ interface PackageSubagentPaths {
229
265
 
230
266
  let cachedGlobalNpmRoot: string | null = null;
231
267
 
232
- 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 {
233
278
  try {
234
- 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;
235
281
  } catch {
236
282
  // Installed package scans are opportunistic; bad third-party manifests
237
283
  // should not break local agent discovery.
@@ -239,9 +285,10 @@ function readJsonFileBestEffort(filePath: string): unknown {
239
285
  }
240
286
  }
241
287
 
242
- function readOptionalJsonFile(filePath: string): unknown {
288
+ function readOptionalJsonFile(filePath: string): JsonObjectFile | null {
289
+ let parsed: unknown;
243
290
  try {
244
- return JSON.parse(fs.readFileSync(filePath, "utf-8"));
291
+ parsed = JSON.parse(fs.readFileSync(filePath, "utf-8"));
245
292
  } catch (error) {
246
293
  const code = typeof error === "object" && error !== null && "code" in error
247
294
  ? (error as { code?: unknown }).code
@@ -249,6 +296,7 @@ function readOptionalJsonFile(filePath: string): unknown {
249
296
  if (code === "ENOENT") return null;
250
297
  throw error;
251
298
  }
299
+ return isJsonObjectRecord(parsed) ? parsed : null;
252
300
  }
253
301
 
254
302
  function isSafePackagePath(value: string): boolean {
@@ -345,7 +393,7 @@ function getGlobalNpmRoot(): string | null {
345
393
  }
346
394
 
347
395
  try {
348
- cachedGlobalNpmRoot = fs.realpathSync(execSync("npm root -g", { encoding: "utf-8", timeout: 5000 }).trim());
396
+ cachedGlobalNpmRoot = fs.realpathSync(execSync("npm root -g", { encoding: "utf-8", timeout: 5000, windowsHide: true }).trim());
349
397
  return cachedGlobalNpmRoot;
350
398
  } catch {
351
399
  cachedGlobalNpmRoot = "";
@@ -361,15 +409,15 @@ function stringArray(value: unknown): string[] {
361
409
  function extractSubagentPathsFromPackageRoot(packageRoot: string): PackageSubagentPaths {
362
410
  const packageJsonPath = path.join(packageRoot, "package.json");
363
411
  const pkg = readJsonFileBestEffort(packageJsonPath);
364
- if (!pkg || typeof pkg !== "object" || Array.isArray(pkg)) return { agents: [], chains: [] };
412
+ if (!pkg) return { agents: [], chains: [] };
365
413
 
366
414
  const roots: Record<string, unknown>[] = [];
367
- const piSubagents = (pkg as { "pi-subagents"?: unknown })["pi-subagents"];
415
+ const piSubagents = pkg["pi-subagents"];
368
416
  if (piSubagents && typeof piSubagents === "object" && !Array.isArray(piSubagents)) {
369
417
  roots.push(piSubagents as Record<string, unknown>);
370
418
  }
371
419
 
372
- const pi = (pkg as { pi?: unknown }).pi;
420
+ const pi = pkg.pi;
373
421
  if (pi && typeof pi === "object" && !Array.isArray(pi)) {
374
422
  const subagents = (pi as { subagents?: unknown }).subagents;
375
423
  if (subagents && typeof subagents === "object" && !Array.isArray(subagents)) {
@@ -424,8 +472,8 @@ function collectPackageRootsFromNodeModules(nodeModulesDir: string): string[] {
424
472
 
425
473
  function collectSettingsPackageRoots(settingsFile: string, baseDir: string): string[] {
426
474
  const settings = readOptionalJsonFile(settingsFile);
427
- if (!settings || typeof settings !== "object" || Array.isArray(settings)) return [];
428
- const packages = (settings as { packages?: unknown }).packages;
475
+ if (!settings) return [];
476
+ const packages = settings.packages;
429
477
  if (!Array.isArray(packages)) return [];
430
478
 
431
479
  const roots: string[] = [];
@@ -502,7 +550,7 @@ function normalizeAgentAliases(rawAliases: string[] | undefined, agentName: stri
502
550
  function effectiveAgentMatch(matches: AgentConfig[]): { agent?: AgentConfig; error?: string } {
503
551
  const distinctNames = [...new Set(matches.map((agent) => agent.name))];
504
552
  if (distinctNames.length === 1) {
505
- const sourceRank = new Map<AgentConfig["source"], number>([["builtin", 0], ["package", 1], ["user", 2], ["project", 3]]);
553
+ const sourceRank = new Map<AgentConfig["source"], number>([["builtin", 0], ["package", 1], ["user", 2], ["project", 3], ["runtime", 4]]);
506
554
  const agent = [...matches].sort((a, b) => (sourceRank.get(b.source) ?? 0) - (sourceRank.get(a.source) ?? 0))[0];
507
555
  return agent ? { agent } : {};
508
556
  }
@@ -566,6 +614,7 @@ function arraysEqual(a: string[] | undefined, b: string[] | undefined): boolean
566
614
  function cloneOverrideBase(agent: AgentConfig): BuiltinAgentOverrideBase {
567
615
  return {
568
616
  description: agent.description,
617
+ ...(agent.outputMode !== undefined ? { outputMode: agent.outputMode } : {}),
569
618
  ...(agent.model !== undefined ? { model: agent.model } : {}),
570
619
  ...(agent.fallbackModels ? { fallbackModels: [...agent.fallbackModels] } : {}),
571
620
  ...(agent.thinking !== undefined ? { thinking: agent.thinking } : {}),
@@ -590,6 +639,7 @@ function cloneOverrideBase(agent: AgentConfig): BuiltinAgentOverrideBase {
590
639
  function cloneOverrideValue(override: BuiltinAgentOverrideConfig): BuiltinAgentOverrideConfig {
591
640
  return {
592
641
  ...(override.description !== undefined ? { description: override.description } : {}),
642
+ ...(override.outputMode !== undefined ? { outputMode: override.outputMode } : {}),
593
643
  ...(override.model !== undefined ? { model: override.model } : {}),
594
644
  ...(override.fallbackModels !== undefined
595
645
  ? { fallbackModels: override.fallbackModels === false ? false : [...override.fallbackModels] }
@@ -770,6 +820,14 @@ function parseBuiltinOverrideEntry(
770
820
  }
771
821
  }
772
822
 
823
+ if ("outputMode" in input) {
824
+ if (input.outputMode === "inline" || input.outputMode === "file-only") {
825
+ override.outputMode = input.outputMode;
826
+ } else {
827
+ throw new Error(`Builtin override '${name}' in '${filePath}' has invalid 'outputMode'; expected 'inline' or 'file-only'.`);
828
+ }
829
+ }
830
+
773
831
  if ("model" in input) {
774
832
  if (typeof input.model === "string" || input.model === false) override.model = input.model;
775
833
  else throw new Error(`Builtin override '${name}' in '${filePath}' has invalid 'model'; expected a string or false.`);
@@ -916,6 +974,14 @@ function readSubagentSettings(filePath: string | null): SubagentSettings {
916
974
  }
917
975
  defaultExtensions = subagentsObject.defaultExtensions.map((item) => item.trim());
918
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
+ }
919
985
  const modelScope = parseModelScopeConfig(subagentsObject.modelScope, { filePath });
920
986
 
921
987
  const parsed: Record<string, BuiltinAgentOverrideConfig> = {};
@@ -928,6 +994,7 @@ function readSubagentSettings(filePath: string | null): SubagentSettings {
928
994
  ...(disableBuiltins !== undefined ? { disableBuiltins } : {}),
929
995
  ...(disableThinking !== undefined ? { disableThinking } : {}),
930
996
  ...(modelScope !== undefined ? { modelScope } : {}),
997
+ ...(injectAgents !== undefined ? { injectAgents } : {}),
931
998
  };
932
999
  if (!agentOverrides || typeof agentOverrides !== "object" || Array.isArray(agentOverrides)) {
933
1000
  return parsedSettings;
@@ -1038,6 +1105,7 @@ function applyBuiltinOverride(
1038
1105
  };
1039
1106
 
1040
1107
  if (override.description !== undefined) next.description = override.description;
1108
+ if (override.outputMode !== undefined) next.outputMode = override.outputMode;
1041
1109
  if (override.model !== undefined) {
1042
1110
  if (override.model === false) delete next.model; else next.model = override.model;
1043
1111
  delete next.modelSource;
@@ -1155,6 +1223,9 @@ function applyCustomAgentOverride(
1155
1223
  mutable().description = override.description;
1156
1224
  anyFilled = true;
1157
1225
  }
1226
+ if (override.outputMode !== undefined) {
1227
+ fill("outputMode", ["outputMode"], override.outputMode);
1228
+ }
1158
1229
  if (override.model !== undefined && !agentHasFrontmatterField(agent, "model")) {
1159
1230
  const target = mutable();
1160
1231
  if (override.model === false) delete target.model; else target.model = override.model;
@@ -1245,7 +1316,7 @@ function applyCustomAgentOverrides(
1245
1316
 
1246
1317
  export function buildBuiltinOverrideConfig(
1247
1318
  base: BuiltinAgentOverrideBase,
1248
- draft: Pick<AgentConfig, "model" | "fallbackModels" | "thinking" | "systemPromptMode" | "inheritProjectContext" | "inheritSkills" | "defaultContext" | "acceptanceRole" | "disabled" | "systemPrompt" | "skills" | "tools" | "mcpDirectTools" | "extensions" | "subagentOnlyExtensions" | "completionGuard" | "toolBudget"> & Partial<Pick<AgentConfig, "description">>,
1319
+ draft: Pick<AgentConfig, "model" | "fallbackModels" | "thinking" | "systemPromptMode" | "inheritProjectContext" | "inheritSkills" | "defaultContext" | "acceptanceRole" | "disabled" | "systemPrompt" | "skills" | "tools" | "mcpDirectTools" | "extensions" | "subagentOnlyExtensions" | "completionGuard" | "toolBudget"> & Partial<Pick<AgentConfig, "description" | "outputMode">>,
1249
1320
  ): BuiltinAgentOverrideConfig | undefined {
1250
1321
  const override: BuiltinAgentOverrideConfig = {};
1251
1322
 
@@ -1253,6 +1324,7 @@ export function buildBuiltinOverrideConfig(
1253
1324
  const description = draft.description.trim();
1254
1325
  if (description && description !== base.description) override.description = description;
1255
1326
  }
1327
+ if (draft.outputMode !== undefined && draft.outputMode !== base.outputMode) override.outputMode = draft.outputMode;
1256
1328
  if (draft.model !== base.model) override.model = draft.model ?? false;
1257
1329
  if (!arraysEqual(draft.fallbackModels, base.fallbackModels)) override.fallbackModels = draft.fallbackModels ? [...draft.fallbackModels] : false;
1258
1330
  if (draft.thinking !== base.thinking) override.thinking = draft.thinking ?? false;
@@ -1448,6 +1520,14 @@ function isLegacyAgentSkillPath(rootDir: string, filePath: string): boolean {
1448
1520
  return parts.some((part, index) => part === ".agents" && parts[index + 1] === "skills");
1449
1521
  }
1450
1522
 
1523
+ function isJsonSerializable(value: unknown): boolean {
1524
+ if (value === null || typeof value === "string" || typeof value === "boolean") return true;
1525
+ if (typeof value === "number") return Number.isFinite(value);
1526
+ if (Array.isArray(value)) return value.every(isJsonSerializable);
1527
+ if (value && typeof value === "object") return Object.values(value).every(isJsonSerializable);
1528
+ return false;
1529
+ }
1530
+
1451
1531
  function parseAgentRunnerFrontmatter(raw: string | undefined, agentName: string): AgentRunnerConfig | undefined {
1452
1532
  if (raw === undefined || !raw.trim()) return undefined;
1453
1533
  let parsed: unknown;
@@ -1464,8 +1544,24 @@ function parseAgentRunnerFrontmatter(raw: string | undefined, agentName: string)
1464
1544
  if (Object.keys(runner).some((key) => key !== "type")) throw new Error(`Agent '${agentName}' has invalid Pi runner frontmatter; only 'type' is supported.`);
1465
1545
  return { type: "pi" };
1466
1546
  }
1547
+ if (runner.type === "external-job") {
1548
+ if (typeof runner.provider !== "string" || !runner.provider.trim() || runner.provider.trim() !== runner.provider) {
1549
+ throw new Error(`Agent '${agentName}' external-job runner requires a non-empty trimmed provider string.`);
1550
+ }
1551
+ if (runner.options !== undefined && (!runner.options || typeof runner.options !== "object" || Array.isArray(runner.options) || !isJsonSerializable(runner.options))) {
1552
+ throw new Error(`Agent '${agentName}' external-job runner options must be a JSON-serializable object.`);
1553
+ }
1554
+ const supported = new Set(["type", "provider", "options"]);
1555
+ const unknown = Object.keys(runner).filter((key) => !supported.has(key));
1556
+ if (unknown.length > 0) throw new Error(`Agent '${agentName}' external-job runner has unsupported fields: ${unknown.join(", ")}.`);
1557
+ return {
1558
+ type: "external-job",
1559
+ provider: runner.provider,
1560
+ ...(runner.options ? { options: runner.options as Record<string, unknown> } : {}),
1561
+ };
1562
+ }
1467
1563
  if (runner.type !== "external-cli") {
1468
- throw new Error(`Agent '${agentName}' has invalid runner.type; expected 'pi' or 'external-cli'.`);
1564
+ throw new Error(`Agent '${agentName}' has invalid runner.type; expected 'pi', 'external-cli', or 'external-job'.`);
1469
1565
  }
1470
1566
  if (typeof runner.command !== "string" || !runner.command.trim()) {
1471
1567
  throw new Error(`Agent '${agentName}' external-cli runner requires a non-empty command string.`);
@@ -1489,11 +1585,11 @@ function parseAgentRunnerFrontmatter(raw: string | undefined, agentName: string)
1489
1585
  }
1490
1586
 
1491
1587
  function validateExternalRunnerProfile(frontmatter: Record<string, string>, agentName: string, runner: AgentRunnerConfig | undefined): void {
1492
- if (runner?.type !== "external-cli") return;
1588
+ if (runner?.type !== "external-cli" && runner?.type !== "external-job") return;
1493
1589
  const unsupported = ["tools", "model", "fallbackModels", "thinking", "extensions", "subagentOnlyExtensions", "maxSubagentDepth", "completionGuard", "skills", "skill", "skillPath", "toolBudget", "permission", "permissions"]
1494
1590
  .filter((field) => frontmatter[field] !== undefined);
1495
1591
  if (unsupported.length > 0) {
1496
- throw new Error(`Agent '${agentName}' uses runner.type='external-cli' and declares unsupported Pi-only fields: ${unsupported.join(", ")}.`);
1592
+ throw new Error(`Agent '${agentName}' uses runner.type='${runner.type}' and declares unsupported Pi-only fields: ${unsupported.join(", ")}.`);
1497
1593
  }
1498
1594
  }
1499
1595
 
@@ -1510,21 +1606,48 @@ function parseAgentAcceptanceFrontmatter(raw: string | undefined, agentName: str
1510
1606
  return parsed as AcceptanceInput;
1511
1607
  }
1512
1608
 
1513
- function loadAgentsFromDir(dir: string, source: AgentSource): AgentConfig[] {
1514
- const agents: AgentConfig[] = [];
1609
+ interface AgentDefinitionFile {
1610
+ filePath: string;
1611
+ content: string;
1612
+ }
1515
1613
 
1614
+ function readAgentDefinitionFiles(dir: string): AgentDefinitionFile[] {
1615
+ const files: AgentDefinitionFile[] = [];
1516
1616
  for (const filePath of listFilesRecursive(dir, (fileName) => fileName.endsWith(".md") && !fileName.endsWith(".chain.md"))) {
1517
1617
  if (isLegacyAgentSkillPath(dir, filePath)) {
1518
1618
  continue;
1519
1619
  }
1520
1620
 
1521
- let content: string;
1522
1621
  try {
1523
- content = fs.readFileSync(filePath, "utf-8");
1622
+ files.push({ filePath, content: fs.readFileSync(filePath, "utf-8") });
1524
1623
  } catch {
1525
1624
  continue;
1526
1625
  }
1626
+ }
1627
+ return files;
1628
+ }
1629
+
1630
+ function resolveAgentRelativeExtensionPaths(paths: string[] | undefined, agentFilePath: string): string[] | undefined {
1631
+ if (paths === undefined) return undefined;
1632
+ const baseDir = path.dirname(agentFilePath);
1633
+ return paths.map((entry) => {
1634
+ const trimmed = entry.trim();
1635
+ if (trimmed === "." || trimmed === ".." || trimmed.startsWith("./") || trimmed.startsWith("../")) {
1636
+ return path.resolve(baseDir, trimmed);
1637
+ }
1638
+ return entry;
1639
+ });
1640
+ }
1641
+
1642
+ function loadAgentsFromDefinitionFiles(files: AgentDefinitionFile[], source: AgentSource, discoveryPriority?: number): { agents: AgentConfig[]; diagnostics: AgentDiscoveryDiagnostic[] } {
1643
+ const agents: AgentConfig[] = [];
1644
+ const diagnostics: AgentDiscoveryDiagnostic[] = [];
1527
1645
 
1646
+ for (const { filePath, content } of files) {
1647
+ let name: string | undefined;
1648
+ let runtimeName: string | undefined;
1649
+ let packageSpecified = false;
1650
+ try {
1528
1651
  const { frontmatter, body } = parseFrontmatter(content);
1529
1652
 
1530
1653
  if (!frontmatter.name || !frontmatter.description) {
@@ -1532,10 +1655,12 @@ function loadAgentsFromDir(dir: string, source: AgentSource): AgentConfig[] {
1532
1655
  }
1533
1656
 
1534
1657
  const localName = frontmatter.name;
1658
+ name = localName;
1535
1659
  const parsedPackage = parsePackageName(frontmatter.package, `Agent '${localName}' package`);
1536
- if (parsedPackage.error) continue;
1660
+ packageSpecified = parsedPackage.packageName !== undefined || parsedPackage.error !== undefined;
1661
+ if (parsedPackage.error) throw new Error(parsedPackage.error);
1537
1662
  const packageName = parsedPackage.packageName;
1538
- const runtimeName = buildRuntimeName(localName, packageName);
1663
+ runtimeName = buildRuntimeName(localName, packageName);
1539
1664
 
1540
1665
  const runner = parseAgentRunnerFrontmatter(frontmatter.runner, localName);
1541
1666
  validateExternalRunnerProfile(frontmatter, localName, runner);
@@ -1599,14 +1724,19 @@ function loadAgentsFromDir(dir: string, source: AgentSource): AgentConfig[] {
1599
1724
  defaultTurnBudget = resolved.turnBudget;
1600
1725
  }
1601
1726
  const defaultAcceptance = parseAgentAcceptanceFrontmatter(frontmatter.acceptance, localName);
1727
+ let outputMode: OutputMode | undefined;
1728
+ if (frontmatter.outputMode !== undefined) {
1729
+ if (frontmatter.outputMode === "inline" || frontmatter.outputMode === "file-only") outputMode = frontmatter.outputMode;
1730
+ else throw new Error(`Agent '${localName}' has invalid outputMode frontmatter; expected 'inline' or 'file-only'.`);
1731
+ }
1602
1732
  let acceptanceRole: AcceptanceRole | undefined;
1603
1733
  if (frontmatter.acceptanceRole !== undefined && frontmatter.acceptanceRole.trim()) {
1604
1734
  if (frontmatter.acceptanceRole === "read-only" || frontmatter.acceptanceRole === "writer") acceptanceRole = frontmatter.acceptanceRole;
1605
1735
  else throw new Error(`Agent '${localName}' has invalid acceptanceRole frontmatter; expected 'read-only' or 'writer'.`);
1606
1736
  }
1607
1737
 
1608
- const extensions = parseFrontmatterList(frontmatter.extensions);
1609
- const subagentOnlyExtensions = parseFrontmatterList(frontmatter.subagentOnlyExtensions);
1738
+ const extensions = resolveAgentRelativeExtensionPaths(parseFrontmatterList(frontmatter.extensions), filePath);
1739
+ const subagentOnlyExtensions = resolveAgentRelativeExtensionPaths(parseFrontmatterList(frontmatter.subagentOnlyExtensions), filePath);
1610
1740
 
1611
1741
  const extraFields: Record<string, string> = {};
1612
1742
  for (const [key, value] of Object.entries(frontmatter)) {
@@ -1664,13 +1794,16 @@ function loadAgentsFromDir(dir: string, source: AgentSource): AgentConfig[] {
1664
1794
  systemPrompt: body,
1665
1795
  source,
1666
1796
  filePath,
1797
+ ...(discoveryPriority !== undefined ? { discoveryPriority } : {}),
1667
1798
  ...(skills?.length ? { skills } : {}),
1668
1799
  ...(skillPath?.length ? { skillPath } : {}),
1669
1800
  ...(extensions !== undefined ? { extensions } : {}),
1670
1801
  ...(subagentOnlyExtensions !== undefined ? { subagentOnlyExtensions } : {}),
1671
1802
  ...(frontmatter.output !== undefined ? { output: frontmatter.output } : {}),
1803
+ ...(outputMode !== undefined ? { outputMode } : {}),
1672
1804
  ...(defaultReads?.length ? { defaultReads } : {}),
1673
1805
  defaultProgress: frontmatter.defaultProgress === "true",
1806
+ injectToContext: frontmatter.injectToContext === "true",
1674
1807
  interactive: frontmatter.interactive === "true",
1675
1808
  ...(maxSubagentDepth !== undefined ? { maxSubagentDepth } : {}),
1676
1809
  ...(completionGuard !== undefined ? { completionGuard } : {}),
@@ -1681,9 +1814,16 @@ function loadAgentsFromDir(dir: string, source: AgentSource): AgentConfig[] {
1681
1814
  };
1682
1815
  agentFrontmatterFields.set(agent, new Set(Object.keys(frontmatter)));
1683
1816
  agents.push(agent);
1817
+ } catch (error) {
1818
+ diagnostics.push({ source, filePath, ...(name ? { name } : {}), ...(runtimeName && runtimeName !== name ? { runtimeName } : {}), ...(packageSpecified ? { packageSpecified: true } : {}), ...(discoveryPriority !== undefined ? { discoveryPriority } : {}), error: error instanceof Error ? error.message : String(error) });
1819
+ }
1684
1820
  }
1685
1821
 
1686
- return agents;
1822
+ return { agents, diagnostics };
1823
+ }
1824
+
1825
+ function loadAgentsFromDir(dir: string, source: AgentSource, discoveryPriority?: number): { agents: AgentConfig[]; diagnostics: AgentDiscoveryDiagnostic[] } {
1826
+ return loadAgentsFromDefinitionFiles(readAgentDefinitionFiles(dir), source, discoveryPriority);
1687
1827
  }
1688
1828
 
1689
1829
  function loadChainsFromDir(dir: string, source: AgentSource): { chains: ChainConfig[]; diagnostics: ChainDiscoveryDiagnostic[] } {
@@ -1747,6 +1887,7 @@ function resolveNearestProjectChainDirs(cwd: string): { readDirs: string[]; pref
1747
1887
  };
1748
1888
  }
1749
1889
  const BUILTIN_AGENTS_DIR = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..", "..", "agents");
1890
+ const BUILTIN_AGENT_DEFINITION_FILES = readAgentDefinitionFiles(BUILTIN_AGENTS_DIR);
1750
1891
 
1751
1892
  export const EXTRA_AGENT_DIRS_ENV = "PI_SUBAGENT_EXTRA_AGENT_DIRS";
1752
1893
 
@@ -1775,40 +1916,51 @@ export function discoverAgents(cwd: string, scope: AgentScope): AgentDiscoveryRe
1775
1916
  const defaultModel = resolveSubagentDefaultModel(userSettings, projectSettings, userSettingsPath, projectSettingsPath);
1776
1917
  const defaultThinking = resolveSubagentDefaultThinking(userSettings, projectSettings, projectSettingsPath);
1777
1918
  const defaultExtensions = resolveSubagentDefaultExtensions(userSettings, projectSettings, projectSettingsPath);
1919
+ const injectAgents = projectSettingsPath && projectSettings.injectAgents !== undefined
1920
+ ? projectSettings.injectAgents
1921
+ : userSettings.injectAgents;
1778
1922
  const modelScope = projectSettings.modelScope ?? userSettings.modelScope;
1779
1923
  const packageSubagentPaths = collectPackageSubagentPaths(cwd, {
1780
1924
  includeUser: scope !== "project",
1781
1925
  includeProject: scope !== "user",
1782
1926
  });
1783
1927
 
1928
+ const builtinLoaded = loadAgentsFromDefinitionFiles(BUILTIN_AGENT_DEFINITION_FILES, "builtin");
1784
1929
  const builtinAgents = applyBuiltinOverrides(
1785
- applySubagentDefaults(loadAgentsFromDir(BUILTIN_AGENTS_DIR, "builtin"), defaultModel, defaultThinking, defaultExtensions),
1930
+ applySubagentDefaults(builtinLoaded.agents, defaultModel, defaultThinking, defaultExtensions),
1786
1931
  userSettings,
1787
1932
  projectSettings,
1788
1933
  userSettingsPath,
1789
1934
  projectSettingsPath,
1790
1935
  );
1791
1936
 
1792
- const userAgentsExtra = scope === "project" ? [] : extraUserAgentDirs().flatMap((dir) => loadAgentsFromDir(dir, "user"));
1793
- const userAgentsOld = scope === "project" ? [] : loadAgentsFromDir(userDirOld, "user");
1794
- const userAgentsNew = scope === "project" ? [] : loadAgentsFromDir(userDirNew, "user");
1937
+ const userLoaded = scope === "project" ? [] : [...extraUserAgentDirs(), userDirOld, userDirNew]
1938
+ .map((dir, discoveryPriority) => loadAgentsFromDir(dir, "user", discoveryPriority));
1795
1939
  const userAgents = applyCustomAgentOverrides(
1796
- applySubagentDefaults([...userAgentsExtra, ...userAgentsOld, ...userAgentsNew], defaultModel, defaultThinking, defaultExtensions),
1940
+ applySubagentDefaults(userLoaded.flatMap((loaded) => loaded.agents), defaultModel, defaultThinking, defaultExtensions),
1797
1941
  userSettings,
1798
1942
  projectSettings,
1799
1943
  userSettingsPath,
1800
1944
  projectSettingsPath,
1801
1945
  );
1802
1946
 
1947
+ const projectLoaded = scope === "user" ? [] : projectAgentDirs.map((dir) => loadAgentsFromDir(dir, "project", dir === projectAgentsDir ? 1 : 0));
1803
1948
  const projectAgents = applyCustomAgentOverrides(
1804
- applySubagentDefaults(scope === "user" ? [] : projectAgentDirs.flatMap((dir) => loadAgentsFromDir(dir, "project")), defaultModel, defaultThinking, defaultExtensions),
1949
+ applySubagentDefaults(projectLoaded.flatMap((loaded) => loaded.agents), defaultModel, defaultThinking, defaultExtensions),
1805
1950
  userSettings,
1806
1951
  projectSettings,
1807
1952
  userSettingsPath,
1808
1953
  projectSettingsPath,
1809
1954
  );
1955
+ const packageLoaded = packageSubagentPaths.agents.map((dir, index) => loadAgentsFromDir(dir, "package", packageSubagentPaths.agents.length - index));
1956
+ const packageMap = new Map<string, AgentConfig>();
1957
+ for (const loaded of packageLoaded) {
1958
+ for (const agent of loaded.agents) {
1959
+ if (!packageMap.has(agent.name)) packageMap.set(agent.name, agent);
1960
+ }
1961
+ }
1810
1962
  const packageAgents = applyCustomAgentOverrides(
1811
- applySubagentDefaults(packageSubagentPaths.agents.flatMap((dir) => loadAgentsFromDir(dir, "package")), defaultModel, defaultThinking, defaultExtensions),
1963
+ applySubagentDefaults(Array.from(packageMap.values()), defaultModel, defaultThinking, defaultExtensions),
1812
1964
  userSettings,
1813
1965
  projectSettings,
1814
1966
  userSettingsPath,
@@ -1817,7 +1969,13 @@ export function discoverAgents(cwd: string, scope: AgentScope): AgentDiscoveryRe
1817
1969
  const agents = mergeAgentsForScope(scope, userAgents, projectAgents, builtinAgents, packageAgents)
1818
1970
  .filter((agent) => agent.disabled !== true);
1819
1971
 
1820
- return { agents, projectAgentsDir, ...(modelScope !== undefined ? { modelScope } : {}) };
1972
+ const agentDiagnostics = [
1973
+ ...builtinLoaded.diagnostics,
1974
+ ...userLoaded.flatMap((loaded) => loaded.diagnostics),
1975
+ ...projectLoaded.flatMap((loaded) => loaded.diagnostics),
1976
+ ...packageLoaded.flatMap((loaded) => loaded.diagnostics),
1977
+ ];
1978
+ return { agents, agentDiagnostics, projectAgentsDir, ...(modelScope !== undefined ? { modelScope } : {}), ...(injectAgents?.length ? { injectAgents } : {}) };
1821
1979
  }
1822
1980
 
1823
1981
  export function discoverAgentsAll(cwd: string): {
@@ -1825,6 +1983,8 @@ export function discoverAgentsAll(cwd: string): {
1825
1983
  package: AgentConfig[];
1826
1984
  user: AgentConfig[];
1827
1985
  project: AgentConfig[];
1986
+ agentDiagnostics?: AgentDiscoveryDiagnostic[];
1987
+ injectAgents?: string[];
1828
1988
  chains: ChainConfig[];
1829
1989
  chainDiagnostics: ChainDiscoveryDiagnostic[];
1830
1990
  userDir: string;
@@ -1846,29 +2006,34 @@ export function discoverAgentsAll(cwd: string): {
1846
2006
  const defaultModel = resolveSubagentDefaultModel(userSettings, projectSettings, userSettingsPath, projectSettingsPath);
1847
2007
  const defaultThinking = resolveSubagentDefaultThinking(userSettings, projectSettings, projectSettingsPath);
1848
2008
  const defaultExtensions = resolveSubagentDefaultExtensions(userSettings, projectSettings, projectSettingsPath);
2009
+ const injectAgents = projectSettingsPath && projectSettings.injectAgents !== undefined
2010
+ ? projectSettings.injectAgents
2011
+ : userSettings.injectAgents;
1849
2012
  const packageSubagentPaths = collectPackageSubagentPaths(cwd);
1850
2013
 
2014
+ const builtinLoaded = loadAgentsFromDefinitionFiles(BUILTIN_AGENT_DEFINITION_FILES, "builtin");
1851
2015
  const builtin = applyBuiltinOverrides(
1852
- applySubagentDefaults(loadAgentsFromDir(BUILTIN_AGENTS_DIR, "builtin"), defaultModel, defaultThinking, defaultExtensions),
2016
+ applySubagentDefaults(builtinLoaded.agents, defaultModel, defaultThinking, defaultExtensions),
1853
2017
  userSettings,
1854
2018
  projectSettings,
1855
2019
  userSettingsPath,
1856
2020
  projectSettingsPath,
1857
2021
  );
2022
+ const userLoaded = [...extraUserAgentDirs(), userDirOld, userDirNew]
2023
+ .map((dir, discoveryPriority) => loadAgentsFromDir(dir, "user", discoveryPriority));
1858
2024
  const user = applyCustomAgentOverrides(
1859
- applySubagentDefaults([
1860
- ...extraUserAgentDirs().flatMap((dir) => loadAgentsFromDir(dir, "user")),
1861
- ...loadAgentsFromDir(userDirOld, "user"),
1862
- ...loadAgentsFromDir(userDirNew, "user"),
1863
- ], defaultModel, defaultThinking, defaultExtensions),
2025
+ applySubagentDefaults(userLoaded.flatMap((loaded) => loaded.agents), defaultModel, defaultThinking, defaultExtensions),
1864
2026
  userSettings,
1865
2027
  projectSettings,
1866
2028
  userSettingsPath,
1867
2029
  projectSettingsPath,
1868
2030
  );
1869
2031
  const packageMap = new Map<string, AgentConfig>();
1870
- for (const dir of packageSubagentPaths.agents) {
1871
- for (const agent of loadAgentsFromDir(dir, "package")) {
2032
+ const packageAgentDiagnostics: AgentDiscoveryDiagnostic[] = [];
2033
+ for (const [index, dir] of packageSubagentPaths.agents.entries()) {
2034
+ const loaded = loadAgentsFromDir(dir, "package", packageSubagentPaths.agents.length - index);
2035
+ packageAgentDiagnostics.push(...loaded.diagnostics);
2036
+ for (const agent of loaded.agents) {
1872
2037
  if (!packageMap.has(agent.name)) packageMap.set(agent.name, agent);
1873
2038
  }
1874
2039
  }
@@ -1880,8 +2045,11 @@ export function discoverAgentsAll(cwd: string): {
1880
2045
  projectSettingsPath,
1881
2046
  );
1882
2047
  const projectMap = new Map<string, AgentConfig>();
2048
+ const projectAgentDiagnostics: AgentDiscoveryDiagnostic[] = [];
1883
2049
  for (const dir of projectDirs) {
1884
- for (const agent of loadAgentsFromDir(dir, "project")) {
2050
+ const loaded = loadAgentsFromDir(dir, "project", dir === projectDir ? 1 : 0);
2051
+ projectAgentDiagnostics.push(...loaded.diagnostics);
2052
+ for (const agent of loaded.agents) {
1885
2053
  projectMap.set(agent.name, agent);
1886
2054
  }
1887
2055
  }
@@ -1922,8 +2090,14 @@ export function discoverAgentsAll(cwd: string): {
1922
2090
  ...userChains.diagnostics,
1923
2091
  ...projectChainDiagnostics,
1924
2092
  ];
2093
+ const agentDiagnostics = [
2094
+ ...builtinLoaded.diagnostics,
2095
+ ...userLoaded.flatMap((loaded) => loaded.diagnostics),
2096
+ ...packageAgentDiagnostics,
2097
+ ...projectAgentDiagnostics,
2098
+ ];
1925
2099
 
1926
2100
  const userDir = process.env.PI_CODING_AGENT_DIR ? userDirOld : fs.existsSync(userDirNew) ? userDirNew : userDirOld;
1927
2101
 
1928
- return { builtin, package: packageAgents, user, project, 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 } : {}) };
1929
2103
  }