pi-subagents 0.52.0 → 0.53.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 (54) hide show
  1. package/CHANGELOG.md +58 -0
  2. package/README.md +4 -0
  3. package/docs/configuration.md +11 -1
  4. package/docs/extension-api.md +3 -1
  5. package/docs/workflows.md +2 -0
  6. package/package.json +2 -1
  7. package/prompts/council.md +48 -0
  8. package/skills/council-mode/SKILL.md +230 -0
  9. package/skills/pi-subagents/SKILL.md +2 -0
  10. package/skills/pi-subagents/references/constraints-and-recipes.md +1 -0
  11. package/skills/pi-subagents/references/execution-controls.md +11 -0
  12. package/skills/pi-subagents/references/multi-lane-orchestration.md +39 -0
  13. package/src/agents/agent-management.ts +22 -3
  14. package/src/agents/agent-serializer.ts +2 -0
  15. package/src/agents/agents.ts +29 -13
  16. package/src/agents/builtin-names.ts +9 -0
  17. package/src/agents/runtime-agent-registry.ts +418 -0
  18. package/src/api/agents.ts +7 -0
  19. package/src/api/external-job-provider.ts +3 -2
  20. package/src/api/preflight.ts +1 -1
  21. package/src/extension/config.ts +3 -0
  22. package/src/extension/doctor.ts +1 -0
  23. package/src/extension/index.ts +17 -2
  24. package/src/extension/rpc.ts +41 -1
  25. package/src/extension/schemas.ts +7 -4
  26. package/src/extension/tool-description.ts +2 -2
  27. package/src/runs/background/async-execution.ts +2 -1
  28. package/src/runs/background/async-job-tracker.ts +4 -3
  29. package/src/runs/background/async-resume.ts +2 -1
  30. package/src/runs/background/async-status-snapshot.ts +14 -5
  31. package/src/runs/background/auto-drain.ts +1 -0
  32. package/src/runs/background/result-watcher.ts +8 -0
  33. package/src/runs/background/subagent-runner.ts +7 -4
  34. package/src/runs/background/subagent-wait.ts +9 -5
  35. package/src/runs/background/terminal-run-index.ts +15 -6
  36. package/src/runs/background/wait-tool.ts +1 -0
  37. package/src/runs/foreground/execution.ts +5 -1
  38. package/src/runs/foreground/subagent-executor.ts +182 -46
  39. package/src/runs/foreground/workflow-detach-reconcile.ts +83 -15
  40. package/src/runs/shared/acceptance.ts +44 -1
  41. package/src/runs/shared/model-exclusions.ts +242 -0
  42. package/src/runs/shared/model-fallback.ts +55 -2
  43. package/src/runs/shared/subagent-control.ts +25 -3
  44. package/src/shared/fork-context.ts +17 -1
  45. package/src/shared/model-info.ts +20 -0
  46. package/src/shared/settings.ts +2 -2
  47. package/src/shared/types.ts +35 -0
  48. package/src/slash/slash-commands.ts +20 -6
  49. package/src/slash/slash-live-state.ts +3 -3
  50. package/src/tui/fleet-status.ts +86 -1
  51. package/src/tui/fleet.ts +55 -2
  52. package/src/tui/render.ts +73 -3
  53. package/src/workflows/scripted-workflow.ts +100 -12
  54. package/src/workflows/workflow-receipt.ts +140 -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;
