@xzzpig/pi-subagents 0.7.0 → 0.9.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.
- package/CHANGELOG.md +456 -4
- package/README.md +3 -3
- package/agents/claude-code-writer.md +15 -0
- package/agents/claude-code.md +15 -0
- package/agents/codex-exec-writer.md +15 -0
- package/agents/codex-exec.md +15 -0
- package/agents/cursor-agent-writer.md +14 -0
- package/agents/cursor-agent.md +14 -0
- package/agents/reviewer.md +13 -3
- package/agents/scout.md +1 -1
- package/docs/agents.md +154 -42
- package/docs/configuration.md +85 -26
- package/docs/extension-api.md +81 -16
- package/docs/missions.md +2 -0
- package/docs/models.md +75 -11
- package/docs/observability.md +34 -21
- package/docs/tool-reference.md +142 -18
- package/docs/watchdog.md +92 -114
- package/docs/workflows.md +148 -4
- package/index.ts +10 -1
- package/install.mjs +1 -1
- package/package.json +7 -6
- package/prompts/council.md +19 -7
- package/prompts/parallel-review.md +5 -1
- package/prompts/review-loop.md +11 -7
- package/skills/council-mode/SKILL.md +44 -215
- package/skills/council-mode/references/pass-contracts.md +150 -0
- package/skills/pi-subagents/SKILL.md +90 -32
- package/skills/pi-subagents/references/constraints-and-recipes.md +34 -223
- package/skills/pi-subagents/references/execution-controls.md +104 -19
- package/skills/pi-subagents/references/management-authoring-rpc.md +5 -5
- package/skills/pi-subagents/references/multi-lane-orchestration.md +16 -4
- package/skills/pi-subagents/references/prompting-and-roles.md +71 -36
- package/skills/pi-subagents/references/review-and-validation.md +73 -0
- package/src/agents/agent-management.ts +471 -114
- package/src/agents/agent-refinements.ts +4 -4
- package/src/agents/agent-serializer.ts +16 -4
- package/src/agents/agents.ts +1076 -351
- package/src/agents/builtin-names.ts +6 -0
- package/src/agents/runtime-agent-events.ts +70 -0
- package/src/agents/runtime-agent-registry.ts +31 -20
- package/src/api/agents.ts +10 -5
- package/src/api/background-work.ts +12 -3
- package/src/api/capability-ceiling.ts +0 -1
- package/src/api/{pi-args.ts → child-tool-plan.ts} +1 -1
- package/src/api/delegation.ts +0 -7
- package/src/api/external-job-provider.ts +10 -1
- package/src/api/external-runs.ts +67 -4
- package/src/api/preflight.ts +97 -34
- package/src/api/project-panes.ts +2 -0
- package/src/api/shared-types.ts +6 -0
- package/src/extension/config.ts +90 -0
- package/src/extension/doctor.ts +15 -13
- package/src/extension/fanout-child.ts +17 -16
- package/src/extension/index.ts +139 -41
- package/src/extension/public-execution.ts +113 -22
- package/src/extension/rpc.ts +182 -13
- package/src/extension/schemas.ts +63 -21
- package/src/extension/tool-description.ts +48 -23
- package/src/extension/tool-result.ts +19 -0
- package/src/inspectors/herdr/actions.ts +2 -1
- package/src/inspectors/herdr/client.ts +3 -3
- package/src/inspectors/herdr/focus.ts +55 -0
- package/src/inspectors/herdr/inspector-runner.ts +21 -23
- package/src/inspectors/herdr/project-panes.ts +228 -44
- package/src/inspectors/herdr/session-roots-codec.ts +42 -0
- package/src/integrations/herdr-status.ts +75 -5
- package/src/intercom/native-supervisor-channel.ts +138 -60
- package/src/intercom/result-intercom.ts +2 -0
- package/src/intercom/supervisor-ui.ts +243 -0
- package/src/profiles/profiles.ts +5 -6
- package/src/runs/background/active-async-capacity.ts +103 -18
- package/src/runs/background/async-execution.ts +492 -125
- package/src/runs/background/async-job-tracker.ts +127 -28
- package/src/runs/background/async-resume.ts +67 -29
- package/src/runs/background/async-retention.ts +21 -4
- package/src/runs/background/async-status-snapshot.ts +23 -261
- package/src/runs/background/async-status.ts +199 -14
- package/src/runs/background/auto-drain.ts +1 -1
- package/src/runs/background/chain-append.ts +8 -3
- package/src/runs/background/chain-root-attachment.ts +79 -8
- package/src/runs/background/control-channel.ts +101 -214
- package/src/runs/background/fleet-view.ts +38 -22
- package/src/runs/background/inspect-rpc.ts +8 -8
- package/src/runs/background/notify.ts +295 -8
- package/src/runs/background/process-terminal.ts +16 -0
- package/src/runs/background/result-delivery-ownership.ts +45 -0
- package/src/runs/background/result-files.ts +28 -14
- package/src/runs/background/result-watcher.ts +43 -19
- package/src/runs/background/resume-guidance.ts +2 -2
- package/src/runs/background/retained-children.ts +1 -1
- package/src/runs/background/run-child-session.ts +613 -0
- package/src/runs/background/run-status.ts +99 -18
- package/src/runs/background/runner-aliases.ts +125 -0
- package/src/runs/background/runner-child-sessions.ts +31 -0
- package/src/runs/background/scheduled-runs.ts +174 -18
- package/src/runs/background/stale-run-reconciler.ts +13 -4
- package/src/runs/background/steering.ts +8 -15
- package/src/runs/background/subagent-runner.ts +959 -1159
- package/src/runs/background/subagent-wait.ts +86 -31
- package/src/runs/background/terminal-run-index.ts +1 -1
- package/src/runs/background/wait-completions.ts +45 -2
- package/src/runs/background/wait-config.ts +23 -9
- package/src/runs/background/wait-tool.ts +27 -19
- package/src/runs/foreground/async-steering-action.ts +3 -19
- package/src/runs/foreground/async-stop-action.ts +23 -2
- package/src/runs/foreground/execution.ts +585 -481
- package/src/runs/foreground/foreground-control.ts +13 -0
- package/src/runs/foreground/foreground-history.ts +26 -3
- package/src/runs/foreground/subagent-executor.ts +1549 -410
- package/src/runs/foreground/workflow-detach-reconcile.ts +141 -104
- package/src/runs/foreground/workflow-foreground-steering.ts +24 -98
- package/src/runs/shared/abort-recovery.ts +119 -0
- package/src/runs/shared/acceptance.ts +147 -39
- package/src/runs/shared/agent-contract.ts +1 -1
- package/src/runs/shared/async-status-projection.ts +565 -0
- package/src/runs/shared/background-process-options.ts +9 -0
- package/src/runs/shared/capability-ceiling.ts +2 -2
- package/src/runs/shared/child-hooks.ts +25 -0
- package/src/runs/shared/child-identity.ts +62 -0
- package/src/runs/shared/child-launch-plan.ts +151 -0
- package/src/runs/shared/child-launch.ts +314 -0
- package/src/runs/shared/child-lifecycle.ts +25 -0
- package/src/runs/shared/child-runtime-config.ts +126 -0
- package/src/runs/shared/child-session.ts +342 -0
- package/src/runs/shared/child-tool-plan.ts +540 -0
- package/src/runs/shared/claude-code-adapter.ts +133 -0
- package/src/runs/shared/codex-exec-adapter.ts +129 -0
- package/src/runs/shared/completion-evidence.ts +89 -0
- package/src/runs/shared/completion-guard.ts +57 -6
- package/src/runs/shared/cursor-agent-adapter.ts +114 -0
- package/src/runs/shared/dynamic-fanout.ts +4 -4
- package/src/runs/shared/extension-bindings.ts +78 -0
- package/src/runs/shared/external-cli-contract.ts +167 -0
- package/src/runs/shared/external-cli-preflight.ts +138 -0
- package/src/runs/shared/external-cli-runner.ts +349 -54
- package/src/runs/shared/external-job-bridge.ts +53 -37
- package/src/runs/shared/external-job-runner.ts +126 -23
- package/src/runs/shared/fast-mode-extension.ts +10 -0
- package/src/runs/shared/host-step-status.ts +231 -0
- package/src/runs/shared/lane-metadata.ts +126 -0
- package/src/runs/shared/launch-cwd.ts +16 -0
- package/src/runs/shared/long-running-guard.ts +2 -1
- package/src/runs/shared/mcp-config-sources.ts +422 -0
- package/src/runs/shared/mcp-direct-tool-allowlist.ts +222 -158
- package/src/runs/shared/mcp-direct-tool-grant.ts +194 -0
- package/src/runs/shared/model-exclusions.ts +141 -10
- package/src/runs/shared/model-fallback.ts +187 -33
- package/src/runs/shared/model-scope.ts +106 -39
- package/src/runs/shared/mutation-evidence.ts +199 -0
- package/src/runs/shared/nested-events.ts +38 -48
- package/src/runs/shared/nested-path.ts +0 -14
- package/src/runs/shared/nested-render.ts +9 -5
- package/src/runs/shared/orca-progress-tabs.ts +83 -16
- package/src/runs/shared/parallel-handoff.ts +423 -7
- package/src/runs/shared/parallel-utils.ts +28 -5
- package/src/runs/shared/permissions.ts +1 -14
- package/src/runs/shared/pi-spawn.ts +69 -35
- package/src/runs/shared/process-signal.ts +16 -0
- package/src/runs/shared/run-fanout-budget.ts +0 -13
- package/src/runs/shared/run-history.ts +21 -1
- package/src/runs/shared/runtime-acknowledged-extensions.ts +0 -27
- package/src/runs/shared/single-output.ts +89 -22
- package/src/runs/shared/structured-output.ts +61 -7
- package/src/runs/shared/subagent-control.ts +6 -2
- package/src/runs/shared/subagent-prompt-runtime.ts +216 -360
- package/src/runs/shared/task-intent.ts +21 -7
- package/src/runs/shared/tool-availability.ts +18 -64
- package/src/runs/shared/tool-budget.ts +0 -14
- package/src/runs/shared/tool-timeout.ts +1 -1
- package/src/runs/shared/workflow-graph.ts +16 -0
- package/src/runs/shared/worktree-cleanup-plan.ts +866 -0
- package/src/runs/shared/worktree.ts +571 -62
- package/src/shared/atomic-json.ts +3 -1
- package/src/shared/child-session-name.ts +46 -0
- package/src/shared/extension-context.ts +24 -0
- package/src/shared/fork-context.ts +21 -12
- package/src/shared/fork-session-cwd.ts +27 -0
- package/src/shared/formatters.ts +18 -3
- package/src/shared/jsonl-writer.ts +11 -0
- package/src/shared/launch-contract.ts +20 -6
- package/src/shared/pruned-fork.ts +450 -0
- package/src/shared/session-file-trust.ts +19 -0
- package/src/shared/session-tokens.ts +14 -3
- package/src/shared/settings.ts +21 -102
- package/src/shared/shortcuts.ts +17 -0
- package/src/shared/thinking-ceiling.ts +46 -0
- package/src/shared/types.ts +644 -75
- package/src/shared/utils.ts +60 -93
- package/src/shared/workflow-child-permit.ts +207 -0
- package/src/slash/delegation-adapters.ts +1 -9
- package/src/slash/delegation-request.ts +0 -4
- package/src/slash/prompt-template-bridge.ts +37 -1
- package/src/slash/slash-bridge.ts +1 -2
- package/src/slash/slash-commands.ts +383 -116
- package/src/slash/slash-live-state.ts +22 -11
- package/src/slash/subagents-admin.ts +29 -12
- package/src/tui/fleet-native-transcript.ts +4 -0
- package/src/tui/fleet-status.ts +278 -90
- package/src/tui/fleet-transcript.ts +11 -5
- package/src/tui/fleet.ts +54 -28
- package/src/tui/render-helpers.ts +31 -0
- package/src/tui/render.ts +1433 -166
- package/src/watchdog/change-signature.ts +40 -1
- package/src/watchdog/child-status.ts +54 -34
- package/src/watchdog/diff-tool.ts +77 -0
- package/src/watchdog/emission-guard.ts +5 -3
- package/src/watchdog/guidance.ts +20 -0
- package/src/watchdog/permission-arbiter.ts +59 -52
- package/src/watchdog/register-child.ts +28 -25
- package/src/watchdog/register-main.ts +10 -9
- package/src/watchdog/render.ts +4 -5
- package/src/watchdog/review.ts +15 -4
- package/src/watchdog/rules.ts +70 -0
- package/src/watchdog/runtime.ts +75 -92
- package/src/watchdog/scope.ts +0 -11
- package/src/watchdog/settings.ts +48 -104
- package/src/watchdog/turn-delta.ts +1 -1
- package/src/watchdog/types.ts +18 -32
- package/src/watchdog/warning-format.ts +0 -1
- package/src/workflows/chat-progress.ts +7 -3
- package/src/workflows/host-command.ts +235 -0
- package/src/workflows/scripted-workflow.ts +1142 -69
- package/src/workflows/workflow-checklist.ts +439 -0
- package/src/workflows/workflow-child-summary.ts +121 -0
- package/src/workflows/workflow-preflight.ts +297 -0
- package/src/workflows/workflow-receipt.ts +232 -6
- package/src/workflows/workflow-resources.ts +150 -0
- package/src/workflows/workflow-settlement.ts +246 -0
- package/src/runs/shared/child-protocol.ts +0 -401
- package/src/runs/shared/pi-args.ts +0 -858
- package/src/runs/shared/subagent-startup-retry.ts +0 -116
- package/src/runs/shared/turn-budget.ts +0 -98
- package/src/shared/post-exit-stdio-guard.ts +0 -85
package/src/extension/schemas.ts
CHANGED
|
@@ -86,10 +86,13 @@ const AcceptanceOverride = Type.Unsafe({
|
|
|
86
86
|
deprecated: true,
|
|
87
87
|
description: "Invalid as an explicit policy. Recognized only so preflight can explain that reviewed is an achieved status.",
|
|
88
88
|
},
|
|
89
|
+
{
|
|
90
|
+
type: "string",
|
|
91
|
+
},
|
|
89
92
|
{ type: "boolean", enum: [false] },
|
|
90
93
|
{ type: "object", additionalProperties: true },
|
|
91
94
|
],
|
|
92
|
-
description: `Optional acceptance policy.
|
|
95
|
+
description: `Optional acceptance policy. Prefer an inline JSON object. JSON-encoded object strings are tolerated only during input normalization; invalid strings fail closed. Reviewer/read-only calls, omit acceptance. { level: "checked", evidence: ["commands-run", "changed-files"] }. Supported evidence kinds: ${AcceptanceEvidenceKinds.join(",")}. acceptance.review.required.`,
|
|
93
96
|
});
|
|
94
97
|
|
|
95
98
|
const AgentContractOverride = Type.Object({
|
|
@@ -101,10 +104,14 @@ const ChainGateOverride = Type.String({
|
|
|
101
104
|
description: "For chain steps with agentContract, choose whether the chain advances on execution success or acceptance success. Defaults to execution.",
|
|
102
105
|
});
|
|
103
106
|
|
|
104
|
-
const
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
107
|
+
const WorkflowLaneMetadata = Type.Object({
|
|
108
|
+
version: Type.Integer({ minimum: 1, maximum: 1 }),
|
|
109
|
+
key: Type.String({ minLength: 1, maxLength: 128, pattern: "^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$" }),
|
|
110
|
+
mode: Type.Optional(Type.String({ enum: ["mutation", "review", "scout", "gate"] })),
|
|
111
|
+
sourceRef: Type.Optional(Type.String({ minLength: 1, maxLength: 128 })),
|
|
112
|
+
claims: Type.Optional(Type.Array(Type.String({ minLength: 1, maxLength: 160 }), { maxItems: 20 })),
|
|
113
|
+
outputPaths: Type.Optional(Type.Array(Type.String({ minLength: 1, maxLength: 256 }), { maxItems: 10 })),
|
|
114
|
+
}, { additionalProperties: false, description: "Optional bounded child lane metadata. Display/triage only; sourceRef is opaque and never resolved during status rendering." });
|
|
108
115
|
|
|
109
116
|
const ToolBudgetBlock = Type.Unsafe({
|
|
110
117
|
anyOf: [
|
|
@@ -129,6 +136,21 @@ const UsageBudgetOverride = Type.Object({
|
|
|
129
136
|
costUsd: Type.Optional(UsageBudgetLimitOverride),
|
|
130
137
|
}, { additionalProperties: false, description: "Optional root-only reported-usage budget. Hard limits prevent future child launches; running children are not stopped." });
|
|
131
138
|
|
|
139
|
+
const WorkflowPreflightLane = Type.Object({
|
|
140
|
+
key: Type.String({ minLength: 1, maxLength: 128 }),
|
|
141
|
+
mode: Type.Optional(Type.String({ enum: ["mutation", "review", "scout", "gate"] })),
|
|
142
|
+
decision: Type.Optional(Type.String({ maxLength: 256 })),
|
|
143
|
+
claims: Type.Optional(Type.Array(Type.String({ maxLength: 256 }), { maxItems: 16 })),
|
|
144
|
+
expectedOutput: Type.Optional(Type.String({ maxLength: 256 })),
|
|
145
|
+
independence: Type.Optional(Type.String({ maxLength: 256 })),
|
|
146
|
+
}, { additionalProperties: false });
|
|
147
|
+
|
|
148
|
+
const WorkflowPreflightOverride = Type.Object({
|
|
149
|
+
version: Type.Integer({ minimum: 1, maximum: 1 }),
|
|
150
|
+
coverage: Type.Optional(Type.String({ enum: ["complete", "partial"] })),
|
|
151
|
+
lanes: Type.Array(WorkflowPreflightLane, { maxItems: 64 }),
|
|
152
|
+
}, { additionalProperties: false, description: "Bounded display-only lane hints for workflow launch/status. V1 coverage mismatches warn but never change launch authority or execution." });
|
|
153
|
+
|
|
132
154
|
// Parallel task item (within a parallel step)
|
|
133
155
|
export const ParallelTaskSchema = Type.Object({
|
|
134
156
|
agent: Type.String(),
|
|
@@ -145,6 +167,7 @@ export const ParallelTaskSchema = Type.Object({
|
|
|
145
167
|
progress: Type.Optional(Type.Boolean({ description: "Enable progress.md tracking in {chain_dir}" })),
|
|
146
168
|
skill: Type.Optional(SkillOverride),
|
|
147
169
|
model: Type.Optional(Type.String({ description: "Override model for this task" })),
|
|
170
|
+
fast: Type.Optional(Type.Boolean({ description: "Opt into priority service tier for supported native OpenAI-Codex child models. This can increase quota or cost." })),
|
|
148
171
|
toolBudget: Type.Optional(ToolBudgetOverride),
|
|
149
172
|
acceptance: Type.Optional(AcceptanceOverride),
|
|
150
173
|
agentContract: Type.Optional(AgentContractOverride),
|
|
@@ -175,6 +198,7 @@ export const DynamicParallelTemplateSchema = Type.Object({
|
|
|
175
198
|
progress: Type.Optional(Type.Boolean({ description: "Enable progress.md tracking in {chain_dir}" })),
|
|
176
199
|
skill: Type.Optional(SkillOverride),
|
|
177
200
|
model: Type.Optional(Type.String({ description: "Override model for this task" })),
|
|
201
|
+
fast: Type.Optional(Type.Boolean({ description: "Opt into priority service tier for supported native OpenAI-Codex child models. This can increase quota or cost." })),
|
|
178
202
|
toolBudget: Type.Optional(ToolBudgetOverride),
|
|
179
203
|
acceptance: Type.Optional(AcceptanceOverride),
|
|
180
204
|
agentContract: Type.Optional(AgentContractOverride),
|
|
@@ -203,6 +227,7 @@ export const ChainItem = Type.Object({
|
|
|
203
227
|
progress: Type.Optional(Type.Boolean({ description: "Enable progress.md tracking in {chain_dir}" })),
|
|
204
228
|
skill: Type.Optional(SkillOverride),
|
|
205
229
|
model: Type.Optional(Type.String({ description: "Override model for this step" })),
|
|
230
|
+
fast: Type.Optional(Type.Boolean({ description: "Opt into priority service tier for supported native OpenAI-Codex child models. This can increase quota or cost." })),
|
|
206
231
|
toolBudget: Type.Optional(ToolBudgetOverride),
|
|
207
232
|
acceptance: Type.Optional(AcceptanceOverride),
|
|
208
233
|
agentContract: Type.Optional(AgentContractOverride),
|
|
@@ -254,11 +279,13 @@ const ControlOverrides = Type.Object({
|
|
|
254
279
|
|
|
255
280
|
const SubagentParamProperties = {
|
|
256
281
|
agent: Type.Optional(Type.String({ description: "Agent for one-child execution, or target for agent management actions." })),
|
|
257
|
-
task: Type.Optional(Type.String({ description: "Optional one-child task. Requires agent; cannot combine with action or
|
|
282
|
+
task: Type.Optional(Type.String({ description: "Optional one-child task. Requires agent; cannot combine with action, workflowScript, or workflowScriptPath." })),
|
|
283
|
+
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." })),
|
|
258
284
|
// Management action (when present, tool operates in management mode)
|
|
259
285
|
action: Type.Optional(Type.String({ minLength: 1,
|
|
260
|
-
description: "Optional management/control action. Omit this field for structured single-child or
|
|
286
|
+
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."
|
|
261
287
|
})),
|
|
288
|
+
capabilities: Type.Optional(Type.Boolean({ description: "For action='list', return compact capability rows and structured details without system prompts." })),
|
|
262
289
|
name: Type.Optional(Type.String({ description: "Human-readable name for action='schedule.create'." })),
|
|
263
290
|
id: Type.Optional(Type.String({
|
|
264
291
|
description: "Run id/prefix for status/debug.run, interrupt, steer, or mission.attach-run."
|
|
@@ -269,8 +296,14 @@ const SubagentParamProperties = {
|
|
|
269
296
|
dir: Type.Optional(Type.String({
|
|
270
297
|
description: "Async run directory for status/debug.run, stop, resume, or steer."
|
|
271
298
|
})),
|
|
272
|
-
handoffPath: Type.Optional(Type.String({ description: "worktree.discard
|
|
299
|
+
handoffPath: Type.Optional(Type.String({ description: "Existing parallel handoff manifest for worktree.discard, worktree.cleanup metadata, or lane evidence actions." })),
|
|
300
|
+
repo: Type.Optional(Type.String({ description: "Repository path for action='worktree.cleanup'; defaults to cwd." })),
|
|
301
|
+
planId: Type.Optional(Type.String({ description: "Cleanup plan id reserved for a future worktree.cleanup apply action." })),
|
|
302
|
+
laneId: Type.Optional(Type.String({ minLength: 1, maxLength: 128, description: "Exact manifest run id for lane.status, lane.recordMerge, or lane.recordSupersession." })),
|
|
303
|
+
merge: Type.Optional(Type.Unsafe({ type: "object", additionalProperties: true, description: "Attested merge evidence for lane.recordMerge: prNumber, reviewedHead, mergeCommit, treeEquivalent, postMergeChecks, attestedBy, and attestedAt." })),
|
|
304
|
+
supersession: Type.Optional(Type.Unsafe({ type: "object", additionalProperties: true, description: "Attested replacement-lane evidence for lane.recordSupersession: supersededBy, attestedBy, and attestedAt." })),
|
|
273
305
|
index: Type.Optional(Type.Integer({ minimum: 0, description: "Zero-based child index for actions that target a specific child or transcript." })),
|
|
306
|
+
childId: Type.Optional(Type.String({ minLength: 1, maxLength: 256, description: "Stable child identity for child-scoped stop requests." })),
|
|
274
307
|
view: Type.Optional(Type.String({
|
|
275
308
|
enum: ["fleet", "transcript"],
|
|
276
309
|
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.",
|
|
@@ -278,17 +311,18 @@ const SubagentParamProperties = {
|
|
|
278
311
|
lines: Type.Optional(Type.Integer({ minimum: 1, maximum: 500, description: "Maximum transcript lines for action='status', view='transcript'. Defaults to 80." })),
|
|
279
312
|
topic: Type.Optional(Type.String()),
|
|
280
313
|
message: Type.Optional(Type.String({ description: "Follow-up message for resume, live guidance for steer, or optional startup prompt for project.open." })),
|
|
281
|
-
mode: Type.Optional(Type.String({ enum: ["steer", "follow_up", "auto"], description: "Delivery mode for action='steer'
|
|
314
|
+
mode: Type.Optional(Type.String({ enum: ["steer", "follow_up", "auto", "plan", "apply"], description: "Delivery mode for action='steer', or plan/apply mode for worktree.cleanup. worktree.cleanup currently supports plan only; apply/removal is not available yet." })),
|
|
282
315
|
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." })),
|
|
283
316
|
additional: Type.Optional(Type.Integer({ minimum: 1, description: "Positive launches to add with action='grant-spawn-budget'. Root interactive parent with native user confirmation only; total grants cannot exceed the original configured cap." })),
|
|
284
317
|
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." })),
|
|
285
318
|
target: Type.Optional(Type.String({ enum: ["main", "children", "child"], description: "Target for watchdog actions." })),
|
|
286
319
|
focus: Type.Optional(Type.Boolean({ description: "Focus the new Herdr pane for inspector.open or project.open." })),
|
|
287
|
-
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)." })),
|
|
320
|
+
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'." })),
|
|
288
321
|
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." })),
|
|
289
322
|
every: Type.Optional(Type.String({ description: "Fixed recurring interval for action='schedule.create', such as '30m', '6h', '2d', or '2w'." })),
|
|
323
|
+
sessionOnly: Type.Optional(Type.Boolean()),
|
|
290
324
|
on: Type.Optional(Type.Unsafe({ anyOf: [{ type: "string" }, { type: "integer" }], description: "Calendar selector reserved for a later schedule slice." })),
|
|
291
|
-
timezone: Type.Optional(Type.String(
|
|
325
|
+
timezone: Type.Optional(Type.String()),
|
|
292
326
|
overlap: Type.Optional(Type.String({ enum: ["skip"], description: "Overlap policy. This slice supports skip only." })),
|
|
293
327
|
catchUp: Type.Optional(Type.String({ enum: ["none", "latest"], description: "Missed occurrence policy for recurring schedules. Defaults to latest." })),
|
|
294
328
|
missionId: Type.Optional(Type.String({ description: "Mission id." })),
|
|
@@ -307,19 +341,26 @@ const SubagentParamProperties = {
|
|
|
307
341
|
],
|
|
308
342
|
description: "Agent config for create/update. Object or JSON string."
|
|
309
343
|
})),
|
|
310
|
-
|
|
344
|
+
workflow: Type.Optional(Type.String({ minLength: 1, description: "Extension-owned workflow resource; resolves its script and authority internally." })),
|
|
345
|
+
args: Type.Optional(Type.Unsafe({ type: "object", maxProperties: 16, additionalProperties: true, description: "Bounded plain-JSON args for workflow; resource validation applies." })),
|
|
346
|
+
workflowScript: Type.Optional(Type.String({ minLength: 1, description: "Inline JavaScript statement body with unknown resource provenance. Normally async unless asyncByDefault:false; set async:true for async workflows and async:false only when the parent must block. Use explicit return, top-level await, plain helper functions, or explicit Promise chains. Nested async function, arrow, and method helpers are rejected. Globals: runs, emit, console, and mission state when enabled. No filesystem, shell, Pi tools, or host globals except through runs.host." })),
|
|
347
|
+
workflowScriptPath: Type.Optional(Type.String({ minLength: 1, description: "Path to a JavaScript workflow file with unknown resource provenance. Mutually exclusive with workflowScript and workflow. Relative paths resolve against the request cwd. The host reads the file before the filesystem-free workflow sandbox starts." })),
|
|
348
|
+
globalConcurrencyLimit: Type.Optional(Type.Integer({ minimum: 1 })),
|
|
349
|
+
maxSubagentSpawnsPerRun: Type.Optional(Type.Integer({ minimum: 1 })),
|
|
350
|
+
preflight: Type.Optional(WorkflowPreflightOverride),
|
|
311
351
|
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." })),
|
|
312
352
|
isolation: Type.Optional(Type.String({ enum: ["none", "worktree"], description: "Workflow child isolation. none runs in the shared cwd; worktree requires managed git worktree isolation." })),
|
|
313
353
|
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." })),
|
|
354
|
+
baseRef: Type.Optional(Type.String()),
|
|
355
|
+
lane: Type.Optional(WorkflowLaneMetadata),
|
|
314
356
|
context: Type.Optional(Type.String({
|
|
315
357
|
enum: ["fresh", "fork", "profile"],
|
|
316
|
-
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.",
|
|
358
|
+
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.",
|
|
317
359
|
})),
|
|
318
360
|
async: Type.Optional(Type.Boolean({ description: "Run in background unless asyncByDefault:false. Set false only when the parent must block until completion." })),
|
|
319
361
|
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." })),
|
|
320
362
|
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." })),
|
|
321
363
|
toolTimeoutMs: Type.Optional(Type.Integer({ minimum: 1, description: "Optional hard per-tool-call timeout in milliseconds; known-fast built-in tools have a five-minute default." })),
|
|
322
|
-
turnBudget: Type.Optional(TurnBudgetOverride),
|
|
323
364
|
toolBudget: Type.Optional(ToolBudgetOverride),
|
|
324
365
|
usageBudget: Type.Optional(UsageBudgetOverride),
|
|
325
366
|
agentScope: Type.Optional(Type.String({ description: "Agent discovery scope: 'user', 'project', or 'both' (default: 'both'; project wins on name collisions)" })),
|
|
@@ -337,11 +378,12 @@ const SubagentParamProperties = {
|
|
|
337
378
|
{ type: "string" },
|
|
338
379
|
{ type: "boolean" },
|
|
339
380
|
],
|
|
340
|
-
description: "Default child output file (string), or false to disable. Relative paths
|
|
381
|
+
description: "Default child output file (string), or false to disable. Relative workflow child paths use managed artifact routing. Task filename prose is not an output declaration; for durable workflow handoff, return the child's outputReference, outputPathMapping, or artifactPaths.",
|
|
341
382
|
})),
|
|
342
383
|
outputMode: Type.Optional(OutputModeOverride),
|
|
343
384
|
skill: Type.Optional(SkillOverride),
|
|
344
|
-
model: Type.Optional(Type.String({ description: "Default child model override. Full provider/id values are accepted; bare ids resolve from the active registry." })),
|
|
385
|
+
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." })),
|
|
386
|
+
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." })),
|
|
345
387
|
outputSchema: Type.Optional(JsonSchemaObject),
|
|
346
388
|
agentContract: Type.Optional(AgentContractOverride),
|
|
347
389
|
acceptance: Type.Optional(AcceptanceOverride),
|
|
@@ -358,20 +400,20 @@ export function createSubagentParamsSchema(): typeof SubagentParams {
|
|
|
358
400
|
|
|
359
401
|
const SubagentWaitParamsSchema = Type.Object({
|
|
360
402
|
id: Type.Optional(Type.String({
|
|
361
|
-
description: "Async run or remembered detached foreground run id/prefix to wait for one specific run. Omit to wait across every active async run started in this session.",
|
|
403
|
+
description: "Async run or remembered detached foreground run id/prefix to wait for one specific run. Ordinary async subagent runs already notify this session natively; use bg_wait for provider, detached, or other background work without native notification, or when same-turn blocking results are truly needed. Omit to wait across every active async run started in this session only when a same-turn wait is truly needed.",
|
|
362
404
|
})),
|
|
363
405
|
nonBlocking: Type.Optional(Type.Boolean({
|
|
364
|
-
description: "When true, resolve id to one exact run, persist a wake subscription, and return immediately. The originating session is woken on completion, failure, attention, reconciliation failure, or timeout. Requires id and cannot be combined with all.",
|
|
406
|
+
description: "When true, resolve id to one exact run, persist a wake subscription, and return immediately. Use this only for provider, detached, or other background work without a native completion notification; ordinary async subagent runs already notify this session natively and do not need a subscription. The originating session is woken on completion, failure, attention, reconciliation failure, or timeout. Requires id and cannot be combined with all.",
|
|
365
407
|
})),
|
|
366
408
|
all: Type.Optional(Type.Boolean({
|
|
367
|
-
description: "Wait for ALL active runs to finish.
|
|
409
|
+
description: "Wait for ALL active runs to finish. Ordinary async subagent runs already notify this session natively; use all only when a same-turn result from tracked background work is truly needed. Default false: return when the first tracked run or provider item finishes or needs attention. Ignored when id targets a single run.",
|
|
368
410
|
})),
|
|
369
411
|
timeoutMs: Type.Optional(Type.Integer({
|
|
370
412
|
minimum: 1,
|
|
371
|
-
description: "Give up waiting after this many milliseconds (the runs keep going regardless). Defaults to 1800000 (30 minutes).",
|
|
413
|
+
description: "Give up waiting after this many milliseconds (the runs keep going regardless). Ordinary async subagent runs already notify this session natively; use a wait timeout only when same-turn results are truly needed for provider, detached, or other background work without native notification. Defaults to config waitTool.defaultTimeoutMs, then 1800000 (30 minutes). Window expiry is a non-error active-work result.",
|
|
372
414
|
})),
|
|
373
415
|
stopOnAttention: Type.Optional(Type.Boolean({
|
|
374
|
-
description: "
|
|
416
|
+
description: "For a blocking wait that is truly needed, stop when a run needs attention by default. Set false to keep waiting through idle or long-thinking attention; supervisor/contact requests still stop the wait.",
|
|
375
417
|
})),
|
|
376
418
|
});
|
|
377
419
|
|
|
@@ -5,62 +5,87 @@ 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.";
|
|
9
|
+
const AGENT_SELECTION_GUIDANCE = "Before execution, call { action: \"list\", capabilities: true } and run only executable, non-disabled agents; for external-cli rows, also require runner.available === true. This is a passive PATH/PATHEXT/X_OK lookup, not authentication, version, or launch proof; launch preflight remains authoritative.";
|
|
10
|
+
const WORKFLOW_RESUME_KEY_GUIDANCE = "Each workflow key identifies one result lane: use a new stable workflow key for every distinct retained resume pass; same-key calls are reused only when launch parameters are identical, and incompatible parameters are rejected.";
|
|
11
|
+
const WORKFLOW_OUTPUT_BINDING_GUIDANCE = "For durable workflow child files, set output on runs.run/runs.all; task filename prose is not an output declaration, and return the child's outputReference, outputPathMapping, or artifactPaths instead of inventing a literal path.";
|
|
12
|
+
const WORKFLOW_LANES_GUIDANCE = "For bounded parallel sequential chains, use runs.lanes([{key,stages:[{key,agent,task},{key,resume:'previous',task},...]}]); first stages run together, later stages sequence per lane, and the bounded board reports lane-local failures. Only an explicit structuredOutput.verdict === 'blocked' blocks a successful stage; reviewer prose is not parsed.";
|
|
13
|
+
const WORKFLOW_SCRIPT_PORTABILITY_GUIDANCE = "workflowScript rejects nested async function, arrow, and method helpers; use top-level await, plain helper functions that return runs.run(...), or explicit Promise chains instead.";
|
|
14
|
+
const WORKFLOW_RESOURCE_GUIDANCE = "For permission/policy-extension interoperability, use an extension-owned named resource such as {workflow:'review',args:{task:'...'}} or {workflow:'run-ci',args:{command:'npm test'}}. The host resolves the script and authority internally so policy can distinguish it from raw workflowScript/workflowScriptPath; args are bounded plain data, and do not combine workflow with agent, task, workflowScript, or workflowScriptPath.";
|
|
15
|
+
const WORKFLOW_HOST_GUIDANCE = "For permission-sensitive host calls, use an extension-owned resource such as {workflow:'run-ci',args:{command:'npm test'}}; raw workflowScript/workflowScriptPath have unknown resource provenance and cannot use runs.host. In a resource that grants it, await runs.host(key,{kind:'command',command,timeoutMs,output?,role?,provider?}). runs.host has no per-step cwd: commands and relative output paths use the workflow cwd; set cwd on the outer subagent request instead (for example, {cwd:'/path/to/worktree',workflowScript:'...'}), or put a trusted directory change in the command (for example, 'cd /path/to/worktree && npm test'). v1 supports only command steps; output is bounded and command failure fails the workflow.";
|
|
8
16
|
|
|
9
|
-
export const DEFAULT_SUBAGENT_TOOL_DESCRIPTION = `Delegate to configured subagents. For execution, omit action and use {agent, task?} for one child or
|
|
17
|
+
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, workflowScriptPath to load a script from the request cwd, or a named workflow resource for permission/policy-aware execution. ${WORKFLOW_RESOURCE_GUIDANCE} ${AGENT_SELECTION_GUIDANCE} 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. ${WORKFLOW_SCRIPT_PORTABILITY_GUIDANCE} ${WORKFLOW_LANES_GUIDANCE} ${WORKFLOW_HOST_GUIDANCE} ${EXTERNAL_CLI_RUNNER_GUIDANCE} Use action only for management/control. Use guide or the pi-subagents skill for advanced workflow details.`;
|
|
10
18
|
|
|
11
19
|
export const SUBAGENT_TOOL_PROMPT_SNIPPET = "Delegate to subagents; orchestrate in one workflowScript call.";
|
|
12
20
|
|
|
13
21
|
export const SUBAGENT_TOOL_PROMPT_GUIDELINES = [
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
"workflowScript
|
|
17
|
-
"
|
|
18
|
-
|
|
19
|
-
"Use guide or the pi-subagents skill for advanced scheduling, missions, steering, and retention.",
|
|
22
|
+
`Use subagent only when delegation is needed. ${AGENT_SELECTION_GUIDANCE}`,
|
|
23
|
+
'Omit action for execution; use { agent, task? } for one child. For multi-step or parallel work, make exactly one top-level { workflowScript, async: true } call and launch children only inside it. Use action only for management/control.',
|
|
24
|
+
"workflowScript rejects nested async function, arrow, and method helpers; use top-level await, plain helper functions, or explicit Promise chains.",
|
|
25
|
+
"Inside workflowScript, use runs.run/runs.all and await their results. runs.all returns an ordered array, not a key map; stored runs.run promises must later be observed with direct await, Promise.race, or Promise.all.",
|
|
26
|
+
'Keep one writer per cwd/worktree; isolate concurrent writers. For durable files, set output on runs.run/runs.all and return the child\'s outputReference, outputPathMapping, or artifactPaths. For advanced workflows, read the bundled pi-subagents skill or call { action: "guide", topic: "workflows" }.',
|
|
20
27
|
];
|
|
21
28
|
|
|
22
29
|
export const SUBAGENT_SAFETY_GUIDANCE = `SAFETY-CRITICAL SUBAGENT GUIDANCE:
|
|
23
|
-
•
|
|
30
|
+
• ${AGENT_SELECTION_GUIDANCE}
|
|
24
31
|
• Keep execution and management separate: omit action for structured single-child or workflowScript execution; use action only for management/control.
|
|
25
|
-
• Async/background runs are the normal default unless config sets asyncByDefault:false; set async:true explicitly when async behavior matters. Use async:false only when the parent must block until completion. Async mode still shows progress. Final reviews and gate checks stay async; needing a result is not a blocking reason. 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
|
|
32
|
+
• Async/background runs are the normal default unless config sets asyncByDefault:false; set async:true explicitly when async behavior matters. Use async:false only when the parent must block until completion. Async mode still shows progress. Final reviews and gate checks stay async; needing a result is not a blocking reason. After an async launch, continue independent work only until its next dependency barrier; consume the result before work that depends on it. Ordinary async subagents notify this session natively, so return control and do not call bg_wait merely to get a completion wake. Do not sleep or poll status just to wait; use bg_wait only for provider, detached, or other background work without a native notification when this turn must receive its result.
|
|
33
|
+
• ${WORKFLOW_RESUME_KEY_GUIDANCE}
|
|
34
|
+
• ${WORKFLOW_OUTPUT_BINDING_GUIDANCE}
|
|
35
|
+
• ${WORKFLOW_HOST_GUIDANCE}
|
|
26
36
|
• Ordinary child subagents are not orchestrators. Only explicitly configured fanout children may use the child-safe subagent tool, still bounded by depth/session limits.
|
|
27
37
|
• Oracle/advisor consultations should use supervisor dialogue for material unknowns when available; request one-shot only when desired.
|
|
28
38
|
• 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.
|
|
29
39
|
• 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.`;
|
|
30
40
|
|
|
31
|
-
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.
|
|
41
|
+
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.
|
|
42
|
+
|
|
43
|
+
${WORKFLOW_RESOURCE_GUIDANCE}
|
|
32
44
|
|
|
33
45
|
EXECUTION:
|
|
34
|
-
•
|
|
35
|
-
•
|
|
36
|
-
•
|
|
46
|
+
• ${EXTERNAL_CLI_RUNNER_GUIDANCE}
|
|
47
|
+
• ${AGENT_SELECTION_GUIDANCE}
|
|
48
|
+
• 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.
|
|
49
|
+
• 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.
|
|
50
|
+
• 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. Set baseRef to a safe Git ref (default HEAD) to choose the managed worktree starting commit; the source checkout must still be clean. 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.
|
|
51
|
+
• ${WORKFLOW_LANES_GUIDANCE}
|
|
52
|
+
• 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.
|
|
37
53
|
• 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" }
|
|
38
54
|
• 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}" }
|
|
39
|
-
• 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.
|
|
55
|
+
• 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.
|
|
40
56
|
• 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}.
|
|
41
57
|
|
|
42
58
|
MANAGEMENT / CONTROL (use action; omit execution fields):
|
|
43
|
-
• 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.
|
|
59
|
+
• 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, worktree.cleanup (plan-only), lane.status, lane.recordMerge, lane.recordSupersession, 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.
|
|
44
60
|
• 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.
|
|
45
|
-
• Create durable project schedules with { action:"schedule.create", id?, name?, at:"+10m" | ISO, workflowScript:"return runs.run('main', {agent:'worker', task:'...'})" } or
|
|
61
|
+
• Create durable project schedules with { action:"schedule.create", id?, name?, sessionOnly?:true, at:"+10m" | ISO, baseRef?, workflowScript:"return runs.run('main', {agent:'worker', task:'...'})" }, or use workflowScriptPath instead. An optional baseRef selects the safe Git ref used by managed worktrees (default HEAD); the source checkout must still be clean. With sessionOnly:true, the schedule records the creating session file and only that session can restore or execute it; omitted/false preserves project-wide behavior. 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.
|
|
46
62
|
|
|
47
63
|
${SUBAGENT_SAFETY_GUIDANCE}`;
|
|
48
64
|
|
|
49
|
-
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.
|
|
65
|
+
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.
|
|
66
|
+
|
|
67
|
+
${WORKFLOW_RESOURCE_GUIDANCE}
|
|
50
68
|
|
|
51
69
|
EXECUTE:
|
|
52
|
-
•
|
|
53
|
-
•
|
|
54
|
-
•
|
|
70
|
+
• ${EXTERNAL_CLI_RUNNER_GUIDANCE}
|
|
71
|
+
• ${AGENT_SELECTION_GUIDANCE}
|
|
72
|
+
• 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.
|
|
73
|
+
• SINGLE {agent:"worker",task:"..."} starts exactly one direct child. Fields apply to that child. Do not combine agent/task with action, workflowScript, or workflowScriptPath.
|
|
74
|
+
• 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; set baseRef to a safe Git ref (default HEAD) to choose the managed worktree starting commit. The source checkout must still be clean. 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.
|
|
75
|
+
• ${WORKFLOW_LANES_GUIDANCE}
|
|
76
|
+
• 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.
|
|
55
77
|
• 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]"}
|
|
56
|
-
• 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.
|
|
78
|
+
• 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.
|
|
57
79
|
|
|
58
80
|
MANAGE / CONTROL:
|
|
59
|
-
• 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.
|
|
81
|
+
• Use action without execution fields for list/get/models/guide/authoring, refine/refine.show/refine.rollback, mission, watchdog, status, interrupt, stop, resume, steer, worktree.cleanup (mode:'plan' only), script-only scheduling, diagnostics, and other management actions. guide reads shipped current-version docs by topic.
|
|
60
82
|
• 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}.
|
|
61
83
|
|
|
62
84
|
ASYNC / SAFETY:
|
|
63
|
-
• Omitted async follows asyncByDefault config; set async:true explicitly when async behavior matters. 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
|
|
85
|
+
• Omitted async follows asyncByDefault config; set async:true explicitly when async behavior matters. Continue independent work only until its next dependency barrier; consume the result before work that depends on it. Ordinary async subagents notify this session natively, so return control and do not call bg_wait merely to get a completion wake. Do not sleep or poll merely to wait; use bg_wait only for provider, detached, or other background work without a native notification when this turn must receive its result.
|
|
86
|
+
• ${WORKFLOW_RESUME_KEY_GUIDANCE}
|
|
87
|
+
• ${WORKFLOW_OUTPUT_BINDING_GUIDANCE}
|
|
88
|
+
• ${WORKFLOW_HOST_GUIDANCE}
|
|
64
89
|
• Ordinary children are not orchestrators. Keep one writer per cwd/worktree and use fresh read-only reviewers for independent checks.
|
|
65
90
|
• Oracle/advisor consultations use available supervisor dialogue for material unknowns; request one-shot when desired.
|
|
66
91
|
• Status and artifacts live under asyncId/asyncDir with status.json, events.jsonl, output logs, and {action:"status",id:"..."}.`;
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import type { AgentToolResult } from "@earendil-works/pi-agent-core";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Convert pi-subagents' internal logical-error result into the rejection Pi's
|
|
5
|
+
* public tool boundary uses to emit a canonical errored ToolResult.
|
|
6
|
+
*
|
|
7
|
+
* Keep this at registered tool boundaries. Internal workflows intentionally
|
|
8
|
+
* retain their return-based error handling.
|
|
9
|
+
*/
|
|
10
|
+
export function finalizeToolResult<T>(result: AgentToolResult<T>): AgentToolResult<T> {
|
|
11
|
+
if (result.isError !== true) return result;
|
|
12
|
+
|
|
13
|
+
const message = result.content
|
|
14
|
+
.flatMap((item) => item.type === "text" && typeof item.text === "string" ? [item.text] : [])
|
|
15
|
+
.join("\n")
|
|
16
|
+
.trim();
|
|
17
|
+
|
|
18
|
+
throw new Error(message || "pi-subagents reported a logical tool failure.");
|
|
19
|
+
}
|
|
@@ -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",
|
|
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);
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { spawn
|
|
1
|
+
import { spawn } from "node:child_process";
|
|
2
2
|
|
|
3
3
|
export type HerdrErrorCode =
|
|
4
4
|
| "HERDR_UNAVAILABLE"
|
|
@@ -16,7 +16,7 @@ export interface HerdrClient {
|
|
|
16
16
|
run<T = unknown>(args: string[], options?: { timeoutMs?: number; signal?: AbortSignal; textOk?: boolean }): Promise<HerdrResult<T>>;
|
|
17
17
|
}
|
|
18
18
|
|
|
19
|
-
type SpawnHerdr = (command: string, args: readonly string[], options: { shell: false; windowsHide: true; env: NodeJS.ProcessEnv }) =>
|
|
19
|
+
type SpawnHerdr = (command: string, args: readonly string[], options: { shell: false; windowsHide: true; env: NodeJS.ProcessEnv }) => ReturnType<typeof spawn>;
|
|
20
20
|
|
|
21
21
|
function error(code: HerdrErrorCode, message: string, details?: unknown): HerdrResult<never> {
|
|
22
22
|
return { ok: false, error: { code, message, ...(details !== undefined ? { details } : {}) } };
|
|
@@ -46,7 +46,7 @@ export function createHerdrClient(options: { bin?: string; spawn?: SpawnHerdr }
|
|
|
46
46
|
return {
|
|
47
47
|
run<T>(args: string[], runOptions: { timeoutMs?: number; signal?: AbortSignal; textOk?: boolean } = {}): Promise<HerdrResult<T>> {
|
|
48
48
|
return new Promise((resolve) => {
|
|
49
|
-
let child:
|
|
49
|
+
let child: ReturnType<typeof spawn>;
|
|
50
50
|
try {
|
|
51
51
|
child = spawnImpl(bin, args, { shell: false, windowsHide: true, env: process.env });
|
|
52
52
|
} catch (cause) {
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import type { HerdrClient, HerdrErrorCode } from "./client.ts";
|
|
2
|
+
|
|
3
|
+
export type HerdrFocusErrorCode = HerdrErrorCode | "PANE_FOCUS_UNSUPPORTED" | "INVALID_PANE_RESPONSE";
|
|
4
|
+
|
|
5
|
+
export type HerdrPaneFocusResult =
|
|
6
|
+
| { ok: true; data: { paneId: string; tabId?: string; workspaceId?: string } }
|
|
7
|
+
| { ok: false; error: { code: HerdrFocusErrorCode; message: string; details?: unknown } };
|
|
8
|
+
|
|
9
|
+
export function herdrPaneRecord(value: unknown): Record<string, unknown> | undefined {
|
|
10
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return undefined;
|
|
11
|
+
const record = value as Record<string, unknown>;
|
|
12
|
+
return record.pane && typeof record.pane === "object" && !Array.isArray(record.pane)
|
|
13
|
+
? record.pane as Record<string, unknown>
|
|
14
|
+
: record;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
function text(record: Record<string, unknown>, ...keys: string[]): string | undefined {
|
|
18
|
+
for (const key of keys) if (typeof record[key] === "string" && record[key]) return record[key] as string;
|
|
19
|
+
return undefined;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function herdrPaneFocusTarget(value: unknown): { paneId?: string; tabId?: string; workspaceId?: string } {
|
|
23
|
+
const pane = herdrPaneRecord(value);
|
|
24
|
+
if (!pane) return {};
|
|
25
|
+
return {
|
|
26
|
+
paneId: text(pane, "pane_id", "paneId", "id"),
|
|
27
|
+
tabId: text(pane, "tab_id", "tabId"),
|
|
28
|
+
workspaceId: text(pane, "workspace_id", "workspaceId"),
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export async function focusHerdrPane(client: HerdrClient, paneId: string, signal?: AbortSignal): Promise<HerdrPaneFocusResult> {
|
|
33
|
+
const live = await client.run(["pane", "get", paneId], { timeoutMs: 5_000, signal });
|
|
34
|
+
if (live.ok === false) return live;
|
|
35
|
+
const target = herdrPaneFocusTarget(live.data);
|
|
36
|
+
if (!target.paneId) {
|
|
37
|
+
return { ok: false, error: { code: "INVALID_PANE_RESPONSE", message: `Herdr pane get returned no pane id for '${paneId}'.`, details: live.data } };
|
|
38
|
+
}
|
|
39
|
+
if (target.tabId) {
|
|
40
|
+
const focused = await client.run(["tab", "focus", target.tabId], { timeoutMs: 5_000, signal });
|
|
41
|
+
return focused.ok ? { ok: true, data: { paneId: target.paneId, tabId: target.tabId, ...(target.workspaceId ? { workspaceId: target.workspaceId } : {}) } } : focused;
|
|
42
|
+
}
|
|
43
|
+
if (target.workspaceId) {
|
|
44
|
+
const focused = await client.run(["workspace", "focus", target.workspaceId], { timeoutMs: 5_000, signal });
|
|
45
|
+
return focused.ok ? { ok: true, data: { paneId: target.paneId, workspaceId: target.workspaceId } } : focused;
|
|
46
|
+
}
|
|
47
|
+
return {
|
|
48
|
+
ok: false,
|
|
49
|
+
error: {
|
|
50
|
+
code: "PANE_FOCUS_UNSUPPORTED",
|
|
51
|
+
message: `Herdr pane '${paneId}' has no tab_id or workspace_id. Select it in Herdr manually, or upgrade Herdr focus support.`,
|
|
52
|
+
details: live.data,
|
|
53
|
+
},
|
|
54
|
+
};
|
|
55
|
+
}
|
|
@@ -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;
|
|
@@ -40,7 +41,8 @@ export function formatInspectorDashboard(input: { status: AsyncStatus; asyncDir:
|
|
|
40
41
|
lines.push("");
|
|
41
42
|
}
|
|
42
43
|
lines.push(formatAsyncRunTranscript(status, asyncDir, { index: input.index, lines: 60, sessionRoots: input.sessionRoots }));
|
|
43
|
-
const
|
|
44
|
+
const acceptsPlainGuidance = input.index !== undefined || status.mode === "single";
|
|
45
|
+
const controls = [input.allowSteer === false || !acceptsPlainGuidance ? undefined : "type guidance", input.allowSteer === false ? undefined : "steer <message>", input.allowStop === false ? undefined : "stop", "status"].filter(Boolean);
|
|
44
46
|
lines.push("", `Controls: ${controls.join(" | ")}`, "Supervisor replies remain in the parent Pi session (subagent_supervisor/intercom).");
|
|
45
47
|
return lines.join("\n");
|
|
46
48
|
}
|
|
@@ -60,16 +62,7 @@ function parseArgs(argv: string[]): RunnerOptions {
|
|
|
60
62
|
const childIndex = indexRaw === undefined ? undefined : Number(indexRaw);
|
|
61
63
|
if (childIndex !== undefined && (!Number.isInteger(childIndex) || childIndex < 0)) throw new Error("--index must be a non-negative integer.");
|
|
62
64
|
const sessionRootsRaw = values.get("--session-roots");
|
|
63
|
-
|
|
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
|
-
}
|
|
65
|
+
const sessionRoots = sessionRootsRaw === undefined ? [] : decodeSessionRoots(sessionRootsRaw);
|
|
73
66
|
const refreshRaw = values.get("--refresh-ms");
|
|
74
67
|
const refreshMs = refreshRaw === undefined ? 1_500 : Number(refreshRaw);
|
|
75
68
|
if (!Number.isInteger(refreshMs) || refreshMs < 250) throw new Error("--refresh-ms must be an integer >= 250.");
|
|
@@ -89,6 +82,20 @@ function isTerminal(status: AsyncStatus): boolean {
|
|
|
89
82
|
return status.state !== "queued" && status.state !== "running";
|
|
90
83
|
}
|
|
91
84
|
|
|
85
|
+
function queueInspectorSteer(options: RunnerOptions, status: AsyncStatus, message: string): string {
|
|
86
|
+
if (options.allowSteer === false) throw new Error("Authority policy does not allow steer from this inspector.");
|
|
87
|
+
if (isTerminal(status)) throw new Error(`Run '${options.runId}' is ${status.state} and cannot be steered.`);
|
|
88
|
+
const runningIndexes = (status.steps ?? []).map((step, index) => step.status === "running" ? index : undefined).filter((index): index is number => index !== undefined);
|
|
89
|
+
const targetIndex = options.index ?? (status.mode === "single" ? 0 : undefined);
|
|
90
|
+
if (targetIndex === undefined && runningIndexes.length === 0) throw new Error("No running child is available to steer. Open a child-specific inspector for a pending child.");
|
|
91
|
+
requestAsyncSteer(options.asyncDir, {
|
|
92
|
+
message,
|
|
93
|
+
...(targetIndex !== undefined ? { targetIndex } : { targetIndexes: runningIndexes }),
|
|
94
|
+
source: "herdr-inspector",
|
|
95
|
+
});
|
|
96
|
+
return steeringReceipt(message, `Steering queued for run ${options.runId}.`);
|
|
97
|
+
}
|
|
98
|
+
|
|
92
99
|
export function submitInspectorControl(options: RunnerOptions, line: string): string {
|
|
93
100
|
const command = line.trim();
|
|
94
101
|
if (!command || command === "status") return "Status refreshed.";
|
|
@@ -101,22 +108,13 @@ export function submitInspectorControl(options: RunnerOptions, line: string): st
|
|
|
101
108
|
return `Stop requested for run ${options.runId}.`;
|
|
102
109
|
}
|
|
103
110
|
if (command.startsWith("steer ")) {
|
|
104
|
-
if (options.allowSteer === false) throw new Error("Authority policy does not allow steer from this inspector.");
|
|
105
111
|
const message = command.slice("steer ".length).trim();
|
|
106
112
|
if (!message) throw new Error("steer requires a message.");
|
|
107
|
-
|
|
108
|
-
const runningIndexes = (status.steps ?? []).map((step, index) => step.status === "running" ? index : undefined).filter((index): index is number => index !== undefined);
|
|
109
|
-
const targetIndex = options.index ?? (status.mode === "single" ? 0 : undefined);
|
|
110
|
-
if (targetIndex === undefined && runningIndexes.length === 0) throw new Error("No running child is available to steer. Open a child-specific inspector for a pending child.");
|
|
111
|
-
requestAsyncSteer(options.asyncDir, {
|
|
112
|
-
message,
|
|
113
|
-
...(targetIndex !== undefined ? { targetIndex } : { targetIndexes: runningIndexes }),
|
|
114
|
-
source: "herdr-inspector",
|
|
115
|
-
});
|
|
116
|
-
return steeringReceipt(message, `Steering queued for run ${options.runId}.`);
|
|
113
|
+
return queueInspectorSteer(options, status, message);
|
|
117
114
|
}
|
|
118
115
|
if (command.startsWith("reply ")) throw new Error("Supervisor replies are owned by the parent Pi session; use subagent_supervisor/intercom there.");
|
|
119
|
-
throw new Error("
|
|
116
|
+
if (options.index === undefined && status.mode !== "single") throw new Error("Plain guidance requires a child-specific inspector. Use steer <message> to target all running children from the aggregate inspector.");
|
|
117
|
+
return queueInspectorSteer(options, status, command);
|
|
120
118
|
}
|
|
121
119
|
|
|
122
120
|
export function runInspector(argv = process.argv.slice(2)): void {
|