@xzzpig/pi-subagents 0.8.0 → 0.10.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 +477 -0
- package/README.md +2 -2
- 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 +1 -1
- package/agents/scout.md +1 -1
- package/docs/agents.md +195 -39
- package/docs/configuration.md +81 -22
- package/docs/extension-api.md +69 -14
- package/docs/missions.md +2 -0
- package/docs/models.md +32 -9
- package/docs/observability.md +22 -20
- package/docs/tool-reference.md +123 -14
- package/docs/watchdog.md +92 -114
- package/docs/workflows.md +142 -4
- package/install.mjs +1 -1
- package/package.json +7 -6
- package/prompts/review-loop.md +2 -2
- package/skills/council-mode/SKILL.md +48 -243
- package/skills/council-mode/references/pass-contracts.md +150 -0
- package/skills/pi-subagents/SKILL.md +89 -35
- package/skills/pi-subagents/references/constraints-and-recipes.md +30 -234
- package/skills/pi-subagents/references/execution-controls.md +91 -15
- package/skills/pi-subagents/references/management-authoring-rpc.md +5 -5
- package/skills/pi-subagents/references/multi-lane-orchestration.md +13 -1
- package/skills/pi-subagents/references/prompting-and-roles.md +59 -31
- package/skills/pi-subagents/references/review-and-validation.md +73 -0
- package/src/agents/agent-management.ts +384 -115
- package/src/agents/agent-refinements.ts +4 -4
- package/src/agents/agent-serializer.ts +14 -2
- package/src/agents/agents.ts +935 -372
- package/src/agents/builtin-names.ts +6 -0
- package/src/agents/runtime-agent-events.ts +70 -0
- package/src/agents/runtime-agent-registry.ts +42 -21
- 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-runs.ts +67 -4
- package/src/api/preflight.ts +77 -21
- package/src/api/shared-types.ts +6 -0
- package/src/extension/config.ts +90 -0
- package/src/extension/doctor.ts +5 -13
- package/src/extension/fanout-child.ts +14 -14
- package/src/extension/index.ts +115 -37
- package/src/extension/public-execution.ts +103 -15
- package/src/extension/rpc.ts +120 -25
- package/src/extension/schemas.ts +65 -29
- package/src/extension/tool-description.ts +48 -26
- package/src/inspectors/herdr/actions.ts +2 -1
- package/src/inspectors/herdr/inspector-runner.ts +21 -23
- package/src/inspectors/herdr/session-roots-codec.ts +42 -0
- package/src/integrations/herdr-status.ts +51 -3
- package/src/intercom/native-supervisor-channel.ts +138 -60
- package/src/intercom/result-intercom.ts +7 -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 +417 -133
- package/src/runs/background/async-job-tracker.ts +95 -15
- package/src/runs/background/async-resume.ts +60 -28
- package/src/runs/background/async-retention.ts +20 -3
- package/src/runs/background/async-status-snapshot.ts +23 -261
- package/src/runs/background/async-status.ts +204 -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 +74 -8
- package/src/runs/background/control-channel.ts +4 -205
- package/src/runs/background/fleet-view.ts +38 -22
- package/src/runs/background/inspect-rpc.ts +8 -8
- package/src/runs/background/notify.ts +238 -12
- 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 +39 -16
- 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 +84 -17
- 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 +10 -4
- package/src/runs/background/steering.ts +8 -15
- package/src/runs/background/subagent-runner.ts +718 -1161
- 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 +43 -2
- package/src/runs/background/wait-config.ts +23 -9
- package/src/runs/background/wait-tool.ts +26 -19
- package/src/runs/foreground/async-steering-action.ts +3 -19
- package/src/runs/foreground/execution.ts +489 -499
- package/src/runs/foreground/foreground-control.ts +13 -0
- package/src/runs/foreground/foreground-history.ts +23 -1
- package/src/runs/foreground/subagent-executor.ts +1223 -402
- package/src/runs/foreground/workflow-detach-reconcile.ts +140 -115
- 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 +138 -36
- 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 +32 -6
- package/src/runs/shared/child-launch-plan.ts +151 -0
- package/src/runs/shared/child-launch.ts +364 -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 +366 -0
- package/src/runs/shared/child-tool-plan.ts +632 -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 +6 -5
- package/src/runs/shared/cursor-agent-adapter.ts +114 -0
- package/src/runs/shared/dynamic-fanout.ts +3 -3
- 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 +348 -55
- package/src/runs/shared/fast-mode-extension.ts +5 -5
- 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 +139 -9
- package/src/runs/shared/model-fallback.ts +146 -14
- package/src/runs/shared/mutation-evidence.ts +57 -3
- package/src/runs/shared/nested-events.ts +99 -77
- 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 +12 -7
- package/src/runs/shared/parallel-handoff.ts +423 -7
- package/src/runs/shared/parallel-utils.ts +20 -7
- 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/sandbox-profile-guard.ts +85 -0
- package/src/runs/shared/sandbox-startup-diagnostics.ts +54 -0
- package/src/runs/shared/single-output.ts +89 -22
- package/src/runs/shared/structured-output.ts +49 -9
- package/src/runs/shared/subagent-control.ts +6 -2
- package/src/runs/shared/subagent-prompt-runtime.ts +188 -365
- package/src/runs/shared/task-intent.ts +21 -7
- package/src/runs/shared/tool-availability.ts +18 -62
- 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 +11 -1
- package/src/shared/pruned-fork.ts +450 -0
- package/src/shared/sandbox-profile.ts +23 -0
- package/src/shared/session-file-trust.ts +19 -0
- package/src/shared/session-tokens.ts +14 -3
- package/src/shared/settings.ts +19 -105
- package/src/shared/shortcuts.ts +17 -0
- package/src/shared/thinking-ceiling.ts +0 -6
- package/src/shared/types.ts +545 -70
- 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 +217 -82
- 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 +1429 -163
- 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/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 +988 -59
- 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 -935
- 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
|
@@ -0,0 +1,235 @@
|
|
|
1
|
+
import { spawn } from "node:child_process";
|
|
2
|
+
import { randomUUID } from "node:crypto";
|
|
3
|
+
import * as fs from "node:fs";
|
|
4
|
+
import * as path from "node:path";
|
|
5
|
+
import { quoteExecutableForShell } from "../runs/shared/acceptance.ts";
|
|
6
|
+
import { createOwnedProcessTreeController, type OwnedProcessTreeController } from "../runs/background/owned-process-tree.ts";
|
|
7
|
+
import { resolveSingleOutputClaimPath } from "../runs/shared/single-output.ts";
|
|
8
|
+
import { DEFAULT_FILE_SYSTEM_RETRY_DELAYS_MS, runFileSystemOperationWithRetry } from "../shared/file-system-retry.ts";
|
|
9
|
+
|
|
10
|
+
const MAX_COMMAND_BYTES = 16 * 1024;
|
|
11
|
+
const MAX_OUTPUT_PATH_BYTES = 240;
|
|
12
|
+
const MAX_CAPTURE_BYTES = 1024 * 1024;
|
|
13
|
+
const MAX_PREVIEW_BYTES = 4 * 1024;
|
|
14
|
+
const MAX_TIMEOUT_MS = 24 * 60 * 60 * 1000;
|
|
15
|
+
|
|
16
|
+
export interface WorkflowHostCommandParams {
|
|
17
|
+
kind: "command";
|
|
18
|
+
command: string;
|
|
19
|
+
timeoutMs: number;
|
|
20
|
+
output?: string;
|
|
21
|
+
role?: "ci" | "gate";
|
|
22
|
+
provider?: string;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export interface WorkflowHostCommandResult {
|
|
26
|
+
key: string;
|
|
27
|
+
kind: "command";
|
|
28
|
+
ok: boolean;
|
|
29
|
+
state: "passed" | "failed" | "timed-out" | "stopped";
|
|
30
|
+
exitCode: number | null;
|
|
31
|
+
stdout: string;
|
|
32
|
+
stderr: string;
|
|
33
|
+
outputPath: string;
|
|
34
|
+
durationMs: number;
|
|
35
|
+
error?: string;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
type ProcessTreeTerminal = Awaited<ReturnType<OwnedProcessTreeController["terminate"]>>;
|
|
39
|
+
type ProcessTreeCleanup = ProcessTreeTerminal | { state: "unknown"; reason: "missing-process-id" };
|
|
40
|
+
|
|
41
|
+
function byteLength(value: string): number {
|
|
42
|
+
return Buffer.byteLength(value, "utf8");
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function boundedText(value: string, maxBytes: number): string {
|
|
46
|
+
if (byteLength(value) <= maxBytes) return value;
|
|
47
|
+
let end = Math.max(0, maxBytes - 3);
|
|
48
|
+
while (end > 0 && byteLength(value.slice(0, end)) > maxBytes - 3) end -= 1;
|
|
49
|
+
return `${value.slice(0, end)}...`;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export function normalizeWorkflowHostCommandParams(value: unknown, label = "runs.host params"): WorkflowHostCommandParams {
|
|
53
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error(`${label} must be an object.`);
|
|
54
|
+
const params = value as Record<string, unknown>;
|
|
55
|
+
const unknownFields = Object.keys(params).filter((field) => !["kind", "command", "timeoutMs", "output", "role", "provider"].includes(field));
|
|
56
|
+
if (unknownFields.length) {
|
|
57
|
+
const cwdHint = unknownFields.includes("cwd")
|
|
58
|
+
? " The host step does not accept per-step cwd; commands and relative output paths use the workflow cwd. Set cwd on the outer subagent request, or put a trusted directory change in command (for example, 'cd /path/to/worktree && npm test')."
|
|
59
|
+
: "";
|
|
60
|
+
throw new Error(`${label} has unsupported fields: ${unknownFields.join(", ")}.${cwdHint}`);
|
|
61
|
+
}
|
|
62
|
+
if (params.kind !== "command") throw new Error(`${label}.kind must be 'command'.`);
|
|
63
|
+
if (typeof params.command !== "string" || !params.command.trim()) throw new Error(`${label}.command must be a non-empty string.`);
|
|
64
|
+
const command = params.command.trim();
|
|
65
|
+
if (byteLength(command) > MAX_COMMAND_BYTES || /[\u0000]/.test(command)) throw new Error(`${label}.command exceeds the ${MAX_COMMAND_BYTES}-byte limit or contains NUL.`);
|
|
66
|
+
if (typeof params.timeoutMs !== "number" || !Number.isInteger(params.timeoutMs) || params.timeoutMs < 1 || params.timeoutMs > MAX_TIMEOUT_MS) throw new Error(`${label}.timeoutMs must be an integer from 1 to ${MAX_TIMEOUT_MS}.`);
|
|
67
|
+
let output: string | undefined;
|
|
68
|
+
if (params.output !== undefined) {
|
|
69
|
+
if (typeof params.output !== "string" || !params.output.trim()) throw new Error(`${label}.output must be a non-empty relative path.`);
|
|
70
|
+
output = params.output.trim();
|
|
71
|
+
if (path.isAbsolute(output) || output.split(/[\\/]/).includes("..") || /[\u0000-\u001f\u007f]/.test(output) || byteLength(output) > MAX_OUTPUT_PATH_BYTES) throw new Error(`${label}.output must be a bounded relative path without traversal or control characters.`);
|
|
72
|
+
}
|
|
73
|
+
if (params.role !== undefined && params.role !== "ci" && params.role !== "gate") throw new Error(`${label}.role must be 'ci' or 'gate'.`);
|
|
74
|
+
let provider: string | undefined;
|
|
75
|
+
if (params.provider !== undefined) {
|
|
76
|
+
if (typeof params.provider !== "string" || !params.provider.trim() || /[\r\n\u0000]/.test(params.provider) || byteLength(params.provider.trim()) > 64) throw new Error(`${label}.provider must be a non-empty single-line string of at most 64 bytes.`);
|
|
77
|
+
provider = params.provider.trim();
|
|
78
|
+
}
|
|
79
|
+
return {
|
|
80
|
+
kind: "command",
|
|
81
|
+
command,
|
|
82
|
+
timeoutMs: params.timeoutMs,
|
|
83
|
+
...(output ? { output } : {}),
|
|
84
|
+
...(params.role ? { role: params.role } : {}),
|
|
85
|
+
...(provider ? { provider } : {}),
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
function appendBounded(current: string, chunk: Buffer, limit: number): string {
|
|
90
|
+
if (byteLength(current) >= limit) return current;
|
|
91
|
+
return boundedText(current + chunk.toString("utf8"), limit);
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
export function resolveWorkflowHostOutputClaimPath(outputPath: string): string {
|
|
95
|
+
return resolveSingleOutputClaimPath(outputPath);
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
function assertSafeExplicitOutput(cwd: string, outputPath: string, key: string): string {
|
|
99
|
+
const root = fs.realpathSync(cwd);
|
|
100
|
+
const outputParent = path.dirname(outputPath);
|
|
101
|
+
let existingParent = outputParent;
|
|
102
|
+
while (!fs.existsSync(existingParent)) existingParent = path.dirname(existingParent);
|
|
103
|
+
const existingParentReal = fs.realpathSync(existingParent);
|
|
104
|
+
const existingRelative = path.relative(root, existingParentReal);
|
|
105
|
+
if (existingRelative === ".." || existingRelative.startsWith(`..${path.sep}`) || path.isAbsolute(existingRelative)) throw new Error(`runs.host('${key}') output resolves outside the workflow cwd.`);
|
|
106
|
+
fs.mkdirSync(outputParent, { recursive: true });
|
|
107
|
+
const parent = fs.realpathSync(outputParent);
|
|
108
|
+
const relative = path.relative(root, parent);
|
|
109
|
+
if (relative === ".." || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative)) throw new Error(`runs.host('${key}') output resolves outside the workflow cwd.`);
|
|
110
|
+
try {
|
|
111
|
+
const stat = fs.lstatSync(outputPath);
|
|
112
|
+
if (!stat.isFile() || stat.nlink > 1) throw new Error(`runs.host('${key}') output must be a regular, non-linked file path.`);
|
|
113
|
+
} catch (error) {
|
|
114
|
+
if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
|
|
115
|
+
}
|
|
116
|
+
return parent;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
function writeExplicitOutput(outputParent: string, outputPath: string, capture: string, key: string): void {
|
|
120
|
+
const destination = path.join(outputParent, path.basename(outputPath));
|
|
121
|
+
const temporaryPath = path.join(outputParent, `.pi-host-output-${process.pid}-${randomUUID()}.tmp`);
|
|
122
|
+
let descriptor: number | undefined;
|
|
123
|
+
try {
|
|
124
|
+
descriptor = fs.openSync(temporaryPath, fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL, 0o600);
|
|
125
|
+
fs.writeFileSync(descriptor, capture, { encoding: "utf8" });
|
|
126
|
+
fs.closeSync(descriptor);
|
|
127
|
+
descriptor = undefined;
|
|
128
|
+
fs.chmodSync(temporaryPath, 0o600);
|
|
129
|
+
runFileSystemOperationWithRetry(() => fs.renameSync(temporaryPath, destination), {
|
|
130
|
+
retryDelaysMs: process.platform === "win32" ? DEFAULT_FILE_SYSTEM_RETRY_DELAYS_MS : [],
|
|
131
|
+
});
|
|
132
|
+
} catch (error) {
|
|
133
|
+
throw new Error(`runs.host('${key}') could not atomically replace its output.`, { cause: error instanceof Error ? error : undefined });
|
|
134
|
+
} finally {
|
|
135
|
+
if (descriptor !== undefined) fs.closeSync(descriptor);
|
|
136
|
+
try {
|
|
137
|
+
fs.unlinkSync(temporaryPath);
|
|
138
|
+
} catch (error) {
|
|
139
|
+
if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
function terminateProcessTree(pid: number, controller: OwnedProcessTreeController): Promise<ProcessTreeTerminal> {
|
|
145
|
+
if (process.platform !== "win32") return controller.terminate();
|
|
146
|
+
return new Promise<ProcessTreeTerminal>((resolve) => {
|
|
147
|
+
const cleanup = spawn("taskkill", ["/PID", String(pid), "/T", "/F"], { stdio: "ignore", windowsHide: true });
|
|
148
|
+
cleanup.once("error", () => { void controller.terminate().then(resolve); });
|
|
149
|
+
cleanup.once("close", () => { void controller.terminate().then(resolve); });
|
|
150
|
+
});
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
export async function executeWorkflowHostCommand(input: {
|
|
154
|
+
key: string;
|
|
155
|
+
params: WorkflowHostCommandParams;
|
|
156
|
+
cwd: string;
|
|
157
|
+
defaultOutputPath: string;
|
|
158
|
+
claimedOutputPath?: string;
|
|
159
|
+
signal: AbortSignal;
|
|
160
|
+
}): Promise<WorkflowHostCommandResult> {
|
|
161
|
+
const outputPath = input.params.output ? path.resolve(input.cwd, input.params.output) : input.defaultOutputPath;
|
|
162
|
+
const relative = path.relative(input.cwd, outputPath);
|
|
163
|
+
if (input.params.output && (relative === "" || relative === ".." || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative))) throw new Error(`runs.host('${input.key}') output escapes the workflow cwd.`);
|
|
164
|
+
const explicitOutputParent = input.params.output ? assertSafeExplicitOutput(input.cwd, outputPath, input.key) : undefined;
|
|
165
|
+
if (!input.params.output) fs.mkdirSync(path.dirname(outputPath), { recursive: true });
|
|
166
|
+
const startedAt = Date.now();
|
|
167
|
+
let stdout = "";
|
|
168
|
+
let stderr = "";
|
|
169
|
+
let capture = "";
|
|
170
|
+
let timedOut = false;
|
|
171
|
+
let stopped = false;
|
|
172
|
+
let settled = false;
|
|
173
|
+
|
|
174
|
+
return new Promise((resolve, reject) => {
|
|
175
|
+
const child = spawn(quoteExecutableForShell(input.params.command), {
|
|
176
|
+
cwd: input.cwd,
|
|
177
|
+
env: process.env,
|
|
178
|
+
shell: true,
|
|
179
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
180
|
+
windowsHide: true,
|
|
181
|
+
detached: process.platform !== "win32",
|
|
182
|
+
});
|
|
183
|
+
const processTree = typeof child.pid === "number" ? createOwnedProcessTreeController(child.pid, { termGraceMs: 1_000 }) : undefined;
|
|
184
|
+
let termination: Promise<ProcessTreeCleanup> | undefined;
|
|
185
|
+
const terminate = (reason: "timeout" | "abort") => {
|
|
186
|
+
if (settled) return;
|
|
187
|
+
timedOut = reason === "timeout";
|
|
188
|
+
stopped = reason === "abort";
|
|
189
|
+
if (processTree && child.pid !== undefined) termination ??= terminateProcessTree(child.pid, processTree);
|
|
190
|
+
else {
|
|
191
|
+
child.kill("SIGTERM");
|
|
192
|
+
termination ??= Promise.resolve({ state: "unknown", reason: "missing-process-id" });
|
|
193
|
+
}
|
|
194
|
+
};
|
|
195
|
+
const timeout = setTimeout(() => terminate("timeout"), input.params.timeoutMs);
|
|
196
|
+
timeout.unref?.();
|
|
197
|
+
const onAbort = () => terminate("abort");
|
|
198
|
+
if (input.signal.aborted) onAbort();
|
|
199
|
+
else input.signal.addEventListener("abort", onAbort, { once: true });
|
|
200
|
+
child.stdout.on("data", (chunk: Buffer) => {
|
|
201
|
+
stdout = appendBounded(stdout, chunk, MAX_PREVIEW_BYTES);
|
|
202
|
+
capture = appendBounded(capture, chunk, MAX_CAPTURE_BYTES);
|
|
203
|
+
});
|
|
204
|
+
child.stderr.on("data", (chunk: Buffer) => {
|
|
205
|
+
stderr = appendBounded(stderr, chunk, MAX_PREVIEW_BYTES);
|
|
206
|
+
capture = appendBounded(capture, chunk, MAX_CAPTURE_BYTES);
|
|
207
|
+
});
|
|
208
|
+
const finish = async (exitCode: number | null, spawnError?: unknown) => {
|
|
209
|
+
if (settled) return;
|
|
210
|
+
settled = true;
|
|
211
|
+
clearTimeout(timeout);
|
|
212
|
+
input.signal.removeEventListener("abort", onAbort);
|
|
213
|
+
const terminal = termination ? await termination : await processTree?.finishAfterWriterClose();
|
|
214
|
+
const cleanupError = process.platform !== "win32" && terminal?.state === "unknown" ? terminal.reason : undefined;
|
|
215
|
+
const state = timedOut ? "timed-out" : stopped ? "stopped" : exitCode === 0 && !spawnError && !cleanupError ? "passed" : "failed";
|
|
216
|
+
const error = spawnError instanceof Error ? spawnError.message : spawnError ? String(spawnError) : cleanupError ? `Process-tree cleanup failed: ${cleanupError}.` : state === "timed-out" ? `Command timed out after ${input.params.timeoutMs}ms.` : state === "stopped" ? "Command stopped because the workflow was aborted." : state === "failed" ? `Command exited with code ${exitCode ?? "unknown"}.` : undefined;
|
|
217
|
+
try {
|
|
218
|
+
if (input.claimedOutputPath && resolveWorkflowHostOutputClaimPath(outputPath) !== input.claimedOutputPath) throw new Error(`output path changed after it was claimed.`);
|
|
219
|
+
if (explicitOutputParent) {
|
|
220
|
+
const currentParent = assertSafeExplicitOutput(input.cwd, outputPath, input.key);
|
|
221
|
+
if (currentParent !== explicitOutputParent) throw new Error(`output parent changed while the command was running.`);
|
|
222
|
+
writeExplicitOutput(explicitOutputParent, outputPath, capture, input.key);
|
|
223
|
+
} else {
|
|
224
|
+
fs.writeFileSync(outputPath, capture, { encoding: "utf8", mode: 0o600 });
|
|
225
|
+
}
|
|
226
|
+
} catch (writeError) {
|
|
227
|
+
reject(new Error(`runs.host('${input.key}') could not save command output: ${writeError instanceof Error ? writeError.message : String(writeError)}`, { cause: writeError instanceof Error ? writeError : undefined }));
|
|
228
|
+
return;
|
|
229
|
+
}
|
|
230
|
+
resolve({ key: input.key, kind: "command", ok: state === "passed", state, exitCode, stdout, stderr, outputPath, durationMs: Date.now() - startedAt, ...(error ? { error } : {}) });
|
|
231
|
+
};
|
|
232
|
+
child.on("close", (code) => { void finish(code); });
|
|
233
|
+
child.on("error", (error) => { void finish(null, error); });
|
|
234
|
+
});
|
|
235
|
+
}
|