@@ -144,6 +137,7 @@ export interface AgentConfig {
144
137
  extensionsFromDefault?: boolean;
145
138
  subagentOnlyExtensions?: string[];
146
139
  output?: string;
140
+ outputMode?: OutputMode;
147
141
  defaultReads?: string[];
148
142
  defaultProgress?: boolean;
149
143
  interactive?: boolean;
@@ -225,6 +219,7 @@ const AGENT_SOURCE_PRIORITY: Record<AgentSource, number> = {
225
219
  package: 1,
226
220
  user: 2,
227
221
  project: 3,
222
+ runtime: 4,
228
223
  };
229
224
 
230
225
  function agentDefinitionPriority(definition: Pick<AgentConfig | AgentDiscoveryDiagnostic, "source" | "discoveryPriority">): number {
@@ -540,7 +535,7 @@ function normalizeAgentAliases(rawAliases: string[] | undefined, agentName: stri
540
535
  function effectiveAgentMatch(matches: AgentConfig[]): { agent?: AgentConfig; error?: string } {
541
536
  const distinctNames = [...new Set(matches.map((agent) => agent.name))];
542
537
  if (distinctNames.length === 1) {
543
- const sourceRank = new Map<AgentConfig["source"], number>([["builtin", 0], ["package", 1], ["user", 2], ["project", 3]]);
538
+ const sourceRank = new Map<AgentConfig["source"], number>([["builtin", 0], ["package", 1], ["user", 2], ["project", 3], ["runtime", 4]]);
544
539
  const agent = [...matches].sort((a, b) => (sourceRank.get(b.source) ?? 0) - (sourceRank.get(a.source) ?? 0))[0];
545
540
  return agent ? { agent } : {};
546
541
  }
@@ -604,6 +599,7 @@ function arraysEqual(a: string[] | undefined, b: string[] | undefined): boolean
604
599
  function cloneOverrideBase(agent: AgentConfig): BuiltinAgentOverrideBase {
605
600
  return {
606
601
  description: agent.description,
602
+ ...(agent.outputMode !== undefined ? { outputMode: agent.outputMode } : {}),
607
603
  ...(agent.model !== undefined ? { model: agent.model } : {}),
608
604
  ...(agent.fallbackModels ? { fallbackModels: [...agent.fallbackModels] } : {}),
609
605
  ...(agent.thinking !== undefined ? { thinking: agent.thinking } : {}),
@@ -628,6 +624,7 @@ function cloneOverrideBase(agent: AgentConfig): BuiltinAgentOverrideBase {
628
624
  function cloneOverrideValue(override: BuiltinAgentOverrideConfig): BuiltinAgentOverrideConfig {
629
625
  return {
630
626
  ...(override.description !== undefined ? { description: override.description } : {}),
627
+ ...(override.outputMode !== undefined ? { outputMode: override.outputMode } : {}),
631
628
  ...(override.model !== undefined ? { model: override.model } : {}),
632
629
  ...(override.fallbackModels !== undefined
633
630
  ? { fallbackModels: override.fallbackModels === false ? false : [...override.fallbackModels] }
@@ -808,6 +805,14 @@ function parseBuiltinOverrideEntry(
808
805
  }
809
806
  }
810
807
 
808
+ if ("outputMode" in input) {
809
+ if (input.outputMode === "inline" || input.outputMode === "file-only") {
810
+ override.outputMode = input.outputMode;
811
+ } else {
812
+ throw new Error(`Builtin override '${name}' in '${filePath}' has invalid 'outputMode'; expected 'inline' or 'file-only'.`);
813
+ }
814
+ }
815
+
811
816
  if ("model" in input) {
812
817
  if (typeof input.model === "string" || input.model === false) override.model = input.model;
813
818
  else throw new Error(`Builtin override '${name}' in '${filePath}' has invalid 'model'; expected a string or false.`);
@@ -1076,6 +1081,7 @@ function applyBuiltinOverride(
1076
1081
  };
1077
1082
 
1078
1083
  if (override.description !== undefined) next.description = override.description;
1084
+ if (override.outputMode !== undefined) next.outputMode = override.outputMode;
1079
1085
  if (override.model !== undefined) {
1080
1086
  if (override.model === false) delete next.model; else next.model = override.model;
1081
1087
  delete next.modelSource;
@@ -1193,6 +1199,9 @@ function applyCustomAgentOverride(
1193
1199
  mutable().description = override.description;
1194
1200
  anyFilled = true;
1195
1201
  }
1202
+ if (override.outputMode !== undefined) {
1203
+ fill("outputMode", ["outputMode"], override.outputMode);
1204
+ }
1196
1205
  if (override.model !== undefined && !agentHasFrontmatterField(agent, "model")) {
1197
1206
  const target = mutable();
1198
1207
  if (override.model === false) delete target.model; else target.model = override.model;
@@ -1283,7 +1292,7 @@ function applyCustomAgentOverrides(
1283
1292
 
1284
1293
  export function buildBuiltinOverrideConfig(
1285
1294
  base: BuiltinAgentOverrideBase,
1286
- draft: Pick<AgentConfig, "model" | "fallbackModels" | "thinking" | "systemPromptMode" | "inheritProjectContext" | "inheritSkills" | "defaultContext" | "acceptanceRole" | "disabled" | "systemPrompt" | "skills" | "tools" | "mcpDirectTools" | "extensions" | "subagentOnlyExtensions" | "completionGuard" | "toolBudget"> & Partial<Pick<AgentConfig, "description">>,
1295
+ 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">>,
1287
1296
  ): BuiltinAgentOverrideConfig | undefined {
1288
1297
  const override: BuiltinAgentOverrideConfig = {};
1289
1298
 
@@ -1291,6 +1300,7 @@ export function buildBuiltinOverrideConfig(
1291
1300
  const description = draft.description.trim();
1292
1301
  if (description && description !== base.description) override.description = description;
1293
1302
  }
1303
+ if (draft.outputMode !== undefined && draft.outputMode !== base.outputMode) override.outputMode = draft.outputMode;
1294
1304
  if (draft.model !== base.model) override.model = draft.model ?? false;
1295
1305
  if (!arraysEqual(draft.fallbackModels, base.fallbackModels)) override.fallbackModels = draft.fallbackModels ? [...draft.fallbackModels] : false;
1296
1306
  if (draft.thinking !== base.thinking) override.thinking = draft.thinking ?? false;
@@ -1690,6 +1700,11 @@ function loadAgentsFromDefinitionFiles(files: AgentDefinitionFile[], source: Age
1690
1700
  defaultTurnBudget = resolved.turnBudget;
1691
1701
  }
1692
1702
  const defaultAcceptance = parseAgentAcceptanceFrontmatter(frontmatter.acceptance, localName);
1703
+ let outputMode: OutputMode | undefined;
1704
+ if (frontmatter.outputMode !== undefined) {
1705
+ if (frontmatter.outputMode === "inline" || frontmatter.outputMode === "file-only") outputMode = frontmatter.outputMode;
1706
+ else throw new Error(`Agent '${localName}' has invalid outputMode frontmatter; expected 'inline' or 'file-only'.`);
1707
+ }
1693
1708
  let acceptanceRole: AcceptanceRole | undefined;
1694
1709
  if (frontmatter.acceptanceRole !== undefined && frontmatter.acceptanceRole.trim()) {
1695
1710
  if (frontmatter.acceptanceRole === "read-only" || frontmatter.acceptanceRole === "writer") acceptanceRole = frontmatter.acceptanceRole;
@@ -1761,6 +1776,7 @@ function loadAgentsFromDefinitionFiles(files: AgentDefinitionFile[], source: Age
1761
1776
  ...(extensions !== undefined ? { extensions } : {}),
1762
1777
  ...(subagentOnlyExtensions !== undefined ? { subagentOnlyExtensions } : {}),
1763
1778
  ...(frontmatter.output !== undefined ? { output: frontmatter.output } : {}),
1779
+ ...(outputMode !== undefined ? { outputMode } : {}),
1764
1780
  ...(defaultReads?.length ? { defaultReads } : {}),
1765
1781
  defaultProgress: frontmatter.defaultProgress === "true",
1766
1782
  interactive: frontmatter.interactive === "true",
@@ -0,0 +1,9 @@
1
+ export const BUILTIN_AGENT_NAMES = [
2
+ "advisor",
3
+ "delegate",
4
+ "oracle",
5
+ "researcher",
6
+ "reviewer",
7
+ "scout",
8
+ "worker",
9
+ ] as const;
@@ -0,0 +1,418 @@
1
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
+ import type { AcceptanceInput, AcceptanceRole, AgentRunnerConfig, OutputMode, ToolBudgetConfig, TurnBudgetConfig } from "../shared/types.ts";
3
+ import { validateAcceptanceInput } from "../runs/shared/acceptance.ts";
4
+ import { validatePermissionRules, type PermissionRules } from "../runs/shared/permissions.ts";
5
+ import { validateToolBudgetConfig } from "../runs/shared/tool-budget.ts";
6
+ import { resolveTurnBudgetConfig } from "../runs/shared/turn-budget.ts";
7
+ import { BUILTIN_AGENT_NAMES } from "./builtin-names.ts";
8
+ import type { AgentConfig, AgentDefaultContext, AgentDiscoveryDiagnostic } from "./agents.ts";
9
+
10
+ export const RUNTIME_AGENT_REGISTRY_KEY = "pi-subagents.runtime-agents.v1";
11
+
12
+ const MAX_RUNTIME_AGENTS_PER_PI = 200;
13
+ const MAX_AGENT_NAME_LENGTH = 128;
14
+ const MAX_DESCRIPTION_LENGTH = 4_096;
15
+ const MAX_SYSTEM_PROMPT_LENGTH = 1024 * 1024;
16
+ const MAX_FIELD_STRING_LENGTH = 8_192;
17
+
18
+ export interface RuntimeAgentDefinition {
19
+ description: string;
20
+ systemPrompt: string;
21
+ aliases?: readonly string[];
22
+ tools?: readonly string[];
23
+ mcpDirectTools?: readonly string[];
24
+ model?: string;
25
+ fallbackModels?: readonly string[];
26
+ thinking?: string | false;
27
+ systemPromptMode?: "append" | "replace";
28
+ inheritProjectContext?: boolean;
29
+ inheritSkills?: boolean;
30
+ defaultContext?: AgentDefaultContext;
31
+ defaultAsync?: boolean;
32
+ defaultTimeoutMs?: number;
33
+ defaultToolTimeoutMs?: number;
34
+ defaultTurnBudget?: TurnBudgetConfig;
35
+ defaultAcceptance?: AcceptanceInput;
36
+ acceptanceRole?: AcceptanceRole;
37
+ runner?: AgentRunnerConfig;
38
+ skills?: readonly string[];
39
+ skillPath?: readonly string[];
40
+ extensions?: readonly string[];
41
+ subagentOnlyExtensions?: readonly string[];
42
+ output?: string;
43
+ outputMode?: OutputMode;
44
+ defaultReads?: readonly string[];
45
+ defaultProgress?: boolean;
46
+ interactive?: boolean;
47
+ maxSubagentDepth?: number;
48
+ completionGuard?: boolean;
49
+ toolBudget?: ToolBudgetConfig;
50
+ permissions?: PermissionRules;
51
+ }
52
+
53
+ export interface RegisterRuntimeAgentInput {
54
+ pi: ExtensionAPI;
55
+ name: string;
56
+ definition: RuntimeAgentDefinition;
57
+ }
58
+
59
+ export interface RuntimeAgentRegistration {
60
+ dispose(): void;
61
+ }
62
+
63
+ interface RuntimeAgentRecord {
64
+ pi: ExtensionAPI;
65
+ agent: AgentConfig;
66
+ }
67
+
68
+ interface RuntimeAgentRegistry {
69
+ version: 1;
70
+ byPi: WeakMap<ExtensionAPI, RuntimeAgentRecord[]>;
71
+ }
72
+
73
+ export type RuntimeAgentOwner = ExtensionAPI;
74
+
75
+ function defaultSystemPromptMode(name: string): "append" | "replace" {
76
+ return name === "delegate" ? "append" : "replace";
77
+ }
78
+
79
+ function defaultInheritProjectContext(name: string): boolean {
80
+ return name === "delegate";
81
+ }
82
+
83
+ function defaultInheritSkills(): boolean {
84
+ return false;
85
+ }
86
+
87
+ function registry(): RuntimeAgentRegistry {
88
+ const key = Symbol.for(RUNTIME_AGENT_REGISTRY_KEY);
89
+ const globalObject = globalThis as Record<PropertyKey, unknown>;
90
+ const existing = globalObject[key];
91
+ if (existing === undefined) {
92
+ const created: RuntimeAgentRegistry = { version: 1, byPi: new WeakMap() };
93
+ globalObject[key] = created;
94
+ return created;
95
+ }
96
+ if (!existing || typeof existing !== "object" || Array.isArray(existing)) {
97
+ throw new Error(`Malformed runtime agent registry at Symbol.for("${RUNTIME_AGENT_REGISTRY_KEY}").`);
98
+ }
99
+ const candidate = existing as Partial<RuntimeAgentRegistry>;
100
+ if (candidate.version !== 1 || !(candidate.byPi instanceof WeakMap)) {
101
+ throw new Error(`Unsupported runtime agent registry at Symbol.for("${RUNTIME_AGENT_REGISTRY_KEY}").`);
102
+ }
103
+ return candidate as RuntimeAgentRegistry;
104
+ }
105
+
106
+ function validatePi(value: unknown): ExtensionAPI {
107
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("Runtime agent pi must be an ExtensionAPI object.");
108
+ const pi = value as Partial<ExtensionAPI>;
109
+ if (typeof pi.on !== "function" || typeof pi.registerTool !== "function") throw new Error("Runtime agent pi must be an ExtensionAPI object.");
110
+ return value as ExtensionAPI;
111
+ }
112
+
113
+ function validateString(value: unknown, field: string, maxLength: number): string {
114
+ if (typeof value !== "string" || value.length === 0 || value.trim() !== value) {
115
+ throw new Error(`${field} must be a non-empty string without leading or trailing whitespace.`);
116
+ }
117
+ if (value.length > maxLength) throw new Error(`${field} must be at most ${maxLength} characters.`);
118
+ if (value.includes("\0")) throw new Error(`${field} must not contain NUL characters.`);
119
+ return value;
120
+ }
121
+
122
+ function validateOptionalString(value: unknown, field: string, maxLength = MAX_FIELD_STRING_LENGTH): string | undefined {
123
+ if (value === undefined) return undefined;
124
+ return validateString(value, field, maxLength);
125
+ }
126
+
127
+ function validateStringList(value: unknown, field: string): string[] | undefined {
128
+ if (value === undefined) return undefined;
129
+ if (!Array.isArray(value)) throw new Error(`${field} must be an array of strings when provided.`);
130
+ return [...new Set(value.map((entry, index) => validateString(entry, `${field}[${index}]`, MAX_FIELD_STRING_LENGTH)))];
131
+ }
132
+
133
+ function validatePositiveInteger(value: unknown, field: string): number | undefined {
134
+ if (value === undefined) return undefined;
135
+ if (!Number.isInteger(value) || (value as number) <= 0) throw new Error(`${field} must be a positive integer when provided.`);
136
+ return value as number;
137
+ }
138
+
139
+ function validateBoolean(value: unknown, field: string): boolean | undefined {
140
+ if (value === undefined) return undefined;
141
+ if (typeof value !== "boolean") throw new Error(`${field} must be a boolean when provided.`);
142
+ return value;
143
+ }
144
+
145
+ function isJsonSerializable(value: unknown): boolean {
146
+ if (value === null || typeof value === "string" || typeof value === "boolean") return true;
147
+ if (typeof value === "number") return Number.isFinite(value);
148
+ if (Array.isArray(value)) return value.every(isJsonSerializable);
149
+ if (value && typeof value === "object") return Object.values(value).every(isJsonSerializable);
150
+ return false;
151
+ }
152
+
153
+ function validateRunner(value: unknown): AgentRunnerConfig | undefined {
154
+ if (value === undefined) return undefined;
155
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("Runtime agent definition runner must be an object when provided.");
156
+ const runner = value as Record<string, unknown>;
157
+ if (runner.type === "pi") {
158
+ if (Object.keys(runner).some((key) => key !== "type")) throw new Error("Runtime agent definition Pi runner supports only 'type'.");
159
+ return { type: "pi" };
160
+ }
161
+ if (runner.type === "external-job") {
162
+ if (typeof runner.provider !== "string" || !runner.provider.trim() || runner.provider.trim() !== runner.provider) throw new Error("Runtime agent definition external-job runner requires a non-empty trimmed provider string.");
163
+ if (runner.options !== undefined && (!runner.options || typeof runner.options !== "object" || Array.isArray(runner.options) || !isJsonSerializable(runner.options))) throw new Error("Runtime agent definition external-job runner options must be a JSON-serializable object.");
164
+ const supported = new Set(["type", "provider", "options"]);
165
+ const unknown = Object.keys(runner).filter((key) => !supported.has(key));
166
+ if (unknown.length > 0) throw new Error(`Runtime agent definition external-job runner has unsupported fields: ${unknown.join(", ")}.`);
167
+ return { type: "external-job", provider: runner.provider, ...(runner.options ? { options: runner.options as Record<string, unknown> } : {}) };
168
+ }
169
+ if (runner.type !== "external-cli") throw new Error("Runtime agent definition runner.type must be 'pi', 'external-cli', or 'external-job'.");
170
+ if (typeof runner.command !== "string" || !runner.command.trim()) throw new Error("Runtime agent definition external-cli runner requires a non-empty command string.");
171
+ if (runner.args !== undefined && (!Array.isArray(runner.args) || runner.args.some((arg) => typeof arg !== "string"))) throw new Error("Runtime agent definition external-cli runner args must be an array of strings.");
172
+ if (runner.promptDelivery !== undefined && runner.promptDelivery !== "stdin") throw new Error("Runtime agent definition external-cli runner promptDelivery must be 'stdin'.");
173
+ const supported = new Set(["type", "command", "args", "promptDelivery"]);
174
+ const unknown = Object.keys(runner).filter((key) => !supported.has(key));
175
+ if (unknown.length > 0) throw new Error(`Runtime agent definition external-cli runner has unsupported fields: ${unknown.join(", ")}.`);
176
+ const args = runner.args as string[] | undefined;
177
+ return { type: "external-cli", command: runner.command.trim(), ...(args?.length ? { args } : {}), ...(runner.promptDelivery ? { promptDelivery: "stdin" as const } : {}) };
178
+ }
179
+
180
+ function validateTurnBudget(value: unknown): TurnBudgetConfig | undefined {
181
+ const result = resolveTurnBudgetConfig(value, "Runtime agent definition defaultTurnBudget");
182
+ if (result.error) throw new Error(result.error);
183
+ return result.turnBudget;
184
+ }
185
+
186
+ function validateAcceptance(value: unknown): AcceptanceInput | undefined {
187
+ const errors = validateAcceptanceInput(value, "Runtime agent definition defaultAcceptance");
188
+ if (errors.length > 0) throw new Error(errors.join(" "));
189
+ return value as AcceptanceInput | undefined;
190
+ }
191
+
192
+ function validateToolBudget(value: unknown): ToolBudgetConfig | undefined {
193
+ const result = validateToolBudgetConfig(value, "Runtime agent definition toolBudget");
194
+ if (result.error) throw new Error(result.error);
195
+ return result.budget;
196
+ }
197
+
198
+ function validateDefinition(value: unknown): RuntimeAgentDefinition {
199
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("Runtime agent definition must be an object.");
200
+ const definition = value as Record<string, unknown>;
201
+ const supported = new Set([
202
+ "description", "systemPrompt", "aliases", "tools", "mcpDirectTools", "model", "fallbackModels", "thinking",
203
+ "systemPromptMode", "inheritProjectContext", "inheritSkills", "defaultContext", "defaultAsync", "defaultTimeoutMs",
204
+ "defaultToolTimeoutMs", "defaultTurnBudget", "defaultAcceptance", "acceptanceRole", "runner", "skills", "skillPath",
205
+ "extensions", "subagentOnlyExtensions", "output", "outputMode", "defaultReads", "defaultProgress", "interactive",
206
+ "maxSubagentDepth", "completionGuard", "toolBudget", "permissions",
207
+ ]);
208
+ const unknown = Object.keys(definition).filter((key) => !supported.has(key));
209
+ if (unknown.length > 0) throw new Error(`Runtime agent definition has unknown fields: ${unknown.join(", ")}.`);
210
+ const systemPromptMode = definition.systemPromptMode;
211
+ if (systemPromptMode !== undefined && systemPromptMode !== "append" && systemPromptMode !== "replace") throw new Error("Runtime agent definition systemPromptMode must be 'append' or 'replace'.");
212
+ const defaultContext = definition.defaultContext;
213
+ if (defaultContext !== undefined && defaultContext !== "fresh" && defaultContext !== "fork") throw new Error("Runtime agent definition defaultContext must be 'fresh' or 'fork'.");
214
+ const thinking = definition.thinking;
215
+ if (thinking !== undefined && thinking !== false && typeof thinking !== "string") throw new Error("Runtime agent definition thinking must be a string or false when provided.");
216
+ const acceptanceRole = definition.acceptanceRole;
217
+ if (acceptanceRole !== undefined && acceptanceRole !== "read-only" && acceptanceRole !== "writer") throw new Error("Runtime agent definition acceptanceRole must be 'read-only' or 'writer'.");
218
+ const outputMode = definition.outputMode;
219
+ if (outputMode !== undefined && outputMode !== "inline" && outputMode !== "file-only") throw new Error("Runtime agent definition outputMode must be 'inline' or 'file-only'.");
220
+ const aliases = validateStringList(definition.aliases, "Runtime agent definition aliases");
221
+ const tools = validateStringList(definition.tools, "Runtime agent definition tools");
222
+ const mcpDirectTools = validateStringList(definition.mcpDirectTools, "Runtime agent definition mcpDirectTools");
223
+ const model = validateOptionalString(definition.model, "Runtime agent definition model");
224
+ const fallbackModels = validateStringList(definition.fallbackModels, "Runtime agent definition fallbackModels");
225
+ const inheritProjectContext = validateBoolean(definition.inheritProjectContext, "Runtime agent definition inheritProjectContext");
226
+ const inheritSkills = validateBoolean(definition.inheritSkills, "Runtime agent definition inheritSkills");
227
+ const defaultAsync = validateBoolean(definition.defaultAsync, "Runtime agent definition defaultAsync");
228
+ const defaultTimeoutMs = validatePositiveInteger(definition.defaultTimeoutMs, "Runtime agent definition defaultTimeoutMs");
229
+ const defaultToolTimeoutMs = validatePositiveInteger(definition.defaultToolTimeoutMs, "Runtime agent definition defaultToolTimeoutMs");
230
+ const defaultTurnBudget = validateTurnBudget(definition.defaultTurnBudget);
231
+ const defaultAcceptance = validateAcceptance(definition.defaultAcceptance);
232
+ const runner = validateRunner(definition.runner);
233
+ const skills = validateStringList(definition.skills, "Runtime agent definition skills");
234
+ const skillPath = validateStringList(definition.skillPath, "Runtime agent definition skillPath");
235
+ const extensions = validateStringList(definition.extensions, "Runtime agent definition extensions");
236
+ const subagentOnlyExtensions = validateStringList(definition.subagentOnlyExtensions, "Runtime agent definition subagentOnlyExtensions");
237
+ const output = validateOptionalString(definition.output, "Runtime agent definition output");
238
+ const defaultReads = validateStringList(definition.defaultReads, "Runtime agent definition defaultReads");
239
+ const defaultProgress = validateBoolean(definition.defaultProgress, "Runtime agent definition defaultProgress");
240
+ const interactive = validateBoolean(definition.interactive, "Runtime agent definition interactive");
241
+ const maxSubagentDepth = validatePositiveInteger(definition.maxSubagentDepth, "Runtime agent definition maxSubagentDepth");
242
+ const completionGuard = validateBoolean(definition.completionGuard, "Runtime agent definition completionGuard");
243
+ const toolBudget = validateToolBudget(definition.toolBudget);
244
+ const permissions = validatePermissionRules(definition.permissions, "Runtime agent definition permissions");
245
+ return {
246
+ description: validateString(definition.description, "Runtime agent definition description", MAX_DESCRIPTION_LENGTH),
247
+ systemPrompt: validateString(definition.systemPrompt, "Runtime agent definition systemPrompt", MAX_SYSTEM_PROMPT_LENGTH),
248
+ ...(aliases ? { aliases } : {}),
249
+ ...(tools ? { tools } : {}),
250
+ ...(mcpDirectTools ? { mcpDirectTools } : {}),
251
+ ...(model ? { model } : {}),
252
+ ...(fallbackModels ? { fallbackModels } : {}),
253
+ ...(thinking !== undefined ? { thinking: thinking as string | false } : {}),
254
+ ...(systemPromptMode !== undefined ? { systemPromptMode: systemPromptMode as "append" | "replace" } : {}),
255
+ ...(inheritProjectContext !== undefined ? { inheritProjectContext } : {}),
256
+ ...(inheritSkills !== undefined ? { inheritSkills } : {}),
257
+ ...(defaultContext !== undefined ? { defaultContext: defaultContext as AgentDefaultContext } : {}),
258
+ ...(defaultAsync !== undefined ? { defaultAsync } : {}),
259
+ ...(defaultTimeoutMs !== undefined ? { defaultTimeoutMs } : {}),
260
+ ...(defaultToolTimeoutMs !== undefined ? { defaultToolTimeoutMs } : {}),
261
+ ...(defaultTurnBudget !== undefined ? { defaultTurnBudget } : {}),
262
+ ...(defaultAcceptance !== undefined ? { defaultAcceptance } : {}),
263
+ ...(acceptanceRole !== undefined ? { acceptanceRole: acceptanceRole as AcceptanceRole } : {}),
264
+ ...(runner !== undefined ? { runner } : {}),
265
+ ...(skills ? { skills } : {}),
266
+ ...(skillPath ? { skillPath } : {}),
267
+ ...(extensions ? { extensions } : {}),
268
+ ...(subagentOnlyExtensions ? { subagentOnlyExtensions } : {}),
269
+ ...(output ? { output } : {}),
270
+ ...(outputMode !== undefined ? { outputMode: outputMode as OutputMode } : {}),
271
+ ...(defaultReads ? { defaultReads } : {}),
272
+ ...(defaultProgress !== undefined ? { defaultProgress } : {}),
273
+ ...(interactive !== undefined ? { interactive } : {}),
274
+ ...(maxSubagentDepth !== undefined ? { maxSubagentDepth } : {}),
275
+ ...(completionGuard !== undefined ? { completionGuard } : {}),
276
+ ...(toolBudget !== undefined ? { toolBudget } : {}),
277
+ ...(permissions !== undefined ? { permissions } : {}),
278
+ };
279
+ }
280
+
281
+ function normalizeAliases(rawAliases: readonly string[] | undefined, agentName: string): string[] | undefined {
282
+ const aliases = [...new Set((rawAliases ?? []).map((alias) => alias.trim()).filter(Boolean))]
283
+ .filter((alias) => alias !== agentName);
284
+ return aliases.length > 0 ? aliases : undefined;
285
+ }
286
+
287
+ function identityKeys(agent: Pick<AgentConfig, "name" | "localName" | "aliases">): string[] {
288
+ return [agent.name, ...(agent.localName ? [agent.localName] : []), ...(agent.aliases ?? [])];
289
+ }
290
+
291
+ function assertNoIdentityCollisions(agents: readonly AgentConfig[], context: string): void {
292
+ const seen = new Map<string, string>();
293
+ for (const agent of agents) {
294
+ for (const key of identityKeys(agent)) {
295
+ const previous = seen.get(key);
296
+ if (previous !== undefined) throw new Error(`${context} collision for '${key}' between '${previous}' and '${agent.name}'.`);
297
+ seen.set(key, agent.name);
298
+ }
299
+ }
300
+ }
301
+
302
+ function assertNoRuntimeCollision(agent: AgentConfig, existing: readonly AgentConfig[]): void {
303
+ const existingKeys = new Map<string, string>();
304
+ for (const registered of existing) {
305
+ for (const key of identityKeys(registered)) existingKeys.set(key, registered.name);
306
+ }
307
+ for (const key of identityKeys(agent)) {
308
+ const previous = existingKeys.get(key);
309
+ if (previous !== undefined) throw new Error(`Runtime agent '${agent.name}' collides with runtime agent '${previous}' on name or alias '${key}'.`);
310
+ }
311
+ }
312
+
313
+ function assertNoBuiltinCollision(agent: AgentConfig): void {
314
+ for (const key of identityKeys(agent)) {
315
+ if ((BUILTIN_AGENT_NAMES as readonly string[]).includes(key)) throw new Error(`Runtime agent '${agent.name}' collides with builtin agent '${key}'.`);
316
+ }
317
+ }
318
+
319
+ function toAgentConfig(name: string, definition: RuntimeAgentDefinition): AgentConfig {
320
+ const aliases = normalizeAliases(definition.aliases, name);
321
+ const agent: AgentConfig = {
322
+ name,
323
+ description: definition.description,
324
+ ...(aliases ? { aliases } : {}),
325
+ ...(definition.runner !== undefined ? { runner: definition.runner } : {}),
326
+ ...(definition.tools !== undefined ? { tools: [...definition.tools] } : {}),
327
+ ...(definition.mcpDirectTools !== undefined ? { mcpDirectTools: [...definition.mcpDirectTools] } : {}),
328
+ ...(definition.model !== undefined ? { model: definition.model } : {}),
329
+ ...(definition.fallbackModels !== undefined ? { fallbackModels: [...definition.fallbackModels] } : {}),
330
+ ...(definition.thinking !== undefined ? { thinking: definition.thinking } : {}),
331
+ systemPromptMode: definition.systemPromptMode ?? defaultSystemPromptMode(name),
332
+ inheritProjectContext: definition.inheritProjectContext ?? defaultInheritProjectContext(name),
333
+ inheritSkills: definition.inheritSkills ?? defaultInheritSkills(),
334
+ ...(definition.defaultContext !== undefined ? { defaultContext: definition.defaultContext } : {}),
335
+ ...(definition.defaultAsync !== undefined ? { defaultAsync: definition.defaultAsync } : {}),
336
+ ...(definition.defaultTimeoutMs !== undefined ? { defaultTimeoutMs: definition.defaultTimeoutMs } : {}),
337
+ ...(definition.defaultToolTimeoutMs !== undefined ? { defaultToolTimeoutMs: definition.defaultToolTimeoutMs } : {}),
338
+ ...(definition.defaultTurnBudget !== undefined ? { defaultTurnBudget: definition.defaultTurnBudget } : {}),
339
+ ...(definition.defaultAcceptance !== undefined ? { defaultAcceptance: definition.defaultAcceptance } : {}),
340
+ ...(definition.acceptanceRole !== undefined ? { acceptanceRole: definition.acceptanceRole } : {}),
341
+ systemPrompt: definition.systemPrompt,
342
+ source: "runtime",
343
+ filePath: `runtime:${name}`,
344
+ ...(definition.skills !== undefined ? { skills: [...definition.skills] } : {}),
345
+ ...(definition.skillPath !== undefined ? { skillPath: [...definition.skillPath] } : {}),
346
+ ...(definition.extensions !== undefined ? { extensions: [...definition.extensions] } : {}),
347
+ ...(definition.subagentOnlyExtensions !== undefined ? { subagentOnlyExtensions: [...definition.subagentOnlyExtensions] } : {}),
348
+ ...(definition.output !== undefined ? { output: definition.output } : {}),
349
+ ...(definition.outputMode !== undefined ? { outputMode: definition.outputMode } : {}),
350
+ ...(definition.defaultReads !== undefined ? { defaultReads: [...definition.defaultReads] } : {}),
351
+ ...(definition.defaultProgress !== undefined ? { defaultProgress: definition.defaultProgress } : {}),
352
+ ...(definition.interactive !== undefined ? { interactive: definition.interactive } : {}),
353
+ ...(definition.maxSubagentDepth !== undefined ? { maxSubagentDepth: definition.maxSubagentDepth } : {}),
354
+ ...(definition.completionGuard !== undefined ? { completionGuard: definition.completionGuard } : {}),
355
+ ...(definition.toolBudget !== undefined ? { toolBudget: definition.toolBudget } : {}),
356
+ ...(definition.permissions !== undefined ? { permissions: definition.permissions } : {}),
357
+ };
358
+ assertNoIdentityCollisions([agent], `Runtime agent '${name}'`);
359
+ return agent;
360
+ }
361
+
362
+ export function registerRuntimeAgent(input: RegisterRuntimeAgentInput): RuntimeAgentRegistration {
363
+ const pi = validatePi(input.pi);
364
+ const name = validateString(input.name, "Runtime agent name", MAX_AGENT_NAME_LENGTH);
365
+ const definition = validateDefinition(input.definition);
366
+ const agent = toAgentConfig(name, definition);
367
+ assertNoBuiltinCollision(agent);
368
+ const current = registry();
369
+ const records = current.byPi.get(pi) ?? [];
370
+ if (records.length >= MAX_RUNTIME_AGENTS_PER_PI) throw new Error(`Runtime agent registry supports at most ${MAX_RUNTIME_AGENTS_PER_PI} agents per Pi runtime.`);
371
+ assertNoRuntimeCollision(agent, records.map((record) => record.agent));
372
+ const record: RuntimeAgentRecord = { pi, agent };
373
+ records.push(record);
374
+ current.byPi.set(pi, records);
375
+ let disposed = false;
376
+ return {
377
+ dispose() {
378
+ if (disposed) return;
379
+ disposed = true;
380
+ const latest = current.byPi.get(pi);
381
+ if (!latest) return;
382
+ const next = latest.filter((entry) => entry !== record);
383
+ if (next.length > 0) current.byPi.set(pi, next);
384
+ else current.byPi.delete(pi);
385
+ },
386
+ };
387
+ }
388
+
389
+ export function clearRuntimeAgentsForPi(pi: RuntimeAgentOwner): void {
390
+ registry().byPi.delete(pi);
391
+ }
392
+
393
+ export function listRuntimeAgentConfigs(pi: RuntimeAgentOwner): AgentConfig[] {
394
+ return (registry().byPi.get(pi) ?? []).map((record) => ({ ...record.agent, aliases: record.agent.aliases ? [...record.agent.aliases] : undefined }));
395
+ }
396
+
397
+ function assertNoConfiguredCollision(configuredAgents: readonly AgentConfig[], runtimeAgents: readonly AgentConfig[]): void {
398
+ const configured = new Map<string, string>();
399
+ for (const agent of configuredAgents) {
400
+ for (const key of identityKeys(agent)) configured.set(key, agent.name);
401
+ }
402
+ for (const agent of runtimeAgents) {
403
+ for (const key of identityKeys(agent)) {
404
+ const previous = configured.get(key);
405
+ if (previous !== undefined) {
406
+ throw new Error(`Runtime agent '${agent.name}' collides with configured agent '${previous}' on name or alias '${key}'.`);
407
+ }
408
+ }
409
+ }
410
+ }
411
+
412
+ export function mergeRuntimeAgents<T extends { agents: AgentConfig[]; agentDiagnostics?: AgentDiscoveryDiagnostic[] }>(pi: RuntimeAgentOwner, discovered: T, configuredAgents: readonly AgentConfig[] = discovered.agents): T {
413
+ const runtimeAgents = listRuntimeAgentConfigs(pi).filter((agent) => agent.disabled !== true);
414
+ if (runtimeAgents.length === 0) return discovered;
415
+ assertNoIdentityCollisions(runtimeAgents, "Runtime agent registration");
416
+ assertNoConfiguredCollision(configuredAgents, runtimeAgents);
417
+ return { ...discovered, agents: [...discovered.agents, ...runtimeAgents] };
418
+ }
@@ -0,0 +1,7 @@
1
+ import { registerRuntimeAgent, type RegisterRuntimeAgentInput, type RuntimeAgentDefinition, type RuntimeAgentRegistration } from "../agents/runtime-agent-registry.ts";
2
+
3
+ export type { RegisterRuntimeAgentInput, RuntimeAgentDefinition, RuntimeAgentRegistration };
4
+
5
+ export function registerAgent(input: RegisterRuntimeAgentInput): RuntimeAgentRegistration {
6
+ return registerRuntimeAgent(input);
7
+ }
@@ -146,8 +146,9 @@ export function validateExternalJobResult(provider: string, value: unknown, fiel
146
146
  function validateProvider(value: unknown): ExternalJobProvider {
147
147
  if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("External-job provider must be an object.");
148
148
  const provider = value as Record<string, unknown>;
149
- const unknownFields = Object.keys(provider).filter((key) => !["name", "start", "status", "result", "reattach"].includes(key));
150
- if (unknownFields.length > 0) throw new Error(`External-job provider has unknown fields: ${unknownFields.join(", ")}.`);
149
+ // Tolerate extra provider fields (for example kind, wakeChannels, or future
150
+ // operations) so one evolving provider cannot poison registry reads for all
151
+ // providers. Payload validation stays strict.
151
152
  const name = validateString(provider.name, "External-job provider name", MAX_PROVIDER_NAME_LENGTH);
152
153
  for (const op of ["start", "status", "result", "reattach"] as const) {
153
154
  if (typeof provider[op] !== "function") throw new Error(`External-job provider '${name}' must expose ${op}().`);
@@ -429,7 +429,7 @@ export async function resolveSubagentLaunchContract(input: SubagentLaunchContrac
429
429
  extensions: toolPlan.extensionArgs,
430
430
  mcpDirectTools: toolPlan.effectiveMcpTools,
431
431
  ...(outputPath ? { outputPath } : {}),
432
- outputMode: input.outputMode ?? "inline",
432
+ outputMode: behavior.outputMode,
433
433
  ...(input.outputSchema ? { structuredOutputSchema: input.outputSchema } : {}),
434
434
  }),
435
435
  };
@@ -110,6 +110,9 @@ function validateConfig(config: Record<string, unknown>): void {
110
110
  || config.maxActiveAsyncRunsPerSession < 0)) {
111
111
  throw new Error("config.maxActiveAsyncRunsPerSession must be a non-negative integer");
112
112
  }
113
+ if (config.resultScanLogging !== undefined && config.resultScanLogging !== "all" && config.resultScanLogging !== "activity" && config.resultScanLogging !== "off") {
114
+ throw new Error('config.resultScanLogging must be "all", "activity", or "off"');
115
+ }
113
116
  validateMissionStoreConfig(config.missions);
114
117
  validateAuthorityPolicy(config.authorityPolicy);
115
118
  validatePermissionConfig(config.permissions);
@@ -141,6 +141,7 @@ function formatDiscovery(input: DoctorReportInput, deps: DoctorDeps): string[] {
141
141
  package: discovered.package?.length ?? 0,
142
142
  user: discovered.user.length,
143
143
  project: discovered.project.length,
144
+ runtime: 0,
144
145
  };
145
146
  const diagnostics = discovered.agentDiagnostics ?? [];
146
147
  return [