@xzzpig/pi-subagents 0.1.0 → 0.3.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 (108) hide show
  1. package/CHANGELOG.md +135 -0
  2. package/README.md +4 -0
  3. package/agents/reviewer.md +3 -4
  4. package/docs/agents.md +343 -0
  5. package/docs/configuration.md +395 -0
  6. package/docs/extension-api.md +308 -0
  7. package/docs/missions.md +121 -0
  8. package/docs/models.md +192 -0
  9. package/docs/observability.md +198 -0
  10. package/docs/tool-reference.md +343 -0
  11. package/docs/watchdog.md +176 -0
  12. package/docs/workflows.md +163 -0
  13. package/package.json +13 -11
  14. package/skills/pi-subagents/references/constraints-and-recipes.md +1 -1
  15. package/skills/pi-subagents/references/execution-controls.md +7 -7
  16. package/skills/pi-subagents/references/management-authoring-rpc.md +1 -1
  17. package/skills/pi-subagents/references/prompting-and-roles.md +1 -1
  18. package/src/agents/agents.ts +53 -23
  19. package/src/agents/frontmatter.ts +7 -3
  20. package/src/agents/skills.ts +2 -9
  21. package/src/api/preflight.ts +1 -1
  22. package/src/api/project-panes.ts +30 -0
  23. package/src/extension/config.ts +54 -1
  24. package/src/extension/doctor.ts +40 -0
  25. package/src/extension/fanout-child.ts +5 -4
  26. package/src/extension/index.ts +114 -38
  27. package/src/extension/public-execution.ts +35 -4
  28. package/src/extension/rpc.ts +10 -15
  29. package/src/extension/schemas.ts +33 -11
  30. package/src/extension/subagent-guide.ts +39 -0
  31. package/src/extension/tool-description.ts +38 -18
  32. package/src/inspectors/herdr/actions.ts +11 -2
  33. package/src/inspectors/herdr/inspector-runner.ts +16 -3
  34. package/src/inspectors/herdr/project-panes.ts +459 -63
  35. package/src/intercom/intercom-bridge.ts +7 -2
  36. package/src/intercom/native-supervisor-channel.ts +102 -4
  37. package/src/missions/actions.ts +25 -2
  38. package/src/missions/lifecycle.ts +25 -9
  39. package/src/missions/store.ts +89 -7
  40. package/src/missions/types.ts +33 -0
  41. package/src/missions/workflow-state.ts +25 -15
  42. package/src/runs/background/active-async-capacity.ts +431 -0
  43. package/src/runs/background/active-run-index.ts +46 -0
  44. package/src/runs/background/async-execution.ts +158 -71
  45. package/src/runs/background/async-job-tracker.ts +297 -133
  46. package/src/runs/background/async-resume.ts +37 -5
  47. package/src/runs/background/async-status.ts +39 -5
  48. package/src/runs/background/chain-append.ts +33 -15
  49. package/src/runs/background/completion-replay.ts +267 -0
  50. package/src/runs/background/control-channel.ts +95 -54
  51. package/src/runs/background/fleet-view.ts +18 -5
  52. package/src/runs/background/owned-process-tree.ts +104 -0
  53. package/src/runs/background/process-terminal.ts +17 -3
  54. package/src/runs/background/result-watcher.ts +113 -10
  55. package/src/runs/background/resume-guidance.ts +53 -0
  56. package/src/runs/background/retained-children.ts +14 -6
  57. package/src/runs/background/run-status.ts +119 -5
  58. package/src/runs/background/scheduled-runs.ts +25 -1
  59. package/src/runs/background/stale-run-reconciler.ts +12 -24
  60. package/src/runs/background/subagent-runner.ts +127 -41
  61. package/src/runs/background/subagent-wait.ts +5 -2
  62. package/src/runs/background/wait-completions.ts +39 -5
  63. package/src/runs/background/wait-subscriptions.ts +21 -5
  64. package/src/runs/foreground/async-dismiss-action.ts +85 -0
  65. package/src/runs/foreground/async-steering-action.ts +7 -8
  66. package/src/runs/foreground/chain-execution.ts +40 -2
  67. package/src/runs/foreground/execution.ts +97 -19
  68. package/src/runs/foreground/foreground-control.ts +12 -0
  69. package/src/runs/foreground/foreground-history.ts +137 -0
  70. package/src/runs/foreground/prompt-audit.ts +172 -0
  71. package/src/runs/foreground/subagent-executor.ts +1274 -243
  72. package/src/runs/foreground/workflow-foreground-steering.ts +187 -0
  73. package/src/runs/shared/acceptance.ts +13 -4
  74. package/src/runs/shared/completion-guard.ts +17 -1
  75. package/src/runs/shared/dynamic-fanout.ts +1 -1
  76. package/src/runs/shared/llm-intent-arbiter.ts +302 -0
  77. package/src/runs/shared/model-fallback.ts +8 -4
  78. package/src/runs/shared/model-scope.ts +12 -2
  79. package/src/runs/shared/parallel-utils.ts +3 -0
  80. package/src/runs/shared/pi-args.ts +44 -1
  81. package/src/runs/shared/run-fanout-budget.ts +280 -0
  82. package/src/runs/shared/single-output.ts +4 -2
  83. package/src/runs/shared/subagent-prompt-runtime.ts +94 -9
  84. package/src/runs/shared/task-intent.ts +19 -3
  85. package/src/runs/shared/worktree.ts +20 -7
  86. package/src/shared/agent-stream-options.ts +5 -0
  87. package/src/shared/artifacts.ts +17 -21
  88. package/src/shared/display-text.ts +150 -0
  89. package/src/shared/file-coalescer.ts +9 -0
  90. package/src/shared/fork-context.ts +13 -0
  91. package/src/shared/formatters.ts +4 -6
  92. package/src/shared/node-executable.ts +21 -0
  93. package/src/shared/prompt-resources.ts +51 -0
  94. package/src/shared/settings.ts +15 -2
  95. package/src/shared/types.ts +158 -4
  96. package/src/shared/utf8.ts +11 -0
  97. package/src/shared/utils.ts +46 -34
  98. package/src/slash/prompt-workflows.ts +2 -15
  99. package/src/slash/slash-commands.ts +22 -2
  100. package/src/tui/fleet-status.ts +29 -17
  101. package/src/tui/fleet-transcript.ts +1 -48
  102. package/src/tui/fleet.ts +362 -37
  103. package/src/tui/render.ts +235 -71
  104. package/src/watchdog/change-signature.ts +4 -3
  105. package/src/watchdog/permission-arbiter.ts +2 -1
  106. package/src/watchdog/review.ts +4 -3
  107. package/src/workflows/chat-progress.ts +8 -2
  108. package/src/workflows/scripted-workflow.ts +273 -20
