pi-subagents 0.86.0 → 0.88.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 +59 -0
- package/bundle/agents.js +3 -3
- package/bundle/child-tool-plan.js +2 -2
- package/bundle/{chunk-PYOAIN3V.js → chunk-2DIEL4WG.js} +2 -2
- package/bundle/{chunk-GJGTMLPE.js → chunk-3DT5X2QC.js} +483 -477
- package/bundle/{chunk-374MZFF4.js → chunk-3MFYKBKI.js} +23 -13
- package/bundle/{chunk-ZJJCPV3L.js → chunk-47GJDBIK.js} +10 -6
- package/bundle/{chunk-77ASNIEM.js → chunk-47ZN7NKR.js} +1 -1
- package/bundle/{chunk-QGO6HXHG.js → chunk-4MVDMA5C.js} +88 -64
- package/bundle/{chunk-O3YH7XIY.js → chunk-4PM6RDE5.js} +46 -32
- package/bundle/{chunk-BWC2LVII.js → chunk-4UGWHREQ.js} +200 -64
- package/bundle/{chunk-3RKFH2UZ.js → chunk-6EUQPQY7.js} +31 -14
- package/bundle/{chunk-A637IMAO.js → chunk-6OWNDN7R.js} +2 -2
- package/bundle/{chunk-6VD7BGIC.js → chunk-6PR44R7E.js} +7 -2
- package/bundle/{chunk-7ZUFN6ME.js → chunk-CKLZ5FGU.js} +2 -2
- package/bundle/{chunk-ZPY5QZCS.js → chunk-CYKNHFXB.js} +1 -1
- package/bundle/{chunk-YK3QYNLE.js → chunk-GDR2ILWY.js} +1 -1
- package/bundle/{chunk-7QA7ZA46.js → chunk-IZEKQEY4.js} +9 -9
- package/bundle/{chunk-NAFLUJ26.js → chunk-KXW62VBU.js} +1 -1
- package/bundle/{chunk-S2Q75LP3.js → chunk-L4YY2TOE.js} +1 -1
- package/bundle/{chunk-QM3JGE4W.js → chunk-MTPICU4A.js} +12 -12
- package/bundle/{chunk-BU6PFPVX.js → chunk-PJSOS2Q4.js} +12 -7
- package/bundle/{chunk-UR7OW5S7.js → chunk-RHYVKQQL.js} +11 -5
- package/bundle/{chunk-BGXEAYUM.js → chunk-SVIXQDIV.js} +20 -5
- package/bundle/{chunk-7ADDXUGF.js → chunk-UVDLJXL6.js} +14 -5
- package/bundle/{chunk-NF7IEKBH.js → chunk-W2BZS6UC.js} +27 -13
- package/bundle/{chunk-5H4BICQZ.js → chunk-W6HIYD2Z.js} +1 -1
- package/bundle/{chunk-2IYBCYFU.js → chunk-XAOHLFJO.js} +174 -56
- package/bundle/{chunk-LGINOOY5.js → chunk-XIA5GSEU.js} +2 -2
- package/bundle/chunk-YDZ7BZD5.js +523 -0
- package/bundle/{chunk-WN2E5XHN.js → chunk-YZPVALSQ.js} +30 -5
- 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 +4 -4
- package/docs/configuration.md +17 -5
- package/docs/extension-api.md +2 -0
- package/docs/models.md +6 -2
- package/docs/observability.md +2 -0
- package/docs/tool-reference.md +5 -1
- 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 +22 -10
- package/src/agents/agent-serializer.d.ts +2 -0
- package/src/agents/agent-serializer.js +1 -1
- package/src/agents/agents.d.ts +1 -0
- package/src/agents/agents.js +39 -14
- 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 +6 -0
- package/src/extension/index.js +8 -5
- package/src/extension/schemas.d.ts +4 -0
- package/src/extension/schemas.js +2 -0
- package/src/extension/tool-activation.js +20 -3
- package/src/runs/background/async-execution.d.ts +2 -1
- package/src/runs/background/async-execution.js +4 -2
- package/src/runs/background/async-resume.js +2 -1
- package/src/runs/background/async-retention.d.ts +0 -2
- package/src/runs/background/async-retention.js +11 -5
- package/src/runs/background/async-status.d.ts +2 -0
- package/src/runs/background/async-status.js +4 -0
- package/src/runs/background/run-child-session.d.ts +2 -2
- package/src/runs/background/run-child-session.js +4 -7
- package/src/runs/background/runner-aliases.js +15 -0
- 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 +0 -2
- package/src/runs/background/subagent-runner.js +73 -58
- package/src/runs/background/wait-subscriptions.js +124 -12
- 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.js +33 -15
- package/src/runs/foreground/prompt-audit.js +1 -0
- package/src/runs/foreground/subagent-executor.d.ts +2 -8
- package/src/runs/foreground/subagent-executor.js +57 -23
- 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-session.d.ts +5 -4
- package/src/runs/shared/child-session.js +64 -36
- package/src/runs/shared/herdr-placed-run.js +3 -2
- 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/model-resolution.d.ts +19 -4
- package/src/runs/shared/model-resolution.js +50 -51
- package/src/runs/shared/subagent-prompt-runtime.js +14 -2
- package/src/runs/shared/supervisor-wait-timer.d.ts +16 -0
- package/src/runs/shared/supervisor-wait-timer.js +61 -0
- package/src/shared/artifacts.d.ts +1 -0
- package/src/shared/artifacts.js +132 -22
- 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/status-format.d.ts +1 -0
- package/src/shared/status-format.js +1 -1
- package/src/shared/types.d.ts +23 -0
- package/src/shared/utils.d.ts +3 -1
- package/src/shared/utils.js +4 -0
- package/src/tui/render.js +33 -2
- package/src/watchdog/model-selection.js +2 -2
- package/src/watchdog/permission-arbiter.js +1 -0
- package/src/watchdog/review.d.ts +0 -5
- package/src/watchdog/review.js +4 -3
- package/src/workflows/scripted-workflow.d.ts +2 -0
- package/src/workflows/scripted-workflow.js +103 -39
- package/src/workflows/structured-workflow-scripts.d.ts +4 -3
- package/src/workflows/structured-workflow-scripts.js +32 -11
- 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 +1 -1
- package/src/workflows/workflow-resume.d.ts +1 -1
- package/src/workflows/workflow-resume.js +3 -1
- package/src/workflows/workflow-script-worker.js +3 -1
- package/bundle/chunk-GRJHIXYF.js +0 -235
|
@@ -2,8 +2,10 @@ import {
|
|
|
2
2
|
agentDefinitionDigest
|
|
3
3
|
} from "./chunk-7F6RKT6W.js";
|
|
4
4
|
import {
|
|
5
|
-
PROJECT_SUBAGENTS_RELATIVE_DIR
|
|
6
|
-
|
|
5
|
+
PROJECT_SUBAGENTS_RELATIVE_DIR,
|
|
6
|
+
canonicalSessionId,
|
|
7
|
+
inspectSessionLease
|
|
8
|
+
} from "./chunk-YDZ7BZD5.js";
|
|
7
9
|
import {
|
|
8
10
|
DEFAULT_FILE_SYSTEM_RETRY_DELAYS_MS,
|
|
9
11
|
DEFAULT_GLOBAL_CONCURRENCY_LIMIT,
|
|
@@ -25,7 +27,7 @@ import {
|
|
|
25
27
|
withFileLease,
|
|
26
28
|
writeAtomicJson,
|
|
27
29
|
writePrivateAtomicJson
|
|
28
|
-
} from "./chunk-
|
|
30
|
+
} from "./chunk-4MVDMA5C.js";
|
|
29
31
|
import {
|
|
30
32
|
DIRS,
|
|
31
33
|
SUBAGENT_LIFECYCLE_ARTIFACT_VERSION,
|
|
@@ -467,53 +469,10 @@ function writeProcessTerminalCandidate(asyncDir, candidate) {
|
|
|
467
469
|
}
|
|
468
470
|
|
|
469
471
|
// src/runs/background/process-terminal.ts
|
|
470
|
-
import * as fs5 from "node:fs";
|
|
471
|
-
import * as path6 from "node:path";
|
|
472
|
-
|
|
473
|
-
// src/runs/shared/session-lease.ts
|
|
474
|
-
import { createHash as createHash2, randomUUID } from "node:crypto";
|
|
475
472
|
import * as fs4 from "node:fs";
|
|
476
473
|
import * as path5 from "node:path";
|
|
477
|
-
var SESSION_LEASES_DIR = path5.join(TEMP_ROOT_DIR, "session-leases");
|
|
478
|
-
function canonicalSessionFilePath(sessionFile) {
|
|
479
|
-
return fs4.realpathSync.native(path5.resolve(sessionFile));
|
|
480
|
-
}
|
|
481
|
-
function canonicalSessionId(sessionFile) {
|
|
482
|
-
const canonical = canonicalSessionFilePath(sessionFile);
|
|
483
|
-
const key = process.platform === "win32" ? canonical.toLowerCase() : canonical;
|
|
484
|
-
return createHash2("sha256").update(key).digest("hex");
|
|
485
|
-
}
|
|
486
|
-
function inspectSessionLease(sessionFile, rootDir = SESSION_LEASES_DIR) {
|
|
487
|
-
const canonicalSessionFile = canonicalSessionFilePath(sessionFile);
|
|
488
|
-
const canonicalSessionIdValue = canonicalSessionId(canonicalSessionFile);
|
|
489
|
-
const leaseDir = path5.join(rootDir, canonicalSessionIdValue);
|
|
490
|
-
if (!fs4.existsSync(leaseDir)) return { state: "free", canonicalSessionFile, canonicalSessionId: canonicalSessionIdValue };
|
|
491
|
-
const owner = readLeaseOwner(leaseDir);
|
|
492
|
-
return owner ? { state: "owned", canonicalSessionFile, canonicalSessionId: canonicalSessionIdValue, owner } : { state: "unreadable", canonicalSessionFile, canonicalSessionId: canonicalSessionIdValue };
|
|
493
|
-
}
|
|
494
|
-
function parseOwner(value) {
|
|
495
|
-
if (!value || typeof value !== "object" || Array.isArray(value)) return void 0;
|
|
496
|
-
const owner = value;
|
|
497
|
-
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;
|
|
498
|
-
if (owner.parentSessionId !== void 0 && typeof owner.parentSessionId !== "string") return void 0;
|
|
499
|
-
if (owner.processStartIdentity !== void 0 && typeof owner.processStartIdentity !== "string") return void 0;
|
|
500
|
-
if (owner.writerPid !== void 0 && (typeof owner.writerPid !== "number" || !Number.isInteger(owner.writerPid) || owner.writerPid <= 0)) return void 0;
|
|
501
|
-
if (owner.writerProcessStartIdentity !== void 0 && typeof owner.writerProcessStartIdentity !== "string") return void 0;
|
|
502
|
-
if (owner.writerState === "running" && owner.writerPid === void 0) return void 0;
|
|
503
|
-
if (owner.writerState !== "running" && (owner.writerPid !== void 0 || owner.writerProcessStartIdentity !== void 0)) return void 0;
|
|
504
|
-
return owner;
|
|
505
|
-
}
|
|
506
|
-
function readLeaseOwner(leaseDir) {
|
|
507
|
-
try {
|
|
508
|
-
return parseOwner(JSON.parse(fs4.readFileSync(path5.join(leaseDir, "owner.json"), "utf-8")));
|
|
509
|
-
} catch {
|
|
510
|
-
return void 0;
|
|
511
|
-
}
|
|
512
|
-
}
|
|
513
|
-
|
|
514
|
-
// src/runs/background/process-terminal.ts
|
|
515
474
|
function processTerminalPath(asyncDir) {
|
|
516
|
-
return
|
|
475
|
+
return path5.join(asyncDir, "process-terminal.json");
|
|
517
476
|
}
|
|
518
477
|
function errorMessage(error) {
|
|
519
478
|
return error instanceof Error ? error.message : String(error);
|
|
@@ -538,7 +497,7 @@ function unknownProof(runId, runnerProcessInstanceId, reason, diagnostic) {
|
|
|
538
497
|
function resumeDisposition(state, sessionFile) {
|
|
539
498
|
if (state === "stopped") return "non-resumable";
|
|
540
499
|
if (state !== "complete" && state !== "completed" && state !== "failed" && state !== "paused") return "unavailable";
|
|
541
|
-
return sessionFile &&
|
|
500
|
+
return sessionFile && fs4.existsSync(sessionFile) ? "resumable" : "unavailable";
|
|
542
501
|
}
|
|
543
502
|
function sessionProjection(candidate, lease) {
|
|
544
503
|
if (!candidate.sessionFile || lease.state !== "free") return void 0;
|
|
@@ -579,12 +538,12 @@ function sanitizeProcessTerminal(value, fallback, label = "status") {
|
|
|
579
538
|
}
|
|
580
539
|
function readProcessTerminal(asyncDir, fallback) {
|
|
581
540
|
try {
|
|
582
|
-
const raw = JSON.parse(
|
|
541
|
+
const raw = JSON.parse(fs4.readFileSync(processTerminalPath(asyncDir), "utf-8"));
|
|
583
542
|
validateProof(raw, asyncDir, fallback);
|
|
584
543
|
return raw;
|
|
585
544
|
} catch (error) {
|
|
586
545
|
if (error.code === "ENOENT") return void 0;
|
|
587
|
-
return unknownProof(fallback?.runId ??
|
|
546
|
+
return unknownProof(fallback?.runId ?? path5.basename(asyncDir), fallback?.runnerProcessInstanceId ?? "unknown", "proof-write-failed", errorMessage(error));
|
|
588
547
|
}
|
|
589
548
|
}
|
|
590
549
|
function stepProcessTerminalProof(proof, childIndex, state, records, resumeDispositionValue) {
|
|
@@ -604,9 +563,9 @@ function stepProcessTerminalProof(proof, childIndex, state, records, resumeDispo
|
|
|
604
563
|
return { ...base, state };
|
|
605
564
|
}
|
|
606
565
|
function overlayStatus(asyncDir, proof, candidate) {
|
|
607
|
-
const statusPath =
|
|
566
|
+
const statusPath = path5.join(asyncDir, "status.json");
|
|
608
567
|
try {
|
|
609
|
-
const status = JSON.parse(
|
|
568
|
+
const status = JSON.parse(fs4.readFileSync(statusPath, "utf-8"));
|
|
610
569
|
status.processTerminal = proof;
|
|
611
570
|
if (status.steps) {
|
|
612
571
|
for (const [index, step] of status.steps.entries()) {
|
|
@@ -622,7 +581,7 @@ function overlayStatus(asyncDir, proof, candidate) {
|
|
|
622
581
|
}
|
|
623
582
|
function finalizeProcessTerminal(asyncDir, runId, runnerClose) {
|
|
624
583
|
const existing = readProcessTerminal(asyncDir, { runId, runnerProcessInstanceId: runnerClose.processInstanceId });
|
|
625
|
-
if (existing &&
|
|
584
|
+
if (existing && fs4.existsSync(processTerminalPath(asyncDir))) {
|
|
626
585
|
if (existing.state === "observed" && existing.runId === runId && existing.runnerProcessInstanceId === runnerClose.processInstanceId) return existing;
|
|
627
586
|
if (existing.state === "unknown") {
|
|
628
587
|
if (existing.instances?.length || existing.reason === "proof-write-failed") return existing;
|
|
@@ -646,7 +605,7 @@ function finalizeProcessTerminal(asyncDir, runId, runnerClose) {
|
|
|
646
605
|
const allWriters = Object.values(candidate.writers).flat();
|
|
647
606
|
const status = (() => {
|
|
648
607
|
try {
|
|
649
|
-
return JSON.parse(
|
|
608
|
+
return JSON.parse(fs4.readFileSync(path5.join(asyncDir, "status.json"), "utf-8"));
|
|
650
609
|
} catch {
|
|
651
610
|
return void 0;
|
|
652
611
|
}
|
|
@@ -691,7 +650,7 @@ function finalizeProcessTerminal(asyncDir, runId, runnerClose) {
|
|
|
691
650
|
durable = true;
|
|
692
651
|
if (proof.state === "observed") releaseActiveRunIndex(asyncDir);
|
|
693
652
|
overlayStatus(asyncDir, proof, candidateForOverlay);
|
|
694
|
-
|
|
653
|
+
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 })}
|
|
695
654
|
`, "utf-8");
|
|
696
655
|
} catch {
|
|
697
656
|
}
|
|
@@ -699,10 +658,10 @@ function finalizeProcessTerminal(asyncDir, runId, runnerClose) {
|
|
|
699
658
|
}
|
|
700
659
|
|
|
701
660
|
// src/runs/shared/nested-events.ts
|
|
702
|
-
import { randomUUID
|
|
703
|
-
import * as
|
|
704
|
-
import * as
|
|
705
|
-
var NESTED_EVENTS_DIR =
|
|
661
|
+
import { randomUUID } from "node:crypto";
|
|
662
|
+
import * as fs5 from "node:fs";
|
|
663
|
+
import * as path6 from "node:path";
|
|
664
|
+
var NESTED_EVENTS_DIR = path6.join(TEMP_ROOT_DIR, "nested-subagent-events");
|
|
706
665
|
var ROUTE_FILE = "route.json";
|
|
707
666
|
var REGISTRY_FILE = "registry.json";
|
|
708
667
|
var ROUTE_INDEX_DIR = ".route-index";
|
|
@@ -720,48 +679,48 @@ function assertSafeId(label, value) {
|
|
|
720
679
|
assertSafeNestedId(label, value);
|
|
721
680
|
}
|
|
722
681
|
function containedPath(base, candidate) {
|
|
723
|
-
const resolvedBase =
|
|
724
|
-
const resolvedCandidate =
|
|
725
|
-
return resolvedCandidate === resolvedBase || resolvedCandidate.startsWith(`${resolvedBase}${
|
|
682
|
+
const resolvedBase = path6.resolve(base);
|
|
683
|
+
const resolvedCandidate = path6.resolve(candidate);
|
|
684
|
+
return resolvedCandidate === resolvedBase || resolvedCandidate.startsWith(`${resolvedBase}${path6.sep}`);
|
|
726
685
|
}
|
|
727
686
|
function commonRouteRoot(route) {
|
|
728
|
-
return
|
|
687
|
+
return path6.dirname(path6.resolve(route.eventSink));
|
|
729
688
|
}
|
|
730
689
|
function routeIndexRoot() {
|
|
731
|
-
return
|
|
690
|
+
return path6.join(NESTED_EVENTS_DIR, ROUTE_INDEX_DIR, "roots");
|
|
732
691
|
}
|
|
733
692
|
function routeIndexDir(rootRunId) {
|
|
734
|
-
return
|
|
693
|
+
return path6.join(routeIndexRoot(), encodeURIComponent(rootRunId));
|
|
735
694
|
}
|
|
736
695
|
function routeIndexPath(rootRunId, capabilityToken) {
|
|
737
|
-
return
|
|
696
|
+
return path6.join(routeIndexDir(rootRunId), `${encodeURIComponent(capabilityToken)}.json`);
|
|
738
697
|
}
|
|
739
698
|
function validateRouteShape(route) {
|
|
740
699
|
assertSafeId("rootRunId", route.rootRunId);
|
|
741
700
|
assertSafeId("capabilityToken", route.capabilityToken);
|
|
742
701
|
if (!containedPath(NESTED_EVENTS_DIR, route.eventSink)) throw new Error("Nested event sink is outside the subagent nested event root.");
|
|
743
702
|
if (!containedPath(NESTED_EVENTS_DIR, route.controlInbox)) throw new Error("Nested control inbox is outside the subagent nested event root.");
|
|
744
|
-
if (commonRouteRoot(route) !==
|
|
703
|
+
if (commonRouteRoot(route) !== path6.dirname(path6.resolve(route.controlInbox))) throw new Error("Nested event sink and control inbox must share one route root.");
|
|
745
704
|
}
|
|
746
705
|
function createNestedRoute(rootRunId) {
|
|
747
706
|
assertSafeId("rootRunId", rootRunId);
|
|
748
|
-
const capabilityToken =
|
|
749
|
-
const routeRoot =
|
|
750
|
-
const eventSink =
|
|
751
|
-
const controlInbox =
|
|
752
|
-
|
|
753
|
-
|
|
707
|
+
const capabilityToken = randomUUID();
|
|
708
|
+
const routeRoot = path6.join(NESTED_EVENTS_DIR, `${rootRunId}-${capabilityToken}`);
|
|
709
|
+
const eventSink = path6.join(routeRoot, "events");
|
|
710
|
+
const controlInbox = path6.join(routeRoot, "controls");
|
|
711
|
+
fs5.mkdirSync(eventSink, { recursive: true, mode: 448 });
|
|
712
|
+
fs5.mkdirSync(controlInbox, { recursive: true, mode: 448 });
|
|
754
713
|
const createdAt = Date.now();
|
|
755
|
-
|
|
756
|
-
writeAtomicJson(routeIndexPath(rootRunId, capabilityToken), { rootRunId, capabilityToken, routeRoot:
|
|
757
|
-
writeAtomicJson(
|
|
714
|
+
fs5.mkdirSync(routeIndexDir(rootRunId), { recursive: true, mode: 448 });
|
|
715
|
+
writeAtomicJson(routeIndexPath(rootRunId, capabilityToken), { rootRunId, capabilityToken, routeRoot: path6.basename(routeRoot), createdAt });
|
|
716
|
+
writeAtomicJson(path6.join(routeRoot, ROUTE_FILE), { rootRunId, capabilityToken, createdAt });
|
|
758
717
|
return { rootRunId, eventSink, controlInbox, capabilityToken };
|
|
759
718
|
}
|
|
760
719
|
function resolveNestedRoute(route) {
|
|
761
720
|
const { rootRunId, capabilityToken } = route;
|
|
762
721
|
validateRouteShape(route);
|
|
763
|
-
const routeFile =
|
|
764
|
-
const metadata = JSON.parse(
|
|
722
|
+
const routeFile = path6.join(commonRouteRoot(route), ROUTE_FILE);
|
|
723
|
+
const metadata = JSON.parse(fs5.readFileSync(routeFile, "utf-8"));
|
|
765
724
|
if (metadata.rootRunId !== rootRunId || metadata.capabilityToken !== capabilityToken) {
|
|
766
725
|
throw new Error("Nested event route metadata does not match the provided root id and capability token.");
|
|
767
726
|
}
|
|
@@ -794,10 +753,10 @@ function nestedRunNotActiveMessage(runId) {
|
|
|
794
753
|
}
|
|
795
754
|
function resolveNestedAsyncDir(rootRunId, run) {
|
|
796
755
|
if (!run.asyncDir) return void 0;
|
|
797
|
-
const resolved2 =
|
|
798
|
-
const nestedRoot =
|
|
799
|
-
const relative4 =
|
|
800
|
-
return resolved2 === nestedRoot || !relative4.startsWith("..") && !
|
|
756
|
+
const resolved2 = path6.resolve(run.asyncDir);
|
|
757
|
+
const nestedRoot = path6.resolve(TEMP_ROOT_DIR, "nested-subagent-runs", rootRunId, run.id);
|
|
758
|
+
const relative4 = path6.relative(nestedRoot, resolved2);
|
|
759
|
+
return resolved2 === nestedRoot || !relative4.startsWith("..") && !path6.isAbsolute(relative4) ? resolved2 : void 0;
|
|
801
760
|
}
|
|
802
761
|
function clampNumber(value) {
|
|
803
762
|
return typeof value === "number" && Number.isFinite(value) ? value : void 0;
|
|
@@ -1108,24 +1067,24 @@ function applyNestedEvent(registry, event) {
|
|
|
1108
1067
|
};
|
|
1109
1068
|
}
|
|
1110
1069
|
function registryPath(route) {
|
|
1111
|
-
return
|
|
1070
|
+
return path6.join(commonRouteRoot(route), REGISTRY_FILE);
|
|
1112
1071
|
}
|
|
1113
1072
|
function routeFromIndexEntry(rootRunId, filePath) {
|
|
1114
1073
|
try {
|
|
1115
|
-
const metadata = JSON.parse(
|
|
1074
|
+
const metadata = JSON.parse(fs5.readFileSync(filePath, "utf-8"));
|
|
1116
1075
|
if (metadata.rootRunId !== rootRunId || typeof metadata.capabilityToken !== "string" || typeof metadata.routeRoot !== "string") return void 0;
|
|
1117
|
-
const routeRoot =
|
|
1076
|
+
const routeRoot = path6.join(NESTED_EVENTS_DIR, path6.basename(metadata.routeRoot));
|
|
1118
1077
|
const route = {
|
|
1119
1078
|
rootRunId,
|
|
1120
|
-
eventSink:
|
|
1121
|
-
controlInbox:
|
|
1079
|
+
eventSink: path6.join(routeRoot, "events"),
|
|
1080
|
+
controlInbox: path6.join(routeRoot, "controls"),
|
|
1122
1081
|
capabilityToken: metadata.capabilityToken
|
|
1123
1082
|
};
|
|
1124
1083
|
validateRouteShape(route);
|
|
1125
|
-
if (!
|
|
1126
|
-
const routeFilePath =
|
|
1084
|
+
if (!fs5.statSync(route.eventSink).isDirectory() || !fs5.statSync(route.controlInbox).isDirectory()) return void 0;
|
|
1085
|
+
const routeFilePath = path6.join(routeRoot, ROUTE_FILE);
|
|
1127
1086
|
try {
|
|
1128
|
-
const routeFile = JSON.parse(
|
|
1087
|
+
const routeFile = JSON.parse(fs5.readFileSync(routeFilePath, "utf-8"));
|
|
1129
1088
|
if (routeFile.rootRunId !== rootRunId || routeFile.capabilityToken !== metadata.capabilityToken) return void 0;
|
|
1130
1089
|
} catch (error) {
|
|
1131
1090
|
if (error.code !== "ENOENT") return void 0;
|
|
@@ -1143,13 +1102,13 @@ function findNestedRouteForRootId(rootRunId) {
|
|
|
1143
1102
|
assertSafeId("rootRunId", rootRunId);
|
|
1144
1103
|
let entries;
|
|
1145
1104
|
try {
|
|
1146
|
-
entries =
|
|
1105
|
+
entries = fs5.readdirSync(routeIndexDir(rootRunId));
|
|
1147
1106
|
} catch (error) {
|
|
1148
1107
|
if (error.code === "ENOENT") return void 0;
|
|
1149
1108
|
throw error;
|
|
1150
1109
|
}
|
|
1151
1110
|
for (const entry of entries) {
|
|
1152
|
-
const route = routeFromIndexEntry(rootRunId,
|
|
1111
|
+
const route = routeFromIndexEntry(rootRunId, path6.join(routeIndexDir(rootRunId), entry));
|
|
1153
1112
|
if (route) return route;
|
|
1154
1113
|
}
|
|
1155
1114
|
return void 0;
|
|
@@ -1195,7 +1154,7 @@ function collectScopedNestedRuns(children, scope, output = []) {
|
|
|
1195
1154
|
function listNestedRoutes() {
|
|
1196
1155
|
let rootEntries;
|
|
1197
1156
|
try {
|
|
1198
|
-
rootEntries =
|
|
1157
|
+
rootEntries = fs5.readdirSync(routeIndexRoot());
|
|
1199
1158
|
} catch (error) {
|
|
1200
1159
|
if (error.code === "ENOENT") return [];
|
|
1201
1160
|
throw error;
|
|
@@ -1209,8 +1168,8 @@ function listNestedRoutes() {
|
|
|
1209
1168
|
continue;
|
|
1210
1169
|
}
|
|
1211
1170
|
try {
|
|
1212
|
-
for (const entry of
|
|
1213
|
-
const route = routeFromIndexEntry(rootRunId,
|
|
1171
|
+
for (const entry of fs5.readdirSync(path6.join(routeIndexRoot(), rootEntry))) {
|
|
1172
|
+
const route = routeFromIndexEntry(rootRunId, path6.join(routeIndexRoot(), rootEntry, entry));
|
|
1214
1173
|
if (route) routes.push(route);
|
|
1215
1174
|
}
|
|
1216
1175
|
} catch {
|
|
@@ -1237,7 +1196,7 @@ function findNestedRunMatchesById(id, options = {}) {
|
|
|
1237
1196
|
function readNestedRegistry(route) {
|
|
1238
1197
|
validateRouteShape(route);
|
|
1239
1198
|
try {
|
|
1240
|
-
const parsed = JSON.parse(
|
|
1199
|
+
const parsed = JSON.parse(fs5.readFileSync(registryPath(route), "utf-8"));
|
|
1241
1200
|
return {
|
|
1242
1201
|
rootRunId: route.rootRunId,
|
|
1243
1202
|
updatedAt: typeof parsed.updatedAt === "number" ? parsed.updatedAt : 0,
|
|
@@ -1256,19 +1215,19 @@ function projectNestedEvents(route) {
|
|
|
1256
1215
|
let changed = false;
|
|
1257
1216
|
let entries = [];
|
|
1258
1217
|
try {
|
|
1259
|
-
entries =
|
|
1218
|
+
entries = fs5.readdirSync(route.eventSink).filter((entry) => entry.endsWith(".json") || entry.endsWith(".jsonl")).sort();
|
|
1260
1219
|
} catch (error) {
|
|
1261
1220
|
if (error.code !== "ENOENT") throw error;
|
|
1262
1221
|
}
|
|
1263
1222
|
for (const entry of entries) {
|
|
1264
1223
|
if (seen.has(entry)) continue;
|
|
1265
|
-
const eventPath =
|
|
1224
|
+
const eventPath = path6.join(route.eventSink, entry);
|
|
1266
1225
|
if (!containedPath(route.eventSink, eventPath)) continue;
|
|
1267
1226
|
let content;
|
|
1268
1227
|
try {
|
|
1269
|
-
const stat =
|
|
1228
|
+
const stat = fs5.statSync(eventPath);
|
|
1270
1229
|
if (!stat.isFile() || stat.size > MAX_EVENT_BYTES) continue;
|
|
1271
|
-
content =
|
|
1230
|
+
content = fs5.readFileSync(eventPath, "utf-8");
|
|
1272
1231
|
} catch {
|
|
1273
1232
|
continue;
|
|
1274
1233
|
}
|
|
@@ -1288,15 +1247,15 @@ function projectNestedEvents(route) {
|
|
|
1288
1247
|
registry = { ...registry, processedEvents: retainedEvents };
|
|
1289
1248
|
writeAtomicJson(registryPath(route), registry);
|
|
1290
1249
|
for (const entry of evictedEvents) {
|
|
1291
|
-
const eventPath =
|
|
1250
|
+
const eventPath = path6.join(route.eventSink, entry);
|
|
1292
1251
|
if (!containedPath(route.eventSink, eventPath)) continue;
|
|
1293
1252
|
try {
|
|
1294
|
-
const stat =
|
|
1253
|
+
const stat = fs5.statSync(eventPath);
|
|
1295
1254
|
if (!stat.isFile() || stat.size > MAX_EVENT_BYTES) continue;
|
|
1296
|
-
const content =
|
|
1255
|
+
const content = fs5.readFileSync(eventPath, "utf-8");
|
|
1297
1256
|
const hasStatusRecord = parseNestedEventRecords(content, route).length > 0;
|
|
1298
1257
|
const hasControlResult = content.split("\n").some((line) => line.trim() && parseControlResult(line.trim(), route));
|
|
1299
|
-
if (hasStatusRecord && !hasControlResult)
|
|
1258
|
+
if (hasStatusRecord && !hasControlResult) fs5.unlinkSync(eventPath);
|
|
1300
1259
|
} catch {
|
|
1301
1260
|
}
|
|
1302
1261
|
}
|
|
@@ -1307,12 +1266,12 @@ function writeRouteRecord(dir, ts, payload) {
|
|
|
1307
1266
|
const content = `${JSON.stringify(payload)}
|
|
1308
1267
|
`;
|
|
1309
1268
|
if (Buffer.byteLength(content, "utf-8") > MAX_EVENT_BYTES) throw new Error("Nested route record exceeds the maximum size.");
|
|
1310
|
-
|
|
1311
|
-
const name = `${String(ts).padStart(13, "0")}-${
|
|
1312
|
-
const tmp =
|
|
1313
|
-
const finalPath =
|
|
1314
|
-
|
|
1315
|
-
|
|
1269
|
+
fs5.mkdirSync(dir, { recursive: true, mode: 448 });
|
|
1270
|
+
const name = `${String(ts).padStart(13, "0")}-${randomUUID()}.json`;
|
|
1271
|
+
const tmp = path6.join(dir, `.${name}.tmp`);
|
|
1272
|
+
const finalPath = path6.join(dir, name);
|
|
1273
|
+
fs5.writeFileSync(tmp, content, { mode: 384 });
|
|
1274
|
+
fs5.renameSync(tmp, finalPath);
|
|
1316
1275
|
return finalPath;
|
|
1317
1276
|
}
|
|
1318
1277
|
function writeNestedEvent(route, event) {
|
|
@@ -1397,18 +1356,18 @@ function readNestedControlRequests(route) {
|
|
|
1397
1356
|
validateRouteShape(route);
|
|
1398
1357
|
let entries = [];
|
|
1399
1358
|
try {
|
|
1400
|
-
entries =
|
|
1359
|
+
entries = fs5.readdirSync(route.controlInbox).filter((entry) => entry.endsWith(".json")).sort();
|
|
1401
1360
|
} catch (error) {
|
|
1402
1361
|
if (error.code !== "ENOENT") throw error;
|
|
1403
1362
|
}
|
|
1404
1363
|
const requests = [];
|
|
1405
1364
|
for (const entry of entries) {
|
|
1406
|
-
const filePath =
|
|
1365
|
+
const filePath = path6.join(route.controlInbox, entry);
|
|
1407
1366
|
if (!containedPath(route.controlInbox, filePath)) continue;
|
|
1408
1367
|
try {
|
|
1409
|
-
const stat =
|
|
1368
|
+
const stat = fs5.statSync(filePath);
|
|
1410
1369
|
if (!stat.isFile() || stat.size > MAX_EVENT_BYTES) continue;
|
|
1411
|
-
const request = parseControlRequest(
|
|
1370
|
+
const request = parseControlRequest(fs5.readFileSync(filePath, "utf-8"), route);
|
|
1412
1371
|
if (request) requests.push({ ...request, filePath });
|
|
1413
1372
|
} catch {
|
|
1414
1373
|
continue;
|
|
@@ -1433,9 +1392,9 @@ function writeNestedControlResult(route, result) {
|
|
|
1433
1392
|
function readControlResultsFromFile(route, eventPath) {
|
|
1434
1393
|
if (!containedPath(route.eventSink, eventPath)) return [];
|
|
1435
1394
|
try {
|
|
1436
|
-
const stat =
|
|
1395
|
+
const stat = fs5.statSync(eventPath);
|
|
1437
1396
|
if (!stat.isFile() || stat.size > MAX_EVENT_BYTES) return [];
|
|
1438
|
-
const content =
|
|
1397
|
+
const content = fs5.readFileSync(eventPath, "utf-8");
|
|
1439
1398
|
const lines = content.includes("\n") ? content.split("\n").filter((line) => line.trim()) : [content];
|
|
1440
1399
|
return lines.map((line) => parseControlResult(line, route)).filter((result) => Boolean(result));
|
|
1441
1400
|
} catch {
|
|
@@ -1445,7 +1404,7 @@ function readControlResultsFromFile(route, eventPath) {
|
|
|
1445
1404
|
function listNestedEventFiles(route) {
|
|
1446
1405
|
validateRouteShape(route);
|
|
1447
1406
|
try {
|
|
1448
|
-
return
|
|
1407
|
+
return fs5.readdirSync(route.eventSink).filter((entry) => entry.endsWith(".json") || entry.endsWith(".jsonl"));
|
|
1449
1408
|
} catch (error) {
|
|
1450
1409
|
if (error.code === "ENOENT") return [];
|
|
1451
1410
|
throw error;
|
|
@@ -1457,7 +1416,7 @@ function snapshotNestedEventFiles(route) {
|
|
|
1457
1416
|
function findNestedControlResult(route, requestId, targetRunId, ignoredFiles) {
|
|
1458
1417
|
const entries = listNestedEventFiles(route).filter((entry) => !ignoredFiles.has(entry)).sort().reverse();
|
|
1459
1418
|
for (const entry of entries) {
|
|
1460
|
-
const result = readControlResultsFromFile(route,
|
|
1419
|
+
const result = readControlResultsFromFile(route, path6.join(route.eventSink, entry)).find((candidate) => candidate.requestId === requestId && candidate.targetRunId === targetRunId);
|
|
1461
1420
|
if (result) return result;
|
|
1462
1421
|
}
|
|
1463
1422
|
return void 0;
|
|
@@ -1572,13 +1531,13 @@ function nestedSummaryFromAsyncStatus(status, asyncDir, fallback) {
|
|
|
1572
1531
|
function nestedRunScope(rootRunId) {
|
|
1573
1532
|
assertSafeId("rootRunId", rootRunId);
|
|
1574
1533
|
return {
|
|
1575
|
-
asyncDirRoot:
|
|
1576
|
-
resultsDir:
|
|
1534
|
+
asyncDirRoot: path6.join(TEMP_ROOT_DIR, "nested-subagent-runs", rootRunId),
|
|
1535
|
+
resultsDir: path6.join(DIRS.results, "nested", rootRunId)
|
|
1577
1536
|
};
|
|
1578
1537
|
}
|
|
1579
1538
|
function nestedResultsPath(rootRunId, id) {
|
|
1580
1539
|
assertSafeId("id", id);
|
|
1581
|
-
return
|
|
1540
|
+
return path6.join(nestedRunScope(rootRunId).resultsDir, `${id}.json`);
|
|
1582
1541
|
}
|
|
1583
1542
|
|
|
1584
1543
|
// src/runs/shared/host-step-status.ts
|
|
@@ -1801,9 +1760,9 @@ function checkRequiredRunnerLauncher(agent, launcherName, required) {
|
|
|
1801
1760
|
|
|
1802
1761
|
// src/workflows/host-command.ts
|
|
1803
1762
|
import { spawn } from "node:child_process";
|
|
1804
|
-
import { randomUUID as
|
|
1805
|
-
import * as
|
|
1806
|
-
import * as
|
|
1763
|
+
import { randomUUID as randomUUID2 } from "node:crypto";
|
|
1764
|
+
import * as fs6 from "node:fs";
|
|
1765
|
+
import * as path7 from "node:path";
|
|
1807
1766
|
var MAX_COMMAND_BYTES = 16 * 1024;
|
|
1808
1767
|
var MAX_OUTPUT_PATH_BYTES = 240;
|
|
1809
1768
|
var MAX_CAPTURE_BYTES = 1024 * 1024;
|
|
@@ -1835,7 +1794,7 @@ function normalizeWorkflowHostCommandParams(value, label = "runs.host params") {
|
|
|
1835
1794
|
if (params.output !== void 0) {
|
|
1836
1795
|
if (typeof params.output !== "string" || !params.output.trim()) throw new Error(`${label}.output must be a non-empty relative path.`);
|
|
1837
1796
|
output = params.output.trim();
|
|
1838
|
-
if (
|
|
1797
|
+
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.`);
|
|
1839
1798
|
}
|
|
1840
1799
|
if (params.role !== void 0 && params.role !== "ci" && params.role !== "gate") throw new Error(`${label}.role must be 'ci' or 'gate'.`);
|
|
1841
1800
|
let provider;
|
|
@@ -1860,19 +1819,19 @@ function resolveWorkflowHostOutputClaimPath(outputPath) {
|
|
|
1860
1819
|
return resolveSingleOutputClaimPath(outputPath);
|
|
1861
1820
|
}
|
|
1862
1821
|
function assertSafeExplicitOutput(cwd, outputPath, key) {
|
|
1863
|
-
const root =
|
|
1864
|
-
const outputParent =
|
|
1822
|
+
const root = fs6.realpathSync(cwd);
|
|
1823
|
+
const outputParent = path7.dirname(outputPath);
|
|
1865
1824
|
let existingParent = outputParent;
|
|
1866
|
-
while (!
|
|
1867
|
-
const existingParentReal =
|
|
1868
|
-
const existingRelative =
|
|
1869
|
-
if (existingRelative === ".." || existingRelative.startsWith(`..${
|
|
1870
|
-
|
|
1871
|
-
const parent =
|
|
1872
|
-
const relative4 =
|
|
1873
|
-
if (relative4 === ".." || relative4.startsWith(`..${
|
|
1825
|
+
while (!fs6.existsSync(existingParent)) existingParent = path7.dirname(existingParent);
|
|
1826
|
+
const existingParentReal = fs6.realpathSync(existingParent);
|
|
1827
|
+
const existingRelative = path7.relative(root, existingParentReal);
|
|
1828
|
+
if (existingRelative === ".." || existingRelative.startsWith(`..${path7.sep}`) || path7.isAbsolute(existingRelative)) throw new Error(`runs.host('${key}') output resolves outside the workflow cwd.`);
|
|
1829
|
+
fs6.mkdirSync(outputParent, { recursive: true });
|
|
1830
|
+
const parent = fs6.realpathSync(outputParent);
|
|
1831
|
+
const relative4 = path7.relative(root, parent);
|
|
1832
|
+
if (relative4 === ".." || relative4.startsWith(`..${path7.sep}`) || path7.isAbsolute(relative4)) throw new Error(`runs.host('${key}') output resolves outside the workflow cwd.`);
|
|
1874
1833
|
try {
|
|
1875
|
-
const stat =
|
|
1834
|
+
const stat = fs6.lstatSync(outputPath);
|
|
1876
1835
|
if (!stat.isFile() || stat.nlink > 1) throw new Error(`runs.host('${key}') output must be a regular, non-linked file path.`);
|
|
1877
1836
|
} catch (error) {
|
|
1878
1837
|
if (error.code !== "ENOENT") throw error;
|
|
@@ -1880,24 +1839,24 @@ function assertSafeExplicitOutput(cwd, outputPath, key) {
|
|
|
1880
1839
|
return parent;
|
|
1881
1840
|
}
|
|
1882
1841
|
function writeExplicitOutput(outputParent, outputPath, capture, key) {
|
|
1883
|
-
const destination =
|
|
1884
|
-
const temporaryPath =
|
|
1842
|
+
const destination = path7.join(outputParent, path7.basename(outputPath));
|
|
1843
|
+
const temporaryPath = path7.join(outputParent, `.pi-host-output-${process.pid}-${randomUUID2()}.tmp`);
|
|
1885
1844
|
let descriptor;
|
|
1886
1845
|
try {
|
|
1887
|
-
descriptor =
|
|
1888
|
-
|
|
1889
|
-
|
|
1846
|
+
descriptor = fs6.openSync(temporaryPath, fs6.constants.O_WRONLY | fs6.constants.O_CREAT | fs6.constants.O_EXCL, 384);
|
|
1847
|
+
fs6.writeFileSync(descriptor, capture, { encoding: "utf8" });
|
|
1848
|
+
fs6.closeSync(descriptor);
|
|
1890
1849
|
descriptor = void 0;
|
|
1891
|
-
|
|
1892
|
-
runFileSystemOperationWithRetry(() =>
|
|
1850
|
+
fs6.chmodSync(temporaryPath, 384);
|
|
1851
|
+
runFileSystemOperationWithRetry(() => fs6.renameSync(temporaryPath, destination), {
|
|
1893
1852
|
retryDelaysMs: process.platform === "win32" ? DEFAULT_FILE_SYSTEM_RETRY_DELAYS_MS : []
|
|
1894
1853
|
});
|
|
1895
1854
|
} catch (error) {
|
|
1896
1855
|
throw new Error(`runs.host('${key}') could not atomically replace its output.`, { cause: error instanceof Error ? error : void 0 });
|
|
1897
1856
|
} finally {
|
|
1898
|
-
if (descriptor !== void 0)
|
|
1857
|
+
if (descriptor !== void 0) fs6.closeSync(descriptor);
|
|
1899
1858
|
try {
|
|
1900
|
-
|
|
1859
|
+
fs6.unlinkSync(temporaryPath);
|
|
1901
1860
|
} catch (error) {
|
|
1902
1861
|
if (error.code !== "ENOENT") throw error;
|
|
1903
1862
|
}
|
|
@@ -1905,22 +1864,22 @@ function writeExplicitOutput(outputParent, outputPath, capture, key) {
|
|
|
1905
1864
|
}
|
|
1906
1865
|
function terminateProcessTree(pid, controller) {
|
|
1907
1866
|
if (process.platform !== "win32") return controller.terminate();
|
|
1908
|
-
return new Promise((
|
|
1867
|
+
return new Promise((resolve5) => {
|
|
1909
1868
|
const cleanup = spawn("taskkill", ["/PID", String(pid), "/T", "/F"], { stdio: "ignore", windowsHide: true });
|
|
1910
1869
|
cleanup.once("error", () => {
|
|
1911
|
-
void controller.terminate().then(
|
|
1870
|
+
void controller.terminate().then(resolve5);
|
|
1912
1871
|
});
|
|
1913
1872
|
cleanup.once("close", () => {
|
|
1914
|
-
void controller.terminate().then(
|
|
1873
|
+
void controller.terminate().then(resolve5);
|
|
1915
1874
|
});
|
|
1916
1875
|
});
|
|
1917
1876
|
}
|
|
1918
1877
|
async function executeWorkflowHostCommand(input) {
|
|
1919
|
-
const outputPath = input.params.output ?
|
|
1920
|
-
const relative4 =
|
|
1921
|
-
if (input.params.output && (relative4 === "" || relative4 === ".." || relative4.startsWith(`..${
|
|
1878
|
+
const outputPath = input.params.output ? path7.resolve(input.cwd, input.params.output) : input.defaultOutputPath;
|
|
1879
|
+
const relative4 = path7.relative(input.cwd, outputPath);
|
|
1880
|
+
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.`);
|
|
1922
1881
|
const explicitOutputParent = input.params.output ? assertSafeExplicitOutput(input.cwd, outputPath, input.key) : void 0;
|
|
1923
|
-
if (!input.params.output)
|
|
1882
|
+
if (!input.params.output) fs6.mkdirSync(path7.dirname(outputPath), { recursive: true });
|
|
1924
1883
|
const startedAt = Date.now();
|
|
1925
1884
|
let stdout = "";
|
|
1926
1885
|
let stderr = "";
|
|
@@ -1928,7 +1887,7 @@ async function executeWorkflowHostCommand(input) {
|
|
|
1928
1887
|
let timedOut = false;
|
|
1929
1888
|
let stopped = false;
|
|
1930
1889
|
let settled = false;
|
|
1931
|
-
return new Promise((
|
|
1890
|
+
return new Promise((resolve5, reject) => {
|
|
1932
1891
|
const child = spawn(quoteExecutableForShell(input.params.command), {
|
|
1933
1892
|
cwd: input.cwd,
|
|
1934
1893
|
env: process.env,
|
|
@@ -1978,13 +1937,13 @@ async function executeWorkflowHostCommand(input) {
|
|
|
1978
1937
|
if (currentParent !== explicitOutputParent) throw new Error(`output parent changed while the command was running.`);
|
|
1979
1938
|
writeExplicitOutput(explicitOutputParent, outputPath, capture, input.key);
|
|
1980
1939
|
} else {
|
|
1981
|
-
|
|
1940
|
+
fs6.writeFileSync(outputPath, capture, { encoding: "utf8", mode: 384 });
|
|
1982
1941
|
}
|
|
1983
1942
|
} catch (writeError) {
|
|
1984
1943
|
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 }));
|
|
1985
1944
|
return;
|
|
1986
1945
|
}
|
|
1987
|
-
|
|
1946
|
+
resolve5({ key: input.key, kind: "command", ok: state === "passed", state, exitCode, stdout, stderr, outputPath, durationMs: Date.now() - startedAt, ...error ? { error } : {} });
|
|
1988
1947
|
};
|
|
1989
1948
|
child.on("close", (code) => {
|
|
1990
1949
|
void finish(code);
|
|
@@ -1996,15 +1955,15 @@ async function executeWorkflowHostCommand(input) {
|
|
|
1996
1955
|
}
|
|
1997
1956
|
|
|
1998
1957
|
// src/workflows/scripted-workflow.ts
|
|
1999
|
-
import { accessSync, constants as constants2, readFileSync as
|
|
1958
|
+
import { accessSync, constants as constants2, readFileSync as readFileSync5, realpathSync as realpathSync3, statSync as statSync4 } from "node:fs";
|
|
2000
1959
|
import { createRequire } from "node:module";
|
|
2001
|
-
import { dirname as
|
|
1960
|
+
import { dirname as dirname6, resolve as resolvePath } from "node:path";
|
|
2002
1961
|
|
|
2003
1962
|
// src/workflows/workflow-script-worker.ts
|
|
2004
1963
|
import { fork } from "node:child_process";
|
|
2005
1964
|
import { EventEmitter } from "node:events";
|
|
2006
|
-
import { realpathSync as
|
|
2007
|
-
import { dirname as
|
|
1965
|
+
import { realpathSync as realpathSync2 } from "node:fs";
|
|
1966
|
+
import { dirname as dirname5 } from "node:path";
|
|
2008
1967
|
import { fileURLToPath } from "node:url";
|
|
2009
1968
|
import { Worker } from "node:worker_threads";
|
|
2010
1969
|
var WORKFLOW_WORKER_URL = new URL("../../workflow-script-worker.cjs", new URL("../src/workflows/workflow-script-worker.js", import.meta.url).href);
|
|
@@ -2016,17 +1975,17 @@ var WorkflowScriptProcess = class extends EventEmitter {
|
|
|
2016
1975
|
stderr = "";
|
|
2017
1976
|
constructor(acornPath) {
|
|
2018
1977
|
super();
|
|
2019
|
-
const acorn =
|
|
2020
|
-
this.child = fork(WORKFLOW_PROCESS_URL, [acorn], {
|
|
1978
|
+
const acorn = realpathSync2(acornPath);
|
|
1979
|
+
this.child = fork(fileURLToPath(WORKFLOW_PROCESS_URL), [acorn], {
|
|
2021
1980
|
// Under --permission, Node lets worker threads read everything under the process cwd, so the cwd must
|
|
2022
1981
|
// hold only public files: acorn's own directory. It also never holds a caller's cwd open on Windows.
|
|
2023
|
-
cwd:
|
|
1982
|
+
cwd: dirname5(acorn),
|
|
2024
1983
|
// No inherited execArgv or NODE_OPTIONS. Only the supervisor may create a worker.
|
|
2025
1984
|
execArgv: [
|
|
2026
1985
|
"--permission",
|
|
2027
1986
|
"--allow-worker",
|
|
2028
|
-
`--allow-fs-read=${
|
|
2029
|
-
`--allow-fs-read=${
|
|
1987
|
+
`--allow-fs-read=${realpathSync2(fileURLToPath(WORKFLOW_PROCESS_URL))}`,
|
|
1988
|
+
`--allow-fs-read=${realpathSync2(fileURLToPath(WORKFLOW_WORKER_URL))}`,
|
|
2030
1989
|
`--allow-fs-read=${acorn}`
|
|
2031
1990
|
],
|
|
2032
1991
|
env: process.platform === "win32" && process.env.SystemRoot ? { SystemRoot: process.env.SystemRoot } : {},
|
|
@@ -2063,8 +2022,8 @@ var WorkflowScriptProcess = class extends EventEmitter {
|
|
|
2063
2022
|
async terminate() {
|
|
2064
2023
|
if (this.exitCode !== void 0) return this.exitCode;
|
|
2065
2024
|
this.stopping = true;
|
|
2066
|
-
return await new Promise((
|
|
2067
|
-
this.once("exit",
|
|
2025
|
+
return await new Promise((resolve5) => {
|
|
2026
|
+
this.once("exit", resolve5);
|
|
2068
2027
|
this.child.kill("SIGKILL");
|
|
2069
2028
|
});
|
|
2070
2029
|
}
|
|
@@ -2084,6 +2043,7 @@ function validGitRef(ref) {
|
|
|
2084
2043
|
}
|
|
2085
2044
|
var requireFromPackage = createRequire(new URL("../src/workflows/scripted-workflow.js", import.meta.url).href);
|
|
2086
2045
|
var WORKFLOW_ASSEMBLY_FLUSH_TIMEOUT_MS = 5e3;
|
|
2046
|
+
var WORKFLOW_DRAIN_CHILD_MESSAGE = "Workflow draining; child not started.";
|
|
2087
2047
|
function isWorkflowScriptFailureKind(value) {
|
|
2088
2048
|
return value === "validation" || value === "script" || value === "child" || value === "return-serialization" || value === "timeout" || value === "detached-child" || value === "runtime";
|
|
2089
2049
|
}
|
|
@@ -2343,25 +2303,25 @@ function omitNonJsonWorkflowResultMetadata(value) {
|
|
|
2343
2303
|
return safeResult;
|
|
2344
2304
|
}
|
|
2345
2305
|
}
|
|
2346
|
-
function assertWorkflowJsonValue(value,
|
|
2306
|
+
function assertWorkflowJsonValue(value, path16 = "value", seen = /* @__PURE__ */ new Set()) {
|
|
2347
2307
|
if (value === null || typeof value === "string" || typeof value === "boolean") return;
|
|
2348
2308
|
if (typeof value === "number") {
|
|
2349
|
-
if (!Number.isFinite(value)) throw new Error(`${
|
|
2309
|
+
if (!Number.isFinite(value)) throw new Error(`${path16} must contain only finite JSON numbers.`);
|
|
2350
2310
|
return;
|
|
2351
2311
|
}
|
|
2352
|
-
if (typeof value !== "object") throw new Error(`${
|
|
2353
|
-
if (seen.has(value)) throw new Error(`${
|
|
2312
|
+
if (typeof value !== "object") throw new Error(`${path16} must be a JSON value; received ${typeof value}.`);
|
|
2313
|
+
if (seen.has(value)) throw new Error(`${path16} must not contain cycles.`);
|
|
2354
2314
|
seen.add(value);
|
|
2355
2315
|
if (Array.isArray(value)) {
|
|
2356
2316
|
for (let index = 0; index < value.length; index++) {
|
|
2357
|
-
if (!Object.hasOwn(value, index)) throw new Error(`${
|
|
2358
|
-
assertWorkflowJsonValue(value[index], `${
|
|
2317
|
+
if (!Object.hasOwn(value, index)) throw new Error(`${path16} must not contain sparse array entries.`);
|
|
2318
|
+
assertWorkflowJsonValue(value[index], `${path16}[${index}]`, seen);
|
|
2359
2319
|
}
|
|
2360
2320
|
} else {
|
|
2361
2321
|
const prototype = Object.getPrototypeOf(value);
|
|
2362
|
-
if (prototype !== null && prototype !== Object.prototype) throw new Error(`${
|
|
2363
|
-
if (Object.getOwnPropertySymbols(value).length > 0) throw new Error(`${
|
|
2364
|
-
for (const [key, entry] of Object.entries(value)) assertWorkflowJsonValue(entry, `${
|
|
2322
|
+
if (prototype !== null && prototype !== Object.prototype) throw new Error(`${path16} must contain only plain JSON objects.`);
|
|
2323
|
+
if (Object.getOwnPropertySymbols(value).length > 0) throw new Error(`${path16} must not contain symbol keys.`);
|
|
2324
|
+
for (const [key, entry] of Object.entries(value)) assertWorkflowJsonValue(entry, `${path16}.${key}`, seen);
|
|
2365
2325
|
}
|
|
2366
2326
|
seen.delete(value);
|
|
2367
2327
|
}
|
|
@@ -2582,23 +2542,46 @@ function directObjectPropertyValue(node, name) {
|
|
|
2582
2542
|
}
|
|
2583
2543
|
return value;
|
|
2584
2544
|
}
|
|
2585
|
-
function
|
|
2586
|
-
|
|
2587
|
-
|
|
2588
|
-
|
|
2589
|
-
|
|
2545
|
+
function arrayElements(node) {
|
|
2546
|
+
return astNode(node) && node.type === "ArrayExpression" && Array.isArray(node.elements) ? node.elements : [];
|
|
2547
|
+
}
|
|
2548
|
+
function finalStaticProperty(node, name) {
|
|
2549
|
+
if (node.type !== "ObjectExpression" || !Array.isArray(node.properties)) return void 0;
|
|
2550
|
+
for (let index = node.properties.length - 1; index >= 0; index--) {
|
|
2551
|
+
const property = node.properties[index];
|
|
2552
|
+
if (!astNode(property) || property.type !== "Property") return void 0;
|
|
2590
2553
|
const key = staticPropertyKey(property);
|
|
2591
|
-
if (key === void 0) return
|
|
2592
|
-
if (key
|
|
2593
|
-
|
|
2594
|
-
|
|
2595
|
-
|
|
2596
|
-
|
|
2597
|
-
|
|
2598
|
-
|
|
2599
|
-
|
|
2554
|
+
if (key === void 0) return void 0;
|
|
2555
|
+
if (key === name) return property;
|
|
2556
|
+
}
|
|
2557
|
+
return void 0;
|
|
2558
|
+
}
|
|
2559
|
+
function validateStaticBaseRef(params, owner) {
|
|
2560
|
+
const property = finalStaticProperty(params, "baseRef");
|
|
2561
|
+
if (property?.kind !== "init" || !astNode(property.value)) return [];
|
|
2562
|
+
const valueNode = property.value;
|
|
2563
|
+
const value = literalString(valueNode);
|
|
2564
|
+
return (value !== void 0 || valueNode.type === "Literal") && !validGitRef(value) ? [{ message: `${owner} ${BASE_REF_VALIDATION_ERROR}`, ...nodeLocation(valueNode) }] : [];
|
|
2565
|
+
}
|
|
2566
|
+
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.';
|
|
2567
|
+
function staticLane(lane) {
|
|
2568
|
+
return astNode(lane) && lane.type === "ObjectExpression" && Array.isArray(lane.properties) && lane.properties.every((property) => astNode(property) && property.type === "Property" && staticPropertyKey(property) !== void 0);
|
|
2569
|
+
}
|
|
2570
|
+
function validateStaticLaneResumes(call) {
|
|
2571
|
+
const args = Array.isArray(call.arguments) ? call.arguments : [];
|
|
2572
|
+
const lanes = arrayElements(args[0]);
|
|
2573
|
+
const errors = [];
|
|
2574
|
+
for (let laneIndex = 0; laneIndex < lanes.length; laneIndex++) {
|
|
2575
|
+
const lane = lanes[laneIndex];
|
|
2576
|
+
if (astNode(lane) && lane.type === "SpreadElement") break;
|
|
2577
|
+
if (!staticLane(lane)) continue;
|
|
2578
|
+
const first = arrayElements(directObjectPropertyValue(lane, "stages"))[0];
|
|
2579
|
+
if (!astNode(first)) continue;
|
|
2580
|
+
const property = finalStaticProperty(first, "resume");
|
|
2581
|
+
const resume = property?.kind === "init" ? literalString(property.value) : void 0;
|
|
2582
|
+
if (resume !== void 0 && resume !== "previous") errors.push({ message: `runs.lanes lane ${laneIndex} stage 0 ${LANE_RETAINED_RESUME_ERROR}`, ...nodeLocation(first) });
|
|
2600
2583
|
}
|
|
2601
|
-
return
|
|
2584
|
+
return errors;
|
|
2602
2585
|
}
|
|
2603
2586
|
function staticChildAgentNode(params) {
|
|
2604
2587
|
if (!astNode(params) || params.type !== "ObjectExpression" || !Array.isArray(params.properties)) return void 0;
|
|
@@ -2613,9 +2596,7 @@ function staticChildAgentNode(params) {
|
|
|
2613
2596
|
}
|
|
2614
2597
|
function validateStaticChildAgents(call, agentNameError) {
|
|
2615
2598
|
const args = Array.isArray(call.arguments) ? call.arguments : [];
|
|
2616
|
-
const
|
|
2617
|
-
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);
|
|
2618
|
-
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 })) : []) : [];
|
|
2599
|
+
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 })) : []) : [];
|
|
2619
2600
|
const errors = [];
|
|
2620
2601
|
for (const child of children) {
|
|
2621
2602
|
const agentNode = staticChildAgentNode(child.params);
|
|
@@ -2627,8 +2608,7 @@ function validateStaticChildAgents(call, agentNameError) {
|
|
|
2627
2608
|
}
|
|
2628
2609
|
function directRunsAllKeys(call) {
|
|
2629
2610
|
const args = Array.isArray(call.arguments) ? call.arguments : [];
|
|
2630
|
-
|
|
2631
|
-
return items.flatMap((item) => {
|
|
2611
|
+
return arrayElements(args[0]).flatMap((item) => {
|
|
2632
2612
|
if (!astNode(item)) return [];
|
|
2633
2613
|
const keyNode = directObjectPropertyValue(item, "key");
|
|
2634
2614
|
const key = literalString(keyNode);
|
|
@@ -2807,15 +2787,14 @@ ${script}
|
|
|
2807
2787
|
errors.push({ message: `${subject}; every runs.all item needs a stable key, for example runs.all([{ key: "review", agent, task }]).`, ...nodeLocation(item.node) });
|
|
2808
2788
|
}
|
|
2809
2789
|
const args = Array.isArray(node.arguments) ? node.arguments : [];
|
|
2810
|
-
|
|
2811
|
-
|
|
2812
|
-
|
|
2813
|
-
|
|
2814
|
-
if (message) errors.push({ message: `runs.all item params are invalid: ${message}.`, ...nodeLocation(item) });
|
|
2815
|
-
}
|
|
2790
|
+
for (const item of arrayElements(args[0])) if (astNode(item)) {
|
|
2791
|
+
errors.push(...validateStaticBaseRef(item, "runs.all item"));
|
|
2792
|
+
const message = definitelyNonJson(item);
|
|
2793
|
+
if (message) errors.push({ message: `runs.all item params are invalid: ${message}.`, ...nodeLocation(item) });
|
|
2816
2794
|
}
|
|
2817
2795
|
}
|
|
2818
2796
|
if (directRunsCall(node, "host")) errors.push(...validateStaticHostCall(node));
|
|
2797
|
+
if (directRunsCall(node, "lanes") && !runsRebound) errors.push(...validateStaticLaneResumes(node));
|
|
2819
2798
|
if (agentNameError) errors.push(...validateStaticChildAgents(node, agentNameError));
|
|
2820
2799
|
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;
|
|
2821
2800
|
if (boundaryValue) {
|
|
@@ -2839,7 +2818,7 @@ ${script}
|
|
|
2839
2818
|
const keys = new Set(directRunsAllKeys(declaration.init.argument).map((entry) => entry.key));
|
|
2840
2819
|
if (keys.size === 0) continue;
|
|
2841
2820
|
const args = Array.isArray(declaration.init.argument.arguments) ? declaration.init.argument.arguments : [];
|
|
2842
|
-
const itemCount =
|
|
2821
|
+
const itemCount = arrayElements(args[0]).length;
|
|
2843
2822
|
const arrayResultShape = Array.from({ length: itemCount });
|
|
2844
2823
|
for (const later of laterStatements) {
|
|
2845
2824
|
walkAstWithoutShadowedIdentifier(later, name, (node) => {
|
|
@@ -2886,9 +2865,9 @@ function resolveWorkflowParserEntry() {
|
|
|
2886
2865
|
} catch (primaryError) {
|
|
2887
2866
|
try {
|
|
2888
2867
|
const manifestPath = requireFromPackage.resolve("acorn/package.json");
|
|
2889
|
-
const manifest = JSON.parse(
|
|
2868
|
+
const manifest = JSON.parse(readFileSync5(manifestPath, "utf8"));
|
|
2890
2869
|
const entry = typeof manifest.main === "string" && manifest.main ? manifest.main : "./dist/acorn.js";
|
|
2891
|
-
return resolvePath(
|
|
2870
|
+
return resolvePath(dirname6(manifestPath), entry);
|
|
2892
2871
|
} catch {
|
|
2893
2872
|
throw primaryError;
|
|
2894
2873
|
}
|
|
@@ -2933,7 +2912,7 @@ async function runWorkflowScript(options) {
|
|
|
2933
2912
|
if (options.processCwd !== void 0) {
|
|
2934
2913
|
let staleCwd = false;
|
|
2935
2914
|
try {
|
|
2936
|
-
|
|
2915
|
+
realpathSync3(process.cwd());
|
|
2937
2916
|
} catch (error) {
|
|
2938
2917
|
const code = typeof error === "object" && error !== null && "code" in error ? error.code : void 0;
|
|
2939
2918
|
if (code !== "ENOENT") throw new WorkflowScriptError("Workflow current cwd could not be validated.", emptyPartial(), "runtime", { cause: error });
|
|
@@ -2942,7 +2921,7 @@ async function runWorkflowScript(options) {
|
|
|
2942
2921
|
try {
|
|
2943
2922
|
if (staleCwd) process.chdir(options.processCwd);
|
|
2944
2923
|
else {
|
|
2945
|
-
const target =
|
|
2924
|
+
const target = realpathSync3(options.processCwd);
|
|
2946
2925
|
if (!statSync4(target).isDirectory()) {
|
|
2947
2926
|
const error = new Error(`ENOTDIR: not a directory, access '${target}'`);
|
|
2948
2927
|
error.code = "ENOTDIR";
|
|
@@ -2985,6 +2964,9 @@ async function runWorkflowScript(options) {
|
|
|
2985
2964
|
let acceptanceRecoveryBarrier;
|
|
2986
2965
|
let settled = false;
|
|
2987
2966
|
let finishing = false;
|
|
2967
|
+
let draining = false;
|
|
2968
|
+
let onDrained;
|
|
2969
|
+
const acquiredLaunches = /* @__PURE__ */ new Set();
|
|
2988
2970
|
let assemblyAbortRequested = false;
|
|
2989
2971
|
let assemblyFlushTimer;
|
|
2990
2972
|
let abortError;
|
|
@@ -3025,6 +3007,12 @@ async function runWorkflowScript(options) {
|
|
|
3025
3007
|
const recordAcceptanceRecoveryBarrier = (key, result) => {
|
|
3026
3008
|
if (isAcceptanceMetadataRecovery(result)) acceptanceRecoveryBarrier = { key };
|
|
3027
3009
|
};
|
|
3010
|
+
const drainIfIdle = () => {
|
|
3011
|
+
if (!onDrained || [...launches.keys()].some((key) => !children.has(key))) return;
|
|
3012
|
+
const done = onDrained;
|
|
3013
|
+
onDrained = void 0;
|
|
3014
|
+
done();
|
|
3015
|
+
};
|
|
3028
3016
|
const stopChild = (key, message = `Workflow child '${key}' stopped.`) => {
|
|
3029
3017
|
if (!launches.has(key) || children.has(key)) return false;
|
|
3030
3018
|
stoppedLaunches.add(key);
|
|
@@ -3042,8 +3030,19 @@ async function runWorkflowScript(options) {
|
|
|
3042
3030
|
error: message
|
|
3043
3031
|
});
|
|
3044
3032
|
traceChanged();
|
|
3033
|
+
drainIfIdle();
|
|
3045
3034
|
return true;
|
|
3046
3035
|
};
|
|
3036
|
+
const drain = (done) => {
|
|
3037
|
+
if (!draining) {
|
|
3038
|
+
draining = true;
|
|
3039
|
+
onDrained = done;
|
|
3040
|
+
}
|
|
3041
|
+
for (const key of launches.keys()) if (!acquiredLaunches.has(key)) stopChild(key, WORKFLOW_DRAIN_CHILD_MESSAGE);
|
|
3042
|
+
const started = [...launches.keys()].filter((key) => !children.has(key)).length;
|
|
3043
|
+
drainIfIdle();
|
|
3044
|
+
return started;
|
|
3045
|
+
};
|
|
3047
3046
|
const notifyChildSettled = (key, result) => {
|
|
3048
3047
|
if (result.state === "running" || !options.onChildSettled || !options.workflowRunId) return;
|
|
3049
3048
|
const outcome = result.ok ? "completed" : result.stopped ? "stopped" : result.detached ? "paused" : "failed";
|
|
@@ -3064,7 +3063,8 @@ async function runWorkflowScript(options) {
|
|
|
3064
3063
|
}
|
|
3065
3064
|
};
|
|
3066
3065
|
options.registerStopChild?.(stopChild);
|
|
3067
|
-
|
|
3066
|
+
options.registerDrain?.(drain);
|
|
3067
|
+
return await new Promise((resolve5, reject) => {
|
|
3068
3068
|
const finish = (outcome) => {
|
|
3069
3069
|
if (settled || finishing) return;
|
|
3070
3070
|
finishing = true;
|
|
@@ -3077,6 +3077,7 @@ async function runWorkflowScript(options) {
|
|
|
3077
3077
|
if (settled) return;
|
|
3078
3078
|
settled = true;
|
|
3079
3079
|
options.registerStopChild?.(void 0);
|
|
3080
|
+
options.registerDrain?.(void 0);
|
|
3080
3081
|
if (timer) clearTimeout(timer);
|
|
3081
3082
|
options.signal?.removeEventListener("abort", onAbort);
|
|
3082
3083
|
void worker.terminate();
|
|
@@ -3089,7 +3090,7 @@ async function runWorkflowScript(options) {
|
|
|
3089
3090
|
})() : void 0;
|
|
3090
3091
|
if ("error" in outcome) reject(new WorkflowScriptError(outcome.error.message, partial(), isWorkflowScriptFailureKind(outcome.error.workflowErrorKind) ? outcome.error.workflowErrorKind : void 0));
|
|
3091
3092
|
else if (completionError) reject(new WorkflowScriptError(completionError.message, partial(), "validation"));
|
|
3092
|
-
else
|
|
3093
|
+
else resolve5({ value: outcome.value, ...partial() });
|
|
3093
3094
|
});
|
|
3094
3095
|
};
|
|
3095
3096
|
const onAbort = () => {
|
|
@@ -3200,7 +3201,7 @@ async function runWorkflowScript(options) {
|
|
|
3200
3201
|
const respond = (promise2, responsePath, onBoundaryError) => {
|
|
3201
3202
|
void promise2.then(
|
|
3202
3203
|
(value) => {
|
|
3203
|
-
if (settled) return;
|
|
3204
|
+
if (settled || draining) return;
|
|
3204
3205
|
const normalized = responsePath ? omitNonJsonWorkflowResultMetadata(value) : omitUndefinedWorkflowValues(value);
|
|
3205
3206
|
if (!responsePath) {
|
|
3206
3207
|
worker.postMessage({ type: "response", callId: message.callId, ok: true, value: normalized });
|
|
@@ -3215,7 +3216,7 @@ async function runWorkflowScript(options) {
|
|
|
3215
3216
|
}
|
|
3216
3217
|
},
|
|
3217
3218
|
(error) => {
|
|
3218
|
-
if (!settled) {
|
|
3219
|
+
if (!settled && !draining) {
|
|
3219
3220
|
const errorKind = error instanceof Error ? error.workflowErrorKind : void 0;
|
|
3220
3221
|
worker.postMessage({ type: "response", callId: message.callId, ok: false, error: error instanceof Error ? error.message : String(error), ...isWorkflowScriptFailureKind(errorKind) ? { errorKind } : {} });
|
|
3221
3222
|
}
|
|
@@ -3299,6 +3300,7 @@ async function runWorkflowScript(options) {
|
|
|
3299
3300
|
return respond(Promise.reject(error));
|
|
3300
3301
|
}
|
|
3301
3302
|
if (acceptanceRecoveryBarrier) return respond(Promise.reject(new Error(recoveryBarrierMessage(acceptanceRecoveryBarrier.key, `runs.host('${key2}')`))));
|
|
3303
|
+
if (draining) return respond(Promise.reject(new Error(`runs.host('${key2}') refused: the workflow is draining.`)));
|
|
3302
3304
|
if (!options.host) return respond(Promise.reject(new Error("runs.host is unavailable in this host context.")));
|
|
3303
3305
|
if (hostCalls.size >= HOST_STEP_MAX_COUNT) return respond(Promise.reject(new Error(`workflowScript supports at most ${HOST_STEP_MAX_COUNT} runs.host calls.`)));
|
|
3304
3306
|
const startedAt2 = Date.now();
|
|
@@ -3417,7 +3419,7 @@ async function runWorkflowScript(options) {
|
|
|
3417
3419
|
return true;
|
|
3418
3420
|
});
|
|
3419
3421
|
admission = Promise.resolve().then(() => {
|
|
3420
|
-
if (settled || finishing) return;
|
|
3422
|
+
if (settled || finishing || draining) return;
|
|
3421
3423
|
for (const call of calls) assertRecoveryBarrierAllowsRun(call.key, call.params);
|
|
3422
3424
|
return options.admit?.(calls, childController.signal);
|
|
3423
3425
|
});
|
|
@@ -3425,6 +3427,7 @@ async function runWorkflowScript(options) {
|
|
|
3425
3427
|
}
|
|
3426
3428
|
let resolvedResumeLineage;
|
|
3427
3429
|
const promise = admission.then(async () => {
|
|
3430
|
+
if (draining) stopChild(key, WORKFLOW_DRAIN_CHILD_MESSAGE);
|
|
3428
3431
|
if (settled || finishing || stoppedLaunches.has(key)) {
|
|
3429
3432
|
const reason = childController.signal.reason;
|
|
3430
3433
|
const text = children.get(key)?.error ?? (reason instanceof Error ? reason.message : typeof reason === "string" ? reason : "Workflow script aborted.");
|
|
@@ -3458,6 +3461,7 @@ async function runWorkflowScript(options) {
|
|
|
3458
3461
|
const text = children.get(key)?.error ?? (reason instanceof Error ? reason.message : typeof reason === "string" ? reason : "Workflow script aborted.");
|
|
3459
3462
|
return stoppedChildResult(key, text);
|
|
3460
3463
|
}
|
|
3464
|
+
acquiredLaunches.add(key);
|
|
3461
3465
|
const result = await options.launch(key, launchParams, childSignal, { admitted: true, batch: batch !== void 0 });
|
|
3462
3466
|
const autoResumeParams = setupAbortResumeParams(params, result, childSignal);
|
|
3463
3467
|
if (!autoResumeParams) return result;
|
|
@@ -3487,6 +3491,7 @@ async function runWorkflowScript(options) {
|
|
|
3487
3491
|
trace.push(settledEntry);
|
|
3488
3492
|
traceChanged();
|
|
3489
3493
|
notifyChildSettled(key, normalized);
|
|
3494
|
+
drainIfIdle();
|
|
3490
3495
|
return normalized;
|
|
3491
3496
|
}, (error) => {
|
|
3492
3497
|
const text = error instanceof Error ? error.message : String(error);
|
|
@@ -3497,6 +3502,7 @@ async function runWorkflowScript(options) {
|
|
|
3497
3502
|
trace.push({ operation: "run", key, state: "failed", durationMs: Date.now() - startedAt, ...workflowStringMetadata(params), ...generatedLaneKey ? { generatedLaneKey } : {}, error: text });
|
|
3498
3503
|
traceChanged();
|
|
3499
3504
|
notifyChildSettled(key, failure);
|
|
3505
|
+
drainIfIdle();
|
|
3500
3506
|
return failure;
|
|
3501
3507
|
});
|
|
3502
3508
|
launches.set(key, { fingerprint, promise, observed: callObserved, ...generatedLaneKey ? { generatedLaneKey } : {} });
|
|
@@ -3510,10 +3516,10 @@ async function runWorkflowScript(options) {
|
|
|
3510
3516
|
}
|
|
3511
3517
|
|
|
3512
3518
|
// src/missions/store.ts
|
|
3513
|
-
import { createHash as
|
|
3514
|
-
import * as
|
|
3519
|
+
import { createHash as createHash2, randomUUID as randomUUID3 } from "node:crypto";
|
|
3520
|
+
import * as fs7 from "node:fs";
|
|
3515
3521
|
import * as os from "node:os";
|
|
3516
|
-
import * as
|
|
3522
|
+
import * as path8 from "node:path";
|
|
3517
3523
|
|
|
3518
3524
|
// src/missions/types.ts
|
|
3519
3525
|
var MISSION_STATUSES = [
|
|
@@ -3728,12 +3734,12 @@ function parseMissionRecord(value, source = "mission record") {
|
|
|
3728
3734
|
};
|
|
3729
3735
|
}
|
|
3730
3736
|
function expandConfiguredPath(value, projectRoot) {
|
|
3731
|
-
const expanded = value.startsWith("~/") ?
|
|
3732
|
-
return
|
|
3737
|
+
const expanded = value.startsWith("~/") ? path8.join(os.homedir(), value.slice(2)) : value;
|
|
3738
|
+
return path8.isAbsolute(expanded) ? path8.normalize(expanded) : path8.resolve(projectRoot, expanded);
|
|
3733
3739
|
}
|
|
3734
3740
|
function projectMissionDirectory(agentDir, projectRoot) {
|
|
3735
|
-
const projectKey =
|
|
3736
|
-
return
|
|
3741
|
+
const projectKey = createHash2("sha256").update(projectRoot).digest("hex");
|
|
3742
|
+
return path8.join(agentDir, "missions", "projects", projectKey);
|
|
3737
3743
|
}
|
|
3738
3744
|
function validateMissionStoreConfig(value, label = "config.missions") {
|
|
3739
3745
|
if (value === void 0) return void 0;
|
|
@@ -3763,23 +3769,23 @@ function canonicalProjectRoot(root) {
|
|
|
3763
3769
|
let current = root;
|
|
3764
3770
|
for (; ; ) {
|
|
3765
3771
|
try {
|
|
3766
|
-
return
|
|
3772
|
+
return path8.join(fs7.realpathSync.native(current), ...missing.reverse());
|
|
3767
3773
|
} catch (error) {
|
|
3768
3774
|
if (error.code !== "ENOENT") throw error;
|
|
3769
|
-
const parent =
|
|
3775
|
+
const parent = path8.dirname(current);
|
|
3770
3776
|
if (parent === current) return root;
|
|
3771
|
-
missing.push(
|
|
3777
|
+
missing.push(path8.basename(current));
|
|
3772
3778
|
current = parent;
|
|
3773
3779
|
}
|
|
3774
3780
|
}
|
|
3775
3781
|
}
|
|
3776
3782
|
function resolveMissionStoreLocation(input) {
|
|
3777
|
-
const givenRoot =
|
|
3783
|
+
const givenRoot = path8.resolve(input.projectRoot);
|
|
3778
3784
|
const configuredDir = input.config?.directory;
|
|
3779
3785
|
const projectRoot = configuredDir ? givenRoot : canonicalProjectRoot(givenRoot);
|
|
3780
3786
|
const agentDir = input.agentDir ?? getAgentDir();
|
|
3781
3787
|
const missionDir = configuredDir ? expandConfiguredPath(configuredDir, givenRoot) : projectMissionDirectory(agentDir, projectRoot);
|
|
3782
|
-
const globalIndexDir = input.config?.globalIndexDir ? expandConfiguredPath(input.config.globalIndexDir, givenRoot) :
|
|
3788
|
+
const globalIndexDir = input.config?.globalIndexDir ? expandConfiguredPath(input.config.globalIndexDir, givenRoot) : path8.join(agentDir, "missions", "index");
|
|
3783
3789
|
return {
|
|
3784
3790
|
projectRoot,
|
|
3785
3791
|
missionDir,
|
|
@@ -3789,7 +3795,7 @@ function resolveMissionStoreLocation(input) {
|
|
|
3789
3795
|
};
|
|
3790
3796
|
}
|
|
3791
3797
|
function missionRecordPath(location, missionId) {
|
|
3792
|
-
return
|
|
3798
|
+
return path8.join(location.missionDir, `${validateMissionId(missionId)}.json`);
|
|
3793
3799
|
}
|
|
3794
3800
|
function parseIndexEntry(value, source) {
|
|
3795
3801
|
const input = asObject(value, source);
|
|
@@ -3806,8 +3812,8 @@ function parseIndexEntry(value, source) {
|
|
|
3806
3812
|
};
|
|
3807
3813
|
}
|
|
3808
3814
|
function indexPath(location, record) {
|
|
3809
|
-
const key =
|
|
3810
|
-
return
|
|
3815
|
+
const key = createHash2("sha256").update(`${location.projectRoot}\0${record.id}`).digest("hex");
|
|
3816
|
+
return path8.join(location.globalIndexDir, `${key}.json`);
|
|
3811
3817
|
}
|
|
3812
3818
|
function writeMission(location, record) {
|
|
3813
3819
|
const validated = parseMissionRecord(record);
|
|
@@ -3832,9 +3838,9 @@ function pruneTerminalMissions(location, maxTerminal) {
|
|
|
3832
3838
|
const terminal3 = listMissions(location).records.filter((record) => TERMINAL_MISSION_STATUSES.has(record.status)).sort((left, right) => right.updatedAt.localeCompare(left.updatedAt));
|
|
3833
3839
|
for (const record of terminal3.slice(maxTerminal)) {
|
|
3834
3840
|
try {
|
|
3835
|
-
|
|
3836
|
-
|
|
3837
|
-
if (location.writeGlobalIndex)
|
|
3841
|
+
fs7.rmSync(missionRecordPath(location, record.id), { force: true });
|
|
3842
|
+
fs7.rmSync(path8.join(location.missionDir, record.id), { recursive: true, force: true });
|
|
3843
|
+
if (location.writeGlobalIndex) fs7.rmSync(indexPath(location, record), { force: true });
|
|
3838
3844
|
} catch {
|
|
3839
3845
|
}
|
|
3840
3846
|
}
|
|
@@ -3843,7 +3849,7 @@ function createMission(location, input, now = /* @__PURE__ */ new Date(), retain
|
|
|
3843
3849
|
const createdAt = now.toISOString();
|
|
3844
3850
|
const record = {
|
|
3845
3851
|
schemaVersion: 1,
|
|
3846
|
-
id:
|
|
3852
|
+
id: randomUUID3(),
|
|
3847
3853
|
title: requiredString(input.title, "mission.title").trim(),
|
|
3848
3854
|
objective: requiredString(input.objective, "mission.objective").trim(),
|
|
3849
3855
|
...input.goal === true ? { goal: { status: "active" } } : {},
|
|
@@ -3881,7 +3887,7 @@ function readMission(location, missionId) {
|
|
|
3881
3887
|
const filePath = missionRecordPath(location, missionId);
|
|
3882
3888
|
let raw;
|
|
3883
3889
|
try {
|
|
3884
|
-
raw =
|
|
3890
|
+
raw = fs7.readFileSync(filePath, "utf-8");
|
|
3885
3891
|
} catch (error) {
|
|
3886
3892
|
if (error.code === "ENOENT") throw new MissionNotFoundError(missionId, location);
|
|
3887
3893
|
throw error;
|
|
@@ -3893,13 +3899,13 @@ function readMission(location, missionId) {
|
|
|
3893
3899
|
}
|
|
3894
3900
|
}
|
|
3895
3901
|
function listMissions(location) {
|
|
3896
|
-
if (!
|
|
3902
|
+
if (!fs7.existsSync(location.missionDir)) return { records: [], warnings: [] };
|
|
3897
3903
|
const records = [];
|
|
3898
3904
|
const warnings = [];
|
|
3899
|
-
for (const name of
|
|
3900
|
-
const filePath =
|
|
3905
|
+
for (const name of fs7.readdirSync(location.missionDir).filter((item) => item.endsWith(".json")).sort()) {
|
|
3906
|
+
const filePath = path8.join(location.missionDir, name);
|
|
3901
3907
|
try {
|
|
3902
|
-
records.push(parseMissionRecord(JSON.parse(
|
|
3908
|
+
records.push(parseMissionRecord(JSON.parse(fs7.readFileSync(filePath, "utf-8")), filePath));
|
|
3903
3909
|
} catch (error) {
|
|
3904
3910
|
warnings.push(`Skipped corrupt mission '${filePath}': ${error instanceof Error ? error.message : String(error)}`);
|
|
3905
3911
|
}
|
|
@@ -3941,7 +3947,7 @@ function updateMission(location, missionId, update, now = /* @__PURE__ */ new Da
|
|
|
3941
3947
|
const artifacts = [...current.artifacts];
|
|
3942
3948
|
for (const candidate of update.addArtifacts ?? []) {
|
|
3943
3949
|
const artifact = parseArtifact(candidate, "mission.update.addArtifacts[]");
|
|
3944
|
-
const existingIndex = artifacts.findIndex((item) => item.kind === artifact.kind &&
|
|
3950
|
+
const existingIndex = artifacts.findIndex((item) => item.kind === artifact.kind && path8.resolve(item.path) === path8.resolve(artifact.path));
|
|
3945
3951
|
if (existingIndex === -1) artifacts.push(artifact);
|
|
3946
3952
|
else artifacts[existingIndex] = { ...artifacts[existingIndex], ...artifact };
|
|
3947
3953
|
}
|
|
@@ -3956,7 +3962,7 @@ function updateMission(location, missionId, update, now = /* @__PURE__ */ new Da
|
|
|
3956
3962
|
const decisions = [
|
|
3957
3963
|
...current.decisions,
|
|
3958
3964
|
...(update.addDecisions ?? []).map((decision) => ({
|
|
3959
|
-
id:
|
|
3965
|
+
id: randomUUID3(),
|
|
3960
3966
|
status: "open",
|
|
3961
3967
|
title: requiredString(decision.title, "mission.update.addDecisions[].title"),
|
|
3962
3968
|
createdAt,
|
|
@@ -4011,15 +4017,15 @@ function updateMission(location, missionId, update, now = /* @__PURE__ */ new Da
|
|
|
4011
4017
|
return updated;
|
|
4012
4018
|
}
|
|
4013
4019
|
function listGlobalMissions(globalIndexDir) {
|
|
4014
|
-
if (!
|
|
4020
|
+
if (!fs7.existsSync(globalIndexDir)) return { entries: [], warnings: [] };
|
|
4015
4021
|
const entries = [];
|
|
4016
4022
|
const warnings = [];
|
|
4017
|
-
for (const name of
|
|
4018
|
-
const filePath =
|
|
4023
|
+
for (const name of fs7.readdirSync(globalIndexDir).filter((item) => item.endsWith(".json")).sort()) {
|
|
4024
|
+
const filePath = path8.join(globalIndexDir, name);
|
|
4019
4025
|
try {
|
|
4020
|
-
const entry = parseIndexEntry(JSON.parse(
|
|
4026
|
+
const entry = parseIndexEntry(JSON.parse(fs7.readFileSync(filePath, "utf-8")), filePath);
|
|
4021
4027
|
try {
|
|
4022
|
-
const record = parseMissionRecord(JSON.parse(
|
|
4028
|
+
const record = parseMissionRecord(JSON.parse(fs7.readFileSync(entry.recordPath, "utf-8")), entry.recordPath);
|
|
4023
4029
|
if (record.id !== entry.missionId) throw new Error(`record id '${record.id}' does not match index id '${entry.missionId}'`);
|
|
4024
4030
|
const projection = {
|
|
4025
4031
|
...entry,
|
|
@@ -4034,7 +4040,7 @@ function listGlobalMissions(globalIndexDir) {
|
|
|
4034
4040
|
} catch (error) {
|
|
4035
4041
|
if (error.code === "ENOENT") {
|
|
4036
4042
|
try {
|
|
4037
|
-
|
|
4043
|
+
fs7.rmSync(filePath, { force: true });
|
|
4038
4044
|
warnings.push(`Removed stale global mission pointer '${filePath}' because '${entry.recordPath}' no longer exists.`);
|
|
4039
4045
|
} catch (removeError) {
|
|
4040
4046
|
warnings.push(`Failed to remove stale global mission pointer '${filePath}': ${removeError instanceof Error ? removeError.message : String(removeError)}`);
|
|
@@ -4053,14 +4059,14 @@ function listGlobalMissions(globalIndexDir) {
|
|
|
4053
4059
|
|
|
4054
4060
|
// src/missions/workflow-state.ts
|
|
4055
4061
|
import { execFileSync } from "node:child_process";
|
|
4056
|
-
import { randomUUID as
|
|
4057
|
-
import * as
|
|
4058
|
-
import * as
|
|
4062
|
+
import { randomUUID as randomUUID4 } from "node:crypto";
|
|
4063
|
+
import * as fs8 from "node:fs";
|
|
4064
|
+
import * as path9 from "node:path";
|
|
4059
4065
|
var STATE_KEY_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
|
|
4060
4066
|
var STATE_LOCK_STALE_MS = 6e4;
|
|
4061
4067
|
var MISSION_STATE_MAX_BYTES = 256 * 1024;
|
|
4062
4068
|
function missionStatePath(location, missionId) {
|
|
4063
|
-
return
|
|
4069
|
+
return path9.join(location.missionDir, validateMissionId(missionId), "state.json");
|
|
4064
4070
|
}
|
|
4065
4071
|
function isProcessAlive(pid) {
|
|
4066
4072
|
try {
|
|
@@ -4072,7 +4078,7 @@ function isProcessAlive(pid) {
|
|
|
4072
4078
|
}
|
|
4073
4079
|
function linuxProcessStartKey(pid) {
|
|
4074
4080
|
try {
|
|
4075
|
-
const raw =
|
|
4081
|
+
const raw = fs8.readFileSync(`/proc/${pid}/stat`, "utf-8");
|
|
4076
4082
|
const tail = raw.slice(raw.lastIndexOf(")") + 2).trim().split(/\s+/);
|
|
4077
4083
|
return tail[19] ? `linux:${tail[19]}` : void 0;
|
|
4078
4084
|
} catch {
|
|
@@ -4108,7 +4114,7 @@ function computeProcessStartKey(pid) {
|
|
|
4108
4114
|
}
|
|
4109
4115
|
function readStateLockOwner(lockPath) {
|
|
4110
4116
|
try {
|
|
4111
|
-
const owner = JSON.parse(
|
|
4117
|
+
const owner = JSON.parse(fs8.readFileSync(path9.join(lockPath, "owner.json"), "utf-8"));
|
|
4112
4118
|
if (Number.isSafeInteger(owner.pid) && owner.pid > 0 && typeof owner.token === "string" && owner.token && Number.isSafeInteger(owner.createdAt)) {
|
|
4113
4119
|
return {
|
|
4114
4120
|
pid: owner.pid,
|
|
@@ -4134,7 +4140,7 @@ function stateLockIsStale(lockPath, options, now = Date.now()) {
|
|
|
4134
4140
|
return false;
|
|
4135
4141
|
}
|
|
4136
4142
|
try {
|
|
4137
|
-
return now -
|
|
4143
|
+
return now - fs8.statSync(lockPath).mtimeMs > STATE_LOCK_STALE_MS;
|
|
4138
4144
|
} catch (error) {
|
|
4139
4145
|
if (error.code === "ENOENT") return false;
|
|
4140
4146
|
throw error;
|
|
@@ -4143,11 +4149,11 @@ function stateLockIsStale(lockPath, options, now = Date.now()) {
|
|
|
4143
4149
|
function removeOwnedStateLock(lockPath, owner) {
|
|
4144
4150
|
const current = readStateLockOwner(lockPath);
|
|
4145
4151
|
if (current?.token !== owner.token) return;
|
|
4146
|
-
|
|
4152
|
+
fs8.rmSync(lockPath, { recursive: true, force: true });
|
|
4147
4153
|
}
|
|
4148
4154
|
function staleDirectoryExists(dirPath, now = Date.now()) {
|
|
4149
4155
|
try {
|
|
4150
|
-
return now -
|
|
4156
|
+
return now - fs8.statSync(dirPath).mtimeMs > STATE_LOCK_STALE_MS;
|
|
4151
4157
|
} catch (error) {
|
|
4152
4158
|
if (error.code === "ENOENT") return false;
|
|
4153
4159
|
throw error;
|
|
@@ -4155,7 +4161,7 @@ function staleDirectoryExists(dirPath, now = Date.now()) {
|
|
|
4155
4161
|
}
|
|
4156
4162
|
function tryMakeDirectory(dirPath, mode) {
|
|
4157
4163
|
try {
|
|
4158
|
-
|
|
4164
|
+
fs8.mkdirSync(dirPath, { mode });
|
|
4159
4165
|
return true;
|
|
4160
4166
|
} catch (error) {
|
|
4161
4167
|
if (error.code === "EEXIST") return false;
|
|
@@ -4171,21 +4177,21 @@ function reclaimStaleStateLock(lockPath, reclaimPath, options) {
|
|
|
4171
4177
|
if (!tryMakeDirectory(reclaimPath, 448)) return false;
|
|
4172
4178
|
try {
|
|
4173
4179
|
if (!stateLockIsStale(lockPath, options)) return false;
|
|
4174
|
-
|
|
4180
|
+
fs8.rmSync(lockPath, { recursive: true, force: true });
|
|
4175
4181
|
return true;
|
|
4176
4182
|
} finally {
|
|
4177
|
-
|
|
4183
|
+
fs8.rmSync(reclaimPath, { recursive: true, force: true });
|
|
4178
4184
|
}
|
|
4179
4185
|
}
|
|
4180
4186
|
function withStateFileLock(filePath, operation, options) {
|
|
4181
|
-
|
|
4187
|
+
fs8.mkdirSync(path9.dirname(filePath), { recursive: true });
|
|
4182
4188
|
const lockPath = `${filePath}.lock`;
|
|
4183
4189
|
const reclaimPath = `${lockPath}.reclaim`;
|
|
4184
4190
|
let owner;
|
|
4185
4191
|
for (let attempt = 0; ; attempt++) {
|
|
4186
|
-
if (
|
|
4192
|
+
if (fs8.existsSync(reclaimPath)) {
|
|
4187
4193
|
if (staleDirectoryExists(reclaimPath)) {
|
|
4188
|
-
|
|
4194
|
+
fs8.rmSync(reclaimPath, { recursive: true, force: true });
|
|
4189
4195
|
continue;
|
|
4190
4196
|
}
|
|
4191
4197
|
waitForStateLock(options.retryDelaysMs[attempt], lockPath);
|
|
@@ -4207,11 +4213,11 @@ function withStateFileLock(filePath, operation, options) {
|
|
|
4207
4213
|
continue;
|
|
4208
4214
|
}
|
|
4209
4215
|
const key = options.getProcessStartKey(process.pid);
|
|
4210
|
-
owner = { pid: process.pid, token:
|
|
4216
|
+
owner = { pid: process.pid, token: randomUUID4(), createdAt: Date.now(), ...key ? { processKey: key } : {} };
|
|
4211
4217
|
try {
|
|
4212
|
-
|
|
4218
|
+
fs8.writeFileSync(path9.join(lockPath, "owner.json"), JSON.stringify(owner), { encoding: "utf-8", mode: 384 });
|
|
4213
4219
|
} catch (error) {
|
|
4214
|
-
|
|
4220
|
+
fs8.rmSync(lockPath, { recursive: true, force: true });
|
|
4215
4221
|
owner = void 0;
|
|
4216
4222
|
throw error;
|
|
4217
4223
|
}
|
|
@@ -4241,7 +4247,7 @@ function createMissionWorkflowState(location, missionId, options = {}) {
|
|
|
4241
4247
|
const readStateFile = () => {
|
|
4242
4248
|
let raw;
|
|
4243
4249
|
try {
|
|
4244
|
-
raw =
|
|
4250
|
+
raw = fs8.readFileSync(filePath, "utf-8");
|
|
4245
4251
|
} catch (error) {
|
|
4246
4252
|
if (error.code === "ENOENT") return /* @__PURE__ */ Object.create(null);
|
|
4247
4253
|
throw new Error(`Failed to read mission state '${filePath}': ${error instanceof Error ? error.message : String(error)}`);
|
|
@@ -4286,13 +4292,13 @@ function createMissionWorkflowState(location, missionId, options = {}) {
|
|
|
4286
4292
|
}
|
|
4287
4293
|
|
|
4288
4294
|
// src/missions/actions.ts
|
|
4289
|
-
import * as fs11 from "node:fs";
|
|
4290
|
-
import * as path12 from "node:path";
|
|
4291
|
-
|
|
4292
|
-
// src/missions/lifecycle.ts
|
|
4293
4295
|
import * as fs10 from "node:fs";
|
|
4294
4296
|
import * as path11 from "node:path";
|
|
4295
|
-
|
|
4297
|
+
|
|
4298
|
+
// src/missions/lifecycle.ts
|
|
4299
|
+
import * as fs9 from "node:fs";
|
|
4300
|
+
import * as path10 from "node:path";
|
|
4301
|
+
import { createHash as createHash3 } from "node:crypto";
|
|
4296
4302
|
var MISSION_BINDING_FILE = "mission.json";
|
|
4297
4303
|
function workflowObjective(params) {
|
|
4298
4304
|
const objective = params.task?.trim() || params.tasks?.find((task) => task.task?.trim())?.task?.trim() || params.chain?.find((step) => step.task?.trim())?.task?.trim();
|
|
@@ -4380,8 +4386,8 @@ function artifactsForResult(result) {
|
|
|
4380
4386
|
const artifacts = [];
|
|
4381
4387
|
if (result.details.asyncDir) {
|
|
4382
4388
|
artifacts.push(
|
|
4383
|
-
{ kind: "status", path:
|
|
4384
|
-
{ kind: "other", path:
|
|
4389
|
+
{ kind: "status", path: path10.join(result.details.asyncDir, "status.json") },
|
|
4390
|
+
{ kind: "other", path: path10.join(result.details.asyncDir, "events.jsonl"), description: "Lifecycle events" }
|
|
4385
4391
|
);
|
|
4386
4392
|
}
|
|
4387
4393
|
for (const child of result.details.results) {
|
|
@@ -4411,7 +4417,7 @@ function persistedBinding(binding) {
|
|
|
4411
4417
|
};
|
|
4412
4418
|
}
|
|
4413
4419
|
function writeMissionAsyncBinding(asyncDir, binding) {
|
|
4414
|
-
writePrivateAtomicJson(
|
|
4420
|
+
writePrivateAtomicJson(path10.join(asyncDir, MISSION_BINDING_FILE), persistedBinding(binding));
|
|
4415
4421
|
}
|
|
4416
4422
|
function attachMissionToLaunchResult(input) {
|
|
4417
4423
|
const runId = input.result.details.runId ?? input.result.details.asyncId;
|
|
@@ -4455,10 +4461,10 @@ function attachMissionToLaunchResult(input) {
|
|
|
4455
4461
|
});
|
|
4456
4462
|
if (input.result.details.asyncDir) {
|
|
4457
4463
|
writeMissionAsyncBinding(input.result.details.asyncDir, input.binding);
|
|
4458
|
-
const statusPath =
|
|
4459
|
-
if (
|
|
4464
|
+
const statusPath = path10.join(input.result.details.asyncDir, "status.json");
|
|
4465
|
+
if (fs9.existsSync(statusPath)) {
|
|
4460
4466
|
try {
|
|
4461
|
-
const status = JSON.parse(
|
|
4467
|
+
const status = JSON.parse(fs9.readFileSync(statusPath, "utf-8"));
|
|
4462
4468
|
if (typeof status.state === "string" && !["queued", "running"].includes(status.state)) {
|
|
4463
4469
|
mission = syncMissionFromAsyncCompletion({
|
|
4464
4470
|
runId,
|
|
@@ -4521,9 +4527,9 @@ function parsePersistedBinding(value, source) {
|
|
|
4521
4527
|
};
|
|
4522
4528
|
}
|
|
4523
4529
|
function readMissionBinding(asyncDir) {
|
|
4524
|
-
const bindingPath =
|
|
4525
|
-
if (!
|
|
4526
|
-
const raw =
|
|
4530
|
+
const bindingPath = path10.join(asyncDir, MISSION_BINDING_FILE);
|
|
4531
|
+
if (!fs9.existsSync(bindingPath)) return void 0;
|
|
4532
|
+
const raw = fs9.readFileSync(bindingPath, "utf-8");
|
|
4527
4533
|
try {
|
|
4528
4534
|
return parsePersistedBinding(JSON.parse(raw), bindingPath);
|
|
4529
4535
|
} catch (error) {
|
|
@@ -4545,12 +4551,12 @@ function syncMissionFromAsyncCompletion(value) {
|
|
|
4545
4551
|
} catch (error) {
|
|
4546
4552
|
if (!(error instanceof MissionNotFoundError)) throw error;
|
|
4547
4553
|
const reason = "mission-record-missing";
|
|
4548
|
-
const markerId =
|
|
4549
|
-
const markerPath3 =
|
|
4554
|
+
const markerId = createHash3("sha256").update(JSON.stringify([runId, binding.missionId, reason])).digest("hex");
|
|
4555
|
+
const markerPath3 = path10.join(event.asyncDir, `.mission-sync-skipped-${markerId}.json`);
|
|
4550
4556
|
try {
|
|
4551
|
-
|
|
4557
|
+
fs9.writeFileSync(markerPath3, `${JSON.stringify({ runId, missionId: binding.missionId, reason })}
|
|
4552
4558
|
`, { encoding: "utf-8", mode: 384, flag: "wx" });
|
|
4553
|
-
|
|
4559
|
+
fs9.appendFileSync(path10.join(event.asyncDir, "events.jsonl"), `${JSON.stringify({
|
|
4554
4560
|
type: "subagent.mission.sync.skipped",
|
|
4555
4561
|
ts: Date.now(),
|
|
4556
4562
|
runId,
|
|
@@ -4565,8 +4571,8 @@ function syncMissionFromAsyncCompletion(value) {
|
|
|
4565
4571
|
}
|
|
4566
4572
|
const completedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
4567
4573
|
const artifacts = [
|
|
4568
|
-
{ kind: "status", path:
|
|
4569
|
-
{ kind: "other", path:
|
|
4574
|
+
{ kind: "status", path: path10.join(event.asyncDir, "status.json") },
|
|
4575
|
+
{ kind: "other", path: path10.join(event.asyncDir, "events.jsonl"), description: "Lifecycle events" }
|
|
4570
4576
|
];
|
|
4571
4577
|
if (event.parallelHandoff && typeof event.parallelHandoff === "object" && typeof event.parallelHandoff.path === "string") {
|
|
4572
4578
|
artifacts.push({ kind: "manifest", path: event.parallelHandoff.path });
|
|
@@ -4762,11 +4768,11 @@ function refreshLinkedRunStatus(location, record) {
|
|
|
4762
4768
|
const runAcceptance = [];
|
|
4763
4769
|
const updates = record.runs.flatMap((run) => {
|
|
4764
4770
|
if (!run.asyncDir) return [];
|
|
4765
|
-
const statusPath =
|
|
4766
|
-
if (!
|
|
4771
|
+
const statusPath = path11.join(run.asyncDir, "status.json");
|
|
4772
|
+
if (!fs10.existsSync(statusPath)) return [];
|
|
4767
4773
|
let status2;
|
|
4768
4774
|
try {
|
|
4769
|
-
status2 = JSON.parse(
|
|
4775
|
+
status2 = JSON.parse(fs10.readFileSync(statusPath, "utf-8"));
|
|
4770
4776
|
} catch (error) {
|
|
4771
4777
|
warnings.push(`Failed to read linked run status '${statusPath}': ${error instanceof Error ? error.message : String(error)}`);
|
|
4772
4778
|
return [];
|
|
@@ -4938,9 +4944,9 @@ ${formatMission(record2)}`, { mode: "management", results: [], missionId: record
|
|
|
4938
4944
|
}
|
|
4939
4945
|
|
|
4940
4946
|
// src/runs/background/result-files.ts
|
|
4941
|
-
import { createHash as
|
|
4942
|
-
import * as
|
|
4943
|
-
import * as
|
|
4947
|
+
import { createHash as createHash4 } from "node:crypto";
|
|
4948
|
+
import * as fs11 from "node:fs";
|
|
4949
|
+
import * as path12 from "node:path";
|
|
4944
4950
|
var RESULT_INDEX_VERSION = 1;
|
|
4945
4951
|
var RESULT_INDEX_DIR = "result-index";
|
|
4946
4952
|
var SESSION_INDEX_DIR = "sessions";
|
|
@@ -4971,31 +4977,31 @@ function resultFileName(runId) {
|
|
|
4971
4977
|
return `${runId}${JSON_EXTENSION}`;
|
|
4972
4978
|
}
|
|
4973
4979
|
function resultFilePath(resultsDir, runId) {
|
|
4974
|
-
return
|
|
4980
|
+
return path12.join(resultsDir, resultFileName(runId));
|
|
4975
4981
|
}
|
|
4976
4982
|
function sessionIndexDir2(resultsDir, sessionId) {
|
|
4977
|
-
return
|
|
4983
|
+
return path12.join(resultsDir, RESULT_INDEX_DIR, SESSION_INDEX_DIR, encodeSegment(sessionId));
|
|
4978
4984
|
}
|
|
4979
4985
|
function sessionIndexDirs(resultsDir, sessionId) {
|
|
4980
|
-
return indexSegmentAliases(sessionId).map((segment) =>
|
|
4986
|
+
return indexSegmentAliases(sessionId).map((segment) => path12.join(resultsDir, RESULT_INDEX_DIR, SESSION_INDEX_DIR, segment));
|
|
4981
4987
|
}
|
|
4982
4988
|
function resultIndexPath(resultsDir, sessionId, runId) {
|
|
4983
|
-
return
|
|
4989
|
+
return path12.join(sessionIndexDir2(resultsDir, sessionId), encodedJsonFileName(runId));
|
|
4984
4990
|
}
|
|
4985
4991
|
function resultIndexPaths(resultsDir, sessionId, runId) {
|
|
4986
|
-
return sessionIndexDirs(resultsDir, sessionId).flatMap((dir) => encodedJsonFileNames(runId).map((fileName) =>
|
|
4992
|
+
return sessionIndexDirs(resultsDir, sessionId).flatMap((dir) => encodedJsonFileNames(runId).map((fileName) => path12.join(dir, fileName)));
|
|
4987
4993
|
}
|
|
4988
4994
|
function runIndexPath(resultsDir, runId) {
|
|
4989
|
-
return
|
|
4995
|
+
return path12.join(resultsDir, RESULT_INDEX_DIR, RUN_INDEX_DIR, encodedJsonFileName(runId));
|
|
4990
4996
|
}
|
|
4991
4997
|
function resultPendingPath(resultsDir, sessionId, runId) {
|
|
4992
|
-
return
|
|
4998
|
+
return path12.join(resultsDir, RESULT_PENDING_DIR, encodeSegment(sessionId), encodedJsonFileName(runId));
|
|
4993
4999
|
}
|
|
4994
5000
|
function resultPendingPaths(resultsDir, sessionId, runId) {
|
|
4995
|
-
return indexSegmentAliases(sessionId).flatMap((segment) => encodedJsonFileNames(runId).map((fileName) =>
|
|
5001
|
+
return indexSegmentAliases(sessionId).flatMap((segment) => encodedJsonFileNames(runId).map((fileName) => path12.join(resultsDir, RESULT_PENDING_DIR, segment, fileName)));
|
|
4996
5002
|
}
|
|
4997
5003
|
function pendingSessionDirs(resultsDir, sessionId) {
|
|
4998
|
-
return indexSegmentAliases(sessionId).map((segment) =>
|
|
5004
|
+
return indexSegmentAliases(sessionId).map((segment) => path12.join(resultsDir, RESULT_PENDING_DIR, segment));
|
|
4999
5005
|
}
|
|
5000
5006
|
function firstExistingResultFile(paths) {
|
|
5001
5007
|
for (const filePath of paths) {
|
|
@@ -5004,19 +5010,19 @@ function firstExistingResultFile(paths) {
|
|
|
5004
5010
|
return void 0;
|
|
5005
5011
|
}
|
|
5006
5012
|
function observerIndexDir(resultsDir, observer) {
|
|
5007
|
-
return
|
|
5013
|
+
return path12.join(resultsDir, RESULT_INDEX_DIR, OBSERVER_INDEX_DIR, observer);
|
|
5008
5014
|
}
|
|
5009
5015
|
function observerIndexPath(resultsDir, observer, runId) {
|
|
5010
|
-
return
|
|
5016
|
+
return path12.join(observerIndexDir(resultsDir, observer), encodedJsonFileName(runId));
|
|
5011
5017
|
}
|
|
5012
5018
|
function missionObserverIndexPath(resultsDir, runId) {
|
|
5013
5019
|
return observerIndexPath(resultsDir, MISSION_OBSERVER, runId);
|
|
5014
5020
|
}
|
|
5015
5021
|
function toolCallIndexDir3(resultsDir, toolCallId) {
|
|
5016
|
-
return
|
|
5022
|
+
return path12.join(resultsDir, RESULT_INDEX_DIR, TOOL_CALL_INDEX_DIR3, encodeIndexSegment(toolCallId));
|
|
5017
5023
|
}
|
|
5018
5024
|
function toolCallIndexPath2(resultsDir, toolCallId, runId) {
|
|
5019
|
-
return
|
|
5025
|
+
return path12.join(toolCallIndexDir3(resultsDir, toolCallId), encodedJsonFileName(runId));
|
|
5020
5026
|
}
|
|
5021
5027
|
function parseResultIndexEntry(value) {
|
|
5022
5028
|
if (!value || typeof value !== "object" || Array.isArray(value)) return void 0;
|
|
@@ -5032,10 +5038,10 @@ function parseResultIndexEntry(value) {
|
|
|
5032
5038
|
};
|
|
5033
5039
|
}
|
|
5034
5040
|
function writeResultIndexForData(resultPath, data) {
|
|
5035
|
-
const runId = nonEmptyString2(data.runId) ?? nonEmptyString2(data.id) ??
|
|
5041
|
+
const runId = nonEmptyString2(data.runId) ?? nonEmptyString2(data.id) ?? path12.basename(resultPath, ".json");
|
|
5036
5042
|
const sessionId = nonEmptyString2(data.sessionId);
|
|
5037
5043
|
if (!runId || !sessionId) return;
|
|
5038
|
-
const file =
|
|
5044
|
+
const file = path12.basename(resultPath);
|
|
5039
5045
|
const entry = {
|
|
5040
5046
|
version: RESULT_INDEX_VERSION,
|
|
5041
5047
|
runId,
|
|
@@ -5044,7 +5050,7 @@ function writeResultIndexForData(resultPath, data) {
|
|
|
5044
5050
|
writtenAt: Date.now(),
|
|
5045
5051
|
...nonEmptyString2(data.asyncDir) ? { asyncDir: nonEmptyString2(data.asyncDir) } : {}
|
|
5046
5052
|
};
|
|
5047
|
-
const resultsDir =
|
|
5053
|
+
const resultsDir = path12.dirname(resultPath);
|
|
5048
5054
|
writeAtomicJson(resultIndexPath(resultsDir, sessionId, runId), entry);
|
|
5049
5055
|
try {
|
|
5050
5056
|
writeAtomicJson(runIndexPath(resultsDir, runId), entry);
|
|
@@ -5058,7 +5064,7 @@ function writeResultIndexForData(resultPath, data) {
|
|
|
5058
5064
|
console.error(`Failed to write async result tool-call index for '${resultPath}':`, error);
|
|
5059
5065
|
}
|
|
5060
5066
|
try {
|
|
5061
|
-
if (entry.asyncDir &&
|
|
5067
|
+
if (entry.asyncDir && fs11.existsSync(path12.join(entry.asyncDir, MISSION_BINDING_FILE))) {
|
|
5062
5068
|
writeAtomicJson(observerIndexPath(resultsDir, MISSION_OBSERVER, runId), entry);
|
|
5063
5069
|
}
|
|
5064
5070
|
} catch (error) {
|
|
@@ -5066,10 +5072,10 @@ function writeResultIndexForData(resultPath, data) {
|
|
|
5066
5072
|
}
|
|
5067
5073
|
}
|
|
5068
5074
|
function writeIndexedPendingResultFile(resultPath, data) {
|
|
5069
|
-
const runId = nonEmptyString2(data.runId) ?? nonEmptyString2(data.id) ??
|
|
5075
|
+
const runId = nonEmptyString2(data.runId) ?? nonEmptyString2(data.id) ?? path12.basename(resultPath, ".json");
|
|
5070
5076
|
const sessionId = nonEmptyString2(data.sessionId);
|
|
5071
5077
|
if (!sessionId) throw new Error(`Cannot write async result '${resultPath}' without a sessionId.`);
|
|
5072
|
-
const resultsDir =
|
|
5078
|
+
const resultsDir = path12.dirname(resultPath);
|
|
5073
5079
|
let indexFailure;
|
|
5074
5080
|
writeAtomicJson(resultPendingPath(resultsDir, sessionId, runId), data, () => {
|
|
5075
5081
|
try {
|
|
@@ -5083,54 +5089,54 @@ function writeIndexedPendingResultFile(resultPath, data) {
|
|
|
5083
5089
|
}
|
|
5084
5090
|
function writeAsyncResultFile(resultPath, data) {
|
|
5085
5091
|
const { runId, sessionId, resultsDir } = writeIndexedPendingResultFile(resultPath, data);
|
|
5086
|
-
return promotePendingResultFile(resultsDir, sessionId, runId,
|
|
5092
|
+
return promotePendingResultFile(resultsDir, sessionId, runId, path12.basename(resultPath), { logFailure: false }) === "promoted" ? { state: "public" } : { state: "pending" };
|
|
5087
5093
|
}
|
|
5088
5094
|
function removeResultIndex(resultsDir, sessionId, runId, toolCallId) {
|
|
5089
5095
|
if (!runId) return;
|
|
5090
5096
|
if (sessionId) {
|
|
5091
5097
|
for (const indexPath2 of resultIndexPaths(resultsDir, sessionId, runId)) {
|
|
5092
5098
|
try {
|
|
5093
|
-
|
|
5099
|
+
fs11.rmSync(indexPath2, { force: true });
|
|
5094
5100
|
} catch {
|
|
5095
5101
|
}
|
|
5096
5102
|
}
|
|
5097
5103
|
for (const pendingPath of resultPendingPaths(resultsDir, sessionId, runId)) {
|
|
5098
5104
|
try {
|
|
5099
|
-
|
|
5105
|
+
fs11.rmSync(pendingPath, { force: true });
|
|
5100
5106
|
} catch {
|
|
5101
5107
|
}
|
|
5102
5108
|
}
|
|
5103
5109
|
}
|
|
5104
5110
|
try {
|
|
5105
|
-
|
|
5111
|
+
fs11.rmSync(runIndexPath(resultsDir, runId), { force: true });
|
|
5106
5112
|
} catch {
|
|
5107
5113
|
}
|
|
5108
5114
|
if (toolCallId) {
|
|
5109
5115
|
try {
|
|
5110
|
-
|
|
5116
|
+
fs11.rmSync(toolCallIndexPath2(resultsDir, toolCallId, runId), { force: true });
|
|
5111
5117
|
} catch {
|
|
5112
5118
|
}
|
|
5113
5119
|
}
|
|
5114
5120
|
try {
|
|
5115
|
-
|
|
5121
|
+
fs11.rmSync(observerIndexPath(resultsDir, MISSION_OBSERVER, runId), { force: true });
|
|
5116
5122
|
} catch {
|
|
5117
5123
|
}
|
|
5118
5124
|
}
|
|
5119
5125
|
function removeMissionObserverIndex(resultsDir, runId) {
|
|
5120
5126
|
if (!runId) return;
|
|
5121
5127
|
try {
|
|
5122
|
-
|
|
5128
|
+
fs11.rmSync(observerIndexPath(resultsDir, MISSION_OBSERVER, runId), { force: true });
|
|
5123
5129
|
} catch {
|
|
5124
5130
|
}
|
|
5125
5131
|
}
|
|
5126
5132
|
function withResultRunLease(resultsDir, runId, action, waitMs) {
|
|
5127
|
-
const leaseDir =
|
|
5128
|
-
|
|
5129
|
-
return withFileLease(
|
|
5133
|
+
const leaseDir = path12.join(resultsDir, RESULT_LEASE_DIR);
|
|
5134
|
+
fs11.mkdirSync(leaseDir, { recursive: true });
|
|
5135
|
+
return withFileLease(path12.join(leaseDir, createHash4("sha256").update(runId).digest("hex")), action, waitMs);
|
|
5130
5136
|
}
|
|
5131
5137
|
function readResultPayload(filePath) {
|
|
5132
5138
|
try {
|
|
5133
|
-
return
|
|
5139
|
+
return fs11.readFileSync(filePath, "utf-8");
|
|
5134
5140
|
} catch (error) {
|
|
5135
5141
|
const code = error.code;
|
|
5136
5142
|
if (code === "ENOENT" || code === "ENOTDIR" || code === "EISDIR" || isUnaddressableResultCandidate(error)) return void 0;
|
|
@@ -5138,7 +5144,7 @@ function readResultPayload(filePath) {
|
|
|
5138
5144
|
}
|
|
5139
5145
|
}
|
|
5140
5146
|
function resultPayloadCandidates(publicPath, read) {
|
|
5141
|
-
return [...read.sessionId ? resultPendingPaths(
|
|
5147
|
+
return [...read.sessionId ? resultPendingPaths(path12.dirname(publicPath), read.sessionId, read.runId) : [], publicPath];
|
|
5142
5148
|
}
|
|
5143
5149
|
function readByConsumer(publicPath, read, candidate, current) {
|
|
5144
5150
|
return current === read.snapshot || candidate === publicPath && current === read.stalePublic;
|
|
@@ -5150,10 +5156,10 @@ function resultSnapshotReplaced(publicPath, read) {
|
|
|
5150
5156
|
});
|
|
5151
5157
|
}
|
|
5152
5158
|
function retireResultSnapshot(publicPath, read, payloadPath = publicPath, leaseWaitMs) {
|
|
5153
|
-
const resultsDir =
|
|
5159
|
+
const resultsDir = path12.dirname(publicPath);
|
|
5154
5160
|
return withResultRunLease(resultsDir, read.runId, () => {
|
|
5155
5161
|
if (resultSnapshotReplaced(publicPath, read)) {
|
|
5156
|
-
if (payloadPath !== publicPath && readResultPayload(payloadPath) === read.snapshot)
|
|
5162
|
+
if (payloadPath !== publicPath && readResultPayload(payloadPath) === read.snapshot) fs11.rmSync(payloadPath, { force: true });
|
|
5157
5163
|
return "replaced";
|
|
5158
5164
|
}
|
|
5159
5165
|
let removalFailure;
|
|
@@ -5161,7 +5167,7 @@ function retireResultSnapshot(publicPath, read, payloadPath = publicPath, leaseW
|
|
|
5161
5167
|
const current = readResultPayload(candidate);
|
|
5162
5168
|
if (current === void 0 || !readByConsumer(publicPath, read, candidate, current)) continue;
|
|
5163
5169
|
try {
|
|
5164
|
-
|
|
5170
|
+
fs11.rmSync(candidate, { force: true });
|
|
5165
5171
|
} catch (error) {
|
|
5166
5172
|
removalFailure ??= { error };
|
|
5167
5173
|
}
|
|
@@ -5172,8 +5178,8 @@ function retireResultSnapshot(publicPath, read, payloadPath = publicPath, leaseW
|
|
|
5172
5178
|
}, leaseWaitMs);
|
|
5173
5179
|
}
|
|
5174
5180
|
function acknowledgeMissionObserverSnapshot(publicPath, read, leaseWaitMs) {
|
|
5175
|
-
const resultsDir =
|
|
5176
|
-
if (!
|
|
5181
|
+
const resultsDir = path12.dirname(publicPath);
|
|
5182
|
+
if (!fs11.existsSync(observerIndexPath(resultsDir, MISSION_OBSERVER, read.runId))) return "acknowledged";
|
|
5177
5183
|
return withResultRunLease(resultsDir, read.runId, () => {
|
|
5178
5184
|
if (resultSnapshotReplaced(publicPath, read)) return "replaced";
|
|
5179
5185
|
removeMissionObserverIndex(resultsDir, read.runId);
|
|
@@ -5182,7 +5188,7 @@ function acknowledgeMissionObserverSnapshot(publicPath, read, leaseWaitMs) {
|
|
|
5182
5188
|
}
|
|
5183
5189
|
function existingResultFile(resultPath) {
|
|
5184
5190
|
try {
|
|
5185
|
-
return
|
|
5191
|
+
return fs11.statSync(resultPath).isFile();
|
|
5186
5192
|
} catch (error) {
|
|
5187
5193
|
if (error.code !== "ENOENT" && !isUnaddressableResultCandidate(error)) console.error(`Failed to inspect async result payload '${resultPath}':`, error);
|
|
5188
5194
|
return false;
|
|
@@ -5198,22 +5204,22 @@ function resultPayloadMatchesSessionRun(data, sessionId, runId) {
|
|
|
5198
5204
|
}
|
|
5199
5205
|
function pendingResultPayloadMatches(filePath, sessionId, runId) {
|
|
5200
5206
|
try {
|
|
5201
|
-
return resultPayloadMatchesSessionRun(JSON.parse(
|
|
5207
|
+
return resultPayloadMatchesSessionRun(JSON.parse(fs11.readFileSync(filePath, "utf-8")), sessionId, runId);
|
|
5202
5208
|
} catch (error) {
|
|
5203
5209
|
if (error.code !== "ENOENT" && !isUnaddressableResultCandidate(error)) console.error(`Ignoring invalid pending async result '${filePath}':`, error);
|
|
5204
5210
|
return false;
|
|
5205
5211
|
}
|
|
5206
5212
|
}
|
|
5207
5213
|
function assertPendingResultPayloadMatches(filePath, sessionId, runId) {
|
|
5208
|
-
return resultPayloadMatchesSessionRun(JSON.parse(
|
|
5214
|
+
return resultPayloadMatchesSessionRun(JSON.parse(fs11.readFileSync(filePath, "utf-8")), sessionId, runId);
|
|
5209
5215
|
}
|
|
5210
5216
|
function promotePendingResultFile(resultsDir, sessionId, runId, file = resultFileName(runId), options = {}) {
|
|
5211
|
-
if (file !==
|
|
5217
|
+
if (file !== path12.basename(file) || !file.endsWith(".json")) return "none";
|
|
5212
5218
|
const pendingPath = firstExistingResultFile(resultPendingPaths(resultsDir, sessionId, runId));
|
|
5213
5219
|
if (!pendingPath) return "none";
|
|
5214
|
-
const resultPath =
|
|
5220
|
+
const resultPath = path12.join(resultsDir, file);
|
|
5215
5221
|
try {
|
|
5216
|
-
|
|
5222
|
+
fs11.renameSync(pendingPath, resultPath);
|
|
5217
5223
|
return existingResultFile(resultPath) ? "promoted" : "pending";
|
|
5218
5224
|
} catch (error) {
|
|
5219
5225
|
const code = error.code;
|
|
@@ -5233,7 +5239,7 @@ function promotePendingResultFile(resultsDir, sessionId, runId, file = resultFil
|
|
|
5233
5239
|
}
|
|
5234
5240
|
}
|
|
5235
5241
|
function pendingResultLocationForSessionRun(resultsDir, sessionId, runId, file = resultFileName(runId)) {
|
|
5236
|
-
if (file !==
|
|
5242
|
+
if (file !== path12.basename(file) || !file.endsWith(".json")) return void 0;
|
|
5237
5243
|
const pendingPath = firstExistingResultFile(resultPendingPaths(resultsDir, sessionId, runId));
|
|
5238
5244
|
if (!pendingPath || !pendingResultPayloadMatches(pendingPath, sessionId, runId)) return void 0;
|
|
5239
5245
|
return { file, path: pendingPath, state: "pending" };
|
|
@@ -5247,19 +5253,19 @@ function resultPayloadFileForSessionRun(resultsDir, sessionId, runId) {
|
|
|
5247
5253
|
return firstExistingResultFile([...resultPendingPaths(resultsDir, sessionId, runId), resultFilePath(resultsDir, runId)]);
|
|
5248
5254
|
}
|
|
5249
5255
|
function resultPayloadLocationFromIndex(resultsDir, entry) {
|
|
5250
|
-
if (entry.file !==
|
|
5256
|
+
if (entry.file !== path12.basename(entry.file) || !entry.file.endsWith(".json")) return void 0;
|
|
5251
5257
|
const pendingState = promotePendingResultFile(resultsDir, entry.sessionId, entry.runId, entry.file);
|
|
5252
5258
|
if (pendingState === "pending") {
|
|
5253
5259
|
return pendingResultLocationForSessionRun(resultsDir, entry.sessionId, entry.runId, entry.file);
|
|
5254
5260
|
}
|
|
5255
|
-
const resultPath =
|
|
5261
|
+
const resultPath = path12.join(resultsDir, entry.file);
|
|
5256
5262
|
if (pendingState === "promoted" || existingResultFile(resultPath)) return { file: entry.file, path: resultPath, state: "public" };
|
|
5257
5263
|
return void 0;
|
|
5258
5264
|
}
|
|
5259
5265
|
function readResultIndexForSessionRun(resultsDir, sessionId, runId) {
|
|
5260
5266
|
for (const indexPath2 of resultIndexPaths(resultsDir, sessionId, runId)) {
|
|
5261
5267
|
try {
|
|
5262
|
-
const entry = parseResultIndexEntry(JSON.parse(
|
|
5268
|
+
const entry = parseResultIndexEntry(JSON.parse(fs11.readFileSync(indexPath2, "utf-8")));
|
|
5263
5269
|
if (!entry || entry.sessionId !== sessionId || entry.runId !== runId) continue;
|
|
5264
5270
|
return entry;
|
|
5265
5271
|
} catch (error) {
|
|
@@ -5278,7 +5284,7 @@ function resultPayloadPathForSessionRun(resultsDir, sessionId, runId) {
|
|
|
5278
5284
|
}
|
|
5279
5285
|
function resultPayloadPathForMissionObserverRun(resultsDir, runId) {
|
|
5280
5286
|
try {
|
|
5281
|
-
const entry = parseResultIndexEntry(JSON.parse(
|
|
5287
|
+
const entry = parseResultIndexEntry(JSON.parse(fs11.readFileSync(observerIndexPath(resultsDir, MISSION_OBSERVER, runId), "utf-8")));
|
|
5282
5288
|
if (!entry || entry.runId !== runId) return void 0;
|
|
5283
5289
|
return resultPayloadLocationFromIndex(resultsDir, entry)?.path;
|
|
5284
5290
|
} catch (error) {
|
|
@@ -5290,9 +5296,9 @@ function resultPayloadPathForMissionObserverRun(resultsDir, runId) {
|
|
|
5290
5296
|
function resultPayloadPathForIndexedRun(resultsDir, runId) {
|
|
5291
5297
|
const entryPath = runIndexPath(resultsDir, runId);
|
|
5292
5298
|
try {
|
|
5293
|
-
const entry = parseResultIndexEntry(JSON.parse(
|
|
5299
|
+
const entry = parseResultIndexEntry(JSON.parse(fs11.readFileSync(entryPath, "utf-8")));
|
|
5294
5300
|
if (!entry || entry.runId !== runId) {
|
|
5295
|
-
|
|
5301
|
+
fs11.rmSync(entryPath, { force: true });
|
|
5296
5302
|
return void 0;
|
|
5297
5303
|
}
|
|
5298
5304
|
return resultPayloadLocationFromIndex(resultsDir, entry)?.path;
|
|
@@ -5302,7 +5308,7 @@ function resultPayloadPathForIndexedRun(resultsDir, runId) {
|
|
|
5302
5308
|
if (code !== "ENOENT" && code !== "ENOTDIR") {
|
|
5303
5309
|
console.error(`Ignoring invalid async result run index '${entryPath}':`, error);
|
|
5304
5310
|
try {
|
|
5305
|
-
|
|
5311
|
+
fs11.rmSync(entryPath, { force: true });
|
|
5306
5312
|
} catch {
|
|
5307
5313
|
}
|
|
5308
5314
|
}
|
|
@@ -5317,7 +5323,7 @@ function indexedResultFile(resultsDir, entry, includePending = false) {
|
|
|
5317
5323
|
function listIndexFiles(dir) {
|
|
5318
5324
|
let files;
|
|
5319
5325
|
try {
|
|
5320
|
-
files =
|
|
5326
|
+
files = fs11.readdirSync(dir, { withFileTypes: true }).filter((entry) => entry.isFile() && entry.name.endsWith(".json")).map((entry) => path12.join(dir, entry.name));
|
|
5321
5327
|
} catch (error) {
|
|
5322
5328
|
const code = error.code;
|
|
5323
5329
|
if (code === "ENOENT" || code === "ENOTDIR" || code === "EPERM" || code === "EACCES" || isUnaddressableResultCandidate(error)) return [];
|
|
@@ -5329,9 +5335,9 @@ function resultFilesFromIndexDir(resultsDir, dir, includePending = false) {
|
|
|
5329
5335
|
const candidates = /* @__PURE__ */ new Set();
|
|
5330
5336
|
for (const entryPath of listIndexFiles(dir)) {
|
|
5331
5337
|
try {
|
|
5332
|
-
const entry = parseResultIndexEntry(JSON.parse(
|
|
5338
|
+
const entry = parseResultIndexEntry(JSON.parse(fs11.readFileSync(entryPath, "utf-8")));
|
|
5333
5339
|
if (!entry) {
|
|
5334
|
-
|
|
5340
|
+
fs11.rmSync(entryPath, { force: true });
|
|
5335
5341
|
continue;
|
|
5336
5342
|
}
|
|
5337
5343
|
const resultFile = indexedResultFile(resultsDir, entry, includePending);
|
|
@@ -5347,7 +5353,7 @@ function pendingResultFilesForSession(resultsDir, sessionId) {
|
|
|
5347
5353
|
for (const dir of pendingSessionDirs(resultsDir, sessionId)) {
|
|
5348
5354
|
let entries;
|
|
5349
5355
|
try {
|
|
5350
|
-
entries =
|
|
5356
|
+
entries = fs11.readdirSync(dir, { withFileTypes: true });
|
|
5351
5357
|
} catch (error) {
|
|
5352
5358
|
const code = error.code;
|
|
5353
5359
|
if (code === "ENOENT" || code === "ENOTDIR" || code === "EPERM" || code === "EACCES" || isUnaddressableResultCandidate(error)) continue;
|
|
@@ -5355,9 +5361,9 @@ function pendingResultFilesForSession(resultsDir, sessionId) {
|
|
|
5355
5361
|
}
|
|
5356
5362
|
for (const entry of entries) {
|
|
5357
5363
|
if (!entry.isFile() || !entry.name.endsWith(".json")) continue;
|
|
5358
|
-
const pendingPath =
|
|
5364
|
+
const pendingPath = path12.join(dir, entry.name);
|
|
5359
5365
|
try {
|
|
5360
|
-
const data = JSON.parse(
|
|
5366
|
+
const data = JSON.parse(fs11.readFileSync(pendingPath, "utf-8"));
|
|
5361
5367
|
const runId = nonEmptyString2(data.runId) ?? nonEmptyString2(data.id);
|
|
5362
5368
|
if (runId && nonEmptyString2(data.sessionId) === sessionId) files.add(resultFileName(runId));
|
|
5363
5369
|
} catch (error) {
|
|
@@ -5382,43 +5388,43 @@ function missionObserverResultCandidateFiles(resultsDir) {
|
|
|
5382
5388
|
return resultFilesFromIndexDir(resultsDir, observerIndexDir(resultsDir, MISSION_OBSERVER), true);
|
|
5383
5389
|
}
|
|
5384
5390
|
function cleanupResultIndexes(resultsDir, now = Date.now(), maxAgeMs = 24 * 60 * 60 * 1e3) {
|
|
5385
|
-
const root =
|
|
5391
|
+
const root = path12.join(resultsDir, RESULT_INDEX_DIR);
|
|
5386
5392
|
const cutoff = now - maxAgeMs;
|
|
5387
5393
|
let removed = 0;
|
|
5388
5394
|
const visit = (dir) => {
|
|
5389
5395
|
let entries;
|
|
5390
5396
|
try {
|
|
5391
|
-
entries =
|
|
5397
|
+
entries = fs11.readdirSync(dir, { withFileTypes: true });
|
|
5392
5398
|
} catch (error) {
|
|
5393
5399
|
const code = error.code;
|
|
5394
5400
|
if (code === "ENOENT" || code === "ENOTDIR" || code === "EPERM" || code === "EACCES" || isUnaddressableResultCandidate(error)) return;
|
|
5395
5401
|
throw error;
|
|
5396
5402
|
}
|
|
5397
5403
|
for (const entry of entries) {
|
|
5398
|
-
const fullPath =
|
|
5404
|
+
const fullPath = path12.join(dir, entry.name);
|
|
5399
5405
|
if (entry.isDirectory()) {
|
|
5400
5406
|
visit(fullPath);
|
|
5401
5407
|
try {
|
|
5402
|
-
|
|
5408
|
+
fs11.rmdirSync(fullPath);
|
|
5403
5409
|
} catch {
|
|
5404
5410
|
}
|
|
5405
5411
|
continue;
|
|
5406
5412
|
}
|
|
5407
5413
|
if (!entry.isFile() || !entry.name.endsWith(".json")) continue;
|
|
5408
5414
|
try {
|
|
5409
|
-
const stat =
|
|
5410
|
-
const index = parseResultIndexEntry(JSON.parse(
|
|
5415
|
+
const stat = fs11.statSync(fullPath);
|
|
5416
|
+
const index = parseResultIndexEntry(JSON.parse(fs11.readFileSync(fullPath, "utf-8")));
|
|
5411
5417
|
const resultFile = index ? indexedResultFile(resultsDir, index) : void 0;
|
|
5412
5418
|
const pendingFile = index ? pendingResultExists(resultsDir, index.sessionId, index.runId) : false;
|
|
5413
5419
|
if (!index || !resultFile && !pendingFile && stat.mtimeMs <= cutoff) {
|
|
5414
|
-
|
|
5420
|
+
fs11.rmSync(fullPath, { force: true });
|
|
5415
5421
|
removed += 1;
|
|
5416
5422
|
}
|
|
5417
5423
|
} catch (error) {
|
|
5418
5424
|
if (isUnaddressableResultCandidate(error)) continue;
|
|
5419
5425
|
if (error.code !== "ENOENT") console.error(`Ignoring invalid async result index '${fullPath}':`, error);
|
|
5420
5426
|
try {
|
|
5421
|
-
|
|
5427
|
+
fs11.rmSync(fullPath, { force: true });
|
|
5422
5428
|
removed += 1;
|
|
5423
5429
|
} catch {
|
|
5424
5430
|
}
|
|
@@ -5430,21 +5436,21 @@ function cleanupResultIndexes(resultsDir, now = Date.now(), maxAgeMs = 24 * 60 *
|
|
|
5430
5436
|
}
|
|
5431
5437
|
|
|
5432
5438
|
// src/shared/completion-owner.ts
|
|
5433
|
-
import { randomUUID as
|
|
5439
|
+
import { randomUUID as randomUUID5 } from "node:crypto";
|
|
5434
5440
|
var COMPLETION_OWNER_KEY = /* @__PURE__ */ Symbol.for("pi-subagents.completion-owner-id");
|
|
5435
5441
|
var OWNING_SESSION_COMPLETION_OWNER = "owning-session";
|
|
5436
5442
|
function currentCompletionOwnerId() {
|
|
5437
5443
|
const runtime2 = globalThis;
|
|
5438
|
-
runtime2[COMPLETION_OWNER_KEY] ??=
|
|
5444
|
+
runtime2[COMPLETION_OWNER_KEY] ??= randomUUID5();
|
|
5439
5445
|
return runtime2[COMPLETION_OWNER_KEY];
|
|
5440
5446
|
}
|
|
5441
5447
|
|
|
5442
5448
|
// src/runs/background/boot-id.ts
|
|
5443
5449
|
import { execFileSync as execFileSync2 } from "node:child_process";
|
|
5444
|
-
import * as
|
|
5450
|
+
import * as fs13 from "node:fs";
|
|
5445
5451
|
|
|
5446
5452
|
// src/runs/background/pid-namespace.ts
|
|
5447
|
-
import * as
|
|
5453
|
+
import * as fs12 from "node:fs";
|
|
5448
5454
|
var resolved = false;
|
|
5449
5455
|
var cachedScope;
|
|
5450
5456
|
function currentPidNamespaceScope() {
|
|
@@ -5452,7 +5458,7 @@ function currentPidNamespaceScope() {
|
|
|
5452
5458
|
resolved = true;
|
|
5453
5459
|
if (process.platform !== "linux") return void 0;
|
|
5454
5460
|
try {
|
|
5455
|
-
const scope =
|
|
5461
|
+
const scope = fs12.readlinkSync("/proc/self/ns/pid", "utf-8").trim();
|
|
5456
5462
|
cachedScope = scope || void 0;
|
|
5457
5463
|
} catch {
|
|
5458
5464
|
cachedScope = void 0;
|
|
@@ -5463,7 +5469,7 @@ function currentPidNamespaceScope() {
|
|
|
5463
5469
|
// src/runs/background/boot-id.ts
|
|
5464
5470
|
function readBootIdFromOs() {
|
|
5465
5471
|
try {
|
|
5466
|
-
if (process.platform === "linux") return
|
|
5472
|
+
if (process.platform === "linux") return fs13.readFileSync("/proc/sys/kernel/random/boot_id", "utf-8").trim() || void 0;
|
|
5467
5473
|
if (process.platform === "darwin") {
|
|
5468
5474
|
return execFileSync2("sysctl", ["-n", "kern.bootsessionuuid"], { encoding: "utf-8", timeout: 1e3, stdio: ["ignore", "pipe", "ignore"] }).trim() || void 0;
|
|
5469
5475
|
}
|
|
@@ -5488,8 +5494,8 @@ function currentRecordedPid() {
|
|
|
5488
5494
|
}
|
|
5489
5495
|
|
|
5490
5496
|
// src/runs/background/stale-run-reconciler.ts
|
|
5491
|
-
import * as
|
|
5492
|
-
import * as
|
|
5497
|
+
import * as fs15 from "node:fs";
|
|
5498
|
+
import * as path14 from "node:path";
|
|
5493
5499
|
|
|
5494
5500
|
// src/runs/background/parallel-groups.ts
|
|
5495
5501
|
function isValidParallelGroup(group, stepCount, chainStepCount) {
|
|
@@ -5530,16 +5536,16 @@ function isReusableWorkflowStopCause(cause) {
|
|
|
5530
5536
|
}
|
|
5531
5537
|
|
|
5532
5538
|
// src/runs/background/workflow-terminal-proof.ts
|
|
5533
|
-
import * as
|
|
5534
|
-
import * as
|
|
5539
|
+
import * as fs14 from "node:fs";
|
|
5540
|
+
import * as path13 from "node:path";
|
|
5535
5541
|
var TERMINAL_WORKFLOW_STATES = /* @__PURE__ */ new Set(["completed", "failed", "stopped"]);
|
|
5536
5542
|
function isTerminalAsyncState(state) {
|
|
5537
5543
|
return state !== "queued" && state !== "running" && state !== "paused";
|
|
5538
5544
|
}
|
|
5539
5545
|
function readWorkflowChildRunModel(workflowAsyncDir, step) {
|
|
5540
|
-
if (step.async !== true || typeof step.runId !== "string" ||
|
|
5546
|
+
if (step.async !== true || typeof step.runId !== "string" || path13.basename(step.runId) !== step.runId) return void 0;
|
|
5541
5547
|
try {
|
|
5542
|
-
const child = readStatus(
|
|
5548
|
+
const child = readStatus(path13.join(path13.dirname(workflowAsyncDir), step.runId));
|
|
5543
5549
|
const first = Array.isArray(child?.steps) ? child.steps[0] : void 0;
|
|
5544
5550
|
const model = typeof first?.model === "string" && first.model ? first.model : void 0;
|
|
5545
5551
|
const thinking = typeof first?.thinking === "string" && first.thinking ? first.thinking : void 0;
|
|
@@ -5568,15 +5574,15 @@ function readWorkflowChildProcessEvidence(workflowAsyncDir, steps) {
|
|
|
5568
5574
|
}
|
|
5569
5575
|
function launchFailedBeforeRunner(step, childDir) {
|
|
5570
5576
|
if (step.status !== "failed" || !step.error) return false;
|
|
5571
|
-
return !childDir || !["process-terminal.json", "runner-startup.json"].some((file) =>
|
|
5577
|
+
return !childDir || !["process-terminal.json", "runner-startup.json"].some((file) => fs14.existsSync(path13.join(childDir, file)));
|
|
5572
5578
|
}
|
|
5573
5579
|
function readWorkflowChildEvidence(workflowAsyncDir, step) {
|
|
5574
5580
|
const label = step.workflowKey ?? step.agent;
|
|
5575
5581
|
if (typeof step.async !== "boolean") return { state: "unknown", reason: `workflow child ${label} is missing async classification` };
|
|
5576
5582
|
if (!step.async) return void 0;
|
|
5577
|
-
if (!step.runId ||
|
|
5578
|
-
const childDir =
|
|
5579
|
-
if (!
|
|
5583
|
+
if (!step.runId || path13.basename(step.runId) !== step.runId) return { state: "unknown", reason: `async workflow child ${label} is missing run id` };
|
|
5584
|
+
const childDir = path13.join(path13.dirname(workflowAsyncDir), step.runId);
|
|
5585
|
+
if (!fs14.existsSync(childDir)) return launchFailedBeforeRunner(step) ? void 0 : { state: "unknown", reason: `async workflow child ${label} directory is missing` };
|
|
5580
5586
|
const childStatus = readStatus(childDir);
|
|
5581
5587
|
if (!childStatus) return launchFailedBeforeRunner(step, childDir) ? void 0 : { state: "unknown", reason: `async workflow child ${label} status is missing or unreadable` };
|
|
5582
5588
|
if (!isTerminalAsyncState(childStatus.state)) return { state: "pending", reason: `async workflow child ${label} is still ${childStatus.state}` };
|
|
@@ -5619,21 +5625,21 @@ function getErrorMessage(error) {
|
|
|
5619
5625
|
return error instanceof Error ? error.message : String(error);
|
|
5620
5626
|
}
|
|
5621
5627
|
function readRunnerStartupDiagnostics(asyncDir) {
|
|
5622
|
-
const stderrPath =
|
|
5628
|
+
const stderrPath = path14.join(asyncDir, "runner.stderr.log");
|
|
5623
5629
|
const maxBytes = 64 * 1024;
|
|
5624
5630
|
let content;
|
|
5625
5631
|
try {
|
|
5626
|
-
const stat =
|
|
5632
|
+
const stat = fs15.statSync(stderrPath);
|
|
5627
5633
|
if (stat.size <= 0) return void 0;
|
|
5628
|
-
const fd =
|
|
5634
|
+
const fd = fs15.openSync(stderrPath, "r");
|
|
5629
5635
|
try {
|
|
5630
5636
|
const bytesToRead = Math.min(stat.size, maxBytes);
|
|
5631
5637
|
const start = Math.max(0, stat.size - bytesToRead);
|
|
5632
5638
|
const buffer = Buffer.alloc(bytesToRead);
|
|
5633
|
-
|
|
5639
|
+
fs15.readSync(fd, buffer, 0, bytesToRead, start);
|
|
5634
5640
|
content = buffer.toString("utf-8").trim();
|
|
5635
5641
|
} finally {
|
|
5636
|
-
|
|
5642
|
+
fs15.closeSync(fd);
|
|
5637
5643
|
}
|
|
5638
5644
|
} catch {
|
|
5639
5645
|
return void 0;
|
|
@@ -5648,15 +5654,15 @@ function isNotFoundError(error) {
|
|
|
5648
5654
|
}
|
|
5649
5655
|
function appendJsonlBestEffort(filePath, payload) {
|
|
5650
5656
|
try {
|
|
5651
|
-
|
|
5652
|
-
|
|
5657
|
+
fs15.mkdirSync(path14.dirname(filePath), { recursive: true });
|
|
5658
|
+
fs15.appendFileSync(filePath, `${JSON.stringify(payload)}
|
|
5653
5659
|
`, "utf-8");
|
|
5654
5660
|
} catch {
|
|
5655
5661
|
}
|
|
5656
5662
|
}
|
|
5657
5663
|
function regularFileExists(filePath) {
|
|
5658
5664
|
try {
|
|
5659
|
-
return
|
|
5665
|
+
return fs15.statSync(filePath).isFile();
|
|
5660
5666
|
} catch (error) {
|
|
5661
5667
|
if (isNotFoundError(error)) return false;
|
|
5662
5668
|
throw error;
|
|
@@ -5664,7 +5670,7 @@ function regularFileExists(filePath) {
|
|
|
5664
5670
|
}
|
|
5665
5671
|
function readResultRepairData(resultPath) {
|
|
5666
5672
|
try {
|
|
5667
|
-
const data = JSON.parse(
|
|
5673
|
+
const data = JSON.parse(fs15.readFileSync(resultPath, "utf-8"));
|
|
5668
5674
|
if (data.error !== void 0 && typeof data.error !== "string") throw new Error(`Invalid async result file '${resultPath}': error must be a string.`);
|
|
5669
5675
|
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";
|
|
5670
5676
|
const results = Array.isArray(data.results) ? data.results.map((entry, index) => {
|
|
@@ -5738,7 +5744,7 @@ function buildStartedStatus(asyncDir, startedRun, now) {
|
|
|
5738
5744
|
const chainStepCount = startedRun.chainStepCount;
|
|
5739
5745
|
const parallelGroups = chainStepCount !== void 0 ? normalizeParallelGroups(startedRun.parallelGroups, agents.length, chainStepCount) : [];
|
|
5740
5746
|
return {
|
|
5741
|
-
runId: startedRun.runId ||
|
|
5747
|
+
runId: startedRun.runId || path14.basename(asyncDir),
|
|
5742
5748
|
...startedRun.sessionId ? { sessionId: startedRun.sessionId } : {},
|
|
5743
5749
|
...startedRun.completionOwnerId ? { completionOwnerId: startedRun.completionOwnerId } : {},
|
|
5744
5750
|
mode: startedRun.mode ?? "single",
|
|
@@ -5760,8 +5766,8 @@ function buildStartedStatus(asyncDir, startedRun, now) {
|
|
|
5760
5766
|
}
|
|
5761
5767
|
function settledWorkflowChildStatus(asyncDir, workflowRunId, step, now) {
|
|
5762
5768
|
const childRunId = step.runId;
|
|
5763
|
-
if (step.async !== true || step.parentWorkflowRunId !== workflowRunId || !childRunId || childRunId === workflowRunId || childRunId !==
|
|
5764
|
-
const child = readStatus(
|
|
5769
|
+
if (step.async !== true || step.parentWorkflowRunId !== workflowRunId || !childRunId || childRunId === workflowRunId || childRunId !== path14.basename(childRunId) || childRunId === "." || childRunId === "..") return void 0;
|
|
5770
|
+
const child = readStatus(path14.join(path14.dirname(asyncDir), childRunId));
|
|
5765
5771
|
if (!child || child.runId !== childRunId || child.parentWorkflowRunId !== workflowRunId || !isTerminalAsyncState(child.state)) return void 0;
|
|
5766
5772
|
if (step.workflowKey !== void 0 && child.workflowKey !== step.workflowKey) return void 0;
|
|
5767
5773
|
const state = child.state;
|
|
@@ -5782,7 +5788,7 @@ function settledWorkflowChildStatus(asyncDir, workflowRunId, step, now) {
|
|
|
5782
5788
|
return settled;
|
|
5783
5789
|
}
|
|
5784
5790
|
function buildFailedRepair(status, asyncDir, now, reason, ownerExited = false, adoptCompletionOwnerId) {
|
|
5785
|
-
const runId = status.runId ||
|
|
5791
|
+
const runId = status.runId || path14.basename(asyncDir);
|
|
5786
5792
|
const pid = typeof status.pid === "number" ? status.pid : "unknown";
|
|
5787
5793
|
const exitedWorkflow = ownerExited && status.mode === "workflow" ? status.workflow : void 0;
|
|
5788
5794
|
const completionOwnerId = exitedWorkflow ? adoptCompletionOwnerId || OWNING_SESSION_COMPLETION_OWNER : status.completionOwnerId;
|
|
@@ -5869,9 +5875,9 @@ ${diagnostics}` : baseMessage;
|
|
|
5869
5875
|
function writeFailedRepair(asyncDir, status, resultPath, now, reason, ownerExited = false, adoptCompletionOwnerId) {
|
|
5870
5876
|
const repair = buildFailedRepair(status, asyncDir, now, reason, ownerExited, adoptCompletionOwnerId);
|
|
5871
5877
|
if (repair.result.sessionId) writeAsyncResultFile(resultPath, repair.result);
|
|
5872
|
-
writeAtomicJson(
|
|
5878
|
+
writeAtomicJson(path14.join(asyncDir, "status.json"), repair.status);
|
|
5873
5879
|
updateActiveRunIndex(asyncDir, repair.status.state, repair.status.toolCallId);
|
|
5874
|
-
appendJsonlBestEffort(
|
|
5880
|
+
appendJsonlBestEffort(path14.join(asyncDir, "events.jsonl"), {
|
|
5875
5881
|
type: "subagent.run.repaired_stale",
|
|
5876
5882
|
ts: now,
|
|
5877
5883
|
runId: repair.status.runId,
|
|
@@ -5899,7 +5905,7 @@ function reconcileNestedAsyncDescendants(route, options = {}) {
|
|
|
5899
5905
|
if (!asyncDir) continue;
|
|
5900
5906
|
const result = reconcileAsyncRun(asyncDir, {
|
|
5901
5907
|
...options,
|
|
5902
|
-
resultsDir:
|
|
5908
|
+
resultsDir: path14.join(options.resultsDir ?? DIRS.results, "nested", route.rootRunId)
|
|
5903
5909
|
});
|
|
5904
5910
|
const status = result.status;
|
|
5905
5911
|
if (!status) continue;
|
|
@@ -5927,7 +5933,7 @@ function checkPidLiveness(pid, kill = process.kill, probeZombie = false) {
|
|
|
5927
5933
|
kill(pid, 0);
|
|
5928
5934
|
if (probeZombie && process.platform === "linux") {
|
|
5929
5935
|
try {
|
|
5930
|
-
const stat =
|
|
5936
|
+
const stat = fs15.readFileSync(`/proc/${pid}/stat`, "utf-8");
|
|
5931
5937
|
const closeParen = stat.lastIndexOf(") ");
|
|
5932
5938
|
if (closeParen >= 0 && stat[closeParen + 2] === "Z") return "dead";
|
|
5933
5939
|
} catch {
|
|
@@ -5961,14 +5967,14 @@ function reconcileAsyncRun(asyncDir, options = {}, observeStatus) {
|
|
|
5961
5967
|
const startedStatus = !status && options.startedRun ? buildStartedStatus(asyncDir, options.startedRun, now) : void 0;
|
|
5962
5968
|
const effectiveStatus = status ?? startedStatus;
|
|
5963
5969
|
if (!effectiveStatus) return { status: null, repaired: false };
|
|
5964
|
-
assertWorkflowGraphHostSteps(effectiveStatus.workflowGraph,
|
|
5965
|
-
const statusPath =
|
|
5970
|
+
assertWorkflowGraphHostSteps(effectiveStatus.workflowGraph, path14.join(asyncDir, "status.json"), effectiveStatus.runId);
|
|
5971
|
+
const statusPath = path14.join(asyncDir, "status.json");
|
|
5966
5972
|
for (const [index, step] of (effectiveStatus.steps ?? []).entries()) {
|
|
5967
5973
|
const stepRecord = step;
|
|
5968
5974
|
if (stepRecord.model !== void 0 && typeof stepRecord.model !== "string") throw new Error(`Invalid async status file '${statusPath}': steps[${index}].model must be a string.`);
|
|
5969
5975
|
if (stepRecord.thinking !== void 0 && typeof stepRecord.thinking !== "string") throw new Error(`Invalid async status file '${statusPath}': steps[${index}].thinking must be a string.`);
|
|
5970
5976
|
}
|
|
5971
|
-
const runId = effectiveStatus.runId ||
|
|
5977
|
+
const runId = effectiveStatus.runId || path14.basename(asyncDir);
|
|
5972
5978
|
const resultsDir = options.resultsDir ?? DIRS.results;
|
|
5973
5979
|
const resultPath = resultFilePath(resultsDir, runId);
|
|
5974
5980
|
const existingResultPath = effectiveStatus.sessionId ? resultPayloadPathForSessionRun(resultsDir, effectiveStatus.sessionId, runId) ?? (regularFileExists(resultPath) ? resultPath : void 0) : regularFileExists(resultPath) ? resultPath : void 0;
|
|
@@ -6065,19 +6071,19 @@ function validateAuthorityPolicy(value, label = "config.authorityPolicy") {
|
|
|
6065
6071
|
}
|
|
6066
6072
|
|
|
6067
6073
|
// src/runs/shared/worktree.ts
|
|
6068
|
-
import { createHash as
|
|
6074
|
+
import { createHash as createHash5 } from "node:crypto";
|
|
6069
6075
|
import { spawnSync } from "node:child_process";
|
|
6070
6076
|
|
|
6071
6077
|
// src/runs/shared/worktree-setup-command.ts
|
|
6072
6078
|
import { spawn as spawn2 } from "node:child_process";
|
|
6073
6079
|
function terminateCommandTree(pid, controller) {
|
|
6074
6080
|
if (process.platform !== "win32") return controller.terminate();
|
|
6075
|
-
return new Promise((
|
|
6081
|
+
return new Promise((resolve5) => {
|
|
6076
6082
|
let settled = false;
|
|
6077
6083
|
const fallback = () => {
|
|
6078
6084
|
if (settled) return;
|
|
6079
6085
|
settled = true;
|
|
6080
|
-
void controller.terminate().then(
|
|
6086
|
+
void controller.terminate().then(resolve5);
|
|
6081
6087
|
};
|
|
6082
6088
|
const cleanup = spawn2("taskkill", ["/PID", String(pid), "/T", "/F"], { stdio: "ignore", windowsHide: true });
|
|
6083
6089
|
cleanup.once("error", fallback);
|
|
@@ -6085,7 +6091,7 @@ function terminateCommandTree(pid, controller) {
|
|
|
6085
6091
|
if (settled) return;
|
|
6086
6092
|
if (status !== 0) return fallback();
|
|
6087
6093
|
settled = true;
|
|
6088
|
-
|
|
6094
|
+
resolve5({ state: "observed", mechanism: "windows-taskkill", pid, verifiedAt: Date.now() });
|
|
6089
6095
|
});
|
|
6090
6096
|
});
|
|
6091
6097
|
}
|
|
@@ -6187,21 +6193,21 @@ async function runSetupCommand(command, args, options) {
|
|
|
6187
6193
|
child.stdout.on("data", onStdout);
|
|
6188
6194
|
child.stderr.on("data", onStderr);
|
|
6189
6195
|
child.stdin.on("error", fail);
|
|
6190
|
-
const close = new Promise((
|
|
6191
|
-
const directExit = new Promise((
|
|
6196
|
+
const close = new Promise((resolve5) => child.once("close", () => resolve5()));
|
|
6197
|
+
const directExit = new Promise((resolve5) => {
|
|
6192
6198
|
child.once("exit", (status, signal) => {
|
|
6193
6199
|
directSettled = true;
|
|
6194
6200
|
result.status = status;
|
|
6195
6201
|
result.signal = signal;
|
|
6196
6202
|
if (status === null || !(options.acceptedExitCodes ?? [0]).includes(status)) terminate();
|
|
6197
6203
|
releaseUnknownIO();
|
|
6198
|
-
|
|
6204
|
+
resolve5();
|
|
6199
6205
|
});
|
|
6200
6206
|
child.once("error", (error) => {
|
|
6201
6207
|
fail(error);
|
|
6202
6208
|
if (child.pid === void 0) {
|
|
6203
6209
|
directSettled = true;
|
|
6204
|
-
|
|
6210
|
+
resolve5();
|
|
6205
6211
|
}
|
|
6206
6212
|
});
|
|
6207
6213
|
});
|
|
@@ -6249,13 +6255,13 @@ async function runSetupCommand(command, args, options) {
|
|
|
6249
6255
|
}
|
|
6250
6256
|
|
|
6251
6257
|
// src/runs/shared/worktree.ts
|
|
6252
|
-
import * as
|
|
6258
|
+
import * as fs16 from "node:fs";
|
|
6253
6259
|
import * as os2 from "node:os";
|
|
6254
|
-
import * as
|
|
6260
|
+
import * as path15 from "node:path";
|
|
6255
6261
|
var DEFAULT_WORKTREE_PROVIDER = "auto";
|
|
6256
6262
|
var DEFAULT_WORKTREE_BASE_REF = "HEAD";
|
|
6257
6263
|
var DEFAULT_WORKTREE_BRANCH_PREFIX = "pi-subagents/";
|
|
6258
|
-
var WORKTREE_AGENT_CWD_PLACEHOLDER =
|
|
6264
|
+
var WORKTREE_AGENT_CWD_PLACEHOLDER = path15.join(path15.parse(process.cwd()).root, "__pi_subagents_worktree_cwd__");
|
|
6259
6265
|
var WORKTREE_NAMING_COMPONENT_MAX_BYTES = 96;
|
|
6260
6266
|
var WORKTREE_NAMING_LABEL_MAX_BYTES = 256;
|
|
6261
6267
|
var WORKTREE_NAMING_BRANCH_MAX_BYTES = 256;
|
|
@@ -6284,8 +6290,8 @@ function assertWorktreeMutationAllowed() {
|
|
|
6284
6290
|
async function withWorktreeTransaction(action) {
|
|
6285
6291
|
const previous = worktreeTurn;
|
|
6286
6292
|
let release;
|
|
6287
|
-
worktreeTurn = new Promise((
|
|
6288
|
-
release =
|
|
6293
|
+
worktreeTurn = new Promise((resolve5) => {
|
|
6294
|
+
release = resolve5;
|
|
6289
6295
|
});
|
|
6290
6296
|
await previous;
|
|
6291
6297
|
try {
|
|
@@ -6389,7 +6395,7 @@ function findListedWorktreeAgentCwd(repoCwd, branch) {
|
|
|
6389
6395
|
const worktree = findListedWorktreeOnBranch(repoCwd, branch);
|
|
6390
6396
|
if (!worktree) return void 0;
|
|
6391
6397
|
const cwdRelative = resolveRepoCwdRelative(repoCwd);
|
|
6392
|
-
return cwdRelative ?
|
|
6398
|
+
return cwdRelative ? path15.join(worktree, cwdRelative) : worktree;
|
|
6393
6399
|
}
|
|
6394
6400
|
function isComparablePathInside(parent, child) {
|
|
6395
6401
|
return isPathInside(normalizeComparableCwd(parent), normalizeComparableCwd(child));
|
|
@@ -6403,11 +6409,11 @@ function currentWorktreePatch(worktreePath, baseCommit) {
|
|
|
6403
6409
|
assertWorktreeMutationAllowed();
|
|
6404
6410
|
let tempDir;
|
|
6405
6411
|
try {
|
|
6406
|
-
tempDir =
|
|
6412
|
+
tempDir = fs16.mkdtempSync(path15.join(os2.tmpdir(), "pi-worktree-index-"));
|
|
6407
6413
|
} catch (error) {
|
|
6408
6414
|
return { error: error instanceof Error ? error.message : String(error) };
|
|
6409
6415
|
}
|
|
6410
|
-
const env = { GIT_INDEX_FILE:
|
|
6416
|
+
const env = { GIT_INDEX_FILE: path15.join(tempDir, "index") };
|
|
6411
6417
|
try {
|
|
6412
6418
|
const readTree = runGit(worktreePath, ["read-tree", "HEAD"], env);
|
|
6413
6419
|
if (readTree.status !== 0) return { error: readTree.stderr.trim() || readTree.stdout.trim() || "git read-tree failed" };
|
|
@@ -6418,7 +6424,7 @@ function currentWorktreePatch(worktreePath, baseCommit) {
|
|
|
6418
6424
|
return { patch: diff.stdout };
|
|
6419
6425
|
} finally {
|
|
6420
6426
|
try {
|
|
6421
|
-
|
|
6427
|
+
fs16.rmSync(tempDir, { recursive: true, force: true });
|
|
6422
6428
|
} catch {
|
|
6423
6429
|
}
|
|
6424
6430
|
}
|
|
@@ -6428,7 +6434,7 @@ function validateWorktreePatchRepresentsCurrentWorktree(worktreePath, baseCommit
|
|
|
6428
6434
|
if (validationError) return validationError;
|
|
6429
6435
|
let capturedPatch;
|
|
6430
6436
|
try {
|
|
6431
|
-
capturedPatch =
|
|
6437
|
+
capturedPatch = fs16.readFileSync(patchPath, "utf-8");
|
|
6432
6438
|
} catch (error) {
|
|
6433
6439
|
return error instanceof Error ? error.message : String(error);
|
|
6434
6440
|
}
|
|
@@ -6461,7 +6467,7 @@ async function preflightWorktreeSource(cwd, options = {}) {
|
|
|
6461
6467
|
async function resolveRepoState(tx, cwd, requestedBaseRef) {
|
|
6462
6468
|
const toplevel = await probeWorktreeSource(tx, cwd);
|
|
6463
6469
|
const rawPrefix = (await tx.gitChecked(cwd, ["rev-parse", "--show-prefix"])).trim();
|
|
6464
|
-
const cwdRelative = rawPrefix ?
|
|
6470
|
+
const cwdRelative = rawPrefix ? path15.normalize(rawPrefix.replace(/[\\/]+$/, "")) : "";
|
|
6465
6471
|
const baseRef = normalizeWorktreeBaseRef(requestedBaseRef) ?? DEFAULT_WORKTREE_BASE_REF;
|
|
6466
6472
|
let baseCommit;
|
|
6467
6473
|
try {
|
|
@@ -6475,22 +6481,22 @@ async function resolveRepoState(tx, cwd, requestedBaseRef) {
|
|
|
6475
6481
|
return { toplevel, cwdRelative, baseCommit };
|
|
6476
6482
|
}
|
|
6477
6483
|
function normalizeComparableCwd(cwd) {
|
|
6478
|
-
const resolved2 =
|
|
6484
|
+
const resolved2 = path15.resolve(cwd);
|
|
6479
6485
|
let existing = resolved2;
|
|
6480
6486
|
const missingSegments = [];
|
|
6481
6487
|
while (true) {
|
|
6482
6488
|
try {
|
|
6483
6489
|
let realpath;
|
|
6484
6490
|
try {
|
|
6485
|
-
realpath =
|
|
6491
|
+
realpath = fs16.realpathSync.native(existing);
|
|
6486
6492
|
} catch {
|
|
6487
|
-
realpath =
|
|
6493
|
+
realpath = fs16.realpathSync(existing);
|
|
6488
6494
|
}
|
|
6489
|
-
return
|
|
6495
|
+
return path15.join(realpath, ...missingSegments.reverse());
|
|
6490
6496
|
} catch {
|
|
6491
|
-
const parent =
|
|
6497
|
+
const parent = path15.dirname(existing);
|
|
6492
6498
|
if (parent === existing) return resolved2;
|
|
6493
|
-
missingSegments.push(
|
|
6499
|
+
missingSegments.push(path15.basename(existing));
|
|
6494
6500
|
existing = parent;
|
|
6495
6501
|
}
|
|
6496
6502
|
}
|
|
@@ -6499,7 +6505,7 @@ function safePatchAgentName(agent) {
|
|
|
6499
6505
|
return agent.replace(/[^\w.-]/g, "_");
|
|
6500
6506
|
}
|
|
6501
6507
|
function shortWorktreeHash(value) {
|
|
6502
|
-
return
|
|
6508
|
+
return createHash5("sha256").update(value, "utf-8").digest("hex").slice(0, 8);
|
|
6503
6509
|
}
|
|
6504
6510
|
function truncateUtf8(value, maxBytes) {
|
|
6505
6511
|
const bytes = Buffer.from(value, "utf-8");
|
|
@@ -6584,7 +6590,7 @@ function hasConfiguredWorktreeBaseDir(baseDir) {
|
|
|
6584
6590
|
return baseDir !== void 0 ? true : (process.env.PI_SUBAGENTS_WORKTREE_DIR?.trim().length ?? 0) > 0;
|
|
6585
6591
|
}
|
|
6586
6592
|
function isInsidePiExtensionsDirectory(targetPath) {
|
|
6587
|
-
const extensionsDir = normalizeComparableCwd(
|
|
6593
|
+
const extensionsDir = normalizeComparableCwd(path15.join(getAgentDir(), "extensions"));
|
|
6588
6594
|
return isPathInside(extensionsDir, normalizeComparableCwd(targetPath));
|
|
6589
6595
|
}
|
|
6590
6596
|
function runWorktrunk(args, cwd) {
|
|
@@ -6666,49 +6672,49 @@ function resolveWorktreeDedicatedRoot(configuredBaseDir, repoRoot, relocateExten
|
|
|
6666
6672
|
const rawBaseDir = configuredBaseDir ?? process.env.PI_SUBAGENTS_WORKTREE_DIR;
|
|
6667
6673
|
let expanded;
|
|
6668
6674
|
if (rawBaseDir === void 0 || configuredBaseDir === void 0 && !rawBaseDir.trim()) {
|
|
6669
|
-
expanded = relocateExtensionRepo && isInsidePiExtensionsDirectory(repoRoot) ?
|
|
6675
|
+
expanded = relocateExtensionRepo && isInsidePiExtensionsDirectory(repoRoot) ? path15.join(getAgentDir(), "worktrees") : path15.join(path15.dirname(repoRoot), "worktrees");
|
|
6670
6676
|
} else {
|
|
6671
6677
|
const trimmed = rawBaseDir.trim();
|
|
6672
6678
|
if (!trimmed) throw new Error("worktree base directory cannot be empty");
|
|
6673
|
-
const candidate = trimmed.startsWith("~/") ?
|
|
6674
|
-
expanded =
|
|
6679
|
+
const candidate = trimmed.startsWith("~/") ? path15.join(os2.homedir(), trimmed.slice(2)) : trimmed;
|
|
6680
|
+
expanded = path15.isAbsolute(candidate) ? candidate : path15.resolve(repoRoot, candidate);
|
|
6675
6681
|
}
|
|
6676
|
-
const extensionsDir = normalizeComparableCwd(
|
|
6682
|
+
const extensionsDir = normalizeComparableCwd(path15.join(getAgentDir(), "extensions"));
|
|
6677
6683
|
if (isPathInside(extensionsDir, normalizeComparableCwd(expanded))) {
|
|
6678
6684
|
throw new Error(`worktree base directory cannot be inside Pi extensions directory: ${extensionsDir}. Choose a directory outside it.`);
|
|
6679
6685
|
}
|
|
6680
6686
|
return expanded;
|
|
6681
6687
|
}
|
|
6682
6688
|
function buildNativeProjectPath(dedicatedRoot, repoRoot) {
|
|
6683
|
-
return
|
|
6689
|
+
return path15.join(dedicatedRoot, path15.basename(repoRoot));
|
|
6684
6690
|
}
|
|
6685
6691
|
function ensureProjectWorktreeDir(dedicatedRoot, repoRoot) {
|
|
6686
6692
|
try {
|
|
6687
|
-
|
|
6693
|
+
fs16.mkdirSync(buildNativeProjectPath(dedicatedRoot, repoRoot), { recursive: true });
|
|
6688
6694
|
} catch (error) {
|
|
6689
6695
|
const message = error instanceof Error ? error.message : String(error);
|
|
6690
6696
|
throw new Error(`failed to create worktree base directory ${dedicatedRoot}: ${message}`);
|
|
6691
6697
|
}
|
|
6692
6698
|
}
|
|
6693
6699
|
function buildNativeWorktreePath(dedicatedRoot, repoRoot, runId, index) {
|
|
6694
|
-
return
|
|
6700
|
+
return path15.join(buildNativeProjectPath(dedicatedRoot, repoRoot), `pi-worktree-${sanitizeWorktreePathComponent(runId, 120)}-${index}`);
|
|
6695
6701
|
}
|
|
6696
6702
|
function isPathInside(parent, child) {
|
|
6697
|
-
const relative4 =
|
|
6703
|
+
const relative4 = path15.relative(parent, child);
|
|
6698
6704
|
if (!relative4 || relative4 === ".") return true;
|
|
6699
|
-
return relative4 !== ".." && !relative4.startsWith(`..${
|
|
6705
|
+
return relative4 !== ".." && !relative4.startsWith(`..${path15.sep}`) && !path15.isAbsolute(relative4);
|
|
6700
6706
|
}
|
|
6701
6707
|
function isStrictChildPath(parent, child) {
|
|
6702
|
-
const relative4 =
|
|
6703
|
-
return Boolean(relative4) && relative4 !== "." && relative4 !== ".." && !relative4.startsWith(`..${
|
|
6708
|
+
const relative4 = path15.relative(parent, child);
|
|
6709
|
+
return Boolean(relative4) && relative4 !== "." && relative4 !== ".." && !relative4.startsWith(`..${path15.sep}`) && !path15.isAbsolute(relative4);
|
|
6704
6710
|
}
|
|
6705
6711
|
function assertSafeWorktreeLocation(worktreePath, repoRoot, dedicatedRoot) {
|
|
6706
6712
|
const resolvedLeaf = normalizeComparableCwd(worktreePath);
|
|
6707
6713
|
const resolvedRepoRoot = normalizeComparableCwd(repoRoot);
|
|
6708
6714
|
const projectDir = normalizeComparableCwd(buildNativeProjectPath(dedicatedRoot, repoRoot));
|
|
6709
|
-
const repoParent = normalizeComparableCwd(
|
|
6710
|
-
const leafParent = normalizeComparableCwd(
|
|
6711
|
-
const extensionsDir = normalizeComparableCwd(
|
|
6715
|
+
const repoParent = normalizeComparableCwd(path15.dirname(resolvedRepoRoot));
|
|
6716
|
+
const leafParent = normalizeComparableCwd(path15.dirname(resolvedLeaf));
|
|
6717
|
+
const extensionsDir = normalizeComparableCwd(path15.join(getAgentDir(), "extensions"));
|
|
6712
6718
|
if (isPathInside(extensionsDir, projectDir) || isPathInside(extensionsDir, resolvedLeaf)) {
|
|
6713
6719
|
throw new Error(`worktree path cannot be inside Pi extensions directory: ${extensionsDir}. Choose a directory outside it.`);
|
|
6714
6720
|
}
|
|
@@ -6728,7 +6734,7 @@ function resolveRepoCwdRelative(cwd) {
|
|
|
6728
6734
|
throw new Error("worktree isolation requires a git repository");
|
|
6729
6735
|
}
|
|
6730
6736
|
const rawPrefix = runGitChecked(cwd, ["rev-parse", "--show-prefix"]).trim();
|
|
6731
|
-
const normalizedPrefix = rawPrefix ?
|
|
6737
|
+
const normalizedPrefix = rawPrefix ? path15.normalize(rawPrefix.replace(/[\\/]+$/, "")) : "";
|
|
6732
6738
|
return normalizedPrefix === "." ? "" : normalizedPrefix;
|
|
6733
6739
|
}
|
|
6734
6740
|
function resolveExpectedWorktreeAgentCwd(cwd, runId, index, baseDir) {
|
|
@@ -6737,14 +6743,14 @@ function resolveExpectedWorktreeAgentCwd(cwd, runId, index, baseDir) {
|
|
|
6737
6743
|
const dedicatedRoot = resolveWorktreeDedicatedRoot(baseDir, repoRoot);
|
|
6738
6744
|
const worktreePath = buildNativeWorktreePath(dedicatedRoot, repoRoot, runId, index);
|
|
6739
6745
|
assertSafeWorktreeLocation(worktreePath, repoRoot, dedicatedRoot);
|
|
6740
|
-
return cwdRelative ?
|
|
6746
|
+
return cwdRelative ? path15.join(worktreePath, cwdRelative) : worktreePath;
|
|
6741
6747
|
}
|
|
6742
6748
|
function linkNodeModulesIfPresent(toplevel, worktreePath) {
|
|
6743
|
-
const nodeModulesPath =
|
|
6744
|
-
const nodeModulesLinkPath =
|
|
6749
|
+
const nodeModulesPath = path15.join(toplevel, "node_modules");
|
|
6750
|
+
const nodeModulesLinkPath = path15.join(worktreePath, "node_modules");
|
|
6745
6751
|
const hasDirectoryEntry = (candidate) => {
|
|
6746
6752
|
try {
|
|
6747
|
-
|
|
6753
|
+
fs16.lstatSync(candidate);
|
|
6748
6754
|
return true;
|
|
6749
6755
|
} catch (error) {
|
|
6750
6756
|
if (error instanceof Error && "code" in error && error.code === "ENOENT") return false;
|
|
@@ -6755,14 +6761,14 @@ function linkNodeModulesIfPresent(toplevel, worktreePath) {
|
|
|
6755
6761
|
if (hasDirectoryEntry(nodeModulesLinkPath)) return false;
|
|
6756
6762
|
let sourceRealPath;
|
|
6757
6763
|
try {
|
|
6758
|
-
if (!
|
|
6759
|
-
sourceRealPath =
|
|
6764
|
+
if (!fs16.statSync(nodeModulesPath).isDirectory()) throw new Error("source node_modules is not a directory");
|
|
6765
|
+
sourceRealPath = fs16.realpathSync.native(nodeModulesPath);
|
|
6760
6766
|
} catch (error) {
|
|
6761
6767
|
if (error instanceof Error && "code" in error && error.code === "ENOENT") return false;
|
|
6762
6768
|
throw error;
|
|
6763
6769
|
}
|
|
6764
|
-
|
|
6765
|
-
if (!
|
|
6770
|
+
fs16.symlinkSync(nodeModulesPath, nodeModulesLinkPath, process.platform === "win32" ? "junction" : "dir");
|
|
6771
|
+
if (!fs16.lstatSync(nodeModulesLinkPath).isSymbolicLink() || fs16.realpathSync.native(nodeModulesLinkPath) !== sourceRealPath) {
|
|
6766
6772
|
throw new Error("created link does not resolve to the source node_modules");
|
|
6767
6773
|
}
|
|
6768
6774
|
return true;
|
|
@@ -6787,19 +6793,19 @@ function resolveWorktreeSetupHook(repoRoot, config) {
|
|
|
6787
6793
|
if (!hookPath) {
|
|
6788
6794
|
throw new Error("worktree setup hook path cannot be empty");
|
|
6789
6795
|
}
|
|
6790
|
-
const expandedHookPath = hookPath.startsWith("~/") ?
|
|
6796
|
+
const expandedHookPath = hookPath.startsWith("~/") ? path15.join(os2.homedir(), hookPath.slice(2)) : hookPath;
|
|
6791
6797
|
let resolvedPath;
|
|
6792
|
-
if (
|
|
6798
|
+
if (path15.isAbsolute(expandedHookPath)) {
|
|
6793
6799
|
resolvedPath = expandedHookPath;
|
|
6794
6800
|
} else if (expandedHookPath.includes("/") || expandedHookPath.includes("\\")) {
|
|
6795
|
-
resolvedPath =
|
|
6801
|
+
resolvedPath = path15.resolve(repoRoot, expandedHookPath);
|
|
6796
6802
|
} else {
|
|
6797
6803
|
throw new Error("worktree setup hook must be an absolute path or a repo-relative path");
|
|
6798
6804
|
}
|
|
6799
|
-
if (!
|
|
6805
|
+
if (!fs16.existsSync(resolvedPath)) {
|
|
6800
6806
|
throw new Error(`worktree setup hook not found: ${resolvedPath}`);
|
|
6801
6807
|
}
|
|
6802
|
-
if (
|
|
6808
|
+
if (fs16.statSync(resolvedPath).isDirectory()) {
|
|
6803
6809
|
throw new Error(`worktree setup hook must be a file, got directory: ${resolvedPath}`);
|
|
6804
6810
|
}
|
|
6805
6811
|
return {
|
|
@@ -6810,16 +6816,16 @@ function resolveWorktreeSetupHook(repoRoot, config) {
|
|
|
6810
6816
|
function normalizeSyntheticPath(worktreePath, rawPath) {
|
|
6811
6817
|
const trimmed = rawPath.trim();
|
|
6812
6818
|
if (!trimmed) throw new Error("synthetic path cannot be empty");
|
|
6813
|
-
if (
|
|
6814
|
-
const resolved2 =
|
|
6815
|
-
const relative4 =
|
|
6819
|
+
if (path15.isAbsolute(trimmed)) throw new Error(`synthetic path must be relative: ${rawPath}`);
|
|
6820
|
+
const resolved2 = path15.resolve(worktreePath, trimmed);
|
|
6821
|
+
const relative4 = path15.relative(worktreePath, resolved2);
|
|
6816
6822
|
if (!relative4 || relative4 === ".") {
|
|
6817
6823
|
throw new Error(`synthetic path cannot target the worktree root: ${rawPath}`);
|
|
6818
6824
|
}
|
|
6819
|
-
if (relative4 === ".." || relative4.startsWith(`..${
|
|
6825
|
+
if (relative4 === ".." || relative4.startsWith(`..${path15.sep}`) || path15.isAbsolute(relative4)) {
|
|
6820
6826
|
throw new Error(`synthetic path escapes the worktree root: ${rawPath}`);
|
|
6821
6827
|
}
|
|
6822
|
-
return
|
|
6828
|
+
return path15.normalize(relative4);
|
|
6823
6829
|
}
|
|
6824
6830
|
function parseWorktreeSetupHookOutput(rawStdout) {
|
|
6825
6831
|
const trimmed = rawStdout.trim();
|
|
@@ -6873,7 +6879,7 @@ async function runWorktreeSetupHook(tx, hook, input) {
|
|
|
6873
6879
|
}
|
|
6874
6880
|
}
|
|
6875
6881
|
async function finalizeCreatedWorktree(tx, toplevel, cwdRelative, runId, baseCommit, setupHook, agent, worktree) {
|
|
6876
|
-
const agentCwd = cwdRelative ?
|
|
6882
|
+
const agentCwd = cwdRelative ? path15.join(worktree.path, cwdRelative) : worktree.path;
|
|
6877
6883
|
tx.check();
|
|
6878
6884
|
const nodeModulesLinked = linkNodeModulesIfPresent(toplevel, worktree.path);
|
|
6879
6885
|
const syntheticPaths = nodeModulesLinked ? ["node_modules"] : [];
|
|
@@ -6900,7 +6906,7 @@ async function createNativeWorktree(tx, toplevel, cwdRelative, runId, index, bas
|
|
|
6900
6906
|
const branch = await tx.git(toplevel, ["show-ref", "--verify", "--quiet", `refs/heads/${naming.requestedBranch}`], [0, 1]);
|
|
6901
6907
|
let pathExists = false;
|
|
6902
6908
|
try {
|
|
6903
|
-
|
|
6909
|
+
fs16.lstatSync(worktreePath);
|
|
6904
6910
|
pathExists = true;
|
|
6905
6911
|
} catch (error) {
|
|
6906
6912
|
if (!(error instanceof Error) || !("code" in error) || error.code !== "ENOENT") throw error;
|
|
@@ -6908,7 +6914,7 @@ async function createNativeWorktree(tx, toplevel, cwdRelative, runId, index, bas
|
|
|
6908
6914
|
if (branch.status !== 1 || pathExists) throw new Error(`worktree path or branch already exists: ${worktreePath}, ${naming.requestedBranch}`);
|
|
6909
6915
|
tx.attempt(index, naming.requestedBranch, worktreePath);
|
|
6910
6916
|
ensureProjectWorktreeDir(dedicatedRoot, toplevel);
|
|
6911
|
-
const recordedBaseDir = normalizeComparableCwd(
|
|
6917
|
+
const recordedBaseDir = normalizeComparableCwd(path15.dirname(worktreePath));
|
|
6912
6918
|
await tx.git(toplevel, ["worktree", "add", worktreePath, "-b", naming.requestedBranch, baseCommit]);
|
|
6913
6919
|
const worktree = {
|
|
6914
6920
|
path: worktreePath,
|
|
@@ -6948,11 +6954,11 @@ async function createWorktrunkWorktree(tx, toplevel, cwdRelative, runId, index,
|
|
|
6948
6954
|
if (output.action !== "created" || output.created_branch !== true || output.branch !== naming.requestedBranch || output.base_branch !== baseCommit) {
|
|
6949
6955
|
throw new Error("Worktrunk provisioning returned inconsistent creation metadata");
|
|
6950
6956
|
}
|
|
6951
|
-
if (typeof output.path !== "string" || !
|
|
6952
|
-
const worktreePathCandidate =
|
|
6957
|
+
if (typeof output.path !== "string" || !path15.isAbsolute(output.path)) throw new Error("Worktrunk provisioning returned a non-absolute worktree path");
|
|
6958
|
+
const worktreePathCandidate = path15.resolve(output.path);
|
|
6953
6959
|
let stat;
|
|
6954
6960
|
try {
|
|
6955
|
-
stat =
|
|
6961
|
+
stat = fs16.lstatSync(worktreePathCandidate);
|
|
6956
6962
|
} catch (error) {
|
|
6957
6963
|
throw new Error(`Worktrunk provisioning returned a missing worktree path: ${worktreePathCandidate}`, { cause: error instanceof Error ? error : void 0 });
|
|
6958
6964
|
}
|
|
@@ -6961,8 +6967,8 @@ async function createWorktrunkWorktree(tx, toplevel, cwdRelative, runId, index,
|
|
|
6961
6967
|
if (worktreePath === normalizeComparableCwd(toplevel)) throw new Error("Worktrunk provisioning returned the source checkout path");
|
|
6962
6968
|
const sourceCommonDirRaw = (await tx.gitChecked(toplevel, ["rev-parse", "--git-common-dir"])).trim();
|
|
6963
6969
|
const returnedCommonDirRaw = (await tx.gitChecked(worktreePath, ["rev-parse", "--git-common-dir"])).trim();
|
|
6964
|
-
const sourceCommonDir = normalizeComparableCwd(
|
|
6965
|
-
const returnedCommonDir = normalizeComparableCwd(
|
|
6970
|
+
const sourceCommonDir = normalizeComparableCwd(path15.isAbsolute(sourceCommonDirRaw) ? sourceCommonDirRaw : path15.resolve(toplevel, sourceCommonDirRaw));
|
|
6971
|
+
const returnedCommonDir = normalizeComparableCwd(path15.isAbsolute(returnedCommonDirRaw) ? returnedCommonDirRaw : path15.resolve(worktreePath, returnedCommonDirRaw));
|
|
6966
6972
|
if (returnedCommonDir !== sourceCommonDir) throw new Error("Worktrunk provisioning returned a worktree for a different repository");
|
|
6967
6973
|
const returnedBranch = (await tx.gitChecked(worktreePath, ["symbolic-ref", "--quiet", "--short", "HEAD"])).trim();
|
|
6968
6974
|
if (returnedBranch !== naming.requestedBranch) throw new Error("Worktrunk provisioning returned a worktree on a different branch");
|
|
@@ -6970,8 +6976,8 @@ async function createWorktrunkWorktree(tx, toplevel, cwdRelative, runId, index,
|
|
|
6970
6976
|
if (returnedHead !== baseCommit) throw new Error("Worktrunk provisioning returned a worktree at a different base commit");
|
|
6971
6977
|
const worktree = {
|
|
6972
6978
|
path: worktreePath,
|
|
6973
|
-
recordedBaseDir: normalizeComparableCwd(
|
|
6974
|
-
agentCwd: cwdRelative ?
|
|
6979
|
+
recordedBaseDir: normalizeComparableCwd(path15.dirname(worktreePath)),
|
|
6980
|
+
agentCwd: cwdRelative ? path15.join(worktreePath, cwdRelative) : worktreePath,
|
|
6975
6981
|
branch: naming.requestedBranch,
|
|
6976
6982
|
index,
|
|
6977
6983
|
nodeModulesLinked: false,
|
|
@@ -6988,28 +6994,28 @@ async function createWorktrunkWorktree(tx, toplevel, cwdRelative, runId, index,
|
|
|
6988
6994
|
}
|
|
6989
6995
|
function removeSyntheticPath(worktree, syntheticPath) {
|
|
6990
6996
|
assertWorktreeMutationAllowed();
|
|
6991
|
-
const resolved2 =
|
|
6992
|
-
const relative4 =
|
|
6993
|
-
if (!relative4 || relative4 === "." || relative4 === ".." || relative4.startsWith(`..${
|
|
6997
|
+
const resolved2 = path15.resolve(worktree.path, syntheticPath);
|
|
6998
|
+
const relative4 = path15.relative(worktree.path, resolved2);
|
|
6999
|
+
if (!relative4 || relative4 === "." || relative4 === ".." || relative4.startsWith(`..${path15.sep}`) || path15.isAbsolute(relative4)) {
|
|
6994
7000
|
return;
|
|
6995
7001
|
}
|
|
6996
7002
|
let stat;
|
|
6997
7003
|
try {
|
|
6998
|
-
stat =
|
|
7004
|
+
stat = fs16.lstatSync(resolved2);
|
|
6999
7005
|
} catch (error) {
|
|
7000
7006
|
const code = error && typeof error === "object" && "code" in error ? error.code : void 0;
|
|
7001
7007
|
if (code === "ENOENT") return;
|
|
7002
7008
|
throw error;
|
|
7003
7009
|
}
|
|
7004
7010
|
if (stat.isSymbolicLink()) {
|
|
7005
|
-
|
|
7011
|
+
fs16.unlinkSync(resolved2);
|
|
7006
7012
|
return;
|
|
7007
7013
|
}
|
|
7008
7014
|
if (stat.isDirectory()) {
|
|
7009
|
-
|
|
7015
|
+
fs16.rmSync(resolved2, { recursive: true, force: true });
|
|
7010
7016
|
return;
|
|
7011
7017
|
}
|
|
7012
|
-
|
|
7018
|
+
fs16.rmSync(resolved2, { force: true });
|
|
7013
7019
|
}
|
|
7014
7020
|
function removeSyntheticPathsBeforeDiff(worktree) {
|
|
7015
7021
|
if (worktree.syntheticPaths.length === 0) return;
|
|
@@ -7053,7 +7059,7 @@ function captureWorktreeDiff(setup, worktree, agent, patchPath) {
|
|
|
7053
7059
|
const diffStat = runGitChecked(worktree.path, ["diff", "--cached", ...MACHINE_DIFF_OPTIONS, "--stat", setup.baseCommit]).trim();
|
|
7054
7060
|
const patch = runGitChecked(worktree.path, ["diff", "--cached", ...MACHINE_PATCH_OPTIONS, setup.baseCommit]);
|
|
7055
7061
|
const numstat = runGitChecked(worktree.path, ["diff", "--cached", ...MACHINE_DIFF_OPTIONS, "--numstat", setup.baseCommit]);
|
|
7056
|
-
|
|
7062
|
+
fs16.writeFileSync(patchPath, patch, "utf-8");
|
|
7057
7063
|
if (!patch.trim()) {
|
|
7058
7064
|
return emptyDiff(worktree.index, agent, worktree.branch, patchPath);
|
|
7059
7065
|
}
|
|
@@ -7073,18 +7079,18 @@ function captureWorktreeDiff(setup, worktree, agent, patchPath) {
|
|
|
7073
7079
|
}
|
|
7074
7080
|
function writeEmptyPatch(patchPath) {
|
|
7075
7081
|
try {
|
|
7076
|
-
|
|
7082
|
+
fs16.writeFileSync(patchPath, "", "utf-8");
|
|
7077
7083
|
} catch {
|
|
7078
7084
|
}
|
|
7079
7085
|
}
|
|
7080
7086
|
function handoffRecordsPatch(manifestPath, patchPath) {
|
|
7081
|
-
if (!manifestPath || !
|
|
7087
|
+
if (!manifestPath || !fs16.existsSync(manifestPath)) return false;
|
|
7082
7088
|
try {
|
|
7083
|
-
const manifest = JSON.parse(
|
|
7089
|
+
const manifest = JSON.parse(fs16.readFileSync(manifestPath, "utf-8"));
|
|
7084
7090
|
if (manifest.version !== 1 || !Array.isArray(manifest.groups)) return false;
|
|
7085
|
-
const resolvedPatchPath =
|
|
7091
|
+
const resolvedPatchPath = path15.resolve(patchPath);
|
|
7086
7092
|
return manifest.groups.some((group) => Array.isArray(group.children) && group.children.some(
|
|
7087
|
-
(child) => child.patch?.error === void 0 && typeof child.patch?.path === "string" &&
|
|
7093
|
+
(child) => child.patch?.error === void 0 && typeof child.patch?.path === "string" && path15.resolve(child.patch.path) === resolvedPatchPath
|
|
7088
7094
|
));
|
|
7089
7095
|
} catch {
|
|
7090
7096
|
return false;
|
|
@@ -7137,9 +7143,9 @@ function cleanupSingleWorktree(setup, worktree, intent) {
|
|
|
7137
7143
|
const captured = (intent.capturedDiffs ?? setup.capturedDiffs)?.find((diff) => diff.index === worktree.index);
|
|
7138
7144
|
let patchValidationError;
|
|
7139
7145
|
let patchCaptured = false;
|
|
7140
|
-
if (captured !== void 0 && captured.error === void 0 &&
|
|
7146
|
+
if (captured !== void 0 && captured.error === void 0 && fs16.existsSync(captured.patchPath) && handoffRecordsPatch(intent.handoffManifestPath, captured.patchPath)) {
|
|
7141
7147
|
try {
|
|
7142
|
-
if (
|
|
7148
|
+
if (fs16.statSync(captured.patchPath).size > 0) {
|
|
7143
7149
|
patchValidationError = validateWorktreePatchRepresentsCurrentWorktree(worktree.path, setup.baseCommit, captured.patchPath);
|
|
7144
7150
|
patchCaptured = patchValidationError === void 0;
|
|
7145
7151
|
}
|
|
@@ -7269,7 +7275,7 @@ async function compensateSetup(tx) {
|
|
|
7269
7275
|
throw new Error(tx.progress.unknown);
|
|
7270
7276
|
}
|
|
7271
7277
|
await git(["worktree", "remove", "--force", attempt.path]);
|
|
7272
|
-
} else if (
|
|
7278
|
+
} else if (fs16.existsSync(attempt.path)) {
|
|
7273
7279
|
tx.unknown("Unregistered partial allocation retained");
|
|
7274
7280
|
throw new Error(tx.progress.unknown);
|
|
7275
7281
|
}
|
|
@@ -7389,7 +7395,7 @@ async function createWorktrees(cwd, runId, count, options = {}) {
|
|
|
7389
7395
|
function diffWorktrees(setup, agents, diffsDir) {
|
|
7390
7396
|
assertWorktreeMutationAllowed();
|
|
7391
7397
|
try {
|
|
7392
|
-
|
|
7398
|
+
fs16.mkdirSync(diffsDir, { recursive: true });
|
|
7393
7399
|
} catch {
|
|
7394
7400
|
return [];
|
|
7395
7401
|
}
|
|
@@ -7397,7 +7403,7 @@ function diffWorktrees(setup, agents, diffsDir) {
|
|
|
7397
7403
|
for (let index = 0; index < setup.worktrees.length; index++) {
|
|
7398
7404
|
const worktree = setup.worktrees[index];
|
|
7399
7405
|
const agent = agents[index] ?? `task-${index + 1}`;
|
|
7400
|
-
const patchPath =
|
|
7406
|
+
const patchPath = path15.join(diffsDir, `task-${index}-${safePatchAgentName(agent)}.patch`);
|
|
7401
7407
|
try {
|
|
7402
7408
|
diffs.push(captureWorktreeDiff(setup, worktree, agent, patchPath));
|
|
7403
7409
|
} catch (error) {
|
|
@@ -7444,7 +7450,7 @@ function formatWorktreeDiffSummary(diffs) {
|
|
|
7444
7450
|
}
|
|
7445
7451
|
lines.push("");
|
|
7446
7452
|
}
|
|
7447
|
-
const patchesDir =
|
|
7453
|
+
const patchesDir = path15.dirname(changed[0].patchPath);
|
|
7448
7454
|
lines.push(`Full patches: ${patchesDir}`);
|
|
7449
7455
|
return lines.join("\n").trimEnd();
|
|
7450
7456
|
}
|