@xzzpig/pi-subagents 0.4.2 → 0.5.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 (127) hide show
  1. package/CHANGELOG.md +168 -0
  2. package/README.md +4 -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 +40 -2
  9. package/docs/configuration.md +41 -13
  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 +2 -0
  26. package/src/agents/agents.ts +186 -44
  27. package/src/agents/builtin-names.ts +9 -0
  28. package/src/agents/runtime-agent-registry.ts +418 -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/doctor.ts +4 -6
  36. package/src/extension/fanout-child.ts +2 -2
  37. package/src/extension/index.ts +183 -90
  38. package/src/extension/public-execution.ts +31 -2
  39. package/src/extension/rpc.ts +41 -1
  40. package/src/extension/schemas.ts +17 -37
  41. package/src/extension/tool-description.ts +35 -24
  42. package/src/inspectors/herdr/actions.ts +2 -2
  43. package/src/inspectors/herdr/inspector-runner.ts +2 -1
  44. package/src/inspectors/herdr/project-panes.ts +2 -2
  45. package/src/intercom/native-supervisor-channel.ts +32 -10
  46. package/src/missions/lifecycle.ts +6 -1
  47. package/src/missions/store.ts +4 -9
  48. package/src/missions/workflow-state.ts +2 -2
  49. package/src/profiles/profiles.ts +3 -1
  50. package/src/runs/background/active-run-index.ts +31 -8
  51. package/src/runs/background/async-execution.ts +70 -41
  52. package/src/runs/background/async-job-tracker.ts +24 -7
  53. package/src/runs/background/async-resume.ts +49 -16
  54. package/src/runs/background/async-retention.ts +886 -0
  55. package/src/runs/background/async-status-snapshot.ts +14 -5
  56. package/src/runs/background/async-status.ts +39 -53
  57. package/src/runs/background/auto-drain.ts +1 -0
  58. package/src/runs/background/chain-append.ts +3 -33
  59. package/src/runs/background/completion-dedupe.ts +5 -1
  60. package/src/runs/background/completion-replay.ts +22 -12
  61. package/src/runs/background/control-channel.ts +14 -68
  62. package/src/runs/background/fleet-view.ts +68 -19
  63. package/src/runs/background/index-segment.ts +59 -0
  64. package/src/runs/background/inspect-rpc.ts +443 -0
  65. package/src/runs/background/notify.ts +31 -5
  66. package/src/runs/background/result-files.ts +158 -90
  67. package/src/runs/background/result-watcher.ts +124 -20
  68. package/src/runs/background/resume-guidance.ts +8 -5
  69. package/src/runs/background/retained-children.ts +13 -3
  70. package/src/runs/background/run-id-query.ts +7 -0
  71. package/src/runs/background/run-id-resolver.ts +11 -9
  72. package/src/runs/background/run-status.ts +27 -18
  73. package/src/runs/background/scheduled-runs.ts +24 -4
  74. package/src/runs/background/stale-run-reconciler.ts +6 -3
  75. package/src/runs/background/steering.ts +11 -1
  76. package/src/runs/background/subagent-runner.ts +260 -144
  77. package/src/runs/background/subagent-wait.ts +17 -13
  78. package/src/runs/background/terminal-run-index.ts +138 -0
  79. package/src/runs/background/wait-completions.ts +21 -4
  80. package/src/runs/background/wait-subscriptions.ts +81 -2
  81. package/src/runs/background/wait-tool.ts +1 -0
  82. package/src/runs/foreground/async-steering-action.ts +21 -14
  83. package/src/runs/foreground/execution.ts +8 -2
  84. package/src/runs/foreground/subagent-executor.ts +816 -1593
  85. package/src/runs/foreground/workflow-detach-reconcile.ts +262 -0
  86. package/src/runs/foreground/workflow-foreground-steering.ts +6 -5
  87. package/src/runs/shared/acceptance.ts +48 -5
  88. package/src/runs/shared/chain-outputs.ts +1 -3
  89. package/src/runs/shared/external-job-bridge.ts +444 -0
  90. package/src/runs/shared/external-job-runner.ts +286 -0
  91. package/src/runs/shared/mcp-direct-tool-allowlist.ts +14 -0
  92. package/src/runs/shared/model-exclusions.ts +242 -0
  93. package/src/runs/shared/model-fallback.ts +153 -40
  94. package/src/runs/shared/orca-progress-tabs.ts +84 -22
  95. package/src/runs/shared/parallel-handoff.ts +46 -4
  96. package/src/runs/shared/parallel-utils.ts +4 -15
  97. package/src/runs/shared/permissions.ts +5 -1
  98. package/src/runs/shared/pi-args.ts +8 -1
  99. package/src/runs/shared/session-lease.ts +0 -6
  100. package/src/runs/shared/subagent-control.ts +51 -7
  101. package/src/runs/shared/subagent-prompt-runtime.ts +12 -6
  102. package/src/runs/shared/workflow-graph.ts +1 -23
  103. package/src/runs/shared/worktree.ts +14 -2
  104. package/src/shared/atomic-json.ts +22 -2
  105. package/src/shared/capacity-resilient-json.ts +102 -0
  106. package/src/shared/completion-owner.ts +14 -0
  107. package/src/shared/file-system-retry.ts +49 -1
  108. package/src/shared/fork-context.ts +59 -1
  109. package/src/shared/model-info.ts +20 -0
  110. package/src/shared/prompt-resources.ts +0 -40
  111. package/src/shared/settings.ts +5 -29
  112. package/src/shared/types.ts +106 -26
  113. package/src/shared/utils.ts +8 -0
  114. package/src/shared/watch-strategy.ts +10 -0
  115. package/src/slash/slash-bridge.ts +2 -1
  116. package/src/slash/slash-commands.ts +47 -7
  117. package/src/slash/slash-live-state.ts +3 -3
  118. package/src/tui/fleet-status.ts +86 -1
  119. package/src/tui/fleet.ts +117 -16
  120. package/src/tui/render.ts +73 -3
  121. package/src/watchdog/change-signature.ts +1 -1
  122. package/src/watchdog/lsp-diagnostics.ts +1 -0
  123. package/src/workflows/chat-progress.ts +2 -2
  124. package/src/workflows/scripted-workflow.ts +320 -79
  125. package/src/workflows/workflow-receipt.ts +140 -0
  126. package/src/runs/foreground/chain-clarify.ts +0 -1354
  127. package/src/runs/foreground/chain-execution.ts +0 -1581
@@ -4,10 +4,9 @@ import type { AgentToolResult } from "@earendil-works/pi-agent-core";
4
4
  import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