@@ -254,22 +254,23 @@ const ControlOverrides = Type.Object({
254
254
  })),
255
255
  });
256
256
 
257
- const SubagentParamsSchema = Type.Object({
258
- agent: Type.Optional(Type.String({ description: "Agent target for management actions such as get, update, delete, and models." })),
257
+ const SubagentParamProperties = {
258
+ agent: Type.Optional(Type.String({ description: "Agent for one-child execution, or target for agent management actions." })),
259
+ task: Type.Optional(Type.String({ description: "Optional one-child task. Requires agent; cannot combine with action or workflowScript." })),
259
260
  resume: Type.Optional(Type.String({ description: "Retained child run id for a workflowScript runs.run/runs.all item. Mutually exclusive with agent; task supplies the follow-up." })),
260
261
  // Management action (when present, tool operates in management mode)
261
262
  action: Type.Optional(Type.String({ minLength: 1,
262
- description: "Optional management/control action. Omit this field for workflowScript execution; use it only for management/control actions."
263
+ description: "Optional management/control action. Omit this field for structured single-child or workflowScript execution; use it only for management/control actions."
263
264
  })),
264
265
  name: Type.Optional(Type.String({ description: "Human-readable name for action='schedule.create'." })),
265
266
  id: Type.Optional(Type.String({
266
- description: "Run id or prefix for status, interrupt, stop, resume, steer, append-step, approve-checkpoint, reject-checkpoint, or mission.attach-run."
267
+ description: "Run id/prefix for status/debug.run, interrupt, steer, append-step, approve-checkpoint, reject-checkpoint, or mission."
267
268
  })),
268
269
  runId: Type.Optional(Type.String({
269
- description: "Target run ID for interrupt, stop, resume, steer, append-step, approve-checkpoint, reject-checkpoint, or mission.attach-run. Prefer id for new calls."
270
+ description: "Target run ID for debug.run, interrupt, steer, append-step, or mission.attach-run. Prefer id."
270
271
  })),
271
272
  dir: Type.Optional(Type.String({
272
- description: "Async run directory for action='status', action='stop', action='resume', or action='steer'."
273
+ description: "Async run directory for status/debug.run, stop, resume, or steer."
273
274
  })),
274
275
  handoffPath: Type.Optional(Type.String({ description: "worktree.discard manifest." })),
275
276
  index: Type.Optional(Type.Integer({ minimum: 0, description: "Zero-based child index for actions that target a specific child or transcript." })),
@@ -278,6 +279,7 @@ const SubagentParamsSchema = Type.Object({
278
279
  description: "Optional status view. Use view='fleet' for a read-only active foreground/async fleet surface, or view='transcript' with id/dir (and optional index) to tail a run transcript.",
279
280
  })),
280
281
  lines: Type.Optional(Type.Integer({ minimum: 1, maximum: 500, description: "Maximum transcript lines for action='status', view='transcript'. Defaults to 80." })),
282
+ topic: Type.Optional(Type.String()),
281
283
  message: Type.Optional(Type.String({ description: "Follow-up message for resume, live guidance for steer, or optional startup prompt for project.open." })),
282
284
  mode: Type.Optional(Type.String({ enum: ["steer", "follow_up", "auto"], description: "Delivery mode for action='steer'. steer interrupts at the next safe point (default), follow_up waits for the next turn boundary, and auto follows up mid-turn but delivers immediately between turns." })),
283
285
  steeringRecovery: Type.Optional(Type.Boolean({ description: "For action='steer', allow pause-and-revive recovery after a missed acknowledgment. Defaults true for direct tool calls in steer mode; extension RPC steering forces false so callers retain exact child ownership." })),
@@ -295,7 +297,7 @@ const SubagentParamsSchema = Type.Object({
295
297
  overlap: Type.Optional(Type.String({ enum: ["skip"], description: "Overlap policy. This slice supports skip only." })),
296
298
  catchUp: Type.Optional(Type.String({ enum: ["none", "latest"], description: "Missed occurrence policy for recurring schedules. Defaults to latest." })),
297
299
  missionId: Type.Optional(Type.String({ description: "Mission id." })),
298
- mission: Type.Optional(Type.Unsafe({ ...MissionLaunchOverride, description: "Mission object, or false for no mission. Use objective for intent; goal:true with budget.tokens enables turn-end continuation notices." })),
300
+ mission: Type.Optional(Type.Unsafe({ ...MissionLaunchOverride, description: "Mission object, or false for no mission. Set exactly one non-empty title or summary; objective and labels are optional. goal may only be true and then requires budget.tokens." })),
299
301
  missionUpdate: Type.Optional(Type.Unsafe({ ...MissionUpdateOverride, description: "Mission update: objective, goal false or {paused:boolean}, budget, summary, labels, decisions, artifacts, or delivery receipts." })),
300
302
  missionStatus: Type.Optional(Type.String({ description: "Mission status." })),
301
303
  missionScope: Type.Optional(Type.String({ description: "Mission list scope: project (default) or global pointer index." })),
@@ -314,7 +316,7 @@ const SubagentParamsSchema = Type.Object({
314
316
  ],
315
317
  description: "Agent/chain config for create/update. Object or JSON string; presence of steps creates a chain."
316
318
  })),
317
- workflowScript: Type.Optional(Type.String({ minLength: 1, description: "Trusted inline JavaScript statement body. Starts async by default; pass async:false for a small foreground run. Use explicit return for output. Use await runs.run(key, {agent, task, worktree?, gate?}) or runs.run(key, {resume, task}), runs.all([...]), runs.status(id), runs.ref(s), emit(value), console, and return. Mission workflows also have async state.get(key) and state.set(key, JSONValue). Use ordinary JavaScript loops, branches, awaits, and arrays to mix sequential and parallel phases dynamically. Set worktree:true at workflow or child level for a separate managed worktree; child fields override workflow defaults. gate is one host-run command and cannot be combined with acceptance. runs.run accepts one child only. No filesystem, shell, Pi tools, or host globals." })),
319
+ workflowScript: Type.Optional(Type.String({ minLength: 1, description: "Trusted inline JavaScript statement body. Starts async by default; pass async:false for a small foreground run. Use explicit return for output. Use await prompts.render(ref, vars?) for task text. Use await runs.run(key, {agent, task, worktree?, gate?}) or runs.run(key, {resume, task}), runs.all([...]), runs.status(id), runs.ref(s), emit(value), console, and return. Mission workflows also have async state.get(key) and state.set(key, JSONValue). Compose sequential and parallel phases dynamically. Set worktree:true at workflow or child level for a separate managed worktree; child fields override workflow defaults. gate is one host-run command and cannot be combined with acceptance. runs.run accepts one child only. No filesystem, shell, Pi tools, or host globals." })),
318
320
  chatProgress: Type.Optional(Type.String({ enum: ["auto", "off", "live-card"], description: "WorkflowScript chat progress projection. auto shows a live in-chat card only for watched foreground workflows in the same Git repository; it is off otherwise." })),
319
321
  worktree: Type.Optional(Type.Boolean({ description: "Managed child isolation. true gives each workflow child a separate git worktree; an individual runs.run/runs.all item can override a workflow default with worktree:false." })),
320
322
  step: Type.Optional(Type.Unsafe({ ...ChainItem, description: "One chain step for action='append-step' only. Not an execution mode." })),
@@ -323,8 +325,8 @@ const SubagentParamsSchema = Type.Object({
323
325
  description: "'fresh' or 'fork' to branch from parent session. Explicit context overrides every child in the invocation. If omitted, each requested agent uses its own defaultContext; agents without defaultContext: 'fork' run fresh.",
324
326
  })),
325
327
  async: Type.Optional(Type.Boolean({ description: "Run in background (default: false, or per config)" })),
326
- timeoutMs: Type.Optional(Type.Integer({ minimum: 1, description: "Optional timeout for foreground and async/background runs. Foreground workflows default to 30m; async workflows have no default timeout. Alias maxRuntimeMs." })),
327
- maxRuntimeMs: Type.Optional(Type.Integer({ minimum: 1, description: "Alias timeoutMs for foreground and async/background runs. Foreground workflows default to 30m; async workflows have no default timeout." })),
328
+ timeoutMs: Type.Optional(Type.Integer({ minimum: 1, description: "Timeout. Foreground and single async runs use config timeoutMs, else 30m; async composites have no default parent deadline. Alias maxRuntimeMs." })),
329
+ maxRuntimeMs: Type.Optional(Type.Integer({ minimum: 1, description: "Alias timeoutMs. Foreground and single async runs use config timeoutMs, else 30m; async composites have no default parent deadline." })),
328
330
  turnBudget: Type.Optional(TurnBudgetOverride),
329
331
  toolBudget: Type.Optional(ToolBudgetOverride),
330
332
  usageBudget: Type.Optional(UsageBudgetOverride),
@@ -352,9 +354,29 @@ const SubagentParamsSchema = Type.Object({
352
354
  agentContract: Type.Optional(AgentContractOverride),
353
355
  acceptance: Type.Optional(AcceptanceOverride),
354
356
  gate: Type.Optional(Type.String({ minLength: 1, description: "Host gate command. Cannot be combined with acceptance." })),
355
- });
357
+ };
358
+
359
+ const { step: _legacyChainStep, ...subagentParamPropertiesWithoutStep } = SubagentParamProperties;
360
+ const trimmedSubagentParamProperties = {
361
+ ...subagentParamPropertiesWithoutStep,
362
+ id: Type.Optional(Type.String({
363
+ description: "Run id/prefix for status/debug.run, interrupt, steer, or mission.attach-run."
364
+ })),
365
+ runId: Type.Optional(Type.String({
366
+ description: "Target run ID for debug.run, interrupt, steer, or mission.attach-run. Prefer id."
367
+ })),
368
+ };
369
+ const SubagentParamsSchema = Type.Object(SubagentParamProperties);
370
+ const TrimmedSubagentParamsSchema = Type.Object(trimmedSubagentParamProperties);
356
371
 
