pi-subagents 0.56.0 → 0.58.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 +92 -0
  2. package/agents/claude-code-writer.md +15 -0
  3. package/agents/claude-code.md +15 -0
  4. package/agents/codex-exec-writer.md +15 -0
  5. package/agents/codex-exec.md +15 -0
  6. package/agents/cursor-agent-writer.md +14 -0
  7. package/agents/cursor-agent.md +14 -0
  8. package/docs/agents.md +124 -21
  9. package/docs/configuration.md +37 -0
  10. package/docs/extension-api.md +41 -2
  11. package/docs/models.md +3 -3
  12. package/docs/observability.md +8 -7
  13. package/docs/tool-reference.md +14 -3
  14. package/docs/workflows.md +44 -0
  15. package/package.json +1 -1
  16. package/skills/pi-subagents/SKILL.md +2 -0
  17. package/skills/pi-subagents/references/execution-controls.md +2 -2
  18. package/skills/pi-subagents/references/management-authoring-rpc.md +1 -0
  19. package/skills/pi-subagents/references/prompting-and-roles.md +2 -2
  20. package/src/agents/agent-management.ts +36 -5
  21. package/src/agents/agent-refinements.ts +4 -4
  22. package/src/agents/agent-serializer.ts +5 -0
  23. package/src/agents/agents.ts +257 -51
  24. package/src/agents/builtin-names.ts +6 -0
  25. package/src/agents/runtime-agent-events.ts +70 -0
  26. package/src/agents/runtime-agent-registry.ts +18 -4
  27. package/src/api/agents.ts +10 -5
  28. package/src/api/preflight.ts +28 -3
  29. package/src/extension/config.ts +70 -0
  30. package/src/extension/doctor.ts +3 -3
  31. package/src/extension/index.ts +33 -8
  32. package/src/extension/public-execution.ts +29 -13
  33. package/src/extension/rpc.ts +55 -19
  34. package/src/extension/schemas.ts +6 -5
  35. package/src/extension/tool-description.ts +18 -12
  36. package/src/inspectors/herdr/actions.ts +2 -1
  37. package/src/inspectors/herdr/inspector-runner.ts +2 -10
  38. package/src/inspectors/herdr/session-roots-codec.ts +42 -0
  39. package/src/integrations/herdr-status.ts +51 -3
  40. package/src/runs/background/active-async-capacity.ts +77 -10
  41. package/src/runs/background/async-execution.ts +127 -19
  42. package/src/runs/background/async-job-tracker.ts +5 -0
  43. package/src/runs/background/async-resume.ts +6 -2
  44. package/src/runs/background/async-retention.ts +20 -3
  45. package/src/runs/background/async-status.ts +7 -0
  46. package/src/runs/background/chain-append.ts +2 -0
  47. package/src/runs/background/chain-root-attachment.ts +15 -1
  48. package/src/runs/background/fleet-view.ts +16 -10
  49. package/src/runs/background/inspect-rpc.ts +8 -8
  50. package/src/runs/background/notify.ts +26 -3
  51. package/src/runs/background/result-delivery-ownership.ts +45 -0
  52. package/src/runs/background/result-files.ts +27 -14
  53. package/src/runs/background/result-watcher.ts +36 -15
  54. package/src/runs/background/run-status.ts +33 -6
  55. package/src/runs/background/scheduled-runs.ts +7 -1
  56. package/src/runs/background/subagent-runner.ts +239 -56
  57. package/src/runs/background/wait-completions.ts +4 -0
  58. package/src/runs/foreground/execution.ts +92 -11
  59. package/src/runs/foreground/foreground-control.ts +6 -0
  60. package/src/runs/foreground/foreground-history.ts +22 -1
  61. package/src/runs/foreground/subagent-executor.ts +322 -102
  62. package/src/runs/foreground/workflow-detach-reconcile.ts +144 -18
  63. package/src/runs/shared/child-protocol.ts +21 -7
  64. package/src/runs/shared/claude-code-adapter.ts +129 -0
  65. package/src/runs/shared/codex-exec-adapter.ts +129 -0
  66. package/src/runs/shared/completion-guard.ts +4 -3
  67. package/src/runs/shared/cursor-agent-adapter.ts +114 -0
  68. package/src/runs/shared/dynamic-fanout.ts +3 -3
  69. package/src/runs/shared/external-cli-contract.ts +167 -0
  70. package/src/runs/shared/external-cli-preflight.ts +122 -0
  71. package/src/runs/shared/external-cli-runner.ts +348 -55
  72. package/src/runs/shared/fast-mode-extension.ts +5 -5
  73. package/src/runs/shared/launch-cwd.ts +16 -0
  74. package/src/runs/shared/long-running-guard.ts +2 -1
  75. package/src/runs/shared/mcp-config-sources.ts +386 -0
  76. package/src/runs/shared/mcp-direct-tool-allowlist.ts +155 -42
  77. package/src/runs/shared/model-exclusions.ts +69 -7
  78. package/src/runs/shared/model-fallback.ts +39 -5
  79. package/src/runs/shared/mutation-evidence.ts +7 -2
  80. package/src/runs/shared/nested-events.ts +3 -1
  81. package/src/runs/shared/nested-render.ts +2 -2
  82. package/src/runs/shared/parallel-utils.ts +8 -1
  83. package/src/runs/shared/pi-args.ts +61 -6
  84. package/src/runs/shared/process-signal.ts +13 -0
  85. package/src/runs/shared/run-history.ts +21 -1
  86. package/src/runs/shared/single-output.ts +17 -0
  87. package/src/runs/shared/subagent-prompt-runtime.ts +85 -9
  88. package/src/shared/fork-context.ts +21 -0
  89. package/src/shared/formatters.ts +13 -1
  90. package/src/shared/launch-contract.ts +4 -0
  91. package/src/shared/pruned-fork.ts +450 -0
  92. package/src/shared/session-file-trust.ts +19 -0
  93. package/src/shared/session-tokens.ts +14 -3
  94. package/src/shared/settings.ts +10 -2
  95. package/src/shared/shortcuts.ts +17 -0
  96. package/src/shared/types.ts +160 -10
  97. package/src/shared/utils.ts +6 -29
  98. package/src/shared/workflow-child-permit.ts +116 -0
  99. package/src/slash/delegation-adapters.ts +0 -1
  100. package/src/slash/slash-commands.ts +8 -6
  101. package/src/slash/subagents-admin.ts +3 -0
  102. package/src/tui/fleet-status.ts +27 -10
  103. package/src/tui/fleet-transcript.ts +11 -5
  104. package/src/tui/fleet.ts +28 -13
  105. package/src/tui/render.ts +55 -21
  106. package/src/workflows/scripted-workflow.ts +299 -31
  107. package/src/workflows/workflow-child-summary.ts +117 -0
  108. package/src/workflows/workflow-receipt.ts +155 -5
