@amaster.ai/employee-runtime-connector 0.1.1-beta.80 → 0.1.1-beta.82
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/dist/amaster-runtime-daemon.mjs +601 -300
- package/dist/amaster-runtime.mjs +1 -1
- package/package.json +1 -1
|
@@ -4,9 +4,9 @@
|
|
|
4
4
|
// src/amaster-runtime-daemon.mjs
|
|
5
5
|
import { createHash as createHash13 } from "node:crypto";
|
|
6
6
|
import { createRequire } from "node:module";
|
|
7
|
-
import { chmodSync as
|
|
7
|
+
import { chmodSync as chmodSync6, copyFileSync as copyFileSync2, existsSync as existsSync12, lstatSync as lstatSync6, mkdirSync as mkdirSync8, mkdtempSync, readFileSync as readFileSync12, readdirSync as readdirSync9, realpathSync as realpathSync5, renameSync as renameSync7, rmSync as rmSync7, statSync as statSync9, symlinkSync as symlinkSync2, unlinkSync as unlinkSync2, writeFileSync as writeFileSync9 } from "node:fs";
|
|
8
8
|
import { arch as arch3, homedir as homedir3, hostname as hostname2, platform as platform3, tmpdir } from "node:os";
|
|
9
|
-
import { basename as basename6, delimiter as delimiter3, dirname as
|
|
9
|
+
import { basename as basename6, delimiter as delimiter3, dirname as dirname9, extname as extname2, isAbsolute as isAbsolute6, join as join14, relative as relative7, resolve as resolve10 } from "node:path";
|
|
10
10
|
import { spawn, spawnSync as spawnSync5 } from "node:child_process";
|
|
11
11
|
|
|
12
12
|
// src/amaster-runtime-daemon/common.mjs
|
|
@@ -1936,24 +1936,24 @@ function reconcileManagedCodexMcpProfiles(rootPath, options = {}) {
|
|
|
1936
1936
|
// src/amaster-runtime-daemon/pi-managed-mcp-profile.mjs
|
|
1937
1937
|
import { createHash as createHash3 } from "node:crypto";
|
|
1938
1938
|
import {
|
|
1939
|
-
chmodSync as
|
|
1939
|
+
chmodSync as chmodSync4,
|
|
1940
1940
|
chownSync as chownSync2,
|
|
1941
1941
|
copyFileSync,
|
|
1942
1942
|
existsSync as existsSync3,
|
|
1943
1943
|
lstatSync as lstatSync3,
|
|
1944
1944
|
mkdirSync as mkdirSync3,
|
|
1945
|
-
readFileSync as
|
|
1945
|
+
readFileSync as readFileSync4,
|
|
1946
1946
|
realpathSync as realpathSync2,
|
|
1947
1947
|
readdirSync as readdirSync3,
|
|
1948
|
-
renameSync as
|
|
1949
|
-
rmSync as
|
|
1948
|
+
renameSync as renameSync3,
|
|
1949
|
+
rmSync as rmSync3,
|
|
1950
1950
|
rmdirSync,
|
|
1951
1951
|
statSync as statSync2,
|
|
1952
1952
|
symlinkSync,
|
|
1953
|
-
writeFileSync as
|
|
1953
|
+
writeFileSync as writeFileSync4
|
|
1954
1954
|
} from "node:fs";
|
|
1955
1955
|
import { arch as arch2, platform as platform2 } from "node:os";
|
|
1956
|
-
import { basename as basename2, delimiter, dirname as
|
|
1956
|
+
import { basename as basename2, delimiter, dirname as dirname4, isAbsolute as isAbsolute2, join as join5, relative as relative2, resolve as resolve3, sep as sep2 } from "node:path";
|
|
1957
1957
|
import { spawnSync as spawnSync2 } from "node:child_process";
|
|
1958
1958
|
|
|
1959
1959
|
// src/amaster-runtime-daemon/pi-provider-config.mjs
|
|
@@ -2520,6 +2520,190 @@ function piMcpAdapterServerConfigIdentity(definition, adapterVersion) {
|
|
|
2520
2520
|
|
|
2521
2521
|
// src/amaster-runtime-daemon/pi-effective-tools-attestor.mjs
|
|
2522
2522
|
import { createHash as createHash2 } from "node:crypto";
|
|
2523
|
+
|
|
2524
|
+
// src/amaster-runtime-daemon/source-acquisition-execution-receipt.mjs
|
|
2525
|
+
import { randomBytes } from "node:crypto";
|
|
2526
|
+
import { chmodSync as chmodSync3, readFileSync as readFileSync3, renameSync as renameSync2, rmSync as rmSync2, writeFileSync as writeFileSync3 } from "node:fs";
|
|
2527
|
+
import { dirname as dirname3, join as join4 } from "node:path";
|
|
2528
|
+
var SOURCE_ACQUISITION_EXECUTION_RECEIPT_SCHEMA_VERSION = "mirrorx.source-acquisition-execution-receipt.v1";
|
|
2529
|
+
var ATTESTOR_STATUSES = /* @__PURE__ */ new Set(["pending", "attested", "rejected", "unknown"]);
|
|
2530
|
+
var MODEL_CONTRACT_STATUSES = /* @__PURE__ */ new Set(["pending", "validated", "rejected", "unknown"]);
|
|
2531
|
+
var ATTESTOR_REASON_CODES = /* @__PURE__ */ new Set([
|
|
2532
|
+
"effective_tool_manifest_invalid",
|
|
2533
|
+
"effective_tool_surface_mismatch",
|
|
2534
|
+
"effective_tool_set_hash_mismatch",
|
|
2535
|
+
"managed_mcp_cache_mismatch",
|
|
2536
|
+
"managed_mcp_config_mismatch",
|
|
2537
|
+
"attestor_unknown"
|
|
2538
|
+
]);
|
|
2539
|
+
var MODEL_CONTRACT_REASON_CODES = /* @__PURE__ */ new Set([
|
|
2540
|
+
"model_missing",
|
|
2541
|
+
"model_output_contract_failed",
|
|
2542
|
+
"model_contract_unknown"
|
|
2543
|
+
]);
|
|
2544
|
+
var SPAWN_ERRNO = /* @__PURE__ */ new Set(["EACCES", "EMFILE", "ENFILE", "ENOENT", "ENOMEM", "EPERM"]);
|
|
2545
|
+
function sourceAcquisitionSpawnErrno(value) {
|
|
2546
|
+
const code = typeof value === "string" ? value.trim().toUpperCase() : "";
|
|
2547
|
+
return SPAWN_ERRNO.has(code) ? code : null;
|
|
2548
|
+
}
|
|
2549
|
+
function validIdentity(identity2) {
|
|
2550
|
+
return identity2 && typeof identity2.commandId === "string" && identity2.commandId.length > 0 && typeof identity2.attemptId === "string" && identity2.attemptId.length > 0 && Number.isSafeInteger(identity2.epoch) && identity2.epoch >= 1;
|
|
2551
|
+
}
|
|
2552
|
+
function sameIdentity(receipt, identity2) {
|
|
2553
|
+
return validIdentity(identity2) && receipt.commandId === identity2.commandId && receipt.attemptId === identity2.attemptId && receipt.epoch === identity2.epoch;
|
|
2554
|
+
}
|
|
2555
|
+
function isNullableBoolean(value) {
|
|
2556
|
+
return value === true || value === false || value === null;
|
|
2557
|
+
}
|
|
2558
|
+
function normalizeReceipt(value) {
|
|
2559
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return null;
|
|
2560
|
+
const receipt = {
|
|
2561
|
+
schemaVersion: value.schemaVersion,
|
|
2562
|
+
commandId: value.commandId,
|
|
2563
|
+
attemptId: value.attemptId,
|
|
2564
|
+
epoch: value.epoch,
|
|
2565
|
+
attestorStatus: value.attestorStatus,
|
|
2566
|
+
attestorReasonCode: value.attestorReasonCode ?? null,
|
|
2567
|
+
modelContractStatus: value.modelContractStatus,
|
|
2568
|
+
modelContractReasonCode: value.modelContractReasonCode ?? null,
|
|
2569
|
+
modelInvocationStarted: value.modelInvocationStarted,
|
|
2570
|
+
sourceReadStarted: value.sourceReadStarted,
|
|
2571
|
+
spawnErrno: value.spawnErrno ?? null
|
|
2572
|
+
};
|
|
2573
|
+
if (receipt.schemaVersion !== SOURCE_ACQUISITION_EXECUTION_RECEIPT_SCHEMA_VERSION || !validIdentity(receipt) || !ATTESTOR_STATUSES.has(receipt.attestorStatus) || !MODEL_CONTRACT_STATUSES.has(receipt.modelContractStatus) || !isNullableBoolean(receipt.modelInvocationStarted) || !isNullableBoolean(receipt.sourceReadStarted) || receipt.attestorReasonCode !== null && !ATTESTOR_REASON_CODES.has(receipt.attestorReasonCode) || receipt.modelContractReasonCode !== null && !MODEL_CONTRACT_REASON_CODES.has(receipt.modelContractReasonCode) || receipt.spawnErrno !== null && !SPAWN_ERRNO.has(receipt.spawnErrno)) return null;
|
|
2574
|
+
return receipt;
|
|
2575
|
+
}
|
|
2576
|
+
function writeReceiptAtomic(path, receipt) {
|
|
2577
|
+
const temporaryPath = join4(dirname3(path), `.source-receipt-${randomBytes(12).toString("hex")}.tmp`);
|
|
2578
|
+
try {
|
|
2579
|
+
writeFileSync3(temporaryPath, `${JSON.stringify(receipt)}
|
|
2580
|
+
`, {
|
|
2581
|
+
encoding: "utf8",
|
|
2582
|
+
flag: "wx",
|
|
2583
|
+
mode: 384
|
|
2584
|
+
});
|
|
2585
|
+
chmodSync3(temporaryPath, 384);
|
|
2586
|
+
renameSync2(temporaryPath, path);
|
|
2587
|
+
chmodSync3(path, 384);
|
|
2588
|
+
} finally {
|
|
2589
|
+
rmSync2(temporaryPath, { force: true });
|
|
2590
|
+
}
|
|
2591
|
+
}
|
|
2592
|
+
function createSourceAcquisitionExecutionReceipt(path, identity2) {
|
|
2593
|
+
if (!validIdentity(identity2)) throw new Error("source_acquisition_execution_receipt_identity_invalid");
|
|
2594
|
+
const receipt = {
|
|
2595
|
+
schemaVersion: SOURCE_ACQUISITION_EXECUTION_RECEIPT_SCHEMA_VERSION,
|
|
2596
|
+
commandId: identity2.commandId,
|
|
2597
|
+
attemptId: identity2.attemptId,
|
|
2598
|
+
epoch: identity2.epoch,
|
|
2599
|
+
attestorStatus: "pending",
|
|
2600
|
+
attestorReasonCode: null,
|
|
2601
|
+
modelContractStatus: "pending",
|
|
2602
|
+
modelContractReasonCode: null,
|
|
2603
|
+
modelInvocationStarted: false,
|
|
2604
|
+
sourceReadStarted: false,
|
|
2605
|
+
spawnErrno: null
|
|
2606
|
+
};
|
|
2607
|
+
writeReceiptAtomic(path, receipt);
|
|
2608
|
+
return receipt;
|
|
2609
|
+
}
|
|
2610
|
+
function readSourceAcquisitionExecutionReceipt(path, identity2) {
|
|
2611
|
+
try {
|
|
2612
|
+
const receipt = normalizeReceipt(JSON.parse(readFileSync3(path, "utf8")));
|
|
2613
|
+
return receipt && sameIdentity(receipt, identity2) ? receipt : null;
|
|
2614
|
+
} catch {
|
|
2615
|
+
return null;
|
|
2616
|
+
}
|
|
2617
|
+
}
|
|
2618
|
+
function monotonicBoolean(previous, next) {
|
|
2619
|
+
if (next === void 0 || next === previous) return previous;
|
|
2620
|
+
if (previous === false && next === true) return true;
|
|
2621
|
+
if (previous === null && next === null) return null;
|
|
2622
|
+
throw new Error("source_acquisition_execution_receipt_non_monotonic");
|
|
2623
|
+
}
|
|
2624
|
+
function monotonicStatus(previous, next, pending) {
|
|
2625
|
+
if (next === void 0 || next === previous) return previous;
|
|
2626
|
+
if (previous === pending && next !== pending) return next;
|
|
2627
|
+
throw new Error("source_acquisition_execution_receipt_non_monotonic");
|
|
2628
|
+
}
|
|
2629
|
+
function updateSourceAcquisitionExecutionReceipt(path, identity2, patch) {
|
|
2630
|
+
const previous = readSourceAcquisitionExecutionReceipt(path, identity2);
|
|
2631
|
+
if (!previous) throw new Error("source_acquisition_execution_receipt_invalid");
|
|
2632
|
+
const next = {
|
|
2633
|
+
...previous,
|
|
2634
|
+
attestorStatus: monotonicStatus(previous.attestorStatus, patch.attestorStatus, "pending"),
|
|
2635
|
+
...patch.attestorReasonCode === void 0 ? {} : { attestorReasonCode: patch.attestorReasonCode },
|
|
2636
|
+
modelContractStatus: monotonicStatus(
|
|
2637
|
+
previous.modelContractStatus,
|
|
2638
|
+
patch.modelContractStatus,
|
|
2639
|
+
"pending"
|
|
2640
|
+
),
|
|
2641
|
+
...patch.modelContractReasonCode === void 0 ? {} : { modelContractReasonCode: patch.modelContractReasonCode },
|
|
2642
|
+
...patch.spawnErrno === void 0 ? {} : { spawnErrno: patch.spawnErrno },
|
|
2643
|
+
modelInvocationStarted: monotonicBoolean(previous.modelInvocationStarted, patch.modelInvocationStarted),
|
|
2644
|
+
sourceReadStarted: monotonicBoolean(previous.sourceReadStarted, patch.sourceReadStarted)
|
|
2645
|
+
};
|
|
2646
|
+
const normalized = normalizeReceipt(next);
|
|
2647
|
+
if (!normalized) throw new Error("source_acquisition_execution_receipt_patch_invalid");
|
|
2648
|
+
writeReceiptAtomic(path, normalized);
|
|
2649
|
+
return normalized;
|
|
2650
|
+
}
|
|
2651
|
+
function failureSummary(receipt, input, overrides) {
|
|
2652
|
+
const sourceReadStarted = input.readerSideEffectObserved === true && receipt?.sourceReadStarted !== true ? null : receipt?.sourceReadStarted ?? null;
|
|
2653
|
+
return {
|
|
2654
|
+
failureCode: overrides.failureCode ?? "source_acquisition_executor_config_failed",
|
|
2655
|
+
reasonCode: overrides.reasonCode,
|
|
2656
|
+
phase: overrides.phase,
|
|
2657
|
+
retryClass: overrides.retryClass,
|
|
2658
|
+
autoRetryEligible: overrides.retryClass === "transient_infra" && receipt?.modelInvocationStarted === false && sourceReadStarted === false,
|
|
2659
|
+
modelInvocationStarted: receipt?.modelInvocationStarted ?? null,
|
|
2660
|
+
sourceReadStarted
|
|
2661
|
+
};
|
|
2662
|
+
}
|
|
2663
|
+
function classifySourceAcquisitionExecutionFailure(input) {
|
|
2664
|
+
const receipt = normalizeReceipt(input.receipt);
|
|
2665
|
+
if (!receipt || !sameIdentity(receipt, input.identity)) {
|
|
2666
|
+
return failureSummary(null, input, { reasonCode: "execution_receipt_missing", phase: "unknown", retryClass: "unknown" });
|
|
2667
|
+
}
|
|
2668
|
+
if (input.readerSideEffectObserved === true && receipt.sourceReadStarted !== true) {
|
|
2669
|
+
return failureSummary(receipt, input, { reasonCode: "source_read_receipt_inconsistent", phase: "unknown", retryClass: "unknown" });
|
|
2670
|
+
}
|
|
2671
|
+
if (receipt.spawnErrno) {
|
|
2672
|
+
const mapping = {
|
|
2673
|
+
ENOENT: ["source_acquisition_executor_binary_missing", "executor_binary_missing", "operator_repair"],
|
|
2674
|
+
EACCES: ["source_acquisition_executor_permission_denied", "executor_permission_denied", "operator_repair"],
|
|
2675
|
+
EPERM: ["source_acquisition_executor_permission_denied", "executor_permission_denied", "operator_repair"],
|
|
2676
|
+
ENOMEM: ["source_acquisition_executor_resource_exhausted", "executor_resource_exhausted", "transient_infra"],
|
|
2677
|
+
EMFILE: ["source_acquisition_executor_resource_exhausted", "executor_resource_exhausted", "transient_infra"],
|
|
2678
|
+
ENFILE: ["source_acquisition_executor_resource_exhausted", "executor_resource_exhausted", "transient_infra"]
|
|
2679
|
+
};
|
|
2680
|
+
const [failureCode2, reasonCode, retryClass] = mapping[receipt.spawnErrno];
|
|
2681
|
+
return failureSummary(receipt, input, { failureCode: failureCode2, reasonCode, phase: "spawn", retryClass });
|
|
2682
|
+
}
|
|
2683
|
+
if (receipt.attestorStatus === "rejected") {
|
|
2684
|
+
return failureSummary(receipt, input, {
|
|
2685
|
+
failureCode: "source_acquisition_tool_attestation_rejected",
|
|
2686
|
+
reasonCode: receipt.attestorReasonCode ?? "attestor_unknown",
|
|
2687
|
+
phase: "attestation",
|
|
2688
|
+
retryClass: "operator_repair"
|
|
2689
|
+
});
|
|
2690
|
+
}
|
|
2691
|
+
if (receipt.modelContractStatus === "rejected") {
|
|
2692
|
+
return failureSummary(receipt, input, {
|
|
2693
|
+
failureCode: receipt.modelContractReasonCode === "model_missing" ? "source_acquisition_model_missing" : "source_acquisition_model_contract_failed",
|
|
2694
|
+
reasonCode: receipt.modelContractReasonCode ?? "model_contract_unknown",
|
|
2695
|
+
phase: "model_contract",
|
|
2696
|
+
retryClass: "operator_repair"
|
|
2697
|
+
});
|
|
2698
|
+
}
|
|
2699
|
+
return failureSummary(receipt, input, {
|
|
2700
|
+
reasonCode: Number(input.exitCode) === 78 ? "executor_exit_78_unknown" : "executor_failure_unknown",
|
|
2701
|
+
phase: "unknown",
|
|
2702
|
+
retryClass: "unknown"
|
|
2703
|
+
});
|
|
2704
|
+
}
|
|
2705
|
+
|
|
2706
|
+
// src/amaster-runtime-daemon/pi-effective-tools-attestor.mjs
|
|
2523
2707
|
var MANAGED_PI_EFFECTIVE_TOOLS_ATTESTOR_FILENAME = "amaster-effective-tools-attestor.js";
|
|
2524
2708
|
var MANAGED_PI_EFFECTIVE_TOOLS_SCHEMA_VERSION = "amaster.pi-effective-tools.v1";
|
|
2525
2709
|
function normalizedSchema(value, adapterNormalized) {
|
|
@@ -2568,12 +2752,15 @@ function stablePiManagedMcpCacheSemanticHash(value) {
|
|
|
2568
2752
|
return createHash2("sha256").update(stablePiJson(parsed)).digest("hex");
|
|
2569
2753
|
}
|
|
2570
2754
|
function managedPiEffectiveToolsAttestorExtensionSource() {
|
|
2571
|
-
return String.raw`import { createHash } from "node:crypto";
|
|
2572
|
-
import { existsSync, readFileSync, writeFileSync } from "node:fs";
|
|
2755
|
+
return String.raw`import { createHash, randomBytes } from "node:crypto";
|
|
2756
|
+
import { existsSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
|
|
2757
|
+
import { dirname, join } from "node:path";
|
|
2573
2758
|
import { fileURLToPath } from "node:url";
|
|
2574
2759
|
import { Value } from "typebox/value";
|
|
2575
2760
|
|
|
2576
2761
|
const SCHEMA_VERSION = ${JSON.stringify(MANAGED_PI_EFFECTIVE_TOOLS_SCHEMA_VERSION)};
|
|
2762
|
+
const SOURCE_EXECUTION_RECEIPT_SCHEMA_VERSION = ${JSON.stringify(SOURCE_ACQUISITION_EXECUTION_RECEIPT_SCHEMA_VERSION)};
|
|
2763
|
+
const sourceExecutionReceiptPath = process.env.AMASTER_SOURCE_ACQUISITION_EXECUTION_RECEIPT?.trim() || null;
|
|
2577
2764
|
|
|
2578
2765
|
function record(value) {
|
|
2579
2766
|
return value && typeof value === "object" && !Array.isArray(value) ? value : {};
|
|
@@ -2624,6 +2811,47 @@ function safeWriteReceipt(receiptPath, receipt) {
|
|
|
2624
2811
|
writeFileSync(receiptPath, JSON.stringify(receipt) + "\n", { encoding: "utf8", mode: 0o600 });
|
|
2625
2812
|
}
|
|
2626
2813
|
|
|
2814
|
+
function sourceReceiptReason(error) {
|
|
2815
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
2816
|
+
if (message.includes("manifest identity")) return "effective_tool_manifest_invalid";
|
|
2817
|
+
if (message.includes("tool surface")) return "effective_tool_surface_mismatch";
|
|
2818
|
+
if (message.includes("tool set hash")) return "effective_tool_set_hash_mismatch";
|
|
2819
|
+
if (message.includes("cache")) return "managed_mcp_cache_mismatch";
|
|
2820
|
+
if (message.includes("config")) return "managed_mcp_config_mismatch";
|
|
2821
|
+
return "attestor_unknown";
|
|
2822
|
+
}
|
|
2823
|
+
|
|
2824
|
+
function updateSourceExecutionReceipt(patch) {
|
|
2825
|
+
// Runtime-generated counterpart to updateSourceAcquisitionExecutionReceipt.
|
|
2826
|
+
// Keep its monotonic transition and private atomic-write behavior covered by
|
|
2827
|
+
// pi-effective-tools-attestor.test.mjs when the canonical receipt changes.
|
|
2828
|
+
const path = sourceExecutionReceiptPath;
|
|
2829
|
+
if (!path) return true;
|
|
2830
|
+
let temporaryPath = null;
|
|
2831
|
+
try {
|
|
2832
|
+
const receipt = JSON.parse(readFileSync(path, "utf8"));
|
|
2833
|
+
if (receipt.schemaVersion !== SOURCE_EXECUTION_RECEIPT_SCHEMA_VERSION) return false;
|
|
2834
|
+
for (const [key, pending] of [["attestorStatus", "pending"], ["modelContractStatus", "pending"]]) {
|
|
2835
|
+
if (!(key in patch) || patch[key] === receipt[key]) continue;
|
|
2836
|
+
if (receipt[key] !== pending || patch[key] === pending) return false;
|
|
2837
|
+
}
|
|
2838
|
+
for (const key of ["modelInvocationStarted", "sourceReadStarted"]) {
|
|
2839
|
+
if (!(key in patch)) continue;
|
|
2840
|
+
if (receipt[key] === true && patch[key] !== true) return false;
|
|
2841
|
+
if (receipt[key] === null || typeof patch[key] !== "boolean") return false;
|
|
2842
|
+
}
|
|
2843
|
+
const next = { ...receipt, ...patch };
|
|
2844
|
+
temporaryPath = join(dirname(path), ".source-receipt-" + randomBytes(12).toString("hex") + ".tmp");
|
|
2845
|
+
writeFileSync(temporaryPath, JSON.stringify(next) + "\n", { encoding: "utf8", flag: "wx", mode: 0o600 });
|
|
2846
|
+
renameSync(temporaryPath, path);
|
|
2847
|
+
return true;
|
|
2848
|
+
} catch {
|
|
2849
|
+
return false;
|
|
2850
|
+
} finally {
|
|
2851
|
+
if (temporaryPath) rmSync(temporaryPath, { force: true });
|
|
2852
|
+
}
|
|
2853
|
+
}
|
|
2854
|
+
|
|
2627
2855
|
function safeWritePhase(phasePath, phase) {
|
|
2628
2856
|
if (!phasePath) return;
|
|
2629
2857
|
let history = [];
|
|
@@ -2772,6 +3000,9 @@ export default function amasterEffectiveToolsAttestor(pi) {
|
|
|
2772
3000
|
attestedAt: new Date().toISOString(),
|
|
2773
3001
|
};
|
|
2774
3002
|
safeWriteReceipt(receiptPath, receipt);
|
|
3003
|
+
if (!updateSourceExecutionReceipt({ attestorStatus: "attested", attestorReasonCode: null })) {
|
|
3004
|
+
process.exit(78);
|
|
3005
|
+
}
|
|
2775
3006
|
safeWritePhase(phasePath, "attested");
|
|
2776
3007
|
if (mode === "probe") process.exit(0);
|
|
2777
3008
|
} catch (error) {
|
|
@@ -2784,11 +3015,33 @@ export default function amasterEffectiveToolsAttestor(pi) {
|
|
|
2784
3015
|
attestedAt: new Date().toISOString(),
|
|
2785
3016
|
};
|
|
2786
3017
|
safeWriteReceipt(receiptPath, receipt);
|
|
3018
|
+
updateSourceExecutionReceipt({
|
|
3019
|
+
attestorStatus: "rejected",
|
|
3020
|
+
attestorReasonCode: sourceReceiptReason(error),
|
|
3021
|
+
});
|
|
2787
3022
|
safeWritePhase(phasePath, "rejected");
|
|
2788
3023
|
process.exit(78);
|
|
2789
3024
|
}
|
|
2790
3025
|
});
|
|
2791
3026
|
|
|
3027
|
+
pi.on("before_agent_start", async (_event, context) => {
|
|
3028
|
+
// Model establishment is a Source Acquisition execution receipt contract,
|
|
3029
|
+
// not an invariant of every diagnosis/full direct-typed governed run.
|
|
3030
|
+
if (mode !== "enforce" || !sourceExecutionReceiptPath) return;
|
|
3031
|
+
if (!context.model) {
|
|
3032
|
+
updateSourceExecutionReceipt({
|
|
3033
|
+
modelContractStatus: "rejected",
|
|
3034
|
+
modelContractReasonCode: "model_missing",
|
|
3035
|
+
});
|
|
3036
|
+
process.exit(78);
|
|
3037
|
+
}
|
|
3038
|
+
if (!updateSourceExecutionReceipt({
|
|
3039
|
+
modelContractStatus: "validated",
|
|
3040
|
+
modelContractReasonCode: null,
|
|
3041
|
+
modelInvocationStarted: true,
|
|
3042
|
+
})) process.exit(78);
|
|
3043
|
+
});
|
|
3044
|
+
|
|
2792
3045
|
pi.on("tool_call", (event) => {
|
|
2793
3046
|
const manifest = JSON.parse(readFileSync(manifestPath, "utf8"));
|
|
2794
3047
|
const entry = Array.isArray(manifest.entries)
|
|
@@ -2796,8 +3049,12 @@ export default function amasterEffectiveToolsAttestor(pi) {
|
|
|
2796
3049
|
: null;
|
|
2797
3050
|
if (!entry) return;
|
|
2798
3051
|
const reason = inputErrorReason(entry.schema, event.input);
|
|
2799
|
-
if (
|
|
2800
|
-
|
|
3052
|
+
if (reason) return { block: true, reason: "Governed tool input rejected: " + reason };
|
|
3053
|
+
if (["source_open", "source_snapshot", "source_screenshot", "source_analyze_screenshot", "source_wait"].includes(event.toolName)) {
|
|
3054
|
+
if (!updateSourceExecutionReceipt({ sourceReadStarted: true })) {
|
|
3055
|
+
return { block: true, reason: "Source execution receipt unavailable" };
|
|
3056
|
+
}
|
|
3057
|
+
}
|
|
2801
3058
|
});
|
|
2802
3059
|
}
|
|
2803
3060
|
`;
|
|
@@ -3133,7 +3390,7 @@ function createManagedPiMcpProfileApi(options = {}) {
|
|
|
3133
3390
|
function readJsonObjectFile(filePath) {
|
|
3134
3391
|
if (!existsSync3(filePath)) return {};
|
|
3135
3392
|
try {
|
|
3136
|
-
const value = JSON.parse(
|
|
3393
|
+
const value = JSON.parse(readFileSync4(filePath, "utf8"));
|
|
3137
3394
|
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
3138
3395
|
throw new Error("JSON value is not an object");
|
|
3139
3396
|
}
|
|
@@ -3151,8 +3408,8 @@ function createManagedPiMcpProfileApi(options = {}) {
|
|
|
3151
3408
|
return rel === "" || !rel.startsWith("..") && !isAbsolute2(rel);
|
|
3152
3409
|
}
|
|
3153
3410
|
function writePrivateFile2(filePath, contents) {
|
|
3154
|
-
|
|
3155
|
-
|
|
3411
|
+
writeFileSync4(filePath, contents, { mode: 384, flag: "wx" });
|
|
3412
|
+
chmodSync4(filePath, 384);
|
|
3156
3413
|
const mode = statSync2(filePath).mode & 511;
|
|
3157
3414
|
if (mode !== 384) throw new Error(`pi_managed_mcp_permissions_failed: ${filePath} mode=${mode.toString(8)}`);
|
|
3158
3415
|
}
|
|
@@ -3163,7 +3420,7 @@ function createManagedPiMcpProfileApi(options = {}) {
|
|
|
3163
3420
|
throw new Error(`pi_managed_mcp_source_config_unsafe: ${source}`);
|
|
3164
3421
|
}
|
|
3165
3422
|
copyFileSync(source, target, 0);
|
|
3166
|
-
|
|
3423
|
+
chmodSync4(target, 384);
|
|
3167
3424
|
return true;
|
|
3168
3425
|
}
|
|
3169
3426
|
function findPiSessionRollout(sessionsRoot, sessionId) {
|
|
@@ -3177,7 +3434,7 @@ function createManagedPiMcpProfileApi(options = {}) {
|
|
|
3177
3434
|
throw new Error("pi_managed_mcp_session_rollout_unsafe: sessions path is not a private directory");
|
|
3178
3435
|
}
|
|
3179
3436
|
for (const entry of readdirSync3(current, { withFileTypes: true })) {
|
|
3180
|
-
const candidate =
|
|
3437
|
+
const candidate = join5(current, entry.name);
|
|
3181
3438
|
if (entry.isSymbolicLink()) throw new Error("pi_managed_mcp_session_rollout_unsafe: symlinks are forbidden");
|
|
3182
3439
|
if (entry.isDirectory()) pending.push(candidate);
|
|
3183
3440
|
else if (entry.isFile() && entry.name.endsWith(`_${sessionId}.jsonl`)) matches.push(candidate);
|
|
@@ -3197,18 +3454,18 @@ function createManagedPiMcpProfileApi(options = {}) {
|
|
|
3197
3454
|
nonEmpty2(session.actionRequestId, "nativeSession.actionRequestId");
|
|
3198
3455
|
nonEmpty2(session.invocationId, "nativeSession.invocationId");
|
|
3199
3456
|
const sourceWorkspacePath = nonEmpty2(session.cwd, "nativeSession.cwd");
|
|
3200
|
-
const issueRoot =
|
|
3457
|
+
const issueRoot = dirname4(runDir);
|
|
3201
3458
|
const managedSourceRunDirName = `${sourceRunId}-${createHash3("sha256").update(sourceRunId).digest("hex").slice(0, 8)}`;
|
|
3202
|
-
const sourceRunDirs = readdirSync3(issueRoot, { withFileTypes: true }).filter((entry) => entry.isDirectory() && !entry.isSymbolicLink() && (entry.name === sourceRunId || entry.name === managedSourceRunDirName)).map((entry) =>
|
|
3459
|
+
const sourceRunDirs = readdirSync3(issueRoot, { withFileTypes: true }).filter((entry) => entry.isDirectory() && !entry.isSymbolicLink() && (entry.name === sourceRunId || entry.name === managedSourceRunDirName)).map((entry) => join5(issueRoot, entry.name));
|
|
3203
3460
|
if (sourceRunDirs.length !== 1) {
|
|
3204
3461
|
throw new Error(`pi_managed_mcp_session_rollout_missing: expected one source run directory for ${sourceRunId}, received ${sourceRunDirs.length}`);
|
|
3205
3462
|
}
|
|
3206
|
-
const cacheRoot =
|
|
3207
|
-
const markerPath =
|
|
3463
|
+
const cacheRoot = join5(sourceRunDirs[0], relative2(runDir, executorHome), "session-rollout");
|
|
3464
|
+
const markerPath = join5(cacheRoot, SESSION_ROLLOUT_MARKER2);
|
|
3208
3465
|
if (!existsSync3(markerPath) || lstatSync3(markerPath).isSymbolicLink() || !lstatSync3(markerPath).isFile()) {
|
|
3209
3466
|
throw new Error("pi_managed_mcp_session_rollout_missing: source rollout marker is unavailable");
|
|
3210
3467
|
}
|
|
3211
|
-
const marker = JSON.parse(
|
|
3468
|
+
const marker = JSON.parse(readFileSync4(markerPath, "utf8"));
|
|
3212
3469
|
if (marker?.version !== 1 || marker?.companyId !== authority.companyId || marker?.agentId !== authority.agentId || marker?.issueId !== authority.issueId || marker?.sourceRunId !== sourceRunId || marker?.sourceCommandId !== sourceCommandId || marker?.sessionId !== sessionId || marker?.sourceWorkspacePath !== sourceWorkspacePath) {
|
|
3213
3470
|
throw new Error("pi_managed_mcp_session_rollout_authority_mismatch: source rollout does not match the approved continuation");
|
|
3214
3471
|
}
|
|
@@ -3220,8 +3477,8 @@ function createManagedPiMcpProfileApi(options = {}) {
|
|
|
3220
3477
|
if (!within2(targetRollout, sessionsRoot)) {
|
|
3221
3478
|
throw new Error("pi_managed_mcp_session_rollout_unsafe: target rollout path is invalid");
|
|
3222
3479
|
}
|
|
3223
|
-
mkdirSync3(
|
|
3224
|
-
writePrivateFile2(targetRollout,
|
|
3480
|
+
mkdirSync3(dirname4(targetRollout), { recursive: true, mode: 448 });
|
|
3481
|
+
writePrivateFile2(targetRollout, readFileSync4(sourceRollout));
|
|
3225
3482
|
return { sessionId, sourceRunId, sourceCommandId, rolloutPath: targetRollout, cacheRoot };
|
|
3226
3483
|
}
|
|
3227
3484
|
function parseVersion(stdout, label, minimum) {
|
|
@@ -3262,12 +3519,12 @@ function createManagedPiMcpProfileApi(options = {}) {
|
|
|
3262
3519
|
hash.update(`d:${relativePath}
|
|
3263
3520
|
`);
|
|
3264
3521
|
const children = readdirSync3(current).filter((child) => current !== root || !ignoredRootEntries.has(child)).sort().reverse();
|
|
3265
|
-
for (const child of children) pending.push(
|
|
3522
|
+
for (const child of children) pending.push(join5(current, child));
|
|
3266
3523
|
continue;
|
|
3267
3524
|
}
|
|
3268
3525
|
if (!currentStat.isFile()) throw new Error(`pi_managed_mcp_bootstrap_cache_unsafe: ${current}`);
|
|
3269
3526
|
hash.update(`f:${relativePath}:${currentStat.mode & 73 ? "x" : "-"}:`);
|
|
3270
|
-
hash.update(
|
|
3527
|
+
hash.update(readFileSync4(current));
|
|
3271
3528
|
hash.update("\n");
|
|
3272
3529
|
}
|
|
3273
3530
|
return hash.digest("hex");
|
|
@@ -3279,10 +3536,10 @@ function createManagedPiMcpProfileApi(options = {}) {
|
|
|
3279
3536
|
throw new Error(`pi_managed_mcp_bootstrap_cache_unsafe: ${source}`);
|
|
3280
3537
|
}
|
|
3281
3538
|
mkdirSync3(targetPath, { recursive: true, mode: 448 });
|
|
3282
|
-
|
|
3539
|
+
chmodSync4(targetPath, 448);
|
|
3283
3540
|
for (const entry of readdirSync3(source, { withFileTypes: true })) {
|
|
3284
|
-
const from =
|
|
3285
|
-
const to =
|
|
3541
|
+
const from = join5(source, entry.name);
|
|
3542
|
+
const to = join5(targetPath, entry.name);
|
|
3286
3543
|
if (entry.isSymbolicLink()) throw new Error(`pi_managed_mcp_bootstrap_cache_unsafe: ${from}`);
|
|
3287
3544
|
if (entry.isDirectory()) {
|
|
3288
3545
|
copyTrustedTree(from, to);
|
|
@@ -3290,7 +3547,7 @@ function createManagedPiMcpProfileApi(options = {}) {
|
|
|
3290
3547
|
}
|
|
3291
3548
|
if (!entry.isFile()) throw new Error(`pi_managed_mcp_bootstrap_cache_unsafe: ${from}`);
|
|
3292
3549
|
copyFileSync(from, to, 0);
|
|
3293
|
-
|
|
3550
|
+
chmodSync4(to, 384 | lstatSync3(from).mode & 73);
|
|
3294
3551
|
}
|
|
3295
3552
|
}
|
|
3296
3553
|
function makeTrustedTreeReadOnly(rootPath) {
|
|
@@ -3303,13 +3560,13 @@ function createManagedPiMcpProfileApi(options = {}) {
|
|
|
3303
3560
|
if (currentStat.isSymbolicLink()) throw new Error(`pi_managed_mcp_bootstrap_cache_unsafe: ${current}`);
|
|
3304
3561
|
if (currentStat.isDirectory()) {
|
|
3305
3562
|
directories.push(current);
|
|
3306
|
-
for (const entry of readdirSync3(current)) pending.push(
|
|
3563
|
+
for (const entry of readdirSync3(current)) pending.push(join5(current, entry));
|
|
3307
3564
|
continue;
|
|
3308
3565
|
}
|
|
3309
3566
|
if (!currentStat.isFile()) throw new Error(`pi_managed_mcp_bootstrap_cache_unsafe: ${current}`);
|
|
3310
|
-
|
|
3567
|
+
chmodSync4(current, 256 | currentStat.mode & 73);
|
|
3311
3568
|
}
|
|
3312
|
-
for (const directory of directories.reverse())
|
|
3569
|
+
for (const directory of directories.reverse()) chmodSync4(directory, 320);
|
|
3313
3570
|
}
|
|
3314
3571
|
function makeTrustedTreeWritable(rootPath) {
|
|
3315
3572
|
const pending = [resolve3(rootPath)];
|
|
@@ -3318,33 +3575,33 @@ function createManagedPiMcpProfileApi(options = {}) {
|
|
|
3318
3575
|
const currentStat = lstatSync3(current);
|
|
3319
3576
|
if (currentStat.isSymbolicLink()) throw new Error(`pi_managed_mcp_bootstrap_cache_unsafe: ${current}`);
|
|
3320
3577
|
if (currentStat.isDirectory()) {
|
|
3321
|
-
|
|
3322
|
-
for (const entry of readdirSync3(current)) pending.push(
|
|
3578
|
+
chmodSync4(current, 448);
|
|
3579
|
+
for (const entry of readdirSync3(current)) pending.push(join5(current, entry));
|
|
3323
3580
|
continue;
|
|
3324
3581
|
}
|
|
3325
3582
|
if (!currentStat.isFile()) throw new Error(`pi_managed_mcp_bootstrap_cache_unsafe: ${current}`);
|
|
3326
|
-
|
|
3583
|
+
chmodSync4(current, 384 | currentStat.mode & 73);
|
|
3327
3584
|
}
|
|
3328
3585
|
}
|
|
3329
3586
|
function piLoaderIdentity(executorPath) {
|
|
3330
|
-
let cursor =
|
|
3587
|
+
let cursor = dirname4(realpathSync2(executorPath));
|
|
3331
3588
|
for (let depth = 0; depth < 4; depth += 1) {
|
|
3332
|
-
const packagePath =
|
|
3333
|
-
const loaderPath =
|
|
3589
|
+
const packagePath = join5(cursor, "package.json");
|
|
3590
|
+
const loaderPath = join5(cursor, "dist", "core", "extensions", "loader.js");
|
|
3334
3591
|
if (existsSync3(packagePath) && existsSync3(loaderPath)) {
|
|
3335
|
-
const packageJson = JSON.parse(
|
|
3592
|
+
const packageJson = JSON.parse(readFileSync4(packagePath, "utf8"));
|
|
3336
3593
|
return sha2562(stablePiJson({
|
|
3337
3594
|
name: packageJson.name,
|
|
3338
3595
|
version: packageJson.version,
|
|
3339
|
-
loaderSha256: sha2562(
|
|
3596
|
+
loaderSha256: sha2562(readFileSync4(loaderPath))
|
|
3340
3597
|
}));
|
|
3341
3598
|
}
|
|
3342
|
-
cursor =
|
|
3599
|
+
cursor = dirname4(cursor);
|
|
3343
3600
|
}
|
|
3344
|
-
return sha2562(
|
|
3601
|
+
return sha2562(readFileSync4(realpathSync2(executorPath)));
|
|
3345
3602
|
}
|
|
3346
3603
|
function effectiveToolsBootstrapKey(input, sharedRuntime, executorCommand) {
|
|
3347
|
-
const adapterRoot =
|
|
3604
|
+
const adapterRoot = join5(sharedRuntime.home, "npm", "node_modules", "pi-mcp-adapter");
|
|
3348
3605
|
const resolvedExecutorCommand = resolvePiExecutablePath(executorCommand, input.baseEnv);
|
|
3349
3606
|
return sha2562(stablePiJson({
|
|
3350
3607
|
schemaVersion: PI_EFFECTIVE_TOOLS_BOOTSTRAP_SCHEMA_VERSION,
|
|
@@ -3365,24 +3622,24 @@ function createManagedPiMcpProfileApi(options = {}) {
|
|
|
3365
3622
|
}));
|
|
3366
3623
|
}
|
|
3367
3624
|
function prepareEffectiveToolsBootstrapCache(input, sharedRuntime, executorCommand, tmpPath) {
|
|
3368
|
-
const cacheRoot = resolve3(nonEmpty2(input.runtimeCacheRoot ??
|
|
3369
|
-
const bootstrapRoot =
|
|
3625
|
+
const cacheRoot = resolve3(nonEmpty2(input.runtimeCacheRoot ?? join5(dirname4(input.runDir), ".runtime-cache"), "runtimeCacheRoot"));
|
|
3626
|
+
const bootstrapRoot = join5(cacheRoot, "pi-effective-tools-jiti-v1");
|
|
3370
3627
|
mkdirSync3(bootstrapRoot, { recursive: true, mode: 448 });
|
|
3371
3628
|
const bootstrapRootStat = lstatSync3(bootstrapRoot);
|
|
3372
3629
|
if (!bootstrapRootStat.isDirectory() || bootstrapRootStat.isSymbolicLink()) {
|
|
3373
3630
|
throw new Error("pi_managed_mcp_bootstrap_cache_unsafe: root");
|
|
3374
3631
|
}
|
|
3375
3632
|
const key = effectiveToolsBootstrapKey(input, sharedRuntime, executorCommand);
|
|
3376
|
-
const entryPath =
|
|
3377
|
-
const markerPath =
|
|
3378
|
-
const sourceCachePath =
|
|
3379
|
-
const runCachePath =
|
|
3633
|
+
const entryPath = join5(bootstrapRoot, key);
|
|
3634
|
+
const markerPath = join5(entryPath, "manifest.json");
|
|
3635
|
+
const sourceCachePath = join5(entryPath, "jiti");
|
|
3636
|
+
const runCachePath = join5(tmpPath, "jiti");
|
|
3380
3637
|
let status = "miss";
|
|
3381
3638
|
if (existsSync3(entryPath)) {
|
|
3382
3639
|
try {
|
|
3383
3640
|
const entryStat = lstatSync3(entryPath);
|
|
3384
3641
|
const markerStat = lstatSync3(markerPath);
|
|
3385
|
-
const marker = JSON.parse(
|
|
3642
|
+
const marker = JSON.parse(readFileSync4(markerPath, "utf8"));
|
|
3386
3643
|
if (!entryStat.isDirectory() || entryStat.isSymbolicLink() || !markerStat.isFile() || markerStat.isSymbolicLink() || marker.schemaVersion !== PI_EFFECTIVE_TOOLS_BOOTSTRAP_SCHEMA_VERSION || marker.key !== key || marker.treeSha256 !== trustedTreeDigest(sourceCachePath)) throw new Error("bootstrap marker mismatch");
|
|
3387
3644
|
copyTrustedTree(sourceCachePath, runCachePath);
|
|
3388
3645
|
status = "hit";
|
|
@@ -3392,7 +3649,7 @@ function createManagedPiMcpProfileApi(options = {}) {
|
|
|
3392
3649
|
throw new Error("pi_managed_mcp_bootstrap_cache_unsafe: entry");
|
|
3393
3650
|
}
|
|
3394
3651
|
makeTrustedTreeWritable(resolvedEntry);
|
|
3395
|
-
|
|
3652
|
+
rmSync3(resolvedEntry, { recursive: true, force: true });
|
|
3396
3653
|
status = "invalidated";
|
|
3397
3654
|
}
|
|
3398
3655
|
}
|
|
@@ -3409,16 +3666,16 @@ function createManagedPiMcpProfileApi(options = {}) {
|
|
|
3409
3666
|
const stagingPath = `${cache.entryPath}.tmp-${process.pid}-${currentTimeMs()}`;
|
|
3410
3667
|
try {
|
|
3411
3668
|
mkdirSync3(stagingPath, { mode: 448 });
|
|
3412
|
-
const stagingCachePath =
|
|
3669
|
+
const stagingCachePath = join5(stagingPath, "jiti");
|
|
3413
3670
|
copyTrustedTree(cache.runCachePath, stagingCachePath);
|
|
3414
|
-
writePrivateFile2(
|
|
3671
|
+
writePrivateFile2(join5(stagingPath, "manifest.json"), `${JSON.stringify({
|
|
3415
3672
|
schemaVersion: PI_EFFECTIVE_TOOLS_BOOTSTRAP_SCHEMA_VERSION,
|
|
3416
3673
|
key: cache.key,
|
|
3417
3674
|
treeSha256: trustedTreeDigest(stagingCachePath)
|
|
3418
3675
|
})}
|
|
3419
3676
|
`);
|
|
3420
3677
|
try {
|
|
3421
|
-
|
|
3678
|
+
renameSync3(stagingPath, cache.entryPath);
|
|
3422
3679
|
makeTrustedTreeReadOnly(cache.entryPath);
|
|
3423
3680
|
} catch (error) {
|
|
3424
3681
|
if (error?.code !== "EEXIST" && error?.code !== "ENOTEMPTY") throw error;
|
|
@@ -3426,7 +3683,7 @@ function createManagedPiMcpProfileApi(options = {}) {
|
|
|
3426
3683
|
} finally {
|
|
3427
3684
|
if (existsSync3(stagingPath)) {
|
|
3428
3685
|
makeTrustedTreeWritable(stagingPath);
|
|
3429
|
-
|
|
3686
|
+
rmSync3(stagingPath, { recursive: true, force: true });
|
|
3430
3687
|
}
|
|
3431
3688
|
}
|
|
3432
3689
|
return existsSync3(cache.entryPath) ? `${cache.status}_published` : `${cache.status}_unavailable`;
|
|
@@ -3435,7 +3692,7 @@ function createManagedPiMcpProfileApi(options = {}) {
|
|
|
3435
3692
|
let history = [];
|
|
3436
3693
|
if (existsSync3(phasePath)) {
|
|
3437
3694
|
try {
|
|
3438
|
-
const parsed = JSON.parse(
|
|
3695
|
+
const parsed = JSON.parse(readFileSync4(phasePath, "utf8"));
|
|
3439
3696
|
history = Array.isArray(parsed.history) ? parsed.history.slice(0, 16) : [];
|
|
3440
3697
|
} catch {
|
|
3441
3698
|
history = [];
|
|
@@ -3450,17 +3707,17 @@ function createManagedPiMcpProfileApi(options = {}) {
|
|
|
3450
3707
|
if (!phaseStat.isFile() || phaseStat.isSymbolicLink()) {
|
|
3451
3708
|
throw new Error("pi_managed_mcp_probe_phase_unsafe");
|
|
3452
3709
|
}
|
|
3453
|
-
|
|
3454
|
-
|
|
3710
|
+
writeFileSync4(phasePath, contents, { encoding: "utf8", mode: 384 });
|
|
3711
|
+
chmodSync4(phasePath, 384);
|
|
3455
3712
|
return;
|
|
3456
3713
|
}
|
|
3457
3714
|
writeOwnedFileAtomic(phasePath, contents);
|
|
3458
3715
|
}
|
|
3459
3716
|
function piMcpAdapterVersion(piHome) {
|
|
3460
|
-
const packagePath =
|
|
3717
|
+
const packagePath = join5(piHome, "npm", "node_modules", "pi-mcp-adapter", "package.json");
|
|
3461
3718
|
let packageJson;
|
|
3462
3719
|
try {
|
|
3463
|
-
packageJson = JSON.parse(
|
|
3720
|
+
packageJson = JSON.parse(readFileSync4(packagePath, "utf8"));
|
|
3464
3721
|
} catch {
|
|
3465
3722
|
throw new Error("pi_managed_mcp_adapter_version_unavailable");
|
|
3466
3723
|
}
|
|
@@ -3556,7 +3813,7 @@ function createManagedPiMcpProfileApi(options = {}) {
|
|
|
3556
3813
|
const pathEntries = String(env?.PATH ?? "").split(delimiter).filter(Boolean);
|
|
3557
3814
|
for (const entry of pathEntries) {
|
|
3558
3815
|
try {
|
|
3559
|
-
const candidate = realpathSync2(
|
|
3816
|
+
const candidate = realpathSync2(join5(entry, executorCommand));
|
|
3560
3817
|
const stat = lstatSync3(candidate);
|
|
3561
3818
|
if (stat.isFile() && !stat.isSymbolicLink()) return candidate;
|
|
3562
3819
|
} catch {
|
|
@@ -3571,7 +3828,7 @@ function createManagedPiMcpProfileApi(options = {}) {
|
|
|
3571
3828
|
if (!executableStat.isFile() || executableStat.isSymbolicLink()) {
|
|
3572
3829
|
throw Object.assign(new Error("Pi executable is not a regular file"), { code: "EUNSAFE" });
|
|
3573
3830
|
}
|
|
3574
|
-
const contentSha256 = createHash3("sha256").update(
|
|
3831
|
+
const contentSha256 = createHash3("sha256").update(readFileSync4(realPath)).digest("hex");
|
|
3575
3832
|
return `sha256:${createHash3("sha256").update(JSON.stringify({ realPath, contentSha256 })).digest("hex")}`;
|
|
3576
3833
|
} catch (error) {
|
|
3577
3834
|
const errorCode = typeof error?.code === "string" ? error.code : "UNKNOWN";
|
|
@@ -3739,7 +3996,7 @@ function createManagedPiMcpProfileApi(options = {}) {
|
|
|
3739
3996
|
if (!existsSync3(filePath)) return false;
|
|
3740
3997
|
let parsed;
|
|
3741
3998
|
try {
|
|
3742
|
-
parsed = JSON.parse(
|
|
3999
|
+
parsed = JSON.parse(readFileSync4(filePath, "utf8"));
|
|
3743
4000
|
} catch {
|
|
3744
4001
|
return true;
|
|
3745
4002
|
}
|
|
@@ -3754,25 +4011,25 @@ function createManagedPiMcpProfileApi(options = {}) {
|
|
|
3754
4011
|
while (within2(cursor, boundary)) {
|
|
3755
4012
|
visit(cursor, cursor === start);
|
|
3756
4013
|
if (cursor === boundary) break;
|
|
3757
|
-
cursor =
|
|
4014
|
+
cursor = dirname4(cursor);
|
|
3758
4015
|
}
|
|
3759
4016
|
}
|
|
3760
4017
|
function assertNoProjectMcpOverride(cwd, runDir) {
|
|
3761
4018
|
walkProjectMcpConfigs(cwd, runDir, (level) => {
|
|
3762
|
-
for (const relativePath of [".mcp.json",
|
|
3763
|
-
const configPath =
|
|
4019
|
+
for (const relativePath of [".mcp.json", join5(".pi", "mcp.json")]) {
|
|
4020
|
+
const configPath = join5(level, relativePath);
|
|
3764
4021
|
if (projectMcpConfigHasContent(configPath)) throw new Error(`pi_managed_mcp_project_override_blocked: ${configPath}`);
|
|
3765
4022
|
}
|
|
3766
4023
|
});
|
|
3767
4024
|
}
|
|
3768
4025
|
function assertWorkspaceMcpOverrideClear(cwd, runDir) {
|
|
3769
4026
|
walkProjectMcpConfigs(cwd, runDir, (level, isCwd) => {
|
|
3770
|
-
const sharedProjectConfig =
|
|
4027
|
+
const sharedProjectConfig = join5(level, ".mcp.json");
|
|
3771
4028
|
if (projectMcpConfigHasContent(sharedProjectConfig)) {
|
|
3772
4029
|
throw new Error(`pi_managed_mcp_project_override_blocked: ${sharedProjectConfig}`);
|
|
3773
4030
|
}
|
|
3774
4031
|
if (!isCwd) {
|
|
3775
|
-
const ancestorPiConfig =
|
|
4032
|
+
const ancestorPiConfig = join5(level, ".pi", "mcp.json");
|
|
3776
4033
|
if (projectMcpConfigHasContent(ancestorPiConfig)) {
|
|
3777
4034
|
throw new Error(`pi_managed_mcp_project_override_blocked: ${ancestorPiConfig}`);
|
|
3778
4035
|
}
|
|
@@ -3783,11 +4040,11 @@ function createManagedPiMcpProfileApi(options = {}) {
|
|
|
3783
4040
|
return resolve3(path).replaceAll("\\", "/").endsWith("/.pi/mcp.json");
|
|
3784
4041
|
}
|
|
3785
4042
|
function managedRunRootForProfile(profileRoot) {
|
|
3786
|
-
const executorsRoot =
|
|
4043
|
+
const executorsRoot = dirname4(dirname4(resolve3(profileRoot)));
|
|
3787
4044
|
if (basename2(executorsRoot) !== "executors") {
|
|
3788
4045
|
throw new Error("pi_managed_mcp_cleanup_owner_mismatch: profile is outside a managed run");
|
|
3789
4046
|
}
|
|
3790
|
-
return
|
|
4047
|
+
return dirname4(executorsRoot);
|
|
3791
4048
|
}
|
|
3792
4049
|
function workspaceMcpConfigBelongsToProfile(configPath, profileRoot) {
|
|
3793
4050
|
const target = resolve3(configPath);
|
|
@@ -3800,11 +4057,11 @@ function createManagedPiMcpProfileApi(options = {}) {
|
|
|
3800
4057
|
throw new Error(`pi_managed_mcp_workspace_config_unsafe: ${filePath}`);
|
|
3801
4058
|
}
|
|
3802
4059
|
}
|
|
3803
|
-
mkdirSync3(
|
|
4060
|
+
mkdirSync3(dirname4(filePath), { recursive: true, mode: 448 });
|
|
3804
4061
|
const tempPath = `${filePath}.tmp.${process.pid}`;
|
|
3805
|
-
|
|
3806
|
-
|
|
3807
|
-
|
|
4062
|
+
writeFileSync4(tempPath, contents, { mode: 384 });
|
|
4063
|
+
renameSync3(tempPath, filePath);
|
|
4064
|
+
chmodSync4(filePath, 384);
|
|
3808
4065
|
const mode = statSync2(filePath).mode & 511;
|
|
3809
4066
|
if (mode !== 384) throw new Error(`pi_managed_mcp_permissions_failed: ${filePath} mode=${mode.toString(8)}`);
|
|
3810
4067
|
}
|
|
@@ -3814,11 +4071,11 @@ function createManagedPiMcpProfileApi(options = {}) {
|
|
|
3814
4071
|
if (!homeStat.isDirectory() || homeStat.isSymbolicLink()) {
|
|
3815
4072
|
throw new Error("pi_managed_mcp_source_config_unsafe: Pi home");
|
|
3816
4073
|
}
|
|
3817
|
-
const settingsPath =
|
|
4074
|
+
const settingsPath = join5(home, "settings.json");
|
|
3818
4075
|
let settings = {};
|
|
3819
4076
|
if (existsSync3(settingsPath)) {
|
|
3820
4077
|
try {
|
|
3821
|
-
settings = record6(JSON.parse(
|
|
4078
|
+
settings = record6(JSON.parse(readFileSync4(settingsPath, "utf8")));
|
|
3822
4079
|
} catch {
|
|
3823
4080
|
throw new Error("pi_managed_mcp_attestation_failed: source Pi settings are invalid");
|
|
3824
4081
|
}
|
|
@@ -3837,17 +4094,17 @@ function createManagedPiMcpProfileApi(options = {}) {
|
|
|
3837
4094
|
if (!SKILL_PROFILE_NAME.test(skillProfile) || !within2(agentFile, agentsRoot) || !existsSync3(agentFile)) {
|
|
3838
4095
|
throw new Error(`pi_managed_mcp_skill_profile_unknown:${skillProfile}`);
|
|
3839
4096
|
}
|
|
3840
|
-
const declared =
|
|
4097
|
+
const declared = readFileSync4(agentFile, "utf8").match(/^---\r?\n([\s\S]*?)\r?\n---/)?.[1].match(/^skills:\s*(.+)$/m)?.[1].split(",").map((entry) => entry.trim()).filter(Boolean) ?? [];
|
|
3841
4098
|
const bundlesRoot = resolve3(piHome, "bundles");
|
|
3842
4099
|
const profile = [];
|
|
3843
4100
|
for (const name of declared) {
|
|
3844
|
-
let source =
|
|
3845
|
-
if (!existsSync3(
|
|
4101
|
+
let source = join5(bundlesRoot, skillProfile, "skills", name);
|
|
4102
|
+
if (!existsSync3(join5(source, "SKILL.md"))) {
|
|
3846
4103
|
const candidates = [];
|
|
3847
4104
|
for (const category of readdirSync3(bundlesRoot).sort()) {
|
|
3848
4105
|
if (category === skillProfile) continue;
|
|
3849
|
-
const candidate =
|
|
3850
|
-
if (existsSync3(
|
|
4106
|
+
const candidate = join5(bundlesRoot, category, "skills", name);
|
|
4107
|
+
if (existsSync3(join5(candidate, "SKILL.md"))) candidates.push(candidate);
|
|
3851
4108
|
}
|
|
3852
4109
|
if (candidates.length > 1) {
|
|
3853
4110
|
throw new Error(`pi_managed_mcp_skill_profile_ambiguous:${skillProfile}:${name}`);
|
|
@@ -3865,8 +4122,8 @@ function createManagedPiMcpProfileApi(options = {}) {
|
|
|
3865
4122
|
const skillsRoot = resolve3(piHome, "bundles", "common", "skills");
|
|
3866
4123
|
if (!existsSync3(skillsRoot)) return [];
|
|
3867
4124
|
return readdirSync3(skillsRoot).sort().flatMap((name) => {
|
|
3868
|
-
const source =
|
|
3869
|
-
return existsSync3(
|
|
4125
|
+
const source = join5(skillsRoot, name);
|
|
4126
|
+
return existsSync3(join5(source, "SKILL.md")) ? [{ name, source }] : [];
|
|
3870
4127
|
});
|
|
3871
4128
|
}
|
|
3872
4129
|
function resolveManagedRoleSkills(piHome, skillProfiles) {
|
|
@@ -3888,7 +4145,7 @@ function createManagedPiMcpProfileApi(options = {}) {
|
|
|
3888
4145
|
}
|
|
3889
4146
|
const entries = [...entriesByName.values()].map((entry) => ({
|
|
3890
4147
|
name: entry.name,
|
|
3891
|
-
filePath: realpathSync2(
|
|
4148
|
+
filePath: realpathSync2(join5(entry.source, "SKILL.md"))
|
|
3892
4149
|
}));
|
|
3893
4150
|
return {
|
|
3894
4151
|
enabled: entries.map((entry) => entry.name),
|
|
@@ -3916,18 +4173,18 @@ function createManagedPiMcpProfileApi(options = {}) {
|
|
|
3916
4173
|
const protectedValues = [];
|
|
3917
4174
|
for (const entry of readdirSync3(source, { withFileTypes: true })) {
|
|
3918
4175
|
if (entry.name === "mcp.json" || entry.name === "mcp-cache.json") continue;
|
|
3919
|
-
const sourcePath =
|
|
3920
|
-
const targetPath =
|
|
4176
|
+
const sourcePath = join5(source, entry.name);
|
|
4177
|
+
const targetPath = join5(agentDir, entry.name);
|
|
3921
4178
|
if (entry.isDirectory()) {
|
|
3922
4179
|
symlinkSync(sourcePath, targetPath, platform2() === "win32" ? "junction" : "dir");
|
|
3923
4180
|
} else if (entry.isFile()) {
|
|
3924
4181
|
copyPrivateFile(sourcePath, targetPath);
|
|
3925
4182
|
}
|
|
3926
4183
|
}
|
|
3927
|
-
const authSource =
|
|
4184
|
+
const authSource = join5(source, "auth.json");
|
|
3928
4185
|
if (existsSync3(authSource)) {
|
|
3929
4186
|
try {
|
|
3930
|
-
collectAuthSecretStrings2(JSON.parse(
|
|
4187
|
+
collectAuthSecretStrings2(JSON.parse(readFileSync4(authSource, "utf8")), protectedValues);
|
|
3931
4188
|
} catch {
|
|
3932
4189
|
throw new Error("pi_delegated_mcp_attestation_failed: source Pi auth is invalid");
|
|
3933
4190
|
}
|
|
@@ -3985,7 +4242,7 @@ ${result3.stderr ?? ""}`, "Pi", MINIMUM_PI_VERSION);
|
|
|
3985
4242
|
}
|
|
3986
4243
|
let effectiveConfig;
|
|
3987
4244
|
try {
|
|
3988
|
-
effectiveConfig = JSON.parse(
|
|
4245
|
+
effectiveConfig = JSON.parse(readFileSync4(configPath, "utf8"));
|
|
3989
4246
|
} catch {
|
|
3990
4247
|
throw new Error("pi_managed_mcp_attestation_failed: managed MCP config is invalid JSON");
|
|
3991
4248
|
}
|
|
@@ -4012,7 +4269,7 @@ ${result3.stderr ?? ""}`, "Pi", MINIMUM_PI_VERSION);
|
|
|
4012
4269
|
let history = [];
|
|
4013
4270
|
if (existsSync3(phasePath)) {
|
|
4014
4271
|
try {
|
|
4015
|
-
const phaseState = JSON.parse(
|
|
4272
|
+
const phaseState = JSON.parse(readFileSync4(phasePath, "utf8"));
|
|
4016
4273
|
phase = typeof phaseState.phase === "string" ? phaseState.phase : "present";
|
|
4017
4274
|
history = Array.isArray(phaseState.history) ? phaseState.history : [];
|
|
4018
4275
|
} catch {
|
|
@@ -4021,7 +4278,7 @@ ${result3.stderr ?? ""}`, "Pi", MINIMUM_PI_VERSION);
|
|
|
4021
4278
|
}
|
|
4022
4279
|
if (!existsSync3(receiptPath)) return { phase, history, receipt: null };
|
|
4023
4280
|
try {
|
|
4024
|
-
const receipt = JSON.parse(
|
|
4281
|
+
const receipt = JSON.parse(readFileSync4(receiptPath, "utf8"));
|
|
4025
4282
|
const receiptPhase = receipt?.status === "attested" || receipt?.status === "rejected" ? receipt.status : phase === "missing" ? "present" : phase;
|
|
4026
4283
|
return { phase: receiptPhase, history, receipt };
|
|
4027
4284
|
} catch {
|
|
@@ -4134,7 +4391,7 @@ ${result3.stderr ?? ""}`, "Pi", MINIMUM_PI_VERSION);
|
|
|
4134
4391
|
if (circuitKey) effectiveToolsProbeCircuits.delete(circuitKey);
|
|
4135
4392
|
let receipt;
|
|
4136
4393
|
try {
|
|
4137
|
-
receipt = JSON.parse(
|
|
4394
|
+
receipt = JSON.parse(readFileSync4(input.receiptPath, "utf8"));
|
|
4138
4395
|
} catch {
|
|
4139
4396
|
throw new Error("pi_managed_mcp_effective_tools_failed: probe receipt missing");
|
|
4140
4397
|
}
|
|
@@ -4142,10 +4399,10 @@ ${result3.stderr ?? ""}`, "Pi", MINIMUM_PI_VERSION);
|
|
|
4142
4399
|
if (receipt.status !== "attested" || receipt.mode !== "probe" || receipt.proxyMode !== input.proxyMode || receipt.proxyPresent !== expectedProxyPresent || receipt.effectiveSetHash !== input.effectiveSetHash || receipt.attestorSourceSha256 !== input.attestorSourceSha256 || receipt.configSha256 !== input.configSha256 || receipt.cacheSha256 !== input.cacheSha256) {
|
|
4143
4400
|
throw new Error("pi_managed_mcp_effective_tools_failed: probe receipt mismatch");
|
|
4144
4401
|
}
|
|
4145
|
-
if (sha2562(
|
|
4402
|
+
if (sha2562(readFileSync4(input.configPath)) !== input.configSha256) {
|
|
4146
4403
|
throw new Error("pi_managed_mcp_effective_tools_failed: config drifted during probe");
|
|
4147
4404
|
}
|
|
4148
|
-
if (sha2562(
|
|
4405
|
+
if (sha2562(readFileSync4(input.cachePath)) !== input.cacheSha256) {
|
|
4149
4406
|
throw new Error("pi_managed_mcp_effective_tools_failed: cache drifted during probe");
|
|
4150
4407
|
}
|
|
4151
4408
|
if (circuitKey) effectiveToolsProbeCircuits.delete(circuitKey);
|
|
@@ -4177,19 +4434,19 @@ ${result3.stderr ?? ""}`, "Pi", MINIMUM_PI_VERSION);
|
|
|
4177
4434
|
const runDir = resolve3(nonEmpty2(input.runDir, "runDir"));
|
|
4178
4435
|
const cwd = resolve3(nonEmpty2(input.cwd, "cwd"));
|
|
4179
4436
|
const executorHome = resolve3(nonEmpty2(input.executorHome, "executorHome"));
|
|
4180
|
-
if (!within2(executorHome,
|
|
4437
|
+
if (!within2(executorHome, join5(runDir, "executors"))) throw new Error("pi_managed_mcp_owner_mismatch: executorHome is outside the managed run");
|
|
4181
4438
|
assertWorkspaceMcpOverrideClear(cwd, runDir);
|
|
4182
|
-
const profileRoot =
|
|
4439
|
+
const profileRoot = join5(executorHome, "managed-mcp");
|
|
4183
4440
|
if (existsSync3(profileRoot)) throw new Error(`pi_managed_mcp_profile_exists: ${profileRoot}`);
|
|
4184
|
-
const home =
|
|
4185
|
-
const piAgentHome =
|
|
4186
|
-
const sessionsRoot =
|
|
4187
|
-
const tmp =
|
|
4441
|
+
const home = join5(profileRoot, "home");
|
|
4442
|
+
const piAgentHome = join5(profileRoot, "pi-agent-home");
|
|
4443
|
+
const sessionsRoot = join5(profileRoot, "sessions");
|
|
4444
|
+
const tmp = join5(profileRoot, "tmp");
|
|
4188
4445
|
for (const directory of [home, piAgentHome, sessionsRoot, tmp]) mkdirSync3(directory, { recursive: true, mode: 448 });
|
|
4189
|
-
const workspaceMcpConfigPath =
|
|
4446
|
+
const workspaceMcpConfigPath = join5(cwd, ".pi", "mcp.json");
|
|
4190
4447
|
const configPath = workspaceMcpConfigPath;
|
|
4191
4448
|
try {
|
|
4192
|
-
const markerPath =
|
|
4449
|
+
const markerPath = join5(profileRoot, PROFILE_MARKER2);
|
|
4193
4450
|
const owner = Object.freeze({ commandId: input.commandId, runId });
|
|
4194
4451
|
writePrivateFile2(markerPath, `${JSON.stringify({
|
|
4195
4452
|
version: 1,
|
|
@@ -4229,16 +4486,16 @@ ${result3.stderr ?? ""}`, "Pi", MINIMUM_PI_VERSION);
|
|
|
4229
4486
|
writeOwnedFileAtomic(configPath, `${JSON.stringify(config, null, 2)}
|
|
4230
4487
|
`);
|
|
4231
4488
|
const extensionArgs = directCatalog ? ["--mcp-config", configPath] : [];
|
|
4232
|
-
const profileExtensionsDir =
|
|
4489
|
+
const profileExtensionsDir = join5(profileRoot, "extensions");
|
|
4233
4490
|
const writeProfileExtension = (fileName, source) => {
|
|
4234
4491
|
mkdirSync3(profileExtensionsDir, { recursive: true, mode: 448 });
|
|
4235
|
-
const extensionPath =
|
|
4492
|
+
const extensionPath = join5(profileExtensionsDir, fileName);
|
|
4236
4493
|
writePrivateFile2(extensionPath, source);
|
|
4237
4494
|
extensionArgs.push("--extension", extensionPath);
|
|
4238
4495
|
return extensionPath;
|
|
4239
4496
|
};
|
|
4240
4497
|
if (directCatalog) {
|
|
4241
|
-
const adapterExtensionPath =
|
|
4498
|
+
const adapterExtensionPath = join5(
|
|
4242
4499
|
sharedRuntime.home,
|
|
4243
4500
|
"npm",
|
|
4244
4501
|
"node_modules",
|
|
@@ -4257,8 +4514,17 @@ ${result3.stderr ?? ""}`, "Pi", MINIMUM_PI_VERSION);
|
|
|
4257
4514
|
if (mcpToolMode !== MANAGED_PI_DIRECT_TYPED_MCP_TOOL_MODE) {
|
|
4258
4515
|
writeProfileExtension(MANAGED_PI_MCP_ARGS_NORMALIZER_FILENAME, managedPiMcpArgsNormalizerExtensionSource());
|
|
4259
4516
|
}
|
|
4260
|
-
const cachePath =
|
|
4517
|
+
const cachePath = join5(profileRoot, "mcp-cache.json");
|
|
4261
4518
|
let directAttestationInput = null;
|
|
4519
|
+
const sourceExecutionIdentity = input.sourceAcquisition && typeof input.sourceAcquisition.profile?.attemptId === "string" && Number.isSafeInteger(input.sourceAcquisition.profile?.epoch) ? {
|
|
4520
|
+
commandId: input.commandId,
|
|
4521
|
+
attemptId: input.sourceAcquisition.profile.attemptId,
|
|
4522
|
+
epoch: input.sourceAcquisition.profile.epoch
|
|
4523
|
+
} : null;
|
|
4524
|
+
const sourceExecutionReceiptPath = sourceExecutionIdentity ? join5(tmp, "source-acquisition-execution-receipt.json") : null;
|
|
4525
|
+
if (sourceExecutionReceiptPath) {
|
|
4526
|
+
createSourceAcquisitionExecutionReceipt(sourceExecutionReceiptPath, sourceExecutionIdentity);
|
|
4527
|
+
}
|
|
4262
4528
|
const adapterVersion = piMcpAdapterVersion(sharedRuntime.home);
|
|
4263
4529
|
if (directCatalog) {
|
|
4264
4530
|
writeProfileExtension(
|
|
@@ -4282,11 +4548,11 @@ ${result3.stderr ?? ""}`, "Pi", MINIMUM_PI_VERSION);
|
|
|
4282
4548
|
};
|
|
4283
4549
|
writeOwnedFileAtomic(cachePath, `${JSON.stringify(cache, null, 2)}
|
|
4284
4550
|
`);
|
|
4285
|
-
const cacheSha256 = sha2562(
|
|
4551
|
+
const cacheSha256 = sha2562(readFileSync4(cachePath));
|
|
4286
4552
|
const attestorSourceSha256 = sha2562(managedPiEffectiveToolsAttestorExtensionSource());
|
|
4287
|
-
const manifestPath =
|
|
4288
|
-
const receiptPath =
|
|
4289
|
-
const phasePath =
|
|
4553
|
+
const manifestPath = join5(profileRoot, "effective-tools-manifest.json");
|
|
4554
|
+
const receiptPath = join5(tmp, "effective-tools-receipt.json");
|
|
4555
|
+
const phasePath = join5(tmp, "effective-tools-phase.json");
|
|
4290
4556
|
const manifest = {
|
|
4291
4557
|
schemaVersion: MANAGED_PI_EFFECTIVE_TOOLS_SCHEMA_VERSION,
|
|
4292
4558
|
serverName: SUPPORTED_SERVER_NAME2,
|
|
@@ -4302,9 +4568,9 @@ ${result3.stderr ?? ""}`, "Pi", MINIMUM_PI_VERSION);
|
|
|
4302
4568
|
}))),
|
|
4303
4569
|
proxyMode: "forbidden",
|
|
4304
4570
|
attestorSourceSha256,
|
|
4305
|
-
configSha256: sha2562(
|
|
4571
|
+
configSha256: sha2562(readFileSync4(configPath)),
|
|
4306
4572
|
cacheSha256,
|
|
4307
|
-
cacheSemanticHash: stablePiManagedMcpCacheSemanticHash(
|
|
4573
|
+
cacheSemanticHash: stablePiManagedMcpCacheSemanticHash(readFileSync4(cachePath))
|
|
4308
4574
|
};
|
|
4309
4575
|
writePrivateFile2(manifestPath, `${JSON.stringify(manifest, null, 2)}
|
|
4310
4576
|
`);
|
|
@@ -4371,9 +4637,9 @@ ${result3.stderr ?? ""}`, "Pi", MINIMUM_PI_VERSION);
|
|
|
4371
4637
|
receiptPath,
|
|
4372
4638
|
phasePath,
|
|
4373
4639
|
cacheSha256,
|
|
4374
|
-
cacheContentsBase64: Buffer.from(
|
|
4640
|
+
cacheContentsBase64: Buffer.from(readFileSync4(cachePath)).toString("base64"),
|
|
4375
4641
|
configPath,
|
|
4376
|
-
configSha256: sha2562(
|
|
4642
|
+
configSha256: sha2562(readFileSync4(configPath)),
|
|
4377
4643
|
attestorSourceSha256,
|
|
4378
4644
|
effectiveSetHash: manifest.effectiveSetHash,
|
|
4379
4645
|
proxyMode: manifest.proxyMode,
|
|
@@ -4409,6 +4675,9 @@ ${result3.stderr ?? ""}`, "Pi", MINIMUM_PI_VERSION);
|
|
|
4409
4675
|
AMASTER_PI_EFFECTIVE_TOOLS_CACHE: directAttestationInput.cachePath,
|
|
4410
4676
|
AMASTER_PI_EFFECTIVE_TOOLS_CONFIG: directAttestationInput.configPath
|
|
4411
4677
|
} : {},
|
|
4678
|
+
...sourceExecutionReceiptPath ? {
|
|
4679
|
+
AMASTER_SOURCE_ACQUISITION_EXECUTION_RECEIPT: sourceExecutionReceiptPath
|
|
4680
|
+
} : {},
|
|
4412
4681
|
...input.sourceAcquisition ? sourceAcquisitionBrowserEnvironment(input.sourceAcquisition, input.baseEnv) : {}
|
|
4413
4682
|
};
|
|
4414
4683
|
if (directAttestationInput) {
|
|
@@ -4475,6 +4744,10 @@ ${result3.stderr ?? ""}`, "Pi", MINIMUM_PI_VERSION);
|
|
|
4475
4744
|
extensionArgs,
|
|
4476
4745
|
spawnIdentity,
|
|
4477
4746
|
workspaceMcpConfigPath,
|
|
4747
|
+
...sourceExecutionReceiptPath ? {
|
|
4748
|
+
sourceAcquisitionExecutionReceiptPath: sourceExecutionReceiptPath,
|
|
4749
|
+
sourceAcquisitionExecutionIdentity: sourceExecutionIdentity
|
|
4750
|
+
} : {},
|
|
4478
4751
|
...directAttestationInput ? {
|
|
4479
4752
|
runExitClosureBaseline: {
|
|
4480
4753
|
schemaVersion: directAttestationInput.closureProfile ? "amaster.pi-run-exit-closure-baseline.v2" : "amaster.pi-run-exit-closure-baseline.v1",
|
|
@@ -4485,7 +4758,7 @@ ${result3.stderr ?? ""}`, "Pi", MINIMUM_PI_VERSION);
|
|
|
4485
4758
|
cacheContentsBase64: directAttestationInput.cacheContentsBase64,
|
|
4486
4759
|
cacheOwnership: runExitClosureOwnership ? { uid: runExitClosureOwnership.cache.uid, gid: runExitClosureOwnership.cache.gid } : null,
|
|
4487
4760
|
manifestPath: directAttestationInput.manifestPath,
|
|
4488
|
-
manifestSha256: sha2562(
|
|
4761
|
+
manifestSha256: sha2562(readFileSync4(directAttestationInput.manifestPath)),
|
|
4489
4762
|
configPath: directAttestationInput.configPath,
|
|
4490
4763
|
configSha256: directAttestationInput.configSha256,
|
|
4491
4764
|
receiptPath: directAttestationInput.receiptPath,
|
|
@@ -4517,7 +4790,7 @@ ${result3.stderr ?? ""}`, "Pi", MINIMUM_PI_VERSION);
|
|
|
4517
4790
|
}
|
|
4518
4791
|
};
|
|
4519
4792
|
} catch (error) {
|
|
4520
|
-
|
|
4793
|
+
rmSync3(profileRoot, { recursive: true, force: true });
|
|
4521
4794
|
removeWorkspaceMcpConfig(workspaceMcpConfigPath, profileRoot);
|
|
4522
4795
|
throw error;
|
|
4523
4796
|
}
|
|
@@ -4567,7 +4840,7 @@ ${result3.stderr ?? ""}`, "Pi", MINIMUM_PI_VERSION);
|
|
|
4567
4840
|
if (closureToolAllowlist && (closureToolAllowlist.length !== RUN_EXIT_CLOSURE_DIRECT_TYPED_TOOL_NAMES.size || new Set(closureToolAllowlist).size !== RUN_EXIT_CLOSURE_DIRECT_TYPED_TOOL_NAMES.size || closureToolAllowlist.some((name) => !PROVIDER_SAFE_TOOL_NAME.test(name)))) {
|
|
4568
4841
|
throw new Error("pi_run_exit_closure_baseline_tool_allowlist_invalid");
|
|
4569
4842
|
}
|
|
4570
|
-
const currentManifestSha256 = sha2562(
|
|
4843
|
+
const currentManifestSha256 = sha2562(readFileSync4(manifestPath));
|
|
4571
4844
|
const acceptedManifestDigests = /* @__PURE__ */ new Set([
|
|
4572
4845
|
nonEmpty2(baseline.manifestSha256, "runExitClosureBaseline.manifestSha256"),
|
|
4573
4846
|
...closureProfile ? [nonEmpty2(closureProfile.manifestSha256, "closureProfile.manifestSha256")] : []
|
|
@@ -4575,7 +4848,7 @@ ${result3.stderr ?? ""}`, "Pi", MINIMUM_PI_VERSION);
|
|
|
4575
4848
|
if (!acceptedManifestDigests.has(currentManifestSha256)) {
|
|
4576
4849
|
throw new Error("pi_run_exit_closure_baseline_manifest_drift");
|
|
4577
4850
|
}
|
|
4578
|
-
const currentConfigSha256 = sha2562(
|
|
4851
|
+
const currentConfigSha256 = sha2562(readFileSync4(configPath));
|
|
4579
4852
|
const acceptedConfigDigests = /* @__PURE__ */ new Set([
|
|
4580
4853
|
nonEmpty2(baseline.configSha256, "runExitClosureBaseline.configSha256"),
|
|
4581
4854
|
...closureProfile ? [nonEmpty2(closureProfile.configSha256, "closureProfile.configSha256")] : []
|
|
@@ -4612,7 +4885,7 @@ ${result3.stderr ?? ""}`, "Pi", MINIMUM_PI_VERSION);
|
|
|
4612
4885
|
ownership: baselineCacheOwnership,
|
|
4613
4886
|
label: "cache"
|
|
4614
4887
|
}];
|
|
4615
|
-
if (existsSync3(receiptPath))
|
|
4888
|
+
if (existsSync3(receiptPath)) rmSync3(receiptPath);
|
|
4616
4889
|
for (const entry of phaseContents) {
|
|
4617
4890
|
if (sha2562(entry.bytes) !== entry.expectedSha256) {
|
|
4618
4891
|
throw new Error(`pi_run_exit_closure_${entry.label}_digest_mismatch`);
|
|
@@ -4623,7 +4896,7 @@ ${result3.stderr ?? ""}`, "Pi", MINIMUM_PI_VERSION);
|
|
|
4623
4896
|
if (replacedStat.uid !== recordedOwnership.uid || replacedStat.gid !== recordedOwnership.gid) {
|
|
4624
4897
|
chownSyncImpl(entry.path, recordedOwnership.uid, recordedOwnership.gid);
|
|
4625
4898
|
}
|
|
4626
|
-
if (sha2562(
|
|
4899
|
+
if (sha2562(readFileSync4(entry.path)) !== entry.expectedSha256) {
|
|
4627
4900
|
throw new Error(`pi_run_exit_closure_${entry.label}_restore_failed`);
|
|
4628
4901
|
}
|
|
4629
4902
|
const restoredStat = ownershipStatSyncImpl(entry.path);
|
|
@@ -4653,7 +4926,7 @@ ${result3.stderr ?? ""}`, "Pi", MINIMUM_PI_VERSION);
|
|
|
4653
4926
|
throw new Error(`pi_run_exit_closure_baseline_unsafe: ${receiptPath}`);
|
|
4654
4927
|
}
|
|
4655
4928
|
try {
|
|
4656
|
-
const receipt = record6(JSON.parse(
|
|
4929
|
+
const receipt = record6(JSON.parse(readFileSync4(receiptPath, "utf8")));
|
|
4657
4930
|
return {
|
|
4658
4931
|
status: nonEmpty2(receipt.status, "effectiveToolsReceipt.status"),
|
|
4659
4932
|
...typeof receipt.mode === "string" ? { mode: receipt.mode } : {},
|
|
@@ -4675,15 +4948,15 @@ ${result3.stderr ?? ""}`, "Pi", MINIMUM_PI_VERSION);
|
|
|
4675
4948
|
if (!within2(cwd, runDir)) throw new Error("pi_delegated_mcp_owner_mismatch: cwd is outside the managed run");
|
|
4676
4949
|
assertNoProjectMcpOverride(cwd, runDir);
|
|
4677
4950
|
const executorHome = resolve3(nonEmpty2(input.executorHome, "executorHome"));
|
|
4678
|
-
if (!within2(executorHome,
|
|
4679
|
-
const profileRoot =
|
|
4951
|
+
if (!within2(executorHome, join5(runDir, "executors"))) throw new Error("pi_delegated_mcp_owner_mismatch: executorHome is outside the managed run");
|
|
4952
|
+
const profileRoot = join5(executorHome, "delegated-mcp");
|
|
4680
4953
|
if (existsSync3(profileRoot)) throw new Error(`pi_delegated_mcp_profile_exists: ${profileRoot}`);
|
|
4681
|
-
const piCodingAgentDir =
|
|
4682
|
-
const sessionsRoot =
|
|
4683
|
-
const tmp =
|
|
4954
|
+
const piCodingAgentDir = join5(profileRoot, "pi-coding-agent-dir");
|
|
4955
|
+
const sessionsRoot = join5(profileRoot, "sessions");
|
|
4956
|
+
const tmp = join5(profileRoot, "tmp");
|
|
4684
4957
|
for (const directory of [profileRoot, piCodingAgentDir, sessionsRoot, tmp]) mkdirSync3(directory, { recursive: true, mode: 448 });
|
|
4685
4958
|
try {
|
|
4686
|
-
const markerPath =
|
|
4959
|
+
const markerPath = join5(profileRoot, DELEGATED_PROFILE_MARKER);
|
|
4687
4960
|
const owner = Object.freeze({ commandId: input.commandId, runId });
|
|
4688
4961
|
writePrivateFile2(markerPath, `${JSON.stringify({ version: 1, ...owner, profileRoot, piCodingAgentDir })}
|
|
4689
4962
|
`);
|
|
@@ -4701,8 +4974,8 @@ ${result3.stderr ?? ""}`, "Pi", MINIMUM_PI_VERSION);
|
|
|
4701
4974
|
throw new Error("pi_delegated_mcp_source_config_unsafe: Pi home");
|
|
4702
4975
|
}
|
|
4703
4976
|
const seededRuntime = seedDelegatedPiRuntime(sourcePiHome, piCodingAgentDir);
|
|
4704
|
-
const sourceMcp = readJsonObjectFile(
|
|
4705
|
-
const configPath =
|
|
4977
|
+
const sourceMcp = readJsonObjectFile(join5(sourcePiHome, "mcp.json"));
|
|
4978
|
+
const configPath = join5(piCodingAgentDir, "mcp.json");
|
|
4706
4979
|
const directToolNames = directCatalog?.tools.map((tool) => tool.exposedName) ?? [];
|
|
4707
4980
|
const serverConfig = {
|
|
4708
4981
|
type: "http",
|
|
@@ -4729,8 +5002,8 @@ ${result3.stderr ?? ""}`, "Pi", MINIMUM_PI_VERSION);
|
|
|
4729
5002
|
let enabledRoleSkills = null;
|
|
4730
5003
|
if (skillProfiles.length > 0) {
|
|
4731
5004
|
const roleSkills = resolveManagedRoleSkills(sourcePiHome, skillProfiles);
|
|
4732
|
-
const extensionsDir =
|
|
4733
|
-
const extensionPath =
|
|
5005
|
+
const extensionsDir = join5(profileRoot, "extensions");
|
|
5006
|
+
const extensionPath = join5(extensionsDir, MANAGED_PI_ROLE_SKILLS_VISIBILITY_FILENAME);
|
|
4734
5007
|
mkdirSync3(extensionsDir, { recursive: true, mode: 448 });
|
|
4735
5008
|
writePrivateFile2(
|
|
4736
5009
|
extensionPath,
|
|
@@ -4765,7 +5038,7 @@ ${result3.stderr ?? ""}`, "Pi", MINIMUM_PI_VERSION);
|
|
|
4765
5038
|
sessionId: gateway.sessionId,
|
|
4766
5039
|
sourcePiHome,
|
|
4767
5040
|
piCodingAgentDir,
|
|
4768
|
-
configSha256: sha2562(
|
|
5041
|
+
configSha256: sha2562(readFileSync4(configPath)),
|
|
4769
5042
|
...skillProfilesAttestation(skillProfiles, enabledRoleSkills)
|
|
4770
5043
|
};
|
|
4771
5044
|
return {
|
|
@@ -4786,7 +5059,7 @@ ${result3.stderr ?? ""}`, "Pi", MINIMUM_PI_VERSION);
|
|
|
4786
5059
|
}
|
|
4787
5060
|
};
|
|
4788
5061
|
} catch (error) {
|
|
4789
|
-
|
|
5062
|
+
rmSync3(profileRoot, { recursive: true, force: true });
|
|
4790
5063
|
throw error;
|
|
4791
5064
|
}
|
|
4792
5065
|
}
|
|
@@ -4799,13 +5072,13 @@ ${result3.stderr ?? ""}`, "Pi", MINIMUM_PI_VERSION);
|
|
|
4799
5072
|
if (!rolloutRelativePath || rolloutRelativePath.startsWith("..") || isAbsolute2(rolloutRelativePath)) {
|
|
4800
5073
|
throw new Error("pi_managed_mcp_session_rollout_unsafe: rollout escaped the managed Pi home");
|
|
4801
5074
|
}
|
|
4802
|
-
const cacheRoot =
|
|
4803
|
-
if (existsSync3(cacheRoot))
|
|
5075
|
+
const cacheRoot = join5(dirname4(resolve3(profile.profileRoot)), "session-rollout");
|
|
5076
|
+
if (existsSync3(cacheRoot)) rmSync3(cacheRoot, { recursive: true, force: false });
|
|
4804
5077
|
mkdirSync3(cacheRoot, { recursive: true, mode: 448 });
|
|
4805
|
-
const targetRollout =
|
|
4806
|
-
mkdirSync3(
|
|
4807
|
-
writePrivateFile2(targetRollout,
|
|
4808
|
-
writePrivateFile2(
|
|
5078
|
+
const targetRollout = join5(cacheRoot, rolloutRelativePath);
|
|
5079
|
+
mkdirSync3(dirname4(targetRollout), { recursive: true, mode: 448 });
|
|
5080
|
+
writePrivateFile2(targetRollout, readFileSync4(sourceRollout));
|
|
5081
|
+
writePrivateFile2(join5(cacheRoot, SESSION_ROLLOUT_MARKER2), `${JSON.stringify({
|
|
4809
5082
|
version: 1,
|
|
4810
5083
|
cacheRoot,
|
|
4811
5084
|
preservedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
@@ -4828,12 +5101,12 @@ ${result3.stderr ?? ""}`, "Pi", MINIMUM_PI_VERSION);
|
|
|
4828
5101
|
}
|
|
4829
5102
|
try {
|
|
4830
5103
|
const stat = lstatSync3(target);
|
|
4831
|
-
if (stat.isFile() && !stat.isSymbolicLink())
|
|
5104
|
+
if (stat.isFile() && !stat.isSymbolicLink()) rmSync3(target);
|
|
4832
5105
|
} catch (error) {
|
|
4833
5106
|
if (error?.code !== "ENOENT") throw error;
|
|
4834
5107
|
}
|
|
4835
5108
|
try {
|
|
4836
|
-
rmdirSync(
|
|
5109
|
+
rmdirSync(dirname4(target));
|
|
4837
5110
|
} catch (error) {
|
|
4838
5111
|
if (!["ENOENT", "ENOTEMPTY", "ENOTDIR"].includes(error?.code)) throw error;
|
|
4839
5112
|
}
|
|
@@ -4850,21 +5123,21 @@ ${result3.stderr ?? ""}`, "Pi", MINIMUM_PI_VERSION);
|
|
|
4850
5123
|
if (!rootStat.isDirectory() || rootStat.isSymbolicLink()) {
|
|
4851
5124
|
throw new Error("pi_managed_mcp_cleanup_owner_mismatch: profile root is not an owned directory");
|
|
4852
5125
|
}
|
|
4853
|
-
const markerPath =
|
|
5126
|
+
const markerPath = join5(profileRoot, PROFILE_MARKER2);
|
|
4854
5127
|
const markerStat = existsSync3(markerPath) ? lstatSync3(markerPath) : null;
|
|
4855
5128
|
if (!markerStat?.isFile() || markerStat.isSymbolicLink()) {
|
|
4856
5129
|
throw new Error("pi_managed_mcp_cleanup_owner_mismatch: ownership marker is missing or unsafe");
|
|
4857
5130
|
}
|
|
4858
5131
|
let marker;
|
|
4859
5132
|
try {
|
|
4860
|
-
marker = JSON.parse(
|
|
5133
|
+
marker = JSON.parse(readFileSync4(markerPath, "utf8"));
|
|
4861
5134
|
} catch {
|
|
4862
5135
|
throw new Error("pi_managed_mcp_cleanup_owner_mismatch: ownership marker is invalid");
|
|
4863
5136
|
}
|
|
4864
5137
|
if (marker?.version !== 1 || marker?.profileRoot !== profileRoot || marker?.commandId !== owner?.commandId || marker?.runId !== owner?.runId) {
|
|
4865
5138
|
throw new Error("pi_managed_mcp_cleanup_owner_mismatch: ownership marker does not match command/run");
|
|
4866
5139
|
}
|
|
4867
|
-
|
|
5140
|
+
rmSync3(profileRoot, { recursive: true, force: false });
|
|
4868
5141
|
if (existsSync3(profileRoot)) throw new Error("pi_managed_mcp_cleanup_failed: profile root still exists");
|
|
4869
5142
|
if (typeof profile?.workspaceMcpConfigPath === "string") {
|
|
4870
5143
|
removeWorkspaceMcpConfig(profile.workspaceMcpConfigPath, profileRoot);
|
|
@@ -4878,21 +5151,21 @@ ${result3.stderr ?? ""}`, "Pi", MINIMUM_PI_VERSION);
|
|
|
4878
5151
|
if (!rootStat.isDirectory() || rootStat.isSymbolicLink()) {
|
|
4879
5152
|
throw new Error("pi_delegated_mcp_cleanup_owner_mismatch: profile root is not an owned directory");
|
|
4880
5153
|
}
|
|
4881
|
-
const markerPath =
|
|
5154
|
+
const markerPath = join5(profileRoot, DELEGATED_PROFILE_MARKER);
|
|
4882
5155
|
const markerStat = existsSync3(markerPath) ? lstatSync3(markerPath) : null;
|
|
4883
5156
|
if (!markerStat?.isFile() || markerStat.isSymbolicLink()) {
|
|
4884
5157
|
throw new Error("pi_delegated_mcp_cleanup_owner_mismatch: ownership marker is missing or unsafe");
|
|
4885
5158
|
}
|
|
4886
5159
|
let marker;
|
|
4887
5160
|
try {
|
|
4888
|
-
marker = JSON.parse(
|
|
5161
|
+
marker = JSON.parse(readFileSync4(markerPath, "utf8"));
|
|
4889
5162
|
} catch {
|
|
4890
5163
|
throw new Error("pi_delegated_mcp_cleanup_owner_mismatch: ownership marker is invalid");
|
|
4891
5164
|
}
|
|
4892
5165
|
if (marker?.version !== 1 || marker?.profileRoot !== profileRoot || marker?.commandId !== owner?.commandId || marker?.runId !== owner?.runId) {
|
|
4893
5166
|
throw new Error("pi_delegated_mcp_cleanup_owner_mismatch: ownership marker does not match command/run");
|
|
4894
5167
|
}
|
|
4895
|
-
|
|
5168
|
+
rmSync3(profileRoot, { recursive: true, force: false });
|
|
4896
5169
|
if (existsSync3(profileRoot)) throw new Error("pi_delegated_mcp_cleanup_failed: profile root still exists");
|
|
4897
5170
|
return { status: "removed", profileRoot };
|
|
4898
5171
|
}
|
|
@@ -4908,7 +5181,7 @@ ${result3.stderr ?? ""}`, "Pi", MINIMUM_PI_VERSION);
|
|
|
4908
5181
|
const currentStat = lstatSync3(current);
|
|
4909
5182
|
if (!currentStat.isDirectory() || currentStat.isSymbolicLink()) continue;
|
|
4910
5183
|
for (const entry of readdirSync3(current, { withFileTypes: true })) {
|
|
4911
|
-
const fullPath =
|
|
5184
|
+
const fullPath = join5(current, entry.name);
|
|
4912
5185
|
if (entry.isDirectory() && !entry.isSymbolicLink()) pending.push(fullPath);
|
|
4913
5186
|
else if (entry.isFile() && entry.name === PROFILE_MARKER2) profileMarkers.push(fullPath);
|
|
4914
5187
|
else if (entry.isFile() && entry.name === SESSION_ROLLOUT_MARKER2) rolloutMarkers.push(fullPath);
|
|
@@ -4920,9 +5193,9 @@ ${result3.stderr ?? ""}`, "Pi", MINIMUM_PI_VERSION);
|
|
|
4920
5193
|
const failures = [];
|
|
4921
5194
|
const protectedCommandIds = new Set(Array.isArray(options2.protectedCommandIds) ? options2.protectedCommandIds.filter((value) => typeof value === "string" && value) : []);
|
|
4922
5195
|
for (const markerPath of profileMarkers) {
|
|
4923
|
-
const profileRoot =
|
|
5196
|
+
const profileRoot = dirname4(markerPath);
|
|
4924
5197
|
try {
|
|
4925
|
-
const marker = JSON.parse(
|
|
5198
|
+
const marker = JSON.parse(readFileSync4(markerPath, "utf8"));
|
|
4926
5199
|
const markerProfileRoot = typeof marker?.profileRoot === "string" ? resolve3(marker.profileRoot) : null;
|
|
4927
5200
|
if (!markerProfileRoot || !existsSync3(markerProfileRoot) || !within2(realpathSync2(profileRoot), canonicalRoot) || realpathSync2(markerProfileRoot) !== realpathSync2(profileRoot)) throw new Error("ownership marker root mismatch");
|
|
4928
5201
|
if (protectedCommandIds.has(marker?.commandId)) {
|
|
@@ -4945,17 +5218,17 @@ ${result3.stderr ?? ""}`, "Pi", MINIMUM_PI_VERSION);
|
|
|
4945
5218
|
const nowMs = Number.isFinite(options2.nowMs) ? options2.nowMs : Date.now();
|
|
4946
5219
|
const rolloutTtlMs = Number.isFinite(options2.sessionRolloutTtlMs) && options2.sessionRolloutTtlMs > 0 ? options2.sessionRolloutTtlMs : DEFAULT_SESSION_ROLLOUT_TTL_MS2;
|
|
4947
5220
|
for (const markerPath of rolloutMarkers) {
|
|
4948
|
-
const cacheRoot =
|
|
5221
|
+
const cacheRoot = dirname4(markerPath);
|
|
4949
5222
|
try {
|
|
4950
5223
|
const markerStat = lstatSync3(markerPath);
|
|
4951
5224
|
const cacheStat = lstatSync3(cacheRoot);
|
|
4952
|
-
const marker = JSON.parse(
|
|
5225
|
+
const marker = JSON.parse(readFileSync4(markerPath, "utf8"));
|
|
4953
5226
|
const markerCacheRoot = typeof marker?.cacheRoot === "string" ? resolve3(marker.cacheRoot) : null;
|
|
4954
5227
|
if (!within2(realpathSync2(cacheRoot), canonicalRoot) || basename2(cacheRoot) !== "session-rollout" || markerStat.isSymbolicLink() || !markerStat.isFile() || cacheStat.isSymbolicLink() || !cacheStat.isDirectory() || marker?.version !== 1 || typeof marker?.companyId !== "string" || typeof marker?.agentId !== "string" || typeof marker?.sourceRunId !== "string" || typeof marker?.sourceCommandId !== "string" || typeof marker?.sessionId !== "string" || !markerCacheRoot || !existsSync3(markerCacheRoot) || realpathSync2(markerCacheRoot) !== realpathSync2(cacheRoot)) throw new Error("session rollout ownership marker mismatch");
|
|
4955
5228
|
const preservedAtMs = typeof marker.preservedAt === "string" ? Date.parse(marker.preservedAt) : Number.NaN;
|
|
4956
5229
|
const markerAgeMs = nowMs - (Number.isFinite(preservedAtMs) ? preservedAtMs : markerStat.mtimeMs);
|
|
4957
5230
|
if (markerAgeMs < rolloutTtlMs) continue;
|
|
4958
|
-
|
|
5231
|
+
rmSync3(cacheRoot, { recursive: true, force: false });
|
|
4959
5232
|
if (existsSync3(cacheRoot)) throw new Error("session rollout cache still exists");
|
|
4960
5233
|
removedRollouts += 1;
|
|
4961
5234
|
} catch (error) {
|
|
@@ -4999,7 +5272,7 @@ function selectExecutor(config, command) {
|
|
|
4999
5272
|
}
|
|
5000
5273
|
|
|
5001
5274
|
// src/amaster-runtime-daemon/executor-process.mjs
|
|
5002
|
-
import { readdirSync as readdirSync4, readFileSync as
|
|
5275
|
+
import { readdirSync as readdirSync4, readFileSync as readFileSync5 } from "node:fs";
|
|
5003
5276
|
var TERMINAL_LINUX_PROCESS_STATES = /* @__PURE__ */ new Set(["Z", "X", "x"]);
|
|
5004
5277
|
function processGroupIdForChild(child, processPlatform = process.platform) {
|
|
5005
5278
|
return processPlatform === "win32" || typeof child.pid !== "number" || child.pid <= 0 ? null : child.pid;
|
|
@@ -5012,7 +5285,7 @@ function linuxProcState(stat) {
|
|
|
5012
5285
|
const processGroupId = Number.parseInt(fields[2], 10);
|
|
5013
5286
|
return Number.isInteger(processGroupId) ? { state: fields[0], processGroupId } : null;
|
|
5014
5287
|
}
|
|
5015
|
-
function linuxProcessGroupHasLiveMembers(processGroupId, procRoot = "/proc", fsApi = { readdirSync: readdirSync4, readFileSync:
|
|
5288
|
+
function linuxProcessGroupHasLiveMembers(processGroupId, procRoot = "/proc", fsApi = { readdirSync: readdirSync4, readFileSync: readFileSync5 }) {
|
|
5016
5289
|
let entries;
|
|
5017
5290
|
try {
|
|
5018
5291
|
entries = fsApi.readdirSync(procRoot, { withFileTypes: true });
|
|
@@ -5059,7 +5332,7 @@ function isProcessIdAlive(pid, processApi = process) {
|
|
|
5059
5332
|
processApi.kill(pid, 0);
|
|
5060
5333
|
if (processApi.platform === "linux") {
|
|
5061
5334
|
try {
|
|
5062
|
-
const parsed = linuxProcState(
|
|
5335
|
+
const parsed = linuxProcState(readFileSync5(`/proc/${pid}/stat`, "utf8"));
|
|
5063
5336
|
if (parsed && TERMINAL_LINUX_PROCESS_STATES.has(parsed.state)) return false;
|
|
5064
5337
|
} catch {
|
|
5065
5338
|
}
|
|
@@ -5109,8 +5382,8 @@ function isTerminalResultOutboxStatus(status) {
|
|
|
5109
5382
|
}
|
|
5110
5383
|
|
|
5111
5384
|
// src/amaster-runtime-daemon/run-completion-state.mjs
|
|
5112
|
-
import { existsSync as existsSync4, mkdirSync as mkdirSync4, readFileSync as
|
|
5113
|
-
import { join as
|
|
5385
|
+
import { existsSync as existsSync4, mkdirSync as mkdirSync4, readFileSync as readFileSync6, readdirSync as readdirSync5, renameSync as renameSync4, unlinkSync, writeFileSync as writeFileSync5 } from "node:fs";
|
|
5386
|
+
import { join as join6 } from "node:path";
|
|
5114
5387
|
var RUN_COMPLETION_STATE_VERSION = 1;
|
|
5115
5388
|
var RUN_COMPLETION_USAGE_SCHEMA_VERSION = "runtime-command-usage-v1";
|
|
5116
5389
|
var RUN_COMPLETION_PHASES = /* @__PURE__ */ new Set([
|
|
@@ -5340,22 +5613,22 @@ function assertValidRunCompletionState(value) {
|
|
|
5340
5613
|
function writeRunCompletionState(directory, state) {
|
|
5341
5614
|
const valid = assertValidRunCompletionState(state);
|
|
5342
5615
|
mkdirSync4(directory, { recursive: true, mode: 448 });
|
|
5343
|
-
const filePath =
|
|
5616
|
+
const filePath = join6(directory, runCompletionStateFileName(valid.commandId));
|
|
5344
5617
|
const temporaryPath = `${filePath}.${process.pid}.${Date.now()}.tmp`;
|
|
5345
|
-
|
|
5618
|
+
writeFileSync5(temporaryPath, `${JSON.stringify(valid, null, 2)}
|
|
5346
5619
|
`, { mode: 384 });
|
|
5347
|
-
|
|
5620
|
+
renameSync4(temporaryPath, filePath);
|
|
5348
5621
|
return filePath;
|
|
5349
5622
|
}
|
|
5350
5623
|
function readRunCompletionState(filePath) {
|
|
5351
|
-
return assertValidRunCompletionState(JSON.parse(
|
|
5624
|
+
return assertValidRunCompletionState(JSON.parse(readFileSync6(filePath, "utf8")));
|
|
5352
5625
|
}
|
|
5353
5626
|
function listRunCompletionStateFiles(directory) {
|
|
5354
5627
|
if (!existsSync4(directory)) return [];
|
|
5355
|
-
return readdirSync5(directory).filter((name) => name.endsWith(".json")).sort().map((name) =>
|
|
5628
|
+
return readdirSync5(directory).filter((name) => name.endsWith(".json")).sort().map((name) => join6(directory, name));
|
|
5356
5629
|
}
|
|
5357
5630
|
function removeRunCompletionState(directory, commandId) {
|
|
5358
|
-
const filePath =
|
|
5631
|
+
const filePath = join6(directory, runCompletionStateFileName(commandId));
|
|
5359
5632
|
if (existsSync4(filePath)) unlinkSync(filePath);
|
|
5360
5633
|
}
|
|
5361
5634
|
|
|
@@ -5801,7 +6074,7 @@ function taskAcceptanceContractSection(context, input) {
|
|
|
5801
6074
|
const validCriteria = criteria.length > 0 && criteria.every((criterion) => readString(criterion.ref) && readString(criterion.text));
|
|
5802
6075
|
const validEnrollmentIdentity = schemaVersion === "mirrorx.task-acceptance-contract.v1" && readString(enrollment.id) && Number.isInteger(enrollment.revision) && enrollmentRequirementRevision && readString(enrollment.request_hash) && sourceRef === `business_task_enrollment:${readString(enrollment.id)}@${enrollmentRequirementRevision}`;
|
|
5803
6076
|
const validParentGovernedChildIdentity = schemaVersion === "mirrorx.task-acceptance-contract.v2" && Object.keys(enrollment).length === 0 && readString(authority.kind) === "parent_governed_child" && parentRequirementRevision && readString(authority.requirements_hash) === canonicalSha256(requirements) && ["required_execution", "final_aggregation"].includes(readString(authority.completion_role)) && ["none", "package", "own_deliverable"].includes(readString(authority.review_authority)) && sourceRef === `parent_governed_child:${readString(contract.issue_id)}@${parentRequirementRevision}`;
|
|
5804
|
-
const
|
|
6077
|
+
const validIdentity2 = readString(contract.company_id) && readString(contract.issue_id) && Number.isInteger(contract.execution_epoch) && readString(contract.observed_at) && requirementRevision && Boolean(validEnrollmentIdentity || validParentGovernedChildIdentity);
|
|
5805
6078
|
const noManifestDelivery = delivery.contract_state === "not_required";
|
|
5806
6079
|
const uniqueAllowedKinds = new Set(allowedKinds).size === allowedKinds.length;
|
|
5807
6080
|
const validNoManifestDelivery = noManifestDelivery && allowedKinds.length === 0 && acceptanceContracts.length === 0;
|
|
@@ -5810,7 +6083,7 @@ function taskAcceptanceContractSection(context, input) {
|
|
|
5810
6083
|
const validOwnedAcceptance = readString(acceptance.owner_agent_id) && Object.keys(asRecord(acceptance.policy)).length > 0 && readString(acceptance.expected_outcome_at);
|
|
5811
6084
|
const validParentDelegatedAcceptance = validParentGovernedChildIdentity && readString(requirementIntent.reason) === "parent_governed_child" && ["required_execution", "final_aggregation"].includes(readString(requirementCompletion.role)) && readString(requirementOutcome.mode) === "none" && readString(acceptance.delegated_to) === "parent" && acceptance.owner_agent_id === null && acceptance.policy === null && acceptance.expected_outcome_at === null;
|
|
5812
6085
|
const validAcceptance = validOwnedAcceptance || validParentDelegatedAcceptance;
|
|
5813
|
-
if (!
|
|
6086
|
+
if (!validIdentity2 || !validCriteria || !validDelivery || !validAcceptance) {
|
|
5814
6087
|
throw taskAcceptanceContractError(
|
|
5815
6088
|
"task_acceptance_contract_invalid",
|
|
5816
6089
|
"Task Acceptance Contract is incomplete or internally inconsistent"
|
|
@@ -7738,9 +8011,9 @@ function resolveAgentInstructionSystemKernelBundle(bundle, options = {}) {
|
|
|
7738
8011
|
}
|
|
7739
8012
|
|
|
7740
8013
|
// src/amaster-runtime-daemon/config-state.mjs
|
|
7741
|
-
import { existsSync as existsSync5, mkdirSync as mkdirSync5, readFileSync as
|
|
8014
|
+
import { existsSync as existsSync5, mkdirSync as mkdirSync5, readFileSync as readFileSync7, renameSync as renameSync5, rmSync as rmSync4, writeFileSync as writeFileSync6 } from "node:fs";
|
|
7742
8015
|
import { homedir as homedir2, hostname } from "node:os";
|
|
7743
|
-
import { dirname as
|
|
8016
|
+
import { dirname as dirname5, join as join7 } from "node:path";
|
|
7744
8017
|
|
|
7745
8018
|
// src/amaster-runtime-daemon/executor-discovery.mjs
|
|
7746
8019
|
import { spawnSync as spawnSync3 } from "node:child_process";
|
|
@@ -7872,11 +8145,11 @@ function defaultMachineId() {
|
|
|
7872
8145
|
}
|
|
7873
8146
|
function runtimeHome(env) {
|
|
7874
8147
|
return expandHomePath(String(
|
|
7875
|
-
env.AMASTER_RUNTIME_STATE_HOME || env.AMASTER_RUNTIME_HOME ||
|
|
8148
|
+
env.AMASTER_RUNTIME_STATE_HOME || env.AMASTER_RUNTIME_HOME || join7(homedir2(), ".amaster-employee")
|
|
7876
8149
|
));
|
|
7877
8150
|
}
|
|
7878
8151
|
function stateFilePath(env) {
|
|
7879
|
-
return env.AMASTER_DAEMON_STATE_FILE ? expandHomePath(String(env.AMASTER_DAEMON_STATE_FILE)) :
|
|
8152
|
+
return env.AMASTER_DAEMON_STATE_FILE ? expandHomePath(String(env.AMASTER_DAEMON_STATE_FILE)) : join7(runtimeHome(env), "runtime-connector-state.json");
|
|
7880
8153
|
}
|
|
7881
8154
|
function corruptStatePath(path) {
|
|
7882
8155
|
const timestamp = (/* @__PURE__ */ new Date()).toISOString().replace(/\D/g, "").slice(0, 14);
|
|
@@ -7891,7 +8164,7 @@ function readState(env) {
|
|
|
7891
8164
|
const path = stateFilePath(env);
|
|
7892
8165
|
if (!existsSync5(path)) return {};
|
|
7893
8166
|
try {
|
|
7894
|
-
const state = JSON.parse(
|
|
8167
|
+
const state = JSON.parse(readFileSync7(path, "utf8"));
|
|
7895
8168
|
if (!state || typeof state !== "object" || Array.isArray(state)) {
|
|
7896
8169
|
throw new TypeError("runtime connector state must be a JSON object");
|
|
7897
8170
|
}
|
|
@@ -7899,7 +8172,7 @@ function readState(env) {
|
|
|
7899
8172
|
} catch {
|
|
7900
8173
|
const quarantinePath = corruptStatePath(path);
|
|
7901
8174
|
try {
|
|
7902
|
-
|
|
8175
|
+
renameSync5(path, quarantinePath);
|
|
7903
8176
|
process.stderr.write(`AMaster runtime state was invalid and quarantined at ${quarantinePath}
|
|
7904
8177
|
`);
|
|
7905
8178
|
} catch (error) {
|
|
@@ -7913,17 +8186,17 @@ function readState(env) {
|
|
|
7913
8186
|
}
|
|
7914
8187
|
function writeState(env, state) {
|
|
7915
8188
|
const path = stateFilePath(env);
|
|
7916
|
-
mkdirSync5(
|
|
8189
|
+
mkdirSync5(dirname5(path), { recursive: true });
|
|
7917
8190
|
const temporaryPath = `${path}.tmp-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}`;
|
|
7918
8191
|
try {
|
|
7919
|
-
|
|
8192
|
+
writeFileSync6(temporaryPath, `${JSON.stringify(state, null, 2)}
|
|
7920
8193
|
`, {
|
|
7921
8194
|
flag: "wx",
|
|
7922
8195
|
mode: 384
|
|
7923
8196
|
});
|
|
7924
|
-
|
|
8197
|
+
renameSync5(temporaryPath, path);
|
|
7925
8198
|
} finally {
|
|
7926
|
-
|
|
8199
|
+
rmSync4(temporaryPath, { force: true });
|
|
7927
8200
|
}
|
|
7928
8201
|
}
|
|
7929
8202
|
function buildConfig(env = process.env, flags = {}) {
|
|
@@ -7935,10 +8208,10 @@ function buildConfig(env = process.env, flags = {}) {
|
|
|
7935
8208
|
const authHeader = String(flags.authHeader ?? env.AMASTER_CONNECTOR_AUTH_HEADER ?? "");
|
|
7936
8209
|
const home = runtimeHome(env);
|
|
7937
8210
|
const runtimeWorkspacesRoot = expandHomePath(
|
|
7938
|
-
String(flags.runtimeWorkspacesRoot ?? env.AMASTER_RUNTIME_WORKSPACES_ROOT ??
|
|
8211
|
+
String(flags.runtimeWorkspacesRoot ?? env.AMASTER_RUNTIME_WORKSPACES_ROOT ?? join7(home, "workspaces"))
|
|
7939
8212
|
);
|
|
7940
8213
|
const browserSessionStateRoot = expandHomePath(String(
|
|
7941
|
-
flags.browserSessionStateRoot ?? env.AMASTER_BROWSER_SESSION_STATE_ROOT ??
|
|
8214
|
+
flags.browserSessionStateRoot ?? env.AMASTER_BROWSER_SESSION_STATE_ROOT ?? join7(home, "browser-auth")
|
|
7942
8215
|
));
|
|
7943
8216
|
const piToolArgumentGuardModeValue = String(
|
|
7944
8217
|
flags.piToolArgumentGuardMode ?? env.AMASTER_PI_TOOL_ARGUMENT_GUARD_MODE ?? "shadow"
|
|
@@ -9729,7 +10002,7 @@ var bestEffortPostJson = bestEffortPostRuntimeConnectorJson;
|
|
|
9729
10002
|
|
|
9730
10003
|
// src/amaster-runtime-daemon/runtime-artifact-upload.mjs
|
|
9731
10004
|
import { createHash as createHash8 } from "node:crypto";
|
|
9732
|
-
import { closeSync, constants, fstatSync, lstatSync as lstatSync4, openSync, readFileSync as
|
|
10005
|
+
import { closeSync, constants, fstatSync, lstatSync as lstatSync4, openSync, readFileSync as readFileSync8, realpathSync as realpathSync3 } from "node:fs";
|
|
9733
10006
|
import { isAbsolute as isAbsolute3, relative as relative3, resolve as resolve4 } from "node:path";
|
|
9734
10007
|
var SHA256_PATTERN = /^[a-f0-9]{64}$/;
|
|
9735
10008
|
function requiredString(value, name) {
|
|
@@ -9781,7 +10054,7 @@ function readOwnedWorkspaceFile(rootPath, sourceRelativePath, label = "Runtime w
|
|
|
9781
10054
|
);
|
|
9782
10055
|
}
|
|
9783
10056
|
}
|
|
9784
|
-
const body =
|
|
10057
|
+
const body = readFileSync8(descriptor);
|
|
9785
10058
|
options.afterRead?.({ sourcePath, descriptor });
|
|
9786
10059
|
const after = fstatSync(descriptor);
|
|
9787
10060
|
const pathAfter = lstatSync4(sourcePath);
|
|
@@ -10067,11 +10340,11 @@ function createRuntimeArtifactIngestQueue({ ingest, onError }) {
|
|
|
10067
10340
|
// src/amaster-runtime-daemon/workspace-guard.mjs
|
|
10068
10341
|
import { createHash as createHash10 } from "node:crypto";
|
|
10069
10342
|
import { existsSync as existsSync7, mkdirSync as mkdirSync6, realpathSync as realpathSync4, statSync as statSync4 } from "node:fs";
|
|
10070
|
-
import { basename as basename4, join as
|
|
10343
|
+
import { basename as basename4, join as join9, isAbsolute as isAbsolute4, relative as relative4, resolve as resolve5 } from "node:path";
|
|
10071
10344
|
|
|
10072
10345
|
// src/amaster-runtime-daemon/workspace-manifest.mjs
|
|
10073
|
-
import { chownSync as chownSync3, existsSync as existsSync6, readFileSync as
|
|
10074
|
-
import { basename as basename3, dirname as
|
|
10346
|
+
import { chownSync as chownSync3, existsSync as existsSync6, readFileSync as readFileSync9, renameSync as renameSync6, rmSync as rmSync5, statSync as statSync3, writeFileSync as writeFileSync7 } from "node:fs";
|
|
10347
|
+
import { basename as basename3, dirname as dirname6, join as join8 } from "node:path";
|
|
10075
10348
|
var WORKSPACE_MANIFEST_FILENAME = ".amaster-runtime.json";
|
|
10076
10349
|
function syncManifestDirOwnership(manifestPath, deps = {}) {
|
|
10077
10350
|
const stat = deps.statSync ?? statSync3;
|
|
@@ -10079,7 +10352,7 @@ function syncManifestDirOwnership(manifestPath, deps = {}) {
|
|
|
10079
10352
|
const geteuid = deps.geteuid ?? (typeof process.geteuid === "function" ? process.geteuid.bind(process) : () => null);
|
|
10080
10353
|
try {
|
|
10081
10354
|
if (geteuid() !== 0) return false;
|
|
10082
|
-
const dirStat = stat(
|
|
10355
|
+
const dirStat = stat(dirname6(manifestPath));
|
|
10083
10356
|
if (dirStat.uid === 0 && dirStat.gid === 0) return false;
|
|
10084
10357
|
chown(manifestPath, dirStat.uid, dirStat.gid);
|
|
10085
10358
|
return true;
|
|
@@ -10092,31 +10365,31 @@ function nowIso() {
|
|
|
10092
10365
|
}
|
|
10093
10366
|
function workspaceManifestPath(workspaceOrCwd) {
|
|
10094
10367
|
if (!workspaceOrCwd) return null;
|
|
10095
|
-
if (typeof workspaceOrCwd === "string") return
|
|
10096
|
-
if (typeof workspaceOrCwd.cwd === "string") return
|
|
10368
|
+
if (typeof workspaceOrCwd === "string") return join8(workspaceOrCwd, WORKSPACE_MANIFEST_FILENAME);
|
|
10369
|
+
if (typeof workspaceOrCwd.cwd === "string") return join8(workspaceOrCwd.cwd, WORKSPACE_MANIFEST_FILENAME);
|
|
10097
10370
|
return null;
|
|
10098
10371
|
}
|
|
10099
10372
|
function readWorkspaceManifest(manifestPath) {
|
|
10100
10373
|
if (!manifestPath || !existsSync6(manifestPath)) return null;
|
|
10101
10374
|
try {
|
|
10102
|
-
const parsed = JSON.parse(
|
|
10375
|
+
const parsed = JSON.parse(readFileSync9(manifestPath, "utf8"));
|
|
10103
10376
|
return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : null;
|
|
10104
10377
|
} catch {
|
|
10105
10378
|
return null;
|
|
10106
10379
|
}
|
|
10107
10380
|
}
|
|
10108
10381
|
function writeWorkspaceManifest(manifestPath, manifest, deps) {
|
|
10109
|
-
const tempPath =
|
|
10110
|
-
|
|
10382
|
+
const tempPath = join8(
|
|
10383
|
+
dirname6(manifestPath),
|
|
10111
10384
|
`.${basename3(manifestPath)}.tmp-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}`
|
|
10112
10385
|
);
|
|
10113
10386
|
try {
|
|
10114
|
-
|
|
10387
|
+
writeFileSync7(tempPath, `${JSON.stringify(manifest, null, 2)}
|
|
10115
10388
|
`, { mode: 384 });
|
|
10116
|
-
|
|
10389
|
+
renameSync6(tempPath, manifestPath);
|
|
10117
10390
|
syncManifestDirOwnership(manifestPath, deps);
|
|
10118
10391
|
} catch (err) {
|
|
10119
|
-
|
|
10392
|
+
rmSync5(tempPath, { force: true });
|
|
10120
10393
|
throw err;
|
|
10121
10394
|
}
|
|
10122
10395
|
return manifest;
|
|
@@ -10229,9 +10502,9 @@ function resolveExecutionWorkspace(config, command, opts = {}) {
|
|
|
10229
10502
|
const workspaceKey = `${safeSegment(workspaceLabel(sourceWorkspacePath, payload), "workspace")}-${shortHash(sourceWorkspacePath)}`;
|
|
10230
10503
|
const issueKey = `${safeSegment(issueLabel(command, payload), "issue")}-${shortHash(issueId, 8)}`;
|
|
10231
10504
|
const runKey = `${safeSegment(runId, "run")}-${shortHash(runId, 8)}`;
|
|
10232
|
-
const runDir =
|
|
10233
|
-
const cwd =
|
|
10234
|
-
const executorHome =
|
|
10505
|
+
const runDir = join9(root, workspaceKey, issueKey, runKey);
|
|
10506
|
+
const cwd = join9(runDir, "workdir");
|
|
10507
|
+
const executorHome = join9(runDir, "executors", safeSegment(executorKind, "executor"));
|
|
10235
10508
|
mkdirSync6(cwd, { recursive: true });
|
|
10236
10509
|
mkdirSync6(executorHome, { recursive: true });
|
|
10237
10510
|
const workspace = {
|
|
@@ -10256,7 +10529,7 @@ function resolveExecutionWorkspace(config, command, opts = {}) {
|
|
|
10256
10529
|
|
|
10257
10530
|
// src/amaster-runtime-daemon/workspace-gc.mjs
|
|
10258
10531
|
import { existsSync as existsSync8, readdirSync as readdirSync6, statSync as statSync5 } from "node:fs";
|
|
10259
|
-
import { join as
|
|
10532
|
+
import { join as join10, resolve as resolve6 } from "node:path";
|
|
10260
10533
|
function readIsoTime(value) {
|
|
10261
10534
|
if (typeof value !== "string" || !value.trim()) return null;
|
|
10262
10535
|
const time = new Date(value).getTime();
|
|
@@ -10279,7 +10552,7 @@ function walkWorkdirs(root) {
|
|
|
10279
10552
|
}
|
|
10280
10553
|
for (const entry of entries) {
|
|
10281
10554
|
if (!entry.isDirectory()) continue;
|
|
10282
|
-
const fullPath =
|
|
10555
|
+
const fullPath = join10(current, entry.name);
|
|
10283
10556
|
if (entry.name === "workdir" && existsSync8(workspaceManifestPath(fullPath))) {
|
|
10284
10557
|
workdirs.push(fullPath);
|
|
10285
10558
|
continue;
|
|
@@ -10311,7 +10584,7 @@ function directorySizeBytes(path) {
|
|
|
10311
10584
|
continue;
|
|
10312
10585
|
}
|
|
10313
10586
|
for (const entry of entries) {
|
|
10314
|
-
stack.push(
|
|
10587
|
+
stack.push(join10(current, entry.name));
|
|
10315
10588
|
}
|
|
10316
10589
|
continue;
|
|
10317
10590
|
}
|
|
@@ -10384,7 +10657,7 @@ function planManagedWorkspaceGcDryRun(input) {
|
|
|
10384
10657
|
|
|
10385
10658
|
// src/amaster-runtime-daemon/runtime-status-summary.mjs
|
|
10386
10659
|
import { existsSync as existsSync9, readdirSync as readdirSync7, statSync as statSync6 } from "node:fs";
|
|
10387
|
-
import { dirname as
|
|
10660
|
+
import { dirname as dirname7, join as join11, resolve as resolve7 } from "node:path";
|
|
10388
10661
|
function runtimeStatusDirectoryEntries(path) {
|
|
10389
10662
|
try {
|
|
10390
10663
|
return readdirSync7(path, { withFileTypes: true });
|
|
@@ -10407,7 +10680,7 @@ function runtimeStatusDirectorySizeBytes(path) {
|
|
|
10407
10680
|
if (!stat || stat.isSymbolicLink()) continue;
|
|
10408
10681
|
if (stat.isDirectory()) {
|
|
10409
10682
|
for (const entry of runtimeStatusDirectoryEntries(current)) {
|
|
10410
|
-
stack.push(
|
|
10683
|
+
stack.push(join11(current, entry.name));
|
|
10411
10684
|
}
|
|
10412
10685
|
continue;
|
|
10413
10686
|
}
|
|
@@ -10424,7 +10697,7 @@ function walkRuntimeStatusManagedWorkdirs(root) {
|
|
|
10424
10697
|
if (!current) continue;
|
|
10425
10698
|
for (const entry of runtimeStatusDirectoryEntries(current)) {
|
|
10426
10699
|
if (!entry.isDirectory()) continue;
|
|
10427
|
-
const fullPath =
|
|
10700
|
+
const fullPath = join11(current, entry.name);
|
|
10428
10701
|
if (entry.name === "workdir" && existsSync9(workspaceManifestPath(fullPath))) {
|
|
10429
10702
|
workdirs.push(fullPath);
|
|
10430
10703
|
continue;
|
|
@@ -10466,7 +10739,7 @@ function summarizeRuntimeStatusRecentRun(workdir, manifest) {
|
|
|
10466
10739
|
}
|
|
10467
10740
|
function runtimeStatusOutboxDir(config) {
|
|
10468
10741
|
const statePath = config.AMASTER_DAEMON_STATE_FILE ?? config.daemonStateFile;
|
|
10469
|
-
return
|
|
10742
|
+
return join11(dirname7(stateFilePath({
|
|
10470
10743
|
AMASTER_DAEMON_STATE_FILE: statePath
|
|
10471
10744
|
})), "result-outbox");
|
|
10472
10745
|
}
|
|
@@ -10474,7 +10747,7 @@ function runtimeStatusRunCompletionDir(config) {
|
|
|
10474
10747
|
const explicit = config.AMASTER_RUN_COMPLETION_STATE_DIR ?? config.runCompletionStateDir;
|
|
10475
10748
|
if (typeof explicit === "string" && explicit.trim()) return resolve7(explicit);
|
|
10476
10749
|
const statePath = config.AMASTER_DAEMON_STATE_FILE ?? config.daemonStateFile;
|
|
10477
|
-
return
|
|
10750
|
+
return join11(dirname7(stateFilePath({
|
|
10478
10751
|
AMASTER_DAEMON_STATE_FILE: statePath
|
|
10479
10752
|
})), "run-completion-state");
|
|
10480
10753
|
}
|
|
@@ -10511,9 +10784,9 @@ function summarizeRuntimeLocalState(input) {
|
|
|
10511
10784
|
}
|
|
10512
10785
|
}
|
|
10513
10786
|
const pendingOutboxDir = runtimeStatusOutboxDir(config);
|
|
10514
|
-
const invalidOutboxDir =
|
|
10787
|
+
const invalidOutboxDir = join11(pendingOutboxDir, "invalid");
|
|
10515
10788
|
const pendingRunCompletionDir = runtimeStatusRunCompletionDir(config);
|
|
10516
|
-
const invalidRunCompletionDir =
|
|
10789
|
+
const invalidRunCompletionDir = join11(pendingRunCompletionDir, "invalid");
|
|
10517
10790
|
return {
|
|
10518
10791
|
managedWorkspacesRoot: root,
|
|
10519
10792
|
managedWorkdirCount: workdirs.length,
|
|
@@ -10637,8 +10910,8 @@ function summarizeAmasterRuntimeVersionDrift(input = {}) {
|
|
|
10637
10910
|
// src/amaster-runtime-daemon/workspace-status.mjs
|
|
10638
10911
|
import { spawnSync as spawnSync4 } from "node:child_process";
|
|
10639
10912
|
import { createHash as createHash11 } from "node:crypto";
|
|
10640
|
-
import { existsSync as existsSync10, readdirSync as readdirSync8, readFileSync as
|
|
10641
|
-
import { basename as basename5, extname, isAbsolute as isAbsolute5, join as
|
|
10913
|
+
import { existsSync as existsSync10, readdirSync as readdirSync8, readFileSync as readFileSync10, statSync as statSync7 } from "node:fs";
|
|
10914
|
+
import { basename as basename5, extname, isAbsolute as isAbsolute5, join as join12, relative as relative5, resolve as resolve8 } from "node:path";
|
|
10642
10915
|
var WORKSPACE_RUNTIME_SERVICES_FILENAME = ".amaster-runtime-services.json";
|
|
10643
10916
|
var ARTIFACT_EXTENSIONS = /* @__PURE__ */ new Map([
|
|
10644
10917
|
[".md", "markdown"],
|
|
@@ -10707,7 +10980,7 @@ function sanitizeTrackedChange(line) {
|
|
|
10707
10980
|
return isSafeRelativePath(path) ? line : null;
|
|
10708
10981
|
}
|
|
10709
10982
|
function sha256File(filePath) {
|
|
10710
|
-
return createHash11("sha256").update(
|
|
10983
|
+
return createHash11("sha256").update(readFileSync10(filePath)).digest("hex");
|
|
10711
10984
|
}
|
|
10712
10985
|
function artifactHashCacheKey(relativePath, stat) {
|
|
10713
10986
|
return `${relativePath}\0${stat.size}\0${stat.mtimeMs}`;
|
|
@@ -10756,7 +11029,7 @@ function scanArtifactCandidates(cwd, opts = {}) {
|
|
|
10756
11029
|
if (entry.name.startsWith(".") && entry.name !== ".amaster-runtime.json") {
|
|
10757
11030
|
if (entry.name === ".git") continue;
|
|
10758
11031
|
}
|
|
10759
|
-
const fullPath =
|
|
11032
|
+
const fullPath = join12(current, entry.name);
|
|
10760
11033
|
const relativePath = normalizeRelativePath(root, fullPath);
|
|
10761
11034
|
if (!isSafeRelativePath(relativePath)) continue;
|
|
10762
11035
|
if (basename5(relativePath) === ".amaster-runtime.json") continue;
|
|
@@ -10834,10 +11107,10 @@ function sanitizeRuntimeService(entry) {
|
|
|
10834
11107
|
};
|
|
10835
11108
|
}
|
|
10836
11109
|
function readRuntimeServicesSnapshot(cwd) {
|
|
10837
|
-
const snapshotPath =
|
|
11110
|
+
const snapshotPath = join12(resolve8(cwd), WORKSPACE_RUNTIME_SERVICES_FILENAME);
|
|
10838
11111
|
if (!existsSync10(snapshotPath)) return [];
|
|
10839
11112
|
try {
|
|
10840
|
-
const parsed = JSON.parse(
|
|
11113
|
+
const parsed = JSON.parse(readFileSync10(snapshotPath, "utf8"));
|
|
10841
11114
|
const rawServices = Array.isArray(parsed) ? parsed : Array.isArray(parsed?.services) ? parsed.services : [];
|
|
10842
11115
|
return rawServices.map((entry) => sanitizeRuntimeService(entry)).filter((entry) => entry !== null).slice(0, 50);
|
|
10843
11116
|
} catch {
|
|
@@ -11069,16 +11342,16 @@ async function executeBrowserSessionCommand(command, dependencies = {}) {
|
|
|
11069
11342
|
// src/amaster-runtime-daemon/browser-session-broker.mjs
|
|
11070
11343
|
import { createHash as createHash12 } from "node:crypto";
|
|
11071
11344
|
import {
|
|
11072
|
-
chmodSync as
|
|
11345
|
+
chmodSync as chmodSync5,
|
|
11073
11346
|
existsSync as existsSync11,
|
|
11074
11347
|
lstatSync as lstatSync5,
|
|
11075
11348
|
mkdirSync as mkdirSync7,
|
|
11076
|
-
readFileSync as
|
|
11077
|
-
rmSync as
|
|
11349
|
+
readFileSync as readFileSync11,
|
|
11350
|
+
rmSync as rmSync6,
|
|
11078
11351
|
statSync as statSync8,
|
|
11079
|
-
writeFileSync as
|
|
11352
|
+
writeFileSync as writeFileSync8
|
|
11080
11353
|
} from "node:fs";
|
|
11081
|
-
import { dirname as
|
|
11354
|
+
import { dirname as dirname8, join as join13, relative as relative6, resolve as resolve9 } from "node:path";
|
|
11082
11355
|
var MARKER_NAME = ".amaster-browser-session.json";
|
|
11083
11356
|
var HUMAN_LEASE_HARD_CAP_MS = 2 * 60 * 60 * 1e3;
|
|
11084
11357
|
function brokerError(code) {
|
|
@@ -11103,7 +11376,7 @@ function ensurePrivateRoot(stateRoot) {
|
|
|
11103
11376
|
throw brokerError("browser_session_profile_root_symlink");
|
|
11104
11377
|
}
|
|
11105
11378
|
mkdirSync7(root, { recursive: true, mode: 448 });
|
|
11106
|
-
|
|
11379
|
+
chmodSync5(root, 448);
|
|
11107
11380
|
if (lstatSync5(root).isSymbolicLink()) {
|
|
11108
11381
|
throw brokerError("browser_session_profile_root_symlink");
|
|
11109
11382
|
}
|
|
@@ -11125,7 +11398,7 @@ function expectedOwner(payload) {
|
|
|
11125
11398
|
function exactProfile(stateRoot, payload, { create = false } = {}) {
|
|
11126
11399
|
const root = ensurePrivateRoot(stateRoot);
|
|
11127
11400
|
const profilePath = resolve9(root, profileName(payload));
|
|
11128
|
-
if (!pathWithin3(profilePath, root) ||
|
|
11401
|
+
if (!pathWithin3(profilePath, root) || dirname8(profilePath) !== root) {
|
|
11129
11402
|
throw brokerError("browser_session_profile_path_invalid");
|
|
11130
11403
|
}
|
|
11131
11404
|
if (existsSync11(profilePath) && lstatSync5(profilePath).isSymbolicLink()) {
|
|
@@ -11134,9 +11407,9 @@ function exactProfile(stateRoot, payload, { create = false } = {}) {
|
|
|
11134
11407
|
if (!existsSync11(profilePath)) {
|
|
11135
11408
|
if (!create) throw brokerError("browser_session_profile_not_found");
|
|
11136
11409
|
mkdirSync7(profilePath, { mode: 448 });
|
|
11137
|
-
|
|
11138
|
-
|
|
11139
|
-
|
|
11410
|
+
chmodSync5(profilePath, 448);
|
|
11411
|
+
writeFileSync8(
|
|
11412
|
+
join13(profilePath, MARKER_NAME),
|
|
11140
11413
|
`${JSON.stringify(expectedOwner(payload))}
|
|
11141
11414
|
`,
|
|
11142
11415
|
{ encoding: "utf8", mode: 384, flag: "wx" }
|
|
@@ -11147,7 +11420,7 @@ function exactProfile(stateRoot, payload, { create = false } = {}) {
|
|
|
11147
11420
|
}
|
|
11148
11421
|
let owner;
|
|
11149
11422
|
try {
|
|
11150
|
-
owner = JSON.parse(
|
|
11423
|
+
owner = JSON.parse(readFileSync11(join13(profilePath, MARKER_NAME), "utf8"));
|
|
11151
11424
|
} catch {
|
|
11152
11425
|
throw brokerError("browser_session_profile_owner_invalid");
|
|
11153
11426
|
}
|
|
@@ -11298,7 +11571,7 @@ function createBrowserSessionBroker({
|
|
|
11298
11571
|
await existing.context.close();
|
|
11299
11572
|
active.delete(payload.localOpaqueRef);
|
|
11300
11573
|
}
|
|
11301
|
-
|
|
11574
|
+
rmSync6(profilePath, { recursive: true, force: false });
|
|
11302
11575
|
return {
|
|
11303
11576
|
bindingId: payload.bindingId,
|
|
11304
11577
|
localOpaqueRef: payload.localOpaqueRef,
|
|
@@ -11327,7 +11600,7 @@ function createBrowserSessionBroker({
|
|
|
11327
11600
|
if (resolve9(payload.userDataDir) !== expectedPath) {
|
|
11328
11601
|
throw brokerError("browser_session_profile_path_invalid");
|
|
11329
11602
|
}
|
|
11330
|
-
const marker = JSON.parse(
|
|
11603
|
+
const marker = JSON.parse(readFileSync11(join13(expectedPath, MARKER_NAME), "utf8"));
|
|
11331
11604
|
if (marker.version !== 1 || typeof marker.provider !== "string" || !marker.provider.trim() || marker.companyId !== payload.companyId || marker.bindingId !== payload.bindingId || marker.localOpaqueRef !== payload.localOpaqueRef || marker.origin !== payload.origin) {
|
|
11332
11605
|
throw brokerError("browser_session_profile_owner_mismatch");
|
|
11333
11606
|
}
|
|
@@ -11377,7 +11650,7 @@ var source_acquisition_compatibility_default = {
|
|
|
11377
11650
|
};
|
|
11378
11651
|
|
|
11379
11652
|
// src/amaster-runtime-daemon.mjs
|
|
11380
|
-
var CONNECTOR_VERSION = "0.1.1-beta.
|
|
11653
|
+
var CONNECTOR_VERSION = "0.1.1-beta.82";
|
|
11381
11654
|
var CONNECTOR_CONTRACT_VERSION = "2026-06-04.v1";
|
|
11382
11655
|
var SOURCE_ACQUISITION_CAPABILITY = source_acquisition_compatibility_default.profileVersion;
|
|
11383
11656
|
var daemonRequire = createRequire(import.meta.url);
|
|
@@ -11421,7 +11694,7 @@ function resultOutboxPendingCount(config) {
|
|
|
11421
11694
|
try {
|
|
11422
11695
|
let pending = 0;
|
|
11423
11696
|
for (const file of readdirSync9(dir).filter((name) => name.endsWith(".json"))) {
|
|
11424
|
-
if (readValidResultOutboxEntryOrQuarantine(config, file,
|
|
11697
|
+
if (readValidResultOutboxEntryOrQuarantine(config, file, join14(dir, file))) {
|
|
11425
11698
|
pending += 1;
|
|
11426
11699
|
}
|
|
11427
11700
|
}
|
|
@@ -11433,17 +11706,17 @@ function resultOutboxPendingCount(config) {
|
|
|
11433
11706
|
function runCompletionStateDir(config) {
|
|
11434
11707
|
const explicit = readString(process.env.AMASTER_RUN_COMPLETION_STATE_DIR);
|
|
11435
11708
|
if (explicit) return resolve10(expandHomePath(explicit));
|
|
11436
|
-
return
|
|
11709
|
+
return join14(dirname9(stateFilePath(process.env)), "run-completion-state");
|
|
11437
11710
|
}
|
|
11438
11711
|
function runCompletionStateInvalidDir(config) {
|
|
11439
|
-
return
|
|
11712
|
+
return join14(runCompletionStateDir(config), "invalid");
|
|
11440
11713
|
}
|
|
11441
11714
|
function quarantineInvalidRunCompletionState(config, filePath, reason) {
|
|
11442
11715
|
const invalidDir = runCompletionStateInvalidDir(config);
|
|
11443
11716
|
mkdirSync8(invalidDir, { recursive: true, mode: 448 });
|
|
11444
|
-
const destination =
|
|
11717
|
+
const destination = join14(invalidDir, basename6(filePath));
|
|
11445
11718
|
try {
|
|
11446
|
-
|
|
11719
|
+
renameSync7(filePath, destination);
|
|
11447
11720
|
} catch {
|
|
11448
11721
|
copyFileSync2(filePath, destination);
|
|
11449
11722
|
unlinkSync2(filePath);
|
|
@@ -11498,7 +11771,7 @@ function resultOutboxActiveRunCommands(config) {
|
|
|
11498
11771
|
const outboxPending = resultOutboxPendingCount(config);
|
|
11499
11772
|
const entries = [];
|
|
11500
11773
|
for (const file of readdirSync9(dir).filter((name) => name.endsWith(".json")).sort()) {
|
|
11501
|
-
const entry = readValidResultOutboxEntryOrQuarantine(config, file,
|
|
11774
|
+
const entry = readValidResultOutboxEntryOrQuarantine(config, file, join14(dir, file));
|
|
11502
11775
|
if (!entry) continue;
|
|
11503
11776
|
const activeRun = asRecord(entry.activeRun);
|
|
11504
11777
|
const commandId = readString(activeRun.commandId) ?? readString(entry.commandId);
|
|
@@ -11533,7 +11806,7 @@ function resultOutboxFailedRunCommands(config) {
|
|
|
11533
11806
|
for (const file of readdirSync9(dir).filter((name) => name.endsWith(".json")).sort().slice(-100)) {
|
|
11534
11807
|
let entry;
|
|
11535
11808
|
try {
|
|
11536
|
-
entry = asRecord(JSON.parse(
|
|
11809
|
+
entry = asRecord(JSON.parse(readFileSync12(join14(dir, file), "utf8")));
|
|
11537
11810
|
} catch {
|
|
11538
11811
|
continue;
|
|
11539
11812
|
}
|
|
@@ -11600,7 +11873,7 @@ function safeExpandPath(value) {
|
|
|
11600
11873
|
}
|
|
11601
11874
|
function safeJsonObjectFromFile(filePath) {
|
|
11602
11875
|
try {
|
|
11603
|
-
const parsed = JSON.parse(
|
|
11876
|
+
const parsed = JSON.parse(readFileSync12(filePath, "utf8"));
|
|
11604
11877
|
return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : null;
|
|
11605
11878
|
} catch {
|
|
11606
11879
|
return null;
|
|
@@ -11643,10 +11916,10 @@ function safeSkillRootSummary(kind, source, pathValue) {
|
|
|
11643
11916
|
try {
|
|
11644
11917
|
for (const name of readdirSync9(pathValue)) {
|
|
11645
11918
|
if (name.startsWith(".")) continue;
|
|
11646
|
-
const skillDir =
|
|
11919
|
+
const skillDir = join14(pathValue, name);
|
|
11647
11920
|
try {
|
|
11648
11921
|
if (!statSync9(skillDir).isDirectory()) continue;
|
|
11649
|
-
if (!existsSync12(
|
|
11922
|
+
if (!existsSync12(join14(skillDir, "SKILL.md"))) continue;
|
|
11650
11923
|
skillCount += 1;
|
|
11651
11924
|
if (skillCount >= MAX_PI_CAPABILITY_SOURCE_ENTRIES) {
|
|
11652
11925
|
truncated = true;
|
|
@@ -11697,7 +11970,7 @@ function objectKeyCount(value) {
|
|
|
11697
11970
|
return value && typeof value === "object" && !Array.isArray(value) ? Object.keys(value).length : 0;
|
|
11698
11971
|
}
|
|
11699
11972
|
function defaultPiCodingAgentDir() {
|
|
11700
|
-
return
|
|
11973
|
+
return join14(homedir3(), ".pi", "agent");
|
|
11701
11974
|
}
|
|
11702
11975
|
function piCapabilitySourcesDiagnostics() {
|
|
11703
11976
|
const configuredPiCodingAgentDir = safeExpandPath(process.env.PI_CODING_AGENT_DIR);
|
|
@@ -11706,14 +11979,14 @@ function piCapabilitySourcesDiagnostics() {
|
|
|
11706
11979
|
const configuredPiAgentHome = safeExpandPath(process.env.PI_AGENT_HOME);
|
|
11707
11980
|
const piAgentHome = configuredPiAgentHome ?? piCodingAgentDir;
|
|
11708
11981
|
const piAgentHomeSource = configuredPiAgentHome ? "PI_AGENT_HOME" : piCodingAgentDirSource;
|
|
11709
|
-
const userSkillsPath = piAgentHome ?
|
|
11982
|
+
const userSkillsPath = piAgentHome ? join14(piAgentHome, "skills") : null;
|
|
11710
11983
|
const configuredMarketplaceSkillsPath = safeExpandPath(
|
|
11711
11984
|
process.env.PI_AGENT_MARKETPLACE_SKILLS_DIR
|
|
11712
11985
|
);
|
|
11713
|
-
const marketplaceSkillsPath = configuredMarketplaceSkillsPath ?? (piAgentHome ?
|
|
11986
|
+
const marketplaceSkillsPath = configuredMarketplaceSkillsPath ?? (piAgentHome ? join14(piAgentHome, "marketplace", "skills") : null);
|
|
11714
11987
|
const builtinSkillsPath = safeExpandPath(process.env.PI_AGENT_BUILTIN_SKILLS_DIR) ?? safeExpandPath(process.env.AMASTER_BUILTIN_SKILLS);
|
|
11715
|
-
const mcpConfigPath = safeExpandPath(process.env.PI_AGENT_MCP_SERVERS_FILE) ?? (piAgentHome ?
|
|
11716
|
-
const settingsConfigPath = piCodingAgentDir ?
|
|
11988
|
+
const mcpConfigPath = safeExpandPath(process.env.PI_AGENT_MCP_SERVERS_FILE) ?? (piAgentHome ? join14(piAgentHome, "mcp.json") : null);
|
|
11989
|
+
const settingsConfigPath = piCodingAgentDir ? join14(piCodingAgentDir, "settings.json") : null;
|
|
11717
11990
|
const skillRoots = [
|
|
11718
11991
|
safeSkillRootSummary("user", `${piAgentHomeSource}/skills`, userSkillsPath),
|
|
11719
11992
|
safeSkillRootSummary(
|
|
@@ -11833,7 +12106,7 @@ function buildExecutorReadiness(config) {
|
|
|
11833
12106
|
function sourceAcquisitionPackageMetadata(packageName) {
|
|
11834
12107
|
const agentDir = readString(process.env.PI_CODING_AGENT_DIR ?? process.env.PI_AGENT_HOME);
|
|
11835
12108
|
if (!agentDir) return null;
|
|
11836
|
-
const packagePath =
|
|
12109
|
+
const packagePath = join14(
|
|
11837
12110
|
resolve10(expandHomePath(agentDir)),
|
|
11838
12111
|
"npm",
|
|
11839
12112
|
"node_modules",
|
|
@@ -12220,7 +12493,7 @@ AMASTER_WORKSPACE_ALLOWLIST=${quoteShell(config.workspaceBindings.join(","))}
|
|
|
12220
12493
|
AMASTER_EXECUTORS=${quoteShell(executorEnv)}
|
|
12221
12494
|
AMASTER_CAPABILITIES=${quoteShell(config.capabilities.join(","))}
|
|
12222
12495
|
AMASTER_NETWORK_DOMAINS=${quoteShell(config.networkDomains.join(","))}
|
|
12223
|
-
AMASTER_DAEMON_STATE_FILE=${quoteShell(
|
|
12496
|
+
AMASTER_DAEMON_STATE_FILE=${quoteShell(join14(homedir3(), ".amaster-employee", "runtime-connector-state.json"))}
|
|
12224
12497
|
EOF
|
|
12225
12498
|
|
|
12226
12499
|
set -a
|
|
@@ -12676,7 +12949,7 @@ async function sourceAcquisitionRuntimeProfile(config, command) {
|
|
|
12676
12949
|
const stateRoot = resolve10(config.browserSessionStateRoot);
|
|
12677
12950
|
const userDataDir = resolve10(stateRoot, profileName2);
|
|
12678
12951
|
if (!pathWithin2(userDataDir, stateRoot)) throw new Error("source_acquisition_browser_profile_invalid");
|
|
12679
|
-
const markerPath =
|
|
12952
|
+
const markerPath = join14(userDataDir, ".amaster-browser-session.json");
|
|
12680
12953
|
if (!existsSync12(userDataDir) || lstatSync6(userDataDir).isSymbolicLink() || !lstatSync6(userDataDir).isDirectory() || !existsSync12(markerPath) || lstatSync6(markerPath).isSymbolicLink()) throw new Error("source_acquisition_browser_profile_invalid");
|
|
12681
12954
|
const marker = readJsonFile2(markerPath);
|
|
12682
12955
|
if (marker.version !== 1 || marker.companyId !== companyId || marker.bindingId !== bindingId || marker.localOpaqueRef !== localOpaqueRef || !readString(marker.provider) || marker.origin !== exactOrigin || Object.keys(marker).length !== 6) {
|
|
@@ -12695,7 +12968,7 @@ async function sourceAcquisitionRuntimeProfile(config, command) {
|
|
|
12695
12968
|
}
|
|
12696
12969
|
function readJsonFile2(filePath) {
|
|
12697
12970
|
try {
|
|
12698
|
-
const parsed = JSON.parse(
|
|
12971
|
+
const parsed = JSON.parse(readFileSync12(filePath, "utf8"));
|
|
12699
12972
|
return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {};
|
|
12700
12973
|
} catch {
|
|
12701
12974
|
return {};
|
|
@@ -12754,8 +13027,8 @@ async function materializeAgentInstructionsBundle(config, command, workspace, bu
|
|
|
12754
13027
|
if (!content) continue;
|
|
12755
13028
|
const target = safeAgentInstructionMaterializationTarget(workspace, filePath);
|
|
12756
13029
|
if (!target) continue;
|
|
12757
|
-
mkdirSync8(
|
|
12758
|
-
|
|
13030
|
+
mkdirSync8(dirname9(target.targetPath), { recursive: true });
|
|
13031
|
+
writeFileSync9(target.targetPath, content, "utf8");
|
|
12759
13032
|
materialized.push({
|
|
12760
13033
|
path: target.relativePath,
|
|
12761
13034
|
byteSize: Buffer.byteLength(content, "utf8")
|
|
@@ -12782,7 +13055,7 @@ function wikiTreePathForCommand(command, workspaceBindings) {
|
|
|
12782
13055
|
const candidates = [];
|
|
12783
13056
|
if (root.endsWith("paperclipai.plugin-llm-wiki")) candidates.push(root);
|
|
12784
13057
|
if (basename6(root) === "plugin-data" && companyId) {
|
|
12785
|
-
candidates.push(
|
|
13058
|
+
candidates.push(join14(root, companyId, "paperclipai.plugin-llm-wiki"));
|
|
12786
13059
|
}
|
|
12787
13060
|
for (const candidate of candidates) {
|
|
12788
13061
|
try {
|
|
@@ -12926,18 +13199,18 @@ function buildExecutorEnv(config, command, workspace) {
|
|
|
12926
13199
|
};
|
|
12927
13200
|
}
|
|
12928
13201
|
function preparePiModelCallProfile(commandId, baseEnv, options = {}) {
|
|
12929
|
-
const profileRoot = mkdtempSync(
|
|
12930
|
-
const home =
|
|
12931
|
-
const sessionsDir =
|
|
12932
|
-
const tempDir =
|
|
13202
|
+
const profileRoot = mkdtempSync(join14(tmpdir(), "amaster-pi-model-call-"));
|
|
13203
|
+
const home = join14(profileRoot, "home");
|
|
13204
|
+
const sessionsDir = join14(profileRoot, "sessions");
|
|
13205
|
+
const tempDir = join14(profileRoot, "tmp");
|
|
12933
13206
|
for (const directory of [home, sessionsDir, tempDir]) {
|
|
12934
13207
|
mkdirSync8(directory, { recursive: true, mode: 448 });
|
|
12935
13208
|
}
|
|
12936
13209
|
try {
|
|
12937
13210
|
const extensionArgs = [];
|
|
12938
13211
|
if (options.responseContract) {
|
|
12939
|
-
const extensionPath =
|
|
12940
|
-
|
|
13212
|
+
const extensionPath = join14(profileRoot, "model-call-output-contract.js");
|
|
13213
|
+
writeFileSync9(
|
|
12941
13214
|
extensionPath,
|
|
12942
13215
|
modelCallOutputContractExtensionSource(options.responseContract.maxOutputTokens),
|
|
12943
13216
|
{ mode: 384 }
|
|
@@ -12957,12 +13230,12 @@ function preparePiModelCallProfile(commandId, baseEnv, options = {}) {
|
|
|
12957
13230
|
}
|
|
12958
13231
|
};
|
|
12959
13232
|
} catch (error) {
|
|
12960
|
-
|
|
13233
|
+
rmSync7(profileRoot, { recursive: true, force: true });
|
|
12961
13234
|
throw error;
|
|
12962
13235
|
}
|
|
12963
13236
|
}
|
|
12964
13237
|
function cleanupPiModelCallProfile(profile) {
|
|
12965
|
-
if (profile?.profileRoot)
|
|
13238
|
+
if (profile?.profileRoot) rmSync7(profile.profileRoot, { recursive: true, force: true });
|
|
12966
13239
|
}
|
|
12967
13240
|
function splitExtraArgs(value) {
|
|
12968
13241
|
return splitList(value).flatMap((entry) => entry.split(/\s+/).filter(Boolean));
|
|
@@ -13725,7 +13998,7 @@ function walkManagedWorkdirs(root) {
|
|
|
13725
13998
|
}
|
|
13726
13999
|
for (const entry of entries) {
|
|
13727
14000
|
if (!entry.isDirectory()) continue;
|
|
13728
|
-
const fullPath =
|
|
14001
|
+
const fullPath = join14(current, entry.name);
|
|
13729
14002
|
if (entry.name === "workdir" && existsSync12(workspaceManifestPath(fullPath))) {
|
|
13730
14003
|
workdirs.push(fullPath);
|
|
13731
14004
|
continue;
|
|
@@ -13862,6 +14135,7 @@ function runExecutor(command, args, options) {
|
|
|
13862
14135
|
let closeCode = null;
|
|
13863
14136
|
let closeSignal = null;
|
|
13864
14137
|
let spawnError = null;
|
|
14138
|
+
let spawnErrorCode = null;
|
|
13865
14139
|
let outputDrainForcedClosed = false;
|
|
13866
14140
|
let killedWorkspaceResidents = [];
|
|
13867
14141
|
let stoppedResidentDrainUntil = 0;
|
|
@@ -13983,6 +14257,7 @@ function runExecutor(command, args, options) {
|
|
|
13983
14257
|
signal: closeSignal,
|
|
13984
14258
|
timedOut: stopReason === "timeout",
|
|
13985
14259
|
spawnError,
|
|
14260
|
+
spawnErrorCode,
|
|
13986
14261
|
cancelled: aborted
|
|
13987
14262
|
});
|
|
13988
14263
|
};
|
|
@@ -14092,6 +14367,7 @@ function runExecutor(command, args, options) {
|
|
|
14092
14367
|
});
|
|
14093
14368
|
child.on("error", (err) => {
|
|
14094
14369
|
spawnError = err.message;
|
|
14370
|
+
spawnErrorCode = sourceAcquisitionSpawnErrno(err.code);
|
|
14095
14371
|
});
|
|
14096
14372
|
child.on("exit", (code, signal) => {
|
|
14097
14373
|
childExited = true;
|
|
@@ -15392,10 +15668,10 @@ async function completeCommand(config, command, status, result3, error) {
|
|
|
15392
15668
|
function resultOutboxDir(config) {
|
|
15393
15669
|
const explicit = readString(process.env.AMASTER_RESULT_OUTBOX_DIR);
|
|
15394
15670
|
if (explicit) return resolve10(expandHomePath(explicit));
|
|
15395
|
-
return
|
|
15671
|
+
return join14(dirname9(stateFilePath(process.env)), "result-outbox");
|
|
15396
15672
|
}
|
|
15397
15673
|
function resultOutboxInvalidDir(config) {
|
|
15398
|
-
return
|
|
15674
|
+
return join14(resultOutboxDir(config), "invalid");
|
|
15399
15675
|
}
|
|
15400
15676
|
function writeResultOutboxEntry(config, entry) {
|
|
15401
15677
|
const dir = resultOutboxDir(config);
|
|
@@ -15407,16 +15683,16 @@ function writeResultOutboxEntry(config, entry) {
|
|
|
15407
15683
|
lastAttemptAt: null,
|
|
15408
15684
|
...entry
|
|
15409
15685
|
};
|
|
15410
|
-
|
|
15686
|
+
writeFileSync9(join14(dir, resultOutboxFileName(entry.commandId)), `${JSON.stringify(body, null, 2)}
|
|
15411
15687
|
`, { mode: 384 });
|
|
15412
15688
|
}
|
|
15413
15689
|
function moveResultOutboxEntryToInvalid(config, file, fullPath, reason, detail, original) {
|
|
15414
15690
|
const invalidDir = resultOutboxInvalidDir(config);
|
|
15415
15691
|
mkdirSync8(invalidDir, { recursive: true });
|
|
15416
|
-
const invalidPath =
|
|
15692
|
+
const invalidPath = join14(invalidDir, file);
|
|
15417
15693
|
if (original === void 0) {
|
|
15418
15694
|
try {
|
|
15419
|
-
|
|
15695
|
+
renameSync7(fullPath, invalidPath);
|
|
15420
15696
|
} catch {
|
|
15421
15697
|
copyFileSync2(fullPath, invalidPath);
|
|
15422
15698
|
unlinkSync2(fullPath);
|
|
@@ -15429,14 +15705,14 @@ function moveResultOutboxEntryToInvalid(config, file, fullPath, reason, detail,
|
|
|
15429
15705
|
...detail ? { detail: truncateText(detail, 1e3) } : {},
|
|
15430
15706
|
original
|
|
15431
15707
|
};
|
|
15432
|
-
|
|
15708
|
+
writeFileSync9(invalidPath, `${JSON.stringify(evidence, null, 2)}
|
|
15433
15709
|
`, { mode: 384 });
|
|
15434
15710
|
unlinkSync2(fullPath);
|
|
15435
15711
|
}
|
|
15436
15712
|
function readValidResultOutboxEntryOrQuarantine(config, file, fullPath) {
|
|
15437
15713
|
let entry;
|
|
15438
15714
|
try {
|
|
15439
|
-
entry = JSON.parse(
|
|
15715
|
+
entry = JSON.parse(readFileSync12(fullPath, "utf8"));
|
|
15440
15716
|
} catch (err) {
|
|
15441
15717
|
const message = err instanceof Error ? err.message : String(err);
|
|
15442
15718
|
moveResultOutboxEntryToInvalid(config, file, fullPath, "malformed_result_outbox_json", message);
|
|
@@ -15466,7 +15742,7 @@ function updateResultOutboxAttempt(fullPath, entry, err) {
|
|
|
15466
15742
|
...typeof err?.httpStatus === "number" ? { httpStatus: err.httpStatus } : {},
|
|
15467
15743
|
lastError: truncateText(err instanceof Error ? err.message : String(err), 1e3)
|
|
15468
15744
|
};
|
|
15469
|
-
|
|
15745
|
+
writeFileSync9(fullPath, `${JSON.stringify(next, null, 2)}
|
|
15470
15746
|
`, { mode: 384 });
|
|
15471
15747
|
return next;
|
|
15472
15748
|
}
|
|
@@ -15480,8 +15756,8 @@ function quarantineResultOutboxEntry(config, fullPath, file, entry, reason, err)
|
|
|
15480
15756
|
...typeof err?.httpStatus === "number" ? { httpStatus: err.httpStatus } : {},
|
|
15481
15757
|
lastError: truncateText(err instanceof Error ? err.message : String(err), 1e3)
|
|
15482
15758
|
};
|
|
15483
|
-
const invalidPath =
|
|
15484
|
-
|
|
15759
|
+
const invalidPath = join14(invalidDir, file);
|
|
15760
|
+
writeFileSync9(invalidPath, `${JSON.stringify(body, null, 2)}
|
|
15485
15761
|
`, { mode: 384 });
|
|
15486
15762
|
try {
|
|
15487
15763
|
unlinkSync2(fullPath);
|
|
@@ -15499,7 +15775,7 @@ async function flushResultOutbox(config) {
|
|
|
15499
15775
|
const files = readdirSync9(dir).filter((name) => name.endsWith(".json")).sort();
|
|
15500
15776
|
let completed = 0;
|
|
15501
15777
|
for (const file of files) {
|
|
15502
|
-
const fullPath =
|
|
15778
|
+
const fullPath = join14(dir, file);
|
|
15503
15779
|
const entry = readValidResultOutboxEntryOrQuarantine(config, file, fullPath);
|
|
15504
15780
|
if (!entry) continue;
|
|
15505
15781
|
try {
|
|
@@ -15696,7 +15972,7 @@ async function materializeIssueAttachments(config, command, workspace) {
|
|
|
15696
15972
|
runtimeAuth,
|
|
15697
15973
|
issueId
|
|
15698
15974
|
);
|
|
15699
|
-
const targetDir =
|
|
15975
|
+
const targetDir = join14(workspace.cwd, "input-attachments");
|
|
15700
15976
|
mkdirSync8(targetDir, { recursive: true });
|
|
15701
15977
|
const usedFilenames = /* @__PURE__ */ new Set();
|
|
15702
15978
|
const materialized = [];
|
|
@@ -15711,9 +15987,9 @@ async function materializeIssueAttachments(config, command, workspace) {
|
|
|
15711
15987
|
filename = `${stem}-${index + 1}${ext}`;
|
|
15712
15988
|
}
|
|
15713
15989
|
usedFilenames.add(filename);
|
|
15714
|
-
const targetPath =
|
|
15990
|
+
const targetPath = join14(targetDir, filename);
|
|
15715
15991
|
const body = await runtimeApiBuffer(runtimeAuth, contentPath);
|
|
15716
|
-
|
|
15992
|
+
writeFileSync9(targetPath, body);
|
|
15717
15993
|
const attachmentId = readString(attachment.id);
|
|
15718
15994
|
const actualSha256 = createHash13("sha256").update(body).digest("hex");
|
|
15719
15995
|
const lineageCandidates = lineageCandidatesByAttachmentId.get(attachmentId) ?? [];
|
|
@@ -15787,8 +16063,8 @@ async function materializeRequiredArtifactInputs(config, command, workspace) {
|
|
|
15787
16063
|
if (manifest.version !== 1 || !Array.isArray(manifest.entries)) {
|
|
15788
16064
|
throw new Error("artifact_input_manifest_invalid: expected version 1 entries array");
|
|
15789
16065
|
}
|
|
15790
|
-
const targetRoot =
|
|
15791
|
-
|
|
16066
|
+
const targetRoot = join14(workspace.cwd, "input-artifacts");
|
|
16067
|
+
rmSync7(targetRoot, { recursive: true, force: true });
|
|
15792
16068
|
mkdirSync8(targetRoot, { recursive: true });
|
|
15793
16069
|
const usedPaths = /* @__PURE__ */ new Set();
|
|
15794
16070
|
const materialized = [];
|
|
@@ -15818,18 +16094,18 @@ async function materializeRequiredArtifactInputs(config, command, workspace) {
|
|
|
15818
16094
|
id: attachmentId,
|
|
15819
16095
|
originalFilename: readString(entry.originalFilename)
|
|
15820
16096
|
}, index);
|
|
15821
|
-
let relativePath =
|
|
16097
|
+
let relativePath = join14("input-artifacts", sourceDir, filename).split(/[\\/]+/).join("/");
|
|
15822
16098
|
if (usedPaths.has(relativePath)) {
|
|
15823
16099
|
const ext = extname2(filename);
|
|
15824
16100
|
const stem = ext ? filename.slice(0, -ext.length) : filename;
|
|
15825
16101
|
filename = `${stem}-${index + 1}${ext}`;
|
|
15826
|
-
relativePath =
|
|
16102
|
+
relativePath = join14("input-artifacts", sourceDir, filename).split(/[\\/]+/).join("/");
|
|
15827
16103
|
}
|
|
15828
16104
|
usedPaths.add(relativePath);
|
|
15829
|
-
const targetPath =
|
|
15830
|
-
mkdirSync8(
|
|
15831
|
-
|
|
15832
|
-
|
|
16105
|
+
const targetPath = join14(workspace.cwd, relativePath);
|
|
16106
|
+
mkdirSync8(dirname9(targetPath), { recursive: true });
|
|
16107
|
+
writeFileSync9(targetPath, body);
|
|
16108
|
+
chmodSync6(targetPath, 292);
|
|
15833
16109
|
materialized.push({
|
|
15834
16110
|
id: attachmentId,
|
|
15835
16111
|
workProductId,
|
|
@@ -15848,9 +16124,9 @@ async function materializeRequiredArtifactInputs(config, command, workspace) {
|
|
|
15848
16124
|
version: 1,
|
|
15849
16125
|
entries: materialized.map(({ path: _path, relativePath, ...entry }) => ({ ...entry, path: relativePath }))
|
|
15850
16126
|
};
|
|
15851
|
-
const manifestPath =
|
|
15852
|
-
|
|
15853
|
-
|
|
16127
|
+
const manifestPath = join14(targetRoot, "artifact-input-manifest.json");
|
|
16128
|
+
writeFileSync9(manifestPath, JSON.stringify(localManifest, null, 2) + "\n");
|
|
16129
|
+
chmodSync6(manifestPath, 292);
|
|
15854
16130
|
updateWorkspaceManifest(workspaceManifestPath(workspace), { artifactInputManifest: localManifest });
|
|
15855
16131
|
await ingestLog(config, command, "system", "info", `Materialized ${materialized.length} required artifact input(s) into the execution workspace`, {
|
|
15856
16132
|
artifactInputCount: materialized.length,
|
|
@@ -15859,12 +16135,12 @@ async function materializeRequiredArtifactInputs(config, command, workspace) {
|
|
|
15859
16135
|
return materialized;
|
|
15860
16136
|
}
|
|
15861
16137
|
function issueCheckpointDir(workspace) {
|
|
15862
|
-
return
|
|
16138
|
+
return join14(dirname9(workspace.runDir), "checkpoint");
|
|
15863
16139
|
}
|
|
15864
16140
|
async function clearIssueCheckpoint(config, command, workspace, reason) {
|
|
15865
16141
|
const checkpointDir = issueCheckpointDir(workspace);
|
|
15866
16142
|
if (!existsSync12(checkpointDir)) return false;
|
|
15867
|
-
|
|
16143
|
+
rmSync7(checkpointDir, { recursive: true, force: true });
|
|
15868
16144
|
await ingestLog(config, command, "system", "info", "Cleared issue continuation checkpoint", { reason });
|
|
15869
16145
|
return true;
|
|
15870
16146
|
}
|
|
@@ -15877,28 +16153,28 @@ function safeCheckpointRelativePath(rawPath) {
|
|
|
15877
16153
|
return normalized;
|
|
15878
16154
|
}
|
|
15879
16155
|
function hashFileSha256(filePath) {
|
|
15880
|
-
return createHash13("sha256").update(
|
|
16156
|
+
return createHash13("sha256").update(readFileSync12(filePath)).digest("hex");
|
|
15881
16157
|
}
|
|
15882
16158
|
async function materializeIssueCheckpoint(config, command, workspace) {
|
|
15883
16159
|
const checkpointDir = issueCheckpointDir(workspace);
|
|
15884
|
-
const manifestPath =
|
|
16160
|
+
const manifestPath = join14(checkpointDir, "manifest.json");
|
|
15885
16161
|
if (!existsSync12(manifestPath)) return [];
|
|
15886
16162
|
let manifest;
|
|
15887
16163
|
try {
|
|
15888
|
-
manifest = asRecord(JSON.parse(
|
|
16164
|
+
manifest = asRecord(JSON.parse(readFileSync12(manifestPath, "utf8")));
|
|
15889
16165
|
} catch (err) {
|
|
15890
|
-
|
|
16166
|
+
rmSync7(checkpointDir, { recursive: true, force: true });
|
|
15891
16167
|
throw new Error(`invalid issue checkpoint manifest: ${err instanceof Error ? err.message : String(err)}`);
|
|
15892
16168
|
}
|
|
15893
16169
|
const expiresAt = Date.parse(readString(manifest.expiresAt) ?? "");
|
|
15894
16170
|
if (!Number.isFinite(expiresAt) || expiresAt <= Date.now() || readString(manifest.issueId) !== commandIssueId(command)) {
|
|
15895
|
-
|
|
16171
|
+
rmSync7(checkpointDir, { recursive: true, force: true });
|
|
15896
16172
|
return [];
|
|
15897
16173
|
}
|
|
15898
16174
|
try {
|
|
15899
16175
|
const files = Array.isArray(manifest.files) ? manifest.files : [];
|
|
15900
16176
|
if (files.length > 20) throw new Error("issue checkpoint manifest exceeds the limit of 20 files");
|
|
15901
|
-
const filesRoot = realpathSync5(
|
|
16177
|
+
const filesRoot = realpathSync5(join14(checkpointDir, "files"));
|
|
15902
16178
|
const workspaceRoot = realpathSync5(workspace.cwd);
|
|
15903
16179
|
const validated = [];
|
|
15904
16180
|
let totalBytes = 0;
|
|
@@ -15936,8 +16212,8 @@ async function materializeIssueCheckpoint(config, command, workspace) {
|
|
|
15936
16212
|
} catch (err) {
|
|
15937
16213
|
if (err?.code !== "ENOENT") throw err;
|
|
15938
16214
|
}
|
|
15939
|
-
mkdirSync8(
|
|
15940
|
-
const targetParent = realpathSync5(
|
|
16215
|
+
mkdirSync8(dirname9(target), { recursive: true });
|
|
16216
|
+
const targetParent = realpathSync5(dirname9(target));
|
|
15941
16217
|
if (!pathWithin2(targetParent, workspaceRoot)) {
|
|
15942
16218
|
throw new Error(`issue checkpoint target escapes its workspace: ${relativePath}`);
|
|
15943
16219
|
}
|
|
@@ -15965,8 +16241,8 @@ async function materializeIssueCheckpoint(config, command, workspace) {
|
|
|
15965
16241
|
}
|
|
15966
16242
|
async function saveIssueCheckpoint(config, command, workspace, candidates) {
|
|
15967
16243
|
const checkpointDir = issueCheckpointDir(workspace);
|
|
15968
|
-
const filesDir =
|
|
15969
|
-
|
|
16244
|
+
const filesDir = join14(checkpointDir, "files");
|
|
16245
|
+
rmSync7(checkpointDir, { recursive: true, force: true });
|
|
15970
16246
|
mkdirSync8(filesDir, { recursive: true });
|
|
15971
16247
|
const files = [];
|
|
15972
16248
|
let totalBytes = 0;
|
|
@@ -15983,13 +16259,13 @@ async function saveIssueCheckpoint(config, command, workspace, candidates) {
|
|
|
15983
16259
|
if (byteSize <= 0 || totalBytes + byteSize > MAX_CHECKPOINT_BYTES) continue;
|
|
15984
16260
|
const target = resolve10(filesDir, relativePath);
|
|
15985
16261
|
if (!pathWithin2(target, filesDir)) continue;
|
|
15986
|
-
mkdirSync8(
|
|
16262
|
+
mkdirSync8(dirname9(target), { recursive: true });
|
|
15987
16263
|
copyFileSync2(ownedSource, target);
|
|
15988
16264
|
totalBytes += byteSize;
|
|
15989
16265
|
files.push({ path: relativePath, byteSize, sha256: hashFileSha256(ownedSource) });
|
|
15990
16266
|
}
|
|
15991
16267
|
if (files.length === 0) {
|
|
15992
|
-
|
|
16268
|
+
rmSync7(checkpointDir, { recursive: true, force: true });
|
|
15993
16269
|
return null;
|
|
15994
16270
|
}
|
|
15995
16271
|
const manifest = {
|
|
@@ -16001,7 +16277,7 @@ async function saveIssueCheckpoint(config, command, workspace, candidates) {
|
|
|
16001
16277
|
totalBytes,
|
|
16002
16278
|
files
|
|
16003
16279
|
};
|
|
16004
|
-
|
|
16280
|
+
writeFileSync9(join14(checkpointDir, "manifest.json"), `${JSON.stringify(manifest, null, 2)}
|
|
16005
16281
|
`);
|
|
16006
16282
|
await ingestLog(config, command, "system", "warn", `Saved ${files.length} required deliverable(s) for continuation recovery`, manifest);
|
|
16007
16283
|
return manifest;
|
|
@@ -16172,7 +16448,7 @@ async function executeRunCommand(config, command) {
|
|
|
16172
16448
|
executorCommand: invocation.command,
|
|
16173
16449
|
executorHome: workspace.executorHome,
|
|
16174
16450
|
runDir: workspace.runDir,
|
|
16175
|
-
runtimeCacheRoot:
|
|
16451
|
+
runtimeCacheRoot: join14(dirname9(config.daemonStateFile), "cache"),
|
|
16176
16452
|
cwd,
|
|
16177
16453
|
runtimeAuth: commandRuntimeAuth(command),
|
|
16178
16454
|
nativeSession: asRecord(asRecord(command.payload).nativeSession),
|
|
@@ -16600,7 +16876,24 @@ async function executeRunCommand(config, command) {
|
|
|
16600
16876
|
const succeeded = !cancelled && !hasOutputFlood && !hasArgumentAmplification && !hasMemoryLimit && (execution.exitCode === 0 || completionOutputStopped || repairedPiTerminalOutputStop) && !execution.timedOut && !execution.spawnError && !parsedErrorMessage;
|
|
16601
16877
|
const resultStderr = filterExecutionStderrForResult(executor.kind, execution.stderr);
|
|
16602
16878
|
const unsafeError = execution.timedOut ? `Executor timed out after ${config.executorTimeoutSeconds}s` : cancelled ? "Executor cancelled by AMaster control plane" : execution.spawnError ?? parsedErrorMessage ?? (succeeded ? null : `Executor exited with code ${execution.exitCode ?? "unknown"}`);
|
|
16603
|
-
const
|
|
16879
|
+
const sourceExecutionReceiptPath = readString(managedMcpProfile?.sourceAcquisitionExecutionReceiptPath);
|
|
16880
|
+
const sourceExecutionIdentity = asRecord(managedMcpProfile?.sourceAcquisitionExecutionIdentity);
|
|
16881
|
+
if (sourceExecutionReceiptPath && execution.spawnErrorCode) {
|
|
16882
|
+
try {
|
|
16883
|
+
updateSourceAcquisitionExecutionReceipt(
|
|
16884
|
+
sourceExecutionReceiptPath,
|
|
16885
|
+
sourceExecutionIdentity,
|
|
16886
|
+
{ spawnErrno: execution.spawnErrorCode }
|
|
16887
|
+
);
|
|
16888
|
+
} catch {
|
|
16889
|
+
}
|
|
16890
|
+
}
|
|
16891
|
+
const sourceExecutionFailure = sourceAcquisition && !succeeded ? classifySourceAcquisitionExecutionFailure({
|
|
16892
|
+
identity: sourceExecutionIdentity,
|
|
16893
|
+
receipt: sourceExecutionReceiptPath ? readSourceAcquisitionExecutionReceipt(sourceExecutionReceiptPath, sourceExecutionIdentity) : null,
|
|
16894
|
+
exitCode: execution.exitCode
|
|
16895
|
+
}) : null;
|
|
16896
|
+
const sourceErrorCode = sourceAcquisition ? execution.timedOut ? "source_acquisition_timeout" : cancelled ? "source_acquisition_cancelled" : hasOutputFlood ? "source_acquisition_output_flood" : hasMemoryLimit ? "source_acquisition_memory_limit" : execution.spawnError ? "source_acquisition_executor_unavailable" : succeeded ? null : sourceExecutionFailure?.failureCode ?? "source_acquisition_executor_failed" : null;
|
|
16604
16897
|
const error = sourceAcquisition ? sourceErrorCode : unsafeError;
|
|
16605
16898
|
const costUsage = parsedCostUsage(parsed.usage);
|
|
16606
16899
|
const cleanPiTerminalOutputStop = succeeded && (completionOutputStopped || repairedPiTerminalOutputStop) && execution.completionOutputType === "agent_end" && parsed.terminalEventType === "agent_end" && Number.isInteger(parsed.terminalEventIndex);
|
|
@@ -16651,7 +16944,8 @@ async function executeRunCommand(config, command) {
|
|
|
16651
16944
|
retentionVersion: sourceAcquisition.profile.retention,
|
|
16652
16945
|
attemptId: sourceAcquisition.profile.attemptId,
|
|
16653
16946
|
epoch: sourceAcquisition.profile.epoch
|
|
16654
|
-
}
|
|
16947
|
+
},
|
|
16948
|
+
...sourceExecutionFailure ? { sourceAcquisitionFailureV1: sourceExecutionFailure } : {}
|
|
16655
16949
|
} : hasArgumentAmplification ? {
|
|
16656
16950
|
stdout: "",
|
|
16657
16951
|
stderr: truncateText(resultStderr, 8e3)
|
|
@@ -16708,6 +17002,13 @@ async function executeRunCommand(config, command) {
|
|
|
16708
17002
|
}
|
|
16709
17003
|
} : {}
|
|
16710
17004
|
};
|
|
17005
|
+
if (sourceAcquisition && sourceErrorCode) {
|
|
17006
|
+
result3 = {
|
|
17007
|
+
...result3,
|
|
17008
|
+
errorCode: sourceErrorCode,
|
|
17009
|
+
errorFamily: "source_acquisition"
|
|
17010
|
+
};
|
|
17011
|
+
}
|
|
16711
17012
|
if (sourceAcquisition) {
|
|
16712
17013
|
execution.stdout = "";
|
|
16713
17014
|
execution.stderr = "";
|