357
372
  export const SubagentParams = keepTopLevelParameterDescriptions(SubagentParamsSchema);
373
+ export const SubagentParamsWithoutLegacyChainControls = keepTopLevelParameterDescriptions(TrimmedSubagentParamsSchema);
374
+
375
+ export function createSubagentParamsSchema(options: { legacyChainControls?: boolean } = {}): typeof SubagentParams | typeof SubagentParamsWithoutLegacyChainControls {
376
+ return options.legacyChainControls === true
377
+ ? SubagentParams
378
+ : SubagentParamsWithoutLegacyChainControls;
379
+ }
358
380
 
359
381
  const SubagentWaitParamsSchema = Type.Object({
360
382
  id: Type.Optional(Type.String({
@@ -0,0 +1,39 @@
1
+ import * as fs from "node:fs";
2
+ import * as path from "node:path";
3
+ import { fileURLToPath } from "node:url";
4
+
5
+ export const SUBAGENT_GUIDE_TOPICS = [
6
+ "overview",
7
+ "workflows",
8
+ "agents",
9
+ "missions",
10
+ "observability",
11
+ "tool-reference",
12
+ "configuration",
13
+ "models",
14
+ "watchdog",
15
+ "extension-api",
16
+ ] as const;
17
+
18
+ export type SubagentGuideTopic = (typeof SUBAGENT_GUIDE_TOPICS)[number];
19
+
20
+ const packageRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..", "..");
21
+
22
+ function isGuideTopic(value: string): value is SubagentGuideTopic {
23
+ return (SUBAGENT_GUIDE_TOPICS as readonly string[]).includes(value);
24
+ }
25
+
26
+ export function readSubagentGuide(topic = "overview", root = packageRoot): string {
27
+ if (!isGuideTopic(topic)) {
28
+ return `Unknown subagents guide topic '${topic}'. Valid topics: ${SUBAGENT_GUIDE_TOPICS.join(", ")}. No files were changed.`;
29
+ }
30
+ const filePath = topic === "overview"
31
+ ? path.join(root, "README.md")
32
+ : path.join(root, "docs", `${topic}.md`);
33
+ try {
34
+ return fs.readFileSync(filePath, "utf-8");
35
+ } catch (error) {
36
+ const message = error instanceof Error ? error.message : String(error);
37
+ throw new Error(`Failed to read packaged subagents guide '${topic}': ${message}`, { cause: error instanceof Error ? error : undefined });
38
+ }
39
+ }
@@ -8,24 +8,25 @@ const CUSTOM_TOOL_DESCRIPTION_MAX_BYTES = 50 * 1024;
8
8
 
9
9
  export const SUBAGENT_SAFETY_GUIDANCE = `SAFETY-CRITICAL SUBAGENT GUIDANCE:
10
10
  • Use { action: "list" } before execution and only run executable/non-disabled agents.
11
- • Keep execution and management separate: omit action for workflowScript execution; use action only for management/control.
12
- • Async/background runs are the default. Use async:false only when a blocking foreground result is needed. Do not sleep or poll status just to wait; use subagent_wait only when the current request must finish in this turn.
11
+ • Keep execution and management separate: omit action for structured single-child or workflowScript execution; use action only for management/control.
12
+ • Async/background runs are the default. Use async:false only when a blocking foreground result is needed. After an async launch, continue independent work only until its next dependency barrier; consume the result before work that depends on it. Do not sleep or poll status just to wait; use subagent_wait only when the current request must finish in this turn.
13
13
  • Ordinary child subagents are not orchestrators. Only explicitly configured fanout children may use the child-safe subagent tool, still bounded by depth/session limits.
14
14
  • Keep one writer for the same cwd/worktree. Use fresh-context read-only reviewers for independent review, then have the parent synthesize and apply fixes.
15
- • Async runs expose asyncId/asyncDir with status.json, events.jsonl, output logs, and status via { action: "status", id }. Include output paths and residual risks when reporting results.`;
15
+ • Async runs expose asyncId/asyncDir with status.json, events.jsonl, output logs, status via { action: "status", id }, and lifecycle diagnostics via { action: "debug.run", id }. Include output paths and residual risks when reporting results.`;
16
16
 
17
- export const FULL_SUBAGENT_TOOL_DESCRIPTION = `Run subagents only through { workflowScript }; omit action. Use action only for management/control actions.
17
+ export const FULL_SUBAGENT_TOOL_DESCRIPTION = `Run one child with { agent, task? }; use { workflowScript } for orchestration. Omit action for execution. Use action only for management/control actions.
18
18
 
19
19
  EXECUTION:
20
20
  • Before executing, use { action: "list" } and run only executable/non-disabled configured agents.
21
- • WORKFLOW SCRIPT: { workflowScript: "return runs.run('main', {agent:'worker', task:'...'})" }. Every execution is a workflow. Use stable-key runs.run for one child and runs.all for parallel children; ordinary JavaScript provides sequence, branching, filtering, retries, and aggregation. workflowScript is an ordinary JavaScript statement body, so use an explicit return for a useful result. Scripts start asynchronously by default; pass async:false only for a small foreground run. Same-repo foreground workflows default to a live in-chat card; set chatProgress to auto, off, or live-card to control that projection. Workflow-level child controls default onto each runs.run launch, and explicit child fields override them. Use {action:"children.list"} to list up to 10 completed retained children from this parent session, then continue one with runs.run(key, {resume:"run-id", task:"follow-up"}); resume and agent are mutually exclusive, and resume keeps the stored agent/model/tool contract. For repository mutation lanes, set worktree:true on the workflow or individual runs.run/runs.all item for managed isolation; each parallel child gets a separate worktree and handoff artifact. A workflow usageBudget is enforced once across the workflow. Available globals are runs.run, runs.all, runs.status, runs.ref/refs, emit, console, and standard JavaScript only. Workflows get async state.get(key) and state.set(key, JSONValue) through their automatic or explicit mission; mission:false workflows do not have a state global. Scripts cannot access filesystem, shell, arbitrary Pi tools, or host globals.
21
+ • SINGLE CHILD: { agent:"worker", task:"..." }. This structured form starts exactly one child through the workflow runtime. Workflow-level fields such as model, context, cwd, worktree, output, budgets, acceptance, and async remain defaults for that child. Do not combine agent/task with action or workflowScript.
22
+ • WORKFLOW SCRIPT: { workflowScript: "return runs.run('main', {agent:'worker', task:'...'})" }. Use stable-key runs.run for one child and runs.all for parallel children; ordinary JavaScript provides sequence, branching, filtering, retries, and aggregation. workflowScript is an ordinary JavaScript statement body, so use an explicit return for a useful result. For task text with Markdown fences or shell blocks, build quoted lines instead of nesting raw template literals: \`const task=["Run:","\`\`\`bash","npm test","\`\`\`"].join("\\n")\`. Scripts start asynchronously by default; pass async:false only for a small foreground run. Same-repo foreground workflows default to a live in-chat card; set chatProgress to auto, off, or live-card to control that projection. Workflow-level child controls default onto each runs.run launch, and explicit child fields override them. Use await prompts.render("package:name" | "user:name" | "project:name", vars?) for reusable plain task text, then pass the result explicitly as task. Use {action:"children.list"} to list up to 10 completed retained children from this parent session, then continue one with runs.run(key, {resume:"run-id", task:"follow-up"}); resume and agent are mutually exclusive, resume keeps the stored agent/model/tool contract, workflow resumes wait for completed output, and loops must continue from each latest returned runId. For repository mutation lanes, set worktree:true on the workflow or individual runs.run/runs.all item for managed isolation; each parallel child gets a separate worktree and handoff artifact. A workflow usageBudget is enforced once across the workflow. Available globals are runs.run, runs.all, runs.status, runs.ref/refs, prompts.render, emit, console, and standard JavaScript only. Workflows get async state.get(key) and state.set(key, JSONValue) through their automatic or explicit mission; mission:false workflows do not have a state global. Scripts cannot access filesystem, shell, arbitrary Pi tools, or host globals.
22
23
  • Sequential example: { workflowScript: "const a = await runs.run('analyze', {agent:'agent-a', task:'Analyze the request'}); return (await runs.run('plan', {agent:'agent-b', task:'Plan from: '+a.output})).output" }
23
24
  • Parallel example: { workflowScript: "const [a,b] = await runs.all([{key:'correctness',agent:'agent-a',task:'Review correctness'},{key:'tests',agent:'agent-b',task:'Review tests'}]); return {correctness:a.output,tests:b.output}" }
24
25
  • Optional context is "fresh" or "fork". timeoutMs/maxRuntimeMs apply to foreground and async workflows; foreground workflows default to 30 minutes and async workflows have no default timeout. Omit acceptance for reviewer/read-only calls; evidence levels end at verified, and acceptance.review.required requests independent writer review.
25
- • Durable mission attachment is automatic by default. Use missionId to attach an existing mission, mission:{...} to override auto-create, or mission:false for ephemeral work.
26
+ • Durable mission attachment is automatic by default. Use missionId to attach an existing mission, mission:{...} to override auto-create, or mission:false for ephemeral work. A mission object needs exactly one non-empty title or summary; objective and labels are optional. goal may only be true and requires budget:{tokens}.
26
27
 
27
28
  MANAGEMENT / CONTROL (use action; omit execution fields):
28
- • list, get, models, children.list, create, update, delete, eject, disable, enable, reset, doctor, grant-spawn-budget, worktree.discard, refine/refine.show/refine.rollback, mission.create/list/show/update/attach-run/close, inspector.open/status/close, project.open/status/close, and watchdog actions remain available.
29
+ • list, get, models, guide, children.list, create, update, delete, eject, disable, enable, reset, status, debug.run, doctor, grant-spawn-budget, worktree.discard, refine/refine.show/refine.rollback, mission.create/list/show/update/resolve-decision/attach-run/close, inspector.open/status/close, project.open/status/close, and watchdog actions remain available. Use {action:"guide", topic:"overview"} for packaged current-version help; topics are overview, workflows, agents, missions, observability, tool-reference, configuration, models, watchdog, and extension-api.
29
30
  • status, interrupt, stop, resume, and steer manage live or persisted runs. Use status view:"fleet" for an overview or view:"transcript" with id and optional index to tail output.
30
31
  • { action: "append-step", id: "...", step: {agent:"agent-c", task:"Use {previous}"} } appends one step to an already-running durable legacy chain. step is control-only, not an execution mode.
31
32
  • approve-checkpoint and reject-checkpoint decide a paused durable legacy chain checkpoint.
@@ -33,20 +34,22 @@ MANAGEMENT / CONTROL (use action; omit execution fields):
33
34
 
34
35
  ${SUBAGENT_SAFETY_GUIDANCE}`;
35
36
 
36
- export const COMPACT_SUBAGENT_TOOL_DESCRIPTION = `Run subagents only through { workflowScript }; omit action. Use action only for management/control actions.
37
+ export const COMPACT_SUBAGENT_TOOL_DESCRIPTION = `Run one child with { agent, task? }; use { workflowScript } for orchestration. Omit action for execution. Use action only for management/control actions.
37
38
 
38
39
  EXECUTE:
39
40
  • Call { action:"list" } first and use only executable/non-disabled agents.
40
- • SCRIPT {workflowScript:"return runs.run('main', {agent:'worker', task:'...'})"}. Use stable-key runs.run for one child and runs.all for parallel work. Use {action:"children.list"} for the last 10 retained children in this parent session, then runs.run(key,{resume:"run-id",task:"follow-up"}) to continue one with its stored contract. Workflows get async state.get/state.set through their automatic or explicit mission; mission:false does not. Scripts are ordinary JavaScript statement bodies; use explicit return for a useful result. Use JavaScript for sequence, branching, retries, and aggregation. For repository mutation lanes, use worktree:true on the workflow or runs.run/runs.all item for managed isolation. Scripts start async by default; async:false is the foreground escape hatch and auto-enables a same-repo live chat card unless chatProgress is off.
41
+ • SINGLE {agent:"worker",task:"..."} starts exactly one child through the workflow runtime. Workflow-level fields remain child defaults. Do not combine agent/task with action or workflowScript.
42
+ • SCRIPT {workflowScript:"return runs.run('main', {agent:'worker', task:'...'})"}. Use stable-key runs.run for one child and runs.all for parallel work. Use await prompts.render("package:name" | "user:name" | "project:name", vars?) for reusable task text and pass it explicitly to runs.run. Use {action:"children.list"} for the last 10 retained children in this parent session, then runs.run(key,{resume:"run-id",task:"follow-up"}) to continue one with its stored contract; workflow resumes wait for completion and loops continue from the latest returned runId. Workflows get async state.get/state.set through their automatic or explicit mission; mission:false does not. Scripts are ordinary JavaScript statement bodies; use explicit return for a useful result. For task text with Markdown fences or shell blocks, build quoted lines instead of nesting raw template literals: \`const task=["Run:","\`\`\`bash","npm test","\`\`\`"].join("\\n")\`. Use JavaScript for sequence, branching, retries, and aggregation. For repository mutation lanes, use worktree:true on the workflow or runs.run/runs.all item for managed isolation. Scripts start async by default; async:false is the foreground escape hatch and auto-enables a same-repo live chat card unless chatProgress is off.
41
43
  • Example: {workflowScript:"const [a,b]=await runs.all([{key:'a',agent:'agent-a',task:'Implement A',worktree:true},{key:'b',agent:'agent-b',task:'Implement B',worktree:true}]); return [a.output,b.output]"}
42
44
  • context can be fresh or fork. timeoutMs/maxRuntimeMs apply to foreground and async workflows; foreground workflows default to 30 minutes and async workflows have no default timeout. Omit acceptance for reviewer/read-only calls.
43
45
 
44
46
  MANAGE / CONTROL:
45
- • Use action without execution fields for list/get/models/authoring, refine/refine.show/refine.rollback, mission, watchdog, status, interrupt, stop, resume, steer, script-only scheduling, diagnostics, and other management actions.
47
+ • Use action without execution fields for list/get/models/guide/authoring, refine/refine.show/refine.rollback, mission, watchdog, status, interrupt, stop, resume, steer, script-only scheduling, diagnostics, and other management actions. guide reads shipped current-version docs by topic.
46
48
  • append-step uses step:{...} only for an already-running durable legacy chain; step is not an execution mode.
49
+ • A mission object needs exactly one non-empty title or summary; objective and labels are optional. goal may only be true and requires budget:{tokens}.
47
50
 
48
51
  ASYNC / SAFETY:
49
- • Omitted async detaches background work. Do not sleep or poll merely to wait; use subagent_wait only when this turn must receive results.
52
+ • Omitted async detaches background work. Continue independent work only until its next dependency barrier; consume the result before work that depends on it. Do not sleep or poll merely to wait; use subagent_wait only when this turn must receive results.
50
53
  • Ordinary children are not orchestrators. Keep one writer per cwd/worktree and use fresh read-only reviewers for independent checks.
51
54
  • Status and artifacts live under asyncId/asyncDir with status.json, events.jsonl, output logs, and {action:"status",id:"..."}.`;
52
55
 
@@ -152,13 +155,30 @@ function withMandatorySafetyGuidance(description: string): string {
152
155
  : SUBAGENT_SAFETY_GUIDANCE;
153
156
  }
154
157
 
155
- export function buildSubagentToolDescription(config: Pick<ExtensionConfig, "toolDescriptionMode"> = {}, options?: ToolDescriptionOptions): string {
158
+ const LEGACY_CHAIN_CONTROL_GUIDANCE_LINES = new Set([
159
+ '• { action: "append-step", id: "...", step: {agent:"agent-c", task:"Use {previous}"} } appends one step to an already-running durable legacy chain. step is control-only, not an execution mode.',
160
+ "• approve-checkpoint and reject-checkpoint decide a paused durable legacy chain checkpoint.",
161
+ "• append-step uses step:{...} only for an already-running durable legacy chain; step is not an execution mode.",
162
+ ]);
163
+
164
+ function withoutLegacyChainControlGuidance(description: string): string {
165
+ return description
166
+ .split("\n")
167
+ .filter((line) => !LEGACY_CHAIN_CONTROL_GUIDANCE_LINES.has(line.trim()))
168
+ .join("\n");
169
+ }
170
+
171
+ export function buildSubagentToolDescription(config: Pick<ExtensionConfig, "toolDescriptionMode" | "legacyChainControls"> = {}, options?: ToolDescriptionOptions): string {
156
172
  const mode = resolveToolDescriptionMode(config, options);
157
- if (mode === "compact") return COMPACT_SUBAGENT_TOOL_DESCRIPTION;
158
- if (mode === "custom") {
173
+ let description: string;
174
+ if (mode === "compact") description = COMPACT_SUBAGENT_TOOL_DESCRIPTION;
175
+ else if (mode === "custom") {
159
176
  const custom = loadCustomToolDescription(options);
160
- if (custom) return withMandatorySafetyGuidance(custom);
161
- warn(options, `${CUSTOM_TOOL_DESCRIPTION_FILE} was not found or valid for toolDescriptionMode "custom"; using full description.`);
162
- }
163
- return FULL_SUBAGENT_TOOL_DESCRIPTION;
177
+ if (custom) description = withMandatorySafetyGuidance(custom);
178
+ else {
179
+ warn(options, `${CUSTOM_TOOL_DESCRIPTION_FILE} was not found or valid for toolDescriptionMode "custom"; using full description.`);
180
+ description = FULL_SUBAGENT_TOOL_DESCRIPTION;
181
+ }
182
+ } else description = FULL_SUBAGENT_TOOL_DESCRIPTION;
183
+ return config.legacyChainControls === true ? description : withoutLegacyChainControlGuidance(description);
164
184
  }
@@ -10,6 +10,7 @@ import { writeAtomicJson } from "../../shared/atomic-json.ts";
10
10
  import { DIRS, type Details, type SubagentState } from "../../shared/types.ts";
11
11
  import { readStatus } from "../../shared/utils.ts";
12
12
  import { resolveSubagentRunId } from "../../runs/background/run-id-resolver.ts";
13
+ import { resolveNodeExecutable } from "../../shared/node-executable.ts";
13
14
  import { createHerdrClient, detectHerdr, type HerdrClient, type HerdrErrorCode, type HerdrResult } from "./client.ts";
14
15
 
15
16
  export const HERDR_INSPECTOR_ACTIONS = ["inspector.open", "inspector.status", "inspector.close"] as const;
@@ -45,6 +46,7 @@ interface InspectorDeps {
45
46
  client?: HerdrClient;
46
47
  missions?: MissionStoreConfig;
47
48
  authorityPolicy?: AuthorityPolicyConfig;
49
+ sessionRoots?: string[];
48
50
  cwd: string;
49
51
  signal?: AbortSignal;
50
52
  now?: () => Date;
@@ -89,8 +91,8 @@ function shellQuote(value: string): string {
89
91
  return `'${value.replaceAll("'", "'\\''")}'`;
90
92
  }
91
93
 
92
- function inspectorCommand(input: { runnerPath: string; asyncDir: string; runId: string; index?: number; missionPath?: string; allowSteer: boolean; allowStop: boolean }): string {
93
- const args = [process.execPath, input.runnerPath, "--async-dir", input.asyncDir, "--run-id", input.runId, "--allow-steer", String(input.allowSteer), "--allow-stop", String(input.allowStop)];
94
+ function inspectorCommand(input: { runnerPath: string; asyncDir: string; runId: string; index?: number; missionPath?: string; allowSteer: boolean; allowStop: boolean; sessionRoots: string[] }): string {
95
+ const args = [resolveNodeExecutable(), input.runnerPath, "--async-dir", input.asyncDir, "--run-id", input.runId, "--allow-steer", String(input.allowSteer), "--allow-stop", String(input.allowStop), "--session-roots", JSON.stringify(input.sessionRoots)];
94
96
  if (input.index !== undefined) args.push("--index", String(input.index));
95
97
  if (input.missionPath) args.push("--mission-path", input.missionPath);
96
98
  return `${process.platform === "win32" ? "& " : ""}${args.map(shellQuote).join(" ")}`;
@@ -114,6 +116,12 @@ function pathWithin(base: string, candidate: string): boolean {
114
116
  return resolvedCandidate === resolvedBase || resolvedCandidate.startsWith(`${resolvedBase}${path.sep}`);
115
117
  }
116
118
 
119
+ function herdrSessionRoots(target: { runId: string }, deps: InspectorDeps): string[] {
120
+ const roots = deps.sessionRoots ?? deps.state?.trustedSessionRoots ?? [];
121
+ const job = deps.state?.asyncJobs.get(target.runId) ?? deps.state?.fleetJobs?.get(target.runId);
122
+ return [...new Set([...roots, ...(job?.sessionRoot ? [job.sessionRoot] : [])])];
123
+ }
124
+
117
125
  function isTrustedAsyncDir(asyncDir: string, deps: InspectorDeps): boolean {
118
126
  try {
119
127
  if (fs.lstatSync(asyncDir).isSymbolicLink() || !fs.statSync(asyncDir).isDirectory()) return false;
@@ -204,6 +212,7 @@ export async function handleHerdrInspectorAction(action: HerdrInspectorAction, p
204
212
  missionPath: mission?.path,
205
213
  allowSteer: resolveAuthorityDecision({ action: "steerRun", policy: deps.authorityPolicy }) === "auto",
206
214
  allowStop: resolveAuthorityDecision({ action: "stopRun", policy: deps.authorityPolicy }) === "auto",
215
+ sessionRoots: herdrSessionRoots(target, deps),
207
216
  });
208
217
  const started = await client.run(["pane", "run", paneId, command], { timeoutMs: 15_000, signal: deps.signal });
209
218
  if (started.ok === false) {
@@ -17,6 +17,7 @@ export interface RunnerOptions {
17
17
  refreshMs: number;
18
18
  allowSteer?: boolean;
19
19
  allowStop?: boolean;
20
+ sessionRoots: string[];
20
21
  }
21
22
 
22
23
  function readMission(filePath: string | undefined): MissionRecord | undefined {
@@ -24,7 +25,7 @@ function readMission(filePath: string | undefined): MissionRecord | undefined {
24
25
  try { return parseMissionRecord(JSON.parse(fs.readFileSync(filePath, "utf-8")), filePath); } catch { return undefined; }
25
26
  }
26
27
 
27
- export function formatInspectorDashboard(input: { status: AsyncStatus; asyncDir: string; index?: number; mission?: MissionRecord; allowSteer?: boolean; allowStop?: boolean }): string {
28
+ export function formatInspectorDashboard(input: { status: AsyncStatus; asyncDir: string; index?: number; mission?: MissionRecord; allowSteer?: boolean; allowStop?: boolean; sessionRoots?: string[] }): string {
28
29
  const { status, asyncDir, mission } = input;
29
30
  const lines = [
30
31
  `pi-subagents inspector for ${status.runId}`,
@@ -37,7 +38,7 @@ export function formatInspectorDashboard(input: { status: AsyncStatus; asyncDir:
37
38
  if (open.length) lines.push(`Open decisions: ${open.map((decision) => `${decision.id}: ${decision.title}`).join(" | ")}`);
38
39
  lines.push("");
39
40
  }
40
- lines.push(formatAsyncRunTranscript(status, asyncDir, { index: input.index, lines: 60 }));
41
+ lines.push(formatAsyncRunTranscript(status, asyncDir, { index: input.index, lines: 60, sessionRoots: input.sessionRoots }));
41
42
  const controls = [input.allowSteer === false ? undefined : "steer <message>", input.allowStop === false ? undefined : "stop", "status"].filter(Boolean);
42
43
  lines.push("", `Controls: ${controls.join(" | ")}`, "Supervisor replies remain in the parent Pi session (subagent_supervisor/intercom).");
43
44
  return lines.join("\n");
@@ -57,6 +58,17 @@ function parseArgs(argv: string[]): RunnerOptions {
57
58
  const indexRaw = values.get("--index");
58
59
  const childIndex = indexRaw === undefined ? undefined : Number(indexRaw);
59
60
  if (childIndex !== undefined && (!Number.isInteger(childIndex) || childIndex < 0)) throw new Error("--index must be a non-negative integer.");
61
+ const sessionRootsRaw = values.get("--session-roots");
62
+ let sessionRoots: string[] = [];
63
+ if (sessionRootsRaw !== undefined) {
64
+ try {
65
+ const parsed = JSON.parse(sessionRootsRaw) as unknown;
66
+ if (!Array.isArray(parsed) || parsed.some((root) => typeof root !== "string")) throw new Error();
67
+ sessionRoots = parsed;
68
+ } catch {
69
+ throw new Error("--session-roots must be a JSON array of strings.");
70
+ }
71
+ }
60
72
  const refreshRaw = values.get("--refresh-ms");
61
73
  const refreshMs = refreshRaw === undefined ? 1_500 : Number(refreshRaw);
62
74
  if (!Number.isInteger(refreshMs) || refreshMs < 250) throw new Error("--refresh-ms must be an integer >= 250.");
@@ -65,6 +77,7 @@ function parseArgs(argv: string[]): RunnerOptions {
65
77
  runId,
66
78
  ...(childIndex !== undefined ? { index: childIndex } : {}),
67
79
  ...(values.get("--mission-path") ? { missionPath: path.resolve(values.get("--mission-path")!) } : {}),
80
+ sessionRoots,
68
81
  refreshMs,
69
82
  allowSteer: values.get("--allow-steer") !== "false",
70
83
  allowStop: values.get("--allow-stop") !== "false",
@@ -115,7 +128,7 @@ export function runInspector(argv = process.argv.slice(2)): void {
115
128
  process.stdout.write(`\x1b[2J\x1b[Hpi-subagents inspector\n\nLifecycle status for ${options.runId} is unavailable.\n`);
116
129
  return;
117
130
  }
118
- process.stdout.write(`\x1b[2J\x1b[H${formatInspectorDashboard({ status, asyncDir: options.asyncDir, index: options.index, mission: readMission(options.missionPath), allowSteer: options.allowSteer, allowStop: options.allowStop })}${notice ? `\n\n${notice}` : ""}\n> `);
131
+ process.stdout.write(`\x1b[2J\x1b[H${formatInspectorDashboard({ status, asyncDir: options.asyncDir, index: options.index, mission: readMission(options.missionPath), allowSteer: options.allowSteer, allowStop: options.allowStop, sessionRoots: options.sessionRoots })}${notice ? `\n\n${notice}` : ""}\n> `);
119
132
  if (isTerminal(status) && timer) {
120
133
  clearInterval(timer);
121
134
  timer = undefined;