5
5
  import {
6
6
  type AgentConfig,
7
+ type AgentDiscoveryDiagnostic,
7
8
  type AgentScope,
8
9
  type AgentSource,
9
- type ChainConfig,
10
- type ChainStepConfig,
11
10
  BUILTIN_AGENT_NAMES,
12
11
  defaultInheritProjectContext,
13
12
  defaultInheritSkills,
@@ -15,6 +14,7 @@ import {
15
14
  discoverAgents,
16
15
  discoverAgentsAll,
17
16
  buildRuntimeName,
17
+ findBlockingAgentDiagnostic,
18
18
  frontmatterNameForConfig,
19
19
  parsePackageName,
20
20
  mergeBuiltinAgentOverride,
@@ -24,12 +24,11 @@ import {
24
24
  } from "./agents.ts";
25
25
  import { serializeAgent } from "./agent-serializer.ts";
26
26
  import { mergeAgentsForScope } from "./agent-selection.ts";
27
- import { serializeChain, serializeJsonChain } from "./chain-serializer.ts";
28
27
  import { discoverAvailableSkills, resolveSkills, resolveSkillsWithFallback } from "./skills.ts";
29
28
  import {
30
29
  buildProactiveSkillSubagentRecommendationLines,
31
30
  } from "./proactive-skills.ts";
32
- import { parseFrontmatter } from "./frontmatter.ts";
31
+ import { parseFrontmatter, parseFrontmatterList } from "./frontmatter.ts";
33
32
  import { resolvePiLaunchToolPlan } from "../runs/shared/pi-args.ts";
34
33
  import { toModelInfo } from "../shared/model-info.ts";
35
34
  import { resolveSubagentModelOverride, type ParentModel } from "../runs/shared/model-fallback.ts";
@@ -39,6 +38,7 @@ import { validateAcceptanceInput } from "../runs/shared/acceptance.ts";
39
38
  import type { AcceptanceInput, Details, ExtensionConfig, ToolBudgetConfig } from "../shared/types.ts";
40
39
  import { getProjectConfigDir } from "../shared/utils.ts";
41
40
  import { capabilityCeilingAgentRestrictionSources, isAgentAllowedByCapabilityCeiling, resolveCurrentSubagentCapabilityCeiling } from "../runs/shared/capability-ceiling.ts";
41
+ import { listRuntimeAgentConfigs, mergeRuntimeAgents, type RuntimeAgentOwner } from "./runtime-agent-registry.ts";
42
42
 
43
43
  export const AGENT_MANAGEMENT_API_VERSION = 1 as const;
44
44
 
@@ -96,12 +96,11 @@ export type EjectAgentDefinitionResult =
96
96
 
97
97
  type ManagementAction = "list" | "get" | "models" | "create" | "update" | "delete" | "eject" | "disable" | "enable" | "reset";
98
98
  type ManagementScope = "user" | "project";
99
- type ManagementContext = Pick<ExtensionContext, "cwd" | "modelRegistry"> & { model?: ExtensionContext["model"]; config?: ExtensionConfig; currentSessionId?: string };
99
+ type ManagementContext = Pick<ExtensionContext, "cwd" | "modelRegistry"> & { model?: ExtensionContext["model"]; config?: ExtensionConfig; currentSessionId?: string; runtimeAgentOwner?: RuntimeAgentOwner };
100
100
 
101
101
  interface ManagementParams {
102
102
  action?: string;
103
103
  agent?: string;
104
- chainName?: string;
105
104
  agentScope?: unknown;
106
105
  config?: unknown;
107
106
  }
@@ -132,6 +131,14 @@ function hasKey(obj: Record<string, unknown>, key: string): boolean {
132
131
  return Object.prototype.hasOwnProperty.call(obj, key);
133
132
  }
134
133
 
134
+ function isJsonSerializable(value: unknown): boolean {
135
+ if (value === null || typeof value === "string" || typeof value === "boolean") return true;
136
+ if (typeof value === "number") return Number.isFinite(value);
137
+ if (Array.isArray(value)) return value.every(isJsonSerializable);
138
+ if (value && typeof value === "object") return Object.values(value).every(isJsonSerializable);
139
+ return false;
140
+ }
141
+
135
142
  function asDisambiguationScope(scope: unknown): ManagementScope | undefined {
136
143
  if (scope === "user" || scope === "project") return scope;
137
144
  return undefined;
@@ -161,14 +168,15 @@ function allAgents(d: { builtin: AgentConfig[]; package: AgentConfig[]; user: Ag
161
168
  return [...d.builtin, ...d.package, ...d.user, ...d.project];
162
169
  }
163
170
 
164
- function availableNames(cwd: string, kind: "agent" | "chain"): string[] {
165
- const d = discoverAgentsAll(cwd);
166
- const items = kind === "agent" ? allAgents(d) : d.chains;
167
- return [...new Set(items.map((x) => x.name))].sort((a, b) => a.localeCompare(b));
171
+ function availableAgentNamesFromDiscovery(d: { builtin: AgentConfig[]; package: AgentConfig[]; user: AgentConfig[]; project: AgentConfig[] }): string[] {
172
+ return [...new Set(allAgents(d).map((agent) => agent.name))].sort((a, b) => a.localeCompare(b));
168
173
  }
169
174
 
170
- function findAgents(name: string, cwd: string, scope: AgentScope = "both"): AgentConfig[] {
171
- const d = discoverAgentsAll(cwd);
175
+ function availableAgentNames(cwd: string): string[] {
176
+ return availableAgentNamesFromDiscovery(discoverAgentsAll(cwd));
177
+ }
178
+
179
+ function findAgentsInDiscovery(name: string, d: { builtin: AgentConfig[]; package: AgentConfig[]; user: AgentConfig[]; project: AgentConfig[] }, scope: AgentScope = "both"): AgentConfig[] {
172
180
  const raw = name.trim();
173
181
  const sanitized = sanitizeName(raw);
174
182
  const scoped = mergeAgentsForScope(scope, d.user, d.project, d.builtin, d.package);
@@ -181,15 +189,17 @@ function findAgents(name: string, cwd: string, scope: AgentScope = "both"): Agen
181
189
  .sort((a, b) => a.source.localeCompare(b.source));
182
190
  }
183
191
 
184
- function findChains(name: string, cwd: string, scope: AgentScope = "both"): ChainConfig[] {
185
- const raw = name.trim();
186
- const sanitized = sanitizeName(raw);
187
- return discoverAgentsAll(cwd).chains
188
- .filter((c) => (scope === "both" || c.source === "package" || c.source === scope) && (c.name === raw || c.name === sanitized))
189
- .sort((a, b) => a.source.localeCompare(b.source));
192
+ function findAgents(name: string, cwd: string, scope: AgentScope = "both"): AgentConfig[] {
193
+ return findAgentsInDiscovery(name, discoverAgentsAll(cwd), scope);
190
194
  }
191
195
 
192
- const AGENT_SOURCE_PRECEDENCE: Record<AgentSource, number> = { builtin: 0, package: 1, user: 2, project: 3 };
196
+ function diagnosticsForScope(diagnostics: AgentDiscoveryDiagnostic[] | undefined, scope: AgentScope): AgentDiscoveryDiagnostic[] | undefined {
197
+ if (scope === "both") return diagnostics;
198
+ const excludedSource = scope === "user" ? "project" : "user";
199
+ return diagnostics?.filter((diagnostic) => diagnostic.source !== excludedSource);
200
+ }
201
+
202
+ const AGENT_SOURCE_PRECEDENCE: Record<AgentSource, number> = { builtin: 0, package: 1, user: 2, project: 3, runtime: 4 };
193
203
 
194
204
  // Returns the highest-precedence definition for a resolved canonical name (project > user > package > builtin),
195
205
  // matching mergeAgentsForScope for "both", including disabled agents so disable/enable can locate hidden targets.
@@ -212,9 +222,6 @@ function nameExistsInScope(cwd: string, scope: ManagementScope, name: string, ex
212
222
  for (const a of scope === "user" ? d.user : d.project) {
213
223
  if (a.name === name && a.filePath !== excludePath) return true;
214
224
  }
215
- for (const c of d.chains) {
216
- if (c.source === scope && c.name === name && c.filePath !== excludePath) return true;
217
- }
218
225
  return false;
219
226
  }
220
227
 
@@ -222,30 +229,6 @@ function isMutableSource(source: AgentSource): source is ManagementScope {
222
229
  return source === "user" || source === "project";
223
230
  }
224
231
 
225
- function unknownChainAgents(cwd: string, steps: ChainStepConfig[]): string[] {
226
- const d = discoverAgentsAll(cwd);
227
- const agents = allAgents(d);
228
- return [...new Set(steps.map((s) => s.agent).filter((agentName): agentName is string => typeof agentName === "string" && !resolveAgentName(agentName, agents).agent))]
229
- .sort((a, b) => a.localeCompare(b));
230
- }
231
-
232
- function chainStepWarnings(ctx: ManagementContext, steps: ChainStepConfig[]): string[] {
233
- const warnings: string[] = [];
234
- const available = new Set(discoverAvailableSkills(ctx.cwd).map((s) => s.name));
235
- for (let i = 0; i < steps.length; i++) {
236
- const s = steps[i]!;
237
- if (s.model) {
238
- const found = ctx.modelRegistry.getAvailable().some((m) => `${m.provider}/${m.id}` === s.model || m.id === s.model);
239
- if (!found) warnings.push(`Warning: step ${i + 1} (${s.agent}): model '${s.model}' is not in the current model registry.`);
240
- }
241
- if (Array.isArray(s.skills) && s.skills.length > 0) {
242
- const missing = s.skills.filter((sk) => !available.has(sk));
243
- if (missing.length) warnings.push(`Warning: step ${i + 1} (${s.agent}): skills not found: ${missing.join(", ")}.`);
244
- }
245
- }
246
- return warnings;
247
- }
248
-
249
232
  function modelWarning(ctx: ManagementContext, model: string | undefined): string | undefined {
250
233
  if (!model) return undefined;
251
234
  const found = ctx.modelRegistry.getAvailable().some((m) => `${m.provider}/${m.id}` === model || m.id === model);
@@ -270,11 +253,24 @@ function skillsWarning(cwd: string, agent: Pick<AgentConfig, "skills" | "skillPa
270
253
  return missing.length ? `Warning: skills not found: ${missing.join(", ")}.` : undefined;
271
254
  }
272
255
 
256
+ function withDeclaredExtensionPaths(config: AgentConfig, filePath: string): AgentConfig {
257
+ const { frontmatter } = parseFrontmatter(fs.readFileSync(filePath, "utf-8"));
258
+ const { extensions: _extensions, subagentOnlyExtensions: _subagentOnlyExtensions, ...withoutResolvedExtensions } = config;
259
+ return {
260
+ ...withoutResolvedExtensions,
261
+ ...(frontmatter.extensions !== undefined ? { extensions: parseFrontmatterList(frontmatter.extensions) } : {}),
262
+ ...(frontmatter.subagentOnlyExtensions !== undefined
263
+ ? { subagentOnlyExtensions: parseFrontmatterList(frontmatter.subagentOnlyExtensions) }
264
+ : {}),
265
+ };
266
+ }
267
+
273
268
  export function editableAgentConfig(agent: AgentConfig): AgentConfig {
274
269
  const { extensions: _extensions, ...withoutExtensions } = agent;
275
270
  const base = agent.override?.base;
276
271
  const {
277
272
  override: _override,
273
+ outputMode: _outputMode,
278
274
  model: _model,
279
275
  fallbackModels: _fallbackModels,
280
276
  thinking: _thinking,
@@ -294,14 +290,15 @@ export function editableAgentConfig(agent: AgentConfig): AgentConfig {
294
290
  ...editable
295
291
  } = withoutExtensions;
296
292
  if (!base) {
297
- return {
293
+ return withDeclaredExtensionPaths({
298
294
  ...withoutExtensions,
299
295
  ...(agent.extensionsFromDefault ? {} : agent.extensions !== undefined ? { extensions: [...agent.extensions] } : {}),
300
- };
296
+ }, agent.filePath);
301
297
  }
302
298
 
303
- return {
299
+ return withDeclaredExtensionPaths({
304
300
  ...editable,
301
+ ...(base.outputMode !== undefined ? { outputMode: base.outputMode } : {}),
305
302
  ...(base.model !== undefined ? { model: base.model } : {}),
306
303
  ...(base.fallbackModels !== undefined ? { fallbackModels: [...base.fallbackModels] } : {}),
307
304
  ...(base.thinking !== undefined ? { thinking: base.thinking } : {}),
@@ -319,7 +316,7 @@ export function editableAgentConfig(agent: AgentConfig): AgentConfig {
319
316
  ...(base.extensions !== undefined ? { extensions: [...base.extensions] } : {}),
320
317
  ...(base.subagentOnlyExtensions !== undefined ? { subagentOnlyExtensions: [...base.subagentOnlyExtensions] } : {}),
321
318
  ...(base.completionGuard !== undefined ? { completionGuard: base.completionGuard } : {}),
322
- };
319
+ }, agent.filePath);
323
320
  }
324
321
 
325
322
  function readAgentFrontmatterFields(filePath: string): Set<string> {
@@ -373,6 +370,7 @@ export function preservedAgentFrontmatterFields(agent: AgentConfig, cfg: Record<
373
370
  if (hasKey(cfg, "acceptance")) changed("acceptance");
374
371
  if (hasKey(cfg, "acceptanceRole")) changed("acceptanceRole");
375
372
  if (hasKey(cfg, "output")) changed("output");
373
+ if (hasKey(cfg, "outputMode")) changed("outputMode");
376
374
  if (hasKey(cfg, "reads")) changed("defaultReads");
377
375
  if (hasKey(cfg, "progress")) changed("defaultProgress");
378
376
  if (hasKey(cfg, "maxSubagentDepth")) changed("maxSubagentDepth");
@@ -385,69 +383,6 @@ export function preservedAgentFrontmatterFields(agent: AgentConfig, cfg: Record<
385
383
  return fields;
386
384
  }
387
385
 
388
- function parseStepList(raw: unknown): { steps?: ChainStepConfig[]; error?: string } {
389
- if (!Array.isArray(raw)) return { error: "config.steps must be an array." };
390
- if (raw.length === 0) return { error: "config.steps must include at least one step." };
391
- const steps: ChainStepConfig[] = [];
392
- for (let i = 0; i < raw.length; i++) {
393
- const item = raw[i];
394
- if (!item || typeof item !== "object" || Array.isArray(item)) return { error: `config.steps[${i}] must be an object.` };
395
- const s = item as Record<string, unknown>;
396
- if (typeof s.agent !== "string" || !s.agent.trim()) return { error: `config.steps[${i}].agent must be a non-empty string.` };
397
- const step: ChainStepConfig = { agent: s.agent.trim(), task: typeof s.task === "string" ? s.task : "" };
398
- if (hasKey(s, "phase")) {
399
- if (typeof s.phase === "string") step.phase = s.phase;
400
- else return { error: `config.steps[${i}].phase must be a string.` };
401
- }
402
- if (hasKey(s, "label")) {
403
- if (typeof s.label === "string") step.label = s.label;
404
- else return { error: `config.steps[${i}].label must be a string.` };
405
- }
406
- if (hasKey(s, "as")) {
407
- if (typeof s.as === "string") step.as = s.as;
408
- else return { error: `config.steps[${i}].as must be a string.` };
409
- }
410
- if (hasKey(s, "outputSchema")) {
411
- if (typeof s.outputSchema === "string") step.outputSchema = s.outputSchema;
412
- else return { error: `config.steps[${i}].outputSchema must be a schema file path string for saved chains.` };
413
- }
414
- if (hasKey(s, "output")) {
415
- if (s.output === false) step.output = false;
416
- else if (typeof s.output === "string") step.output = s.output;
417
- else return { error: `config.steps[${i}].output must be a string or false.` };
418
- }
419
- if (hasKey(s, "outputMode")) {
420
- if (s.outputMode === "inline" || s.outputMode === "file-only") step.outputMode = s.outputMode;
421
- else return { error: `config.steps[${i}].outputMode must be 'inline' or 'file-only'.` };
422
- }
423
- if (hasKey(s, "reads")) {
424
- if (s.reads === false) step.reads = false;
425
- else if (Array.isArray(s.reads)) step.reads = s.reads.filter((v): v is string => typeof v === "string").map((v) => v.trim()).filter(Boolean);
426
- else return { error: `config.steps[${i}].reads must be an array or false.` };
427
- }
428
- if (hasKey(s, "model")) {
429
- if (typeof s.model === "string") step.model = s.model;
430
- else return { error: `config.steps[${i}].model must be a string.` };
431
- }
432
- if (hasKey(s, "skills")) {
433
- if (s.skills === false) step.skills = false;
434
- else if (Array.isArray(s.skills)) step.skills = s.skills.filter((v): v is string => typeof v === "string").map((v) => v.trim()).filter(Boolean);
435
- else return { error: `config.steps[${i}].skills must be an array or false.` };
436
- }
437
- if (hasKey(s, "progress")) {
438
- if (typeof s.progress === "boolean") step.progress = s.progress;
439
- else return { error: `config.steps[${i}].progress must be a boolean.` };
440
- }
441
- if (hasKey(s, "toolBudget")) {
442
- const validation = validateToolBudgetConfig(s.toolBudget, `config.steps[${i}].toolBudget`);
443
- if (validation.error) return { error: validation.error };
444
- if (s.toolBudget !== undefined) step.toolBudget = s.toolBudget as ToolBudgetConfig;
445
- }
446
- steps.push(step);
447
- }
448
- return { steps };
449
- }
450
-
451
386
  function parseTools(raw: string): { tools?: string[]; mcpDirectTools?: string[] } {
452
387
  const tools: string[] = [];
453
388
  const mcpDirectTools: string[] = [];
@@ -492,7 +427,11 @@ function applyAgentConfig(target: AgentConfig, cfg: Record<string, unknown>): st
492
427
  && Object.keys(runner).every((key) => ["type", "command", "args", "promptDelivery"].includes(key))) {
493
428
  const runnerArgs = Array.isArray(runner.args) ? runner.args.filter((arg): arg is string => typeof arg === "string") : undefined;
494
429
  target.runner = { type: "external-cli", command: runner.command.trim(), ...(runnerArgs?.length ? { args: runnerArgs } : {}), ...(runner.promptDelivery ? { promptDelivery: "stdin" } : {}) };
495
- } else return "config.runner must be { type: 'pi' } or { type: 'external-cli', command: string, args?: string[], promptDelivery?: 'stdin' }.";
430
+ } else if (runner.type === "external-job" && typeof runner.provider === "string" && runner.provider.trim() === runner.provider && runner.provider
431
+ && (runner.options === undefined || (runner.options && typeof runner.options === "object" && !Array.isArray(runner.options) && isJsonSerializable(runner.options)))
432
+ && Object.keys(runner).every((key) => ["type", "provider", "options"].includes(key))) {
433
+ target.runner = { type: "external-job", provider: runner.provider, ...(runner.options ? { options: runner.options as Record<string, unknown> } : {}) };
434
+ } else return "config.runner must be { type: 'pi' }, { type: 'external-cli', command: string, args?: string[], promptDelivery?: 'stdin' }, or { type: 'external-job', provider: string, options?: object }.";
496
435
  } else return "config.runner must be an object, false, or empty string when provided.";
497
436
  }
498
437
  if (hasKey(cfg, "model")) {
@@ -622,6 +561,10 @@ function applyAgentConfig(target: AgentConfig, cfg: Record<string, unknown>): st
622
561
  else if (typeof cfg.output === "string") target.output = cfg.output;
623
562
  else return "config.output must be a string or false when provided.";
624
563
  }
564
+ if (hasKey(cfg, "outputMode")) {
565
+ if (cfg.outputMode === "inline" || cfg.outputMode === "file-only") target.outputMode = cfg.outputMode;
566
+ else return "config.outputMode must be 'inline' or 'file-only' when provided.";
567
+ }
625
568
  if (hasKey(cfg, "reads")) {
626
569
  if (cfg.reads === false || cfg.reads === "") delete target.defaultReads;
627
570
  else if (typeof cfg.reads === "string") {
@@ -652,7 +595,7 @@ function applyAgentConfig(target: AgentConfig, cfg: Record<string, unknown>): st
652
595
  target.toolBudget = cfg.toolBudget as ToolBudgetConfig;
653
596
  }
654
597
  }
655
- if (target.runner?.type === "external-cli") {
598
+ if (target.runner?.type === "external-cli" || target.runner?.type === "external-job") {
656
599
  const unsupported = [
657
600
  target.tools?.length || target.mcpDirectTools?.length ? "tools" : undefined,
658
601
  target.model ? "model" : undefined,
@@ -665,55 +608,40 @@ function applyAgentConfig(target: AgentConfig, cfg: Record<string, unknown>): st
665
608
  target.completionGuard !== undefined ? "completionGuard" : undefined,
666
609
  target.toolBudget ? "toolBudget" : undefined,
667
610
  ].filter((field): field is string => Boolean(field));
668
- if (unsupported.length > 0) return `config.runner type 'external-cli' does not support Pi-only fields: ${unsupported.join(", ")}.`;
611
+ if (unsupported.length > 0) return `config.runner type '${target.runner.type}' does not support Pi-only fields: ${unsupported.join(", ")}.`;
669
612
  }
670
613
  return undefined;
671
614
  }
672
615
 
673
616
  function resolveTarget<T extends { name: string; source: AgentSource; filePath: string }>(
674
- kind: "agent" | "chain",
675
617
  name: string,
676
618
  matches: T[],
677
619
  cwd: string,
678
620
  scopeHint?: string,
679
621
  ): T | AgentToolResult<Details> {
680
- const distinctNames = [...new Set(matches.map((m) => m.name))];
681
- if (distinctNames.length > 1) {
682
- return result(`Ambiguous ${kind} alias or name '${name}': ${distinctNames.sort((a, b) => a.localeCompare(b)).join(", ")}`, true);
683
- }
684
- const mutable = matches.filter((m): m is T & { source: ManagementScope } => isMutableSource(m.source));
622
+ const distinctNames = [...new Set(matches.map((match) => match.name))];
623
+ if (distinctNames.length > 1) return result(`Ambiguous agent alias or name '${name}': ${distinctNames.sort((a, b) => a.localeCompare(b)).join(", ")}`, true);
624
+ const mutable = matches.filter((match): match is T & { source: ManagementScope } => isMutableSource(match.source));
685
625
  if (mutable.length === 0) {
686
- if (matches.length > 0) {
687
- return result(`${kind === "agent" ? "Agent" : "Chain"} '${name}' is read-only and cannot be modified. Create a same-named ${kind} in user or project scope to override it.`, true);
688
- }
689
- const available = availableNames(cwd, kind);
690
- return result(`${kind === "agent" ? "Agent" : "Chain"} '${name}' not found. Available: ${available.join(", ") || "none"}.`, true);
626
+ if (matches.length > 0) return result(`Agent '${name}' is read-only and cannot be modified. Create a same-named agent in user or project scope to override it.`, true);
627
+ return result(`Agent '${name}' not found. Available: ${availableAgentNames(cwd).join(", ") || "none"}.`, true);
691
628
  }
692
629
  if (mutable.length === 1) return mutable[0]!;
693
630
  const scope = asDisambiguationScope(scopeHint);
694
631
  if (!scope) {
695
- const paths = mutable.map((m) => `${m.source}: ${m.filePath}`).join("\n");
696
- return result(`${kind === "agent" ? "Agent" : "Chain"} '${name}' exists in both scopes. Specify agentScope: 'user' or 'project'.\n${paths}`, true);
632
+ const paths = mutable.map((match) => `${match.source}: ${match.filePath}`).join("\n");
633
+ return result(`Agent '${name}' exists in both scopes. Specify agentScope: 'user' or 'project'.\n${paths}`, true);
697
634
  }
698
- const scoped = mutable.filter((m) => m.source === scope);
699
- if (scoped.length === 0) return result(`${kind === "agent" ? "Agent" : "Chain"} '${name}' not found in scope '${scope}'.`, true);
700
- if (scoped.length > 1) return result(`Multiple ${kind}s named '${name}' found in scope '${scope}': ${scoped.map((m) => m.filePath).join(", ")}`, true);
635
+ const scoped = mutable.filter((match) => match.source === scope);
636
+ if (scoped.length === 0) return result(`Agent '${name}' not found in scope '${scope}'.`, true);
637
+ if (scoped.length > 1) return result(`Multiple agents named '${name}' found in scope '${scope}': ${scoped.map((match) => match.filePath).join(", ")}`, true);
701
638
  return scoped[0]!;
702
639
  }
703
640
 
704
- function renamePath(
705
- kind: "agent" | "chain",
706
- currentPath: string,
707
- newName: string,
708
- scope: ManagementScope,
709
- cwd: string,
710
- ): { filePath?: string; error?: string } {
641
+ function renamePath(currentPath: string, newName: string, scope: ManagementScope, cwd: string): { filePath?: string; error?: string } {
711
642
  if (nameExistsInScope(cwd, scope, newName, currentPath)) return { error: `Name '${newName}' already exists in ${scope} scope.` };
712
- const ext = kind === "agent" ? ".md" : currentPath.endsWith(".chain.json") ? ".chain.json" : ".chain.md";
713
- const filePath = path.join(path.dirname(currentPath), `${newName}${ext}`);
714
- if (fs.existsSync(filePath) && filePath !== currentPath) {
715
- return { error: `File already exists at ${filePath} but is not a valid ${kind} definition. Remove or rename it first.` };
716
- }
643
+ const filePath = path.join(path.dirname(currentPath), `${newName}.md`);
644
+ if (fs.existsSync(filePath) && filePath !== currentPath) return { error: `File already exists at ${filePath} but is not a valid agent definition. Remove or rename it first.` };
717
645
  fs.renameSync(currentPath, filePath);
718
646
  return { filePath };
719
647
  }
@@ -746,6 +674,7 @@ function formatAgentDetail(agent: AgentConfig): string {
746
674
  if (agent.subagentOnlyExtensions !== undefined) lines.push(`Subagent-only extensions: ${agent.subagentOnlyExtensions.length ? agent.subagentOnlyExtensions.join(", ") : "(none)"}`);
747
675
  if (agent.thinking) lines.push(`Thinking: ${agent.thinking}`);
748
676
  if (agent.output) lines.push(`Output: ${agent.output}`);
677
+ if (agent.outputMode) lines.push(`Output mode: ${agent.outputMode}`);
749
678
  if (agent.defaultReads?.length) lines.push(`Reads: ${agent.defaultReads.join(", ")}`);
750
679
  if (agent.defaultProgress) lines.push("Progress: true");
751
680
  if (agent.maxSubagentDepth !== undefined) lines.push(`Max subagent depth: ${agent.maxSubagentDepth}`);
@@ -756,71 +685,28 @@ function formatAgentDetail(agent: AgentConfig): string {
756
685
  return lines.join("\n");
757
686
  }
758
687
 
759
- function formatChainStepDetail(step: ChainStepConfig, index: number): string[] {
760
- const lines: string[] = [];
761
- if (step.expand || step.collect) {
762
- const parallel = step.parallel && !Array.isArray(step.parallel) && typeof step.parallel === "object" ? step.parallel as { agent?: unknown; task?: unknown; label?: unknown; outputSchema?: unknown } : undefined;
763
- const expand = step.expand && typeof step.expand === "object" ? step.expand as { from?: { output?: unknown; path?: unknown }; item?: unknown; key?: unknown; maxItems?: unknown; onEmpty?: unknown } : undefined;
764
- const collect = step.collect && typeof step.collect === "object" ? step.collect as { as?: unknown; outputSchema?: unknown } : undefined;
765
- lines.push(`${index + 1}. Dynamic fanout${typeof collect?.as === "string" ? ` -> ${collect.as}` : ""}`);
766
- if (expand?.from) lines.push(` Expand: ${String(expand.from.output ?? "?")}${String(expand.from.path ?? "")}`);
767
- if (typeof expand?.item === "string") lines.push(` Item variable: ${expand.item}`);
768
- if (typeof expand?.key === "string") lines.push(` Key: ${expand.key}`);
769
- if (typeof expand?.maxItems === "number") lines.push(` Max items: ${expand.maxItems}`);
770
- if (typeof expand?.onEmpty === "string") lines.push(` On empty: ${expand.onEmpty}`);
771
- if (parallel?.agent) lines.push(` Agent: ${String(parallel.agent)}`);
772
- if (typeof parallel?.label === "string") lines.push(` Label: ${parallel.label}`);
773
- if (typeof parallel?.task === "string" && parallel.task.trim()) lines.push(` Task: ${parallel.task}`);
774
- if (parallel?.outputSchema) lines.push(" Structured output: true");
775
- if (parallel && "toolBudget" in parallel) lines.push(` Tool budget: ${JSON.stringify((parallel as { toolBudget?: unknown }).toolBudget)}`);
776
- if (collect?.outputSchema) lines.push(" Collect schema: true");
777
- if (step.concurrency !== undefined) lines.push(` Concurrency: ${step.concurrency}`);
778
- if (step.failFast !== undefined) lines.push(` Fail fast: ${step.failFast ? "true" : "false"}`);
779
- return lines;
780
- }
781
- lines.push(`${index + 1}. ${step.agent}`);
782
- if (step.task?.trim()) lines.push(` Task: ${step.task}`);
783
- if (step.output === false) lines.push(" Output: false");
784
- else if (step.output) lines.push(` Output: ${step.output}`);
785
- if (step.outputMode) lines.push(` Output mode: ${step.outputMode}`);
786
- if (step.toolBudget) lines.push(` Tool budget: ${JSON.stringify(step.toolBudget)}`);
787
- if (step.reads === false) lines.push(" Reads: false");
788
- else if (Array.isArray(step.reads) && step.reads.length > 0) lines.push(` Reads: ${step.reads.join(", ")}`);
789
- if (step.model) lines.push(` Model: ${step.model}`);
790
- if (step.skills === false) lines.push(" Skills: false");
791
- else if (Array.isArray(step.skills) && step.skills.length > 0) lines.push(` Skills: ${step.skills.join(", ")}`);
792
- if (step.progress !== undefined) lines.push(` Progress: ${step.progress ? "true" : "false"}`);
793
- return lines;
794
- }
795
-
796
- function formatChainDetail(chain: ChainConfig): string {
797
- const lines: string[] = [`Chain: ${chain.name} (${chain.source})`, `Path: ${chain.filePath}`, `Description: ${chain.description}`];
798
- if (chain.packageName) {
799
- lines.push(`Local name: ${frontmatterNameForConfig(chain)}`);
800
- lines.push(`Package: ${chain.packageName}`);
801
- }
802
- lines.push("", "Steps:");
803
- for (let i = 0; i < chain.steps.length; i++) {
804
- lines.push(...formatChainStepDetail(chain.steps[i]!, i));
805
- }
806
- return lines.join("\n");
807
- }
808
-
809
688
  export function handleList(params: ManagementParams, ctx: ManagementContext): AgentToolResult<Details> {
810
689
  const scope = normalizeListScope(params.agentScope) ?? "both";
811
690
  const d = discoverAgentsAll(ctx.cwd);
812
- const scopedAgents = mergeAgentsForScope(scope, d.user, d.project, d.builtin, d.package)
691
+ let scopedAgents = mergeAgentsForScope(scope, d.user, d.project, d.builtin, d.package);
692
+ if (ctx.runtimeAgentOwner && listRuntimeAgentConfigs(ctx.runtimeAgentOwner).length > 0) {
693
+ const configuredAgents: AgentConfig[] = [
694
+ ...d.builtin,
695
+ ...d.package,
696
+ ...d.user,
697
+ ...d.project,
698
+ ];
699
+ scopedAgents = mergeRuntimeAgents(ctx.runtimeAgentOwner, { agents: scopedAgents }, configuredAgents).agents;
700
+ }
701
+ scopedAgents = scopedAgents
813
702
  .sort((a, b) => a.name.localeCompare(b.name));
814
703
  const capabilityCeiling = resolveCurrentSubagentCapabilityCeiling(ctx.currentSessionId);
815
704
  const visibleAgents = scopedAgents.filter((a) => !a.disabled);
816
705
  const agents = visibleAgents.filter((a) => isAgentAllowedByCapabilityCeiling(a.name, capabilityCeiling));
817
706
  const restrictedAgents = visibleAgents.filter((a) => !isAgentAllowedByCapabilityCeiling(a.name, capabilityCeiling));
818
707
  const restrictedSources = capabilityCeilingAgentRestrictionSources(capabilityCeiling);
819
- const chains = d.chains.filter((c) => scope === "both" || c.source === "package" || c.source === scope).sort((a, b) => a.name.localeCompare(b.name));
820
- const diagnostics = d.chainDiagnostics.filter((entry) => scope === "both" || entry.source === scope);
821
708
  const proactiveSuggestions = buildProactiveSkillSubagentRecommendationLines({
822
709
  agents,
823
- chains,
824
710
  ...(ctx.config?.proactiveSkillSubagents !== undefined ? { config: ctx.config.proactiveSkillSubagents } : {}),
825
711
  discoverAvailableSkills: () => discoverAvailableSkills(ctx.cwd),
826
712
  });
@@ -834,11 +720,12 @@ export function handleList(params: ManagementParams, ctx: ManagementContext): Ag
834
720
  `Restricted agents (not executable in this session${restrictedSources?.length ? `; capability ceiling: ${restrictedSources.join(", ")}` : ""}):`,
835
721
  ...restrictedAgents.map((a) => `- ${a.name} (${a.source}${a.aliases?.length ? `, aliases: ${a.aliases.join(", ")}` : ""}): ${a.description}`),
836
722
  ] : []),
837
- "",
838
- "Chains:",
839
- ...(chains.length ? chains.map((c) => `- ${c.name} (${c.source}): ${c.description}`) : ["- (none)"]),
723
+ ...(d.agentDiagnostics?.length ? [
724
+ "",
725
+ "Invalid agent definitions:",
726
+ ...d.agentDiagnostics.map((diagnostic) => `- ${diagnostic.name ?? diagnostic.filePath} (${diagnostic.source}): ${diagnostic.error}`),
727
+ ] : []),
840
728
  ...(proactiveSuggestions.length ? ["", ...proactiveSuggestions] : []),
841
- ...(diagnostics.length ? ["", "Chain diagnostics:", ...diagnostics.map((entry) => `- ${entry.filePath}: ${entry.error}`)] : []),
842
729
  ];
843
730
  return result(lines.join("\n"));
844
731
  }
@@ -925,40 +812,23 @@ function handleModels(params: ManagementParams, ctx: ManagementContext): AgentTo
925
812
  }
926
813
 
927
814
  function handleGet(params: ManagementParams, ctx: ManagementContext): AgentToolResult<Details> {
928
- if (!params.agent && !params.chainName) return result("Specify 'agent' or 'chainName' for get.", true);
815
+ if (!params.agent) return result("Specify 'agent' for get.", true);
929
816
  const scope = normalizeListScope(params.agentScope);
930
817
  if (!scope) return result("agentScope must be 'user', 'project', or 'both' for get.", true);
931
- const hasBoth = Boolean(params.agent && params.chainName);
932
- const blocks: string[] = [];
933
- let anyFound = false;
934
- if (params.agent) {
935
- const matches = findAgents(params.agent, ctx.cwd, scope);
936
- const distinctNames = [...new Set(matches.map((agent) => agent.name))];
937
- if (distinctNames.length > 1) {
938
- const msg = `Ambiguous agent alias or name '${params.agent}': ${distinctNames.sort((a, b) => a.localeCompare(b)).join(", ")}`;
939
- if (!hasBoth) return result(msg, true);
940
- blocks.push(msg);
941
- } else if (!matches.length) {
942
- const msg = `Agent '${params.agent}' not found. Available: ${availableNames(ctx.cwd, "agent").join(", ") || "none"}.`;
943
- if (!hasBoth) return result(msg, true);
944
- blocks.push(msg);
945
- } else {
946
- anyFound = true;
947
- blocks.push(...matches.map(formatAgentDetail));
948
- }
949
- }
950
- if (params.chainName) {
951
- const matches = findChains(params.chainName, ctx.cwd, scope);
952
- if (!matches.length) {
953
- const msg = `Chain '${params.chainName}' not found. Available: ${availableNames(ctx.cwd, "chain").join(", ") || "none"}.`;
954
- if (!hasBoth) return result(msg, true);
955
- blocks.push(msg);
956
- } else {
957
- anyFound = true;
958
- blocks.push(...matches.map(formatChainDetail));
959
- }
960
- }
961
- return result(blocks.join("\n\n"), !anyFound);
818
+ const discovered = discoverAgentsAll(ctx.cwd);
819
+ const matches = findAgentsInDiscovery(params.agent, discovered, scope);
820
+ const diagnostics = diagnosticsForScope(discovered.agentDiagnostics, scope);
821
+ const rawName = params.agent.trim();
822
+ const normalizedName = sanitizeName(rawName);
823
+ const diagnostic = findBlockingAgentDiagnostic(rawName, matches, diagnostics)
824
+ ?? (normalizedName !== rawName ? findBlockingAgentDiagnostic(normalizedName, matches, diagnostics) : undefined);
825
+ if (diagnostic) return result(`Agent '${params.agent}' has invalid configuration: ${diagnostic.error}`, true);
826
+ const distinctNames = [...new Set(matches.map((agent) => agent.name))];
827
+ if (distinctNames.length > 1) return result(`Ambiguous agent alias or name '${params.agent}': ${distinctNames.sort((a, b) => a.localeCompare(b)).join(", ")}`, true);
828
+ if (!matches.length) {
829
+ return result(`Agent '${params.agent}' not found. Available: ${availableAgentNamesFromDiscovery(discovered).join(", ") || "none"}.`, true);
830
+ }
831
+ return result(matches.map(formatAgentDetail).join("\n\n"));
962
832
  }
963
833
 
964
834
  export function handleCreate(params: ManagementParams, ctx: ManagementContext): AgentToolResult<Details> {
@@ -976,36 +846,16 @@ export function handleCreate(params: ManagementParams, ctx: ManagementContext):
976
846
  const scopeRaw = cfg.scope ?? "user";
977
847
  if (scopeRaw !== "user" && scopeRaw !== "project") return result("config.scope must be 'user' or 'project'.", true);
978
848
  const scope = scopeRaw as ManagementScope;
979
- const isChain = hasKey(cfg, "steps");
849
+ if (hasKey(cfg, "steps")) return result("Durable chain definitions were removed; use workflowScript or /prompt-workflow for repeatable workflows.", true);
980
850
  const d = discoverAgentsAll(ctx.cwd);
981
851
  const projectConfigDir = getProjectConfigDir(ctx.cwd);
982
- const targetDir = isChain
983
- ? scope === "user" ? d.userChainDir : d.projectChainDir ?? path.join(projectConfigDir, "chains")
984
- : scope === "user" ? d.userDir : d.projectDir ?? path.join(projectConfigDir, "agents");
852
+ const targetDir = scope === "user" ? d.userDir : d.projectDir ?? path.join(projectConfigDir, "agents");
985
853
  fs.mkdirSync(targetDir, { recursive: true });
986
854
  if (nameExistsInScope(ctx.cwd, scope, runtimeName)) return result(`Name '${runtimeName}' already exists in ${scope} scope. Use update instead.`, true);
987
- const targetPath = path.join(targetDir, isChain ? `${runtimeName}.chain.md` : `${runtimeName}.md`);
988
- if (fs.existsSync(targetPath)) return result(`File already exists at ${targetPath} but is not a valid ${isChain ? "chain" : "agent"} definition. Remove or rename it first.`, true);
855
+ const targetPath = path.join(targetDir, `${runtimeName}.md`);
856
+ if (fs.existsSync(targetPath)) return result(`File already exists at ${targetPath} but is not a valid agent definition. Remove or rename it first.`, true);
989
857
  const warnings: string[] = [];
990
- if (!isChain && d.builtin.some((a) => a.name === runtimeName)) warnings.push(`Note: this shadows the builtin agent '${runtimeName}'.`);
991
- if (isChain) {
992
- const parsed = parseStepList(cfg.steps);
993
- if (parsed.error) return result(parsed.error, true);
994
- const chain: ChainConfig = {
995
- name: runtimeName,
996
- localName: name,
997
- ...(parsedPackage.packageName !== undefined ? { packageName: parsedPackage.packageName } : {}),
998
- description: cfg.description.trim(),
999
- source: scope,
1000
- filePath: targetPath,
1001
- steps: parsed.steps!,
1002
- };
1003
- fs.writeFileSync(targetPath, serializeChain(chain), "utf-8");
1004
- const missing = unknownChainAgents(ctx.cwd, chain.steps);
1005
- if (missing.length) warnings.push(`Warning: chain steps reference unknown agents: ${missing.join(", ")}.`);
1006
- warnings.push(...chainStepWarnings(ctx, chain.steps));
1007
- return result([`Created chain '${runtimeName}' at ${targetPath}.`, ...warnings].join("\n"));
1008
- }
858
+ if (d.builtin.some((a) => a.name === runtimeName)) warnings.push(`Note: this shadows the builtin agent '${runtimeName}'.`);
1009
859
  const agent: AgentConfig = {
1010
860
  name: runtimeName,
1011
861
  localName: name,
@@ -1031,75 +881,25 @@ export function handleCreate(params: ManagementParams, ctx: ManagementContext):
1031
881
  }
1032
882
 
1033
883
  export function handleUpdate(params: ManagementParams, ctx: ManagementContext): AgentToolResult<Details> {
1034
- if (!params.agent && !params.chainName) return result("Specify 'agent' or 'chainName' for update.", true);
1035
- if (params.agent && params.chainName) return result("Specify either 'agent' or 'chainName', not both.", true);
884
+ if (!params.agent) return result("Specify 'agent' for update.", true);
1036
885
  const parsedConfig = configObject(params.config);
1037
886
  if (parsedConfig.error) return result(parsedConfig.error, true);
1038
887
  const cfg = parsedConfig.value;
1039
888
  if (!cfg) return result("config required for update.", true);
889
+ if (hasKey(cfg, "steps")) return result("Durable chain definitions were removed; use workflowScript or /prompt-workflow for repeatable workflows.", true);
1040
890
  const warnings: string[] = [];
1041
- if (params.agent) {
1042
- const scopeHint = asDisambiguationScope(params.agentScope);
1043
- const targetOrError = resolveTarget("agent", params.agent, findAgents(params.agent, ctx.cwd, scopeHint ?? "both"), ctx.cwd, scopeHint);
1044
- if ("content" in targetOrError) return targetOrError;
1045
- const target = targetOrError;
1046
- if (target.source !== "user" && target.source !== "project") return result(`Cannot update ${target.source} agent '${target.name}'. Eject it to user or project scope first.`, true);
1047
- const updated = editableAgentConfig(target);
1048
- const oldName = target.name;
1049
- if (hasKey(cfg, "name") && (typeof cfg.name !== "string" || !cfg.name.trim())) return result("config.name must be a non-empty string when provided.", true);
1050
- if (hasKey(cfg, "description") && (typeof cfg.description !== "string" || !cfg.description.trim())) return result("config.description must be a non-empty string when provided.", true);
1051
- let newLocalName = target.localName ?? frontmatterNameForConfig(target);
1052
- if (hasKey(cfg, "name")) {
1053
- newLocalName = sanitizeName(cfg.name as string);
1054
- if (!newLocalName) return result("config.name is invalid after sanitization.", true);
1055
- }
1056
- let newPackageName = target.packageName;
1057
- if (hasKey(cfg, "package")) {
1058
- const parsedPackage = parsePackageConfig(cfg.package);
1059
- if (parsedPackage.error) return result(parsedPackage.error, true);
1060
- newPackageName = parsedPackage.packageName;
1061
- }
1062
- const applyError = applyAgentConfig(updated, cfg);
1063
- if (applyError) return result(applyError, true);
1064
- const preserveFrontmatterFields = preservedAgentFrontmatterFields(target, cfg);
1065
- updated.localName = newLocalName;
1066
- if (newPackageName !== undefined) updated.packageName = newPackageName;
1067
- else delete updated.packageName;
1068
- updated.name = buildRuntimeName(newLocalName, newPackageName);
1069
- if (hasKey(cfg, "description")) updated.description = (cfg.description as string).trim();
1070
- if (hasKey(cfg, "model")) {
1071
- const mw = modelWarning(ctx, updated.model);
1072
- if (mw) warnings.push(mw);
1073
- }
1074
- if (hasKey(cfg, "fallbackModels")) {
1075
- const fmw = fallbackModelsWarning(ctx, updated.fallbackModels);
1076
- if (fmw) warnings.push(fmw);
1077
- }
1078
- if (hasKey(cfg, "skills") || hasKey(cfg, "skillPath")) {
1079
- const sw = skillsWarning(ctx.cwd, updated);
1080
- if (sw) warnings.push(sw);
1081
- }
1082
- if (updated.name !== oldName) {
1083
- const renamed = renamePath("agent", target.filePath, updated.name, target.source, ctx.cwd);
1084
- if (renamed.error) return result(renamed.error, true);
1085
- updated.filePath = renamed.filePath!;
1086
- }
1087
- fs.writeFileSync(updated.filePath, serializeAgent(updated, { preserveFrontmatterFields }), "utf-8");
1088
- if (updated.name !== oldName) {
1089
- const refs = discoverAgentsAll(ctx.cwd).chains.filter((c) => c.steps.some((s) => s.agent === oldName)).map((c) => `${c.name} (${c.source})`);
1090
- if (refs.length) warnings.push(`Warning: chains still reference '${oldName}': ${refs.join(", ")}.`);
1091
- }
1092
- const headline = updated.name === oldName
1093
- ? `Updated agent '${updated.name}' at ${updated.filePath}.`
1094
- : `Updated agent '${oldName}' to '${updated.name}' at ${updated.filePath}.`;
1095
- return result([headline, ...warnings].join("\n"));
1096
- }
1097
891
  const scopeHint = asDisambiguationScope(params.agentScope);
1098
- const targetOrError = resolveTarget("chain", params.chainName!, findChains(params.chainName!, ctx.cwd, scopeHint ?? "both"), ctx.cwd, scopeHint);
892
+ const targetOrError = resolveTarget(params.agent, findAgents(params.agent, ctx.cwd, scopeHint ?? "both"), ctx.cwd, scopeHint);
1099
893
  if ("content" in targetOrError) return targetOrError;
1100
894
  const target = targetOrError;
1101
- if (target.source !== "user" && target.source !== "project") return result(`Cannot update ${target.source} chain '${target.name}'. Eject it to user or project scope first.`, true);
1102
- const updated: ChainConfig = { ...target, steps: [...target.steps] };
895
+ if (target.source !== "user" && target.source !== "project") return result(`Cannot update ${target.source} agent '${target.name}'. Eject it to user or project scope first.`, true);
896
+ let updated: AgentConfig;
897
+ try {
898
+ updated = editableAgentConfig(target);
899
+ } catch (error) {
900
+ const message = error instanceof Error ? error.message : String(error);
901
+ return result(`Could not reread agent definition ${target.filePath} before updating '${target.name}': ${message}`, true);
902
+ }
1103
903
  const oldName = target.name;
1104
904
  if (hasKey(cfg, "name") && (typeof cfg.name !== "string" || !cfg.name.trim())) return result("config.name must be a non-empty string when provided.", true);
1105
905
  if (hasKey(cfg, "description") && (typeof cfg.description !== "string" || !cfg.description.trim())) return result("config.description must be a non-empty string when provided.", true);
@@ -1114,70 +914,71 @@ export function handleUpdate(params: ManagementParams, ctx: ManagementContext):
1114
914
  if (parsedPackage.error) return result(parsedPackage.error, true);
1115
915
  newPackageName = parsedPackage.packageName;
1116
916
  }
1117
- let parsedSteps: ChainStepConfig[] | undefined;
1118
- if (hasKey(cfg, "steps")) {
1119
- const parsed = parseStepList(cfg.steps);
1120
- if (parsed.error) return result(parsed.error, true);
1121
- parsedSteps = parsed.steps!;
1122
- }
917
+ const applyError = applyAgentConfig(updated, cfg);
918
+ if (applyError) return result(applyError, true);
919
+ const preserveFrontmatterFields = preservedAgentFrontmatterFields(target, cfg);
1123
920
  updated.localName = newLocalName;
1124
921
  if (newPackageName !== undefined) updated.packageName = newPackageName;
1125
922
  else delete updated.packageName;
1126
923
  updated.name = buildRuntimeName(newLocalName, newPackageName);
1127
924
  if (hasKey(cfg, "description")) updated.description = (cfg.description as string).trim();
1128
- if (parsedSteps) {
1129
- updated.steps = parsedSteps;
1130
- const missing = unknownChainAgents(ctx.cwd, updated.steps);
1131
- if (missing.length) warnings.push(`Warning: chain steps reference unknown agents: ${missing.join(", ")}.`);
1132
- warnings.push(...chainStepWarnings(ctx, updated.steps));
925
+ if (hasKey(cfg, "model")) {
926
+ const mw = modelWarning(ctx, updated.model);
927
+ if (mw) warnings.push(mw);
928
+ }
929
+ if (hasKey(cfg, "fallbackModels")) {
930
+ const fmw = fallbackModelsWarning(ctx, updated.fallbackModels);
931
+ if (fmw) warnings.push(fmw);
932
+ }
933
+ if (hasKey(cfg, "skills") || hasKey(cfg, "skillPath")) {
934
+ const sw = skillsWarning(ctx.cwd, updated);
935
+ if (sw) warnings.push(sw);
1133
936
  }
1134
937
  if (updated.name !== oldName) {
1135
- const renamed = renamePath("chain", target.filePath, updated.name, target.source, ctx.cwd);
938
+ const renamed = renamePath(target.filePath, updated.name, target.source, ctx.cwd);
1136
939
  if (renamed.error) return result(renamed.error, true);
1137
940
  updated.filePath = renamed.filePath!;
1138
941
  }
1139
- fs.writeFileSync(updated.filePath, updated.filePath.endsWith(".chain.json") ? serializeJsonChain(updated) : serializeChain(updated), "utf-8");
942
+ fs.writeFileSync(updated.filePath, serializeAgent(updated, { preserveFrontmatterFields }), "utf-8");
1140
943
  const headline = updated.name === oldName
1141
- ? `Updated chain '${updated.name}' at ${updated.filePath}.`
1142
- : `Updated chain '${oldName}' to '${updated.name}' at ${updated.filePath}.`;
944
+ ? `Updated agent '${updated.name}' at ${updated.filePath}.`
945
+ : `Updated agent '${oldName}' to '${updated.name}' at ${updated.filePath}.`;
1143
946
  return result([headline, ...warnings].join("\n"));
1144
947
  }
1145
948
 
1146
949
  function handleDelete(params: ManagementParams, ctx: ManagementContext): AgentToolResult<Details> {
1147
- if (!params.agent && !params.chainName) return result("Specify 'agent' or 'chainName' for delete.", true);
1148
- if (params.agent && params.chainName) return result("Specify either 'agent' or 'chainName', not both.", true);
950
+ if (!params.agent) return result("Specify 'agent' for delete.", true);
1149
951
  const scopeHint = asDisambiguationScope(params.agentScope);
1150
- if (params.agent) {
1151
- const targetOrError = resolveTarget("agent", params.agent, findAgents(params.agent, ctx.cwd, scopeHint ?? "both"), ctx.cwd, scopeHint);
1152
- if ("content" in targetOrError) return targetOrError;
1153
- const target = targetOrError;
1154
- fs.unlinkSync(target.filePath);
1155
- const refs = discoverAgentsAll(ctx.cwd).chains.filter((c) => c.steps.some((s) => s.agent === target.name)).map((c) => `${c.name} (${c.source})`);
1156
- const lines = [`Deleted agent '${target.name}' at ${target.filePath}.`];
1157
- if (refs.length) lines.push(`Warning: chains reference deleted agent '${target.name}': ${refs.join(", ")}.`);
1158
- return result(lines.join("\n"));
1159
- }
1160
- const targetOrError = resolveTarget("chain", params.chainName!, findChains(params.chainName!, ctx.cwd, scopeHint ?? "both"), ctx.cwd, scopeHint);
952
+ const targetOrError = resolveTarget(params.agent, findAgents(params.agent, ctx.cwd, scopeHint ?? "both"), ctx.cwd, scopeHint);
1161
953
  if ("content" in targetOrError) return targetOrError;
1162
954
  const target = targetOrError;
1163
955
  fs.unlinkSync(target.filePath);
1164
- return result(`Deleted chain '${target.name}' at ${target.filePath}.`);
956
+ return result(`Deleted agent '${target.name}' at ${target.filePath}.`);
1165
957
  }
1166
958
 
1167
959
  function isRelativeAgentResourcePath(value: string): boolean {
1168
960
  return value === "." || value === ".." || value.startsWith("./") || value.startsWith("../");
1169
961
  }
1170
962
 
963
+ /**
964
+ * Upstream v0.53.0 resolves agent-frontmatter extension paths to absolute
965
+ * paths at discovery time, so a portable resource is any entry that is a
966
+ * path (relative or absolute) rather than a bare tool name.
967
+ */
968
+ function isAgentResourcePath(value: string): boolean {
969
+ return isRelativeAgentResourcePath(value) || path.isAbsolute(value);
970
+ }
971
+
1171
972
  function resolvePortableAgentResources(
1172
973
  entries: string[] | undefined,
1173
974
  sourceFilePath: string,
1174
975
  ): { entries: string[] | undefined; resourcePaths: string[] } {
1175
976
  const baseDir = path.dirname(sourceFilePath);
1176
- const resourcePaths = (entries ?? [])
1177
- .filter(isRelativeAgentResourcePath)
1178
- .map((entry) => path.resolve(baseDir, entry));
977
+ const resourcePaths = (entries ?? []).flatMap((entry) =>
978
+ isAgentResourcePath(entry) ? [path.resolve(baseDir, entry)] : [],
979
+ );
1179
980
  return {
1180
- entries: entries?.map((entry) => isRelativeAgentResourcePath(entry) ? path.resolve(baseDir, entry) : entry),
981
+ entries: entries?.map((entry) => isAgentResourcePath(entry) ? path.resolve(baseDir, entry) : entry),
1181
982
  resourcePaths,
1182
983
  };
1183
984
  }
@@ -1335,7 +1136,7 @@ export function ejectAgentDefinition(input: EjectAgentDefinitionInput): EjectAge
1335
1136
  ok: false,
1336
1137
  code: "missing_source",
1337
1138
  scope: input.scope,
1338
- message: `Agent '${raw}' not found or is not a bundled/package agent. eject copies a builtin or package agent to ${input.scope} scope so it can be customized. Available: ${availableNames(input.cwd, "agent").join(", ") || "none"}.`,
1139
+ message: `Agent '${raw}' not found or is not a bundled/package agent. eject copies a builtin or package agent to ${input.scope} scope so it can be customized. Available: ${availableAgentNames(input.cwd).join(", ") || "none"}.`,
1339
1140
  };
1340
1141
  }
1341
1142
  const runtimeName = source.name;
@@ -1452,7 +1253,7 @@ function handleDisable(params: ManagementParams, ctx: ManagementContext): AgentT
1452
1253
  const effective = resolveEffectiveAgent(d, raw);
1453
1254
  if (effective.error) return result(effective.error, true);
1454
1255
  if (!effective.agent) {
1455
- return result(`Agent '${raw}' not found. Available: ${availableNames(ctx.cwd, "agent").join(", ") || "none"}.`, true);
1256
+ return result(`Agent '${raw}' not found. Available: ${availableAgentNames(ctx.cwd).join(", ") || "none"}.`, true);
1456
1257
  }
1457
1258
  const runtimeName = effective.agent.name;
1458
1259
  const settingsPath = mergeBuiltinAgentOverride(ctx.cwd, runtimeName, scope, { disabled: true });
@@ -1476,7 +1277,7 @@ function handleEnable(params: ManagementParams, ctx: ManagementContext): AgentTo
1476
1277
  const effective = resolveEffectiveAgent(d, raw);
1477
1278
  if (effective.error) return result(effective.error, true);
1478
1279
  if (!effective.agent) {
1479
- return result(`Agent '${raw}' not found. Available: ${availableNames(ctx.cwd, "agent").join(", ") || "none"}.`, true);
1280
+ return result(`Agent '${raw}' not found. Available: ${availableAgentNames(ctx.cwd).join(", ") || "none"}.`, true);
1480
1281
  }
1481
1282
  const runtimeName = effective.agent.name;
1482
1283
  const { path: settingsPath, removed } = removeBuiltinAgentOverrideFields(ctx.cwd, runtimeName, scope, ["disabled"]);
@@ -1508,7 +1309,7 @@ function handleReset(params: ManagementParams, ctx: ManagementContext): AgentToo
1508
1309
  if (custom) {
1509
1310
  return result(`Agent '${raw}' has no bundled default to reset to. Use { action: "delete", agent: "${custom.name}" } to remove the custom ${custom.source} agent.`, true);
1510
1311
  }
1511
- return result(`Agent '${raw}' not found. Available: ${availableNames(ctx.cwd, "agent").join(", ") || "none"}.`, true);
1312
+ return result(`Agent '${raw}' not found. Available: ${availableAgentNames(ctx.cwd).join(", ") || "none"}.`, true);
1512
1313
  }
1513
1314
  const runtimeName = bundled.name;
1514
1315
  const custom = (scope === "user" ? d.user : d.project).find((a) => a.name === raw || a.name === sanitized);