pi-subagents 0.87.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 +32 -0
- package/bundle/agents.js +3 -3
- package/bundle/child-tool-plan.js +2 -2
- package/bundle/{chunk-3CVOAS77.js → chunk-2DIEL4WG.js} +2 -2
- package/bundle/{chunk-PGU4TZV3.js → chunk-3DT5X2QC.js} +406 -447
- package/bundle/{chunk-SIAQXPJ4.js → chunk-3MFYKBKI.js} +18 -6
- package/bundle/{chunk-AIL46SZU.js → chunk-47GJDBIK.js} +6 -4
- package/bundle/{chunk-ESWW6XSX.js → chunk-47ZN7NKR.js} +1 -1
- package/bundle/{chunk-C3KWLXDH.js → chunk-4MVDMA5C.js} +9 -1
- package/bundle/{chunk-DGTZKYIE.js → chunk-4PM6RDE5.js} +42 -29
- package/bundle/{chunk-EYGBK6CE.js → chunk-4UGWHREQ.js} +45 -15
- package/bundle/{chunk-HDICKROY.js → chunk-6EUQPQY7.js} +31 -14
- package/bundle/{chunk-LFKMM3UH.js → chunk-6OWNDN7R.js} +2 -2
- package/bundle/{chunk-M2VBGET6.js → chunk-6PR44R7E.js} +7 -2
- package/bundle/{chunk-OOE3R7IQ.js → chunk-CKLZ5FGU.js} +2 -2
- package/bundle/{chunk-W52LJANO.js → chunk-CYKNHFXB.js} +1 -1
- package/bundle/{chunk-6O7YH2QV.js → chunk-GDR2ILWY.js} +1 -1
- package/bundle/{chunk-2D2DQGC2.js → chunk-IZEKQEY4.js} +9 -9
- package/bundle/{chunk-C5QWQSSM.js → chunk-KXW62VBU.js} +1 -1
- package/bundle/{chunk-BFF6YDK6.js → chunk-L4YY2TOE.js} +1 -1
- package/bundle/{chunk-JLDQ6YUR.js → chunk-MTPICU4A.js} +11 -11
- package/bundle/{chunk-YEXKJJVS.js → chunk-PJSOS2Q4.js} +4 -4
- package/bundle/{chunk-2NY5PCKQ.js → chunk-RHYVKQQL.js} +4 -4
- package/bundle/{chunk-XV7RTWTS.js → chunk-SVIXQDIV.js} +20 -5
- package/bundle/{chunk-OTLDAYEQ.js → chunk-UVDLJXL6.js} +14 -5
- package/bundle/{chunk-VFUFOZBU.js → chunk-W6HIYD2Z.js} +1 -1
- package/bundle/{chunk-OZCPYJEY.js → chunk-XAOHLFJO.js} +118 -42
- package/bundle/{chunk-USRX7QXD.js → chunk-XIA5GSEU.js} +2 -2
- package/bundle/chunk-YDZ7BZD5.js +523 -0
- package/bundle/{chunk-LZKVUWIY.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 +8 -8
- package/bundle/project-panes.js +3 -3
- package/docs/agents.md +1 -1
- package/docs/configuration.md +7 -3
- package/docs/observability.md +2 -0
- package/docs/tool-reference.md +4 -1
- package/package.json +2 -2
- package/skills/pi-subagents/SKILL.md +8 -2
- package/src/agents/agent-management.d.ts +1 -0
- package/src/agents/agent-management.js +12 -4
- package/src/agents/agents.d.ts +1 -0
- package/src/agents/agents.js +2 -2
- package/src/extension/config.d.ts +1 -0
- package/src/extension/config.js +6 -0
- package/src/extension/index.js +4 -3
- package/src/extension/schemas.d.ts +2 -0
- package/src/extension/schemas.js +1 -0
- package/src/extension/tool-activation.js +20 -3
- 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/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/foreground/async-steering-action.js +24 -9
- package/src/runs/foreground/execution.js +32 -15
- package/src/runs/foreground/prompt-audit.js +1 -0
- package/src/runs/foreground/subagent-executor.d.ts +1 -8
- package/src/runs/foreground/subagent-executor.js +6 -15
- 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.js +21 -3
- package/src/runs/shared/mcp-config-sources.d.ts +2 -0
- package/src/runs/shared/mcp-direct-tool-allowlist.d.ts +0 -2
- package/src/runs/shared/mcp-direct-tool-allowlist.js +21 -11
- 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 +107 -9
- 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 +9 -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/permission-arbiter.js +1 -0
- package/src/watchdog/review.d.ts +0 -5
- package/src/watchdog/review.js +2 -1
- package/src/workflows/workflow-script-worker.js +3 -1
- package/bundle/chunk-XSDYTXHF.js +0 -242
|
@@ -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
|
}
|
|
@@ -2344,25 +2303,25 @@ function omitNonJsonWorkflowResultMetadata(value) {
|
|
|
2344
2303
|
return safeResult;
|
|
2345
2304
|
}
|
|
2346
2305
|
}
|
|
2347
|
-
function assertWorkflowJsonValue(value,
|
|
2306
|
+
function assertWorkflowJsonValue(value, path16 = "value", seen = /* @__PURE__ */ new Set()) {
|
|
2348
2307
|
if (value === null || typeof value === "string" || typeof value === "boolean") return;
|
|
2349
2308
|
if (typeof value === "number") {
|
|
2350
|
-
if (!Number.isFinite(value)) throw new Error(`${
|
|
2309
|
+
if (!Number.isFinite(value)) throw new Error(`${path16} must contain only finite JSON numbers.`);
|
|
2351
2310
|
return;
|
|
2352
2311
|
}
|
|
2353
|
-
if (typeof value !== "object") throw new Error(`${
|
|
2354
|
-
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.`);
|
|
2355
2314
|
seen.add(value);
|
|
2356
2315
|
if (Array.isArray(value)) {
|
|
2357
2316
|
for (let index = 0; index < value.length; index++) {
|
|
2358
|
-
if (!Object.hasOwn(value, index)) throw new Error(`${
|
|
2359
|
-
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);
|
|
2360
2319
|
}
|
|
2361
2320
|
} else {
|
|
2362
2321
|
const prototype = Object.getPrototypeOf(value);
|
|
2363
|
-
if (prototype !== null && prototype !== Object.prototype) throw new Error(`${
|
|
2364
|
-
if (Object.getOwnPropertySymbols(value).length > 0) throw new Error(`${
|
|
2365
|
-
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);
|
|
2366
2325
|
}
|
|
2367
2326
|
seen.delete(value);
|
|
2368
2327
|
}
|
|
@@ -2906,9 +2865,9 @@ function resolveWorkflowParserEntry() {
|
|
|
2906
2865
|
} catch (primaryError) {
|
|
2907
2866
|
try {
|
|
2908
2867
|
const manifestPath = requireFromPackage.resolve("acorn/package.json");
|
|
2909
|
-
const manifest = JSON.parse(
|
|
2868
|
+
const manifest = JSON.parse(readFileSync5(manifestPath, "utf8"));
|
|
2910
2869
|
const entry = typeof manifest.main === "string" && manifest.main ? manifest.main : "./dist/acorn.js";
|
|
2911
|
-
return resolvePath(
|
|
2870
|
+
return resolvePath(dirname6(manifestPath), entry);
|
|
2912
2871
|
} catch {
|
|
2913
2872
|
throw primaryError;
|
|
2914
2873
|
}
|
|
@@ -2953,7 +2912,7 @@ async function runWorkflowScript(options) {
|
|
|
2953
2912
|
if (options.processCwd !== void 0) {
|
|
2954
2913
|
let staleCwd = false;
|
|
2955
2914
|
try {
|
|
2956
|
-
|
|
2915
|
+
realpathSync3(process.cwd());
|
|
2957
2916
|
} catch (error) {
|
|
2958
2917
|
const code = typeof error === "object" && error !== null && "code" in error ? error.code : void 0;
|
|
2959
2918
|
if (code !== "ENOENT") throw new WorkflowScriptError("Workflow current cwd could not be validated.", emptyPartial(), "runtime", { cause: error });
|
|
@@ -2962,7 +2921,7 @@ async function runWorkflowScript(options) {
|
|
|
2962
2921
|
try {
|
|
2963
2922
|
if (staleCwd) process.chdir(options.processCwd);
|
|
2964
2923
|
else {
|
|
2965
|
-
const target =
|
|
2924
|
+
const target = realpathSync3(options.processCwd);
|
|
2966
2925
|
if (!statSync4(target).isDirectory()) {
|
|
2967
2926
|
const error = new Error(`ENOTDIR: not a directory, access '${target}'`);
|
|
2968
2927
|
error.code = "ENOTDIR";
|
|
@@ -3105,7 +3064,7 @@ async function runWorkflowScript(options) {
|
|
|
3105
3064
|
};
|
|
3106
3065
|
options.registerStopChild?.(stopChild);
|
|
3107
3066
|
options.registerDrain?.(drain);
|
|
3108
|
-
return await new Promise((
|
|
3067
|
+
return await new Promise((resolve5, reject) => {
|
|
3109
3068
|
const finish = (outcome) => {
|
|
3110
3069
|
if (settled || finishing) return;
|
|
3111
3070
|
finishing = true;
|
|
@@ -3131,7 +3090,7 @@ async function runWorkflowScript(options) {
|
|
|
3131
3090
|
})() : void 0;
|
|
3132
3091
|
if ("error" in outcome) reject(new WorkflowScriptError(outcome.error.message, partial(), isWorkflowScriptFailureKind(outcome.error.workflowErrorKind) ? outcome.error.workflowErrorKind : void 0));
|
|
3133
3092
|
else if (completionError) reject(new WorkflowScriptError(completionError.message, partial(), "validation"));
|
|
3134
|
-
else
|
|
3093
|
+
else resolve5({ value: outcome.value, ...partial() });
|
|
3135
3094
|
});
|
|
3136
3095
|
};
|
|
3137
3096
|
const onAbort = () => {
|
|
@@ -3557,10 +3516,10 @@ async function runWorkflowScript(options) {
|
|
|
3557
3516
|
}
|
|
3558
3517
|
|
|
3559
3518
|
// src/missions/store.ts
|
|
3560
|
-
import { createHash as
|
|
3561
|
-
import * as
|
|
3519
|
+
import { createHash as createHash2, randomUUID as randomUUID3 } from "node:crypto";
|
|
3520
|
+
import * as fs7 from "node:fs";
|
|
3562
3521
|
import * as os from "node:os";
|
|
3563
|
-
import * as
|
|
3522
|
+
import * as path8 from "node:path";
|
|
3564
3523
|
|
|
3565
3524
|
// src/missions/types.ts
|
|
3566
3525
|
var MISSION_STATUSES = [
|
|
@@ -3775,12 +3734,12 @@ function parseMissionRecord(value, source = "mission record") {
|
|
|
3775
3734
|
};
|
|
3776
3735
|
}
|
|
3777
3736
|
function expandConfiguredPath(value, projectRoot) {
|
|
3778
|
-
const expanded = value.startsWith("~/") ?
|
|
3779
|
-
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);
|
|
3780
3739
|
}
|
|
3781
3740
|
function projectMissionDirectory(agentDir, projectRoot) {
|
|
3782
|
-
const projectKey =
|
|
3783
|
-
return
|
|
3741
|
+
const projectKey = createHash2("sha256").update(projectRoot).digest("hex");
|
|
3742
|
+
return path8.join(agentDir, "missions", "projects", projectKey);
|
|
3784
3743
|
}
|
|
3785
3744
|
function validateMissionStoreConfig(value, label = "config.missions") {
|
|
3786
3745
|
if (value === void 0) return void 0;
|
|
@@ -3810,23 +3769,23 @@ function canonicalProjectRoot(root) {
|
|
|
3810
3769
|
let current = root;
|
|
3811
3770
|
for (; ; ) {
|
|
3812
3771
|
try {
|
|
3813
|
-
return
|
|
3772
|
+
return path8.join(fs7.realpathSync.native(current), ...missing.reverse());
|
|
3814
3773
|
} catch (error) {
|
|
3815
3774
|
if (error.code !== "ENOENT") throw error;
|
|
3816
|
-
const parent =
|
|
3775
|
+
const parent = path8.dirname(current);
|
|
3817
3776
|
if (parent === current) return root;
|
|
3818
|
-
missing.push(
|
|
3777
|
+
missing.push(path8.basename(current));
|
|
3819
3778
|
current = parent;
|
|
3820
3779
|
}
|
|
3821
3780
|
}
|
|
3822
3781
|
}
|
|
3823
3782
|
function resolveMissionStoreLocation(input) {
|
|
3824
|
-
const givenRoot =
|
|
3783
|
+
const givenRoot = path8.resolve(input.projectRoot);
|
|
3825
3784
|
const configuredDir = input.config?.directory;
|
|
3826
3785
|
const projectRoot = configuredDir ? givenRoot : canonicalProjectRoot(givenRoot);
|
|
3827
3786
|
const agentDir = input.agentDir ?? getAgentDir();
|
|
3828
3787
|
const missionDir = configuredDir ? expandConfiguredPath(configuredDir, givenRoot) : projectMissionDirectory(agentDir, projectRoot);
|
|
3829
|
-
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");
|
|
3830
3789
|
return {
|
|
3831
3790
|
projectRoot,
|
|
3832
3791
|
missionDir,
|
|
@@ -3836,7 +3795,7 @@ function resolveMissionStoreLocation(input) {
|
|
|
3836
3795
|
};
|
|
3837
3796
|
}
|
|
3838
3797
|
function missionRecordPath(location, missionId) {
|
|
3839
|
-
return
|
|
3798
|
+
return path8.join(location.missionDir, `${validateMissionId(missionId)}.json`);
|
|
3840
3799
|
}
|
|
3841
3800
|
function parseIndexEntry(value, source) {
|
|
3842
3801
|
const input = asObject(value, source);
|
|
@@ -3853,8 +3812,8 @@ function parseIndexEntry(value, source) {
|
|
|
3853
3812
|
};
|
|
3854
3813
|
}
|
|
3855
3814
|
function indexPath(location, record) {
|
|
3856
|
-
const key =
|
|
3857
|
-
return
|
|
3815
|
+
const key = createHash2("sha256").update(`${location.projectRoot}\0${record.id}`).digest("hex");
|
|
3816
|
+
return path8.join(location.globalIndexDir, `${key}.json`);
|
|
3858
3817
|
}
|
|
3859
3818
|
function writeMission(location, record) {
|
|
3860
3819
|
const validated = parseMissionRecord(record);
|
|
@@ -3879,9 +3838,9 @@ function pruneTerminalMissions(location, maxTerminal) {
|
|
|
3879
3838
|
const terminal3 = listMissions(location).records.filter((record) => TERMINAL_MISSION_STATUSES.has(record.status)).sort((left, right) => right.updatedAt.localeCompare(left.updatedAt));
|
|
3880
3839
|
for (const record of terminal3.slice(maxTerminal)) {
|
|
3881
3840
|
try {
|
|
3882
|
-
|
|
3883
|
-
|
|
3884
|
-
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 });
|
|
3885
3844
|
} catch {
|
|
3886
3845
|
}
|
|
3887
3846
|
}
|
|
@@ -3890,7 +3849,7 @@ function createMission(location, input, now = /* @__PURE__ */ new Date(), retain
|
|
|
3890
3849
|
const createdAt = now.toISOString();
|
|
3891
3850
|
const record = {
|
|
3892
3851
|
schemaVersion: 1,
|
|
3893
|
-
id:
|
|
3852
|
+
id: randomUUID3(),
|
|
3894
3853
|
title: requiredString(input.title, "mission.title").trim(),
|
|
3895
3854
|
objective: requiredString(input.objective, "mission.objective").trim(),
|
|
3896
3855
|
...input.goal === true ? { goal: { status: "active" } } : {},
|
|
@@ -3928,7 +3887,7 @@ function readMission(location, missionId) {
|
|
|
3928
3887
|
const filePath = missionRecordPath(location, missionId);
|
|
3929
3888
|
let raw;
|
|
3930
3889
|
try {
|
|
3931
|
-
raw =
|
|
3890
|
+
raw = fs7.readFileSync(filePath, "utf-8");
|
|
3932
3891
|
} catch (error) {
|
|
3933
3892
|
if (error.code === "ENOENT") throw new MissionNotFoundError(missionId, location);
|
|
3934
3893
|
throw error;
|
|
@@ -3940,13 +3899,13 @@ function readMission(location, missionId) {
|
|
|
3940
3899
|
}
|
|
3941
3900
|
}
|
|
3942
3901
|
function listMissions(location) {
|
|
3943
|
-
if (!
|
|
3902
|
+
if (!fs7.existsSync(location.missionDir)) return { records: [], warnings: [] };
|
|
3944
3903
|
const records = [];
|
|
3945
3904
|
const warnings = [];
|
|
3946
|
-
for (const name of
|
|
3947
|
-
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);
|
|
3948
3907
|
try {
|
|
3949
|
-
records.push(parseMissionRecord(JSON.parse(
|
|
3908
|
+
records.push(parseMissionRecord(JSON.parse(fs7.readFileSync(filePath, "utf-8")), filePath));
|
|
3950
3909
|
} catch (error) {
|
|
3951
3910
|
warnings.push(`Skipped corrupt mission '${filePath}': ${error instanceof Error ? error.message : String(error)}`);
|
|
3952
3911
|
}
|
|
@@ -3988,7 +3947,7 @@ function updateMission(location, missionId, update, now = /* @__PURE__ */ new Da
|
|
|
3988
3947
|
const artifacts = [...current.artifacts];
|
|
3989
3948
|
for (const candidate of update.addArtifacts ?? []) {
|
|
3990
3949
|
const artifact = parseArtifact(candidate, "mission.update.addArtifacts[]");
|
|
3991
|
-
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));
|
|
3992
3951
|
if (existingIndex === -1) artifacts.push(artifact);
|
|
3993
3952
|
else artifacts[existingIndex] = { ...artifacts[existingIndex], ...artifact };
|
|
3994
3953
|
}
|
|
@@ -4003,7 +3962,7 @@ function updateMission(location, missionId, update, now = /* @__PURE__ */ new Da
|
|
|
4003
3962
|
const decisions = [
|
|
4004
3963
|
...current.decisions,
|
|
4005
3964
|
...(update.addDecisions ?? []).map((decision) => ({
|
|
4006
|
-
id:
|
|
3965
|
+
id: randomUUID3(),
|
|
4007
3966
|
status: "open",
|
|
4008
3967
|
title: requiredString(decision.title, "mission.update.addDecisions[].title"),
|
|
4009
3968
|
createdAt,
|
|
@@ -4058,15 +4017,15 @@ function updateMission(location, missionId, update, now = /* @__PURE__ */ new Da
|
|
|
4058
4017
|
return updated;
|
|
4059
4018
|
}
|
|
4060
4019
|
function listGlobalMissions(globalIndexDir) {
|
|
4061
|
-
if (!
|
|
4020
|
+
if (!fs7.existsSync(globalIndexDir)) return { entries: [], warnings: [] };
|
|
4062
4021
|
const entries = [];
|
|
4063
4022
|
const warnings = [];
|
|
4064
|
-
for (const name of
|
|
4065
|
-
const filePath =
|
|
4023
|
+
for (const name of fs7.readdirSync(globalIndexDir).filter((item) => item.endsWith(".json")).sort()) {
|
|
4024
|
+
const filePath = path8.join(globalIndexDir, name);
|
|
4066
4025
|
try {
|
|
4067
|
-
const entry = parseIndexEntry(JSON.parse(
|
|
4026
|
+
const entry = parseIndexEntry(JSON.parse(fs7.readFileSync(filePath, "utf-8")), filePath);
|
|
4068
4027
|
try {
|
|
4069
|
-
const record = parseMissionRecord(JSON.parse(
|
|
4028
|
+
const record = parseMissionRecord(JSON.parse(fs7.readFileSync(entry.recordPath, "utf-8")), entry.recordPath);
|
|
4070
4029
|
if (record.id !== entry.missionId) throw new Error(`record id '${record.id}' does not match index id '${entry.missionId}'`);
|
|
4071
4030
|
const projection = {
|
|
4072
4031
|
...entry,
|
|
@@ -4081,7 +4040,7 @@ function listGlobalMissions(globalIndexDir) {
|
|
|
4081
4040
|
} catch (error) {
|
|
4082
4041
|
if (error.code === "ENOENT") {
|
|
4083
4042
|
try {
|
|
4084
|
-
|
|
4043
|
+
fs7.rmSync(filePath, { force: true });
|
|
4085
4044
|
warnings.push(`Removed stale global mission pointer '${filePath}' because '${entry.recordPath}' no longer exists.`);
|
|
4086
4045
|
} catch (removeError) {
|
|
4087
4046
|
warnings.push(`Failed to remove stale global mission pointer '${filePath}': ${removeError instanceof Error ? removeError.message : String(removeError)}`);
|
|
@@ -4100,14 +4059,14 @@ function listGlobalMissions(globalIndexDir) {
|
|
|
4100
4059
|
|
|
4101
4060
|
// src/missions/workflow-state.ts
|
|
4102
4061
|
import { execFileSync } from "node:child_process";
|
|
4103
|
-
import { randomUUID as
|
|
4104
|
-
import * as
|
|
4105
|
-
import * as
|
|
4062
|
+
import { randomUUID as randomUUID4 } from "node:crypto";
|
|
4063
|
+
import * as fs8 from "node:fs";
|
|
4064
|
+
import * as path9 from "node:path";
|
|
4106
4065
|
var STATE_KEY_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
|
|
4107
4066
|
var STATE_LOCK_STALE_MS = 6e4;
|
|
4108
4067
|
var MISSION_STATE_MAX_BYTES = 256 * 1024;
|
|
4109
4068
|
function missionStatePath(location, missionId) {
|
|
4110
|
-
return
|
|
4069
|
+
return path9.join(location.missionDir, validateMissionId(missionId), "state.json");
|
|
4111
4070
|
}
|
|
4112
4071
|
function isProcessAlive(pid) {
|
|
4113
4072
|
try {
|
|
@@ -4119,7 +4078,7 @@ function isProcessAlive(pid) {
|
|
|
4119
4078
|
}
|
|
4120
4079
|
function linuxProcessStartKey(pid) {
|
|
4121
4080
|
try {
|
|
4122
|
-
const raw =
|
|
4081
|
+
const raw = fs8.readFileSync(`/proc/${pid}/stat`, "utf-8");
|
|
4123
4082
|
const tail = raw.slice(raw.lastIndexOf(")") + 2).trim().split(/\s+/);
|
|
4124
4083
|
return tail[19] ? `linux:${tail[19]}` : void 0;
|
|
4125
4084
|
} catch {
|
|
@@ -4155,7 +4114,7 @@ function computeProcessStartKey(pid) {
|
|
|
4155
4114
|
}
|
|
4156
4115
|
function readStateLockOwner(lockPath) {
|
|
4157
4116
|
try {
|
|
4158
|
-
const owner = JSON.parse(
|
|
4117
|
+
const owner = JSON.parse(fs8.readFileSync(path9.join(lockPath, "owner.json"), "utf-8"));
|
|
4159
4118
|
if (Number.isSafeInteger(owner.pid) && owner.pid > 0 && typeof owner.token === "string" && owner.token && Number.isSafeInteger(owner.createdAt)) {
|
|
4160
4119
|
return {
|
|
4161
4120
|
pid: owner.pid,
|
|
@@ -4181,7 +4140,7 @@ function stateLockIsStale(lockPath, options, now = Date.now()) {
|
|
|
4181
4140
|
return false;
|
|
4182
4141
|
}
|
|
4183
4142
|
try {
|
|
4184
|
-
return now -
|
|
4143
|
+
return now - fs8.statSync(lockPath).mtimeMs > STATE_LOCK_STALE_MS;
|
|
4185
4144
|
} catch (error) {
|
|
4186
4145
|
if (error.code === "ENOENT") return false;
|
|
4187
4146
|
throw error;
|
|
@@ -4190,11 +4149,11 @@ function stateLockIsStale(lockPath, options, now = Date.now()) {
|
|
|
4190
4149
|
function removeOwnedStateLock(lockPath, owner) {
|
|
4191
4150
|
const current = readStateLockOwner(lockPath);
|
|
4192
4151
|
if (current?.token !== owner.token) return;
|
|
4193
|
-
|
|
4152
|
+
fs8.rmSync(lockPath, { recursive: true, force: true });
|
|
4194
4153
|
}
|
|
4195
4154
|
function staleDirectoryExists(dirPath, now = Date.now()) {
|
|
4196
4155
|
try {
|
|
4197
|
-
return now -
|
|
4156
|
+
return now - fs8.statSync(dirPath).mtimeMs > STATE_LOCK_STALE_MS;
|
|
4198
4157
|
} catch (error) {
|
|
4199
4158
|
if (error.code === "ENOENT") return false;
|
|
4200
4159
|
throw error;
|
|
@@ -4202,7 +4161,7 @@ function staleDirectoryExists(dirPath, now = Date.now()) {
|
|
|
4202
4161
|
}
|
|
4203
4162
|
function tryMakeDirectory(dirPath, mode) {
|
|
4204
4163
|
try {
|
|
4205
|
-
|
|
4164
|
+
fs8.mkdirSync(dirPath, { mode });
|
|
4206
4165
|
return true;
|
|
4207
4166
|
} catch (error) {
|
|
4208
4167
|
if (error.code === "EEXIST") return false;
|
|
@@ -4218,21 +4177,21 @@ function reclaimStaleStateLock(lockPath, reclaimPath, options) {
|
|
|
4218
4177
|
if (!tryMakeDirectory(reclaimPath, 448)) return false;
|
|
4219
4178
|
try {
|
|
4220
4179
|
if (!stateLockIsStale(lockPath, options)) return false;
|
|
4221
|
-
|
|
4180
|
+
fs8.rmSync(lockPath, { recursive: true, force: true });
|
|
4222
4181
|
return true;
|
|
4223
4182
|
} finally {
|
|
4224
|
-
|
|
4183
|
+
fs8.rmSync(reclaimPath, { recursive: true, force: true });
|
|
4225
4184
|
}
|
|
4226
4185
|
}
|
|
4227
4186
|
function withStateFileLock(filePath, operation, options) {
|
|
4228
|
-
|
|
4187
|
+
fs8.mkdirSync(path9.dirname(filePath), { recursive: true });
|
|
4229
4188
|
const lockPath = `${filePath}.lock`;
|
|
4230
4189
|
const reclaimPath = `${lockPath}.reclaim`;
|
|
4231
4190
|
let owner;
|
|
4232
4191
|
for (let attempt = 0; ; attempt++) {
|
|
4233
|
-
if (
|
|
4192
|
+
if (fs8.existsSync(reclaimPath)) {
|
|
4234
4193
|
if (staleDirectoryExists(reclaimPath)) {
|
|
4235
|
-
|
|
4194
|
+
fs8.rmSync(reclaimPath, { recursive: true, force: true });
|
|
4236
4195
|
continue;
|
|
4237
4196
|
}
|
|
4238
4197
|
waitForStateLock(options.retryDelaysMs[attempt], lockPath);
|
|
@@ -4254,11 +4213,11 @@ function withStateFileLock(filePath, operation, options) {
|
|
|
4254
4213
|
continue;
|
|
4255
4214
|
}
|
|
4256
4215
|
const key = options.getProcessStartKey(process.pid);
|
|
4257
|
-
owner = { pid: process.pid, token:
|
|
4216
|
+
owner = { pid: process.pid, token: randomUUID4(), createdAt: Date.now(), ...key ? { processKey: key } : {} };
|
|
4258
4217
|
try {
|
|
4259
|
-
|
|
4218
|
+
fs8.writeFileSync(path9.join(lockPath, "owner.json"), JSON.stringify(owner), { encoding: "utf-8", mode: 384 });
|
|
4260
4219
|
} catch (error) {
|
|
4261
|
-
|
|
4220
|
+
fs8.rmSync(lockPath, { recursive: true, force: true });
|
|
4262
4221
|
owner = void 0;
|
|
4263
4222
|
throw error;
|
|
4264
4223
|
}
|
|
@@ -4288,7 +4247,7 @@ function createMissionWorkflowState(location, missionId, options = {}) {
|
|
|
4288
4247
|
const readStateFile = () => {
|
|
4289
4248
|
let raw;
|
|
4290
4249
|
try {
|
|
4291
|
-
raw =
|
|
4250
|
+
raw = fs8.readFileSync(filePath, "utf-8");
|
|
4292
4251
|
} catch (error) {
|
|
4293
4252
|
if (error.code === "ENOENT") return /* @__PURE__ */ Object.create(null);
|
|
4294
4253
|
throw new Error(`Failed to read mission state '${filePath}': ${error instanceof Error ? error.message : String(error)}`);
|
|
@@ -4333,13 +4292,13 @@ function createMissionWorkflowState(location, missionId, options = {}) {
|
|
|
4333
4292
|
}
|
|
4334
4293
|
|
|
4335
4294
|
// src/missions/actions.ts
|
|
4336
|
-
import * as fs11 from "node:fs";
|
|
4337
|
-
import * as path12 from "node:path";
|
|
4338
|
-
|
|
4339
|
-
// src/missions/lifecycle.ts
|
|
4340
4295
|
import * as fs10 from "node:fs";
|
|
4341
4296
|
import * as path11 from "node:path";
|
|
4342
|
-
|
|
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";
|
|
4343
4302
|
var MISSION_BINDING_FILE = "mission.json";
|
|
4344
4303
|
function workflowObjective(params) {
|
|
4345
4304
|
const objective = params.task?.trim() || params.tasks?.find((task) => task.task?.trim())?.task?.trim() || params.chain?.find((step) => step.task?.trim())?.task?.trim();
|
|
@@ -4427,8 +4386,8 @@ function artifactsForResult(result) {
|
|
|
4427
4386
|
const artifacts = [];
|
|
4428
4387
|
if (result.details.asyncDir) {
|
|
4429
4388
|
artifacts.push(
|
|
4430
|
-
{ kind: "status", path:
|
|
4431
|
-
{ 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" }
|
|
4432
4391
|
);
|
|
4433
4392
|
}
|
|
4434
4393
|
for (const child of result.details.results) {
|
|
@@ -4458,7 +4417,7 @@ function persistedBinding(binding) {
|
|
|
4458
4417
|
};
|
|
4459
4418
|
}
|
|
4460
4419
|
function writeMissionAsyncBinding(asyncDir, binding) {
|
|
4461
|
-
writePrivateAtomicJson(
|
|
4420
|
+
writePrivateAtomicJson(path10.join(asyncDir, MISSION_BINDING_FILE), persistedBinding(binding));
|
|
4462
4421
|
}
|
|
4463
4422
|
function attachMissionToLaunchResult(input) {
|
|
4464
4423
|
const runId = input.result.details.runId ?? input.result.details.asyncId;
|
|
@@ -4502,10 +4461,10 @@ function attachMissionToLaunchResult(input) {
|
|
|
4502
4461
|
});
|
|
4503
4462
|
if (input.result.details.asyncDir) {
|
|
4504
4463
|
writeMissionAsyncBinding(input.result.details.asyncDir, input.binding);
|
|
4505
|
-
const statusPath =
|
|
4506
|
-
if (
|
|
4464
|
+
const statusPath = path10.join(input.result.details.asyncDir, "status.json");
|
|
4465
|
+
if (fs9.existsSync(statusPath)) {
|
|
4507
4466
|
try {
|
|
4508
|
-
const status = JSON.parse(
|
|
4467
|
+
const status = JSON.parse(fs9.readFileSync(statusPath, "utf-8"));
|
|
4509
4468
|
if (typeof status.state === "string" && !["queued", "running"].includes(status.state)) {
|
|
4510
4469
|
mission = syncMissionFromAsyncCompletion({
|
|
4511
4470
|
runId,
|
|
@@ -4568,9 +4527,9 @@ function parsePersistedBinding(value, source) {
|
|
|
4568
4527
|
};
|
|
4569
4528
|
}
|
|
4570
4529
|
function readMissionBinding(asyncDir) {
|
|
4571
|
-
const bindingPath =
|
|
4572
|
-
if (!
|
|
4573
|
-
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");
|
|
4574
4533
|
try {
|
|
4575
4534
|
return parsePersistedBinding(JSON.parse(raw), bindingPath);
|
|
4576
4535
|
} catch (error) {
|
|
@@ -4592,12 +4551,12 @@ function syncMissionFromAsyncCompletion(value) {
|
|
|
4592
4551
|
} catch (error) {
|
|
4593
4552
|
if (!(error instanceof MissionNotFoundError)) throw error;
|
|
4594
4553
|
const reason = "mission-record-missing";
|
|
4595
|
-
const markerId =
|
|
4596
|
-
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`);
|
|
4597
4556
|
try {
|
|
4598
|
-
|
|
4557
|
+
fs9.writeFileSync(markerPath3, `${JSON.stringify({ runId, missionId: binding.missionId, reason })}
|
|
4599
4558
|
`, { encoding: "utf-8", mode: 384, flag: "wx" });
|
|
4600
|
-
|
|
4559
|
+
fs9.appendFileSync(path10.join(event.asyncDir, "events.jsonl"), `${JSON.stringify({
|
|
4601
4560
|
type: "subagent.mission.sync.skipped",
|
|
4602
4561
|
ts: Date.now(),
|
|
4603
4562
|
runId,
|
|
@@ -4612,8 +4571,8 @@ function syncMissionFromAsyncCompletion(value) {
|
|
|
4612
4571
|
}
|
|
4613
4572
|
const completedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
4614
4573
|
const artifacts = [
|
|
4615
|
-
{ kind: "status", path:
|
|
4616
|
-
{ 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" }
|
|
4617
4576
|
];
|
|
4618
4577
|
if (event.parallelHandoff && typeof event.parallelHandoff === "object" && typeof event.parallelHandoff.path === "string") {
|
|
4619
4578
|
artifacts.push({ kind: "manifest", path: event.parallelHandoff.path });
|
|
@@ -4809,11 +4768,11 @@ function refreshLinkedRunStatus(location, record) {
|
|
|
4809
4768
|
const runAcceptance = [];
|
|
4810
4769
|
const updates = record.runs.flatMap((run) => {
|
|
4811
4770
|
if (!run.asyncDir) return [];
|
|
4812
|
-
const statusPath =
|
|
4813
|
-
if (!
|
|
4771
|
+
const statusPath = path11.join(run.asyncDir, "status.json");
|
|
4772
|
+
if (!fs10.existsSync(statusPath)) return [];
|
|
4814
4773
|
let status2;
|
|
4815
4774
|
try {
|
|
4816
|
-
status2 = JSON.parse(
|
|
4775
|
+
status2 = JSON.parse(fs10.readFileSync(statusPath, "utf-8"));
|
|
4817
4776
|
} catch (error) {
|
|
4818
4777
|
warnings.push(`Failed to read linked run status '${statusPath}': ${error instanceof Error ? error.message : String(error)}`);
|
|
4819
4778
|
return [];
|
|
@@ -4985,9 +4944,9 @@ ${formatMission(record2)}`, { mode: "management", results: [], missionId: record
|
|
|
4985
4944
|
}
|
|
4986
4945
|
|
|
4987
4946
|
// src/runs/background/result-files.ts
|
|
4988
|
-
import { createHash as
|
|
4989
|
-
import * as
|
|
4990
|
-
import * as
|
|
4947
|
+
import { createHash as createHash4 } from "node:crypto";
|
|
4948
|
+
import * as fs11 from "node:fs";
|
|
4949
|
+
import * as path12 from "node:path";
|
|
4991
4950
|
var RESULT_INDEX_VERSION = 1;
|
|
4992
4951
|
var RESULT_INDEX_DIR = "result-index";
|
|
4993
4952
|
var SESSION_INDEX_DIR = "sessions";
|
|
@@ -5018,31 +4977,31 @@ function resultFileName(runId) {
|
|
|
5018
4977
|
return `${runId}${JSON_EXTENSION}`;
|
|
5019
4978
|
}
|
|
5020
4979
|
function resultFilePath(resultsDir, runId) {
|
|
5021
|
-
return
|
|
4980
|
+
return path12.join(resultsDir, resultFileName(runId));
|
|
5022
4981
|
}
|
|
5023
4982
|
function sessionIndexDir2(resultsDir, sessionId) {
|
|
5024
|
-
return
|
|
4983
|
+
return path12.join(resultsDir, RESULT_INDEX_DIR, SESSION_INDEX_DIR, encodeSegment(sessionId));
|
|
5025
4984
|
}
|
|
5026
4985
|
function sessionIndexDirs(resultsDir, sessionId) {
|
|
5027
|
-
return indexSegmentAliases(sessionId).map((segment) =>
|
|
4986
|
+
return indexSegmentAliases(sessionId).map((segment) => path12.join(resultsDir, RESULT_INDEX_DIR, SESSION_INDEX_DIR, segment));
|
|
5028
4987
|
}
|
|
5029
4988
|
function resultIndexPath(resultsDir, sessionId, runId) {
|
|
5030
|
-
return
|
|
4989
|
+
return path12.join(sessionIndexDir2(resultsDir, sessionId), encodedJsonFileName(runId));
|
|
5031
4990
|
}
|
|
5032
4991
|
function resultIndexPaths(resultsDir, sessionId, runId) {
|
|
5033
|
-
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)));
|
|
5034
4993
|
}
|
|
5035
4994
|
function runIndexPath(resultsDir, runId) {
|
|
5036
|
-
return
|
|
4995
|
+
return path12.join(resultsDir, RESULT_INDEX_DIR, RUN_INDEX_DIR, encodedJsonFileName(runId));
|
|
5037
4996
|
}
|
|
5038
4997
|
function resultPendingPath(resultsDir, sessionId, runId) {
|
|
5039
|
-
return
|
|
4998
|
+
return path12.join(resultsDir, RESULT_PENDING_DIR, encodeSegment(sessionId), encodedJsonFileName(runId));
|
|
5040
4999
|
}
|
|
5041
5000
|
function resultPendingPaths(resultsDir, sessionId, runId) {
|
|
5042
|
-
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)));
|
|
5043
5002
|
}
|
|
5044
5003
|
function pendingSessionDirs(resultsDir, sessionId) {
|
|
5045
|
-
return indexSegmentAliases(sessionId).map((segment) =>
|
|
5004
|
+
return indexSegmentAliases(sessionId).map((segment) => path12.join(resultsDir, RESULT_PENDING_DIR, segment));
|
|
5046
5005
|
}
|
|
5047
5006
|
function firstExistingResultFile(paths) {
|
|
5048
5007
|
for (const filePath of paths) {
|
|
@@ -5051,19 +5010,19 @@ function firstExistingResultFile(paths) {
|
|
|
5051
5010
|
return void 0;
|
|
5052
5011
|
}
|
|
5053
5012
|
function observerIndexDir(resultsDir, observer) {
|
|
5054
|
-
return
|
|
5013
|
+
return path12.join(resultsDir, RESULT_INDEX_DIR, OBSERVER_INDEX_DIR, observer);
|
|
5055
5014
|
}
|
|
5056
5015
|
function observerIndexPath(resultsDir, observer, runId) {
|
|
5057
|
-
return
|
|
5016
|
+
return path12.join(observerIndexDir(resultsDir, observer), encodedJsonFileName(runId));
|
|
5058
5017
|
}
|
|
5059
5018
|
function missionObserverIndexPath(resultsDir, runId) {
|
|
5060
5019
|
return observerIndexPath(resultsDir, MISSION_OBSERVER, runId);
|
|
5061
5020
|
}
|
|
5062
5021
|
function toolCallIndexDir3(resultsDir, toolCallId) {
|
|
5063
|
-
return
|
|
5022
|
+
return path12.join(resultsDir, RESULT_INDEX_DIR, TOOL_CALL_INDEX_DIR3, encodeIndexSegment(toolCallId));
|
|
5064
5023
|
}
|
|
5065
5024
|
function toolCallIndexPath2(resultsDir, toolCallId, runId) {
|
|
5066
|
-
return
|
|
5025
|
+
return path12.join(toolCallIndexDir3(resultsDir, toolCallId), encodedJsonFileName(runId));
|
|
5067
5026
|
}
|
|
5068
5027
|
function parseResultIndexEntry(value) {
|
|
5069
5028
|
if (!value || typeof value !== "object" || Array.isArray(value)) return void 0;
|
|
@@ -5079,10 +5038,10 @@ function parseResultIndexEntry(value) {
|
|
|
5079
5038
|
};
|
|
5080
5039
|
}
|
|
5081
5040
|
function writeResultIndexForData(resultPath, data) {
|
|
5082
|
-
const runId = nonEmptyString2(data.runId) ?? nonEmptyString2(data.id) ??
|
|
5041
|
+
const runId = nonEmptyString2(data.runId) ?? nonEmptyString2(data.id) ?? path12.basename(resultPath, ".json");
|
|
5083
5042
|
const sessionId = nonEmptyString2(data.sessionId);
|
|
5084
5043
|
if (!runId || !sessionId) return;
|
|
5085
|
-
const file =
|
|
5044
|
+
const file = path12.basename(resultPath);
|
|
5086
5045
|
const entry = {
|
|
5087
5046
|
version: RESULT_INDEX_VERSION,
|
|
5088
5047
|
runId,
|
|
@@ -5091,7 +5050,7 @@ function writeResultIndexForData(resultPath, data) {
|
|
|
5091
5050
|
writtenAt: Date.now(),
|
|
5092
5051
|
...nonEmptyString2(data.asyncDir) ? { asyncDir: nonEmptyString2(data.asyncDir) } : {}
|
|
5093
5052
|
};
|
|
5094
|
-
const resultsDir =
|
|
5053
|
+
const resultsDir = path12.dirname(resultPath);
|
|
5095
5054
|
writeAtomicJson(resultIndexPath(resultsDir, sessionId, runId), entry);
|
|
5096
5055
|
try {
|
|
5097
5056
|
writeAtomicJson(runIndexPath(resultsDir, runId), entry);
|
|
@@ -5105,7 +5064,7 @@ function writeResultIndexForData(resultPath, data) {
|
|
|
5105
5064
|
console.error(`Failed to write async result tool-call index for '${resultPath}':`, error);
|
|
5106
5065
|
}
|
|
5107
5066
|
try {
|
|
5108
|
-
if (entry.asyncDir &&
|
|
5067
|
+
if (entry.asyncDir && fs11.existsSync(path12.join(entry.asyncDir, MISSION_BINDING_FILE))) {
|
|
5109
5068
|
writeAtomicJson(observerIndexPath(resultsDir, MISSION_OBSERVER, runId), entry);
|
|
5110
5069
|
}
|
|
5111
5070
|
} catch (error) {
|
|
@@ -5113,10 +5072,10 @@ function writeResultIndexForData(resultPath, data) {
|
|
|
5113
5072
|
}
|
|
5114
5073
|
}
|
|
5115
5074
|
function writeIndexedPendingResultFile(resultPath, data) {
|
|
5116
|
-
const runId = nonEmptyString2(data.runId) ?? nonEmptyString2(data.id) ??
|
|
5075
|
+
const runId = nonEmptyString2(data.runId) ?? nonEmptyString2(data.id) ?? path12.basename(resultPath, ".json");
|
|
5117
5076
|
const sessionId = nonEmptyString2(data.sessionId);
|
|
5118
5077
|
if (!sessionId) throw new Error(`Cannot write async result '${resultPath}' without a sessionId.`);
|
|
5119
|
-
const resultsDir =
|
|
5078
|
+
const resultsDir = path12.dirname(resultPath);
|
|
5120
5079
|
let indexFailure;
|
|
5121
5080
|
writeAtomicJson(resultPendingPath(resultsDir, sessionId, runId), data, () => {
|
|
5122
5081
|
try {
|
|
@@ -5130,54 +5089,54 @@ function writeIndexedPendingResultFile(resultPath, data) {
|
|
|
5130
5089
|
}
|
|
5131
5090
|
function writeAsyncResultFile(resultPath, data) {
|
|
5132
5091
|
const { runId, sessionId, resultsDir } = writeIndexedPendingResultFile(resultPath, data);
|
|
5133
|
-
return promotePendingResultFile(resultsDir, sessionId, runId,
|
|
5092
|
+
return promotePendingResultFile(resultsDir, sessionId, runId, path12.basename(resultPath), { logFailure: false }) === "promoted" ? { state: "public" } : { state: "pending" };
|
|
5134
5093
|
}
|
|
5135
5094
|
function removeResultIndex(resultsDir, sessionId, runId, toolCallId) {
|
|
5136
5095
|
if (!runId) return;
|
|
5137
5096
|
if (sessionId) {
|
|
5138
5097
|
for (const indexPath2 of resultIndexPaths(resultsDir, sessionId, runId)) {
|
|
5139
5098
|
try {
|
|
5140
|
-
|
|
5099
|
+
fs11.rmSync(indexPath2, { force: true });
|
|
5141
5100
|
} catch {
|
|
5142
5101
|
}
|
|
5143
5102
|
}
|
|
5144
5103
|
for (const pendingPath of resultPendingPaths(resultsDir, sessionId, runId)) {
|
|
5145
5104
|
try {
|
|
5146
|
-
|
|
5105
|
+
fs11.rmSync(pendingPath, { force: true });
|
|
5147
5106
|
} catch {
|
|
5148
5107
|
}
|
|
5149
5108
|
}
|
|
5150
5109
|
}
|
|
5151
5110
|
try {
|
|
5152
|
-
|
|
5111
|
+
fs11.rmSync(runIndexPath(resultsDir, runId), { force: true });
|
|
5153
5112
|
} catch {
|
|
5154
5113
|
}
|
|
5155
5114
|
if (toolCallId) {
|
|
5156
5115
|
try {
|
|
5157
|
-
|
|
5116
|
+
fs11.rmSync(toolCallIndexPath2(resultsDir, toolCallId, runId), { force: true });
|
|
5158
5117
|
} catch {
|
|
5159
5118
|
}
|
|
5160
5119
|
}
|
|
5161
5120
|
try {
|
|
5162
|
-
|
|
5121
|
+
fs11.rmSync(observerIndexPath(resultsDir, MISSION_OBSERVER, runId), { force: true });
|
|
5163
5122
|
} catch {
|
|
5164
5123
|
}
|
|
5165
5124
|
}
|
|
5166
5125
|
function removeMissionObserverIndex(resultsDir, runId) {
|
|
5167
5126
|
if (!runId) return;
|
|
5168
5127
|
try {
|
|
5169
|
-
|
|
5128
|
+
fs11.rmSync(observerIndexPath(resultsDir, MISSION_OBSERVER, runId), { force: true });
|
|
5170
5129
|
} catch {
|
|
5171
5130
|
}
|
|
5172
5131
|
}
|
|
5173
5132
|
function withResultRunLease(resultsDir, runId, action, waitMs) {
|
|
5174
|
-
const leaseDir =
|
|
5175
|
-
|
|
5176
|
-
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);
|
|
5177
5136
|
}
|
|
5178
5137
|
function readResultPayload(filePath) {
|
|
5179
5138
|
try {
|
|
5180
|
-
return
|
|
5139
|
+
return fs11.readFileSync(filePath, "utf-8");
|
|
5181
5140
|
} catch (error) {
|
|
5182
5141
|
const code = error.code;
|
|
5183
5142
|
if (code === "ENOENT" || code === "ENOTDIR" || code === "EISDIR" || isUnaddressableResultCandidate(error)) return void 0;
|
|
@@ -5185,7 +5144,7 @@ function readResultPayload(filePath) {
|
|
|
5185
5144
|
}
|
|
5186
5145
|
}
|
|
5187
5146
|
function resultPayloadCandidates(publicPath, read) {
|
|
5188
|
-
return [...read.sessionId ? resultPendingPaths(
|
|
5147
|
+
return [...read.sessionId ? resultPendingPaths(path12.dirname(publicPath), read.sessionId, read.runId) : [], publicPath];
|
|
5189
5148
|
}
|
|
5190
5149
|
function readByConsumer(publicPath, read, candidate, current) {
|
|
5191
5150
|
return current === read.snapshot || candidate === publicPath && current === read.stalePublic;
|
|
@@ -5197,10 +5156,10 @@ function resultSnapshotReplaced(publicPath, read) {
|
|
|
5197
5156
|
});
|
|
5198
5157
|
}
|
|
5199
5158
|
function retireResultSnapshot(publicPath, read, payloadPath = publicPath, leaseWaitMs) {
|
|
5200
|
-
const resultsDir =
|
|
5159
|
+
const resultsDir = path12.dirname(publicPath);
|
|
5201
5160
|
return withResultRunLease(resultsDir, read.runId, () => {
|
|
5202
5161
|
if (resultSnapshotReplaced(publicPath, read)) {
|
|
5203
|
-
if (payloadPath !== publicPath && readResultPayload(payloadPath) === read.snapshot)
|
|
5162
|
+
if (payloadPath !== publicPath && readResultPayload(payloadPath) === read.snapshot) fs11.rmSync(payloadPath, { force: true });
|
|
5204
5163
|
return "replaced";
|
|
5205
5164
|
}
|
|
5206
5165
|
let removalFailure;
|
|
@@ -5208,7 +5167,7 @@ function retireResultSnapshot(publicPath, read, payloadPath = publicPath, leaseW
|
|
|
5208
5167
|
const current = readResultPayload(candidate);
|
|
5209
5168
|
if (current === void 0 || !readByConsumer(publicPath, read, candidate, current)) continue;
|
|
5210
5169
|
try {
|
|
5211
|
-
|
|
5170
|
+
fs11.rmSync(candidate, { force: true });
|
|
5212
5171
|
} catch (error) {
|
|
5213
5172
|
removalFailure ??= { error };
|
|
5214
5173
|
}
|
|
@@ -5219,8 +5178,8 @@ function retireResultSnapshot(publicPath, read, payloadPath = publicPath, leaseW
|
|
|
5219
5178
|
}, leaseWaitMs);
|
|
5220
5179
|
}
|
|
5221
5180
|
function acknowledgeMissionObserverSnapshot(publicPath, read, leaseWaitMs) {
|
|
5222
|
-
const resultsDir =
|
|
5223
|
-
if (!
|
|
5181
|
+
const resultsDir = path12.dirname(publicPath);
|
|
5182
|
+
if (!fs11.existsSync(observerIndexPath(resultsDir, MISSION_OBSERVER, read.runId))) return "acknowledged";
|
|
5224
5183
|
return withResultRunLease(resultsDir, read.runId, () => {
|
|
5225
5184
|
if (resultSnapshotReplaced(publicPath, read)) return "replaced";
|
|
5226
5185
|
removeMissionObserverIndex(resultsDir, read.runId);
|
|
@@ -5229,7 +5188,7 @@ function acknowledgeMissionObserverSnapshot(publicPath, read, leaseWaitMs) {
|
|
|
5229
5188
|
}
|
|
5230
5189
|
function existingResultFile(resultPath) {
|
|
5231
5190
|
try {
|
|
5232
|
-
return
|
|
5191
|
+
return fs11.statSync(resultPath).isFile();
|
|
5233
5192
|
} catch (error) {
|
|
5234
5193
|
if (error.code !== "ENOENT" && !isUnaddressableResultCandidate(error)) console.error(`Failed to inspect async result payload '${resultPath}':`, error);
|
|
5235
5194
|
return false;
|
|
@@ -5245,22 +5204,22 @@ function resultPayloadMatchesSessionRun(data, sessionId, runId) {
|
|
|
5245
5204
|
}
|
|
5246
5205
|
function pendingResultPayloadMatches(filePath, sessionId, runId) {
|
|
5247
5206
|
try {
|
|
5248
|
-
return resultPayloadMatchesSessionRun(JSON.parse(
|
|
5207
|
+
return resultPayloadMatchesSessionRun(JSON.parse(fs11.readFileSync(filePath, "utf-8")), sessionId, runId);
|
|
5249
5208
|
} catch (error) {
|
|
5250
5209
|
if (error.code !== "ENOENT" && !isUnaddressableResultCandidate(error)) console.error(`Ignoring invalid pending async result '${filePath}':`, error);
|
|
5251
5210
|
return false;
|
|
5252
5211
|
}
|
|
5253
5212
|
}
|
|
5254
5213
|
function assertPendingResultPayloadMatches(filePath, sessionId, runId) {
|
|
5255
|
-
return resultPayloadMatchesSessionRun(JSON.parse(
|
|
5214
|
+
return resultPayloadMatchesSessionRun(JSON.parse(fs11.readFileSync(filePath, "utf-8")), sessionId, runId);
|
|
5256
5215
|
}
|
|
5257
5216
|
function promotePendingResultFile(resultsDir, sessionId, runId, file = resultFileName(runId), options = {}) {
|
|
5258
|
-
if (file !==
|
|
5217
|
+
if (file !== path12.basename(file) || !file.endsWith(".json")) return "none";
|
|
5259
5218
|
const pendingPath = firstExistingResultFile(resultPendingPaths(resultsDir, sessionId, runId));
|
|
5260
5219
|
if (!pendingPath) return "none";
|
|
5261
|
-
const resultPath =
|
|
5220
|
+
const resultPath = path12.join(resultsDir, file);
|
|
5262
5221
|
try {
|
|
5263
|
-
|
|
5222
|
+
fs11.renameSync(pendingPath, resultPath);
|
|
5264
5223
|
return existingResultFile(resultPath) ? "promoted" : "pending";
|
|
5265
5224
|
} catch (error) {
|
|
5266
5225
|
const code = error.code;
|
|
@@ -5280,7 +5239,7 @@ function promotePendingResultFile(resultsDir, sessionId, runId, file = resultFil
|
|
|
5280
5239
|
}
|
|
5281
5240
|
}
|
|
5282
5241
|
function pendingResultLocationForSessionRun(resultsDir, sessionId, runId, file = resultFileName(runId)) {
|
|
5283
|
-
if (file !==
|
|
5242
|
+
if (file !== path12.basename(file) || !file.endsWith(".json")) return void 0;
|
|
5284
5243
|
const pendingPath = firstExistingResultFile(resultPendingPaths(resultsDir, sessionId, runId));
|
|
5285
5244
|
if (!pendingPath || !pendingResultPayloadMatches(pendingPath, sessionId, runId)) return void 0;
|
|
5286
5245
|
return { file, path: pendingPath, state: "pending" };
|
|
@@ -5294,19 +5253,19 @@ function resultPayloadFileForSessionRun(resultsDir, sessionId, runId) {
|
|
|
5294
5253
|
return firstExistingResultFile([...resultPendingPaths(resultsDir, sessionId, runId), resultFilePath(resultsDir, runId)]);
|
|
5295
5254
|
}
|
|
5296
5255
|
function resultPayloadLocationFromIndex(resultsDir, entry) {
|
|
5297
|
-
if (entry.file !==
|
|
5256
|
+
if (entry.file !== path12.basename(entry.file) || !entry.file.endsWith(".json")) return void 0;
|
|
5298
5257
|
const pendingState = promotePendingResultFile(resultsDir, entry.sessionId, entry.runId, entry.file);
|
|
5299
5258
|
if (pendingState === "pending") {
|
|
5300
5259
|
return pendingResultLocationForSessionRun(resultsDir, entry.sessionId, entry.runId, entry.file);
|
|
5301
5260
|
}
|
|
5302
|
-
const resultPath =
|
|
5261
|
+
const resultPath = path12.join(resultsDir, entry.file);
|
|
5303
5262
|
if (pendingState === "promoted" || existingResultFile(resultPath)) return { file: entry.file, path: resultPath, state: "public" };
|
|
5304
5263
|
return void 0;
|
|
5305
5264
|
}
|
|
5306
5265
|
function readResultIndexForSessionRun(resultsDir, sessionId, runId) {
|
|
5307
5266
|
for (const indexPath2 of resultIndexPaths(resultsDir, sessionId, runId)) {
|
|
5308
5267
|
try {
|
|
5309
|
-
const entry = parseResultIndexEntry(JSON.parse(
|
|
5268
|
+
const entry = parseResultIndexEntry(JSON.parse(fs11.readFileSync(indexPath2, "utf-8")));
|
|
5310
5269
|
if (!entry || entry.sessionId !== sessionId || entry.runId !== runId) continue;
|
|
5311
5270
|
return entry;
|
|
5312
5271
|
} catch (error) {
|
|
@@ -5325,7 +5284,7 @@ function resultPayloadPathForSessionRun(resultsDir, sessionId, runId) {
|
|
|
5325
5284
|
}
|
|
5326
5285
|
function resultPayloadPathForMissionObserverRun(resultsDir, runId) {
|
|
5327
5286
|
try {
|
|
5328
|
-
const entry = parseResultIndexEntry(JSON.parse(
|
|
5287
|
+
const entry = parseResultIndexEntry(JSON.parse(fs11.readFileSync(observerIndexPath(resultsDir, MISSION_OBSERVER, runId), "utf-8")));
|
|
5329
5288
|
if (!entry || entry.runId !== runId) return void 0;
|
|
5330
5289
|
return resultPayloadLocationFromIndex(resultsDir, entry)?.path;
|
|
5331
5290
|
} catch (error) {
|
|
@@ -5337,9 +5296,9 @@ function resultPayloadPathForMissionObserverRun(resultsDir, runId) {
|
|
|
5337
5296
|
function resultPayloadPathForIndexedRun(resultsDir, runId) {
|
|
5338
5297
|
const entryPath = runIndexPath(resultsDir, runId);
|
|
5339
5298
|
try {
|
|
5340
|
-
const entry = parseResultIndexEntry(JSON.parse(
|
|
5299
|
+
const entry = parseResultIndexEntry(JSON.parse(fs11.readFileSync(entryPath, "utf-8")));
|
|
5341
5300
|
if (!entry || entry.runId !== runId) {
|
|
5342
|
-
|
|
5301
|
+
fs11.rmSync(entryPath, { force: true });
|
|
5343
5302
|
return void 0;
|
|
5344
5303
|
}
|
|
5345
5304
|
return resultPayloadLocationFromIndex(resultsDir, entry)?.path;
|
|
@@ -5349,7 +5308,7 @@ function resultPayloadPathForIndexedRun(resultsDir, runId) {
|
|
|
5349
5308
|
if (code !== "ENOENT" && code !== "ENOTDIR") {
|
|
5350
5309
|
console.error(`Ignoring invalid async result run index '${entryPath}':`, error);
|
|
5351
5310
|
try {
|
|
5352
|
-
|
|
5311
|
+
fs11.rmSync(entryPath, { force: true });
|
|
5353
5312
|
} catch {
|
|
5354
5313
|
}
|
|
5355
5314
|
}
|
|
@@ -5364,7 +5323,7 @@ function indexedResultFile(resultsDir, entry, includePending = false) {
|
|
|
5364
5323
|
function listIndexFiles(dir) {
|
|
5365
5324
|
let files;
|
|
5366
5325
|
try {
|
|
5367
|
-
files =
|
|
5326
|
+
files = fs11.readdirSync(dir, { withFileTypes: true }).filter((entry) => entry.isFile() && entry.name.endsWith(".json")).map((entry) => path12.join(dir, entry.name));
|
|
5368
5327
|
} catch (error) {
|
|
5369
5328
|
const code = error.code;
|
|
5370
5329
|
if (code === "ENOENT" || code === "ENOTDIR" || code === "EPERM" || code === "EACCES" || isUnaddressableResultCandidate(error)) return [];
|
|
@@ -5376,9 +5335,9 @@ function resultFilesFromIndexDir(resultsDir, dir, includePending = false) {
|
|
|
5376
5335
|
const candidates = /* @__PURE__ */ new Set();
|
|
5377
5336
|
for (const entryPath of listIndexFiles(dir)) {
|
|
5378
5337
|
try {
|
|
5379
|
-
const entry = parseResultIndexEntry(JSON.parse(
|
|
5338
|
+
const entry = parseResultIndexEntry(JSON.parse(fs11.readFileSync(entryPath, "utf-8")));
|
|
5380
5339
|
if (!entry) {
|
|
5381
|
-
|
|
5340
|
+
fs11.rmSync(entryPath, { force: true });
|
|
5382
5341
|
continue;
|
|
5383
5342
|
}
|
|
5384
5343
|
const resultFile = indexedResultFile(resultsDir, entry, includePending);
|
|
@@ -5394,7 +5353,7 @@ function pendingResultFilesForSession(resultsDir, sessionId) {
|
|
|
5394
5353
|
for (const dir of pendingSessionDirs(resultsDir, sessionId)) {
|
|
5395
5354
|
let entries;
|
|
5396
5355
|
try {
|
|
5397
|
-
entries =
|
|
5356
|
+
entries = fs11.readdirSync(dir, { withFileTypes: true });
|
|
5398
5357
|
} catch (error) {
|
|
5399
5358
|
const code = error.code;
|
|
5400
5359
|
if (code === "ENOENT" || code === "ENOTDIR" || code === "EPERM" || code === "EACCES" || isUnaddressableResultCandidate(error)) continue;
|
|
@@ -5402,9 +5361,9 @@ function pendingResultFilesForSession(resultsDir, sessionId) {
|
|
|
5402
5361
|
}
|
|
5403
5362
|
for (const entry of entries) {
|
|
5404
5363
|
if (!entry.isFile() || !entry.name.endsWith(".json")) continue;
|
|
5405
|
-
const pendingPath =
|
|
5364
|
+
const pendingPath = path12.join(dir, entry.name);
|
|
5406
5365
|
try {
|
|
5407
|
-
const data = JSON.parse(
|
|
5366
|
+
const data = JSON.parse(fs11.readFileSync(pendingPath, "utf-8"));
|
|
5408
5367
|
const runId = nonEmptyString2(data.runId) ?? nonEmptyString2(data.id);
|
|
5409
5368
|
if (runId && nonEmptyString2(data.sessionId) === sessionId) files.add(resultFileName(runId));
|
|
5410
5369
|
} catch (error) {
|
|
@@ -5429,43 +5388,43 @@ function missionObserverResultCandidateFiles(resultsDir) {
|
|
|
5429
5388
|
return resultFilesFromIndexDir(resultsDir, observerIndexDir(resultsDir, MISSION_OBSERVER), true);
|
|
5430
5389
|
}
|
|
5431
5390
|
function cleanupResultIndexes(resultsDir, now = Date.now(), maxAgeMs = 24 * 60 * 60 * 1e3) {
|
|
5432
|
-
const root =
|
|
5391
|
+
const root = path12.join(resultsDir, RESULT_INDEX_DIR);
|
|
5433
5392
|
const cutoff = now - maxAgeMs;
|
|
5434
5393
|
let removed = 0;
|
|
5435
5394
|
const visit = (dir) => {
|
|
5436
5395
|
let entries;
|
|
5437
5396
|
try {
|
|
5438
|
-
entries =
|
|
5397
|
+
entries = fs11.readdirSync(dir, { withFileTypes: true });
|
|
5439
5398
|
} catch (error) {
|
|
5440
5399
|
const code = error.code;
|
|
5441
5400
|
if (code === "ENOENT" || code === "ENOTDIR" || code === "EPERM" || code === "EACCES" || isUnaddressableResultCandidate(error)) return;
|
|
5442
5401
|
throw error;
|
|
5443
5402
|
}
|
|
5444
5403
|
for (const entry of entries) {
|
|
5445
|
-
const fullPath =
|
|
5404
|
+
const fullPath = path12.join(dir, entry.name);
|
|
5446
5405
|
if (entry.isDirectory()) {
|
|
5447
5406
|
visit(fullPath);
|
|
5448
5407
|
try {
|
|
5449
|
-
|
|
5408
|
+
fs11.rmdirSync(fullPath);
|
|
5450
5409
|
} catch {
|
|
5451
5410
|
}
|
|
5452
5411
|
continue;
|
|
5453
5412
|
}
|
|
5454
5413
|
if (!entry.isFile() || !entry.name.endsWith(".json")) continue;
|
|
5455
5414
|
try {
|
|
5456
|
-
const stat =
|
|
5457
|
-
const index = parseResultIndexEntry(JSON.parse(
|
|
5415
|
+
const stat = fs11.statSync(fullPath);
|
|
5416
|
+
const index = parseResultIndexEntry(JSON.parse(fs11.readFileSync(fullPath, "utf-8")));
|
|
5458
5417
|
const resultFile = index ? indexedResultFile(resultsDir, index) : void 0;
|
|
5459
5418
|
const pendingFile = index ? pendingResultExists(resultsDir, index.sessionId, index.runId) : false;
|
|
5460
5419
|
if (!index || !resultFile && !pendingFile && stat.mtimeMs <= cutoff) {
|
|
5461
|
-
|
|
5420
|
+
fs11.rmSync(fullPath, { force: true });
|
|
5462
5421
|
removed += 1;
|
|
5463
5422
|
}
|
|
5464
5423
|
} catch (error) {
|
|
5465
5424
|
if (isUnaddressableResultCandidate(error)) continue;
|
|
5466
5425
|
if (error.code !== "ENOENT") console.error(`Ignoring invalid async result index '${fullPath}':`, error);
|
|
5467
5426
|
try {
|
|
5468
|
-
|
|
5427
|
+
fs11.rmSync(fullPath, { force: true });
|
|
5469
5428
|
removed += 1;
|
|
5470
5429
|
} catch {
|
|
5471
5430
|
}
|
|
@@ -5477,21 +5436,21 @@ function cleanupResultIndexes(resultsDir, now = Date.now(), maxAgeMs = 24 * 60 *
|
|
|
5477
5436
|
}
|
|
5478
5437
|
|
|
5479
5438
|
// src/shared/completion-owner.ts
|
|
5480
|
-
import { randomUUID as
|
|
5439
|
+
import { randomUUID as randomUUID5 } from "node:crypto";
|
|
5481
5440
|
var COMPLETION_OWNER_KEY = /* @__PURE__ */ Symbol.for("pi-subagents.completion-owner-id");
|
|
5482
5441
|
var OWNING_SESSION_COMPLETION_OWNER = "owning-session";
|
|
5483
5442
|
function currentCompletionOwnerId() {
|
|
5484
5443
|
const runtime2 = globalThis;
|
|
5485
|
-
runtime2[COMPLETION_OWNER_KEY] ??=
|
|
5444
|
+
runtime2[COMPLETION_OWNER_KEY] ??= randomUUID5();
|
|
5486
5445
|
return runtime2[COMPLETION_OWNER_KEY];
|
|
5487
5446
|
}
|
|
5488
5447
|
|
|
5489
5448
|
// src/runs/background/boot-id.ts
|
|
5490
5449
|
import { execFileSync as execFileSync2 } from "node:child_process";
|
|
5491
|
-
import * as
|
|
5450
|
+
import * as fs13 from "node:fs";
|
|
5492
5451
|
|
|
5493
5452
|
// src/runs/background/pid-namespace.ts
|
|
5494
|
-
import * as
|
|
5453
|
+
import * as fs12 from "node:fs";
|
|
5495
5454
|
var resolved = false;
|
|
5496
5455
|
var cachedScope;
|
|
5497
5456
|
function currentPidNamespaceScope() {
|
|
@@ -5499,7 +5458,7 @@ function currentPidNamespaceScope() {
|
|
|
5499
5458
|
resolved = true;
|
|
5500
5459
|
if (process.platform !== "linux") return void 0;
|
|
5501
5460
|
try {
|
|
5502
|
-
const scope =
|
|
5461
|
+
const scope = fs12.readlinkSync("/proc/self/ns/pid", "utf-8").trim();
|
|
5503
5462
|
cachedScope = scope || void 0;
|
|
5504
5463
|
} catch {
|
|
5505
5464
|
cachedScope = void 0;
|
|
@@ -5510,7 +5469,7 @@ function currentPidNamespaceScope() {
|
|
|
5510
5469
|
// src/runs/background/boot-id.ts
|
|
5511
5470
|
function readBootIdFromOs() {
|
|
5512
5471
|
try {
|
|
5513
|
-
if (process.platform === "linux") return
|
|
5472
|
+
if (process.platform === "linux") return fs13.readFileSync("/proc/sys/kernel/random/boot_id", "utf-8").trim() || void 0;
|
|
5514
5473
|
if (process.platform === "darwin") {
|
|
5515
5474
|
return execFileSync2("sysctl", ["-n", "kern.bootsessionuuid"], { encoding: "utf-8", timeout: 1e3, stdio: ["ignore", "pipe", "ignore"] }).trim() || void 0;
|
|
5516
5475
|
}
|
|
@@ -5535,8 +5494,8 @@ function currentRecordedPid() {
|
|
|
5535
5494
|
}
|
|
5536
5495
|
|
|
5537
5496
|
// src/runs/background/stale-run-reconciler.ts
|
|
5538
|
-
import * as
|
|
5539
|
-
import * as
|
|
5497
|
+
import * as fs15 from "node:fs";
|
|
5498
|
+
import * as path14 from "node:path";
|
|
5540
5499
|
|
|
5541
5500
|
// src/runs/background/parallel-groups.ts
|
|
5542
5501
|
function isValidParallelGroup(group, stepCount, chainStepCount) {
|
|
@@ -5577,16 +5536,16 @@ function isReusableWorkflowStopCause(cause) {
|
|
|
5577
5536
|
}
|
|
5578
5537
|
|
|
5579
5538
|
// src/runs/background/workflow-terminal-proof.ts
|
|
5580
|
-
import * as
|
|
5581
|
-
import * as
|
|
5539
|
+
import * as fs14 from "node:fs";
|
|
5540
|
+
import * as path13 from "node:path";
|
|
5582
5541
|
var TERMINAL_WORKFLOW_STATES = /* @__PURE__ */ new Set(["completed", "failed", "stopped"]);
|
|
5583
5542
|
function isTerminalAsyncState(state) {
|
|
5584
5543
|
return state !== "queued" && state !== "running" && state !== "paused";
|
|
5585
5544
|
}
|
|
5586
5545
|
function readWorkflowChildRunModel(workflowAsyncDir, step) {
|
|
5587
|
-
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;
|
|
5588
5547
|
try {
|
|
5589
|
-
const child = readStatus(
|
|
5548
|
+
const child = readStatus(path13.join(path13.dirname(workflowAsyncDir), step.runId));
|
|
5590
5549
|
const first = Array.isArray(child?.steps) ? child.steps[0] : void 0;
|
|
5591
5550
|
const model = typeof first?.model === "string" && first.model ? first.model : void 0;
|
|
5592
5551
|
const thinking = typeof first?.thinking === "string" && first.thinking ? first.thinking : void 0;
|
|
@@ -5615,15 +5574,15 @@ function readWorkflowChildProcessEvidence(workflowAsyncDir, steps) {
|
|
|
5615
5574
|
}
|
|
5616
5575
|
function launchFailedBeforeRunner(step, childDir) {
|
|
5617
5576
|
if (step.status !== "failed" || !step.error) return false;
|
|
5618
|
-
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)));
|
|
5619
5578
|
}
|
|
5620
5579
|
function readWorkflowChildEvidence(workflowAsyncDir, step) {
|
|
5621
5580
|
const label = step.workflowKey ?? step.agent;
|
|
5622
5581
|
if (typeof step.async !== "boolean") return { state: "unknown", reason: `workflow child ${label} is missing async classification` };
|
|
5623
5582
|
if (!step.async) return void 0;
|
|
5624
|
-
if (!step.runId ||
|
|
5625
|
-
const childDir =
|
|
5626
|
-
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` };
|
|
5627
5586
|
const childStatus = readStatus(childDir);
|
|
5628
5587
|
if (!childStatus) return launchFailedBeforeRunner(step, childDir) ? void 0 : { state: "unknown", reason: `async workflow child ${label} status is missing or unreadable` };
|
|
5629
5588
|
if (!isTerminalAsyncState(childStatus.state)) return { state: "pending", reason: `async workflow child ${label} is still ${childStatus.state}` };
|
|
@@ -5666,21 +5625,21 @@ function getErrorMessage(error) {
|
|
|
5666
5625
|
return error instanceof Error ? error.message : String(error);
|
|
5667
5626
|
}
|
|
5668
5627
|
function readRunnerStartupDiagnostics(asyncDir) {
|
|
5669
|
-
const stderrPath =
|
|
5628
|
+
const stderrPath = path14.join(asyncDir, "runner.stderr.log");
|
|
5670
5629
|
const maxBytes = 64 * 1024;
|
|
5671
5630
|
let content;
|
|
5672
5631
|
try {
|
|
5673
|
-
const stat =
|
|
5632
|
+
const stat = fs15.statSync(stderrPath);
|
|
5674
5633
|
if (stat.size <= 0) return void 0;
|
|
5675
|
-
const fd =
|
|
5634
|
+
const fd = fs15.openSync(stderrPath, "r");
|
|
5676
5635
|
try {
|
|
5677
5636
|
const bytesToRead = Math.min(stat.size, maxBytes);
|
|
5678
5637
|
const start = Math.max(0, stat.size - bytesToRead);
|
|
5679
5638
|
const buffer = Buffer.alloc(bytesToRead);
|
|
5680
|
-
|
|
5639
|
+
fs15.readSync(fd, buffer, 0, bytesToRead, start);
|
|
5681
5640
|
content = buffer.toString("utf-8").trim();
|
|
5682
5641
|
} finally {
|
|
5683
|
-
|
|
5642
|
+
fs15.closeSync(fd);
|
|
5684
5643
|
}
|
|
5685
5644
|
} catch {
|
|
5686
5645
|
return void 0;
|
|
@@ -5695,15 +5654,15 @@ function isNotFoundError(error) {
|
|
|
5695
5654
|
}
|
|
5696
5655
|
function appendJsonlBestEffort(filePath, payload) {
|
|
5697
5656
|
try {
|
|
5698
|
-
|
|
5699
|
-
|
|
5657
|
+
fs15.mkdirSync(path14.dirname(filePath), { recursive: true });
|
|
5658
|
+
fs15.appendFileSync(filePath, `${JSON.stringify(payload)}
|
|
5700
5659
|
`, "utf-8");
|
|
5701
5660
|
} catch {
|
|
5702
5661
|
}
|
|
5703
5662
|
}
|
|
5704
5663
|
function regularFileExists(filePath) {
|
|
5705
5664
|
try {
|
|
5706
|
-
return
|
|
5665
|
+
return fs15.statSync(filePath).isFile();
|
|
5707
5666
|
} catch (error) {
|
|
5708
5667
|
if (isNotFoundError(error)) return false;
|
|
5709
5668
|
throw error;
|
|
@@ -5711,7 +5670,7 @@ function regularFileExists(filePath) {
|
|
|
5711
5670
|
}
|
|
5712
5671
|
function readResultRepairData(resultPath) {
|
|
5713
5672
|
try {
|
|
5714
|
-
const data = JSON.parse(
|
|
5673
|
+
const data = JSON.parse(fs15.readFileSync(resultPath, "utf-8"));
|
|
5715
5674
|
if (data.error !== void 0 && typeof data.error !== "string") throw new Error(`Invalid async result file '${resultPath}': error must be a string.`);
|
|
5716
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";
|
|
5717
5676
|
const results = Array.isArray(data.results) ? data.results.map((entry, index) => {
|
|
@@ -5785,7 +5744,7 @@ function buildStartedStatus(asyncDir, startedRun, now) {
|
|
|
5785
5744
|
const chainStepCount = startedRun.chainStepCount;
|
|
5786
5745
|
const parallelGroups = chainStepCount !== void 0 ? normalizeParallelGroups(startedRun.parallelGroups, agents.length, chainStepCount) : [];
|
|
5787
5746
|
return {
|
|
5788
|
-
runId: startedRun.runId ||
|
|
5747
|
+
runId: startedRun.runId || path14.basename(asyncDir),
|
|
5789
5748
|
...startedRun.sessionId ? { sessionId: startedRun.sessionId } : {},
|
|
5790
5749
|
...startedRun.completionOwnerId ? { completionOwnerId: startedRun.completionOwnerId } : {},
|
|
5791
5750
|
mode: startedRun.mode ?? "single",
|
|
@@ -5807,8 +5766,8 @@ function buildStartedStatus(asyncDir, startedRun, now) {
|
|
|
5807
5766
|
}
|
|
5808
5767
|
function settledWorkflowChildStatus(asyncDir, workflowRunId, step, now) {
|
|
5809
5768
|
const childRunId = step.runId;
|
|
5810
|
-
if (step.async !== true || step.parentWorkflowRunId !== workflowRunId || !childRunId || childRunId === workflowRunId || childRunId !==
|
|
5811
|
-
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));
|
|
5812
5771
|
if (!child || child.runId !== childRunId || child.parentWorkflowRunId !== workflowRunId || !isTerminalAsyncState(child.state)) return void 0;
|
|
5813
5772
|
if (step.workflowKey !== void 0 && child.workflowKey !== step.workflowKey) return void 0;
|
|
5814
5773
|
const state = child.state;
|
|
@@ -5829,7 +5788,7 @@ function settledWorkflowChildStatus(asyncDir, workflowRunId, step, now) {
|
|
|
5829
5788
|
return settled;
|
|
5830
5789
|
}
|
|
5831
5790
|
function buildFailedRepair(status, asyncDir, now, reason, ownerExited = false, adoptCompletionOwnerId) {
|
|
5832
|
-
const runId = status.runId ||
|
|
5791
|
+
const runId = status.runId || path14.basename(asyncDir);
|
|
5833
5792
|
const pid = typeof status.pid === "number" ? status.pid : "unknown";
|
|
5834
5793
|
const exitedWorkflow = ownerExited && status.mode === "workflow" ? status.workflow : void 0;
|
|
5835
5794
|
const completionOwnerId = exitedWorkflow ? adoptCompletionOwnerId || OWNING_SESSION_COMPLETION_OWNER : status.completionOwnerId;
|
|
@@ -5916,9 +5875,9 @@ ${diagnostics}` : baseMessage;
|
|
|
5916
5875
|
function writeFailedRepair(asyncDir, status, resultPath, now, reason, ownerExited = false, adoptCompletionOwnerId) {
|
|
5917
5876
|
const repair = buildFailedRepair(status, asyncDir, now, reason, ownerExited, adoptCompletionOwnerId);
|
|
5918
5877
|
if (repair.result.sessionId) writeAsyncResultFile(resultPath, repair.result);
|
|
5919
|
-
writeAtomicJson(
|
|
5878
|
+
writeAtomicJson(path14.join(asyncDir, "status.json"), repair.status);
|
|
5920
5879
|
updateActiveRunIndex(asyncDir, repair.status.state, repair.status.toolCallId);
|
|
5921
|
-
appendJsonlBestEffort(
|
|
5880
|
+
appendJsonlBestEffort(path14.join(asyncDir, "events.jsonl"), {
|
|
5922
5881
|
type: "subagent.run.repaired_stale",
|
|
5923
5882
|
ts: now,
|
|
5924
5883
|
runId: repair.status.runId,
|
|
@@ -5946,7 +5905,7 @@ function reconcileNestedAsyncDescendants(route, options = {}) {
|
|
|
5946
5905
|
if (!asyncDir) continue;
|
|
5947
5906
|
const result = reconcileAsyncRun(asyncDir, {
|
|
5948
5907
|
...options,
|
|
5949
|
-
resultsDir:
|
|
5908
|
+
resultsDir: path14.join(options.resultsDir ?? DIRS.results, "nested", route.rootRunId)
|
|
5950
5909
|
});
|
|
5951
5910
|
const status = result.status;
|
|
5952
5911
|
if (!status) continue;
|
|
@@ -5974,7 +5933,7 @@ function checkPidLiveness(pid, kill = process.kill, probeZombie = false) {
|
|
|
5974
5933
|
kill(pid, 0);
|
|
5975
5934
|
if (probeZombie && process.platform === "linux") {
|
|
5976
5935
|
try {
|
|
5977
|
-
const stat =
|
|
5936
|
+
const stat = fs15.readFileSync(`/proc/${pid}/stat`, "utf-8");
|
|
5978
5937
|
const closeParen = stat.lastIndexOf(") ");
|
|
5979
5938
|
if (closeParen >= 0 && stat[closeParen + 2] === "Z") return "dead";
|
|
5980
5939
|
} catch {
|
|
@@ -6008,14 +5967,14 @@ function reconcileAsyncRun(asyncDir, options = {}, observeStatus) {
|
|
|
6008
5967
|
const startedStatus = !status && options.startedRun ? buildStartedStatus(asyncDir, options.startedRun, now) : void 0;
|
|
6009
5968
|
const effectiveStatus = status ?? startedStatus;
|
|
6010
5969
|
if (!effectiveStatus) return { status: null, repaired: false };
|
|
6011
|
-
assertWorkflowGraphHostSteps(effectiveStatus.workflowGraph,
|
|
6012
|
-
const statusPath =
|
|
5970
|
+
assertWorkflowGraphHostSteps(effectiveStatus.workflowGraph, path14.join(asyncDir, "status.json"), effectiveStatus.runId);
|
|
5971
|
+
const statusPath = path14.join(asyncDir, "status.json");
|
|
6013
5972
|
for (const [index, step] of (effectiveStatus.steps ?? []).entries()) {
|
|
6014
5973
|
const stepRecord = step;
|
|
6015
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.`);
|
|
6016
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.`);
|
|
6017
5976
|
}
|
|
6018
|
-
const runId = effectiveStatus.runId ||
|
|
5977
|
+
const runId = effectiveStatus.runId || path14.basename(asyncDir);
|
|
6019
5978
|
const resultsDir = options.resultsDir ?? DIRS.results;
|
|
6020
5979
|
const resultPath = resultFilePath(resultsDir, runId);
|
|
6021
5980
|
const existingResultPath = effectiveStatus.sessionId ? resultPayloadPathForSessionRun(resultsDir, effectiveStatus.sessionId, runId) ?? (regularFileExists(resultPath) ? resultPath : void 0) : regularFileExists(resultPath) ? resultPath : void 0;
|
|
@@ -6112,19 +6071,19 @@ function validateAuthorityPolicy(value, label = "config.authorityPolicy") {
|
|
|
6112
6071
|
}
|
|
6113
6072
|
|
|
6114
6073
|
// src/runs/shared/worktree.ts
|
|
6115
|
-
import { createHash as
|
|
6074
|
+
import { createHash as createHash5 } from "node:crypto";
|
|
6116
6075
|
import { spawnSync } from "node:child_process";
|
|
6117
6076
|
|
|
6118
6077
|
// src/runs/shared/worktree-setup-command.ts
|
|
6119
6078
|
import { spawn as spawn2 } from "node:child_process";
|
|
6120
6079
|
function terminateCommandTree(pid, controller) {
|
|
6121
6080
|
if (process.platform !== "win32") return controller.terminate();
|
|
6122
|
-
return new Promise((
|
|
6081
|
+
return new Promise((resolve5) => {
|
|
6123
6082
|
let settled = false;
|
|
6124
6083
|
const fallback = () => {
|
|
6125
6084
|
if (settled) return;
|
|
6126
6085
|
settled = true;
|
|
6127
|
-
void controller.terminate().then(
|
|
6086
|
+
void controller.terminate().then(resolve5);
|
|
6128
6087
|
};
|
|
6129
6088
|
const cleanup = spawn2("taskkill", ["/PID", String(pid), "/T", "/F"], { stdio: "ignore", windowsHide: true });
|
|
6130
6089
|
cleanup.once("error", fallback);
|
|
@@ -6132,7 +6091,7 @@ function terminateCommandTree(pid, controller) {
|
|
|
6132
6091
|
if (settled) return;
|
|
6133
6092
|
if (status !== 0) return fallback();
|
|
6134
6093
|
settled = true;
|
|
6135
|
-
|
|
6094
|
+
resolve5({ state: "observed", mechanism: "windows-taskkill", pid, verifiedAt: Date.now() });
|
|
6136
6095
|
});
|
|
6137
6096
|
});
|
|
6138
6097
|
}
|
|
@@ -6234,21 +6193,21 @@ async function runSetupCommand(command, args, options) {
|
|
|
6234
6193
|
child.stdout.on("data", onStdout);
|
|
6235
6194
|
child.stderr.on("data", onStderr);
|
|
6236
6195
|
child.stdin.on("error", fail);
|
|
6237
|
-
const close = new Promise((
|
|
6238
|
-
const directExit = new Promise((
|
|
6196
|
+
const close = new Promise((resolve5) => child.once("close", () => resolve5()));
|
|
6197
|
+
const directExit = new Promise((resolve5) => {
|
|
6239
6198
|
child.once("exit", (status, signal) => {
|
|
6240
6199
|
directSettled = true;
|
|
6241
6200
|
result.status = status;
|
|
6242
6201
|
result.signal = signal;
|
|
6243
6202
|
if (status === null || !(options.acceptedExitCodes ?? [0]).includes(status)) terminate();
|
|
6244
6203
|
releaseUnknownIO();
|
|
6245
|
-
|
|
6204
|
+
resolve5();
|
|
6246
6205
|
});
|
|
6247
6206
|
child.once("error", (error) => {
|
|
6248
6207
|
fail(error);
|
|
6249
6208
|
if (child.pid === void 0) {
|
|
6250
6209
|
directSettled = true;
|
|
6251
|
-
|
|
6210
|
+
resolve5();
|
|
6252
6211
|
}
|
|
6253
6212
|
});
|
|
6254
6213
|
});
|
|
@@ -6296,13 +6255,13 @@ async function runSetupCommand(command, args, options) {
|
|
|
6296
6255
|
}
|
|
6297
6256
|
|
|
6298
6257
|
// src/runs/shared/worktree.ts
|
|
6299
|
-
import * as
|
|
6258
|
+
import * as fs16 from "node:fs";
|
|
6300
6259
|
import * as os2 from "node:os";
|
|
6301
|
-
import * as
|
|
6260
|
+
import * as path15 from "node:path";
|
|
6302
6261
|
var DEFAULT_WORKTREE_PROVIDER = "auto";
|
|
6303
6262
|
var DEFAULT_WORKTREE_BASE_REF = "HEAD";
|
|
6304
6263
|
var DEFAULT_WORKTREE_BRANCH_PREFIX = "pi-subagents/";
|
|
6305
|
-
var WORKTREE_AGENT_CWD_PLACEHOLDER =
|
|
6264
|
+
var WORKTREE_AGENT_CWD_PLACEHOLDER = path15.join(path15.parse(process.cwd()).root, "__pi_subagents_worktree_cwd__");
|
|
6306
6265
|
var WORKTREE_NAMING_COMPONENT_MAX_BYTES = 96;
|
|
6307
6266
|
var WORKTREE_NAMING_LABEL_MAX_BYTES = 256;
|
|
6308
6267
|
var WORKTREE_NAMING_BRANCH_MAX_BYTES = 256;
|
|
@@ -6331,8 +6290,8 @@ function assertWorktreeMutationAllowed() {
|
|
|
6331
6290
|
async function withWorktreeTransaction(action) {
|
|
6332
6291
|
const previous = worktreeTurn;
|
|
6333
6292
|
let release;
|
|
6334
|
-
worktreeTurn = new Promise((
|
|
6335
|
-
release =
|
|
6293
|
+
worktreeTurn = new Promise((resolve5) => {
|
|
6294
|
+
release = resolve5;
|
|
6336
6295
|
});
|
|
6337
6296
|
await previous;
|
|
6338
6297
|
try {
|
|
@@ -6436,7 +6395,7 @@ function findListedWorktreeAgentCwd(repoCwd, branch) {
|
|
|
6436
6395
|
const worktree = findListedWorktreeOnBranch(repoCwd, branch);
|
|
6437
6396
|
if (!worktree) return void 0;
|
|
6438
6397
|
const cwdRelative = resolveRepoCwdRelative(repoCwd);
|
|
6439
|
-
return cwdRelative ?
|
|
6398
|
+
return cwdRelative ? path15.join(worktree, cwdRelative) : worktree;
|
|
6440
6399
|
}
|
|
6441
6400
|
function isComparablePathInside(parent, child) {
|
|
6442
6401
|
return isPathInside(normalizeComparableCwd(parent), normalizeComparableCwd(child));
|
|
@@ -6450,11 +6409,11 @@ function currentWorktreePatch(worktreePath, baseCommit) {
|
|
|
6450
6409
|
assertWorktreeMutationAllowed();
|
|
6451
6410
|
let tempDir;
|
|
6452
6411
|
try {
|
|
6453
|
-
tempDir =
|
|
6412
|
+
tempDir = fs16.mkdtempSync(path15.join(os2.tmpdir(), "pi-worktree-index-"));
|
|
6454
6413
|
} catch (error) {
|
|
6455
6414
|
return { error: error instanceof Error ? error.message : String(error) };
|
|
6456
6415
|
}
|
|
6457
|
-
const env = { GIT_INDEX_FILE:
|
|
6416
|
+
const env = { GIT_INDEX_FILE: path15.join(tempDir, "index") };
|
|
6458
6417
|
try {
|
|
6459
6418
|
const readTree = runGit(worktreePath, ["read-tree", "HEAD"], env);
|
|
6460
6419
|
if (readTree.status !== 0) return { error: readTree.stderr.trim() || readTree.stdout.trim() || "git read-tree failed" };
|
|
@@ -6465,7 +6424,7 @@ function currentWorktreePatch(worktreePath, baseCommit) {
|
|
|
6465
6424
|
return { patch: diff.stdout };
|
|
6466
6425
|
} finally {
|
|
6467
6426
|
try {
|
|
6468
|
-
|
|
6427
|
+
fs16.rmSync(tempDir, { recursive: true, force: true });
|
|
6469
6428
|
} catch {
|
|
6470
6429
|
}
|
|
6471
6430
|
}
|
|
@@ -6475,7 +6434,7 @@ function validateWorktreePatchRepresentsCurrentWorktree(worktreePath, baseCommit
|
|
|
6475
6434
|
if (validationError) return validationError;
|
|
6476
6435
|
let capturedPatch;
|
|
6477
6436
|
try {
|
|
6478
|
-
capturedPatch =
|
|
6437
|
+
capturedPatch = fs16.readFileSync(patchPath, "utf-8");
|
|
6479
6438
|
} catch (error) {
|
|
6480
6439
|
return error instanceof Error ? error.message : String(error);
|
|
6481
6440
|
}
|
|
@@ -6508,7 +6467,7 @@ async function preflightWorktreeSource(cwd, options = {}) {
|
|
|
6508
6467
|
async function resolveRepoState(tx, cwd, requestedBaseRef) {
|
|
6509
6468
|
const toplevel = await probeWorktreeSource(tx, cwd);
|
|
6510
6469
|
const rawPrefix = (await tx.gitChecked(cwd, ["rev-parse", "--show-prefix"])).trim();
|
|
6511
|
-
const cwdRelative = rawPrefix ?
|
|
6470
|
+
const cwdRelative = rawPrefix ? path15.normalize(rawPrefix.replace(/[\\/]+$/, "")) : "";
|
|
6512
6471
|
const baseRef = normalizeWorktreeBaseRef(requestedBaseRef) ?? DEFAULT_WORKTREE_BASE_REF;
|
|
6513
6472
|
let baseCommit;
|
|
6514
6473
|
try {
|
|
@@ -6522,22 +6481,22 @@ async function resolveRepoState(tx, cwd, requestedBaseRef) {
|
|
|
6522
6481
|
return { toplevel, cwdRelative, baseCommit };
|
|
6523
6482
|
}
|
|
6524
6483
|
function normalizeComparableCwd(cwd) {
|
|
6525
|
-
const resolved2 =
|
|
6484
|
+
const resolved2 = path15.resolve(cwd);
|
|
6526
6485
|
let existing = resolved2;
|
|
6527
6486
|
const missingSegments = [];
|
|
6528
6487
|
while (true) {
|
|
6529
6488
|
try {
|
|
6530
6489
|
let realpath;
|
|
6531
6490
|
try {
|
|
6532
|
-
realpath =
|
|
6491
|
+
realpath = fs16.realpathSync.native(existing);
|
|
6533
6492
|
} catch {
|
|
6534
|
-
realpath =
|
|
6493
|
+
realpath = fs16.realpathSync(existing);
|
|
6535
6494
|
}
|
|
6536
|
-
return
|
|
6495
|
+
return path15.join(realpath, ...missingSegments.reverse());
|
|
6537
6496
|
} catch {
|
|
6538
|
-
const parent =
|
|
6497
|
+
const parent = path15.dirname(existing);
|
|
6539
6498
|
if (parent === existing) return resolved2;
|
|
6540
|
-
missingSegments.push(
|
|
6499
|
+
missingSegments.push(path15.basename(existing));
|
|
6541
6500
|
existing = parent;
|
|
6542
6501
|
}
|
|
6543
6502
|
}
|
|
@@ -6546,7 +6505,7 @@ function safePatchAgentName(agent) {
|
|
|
6546
6505
|
return agent.replace(/[^\w.-]/g, "_");
|
|
6547
6506
|
}
|
|
6548
6507
|
function shortWorktreeHash(value) {
|
|
6549
|
-
return
|
|
6508
|
+
return createHash5("sha256").update(value, "utf-8").digest("hex").slice(0, 8);
|
|
6550
6509
|
}
|
|
6551
6510
|
function truncateUtf8(value, maxBytes) {
|
|
6552
6511
|
const bytes = Buffer.from(value, "utf-8");
|
|
@@ -6631,7 +6590,7 @@ function hasConfiguredWorktreeBaseDir(baseDir) {
|
|
|
6631
6590
|
return baseDir !== void 0 ? true : (process.env.PI_SUBAGENTS_WORKTREE_DIR?.trim().length ?? 0) > 0;
|
|
6632
6591
|
}
|
|
6633
6592
|
function isInsidePiExtensionsDirectory(targetPath) {
|
|
6634
|
-
const extensionsDir = normalizeComparableCwd(
|
|
6593
|
+
const extensionsDir = normalizeComparableCwd(path15.join(getAgentDir(), "extensions"));
|
|
6635
6594
|
return isPathInside(extensionsDir, normalizeComparableCwd(targetPath));
|
|
6636
6595
|
}
|
|
6637
6596
|
function runWorktrunk(args, cwd) {
|
|
@@ -6713,49 +6672,49 @@ function resolveWorktreeDedicatedRoot(configuredBaseDir, repoRoot, relocateExten
|
|
|
6713
6672
|
const rawBaseDir = configuredBaseDir ?? process.env.PI_SUBAGENTS_WORKTREE_DIR;
|
|
6714
6673
|
let expanded;
|
|
6715
6674
|
if (rawBaseDir === void 0 || configuredBaseDir === void 0 && !rawBaseDir.trim()) {
|
|
6716
|
-
expanded = relocateExtensionRepo && isInsidePiExtensionsDirectory(repoRoot) ?
|
|
6675
|
+
expanded = relocateExtensionRepo && isInsidePiExtensionsDirectory(repoRoot) ? path15.join(getAgentDir(), "worktrees") : path15.join(path15.dirname(repoRoot), "worktrees");
|
|
6717
6676
|
} else {
|
|
6718
6677
|
const trimmed = rawBaseDir.trim();
|
|
6719
6678
|
if (!trimmed) throw new Error("worktree base directory cannot be empty");
|
|
6720
|
-
const candidate = trimmed.startsWith("~/") ?
|
|
6721
|
-
expanded =
|
|
6679
|
+
const candidate = trimmed.startsWith("~/") ? path15.join(os2.homedir(), trimmed.slice(2)) : trimmed;
|
|
6680
|
+
expanded = path15.isAbsolute(candidate) ? candidate : path15.resolve(repoRoot, candidate);
|
|
6722
6681
|
}
|
|
6723
|
-
const extensionsDir = normalizeComparableCwd(
|
|
6682
|
+
const extensionsDir = normalizeComparableCwd(path15.join(getAgentDir(), "extensions"));
|
|
6724
6683
|
if (isPathInside(extensionsDir, normalizeComparableCwd(expanded))) {
|
|
6725
6684
|
throw new Error(`worktree base directory cannot be inside Pi extensions directory: ${extensionsDir}. Choose a directory outside it.`);
|
|
6726
6685
|
}
|
|
6727
6686
|
return expanded;
|
|
6728
6687
|
}
|
|
6729
6688
|
function buildNativeProjectPath(dedicatedRoot, repoRoot) {
|
|
6730
|
-
return
|
|
6689
|
+
return path15.join(dedicatedRoot, path15.basename(repoRoot));
|
|
6731
6690
|
}
|
|
6732
6691
|
function ensureProjectWorktreeDir(dedicatedRoot, repoRoot) {
|
|
6733
6692
|
try {
|
|
6734
|
-
|
|
6693
|
+
fs16.mkdirSync(buildNativeProjectPath(dedicatedRoot, repoRoot), { recursive: true });
|
|
6735
6694
|
} catch (error) {
|
|
6736
6695
|
const message = error instanceof Error ? error.message : String(error);
|
|
6737
6696
|
throw new Error(`failed to create worktree base directory ${dedicatedRoot}: ${message}`);
|
|
6738
6697
|
}
|
|
6739
6698
|
}
|
|
6740
6699
|
function buildNativeWorktreePath(dedicatedRoot, repoRoot, runId, index) {
|
|
6741
|
-
return
|
|
6700
|
+
return path15.join(buildNativeProjectPath(dedicatedRoot, repoRoot), `pi-worktree-${sanitizeWorktreePathComponent(runId, 120)}-${index}`);
|
|
6742
6701
|
}
|
|
6743
6702
|
function isPathInside(parent, child) {
|
|
6744
|
-
const relative4 =
|
|
6703
|
+
const relative4 = path15.relative(parent, child);
|
|
6745
6704
|
if (!relative4 || relative4 === ".") return true;
|
|
6746
|
-
return relative4 !== ".." && !relative4.startsWith(`..${
|
|
6705
|
+
return relative4 !== ".." && !relative4.startsWith(`..${path15.sep}`) && !path15.isAbsolute(relative4);
|
|
6747
6706
|
}
|
|
6748
6707
|
function isStrictChildPath(parent, child) {
|
|
6749
|
-
const relative4 =
|
|
6750
|
-
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);
|
|
6751
6710
|
}
|
|
6752
6711
|
function assertSafeWorktreeLocation(worktreePath, repoRoot, dedicatedRoot) {
|
|
6753
6712
|
const resolvedLeaf = normalizeComparableCwd(worktreePath);
|
|
6754
6713
|
const resolvedRepoRoot = normalizeComparableCwd(repoRoot);
|
|
6755
6714
|
const projectDir = normalizeComparableCwd(buildNativeProjectPath(dedicatedRoot, repoRoot));
|
|
6756
|
-
const repoParent = normalizeComparableCwd(
|
|
6757
|
-
const leafParent = normalizeComparableCwd(
|
|
6758
|
-
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"));
|
|
6759
6718
|
if (isPathInside(extensionsDir, projectDir) || isPathInside(extensionsDir, resolvedLeaf)) {
|
|
6760
6719
|
throw new Error(`worktree path cannot be inside Pi extensions directory: ${extensionsDir}. Choose a directory outside it.`);
|
|
6761
6720
|
}
|
|
@@ -6775,7 +6734,7 @@ function resolveRepoCwdRelative(cwd) {
|
|
|
6775
6734
|
throw new Error("worktree isolation requires a git repository");
|
|
6776
6735
|
}
|
|
6777
6736
|
const rawPrefix = runGitChecked(cwd, ["rev-parse", "--show-prefix"]).trim();
|
|
6778
|
-
const normalizedPrefix = rawPrefix ?
|
|
6737
|
+
const normalizedPrefix = rawPrefix ? path15.normalize(rawPrefix.replace(/[\\/]+$/, "")) : "";
|
|
6779
6738
|
return normalizedPrefix === "." ? "" : normalizedPrefix;
|
|
6780
6739
|
}
|
|
6781
6740
|
function resolveExpectedWorktreeAgentCwd(cwd, runId, index, baseDir) {
|
|
@@ -6784,14 +6743,14 @@ function resolveExpectedWorktreeAgentCwd(cwd, runId, index, baseDir) {
|
|
|
6784
6743
|
const dedicatedRoot = resolveWorktreeDedicatedRoot(baseDir, repoRoot);
|
|
6785
6744
|
const worktreePath = buildNativeWorktreePath(dedicatedRoot, repoRoot, runId, index);
|
|
6786
6745
|
assertSafeWorktreeLocation(worktreePath, repoRoot, dedicatedRoot);
|
|
6787
|
-
return cwdRelative ?
|
|
6746
|
+
return cwdRelative ? path15.join(worktreePath, cwdRelative) : worktreePath;
|
|
6788
6747
|
}
|
|
6789
6748
|
function linkNodeModulesIfPresent(toplevel, worktreePath) {
|
|
6790
|
-
const nodeModulesPath =
|
|
6791
|
-
const nodeModulesLinkPath =
|
|
6749
|
+
const nodeModulesPath = path15.join(toplevel, "node_modules");
|
|
6750
|
+
const nodeModulesLinkPath = path15.join(worktreePath, "node_modules");
|
|
6792
6751
|
const hasDirectoryEntry = (candidate) => {
|
|
6793
6752
|
try {
|
|
6794
|
-
|
|
6753
|
+
fs16.lstatSync(candidate);
|
|
6795
6754
|
return true;
|
|
6796
6755
|
} catch (error) {
|
|
6797
6756
|
if (error instanceof Error && "code" in error && error.code === "ENOENT") return false;
|
|
@@ -6802,14 +6761,14 @@ function linkNodeModulesIfPresent(toplevel, worktreePath) {
|
|
|
6802
6761
|
if (hasDirectoryEntry(nodeModulesLinkPath)) return false;
|
|
6803
6762
|
let sourceRealPath;
|
|
6804
6763
|
try {
|
|
6805
|
-
if (!
|
|
6806
|
-
sourceRealPath =
|
|
6764
|
+
if (!fs16.statSync(nodeModulesPath).isDirectory()) throw new Error("source node_modules is not a directory");
|
|
6765
|
+
sourceRealPath = fs16.realpathSync.native(nodeModulesPath);
|
|
6807
6766
|
} catch (error) {
|
|
6808
6767
|
if (error instanceof Error && "code" in error && error.code === "ENOENT") return false;
|
|
6809
6768
|
throw error;
|
|
6810
6769
|
}
|
|
6811
|
-
|
|
6812
|
-
if (!
|
|
6770
|
+
fs16.symlinkSync(nodeModulesPath, nodeModulesLinkPath, process.platform === "win32" ? "junction" : "dir");
|
|
6771
|
+
if (!fs16.lstatSync(nodeModulesLinkPath).isSymbolicLink() || fs16.realpathSync.native(nodeModulesLinkPath) !== sourceRealPath) {
|
|
6813
6772
|
throw new Error("created link does not resolve to the source node_modules");
|
|
6814
6773
|
}
|
|
6815
6774
|
return true;
|
|
@@ -6834,19 +6793,19 @@ function resolveWorktreeSetupHook(repoRoot, config) {
|
|
|
6834
6793
|
if (!hookPath) {
|
|
6835
6794
|
throw new Error("worktree setup hook path cannot be empty");
|
|
6836
6795
|
}
|
|
6837
|
-
const expandedHookPath = hookPath.startsWith("~/") ?
|
|
6796
|
+
const expandedHookPath = hookPath.startsWith("~/") ? path15.join(os2.homedir(), hookPath.slice(2)) : hookPath;
|
|
6838
6797
|
let resolvedPath;
|
|
6839
|
-
if (
|
|
6798
|
+
if (path15.isAbsolute(expandedHookPath)) {
|
|
6840
6799
|
resolvedPath = expandedHookPath;
|
|
6841
6800
|
} else if (expandedHookPath.includes("/") || expandedHookPath.includes("\\")) {
|
|
6842
|
-
resolvedPath =
|
|
6801
|
+
resolvedPath = path15.resolve(repoRoot, expandedHookPath);
|
|
6843
6802
|
} else {
|
|
6844
6803
|
throw new Error("worktree setup hook must be an absolute path or a repo-relative path");
|
|
6845
6804
|
}
|
|
6846
|
-
if (!
|
|
6805
|
+
if (!fs16.existsSync(resolvedPath)) {
|
|
6847
6806
|
throw new Error(`worktree setup hook not found: ${resolvedPath}`);
|
|
6848
6807
|
}
|
|
6849
|
-
if (
|
|
6808
|
+
if (fs16.statSync(resolvedPath).isDirectory()) {
|
|
6850
6809
|
throw new Error(`worktree setup hook must be a file, got directory: ${resolvedPath}`);
|
|
6851
6810
|
}
|
|
6852
6811
|
return {
|
|
@@ -6857,16 +6816,16 @@ function resolveWorktreeSetupHook(repoRoot, config) {
|
|
|
6857
6816
|
function normalizeSyntheticPath(worktreePath, rawPath) {
|
|
6858
6817
|
const trimmed = rawPath.trim();
|
|
6859
6818
|
if (!trimmed) throw new Error("synthetic path cannot be empty");
|
|
6860
|
-
if (
|
|
6861
|
-
const resolved2 =
|
|
6862
|
-
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);
|
|
6863
6822
|
if (!relative4 || relative4 === ".") {
|
|
6864
6823
|
throw new Error(`synthetic path cannot target the worktree root: ${rawPath}`);
|
|
6865
6824
|
}
|
|
6866
|
-
if (relative4 === ".." || relative4.startsWith(`..${
|
|
6825
|
+
if (relative4 === ".." || relative4.startsWith(`..${path15.sep}`) || path15.isAbsolute(relative4)) {
|
|
6867
6826
|
throw new Error(`synthetic path escapes the worktree root: ${rawPath}`);
|
|
6868
6827
|
}
|
|
6869
|
-
return
|
|
6828
|
+
return path15.normalize(relative4);
|
|
6870
6829
|
}
|
|
6871
6830
|
function parseWorktreeSetupHookOutput(rawStdout) {
|
|
6872
6831
|
const trimmed = rawStdout.trim();
|
|
@@ -6920,7 +6879,7 @@ async function runWorktreeSetupHook(tx, hook, input) {
|
|
|
6920
6879
|
}
|
|
6921
6880
|
}
|
|
6922
6881
|
async function finalizeCreatedWorktree(tx, toplevel, cwdRelative, runId, baseCommit, setupHook, agent, worktree) {
|
|
6923
|
-
const agentCwd = cwdRelative ?
|
|
6882
|
+
const agentCwd = cwdRelative ? path15.join(worktree.path, cwdRelative) : worktree.path;
|
|
6924
6883
|
tx.check();
|
|
6925
6884
|
const nodeModulesLinked = linkNodeModulesIfPresent(toplevel, worktree.path);
|
|
6926
6885
|
const syntheticPaths = nodeModulesLinked ? ["node_modules"] : [];
|
|
@@ -6947,7 +6906,7 @@ async function createNativeWorktree(tx, toplevel, cwdRelative, runId, index, bas
|
|
|
6947
6906
|
const branch = await tx.git(toplevel, ["show-ref", "--verify", "--quiet", `refs/heads/${naming.requestedBranch}`], [0, 1]);
|
|
6948
6907
|
let pathExists = false;
|
|
6949
6908
|
try {
|
|
6950
|
-
|
|
6909
|
+
fs16.lstatSync(worktreePath);
|
|
6951
6910
|
pathExists = true;
|
|
6952
6911
|
} catch (error) {
|
|
6953
6912
|
if (!(error instanceof Error) || !("code" in error) || error.code !== "ENOENT") throw error;
|
|
@@ -6955,7 +6914,7 @@ async function createNativeWorktree(tx, toplevel, cwdRelative, runId, index, bas
|
|
|
6955
6914
|
if (branch.status !== 1 || pathExists) throw new Error(`worktree path or branch already exists: ${worktreePath}, ${naming.requestedBranch}`);
|
|
6956
6915
|
tx.attempt(index, naming.requestedBranch, worktreePath);
|
|
6957
6916
|
ensureProjectWorktreeDir(dedicatedRoot, toplevel);
|
|
6958
|
-
const recordedBaseDir = normalizeComparableCwd(
|
|
6917
|
+
const recordedBaseDir = normalizeComparableCwd(path15.dirname(worktreePath));
|
|
6959
6918
|
await tx.git(toplevel, ["worktree", "add", worktreePath, "-b", naming.requestedBranch, baseCommit]);
|
|
6960
6919
|
const worktree = {
|
|
6961
6920
|
path: worktreePath,
|
|
@@ -6995,11 +6954,11 @@ async function createWorktrunkWorktree(tx, toplevel, cwdRelative, runId, index,
|
|
|
6995
6954
|
if (output.action !== "created" || output.created_branch !== true || output.branch !== naming.requestedBranch || output.base_branch !== baseCommit) {
|
|
6996
6955
|
throw new Error("Worktrunk provisioning returned inconsistent creation metadata");
|
|
6997
6956
|
}
|
|
6998
|
-
if (typeof output.path !== "string" || !
|
|
6999
|
-
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);
|
|
7000
6959
|
let stat;
|
|
7001
6960
|
try {
|
|
7002
|
-
stat =
|
|
6961
|
+
stat = fs16.lstatSync(worktreePathCandidate);
|
|
7003
6962
|
} catch (error) {
|
|
7004
6963
|
throw new Error(`Worktrunk provisioning returned a missing worktree path: ${worktreePathCandidate}`, { cause: error instanceof Error ? error : void 0 });
|
|
7005
6964
|
}
|
|
@@ -7008,8 +6967,8 @@ async function createWorktrunkWorktree(tx, toplevel, cwdRelative, runId, index,
|
|
|
7008
6967
|
if (worktreePath === normalizeComparableCwd(toplevel)) throw new Error("Worktrunk provisioning returned the source checkout path");
|
|
7009
6968
|
const sourceCommonDirRaw = (await tx.gitChecked(toplevel, ["rev-parse", "--git-common-dir"])).trim();
|
|
7010
6969
|
const returnedCommonDirRaw = (await tx.gitChecked(worktreePath, ["rev-parse", "--git-common-dir"])).trim();
|
|
7011
|
-
const sourceCommonDir = normalizeComparableCwd(
|
|
7012
|
-
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));
|
|
7013
6972
|
if (returnedCommonDir !== sourceCommonDir) throw new Error("Worktrunk provisioning returned a worktree for a different repository");
|
|
7014
6973
|
const returnedBranch = (await tx.gitChecked(worktreePath, ["symbolic-ref", "--quiet", "--short", "HEAD"])).trim();
|
|
7015
6974
|
if (returnedBranch !== naming.requestedBranch) throw new Error("Worktrunk provisioning returned a worktree on a different branch");
|
|
@@ -7017,8 +6976,8 @@ async function createWorktrunkWorktree(tx, toplevel, cwdRelative, runId, index,
|
|
|
7017
6976
|
if (returnedHead !== baseCommit) throw new Error("Worktrunk provisioning returned a worktree at a different base commit");
|
|
7018
6977
|
const worktree = {
|
|
7019
6978
|
path: worktreePath,
|
|
7020
|
-
recordedBaseDir: normalizeComparableCwd(
|
|
7021
|
-
agentCwd: cwdRelative ?
|
|
6979
|
+
recordedBaseDir: normalizeComparableCwd(path15.dirname(worktreePath)),
|
|
6980
|
+
agentCwd: cwdRelative ? path15.join(worktreePath, cwdRelative) : worktreePath,
|
|
7022
6981
|
branch: naming.requestedBranch,
|
|
7023
6982
|
index,
|
|
7024
6983
|
nodeModulesLinked: false,
|
|
@@ -7035,28 +6994,28 @@ async function createWorktrunkWorktree(tx, toplevel, cwdRelative, runId, index,
|
|
|
7035
6994
|
}
|
|
7036
6995
|
function removeSyntheticPath(worktree, syntheticPath) {
|
|
7037
6996
|
assertWorktreeMutationAllowed();
|
|
7038
|
-
const resolved2 =
|
|
7039
|
-
const relative4 =
|
|
7040
|
-
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)) {
|
|
7041
7000
|
return;
|
|
7042
7001
|
}
|
|
7043
7002
|
let stat;
|
|
7044
7003
|
try {
|
|
7045
|
-
stat =
|
|
7004
|
+
stat = fs16.lstatSync(resolved2);
|
|
7046
7005
|
} catch (error) {
|
|
7047
7006
|
const code = error && typeof error === "object" && "code" in error ? error.code : void 0;
|
|
7048
7007
|
if (code === "ENOENT") return;
|
|
7049
7008
|
throw error;
|
|
7050
7009
|
}
|
|
7051
7010
|
if (stat.isSymbolicLink()) {
|
|
7052
|
-
|
|
7011
|
+
fs16.unlinkSync(resolved2);
|
|
7053
7012
|
return;
|
|
7054
7013
|
}
|
|
7055
7014
|
if (stat.isDirectory()) {
|
|
7056
|
-
|
|
7015
|
+
fs16.rmSync(resolved2, { recursive: true, force: true });
|
|
7057
7016
|
return;
|
|
7058
7017
|
}
|
|
7059
|
-
|
|
7018
|
+
fs16.rmSync(resolved2, { force: true });
|
|
7060
7019
|
}
|
|
7061
7020
|
function removeSyntheticPathsBeforeDiff(worktree) {
|
|
7062
7021
|
if (worktree.syntheticPaths.length === 0) return;
|
|
@@ -7100,7 +7059,7 @@ function captureWorktreeDiff(setup, worktree, agent, patchPath) {
|
|
|
7100
7059
|
const diffStat = runGitChecked(worktree.path, ["diff", "--cached", ...MACHINE_DIFF_OPTIONS, "--stat", setup.baseCommit]).trim();
|
|
7101
7060
|
const patch = runGitChecked(worktree.path, ["diff", "--cached", ...MACHINE_PATCH_OPTIONS, setup.baseCommit]);
|
|
7102
7061
|
const numstat = runGitChecked(worktree.path, ["diff", "--cached", ...MACHINE_DIFF_OPTIONS, "--numstat", setup.baseCommit]);
|
|
7103
|
-
|
|
7062
|
+
fs16.writeFileSync(patchPath, patch, "utf-8");
|
|
7104
7063
|
if (!patch.trim()) {
|
|
7105
7064
|
return emptyDiff(worktree.index, agent, worktree.branch, patchPath);
|
|
7106
7065
|
}
|
|
@@ -7120,18 +7079,18 @@ function captureWorktreeDiff(setup, worktree, agent, patchPath) {
|
|
|
7120
7079
|
}
|
|
7121
7080
|
function writeEmptyPatch(patchPath) {
|
|
7122
7081
|
try {
|
|
7123
|
-
|
|
7082
|
+
fs16.writeFileSync(patchPath, "", "utf-8");
|
|
7124
7083
|
} catch {
|
|
7125
7084
|
}
|
|
7126
7085
|
}
|
|
7127
7086
|
function handoffRecordsPatch(manifestPath, patchPath) {
|
|
7128
|
-
if (!manifestPath || !
|
|
7087
|
+
if (!manifestPath || !fs16.existsSync(manifestPath)) return false;
|
|
7129
7088
|
try {
|
|
7130
|
-
const manifest = JSON.parse(
|
|
7089
|
+
const manifest = JSON.parse(fs16.readFileSync(manifestPath, "utf-8"));
|
|
7131
7090
|
if (manifest.version !== 1 || !Array.isArray(manifest.groups)) return false;
|
|
7132
|
-
const resolvedPatchPath =
|
|
7091
|
+
const resolvedPatchPath = path15.resolve(patchPath);
|
|
7133
7092
|
return manifest.groups.some((group) => Array.isArray(group.children) && group.children.some(
|
|
7134
|
-
(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
|
|
7135
7094
|
));
|
|
7136
7095
|
} catch {
|
|
7137
7096
|
return false;
|
|
@@ -7184,9 +7143,9 @@ function cleanupSingleWorktree(setup, worktree, intent) {
|
|
|
7184
7143
|
const captured = (intent.capturedDiffs ?? setup.capturedDiffs)?.find((diff) => diff.index === worktree.index);
|
|
7185
7144
|
let patchValidationError;
|
|
7186
7145
|
let patchCaptured = false;
|
|
7187
|
-
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)) {
|
|
7188
7147
|
try {
|
|
7189
|
-
if (
|
|
7148
|
+
if (fs16.statSync(captured.patchPath).size > 0) {
|
|
7190
7149
|
patchValidationError = validateWorktreePatchRepresentsCurrentWorktree(worktree.path, setup.baseCommit, captured.patchPath);
|
|
7191
7150
|
patchCaptured = patchValidationError === void 0;
|
|
7192
7151
|
}
|
|
@@ -7316,7 +7275,7 @@ async function compensateSetup(tx) {
|
|
|
7316
7275
|
throw new Error(tx.progress.unknown);
|
|
7317
7276
|
}
|
|
7318
7277
|
await git(["worktree", "remove", "--force", attempt.path]);
|
|
7319
|
-
} else if (
|
|
7278
|
+
} else if (fs16.existsSync(attempt.path)) {
|
|
7320
7279
|
tx.unknown("Unregistered partial allocation retained");
|
|
7321
7280
|
throw new Error(tx.progress.unknown);
|
|
7322
7281
|
}
|
|
@@ -7436,7 +7395,7 @@ async function createWorktrees(cwd, runId, count, options = {}) {
|
|
|
7436
7395
|
function diffWorktrees(setup, agents, diffsDir) {
|
|
7437
7396
|
assertWorktreeMutationAllowed();
|
|
7438
7397
|
try {
|
|
7439
|
-
|
|
7398
|
+
fs16.mkdirSync(diffsDir, { recursive: true });
|
|
7440
7399
|
} catch {
|
|
7441
7400
|
return [];
|
|
7442
7401
|
}
|
|
@@ -7444,7 +7403,7 @@ function diffWorktrees(setup, agents, diffsDir) {
|
|
|
7444
7403
|
for (let index = 0; index < setup.worktrees.length; index++) {
|
|
7445
7404
|
const worktree = setup.worktrees[index];
|
|
7446
7405
|
const agent = agents[index] ?? `task-${index + 1}`;
|
|
7447
|
-
const patchPath =
|
|
7406
|
+
const patchPath = path15.join(diffsDir, `task-${index}-${safePatchAgentName(agent)}.patch`);
|
|
7448
7407
|
try {
|
|
7449
7408
|
diffs.push(captureWorktreeDiff(setup, worktree, agent, patchPath));
|
|
7450
7409
|
} catch (error) {
|
|
@@ -7491,7 +7450,7 @@ function formatWorktreeDiffSummary(diffs) {
|
|
|
7491
7450
|
}
|
|
7492
7451
|
lines.push("");
|
|
7493
7452
|
}
|
|
7494
|
-
const patchesDir =
|
|
7453
|
+
const patchesDir = path15.dirname(changed[0].patchPath);
|
|
7495
7454
|
lines.push(`Full patches: ${patchesDir}`);
|
|
7496
7455
|
return lines.join("\n").trimEnd();
|
|
7497
7456
|
}
|