@xzzpig/pi-subagents 0.24.2 → 0.25.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 +22 -0
- package/bundle/agent-management.js +4 -4
- package/bundle/agents.js +3 -3
- package/bundle/child-tool-plan.js +2 -2
- package/bundle/chunk-34TUUBRN.js +1107 -0
- package/bundle/{chunk-SW2VMNIU.js → chunk-5OD3OWTE.js} +2 -2
- package/bundle/{chunk-XWWUDWUW.js → chunk-5YEOWNSD.js} +371 -135
- package/bundle/{chunk-EUPJB4S7.js → chunk-5Z7JAORM.js} +196 -1219
- package/bundle/{chunk-LCDJWBVM.js → chunk-66JNFRFS.js} +1 -1
- package/bundle/{chunk-4UH4WS4G.js → chunk-6MNRKUHY.js} +23 -12
- package/bundle/{chunk-ED55MIC2.js → chunk-CGFF4WA3.js} +42 -19
- package/bundle/{chunk-TMHVDPYW.js → chunk-DLVPMML3.js} +263 -154
- package/bundle/chunk-HXRB42AF.js +108 -0
- package/bundle/{chunk-355ECEP2.js → chunk-IH7LQVEE.js} +29 -14
- package/bundle/{chunk-CYY5UMJU.js → chunk-IJWITCC6.js} +411 -249
- package/bundle/{chunk-RU522D5W.js → chunk-IKFKH5EL.js} +369 -50
- package/bundle/{chunk-Z6TFJ6BR.js → chunk-INWSUNI6.js} +1 -1
- package/bundle/{chunk-JEA2ZKUA.js → chunk-IUDEI6FJ.js} +35 -200
- package/bundle/{chunk-WW76JRIX.js → chunk-JAXVBXGF.js} +1 -1
- package/bundle/{chunk-ICNYIALB.js → chunk-JH5H4CYJ.js} +784 -474
- package/bundle/{chunk-35GII5EF.js → chunk-JWFLPSTP.js} +41 -117
- package/bundle/{chunk-224WMDIV.js → chunk-KCJFGKVK.js} +350 -123
- package/bundle/{chunk-RB4GELQA.js → chunk-LPJEKHOY.js} +1 -1
- package/bundle/chunk-LYKG4FKH.js +523 -0
- package/bundle/{chunk-X6LOM3Z4.js → chunk-LZ3HBDTR.js} +161 -78
- package/bundle/{chunk-FG6SQJAR.js → chunk-OGPOCGWX.js} +24 -6
- package/bundle/{chunk-BQ2OAB4Q.js → chunk-OSVXFWPG.js} +67 -30
- package/bundle/{chunk-FJWI64H7.js → chunk-RMSABUN3.js} +27 -13
- package/bundle/{chunk-H36HBZB2.js → chunk-SJPABBZG.js} +2 -2
- package/bundle/{chunk-3U633XDZ.js → chunk-U3ZDUUTM.js} +11 -3
- package/bundle/{chunk-LVWU2HOO.js → chunk-ULGMXABL.js} +16 -7
- package/bundle/{chunk-WPW4V6HM.js → chunk-W7ZA6TYD.js} +2 -2
- package/bundle/{chunk-V2KFIGFH.js → chunk-XAC2XNAP.js} +503 -304
- package/bundle/{chunk-O4D5PBVI.js → chunk-YWXILP5N.js} +3 -2
- package/bundle/control-channel.js +2 -2
- package/bundle/index.js +1 -1
- package/bundle/intercom-bridge.js +2 -2
- package/bundle/preflight.js +12 -10
- package/bundle/project-panes.js +3 -3
- package/bundle/workflow-resources.js +1 -1
- package/docs/agents.md +27 -6
- package/docs/configuration.md +20 -8
- package/docs/extension-api.md +18 -1
- package/docs/models.md +6 -2
- package/docs/observability.md +2 -0
- package/docs/tool-reference.md +7 -1
- package/docs/workflows.md +30 -2
- package/package.json +2 -2
- package/skills/pi-subagents/SKILL.md +15 -6
- package/skills/pi-subagents/references/prompting-and-roles.md +1 -0
- package/src/agents/agent-management.d.ts +1 -0
- package/src/agents/agent-management.js +46 -18
- package/src/agents/agent-memory.d.ts +1 -4
- package/src/agents/agent-memory.js +1 -4
- package/src/agents/agent-serializer.d.ts +2 -0
- package/src/agents/agent-serializer.js +1 -1
- package/src/agents/agents.d.ts +2 -3
- package/src/agents/agents.js +46 -20
- package/src/agents/frontmatter.js +1 -8
- package/src/agents/global-npm-root.d.ts +1 -0
- package/src/agents/global-npm-root.js +11 -3
- package/src/agents/skills.d.ts +0 -3
- package/src/agents/skills.js +0 -3
- package/src/api/preflight.d.ts +3 -1
- package/src/api/preflight.js +2 -0
- package/src/extension/config.d.ts +1 -0
- package/src/extension/config.js +13 -1
- package/src/extension/herdr-pi-bridge.js +10 -2
- package/src/extension/index.d.ts +0 -13
- package/src/extension/index.js +51 -37
- package/src/extension/public-execution.d.ts +1 -0
- package/src/extension/public-execution.js +4 -0
- package/src/extension/reply-workflow-script.js +24 -4
- package/src/extension/schemas.d.ts +12 -3
- package/src/extension/schemas.js +7 -3
- package/src/extension/session-switch.d.ts +25 -0
- package/src/extension/session-switch.js +138 -0
- package/src/extension/subagent-guide.d.ts +1 -1
- package/src/extension/subagent-guide.js +1 -1
- package/src/extension/subagent-launch-tool.d.ts +25 -0
- package/src/extension/subagent-launch-tool.js +48 -0
- package/src/extension/tool-activation.js +55 -15
- package/src/extension/tool-description.d.ts +1 -1
- package/src/extension/tool-description.js +14 -8
- package/src/inspectors/herdr/actions.d.ts +0 -1
- package/src/inspectors/herdr/actions.js +0 -1
- package/src/inspectors/session-roots-codec.d.ts +0 -1
- package/src/inspectors/session-roots-codec.js +0 -1
- package/src/inspectors/tmux/actions.d.ts +0 -1
- package/src/inspectors/tmux/actions.js +0 -1
- package/src/integrations/herdr-status.js +3 -8
- package/src/intercom/native-supervisor-channel.js +65 -9
- package/src/runs/background/async-execution.d.ts +7 -10
- package/src/runs/background/async-execution.js +66 -29
- package/src/runs/background/async-job-tracker.js +12 -0
- package/src/runs/background/async-resume.d.ts +2 -1
- package/src/runs/background/async-resume.js +114 -40
- package/src/runs/background/async-retention.d.ts +0 -2
- package/src/runs/background/async-retention.js +17 -6
- package/src/runs/background/async-status.d.ts +2 -0
- package/src/runs/background/async-status.js +4 -0
- package/src/runs/background/auto-drain.js +2 -1
- package/src/runs/background/boot-id.d.ts +1 -3
- package/src/runs/background/boot-id.js +1 -3
- package/src/runs/background/completion-batcher.d.ts +3 -4
- package/src/runs/background/completion-batcher.js +2 -3
- package/src/runs/background/control-channel.d.ts +0 -6
- package/src/runs/background/control-channel.js +0 -6
- package/src/runs/background/fleet-view.js +2 -3
- package/src/runs/background/notify.d.ts +0 -2
- package/src/runs/background/notify.js +0 -2
- package/src/runs/background/result-watcher.d.ts +1 -0
- package/src/runs/background/result-watcher.js +59 -29
- package/src/runs/background/resume-guidance.js +4 -2
- package/src/runs/background/retained-children.js +2 -1
- package/src/runs/background/run-child-session.d.ts +2 -3
- package/src/runs/background/run-child-session.js +5 -8
- package/src/runs/background/run-status.js +9 -7
- package/src/runs/background/runner-aliases.js +15 -0
- package/src/runs/background/scheduled-runs.d.ts +3 -1
- package/src/runs/background/scheduled-runs.js +13 -16
- package/src/runs/background/steering.d.ts +2 -11
- package/src/runs/background/steering.js +11 -6
- package/src/runs/background/subagent-runner.d.ts +2 -6
- package/src/runs/background/subagent-runner.js +88 -70
- package/src/runs/background/subagent-wait.js +12 -15
- package/src/runs/background/wait-config.d.ts +2 -0
- package/src/runs/background/wait-config.js +17 -3
- package/src/runs/background/wait-subscriptions.js +124 -12
- package/src/runs/background/wait-tool.js +4 -2
- package/src/runs/background/workflow-terminal-proof.d.ts +0 -1
- package/src/runs/background/workflow-terminal-proof.js +0 -1
- package/src/runs/foreground/async-steering-action.js +24 -9
- package/src/runs/foreground/async-stop-action.d.ts +1 -1
- package/src/runs/foreground/async-stop-action.js +9 -1
- package/src/runs/foreground/execution.d.ts +0 -3
- package/src/runs/foreground/execution.js +56 -24
- package/src/runs/foreground/prompt-audit.js +1 -0
- package/src/runs/foreground/subagent-executor.d.ts +5 -10
- package/src/runs/foreground/subagent-executor.js +164 -49
- package/src/runs/shared/acceptance.js +69 -26
- package/src/runs/shared/async-status-projection.d.ts +2 -0
- package/src/runs/shared/async-status-projection.js +10 -0
- package/src/runs/shared/child-commands.js +15 -2
- package/src/runs/shared/child-hooks.d.ts +1 -7
- package/src/runs/shared/child-hooks.js +13 -5
- package/src/runs/shared/child-launch.js +6 -2
- package/src/runs/shared/child-runtime-config.d.ts +0 -1
- package/src/runs/shared/child-session.d.ts +6 -5
- package/src/runs/shared/child-session.js +85 -38
- package/src/runs/shared/child-tool-plan.d.ts +0 -1
- package/src/runs/shared/child-tool-plan.js +0 -1
- package/src/runs/shared/claude-code-adapter.js +11 -0
- package/src/runs/shared/external-cli-contract.d.ts +49 -0
- package/src/runs/shared/external-cli-contract.js +18 -13
- package/src/runs/shared/external-cli-runner.js +26 -6
- package/src/runs/shared/herdr-connection.js +2 -1
- package/src/runs/shared/herdr-pane-host.d.ts +2 -2
- package/src/runs/shared/herdr-pane-host.js +17 -1
- package/src/runs/shared/herdr-placed-run.js +51 -24
- package/src/runs/shared/lane-metadata.d.ts +0 -1
- package/src/runs/shared/lane-metadata.js +0 -1
- package/src/runs/shared/mcp-config-sources.d.ts +4 -1
- package/src/runs/shared/mcp-config-sources.js +1 -1
- package/src/runs/shared/mcp-direct-tool-allowlist.d.ts +0 -3
- package/src/runs/shared/mcp-direct-tool-allowlist.js +26 -17
- package/src/runs/shared/mcp-direct-tool-grant.js +8 -1
- package/src/runs/shared/model-resolution-diagnostic.d.ts +0 -1
- package/src/runs/shared/model-resolution.d.ts +20 -5
- package/src/runs/shared/model-resolution.js +55 -50
- package/src/runs/shared/model-scope.d.ts +1 -5
- package/src/runs/shared/model-scope.js +1 -5
- package/src/runs/shared/mutation-evidence.d.ts +1 -1
- package/src/runs/shared/mutation-evidence.js +52 -7
- package/src/runs/shared/nested-events.d.ts +1 -0
- package/src/runs/shared/nested-events.js +1 -1
- package/src/runs/shared/parallel-utils.d.ts +0 -1
- package/src/runs/shared/permissions.js +5 -3
- package/src/runs/shared/placement-host.d.ts +5 -1
- package/src/runs/shared/rex-pane-host.d.ts +0 -1
- package/src/runs/shared/rex-pane-host.js +0 -2
- package/src/runs/shared/run-launch-folder.d.ts +12 -0
- package/src/runs/shared/run-launch-folder.js +21 -0
- package/src/runs/shared/runner-launcher.d.ts +12 -1
- package/src/runs/shared/runner-launcher.js +16 -0
- package/src/runs/shared/single-output.d.ts +3 -3
- package/src/runs/shared/single-output.js +5 -3
- package/src/runs/shared/structured-output.d.ts +8 -0
- package/src/runs/shared/structured-output.js +40 -5
- package/src/runs/shared/subagent-prompt-runtime.d.ts +0 -1
- package/src/runs/shared/subagent-prompt-runtime.js +18 -4
- package/src/runs/shared/supervisor-wait-timer.d.ts +16 -0
- package/src/runs/shared/supervisor-wait-timer.js +61 -0
- package/src/runs/shared/tool-timeout.js +2 -1
- package/src/runs/shared/worktree-cleanup-plan.d.ts +0 -1
- package/src/runs/shared/worktree-cleanup-plan.js +0 -1
- package/src/runs/shared/worktree.d.ts +3 -0
- package/src/runs/shared/worktree.js +20 -0
- package/src/shared/artifacts.d.ts +1 -0
- package/src/shared/artifacts.js +132 -22
- package/src/shared/capacity-resilient-json.d.ts +1 -1
- package/src/shared/child-cache-retention.d.ts +1 -2
- package/src/shared/child-cache-retention.js +1 -2
- package/src/shared/fleet-transcript-reader.d.ts +51 -0
- package/src/shared/fleet-transcript-reader.js +333 -0
- package/src/shared/formatters.d.ts +0 -18
- package/src/shared/formatters.js +0 -18
- package/src/shared/pruned-fork.js +2 -2
- package/src/shared/reported-progress.d.ts +1 -0
- package/src/shared/reported-progress.js +12 -0
- package/src/shared/session-succession.d.ts +16 -1
- package/src/shared/session-succession.js +41 -2
- package/src/shared/session-warnings.d.ts +7 -0
- package/src/shared/session-warnings.js +26 -0
- package/src/shared/settings.d.ts +0 -23
- package/src/shared/settings.js +3 -35
- package/src/shared/status-format.d.ts +1 -0
- package/src/shared/status-format.js +1 -1
- package/src/shared/types.d.ts +108 -59
- package/src/shared/types.js +0 -12
- package/src/shared/utils.d.ts +3 -15
- package/src/shared/utils.js +4 -22
- package/src/shared/wait-tool-name.d.ts +8 -0
- package/src/shared/wait-tool-name.js +13 -0
- package/src/slash/slash-commands.js +2 -1
- package/src/slash/subagent-cost.d.ts +3 -2
- package/src/slash/subagent-cost.js +22 -3
- package/src/slash/subagents-admin.js +0 -1
- package/src/tui/fleet-status.d.ts +0 -5
- package/src/tui/fleet-status.js +4 -24
- package/src/tui/fleet.js +6 -4
- package/src/tui/render.d.ts +0 -9
- package/src/tui/render.js +194 -68
- package/src/tui/subagent-messages.js +3 -2
- package/src/watchdog/model-selection.js +2 -2
- package/src/watchdog/permission-arbiter.js +1 -0
- package/src/watchdog/register-child.d.ts +2 -3
- package/src/watchdog/register-child.js +2 -3
- package/src/watchdog/review.d.ts +0 -5
- package/src/watchdog/review.js +4 -3
- package/src/watchdog/turn-delta.js +2 -1
- package/src/workflows/scripted-workflow.d.ts +2 -0
- package/src/workflows/scripted-workflow.js +344 -59
- package/src/workflows/structured-workflow-scripts.d.ts +4 -3
- package/src/workflows/structured-workflow-scripts.js +32 -11
- package/src/workflows/workflow-launch-record.d.ts +15 -6
- package/src/workflows/workflow-launch-record.js +30 -12
- package/src/workflows/workflow-receipt.js +36 -53
- package/src/workflows/workflow-resources.js +4 -4
- package/src/workflows/workflow-resume-claim.d.ts +2 -0
- package/src/workflows/workflow-resume-claim.js +3 -3
- package/src/workflows/workflow-resume.d.ts +1 -1
- package/src/workflows/workflow-resume.js +13 -8
- package/src/workflows/workflow-script-worker.d.ts +13 -0
- package/src/workflows/workflow-script-worker.js +81 -0
- package/workflow-script-process.cjs +36 -0
- package/workflow-script-worker.cjs +4 -1
- package/bundle/chunk-U4ODUYAG.js +0 -235
|
@@ -1,6 +1,11 @@
|
|
|
1
1
|
import {
|
|
2
|
-
PROJECT_SUBAGENTS_RELATIVE_DIR
|
|
3
|
-
|
|
2
|
+
PROJECT_SUBAGENTS_RELATIVE_DIR,
|
|
3
|
+
canonicalSessionId,
|
|
4
|
+
inspectSessionLease
|
|
5
|
+
} from "./chunk-LYKG4FKH.js";
|
|
6
|
+
import {
|
|
7
|
+
agentDefinitionDigest
|
|
8
|
+
} from "./chunk-BGIYHF2W.js";
|
|
4
9
|
import {
|
|
5
10
|
DEFAULT_FILE_SYSTEM_RETRY_DELAYS_MS,
|
|
6
11
|
DEFAULT_GLOBAL_CONCURRENCY_LIMIT,
|
|
@@ -24,7 +29,7 @@ import {
|
|
|
24
29
|
withFileLease,
|
|
25
30
|
writeAtomicJson,
|
|
26
31
|
writePrivateAtomicJson
|
|
27
|
-
} from "./chunk-
|
|
32
|
+
} from "./chunk-XAC2XNAP.js";
|
|
28
33
|
import {
|
|
29
34
|
DIRS,
|
|
30
35
|
SUBAGENT_LIFECYCLE_ARTIFACT_VERSION,
|
|
@@ -466,53 +471,10 @@ function writeProcessTerminalCandidate(asyncDir, candidate) {
|
|
|
466
471
|
}
|
|
467
472
|
|
|
468
473
|
// src/runs/background/process-terminal.ts
|
|
469
|
-
import * as fs5 from "node:fs";
|
|
470
|
-
import * as path6 from "node:path";
|
|
471
|
-
|
|
472
|
-
// src/runs/shared/session-lease.ts
|
|
473
|
-
import { createHash as createHash2, randomUUID } from "node:crypto";
|
|
474
474
|
import * as fs4 from "node:fs";
|
|
475
475
|
import * as path5 from "node:path";
|
|
476
|
-
var SESSION_LEASES_DIR = path5.join(TEMP_ROOT_DIR, "session-leases");
|
|
477
|
-
function canonicalSessionFilePath(sessionFile) {
|
|
478
|
-
return fs4.realpathSync.native(path5.resolve(sessionFile));
|
|
479
|
-
}
|
|
480
|
-
function canonicalSessionId(sessionFile) {
|
|
481
|
-
const canonical = canonicalSessionFilePath(sessionFile);
|
|
482
|
-
const key = process.platform === "win32" ? canonical.toLowerCase() : canonical;
|
|
483
|
-
return createHash2("sha256").update(key).digest("hex");
|
|
484
|
-
}
|
|
485
|
-
function inspectSessionLease(sessionFile, rootDir = SESSION_LEASES_DIR) {
|
|
486
|
-
const canonicalSessionFile = canonicalSessionFilePath(sessionFile);
|
|
487
|
-
const canonicalSessionIdValue = canonicalSessionId(canonicalSessionFile);
|
|
488
|
-
const leaseDir = path5.join(rootDir, canonicalSessionIdValue);
|
|
489
|
-
if (!fs4.existsSync(leaseDir)) return { state: "free", canonicalSessionFile, canonicalSessionId: canonicalSessionIdValue };
|
|
490
|
-
const owner = readLeaseOwner(leaseDir);
|
|
491
|
-
return owner ? { state: "owned", canonicalSessionFile, canonicalSessionId: canonicalSessionIdValue, owner } : { state: "unreadable", canonicalSessionFile, canonicalSessionId: canonicalSessionIdValue };
|
|
492
|
-
}
|
|
493
|
-
function parseOwner(value) {
|
|
494
|
-
if (!value || typeof value !== "object" || Array.isArray(value)) return void 0;
|
|
495
|
-
const owner = value;
|
|
496
|
-
if (owner.version !== 1 || typeof owner.token !== "string" || typeof owner.canonicalSessionFile !== "string" || typeof owner.runId !== "string" || typeof owner.sourceRunId !== "string" || typeof owner.pid !== "number" || !Number.isInteger(owner.pid) || owner.pid <= 0 || typeof owner.hostname !== "string" || owner.writerState !== "none" && owner.writerState !== "spawning" && owner.writerState !== "running" || typeof owner.acquiredAt !== "string" || typeof owner.acquiredAtMs !== "number" || typeof owner.updatedAtMs !== "number") return void 0;
|
|
497
|
-
if (owner.parentSessionId !== void 0 && typeof owner.parentSessionId !== "string") return void 0;
|
|
498
|
-
if (owner.processStartIdentity !== void 0 && typeof owner.processStartIdentity !== "string") return void 0;
|
|
499
|
-
if (owner.writerPid !== void 0 && (typeof owner.writerPid !== "number" || !Number.isInteger(owner.writerPid) || owner.writerPid <= 0)) return void 0;
|
|
500
|
-
if (owner.writerProcessStartIdentity !== void 0 && typeof owner.writerProcessStartIdentity !== "string") return void 0;
|
|
501
|
-
if (owner.writerState === "running" && owner.writerPid === void 0) return void 0;
|
|
502
|
-
if (owner.writerState !== "running" && (owner.writerPid !== void 0 || owner.writerProcessStartIdentity !== void 0)) return void 0;
|
|
503
|
-
return owner;
|
|
504
|
-
}
|
|
505
|
-
function readLeaseOwner(leaseDir) {
|
|
506
|
-
try {
|
|
507
|
-
return parseOwner(JSON.parse(fs4.readFileSync(path5.join(leaseDir, "owner.json"), "utf-8")));
|
|
508
|
-
} catch {
|
|
509
|
-
return void 0;
|
|
510
|
-
}
|
|
511
|
-
}
|
|
512
|
-
|
|
513
|
-
// src/runs/background/process-terminal.ts
|
|
514
476
|
function processTerminalPath(asyncDir) {
|
|
515
|
-
return
|
|
477
|
+
return path5.join(asyncDir, "process-terminal.json");
|
|
516
478
|
}
|
|
517
479
|
function errorMessage(error) {
|
|
518
480
|
return error instanceof Error ? error.message : String(error);
|
|
@@ -537,7 +499,7 @@ function unknownProof(runId, runnerProcessInstanceId, reason, diagnostic) {
|
|
|
537
499
|
function resumeDisposition(state, sessionFile) {
|
|
538
500
|
if (state === "stopped") return "non-resumable";
|
|
539
501
|
if (state !== "complete" && state !== "completed" && state !== "failed" && state !== "paused") return "unavailable";
|
|
540
|
-
return sessionFile &&
|
|
502
|
+
return sessionFile && fs4.existsSync(sessionFile) ? "resumable" : "unavailable";
|
|
541
503
|
}
|
|
542
504
|
function sessionProjection(candidate, lease) {
|
|
543
505
|
if (!candidate.sessionFile || lease.state !== "free") return void 0;
|
|
@@ -578,12 +540,12 @@ function sanitizeProcessTerminal(value, fallback, label = "status") {
|
|
|
578
540
|
}
|
|
579
541
|
function readProcessTerminal(asyncDir, fallback) {
|
|
580
542
|
try {
|
|
581
|
-
const raw = JSON.parse(
|
|
543
|
+
const raw = JSON.parse(fs4.readFileSync(processTerminalPath(asyncDir), "utf-8"));
|
|
582
544
|
validateProof(raw, asyncDir, fallback);
|
|
583
545
|
return raw;
|
|
584
546
|
} catch (error) {
|
|
585
547
|
if (error.code === "ENOENT") return void 0;
|
|
586
|
-
return unknownProof(fallback?.runId ??
|
|
548
|
+
return unknownProof(fallback?.runId ?? path5.basename(asyncDir), fallback?.runnerProcessInstanceId ?? "unknown", "proof-write-failed", errorMessage(error));
|
|
587
549
|
}
|
|
588
550
|
}
|
|
589
551
|
function stepProcessTerminalProof(proof, childIndex, state, records, resumeDispositionValue) {
|
|
@@ -603,9 +565,9 @@ function stepProcessTerminalProof(proof, childIndex, state, records, resumeDispo
|
|
|
603
565
|
return { ...base, state };
|
|
604
566
|
}
|
|
605
567
|
function overlayStatus(asyncDir, proof, candidate) {
|
|
606
|
-
const statusPath =
|
|
568
|
+
const statusPath = path5.join(asyncDir, "status.json");
|
|
607
569
|
try {
|
|
608
|
-
const status = JSON.parse(
|
|
570
|
+
const status = JSON.parse(fs4.readFileSync(statusPath, "utf-8"));
|
|
609
571
|
status.processTerminal = proof;
|
|
610
572
|
if (status.steps) {
|
|
611
573
|
for (const [index, step] of status.steps.entries()) {
|
|
@@ -621,7 +583,7 @@ function overlayStatus(asyncDir, proof, candidate) {
|
|
|
621
583
|
}
|
|
622
584
|
function finalizeProcessTerminal(asyncDir, runId, runnerClose) {
|
|
623
585
|
const existing = readProcessTerminal(asyncDir, { runId, runnerProcessInstanceId: runnerClose.processInstanceId });
|
|
624
|
-
if (existing &&
|
|
586
|
+
if (existing && fs4.existsSync(processTerminalPath(asyncDir))) {
|
|
625
587
|
if (existing.state === "observed" && existing.runId === runId && existing.runnerProcessInstanceId === runnerClose.processInstanceId) return existing;
|
|
626
588
|
if (existing.state === "unknown") {
|
|
627
589
|
if (existing.instances?.length || existing.reason === "proof-write-failed") return existing;
|
|
@@ -645,7 +607,7 @@ function finalizeProcessTerminal(asyncDir, runId, runnerClose) {
|
|
|
645
607
|
const allWriters = Object.values(candidate.writers).flat();
|
|
646
608
|
const status = (() => {
|
|
647
609
|
try {
|
|
648
|
-
return JSON.parse(
|
|
610
|
+
return JSON.parse(fs4.readFileSync(path5.join(asyncDir, "status.json"), "utf-8"));
|
|
649
611
|
} catch {
|
|
650
612
|
return void 0;
|
|
651
613
|
}
|
|
@@ -690,7 +652,7 @@ function finalizeProcessTerminal(asyncDir, runId, runnerClose) {
|
|
|
690
652
|
durable = true;
|
|
691
653
|
if (proof.state === "observed") releaseActiveRunIndex(asyncDir);
|
|
692
654
|
overlayStatus(asyncDir, proof, candidateForOverlay);
|
|
693
|
-
|
|
655
|
+
fs4.appendFileSync(path5.join(asyncDir, "events.jsonl"), `${JSON.stringify({ type: "subagent.run.process_terminal", lifecycleArtifactVersion: SUBAGENT_LIFECYCLE_ARTIFACT_VERSION, ts: Date.now(), runId, processTerminal: proof })}
|
|
694
656
|
`, "utf-8");
|
|
695
657
|
} catch {
|
|
696
658
|
}
|
|
@@ -698,10 +660,10 @@ function finalizeProcessTerminal(asyncDir, runId, runnerClose) {
|
|
|
698
660
|
}
|
|
699
661
|
|
|
700
662
|
// src/runs/shared/nested-events.ts
|
|
701
|
-
import { randomUUID
|
|
702
|
-
import * as
|
|
703
|
-
import * as
|
|
704
|
-
var NESTED_EVENTS_DIR =
|
|
663
|
+
import { randomUUID } from "node:crypto";
|
|
664
|
+
import * as fs5 from "node:fs";
|
|
665
|
+
import * as path6 from "node:path";
|
|
666
|
+
var NESTED_EVENTS_DIR = path6.join(TEMP_ROOT_DIR, "nested-subagent-events");
|
|
705
667
|
var ROUTE_FILE = "route.json";
|
|
706
668
|
var REGISTRY_FILE = "registry.json";
|
|
707
669
|
var ROUTE_INDEX_DIR = ".route-index";
|
|
@@ -719,50 +681,50 @@ function assertSafeId(label, value) {
|
|
|
719
681
|
assertSafeNestedId(label, value);
|
|
720
682
|
}
|
|
721
683
|
function containedPath(base, candidate) {
|
|
722
|
-
const resolvedBase =
|
|
723
|
-
const resolvedCandidate =
|
|
724
|
-
return resolvedCandidate === resolvedBase || resolvedCandidate.startsWith(`${resolvedBase}${
|
|
684
|
+
const resolvedBase = path6.resolve(base);
|
|
685
|
+
const resolvedCandidate = path6.resolve(candidate);
|
|
686
|
+
return resolvedCandidate === resolvedBase || resolvedCandidate.startsWith(`${resolvedBase}${path6.sep}`);
|
|
725
687
|
}
|
|
726
688
|
function commonRouteRoot(route) {
|
|
727
|
-
return
|
|
689
|
+
return path6.dirname(path6.resolve(route.eventSink));
|
|
728
690
|
}
|
|
729
691
|
function routeIndexRoot() {
|
|
730
|
-
return
|
|
692
|
+
return path6.join(NESTED_EVENTS_DIR, ROUTE_INDEX_DIR, "roots");
|
|
731
693
|
}
|
|
732
694
|
function routeIndexDir(rootRunId) {
|
|
733
|
-
return
|
|
695
|
+
return path6.join(routeIndexRoot(), encodeURIComponent(rootRunId));
|
|
734
696
|
}
|
|
735
697
|
function routeIndexPath(rootRunId, capabilityToken) {
|
|
736
|
-
return
|
|
698
|
+
return path6.join(routeIndexDir(rootRunId), `${encodeURIComponent(capabilityToken)}.json`);
|
|
737
699
|
}
|
|
738
700
|
function validateRouteShape(route) {
|
|
739
701
|
assertSafeId("rootRunId", route.rootRunId);
|
|
740
702
|
assertSafeId("capabilityToken", route.capabilityToken);
|
|
741
703
|
if (!containedPath(NESTED_EVENTS_DIR, route.eventSink)) throw new Error("Nested event sink is outside the subagent nested event root.");
|
|
742
704
|
if (!containedPath(NESTED_EVENTS_DIR, route.controlInbox)) throw new Error("Nested control inbox is outside the subagent nested event root.");
|
|
743
|
-
if (commonRouteRoot(route) !==
|
|
705
|
+
if (commonRouteRoot(route) !== path6.dirname(path6.resolve(route.controlInbox))) throw new Error("Nested event sink and control inbox must share one route root.");
|
|
744
706
|
}
|
|
745
707
|
function createNestedRoute(rootRunId) {
|
|
746
708
|
assertSafeId("rootRunId", rootRunId);
|
|
747
|
-
const capabilityToken =
|
|
748
|
-
const routeRoot =
|
|
749
|
-
const eventSink =
|
|
750
|
-
const controlInbox =
|
|
751
|
-
|
|
752
|
-
|
|
709
|
+
const capabilityToken = randomUUID();
|
|
710
|
+
const routeRoot = path6.join(NESTED_EVENTS_DIR, `${rootRunId}-${capabilityToken}`);
|
|
711
|
+
const eventSink = path6.join(routeRoot, "events");
|
|
712
|
+
const controlInbox = path6.join(routeRoot, "controls");
|
|
713
|
+
fs5.mkdirSync(eventSink, { recursive: true, mode: 448 });
|
|
714
|
+
fs5.mkdirSync(controlInbox, { recursive: true, mode: 448 });
|
|
753
715
|
const createdAt = Date.now();
|
|
754
|
-
|
|
755
|
-
writeAtomicJson(routeIndexPath(rootRunId, capabilityToken), { rootRunId, capabilityToken, routeRoot:
|
|
756
|
-
writeAtomicJson(
|
|
716
|
+
fs5.mkdirSync(routeIndexDir(rootRunId), { recursive: true, mode: 448 });
|
|
717
|
+
writeAtomicJson(routeIndexPath(rootRunId, capabilityToken), { rootRunId, capabilityToken, routeRoot: path6.basename(routeRoot), createdAt });
|
|
718
|
+
writeAtomicJson(path6.join(routeRoot, ROUTE_FILE), { rootRunId, capabilityToken, createdAt });
|
|
757
719
|
return { rootRunId, eventSink, controlInbox, capabilityToken };
|
|
758
720
|
}
|
|
759
721
|
function resolveNestedRoute(route) {
|
|
760
722
|
const { rootRunId, capabilityToken } = route;
|
|
761
723
|
validateRouteShape(route);
|
|
762
|
-
const routeFile =
|
|
724
|
+
const routeFile = path6.join(commonRouteRoot(route), ROUTE_FILE);
|
|
763
725
|
let metadata;
|
|
764
726
|
try {
|
|
765
|
-
const parsed = JSON.parse(
|
|
727
|
+
const parsed = JSON.parse(fs5.readFileSync(routeFile, "utf-8"));
|
|
766
728
|
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
|
|
767
729
|
throw new Error("route metadata must be an object");
|
|
768
730
|
}
|
|
@@ -803,10 +765,10 @@ function nestedRunNotActiveMessage(runId) {
|
|
|
803
765
|
}
|
|
804
766
|
function resolveNestedAsyncDir(rootRunId, run) {
|
|
805
767
|
if (!run.asyncDir) return void 0;
|
|
806
|
-
const resolved2 =
|
|
807
|
-
const nestedRoot =
|
|
808
|
-
const relative4 =
|
|
809
|
-
return resolved2 === nestedRoot || !relative4.startsWith("..") && !
|
|
768
|
+
const resolved2 = path6.resolve(run.asyncDir);
|
|
769
|
+
const nestedRoot = path6.resolve(TEMP_ROOT_DIR, "nested-subagent-runs", rootRunId, run.id);
|
|
770
|
+
const relative4 = path6.relative(nestedRoot, resolved2);
|
|
771
|
+
return resolved2 === nestedRoot || !relative4.startsWith("..") && !path6.isAbsolute(relative4) ? resolved2 : void 0;
|
|
810
772
|
}
|
|
811
773
|
function clampNumber(value) {
|
|
812
774
|
return typeof value === "number" && Number.isFinite(value) ? value : void 0;
|
|
@@ -1125,24 +1087,24 @@ function applyNestedEvent(registry, event) {
|
|
|
1125
1087
|
};
|
|
1126
1088
|
}
|
|
1127
1089
|
function registryPath(route) {
|
|
1128
|
-
return
|
|
1090
|
+
return path6.join(commonRouteRoot(route), REGISTRY_FILE);
|
|
1129
1091
|
}
|
|
1130
1092
|
function routeFromIndexEntry(rootRunId, filePath) {
|
|
1131
1093
|
try {
|
|
1132
|
-
const metadata = JSON.parse(
|
|
1094
|
+
const metadata = JSON.parse(fs5.readFileSync(filePath, "utf-8"));
|
|
1133
1095
|
if (metadata.rootRunId !== rootRunId || typeof metadata.capabilityToken !== "string" || typeof metadata.routeRoot !== "string") return void 0;
|
|
1134
|
-
const routeRoot =
|
|
1096
|
+
const routeRoot = path6.join(NESTED_EVENTS_DIR, path6.basename(metadata.routeRoot));
|
|
1135
1097
|
const route = {
|
|
1136
1098
|
rootRunId,
|
|
1137
|
-
eventSink:
|
|
1138
|
-
controlInbox:
|
|
1099
|
+
eventSink: path6.join(routeRoot, "events"),
|
|
1100
|
+
controlInbox: path6.join(routeRoot, "controls"),
|
|
1139
1101
|
capabilityToken: metadata.capabilityToken
|
|
1140
1102
|
};
|
|
1141
1103
|
validateRouteShape(route);
|
|
1142
|
-
if (!
|
|
1143
|
-
const routeFilePath =
|
|
1104
|
+
if (!fs5.statSync(route.eventSink).isDirectory() || !fs5.statSync(route.controlInbox).isDirectory()) return void 0;
|
|
1105
|
+
const routeFilePath = path6.join(routeRoot, ROUTE_FILE);
|
|
1144
1106
|
try {
|
|
1145
|
-
const routeFile = JSON.parse(
|
|
1107
|
+
const routeFile = JSON.parse(fs5.readFileSync(routeFilePath, "utf-8"));
|
|
1146
1108
|
if (routeFile.rootRunId !== rootRunId || routeFile.capabilityToken !== metadata.capabilityToken) return void 0;
|
|
1147
1109
|
} catch (error) {
|
|
1148
1110
|
if (error.code !== "ENOENT") return void 0;
|
|
@@ -1160,13 +1122,13 @@ function findNestedRouteForRootId(rootRunId) {
|
|
|
1160
1122
|
assertSafeId("rootRunId", rootRunId);
|
|
1161
1123
|
let entries;
|
|
1162
1124
|
try {
|
|
1163
|
-
entries =
|
|
1125
|
+
entries = fs5.readdirSync(routeIndexDir(rootRunId));
|
|
1164
1126
|
} catch (error) {
|
|
1165
1127
|
if (error.code === "ENOENT") return void 0;
|
|
1166
1128
|
throw error;
|
|
1167
1129
|
}
|
|
1168
1130
|
for (const entry of entries) {
|
|
1169
|
-
const route = routeFromIndexEntry(rootRunId,
|
|
1131
|
+
const route = routeFromIndexEntry(rootRunId, path6.join(routeIndexDir(rootRunId), entry));
|
|
1170
1132
|
if (route) return route;
|
|
1171
1133
|
}
|
|
1172
1134
|
return void 0;
|
|
@@ -1212,7 +1174,7 @@ function collectScopedNestedRuns(children, scope, output = []) {
|
|
|
1212
1174
|
function listNestedRoutes() {
|
|
1213
1175
|
let rootEntries;
|
|
1214
1176
|
try {
|
|
1215
|
-
rootEntries =
|
|
1177
|
+
rootEntries = fs5.readdirSync(routeIndexRoot());
|
|
1216
1178
|
} catch (error) {
|
|
1217
1179
|
if (error.code === "ENOENT") return [];
|
|
1218
1180
|
throw error;
|
|
@@ -1226,8 +1188,8 @@ function listNestedRoutes() {
|
|
|
1226
1188
|
continue;
|
|
1227
1189
|
}
|
|
1228
1190
|
try {
|
|
1229
|
-
for (const entry of
|
|
1230
|
-
const route = routeFromIndexEntry(rootRunId,
|
|
1191
|
+
for (const entry of fs5.readdirSync(path6.join(routeIndexRoot(), rootEntry))) {
|
|
1192
|
+
const route = routeFromIndexEntry(rootRunId, path6.join(routeIndexRoot(), rootEntry, entry));
|
|
1231
1193
|
if (route) routes.push(route);
|
|
1232
1194
|
}
|
|
1233
1195
|
} catch {
|
|
@@ -1254,7 +1216,7 @@ function findNestedRunMatchesById(id, options = {}) {
|
|
|
1254
1216
|
function readNestedRegistry(route) {
|
|
1255
1217
|
validateRouteShape(route);
|
|
1256
1218
|
try {
|
|
1257
|
-
const parsed = JSON.parse(
|
|
1219
|
+
const parsed = JSON.parse(fs5.readFileSync(registryPath(route), "utf-8"));
|
|
1258
1220
|
return {
|
|
1259
1221
|
rootRunId: route.rootRunId,
|
|
1260
1222
|
updatedAt: typeof parsed.updatedAt === "number" ? parsed.updatedAt : 0,
|
|
@@ -1273,19 +1235,19 @@ function projectNestedEvents(route) {
|
|
|
1273
1235
|
let changed = false;
|
|
1274
1236
|
let entries = [];
|
|
1275
1237
|
try {
|
|
1276
|
-
entries =
|
|
1238
|
+
entries = fs5.readdirSync(route.eventSink).filter((entry) => entry.endsWith(".json") || entry.endsWith(".jsonl")).sort();
|
|
1277
1239
|
} catch (error) {
|
|
1278
1240
|
if (error.code !== "ENOENT") throw error;
|
|
1279
1241
|
}
|
|
1280
1242
|
for (const entry of entries) {
|
|
1281
1243
|
if (seen.has(entry)) continue;
|
|
1282
|
-
const eventPath =
|
|
1244
|
+
const eventPath = path6.join(route.eventSink, entry);
|
|
1283
1245
|
if (!containedPath(route.eventSink, eventPath)) continue;
|
|
1284
1246
|
let content;
|
|
1285
1247
|
try {
|
|
1286
|
-
const stat =
|
|
1248
|
+
const stat = fs5.statSync(eventPath);
|
|
1287
1249
|
if (!stat.isFile() || stat.size > MAX_EVENT_BYTES) continue;
|
|
1288
|
-
content =
|
|
1250
|
+
content = fs5.readFileSync(eventPath, "utf-8");
|
|
1289
1251
|
} catch {
|
|
1290
1252
|
continue;
|
|
1291
1253
|
}
|
|
@@ -1305,15 +1267,15 @@ function projectNestedEvents(route) {
|
|
|
1305
1267
|
registry = { ...registry, processedEvents: retainedEvents };
|
|
1306
1268
|
writeAtomicJson(registryPath(route), registry);
|
|
1307
1269
|
for (const entry of evictedEvents) {
|
|
1308
|
-
const eventPath =
|
|
1270
|
+
const eventPath = path6.join(route.eventSink, entry);
|
|
1309
1271
|
if (!containedPath(route.eventSink, eventPath)) continue;
|
|
1310
1272
|
try {
|
|
1311
|
-
const stat =
|
|
1273
|
+
const stat = fs5.statSync(eventPath);
|
|
1312
1274
|
if (!stat.isFile() || stat.size > MAX_EVENT_BYTES) continue;
|
|
1313
|
-
const content =
|
|
1275
|
+
const content = fs5.readFileSync(eventPath, "utf-8");
|
|
1314
1276
|
const hasStatusRecord = parseNestedEventRecords(content, route).length > 0;
|
|
1315
1277
|
const hasControlResult = content.split("\n").some((line) => line.trim() && parseControlResult(line.trim(), route));
|
|
1316
|
-
if (hasStatusRecord && !hasControlResult)
|
|
1278
|
+
if (hasStatusRecord && !hasControlResult) fs5.unlinkSync(eventPath);
|
|
1317
1279
|
} catch {
|
|
1318
1280
|
}
|
|
1319
1281
|
}
|
|
@@ -1324,12 +1286,12 @@ function writeRouteRecord(dir, ts, payload) {
|
|
|
1324
1286
|
const content = `${JSON.stringify(payload)}
|
|
1325
1287
|
`;
|
|
1326
1288
|
if (Buffer.byteLength(content, "utf-8") > MAX_EVENT_BYTES) throw new Error("Nested route record exceeds the maximum size.");
|
|
1327
|
-
|
|
1328
|
-
const name = `${String(ts).padStart(13, "0")}-${
|
|
1329
|
-
const tmp =
|
|
1330
|
-
const finalPath =
|
|
1331
|
-
|
|
1332
|
-
|
|
1289
|
+
fs5.mkdirSync(dir, { recursive: true, mode: 448 });
|
|
1290
|
+
const name = `${String(ts).padStart(13, "0")}-${randomUUID()}.json`;
|
|
1291
|
+
const tmp = path6.join(dir, `.${name}.tmp`);
|
|
1292
|
+
const finalPath = path6.join(dir, name);
|
|
1293
|
+
fs5.writeFileSync(tmp, content, { mode: 384 });
|
|
1294
|
+
fs5.renameSync(tmp, finalPath);
|
|
1333
1295
|
return finalPath;
|
|
1334
1296
|
}
|
|
1335
1297
|
function writeNestedEvent(route, event) {
|
|
@@ -1414,18 +1376,18 @@ function readNestedControlRequests(route) {
|
|
|
1414
1376
|
validateRouteShape(route);
|
|
1415
1377
|
let entries = [];
|
|
1416
1378
|
try {
|
|
1417
|
-
entries =
|
|
1379
|
+
entries = fs5.readdirSync(route.controlInbox).filter((entry) => entry.endsWith(".json")).sort();
|
|
1418
1380
|
} catch (error) {
|
|
1419
1381
|
if (error.code !== "ENOENT") throw error;
|
|
1420
1382
|
}
|
|
1421
1383
|
const requests = [];
|
|
1422
1384
|
for (const entry of entries) {
|
|
1423
|
-
const filePath =
|
|
1385
|
+
const filePath = path6.join(route.controlInbox, entry);
|
|
1424
1386
|
if (!containedPath(route.controlInbox, filePath)) continue;
|
|
1425
1387
|
try {
|
|
1426
|
-
const stat =
|
|
1388
|
+
const stat = fs5.statSync(filePath);
|
|
1427
1389
|
if (!stat.isFile() || stat.size > MAX_EVENT_BYTES) continue;
|
|
1428
|
-
const request = parseControlRequest(
|
|
1390
|
+
const request = parseControlRequest(fs5.readFileSync(filePath, "utf-8"), route);
|
|
1429
1391
|
if (request) requests.push({ ...request, filePath });
|
|
1430
1392
|
} catch {
|
|
1431
1393
|
continue;
|
|
@@ -1450,9 +1412,9 @@ function writeNestedControlResult(route, result) {
|
|
|
1450
1412
|
function readControlResultsFromFile(route, eventPath) {
|
|
1451
1413
|
if (!containedPath(route.eventSink, eventPath)) return [];
|
|
1452
1414
|
try {
|
|
1453
|
-
const stat =
|
|
1415
|
+
const stat = fs5.statSync(eventPath);
|
|
1454
1416
|
if (!stat.isFile() || stat.size > MAX_EVENT_BYTES) return [];
|
|
1455
|
-
const content =
|
|
1417
|
+
const content = fs5.readFileSync(eventPath, "utf-8");
|
|
1456
1418
|
const lines = content.includes("\n") ? content.split("\n").filter((line) => line.trim()) : [content];
|
|
1457
1419
|
return lines.map((line) => parseControlResult(line, route)).filter((result) => Boolean(result));
|
|
1458
1420
|
} catch {
|
|
@@ -1462,7 +1424,7 @@ function readControlResultsFromFile(route, eventPath) {
|
|
|
1462
1424
|
function listNestedEventFiles(route) {
|
|
1463
1425
|
validateRouteShape(route);
|
|
1464
1426
|
try {
|
|
1465
|
-
return
|
|
1427
|
+
return fs5.readdirSync(route.eventSink).filter((entry) => entry.endsWith(".json") || entry.endsWith(".jsonl"));
|
|
1466
1428
|
} catch (error) {
|
|
1467
1429
|
if (error.code === "ENOENT") return [];
|
|
1468
1430
|
throw error;
|
|
@@ -1474,7 +1436,7 @@ function snapshotNestedEventFiles(route) {
|
|
|
1474
1436
|
function findNestedControlResult(route, requestId, targetRunId, ignoredFiles) {
|
|
1475
1437
|
const entries = listNestedEventFiles(route).filter((entry) => !ignoredFiles.has(entry)).sort().reverse();
|
|
1476
1438
|
for (const entry of entries) {
|
|
1477
|
-
const result = readControlResultsFromFile(route,
|
|
1439
|
+
const result = readControlResultsFromFile(route, path6.join(route.eventSink, entry)).find((candidate) => candidate.requestId === requestId && candidate.targetRunId === targetRunId);
|
|
1478
1440
|
if (result) return result;
|
|
1479
1441
|
}
|
|
1480
1442
|
return void 0;
|
|
@@ -1597,13 +1559,13 @@ function nestedSummaryFromAsyncStatus(status, asyncDir, fallback) {
|
|
|
1597
1559
|
function nestedRunScope(rootRunId) {
|
|
1598
1560
|
assertSafeId("rootRunId", rootRunId);
|
|
1599
1561
|
return {
|
|
1600
|
-
asyncDirRoot:
|
|
1601
|
-
resultsDir:
|
|
1562
|
+
asyncDirRoot: path6.join(TEMP_ROOT_DIR, "nested-subagent-runs", rootRunId),
|
|
1563
|
+
resultsDir: path6.join(DIRS.results, "nested", rootRunId)
|
|
1602
1564
|
};
|
|
1603
1565
|
}
|
|
1604
1566
|
function nestedResultsPath(rootRunId, id) {
|
|
1605
1567
|
assertSafeId("id", id);
|
|
1606
|
-
return
|
|
1568
|
+
return path6.join(nestedRunScope(rootRunId).resultsDir, `${id}.json`);
|
|
1607
1569
|
}
|
|
1608
1570
|
|
|
1609
1571
|
// src/runs/shared/host-step-status.ts
|
|
@@ -1797,11 +1759,38 @@ function hostStepReportName(reportPath) {
|
|
|
1797
1759
|
return reportPath.split(/[\\/]/).filter(Boolean).at(-1);
|
|
1798
1760
|
}
|
|
1799
1761
|
|
|
1762
|
+
// src/runs/shared/runner-launcher.ts
|
|
1763
|
+
var REQUIRE_LAUNCHER_SHAPE_ERROR = "requireLauncher is supported only on a top-level single-agent call (agent + task); it cannot be combined with tasks, chain, workflow, an action, resume, or a workflow child.";
|
|
1764
|
+
function lookupRunnerLauncher(runnerLaunchers, name) {
|
|
1765
|
+
const argv = runnerLaunchers && Object.hasOwn(runnerLaunchers, name) ? runnerLaunchers[name] : void 0;
|
|
1766
|
+
return argv ? { name, argv: [...argv] } : void 0;
|
|
1767
|
+
}
|
|
1768
|
+
function runnerLauncherPlacementError(agent, machine) {
|
|
1769
|
+
if (agent.launcher === void 0) return void 0;
|
|
1770
|
+
const runnerType = agent.runner?.type === "external-cli" || agent.runner?.type === "external-job" ? agent.runner.type : void 0;
|
|
1771
|
+
if (!machine && !runnerType) return void 0;
|
|
1772
|
+
return `Agent '${agent.name}' uses launcher '${agent.launcher}', which wraps the local Pi background runner, so it cannot run ${machine ? `on machine '${machine}'` : `with runner.type='${runnerType}'`}.`;
|
|
1773
|
+
}
|
|
1774
|
+
function resolveAgentRunnerLauncher(agent, runnerLaunchers, machine) {
|
|
1775
|
+
if (agent.launcher === void 0) return {};
|
|
1776
|
+
const placementError = runnerLauncherPlacementError(agent, machine);
|
|
1777
|
+
if (placementError) return { error: placementError };
|
|
1778
|
+
const launcher = lookupRunnerLauncher(runnerLaunchers, agent.launcher);
|
|
1779
|
+
return launcher ? { launcher } : { error: `Agent '${agent.name}' uses launcher '${agent.launcher}', which is not defined in runnerLaunchers in the user subagent config.` };
|
|
1780
|
+
}
|
|
1781
|
+
function checkRequiredRunnerLauncher(agent, launcherName, required) {
|
|
1782
|
+
if (launcherName === void 0) return { error: `Agent '${agent.name}' has no launcher, but the call requires launcher '${required.name}'.` };
|
|
1783
|
+
if (launcherName !== required.name) return { error: `Agent '${agent.name}' uses launcher '${launcherName}', but the call requires launcher '${required.name}'.` };
|
|
1784
|
+
const definitionDigest = agentDefinitionDigest(agent);
|
|
1785
|
+
if (definitionDigest !== required.definitionDigest) return { error: `Agent '${agent.name}' definition digest is ${definitionDigest}, but the call requires ${required.definitionDigest}; the agent definition changed after it was checked.` };
|
|
1786
|
+
return { definitionDigest };
|
|
1787
|
+
}
|
|
1788
|
+
|
|
1800
1789
|
// src/workflows/host-command.ts
|
|
1801
1790
|
import { spawn } from "node:child_process";
|
|
1802
|
-
import { randomUUID as
|
|
1803
|
-
import * as
|
|
1804
|
-
import * as
|
|
1791
|
+
import { randomUUID as randomUUID2 } from "node:crypto";
|
|
1792
|
+
import * as fs6 from "node:fs";
|
|
1793
|
+
import * as path7 from "node:path";
|
|
1805
1794
|
var MAX_COMMAND_BYTES = 16 * 1024;
|
|
1806
1795
|
var MAX_OUTPUT_PATH_BYTES = 240;
|
|
1807
1796
|
var MAX_CAPTURE_BYTES = 1024 * 1024;
|
|
@@ -1833,7 +1822,7 @@ function normalizeWorkflowHostCommandParams(value, label = "runs.host params") {
|
|
|
1833
1822
|
if (params.output !== void 0) {
|
|
1834
1823
|
if (typeof params.output !== "string" || !params.output.trim()) throw new Error(`${label}.output must be a non-empty relative path.`);
|
|
1835
1824
|
output = params.output.trim();
|
|
1836
|
-
if (
|
|
1825
|
+
if (path7.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.`);
|
|
1837
1826
|
}
|
|
1838
1827
|
if (params.role !== void 0 && params.role !== "ci" && params.role !== "gate") throw new Error(`${label}.role must be 'ci' or 'gate'.`);
|
|
1839
1828
|
let provider;
|
|
@@ -1858,19 +1847,19 @@ function resolveWorkflowHostOutputClaimPath(outputPath) {
|
|
|
1858
1847
|
return resolveSingleOutputClaimPath(outputPath);
|
|
1859
1848
|
}
|
|
1860
1849
|
function assertSafeExplicitOutput(cwd, outputPath, key) {
|
|
1861
|
-
const root =
|
|
1862
|
-
const outputParent =
|
|
1850
|
+
const root = fs6.realpathSync(cwd);
|
|
1851
|
+
const outputParent = path7.dirname(outputPath);
|
|
1863
1852
|
let existingParent = outputParent;
|
|
1864
|
-
while (!
|
|
1865
|
-
const existingParentReal =
|
|
1866
|
-
const existingRelative =
|
|
1867
|
-
if (existingRelative === ".." || existingRelative.startsWith(`..${
|
|
1868
|
-
|
|
1869
|
-
const parent =
|
|
1870
|
-
const relative4 =
|
|
1871
|
-
if (relative4 === ".." || relative4.startsWith(`..${
|
|
1853
|
+
while (!fs6.existsSync(existingParent)) existingParent = path7.dirname(existingParent);
|
|
1854
|
+
const existingParentReal = fs6.realpathSync(existingParent);
|
|
1855
|
+
const existingRelative = path7.relative(root, existingParentReal);
|
|
1856
|
+
if (existingRelative === ".." || existingRelative.startsWith(`..${path7.sep}`) || path7.isAbsolute(existingRelative)) throw new Error(`runs.host('${key}') output resolves outside the workflow cwd.`);
|
|
1857
|
+
fs6.mkdirSync(outputParent, { recursive: true });
|
|
1858
|
+
const parent = fs6.realpathSync(outputParent);
|
|
1859
|
+
const relative4 = path7.relative(root, parent);
|
|
1860
|
+
if (relative4 === ".." || relative4.startsWith(`..${path7.sep}`) || path7.isAbsolute(relative4)) throw new Error(`runs.host('${key}') output resolves outside the workflow cwd.`);
|
|
1872
1861
|
try {
|
|
1873
|
-
const stat =
|
|
1862
|
+
const stat = fs6.lstatSync(outputPath);
|
|
1874
1863
|
if (!stat.isFile() || stat.nlink > 1) throw new Error(`runs.host('${key}') output must be a regular, non-linked file path.`);
|
|
1875
1864
|
} catch (error) {
|
|
1876
1865
|
if (error.code !== "ENOENT") throw error;
|
|
@@ -1878,24 +1867,24 @@ function assertSafeExplicitOutput(cwd, outputPath, key) {
|
|
|
1878
1867
|
return parent;
|
|
1879
1868
|
}
|
|
1880
1869
|
function writeExplicitOutput(outputParent, outputPath, capture, key) {
|
|
1881
|
-
const destination =
|
|
1882
|
-
const temporaryPath =
|
|
1870
|
+
const destination = path7.join(outputParent, path7.basename(outputPath));
|
|
1871
|
+
const temporaryPath = path7.join(outputParent, `.pi-host-output-${process.pid}-${randomUUID2()}.tmp`);
|
|
1883
1872
|
let descriptor;
|
|
1884
1873
|
try {
|
|
1885
|
-
descriptor =
|
|
1886
|
-
|
|
1887
|
-
|
|
1874
|
+
descriptor = fs6.openSync(temporaryPath, fs6.constants.O_WRONLY | fs6.constants.O_CREAT | fs6.constants.O_EXCL, 384);
|
|
1875
|
+
fs6.writeFileSync(descriptor, capture, { encoding: "utf8" });
|
|
1876
|
+
fs6.closeSync(descriptor);
|
|
1888
1877
|
descriptor = void 0;
|
|
1889
|
-
|
|
1890
|
-
runFileSystemOperationWithRetry(() =>
|
|
1878
|
+
fs6.chmodSync(temporaryPath, 384);
|
|
1879
|
+
runFileSystemOperationWithRetry(() => fs6.renameSync(temporaryPath, destination), {
|
|
1891
1880
|
retryDelaysMs: process.platform === "win32" ? DEFAULT_FILE_SYSTEM_RETRY_DELAYS_MS : []
|
|
1892
1881
|
});
|
|
1893
1882
|
} catch (error) {
|
|
1894
1883
|
throw new Error(`runs.host('${key}') could not atomically replace its output.`, { cause: error instanceof Error ? error : void 0 });
|
|
1895
1884
|
} finally {
|
|
1896
|
-
if (descriptor !== void 0)
|
|
1885
|
+
if (descriptor !== void 0) fs6.closeSync(descriptor);
|
|
1897
1886
|
try {
|
|
1898
|
-
|
|
1887
|
+
fs6.unlinkSync(temporaryPath);
|
|
1899
1888
|
} catch (error) {
|
|
1900
1889
|
if (error.code !== "ENOENT") throw error;
|
|
1901
1890
|
}
|
|
@@ -1903,22 +1892,22 @@ function writeExplicitOutput(outputParent, outputPath, capture, key) {
|
|
|
1903
1892
|
}
|
|
1904
1893
|
function terminateProcessTree(pid, controller) {
|
|
1905
1894
|
if (process.platform !== "win32") return controller.terminate();
|
|
1906
|
-
return new Promise((
|
|
1895
|
+
return new Promise((resolve5) => {
|
|
1907
1896
|
const cleanup = spawn("taskkill", ["/PID", String(pid), "/T", "/F"], { stdio: "ignore", windowsHide: true });
|
|
1908
1897
|
cleanup.once("error", () => {
|
|
1909
|
-
void controller.terminate().then(
|
|
1898
|
+
void controller.terminate().then(resolve5);
|
|
1910
1899
|
});
|
|
1911
1900
|
cleanup.once("close", () => {
|
|
1912
|
-
void controller.terminate().then(
|
|
1901
|
+
void controller.terminate().then(resolve5);
|
|
1913
1902
|
});
|
|
1914
1903
|
});
|
|
1915
1904
|
}
|
|
1916
1905
|
async function executeWorkflowHostCommand(input) {
|
|
1917
|
-
const outputPath = input.params.output ?
|
|
1918
|
-
const relative4 =
|
|
1919
|
-
if (input.params.output && (relative4 === "" || relative4 === ".." || relative4.startsWith(`..${
|
|
1906
|
+
const outputPath = input.params.output ? path7.resolve(input.cwd, input.params.output) : input.defaultOutputPath;
|
|
1907
|
+
const relative4 = path7.relative(input.cwd, outputPath);
|
|
1908
|
+
if (input.params.output && (relative4 === "" || relative4 === ".." || relative4.startsWith(`..${path7.sep}`) || path7.isAbsolute(relative4))) throw new Error(`runs.host('${input.key}') output escapes the workflow cwd.`);
|
|
1920
1909
|
const explicitOutputParent = input.params.output ? assertSafeExplicitOutput(input.cwd, outputPath, input.key) : void 0;
|
|
1921
|
-
if (!input.params.output)
|
|
1910
|
+
if (!input.params.output) fs6.mkdirSync(path7.dirname(outputPath), { recursive: true });
|
|
1922
1911
|
const startedAt = Date.now();
|
|
1923
1912
|
let stdout = "";
|
|
1924
1913
|
let stderr = "";
|
|
@@ -1926,7 +1915,7 @@ async function executeWorkflowHostCommand(input) {
|
|
|
1926
1915
|
let timedOut = false;
|
|
1927
1916
|
let stopped = false;
|
|
1928
1917
|
let settled = false;
|
|
1929
|
-
return new Promise((
|
|
1918
|
+
return new Promise((resolve5, reject) => {
|
|
1930
1919
|
const child = spawn(quoteExecutableForShell(input.params.command), {
|
|
1931
1920
|
cwd: input.cwd,
|
|
1932
1921
|
env: process.env,
|
|
@@ -1976,13 +1965,13 @@ async function executeWorkflowHostCommand(input) {
|
|
|
1976
1965
|
if (currentParent !== explicitOutputParent) throw new Error(`output parent changed while the command was running.`);
|
|
1977
1966
|
writeExplicitOutput(explicitOutputParent, outputPath, capture, input.key);
|
|
1978
1967
|
} else {
|
|
1979
|
-
|
|
1968
|
+
fs6.writeFileSync(outputPath, capture, { encoding: "utf8", mode: 384 });
|
|
1980
1969
|
}
|
|
1981
1970
|
} catch (writeError) {
|
|
1982
1971
|
reject(new Error(`runs.host('${input.key}') could not save command output: ${writeError instanceof Error ? writeError.message : String(writeError)}`, { cause: writeError instanceof Error ? writeError : void 0 }));
|
|
1983
1972
|
return;
|
|
1984
1973
|
}
|
|
1985
|
-
|
|
1974
|
+
resolve5({ key: input.key, kind: "command", ok: state === "passed", state, exitCode, stdout, stderr, outputPath, durationMs: Date.now() - startedAt, ...error ? { error } : {} });
|
|
1986
1975
|
};
|
|
1987
1976
|
child.on("close", (code) => {
|
|
1988
1977
|
void finish(code);
|
|
@@ -1994,10 +1983,84 @@ async function executeWorkflowHostCommand(input) {
|
|
|
1994
1983
|
}
|
|
1995
1984
|
|
|
1996
1985
|
// src/workflows/scripted-workflow.ts
|
|
1997
|
-
import { accessSync, constants as constants2, readFileSync as
|
|
1986
|
+
import { accessSync, constants as constants2, readFileSync as readFileSync5, realpathSync as realpathSync3, statSync as statSync4 } from "node:fs";
|
|
1998
1987
|
import { createRequire } from "node:module";
|
|
1999
1988
|
import { dirname as dirname6, resolve as resolvePath } from "node:path";
|
|
1989
|
+
|
|
1990
|
+
// src/workflows/workflow-script-worker.ts
|
|
1991
|
+
import { fork } from "node:child_process";
|
|
1992
|
+
import { EventEmitter } from "node:events";
|
|
1993
|
+
import { realpathSync as realpathSync2 } from "node:fs";
|
|
1994
|
+
import { dirname as dirname5 } from "node:path";
|
|
1995
|
+
import { fileURLToPath } from "node:url";
|
|
2000
1996
|
import { Worker } from "node:worker_threads";
|
|
1997
|
+
var WORKFLOW_WORKER_URL = new URL("../../workflow-script-worker.cjs", new URL("../src/workflows/workflow-script-worker.js", import.meta.url).href);
|
|
1998
|
+
var WORKFLOW_PROCESS_URL = new URL("../../workflow-script-process.cjs", new URL("../src/workflows/workflow-script-worker.js", import.meta.url).href);
|
|
1999
|
+
var WorkflowScriptProcess = class extends EventEmitter {
|
|
2000
|
+
child;
|
|
2001
|
+
exitCode;
|
|
2002
|
+
stopping = false;
|
|
2003
|
+
stderr = "";
|
|
2004
|
+
constructor(acornPath) {
|
|
2005
|
+
super();
|
|
2006
|
+
const acorn = realpathSync2(acornPath);
|
|
2007
|
+
this.child = fork(fileURLToPath(WORKFLOW_PROCESS_URL), [acorn], {
|
|
2008
|
+
// Under --permission, Node lets worker threads read everything under the process cwd, so the cwd must
|
|
2009
|
+
// hold only public files: acorn's own directory. It also never holds a caller's cwd open on Windows.
|
|
2010
|
+
cwd: dirname5(acorn),
|
|
2011
|
+
// No inherited execArgv or NODE_OPTIONS. Only the supervisor may create a worker.
|
|
2012
|
+
execArgv: [
|
|
2013
|
+
"--permission",
|
|
2014
|
+
"--allow-worker",
|
|
2015
|
+
`--allow-fs-read=${realpathSync2(fileURLToPath(WORKFLOW_PROCESS_URL))}`,
|
|
2016
|
+
`--allow-fs-read=${realpathSync2(fileURLToPath(WORKFLOW_WORKER_URL))}`,
|
|
2017
|
+
`--allow-fs-read=${acorn}`
|
|
2018
|
+
],
|
|
2019
|
+
env: process.platform === "win32" && process.env.SystemRoot ? { SystemRoot: process.env.SystemRoot } : {},
|
|
2020
|
+
stdio: ["ignore", "ignore", "pipe", "ipc"]
|
|
2021
|
+
});
|
|
2022
|
+
this.child.stderr.on("data", (chunk) => {
|
|
2023
|
+
this.stderr = (this.stderr + chunk.toString("utf8")).slice(-4096);
|
|
2024
|
+
});
|
|
2025
|
+
this.child.on("error", (error) => this.emit("error", error));
|
|
2026
|
+
this.child.on("message", (json) => {
|
|
2027
|
+
if (this.stopping) return;
|
|
2028
|
+
try {
|
|
2029
|
+
if (typeof json !== "string") throw new Error("Workflow process sent a non-string IPC message.");
|
|
2030
|
+
const message = JSON.parse(json);
|
|
2031
|
+
if (!message || typeof message !== "object" || Array.isArray(message)) throw new Error("Workflow process sent an invalid IPC message.");
|
|
2032
|
+
this.emit("message", message);
|
|
2033
|
+
} catch (error) {
|
|
2034
|
+
this.emit("error", error);
|
|
2035
|
+
}
|
|
2036
|
+
});
|
|
2037
|
+
this.child.on("exit", (code) => {
|
|
2038
|
+
this.exitCode = code ?? 1;
|
|
2039
|
+
this.child.stderr.destroy();
|
|
2040
|
+
if (!this.stopping && code !== 0 && this.stderr.trim()) this.emit("error", new Error(this.stderr.trim()));
|
|
2041
|
+
this.emit("exit", this.exitCode);
|
|
2042
|
+
});
|
|
2043
|
+
}
|
|
2044
|
+
postMessage(message) {
|
|
2045
|
+
if (this.stopping || !this.child.connected) return;
|
|
2046
|
+
this.child.send(JSON.stringify(message), (error) => {
|
|
2047
|
+
if (error && !this.stopping) this.emit("error", error);
|
|
2048
|
+
});
|
|
2049
|
+
}
|
|
2050
|
+
async terminate() {
|
|
2051
|
+
if (this.exitCode !== void 0) return this.exitCode;
|
|
2052
|
+
this.stopping = true;
|
|
2053
|
+
return await new Promise((resolve5) => {
|
|
2054
|
+
this.once("exit", resolve5);
|
|
2055
|
+
this.child.kill("SIGKILL");
|
|
2056
|
+
});
|
|
2057
|
+
}
|
|
2058
|
+
};
|
|
2059
|
+
function createWorkflowScriptWorker(acornPath) {
|
|
2060
|
+
return typeof process.versions.bun === "string" ? new Worker(WORKFLOW_WORKER_URL, { workerData: { acornPath } }) : new WorkflowScriptProcess(acornPath);
|
|
2061
|
+
}
|
|
2062
|
+
|
|
2063
|
+
// src/workflows/scripted-workflow.ts
|
|
2001
2064
|
var KEY_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
|
|
2002
2065
|
var BASE_REF_VALIDATION_ERROR = "baseRef must be a valid Git ref: use HEAD or a supported named ref (for example, refs/heads/main). Full 40/64-character commit IDs and revision expressions are unsupported.";
|
|
2003
2066
|
function validGitRef(ref) {
|
|
@@ -2008,8 +2071,7 @@ function validGitRef(ref) {
|
|
|
2008
2071
|
}
|
|
2009
2072
|
var requireFromPackage = createRequire(new URL("../src/workflows/scripted-workflow.js", import.meta.url).href);
|
|
2010
2073
|
var WORKFLOW_ASSEMBLY_FLUSH_TIMEOUT_MS = 5e3;
|
|
2011
|
-
var
|
|
2012
|
-
var nodeWorkerSource;
|
|
2074
|
+
var WORKFLOW_DRAIN_CHILD_MESSAGE = "Workflow draining; child not started.";
|
|
2013
2075
|
function isWorkflowScriptFailureKind(value) {
|
|
2014
2076
|
return value === "validation" || value === "script" || value === "child" || value === "return-serialization" || value === "timeout" || value === "detached-child" || value === "runtime";
|
|
2015
2077
|
}
|
|
@@ -2081,15 +2143,157 @@ var RECOVERY_REVIEW_NO_ANAPHORIC_MUTATION_CLAUSE_PATTERN = /\b(?:do not|don't|mu
|
|
|
2081
2143
|
var RECOVERY_REVIEW_NO_DELEGATION_CLAUSE_PATTERN = /\b(?:do not|don't|must not)\s+(?:(?:launch|start|spawn|run)\b(?:(?!\b(?:and|but|then|however|nevertheless|nonetheless|yet)\b)[^,.;!?\n])*(?:workers?|reviewers?|agents?|subagents?|children|child|runs?)|(?:get|let|request|hand\s+off|assign|use|have|tell)\b(?:(?!\b(?:and|but|then|however|nevertheless|nonetheless|yet)\b)[^,.;!?\n])*(?:workers?|reviewers?|agents?|subagents?|children|child)|(?:get|let|have|tell|request)\b(?:(?!\b(?:and|but|then|however|nevertheless|nonetheless|yet)\b)[^,.;!?\n])*(?:review|implementation|fix(?:es)?|changes?|follow-up)\b(?:(?!\b(?:and|but|then|however|nevertheless|nonetheless|yet)\b)[^,.;!?\n])*\b(?:from|with|via|by)\b(?:(?!\b(?:and|but|then|however|nevertheless|nonetheless|yet)\b)[^,.;!?\n])*(?:workers?|reviewers?|agents?|subagents?|children|child)|ask\b(?:(?!\b(?:and|but|then|however|nevertheless|nonetheless|yet)\b)[^,.;!?\n])*(?:(?:workers?|reviewers?|agents?|subagents?|children|child)\b(?:(?!\b(?:and|but|then|however|nevertheless|nonetheless|yet)\b)[^,.;!?\n])*\b(?:continue|implement|review|fix|edit|write|modify|change|patch|update|delete|remove|create|follow-up)|(?:review|implementation|fix(?:es)?|changes?|follow-up)\b(?:(?!\b(?:and|but|then|however|nevertheless|nonetheless|yet)\b)[^,.;!?\n])*\b(?:from|via)\b(?:(?!\b(?:and|but|then|however|nevertheless|nonetheless|yet)\b)[^,.;!?\n])*(?:workers?|reviewers?|agents?|subagents?|children|child)))\b/gi;
|
|
2082
2144
|
var RECOVERY_REVIEW_DELEGATION_PATTERN = /\b(?:launch|start|spawn|run)\b[^,.;!?\n]*(?:workers?|reviewers?|agents?|subagents?|children|child|runs?)\b|\b(?:delegate|hand\s+off|assign)\s+(?:remediation|implementation(?:\s+follow-up)?|changes?|fix(?:es)?|follow-up)\s+to\s+(?:(?:a|an|the)\s+)?(?:workers?|reviewers?|agents?|subagents?|children|child)\b|\b(?:get|let|have|tell|request)\b[^,.;!?\n]*(?:workers?|reviewers?|agents?|subagents?|children|child)\b[^,.;!?\n]*\b(?:continue|implement|review|fix|edit|write|modify|change|patch|update|delete|remove|create|follow-up)\b|\b(?:get|let|have|tell|request)\b[^,.;!?\n]*(?:review|implementation|fix(?:es)?|changes?|follow-up)\b[^,.;!?\n]*\b(?:from|with|via|by)\b[^,.;!?\n]*(?:workers?|reviewers?|agents?|subagents?|children|child)\b|\bask\b[^,.;!?\n]*(?:(?:workers?|reviewers?|agents?|subagents?|children|child)\b[^,.;!?\n]*\b(?:continue|implement|review|fix|edit|write|modify|change|patch|update|delete|remove|create|follow-up)|(?:review|implementation|fix(?:es)?|changes?|follow-up)\b[^,.;!?\n]*\b(?:from|via)\b[^,.;!?\n]*(?:workers?|reviewers?|agents?|subagents?|children|child))\b|\buse\b[^,.;!?\n]*(?:workers?|reviewers?|agents?|subagents?|children|child|runs?)\s+(?:for|to)\s+(?:implementation|follow-up|remediation|fix|edit|write|modify|change|patch|update|delete|remove|create)\b/i;
|
|
2083
2145
|
var RECOVERY_REVIEW_ANAPHORIC_MUTATION_PATTERN = /\b(?:do|run|execute|perform|apply)\s+(?:it|that|this|(?:the\s+)?(?:(?:\d+(?:st|nd|rd|th)|first|second|third|fourth|fifth|sixth|seventh|eighth|ninth|tenth|last|next|previous(?:ly)?|prior|above|quoted|blocked)\s+){0,4}(?:command|example|operation|action|phrase|instruction|request|one))(?!(?:\s+(?:(?:now|still|also|already)\s+)*(?:is|are|remains?)\s+blocked\b))(?:(?:[\s,]+\w+){0,4}[\s,]+anyway|(?:(?!\b(?:and|but|then|however|nevertheless|nonetheless|yet)\b)[^,.;!?\n]){0,80})(?=\s*(?:[,.;!?\n)]|\b(?:and|but|then|however|nevertheless|nonetheless|yet)\b|$))/i;
|
|
2084
|
-
var
|
|
2085
|
-
var
|
|
2146
|
+
var RECOVERY_REVIEW_MUTATING_PATH_COMMAND_PATTERN = /(?:^|[\s;,.`'"([{])(?:[^\s;,.`'"([{]*\/)?(?:rm|rmdir|unlink|truncate|mv|cp|chmod|chown)\b/i;
|
|
2147
|
+
var RECOVERY_REVIEW_WORD_CHARACTER_PATTERN = /^\w$/;
|
|
2148
|
+
var RECOVERY_REVIEW_DASH_SEPARATOR_AT_PATTERN = /(?:[—–]|--|\s-\s|:|\s\/\s)/iy;
|
|
2149
|
+
var RECOVERY_REVIEW_DASH_SEPARATOR_EXISTS_PATTERN = /(?:[—–]|--|\s-\s|:|\s\/\s)/i;
|
|
2150
|
+
var RECOVERY_REVIEW_DASH_ACTION_AT_PATTERN = /(?:add|append|apply|change|cherry[ -]pick|clean|commit|copy|create|delete|edit|fix|implement|insert|make|merge|move|modify|mutate|open|patch|prepend|push|rebase|refactor|remove|rename|replace|revert|revise|rewrite|save|stage|stash|tag|touch|update|write)\b/iy;
|
|
2151
|
+
var RECOVERY_REVIEW_DASH_LAUNCH_AT_PATTERN = /(?:launch|start|spawn|run)\b/iy;
|
|
2152
|
+
var RECOVERY_REVIEW_DASH_WORKER_AT_PATTERN = /(?:workers?|reviewers?|agents?|subagents?|children|child|runs?)\b/iy;
|
|
2153
|
+
var RECOVERY_REVIEW_DASH_GIT_AT_PATTERN = /git\b/iy;
|
|
2154
|
+
var RECOVERY_REVIEW_DASH_GIT_COMMAND_AT_PATTERN = /\b(?:add|branch|cherry-pick|clean|commit|merge|rebase|reset|restore|revert|stash|tag|checkout|switch)\b/iy;
|
|
2155
|
+
var RECOVERY_REVIEW_DASH_FILE_COMMAND_AT_PATTERN = /(?:rm|rmdir|unlink|truncate|mv|cp|chmod|chown)\b/iy;
|
|
2156
|
+
var RECOVERY_REVIEW_DASH_THEN_AT_PATTERN = /then/iy;
|
|
2157
|
+
var RECOVERY_REVIEW_DASH_LINE_STOP_CHARACTERS = ",.;!?\n";
|
|
2158
|
+
var RECOVERY_REVIEW_WHITESPACE_CHARACTER_PATTERN = /^\s$/;
|
|
2159
|
+
function matchesDashBranchAt(pattern, text, index) {
|
|
2160
|
+
pattern.lastIndex = index;
|
|
2161
|
+
return pattern.test(text);
|
|
2162
|
+
}
|
|
2163
|
+
function dashBranchLengthAt(pattern, text, index) {
|
|
2164
|
+
pattern.lastIndex = index;
|
|
2165
|
+
const match = pattern.exec(text);
|
|
2166
|
+
return match === null ? 0 : match[0].length;
|
|
2167
|
+
}
|
|
2168
|
+
function skipDashSeparatorWhitespace(text, index) {
|
|
2169
|
+
while (index < text.length && RECOVERY_REVIEW_WHITESPACE_CHARACTER_PATTERN.test(text.charAt(index))) index++;
|
|
2170
|
+
return index;
|
|
2171
|
+
}
|
|
2172
|
+
function acceptsDashLiveActionAt(text, index, workerAhead, gitCommandAhead, pathCommandAhead) {
|
|
2173
|
+
if (matchesDashBranchAt(RECOVERY_REVIEW_DASH_ACTION_AT_PATTERN, text, index)) return true;
|
|
2174
|
+
const launchLength = dashBranchLengthAt(RECOVERY_REVIEW_DASH_LAUNCH_AT_PATTERN, text, index);
|
|
2175
|
+
if (launchLength > 0 && workerAhead[index + launchLength] === 1) return true;
|
|
2176
|
+
if (matchesDashBranchAt(RECOVERY_REVIEW_DASH_FILE_COMMAND_AT_PATTERN, text, index) || pathCommandAhead[index] === 1) return true;
|
|
2177
|
+
return matchesDashBranchAt(RECOVERY_REVIEW_DASH_GIT_AT_PATTERN, text, index) && gitCommandAhead[index + 3] === 1;
|
|
2178
|
+
}
|
|
2179
|
+
function mentionsDashLiveAction(text) {
|
|
2180
|
+
if (!RECOVERY_REVIEW_DASH_SEPARATOR_EXISTS_PATTERN.test(text)) return false;
|
|
2181
|
+
const workerAhead = new Uint8Array(text.length + 1);
|
|
2182
|
+
const gitCommandAhead = new Uint8Array(text.length + 1);
|
|
2183
|
+
const pathCommandAhead = new Uint8Array(text.length + 1);
|
|
2184
|
+
for (let index = text.length - 1; index >= 0; index--) {
|
|
2185
|
+
const character = text.charAt(index);
|
|
2186
|
+
const lineCharacter = !RECOVERY_REVIEW_DASH_LINE_STOP_CHARACTERS.includes(character);
|
|
2187
|
+
const pathCharacter = !RECOVERY_REVIEW_WHITESPACE_CHARACTER_PATTERN.test(character);
|
|
2188
|
+
workerAhead[index] = matchesDashBranchAt(RECOVERY_REVIEW_DASH_WORKER_AT_PATTERN, text, index) || lineCharacter && workerAhead[index + 1] === 1 ? 1 : 0;
|
|
2189
|
+
gitCommandAhead[index] = matchesDashBranchAt(RECOVERY_REVIEW_DASH_GIT_COMMAND_AT_PATTERN, text, index) || lineCharacter && gitCommandAhead[index + 1] === 1 ? 1 : 0;
|
|
2190
|
+
pathCommandAhead[index] = character === "/" && matchesDashBranchAt(RECOVERY_REVIEW_DASH_FILE_COMMAND_AT_PATTERN, text, index + 1) || pathCharacter && pathCommandAhead[index + 1] === 1 ? 1 : 0;
|
|
2191
|
+
}
|
|
2192
|
+
for (let index = 0; index < text.length; index++) {
|
|
2193
|
+
const separatorLength = dashBranchLengthAt(RECOVERY_REVIEW_DASH_SEPARATOR_AT_PATTERN, text, index);
|
|
2194
|
+
if (separatorLength === 0) continue;
|
|
2195
|
+
const anchor = skipDashSeparatorWhitespace(text, index + separatorLength);
|
|
2196
|
+
if (acceptsDashLiveActionAt(text, anchor, workerAhead, gitCommandAhead, pathCommandAhead)) return true;
|
|
2197
|
+
if (!matchesDashBranchAt(RECOVERY_REVIEW_DASH_THEN_AT_PATTERN, text, anchor)) continue;
|
|
2198
|
+
const afterThen = skipDashSeparatorWhitespace(text, anchor + 4);
|
|
2199
|
+
if (afterThen > anchor + 4 && acceptsDashLiveActionAt(text, afterThen, workerAhead, gitCommandAhead, pathCommandAhead)) return true;
|
|
2200
|
+
}
|
|
2201
|
+
return false;
|
|
2202
|
+
}
|
|
2203
|
+
function createMutatingGitStates() {
|
|
2204
|
+
const state = () => ({ edges: [], epsilon: [] });
|
|
2205
|
+
const edge = (from, character, next) => {
|
|
2206
|
+
from.edges.push({ character, next });
|
|
2207
|
+
};
|
|
2208
|
+
const literal = (from, word, end) => {
|
|
2209
|
+
for (let index = 0; index < word.length; index++) {
|
|
2210
|
+
const next = index === word.length - 1 ? end : state();
|
|
2211
|
+
edge(from, new RegExp(word.charAt(index), "i"), next);
|
|
2212
|
+
from = next;
|
|
2213
|
+
}
|
|
2214
|
+
};
|
|
2215
|
+
const start = state();
|
|
2216
|
+
const accept = state();
|
|
2217
|
+
const afterOption = state();
|
|
2218
|
+
const afterSpace = state();
|
|
2219
|
+
literal(start, "git", afterOption);
|
|
2220
|
+
edge(afterOption, /\s/, afterSpace);
|
|
2221
|
+
edge(afterSpace, /\s/, afterSpace);
|
|
2222
|
+
for (const command of ["add", "branch", "cherry-pick", "clean", "commit", "merge", "rebase", "reset", "restore", "revert", "stash", "tag", "checkout", "switch"]) {
|
|
2223
|
+
literal(afterSpace, command, accept);
|
|
2224
|
+
}
|
|
2225
|
+
const value = state();
|
|
2226
|
+
const beforeSeparatedValue = state();
|
|
2227
|
+
const separatedValue = state();
|
|
2228
|
+
edge(beforeSeparatedValue, /\s/, separatedValue);
|
|
2229
|
+
edge(separatedValue, /\s/, separatedValue);
|
|
2230
|
+
separatedValue.epsilon.push(value);
|
|
2231
|
+
const shortDash = state();
|
|
2232
|
+
const shortOption = state();
|
|
2233
|
+
literal(afterSpace, "-", shortDash);
|
|
2234
|
+
edge(shortDash, /[A-Za-z]/, shortOption);
|
|
2235
|
+
shortOption.epsilon.push(afterOption, beforeSeparatedValue);
|
|
2236
|
+
const longStart = state();
|
|
2237
|
+
const longName = state();
|
|
2238
|
+
literal(shortDash, "-", longStart);
|
|
2239
|
+
edge(longStart, /[A-Za-z0-9-]/, longName);
|
|
2240
|
+
edge(longName, /[A-Za-z0-9-]/, longName);
|
|
2241
|
+
longName.epsilon.push(afterOption);
|
|
2242
|
+
edge(longName, /=/, value);
|
|
2243
|
+
for (const option of ["git-dir", "work-tree", "namespace", "exec-path", "config-env"]) {
|
|
2244
|
+
const specialOption = state();
|
|
2245
|
+
literal(longStart, option, specialOption);
|
|
2246
|
+
edge(specialOption, /=/, value);
|
|
2247
|
+
specialOption.epsilon.push(beforeSeparatedValue);
|
|
2248
|
+
}
|
|
2249
|
+
for (const [quote, body] of [[/"/, /[^"\n]/], [/'/, /[^'\n]/]]) {
|
|
2250
|
+
const quotedValue = state();
|
|
2251
|
+
edge(value, quote, quotedValue);
|
|
2252
|
+
edge(quotedValue, body, quotedValue);
|
|
2253
|
+
edge(quotedValue, quote, afterOption);
|
|
2254
|
+
}
|
|
2255
|
+
const plainValue = state();
|
|
2256
|
+
edge(value, /\S/, plainValue);
|
|
2257
|
+
edge(plainValue, /\S/, plainValue);
|
|
2258
|
+
plainValue.epsilon.push(afterOption);
|
|
2259
|
+
return { start, accept };
|
|
2260
|
+
}
|
|
2261
|
+
var MUTATING_GIT_STATES = createMutatingGitStates();
|
|
2262
|
+
function mentionsMutatingGitCommand(text) {
|
|
2263
|
+
let active = /* @__PURE__ */ new Set();
|
|
2264
|
+
let next = /* @__PURE__ */ new Set();
|
|
2265
|
+
const addState = (states, state) => {
|
|
2266
|
+
if (states.has(state)) return;
|
|
2267
|
+
states.add(state);
|
|
2268
|
+
for (const reachable of state.epsilon) addState(states, reachable);
|
|
2269
|
+
};
|
|
2270
|
+
for (let position = 0; position <= text.length; position++) {
|
|
2271
|
+
const character = text.charAt(position);
|
|
2272
|
+
const previousIsWord = RECOVERY_REVIEW_WORD_CHARACTER_PATTERN.test(text.charAt(position - 1));
|
|
2273
|
+
const currentIsWord = RECOVERY_REVIEW_WORD_CHARACTER_PATTERN.test(character);
|
|
2274
|
+
if (active.has(MUTATING_GIT_STATES.accept) && previousIsWord !== currentIsWord) return true;
|
|
2275
|
+
if (!previousIsWord) addState(active, MUTATING_GIT_STATES.start);
|
|
2276
|
+
if (position === text.length) break;
|
|
2277
|
+
next.clear();
|
|
2278
|
+
for (const state of active) {
|
|
2279
|
+
for (const edge of state.edges) {
|
|
2280
|
+
if (edge.character.test(character)) addState(next, edge.next);
|
|
2281
|
+
}
|
|
2282
|
+
}
|
|
2283
|
+
[active, next] = [next, active];
|
|
2284
|
+
}
|
|
2285
|
+
return false;
|
|
2286
|
+
}
|
|
2287
|
+
function mentionsMutatingCommand(text) {
|
|
2288
|
+
return RECOVERY_REVIEW_MUTATING_PATH_COMMAND_PATTERN.test(text) || mentionsMutatingGitCommand(text);
|
|
2289
|
+
}
|
|
2086
2290
|
function isExplicitReadOnlyRecoveryReview(params) {
|
|
2087
2291
|
const agent = typeof params.agent === "string" ? params.agent.trim() : "";
|
|
2088
2292
|
const task = typeof params.task === "string" ? params.task.trim() : "";
|
|
2089
2293
|
const taskDestructiveCommandText = task.replace(RECOVERY_REVIEW_BLOCKED_CONTEXT_FRAGMENT_PATTERN, " ").replace(RECOVERY_REVIEW_REGRESSION_EVIDENCE_PATTERN, " ").replace(RECOVERY_REVIEW_BLOCKED_QUOTED_EXAMPLE_PATTERN, " ").replace(RECOVERY_REVIEW_CONTEXT_QUOTED_EXAMPLE_PATTERN, " ").replace(RECOVERY_REVIEW_LISTED_BLOCKED_EXAMPLE_PATTERN, " ").replace(RECOVERY_REVIEW_BLOCKS_QUOTED_EXAMPLE_PATTERN, " ").replace(RECOVERY_REVIEW_EXAMPLES_LIKE_BLOCKED_PATTERN, " ").replace(RECOVERY_REVIEW_QUOTED_VISIBLE_BLOCKED_PATTERN, " ").replace(RECOVERY_REVIEW_PROMPTS_LIKE_BLOCKED_PATTERN, " ").replace(RECOVERY_REVIEW_GIT_MUTATIONS_BROADER_CONTEXT_PATTERN, " ").replace(RECOVERY_REVIEW_GIT_COVERAGE_CONTEXT_PATTERN, " ").replace(RECOVERY_REVIEW_REGRESSION_FOLLOWED_BY_NAMED_RM_PATTERN, " ");
|
|
2090
2294
|
const taskDashLiveActionText = task.replace(RECOVERY_REVIEW_DELIVERABLE_PATTERN, " ").replace(RECOVERY_REVIEW_CONTEXT_OBJECT_PATTERN, " ").replace(RECOVERY_REVIEW_MUTATION_NOUN_CONTEXT_PATTERN, " ").replace(RECOVERY_REVIEW_PRIOR_FIX_CONTEXT_PATTERN, " ").replace(RECOVERY_REVIEW_DETECTION_CONTEXT_PATTERN, " ").replace(RECOVERY_REVIEW_PATTERN_CHANGE_CONTEXT_PATTERN, " ").replace(RECOVERY_REVIEW_GIT_PATTERN_CHANGE_CONTEXT_PATTERN, " ").replace(RECOVERY_REVIEW_VALIDATION_EVIDENCE_PATTERN, " ").replace(RECOVERY_REVIEW_CONTRACT_PROHIBITION_PATTERN, " ").replace(RECOVERY_REVIEW_ONLY_REVIEW_CONTRACT_PATTERN, " ").replace(RECOVERY_REVIEW_BLOCKED_QUOTED_EXAMPLE_PATTERN, " ").replace(RECOVERY_REVIEW_CONTEXT_QUOTED_EXAMPLE_PATTERN, " ").replace(RECOVERY_REVIEW_LISTED_BLOCKED_EXAMPLE_PATTERN, " ").replace(RECOVERY_REVIEW_BLOCKS_QUOTED_EXAMPLE_PATTERN, " ").replace(RECOVERY_REVIEW_EXAMPLES_LIKE_BLOCKED_PATTERN, " ").replace(RECOVERY_REVIEW_QUOTED_VISIBLE_BLOCKED_PATTERN, " ").replace(RECOVERY_REVIEW_PROMPTS_LIKE_BLOCKED_PATTERN, " ").replace(RECOVERY_REVIEW_GIT_MUTATIONS_BROADER_CONTEXT_PATTERN, " ").replace(RECOVERY_REVIEW_GIT_COVERAGE_CONTEXT_PATTERN, " ").replace(RECOVERY_REVIEW_REGRESSION_QUOTED_EXAMPLE_PATTERN, " ").replace(RECOVERY_REVIEW_REGRESSION_ANAPHORIC_EXAMPLE_PATTERN, " ").replace(RECOVERY_REVIEW_REGRESSION_FOLLOWED_BY_ANAPHORIC_PATTERN, " ").replace(RECOVERY_REVIEW_BLOCKED_LIVE_VARIANT_CONTEXT_PATTERN, " ").replace(RECOVERY_REVIEW_ANAPHORIC_REFERENCES_CONTEXT_PATTERN, " ");
|
|
2091
2295
|
const taskMutationText = task.replace(RECOVERY_REVIEW_DELIVERABLE_PATTERN, " ").replace(RECOVERY_REVIEW_CONTEXT_OBJECT_PATTERN, " ").replace(RECOVERY_REVIEW_MUTATION_NOUN_CONTEXT_PATTERN, " ").replace(RECOVERY_REVIEW_PRIOR_FIX_CONTEXT_PATTERN, " ").replace(RECOVERY_REVIEW_DETECTION_CONTEXT_PATTERN, " ").replace(RECOVERY_REVIEW_PATTERN_CHANGE_CONTEXT_PATTERN, " ").replace(RECOVERY_REVIEW_GIT_PATTERN_CHANGE_CONTEXT_PATTERN, " ").replace(RECOVERY_REVIEW_VALIDATION_EVIDENCE_PATTERN, " ").replace(RECOVERY_REVIEW_CONTRACT_PROHIBITION_PATTERN, " ").replace(RECOVERY_REVIEW_ONLY_REVIEW_CONTRACT_PATTERN, " ").replace(RECOVERY_REVIEW_BLOCKED_CONTEXT_FRAGMENT_PATTERN, " ").replace(RECOVERY_REVIEW_REGRESSION_EVIDENCE_PATTERN, " ").replace(RECOVERY_REVIEW_BLOCKED_QUOTED_EXAMPLE_PATTERN, " ").replace(RECOVERY_REVIEW_CONTEXT_QUOTED_EXAMPLE_PATTERN, " ").replace(RECOVERY_REVIEW_LISTED_BLOCKED_EXAMPLE_PATTERN, " ").replace(RECOVERY_REVIEW_BLOCKS_QUOTED_EXAMPLE_PATTERN, " ").replace(RECOVERY_REVIEW_EXAMPLES_LIKE_BLOCKED_PATTERN, " ").replace(RECOVERY_REVIEW_QUOTED_VISIBLE_BLOCKED_PATTERN, " ").replace(RECOVERY_REVIEW_PROMPTS_LIKE_BLOCKED_PATTERN, " ").replace(RECOVERY_REVIEW_GIT_MUTATIONS_BROADER_CONTEXT_PATTERN, " ").replace(RECOVERY_REVIEW_GIT_COVERAGE_CONTEXT_PATTERN, " ").replace(RECOVERY_REVIEW_REGRESSION_QUOTED_EXAMPLE_PATTERN, " ").replace(RECOVERY_REVIEW_REGRESSION_ANAPHORIC_EXAMPLE_PATTERN, " ").replace(RECOVERY_REVIEW_REGRESSION_FOLLOWED_BY_ANAPHORIC_PATTERN, " ").replace(RECOVERY_REVIEW_BLOCKED_LIVE_VARIANT_CONTEXT_PATTERN, " ").replace(RECOVERY_REVIEW_ANAPHORIC_REFERENCES_CONTEXT_PATTERN, " ").replace(RECOVERY_REVIEW_NO_ANAPHORIC_MUTATION_CLAUSE_PATTERN, " ").replace(RECOVERY_REVIEW_NO_DELEGATION_CLAUSE_PATTERN, " ").replace(RECOVERY_REVIEW_NO_MUTATION_CLAUSE_PATTERN, " ").replace(new RegExp(RECOVERY_REVIEW_READ_ONLY_PATTERN.source, "gi"), " ");
|
|
2092
|
-
return params.acceptance === false && agent !== "" && /\b(?:advisor|oracle|review|reviewer)\b/i.test(agent) && RECOVERY_REVIEW_READ_ONLY_PATTERN.test(task) && !
|
|
2296
|
+
return params.acceptance === false && agent !== "" && /\b(?:advisor|oracle|review|reviewer)\b/i.test(agent) && RECOVERY_REVIEW_READ_ONLY_PATTERN.test(task) && !mentionsMutatingCommand(taskDestructiveCommandText) && !RECOVERY_REVIEW_MUTATION_VERB_PATTERN.test(taskMutationText) && !RECOVERY_REVIEW_DELEGATION_PATTERN.test(taskMutationText) && !RECOVERY_REVIEW_ANAPHORIC_MUTATION_PATTERN.test(taskMutationText) && !mentionsMutatingCommand(taskMutationText) && !mentionsDashLiveAction(taskDashLiveActionText);
|
|
2093
2297
|
}
|
|
2094
2298
|
function recoveryBarrierMessage(sourceKey, target) {
|
|
2095
2299
|
return `Run '${target}' cannot launch after run '${sourceKey}' returned rejected acceptance recovery; only explicit read-only review children with acceptance:false may follow.`;
|
|
@@ -2127,25 +2331,25 @@ function omitNonJsonWorkflowResultMetadata(value) {
|
|
|
2127
2331
|
return safeResult;
|
|
2128
2332
|
}
|
|
2129
2333
|
}
|
|
2130
|
-
function assertWorkflowJsonValue(value,
|
|
2334
|
+
function assertWorkflowJsonValue(value, path16 = "value", seen = /* @__PURE__ */ new Set()) {
|
|
2131
2335
|
if (value === null || typeof value === "string" || typeof value === "boolean") return;
|
|
2132
2336
|
if (typeof value === "number") {
|
|
2133
|
-
if (!Number.isFinite(value)) throw new Error(`${
|
|
2337
|
+
if (!Number.isFinite(value)) throw new Error(`${path16} must contain only finite JSON numbers.`);
|
|
2134
2338
|
return;
|
|
2135
2339
|
}
|
|
2136
|
-
if (typeof value !== "object") throw new Error(`${
|
|
2137
|
-
if (seen.has(value)) throw new Error(`${
|
|
2340
|
+
if (typeof value !== "object") throw new Error(`${path16} must be a JSON value; received ${typeof value}.`);
|
|
2341
|
+
if (seen.has(value)) throw new Error(`${path16} must not contain cycles.`);
|
|
2138
2342
|
seen.add(value);
|
|
2139
2343
|
if (Array.isArray(value)) {
|
|
2140
2344
|
for (let index = 0; index < value.length; index++) {
|
|
2141
|
-
if (!Object.hasOwn(value, index)) throw new Error(`${
|
|
2142
|
-
assertWorkflowJsonValue(value[index], `${
|
|
2345
|
+
if (!Object.hasOwn(value, index)) throw new Error(`${path16} must not contain sparse array entries.`);
|
|
2346
|
+
assertWorkflowJsonValue(value[index], `${path16}[${index}]`, seen);
|
|
2143
2347
|
}
|
|
2144
2348
|
} else {
|
|
2145
2349
|
const prototype = Object.getPrototypeOf(value);
|
|
2146
|
-
if (prototype !== null && prototype !== Object.prototype) throw new Error(`${
|
|
2147
|
-
if (Object.getOwnPropertySymbols(value).length > 0) throw new Error(`${
|
|
2148
|
-
for (const [key, entry] of Object.entries(value)) assertWorkflowJsonValue(entry, `${
|
|
2350
|
+
if (prototype !== null && prototype !== Object.prototype) throw new Error(`${path16} must contain only plain JSON objects.`);
|
|
2351
|
+
if (Object.getOwnPropertySymbols(value).length > 0) throw new Error(`${path16} must not contain symbol keys.`);
|
|
2352
|
+
for (const [key, entry] of Object.entries(value)) assertWorkflowJsonValue(entry, `${path16}.${key}`, seen);
|
|
2149
2353
|
}
|
|
2150
2354
|
seen.delete(value);
|
|
2151
2355
|
}
|
|
@@ -2366,23 +2570,46 @@ function directObjectPropertyValue(node, name) {
|
|
|
2366
2570
|
}
|
|
2367
2571
|
return value;
|
|
2368
2572
|
}
|
|
2369
|
-
function
|
|
2370
|
-
|
|
2371
|
-
|
|
2372
|
-
|
|
2373
|
-
|
|
2573
|
+
function arrayElements(node) {
|
|
2574
|
+
return astNode(node) && node.type === "ArrayExpression" && Array.isArray(node.elements) ? node.elements : [];
|
|
2575
|
+
}
|
|
2576
|
+
function finalStaticProperty(node, name) {
|
|
2577
|
+
if (node.type !== "ObjectExpression" || !Array.isArray(node.properties)) return void 0;
|
|
2578
|
+
for (let index = node.properties.length - 1; index >= 0; index--) {
|
|
2579
|
+
const property = node.properties[index];
|
|
2580
|
+
if (!astNode(property) || property.type !== "Property") return void 0;
|
|
2374
2581
|
const key = staticPropertyKey(property);
|
|
2375
|
-
if (key === void 0) return
|
|
2376
|
-
if (key
|
|
2377
|
-
|
|
2378
|
-
|
|
2379
|
-
|
|
2380
|
-
|
|
2381
|
-
|
|
2382
|
-
|
|
2383
|
-
|
|
2582
|
+
if (key === void 0) return void 0;
|
|
2583
|
+
if (key === name) return property;
|
|
2584
|
+
}
|
|
2585
|
+
return void 0;
|
|
2586
|
+
}
|
|
2587
|
+
function validateStaticBaseRef(params, owner) {
|
|
2588
|
+
const property = finalStaticProperty(params, "baseRef");
|
|
2589
|
+
if (property?.kind !== "init" || !astNode(property.value)) return [];
|
|
2590
|
+
const valueNode = property.value;
|
|
2591
|
+
const value = literalString(valueNode);
|
|
2592
|
+
return (value !== void 0 || valueNode.type === "Literal") && !validGitRef(value) ? [{ message: `${owner} ${BASE_REF_VALIDATION_ERROR}`, ...nodeLocation(valueNode) }] : [];
|
|
2593
|
+
}
|
|
2594
|
+
var LANE_RETAINED_RESUME_ERROR = 'cannot resume a retained run id in runs.lanes; use runs.run(key, { resume: id }) outside lanes, or start the lane with an agent stage and use resume: "previous" later.';
|
|
2595
|
+
function staticLane(lane) {
|
|
2596
|
+
return astNode(lane) && lane.type === "ObjectExpression" && Array.isArray(lane.properties) && lane.properties.every((property) => astNode(property) && property.type === "Property" && staticPropertyKey(property) !== void 0);
|
|
2597
|
+
}
|
|
2598
|
+
function validateStaticLaneResumes(call) {
|
|
2599
|
+
const args = Array.isArray(call.arguments) ? call.arguments : [];
|
|
2600
|
+
const lanes = arrayElements(args[0]);
|
|
2601
|
+
const errors = [];
|
|
2602
|
+
for (let laneIndex = 0; laneIndex < lanes.length; laneIndex++) {
|
|
2603
|
+
const lane = lanes[laneIndex];
|
|
2604
|
+
if (astNode(lane) && lane.type === "SpreadElement") break;
|
|
2605
|
+
if (!staticLane(lane)) continue;
|
|
2606
|
+
const first = arrayElements(directObjectPropertyValue(lane, "stages"))[0];
|
|
2607
|
+
if (!astNode(first)) continue;
|
|
2608
|
+
const property = finalStaticProperty(first, "resume");
|
|
2609
|
+
const resume = property?.kind === "init" ? literalString(property.value) : void 0;
|
|
2610
|
+
if (resume !== void 0 && resume !== "previous") errors.push({ message: `runs.lanes lane ${laneIndex} stage 0 ${LANE_RETAINED_RESUME_ERROR}`, ...nodeLocation(first) });
|
|
2384
2611
|
}
|
|
2385
|
-
return
|
|
2612
|
+
return errors;
|
|
2386
2613
|
}
|
|
2387
2614
|
function staticChildAgentNode(params) {
|
|
2388
2615
|
if (!astNode(params) || params.type !== "ObjectExpression" || !Array.isArray(params.properties)) return void 0;
|
|
@@ -2397,9 +2624,7 @@ function staticChildAgentNode(params) {
|
|
|
2397
2624
|
}
|
|
2398
2625
|
function validateStaticChildAgents(call, agentNameError) {
|
|
2399
2626
|
const args = Array.isArray(call.arguments) ? call.arguments : [];
|
|
2400
|
-
const
|
|
2401
|
-
const staticLane = (lane) => astNode(lane) && lane.type === "ObjectExpression" && Array.isArray(lane.properties) && lane.properties.every((property) => astNode(property) && property.type === "Property" && staticPropertyKey(property) !== void 0);
|
|
2402
|
-
const children = directRunsCall(call, "run") ? [{ owner: "runs.run", params: args[1] }] : directRunsCall(call, "all") ? elements(args[0]).map((params) => ({ owner: "runs.all item", params })) : directRunsCall(call, "lanes") ? elements(args[0]).flatMap((lane) => staticLane(lane) ? elements(directObjectPropertyValue(lane, "stages")).map((params) => ({ owner: "runs.lanes stage", params })) : []) : [];
|
|
2627
|
+
const children = directRunsCall(call, "run") ? [{ owner: "runs.run", params: args[1] }] : directRunsCall(call, "all") ? arrayElements(args[0]).map((params) => ({ owner: "runs.all item", params })) : directRunsCall(call, "lanes") ? arrayElements(args[0]).flatMap((lane) => staticLane(lane) ? arrayElements(directObjectPropertyValue(lane, "stages")).map((params) => ({ owner: "runs.lanes stage", params })) : []) : [];
|
|
2403
2628
|
const errors = [];
|
|
2404
2629
|
for (const child of children) {
|
|
2405
2630
|
const agentNode = staticChildAgentNode(child.params);
|
|
@@ -2411,14 +2636,37 @@ function validateStaticChildAgents(call, agentNameError) {
|
|
|
2411
2636
|
}
|
|
2412
2637
|
function directRunsAllKeys(call) {
|
|
2413
2638
|
const args = Array.isArray(call.arguments) ? call.arguments : [];
|
|
2414
|
-
|
|
2415
|
-
return items.flatMap((item) => {
|
|
2639
|
+
return arrayElements(args[0]).flatMap((item) => {
|
|
2416
2640
|
if (!astNode(item)) return [];
|
|
2417
2641
|
const keyNode = directObjectPropertyValue(item, "key");
|
|
2418
2642
|
const key = literalString(keyNode);
|
|
2419
2643
|
return keyNode && key !== void 0 ? [{ key, node: keyNode }] : [];
|
|
2420
2644
|
});
|
|
2421
2645
|
}
|
|
2646
|
+
function keylessRunsAllItems(call) {
|
|
2647
|
+
const args = Array.isArray(call.arguments) ? call.arguments : [];
|
|
2648
|
+
const items = args[0];
|
|
2649
|
+
if (!astNode(items)) return [];
|
|
2650
|
+
if (items.type === "ArrayExpression" && Array.isArray(items.elements)) {
|
|
2651
|
+
return items.elements.flatMap((item, index) => keylessItemLiteral(item) ? [{ node: item, index }] : []);
|
|
2652
|
+
}
|
|
2653
|
+
const callee = items.type === "CallExpression" && astNode(items.callee) && items.callee.type === "MemberExpression" && items.callee.computed !== true ? items.callee : void 0;
|
|
2654
|
+
if (!callee || !astNode(callee.property) || callee.property.type !== "Identifier" || callee.property.name !== "map") return [];
|
|
2655
|
+
const callback = Array.isArray(items.arguments) ? items.arguments[0] : void 0;
|
|
2656
|
+
if (!astNode(callback) || callback.type !== "ArrowFunctionExpression" && callback.type !== "FunctionExpression" || !astNode(callback.body)) return [];
|
|
2657
|
+
let result = callback.body;
|
|
2658
|
+
if (callback.body.type === "BlockStatement" && Array.isArray(callback.body.body)) {
|
|
2659
|
+
const returns = [];
|
|
2660
|
+
walkAst(callback.body, (node) => {
|
|
2661
|
+
if (node.type === "ReturnStatement") returns.push(node);
|
|
2662
|
+
}, false);
|
|
2663
|
+
result = returns.length === 1 && returns[0] === callback.body.body.at(-1) ? returns[0].argument : void 0;
|
|
2664
|
+
}
|
|
2665
|
+
return keylessItemLiteral(result) ? [{ node: result }] : [];
|
|
2666
|
+
}
|
|
2667
|
+
function keylessItemLiteral(node) {
|
|
2668
|
+
return astNode(node) && node.type === "ObjectExpression" && Array.isArray(node.properties) && node.properties.every((property) => astNode(property) && property.type === "Property" && property.kind === "init" && property.computed !== true && staticPropertyKey(property) !== "__proto__") && !directObjectPropertyValue(node, "key") && !directObjectPropertyValue(node, "then");
|
|
2669
|
+
}
|
|
2422
2670
|
function containsWorkflowLaunch(node) {
|
|
2423
2671
|
let found = false;
|
|
2424
2672
|
walkAst(node, (candidate) => {
|
|
@@ -2534,7 +2782,9 @@ ${script}
|
|
|
2534
2782
|
})()`, { ecmaVersion: "latest", sourceType: "script", locations: true });
|
|
2535
2783
|
} catch (error) {
|
|
2536
2784
|
const location = error && typeof error === "object" && "loc" in error && error.loc && typeof error.loc === "object" ? error.loc : void 0;
|
|
2537
|
-
const
|
|
2785
|
+
const parserMessage = (error instanceof Error ? error.message : String(error)).replace(/\s+\(\d+:\d+\)$/, "");
|
|
2786
|
+
const source = script.trim();
|
|
2787
|
+
const message = /^\S+$/.test(source) && (/^(?:~|\.{1,2})?\//.test(source) || /\.(?:[cm]?[jt]s|json)$/.test(source)) ? `${parserMessage}. The script looks like a file path ('${source}'): options.script takes the script's source text; pass a script file as workflow: "${source}".` : parserMessage;
|
|
2538
2788
|
return { ok: false, errors: [{ message, ...typeof location?.line === "number" ? { line: Math.max(1, location.line - 1) } : {}, ...typeof location?.column === "number" ? { column: location.column + 1 } : {} }] };
|
|
2539
2789
|
}
|
|
2540
2790
|
const wrapper = astNode(root.body) ? void 0 : Array.isArray(root.body) && astNode(root.body[0]) && astNode(root.body[0].expression) && astNode(root.body[0].expression.callee) ? root.body[0].expression.callee : void 0;
|
|
@@ -2560,16 +2810,19 @@ ${script}
|
|
|
2560
2810
|
}
|
|
2561
2811
|
if (directRunsCall(node, "all")) {
|
|
2562
2812
|
for (const entry of directRunsAllKeys(node)) if (!KEY_PATTERN.test(entry.key)) errors.push({ message: "runs.all item key must be 1-128 characters using letters, numbers, '.', '_' or '-', and start with a letter or number.", ...nodeLocation(entry.node) });
|
|
2813
|
+
if (!runsRebound) for (const item of keylessRunsAllItems(node)) {
|
|
2814
|
+
const subject = item.index === void 0 ? "runs.all items built by this map(...) callback have no key" : `runs.all item ${item.index} has no key`;
|
|
2815
|
+
errors.push({ message: `${subject}; every runs.all item needs a stable key, for example runs.all([{ key: "review", agent, task }]).`, ...nodeLocation(item.node) });
|
|
2816
|
+
}
|
|
2563
2817
|
const args = Array.isArray(node.arguments) ? node.arguments : [];
|
|
2564
|
-
|
|
2565
|
-
|
|
2566
|
-
|
|
2567
|
-
|
|
2568
|
-
if (message) errors.push({ message: `runs.all item params are invalid: ${message}.`, ...nodeLocation(item) });
|
|
2569
|
-
}
|
|
2818
|
+
for (const item of arrayElements(args[0])) if (astNode(item)) {
|
|
2819
|
+
errors.push(...validateStaticBaseRef(item, "runs.all item"));
|
|
2820
|
+
const message = definitelyNonJson(item);
|
|
2821
|
+
if (message) errors.push({ message: `runs.all item params are invalid: ${message}.`, ...nodeLocation(item) });
|
|
2570
2822
|
}
|
|
2571
2823
|
}
|
|
2572
2824
|
if (directRunsCall(node, "host")) errors.push(...validateStaticHostCall(node));
|
|
2825
|
+
if (directRunsCall(node, "lanes") && !runsRebound) errors.push(...validateStaticLaneResumes(node));
|
|
2573
2826
|
if (agentNameError) errors.push(...validateStaticChildAgents(node, agentNameError));
|
|
2574
2827
|
const boundaryValue = node.type === "CallExpression" && astNode(node.callee) && node.callee.type === "Identifier" && node.callee.name === "emit" && Array.isArray(node.arguments) && astNode(node.arguments[0]) ? node.arguments[0] : node.type === "CallExpression" && astNode(node.callee) && node.callee.type === "MemberExpression" && astNode(node.callee.object) && node.callee.object.type === "Identifier" && node.callee.object.name === "state" && astNode(node.callee.property) && node.callee.property.type === "Identifier" && node.callee.property.name === "set" && Array.isArray(node.arguments) && astNode(node.arguments[1]) ? node.arguments[1] : void 0;
|
|
2575
2828
|
if (boundaryValue) {
|
|
@@ -2593,7 +2846,7 @@ ${script}
|
|
|
2593
2846
|
const keys = new Set(directRunsAllKeys(declaration.init.argument).map((entry) => entry.key));
|
|
2594
2847
|
if (keys.size === 0) continue;
|
|
2595
2848
|
const args = Array.isArray(declaration.init.argument.arguments) ? declaration.init.argument.arguments : [];
|
|
2596
|
-
const itemCount =
|
|
2849
|
+
const itemCount = arrayElements(args[0]).length;
|
|
2597
2850
|
const arrayResultShape = Array.from({ length: itemCount });
|
|
2598
2851
|
for (const later of laterStatements) {
|
|
2599
2852
|
walkAstWithoutShadowedIdentifier(later, name, (node) => {
|
|
@@ -2640,7 +2893,7 @@ function resolveWorkflowParserEntry() {
|
|
|
2640
2893
|
} catch (primaryError) {
|
|
2641
2894
|
try {
|
|
2642
2895
|
const manifestPath = requireFromPackage.resolve("acorn/package.json");
|
|
2643
|
-
const manifest = JSON.parse(
|
|
2896
|
+
const manifest = JSON.parse(readFileSync5(manifestPath, "utf8"));
|
|
2644
2897
|
const entry = typeof manifest.main === "string" && manifest.main ? manifest.main : "./dist/acorn.js";
|
|
2645
2898
|
return resolvePath(dirname6(manifestPath), entry);
|
|
2646
2899
|
} catch {
|
|
@@ -2717,8 +2970,7 @@ async function runWorkflowScript(options) {
|
|
|
2717
2970
|
}
|
|
2718
2971
|
let worker;
|
|
2719
2972
|
try {
|
|
2720
|
-
|
|
2721
|
-
worker = bun ? new Worker(WORKFLOW_WORKER_URL, { workerData: { acornPath } }) : new Worker(nodeWorkerSource ??= readFileSync6(WORKFLOW_WORKER_URL, "utf8"), { eval: true, workerData: { acornPath } });
|
|
2973
|
+
worker = createWorkflowScriptWorker(acornPath);
|
|
2722
2974
|
} catch (error) {
|
|
2723
2975
|
throw new WorkflowScriptError(`Workflow worker could not start: ${error instanceof Error ? error.message : String(error)}`, emptyPartial(), "runtime", { cause: error });
|
|
2724
2976
|
}
|
|
@@ -2740,6 +2992,9 @@ async function runWorkflowScript(options) {
|
|
|
2740
2992
|
let acceptanceRecoveryBarrier;
|
|
2741
2993
|
let settled = false;
|
|
2742
2994
|
let finishing = false;
|
|
2995
|
+
let draining = false;
|
|
2996
|
+
let onDrained;
|
|
2997
|
+
const acquiredLaunches = /* @__PURE__ */ new Set();
|
|
2743
2998
|
let assemblyAbortRequested = false;
|
|
2744
2999
|
let assemblyFlushTimer;
|
|
2745
3000
|
let abortError;
|
|
@@ -2780,6 +3035,12 @@ async function runWorkflowScript(options) {
|
|
|
2780
3035
|
const recordAcceptanceRecoveryBarrier = (key, result) => {
|
|
2781
3036
|
if (isAcceptanceMetadataRecovery(result)) acceptanceRecoveryBarrier = { key };
|
|
2782
3037
|
};
|
|
3038
|
+
const drainIfIdle = () => {
|
|
3039
|
+
if (!onDrained || [...launches.keys()].some((key) => !children.has(key))) return;
|
|
3040
|
+
const done = onDrained;
|
|
3041
|
+
onDrained = void 0;
|
|
3042
|
+
done();
|
|
3043
|
+
};
|
|
2783
3044
|
const stopChild = (key, message = `Workflow child '${key}' stopped.`) => {
|
|
2784
3045
|
if (!launches.has(key) || children.has(key)) return false;
|
|
2785
3046
|
stoppedLaunches.add(key);
|
|
@@ -2797,8 +3058,19 @@ async function runWorkflowScript(options) {
|
|
|
2797
3058
|
error: message
|
|
2798
3059
|
});
|
|
2799
3060
|
traceChanged();
|
|
3061
|
+
drainIfIdle();
|
|
2800
3062
|
return true;
|
|
2801
3063
|
};
|
|
3064
|
+
const drain = (done) => {
|
|
3065
|
+
if (!draining) {
|
|
3066
|
+
draining = true;
|
|
3067
|
+
onDrained = done;
|
|
3068
|
+
}
|
|
3069
|
+
for (const key of launches.keys()) if (!acquiredLaunches.has(key)) stopChild(key, WORKFLOW_DRAIN_CHILD_MESSAGE);
|
|
3070
|
+
const started = [...launches.keys()].filter((key) => !children.has(key)).length;
|
|
3071
|
+
drainIfIdle();
|
|
3072
|
+
return started;
|
|
3073
|
+
};
|
|
2802
3074
|
const notifyChildSettled = (key, result) => {
|
|
2803
3075
|
if (result.state === "running" || !options.onChildSettled || !options.workflowRunId) return;
|
|
2804
3076
|
const outcome = result.ok ? "completed" : result.stopped ? "stopped" : result.detached ? "paused" : "failed";
|
|
@@ -2819,7 +3091,8 @@ async function runWorkflowScript(options) {
|
|
|
2819
3091
|
}
|
|
2820
3092
|
};
|
|
2821
3093
|
options.registerStopChild?.(stopChild);
|
|
2822
|
-
|
|
3094
|
+
options.registerDrain?.(drain);
|
|
3095
|
+
return await new Promise((resolve5, reject) => {
|
|
2823
3096
|
const finish = (outcome) => {
|
|
2824
3097
|
if (settled || finishing) return;
|
|
2825
3098
|
finishing = true;
|
|
@@ -2832,6 +3105,7 @@ async function runWorkflowScript(options) {
|
|
|
2832
3105
|
if (settled) return;
|
|
2833
3106
|
settled = true;
|
|
2834
3107
|
options.registerStopChild?.(void 0);
|
|
3108
|
+
options.registerDrain?.(void 0);
|
|
2835
3109
|
if (timer) clearTimeout(timer);
|
|
2836
3110
|
options.signal?.removeEventListener("abort", onAbort);
|
|
2837
3111
|
void worker.terminate();
|
|
@@ -2844,7 +3118,7 @@ async function runWorkflowScript(options) {
|
|
|
2844
3118
|
})() : void 0;
|
|
2845
3119
|
if ("error" in outcome) reject(new WorkflowScriptError(outcome.error.message, partial(), isWorkflowScriptFailureKind(outcome.error.workflowErrorKind) ? outcome.error.workflowErrorKind : void 0));
|
|
2846
3120
|
else if (completionError) reject(new WorkflowScriptError(completionError.message, partial(), "validation"));
|
|
2847
|
-
else
|
|
3121
|
+
else resolve5({ value: outcome.value, ...partial() });
|
|
2848
3122
|
});
|
|
2849
3123
|
};
|
|
2850
3124
|
const onAbort = () => {
|
|
@@ -2891,7 +3165,7 @@ async function runWorkflowScript(options) {
|
|
|
2891
3165
|
if (options.signal?.aborted) return onAbort();
|
|
2892
3166
|
worker.on("error", (error) => finish({ error: taggedWorkflowError(`Workflow worker failed: ${error instanceof Error ? error.message : String(error)}`, "runtime") }));
|
|
2893
3167
|
worker.on("exit", (code) => {
|
|
2894
|
-
if (!settled &&
|
|
3168
|
+
if (!settled && !finishing) finish({ error: taggedWorkflowError(`Workflow worker exited before returning a result (code ${code}).`, "runtime") });
|
|
2895
3169
|
});
|
|
2896
3170
|
worker.on("message", (message) => {
|
|
2897
3171
|
if (settled) return;
|
|
@@ -2955,7 +3229,7 @@ async function runWorkflowScript(options) {
|
|
|
2955
3229
|
const respond = (promise2, responsePath, onBoundaryError) => {
|
|
2956
3230
|
void promise2.then(
|
|
2957
3231
|
(value) => {
|
|
2958
|
-
if (settled) return;
|
|
3232
|
+
if (settled || draining) return;
|
|
2959
3233
|
const normalized = responsePath ? omitNonJsonWorkflowResultMetadata(value) : omitUndefinedWorkflowValues(value);
|
|
2960
3234
|
if (!responsePath) {
|
|
2961
3235
|
worker.postMessage({ type: "response", callId: message.callId, ok: true, value: normalized });
|
|
@@ -2970,7 +3244,7 @@ async function runWorkflowScript(options) {
|
|
|
2970
3244
|
}
|
|
2971
3245
|
},
|
|
2972
3246
|
(error) => {
|
|
2973
|
-
if (!settled) {
|
|
3247
|
+
if (!settled && !draining) {
|
|
2974
3248
|
const errorKind = error instanceof Error ? error.workflowErrorKind : void 0;
|
|
2975
3249
|
worker.postMessage({ type: "response", callId: message.callId, ok: false, error: error instanceof Error ? error.message : String(error), ...isWorkflowScriptFailureKind(errorKind) ? { errorKind } : {} });
|
|
2976
3250
|
}
|
|
@@ -3054,6 +3328,7 @@ async function runWorkflowScript(options) {
|
|
|
3054
3328
|
return respond(Promise.reject(error));
|
|
3055
3329
|
}
|
|
3056
3330
|
if (acceptanceRecoveryBarrier) return respond(Promise.reject(new Error(recoveryBarrierMessage(acceptanceRecoveryBarrier.key, `runs.host('${key2}')`))));
|
|
3331
|
+
if (draining) return respond(Promise.reject(new Error(`runs.host('${key2}') refused: the workflow is draining.`)));
|
|
3057
3332
|
if (!options.host) return respond(Promise.reject(new Error("runs.host is unavailable in this host context.")));
|
|
3058
3333
|
if (hostCalls.size >= HOST_STEP_MAX_COUNT) return respond(Promise.reject(new Error(`workflowScript supports at most ${HOST_STEP_MAX_COUNT} runs.host calls.`)));
|
|
3059
3334
|
const startedAt2 = Date.now();
|
|
@@ -3115,8 +3390,11 @@ async function runWorkflowScript(options) {
|
|
|
3115
3390
|
if (existing) {
|
|
3116
3391
|
if (existing.fingerprint !== fingerprint) return respond(Promise.reject(new Error(`Duplicate workflow key '${key}' used with incompatible launch params.`)));
|
|
3117
3392
|
if (callObserved) existing.observed = true;
|
|
3118
|
-
|
|
3119
|
-
|
|
3393
|
+
if (!existing.reuseTraced) {
|
|
3394
|
+
existing.reuseTraced = true;
|
|
3395
|
+
trace.push({ operation: "run", key, state: "reused", ...workflowStringMetadata(params), ...existing.generatedLaneKey ? { generatedLaneKey: existing.generatedLaneKey } : {} });
|
|
3396
|
+
traceChanged();
|
|
3397
|
+
}
|
|
3120
3398
|
return respond(deliver(existing.promise), `runs.run('${key}') result`, (error) => children.set(key, responseBoundaryFailure(key, error)));
|
|
3121
3399
|
}
|
|
3122
3400
|
const permitError = options.oneUsePermit?.claim(key);
|
|
@@ -3124,6 +3402,7 @@ async function runWorkflowScript(options) {
|
|
|
3124
3402
|
if (options.oneUsePermit && message.args.batch !== void 0) return respond(Promise.reject(new Error("Workflow child permit does not support runs.all.")));
|
|
3125
3403
|
if (options.oneUsePermit && params.resume !== void 0) return respond(Promise.reject(new Error("Workflow child permit does not support retained resume.")));
|
|
3126
3404
|
if (params.action !== void 0) return respond(Promise.reject(new Error(`runs.run('${key}') accepts execution params only; management action is not allowed.`)));
|
|
3405
|
+
if (params.requireLauncher !== void 0) return respond(Promise.reject(new Error(`runs.run('${key}'): ${REQUIRE_LAUNCHER_SHAPE_ERROR}`)));
|
|
3127
3406
|
if (params.workflowScript !== void 0) return respond(Promise.reject(new Error(`runs.run('${key}') cannot start a nested workflow script.`)));
|
|
3128
3407
|
if (params.tasks !== void 0 || params.chain !== void 0 || params.parallel !== void 0 || params.concurrency !== void 0 || params.chainDir !== void 0) {
|
|
3129
3408
|
return respond(Promise.reject(new Error(`runs.run('${key}') accepts one child via { agent, task }; use runs.all(...) and JavaScript control flow for orchestration.`)));
|
|
@@ -3168,7 +3447,7 @@ async function runWorkflowScript(options) {
|
|
|
3168
3447
|
return true;
|
|
3169
3448
|
});
|
|
3170
3449
|
admission = Promise.resolve().then(() => {
|
|
3171
|
-
if (settled || finishing) return;
|
|
3450
|
+
if (settled || finishing || draining) return;
|
|
3172
3451
|
for (const call of calls) assertRecoveryBarrierAllowsRun(call.key, call.params);
|
|
3173
3452
|
return options.admit?.(calls, childController.signal);
|
|
3174
3453
|
});
|
|
@@ -3176,6 +3455,7 @@ async function runWorkflowScript(options) {
|
|
|
3176
3455
|
}
|
|
3177
3456
|
let resolvedResumeLineage;
|
|
3178
3457
|
const promise = admission.then(async () => {
|
|
3458
|
+
if (draining) stopChild(key, WORKFLOW_DRAIN_CHILD_MESSAGE);
|
|
3179
3459
|
if (settled || finishing || stoppedLaunches.has(key)) {
|
|
3180
3460
|
const reason = childController.signal.reason;
|
|
3181
3461
|
const text = children.get(key)?.error ?? (reason instanceof Error ? reason.message : typeof reason === "string" ? reason : "Workflow script aborted.");
|
|
@@ -3209,6 +3489,7 @@ async function runWorkflowScript(options) {
|
|
|
3209
3489
|
const text = children.get(key)?.error ?? (reason instanceof Error ? reason.message : typeof reason === "string" ? reason : "Workflow script aborted.");
|
|
3210
3490
|
return stoppedChildResult(key, text);
|
|
3211
3491
|
}
|
|
3492
|
+
acquiredLaunches.add(key);
|
|
3212
3493
|
const result = await options.launch(key, launchParams, childSignal, { admitted: true, batch: batch !== void 0 });
|
|
3213
3494
|
const autoResumeParams = setupAbortResumeParams(params, result, childSignal);
|
|
3214
3495
|
if (!autoResumeParams) return result;
|
|
@@ -3238,6 +3519,7 @@ async function runWorkflowScript(options) {
|
|
|
3238
3519
|
trace.push(settledEntry);
|
|
3239
3520
|
traceChanged();
|
|
3240
3521
|
notifyChildSettled(key, normalized);
|
|
3522
|
+
drainIfIdle();
|
|
3241
3523
|
return normalized;
|
|
3242
3524
|
}, (error) => {
|
|
3243
3525
|
const text = error instanceof Error ? error.message : String(error);
|
|
@@ -3248,6 +3530,7 @@ async function runWorkflowScript(options) {
|
|
|
3248
3530
|
trace.push({ operation: "run", key, state: "failed", durationMs: Date.now() - startedAt, ...workflowStringMetadata(params), ...generatedLaneKey ? { generatedLaneKey } : {}, error: text });
|
|
3249
3531
|
traceChanged();
|
|
3250
3532
|
notifyChildSettled(key, failure);
|
|
3533
|
+
drainIfIdle();
|
|
3251
3534
|
return failure;
|
|
3252
3535
|
});
|
|
3253
3536
|
launches.set(key, { fingerprint, promise, observed: callObserved, ...generatedLaneKey ? { generatedLaneKey } : {} });
|
|
@@ -3261,10 +3544,10 @@ async function runWorkflowScript(options) {
|
|
|
3261
3544
|
}
|
|
3262
3545
|
|
|
3263
3546
|
// src/missions/store.ts
|
|
3264
|
-
import { createHash as
|
|
3265
|
-
import * as
|
|
3547
|
+
import { createHash as createHash2, randomUUID as randomUUID3 } from "node:crypto";
|
|
3548
|
+
import * as fs7 from "node:fs";
|
|
3266
3549
|
import * as os from "node:os";
|
|
3267
|
-
import * as
|
|
3550
|
+
import * as path8 from "node:path";
|
|
3268
3551
|
|
|
3269
3552
|
// src/missions/types.ts
|
|
3270
3553
|
var MISSION_STATUSES = [
|
|
@@ -3479,12 +3762,12 @@ function parseMissionRecord(value, source = "mission record") {
|
|
|
3479
3762
|
};
|
|
3480
3763
|
}
|
|
3481
3764
|
function expandConfiguredPath(value, projectRoot) {
|
|
3482
|
-
const expanded = value.startsWith("~/") ?
|
|
3483
|
-
return
|
|
3765
|
+
const expanded = value.startsWith("~/") ? path8.join(os.homedir(), value.slice(2)) : value;
|
|
3766
|
+
return path8.isAbsolute(expanded) ? path8.normalize(expanded) : path8.resolve(projectRoot, expanded);
|
|
3484
3767
|
}
|
|
3485
3768
|
function projectMissionDirectory(agentDir, projectRoot) {
|
|
3486
|
-
const projectKey =
|
|
3487
|
-
return
|
|
3769
|
+
const projectKey = createHash2("sha256").update(projectRoot).digest("hex");
|
|
3770
|
+
return path8.join(agentDir, "missions", "projects", projectKey);
|
|
3488
3771
|
}
|
|
3489
3772
|
function validateMissionStoreConfig(value, label = "config.missions") {
|
|
3490
3773
|
if (value === void 0) return void 0;
|
|
@@ -3514,23 +3797,23 @@ function canonicalProjectRoot(root) {
|
|
|
3514
3797
|
let current = root;
|
|
3515
3798
|
for (; ; ) {
|
|
3516
3799
|
try {
|
|
3517
|
-
return
|
|
3800
|
+
return path8.join(fs7.realpathSync.native(current), ...missing.reverse());
|
|
3518
3801
|
} catch (error) {
|
|
3519
3802
|
if (error.code !== "ENOENT") throw error;
|
|
3520
|
-
const parent =
|
|
3803
|
+
const parent = path8.dirname(current);
|
|
3521
3804
|
if (parent === current) return root;
|
|
3522
|
-
missing.push(
|
|
3805
|
+
missing.push(path8.basename(current));
|
|
3523
3806
|
current = parent;
|
|
3524
3807
|
}
|
|
3525
3808
|
}
|
|
3526
3809
|
}
|
|
3527
3810
|
function resolveMissionStoreLocation(input) {
|
|
3528
|
-
const givenRoot =
|
|
3811
|
+
const givenRoot = path8.resolve(input.projectRoot);
|
|
3529
3812
|
const configuredDir = input.config?.directory;
|
|
3530
3813
|
const projectRoot = configuredDir ? givenRoot : canonicalProjectRoot(givenRoot);
|
|
3531
3814
|
const agentDir = input.agentDir ?? getAgentDir();
|
|
3532
3815
|
const missionDir = configuredDir ? expandConfiguredPath(configuredDir, givenRoot) : projectMissionDirectory(agentDir, projectRoot);
|
|
3533
|
-
const globalIndexDir = input.config?.globalIndexDir ? expandConfiguredPath(input.config.globalIndexDir, givenRoot) :
|
|
3816
|
+
const globalIndexDir = input.config?.globalIndexDir ? expandConfiguredPath(input.config.globalIndexDir, givenRoot) : path8.join(agentDir, "missions", "index");
|
|
3534
3817
|
return {
|
|
3535
3818
|
projectRoot,
|
|
3536
3819
|
missionDir,
|
|
@@ -3540,7 +3823,7 @@ function resolveMissionStoreLocation(input) {
|
|
|
3540
3823
|
};
|
|
3541
3824
|
}
|
|
3542
3825
|
function missionRecordPath(location, missionId) {
|
|
3543
|
-
return
|
|
3826
|
+
return path8.join(location.missionDir, `${validateMissionId(missionId)}.json`);
|
|
3544
3827
|
}
|
|
3545
3828
|
function parseIndexEntry(value, source) {
|
|
3546
3829
|
const input = asObject(value, source);
|
|
@@ -3557,8 +3840,8 @@ function parseIndexEntry(value, source) {
|
|
|
3557
3840
|
};
|
|
3558
3841
|
}
|
|
3559
3842
|
function indexPath(location, record) {
|
|
3560
|
-
const key =
|
|
3561
|
-
return
|
|
3843
|
+
const key = createHash2("sha256").update(`${location.projectRoot}\0${record.id}`).digest("hex");
|
|
3844
|
+
return path8.join(location.globalIndexDir, `${key}.json`);
|
|
3562
3845
|
}
|
|
3563
3846
|
function writeMission(location, record) {
|
|
3564
3847
|
const validated = parseMissionRecord(record);
|
|
@@ -3583,9 +3866,9 @@ function pruneTerminalMissions(location, maxTerminal) {
|
|
|
3583
3866
|
const terminal3 = listMissions(location).records.filter((record) => TERMINAL_MISSION_STATUSES.has(record.status)).sort((left, right) => right.updatedAt.localeCompare(left.updatedAt));
|
|
3584
3867
|
for (const record of terminal3.slice(maxTerminal)) {
|
|
3585
3868
|
try {
|
|
3586
|
-
|
|
3587
|
-
|
|
3588
|
-
if (location.writeGlobalIndex)
|
|
3869
|
+
fs7.rmSync(missionRecordPath(location, record.id), { force: true });
|
|
3870
|
+
fs7.rmSync(path8.join(location.missionDir, record.id), { recursive: true, force: true });
|
|
3871
|
+
if (location.writeGlobalIndex) fs7.rmSync(indexPath(location, record), { force: true });
|
|
3589
3872
|
} catch {
|
|
3590
3873
|
}
|
|
3591
3874
|
}
|
|
@@ -3594,7 +3877,7 @@ function createMission(location, input, now = /* @__PURE__ */ new Date(), retain
|
|
|
3594
3877
|
const createdAt = now.toISOString();
|
|
3595
3878
|
const record = {
|
|
3596
3879
|
schemaVersion: 1,
|
|
3597
|
-
id:
|
|
3880
|
+
id: randomUUID3(),
|
|
3598
3881
|
title: requiredString(input.title, "mission.title").trim(),
|
|
3599
3882
|
objective: requiredString(input.objective, "mission.objective").trim(),
|
|
3600
3883
|
...input.goal === true ? { goal: { status: "active" } } : {},
|
|
@@ -3632,7 +3915,7 @@ function readMission(location, missionId) {
|
|
|
3632
3915
|
const filePath = missionRecordPath(location, missionId);
|
|
3633
3916
|
let raw;
|
|
3634
3917
|
try {
|
|
3635
|
-
raw =
|
|
3918
|
+
raw = fs7.readFileSync(filePath, "utf-8");
|
|
3636
3919
|
} catch (error) {
|
|
3637
3920
|
if (error.code === "ENOENT") throw new MissionNotFoundError(missionId, location);
|
|
3638
3921
|
throw error;
|
|
@@ -3644,13 +3927,13 @@ function readMission(location, missionId) {
|
|
|
3644
3927
|
}
|
|
3645
3928
|
}
|
|
3646
3929
|
function listMissions(location) {
|
|
3647
|
-
if (!
|
|
3930
|
+
if (!fs7.existsSync(location.missionDir)) return { records: [], warnings: [] };
|
|
3648
3931
|
const records = [];
|
|
3649
3932
|
const warnings = [];
|
|
3650
|
-
for (const name of
|
|
3651
|
-
const filePath =
|
|
3933
|
+
for (const name of fs7.readdirSync(location.missionDir).filter((item) => item.endsWith(".json")).sort()) {
|
|
3934
|
+
const filePath = path8.join(location.missionDir, name);
|
|
3652
3935
|
try {
|
|
3653
|
-
records.push(parseMissionRecord(JSON.parse(
|
|
3936
|
+
records.push(parseMissionRecord(JSON.parse(fs7.readFileSync(filePath, "utf-8")), filePath));
|
|
3654
3937
|
} catch (error) {
|
|
3655
3938
|
warnings.push(`Skipped corrupt mission '${filePath}': ${error instanceof Error ? error.message : String(error)}`);
|
|
3656
3939
|
}
|
|
@@ -3692,7 +3975,7 @@ function updateMission(location, missionId, update, now = /* @__PURE__ */ new Da
|
|
|
3692
3975
|
const artifacts = [...current.artifacts];
|
|
3693
3976
|
for (const candidate of update.addArtifacts ?? []) {
|
|
3694
3977
|
const artifact = parseArtifact(candidate, "mission.update.addArtifacts[]");
|
|
3695
|
-
const existingIndex = artifacts.findIndex((item) => item.kind === artifact.kind &&
|
|
3978
|
+
const existingIndex = artifacts.findIndex((item) => item.kind === artifact.kind && path8.resolve(item.path) === path8.resolve(artifact.path));
|
|
3696
3979
|
if (existingIndex === -1) artifacts.push(artifact);
|
|
3697
3980
|
else artifacts[existingIndex] = { ...artifacts[existingIndex], ...artifact };
|
|
3698
3981
|
}
|
|
@@ -3707,7 +3990,7 @@ function updateMission(location, missionId, update, now = /* @__PURE__ */ new Da
|
|
|
3707
3990
|
const decisions = [
|
|
3708
3991
|
...current.decisions,
|
|
3709
3992
|
...(update.addDecisions ?? []).map((decision) => ({
|
|
3710
|
-
id:
|
|
3993
|
+
id: randomUUID3(),
|
|
3711
3994
|
status: "open",
|
|
3712
3995
|
title: requiredString(decision.title, "mission.update.addDecisions[].title"),
|
|
3713
3996
|
createdAt,
|
|
@@ -3762,15 +4045,15 @@ function updateMission(location, missionId, update, now = /* @__PURE__ */ new Da
|
|
|
3762
4045
|
return updated;
|
|
3763
4046
|
}
|
|
3764
4047
|
function listGlobalMissions(globalIndexDir) {
|
|
3765
|
-
if (!
|
|
4048
|
+
if (!fs7.existsSync(globalIndexDir)) return { entries: [], warnings: [] };
|
|
3766
4049
|
const entries = [];
|
|
3767
4050
|
const warnings = [];
|
|
3768
|
-
for (const name of
|
|
3769
|
-
const filePath =
|
|
4051
|
+
for (const name of fs7.readdirSync(globalIndexDir).filter((item) => item.endsWith(".json")).sort()) {
|
|
4052
|
+
const filePath = path8.join(globalIndexDir, name);
|
|
3770
4053
|
try {
|
|
3771
|
-
const entry = parseIndexEntry(JSON.parse(
|
|
4054
|
+
const entry = parseIndexEntry(JSON.parse(fs7.readFileSync(filePath, "utf-8")), filePath);
|
|
3772
4055
|
try {
|
|
3773
|
-
const record = parseMissionRecord(JSON.parse(
|
|
4056
|
+
const record = parseMissionRecord(JSON.parse(fs7.readFileSync(entry.recordPath, "utf-8")), entry.recordPath);
|
|
3774
4057
|
if (record.id !== entry.missionId) throw new Error(`record id '${record.id}' does not match index id '${entry.missionId}'`);
|
|
3775
4058
|
const projection = {
|
|
3776
4059
|
...entry,
|
|
@@ -3785,7 +4068,7 @@ function listGlobalMissions(globalIndexDir) {
|
|
|
3785
4068
|
} catch (error) {
|
|
3786
4069
|
if (error.code === "ENOENT") {
|
|
3787
4070
|
try {
|
|
3788
|
-
|
|
4071
|
+
fs7.rmSync(filePath, { force: true });
|
|
3789
4072
|
warnings.push(`Removed stale global mission pointer '${filePath}' because '${entry.recordPath}' no longer exists.`);
|
|
3790
4073
|
} catch (removeError) {
|
|
3791
4074
|
warnings.push(`Failed to remove stale global mission pointer '${filePath}': ${removeError instanceof Error ? removeError.message : String(removeError)}`);
|
|
@@ -3804,14 +4087,14 @@ function listGlobalMissions(globalIndexDir) {
|
|
|
3804
4087
|
|
|
3805
4088
|
// src/missions/workflow-state.ts
|
|
3806
4089
|
import { execFileSync } from "node:child_process";
|
|
3807
|
-
import { randomUUID as
|
|
3808
|
-
import * as
|
|
3809
|
-
import * as
|
|
4090
|
+
import { randomUUID as randomUUID4 } from "node:crypto";
|
|
4091
|
+
import * as fs8 from "node:fs";
|
|
4092
|
+
import * as path9 from "node:path";
|
|
3810
4093
|
var STATE_KEY_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
|
|
3811
4094
|
var STATE_LOCK_STALE_MS = 6e4;
|
|
3812
4095
|
var MISSION_STATE_MAX_BYTES = 256 * 1024;
|
|
3813
4096
|
function missionStatePath(location, missionId) {
|
|
3814
|
-
return
|
|
4097
|
+
return path9.join(location.missionDir, validateMissionId(missionId), "state.json");
|
|
3815
4098
|
}
|
|
3816
4099
|
function isProcessAlive(pid) {
|
|
3817
4100
|
try {
|
|
@@ -3823,7 +4106,7 @@ function isProcessAlive(pid) {
|
|
|
3823
4106
|
}
|
|
3824
4107
|
function linuxProcessStartKey(pid) {
|
|
3825
4108
|
try {
|
|
3826
|
-
const raw =
|
|
4109
|
+
const raw = fs8.readFileSync(`/proc/${pid}/stat`, "utf-8");
|
|
3827
4110
|
const tail = raw.slice(raw.lastIndexOf(")") + 2).trim().split(/\s+/);
|
|
3828
4111
|
return tail[19] ? `linux:${tail[19]}` : void 0;
|
|
3829
4112
|
} catch {
|
|
@@ -3859,7 +4142,7 @@ function computeProcessStartKey(pid) {
|
|
|
3859
4142
|
}
|
|
3860
4143
|
function readStateLockOwner(lockPath) {
|
|
3861
4144
|
try {
|
|
3862
|
-
const owner = JSON.parse(
|
|
4145
|
+
const owner = JSON.parse(fs8.readFileSync(path9.join(lockPath, "owner.json"), "utf-8"));
|
|
3863
4146
|
if (Number.isSafeInteger(owner.pid) && owner.pid > 0 && typeof owner.token === "string" && owner.token && Number.isSafeInteger(owner.createdAt)) {
|
|
3864
4147
|
return {
|
|
3865
4148
|
pid: owner.pid,
|
|
@@ -3885,7 +4168,7 @@ function stateLockIsStale(lockPath, options, now = Date.now()) {
|
|
|
3885
4168
|
return false;
|
|
3886
4169
|
}
|
|
3887
4170
|
try {
|
|
3888
|
-
return now -
|
|
4171
|
+
return now - fs8.statSync(lockPath).mtimeMs > STATE_LOCK_STALE_MS;
|
|
3889
4172
|
} catch (error) {
|
|
3890
4173
|
if (error.code === "ENOENT") return false;
|
|
3891
4174
|
throw error;
|
|
@@ -3894,11 +4177,11 @@ function stateLockIsStale(lockPath, options, now = Date.now()) {
|
|
|
3894
4177
|
function removeOwnedStateLock(lockPath, owner) {
|
|
3895
4178
|
const current = readStateLockOwner(lockPath);
|
|
3896
4179
|
if (current?.token !== owner.token) return;
|
|
3897
|
-
|
|
4180
|
+
fs8.rmSync(lockPath, { recursive: true, force: true });
|
|
3898
4181
|
}
|
|
3899
4182
|
function staleDirectoryExists(dirPath, now = Date.now()) {
|
|
3900
4183
|
try {
|
|
3901
|
-
return now -
|
|
4184
|
+
return now - fs8.statSync(dirPath).mtimeMs > STATE_LOCK_STALE_MS;
|
|
3902
4185
|
} catch (error) {
|
|
3903
4186
|
if (error.code === "ENOENT") return false;
|
|
3904
4187
|
throw error;
|
|
@@ -3906,7 +4189,7 @@ function staleDirectoryExists(dirPath, now = Date.now()) {
|
|
|
3906
4189
|
}
|
|
3907
4190
|
function tryMakeDirectory(dirPath, mode) {
|
|
3908
4191
|
try {
|
|
3909
|
-
|
|
4192
|
+
fs8.mkdirSync(dirPath, { mode });
|
|
3910
4193
|
return true;
|
|
3911
4194
|
} catch (error) {
|
|
3912
4195
|
if (error.code === "EEXIST") return false;
|
|
@@ -3922,21 +4205,21 @@ function reclaimStaleStateLock(lockPath, reclaimPath, options) {
|
|
|
3922
4205
|
if (!tryMakeDirectory(reclaimPath, 448)) return false;
|
|
3923
4206
|
try {
|
|
3924
4207
|
if (!stateLockIsStale(lockPath, options)) return false;
|
|
3925
|
-
|
|
4208
|
+
fs8.rmSync(lockPath, { recursive: true, force: true });
|
|
3926
4209
|
return true;
|
|
3927
4210
|
} finally {
|
|
3928
|
-
|
|
4211
|
+
fs8.rmSync(reclaimPath, { recursive: true, force: true });
|
|
3929
4212
|
}
|
|
3930
4213
|
}
|
|
3931
4214
|
function withStateFileLock(filePath, operation, options) {
|
|
3932
|
-
|
|
4215
|
+
fs8.mkdirSync(path9.dirname(filePath), { recursive: true });
|
|
3933
4216
|
const lockPath = `${filePath}.lock`;
|
|
3934
4217
|
const reclaimPath = `${lockPath}.reclaim`;
|
|
3935
4218
|
let owner;
|
|
3936
4219
|
for (let attempt = 0; ; attempt++) {
|
|
3937
|
-
if (
|
|
4220
|
+
if (fs8.existsSync(reclaimPath)) {
|
|
3938
4221
|
if (staleDirectoryExists(reclaimPath)) {
|
|
3939
|
-
|
|
4222
|
+
fs8.rmSync(reclaimPath, { recursive: true, force: true });
|
|
3940
4223
|
continue;
|
|
3941
4224
|
}
|
|
3942
4225
|
waitForStateLock(options.retryDelaysMs[attempt], lockPath);
|
|
@@ -3958,11 +4241,11 @@ function withStateFileLock(filePath, operation, options) {
|
|
|
3958
4241
|
continue;
|
|
3959
4242
|
}
|
|
3960
4243
|
const key = options.getProcessStartKey(process.pid);
|
|
3961
|
-
owner = { pid: process.pid, token:
|
|
4244
|
+
owner = { pid: process.pid, token: randomUUID4(), createdAt: Date.now(), ...key ? { processKey: key } : {} };
|
|
3962
4245
|
try {
|
|
3963
|
-
|
|
4246
|
+
fs8.writeFileSync(path9.join(lockPath, "owner.json"), JSON.stringify(owner), { encoding: "utf-8", mode: 384 });
|
|
3964
4247
|
} catch (error) {
|
|
3965
|
-
|
|
4248
|
+
fs8.rmSync(lockPath, { recursive: true, force: true });
|
|
3966
4249
|
owner = void 0;
|
|
3967
4250
|
throw error;
|
|
3968
4251
|
}
|
|
@@ -3992,7 +4275,7 @@ function createMissionWorkflowState(location, missionId, options = {}) {
|
|
|
3992
4275
|
const readStateFile = () => {
|
|
3993
4276
|
let raw;
|
|
3994
4277
|
try {
|
|
3995
|
-
raw =
|
|
4278
|
+
raw = fs8.readFileSync(filePath, "utf-8");
|
|
3996
4279
|
} catch (error) {
|
|
3997
4280
|
if (error.code === "ENOENT") return /* @__PURE__ */ Object.create(null);
|
|
3998
4281
|
throw new Error(`Failed to read mission state '${filePath}': ${error instanceof Error ? error.message : String(error)}`);
|
|
@@ -4037,13 +4320,13 @@ function createMissionWorkflowState(location, missionId, options = {}) {
|
|
|
4037
4320
|
}
|
|
4038
4321
|
|
|
4039
4322
|
// src/missions/actions.ts
|
|
4040
|
-
import * as fs11 from "node:fs";
|
|
4041
|
-
import * as path12 from "node:path";
|
|
4042
|
-
|
|
4043
|
-
// src/missions/lifecycle.ts
|
|
4044
4323
|
import * as fs10 from "node:fs";
|
|
4045
4324
|
import * as path11 from "node:path";
|
|
4046
|
-
|
|
4325
|
+
|
|
4326
|
+
// src/missions/lifecycle.ts
|
|
4327
|
+
import * as fs9 from "node:fs";
|
|
4328
|
+
import * as path10 from "node:path";
|
|
4329
|
+
import { createHash as createHash3 } from "node:crypto";
|
|
4047
4330
|
var MISSION_BINDING_FILE = "mission.json";
|
|
4048
4331
|
function workflowObjective(params) {
|
|
4049
4332
|
const objective = params.task?.trim() || params.tasks?.find((task) => task.task?.trim())?.task?.trim() || params.chain?.find((step) => step.task?.trim())?.task?.trim();
|
|
@@ -4131,8 +4414,8 @@ function artifactsForResult(result) {
|
|
|
4131
4414
|
const artifacts = [];
|
|
4132
4415
|
if (result.details.asyncDir) {
|
|
4133
4416
|
artifacts.push(
|
|
4134
|
-
{ kind: "status", path:
|
|
4135
|
-
{ kind: "other", path:
|
|
4417
|
+
{ kind: "status", path: path10.join(result.details.asyncDir, "status.json") },
|
|
4418
|
+
{ kind: "other", path: path10.join(result.details.asyncDir, "events.jsonl"), description: "Lifecycle events" }
|
|
4136
4419
|
);
|
|
4137
4420
|
}
|
|
4138
4421
|
for (const child of result.details.results) {
|
|
@@ -4162,7 +4445,7 @@ function persistedBinding(binding) {
|
|
|
4162
4445
|
};
|
|
4163
4446
|
}
|
|
4164
4447
|
function writeMissionAsyncBinding(asyncDir, binding) {
|
|
4165
|
-
writePrivateAtomicJson(
|
|
4448
|
+
writePrivateAtomicJson(path10.join(asyncDir, MISSION_BINDING_FILE), persistedBinding(binding));
|
|
4166
4449
|
}
|
|
4167
4450
|
function attachMissionToLaunchResult(input) {
|
|
4168
4451
|
const runId = input.result.details.runId ?? input.result.details.asyncId;
|
|
@@ -4206,10 +4489,10 @@ function attachMissionToLaunchResult(input) {
|
|
|
4206
4489
|
});
|
|
4207
4490
|
if (input.result.details.asyncDir) {
|
|
4208
4491
|
writeMissionAsyncBinding(input.result.details.asyncDir, input.binding);
|
|
4209
|
-
const statusPath =
|
|
4210
|
-
if (
|
|
4492
|
+
const statusPath = path10.join(input.result.details.asyncDir, "status.json");
|
|
4493
|
+
if (fs9.existsSync(statusPath)) {
|
|
4211
4494
|
try {
|
|
4212
|
-
const status = JSON.parse(
|
|
4495
|
+
const status = JSON.parse(fs9.readFileSync(statusPath, "utf-8"));
|
|
4213
4496
|
if (typeof status.state === "string" && !["queued", "running"].includes(status.state)) {
|
|
4214
4497
|
mission = syncMissionFromAsyncCompletion({
|
|
4215
4498
|
runId,
|
|
@@ -4272,9 +4555,9 @@ function parsePersistedBinding(value, source) {
|
|
|
4272
4555
|
};
|
|
4273
4556
|
}
|
|
4274
4557
|
function readMissionBinding(asyncDir) {
|
|
4275
|
-
const bindingPath =
|
|
4276
|
-
if (!
|
|
4277
|
-
const raw =
|
|
4558
|
+
const bindingPath = path10.join(asyncDir, MISSION_BINDING_FILE);
|
|
4559
|
+
if (!fs9.existsSync(bindingPath)) return void 0;
|
|
4560
|
+
const raw = fs9.readFileSync(bindingPath, "utf-8");
|
|
4278
4561
|
try {
|
|
4279
4562
|
return parsePersistedBinding(JSON.parse(raw), bindingPath);
|
|
4280
4563
|
} catch (error) {
|
|
@@ -4296,12 +4579,12 @@ function syncMissionFromAsyncCompletion(value) {
|
|
|
4296
4579
|
} catch (error) {
|
|
4297
4580
|
if (!(error instanceof MissionNotFoundError)) throw error;
|
|
4298
4581
|
const reason = "mission-record-missing";
|
|
4299
|
-
const markerId =
|
|
4300
|
-
const markerPath3 =
|
|
4582
|
+
const markerId = createHash3("sha256").update(JSON.stringify([runId, binding.missionId, reason])).digest("hex");
|
|
4583
|
+
const markerPath3 = path10.join(event.asyncDir, `.mission-sync-skipped-${markerId}.json`);
|
|
4301
4584
|
try {
|
|
4302
|
-
|
|
4585
|
+
fs9.writeFileSync(markerPath3, `${JSON.stringify({ runId, missionId: binding.missionId, reason })}
|
|
4303
4586
|
`, { encoding: "utf-8", mode: 384, flag: "wx" });
|
|
4304
|
-
|
|
4587
|
+
fs9.appendFileSync(path10.join(event.asyncDir, "events.jsonl"), `${JSON.stringify({
|
|
4305
4588
|
type: "subagent.mission.sync.skipped",
|
|
4306
4589
|
ts: Date.now(),
|
|
4307
4590
|
runId,
|
|
@@ -4316,8 +4599,8 @@ function syncMissionFromAsyncCompletion(value) {
|
|
|
4316
4599
|
}
|
|
4317
4600
|
const completedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
4318
4601
|
const artifacts = [
|
|
4319
|
-
{ kind: "status", path:
|
|
4320
|
-
{ kind: "other", path:
|
|
4602
|
+
{ kind: "status", path: path10.join(event.asyncDir, "status.json") },
|
|
4603
|
+
{ kind: "other", path: path10.join(event.asyncDir, "events.jsonl"), description: "Lifecycle events" }
|
|
4321
4604
|
];
|
|
4322
4605
|
if (event.parallelHandoff && typeof event.parallelHandoff === "object" && typeof event.parallelHandoff.path === "string") {
|
|
4323
4606
|
artifacts.push({ kind: "manifest", path: event.parallelHandoff.path });
|
|
@@ -4513,11 +4796,11 @@ function refreshLinkedRunStatus(location, record) {
|
|
|
4513
4796
|
const runAcceptance = [];
|
|
4514
4797
|
const updates = record.runs.flatMap((run) => {
|
|
4515
4798
|
if (!run.asyncDir) return [];
|
|
4516
|
-
const statusPath =
|
|
4517
|
-
if (!
|
|
4799
|
+
const statusPath = path11.join(run.asyncDir, "status.json");
|
|
4800
|
+
if (!fs10.existsSync(statusPath)) return [];
|
|
4518
4801
|
let status2;
|
|
4519
4802
|
try {
|
|
4520
|
-
status2 = JSON.parse(
|
|
4803
|
+
status2 = JSON.parse(fs10.readFileSync(statusPath, "utf-8"));
|
|
4521
4804
|
} catch (error) {
|
|
4522
4805
|
warnings.push(`Failed to read linked run status '${statusPath}': ${error instanceof Error ? error.message : String(error)}`);
|
|
4523
4806
|
return [];
|
|
@@ -4689,9 +4972,9 @@ ${formatMission(record2)}`, { mode: "management", results: [], missionId: record
|
|
|
4689
4972
|
}
|
|
4690
4973
|
|
|
4691
4974
|
// src/runs/background/result-files.ts
|
|
4692
|
-
import { createHash as
|
|
4693
|
-
import * as
|
|
4694
|
-
import * as
|
|
4975
|
+
import { createHash as createHash4 } from "node:crypto";
|
|
4976
|
+
import * as fs11 from "node:fs";
|
|
4977
|
+
import * as path12 from "node:path";
|
|
4695
4978
|
var RESULT_INDEX_VERSION = 1;
|
|
4696
4979
|
var RESULT_INDEX_DIR = "result-index";
|
|
4697
4980
|
var SESSION_INDEX_DIR = "sessions";
|
|
@@ -4722,31 +5005,31 @@ function resultFileName(runId) {
|
|
|
4722
5005
|
return `${runId}${JSON_EXTENSION}`;
|
|
4723
5006
|
}
|
|
4724
5007
|
function resultFilePath(resultsDir, runId) {
|
|
4725
|
-
return
|
|
5008
|
+
return path12.join(resultsDir, resultFileName(runId));
|
|
4726
5009
|
}
|
|
4727
5010
|
function sessionIndexDir2(resultsDir, sessionId) {
|
|
4728
|
-
return
|
|
5011
|
+
return path12.join(resultsDir, RESULT_INDEX_DIR, SESSION_INDEX_DIR, encodeSegment(sessionId));
|
|
4729
5012
|
}
|
|
4730
5013
|
function sessionIndexDirs(resultsDir, sessionId) {
|
|
4731
|
-
return indexSegmentAliases(sessionId).map((segment) =>
|
|
5014
|
+
return indexSegmentAliases(sessionId).map((segment) => path12.join(resultsDir, RESULT_INDEX_DIR, SESSION_INDEX_DIR, segment));
|
|
4732
5015
|
}
|
|
4733
5016
|
function resultIndexPath(resultsDir, sessionId, runId) {
|
|
4734
|
-
return
|
|
5017
|
+
return path12.join(sessionIndexDir2(resultsDir, sessionId), encodedJsonFileName(runId));
|
|
4735
5018
|
}
|
|
4736
5019
|
function resultIndexPaths(resultsDir, sessionId, runId) {
|
|
4737
|
-
return sessionIndexDirs(resultsDir, sessionId).flatMap((dir) => encodedJsonFileNames(runId).map((fileName) =>
|
|
5020
|
+
return sessionIndexDirs(resultsDir, sessionId).flatMap((dir) => encodedJsonFileNames(runId).map((fileName) => path12.join(dir, fileName)));
|
|
4738
5021
|
}
|
|
4739
5022
|
function runIndexPath(resultsDir, runId) {
|
|
4740
|
-
return
|
|
5023
|
+
return path12.join(resultsDir, RESULT_INDEX_DIR, RUN_INDEX_DIR, encodedJsonFileName(runId));
|
|
4741
5024
|
}
|
|
4742
5025
|
function resultPendingPath(resultsDir, sessionId, runId) {
|
|
4743
|
-
return
|
|
5026
|
+
return path12.join(resultsDir, RESULT_PENDING_DIR, encodeSegment(sessionId), encodedJsonFileName(runId));
|
|
4744
5027
|
}
|
|
4745
5028
|
function resultPendingPaths(resultsDir, sessionId, runId) {
|
|
4746
|
-
return indexSegmentAliases(sessionId).flatMap((segment) => encodedJsonFileNames(runId).map((fileName) =>
|
|
5029
|
+
return indexSegmentAliases(sessionId).flatMap((segment) => encodedJsonFileNames(runId).map((fileName) => path12.join(resultsDir, RESULT_PENDING_DIR, segment, fileName)));
|
|
4747
5030
|
}
|
|
4748
5031
|
function pendingSessionDirs(resultsDir, sessionId) {
|
|
4749
|
-
return indexSegmentAliases(sessionId).map((segment) =>
|
|
5032
|
+
return indexSegmentAliases(sessionId).map((segment) => path12.join(resultsDir, RESULT_PENDING_DIR, segment));
|
|
4750
5033
|
}
|
|
4751
5034
|
function firstExistingResultFile(paths) {
|
|
4752
5035
|
for (const filePath of paths) {
|
|
@@ -4755,19 +5038,19 @@ function firstExistingResultFile(paths) {
|
|
|
4755
5038
|
return void 0;
|
|
4756
5039
|
}
|
|
4757
5040
|
function observerIndexDir(resultsDir, observer) {
|
|
4758
|
-
return
|
|
5041
|
+
return path12.join(resultsDir, RESULT_INDEX_DIR, OBSERVER_INDEX_DIR, observer);
|
|
4759
5042
|
}
|
|
4760
5043
|
function observerIndexPath(resultsDir, observer, runId) {
|
|
4761
|
-
return
|
|
5044
|
+
return path12.join(observerIndexDir(resultsDir, observer), encodedJsonFileName(runId));
|
|
4762
5045
|
}
|
|
4763
5046
|
function missionObserverIndexPath(resultsDir, runId) {
|
|
4764
5047
|
return observerIndexPath(resultsDir, MISSION_OBSERVER, runId);
|
|
4765
5048
|
}
|
|
4766
5049
|
function toolCallIndexDir3(resultsDir, toolCallId) {
|
|
4767
|
-
return
|
|
5050
|
+
return path12.join(resultsDir, RESULT_INDEX_DIR, TOOL_CALL_INDEX_DIR3, encodeIndexSegment(toolCallId));
|
|
4768
5051
|
}
|
|
4769
5052
|
function toolCallIndexPath2(resultsDir, toolCallId, runId) {
|
|
4770
|
-
return
|
|
5053
|
+
return path12.join(toolCallIndexDir3(resultsDir, toolCallId), encodedJsonFileName(runId));
|
|
4771
5054
|
}
|
|
4772
5055
|
function parseResultIndexEntry(value) {
|
|
4773
5056
|
if (!value || typeof value !== "object" || Array.isArray(value)) return void 0;
|
|
@@ -4783,10 +5066,10 @@ function parseResultIndexEntry(value) {
|
|
|
4783
5066
|
};
|
|
4784
5067
|
}
|
|
4785
5068
|
function writeResultIndexForData(resultPath, data) {
|
|
4786
|
-
const runId = nonEmptyString2(data.runId) ?? nonEmptyString2(data.id) ??
|
|
5069
|
+
const runId = nonEmptyString2(data.runId) ?? nonEmptyString2(data.id) ?? path12.basename(resultPath, ".json");
|
|
4787
5070
|
const sessionId = nonEmptyString2(data.sessionId);
|
|
4788
5071
|
if (!runId || !sessionId) return;
|
|
4789
|
-
const file =
|
|
5072
|
+
const file = path12.basename(resultPath);
|
|
4790
5073
|
const entry = {
|
|
4791
5074
|
version: RESULT_INDEX_VERSION,
|
|
4792
5075
|
runId,
|
|
@@ -4795,7 +5078,7 @@ function writeResultIndexForData(resultPath, data) {
|
|
|
4795
5078
|
writtenAt: Date.now(),
|
|
4796
5079
|
...nonEmptyString2(data.asyncDir) ? { asyncDir: nonEmptyString2(data.asyncDir) } : {}
|
|
4797
5080
|
};
|
|
4798
|
-
const resultsDir =
|
|
5081
|
+
const resultsDir = path12.dirname(resultPath);
|
|
4799
5082
|
writeAtomicJson(resultIndexPath(resultsDir, sessionId, runId), entry);
|
|
4800
5083
|
try {
|
|
4801
5084
|
writeAtomicJson(runIndexPath(resultsDir, runId), entry);
|
|
@@ -4809,7 +5092,7 @@ function writeResultIndexForData(resultPath, data) {
|
|
|
4809
5092
|
console.error(`Failed to write async result tool-call index for '${resultPath}':`, error);
|
|
4810
5093
|
}
|
|
4811
5094
|
try {
|
|
4812
|
-
if (entry.asyncDir &&
|
|
5095
|
+
if (entry.asyncDir && fs11.existsSync(path12.join(entry.asyncDir, MISSION_BINDING_FILE))) {
|
|
4813
5096
|
writeAtomicJson(observerIndexPath(resultsDir, MISSION_OBSERVER, runId), entry);
|
|
4814
5097
|
}
|
|
4815
5098
|
} catch (error) {
|
|
@@ -4817,10 +5100,10 @@ function writeResultIndexForData(resultPath, data) {
|
|
|
4817
5100
|
}
|
|
4818
5101
|
}
|
|
4819
5102
|
function writeIndexedPendingResultFile(resultPath, data) {
|
|
4820
|
-
const runId = nonEmptyString2(data.runId) ?? nonEmptyString2(data.id) ??
|
|
5103
|
+
const runId = nonEmptyString2(data.runId) ?? nonEmptyString2(data.id) ?? path12.basename(resultPath, ".json");
|
|
4821
5104
|
const sessionId = nonEmptyString2(data.sessionId);
|
|
4822
5105
|
if (!sessionId) throw new Error(`Cannot write async result '${resultPath}' without a sessionId.`);
|
|
4823
|
-
const resultsDir =
|
|
5106
|
+
const resultsDir = path12.dirname(resultPath);
|
|
4824
5107
|
let indexFailure;
|
|
4825
5108
|
writeAtomicJson(resultPendingPath(resultsDir, sessionId, runId), data, () => {
|
|
4826
5109
|
try {
|
|
@@ -4834,54 +5117,54 @@ function writeIndexedPendingResultFile(resultPath, data) {
|
|
|
4834
5117
|
}
|
|
4835
5118
|
function writeAsyncResultFile(resultPath, data) {
|
|
4836
5119
|
const { runId, sessionId, resultsDir } = writeIndexedPendingResultFile(resultPath, data);
|
|
4837
|
-
return promotePendingResultFile(resultsDir, sessionId, runId,
|
|
5120
|
+
return promotePendingResultFile(resultsDir, sessionId, runId, path12.basename(resultPath), { logFailure: false }) === "promoted" ? { state: "public" } : { state: "pending" };
|
|
4838
5121
|
}
|
|
4839
5122
|
function removeResultIndex(resultsDir, sessionId, runId, toolCallId) {
|
|
4840
5123
|
if (!runId) return;
|
|
4841
5124
|
if (sessionId) {
|
|
4842
5125
|
for (const indexPath2 of resultIndexPaths(resultsDir, sessionId, runId)) {
|
|
4843
5126
|
try {
|
|
4844
|
-
|
|
5127
|
+
fs11.rmSync(indexPath2, { force: true });
|
|
4845
5128
|
} catch {
|
|
4846
5129
|
}
|
|
4847
5130
|
}
|
|
4848
5131
|
for (const pendingPath of resultPendingPaths(resultsDir, sessionId, runId)) {
|
|
4849
5132
|
try {
|
|
4850
|
-
|
|
5133
|
+
fs11.rmSync(pendingPath, { force: true });
|
|
4851
5134
|
} catch {
|
|
4852
5135
|
}
|
|
4853
5136
|
}
|
|
4854
5137
|
}
|
|
4855
5138
|
try {
|
|
4856
|
-
|
|
5139
|
+
fs11.rmSync(runIndexPath(resultsDir, runId), { force: true });
|
|
4857
5140
|
} catch {
|
|
4858
5141
|
}
|
|
4859
5142
|
if (toolCallId) {
|
|
4860
5143
|
try {
|
|
4861
|
-
|
|
5144
|
+
fs11.rmSync(toolCallIndexPath2(resultsDir, toolCallId, runId), { force: true });
|
|
4862
5145
|
} catch {
|
|
4863
5146
|
}
|
|
4864
5147
|
}
|
|
4865
5148
|
try {
|
|
4866
|
-
|
|
5149
|
+
fs11.rmSync(observerIndexPath(resultsDir, MISSION_OBSERVER, runId), { force: true });
|
|
4867
5150
|
} catch {
|
|
4868
5151
|
}
|
|
4869
5152
|
}
|
|
4870
5153
|
function removeMissionObserverIndex(resultsDir, runId) {
|
|
4871
5154
|
if (!runId) return;
|
|
4872
5155
|
try {
|
|
4873
|
-
|
|
5156
|
+
fs11.rmSync(observerIndexPath(resultsDir, MISSION_OBSERVER, runId), { force: true });
|
|
4874
5157
|
} catch {
|
|
4875
5158
|
}
|
|
4876
5159
|
}
|
|
4877
5160
|
function withResultRunLease(resultsDir, runId, action, waitMs) {
|
|
4878
|
-
const leaseDir =
|
|
4879
|
-
|
|
4880
|
-
return withFileLease(
|
|
5161
|
+
const leaseDir = path12.join(resultsDir, RESULT_LEASE_DIR);
|
|
5162
|
+
fs11.mkdirSync(leaseDir, { recursive: true });
|
|
5163
|
+
return withFileLease(path12.join(leaseDir, createHash4("sha256").update(runId).digest("hex")), action, waitMs);
|
|
4881
5164
|
}
|
|
4882
5165
|
function readResultPayload(filePath) {
|
|
4883
5166
|
try {
|
|
4884
|
-
return
|
|
5167
|
+
return fs11.readFileSync(filePath, "utf-8");
|
|
4885
5168
|
} catch (error) {
|
|
4886
5169
|
const code = error.code;
|
|
4887
5170
|
if (code === "ENOENT" || code === "ENOTDIR" || code === "EISDIR" || isUnaddressableResultCandidate(error)) return void 0;
|
|
@@ -4889,7 +5172,7 @@ function readResultPayload(filePath) {
|
|
|
4889
5172
|
}
|
|
4890
5173
|
}
|
|
4891
5174
|
function resultPayloadCandidates(publicPath, read) {
|
|
4892
|
-
return [...read.sessionId ? resultPendingPaths(
|
|
5175
|
+
return [...read.sessionId ? resultPendingPaths(path12.dirname(publicPath), read.sessionId, read.runId) : [], publicPath];
|
|
4893
5176
|
}
|
|
4894
5177
|
function readByConsumer(publicPath, read, candidate, current) {
|
|
4895
5178
|
return current === read.snapshot || candidate === publicPath && current === read.stalePublic;
|
|
@@ -4901,10 +5184,10 @@ function resultSnapshotReplaced(publicPath, read) {
|
|
|
4901
5184
|
});
|
|
4902
5185
|
}
|
|
4903
5186
|
function retireResultSnapshot(publicPath, read, payloadPath = publicPath, leaseWaitMs) {
|
|
4904
|
-
const resultsDir =
|
|
5187
|
+
const resultsDir = path12.dirname(publicPath);
|
|
4905
5188
|
return withResultRunLease(resultsDir, read.runId, () => {
|
|
4906
5189
|
if (resultSnapshotReplaced(publicPath, read)) {
|
|
4907
|
-
if (payloadPath !== publicPath && readResultPayload(payloadPath) === read.snapshot)
|
|
5190
|
+
if (payloadPath !== publicPath && readResultPayload(payloadPath) === read.snapshot) fs11.rmSync(payloadPath, { force: true });
|
|
4908
5191
|
return "replaced";
|
|
4909
5192
|
}
|
|
4910
5193
|
let removalFailure;
|
|
@@ -4912,7 +5195,7 @@ function retireResultSnapshot(publicPath, read, payloadPath = publicPath, leaseW
|
|
|
4912
5195
|
const current = readResultPayload(candidate);
|
|
4913
5196
|
if (current === void 0 || !readByConsumer(publicPath, read, candidate, current)) continue;
|
|
4914
5197
|
try {
|
|
4915
|
-
|
|
5198
|
+
fs11.rmSync(candidate, { force: true });
|
|
4916
5199
|
} catch (error) {
|
|
4917
5200
|
removalFailure ??= { error };
|
|
4918
5201
|
}
|
|
@@ -4923,8 +5206,8 @@ function retireResultSnapshot(publicPath, read, payloadPath = publicPath, leaseW
|
|
|
4923
5206
|
}, leaseWaitMs);
|
|
4924
5207
|
}
|
|
4925
5208
|
function acknowledgeMissionObserverSnapshot(publicPath, read, leaseWaitMs) {
|
|
4926
|
-
const resultsDir =
|
|
4927
|
-
if (!
|
|
5209
|
+
const resultsDir = path12.dirname(publicPath);
|
|
5210
|
+
if (!fs11.existsSync(observerIndexPath(resultsDir, MISSION_OBSERVER, read.runId))) return "acknowledged";
|
|
4928
5211
|
return withResultRunLease(resultsDir, read.runId, () => {
|
|
4929
5212
|
if (resultSnapshotReplaced(publicPath, read)) return "replaced";
|
|
4930
5213
|
removeMissionObserverIndex(resultsDir, read.runId);
|
|
@@ -4933,7 +5216,7 @@ function acknowledgeMissionObserverSnapshot(publicPath, read, leaseWaitMs) {
|
|
|
4933
5216
|
}
|
|
4934
5217
|
function existingResultFile(resultPath) {
|
|
4935
5218
|
try {
|
|
4936
|
-
return
|
|
5219
|
+
return fs11.statSync(resultPath).isFile();
|
|
4937
5220
|
} catch (error) {
|
|
4938
5221
|
if (error.code !== "ENOENT" && !isUnaddressableResultCandidate(error)) console.error(`Failed to inspect async result payload '${resultPath}':`, error);
|
|
4939
5222
|
return false;
|
|
@@ -4949,22 +5232,22 @@ function resultPayloadMatchesSessionRun(data, sessionId, runId) {
|
|
|
4949
5232
|
}
|
|
4950
5233
|
function pendingResultPayloadMatches(filePath, sessionId, runId) {
|
|
4951
5234
|
try {
|
|
4952
|
-
return resultPayloadMatchesSessionRun(JSON.parse(
|
|
5235
|
+
return resultPayloadMatchesSessionRun(JSON.parse(fs11.readFileSync(filePath, "utf-8")), sessionId, runId);
|
|
4953
5236
|
} catch (error) {
|
|
4954
5237
|
if (error.code !== "ENOENT" && !isUnaddressableResultCandidate(error)) console.error(`Ignoring invalid pending async result '${filePath}':`, error);
|
|
4955
5238
|
return false;
|
|
4956
5239
|
}
|
|
4957
5240
|
}
|
|
4958
5241
|
function assertPendingResultPayloadMatches(filePath, sessionId, runId) {
|
|
4959
|
-
return resultPayloadMatchesSessionRun(JSON.parse(
|
|
5242
|
+
return resultPayloadMatchesSessionRun(JSON.parse(fs11.readFileSync(filePath, "utf-8")), sessionId, runId);
|
|
4960
5243
|
}
|
|
4961
5244
|
function promotePendingResultFile(resultsDir, sessionId, runId, file = resultFileName(runId), options = {}) {
|
|
4962
|
-
if (file !==
|
|
5245
|
+
if (file !== path12.basename(file) || !file.endsWith(".json")) return "none";
|
|
4963
5246
|
const pendingPath = firstExistingResultFile(resultPendingPaths(resultsDir, sessionId, runId));
|
|
4964
5247
|
if (!pendingPath) return "none";
|
|
4965
|
-
const resultPath =
|
|
5248
|
+
const resultPath = path12.join(resultsDir, file);
|
|
4966
5249
|
try {
|
|
4967
|
-
|
|
5250
|
+
fs11.renameSync(pendingPath, resultPath);
|
|
4968
5251
|
return existingResultFile(resultPath) ? "promoted" : "pending";
|
|
4969
5252
|
} catch (error) {
|
|
4970
5253
|
const code = error.code;
|
|
@@ -4984,7 +5267,7 @@ function promotePendingResultFile(resultsDir, sessionId, runId, file = resultFil
|
|
|
4984
5267
|
}
|
|
4985
5268
|
}
|
|
4986
5269
|
function pendingResultLocationForSessionRun(resultsDir, sessionId, runId, file = resultFileName(runId)) {
|
|
4987
|
-
if (file !==
|
|
5270
|
+
if (file !== path12.basename(file) || !file.endsWith(".json")) return void 0;
|
|
4988
5271
|
const pendingPath = firstExistingResultFile(resultPendingPaths(resultsDir, sessionId, runId));
|
|
4989
5272
|
if (!pendingPath || !pendingResultPayloadMatches(pendingPath, sessionId, runId)) return void 0;
|
|
4990
5273
|
return { file, path: pendingPath, state: "pending" };
|
|
@@ -4998,19 +5281,19 @@ function resultPayloadFileForSessionRun(resultsDir, sessionId, runId) {
|
|
|
4998
5281
|
return firstExistingResultFile([...resultPendingPaths(resultsDir, sessionId, runId), resultFilePath(resultsDir, runId)]);
|
|
4999
5282
|
}
|
|
5000
5283
|
function resultPayloadLocationFromIndex(resultsDir, entry) {
|
|
5001
|
-
if (entry.file !==
|
|
5284
|
+
if (entry.file !== path12.basename(entry.file) || !entry.file.endsWith(".json")) return void 0;
|
|
5002
5285
|
const pendingState = promotePendingResultFile(resultsDir, entry.sessionId, entry.runId, entry.file);
|
|
5003
5286
|
if (pendingState === "pending") {
|
|
5004
5287
|
return pendingResultLocationForSessionRun(resultsDir, entry.sessionId, entry.runId, entry.file);
|
|
5005
5288
|
}
|
|
5006
|
-
const resultPath =
|
|
5289
|
+
const resultPath = path12.join(resultsDir, entry.file);
|
|
5007
5290
|
if (pendingState === "promoted" || existingResultFile(resultPath)) return { file: entry.file, path: resultPath, state: "public" };
|
|
5008
5291
|
return void 0;
|
|
5009
5292
|
}
|
|
5010
5293
|
function readResultIndexForSessionRun(resultsDir, sessionId, runId) {
|
|
5011
5294
|
for (const indexPath2 of resultIndexPaths(resultsDir, sessionId, runId)) {
|
|
5012
5295
|
try {
|
|
5013
|
-
const entry = parseResultIndexEntry(JSON.parse(
|
|
5296
|
+
const entry = parseResultIndexEntry(JSON.parse(fs11.readFileSync(indexPath2, "utf-8")));
|
|
5014
5297
|
if (!entry || entry.sessionId !== sessionId || entry.runId !== runId) continue;
|
|
5015
5298
|
return entry;
|
|
5016
5299
|
} catch (error) {
|
|
@@ -5029,7 +5312,7 @@ function resultPayloadPathForSessionRun(resultsDir, sessionId, runId) {
|
|
|
5029
5312
|
}
|
|
5030
5313
|
function resultPayloadPathForMissionObserverRun(resultsDir, runId) {
|
|
5031
5314
|
try {
|
|
5032
|
-
const entry = parseResultIndexEntry(JSON.parse(
|
|
5315
|
+
const entry = parseResultIndexEntry(JSON.parse(fs11.readFileSync(observerIndexPath(resultsDir, MISSION_OBSERVER, runId), "utf-8")));
|
|
5033
5316
|
if (!entry || entry.runId !== runId) return void 0;
|
|
5034
5317
|
return resultPayloadLocationFromIndex(resultsDir, entry)?.path;
|
|
5035
5318
|
} catch (error) {
|
|
@@ -5041,9 +5324,9 @@ function resultPayloadPathForMissionObserverRun(resultsDir, runId) {
|
|
|
5041
5324
|
function resultPayloadPathForIndexedRun(resultsDir, runId) {
|
|
5042
5325
|
const entryPath = runIndexPath(resultsDir, runId);
|
|
5043
5326
|
try {
|
|
5044
|
-
const entry = parseResultIndexEntry(JSON.parse(
|
|
5327
|
+
const entry = parseResultIndexEntry(JSON.parse(fs11.readFileSync(entryPath, "utf-8")));
|
|
5045
5328
|
if (!entry || entry.runId !== runId) {
|
|
5046
|
-
|
|
5329
|
+
fs11.rmSync(entryPath, { force: true });
|
|
5047
5330
|
return void 0;
|
|
5048
5331
|
}
|
|
5049
5332
|
return resultPayloadLocationFromIndex(resultsDir, entry)?.path;
|
|
@@ -5053,7 +5336,7 @@ function resultPayloadPathForIndexedRun(resultsDir, runId) {
|
|
|
5053
5336
|
if (code !== "ENOENT" && code !== "ENOTDIR") {
|
|
5054
5337
|
console.error(`Ignoring invalid async result run index '${entryPath}':`, error);
|
|
5055
5338
|
try {
|
|
5056
|
-
|
|
5339
|
+
fs11.rmSync(entryPath, { force: true });
|
|
5057
5340
|
} catch {
|
|
5058
5341
|
}
|
|
5059
5342
|
}
|
|
@@ -5068,7 +5351,7 @@ function indexedResultFile(resultsDir, entry, includePending = false) {
|
|
|
5068
5351
|
function listIndexFiles(dir) {
|
|
5069
5352
|
let files;
|
|
5070
5353
|
try {
|
|
5071
|
-
files =
|
|
5354
|
+
files = fs11.readdirSync(dir, { withFileTypes: true }).filter((entry) => entry.isFile() && entry.name.endsWith(".json")).map((entry) => path12.join(dir, entry.name));
|
|
5072
5355
|
} catch (error) {
|
|
5073
5356
|
const code = error.code;
|
|
5074
5357
|
if (code === "ENOENT" || code === "ENOTDIR" || code === "EPERM" || code === "EACCES" || isUnaddressableResultCandidate(error)) return [];
|
|
@@ -5080,9 +5363,9 @@ function resultFilesFromIndexDir(resultsDir, dir, includePending = false) {
|
|
|
5080
5363
|
const candidates = /* @__PURE__ */ new Set();
|
|
5081
5364
|
for (const entryPath of listIndexFiles(dir)) {
|
|
5082
5365
|
try {
|
|
5083
|
-
const entry = parseResultIndexEntry(JSON.parse(
|
|
5366
|
+
const entry = parseResultIndexEntry(JSON.parse(fs11.readFileSync(entryPath, "utf-8")));
|
|
5084
5367
|
if (!entry) {
|
|
5085
|
-
|
|
5368
|
+
fs11.rmSync(entryPath, { force: true });
|
|
5086
5369
|
continue;
|
|
5087
5370
|
}
|
|
5088
5371
|
const resultFile = indexedResultFile(resultsDir, entry, includePending);
|
|
@@ -5098,7 +5381,7 @@ function pendingResultFilesForSession(resultsDir, sessionId) {
|
|
|
5098
5381
|
for (const dir of pendingSessionDirs(resultsDir, sessionId)) {
|
|
5099
5382
|
let entries;
|
|
5100
5383
|
try {
|
|
5101
|
-
entries =
|
|
5384
|
+
entries = fs11.readdirSync(dir, { withFileTypes: true });
|
|
5102
5385
|
} catch (error) {
|
|
5103
5386
|
const code = error.code;
|
|
5104
5387
|
if (code === "ENOENT" || code === "ENOTDIR" || code === "EPERM" || code === "EACCES" || isUnaddressableResultCandidate(error)) continue;
|
|
@@ -5106,9 +5389,9 @@ function pendingResultFilesForSession(resultsDir, sessionId) {
|
|
|
5106
5389
|
}
|
|
5107
5390
|
for (const entry of entries) {
|
|
5108
5391
|
if (!entry.isFile() || !entry.name.endsWith(".json")) continue;
|
|
5109
|
-
const pendingPath =
|
|
5392
|
+
const pendingPath = path12.join(dir, entry.name);
|
|
5110
5393
|
try {
|
|
5111
|
-
const data = JSON.parse(
|
|
5394
|
+
const data = JSON.parse(fs11.readFileSync(pendingPath, "utf-8"));
|
|
5112
5395
|
const runId = nonEmptyString2(data.runId) ?? nonEmptyString2(data.id);
|
|
5113
5396
|
if (runId && nonEmptyString2(data.sessionId) === sessionId) files.add(resultFileName(runId));
|
|
5114
5397
|
} catch (error) {
|
|
@@ -5133,43 +5416,43 @@ function missionObserverResultCandidateFiles(resultsDir) {
|
|
|
5133
5416
|
return resultFilesFromIndexDir(resultsDir, observerIndexDir(resultsDir, MISSION_OBSERVER), true);
|
|
5134
5417
|
}
|
|
5135
5418
|
function cleanupResultIndexes(resultsDir, now = Date.now(), maxAgeMs = 24 * 60 * 60 * 1e3) {
|
|
5136
|
-
const root =
|
|
5419
|
+
const root = path12.join(resultsDir, RESULT_INDEX_DIR);
|
|
5137
5420
|
const cutoff = now - maxAgeMs;
|
|
5138
5421
|
let removed = 0;
|
|
5139
5422
|
const visit = (dir) => {
|
|
5140
5423
|
let entries;
|
|
5141
5424
|
try {
|
|
5142
|
-
entries =
|
|
5425
|
+
entries = fs11.readdirSync(dir, { withFileTypes: true });
|
|
5143
5426
|
} catch (error) {
|
|
5144
5427
|
const code = error.code;
|
|
5145
5428
|
if (code === "ENOENT" || code === "ENOTDIR" || code === "EPERM" || code === "EACCES" || isUnaddressableResultCandidate(error)) return;
|
|
5146
5429
|
throw error;
|
|
5147
5430
|
}
|
|
5148
5431
|
for (const entry of entries) {
|
|
5149
|
-
const fullPath =
|
|
5432
|
+
const fullPath = path12.join(dir, entry.name);
|
|
5150
5433
|
if (entry.isDirectory()) {
|
|
5151
5434
|
visit(fullPath);
|
|
5152
5435
|
try {
|
|
5153
|
-
|
|
5436
|
+
fs11.rmdirSync(fullPath);
|
|
5154
5437
|
} catch {
|
|
5155
5438
|
}
|
|
5156
5439
|
continue;
|
|
5157
5440
|
}
|
|
5158
5441
|
if (!entry.isFile() || !entry.name.endsWith(".json")) continue;
|
|
5159
5442
|
try {
|
|
5160
|
-
const stat =
|
|
5161
|
-
const index = parseResultIndexEntry(JSON.parse(
|
|
5443
|
+
const stat = fs11.statSync(fullPath);
|
|
5444
|
+
const index = parseResultIndexEntry(JSON.parse(fs11.readFileSync(fullPath, "utf-8")));
|
|
5162
5445
|
const resultFile = index ? indexedResultFile(resultsDir, index) : void 0;
|
|
5163
5446
|
const pendingFile = index ? pendingResultExists(resultsDir, index.sessionId, index.runId) : false;
|
|
5164
5447
|
if (!index || !resultFile && !pendingFile && stat.mtimeMs <= cutoff) {
|
|
5165
|
-
|
|
5448
|
+
fs11.rmSync(fullPath, { force: true });
|
|
5166
5449
|
removed += 1;
|
|
5167
5450
|
}
|
|
5168
5451
|
} catch (error) {
|
|
5169
5452
|
if (isUnaddressableResultCandidate(error)) continue;
|
|
5170
5453
|
if (error.code !== "ENOENT") console.error(`Ignoring invalid async result index '${fullPath}':`, error);
|
|
5171
5454
|
try {
|
|
5172
|
-
|
|
5455
|
+
fs11.rmSync(fullPath, { force: true });
|
|
5173
5456
|
removed += 1;
|
|
5174
5457
|
} catch {
|
|
5175
5458
|
}
|
|
@@ -5181,21 +5464,21 @@ function cleanupResultIndexes(resultsDir, now = Date.now(), maxAgeMs = 24 * 60 *
|
|
|
5181
5464
|
}
|
|
5182
5465
|
|
|
5183
5466
|
// src/shared/completion-owner.ts
|
|
5184
|
-
import { randomUUID as
|
|
5467
|
+
import { randomUUID as randomUUID5 } from "node:crypto";
|
|
5185
5468
|
var COMPLETION_OWNER_KEY = /* @__PURE__ */ Symbol.for("pi-subagents.completion-owner-id");
|
|
5186
5469
|
var OWNING_SESSION_COMPLETION_OWNER = "owning-session";
|
|
5187
5470
|
function currentCompletionOwnerId() {
|
|
5188
5471
|
const runtime2 = globalThis;
|
|
5189
|
-
runtime2[COMPLETION_OWNER_KEY] ??=
|
|
5472
|
+
runtime2[COMPLETION_OWNER_KEY] ??= randomUUID5();
|
|
5190
5473
|
return runtime2[COMPLETION_OWNER_KEY];
|
|
5191
5474
|
}
|
|
5192
5475
|
|
|
5193
5476
|
// src/runs/background/boot-id.ts
|
|
5194
5477
|
import { execFileSync as execFileSync2 } from "node:child_process";
|
|
5195
|
-
import * as
|
|
5478
|
+
import * as fs13 from "node:fs";
|
|
5196
5479
|
|
|
5197
5480
|
// src/runs/background/pid-namespace.ts
|
|
5198
|
-
import * as
|
|
5481
|
+
import * as fs12 from "node:fs";
|
|
5199
5482
|
var resolved = false;
|
|
5200
5483
|
var cachedScope;
|
|
5201
5484
|
function currentPidNamespaceScope() {
|
|
@@ -5203,7 +5486,7 @@ function currentPidNamespaceScope() {
|
|
|
5203
5486
|
resolved = true;
|
|
5204
5487
|
if (process.platform !== "linux") return void 0;
|
|
5205
5488
|
try {
|
|
5206
|
-
const scope =
|
|
5489
|
+
const scope = fs12.readlinkSync("/proc/self/ns/pid", "utf-8").trim();
|
|
5207
5490
|
cachedScope = scope || void 0;
|
|
5208
5491
|
} catch {
|
|
5209
5492
|
cachedScope = void 0;
|
|
@@ -5214,7 +5497,7 @@ function currentPidNamespaceScope() {
|
|
|
5214
5497
|
// src/runs/background/boot-id.ts
|
|
5215
5498
|
function readBootIdFromOs() {
|
|
5216
5499
|
try {
|
|
5217
|
-
if (process.platform === "linux") return
|
|
5500
|
+
if (process.platform === "linux") return fs13.readFileSync("/proc/sys/kernel/random/boot_id", "utf-8").trim() || void 0;
|
|
5218
5501
|
if (process.platform === "darwin") {
|
|
5219
5502
|
return execFileSync2("sysctl", ["-n", "kern.bootsessionuuid"], { encoding: "utf-8", timeout: 1e3, stdio: ["ignore", "pipe", "ignore"] }).trim() || void 0;
|
|
5220
5503
|
}
|
|
@@ -5239,8 +5522,8 @@ function currentRecordedPid() {
|
|
|
5239
5522
|
}
|
|
5240
5523
|
|
|
5241
5524
|
// src/runs/background/stale-run-reconciler.ts
|
|
5242
|
-
import * as
|
|
5243
|
-
import * as
|
|
5525
|
+
import * as fs15 from "node:fs";
|
|
5526
|
+
import * as path14 from "node:path";
|
|
5244
5527
|
|
|
5245
5528
|
// src/runs/background/parallel-groups.ts
|
|
5246
5529
|
function isValidParallelGroup(group, stepCount, chainStepCount) {
|
|
@@ -5281,16 +5564,16 @@ function isReusableWorkflowStopCause(cause) {
|
|
|
5281
5564
|
}
|
|
5282
5565
|
|
|
5283
5566
|
// src/runs/background/workflow-terminal-proof.ts
|
|
5284
|
-
import * as
|
|
5285
|
-
import * as
|
|
5567
|
+
import * as fs14 from "node:fs";
|
|
5568
|
+
import * as path13 from "node:path";
|
|
5286
5569
|
var TERMINAL_WORKFLOW_STATES = /* @__PURE__ */ new Set(["completed", "failed", "stopped"]);
|
|
5287
5570
|
function isTerminalAsyncState(state) {
|
|
5288
5571
|
return state !== "queued" && state !== "running" && state !== "paused";
|
|
5289
5572
|
}
|
|
5290
5573
|
function readWorkflowChildRunModel(workflowAsyncDir, step) {
|
|
5291
|
-
if (step.async !== true || typeof step.runId !== "string" ||
|
|
5574
|
+
if (step.async !== true || typeof step.runId !== "string" || path13.basename(step.runId) !== step.runId) return void 0;
|
|
5292
5575
|
try {
|
|
5293
|
-
const child = readStatus(
|
|
5576
|
+
const child = readStatus(path13.join(path13.dirname(workflowAsyncDir), step.runId));
|
|
5294
5577
|
const first = Array.isArray(child?.steps) ? child.steps[0] : void 0;
|
|
5295
5578
|
const model = typeof first?.model === "string" && first.model ? first.model : void 0;
|
|
5296
5579
|
const thinking = typeof first?.thinking === "string" && first.thinking ? first.thinking : void 0;
|
|
@@ -5319,15 +5602,15 @@ function readWorkflowChildProcessEvidence(workflowAsyncDir, steps) {
|
|
|
5319
5602
|
}
|
|
5320
5603
|
function launchFailedBeforeRunner(step, childDir) {
|
|
5321
5604
|
if (step.status !== "failed" || !step.error) return false;
|
|
5322
|
-
return !childDir || !["process-terminal.json", "runner-startup.json"].some((file) =>
|
|
5605
|
+
return !childDir || !["process-terminal.json", "runner-startup.json"].some((file) => fs14.existsSync(path13.join(childDir, file)));
|
|
5323
5606
|
}
|
|
5324
5607
|
function readWorkflowChildEvidence(workflowAsyncDir, step) {
|
|
5325
5608
|
const label = step.workflowKey ?? step.agent;
|
|
5326
5609
|
if (typeof step.async !== "boolean") return { state: "unknown", reason: `workflow child ${label} is missing async classification` };
|
|
5327
5610
|
if (!step.async) return void 0;
|
|
5328
|
-
if (!step.runId ||
|
|
5329
|
-
const childDir =
|
|
5330
|
-
if (!
|
|
5611
|
+
if (!step.runId || path13.basename(step.runId) !== step.runId) return { state: "unknown", reason: `async workflow child ${label} is missing run id` };
|
|
5612
|
+
const childDir = path13.join(path13.dirname(workflowAsyncDir), step.runId);
|
|
5613
|
+
if (!fs14.existsSync(childDir)) return launchFailedBeforeRunner(step) ? void 0 : { state: "unknown", reason: `async workflow child ${label} directory is missing` };
|
|
5331
5614
|
const childStatus = readStatus(childDir);
|
|
5332
5615
|
if (!childStatus) return launchFailedBeforeRunner(step, childDir) ? void 0 : { state: "unknown", reason: `async workflow child ${label} status is missing or unreadable` };
|
|
5333
5616
|
if (!isTerminalAsyncState(childStatus.state)) return { state: "pending", reason: `async workflow child ${label} is still ${childStatus.state}` };
|
|
@@ -5370,21 +5653,21 @@ function getErrorMessage(error) {
|
|
|
5370
5653
|
return error instanceof Error ? error.message : String(error);
|
|
5371
5654
|
}
|
|
5372
5655
|
function readRunnerStartupDiagnostics(asyncDir) {
|
|
5373
|
-
const stderrPath =
|
|
5656
|
+
const stderrPath = path14.join(asyncDir, "runner.stderr.log");
|
|
5374
5657
|
const maxBytes = 64 * 1024;
|
|
5375
5658
|
let content;
|
|
5376
5659
|
try {
|
|
5377
|
-
const stat =
|
|
5660
|
+
const stat = fs15.statSync(stderrPath);
|
|
5378
5661
|
if (stat.size <= 0) return void 0;
|
|
5379
|
-
const fd =
|
|
5662
|
+
const fd = fs15.openSync(stderrPath, "r");
|
|
5380
5663
|
try {
|
|
5381
5664
|
const bytesToRead = Math.min(stat.size, maxBytes);
|
|
5382
5665
|
const start = Math.max(0, stat.size - bytesToRead);
|
|
5383
5666
|
const buffer = Buffer.alloc(bytesToRead);
|
|
5384
|
-
|
|
5667
|
+
fs15.readSync(fd, buffer, 0, bytesToRead, start);
|
|
5385
5668
|
content = buffer.toString("utf-8").trim();
|
|
5386
5669
|
} finally {
|
|
5387
|
-
|
|
5670
|
+
fs15.closeSync(fd);
|
|
5388
5671
|
}
|
|
5389
5672
|
} catch {
|
|
5390
5673
|
return void 0;
|
|
@@ -5399,15 +5682,15 @@ function isNotFoundError(error) {
|
|
|
5399
5682
|
}
|
|
5400
5683
|
function appendJsonlBestEffort(filePath, payload) {
|
|
5401
5684
|
try {
|
|
5402
|
-
|
|
5403
|
-
|
|
5685
|
+
fs15.mkdirSync(path14.dirname(filePath), { recursive: true });
|
|
5686
|
+
fs15.appendFileSync(filePath, `${JSON.stringify(payload)}
|
|
5404
5687
|
`, "utf-8");
|
|
5405
5688
|
} catch {
|
|
5406
5689
|
}
|
|
5407
5690
|
}
|
|
5408
5691
|
function regularFileExists(filePath) {
|
|
5409
5692
|
try {
|
|
5410
|
-
return
|
|
5693
|
+
return fs15.statSync(filePath).isFile();
|
|
5411
5694
|
} catch (error) {
|
|
5412
5695
|
if (isNotFoundError(error)) return false;
|
|
5413
5696
|
throw error;
|
|
@@ -5415,7 +5698,7 @@ function regularFileExists(filePath) {
|
|
|
5415
5698
|
}
|
|
5416
5699
|
function readResultRepairData(resultPath) {
|
|
5417
5700
|
try {
|
|
5418
|
-
const data = JSON.parse(
|
|
5701
|
+
const data = JSON.parse(fs15.readFileSync(resultPath, "utf-8"));
|
|
5419
5702
|
if (data.error !== void 0 && typeof data.error !== "string") throw new Error(`Invalid async result file '${resultPath}': error must be a string.`);
|
|
5420
5703
|
const state = data.success ? "complete" : data.state === "stopped" ? "stopped" : data.state === "rejected" ? "rejected" : data.state === "partial" ? "partial" : data.state === "paused" || data.exitCode === 0 ? "paused" : "failed";
|
|
5421
5704
|
const results = Array.isArray(data.results) ? data.results.map((entry, index) => {
|
|
@@ -5489,7 +5772,7 @@ function buildStartedStatus(asyncDir, startedRun, now) {
|
|
|
5489
5772
|
const chainStepCount = startedRun.chainStepCount;
|
|
5490
5773
|
const parallelGroups = chainStepCount !== void 0 ? normalizeParallelGroups(startedRun.parallelGroups, agents.length, chainStepCount) : [];
|
|
5491
5774
|
return {
|
|
5492
|
-
runId: startedRun.runId ||
|
|
5775
|
+
runId: startedRun.runId || path14.basename(asyncDir),
|
|
5493
5776
|
...startedRun.sessionId ? { sessionId: startedRun.sessionId } : {},
|
|
5494
5777
|
...startedRun.completionOwnerId ? { completionOwnerId: startedRun.completionOwnerId } : {},
|
|
5495
5778
|
mode: startedRun.mode ?? "single",
|
|
@@ -5511,8 +5794,8 @@ function buildStartedStatus(asyncDir, startedRun, now) {
|
|
|
5511
5794
|
}
|
|
5512
5795
|
function settledWorkflowChildStatus(asyncDir, workflowRunId, step, now) {
|
|
5513
5796
|
const childRunId = step.runId;
|
|
5514
|
-
if (step.async !== true || step.parentWorkflowRunId !== workflowRunId || !childRunId || childRunId === workflowRunId || childRunId !==
|
|
5515
|
-
const child = readStatus(
|
|
5797
|
+
if (step.async !== true || step.parentWorkflowRunId !== workflowRunId || !childRunId || childRunId === workflowRunId || childRunId !== path14.basename(childRunId) || childRunId === "." || childRunId === "..") return void 0;
|
|
5798
|
+
const child = readStatus(path14.join(path14.dirname(asyncDir), childRunId));
|
|
5516
5799
|
if (!child || child.runId !== childRunId || child.parentWorkflowRunId !== workflowRunId || !isTerminalAsyncState(child.state)) return void 0;
|
|
5517
5800
|
if (step.workflowKey !== void 0 && child.workflowKey !== step.workflowKey) return void 0;
|
|
5518
5801
|
const state = child.state;
|
|
@@ -5533,7 +5816,7 @@ function settledWorkflowChildStatus(asyncDir, workflowRunId, step, now) {
|
|
|
5533
5816
|
return settled;
|
|
5534
5817
|
}
|
|
5535
5818
|
function buildFailedRepair(status, asyncDir, now, reason, ownerExited = false, adoptCompletionOwnerId) {
|
|
5536
|
-
const runId = status.runId ||
|
|
5819
|
+
const runId = status.runId || path14.basename(asyncDir);
|
|
5537
5820
|
const pid = typeof status.pid === "number" ? status.pid : "unknown";
|
|
5538
5821
|
const exitedWorkflow = ownerExited && status.mode === "workflow" ? status.workflow : void 0;
|
|
5539
5822
|
const completionOwnerId = exitedWorkflow ? adoptCompletionOwnerId || OWNING_SESSION_COMPLETION_OWNER : status.completionOwnerId;
|
|
@@ -5620,9 +5903,9 @@ ${diagnostics}` : baseMessage;
|
|
|
5620
5903
|
function writeFailedRepair(asyncDir, status, resultPath, now, reason, ownerExited = false, adoptCompletionOwnerId) {
|
|
5621
5904
|
const repair = buildFailedRepair(status, asyncDir, now, reason, ownerExited, adoptCompletionOwnerId);
|
|
5622
5905
|
if (repair.result.sessionId) writeAsyncResultFile(resultPath, repair.result);
|
|
5623
|
-
writeAtomicJson(
|
|
5906
|
+
writeAtomicJson(path14.join(asyncDir, "status.json"), repair.status);
|
|
5624
5907
|
updateActiveRunIndex(asyncDir, repair.status.state, repair.status.toolCallId);
|
|
5625
|
-
appendJsonlBestEffort(
|
|
5908
|
+
appendJsonlBestEffort(path14.join(asyncDir, "events.jsonl"), {
|
|
5626
5909
|
type: "subagent.run.repaired_stale",
|
|
5627
5910
|
ts: now,
|
|
5628
5911
|
runId: repair.status.runId,
|
|
@@ -5650,7 +5933,7 @@ function reconcileNestedAsyncDescendants(route, options = {}) {
|
|
|
5650
5933
|
if (!asyncDir) continue;
|
|
5651
5934
|
const result = reconcileAsyncRun(asyncDir, {
|
|
5652
5935
|
...options,
|
|
5653
|
-
resultsDir:
|
|
5936
|
+
resultsDir: path14.join(options.resultsDir ?? DIRS.results, "nested", route.rootRunId)
|
|
5654
5937
|
});
|
|
5655
5938
|
const status = result.status;
|
|
5656
5939
|
if (!status) continue;
|
|
@@ -5678,7 +5961,7 @@ function checkPidLiveness(pid, kill = process.kill, probeZombie = false) {
|
|
|
5678
5961
|
kill(pid, 0);
|
|
5679
5962
|
if (probeZombie && process.platform === "linux") {
|
|
5680
5963
|
try {
|
|
5681
|
-
const stat =
|
|
5964
|
+
const stat = fs15.readFileSync(`/proc/${pid}/stat`, "utf-8");
|
|
5682
5965
|
const closeParen = stat.lastIndexOf(") ");
|
|
5683
5966
|
if (closeParen >= 0 && stat[closeParen + 2] === "Z") return "dead";
|
|
5684
5967
|
} catch {
|
|
@@ -5712,14 +5995,14 @@ function reconcileAsyncRun(asyncDir, options = {}, observeStatus) {
|
|
|
5712
5995
|
const startedStatus = !status && options.startedRun ? buildStartedStatus(asyncDir, options.startedRun, now) : void 0;
|
|
5713
5996
|
const effectiveStatus = status ?? startedStatus;
|
|
5714
5997
|
if (!effectiveStatus) return { status: null, repaired: false };
|
|
5715
|
-
assertWorkflowGraphHostSteps(effectiveStatus.workflowGraph,
|
|
5716
|
-
const statusPath =
|
|
5998
|
+
assertWorkflowGraphHostSteps(effectiveStatus.workflowGraph, path14.join(asyncDir, "status.json"), effectiveStatus.runId);
|
|
5999
|
+
const statusPath = path14.join(asyncDir, "status.json");
|
|
5717
6000
|
for (const [index, step] of (effectiveStatus.steps ?? []).entries()) {
|
|
5718
6001
|
const stepRecord = step;
|
|
5719
6002
|
if (stepRecord.model !== void 0 && typeof stepRecord.model !== "string") throw new Error(`Invalid async status file '${statusPath}': steps[${index}].model must be a string.`);
|
|
5720
6003
|
if (stepRecord.thinking !== void 0 && typeof stepRecord.thinking !== "string") throw new Error(`Invalid async status file '${statusPath}': steps[${index}].thinking must be a string.`);
|
|
5721
6004
|
}
|
|
5722
|
-
const runId = effectiveStatus.runId ||
|
|
6005
|
+
const runId = effectiveStatus.runId || path14.basename(asyncDir);
|
|
5723
6006
|
const resultsDir = options.resultsDir ?? DIRS.results;
|
|
5724
6007
|
const resultPath = resultFilePath(resultsDir, runId);
|
|
5725
6008
|
const existingResultPath = effectiveStatus.sessionId ? resultPayloadPathForSessionRun(resultsDir, effectiveStatus.sessionId, runId) ?? (regularFileExists(resultPath) ? resultPath : void 0) : regularFileExists(resultPath) ? resultPath : void 0;
|
|
@@ -5816,19 +6099,19 @@ function validateAuthorityPolicy(value, label = "config.authorityPolicy") {
|
|
|
5816
6099
|
}
|
|
5817
6100
|
|
|
5818
6101
|
// src/runs/shared/worktree.ts
|
|
5819
|
-
import { createHash as
|
|
6102
|
+
import { createHash as createHash5 } from "node:crypto";
|
|
5820
6103
|
import { spawnSync } from "node:child_process";
|
|
5821
6104
|
|
|
5822
6105
|
// src/runs/shared/worktree-setup-command.ts
|
|
5823
6106
|
import { spawn as spawn2 } from "node:child_process";
|
|
5824
6107
|
function terminateCommandTree(pid, controller) {
|
|
5825
6108
|
if (process.platform !== "win32") return controller.terminate();
|
|
5826
|
-
return new Promise((
|
|
6109
|
+
return new Promise((resolve5) => {
|
|
5827
6110
|
let settled = false;
|
|
5828
6111
|
const fallback = () => {
|
|
5829
6112
|
if (settled) return;
|
|
5830
6113
|
settled = true;
|
|
5831
|
-
void controller.terminate().then(
|
|
6114
|
+
void controller.terminate().then(resolve5);
|
|
5832
6115
|
};
|
|
5833
6116
|
const cleanup = spawn2("taskkill", ["/PID", String(pid), "/T", "/F"], { stdio: "ignore", windowsHide: true });
|
|
5834
6117
|
cleanup.once("error", fallback);
|
|
@@ -5836,7 +6119,7 @@ function terminateCommandTree(pid, controller) {
|
|
|
5836
6119
|
if (settled) return;
|
|
5837
6120
|
if (status !== 0) return fallback();
|
|
5838
6121
|
settled = true;
|
|
5839
|
-
|
|
6122
|
+
resolve5({ state: "observed", mechanism: "windows-taskkill", pid, verifiedAt: Date.now() });
|
|
5840
6123
|
});
|
|
5841
6124
|
});
|
|
5842
6125
|
}
|
|
@@ -5938,21 +6221,21 @@ async function runSetupCommand(command, args, options) {
|
|
|
5938
6221
|
child.stdout.on("data", onStdout);
|
|
5939
6222
|
child.stderr.on("data", onStderr);
|
|
5940
6223
|
child.stdin.on("error", fail);
|
|
5941
|
-
const close = new Promise((
|
|
5942
|
-
const directExit = new Promise((
|
|
6224
|
+
const close = new Promise((resolve5) => child.once("close", () => resolve5()));
|
|
6225
|
+
const directExit = new Promise((resolve5) => {
|
|
5943
6226
|
child.once("exit", (status, signal) => {
|
|
5944
6227
|
directSettled = true;
|
|
5945
6228
|
result.status = status;
|
|
5946
6229
|
result.signal = signal;
|
|
5947
6230
|
if (status === null || !(options.acceptedExitCodes ?? [0]).includes(status)) terminate();
|
|
5948
6231
|
releaseUnknownIO();
|
|
5949
|
-
|
|
6232
|
+
resolve5();
|
|
5950
6233
|
});
|
|
5951
6234
|
child.once("error", (error) => {
|
|
5952
6235
|
fail(error);
|
|
5953
6236
|
if (child.pid === void 0) {
|
|
5954
6237
|
directSettled = true;
|
|
5955
|
-
|
|
6238
|
+
resolve5();
|
|
5956
6239
|
}
|
|
5957
6240
|
});
|
|
5958
6241
|
});
|
|
@@ -6000,13 +6283,13 @@ async function runSetupCommand(command, args, options) {
|
|
|
6000
6283
|
}
|
|
6001
6284
|
|
|
6002
6285
|
// src/runs/shared/worktree.ts
|
|
6003
|
-
import * as
|
|
6286
|
+
import * as fs16 from "node:fs";
|
|
6004
6287
|
import * as os2 from "node:os";
|
|
6005
|
-
import * as
|
|
6288
|
+
import * as path15 from "node:path";
|
|
6006
6289
|
var DEFAULT_WORKTREE_PROVIDER = "auto";
|
|
6007
6290
|
var DEFAULT_WORKTREE_BASE_REF = "HEAD";
|
|
6008
6291
|
var DEFAULT_WORKTREE_BRANCH_PREFIX = "pi-subagents/";
|
|
6009
|
-
var WORKTREE_AGENT_CWD_PLACEHOLDER =
|
|
6292
|
+
var WORKTREE_AGENT_CWD_PLACEHOLDER = path15.join(path15.parse(process.cwd()).root, "__pi_subagents_worktree_cwd__");
|
|
6010
6293
|
var WORKTREE_NAMING_COMPONENT_MAX_BYTES = 96;
|
|
6011
6294
|
var WORKTREE_NAMING_LABEL_MAX_BYTES = 256;
|
|
6012
6295
|
var WORKTREE_NAMING_BRANCH_MAX_BYTES = 256;
|
|
@@ -6035,8 +6318,8 @@ function assertWorktreeMutationAllowed() {
|
|
|
6035
6318
|
async function withWorktreeTransaction(action) {
|
|
6036
6319
|
const previous = worktreeTurn;
|
|
6037
6320
|
let release;
|
|
6038
|
-
worktreeTurn = new Promise((
|
|
6039
|
-
release =
|
|
6321
|
+
worktreeTurn = new Promise((resolve5) => {
|
|
6322
|
+
release = resolve5;
|
|
6040
6323
|
});
|
|
6041
6324
|
await previous;
|
|
6042
6325
|
try {
|
|
@@ -6128,6 +6411,23 @@ function runGitChecked(cwd, args) {
|
|
|
6128
6411
|
}
|
|
6129
6412
|
return result.stdout;
|
|
6130
6413
|
}
|
|
6414
|
+
function findListedWorktreeOnBranch(repoCwd, branch) {
|
|
6415
|
+
let current;
|
|
6416
|
+
for (const line of runGitChecked(repoCwd, ["worktree", "list", "--porcelain"]).split("\n")) {
|
|
6417
|
+
if (line.startsWith("worktree ")) current = line.slice("worktree ".length);
|
|
6418
|
+
else if (line === `branch refs/heads/${branch}` && current) return normalizeComparableCwd(current);
|
|
6419
|
+
}
|
|
6420
|
+
return void 0;
|
|
6421
|
+
}
|
|
6422
|
+
function findListedWorktreeAgentCwd(repoCwd, branch) {
|
|
6423
|
+
const worktree = findListedWorktreeOnBranch(repoCwd, branch);
|
|
6424
|
+
if (!worktree) return void 0;
|
|
6425
|
+
const cwdRelative = resolveRepoCwdRelative(repoCwd);
|
|
6426
|
+
return cwdRelative ? path15.join(worktree, cwdRelative) : worktree;
|
|
6427
|
+
}
|
|
6428
|
+
function isComparablePathInside(parent, child) {
|
|
6429
|
+
return isPathInside(normalizeComparableCwd(parent), normalizeComparableCwd(child));
|
|
6430
|
+
}
|
|
6131
6431
|
function validateWorktreePatch(worktreePath, patchPath) {
|
|
6132
6432
|
const result = runGit(worktreePath, [...PATCH_VALIDATION_OPTIONS, patchPath]);
|
|
6133
6433
|
if (result.status === 0) return void 0;
|
|
@@ -6137,11 +6437,11 @@ function currentWorktreePatch(worktreePath, baseCommit) {
|
|
|
6137
6437
|
assertWorktreeMutationAllowed();
|
|
6138
6438
|
let tempDir;
|
|
6139
6439
|
try {
|
|
6140
|
-
tempDir =
|
|
6440
|
+
tempDir = fs16.mkdtempSync(path15.join(os2.tmpdir(), "pi-worktree-index-"));
|
|
6141
6441
|
} catch (error) {
|
|
6142
6442
|
return { error: error instanceof Error ? error.message : String(error) };
|
|
6143
6443
|
}
|
|
6144
|
-
const env = { GIT_INDEX_FILE:
|
|
6444
|
+
const env = { GIT_INDEX_FILE: path15.join(tempDir, "index") };
|
|
6145
6445
|
try {
|
|
6146
6446
|
const readTree = runGit(worktreePath, ["read-tree", "HEAD"], env);
|
|
6147
6447
|
if (readTree.status !== 0) return { error: readTree.stderr.trim() || readTree.stdout.trim() || "git read-tree failed" };
|
|
@@ -6152,7 +6452,7 @@ function currentWorktreePatch(worktreePath, baseCommit) {
|
|
|
6152
6452
|
return { patch: diff.stdout };
|
|
6153
6453
|
} finally {
|
|
6154
6454
|
try {
|
|
6155
|
-
|
|
6455
|
+
fs16.rmSync(tempDir, { recursive: true, force: true });
|
|
6156
6456
|
} catch {
|
|
6157
6457
|
}
|
|
6158
6458
|
}
|
|
@@ -6162,7 +6462,7 @@ function validateWorktreePatchRepresentsCurrentWorktree(worktreePath, baseCommit
|
|
|
6162
6462
|
if (validationError) return validationError;
|
|
6163
6463
|
let capturedPatch;
|
|
6164
6464
|
try {
|
|
6165
|
-
capturedPatch =
|
|
6465
|
+
capturedPatch = fs16.readFileSync(patchPath, "utf-8");
|
|
6166
6466
|
} catch (error) {
|
|
6167
6467
|
return error instanceof Error ? error.message : String(error);
|
|
6168
6468
|
}
|
|
@@ -6195,7 +6495,7 @@ async function preflightWorktreeSource(cwd, options = {}) {
|
|
|
6195
6495
|
async function resolveRepoState(tx, cwd, requestedBaseRef) {
|
|
6196
6496
|
const toplevel = await probeWorktreeSource(tx, cwd);
|
|
6197
6497
|
const rawPrefix = (await tx.gitChecked(cwd, ["rev-parse", "--show-prefix"])).trim();
|
|
6198
|
-
const cwdRelative = rawPrefix ?
|
|
6498
|
+
const cwdRelative = rawPrefix ? path15.normalize(rawPrefix.replace(/[\\/]+$/, "")) : "";
|
|
6199
6499
|
const baseRef = normalizeWorktreeBaseRef(requestedBaseRef) ?? DEFAULT_WORKTREE_BASE_REF;
|
|
6200
6500
|
let baseCommit;
|
|
6201
6501
|
try {
|
|
@@ -6209,22 +6509,22 @@ async function resolveRepoState(tx, cwd, requestedBaseRef) {
|
|
|
6209
6509
|
return { toplevel, cwdRelative, baseCommit };
|
|
6210
6510
|
}
|
|
6211
6511
|
function normalizeComparableCwd(cwd) {
|
|
6212
|
-
const resolved2 =
|
|
6512
|
+
const resolved2 = path15.resolve(cwd);
|
|
6213
6513
|
let existing = resolved2;
|
|
6214
6514
|
const missingSegments = [];
|
|
6215
6515
|
while (true) {
|
|
6216
6516
|
try {
|
|
6217
6517
|
let realpath;
|
|
6218
6518
|
try {
|
|
6219
|
-
realpath =
|
|
6519
|
+
realpath = fs16.realpathSync.native(existing);
|
|
6220
6520
|
} catch {
|
|
6221
|
-
realpath =
|
|
6521
|
+
realpath = fs16.realpathSync(existing);
|
|
6222
6522
|
}
|
|
6223
|
-
return
|
|
6523
|
+
return path15.join(realpath, ...missingSegments.reverse());
|
|
6224
6524
|
} catch {
|
|
6225
|
-
const parent =
|
|
6525
|
+
const parent = path15.dirname(existing);
|
|
6226
6526
|
if (parent === existing) return resolved2;
|
|
6227
|
-
missingSegments.push(
|
|
6527
|
+
missingSegments.push(path15.basename(existing));
|
|
6228
6528
|
existing = parent;
|
|
6229
6529
|
}
|
|
6230
6530
|
}
|
|
@@ -6233,7 +6533,7 @@ function safePatchAgentName(agent) {
|
|
|
6233
6533
|
return agent.replace(/[^\w.-]/g, "_");
|
|
6234
6534
|
}
|
|
6235
6535
|
function shortWorktreeHash(value) {
|
|
6236
|
-
return
|
|
6536
|
+
return createHash5("sha256").update(value, "utf-8").digest("hex").slice(0, 8);
|
|
6237
6537
|
}
|
|
6238
6538
|
function truncateUtf8(value, maxBytes) {
|
|
6239
6539
|
const bytes = Buffer.from(value, "utf-8");
|
|
@@ -6318,7 +6618,7 @@ function hasConfiguredWorktreeBaseDir(baseDir) {
|
|
|
6318
6618
|
return baseDir !== void 0 ? true : (process.env.PI_SUBAGENTS_WORKTREE_DIR?.trim().length ?? 0) > 0;
|
|
6319
6619
|
}
|
|
6320
6620
|
function isInsidePiExtensionsDirectory(targetPath) {
|
|
6321
|
-
const extensionsDir = normalizeComparableCwd(
|
|
6621
|
+
const extensionsDir = normalizeComparableCwd(path15.join(getAgentDir(), "extensions"));
|
|
6322
6622
|
return isPathInside(extensionsDir, normalizeComparableCwd(targetPath));
|
|
6323
6623
|
}
|
|
6324
6624
|
function runWorktrunk(args, cwd) {
|
|
@@ -6400,49 +6700,49 @@ function resolveWorktreeDedicatedRoot(configuredBaseDir, repoRoot, relocateExten
|
|
|
6400
6700
|
const rawBaseDir = configuredBaseDir ?? process.env.PI_SUBAGENTS_WORKTREE_DIR;
|
|
6401
6701
|
let expanded;
|
|
6402
6702
|
if (rawBaseDir === void 0 || configuredBaseDir === void 0 && !rawBaseDir.trim()) {
|
|
6403
|
-
expanded = relocateExtensionRepo && isInsidePiExtensionsDirectory(repoRoot) ?
|
|
6703
|
+
expanded = relocateExtensionRepo && isInsidePiExtensionsDirectory(repoRoot) ? path15.join(getAgentDir(), "worktrees") : path15.join(path15.dirname(repoRoot), "worktrees");
|
|
6404
6704
|
} else {
|
|
6405
6705
|
const trimmed = rawBaseDir.trim();
|
|
6406
6706
|
if (!trimmed) throw new Error("worktree base directory cannot be empty");
|
|
6407
|
-
const candidate = trimmed.startsWith("~/") ?
|
|
6408
|
-
expanded =
|
|
6707
|
+
const candidate = trimmed.startsWith("~/") ? path15.join(os2.homedir(), trimmed.slice(2)) : trimmed;
|
|
6708
|
+
expanded = path15.isAbsolute(candidate) ? candidate : path15.resolve(repoRoot, candidate);
|
|
6409
6709
|
}
|
|
6410
|
-
const extensionsDir = normalizeComparableCwd(
|
|
6710
|
+
const extensionsDir = normalizeComparableCwd(path15.join(getAgentDir(), "extensions"));
|
|
6411
6711
|
if (isPathInside(extensionsDir, normalizeComparableCwd(expanded))) {
|
|
6412
6712
|
throw new Error(`worktree base directory cannot be inside Pi extensions directory: ${extensionsDir}. Choose a directory outside it.`);
|
|
6413
6713
|
}
|
|
6414
6714
|
return expanded;
|
|
6415
6715
|
}
|
|
6416
6716
|
function buildNativeProjectPath(dedicatedRoot, repoRoot) {
|
|
6417
|
-
return
|
|
6717
|
+
return path15.join(dedicatedRoot, path15.basename(repoRoot));
|
|
6418
6718
|
}
|
|
6419
6719
|
function ensureProjectWorktreeDir(dedicatedRoot, repoRoot) {
|
|
6420
6720
|
try {
|
|
6421
|
-
|
|
6721
|
+
fs16.mkdirSync(buildNativeProjectPath(dedicatedRoot, repoRoot), { recursive: true });
|
|
6422
6722
|
} catch (error) {
|
|
6423
6723
|
const message = error instanceof Error ? error.message : String(error);
|
|
6424
6724
|
throw new Error(`failed to create worktree base directory ${dedicatedRoot}: ${message}`);
|
|
6425
6725
|
}
|
|
6426
6726
|
}
|
|
6427
6727
|
function buildNativeWorktreePath(dedicatedRoot, repoRoot, runId, index) {
|
|
6428
|
-
return
|
|
6728
|
+
return path15.join(buildNativeProjectPath(dedicatedRoot, repoRoot), `pi-worktree-${sanitizeWorktreePathComponent(runId, 120)}-${index}`);
|
|
6429
6729
|
}
|
|
6430
6730
|
function isPathInside(parent, child) {
|
|
6431
|
-
const relative4 =
|
|
6731
|
+
const relative4 = path15.relative(parent, child);
|
|
6432
6732
|
if (!relative4 || relative4 === ".") return true;
|
|
6433
|
-
return relative4 !== ".." && !relative4.startsWith(`..${
|
|
6733
|
+
return relative4 !== ".." && !relative4.startsWith(`..${path15.sep}`) && !path15.isAbsolute(relative4);
|
|
6434
6734
|
}
|
|
6435
6735
|
function isStrictChildPath(parent, child) {
|
|
6436
|
-
const relative4 =
|
|
6437
|
-
return Boolean(relative4) && relative4 !== "." && relative4 !== ".." && !relative4.startsWith(`..${
|
|
6736
|
+
const relative4 = path15.relative(parent, child);
|
|
6737
|
+
return Boolean(relative4) && relative4 !== "." && relative4 !== ".." && !relative4.startsWith(`..${path15.sep}`) && !path15.isAbsolute(relative4);
|
|
6438
6738
|
}
|
|
6439
6739
|
function assertSafeWorktreeLocation(worktreePath, repoRoot, dedicatedRoot) {
|
|
6440
6740
|
const resolvedLeaf = normalizeComparableCwd(worktreePath);
|
|
6441
6741
|
const resolvedRepoRoot = normalizeComparableCwd(repoRoot);
|
|
6442
6742
|
const projectDir = normalizeComparableCwd(buildNativeProjectPath(dedicatedRoot, repoRoot));
|
|
6443
|
-
const repoParent = normalizeComparableCwd(
|
|
6444
|
-
const leafParent = normalizeComparableCwd(
|
|
6445
|
-
const extensionsDir = normalizeComparableCwd(
|
|
6743
|
+
const repoParent = normalizeComparableCwd(path15.dirname(resolvedRepoRoot));
|
|
6744
|
+
const leafParent = normalizeComparableCwd(path15.dirname(resolvedLeaf));
|
|
6745
|
+
const extensionsDir = normalizeComparableCwd(path15.join(getAgentDir(), "extensions"));
|
|
6446
6746
|
if (isPathInside(extensionsDir, projectDir) || isPathInside(extensionsDir, resolvedLeaf)) {
|
|
6447
6747
|
throw new Error(`worktree path cannot be inside Pi extensions directory: ${extensionsDir}. Choose a directory outside it.`);
|
|
6448
6748
|
}
|
|
@@ -6462,7 +6762,7 @@ function resolveRepoCwdRelative(cwd) {
|
|
|
6462
6762
|
throw new Error("worktree isolation requires a git repository");
|
|
6463
6763
|
}
|
|
6464
6764
|
const rawPrefix = runGitChecked(cwd, ["rev-parse", "--show-prefix"]).trim();
|
|
6465
|
-
const normalizedPrefix = rawPrefix ?
|
|
6765
|
+
const normalizedPrefix = rawPrefix ? path15.normalize(rawPrefix.replace(/[\\/]+$/, "")) : "";
|
|
6466
6766
|
return normalizedPrefix === "." ? "" : normalizedPrefix;
|
|
6467
6767
|
}
|
|
6468
6768
|
function resolveExpectedWorktreeAgentCwd(cwd, runId, index, baseDir) {
|
|
@@ -6471,14 +6771,14 @@ function resolveExpectedWorktreeAgentCwd(cwd, runId, index, baseDir) {
|
|
|
6471
6771
|
const dedicatedRoot = resolveWorktreeDedicatedRoot(baseDir, repoRoot);
|
|
6472
6772
|
const worktreePath = buildNativeWorktreePath(dedicatedRoot, repoRoot, runId, index);
|
|
6473
6773
|
assertSafeWorktreeLocation(worktreePath, repoRoot, dedicatedRoot);
|
|
6474
|
-
return cwdRelative ?
|
|
6774
|
+
return cwdRelative ? path15.join(worktreePath, cwdRelative) : worktreePath;
|
|
6475
6775
|
}
|
|
6476
6776
|
function linkNodeModulesIfPresent(toplevel, worktreePath) {
|
|
6477
|
-
const nodeModulesPath =
|
|
6478
|
-
const nodeModulesLinkPath =
|
|
6777
|
+
const nodeModulesPath = path15.join(toplevel, "node_modules");
|
|
6778
|
+
const nodeModulesLinkPath = path15.join(worktreePath, "node_modules");
|
|
6479
6779
|
const hasDirectoryEntry = (candidate) => {
|
|
6480
6780
|
try {
|
|
6481
|
-
|
|
6781
|
+
fs16.lstatSync(candidate);
|
|
6482
6782
|
return true;
|
|
6483
6783
|
} catch (error) {
|
|
6484
6784
|
if (error instanceof Error && "code" in error && error.code === "ENOENT") return false;
|
|
@@ -6489,14 +6789,14 @@ function linkNodeModulesIfPresent(toplevel, worktreePath) {
|
|
|
6489
6789
|
if (hasDirectoryEntry(nodeModulesLinkPath)) return false;
|
|
6490
6790
|
let sourceRealPath;
|
|
6491
6791
|
try {
|
|
6492
|
-
if (!
|
|
6493
|
-
sourceRealPath =
|
|
6792
|
+
if (!fs16.statSync(nodeModulesPath).isDirectory()) throw new Error("source node_modules is not a directory");
|
|
6793
|
+
sourceRealPath = fs16.realpathSync.native(nodeModulesPath);
|
|
6494
6794
|
} catch (error) {
|
|
6495
6795
|
if (error instanceof Error && "code" in error && error.code === "ENOENT") return false;
|
|
6496
6796
|
throw error;
|
|
6497
6797
|
}
|
|
6498
|
-
|
|
6499
|
-
if (!
|
|
6798
|
+
fs16.symlinkSync(nodeModulesPath, nodeModulesLinkPath, process.platform === "win32" ? "junction" : "dir");
|
|
6799
|
+
if (!fs16.lstatSync(nodeModulesLinkPath).isSymbolicLink() || fs16.realpathSync.native(nodeModulesLinkPath) !== sourceRealPath) {
|
|
6500
6800
|
throw new Error("created link does not resolve to the source node_modules");
|
|
6501
6801
|
}
|
|
6502
6802
|
return true;
|
|
@@ -6521,19 +6821,19 @@ function resolveWorktreeSetupHook(repoRoot, config) {
|
|
|
6521
6821
|
if (!hookPath) {
|
|
6522
6822
|
throw new Error("worktree setup hook path cannot be empty");
|
|
6523
6823
|
}
|
|
6524
|
-
const expandedHookPath = hookPath.startsWith("~/") ?
|
|
6824
|
+
const expandedHookPath = hookPath.startsWith("~/") ? path15.join(os2.homedir(), hookPath.slice(2)) : hookPath;
|
|
6525
6825
|
let resolvedPath;
|
|
6526
|
-
if (
|
|
6826
|
+
if (path15.isAbsolute(expandedHookPath)) {
|
|
6527
6827
|
resolvedPath = expandedHookPath;
|
|
6528
6828
|
} else if (expandedHookPath.includes("/") || expandedHookPath.includes("\\")) {
|
|
6529
|
-
resolvedPath =
|
|
6829
|
+
resolvedPath = path15.resolve(repoRoot, expandedHookPath);
|
|
6530
6830
|
} else {
|
|
6531
6831
|
throw new Error("worktree setup hook must be an absolute path or a repo-relative path");
|
|
6532
6832
|
}
|
|
6533
|
-
if (!
|
|
6833
|
+
if (!fs16.existsSync(resolvedPath)) {
|
|
6534
6834
|
throw new Error(`worktree setup hook not found: ${resolvedPath}`);
|
|
6535
6835
|
}
|
|
6536
|
-
if (
|
|
6836
|
+
if (fs16.statSync(resolvedPath).isDirectory()) {
|
|
6537
6837
|
throw new Error(`worktree setup hook must be a file, got directory: ${resolvedPath}`);
|
|
6538
6838
|
}
|
|
6539
6839
|
return {
|
|
@@ -6544,16 +6844,16 @@ function resolveWorktreeSetupHook(repoRoot, config) {
|
|
|
6544
6844
|
function normalizeSyntheticPath(worktreePath, rawPath) {
|
|
6545
6845
|
const trimmed = rawPath.trim();
|
|
6546
6846
|
if (!trimmed) throw new Error("synthetic path cannot be empty");
|
|
6547
|
-
if (
|
|
6548
|
-
const resolved2 =
|
|
6549
|
-
const relative4 =
|
|
6847
|
+
if (path15.isAbsolute(trimmed)) throw new Error(`synthetic path must be relative: ${rawPath}`);
|
|
6848
|
+
const resolved2 = path15.resolve(worktreePath, trimmed);
|
|
6849
|
+
const relative4 = path15.relative(worktreePath, resolved2);
|
|
6550
6850
|
if (!relative4 || relative4 === ".") {
|
|
6551
6851
|
throw new Error(`synthetic path cannot target the worktree root: ${rawPath}`);
|
|
6552
6852
|
}
|
|
6553
|
-
if (relative4 === ".." || relative4.startsWith(`..${
|
|
6853
|
+
if (relative4 === ".." || relative4.startsWith(`..${path15.sep}`) || path15.isAbsolute(relative4)) {
|
|
6554
6854
|
throw new Error(`synthetic path escapes the worktree root: ${rawPath}`);
|
|
6555
6855
|
}
|
|
6556
|
-
return
|
|
6856
|
+
return path15.normalize(relative4);
|
|
6557
6857
|
}
|
|
6558
6858
|
function parseWorktreeSetupHookOutput(rawStdout) {
|
|
6559
6859
|
const trimmed = rawStdout.trim();
|
|
@@ -6607,7 +6907,7 @@ async function runWorktreeSetupHook(tx, hook, input) {
|
|
|
6607
6907
|
}
|
|
6608
6908
|
}
|
|
6609
6909
|
async function finalizeCreatedWorktree(tx, toplevel, cwdRelative, runId, baseCommit, setupHook, agent, worktree) {
|
|
6610
|
-
const agentCwd = cwdRelative ?
|
|
6910
|
+
const agentCwd = cwdRelative ? path15.join(worktree.path, cwdRelative) : worktree.path;
|
|
6611
6911
|
tx.check();
|
|
6612
6912
|
const nodeModulesLinked = linkNodeModulesIfPresent(toplevel, worktree.path);
|
|
6613
6913
|
const syntheticPaths = nodeModulesLinked ? ["node_modules"] : [];
|
|
@@ -6634,7 +6934,7 @@ async function createNativeWorktree(tx, toplevel, cwdRelative, runId, index, bas
|
|
|
6634
6934
|
const branch = await tx.git(toplevel, ["show-ref", "--verify", "--quiet", `refs/heads/${naming.requestedBranch}`], [0, 1]);
|
|
6635
6935
|
let pathExists = false;
|
|
6636
6936
|
try {
|
|
6637
|
-
|
|
6937
|
+
fs16.lstatSync(worktreePath);
|
|
6638
6938
|
pathExists = true;
|
|
6639
6939
|
} catch (error) {
|
|
6640
6940
|
if (!(error instanceof Error) || !("code" in error) || error.code !== "ENOENT") throw error;
|
|
@@ -6642,7 +6942,7 @@ async function createNativeWorktree(tx, toplevel, cwdRelative, runId, index, bas
|
|
|
6642
6942
|
if (branch.status !== 1 || pathExists) throw new Error(`worktree path or branch already exists: ${worktreePath}, ${naming.requestedBranch}`);
|
|
6643
6943
|
tx.attempt(index, naming.requestedBranch, worktreePath);
|
|
6644
6944
|
ensureProjectWorktreeDir(dedicatedRoot, toplevel);
|
|
6645
|
-
const recordedBaseDir = normalizeComparableCwd(
|
|
6945
|
+
const recordedBaseDir = normalizeComparableCwd(path15.dirname(worktreePath));
|
|
6646
6946
|
await tx.git(toplevel, ["worktree", "add", worktreePath, "-b", naming.requestedBranch, baseCommit]);
|
|
6647
6947
|
const worktree = {
|
|
6648
6948
|
path: worktreePath,
|
|
@@ -6682,11 +6982,11 @@ async function createWorktrunkWorktree(tx, toplevel, cwdRelative, runId, index,
|
|
|
6682
6982
|
if (output.action !== "created" || output.created_branch !== true || output.branch !== naming.requestedBranch || output.base_branch !== baseCommit) {
|
|
6683
6983
|
throw new Error("Worktrunk provisioning returned inconsistent creation metadata");
|
|
6684
6984
|
}
|
|
6685
|
-
if (typeof output.path !== "string" || !
|
|
6686
|
-
const worktreePathCandidate =
|
|
6985
|
+
if (typeof output.path !== "string" || !path15.isAbsolute(output.path)) throw new Error("Worktrunk provisioning returned a non-absolute worktree path");
|
|
6986
|
+
const worktreePathCandidate = path15.resolve(output.path);
|
|
6687
6987
|
let stat;
|
|
6688
6988
|
try {
|
|
6689
|
-
stat =
|
|
6989
|
+
stat = fs16.lstatSync(worktreePathCandidate);
|
|
6690
6990
|
} catch (error) {
|
|
6691
6991
|
throw new Error(`Worktrunk provisioning returned a missing worktree path: ${worktreePathCandidate}`, { cause: error instanceof Error ? error : void 0 });
|
|
6692
6992
|
}
|
|
@@ -6695,8 +6995,8 @@ async function createWorktrunkWorktree(tx, toplevel, cwdRelative, runId, index,
|
|
|
6695
6995
|
if (worktreePath === normalizeComparableCwd(toplevel)) throw new Error("Worktrunk provisioning returned the source checkout path");
|
|
6696
6996
|
const sourceCommonDirRaw = (await tx.gitChecked(toplevel, ["rev-parse", "--git-common-dir"])).trim();
|
|
6697
6997
|
const returnedCommonDirRaw = (await tx.gitChecked(worktreePath, ["rev-parse", "--git-common-dir"])).trim();
|
|
6698
|
-
const sourceCommonDir = normalizeComparableCwd(
|
|
6699
|
-
const returnedCommonDir = normalizeComparableCwd(
|
|
6998
|
+
const sourceCommonDir = normalizeComparableCwd(path15.isAbsolute(sourceCommonDirRaw) ? sourceCommonDirRaw : path15.resolve(toplevel, sourceCommonDirRaw));
|
|
6999
|
+
const returnedCommonDir = normalizeComparableCwd(path15.isAbsolute(returnedCommonDirRaw) ? returnedCommonDirRaw : path15.resolve(worktreePath, returnedCommonDirRaw));
|
|
6700
7000
|
if (returnedCommonDir !== sourceCommonDir) throw new Error("Worktrunk provisioning returned a worktree for a different repository");
|
|
6701
7001
|
const returnedBranch = (await tx.gitChecked(worktreePath, ["symbolic-ref", "--quiet", "--short", "HEAD"])).trim();
|
|
6702
7002
|
if (returnedBranch !== naming.requestedBranch) throw new Error("Worktrunk provisioning returned a worktree on a different branch");
|
|
@@ -6704,8 +7004,8 @@ async function createWorktrunkWorktree(tx, toplevel, cwdRelative, runId, index,
|
|
|
6704
7004
|
if (returnedHead !== baseCommit) throw new Error("Worktrunk provisioning returned a worktree at a different base commit");
|
|
6705
7005
|
const worktree = {
|
|
6706
7006
|
path: worktreePath,
|
|
6707
|
-
recordedBaseDir: normalizeComparableCwd(
|
|
6708
|
-
agentCwd: cwdRelative ?
|
|
7007
|
+
recordedBaseDir: normalizeComparableCwd(path15.dirname(worktreePath)),
|
|
7008
|
+
agentCwd: cwdRelative ? path15.join(worktreePath, cwdRelative) : worktreePath,
|
|
6709
7009
|
branch: naming.requestedBranch,
|
|
6710
7010
|
index,
|
|
6711
7011
|
nodeModulesLinked: false,
|
|
@@ -6722,28 +7022,28 @@ async function createWorktrunkWorktree(tx, toplevel, cwdRelative, runId, index,
|
|
|
6722
7022
|
}
|
|
6723
7023
|
function removeSyntheticPath(worktree, syntheticPath) {
|
|
6724
7024
|
assertWorktreeMutationAllowed();
|
|
6725
|
-
const resolved2 =
|
|
6726
|
-
const relative4 =
|
|
6727
|
-
if (!relative4 || relative4 === "." || relative4 === ".." || relative4.startsWith(`..${
|
|
7025
|
+
const resolved2 = path15.resolve(worktree.path, syntheticPath);
|
|
7026
|
+
const relative4 = path15.relative(worktree.path, resolved2);
|
|
7027
|
+
if (!relative4 || relative4 === "." || relative4 === ".." || relative4.startsWith(`..${path15.sep}`) || path15.isAbsolute(relative4)) {
|
|
6728
7028
|
return;
|
|
6729
7029
|
}
|
|
6730
7030
|
let stat;
|
|
6731
7031
|
try {
|
|
6732
|
-
stat =
|
|
7032
|
+
stat = fs16.lstatSync(resolved2);
|
|
6733
7033
|
} catch (error) {
|
|
6734
7034
|
const code = error && typeof error === "object" && "code" in error ? error.code : void 0;
|
|
6735
7035
|
if (code === "ENOENT") return;
|
|
6736
7036
|
throw error;
|
|
6737
7037
|
}
|
|
6738
7038
|
if (stat.isSymbolicLink()) {
|
|
6739
|
-
|
|
7039
|
+
fs16.unlinkSync(resolved2);
|
|
6740
7040
|
return;
|
|
6741
7041
|
}
|
|
6742
7042
|
if (stat.isDirectory()) {
|
|
6743
|
-
|
|
7043
|
+
fs16.rmSync(resolved2, { recursive: true, force: true });
|
|
6744
7044
|
return;
|
|
6745
7045
|
}
|
|
6746
|
-
|
|
7046
|
+
fs16.rmSync(resolved2, { force: true });
|
|
6747
7047
|
}
|
|
6748
7048
|
function removeSyntheticPathsBeforeDiff(worktree) {
|
|
6749
7049
|
if (worktree.syntheticPaths.length === 0) return;
|
|
@@ -6787,7 +7087,7 @@ function captureWorktreeDiff(setup, worktree, agent, patchPath) {
|
|
|
6787
7087
|
const diffStat = runGitChecked(worktree.path, ["diff", "--cached", ...MACHINE_DIFF_OPTIONS, "--stat", setup.baseCommit]).trim();
|
|
6788
7088
|
const patch = runGitChecked(worktree.path, ["diff", "--cached", ...MACHINE_PATCH_OPTIONS, setup.baseCommit]);
|
|
6789
7089
|
const numstat = runGitChecked(worktree.path, ["diff", "--cached", ...MACHINE_DIFF_OPTIONS, "--numstat", setup.baseCommit]);
|
|
6790
|
-
|
|
7090
|
+
fs16.writeFileSync(patchPath, patch, "utf-8");
|
|
6791
7091
|
if (!patch.trim()) {
|
|
6792
7092
|
return emptyDiff(worktree.index, agent, worktree.branch, patchPath);
|
|
6793
7093
|
}
|
|
@@ -6807,18 +7107,18 @@ function captureWorktreeDiff(setup, worktree, agent, patchPath) {
|
|
|
6807
7107
|
}
|
|
6808
7108
|
function writeEmptyPatch(patchPath) {
|
|
6809
7109
|
try {
|
|
6810
|
-
|
|
7110
|
+
fs16.writeFileSync(patchPath, "", "utf-8");
|
|
6811
7111
|
} catch {
|
|
6812
7112
|
}
|
|
6813
7113
|
}
|
|
6814
7114
|
function handoffRecordsPatch(manifestPath, patchPath) {
|
|
6815
|
-
if (!manifestPath || !
|
|
7115
|
+
if (!manifestPath || !fs16.existsSync(manifestPath)) return false;
|
|
6816
7116
|
try {
|
|
6817
|
-
const manifest = JSON.parse(
|
|
7117
|
+
const manifest = JSON.parse(fs16.readFileSync(manifestPath, "utf-8"));
|
|
6818
7118
|
if (manifest.version !== 1 || !Array.isArray(manifest.groups)) return false;
|
|
6819
|
-
const resolvedPatchPath =
|
|
7119
|
+
const resolvedPatchPath = path15.resolve(patchPath);
|
|
6820
7120
|
return manifest.groups.some((group) => Array.isArray(group.children) && group.children.some(
|
|
6821
|
-
(child) => child.patch?.error === void 0 && typeof child.patch?.path === "string" &&
|
|
7121
|
+
(child) => child.patch?.error === void 0 && typeof child.patch?.path === "string" && path15.resolve(child.patch.path) === resolvedPatchPath
|
|
6822
7122
|
));
|
|
6823
7123
|
} catch {
|
|
6824
7124
|
return false;
|
|
@@ -6871,9 +7171,9 @@ function cleanupSingleWorktree(setup, worktree, intent) {
|
|
|
6871
7171
|
const captured = (intent.capturedDiffs ?? setup.capturedDiffs)?.find((diff) => diff.index === worktree.index);
|
|
6872
7172
|
let patchValidationError;
|
|
6873
7173
|
let patchCaptured = false;
|
|
6874
|
-
if (captured !== void 0 && captured.error === void 0 &&
|
|
7174
|
+
if (captured !== void 0 && captured.error === void 0 && fs16.existsSync(captured.patchPath) && handoffRecordsPatch(intent.handoffManifestPath, captured.patchPath)) {
|
|
6875
7175
|
try {
|
|
6876
|
-
if (
|
|
7176
|
+
if (fs16.statSync(captured.patchPath).size > 0) {
|
|
6877
7177
|
patchValidationError = validateWorktreePatchRepresentsCurrentWorktree(worktree.path, setup.baseCommit, captured.patchPath);
|
|
6878
7178
|
patchCaptured = patchValidationError === void 0;
|
|
6879
7179
|
}
|
|
@@ -7003,7 +7303,7 @@ async function compensateSetup(tx) {
|
|
|
7003
7303
|
throw new Error(tx.progress.unknown);
|
|
7004
7304
|
}
|
|
7005
7305
|
await git(["worktree", "remove", "--force", attempt.path]);
|
|
7006
|
-
} else if (
|
|
7306
|
+
} else if (fs16.existsSync(attempt.path)) {
|
|
7007
7307
|
tx.unknown("Unregistered partial allocation retained");
|
|
7008
7308
|
throw new Error(tx.progress.unknown);
|
|
7009
7309
|
}
|
|
@@ -7123,7 +7423,7 @@ async function createWorktrees(cwd, runId, count, options = {}) {
|
|
|
7123
7423
|
function diffWorktrees(setup, agents, diffsDir) {
|
|
7124
7424
|
assertWorktreeMutationAllowed();
|
|
7125
7425
|
try {
|
|
7126
|
-
|
|
7426
|
+
fs16.mkdirSync(diffsDir, { recursive: true });
|
|
7127
7427
|
} catch {
|
|
7128
7428
|
return [];
|
|
7129
7429
|
}
|
|
@@ -7131,7 +7431,7 @@ function diffWorktrees(setup, agents, diffsDir) {
|
|
|
7131
7431
|
for (let index = 0; index < setup.worktrees.length; index++) {
|
|
7132
7432
|
const worktree = setup.worktrees[index];
|
|
7133
7433
|
const agent = agents[index] ?? `task-${index + 1}`;
|
|
7134
|
-
const patchPath =
|
|
7434
|
+
const patchPath = path15.join(diffsDir, `task-${index}-${safePatchAgentName(agent)}.patch`);
|
|
7135
7435
|
try {
|
|
7136
7436
|
diffs.push(captureWorktreeDiff(setup, worktree, agent, patchPath));
|
|
7137
7437
|
} catch (error) {
|
|
@@ -7178,7 +7478,7 @@ function formatWorktreeDiffSummary(diffs) {
|
|
|
7178
7478
|
}
|
|
7179
7479
|
lines.push("");
|
|
7180
7480
|
}
|
|
7181
|
-
const patchesDir =
|
|
7481
|
+
const patchesDir = path15.dirname(changed[0].patchPath);
|
|
7182
7482
|
lines.push(`Full patches: ${patchesDir}`);
|
|
7183
7483
|
return lines.join("\n").trimEnd();
|
|
7184
7484
|
}
|
|
@@ -7231,6 +7531,7 @@ export {
|
|
|
7231
7531
|
buildNestedRouteIndex,
|
|
7232
7532
|
projectNestedRegistryForRoot,
|
|
7233
7533
|
retainNestedLookupRoute,
|
|
7534
|
+
collectNestedRuns,
|
|
7234
7535
|
findNestedRunMatchesById,
|
|
7235
7536
|
projectNestedEvents,
|
|
7236
7537
|
writeNestedEvent,
|
|
@@ -7263,6 +7564,11 @@ export {
|
|
|
7263
7564
|
upsertHostStep,
|
|
7264
7565
|
hostStepVerdictLabel,
|
|
7265
7566
|
hostStepReportName,
|
|
7567
|
+
REQUIRE_LAUNCHER_SHAPE_ERROR,
|
|
7568
|
+
lookupRunnerLauncher,
|
|
7569
|
+
runnerLauncherPlacementError,
|
|
7570
|
+
resolveAgentRunnerLauncher,
|
|
7571
|
+
checkRequiredRunnerLauncher,
|
|
7266
7572
|
resolveWorkflowHostOutputClaimPath,
|
|
7267
7573
|
executeWorkflowHostCommand,
|
|
7268
7574
|
WorkflowScriptError,
|
|
@@ -7332,10 +7638,14 @@ export {
|
|
|
7332
7638
|
WORKTREE_AGENT_CWD_PLACEHOLDER,
|
|
7333
7639
|
MACHINE_DIFF_OPTIONS,
|
|
7334
7640
|
withWorktreeTransaction,
|
|
7641
|
+
findListedWorktreeOnBranch,
|
|
7642
|
+
findListedWorktreeAgentCwd,
|
|
7643
|
+
isComparablePathInside,
|
|
7335
7644
|
validateWorktreePatchRepresentsCurrentWorktree,
|
|
7336
7645
|
preflightWorktreeSource,
|
|
7337
7646
|
normalizeWorktreeBaseRef,
|
|
7338
7647
|
normalizeWorktreeBranchPrefix,
|
|
7648
|
+
buildWorktreeNaming,
|
|
7339
7649
|
resolveWorktreeProvider,
|
|
7340
7650
|
shouldDeferWorktreeCwd,
|
|
7341
7651
|
resolveExpectedWorktreeAgentCwd,
|