pi-subagents 0.56.0 → 0.57.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 +53 -0
- 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/docs/agents.md +111 -15
- package/docs/configuration.md +37 -0
- package/docs/extension-api.md +2 -2
- package/docs/observability.md +8 -7
- package/docs/tool-reference.md +11 -1
- package/docs/workflows.md +20 -0
- package/package.json +1 -1
- package/skills/pi-subagents/references/execution-controls.md +1 -1
- package/src/agents/agent-management.ts +13 -5
- package/src/agents/agent-refinements.ts +4 -4
- package/src/agents/agents.ts +219 -48
- package/src/agents/builtin-names.ts +6 -0
- package/src/agents/runtime-agent-registry.ts +8 -2
- package/src/api/preflight.ts +2 -2
- package/src/extension/config.ts +70 -0
- package/src/extension/doctor.ts +3 -3
- package/src/extension/index.ts +18 -4
- package/src/extension/public-execution.ts +29 -13
- package/src/extension/rpc.ts +20 -5
- package/src/extension/schemas.ts +4 -3
- package/src/extension/tool-description.ts +11 -9
- package/src/inspectors/herdr/actions.ts +2 -1
- package/src/inspectors/herdr/inspector-runner.ts +2 -10
- package/src/inspectors/herdr/session-roots-codec.ts +42 -0
- package/src/integrations/herdr-status.ts +46 -3
- package/src/runs/background/active-async-capacity.ts +77 -10
- package/src/runs/background/async-execution.ts +100 -9
- package/src/runs/background/async-job-tracker.ts +5 -0
- package/src/runs/background/async-retention.ts +20 -3
- package/src/runs/background/async-status.ts +5 -0
- package/src/runs/background/chain-root-attachment.ts +15 -1
- package/src/runs/background/fleet-view.ts +16 -10
- package/src/runs/background/inspect-rpc.ts +8 -8
- package/src/runs/background/result-files.ts +27 -14
- package/src/runs/background/result-watcher.ts +9 -5
- package/src/runs/background/run-status.ts +33 -6
- package/src/runs/background/scheduled-runs.ts +7 -1
- package/src/runs/background/subagent-runner.ts +177 -44
- package/src/runs/background/wait-completions.ts +4 -0
- package/src/runs/foreground/execution.ts +72 -10
- package/src/runs/foreground/foreground-control.ts +6 -0
- package/src/runs/foreground/foreground-history.ts +22 -1
- package/src/runs/foreground/subagent-executor.ts +270 -81
- package/src/runs/foreground/workflow-detach-reconcile.ts +16 -1
- package/src/runs/shared/child-protocol.ts +21 -7
- package/src/runs/shared/claude-code-adapter.ts +129 -0
- package/src/runs/shared/codex-exec-adapter.ts +129 -0
- package/src/runs/shared/cursor-agent-adapter.ts +114 -0
- package/src/runs/shared/external-cli-contract.ts +167 -0
- package/src/runs/shared/external-cli-preflight.ts +122 -0
- package/src/runs/shared/external-cli-runner.ts +348 -55
- package/src/runs/shared/model-exclusions.ts +57 -7
- package/src/runs/shared/model-fallback.ts +23 -1
- package/src/runs/shared/mutation-evidence.ts +7 -2
- package/src/runs/shared/nested-events.ts +3 -1
- package/src/runs/shared/nested-render.ts +2 -2
- package/src/runs/shared/process-signal.ts +13 -0
- package/src/runs/shared/run-history.ts +21 -1
- package/src/shared/fork-context.ts +21 -0
- package/src/shared/formatters.ts +7 -1
- 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 +10 -2
- package/src/shared/shortcuts.ts +17 -0
- package/src/shared/types.ts +118 -9
- package/src/shared/workflow-child-permit.ts +116 -0
- package/src/slash/delegation-adapters.ts +0 -1
- package/src/slash/slash-commands.ts +8 -6
- package/src/tui/fleet-status.ts +27 -10
- package/src/tui/fleet-transcript.ts +11 -5
- package/src/tui/fleet.ts +28 -13
- package/src/tui/render.ts +47 -21
- package/src/workflows/scripted-workflow.ts +248 -27
- package/src/workflows/workflow-child-summary.ts +117 -0
- package/src/workflows/workflow-receipt.ts +119 -4
package/src/extension/index.ts
CHANGED
|
@@ -9,7 +9,7 @@
|
|
|
9
9
|
* Toggle: async parameter (default: true; set asyncByDefault:false in config.json to opt out)
|
|
10
10
|
*
|
|
11
11
|
* Config file: ~/.pi/agent/extensions/subagent/config.json
|
|
12
|
-
* { "asyncByDefault": true, "defaultSubagentContext": "fork", "forceTopLevelAsync": true, "maxSubagentDepth": 1, "intercomBridge": { "mode": "always", "instructionFile": "./intercom-bridge.md" }, "worktreeSetupHook": "./scripts/setup-worktree.mjs" }
|
|
12
|
+
* { "asyncByDefault": true, "defaultSubagentContext": "fork", "forkContext": { "mode": "pruned", "model": "provider/model" }, "forceTopLevelAsync": true, "maxSubagentDepth": 1, "intercomBridge": { "mode": "always", "instructionFile": "./intercom-bridge.md" }, "worktreeSetupHook": "./scripts/setup-worktree.mjs" }
|
|
13
13
|
*/
|
|
14
14
|
|
|
15
15
|
import { randomUUID } from "node:crypto";
|
|
@@ -24,6 +24,7 @@ import { clearRuntimeAgentsForPi, listRuntimeAgentConfigs, mergeRuntimeAgents }
|
|
|
24
24
|
import { ensureAccessibleDir } from "../shared/accessible-dir.ts";
|
|
25
25
|
import { cleanupAllArtifactDirs, cleanupOldArtifacts, getArtifactsDir } from "../shared/artifacts.ts";
|
|
26
26
|
import { resolveCurrentSessionId } from "../shared/session-identity.ts";
|
|
27
|
+
import { getAgentDir } from "../shared/utils.ts";
|
|
27
28
|
import { currentCompletionOwnerId } from "../shared/completion-owner.ts";
|
|
28
29
|
import { cleanupOldChainDirs } from "../shared/settings.ts";
|
|
29
30
|
import { clearLegacyResultAnimationTimer, renderSubagentResult, renderSubagentSummary } from "../tui/render.ts";
|
|
@@ -32,7 +33,7 @@ import { SubagentFleetStatus, resolveFleetViewPlacement } from "../tui/fleet-sta
|
|
|
32
33
|
import { createSubagentParamsSchema } from "./schemas.ts";
|
|
33
34
|
import { createSubagentExecutor, type SubagentParamsLike } from "../runs/foreground/subagent-executor.ts";
|
|
34
35
|
import { createAsyncJobTracker } from "../runs/background/async-job-tracker.ts";
|
|
35
|
-
import { getActiveAsyncCapacitySnapshot, resolveMaxActiveAsyncRunsPerSession } from "../runs/background/active-async-capacity.ts";
|
|
36
|
+
import { getActiveAsyncCapacitySnapshot, resolveAbandonedSlotReleaseAfterMs, resolveMaxActiveAsyncRunsPerSession } from "../runs/background/active-async-capacity.ts";
|
|
36
37
|
import { cleanupResultIndexes, missionObserverResultCandidateFiles } from "../runs/background/result-files.ts";
|
|
37
38
|
import { ASYNC_RETENTION_DELAY_MS, cleanupAsyncRetention } from "../runs/background/async-retention.ts";
|
|
38
39
|
import { createResultWatcher } from "../runs/background/result-watcher.ts";
|
|
@@ -56,7 +57,7 @@ import { formatSteeringNotice, handleSubagentSteeringNotice, SUBAGENT_STEERING_M
|
|
|
56
57
|
import { SUBAGENT_CHILD_ENV, SUBAGENT_PARENT_SESSION_ENV } from "../runs/shared/pi-args.ts";
|
|
57
58
|
import { resolveCurrentSubagentCapabilityCeiling } from "../runs/shared/capability-ceiling.ts";
|
|
58
59
|
import { formatDuration, shortenPath } from "../shared/formatters.ts";
|
|
59
|
-
import { loadConfig, resolveAsyncByDefault, resolveScheduledStoreRoot } from "./config.ts";
|
|
60
|
+
import { applyModelExclusionsConfig, loadConfig, resolveAsyncByDefault, resolveScheduledStoreRoot } from "./config.ts";
|
|
60
61
|
import { buildSubagentToolDescription, buildSubagentToolPromptMetadata } from "./tool-description.ts";
|
|
61
62
|
import { finalizeToolResult } from "./tool-result.ts";
|
|
62
63
|
import { collectGoalContinuationNotices } from "../missions/goal-driver.ts";
|
|
@@ -382,9 +383,13 @@ export function projectActiveHerdrRuns(state: SubagentState): HerdrStatusRun[] {
|
|
|
382
383
|
.filter((job) => active(job.status))
|
|
383
384
|
.map((job) => {
|
|
384
385
|
const children = job.mode === "workflow" ? foregroundChildrenByWorkflow.get(job.asyncId) : undefined;
|
|
386
|
+
const currentStep = job.steps?.find((step) => step.status === "running")
|
|
387
|
+
?? (job.currentStep !== undefined ? job.steps?.[job.currentStep] : undefined)
|
|
388
|
+
?? job.steps?.find((step) => step.status === "pending");
|
|
385
389
|
return {
|
|
386
390
|
id: job.asyncId,
|
|
387
391
|
agents: children?.length ? children.map((child) => child.agent) : job.agents,
|
|
392
|
+
...(currentStep?.label ? { taskLabel: currentStep.label } : {}),
|
|
388
393
|
needsAttention: job.activityState === "needs_attention" || children?.some((child) => child.needsAttention),
|
|
389
394
|
};
|
|
390
395
|
});
|
|
@@ -401,6 +406,8 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
|
|
|
401
406
|
cleanupOldChainDirs();
|
|
402
407
|
|
|
403
408
|
const config = loadConfig();
|
|
409
|
+
// Apply the process-wide exclusion TTL before any child launch can record a model failure.
|
|
410
|
+
applyModelExclusionsConfig(config);
|
|
404
411
|
const waitToolConfig = resolveWaitToolConfig(config.waitTool);
|
|
405
412
|
const asyncByDefault = resolveAsyncByDefault(config);
|
|
406
413
|
const fleetViewEnabled = config.fleetView !== false;
|
|
@@ -695,6 +702,12 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
|
|
|
695
702
|
0,
|
|
696
703
|
0,
|
|
697
704
|
);
|
|
705
|
+
if (args.workflowScriptPath)
|
|
706
|
+
return new Text(
|
|
707
|
+
`${title}${gap}${theme.fg("accent", args.workflowScriptPath)}${args.async === true ? `${gap}${theme.fg("warning", "[async]")}` : ""}`,
|
|
708
|
+
0,
|
|
709
|
+
0,
|
|
710
|
+
);
|
|
698
711
|
const asyncLabel = args.async === true ? `${gap}${theme.fg("warning", "[async]")}` : "";
|
|
699
712
|
return new Text(
|
|
700
713
|
`${title}${gap}${theme.fg("accent", args.agent || "?")}${asyncLabel}`,
|
|
@@ -836,7 +849,7 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
|
|
|
836
849
|
state.activeAsyncCapacity = getActiveAsyncCapacitySnapshot(
|
|
837
850
|
state.currentSessionId,
|
|
838
851
|
resolveMaxActiveAsyncRunsPerSession(config.maxActiveAsyncRunsPerSession),
|
|
839
|
-
{ liveWorkflowRunIds: new Set(state.workflowControllers?.keys() ?? []) },
|
|
852
|
+
{ liveWorkflowRunIds: new Set(state.workflowControllers?.keys() ?? []), abandonedSlotReleaseAfterMs: resolveAbandonedSlotReleaseAfterMs(config.capacity?.abandonedSlotReleaseAfterMs) },
|
|
840
853
|
);
|
|
841
854
|
};
|
|
842
855
|
|
|
@@ -846,6 +859,7 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
|
|
|
846
859
|
goalTurnId = 0;
|
|
847
860
|
state.currentSessionId = resolveCurrentSessionId(ctx.sessionManager);
|
|
848
861
|
state.parentSessionFile = ctx.sessionManager.getSessionFile();
|
|
862
|
+
state.trustedSessionFileRoot = state.parentSessionFile ? path.join(getAgentDir(), "sessions") : undefined;
|
|
849
863
|
state.trustedSessionRoots = [...new Set([
|
|
850
864
|
...(config.defaultSessionDir ? [path.resolve(expandTilde(config.defaultSessionDir))] : []),
|
|
851
865
|
...(state.parentSessionFile ? [getSubagentSessionRoot(state.parentSessionFile)] : []),
|
|
@@ -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:
|
|
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:
|
|
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:
|
|
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:
|
|
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 (
|
|
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 (
|
|
103
|
-
return { ok: false, error: "
|
|
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 (
|
|
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 (
|
|
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
|
}
|
package/src/extension/rpc.ts
CHANGED
|
@@ -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:
|
|
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):
|
|
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
|
-
|
|
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
|
}
|
package/src/extension/schemas.ts
CHANGED
|
@@ -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
|
|
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
|
|
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({
|
|
@@ -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." })),
|
|
@@ -6,7 +6,7 @@ import { getAgentDir, getProjectConfigDir } from "../shared/utils.ts";
|
|
|
6
6
|
const CUSTOM_TOOL_DESCRIPTION_FILE = "subagent-tool-description.md";
|
|
7
7
|
const CUSTOM_TOOL_DESCRIPTION_MAX_BYTES = 50 * 1024;
|
|
8
8
|
|
|
9
|
-
export const DEFAULT_SUBAGENT_TOOL_DESCRIPTION = `Delegate to configured subagents. For execution, omit action and use {agent, task?} for one child
|
|
9
|
+
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. Use action only for management/control. Use guide or the pi-subagents skill for advanced workflow details.`;
|
|
10
10
|
|
|
11
11
|
export const SUBAGENT_TOOL_PROMPT_SNIPPET = "Delegate to subagents; orchestrate in one workflowScript call.";
|
|
12
12
|
|
|
@@ -29,34 +29,36 @@ export const SUBAGENT_SAFETY_GUIDANCE = `SAFETY-CRITICAL SUBAGENT GUIDANCE:
|
|
|
29
29
|
• 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
30
|
• 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
31
|
|
|
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.
|
|
32
|
+
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
33
|
|
|
34
34
|
EXECUTION:
|
|
35
35
|
• Before executing, use { action: "list" } and run only executable/non-disabled configured agents.
|
|
36
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
|
|
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, workflowScript, or workflowScriptPath.
|
|
38
38
|
• 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.
|
|
39
|
+
• 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
40
|
• 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
41
|
• 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.
|
|
42
|
+
• 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
43
|
• 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
44
|
|
|
44
45
|
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.
|
|
46
|
+
• 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
47
|
• 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
|
|
48
|
+
• 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
49
|
|
|
49
50
|
${SUBAGENT_SAFETY_GUIDANCE}`;
|
|
50
51
|
|
|
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.
|
|
52
|
+
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
53
|
|
|
53
54
|
EXECUTE:
|
|
54
55
|
• Call { action:"list" } first and use only executable/non-disabled agents.
|
|
55
56
|
• 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
|
|
57
|
+
• 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
58
|
• 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.
|
|
59
|
+
• 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
60
|
• 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.
|
|
61
|
+
• 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
62
|
|
|
61
63
|
MANAGE / CONTROL:
|
|
62
64
|
• 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",
|
|
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
|
-
|
|
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
|
}
|
|
@@ -61,12 +68,42 @@ function isRecord(value: unknown): value is Record<string, unknown> {
|
|
|
61
68
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
62
69
|
}
|
|
63
70
|
|
|
71
|
+
function boundedTaskLabel(value: unknown, maxChars = MAX_TASK_LABEL_CHARS): string | undefined {
|
|
72
|
+
if (typeof value !== "string") return undefined;
|
|
73
|
+
const normalized = sanitizeDisplayText(value).trim();
|
|
74
|
+
if (!normalized) return undefined;
|
|
75
|
+
return previewDisplayText(normalized, maxChars);
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function workflowTaskLabel(data: Record<string, unknown>): string | undefined {
|
|
79
|
+
const explicit = boundedTaskLabel(data.taskLabel);
|
|
80
|
+
if (explicit) return explicit;
|
|
81
|
+
if (!isRecord(data.workflowGraph) || !Array.isArray(data.workflowGraph.nodes)) return undefined;
|
|
82
|
+
const currentNodeId = typeof data.workflowGraph.currentNodeId === "string" ? data.workflowGraph.currentNodeId : undefined;
|
|
83
|
+
const nodes: Record<string, unknown>[] = [];
|
|
84
|
+
const collect = (values: unknown[], depth: number): void => {
|
|
85
|
+
if (depth > MAX_WORKFLOW_LABEL_DEPTH || nodes.length >= MAX_WORKFLOW_LABEL_NODES) return;
|
|
86
|
+
for (const value of values) {
|
|
87
|
+
if (nodes.length >= MAX_WORKFLOW_LABEL_NODES) return;
|
|
88
|
+
if (!isRecord(value)) continue;
|
|
89
|
+
nodes.push(value);
|
|
90
|
+
if (Array.isArray(value.children)) collect(value.children, depth + 1);
|
|
91
|
+
}
|
|
92
|
+
};
|
|
93
|
+
collect(data.workflowGraph.nodes, 0);
|
|
94
|
+
const current = currentNodeId ? nodes.find((node) => node.id === currentNodeId) : undefined;
|
|
95
|
+
const active = current ?? nodes.find((node) => node.status === "running") ?? nodes.find((node) => node.status === "pending");
|
|
96
|
+
return boundedTaskLabel(active?.label);
|
|
97
|
+
}
|
|
98
|
+
|
|
64
99
|
function startedRun(data: unknown): HerdrStatusRun | undefined {
|
|
65
100
|
if (!isRecord(data) || typeof data.id !== "string" || !data.id) return undefined;
|
|
101
|
+
const taskLabel = workflowTaskLabel(data);
|
|
66
102
|
return {
|
|
67
103
|
id: data.id,
|
|
68
104
|
...(typeof data.agent === "string" ? { agent: data.agent } : {}),
|
|
69
105
|
...(Array.isArray(data.agents) && data.agents.every((agent) => typeof agent === "string") ? { agents: data.agents as string[] } : {}),
|
|
106
|
+
...(taskLabel ? { taskLabel } : {}),
|
|
70
107
|
};
|
|
71
108
|
}
|
|
72
109
|
|
|
@@ -113,6 +150,7 @@ export function registerHerdrStatusBridge(options: HerdrStatusBridgeOptions): He
|
|
|
113
150
|
|
|
114
151
|
const activeAgentNames = (): string[] => [...new Set([...runs.values()].flatMap((run) => run.agents?.length ? run.agents : run.agent ? [run.agent] : []))];
|
|
115
152
|
const activeSubagentCount = (): number => [...runs.values()].reduce((total, run) => total + Math.max(1, run.agents?.length ?? (run.agent ? 1 : 0)), 0);
|
|
153
|
+
const activeTaskLabel = (): string | undefined => [...runs.values()].reverse().find((run) => run.taskLabel)?.taskLabel;
|
|
116
154
|
|
|
117
155
|
const label = (includeAttention = false): string => {
|
|
118
156
|
const agents = activeAgentNames();
|
|
@@ -122,15 +160,18 @@ export function registerHerdrStatusBridge(options: HerdrStatusBridgeOptions): He
|
|
|
122
160
|
: "";
|
|
123
161
|
const panes = Math.max(0, options.getProjectPaneCount?.() ?? 0);
|
|
124
162
|
const paneText = panes > 0 ? ` · ${panes} pane${panes === 1 ? "" : "s"}` : "";
|
|
163
|
+
const task = activeTaskLabel();
|
|
164
|
+
const taskText = task ? ` · ${task}` : "";
|
|
125
165
|
const attention = includeAttention && attentionLabels.size > 0 ? " ⚠" : "";
|
|
126
|
-
return `⏳ ${activeCount} subagent${activeCount === 1 ? "" : "s"}${who}${paneText}${attention}`;
|
|
166
|
+
return `⏳ ${activeCount} subagent${activeCount === 1 ? "" : "s"}${who}${paneText}${taskText}${attention}`;
|
|
127
167
|
};
|
|
128
168
|
|
|
129
169
|
const titleSuffix = (): string | undefined => {
|
|
130
170
|
if (runs.size === 0) return undefined;
|
|
131
171
|
const agentNames = activeAgentNames();
|
|
132
172
|
const activeCount = activeSubagentCount();
|
|
133
|
-
const
|
|
173
|
+
const task = boundedTaskLabel(activeTaskLabel(), MAX_TITLE_TASK_CHARS);
|
|
174
|
+
const target = task ?? (activeCount === 1 && agentNames.length === 1 ? agentNames[0]! : String(activeCount));
|
|
134
175
|
return `⏳${target}${attentionLabels.size > 0 ? "⚠" : ""}`;
|
|
135
176
|
};
|
|
136
177
|
|
|
@@ -259,7 +300,9 @@ export function registerHerdrStatusBridge(options: HerdrStatusBridgeOptions): He
|
|
|
259
300
|
for (const run of nextRuns) {
|
|
260
301
|
if (!run || typeof run.id !== "string" || !run.id) continue;
|
|
261
302
|
activeIds.add(run.id);
|
|
262
|
-
|
|
303
|
+
const taskLabel = boundedTaskLabel(run.taskLabel);
|
|
304
|
+
const { taskLabel: _rawTaskLabel, ...sanitizedRun } = run;
|
|
305
|
+
runs.set(run.id, { ...sanitizedRun, ...(taskLabel ? { taskLabel } : {}) });
|
|
263
306
|
if (!run.needsAttention) {
|
|
264
307
|
acknowledgedAttention.delete(run.id);
|
|
265
308
|
} else if (!acknowledgedAttention.has(run.id)) {
|