@@ -11,6 +11,7 @@ export interface PublicSubagentExecutionParams {
11
11
  chainName?: unknown;
12
12
  config?: unknown;
13
13
  workflowScript?: unknown;
14
+ workflowScriptPath?: unknown;
14
15
  isolation?: unknown;
15
16
  worktree?: unknown;
16
17
  async?: unknown;
@@ -38,22 +39,28 @@ export type PublicSubagentExecutionNormalization<T> =
38
39
  * Internal runs.run children and structured owned delegation bypass this boundary.
39
40
  */
40
41
  export function normalizePublicSubagentExecution<T extends PublicSubagentExecutionParams>(params: T, options: { asyncByDefault?: boolean } = {}): PublicSubagentExecutionNormalization<T> {
42
+ if (params.workflowScript !== undefined && params.workflowScriptPath !== undefined) {
43
+ return { ok: false, error: "workflowScript and workflowScriptPath are mutually exclusive.", mode: "workflow" };
44
+ }
45
+ const hasWorkflowInput = params.workflowScript !== undefined || params.workflowScriptPath !== undefined;
46
+ const hasValidWorkflowInput = (typeof params.workflowScript === "string" && Boolean(params.workflowScript.trim()))
47
+ || (typeof params.workflowScriptPath === "string" && Boolean(params.workflowScriptPath.trim()));
41
48
  if (params.isolation !== undefined) {
42
49
  if (params.isolation !== "none" && params.isolation !== "worktree") {
43
- return { ok: false, error: "isolation must be 'none' or 'worktree'.", mode: params.workflowScript !== undefined ? "workflow" : "management" };
50
+ return { ok: false, error: "isolation must be 'none' or 'worktree'.", mode: hasWorkflowInput ? "workflow" : "management" };
44
51
  }
45
52
  const isolationWorktree = params.isolation === "worktree";
46
53
  if (params.worktree !== undefined && params.worktree !== isolationWorktree) {
47
- return { ok: false, error: `isolation '${params.isolation}' conflicts with worktree: ${String(params.worktree)}.`, mode: params.workflowScript !== undefined ? "workflow" : "management" };
54
+ return { ok: false, error: `isolation '${params.isolation}' conflicts with worktree: ${String(params.worktree)}.`, mode: hasWorkflowInput ? "workflow" : "management" };
48
55
  }
49
56
  const { isolation: _isolation, ...normalizedParams } = params;
50
57
  params = { ...normalizedParams, worktree: isolationWorktree } as T;
51
58
  }
52
59
  if (params.runFanoutBudget !== undefined || params.runFanoutAdmitted !== undefined) {
53
- return { ok: false, error: "Public execution does not accept internal run fan-out fields.", mode: params.workflowScript !== undefined ? "workflow" : "management" };
60
+ return { ok: false, error: "Public execution does not accept internal run fan-out fields.", mode: hasWorkflowInput ? "workflow" : "management" };
54
61
  }
55
62
  if (params.workflowParentRunId !== undefined || params.workflowKey !== undefined || params.workflowChildAsyncId !== undefined || params.workflowAwaitAsync !== undefined || params.workflowParentDeadlineAt !== undefined || params.suppressRoutineResultIntercom !== undefined) {
56
- return { ok: false, error: "Public execution does not accept internal workflow child fields.", mode: params.workflowScript !== undefined ? "workflow" : "management" };
63
+ return { ok: false, error: "Public execution does not accept internal workflow child fields.", mode: hasWorkflowInput ? "workflow" : "management" };
57
64
  }
58
65
  const action = params.action;
59
66
  if (action !== undefined && (typeof action !== "string" || !action.trim())) {
@@ -90,17 +97,26 @@ export function normalizePublicSubagentExecution<T extends PublicSubagentExecuti
90
97
  if (legacyAction === "parallel" || legacyAction === "tasks" || legacyAction === "chain") {
91
98
  return { ok: false, error: "Legacy top-level chain and parallel inputs were removed; use workflowScript.", mode: "workflow" };
92
99
  }
100
+ if (normalizedAction === "validate") {
101
+ if (params.agent !== undefined || params.task !== undefined || params.step !== undefined) {
102
+ return { ok: false, error: "validate requires workflowScript or workflowScriptPath and does not accept direct agent, task, or step execution fields.", mode: "management" };
103
+ }
104
+ if (!hasValidWorkflowInput) {
105
+ return { ok: false, error: "validate requires a non-empty workflowScript or workflowScriptPath.", mode: "management" };
106
+ }
107
+ return { ok: true, params: { ...params, action: normalizedAction } };
108
+ }
93
109
  if (normalizedAction === "schedule.create") {
94
110
  if (params.agent !== undefined || params.task !== undefined || params.step !== undefined) {
95
- return { ok: false, error: "schedule.create requires workflowScript and does not accept direct agent, task, or step execution fields.", mode: "management" };
111
+ return { ok: false, error: "schedule.create requires workflowScript or workflowScriptPath and does not accept direct agent, task, or step execution fields.", mode: "management" };
96
112
  }
97
- if (typeof params.workflowScript !== "string" || !params.workflowScript.trim()) {
98
- return { ok: false, error: "schedule.create requires a non-empty workflowScript.", mode: "management" };
113
+ if (!hasValidWorkflowInput) {
114
+ return { ok: false, error: "schedule.create requires a non-empty workflowScript or workflowScriptPath.", mode: "management" };
99
115
  }
100
116
  return { ok: true, params: { ...params, action: normalizedAction } };
101
117
  }
102
- if (params.workflowScript !== undefined) {
103
- return { ok: false, error: "workflowScript execution must omit action; only schedule.create accepts action with workflowScript.", mode: "management" };
118
+ if (hasWorkflowInput) {
119
+ return { ok: false, error: "Workflow execution must omit action; only validate and schedule.create accept action with workflowScript or workflowScriptPath.", mode: "management" };
104
120
  }
105
121
  if (params.task !== undefined) {
106
122
  return { ok: false, error: "Structured single-child task cannot be combined with a management/control action.", mode: "management" };
@@ -110,8 +126,8 @@ export function normalizePublicSubagentExecution<T extends PublicSubagentExecuti
110
126
  if (params.step !== undefined) {
111
127
  return { ok: false, error: "step is not a public execution field; use workflowScript for orchestration.", mode: "workflow" };
112
128
  }
113
- if (params.workflowScript !== undefined && (params.agent !== undefined || params.task !== undefined)) {
114
- return { ok: false, error: "Structured single-child execution cannot be combined with workflowScript.", mode: "workflow" };
129
+ if (hasWorkflowInput && (params.agent !== undefined || params.task !== undefined)) {
130
+ return { ok: false, error: "Structured single-child execution cannot be combined with workflowScript or workflowScriptPath.", mode: "workflow" };
115
131
  }
116
132
  if (params.agent !== undefined || params.task !== undefined) {
117
133
  if (typeof params.agent !== "string" || !params.agent.trim()) {
@@ -129,8 +145,8 @@ export function normalizePublicSubagentExecution<T extends PublicSubagentExecuti
129
145
  } as T,
130
146
  };
131
147
  }
132
- if (typeof params.workflowScript !== "string" || !params.workflowScript.trim()) {
133
- return { ok: false, error: "Execution requires either { agent, task? } for one child or a non-empty workflowScript for orchestration.", mode: "workflow" };
148
+ if (!hasValidWorkflowInput) {
149
+ return { ok: false, error: "Execution requires either { agent, task? } for one child or a non-empty workflowScript or workflowScriptPath for orchestration.", mode: "workflow" };
134
150
  }
135
151
  return { ok: true, params };
136
152
  }
@@ -11,6 +11,7 @@ import {
11
11
  type AsyncJobStep,
12
12
  type Details,
13
13
  type SubagentState,
14
+ type TokenUsage,
14
15
  DIRS,
15
16
  SUBAGENT_ASYNC_COMPLETE_EVENT,
16
17
  SUBAGENT_CHILD_STATUS_EVENT,
@@ -97,7 +98,7 @@ export interface SubagentRpcFleetEntry {
97
98
  model?: string;
98
99
  effort?: string;
99
100
  startedAt: number;
100
- tokens: { input: number; output: number; total: number };
101
+ tokens: TokenUsage;
101
102
  goal?: string;
102
103
  }
103
104
 
@@ -122,7 +123,7 @@ function displayText(value: unknown, maxLength: number): string | undefined {
122
123
  return normalized ? truncateDisplayText(normalized, maxLength) : undefined;
123
124
  }
124
125
 
125
- function publicTokens(value: unknown): { input: number; output: number; total: number } {
126
+ function publicTokens(value: unknown): TokenUsage {
126
127
  const record = isRecord(value) ? value : {};
127
128
  const count = (field: "input" | "output" | "total") => {
128
129
  const raw = record[field];
@@ -133,7 +134,21 @@ function publicTokens(value: unknown): { input: number; output: number; total: n
133
134
  const input = count("input");
134
135
  const output = count("output");
135
136
  const sum = Math.min(Number.MAX_SAFE_INTEGER, input + output);
136
- return { input, output, total: Math.max(sum, count("total")) };
137
+ const optionalCount = (field: "window" | "windowPeak") => {
138
+ const raw = record[field];
139
+ return typeof raw === "number" && Number.isFinite(raw) && raw >= 0
140
+ ? Math.min(Number.MAX_SAFE_INTEGER, Math.floor(raw))
141
+ : undefined;
142
+ };
143
+ const window = optionalCount("window");
144
+ const windowPeak = optionalCount("windowPeak");
145
+ return {
146
+ input,
147
+ output,
148
+ total: Math.max(sum, count("total")),
149
+ ...(window !== undefined ? { window } : {}),
150
+ ...(windowPeak !== undefined ? { windowPeak } : {}),
151
+ };
137
152
  }
138
153
 
139
154
  function activeState(value: unknown): boolean {
@@ -188,7 +203,7 @@ function buildFleetStatus(
188
203
  model: child.model,
189
204
  effort: child.thinking,
190
205
  startedAt: child.startedAt,
191
- tokens: { input: child.inputTokens ?? 0, output: child.outputTokens ?? 0, total: child.tokens ?? 0 },
206
+ tokens: { input: child.inputTokens ?? 0, output: child.outputTokens ?? 0, total: child.tokens ?? 0, ...(child.window !== undefined ? { window: child.window } : {}), ...(child.windowPeak !== undefined ? { windowPeak: child.windowPeak } : {}) },
192
207
  });
193
208
  } else {
194
209
  addCandidate({
@@ -197,7 +212,7 @@ function buildFleetStatus(
197
212
  model: control.model,
198
213
  effort: control.thinking,
199
214
  startedAt: control.startedAt,
200
- tokens: { input: control.inputTokens ?? 0, output: control.outputTokens ?? 0, total: control.tokens ?? 0 },
215
+ tokens: { input: control.inputTokens ?? 0, output: control.outputTokens ?? 0, total: control.tokens ?? 0, ...(control.window !== undefined ? { window: control.window } : {}), ...(control.windowPeak !== undefined ? { windowPeak: control.windowPeak } : {}) },
201
216
  });
202
217
  }
203
218
  }
@@ -542,7 +557,7 @@ function stopAsyncRun(
542
557
  childId: stoppedChild.id,
543
558
  status: "stopping",
544
559
  ts,
545
- reason: "user",
560
+ reason: "rpc",
546
561
  source: "rpc",
547
562
  asyncDir,
548
563
  stepIndex: stoppedChild.index,
@@ -564,20 +579,21 @@ function stopAsyncRun(
564
579
  if (initialStatus.mode === "workflow" && initialStatus.state === "running") {
565
580
  if (child) {
566
581
  const stopChild = options.state?.workflowChildStops?.get(initialRunId);
567
- if (!stopChild) throw new SubagentRpcError("invalid_state", `Workflow ${initialRunId} is not controlled by this extension runtime; child stop is unavailable.`);
568
- if (!stopChild(child.id, `Workflow child '${child.id}' stopped by RPC.`)) throw new SubagentRpcError("invalid_state", `Child '${childId}' in workflow ${initialRunId} is not available to stop.`);
569
- emitChildStopping(initialRunId, location.asyncDir, child);
570
- return {
571
- runId: initialRunId,
572
- asyncDir: location.asyncDir,
573
- previousState: initialStatus.state,
574
- state: "stopping",
575
- childId: child.id,
576
- message: `Stop requested for child ${child.id} in async run ${initialRunId}.`,
577
- };
582
+ if (stopChild) {
583
+ if (!stopChild(child.id, `Workflow child '${child.id}' stopped by RPC.`)) throw new SubagentRpcError("invalid_state", `Child '${childId}' in workflow ${initialRunId} is not available to stop.`);
584
+ emitChildStopping(initialRunId, location.asyncDir, child);
585
+ return {
586
+ runId: initialRunId,
587
+ asyncDir: location.asyncDir,
588
+ previousState: initialStatus.state,
589
+ state: "stopping",
590
+ childId: child.id,
591
+ message: `Stop requested for child ${child.id} in async run ${initialRunId}.`,
592
+ };
593
+ }
578
594
  }
579
595
  const workflowController = options.state?.workflowControllers?.get(initialRunId);
580
- if (workflowController) {
596
+ if (workflowController && !child) {
581
597
  workflowController.abort(new Error("Workflow stopped by RPC."));
582
598
  return {
583
599
  runId: initialRunId,
@@ -587,7 +603,27 @@ function stopAsyncRun(
587
603
  message: `Stop requested for async run ${initialRunId}.`,
588
604
  };
589
605
  }
590
- throw new SubagentRpcError("invalid_state", `Workflow ${initialRunId} is not controlled by this extension runtime; reload recovery cannot stop it safely.`);
606
+ try {
607
+ deliverStopRequest({
608
+ asyncDir: location.asyncDir,
609
+ pid: initialStatus.pid,
610
+ kill: options.kill,
611
+ now: options.now,
612
+ source: "rpc-stop",
613
+ ...(child ? { targetIndex: child.index, childId: child.id } : {}),
614
+ });
615
+ } catch (error) {
616
+ throw new SubagentRpcError("execution_failed", error instanceof Error ? error.message : String(error));
617
+ }
618
+ if (child) emitChildStopping(initialRunId, location.asyncDir, child);
619
+ return {
620
+ runId: initialRunId,
621
+ asyncDir: location.asyncDir,
622
+ previousState: initialStatus.state,
623
+ state: "stopping",
624
+ ...(child ? { childId: child.id } : {}),
625
+ message: child ? `Stop requested for child ${child.id} in async run ${initialRunId}.` : `Stop requested for async run ${initialRunId}.`,
626
+ };
591
627
  }
592
628
 
593
629
  let status;
@@ -257,11 +257,11 @@ const ControlOverrides = Type.Object({
257
257
 
258
258
  const SubagentParamProperties = {
259
259
  agent: Type.Optional(Type.String({ description: "Agent for one-child execution, or target for agent management actions." })),
260
- task: Type.Optional(Type.String({ description: "Optional one-child task. Requires agent; cannot combine with action or workflowScript." })),
260
+ task: Type.Optional(Type.String({ description: "Optional one-child task. Requires agent; cannot combine with action, workflowScript, or workflowScriptPath." })),
261
261
  extensionBindings: Type.Optional(Type.Unsafe({ type: "object", maxProperties: 16, additionalProperties: true, description: "Namespaced, bounded plain-JSON metadata delivered only to the child runtime. Namespace keys use package.name/1 syntax." })),
262
262
  // Management action (when present, tool operates in management mode)
263
263
  action: Type.Optional(Type.String({ minLength: 1,
264
- description: "Optional management/control action. Omit this field for structured single-child or workflowScript execution; use it only for management/control actions."
264
+ description: "Optional management/control action. Use action='validate' with workflowScript or workflowScriptPath for offline checks. Omit this field for structured single-child or workflow execution; otherwise, use it only for management/control actions."
265
265
  })),
266
266
  name: Type.Optional(Type.String({ description: "Human-readable name for action='schedule.create'." })),
267
267
  id: Type.Optional(Type.String({
@@ -289,7 +289,7 @@ const SubagentParamProperties = {
289
289
  scope: Type.Optional(Type.String({ enum: ["session", "user", "project"], description: "Scope for action='watchdog.configure'. Defaults to session to avoid persistent settings writes unless user/project is explicit." })),
290
290
  target: Type.Optional(Type.String({ enum: ["main", "children", "child"], description: "Target for watchdog actions." })),
291
291
  focus: Type.Optional(Type.Boolean({ description: "Focus the new Herdr pane for inspector.open or project.open." })),
292
- thinking: Type.Optional(Type.Unsafe({ anyOf: [{ type: "string" }, { type: "boolean", enum: [false] }], description: "Thinking level for action='watchdog.configure' (off/minimal/low/medium/high/xhigh/max, inherit, or false for off)." })),
292
+ thinking: Type.Optional(Type.Unsafe({ anyOf: [{ type: "string" }, { type: "boolean", enum: [false] }], description: "Thinking level for action='watchdog.configure' only (off/minimal/low/medium/high/xhigh/max, inherit, or false for off). Ignored on dispatch; set per-run child thinking with a suffix on the model string, e.g. model: 'provider/id:high'." })),
293
293
  at: Type.Optional(Type.String({ description: "One-shot trigger for action='schedule.create': a relative delay such as '+10m' or an ISO timestamp with timezone." })),
294
294
  every: Type.Optional(Type.String({ description: "Fixed recurring interval for action='schedule.create', such as '30m', '6h', '2d', or '2w'." })),
295
295
  on: Type.Optional(Type.Unsafe({ anyOf: [{ type: "string" }, { type: "integer" }], description: "Calendar selector reserved for a later schedule slice." })),
@@ -313,12 +313,13 @@ const SubagentParamProperties = {
313
313
  description: "Agent config for create/update. Object or JSON string."
314
314
  })),
315
315
  workflowScript: Type.Optional(Type.String({ minLength: 1, description: "Trusted inline JavaScript statement body. Normally async unless asyncByDefault:false; set async:true when async matters. Use async:false only when the parent must block until completion, never for reviews or gates. Use explicit return for output. Use top-level await, plain helper functions, or explicit Promise chains; nested async function, arrow, and method helpers are rejected. Use await runs.run(key, {agent, task, worktree?, gate?}) or runs.run(key, {resume, task}), where resume is a retained run id or {workflowRunId,key,latest:true} from a durable async workflow receipt. Use runs.all([...]), await runs.steer(key, message, {mode?, index?, ackTimeoutMs?}), runs.status(id), runs.ref(s), emit(value), console, and return. For ordinary parallel fanout, use await runs.all([{key, agent, task}, ...]); it resolves to an ordered array, not a key map, so use results[0], destructuring, or results.map(...), not results.<key>. Do not read .output from unawaited runs.run launches. Stored runs.run promises are only for advanced rolling fanout, and each must later be observed with direct await, Promise.race, or Promise.all. runs.steer targets a prior stable child key, never a raw run id, and must be awaited or returned. 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." })),
316
+ workflowScriptPath: Type.Optional(Type.String({ minLength: 1, description: "Path to a trusted JavaScript workflow file. Mutually exclusive with workflowScript. Relative paths resolve against the request cwd. The host reads the file before the filesystem-free workflow sandbox starts." })),
316
317
  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. Explicit live-card requires same-repository async:false; async workflows should omit chatProgress or use auto/off." })),
317
318
  isolation: Type.Optional(Type.String({ enum: ["none", "worktree"], description: "Workflow child isolation. none runs in the shared cwd; worktree requires managed git worktree isolation." })),
318
319
  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." })),
319
320
  context: Type.Optional(Type.String({
320
321
  enum: ["fresh", "fork", "profile"],
321
- description: "'fresh' or 'fork' to branch from parent session, or 'profile' to require the selected agent's declared defaultContext. Explicit fresh/fork overrides every child; profile ignores config defaultSubagentContext and fails when an agent has no defaultContext. If omitted, config defaultSubagentContext wins over each agent defaultContext; implicit fork needs a persisted parent session and leaf, else fresh.",
322
+ description: "'fresh' or 'fork' to branch from parent session, or 'profile' to require the selected agent's declared defaultContext. Explicit fresh/fork overrides every child; profile ignores config defaultSubagentContext and fails when an agent has no defaultContext. If omitted, config defaultSubagentContext wins over each agent defaultContext; implicit fork needs a persisted parent session and leaf, else fresh. Config forkContext may prune resolved forks before spawn without adding another context value.",
322
323
  })),
323
324
  async: Type.Optional(Type.Boolean({ description: "Run in background unless asyncByDefault:false. Set false only when the parent must block until completion." })),
324
325
  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." })),
@@ -346,7 +347,7 @@ const SubagentParamProperties = {
346
347
  })),
347
348
  outputMode: Type.Optional(OutputModeOverride),
348
349
  skill: Type.Optional(SkillOverride),
349
- model: Type.Optional(Type.String({ description: "Default child model override. Full provider/id values are accepted; bare ids resolve from the active registry." })),
350
+ model: Type.Optional(Type.String({ description: "Default child model override. Full provider/id values are accepted; bare ids resolve from the active registry. Append a thinking suffix (off/minimal/low/medium/high/xhigh/max, e.g. 'provider/id:low') to set the child's thinking level for the run; the suffix wins over the agent's thinking default." })),
350
351
  fast: Type.Optional(Type.Boolean({ description: "Opt into priority service tier for supported native OpenAI-Codex child models. Default false. This can increase quota or cost." })),
351
352
  outputSchema: Type.Optional(JsonSchemaObject),
352
353
  agentContract: Type.Optional(AgentContractOverride),
@@ -5,8 +5,9 @@ import { getAgentDir, getProjectConfigDir } from "../shared/utils.ts";
5
5
 
6
6
  const CUSTOM_TOOL_DESCRIPTION_FILE = "subagent-tool-description.md";
7
7
  const CUSTOM_TOOL_DESCRIPTION_MAX_BYTES = 50 * 1024;
8
+ const EXTERNAL_CLI_RUNNER_GUIDANCE = "External CLI agents (codex-exec, codex-exec-writer, claude-code, claude-code-writer, cursor-agent, cursor-agent-writer) use their own runner contract and do not support native Pi child options such as model override, structured output, acceptance/agent contract, tool budget, fast mode, fork context, skills, or native Pi tools unless the runner explicitly implements them.";
8
9
 
9
- export const DEFAULT_SUBAGENT_TOOL_DESCRIPTION = `Delegate to configured subagents. For execution, omit action and use {agent, task?} for one child or workflowScript for orchestration. For multi-step or parallel work, make exactly one top-level subagent call with workflowScript and async:true; launch children only inside that script and do not make another top-level call for them. Use runs.run('key',{agent,task}) for one child, await runs.all([{key:'a',agent:'reviewer',task:'...'},{key:'b',agent:'reviewer',task:'...'}]) for ordinary parallel children, and read its ordered array result with indexes, destructuring, or .map(...), not by key property. Use action only for management/control. Use guide or the pi-subagents skill for advanced workflow details.`;
10
+ export const DEFAULT_SUBAGENT_TOOL_DESCRIPTION = `Delegate to configured subagents. For execution, omit action and use {agent, task?} for one child, workflowScript for inline orchestration, or workflowScriptPath to load a script from the request cwd. The script inputs are mutually exclusive. Use action:'validate' with either script input to check it without launching children. For multi-step or parallel work, make exactly one top-level subagent call with async:true; launch children only inside that workflow and do not make another top-level call for them. Use runs.run('key',{agent,task}) for one child, await runs.all([{key:'a',agent:'reviewer',task:'...'},{key:'b',agent:'reviewer',task:'...'}]) for ordinary parallel children, and read its ordered array result with indexes, destructuring, or .map(...), not by key property. ${EXTERNAL_CLI_RUNNER_GUIDANCE} Use action only for management/control. Use guide or the pi-subagents skill for advanced workflow details.`;
10
11
 
11
12
  export const SUBAGENT_TOOL_PROMPT_SNIPPET = "Delegate to subagents; orchestrate in one workflowScript call.";
12
13
 
@@ -16,7 +17,8 @@ export const SUBAGENT_TOOL_PROMPT_GUIDELINES = [
16
17
  "workflowScript means exactly one top-level subagent tool call with async:true. Inside it, use runs.run/runs.all to launch children; do not make another top-level subagent call for those children.",
17
18
  "For ordinary parallel work, use await runs.all([{key,agent,task}, ...]); it resolves to an ordered array, not a key map, so use results[0], destructuring, or results.map(...), not results.<key>. Do not read .output from unawaited runs.run launches. Stored runs.run promises are only for advanced rolling fanout and each must later be observed with direct await, Promise.race, or Promise.all.",
18
19
  "Keep one writer per cwd/worktree unless writers run in isolated worktrees.",
19
- "To pass an explicit model to a child, first call { action: \"models\" } and copy an exact provider/id (e.g. openai-codex/gpt-5.6-sol); bare ids resolve only when unique in the registry, and agent names (gpt-pro, advisor) are not model ids.",
20
+ "To pass an explicit model to a child, first call { action: \"models\" } and copy an exact provider/id (e.g. openai-codex/gpt-5.6-sol); bare ids resolve only when unique in the registry, and agent names (gpt-pro, advisor) are not model ids. Set per-run thinking with a suffix on the model string (e.g. openai-codex/gpt-5.6-sol:high; off/minimal/low/medium/high/xhigh/max); the suffix wins over the agent's thinking default. The thinking field only applies to action='watchdog.configure' and is ignored on dispatch.",
21
+ EXTERNAL_CLI_RUNNER_GUIDANCE,
20
22
  "Use guide or the pi-subagents skill for advanced scheduling, missions, steering, and retention.",
21
23
  ];
22
24
 
@@ -29,34 +31,38 @@ export const SUBAGENT_SAFETY_GUIDANCE = `SAFETY-CRITICAL SUBAGENT GUIDANCE:
29
31
  • 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.
30
32
  • 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.`;
31
33
 
32
- 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.
34
+ export const FULL_SUBAGENT_TOOL_DESCRIPTION = `Run one child with { agent, task? }; use { workflowScript } for inline orchestration or { workflowScriptPath } to load it from the request cwd. The script inputs are mutually exclusive. Omit action for execution. Use action only for management/control actions.
33
35
 
34
36
  EXECUTION:
37
+ • ${EXTERNAL_CLI_RUNNER_GUIDANCE}
35
38
  • Before executing, use { action: "list" } and run only executable/non-disabled configured agents.
36
- • When passing an explicit model to a child (on the call or a runs.run/runs.all item), first call { action: "models" } and copy an exact provider/id; bare ids resolve only when unique in the registry, and agent names (e.g. gpt-pro, advisor) are not model ids.
37
- • SINGLE CHILD: { agent:"worker", task:"..." }. This structured form starts exactly one direct child. Fields such as model, context, cwd, worktree, output, budgets, acceptance, and async apply to that child. Do not combine agent/task with action or workflowScript.
39
+ • When passing an explicit model to a child (on the call or a runs.run/runs.all item), first call { action: "models" } and copy an exact provider/id; bare ids resolve only when unique in the registry, and agent names (e.g. gpt-pro, advisor) are not model ids. Set per-run thinking with a suffix on the model string (e.g. provider/id:high; off/minimal/low/medium/high/xhigh/max); the suffix wins over the agent's thinking default. The thinking field only applies to action='watchdog.configure' and is ignored on dispatch.
40
+ • SINGLE CHILD: { agent:"worker", task:"..." }. This structured form starts exactly one direct child. Fields such as model, context, cwd, worktree, output, budgets, acceptance, and async apply to that child. Do not combine agent/task with action, workflowScript, or workflowScriptPath.
38
41
  • WORKFLOW SCRIPT: { workflowScript: "return runs.run('main', {agent:'worker', task:'...'})" }. Use stable-key runs.run for one child and await runs.all([{key,agent,task}, ...]) for ordinary parallel children. runs.all resolves to an ordered array, not a key map, so use results[0], array destructuring, or results.map((result) => result.output), not results.<key>. Do not read .output from unawaited runs.run launches. Stored runs.run promises are only for advanced rolling fanout and each must later be observed with direct await, Promise.race, or Promise.all. 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. Use top-level await, plain helper functions, or explicit Promise chains; nested async function, arrow, and method helpers are rejected. 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 normally start async unless config sets asyncByDefault:false; set async:true explicitly when async behavior matters. Pass async:false only when the parent must block until completion, never for final reviews or gates. Same-repo blocking workflows default to a live in-chat card; explicit live-card requires same-repository async:false, so async workflows should omit chatProgress or use auto/off. Workflow-level child controls default onto each runs.run launch, and explicit child fields override them. Use {action:"children.list"} to list recent retained workflow children with resumable/not-resumable reasons. Resume only rows reported resumable. For a simple follow-up or implementation challenge, use {action:"resume", id:"run-id", message:"..."}. Resume keeps the stored agent/model/tool contract. If no resumable child is listed, launch a same-role fallback challenge and label it as fallback. Inside workflowScript, continue one with runs.run(key, {resume:"run-id", task:"follow-up"}); workflow resumes wait for completed output, and loops must continue from each latest returned runId. Await runs.steer(key, message, {mode?, index?, ackTimeoutMs?}) to guide a prior keyed child without exposing its run id; receipts are queued, delivered, missed, or failed. Always await or return runs.steer. 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.steer, 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.
42
+ • FILE SCRIPT: { workflowScriptPath:"workflows/review.js" }. Relative paths resolve against the request cwd. The host reads the file before the filesystem-free workflow sandbox starts. Do not combine this field with workflowScript.
39
43
  • 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" }
40
44
  • 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}" }
41
- • Optional context is "fresh", "fork", or "profile". profile requires the selected agent's declared defaultContext and ignores config defaultSubagentContext. Explicit fresh/fork wins. When omitted, config defaultSubagentContext wins over agent defaultContext. 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.
45
+ • Optional context is "fresh", "fork", or "profile". profile requires the selected agent's declared defaultContext and ignores config defaultSubagentContext. Explicit fresh/fork wins. When omitted, config defaultSubagentContext wins over agent defaultContext. Config forkContext can summarize transcript overflow with stable recovery refs before spawn without adding another public context value. 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.
42
46
  • 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}.
43
47
 
44
48
  MANAGEMENT / CONTROL (use action; omit execution fields):
45
- • 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.
49
+ • validate checks workflowScript or workflowScriptPath syntax and statically decidable structure without launching children. 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.
46
50
  • 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.
47
- • Create durable project schedules with { action:"schedule.create", id?, name?, at:"+10m" | ISO, workflowScript:"return runs.run('main', {agent:'worker', task:'...'})" } or { every:"6h", workflowScript:"..." }. Manage them with schedule.list/show/history/pause/resume/run/run-due/delete. This first slice supports fixed intervals; calendar schedules and schedule mission attachment are deferred.
51
+ • Create durable project schedules with { action:"schedule.create", id?, name?, at:"+10m" | ISO, workflowScript:"return runs.run('main', {agent:'worker', task:'...'})" }, or use workflowScriptPath instead. Manage them with schedule.list/show/history/pause/resume/run/run-due/delete. This first slice supports fixed intervals; calendar schedules and schedule mission attachment are deferred.
48
52
 
49
53
  ${SUBAGENT_SAFETY_GUIDANCE}`;
50
54
 
51
- 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.
55
+ export const COMPACT_SUBAGENT_TOOL_DESCRIPTION = `Run one child with { agent, task? }; use { workflowScript } for inline orchestration or { workflowScriptPath } to load it from the request cwd. The script inputs are mutually exclusive. Omit action for execution. Use action only for management/control actions.
52
56
 
53
57
  EXECUTE:
58
+ • ${EXTERNAL_CLI_RUNNER_GUIDANCE}
54
59
  • Call { action:"list" } first and use only executable/non-disabled agents.
55
- • Passing an explicit model? Call {action:"models"} first and copy an exact provider/id; bare ids resolve only when unique in the registry; agent names (e.g. gpt-pro, advisor) are not model ids.
56
- • SINGLE {agent:"worker",task:"..."} starts exactly one direct child. Fields apply to that child. Do not combine agent/task with action or workflowScript.
60
+ • Passing an explicit model? Call {action:"models"} first and copy an exact provider/id; bare ids resolve only when unique in the registry; agent names (e.g. gpt-pro, advisor) are not model ids. Per-run thinking is a suffix on the model string (provider/id:high; off/minimal/low/medium/high/xhigh/max), and the suffix wins over the agent's thinking default; the thinking field only applies to action='watchdog.configure' and is ignored on dispatch.
61
+ • SINGLE {agent:"worker",task:"..."} starts exactly one direct child. Fields apply to that child. Do not combine agent/task with action, workflowScript, or workflowScriptPath.
57
62
  • SCRIPT {workflowScript:"return runs.run('main', {agent:'worker', task:'...'})"}. Use stable-key runs.run for one child and await runs.all([{key,agent,task}, ...]) for ordinary parallel work. runs.all resolves to an ordered array, not a key map; use results[0], destructuring, or results.map(...), not results.<key>. Do not read .output from unawaited runs.run launches. Stored runs.run promises are only for advanced rolling fanout and each must later be observed with direct await, Promise.race, or Promise.all. Await runs.steer(key,message,options?) to guide a prior keyed child; it returns queued, delivered, missed, or failed and never accepts a raw run id. Always await or return steering calls. Use {action:"children.list"} for recent retained workflow children and resume only rows reported resumable. Use {action:"resume",id:"run-id",message:"..."} for a simple follow-up or challenge; resume keeps the stored agent/model/tool contract. If none is resumable, launch a same-role fallback challenge and label it as fallback. Inside workflowScript use runs.run(key,{resume:"run-id",task:"follow-up"}) when the script must wait for completion and 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. Use top-level await, plain helper functions, or explicit Promise chains; nested async function, arrow, and method helpers are rejected. 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 normally start async unless config sets asyncByDefault:false; set async:true explicitly when async behavior matters. async:false blocks the parent until completion and auto-enables a same-repo live chat card unless chatProgress is off; explicit live-card requires same-repository async:false, so async workflows should omit chatProgress or use auto/off.
63
+ • FILE SCRIPT {workflowScriptPath:"workflows/review.js"} loads the script on the host relative to the request cwd before sandbox execution. Do not combine it with workflowScript.
58
64
  • 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]"}
59
- • context can be fresh, fork, or profile. profile requires the selected agent's declared defaultContext and ignores defaultSubagentContext. Explicit fresh/fork wins; omitted context follows defaultSubagentContext before agent defaultContext. 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.
65
+ • context can be fresh, fork, or profile. profile requires the selected agent's declared defaultContext and ignores defaultSubagentContext. Explicit fresh/fork wins; omitted context follows defaultSubagentContext before agent defaultContext. Config forkContext can summarize transcript overflow with stable recovery refs before spawn without adding another public context value. 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.
60
66
 
61
67
  MANAGE / CONTROL:
62
68
  • 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.
@@ -12,6 +12,7 @@ import { readStatus } from "../../shared/utils.ts";
12
12
  import { resolveSubagentRunId } from "../../runs/background/run-id-resolver.ts";
13
13
  import { resolveNodeExecutable } from "../../shared/node-executable.ts";
14
14
  import { createHerdrClient, detectHerdr, type HerdrClient, type HerdrErrorCode, type HerdrResult } from "./client.ts";
15
+ import { encodeSessionRoots } from "./session-roots-codec.ts";
15
16
  import { formatShellCommand } from "./shell-command.ts";
16
17
 
17
18
  export const HERDR_INSPECTOR_ACTIONS = ["inspector.open", "inspector.status", "inspector.close"] as const;
@@ -88,7 +89,7 @@ function extractPaneId(value: unknown): string | undefined {
88
89
  }
89
90
 
90
91
  function inspectorCommand(input: { runnerPath: string; asyncDir: string; runId: string; index?: number; missionPath?: string; allowSteer: boolean; allowStop: boolean; sessionRoots: string[] }): string {
91
- const args = [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)];
92
+ const args = [input.runnerPath, "--async-dir", input.asyncDir, "--run-id", input.runId, "--allow-steer", String(input.allowSteer), "--allow-stop", String(input.allowStop), "--session-roots", encodeSessionRoots(input.sessionRoots)];
92
93
  if (input.index !== undefined) args.push("--index", String(input.index));
93
94
  if (input.missionPath) args.push("--mission-path", input.missionPath);
94
95
  return formatShellCommand(resolveNodeExecutable(), args);
@@ -9,6 +9,7 @@ import { formatAsyncRunTranscript } from "../../runs/background/fleet-view.ts";
9
9
  import { steeringReceipt } from "../../runs/background/steering.ts";
10
10
  import type { AsyncStatus } from "../../shared/types.ts";
11
11
  import { readStatus } from "../../shared/utils.ts";
12
+ import { decodeSessionRoots } from "./session-roots-codec.ts";
12
13
 
13
14
  export interface RunnerOptions {
14
15
  asyncDir: string;
@@ -60,16 +61,7 @@ function parseArgs(argv: string[]): RunnerOptions {
60
61
  const childIndex = indexRaw === undefined ? undefined : Number(indexRaw);
61
62
  if (childIndex !== undefined && (!Number.isInteger(childIndex) || childIndex < 0)) throw new Error("--index must be a non-negative integer.");
62
63
  const sessionRootsRaw = values.get("--session-roots");
63
- let sessionRoots: string[] = [];
64
- if (sessionRootsRaw !== undefined) {
65
- try {
66
- const parsed = JSON.parse(sessionRootsRaw) as unknown;
67
- if (!Array.isArray(parsed) || parsed.some((root) => typeof root !== "string")) throw new Error();
68
- sessionRoots = parsed;
69
- } catch {
70
- throw new Error("--session-roots must be a JSON array of strings.");
71
- }
72
- }
64
+ const sessionRoots = sessionRootsRaw === undefined ? [] : decodeSessionRoots(sessionRootsRaw);
73
65
  const refreshRaw = values.get("--refresh-ms");
74
66
  const refreshMs = refreshRaw === undefined ? 1_500 : Number(refreshRaw);
75
67
  if (!Number.isInteger(refreshMs) || refreshMs < 250) throw new Error("--refresh-ms must be an integer >= 250.");
@@ -0,0 +1,42 @@
1
+ /**
2
+ * Windows PowerShell has no backslash-escape for embedded double quotes: a
3
+ * double-quoted string literal only recognizes `` `" `` or `""` to embed a
4
+ * literal quote, so a naively-quoted JSON array (which is full of `"` and
5
+ * `\` characters) gets truncated or split into multiple argv tokens the
6
+ * moment PowerShell tokenizes the `pane run` command line.
7
+ *
8
+ * Base64 has no quotes, backslashes, or spaces for any shell to mangle, so
9
+ * encoding the `--session-roots` payload sidesteps quoting entirely. It is
10
+ * also plain ASCII, so it never hits shellQuote's Windows quoting branch in
11
+ * a way that could still fail as new characters are added upstream.
12
+ */
13
+ export function encodeSessionRoots(roots: readonly string[]): string {
14
+ return Buffer.from(JSON.stringify(roots), "utf-8").toString("base64");
15
+ }
16
+
17
+ function parseStringArray(value: unknown): string[] | undefined {
18
+ if (!Array.isArray(value) || value.some((root) => typeof root !== "string")) return undefined;
19
+ return value;
20
+ }
21
+
22
+ /**
23
+ * Decodes a `--session-roots` argument produced by {@link encodeSessionRoots}.
24
+ * Falls back to parsing the value as raw JSON so any externally-launched
25
+ * inspector runner (a cached copy, or a manual invocation) that still passes
26
+ * the legacy unencoded form keeps working.
27
+ */
28
+ export function decodeSessionRoots(raw: string): string[] {
29
+ try {
30
+ const decoded = parseStringArray(JSON.parse(Buffer.from(raw, "base64").toString("utf-8")));
31
+ if (decoded) return decoded;
32
+ } catch {
33
+ // fall through to legacy raw-JSON parsing below
34
+ }
35
+ try {
36
+ const parsed = parseStringArray(JSON.parse(raw));
37
+ if (parsed) return parsed;
38
+ } catch {
39
+ // fall through to the shared error below
40
+ }
41
+ throw new Error("--session-roots must be a base64-encoded or raw JSON array of strings.");
42
+ }
@@ -3,10 +3,15 @@ import {
3
3
  SUBAGENT_ASYNC_STARTED_EVENT,
4
4
  SUBAGENT_CONTROL_EVENT,
5
5
  } from "../shared/types.ts";
6
+ import { previewDisplayText, sanitizeDisplayText } from "../shared/display-text.ts";
6
7
 
7
8
  const DEFAULT_SOURCE = "pi-subagents:herdr";
8
9
  const DEFAULT_TTL_MS = 120_000;
9
10
  const DEFAULT_REFRESH_MS = 45_000;
11
+ const MAX_TASK_LABEL_CHARS = 80;
12
+ const MAX_TITLE_TASK_CHARS = 42;
13
+ const MAX_WORKFLOW_LABEL_NODES = 128;
14
+ const MAX_WORKFLOW_LABEL_DEPTH = 8;
10
15
 
11
16
  let metadataReportSeq = Date.now() * 1000;
12
17
 
@@ -24,6 +29,8 @@ export interface HerdrStatusRun {
24
29
  id: string;
25
30
  agent?: string;
26
31
  agents?: string[];
32
+ /** Explicit launch/workflow label only; raw prompts never enter pane metadata. */
33
+ taskLabel?: string;
27
34
  needsAttention?: boolean;
28
35
  attentionLabel?: string;
29
36
  }
@@ -52,6 +59,7 @@ export interface HerdrStatusBridge {
52
59
  * state. Also re-syncs runs that survived a reload/resume.
53
60
  */
54
61
  sessionStarted(input: { hasUI: boolean; runs: Iterable<HerdrStatusRun> }): void;
62
+ syncRuns(): void;
55
63
  agentStarted(): void;
56
64
  flush(): Promise<void>;
57
65
  dispose(): void;
@@ -61,12 +69,42 @@ function isRecord(value: unknown): value is Record<string, unknown> {
61
69
  return typeof value === "object" && value !== null && !Array.isArray(value);
62
70
  }
63
71
 
72
+ function boundedTaskLabel(value: unknown, maxChars = MAX_TASK_LABEL_CHARS): string | undefined {
73
+ if (typeof value !== "string") return undefined;
74
+ const normalized = sanitizeDisplayText(value).trim();
75
+ if (!normalized) return undefined;
76
+ return previewDisplayText(normalized, maxChars);
77
+ }
78
+
79
+ function workflowTaskLabel(data: Record<string, unknown>): string | undefined {
80
+ const explicit = boundedTaskLabel(data.taskLabel);
81
+ if (explicit) return explicit;
82
+ if (!isRecord(data.workflowGraph) || !Array.isArray(data.workflowGraph.nodes)) return undefined;
83
+ const currentNodeId = typeof data.workflowGraph.currentNodeId === "string" ? data.workflowGraph.currentNodeId : undefined;
84
+ const nodes: Record<string, unknown>[] = [];
85
+ const collect = (values: unknown[], depth: number): void => {
86
+ if (depth > MAX_WORKFLOW_LABEL_DEPTH || nodes.length >= MAX_WORKFLOW_LABEL_NODES) return;
87
+ for (const value of values) {
88
+ if (nodes.length >= MAX_WORKFLOW_LABEL_NODES) return;
89
+ if (!isRecord(value)) continue;
90
+ nodes.push(value);
91
+ if (Array.isArray(value.children)) collect(value.children, depth + 1);
92
+ }
93
+ };
94
+ collect(data.workflowGraph.nodes, 0);
95
+ const current = currentNodeId ? nodes.find((node) => node.id === currentNodeId) : undefined;
96
+ const active = current ?? nodes.find((node) => node.status === "running") ?? nodes.find((node) => node.status === "pending");
97
+ return boundedTaskLabel(active?.label);
98
+ }
99
+
64
100
  function startedRun(data: unknown): HerdrStatusRun | undefined {
65
101
  if (!isRecord(data) || typeof data.id !== "string" || !data.id) return undefined;
102
+ const taskLabel = workflowTaskLabel(data);
66
103
  return {
67
104
  id: data.id,
68
105
  ...(typeof data.agent === "string" ? { agent: data.agent } : {}),
69
106
  ...(Array.isArray(data.agents) && data.agents.every((agent) => typeof agent === "string") ? { agents: data.agents as string[] } : {}),
107
+ ...(taskLabel ? { taskLabel } : {}),
70
108
  };
71
109
  }
72
110
 
@@ -113,6 +151,7 @@ export function registerHerdrStatusBridge(options: HerdrStatusBridgeOptions): He
113
151
 
114
152
  const activeAgentNames = (): string[] => [...new Set([...runs.values()].flatMap((run) => run.agents?.length ? run.agents : run.agent ? [run.agent] : []))];
115
153
  const activeSubagentCount = (): number => [...runs.values()].reduce((total, run) => total + Math.max(1, run.agents?.length ?? (run.agent ? 1 : 0)), 0);
154
+ const activeTaskLabel = (): string | undefined => [...runs.values()].reverse().find((run) => run.taskLabel)?.taskLabel;
116
155
 
117
156
  const label = (includeAttention = false): string => {
118
157
  const agents = activeAgentNames();
@@ -122,15 +161,18 @@ export function registerHerdrStatusBridge(options: HerdrStatusBridgeOptions): He
122
161
  : "";
123
162
  const panes = Math.max(0, options.getProjectPaneCount?.() ?? 0);
124
163
  const paneText = panes > 0 ? ` · ${panes} pane${panes === 1 ? "" : "s"}` : "";
164
+ const task = activeTaskLabel();
165
+ const taskText = task ? ` · ${task}` : "";
125
166
  const attention = includeAttention && attentionLabels.size > 0 ? " ⚠" : "";
126
- return `⏳ ${activeCount} subagent${activeCount === 1 ? "" : "s"}${who}${paneText}${attention}`;
167
+ return `⏳ ${activeCount} subagent${activeCount === 1 ? "" : "s"}${who}${paneText}${taskText}${attention}`;
127
168
  };
128
169
 
129
170
  const titleSuffix = (): string | undefined => {
130
171
  if (runs.size === 0) return undefined;
131
172
  const agentNames = activeAgentNames();
132
173
  const activeCount = activeSubagentCount();
133
- const target = activeCount === 1 && agentNames.length === 1 ? agentNames[0]! : String(activeCount);
174
+ const task = boundedTaskLabel(activeTaskLabel(), MAX_TITLE_TASK_CHARS);
175
+ const target = task ?? (activeCount === 1 && agentNames.length === 1 ? agentNames[0]! : String(activeCount));
134
176
  return `⏳${target}${attentionLabels.size > 0 ? "⚠" : ""}`;
135
177
  };
136
178
 
@@ -259,7 +301,9 @@ export function registerHerdrStatusBridge(options: HerdrStatusBridgeOptions): He
259
301
  for (const run of nextRuns) {
260
302
  if (!run || typeof run.id !== "string" || !run.id) continue;
261
303
  activeIds.add(run.id);
262
- runs.set(run.id, { ...run });
304
+ const taskLabel = boundedTaskLabel(run.taskLabel);
305
+ const { taskLabel: _rawTaskLabel, ...sanitizedRun } = run;
306
+ runs.set(run.id, { ...sanitizedRun, ...(taskLabel ? { taskLabel } : {}) });
263
307
  if (!run.needsAttention) {
264
308
  acknowledgedAttention.delete(run.id);
265
309
  } else if (!acknowledgedAttention.has(run.id)) {
@@ -334,6 +378,10 @@ export function registerHerdrStatusBridge(options: HerdrStatusBridgeOptions): He
334
378
  rootSession = true;
335
379
  replaceRuns(restoredRuns);
336
380
  },
381
+ syncRuns() {
382
+ if (!enabled || !rootSession || disposed) return;
383
+ refresh();
384
+ },
337
385
  async flush() {
338
386
  while (draining || pendingReport) await drainPromise;
339
387
  },