@tangle-network/agent-runtime 0.337.1 → 0.338.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{activation-DMehb166.d.ts → activation-CsbNax2X.d.ts} +92 -4
- package/dist/activation-kbkAuSmY.js +889 -0
- package/dist/activation-kbkAuSmY.js.map +1 -0
- package/dist/agent.d.ts +1 -1
- package/dist/agent.js +3 -6
- package/dist/agent.js.map +1 -1
- package/dist/{bundle-BPGjESee.js → bundle-DM60AI2B.js} +2 -2
- package/dist/{bundle-BPGjESee.js.map → bundle-DM60AI2B.js.map} +1 -1
- package/dist/candidate-execution/index.d.ts +2 -2
- package/dist/candidate-execution/index.js +4 -5
- package/dist/candidate-execution/index.js.map +1 -1
- package/dist/content-digest-sBTLujlK.js +9 -0
- package/dist/content-digest-sBTLujlK.js.map +1 -0
- package/dist/{delegate-aC14Cww3.js → delegate-Se1YZKMb.js} +2 -2
- package/dist/{delegate-aC14Cww3.js.map → delegate-Se1YZKMb.js.map} +1 -1
- package/dist/{coordination-driver-Dg9a6qsm.js → driver-control-acknowledgers-T2a1Ouay.js} +4514 -4440
- package/dist/driver-control-acknowledgers-T2a1Ouay.js.map +1 -0
- package/dist/durable.d.ts +1 -1
- package/dist/durable.js +223 -227
- package/dist/durable.js.map +1 -1
- package/dist/{graph-Cfx711ES.js → graph-CY0wH838.js} +65 -18
- package/dist/graph-CY0wH838.js.map +1 -0
- package/dist/{graph-registry-DAI6KNXB.js → graph-registry-By0tUj4S.js} +16 -15
- package/dist/graph-registry-By0tUj4S.js.map +1 -0
- package/dist/{improvement-cycle-DHKcb_YW.js → improve-CWGBT13K.js} +75 -1220
- package/dist/improve-CWGBT13K.js.map +1 -0
- package/dist/index.d.ts +6 -6
- package/dist/index.js +10 -13
- package/dist/index.js.map +1 -1
- package/dist/{integrations-DopfCC2a.d.ts → integrations-6xttbPi9.d.ts} +3 -3
- package/dist/integrations-dFi-ALk7.js.map +1 -1
- package/dist/intelligence.d.ts +7 -94
- package/dist/intelligence.js +505 -13
- package/dist/intelligence.js.map +1 -1
- package/dist/kernel.d.ts +2 -2
- package/dist/kernel.js +13 -12
- package/dist/{loop-runner-bin-B86AiPBf.d.ts → loop-runner-bin-CFnrAHpl.d.ts} +2 -2
- package/dist/{loop-runner-bin-BSKBNC38.js → loop-runner-bin-CdPlhy9g.js} +3 -3
- package/dist/{loop-runner-bin-BSKBNC38.js.map → loop-runner-bin-CdPlhy9g.js.map} +1 -1
- package/dist/loop-runner-bin.d.ts +1 -1
- package/dist/loop-runner-bin.js +1 -1
- package/dist/mcp/bin.js +3 -3
- package/dist/mcp/bin.js.map +1 -1
- package/dist/mcp/index.d.ts +7 -3
- package/dist/mcp/index.js +6 -8
- package/dist/mcp/index.js.map +1 -1
- package/dist/{openai-tools-DHO2QS1q.d.ts → openai-tools-zh2I_uD7.d.ts} +2 -2
- package/dist/platform.d.ts +7 -2
- package/dist/platform.js +16 -8
- package/dist/platform.js.map +1 -1
- package/dist/{prepare-CER-ZkPp.js → prepare-Bt0IouPq.js} +1241 -586
- package/dist/prepare-Bt0IouPq.js.map +1 -0
- package/dist/{profile-gNUsHNIJ.js → profile-Do-5xO_D.js} +89 -3
- package/dist/profile-Do-5xO_D.js.map +1 -0
- package/dist/profiles.d.ts +1 -1
- package/dist/profiles.js +1 -3
- package/dist/profiles.js.map +1 -1
- package/dist/{protected-model-port-BhpQRTw-.d.ts → protected-model-port-DGxQ8_YM.d.ts} +3 -3
- package/dist/{provision-supervisor-72YFf-i_.js → provision-supervisor-0jMufp4h.js} +12 -9
- package/dist/provision-supervisor-0jMufp4h.js.map +1 -0
- package/dist/record-value-B6bwJxLa.js +12 -0
- package/dist/record-value-B6bwJxLa.js.map +1 -0
- package/dist/{run-layout-Cu8H7aeh.js → run-cancellation-BoW5Sg9Y.js} +174 -95
- package/dist/run-cancellation-BoW5Sg9Y.js.map +1 -0
- package/dist/{runtime-qFLOq1R9.js → runtime-D37zRSs7.js} +432 -684
- package/dist/runtime-D37zRSs7.js.map +1 -0
- package/dist/{sandbox-profile-compat-QTkLe1Z6.js → sandbox-profile-compat-xSoVtdWw.js} +690 -697
- package/dist/sandbox-profile-compat-xSoVtdWw.js.map +1 -0
- package/dist/search-executor-DmgUm5p7.js +1916 -0
- package/dist/search-executor-DmgUm5p7.js.map +1 -0
- package/dist/{server-_FldJ9Cl.js → server-DQHJszfk.js} +4 -4
- package/dist/server-DQHJszfk.js.map +1 -0
- package/dist/{search-executor-CGxvizHh.js → structural-rollout-DAvIE8mw.js} +2262 -3984
- package/dist/structural-rollout-DAvIE8mw.js.map +1 -0
- package/dist/{supervise-H4BTN6uA.js → supervise-WuPAwfPh.js} +7793 -5338
- package/dist/supervise-WuPAwfPh.js.map +1 -0
- package/dist/{supervisor-C27ne4yv.js → supervisor-CPG1I9UN.js} +27379 -27899
- package/dist/supervisor-CPG1I9UN.js.map +1 -0
- package/dist/testing.d.ts +226 -1
- package/dist/testing.js +13 -14
- package/dist/testing.js.map +1 -1
- package/dist/{top-app-BaMw1W2z.js → top-app-C55Wa7uy.js} +339 -337
- package/dist/top-app-C55Wa7uy.js.map +1 -0
- package/dist/tui/bin.js +1 -1
- package/dist/tui/index.d.ts +17 -15
- package/dist/tui/index.js +2 -2
- package/dist/{types-CupCBY-j.d.ts → types-CrNWif8-.d.ts} +17655 -17406
- package/dist/{workspace-streams-JLjh5DC6.d.ts → workspace-streams-BZZds1Fw.d.ts} +18 -16
- package/package.json +4 -4
- package/skills/agent-graphs/SKILL.md +10 -3
- package/skills/agent-graphs/references/authoring.md +17 -0
- package/skills/profile-authoring/SKILL.md +3 -3
- package/skills/supervise/SKILL.md +2 -2
- package/dist/activation-BgWVlVu2.js +0 -234
- package/dist/activation-BgWVlVu2.js.map +0 -1
- package/dist/coordination-driver-Dg9a6qsm.js.map +0 -1
- package/dist/graph-Cfx711ES.js.map +0 -1
- package/dist/graph-registry-DAI6KNXB.js.map +0 -1
- package/dist/improvement-cycle-DHKcb_YW.js.map +0 -1
- package/dist/prepare-CER-ZkPp.js.map +0 -1
- package/dist/profile-gNUsHNIJ.js.map +0 -1
- package/dist/protected-model-port-BuRsviSL.js +0 -766
- package/dist/protected-model-port-BuRsviSL.js.map +0 -1
- package/dist/provision-supervisor-72YFf-i_.js.map +0 -1
- package/dist/run-layout-Cu8H7aeh.js.map +0 -1
- package/dist/runtime-qFLOq1R9.js.map +0 -1
- package/dist/sandbox-profile-compat-QTkLe1Z6.js.map +0 -1
- package/dist/search-executor-CGxvizHh.js.map +0 -1
- package/dist/server-_FldJ9Cl.js.map +0 -1
- package/dist/supervise-H4BTN6uA.js.map +0 -1
- package/dist/supervisor-C27ne4yv.js.map +0 -1
- package/dist/top-app-BaMw1W2z.js.map +0 -1
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { m as ValidationError } from "./errors-DodWX-cb.js";
|
|
2
|
+
import { t as isRecord } from "./record-value-B6bwJxLa.js";
|
|
2
3
|
import { runTaskQueue } from "./task-queue.js";
|
|
3
4
|
import { agentCandidateArtifactRefSchema, canonicalCandidateBytes as canonicalCandidateBytes$1 } from "@tangle-network/agent-interface";
|
|
4
5
|
import { createHash, randomUUID } from "node:crypto";
|
|
@@ -233,9 +234,9 @@ function randomSuffix(len = 8) {
|
|
|
233
234
|
function randomUuid() {
|
|
234
235
|
return crypto.randomUUID();
|
|
235
236
|
}
|
|
236
|
-
/** Construct an AbortError. Downstream code pattern-matches on `err.name`. */
|
|
237
|
-
function abortError() {
|
|
238
|
-
const err =
|
|
237
|
+
/** Construct an AbortError carrying the abort reason's message. Downstream code pattern-matches on `err.name`. */
|
|
238
|
+
function abortError(reason) {
|
|
239
|
+
const err = new Error(reason instanceof Error ? reason.message : reason === void 0 ? "aborted" : String(reason));
|
|
239
240
|
err.name = "AbortError";
|
|
240
241
|
return err;
|
|
241
242
|
}
|
|
@@ -635,6 +636,16 @@ function fnv1a32Hex(text) {
|
|
|
635
636
|
return (h >>> 0).toString(16).padStart(8, "0");
|
|
636
637
|
}
|
|
637
638
|
//#endregion
|
|
639
|
+
//#region src/path-control-characters.ts
|
|
640
|
+
/** Whether a serialized field contains an ASCII control or delete character. */
|
|
641
|
+
function hasControlCharacter(value) {
|
|
642
|
+
for (let index = 0; index < value.length; index++) {
|
|
643
|
+
const code = value.charCodeAt(index);
|
|
644
|
+
if (code < 32 || code === 127) return true;
|
|
645
|
+
}
|
|
646
|
+
return false;
|
|
647
|
+
}
|
|
648
|
+
//#endregion
|
|
638
649
|
//#region src/candidate-execution/digest.ts
|
|
639
650
|
/** Use native hashing for workspace archives. */
|
|
640
651
|
function sha256Bytes$1(bytes) {
|
|
@@ -1035,170 +1046,609 @@ function isWellFormedUnicode(value) {
|
|
|
1035
1046
|
return true;
|
|
1036
1047
|
}
|
|
1037
1048
|
//#endregion
|
|
1038
|
-
//#region src/candidate-execution/
|
|
1039
|
-
|
|
1040
|
-
|
|
1041
|
-
|
|
1042
|
-
|
|
1043
|
-
|
|
1044
|
-
|
|
1045
|
-
|
|
1046
|
-
|
|
1047
|
-
|
|
1048
|
-
|
|
1049
|
-
|
|
1050
|
-
|
|
1051
|
-
|
|
1052
|
-
|
|
1053
|
-
|
|
1054
|
-
|
|
1055
|
-
|
|
1056
|
-
"--whitespace=nowarn",
|
|
1057
|
-
"-"
|
|
1058
|
-
], patchBytes, { GIT_INDEX_FILE: indexFile });
|
|
1059
|
-
const candidateTree = (await runCandidateGit(repositoryRoot, ["write-tree"], void 0, { GIT_INDEX_FILE: indexFile })).stdout.toString("utf8").trim();
|
|
1060
|
-
if (candidateTree !== code.candidateTree) throw new Error(`git patch materialized tree ${candidateTree} does not match ${code.candidateTree}`);
|
|
1061
|
-
await assertSafeTree(repositoryRoot, candidateTree);
|
|
1062
|
-
return candidateTree;
|
|
1063
|
-
} finally {
|
|
1064
|
-
await rm(temporary, {
|
|
1065
|
-
recursive: true,
|
|
1066
|
-
force: true
|
|
1067
|
-
});
|
|
1068
|
-
}
|
|
1049
|
+
//#region src/candidate-execution/output-artifacts.ts
|
|
1050
|
+
/** Persist evaluator evidence, read it back, and bind the returned locator to the exact bytes. */
|
|
1051
|
+
async function persistCandidateOutputArtifact(port, input) {
|
|
1052
|
+
input.signal?.throwIfAborted();
|
|
1053
|
+
const bytes = Uint8Array.from(input.bytes);
|
|
1054
|
+
const expectedDigest = sha256Bytes$1(bytes);
|
|
1055
|
+
const ref = agentCandidateArtifactRefSchema.parse(await port.put({
|
|
1056
|
+
executionId: input.executionId,
|
|
1057
|
+
purpose: input.purpose,
|
|
1058
|
+
bytes: Uint8Array.from(bytes),
|
|
1059
|
+
...input.signal ? { signal: input.signal } : {}
|
|
1060
|
+
}));
|
|
1061
|
+
input.signal?.throwIfAborted();
|
|
1062
|
+
if (ref.sha256 !== expectedDigest || ref.byteLength !== bytes.byteLength) throw new Error("candidate output locator does not identify the submitted bytes");
|
|
1063
|
+
const stored = await port.read(ref);
|
|
1064
|
+
input.signal?.throwIfAborted();
|
|
1065
|
+
verifyBytes(stored, expectedDigest, bytes.byteLength, "persisted candidate output");
|
|
1066
|
+
return immutableCandidateValue(ref);
|
|
1069
1067
|
}
|
|
1070
|
-
|
|
1071
|
-
|
|
1072
|
-
|
|
1073
|
-
|
|
1074
|
-
|
|
1075
|
-
|
|
1076
|
-
|
|
1077
|
-
|
|
1078
|
-
|
|
1079
|
-
|
|
1080
|
-
|
|
1081
|
-
|
|
1082
|
-
|
|
1083
|
-
|
|
1084
|
-
|
|
1085
|
-
|
|
1086
|
-
|
|
1087
|
-
|
|
1088
|
-
|
|
1089
|
-
|
|
1090
|
-
|
|
1091
|
-
|
|
1092
|
-
])).stdout;
|
|
1093
|
-
verifyBytes(bytes, resource.sha256, resource.byteLength, `GitHub resource ${resource.path}`);
|
|
1094
|
-
return Uint8Array.from(bytes);
|
|
1068
|
+
//#endregion
|
|
1069
|
+
//#region src/candidate-execution/workspace-archive.ts
|
|
1070
|
+
const archiveKind = "agent-candidate-workspace-archive";
|
|
1071
|
+
const workspaceEntryPrefix = "workspace/";
|
|
1072
|
+
const repositoryMetadataEntry = "metadata/repository.json";
|
|
1073
|
+
const repositoryBundleEntry = "metadata/repository.bundle";
|
|
1074
|
+
const repositoryIndexEntry = "metadata/repository.index.json";
|
|
1075
|
+
const repositoryIndexPrefix = "index/";
|
|
1076
|
+
const fixedTarTime = /* @__PURE__ */ new Date(0);
|
|
1077
|
+
const defaultLimits = Object.freeze({
|
|
1078
|
+
maxArchiveBytes: 512 * 1024 * 1024,
|
|
1079
|
+
maxEmbeddedArtifactBytes: 1024 * 1024,
|
|
1080
|
+
maxFiles: 5e4,
|
|
1081
|
+
maxFileBytes: 128 * 1024 * 1024,
|
|
1082
|
+
maxTotalFileBytes: 256 * 1024 * 1024,
|
|
1083
|
+
maxPathBytes: 4096,
|
|
1084
|
+
maxRepositoryBundleBytes: 128 * 1024 * 1024
|
|
1085
|
+
});
|
|
1086
|
+
/** Capture detached files returned by a remote executor into the standard archive. */
|
|
1087
|
+
async function captureAgentCandidateWorkspaceFiles(input, options = {}) {
|
|
1088
|
+
const limits = workspaceLimits(options.limits);
|
|
1089
|
+
return captureWorkspaceFiles(normalizeWorkspaceFiles(input, limits), void 0, limits, options.artifactPersistence);
|
|
1095
1090
|
}
|
|
1096
|
-
async function
|
|
1097
|
-
const
|
|
1098
|
-
const
|
|
1099
|
-
|
|
1100
|
-
|
|
1101
|
-
|
|
1091
|
+
async function captureWorkspaceFiles(files, repository, limits, artifactPersistence) {
|
|
1092
|
+
const material = candidateWorkspaceManifest(files);
|
|
1093
|
+
const manifest = canonicalCandidateBytes$1(material);
|
|
1094
|
+
const archive = await encodeWorkspaceArchive(files, repository, limits.maxArchiveBytes);
|
|
1095
|
+
if (!artifactPersistence && (manifest.byteLength > limits.maxEmbeddedArtifactBytes || archive.byteLength > limits.maxEmbeddedArtifactBytes)) throw new Error("candidate workspace artifacts exceed maxEmbeddedArtifactBytes; artifactPersistence is required");
|
|
1096
|
+
const manifestArtifact = await captureWorkspaceArtifact("manifest", manifest, artifactPersistence);
|
|
1097
|
+
const archiveArtifact = await captureWorkspaceArtifact("archive", archive, artifactPersistence);
|
|
1098
|
+
const snapshot = deepFreezeCandidate({
|
|
1099
|
+
kind: "agent-candidate-workspace-snapshot",
|
|
1100
|
+
digest: canonicalCandidateDigest$1(material),
|
|
1101
|
+
material,
|
|
1102
|
+
manifest: manifestArtifact,
|
|
1103
|
+
archive: archiveArtifact
|
|
1104
|
+
});
|
|
1105
|
+
return Object.freeze({
|
|
1106
|
+
snapshot,
|
|
1107
|
+
archive
|
|
1108
|
+
});
|
|
1102
1109
|
}
|
|
1103
|
-
|
|
1104
|
-
|
|
1105
|
-
|
|
1106
|
-
|
|
1107
|
-
|
|
1108
|
-
|
|
1109
|
-
|
|
1110
|
-
|
|
1111
|
-
|
|
1112
|
-
await assertNoGitIndirection(repositoryRoot, gitDir, "task repository");
|
|
1113
|
-
const temporary = await mkdtemp(join(tmpdir(), "agent-candidate-task-outcome-"));
|
|
1114
|
-
try {
|
|
1115
|
-
const objectDirectory = join(temporary, "objects");
|
|
1116
|
-
const indexFile = join(temporary, "index");
|
|
1117
|
-
await mkdir(objectDirectory);
|
|
1118
|
-
const gitEnvironment = {
|
|
1119
|
-
GIT_INDEX_FILE: indexFile,
|
|
1120
|
-
GIT_OBJECT_DIRECTORY: objectDirectory,
|
|
1121
|
-
GIT_ALTERNATE_OBJECT_DIRECTORIES: join(gitDir, "objects")
|
|
1122
|
-
};
|
|
1123
|
-
await runCandidateGit(repositoryRoot, ["read-tree", input.baseTree], void 0, gitEnvironment);
|
|
1124
|
-
if (input.patch.byteLength > 0) await runCandidateGit(repositoryRoot, [
|
|
1125
|
-
"apply",
|
|
1126
|
-
"--cached",
|
|
1127
|
-
"--binary",
|
|
1128
|
-
"--whitespace=nowarn",
|
|
1129
|
-
"-"
|
|
1130
|
-
], input.patch, gitEnvironment);
|
|
1131
|
-
const resultTree = (await runCandidateGit(repositoryRoot, ["write-tree"], void 0, gitEnvironment)).stdout.toString("utf8").trim();
|
|
1132
|
-
if (resultTree !== input.resultTree) throw new Error(`task outcome patch materialized tree ${resultTree} does not match ${input.resultTree}`);
|
|
1133
|
-
await assertSafeTree(repositoryRoot, resultTree, gitEnvironment);
|
|
1134
|
-
const observed = await workspaceManifestFromGitTree(repositoryRoot, resultTree, gitEnvironment);
|
|
1135
|
-
if (!Buffer.from(canonicalCandidateBytes$1(observed)).equals(Buffer.from(canonicalCandidateBytes$1(input.afterState)))) throw new Error("task outcome after-state does not match the materialized result tree");
|
|
1136
|
-
const resultCommit = (await runCandidateGit(repositoryRoot, [
|
|
1137
|
-
"commit-tree",
|
|
1138
|
-
resultTree,
|
|
1139
|
-
"-p",
|
|
1140
|
-
input.baseCommit
|
|
1141
|
-
], Buffer.from("candidate task outcome\n", "utf8"), {
|
|
1142
|
-
...gitEnvironment,
|
|
1143
|
-
GIT_AUTHOR_NAME: "Tangle Evaluator",
|
|
1144
|
-
GIT_AUTHOR_EMAIL: "evaluator@tangle.tools",
|
|
1145
|
-
GIT_AUTHOR_DATE: "2000-01-01T00:00:00Z",
|
|
1146
|
-
GIT_COMMITTER_NAME: "Tangle Evaluator",
|
|
1147
|
-
GIT_COMMITTER_EMAIL: "evaluator@tangle.tools",
|
|
1148
|
-
GIT_COMMITTER_DATE: "2000-01-01T00:00:00Z"
|
|
1149
|
-
})).stdout.toString("utf8").trim();
|
|
1150
|
-
if ((await runCandidateGit(repositoryRoot, ["rev-parse", `${resultCommit}^{tree}`], void 0, gitEnvironment)).stdout.toString("utf8").trim() !== resultTree) throw new Error("task outcome evaluator commit does not bind the verified result tree");
|
|
1151
|
-
return {
|
|
1152
|
-
resultTree,
|
|
1153
|
-
resultCommit
|
|
1154
|
-
};
|
|
1155
|
-
} finally {
|
|
1156
|
-
await rm(temporary, {
|
|
1157
|
-
recursive: true,
|
|
1158
|
-
force: true
|
|
1159
|
-
});
|
|
1160
|
-
}
|
|
1110
|
+
async function captureWorkspaceArtifact(kind, bytes, persistence) {
|
|
1111
|
+
if (!persistence) return embeddedCandidateArtifact(bytes);
|
|
1112
|
+
if (!persistence.executionId.trim()) throw new Error("candidate workspace artifact persistence requires an executionId");
|
|
1113
|
+
return persistCandidateOutputArtifact(persistence.outputArtifacts, {
|
|
1114
|
+
executionId: persistence.executionId,
|
|
1115
|
+
purpose: kind === "manifest" ? "candidate-workspace-manifest" : "candidate-workspace-archive",
|
|
1116
|
+
bytes,
|
|
1117
|
+
...persistence.signal ? { signal: persistence.signal } : {}
|
|
1118
|
+
});
|
|
1161
1119
|
}
|
|
1162
|
-
|
|
1163
|
-
|
|
1164
|
-
|
|
1165
|
-
|
|
1166
|
-
|
|
1167
|
-
|
|
1168
|
-
"origin"
|
|
1169
|
-
])).stdout.toString("utf8").trim();
|
|
1170
|
-
const actual = parseGitHubRemote(origin);
|
|
1171
|
-
if (!actual || actual.owner !== repository.owner || actual.repo !== repository.repo) throw new Error(`local repository origin ${origin || "<missing>"} does not match github.com/${repository.owner}/${repository.repo}`);
|
|
1172
|
-
await assertNoGitIndirection(repositoryRoot, resolve((await runCandidateGit(repositoryRoot, ["rev-parse", "--absolute-git-dir"])).stdout.toString("utf8").trim()), "candidate repository");
|
|
1173
|
-
return repositoryRoot;
|
|
1120
|
+
/** Verify a portable archive before its source environment may be discarded. */
|
|
1121
|
+
async function verifyAgentCandidateWorkspaceArchive(input) {
|
|
1122
|
+
await decodeVerifiedWorkspaceArchive({
|
|
1123
|
+
...input,
|
|
1124
|
+
limits: workspaceLimits(input.limits)
|
|
1125
|
+
});
|
|
1174
1126
|
}
|
|
1175
|
-
async function
|
|
1176
|
-
|
|
1177
|
-
|
|
1178
|
-
|
|
1179
|
-
|
|
1180
|
-
|
|
1181
|
-
const commonDir = await realpath(resolve(repositoryRoot, (await runCandidateGit(repositoryRoot, ["rev-parse", "--git-common-dir"])).stdout.toString("utf8").trim()));
|
|
1182
|
-
if (commonDir.includes(":")) throw new Error(`${label} Git common directory has an unsupported path`);
|
|
1183
|
-
for (const objectRoot of /* @__PURE__ */ new Set([gitDir, commonDir])) for (const name of ["alternates", "http-alternates"]) {
|
|
1184
|
-
const path = join(objectRoot, "objects", "info", name);
|
|
1185
|
-
try {
|
|
1186
|
-
if ((await readFile(path, "utf8")).trim()) throw new Error(`${label} uses forbidden Git ${name}`);
|
|
1187
|
-
} catch (error) {
|
|
1188
|
-
if (!isNoEntry(error)) throw error;
|
|
1189
|
-
}
|
|
1190
|
-
}
|
|
1127
|
+
async function decodeVerifiedWorkspaceArchive(input) {
|
|
1128
|
+
verifyBytes(input.archive, input.snapshot.archive.sha256, input.snapshot.archive.byteLength, "candidate workspace archive");
|
|
1129
|
+
const decoded = await parseWorkspaceArchive(input.archive, input.limits);
|
|
1130
|
+
if (decoded.repository && input.role !== "task") throw new Error("only task workspaces may carry a Git repository");
|
|
1131
|
+
assertArchiveMatchesSnapshot(decoded.files, input.snapshot);
|
|
1132
|
+
return decoded;
|
|
1191
1133
|
}
|
|
1192
|
-
async function
|
|
1193
|
-
|
|
1194
|
-
|
|
1195
|
-
|
|
1196
|
-
|
|
1197
|
-
|
|
1198
|
-
|
|
1199
|
-
|
|
1134
|
+
async function encodeWorkspaceArchive(files, repository, maxArchiveBytes) {
|
|
1135
|
+
const archive = pack();
|
|
1136
|
+
const output = collectStream(archive, maxArchiveBytes, "candidate workspace archive");
|
|
1137
|
+
try {
|
|
1138
|
+
await writeWorkspaceArchiveEntries(archive, files, repository);
|
|
1139
|
+
archive.finalize();
|
|
1140
|
+
return await output;
|
|
1141
|
+
} catch (error) {
|
|
1142
|
+
archive.destroy(error instanceof Error ? error : new Error(String(error)));
|
|
1143
|
+
await output.catch(() => void 0);
|
|
1144
|
+
throw error;
|
|
1145
|
+
}
|
|
1200
1146
|
}
|
|
1201
|
-
async function
|
|
1147
|
+
async function verifyCanonicalWorkspaceArchive(files, repository, expected, maxArchiveBytes) {
|
|
1148
|
+
const archive = pack();
|
|
1149
|
+
const comparison = streamEqualsBytes(archive, expected, maxArchiveBytes, "candidate workspace archive");
|
|
1150
|
+
try {
|
|
1151
|
+
await writeWorkspaceArchiveEntries(archive, files, repository);
|
|
1152
|
+
archive.finalize();
|
|
1153
|
+
if (!await comparison) throw new Error("candidate workspace tar is not canonical");
|
|
1154
|
+
} catch (error) {
|
|
1155
|
+
archive.destroy(error instanceof Error ? error : new Error(String(error)));
|
|
1156
|
+
await comparison.catch(() => void 0);
|
|
1157
|
+
throw error;
|
|
1158
|
+
}
|
|
1159
|
+
}
|
|
1160
|
+
async function writeWorkspaceArchiveEntries(archive, files, repository) {
|
|
1161
|
+
for (const file of files) await writeTarEntry(archive, `${workspaceEntryPrefix}${file.path}`, file.mode, file.bytes);
|
|
1162
|
+
if (!repository) return;
|
|
1163
|
+
const indexManifest = repository.workingTree ? canonicalCandidateBytes$1(candidateWorkspaceManifest(repository.workingTree.files)) : void 0;
|
|
1164
|
+
const metadata = canonicalCandidateBytes$1({
|
|
1165
|
+
kind: archiveKind,
|
|
1166
|
+
headCommit: repository.headCommit,
|
|
1167
|
+
headTree: repository.headTree,
|
|
1168
|
+
bundle: {
|
|
1169
|
+
sha256: repository.bundle.sha256,
|
|
1170
|
+
byteLength: repository.bundle.byteLength
|
|
1171
|
+
},
|
|
1172
|
+
...indexManifest ? { workingTree: { indexManifest: {
|
|
1173
|
+
sha256: sha256Bytes$1(indexManifest),
|
|
1174
|
+
byteLength: indexManifest.byteLength
|
|
1175
|
+
} } } : {}
|
|
1176
|
+
});
|
|
1177
|
+
await writeTarEntry(archive, repositoryMetadataEntry, 384, metadata);
|
|
1178
|
+
await writeTarEntry(archive, repositoryBundleEntry, 384, repository.bundle.bytes);
|
|
1179
|
+
if (repository.workingTree && indexManifest) {
|
|
1180
|
+
await writeTarEntry(archive, repositoryIndexEntry, 384, indexManifest);
|
|
1181
|
+
for (const file of repository.workingTree.files) await writeTarEntry(archive, `${repositoryIndexPrefix}${file.path}`, file.mode, file.bytes);
|
|
1182
|
+
}
|
|
1183
|
+
}
|
|
1184
|
+
async function parseWorkspaceArchive(bytes, limits) {
|
|
1185
|
+
if (bytes.byteLength > limits.maxArchiveBytes) throw new Error("candidate workspace archive exceeds maxArchiveBytes");
|
|
1186
|
+
const parser = extract();
|
|
1187
|
+
const files = [];
|
|
1188
|
+
const observedEntryNames = /* @__PURE__ */ new Set();
|
|
1189
|
+
const observedPaths = /* @__PURE__ */ new Set();
|
|
1190
|
+
let totalBytes = 0;
|
|
1191
|
+
let retainedEntryBytes = 0;
|
|
1192
|
+
let previousPath;
|
|
1193
|
+
let repositoryMetadata;
|
|
1194
|
+
let repositoryBundle;
|
|
1195
|
+
let repositoryIndex;
|
|
1196
|
+
const indexFiles = [];
|
|
1197
|
+
const indexPaths = /* @__PURE__ */ new Set();
|
|
1198
|
+
let previousIndexPath;
|
|
1199
|
+
let indexBytes = 0;
|
|
1200
|
+
const decoded = (async () => {
|
|
1201
|
+
for await (const entry of parser) {
|
|
1202
|
+
const name = entry.header.name;
|
|
1203
|
+
if (entry.header.type !== "file" || typeof name !== "string" || observedEntryNames.has(name)) throw new Error("candidate workspace tar contains an invalid entry");
|
|
1204
|
+
observedEntryNames.add(name);
|
|
1205
|
+
if (name.startsWith(workspaceEntryPrefix)) {
|
|
1206
|
+
if (files.length >= limits.maxFiles) throw new Error("candidate workspace archive has an invalid file count");
|
|
1207
|
+
const path = safeArchivePath(name.slice(10), limits.maxPathBytes);
|
|
1208
|
+
if (!isWorkspaceFileMode(entry.header.mode)) throw new Error(`candidate workspace archive has an unsupported mode: ${path}`);
|
|
1209
|
+
assertRetainedArchiveSize(bytes.byteLength, retainedEntryBytes, entry.header.size, limits);
|
|
1210
|
+
const fileBytes = await readTarEntry(entry, limits.maxFileBytes, `workspace file ${path}`);
|
|
1211
|
+
retainedEntryBytes += fileBytes.byteLength;
|
|
1212
|
+
assertWorkspacePathOrder(path, previousPath, observedPaths, "candidate workspace archive paths must be unique and sorted");
|
|
1213
|
+
previousPath = path;
|
|
1214
|
+
if (fileBytes.byteLength > limits.maxTotalFileBytes - totalBytes) throw new Error("candidate workspace archive exceeds maxTotalFileBytes");
|
|
1215
|
+
totalBytes += fileBytes.byteLength;
|
|
1216
|
+
files.push({
|
|
1217
|
+
path,
|
|
1218
|
+
mode: entry.header.mode,
|
|
1219
|
+
bytes: fileBytes
|
|
1220
|
+
});
|
|
1221
|
+
} else if (name === repositoryMetadataEntry) {
|
|
1222
|
+
if (entry.header.mode !== 384 || repositoryMetadata) throw new Error("candidate workspace archive repository metadata is invalid");
|
|
1223
|
+
assertRetainedArchiveSize(bytes.byteLength, retainedEntryBytes, entry.header.size, limits);
|
|
1224
|
+
const metadataBytes = await readTarEntry(entry, limits.maxPathBytes, "candidate repository metadata");
|
|
1225
|
+
retainedEntryBytes += metadataBytes.byteLength;
|
|
1226
|
+
repositoryMetadata = parseRepositoryMetadata(metadataBytes, limits);
|
|
1227
|
+
} else if (name === repositoryBundleEntry) {
|
|
1228
|
+
if (entry.header.mode !== 384 || repositoryBundle) throw new Error("candidate workspace archive repository bundle is invalid");
|
|
1229
|
+
assertRetainedArchiveSize(bytes.byteLength, retainedEntryBytes, entry.header.size, limits);
|
|
1230
|
+
repositoryBundle = await readTarEntry(entry, limits.maxRepositoryBundleBytes, "candidate Git bundle");
|
|
1231
|
+
retainedEntryBytes += repositoryBundle.byteLength;
|
|
1232
|
+
} else if (name === repositoryIndexEntry) {
|
|
1233
|
+
if (entry.header.mode !== 384 || repositoryIndex) throw new Error("candidate workspace archive repository index is invalid");
|
|
1234
|
+
assertRetainedArchiveSize(bytes.byteLength, retainedEntryBytes, entry.header.size, limits);
|
|
1235
|
+
repositoryIndex = await readTarEntry(entry, limits.maxArchiveBytes, "candidate Git index manifest");
|
|
1236
|
+
retainedEntryBytes += repositoryIndex.byteLength;
|
|
1237
|
+
} else if (name.startsWith(repositoryIndexPrefix)) {
|
|
1238
|
+
if (!repositoryMetadata?.workingTree || !repositoryIndex || indexFiles.length >= limits.maxFiles) throw new Error("candidate Git index evidence is incomplete or exceeds maxFiles");
|
|
1239
|
+
const path = safeArchivePath(name.slice(6), limits.maxPathBytes);
|
|
1240
|
+
if (entry.header.mode !== 420 && entry.header.mode !== 493) throw new Error("candidate Git index contains an unsupported mode");
|
|
1241
|
+
assertWorkspacePathOrder(path, previousIndexPath, indexPaths, "candidate Git index paths must be unique and sorted");
|
|
1242
|
+
previousIndexPath = path;
|
|
1243
|
+
assertRetainedArchiveSize(bytes.byteLength, retainedEntryBytes, entry.header.size, limits);
|
|
1244
|
+
if (entry.header.size === void 0 || entry.header.size > limits.maxTotalFileBytes - indexBytes) throw new Error("candidate Git index exceeds maxTotalFileBytes");
|
|
1245
|
+
if (entry.header.size > limits.maxFileBytes) throw new Error("candidate Git index exceeds maxFileBytes");
|
|
1246
|
+
const fileBytes = await readTarEntry(entry, limits.maxFileBytes, `Git index file ${path}`);
|
|
1247
|
+
retainedEntryBytes += fileBytes.byteLength;
|
|
1248
|
+
indexBytes += fileBytes.byteLength;
|
|
1249
|
+
indexFiles.push({
|
|
1250
|
+
path,
|
|
1251
|
+
mode: entry.header.mode,
|
|
1252
|
+
bytes: fileBytes
|
|
1253
|
+
});
|
|
1254
|
+
} else throw new Error(`candidate workspace tar contains an unsupported entry: ${name}`);
|
|
1255
|
+
}
|
|
1256
|
+
if (Boolean(repositoryMetadata) !== Boolean(repositoryBundle)) throw new Error("candidate workspace archive repository evidence is incomplete");
|
|
1257
|
+
if (Boolean(repositoryMetadata?.workingTree) !== Boolean(repositoryIndex)) throw new Error("candidate workspace archive repository index evidence is incomplete");
|
|
1258
|
+
const repository = repositoryMetadata && repositoryBundle ? repositoryFromTar(repositoryMetadata, repositoryBundle, repositoryIndex, indexFiles) : void 0;
|
|
1259
|
+
return {
|
|
1260
|
+
files,
|
|
1261
|
+
...repository ? { repository } : {}
|
|
1262
|
+
};
|
|
1263
|
+
})();
|
|
1264
|
+
parser.end(Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength));
|
|
1265
|
+
const result = await decoded;
|
|
1266
|
+
await verifyCanonicalWorkspaceArchive(result.files, result.repository, bytes, limits.maxArchiveBytes);
|
|
1267
|
+
return result;
|
|
1268
|
+
}
|
|
1269
|
+
function assertRetainedArchiveSize(archiveBytes, retainedEntryBytes, entryBytes, limits) {
|
|
1270
|
+
if (!Number.isSafeInteger(entryBytes) || entryBytes === void 0 || entryBytes < 0 || entryBytes > limits.maxArchiveBytes - archiveBytes - retainedEntryBytes) throw new Error("candidate workspace archive exceeds maxArchiveBytes while decoding");
|
|
1271
|
+
}
|
|
1272
|
+
function parseRepositoryMetadata(bytes, limits) {
|
|
1273
|
+
let value;
|
|
1274
|
+
try {
|
|
1275
|
+
value = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes));
|
|
1276
|
+
} catch (error) {
|
|
1277
|
+
throw new Error("candidate workspace archive repository metadata is invalid", { cause: error });
|
|
1278
|
+
}
|
|
1279
|
+
if (!isRecord(value) || !["bundle,headCommit,headTree,kind", "bundle,headCommit,headTree,kind,workingTree"].includes(Object.keys(value).sort().join(",")) || value.kind !== archiveKind || typeof value.headCommit !== "string" || typeof value.headTree !== "string" || !isRecord(value.bundle) || Object.keys(value.bundle).sort().join(",") !== "byteLength,sha256" || typeof value.bundle.sha256 !== "string" || !/^sha256:[a-f0-9]{64}$/.test(value.bundle.sha256) || !Number.isSafeInteger(value.bundle.byteLength) || value.bundle.byteLength <= 0 || value.bundle.byteLength > limits.maxRepositoryBundleBytes) throw new Error("candidate workspace archive repository is invalid");
|
|
1280
|
+
if (!Buffer.from(canonicalCandidateBytes$1(value)).equals(Buffer.from(bytes))) throw new Error("candidate workspace archive repository metadata is not canonical");
|
|
1281
|
+
assertGitObjectId(value.headCommit, "repository HEAD");
|
|
1282
|
+
assertGitObjectId(value.headTree, "repository HEAD tree");
|
|
1283
|
+
if (value.headCommit.length !== value.headTree.length) throw new Error("candidate repository HEAD and tree use different object formats");
|
|
1284
|
+
let workingTree;
|
|
1285
|
+
if ("workingTree" in value) {
|
|
1286
|
+
const working = value.workingTree;
|
|
1287
|
+
if (!isRecord(working) || Object.keys(working).join(",") !== "indexManifest" || !isRecord(working.indexManifest) || Object.keys(working.indexManifest).sort().join(",") !== "byteLength,sha256" || typeof working.indexManifest.sha256 !== "string" || !/^sha256:[a-f0-9]{64}$/.test(working.indexManifest.sha256) || !Number.isSafeInteger(working.indexManifest.byteLength) || working.indexManifest.byteLength < 0 || working.indexManifest.byteLength > limits.maxArchiveBytes) throw new Error("candidate workspace archive repository index is invalid");
|
|
1288
|
+
workingTree = { indexManifest: {
|
|
1289
|
+
sha256: working.indexManifest.sha256,
|
|
1290
|
+
byteLength: working.indexManifest.byteLength
|
|
1291
|
+
} };
|
|
1292
|
+
}
|
|
1293
|
+
return {
|
|
1294
|
+
kind: archiveKind,
|
|
1295
|
+
headCommit: value.headCommit,
|
|
1296
|
+
headTree: value.headTree,
|
|
1297
|
+
bundle: {
|
|
1298
|
+
sha256: value.bundle.sha256,
|
|
1299
|
+
byteLength: value.bundle.byteLength
|
|
1300
|
+
},
|
|
1301
|
+
...workingTree ? { workingTree } : {}
|
|
1302
|
+
};
|
|
1303
|
+
}
|
|
1304
|
+
function repositoryFromTar(metadata, bundle, indexManifest, indexFiles) {
|
|
1305
|
+
verifyBytes(bundle, metadata.bundle.sha256, metadata.bundle.byteLength, "candidate Git bundle");
|
|
1306
|
+
if (metadata.workingTree && indexManifest) {
|
|
1307
|
+
verifyBytes(indexManifest, metadata.workingTree.indexManifest.sha256, metadata.workingTree.indexManifest.byteLength, "candidate Git index manifest");
|
|
1308
|
+
if (!Buffer.from(indexManifest).equals(Buffer.from(canonicalCandidateBytes$1(candidateWorkspaceManifest(indexFiles))))) throw new Error("candidate Git index files do not match the captured manifest");
|
|
1309
|
+
}
|
|
1310
|
+
return {
|
|
1311
|
+
headCommit: metadata.headCommit,
|
|
1312
|
+
headTree: metadata.headTree,
|
|
1313
|
+
bundle: {
|
|
1314
|
+
...metadata.bundle,
|
|
1315
|
+
bytes: bundle
|
|
1316
|
+
},
|
|
1317
|
+
...metadata.workingTree && indexManifest ? { workingTree: { files: indexFiles } } : {}
|
|
1318
|
+
};
|
|
1319
|
+
}
|
|
1320
|
+
async function writeTarEntry(archive, name, mode, bytes) {
|
|
1321
|
+
await new Promise((resolveEntry, rejectEntry) => {
|
|
1322
|
+
archive.entry(workspaceTarHeader(name, mode, bytes.byteLength), Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength), (error) => error ? rejectEntry(error) : resolveEntry());
|
|
1323
|
+
});
|
|
1324
|
+
}
|
|
1325
|
+
async function readTarEntry(entry, maxBytes, label) {
|
|
1326
|
+
const size = entry.header.size;
|
|
1327
|
+
if (!Number.isSafeInteger(size) || size === void 0 || size < 0 || size > maxBytes) throw new Error(`${label} has an invalid tar size`);
|
|
1328
|
+
const bytes = await collectStream(entry, maxBytes, label);
|
|
1329
|
+
if (bytes.byteLength !== size) throw new Error(`${label} differs from its tar size`);
|
|
1330
|
+
return bytes;
|
|
1331
|
+
}
|
|
1332
|
+
async function collectStream(stream, maxBytes, label) {
|
|
1333
|
+
const chunks = [];
|
|
1334
|
+
let totalBytes = 0;
|
|
1335
|
+
for await (const chunk of stream) {
|
|
1336
|
+
if (!(chunk instanceof Uint8Array)) throw new Error(`${label} emitted a non-byte chunk`);
|
|
1337
|
+
if (chunk.byteLength > maxBytes - totalBytes) {
|
|
1338
|
+
const error = /* @__PURE__ */ new Error(`${label} exceeds its size limit`);
|
|
1339
|
+
if ("destroy" in stream && typeof stream.destroy === "function") stream.destroy(error);
|
|
1340
|
+
throw error;
|
|
1341
|
+
}
|
|
1342
|
+
const bytes = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
|
|
1343
|
+
chunks.push(bytes);
|
|
1344
|
+
totalBytes += bytes.byteLength;
|
|
1345
|
+
}
|
|
1346
|
+
return Buffer.concat(chunks, totalBytes);
|
|
1347
|
+
}
|
|
1348
|
+
async function streamEqualsBytes(stream, expected, maxBytes, label) {
|
|
1349
|
+
const expectedBuffer = Buffer.from(expected.buffer, expected.byteOffset, expected.byteLength);
|
|
1350
|
+
let equal = true;
|
|
1351
|
+
let offset = 0;
|
|
1352
|
+
for await (const chunk of stream) {
|
|
1353
|
+
if (!(chunk instanceof Uint8Array)) throw new Error(`${label} emitted a non-byte chunk`);
|
|
1354
|
+
if (chunk.byteLength > maxBytes - offset) {
|
|
1355
|
+
const error = /* @__PURE__ */ new Error(`${label} exceeds its size limit`);
|
|
1356
|
+
if ("destroy" in stream && typeof stream.destroy === "function") stream.destroy(error);
|
|
1357
|
+
throw error;
|
|
1358
|
+
}
|
|
1359
|
+
const observed = Buffer.from(chunk.buffer, chunk.byteOffset, chunk.byteLength);
|
|
1360
|
+
if (offset + observed.byteLength > expectedBuffer.byteLength || !observed.equals(expectedBuffer.subarray(offset, offset + observed.byteLength))) equal = false;
|
|
1361
|
+
offset += observed.byteLength;
|
|
1362
|
+
}
|
|
1363
|
+
return equal && offset === expectedBuffer.byteLength;
|
|
1364
|
+
}
|
|
1365
|
+
function assertArchiveMatchesSnapshot(files, snapshot) {
|
|
1366
|
+
const material = candidateWorkspaceManifest(files);
|
|
1367
|
+
const materialBytes = canonicalCandidateBytes$1(material);
|
|
1368
|
+
verifyBytes(materialBytes, snapshot.manifest.sha256, snapshot.manifest.byteLength, "candidate workspace manifest");
|
|
1369
|
+
if (canonicalCandidateDigest$1(material) !== snapshot.digest || !Buffer.from(materialBytes).equals(Buffer.from(canonicalCandidateBytes$1(snapshot.material)))) throw new Error("candidate workspace archive does not match its snapshot manifest");
|
|
1370
|
+
}
|
|
1371
|
+
function assertWorkspaceFilesWithinLimits(files, limits) {
|
|
1372
|
+
if (files.length > limits.maxFiles) throw new Error("candidate workspace exceeds maxFiles");
|
|
1373
|
+
let totalBytes = 0;
|
|
1374
|
+
let previousPath;
|
|
1375
|
+
const observedPaths = /* @__PURE__ */ new Set();
|
|
1376
|
+
for (const file of files) {
|
|
1377
|
+
const path = safeArchivePath(file.path, limits.maxPathBytes);
|
|
1378
|
+
assertWorkspacePathOrder(path, previousPath, observedPaths, "candidate workspace paths must be unique and sorted");
|
|
1379
|
+
previousPath = path;
|
|
1380
|
+
if (!isWorkspaceFileMode(file.mode)) throw new Error(`candidate workspace file has unsupported mode: ${path}`);
|
|
1381
|
+
if (file.bytes.byteLength > limits.maxFileBytes) throw new Error(`candidate workspace file exceeds maxFileBytes: ${path}`);
|
|
1382
|
+
totalBytes += file.bytes.byteLength;
|
|
1383
|
+
if (totalBytes > limits.maxTotalFileBytes) throw new Error("candidate workspace exceeds maxTotalFileBytes");
|
|
1384
|
+
}
|
|
1385
|
+
}
|
|
1386
|
+
function normalizeWorkspaceFiles(input, limits) {
|
|
1387
|
+
if (!Array.isArray(input)) throw new Error("candidate workspace files must be an array");
|
|
1388
|
+
const fileCount = input.length;
|
|
1389
|
+
if (fileCount > limits.maxFiles) throw new Error("candidate workspace exceeds maxFiles");
|
|
1390
|
+
let totalBytes = 0;
|
|
1391
|
+
const files = [];
|
|
1392
|
+
for (let index = 0; index < fileCount; index++) {
|
|
1393
|
+
const inputFile = input[index];
|
|
1394
|
+
if (!isRecord(inputFile) || Object.keys(inputFile).sort().join(",") !== "bytes,mode,path") throw new Error(`candidate workspace file ${index} is invalid`);
|
|
1395
|
+
const descriptors = Object.getOwnPropertyDescriptors(inputFile);
|
|
1396
|
+
if (!("value" in (descriptors.path ?? {})) || !("value" in (descriptors.mode ?? {})) || !("value" in (descriptors.bytes ?? {}))) throw new Error(`candidate workspace file ${index} must use fixed values`);
|
|
1397
|
+
const path = safeArchivePath(descriptors.path?.value, limits.maxPathBytes);
|
|
1398
|
+
const mode = descriptors.mode?.value;
|
|
1399
|
+
const inputBytes = descriptors.bytes?.value;
|
|
1400
|
+
if (!isWorkspaceFileMode(mode)) throw new Error(`candidate workspace file has unsupported mode: ${path}`);
|
|
1401
|
+
const view = inspectWorkspaceBytes(inputBytes, path);
|
|
1402
|
+
if (view.byteLength > limits.maxFileBytes) throw new Error(`candidate workspace file exceeds maxFileBytes: ${path}`);
|
|
1403
|
+
if (view.byteLength > limits.maxTotalFileBytes - totalBytes) throw new Error("candidate workspace exceeds maxTotalFileBytes");
|
|
1404
|
+
if (view.byteLength > Math.max(0, limits.maxArchiveBytes - 1024)) throw new Error("candidate workspace archive exceeds maxArchiveBytes");
|
|
1405
|
+
totalBytes += view.byteLength;
|
|
1406
|
+
files.push({
|
|
1407
|
+
path,
|
|
1408
|
+
mode,
|
|
1409
|
+
bytes: detachWorkspaceBytes(view)
|
|
1410
|
+
});
|
|
1411
|
+
}
|
|
1412
|
+
files.sort((left, right) => left.path < right.path ? -1 : left.path > right.path ? 1 : 0);
|
|
1413
|
+
assertWorkspaceFilesWithinLimits(files, limits);
|
|
1414
|
+
return files;
|
|
1415
|
+
}
|
|
1416
|
+
function isWorkspaceFileMode(value) {
|
|
1417
|
+
return Number.isSafeInteger(value) && value >= 0 && value <= 511;
|
|
1418
|
+
}
|
|
1419
|
+
function workspaceLimits(overrides) {
|
|
1420
|
+
const limits = {
|
|
1421
|
+
...defaultLimits,
|
|
1422
|
+
...overrides
|
|
1423
|
+
};
|
|
1424
|
+
for (const [name, value] of Object.entries(limits)) if (!Number.isSafeInteger(value) || value <= 0) throw new Error(`candidate workspace ${name} must be a positive safe integer`);
|
|
1425
|
+
return Object.freeze(limits);
|
|
1426
|
+
}
|
|
1427
|
+
function safeArchivePath(value, maxPathBytes) {
|
|
1428
|
+
if (typeof value !== "string" || !value || !isWellFormedUnicode(value) || Buffer.byteLength(value, "utf8") > maxPathBytes || isAbsolute(value) || win32.isAbsolute(value) || value.includes("\\") || value.includes("\0") || hasControlCharacter(value) || value.split("/").some((part) => !part || part === "." || part === "..") || [".git", ".sidecar"].includes(value.split("/")[0]?.toLowerCase() ?? "")) throw new Error(`candidate workspace archive contains an unsafe path: ${String(value)}`);
|
|
1429
|
+
return value;
|
|
1430
|
+
}
|
|
1431
|
+
function assertWorkspacePathOrder(path, previousPath, observedPaths, errorMessage) {
|
|
1432
|
+
if (previousPath !== void 0 && previousPath >= path) throw new Error(errorMessage);
|
|
1433
|
+
for (let slash = path.indexOf("/"); slash !== -1; slash = path.indexOf("/", slash + 1)) if (observedPaths.has(path.slice(0, slash))) throw new Error(errorMessage);
|
|
1434
|
+
observedPaths.add(path);
|
|
1435
|
+
}
|
|
1436
|
+
function inspectWorkspaceBytes(input, path) {
|
|
1437
|
+
let buffer;
|
|
1438
|
+
let byteOffset;
|
|
1439
|
+
let byteLength;
|
|
1440
|
+
try {
|
|
1441
|
+
buffer = typedArrayBufferGetter.call(input);
|
|
1442
|
+
byteOffset = typedArrayByteOffsetGetter.call(input);
|
|
1443
|
+
byteLength = typedArrayByteLengthGetter.call(input);
|
|
1444
|
+
} catch {
|
|
1445
|
+
throw new Error(`candidate workspace file bytes are invalid: ${path}`);
|
|
1446
|
+
}
|
|
1447
|
+
if (isSharedArrayBuffer(buffer)) throw new Error(`candidate workspace file uses shared bytes: ${path}`);
|
|
1448
|
+
if (!isAnyArrayBuffer(buffer)) throw new Error(`candidate workspace file bytes are invalid: ${path}`);
|
|
1449
|
+
return {
|
|
1450
|
+
buffer,
|
|
1451
|
+
byteOffset,
|
|
1452
|
+
byteLength
|
|
1453
|
+
};
|
|
1454
|
+
}
|
|
1455
|
+
function detachWorkspaceBytes(input) {
|
|
1456
|
+
const { buffer, byteOffset, byteLength } = input;
|
|
1457
|
+
const copy = new Uint8Array(byteLength);
|
|
1458
|
+
Uint8Array.prototype.set.call(copy, new Uint8Array(buffer, byteOffset, byteLength));
|
|
1459
|
+
return copy;
|
|
1460
|
+
}
|
|
1461
|
+
function assertGitObjectId(value, label) {
|
|
1462
|
+
if (!/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(value)) throw new Error(`candidate repository ${label} is not a Git object id`);
|
|
1463
|
+
}
|
|
1464
|
+
function requireTypedArrayGetter(name) {
|
|
1465
|
+
const typedArrayPrototype = Object.getPrototypeOf(Uint8Array.prototype);
|
|
1466
|
+
const getter = Object.getOwnPropertyDescriptor(typedArrayPrototype, name)?.get;
|
|
1467
|
+
if (!getter) throw new Error(`typed array intrinsic ${name} accessor is unavailable`);
|
|
1468
|
+
return getter;
|
|
1469
|
+
}
|
|
1470
|
+
const typedArrayBufferGetter = requireTypedArrayGetter("buffer");
|
|
1471
|
+
const typedArrayByteOffsetGetter = requireTypedArrayGetter("byteOffset");
|
|
1472
|
+
const typedArrayByteLengthGetter = requireTypedArrayGetter("byteLength");
|
|
1473
|
+
/** Shared canonical header for both archive encoders. */
|
|
1474
|
+
function workspaceTarHeader(name, mode, size) {
|
|
1475
|
+
return {
|
|
1476
|
+
name,
|
|
1477
|
+
mode,
|
|
1478
|
+
uid: 0,
|
|
1479
|
+
gid: 0,
|
|
1480
|
+
size,
|
|
1481
|
+
mtime: fixedTarTime,
|
|
1482
|
+
type: "file",
|
|
1483
|
+
uname: "",
|
|
1484
|
+
gname: ""
|
|
1485
|
+
};
|
|
1486
|
+
}
|
|
1487
|
+
//#endregion
|
|
1488
|
+
//#region src/candidate-execution/git-materialize.ts
|
|
1489
|
+
async function verifyCandidateCode(code, repositories, patchBytes) {
|
|
1490
|
+
if (code.kind === "disabled") return void 0;
|
|
1491
|
+
const repositoryRoot = await verifiedRepositoryRoot(code.repository, repositories);
|
|
1492
|
+
await assertCommitAndBaseTree(repositoryRoot, code.baseCommit, code.baseTree);
|
|
1493
|
+
if (code.kind === "no-op") {
|
|
1494
|
+
await assertSafeTree(repositoryRoot, code.baseTree);
|
|
1495
|
+
return code.baseTree;
|
|
1496
|
+
}
|
|
1497
|
+
if (!patchBytes) throw new Error("git-patch candidate is missing verified patch bytes");
|
|
1498
|
+
const temporary = await mkdtemp(join(tmpdir(), "agent-candidate-git-"));
|
|
1499
|
+
try {
|
|
1500
|
+
const indexFile = join(temporary, "index");
|
|
1501
|
+
await runCandidateGit(repositoryRoot, ["read-tree", code.baseTree], void 0, { GIT_INDEX_FILE: indexFile });
|
|
1502
|
+
await runCandidateGit(repositoryRoot, [
|
|
1503
|
+
"apply",
|
|
1504
|
+
"--cached",
|
|
1505
|
+
"--binary",
|
|
1506
|
+
"--whitespace=nowarn",
|
|
1507
|
+
"-"
|
|
1508
|
+
], patchBytes, { GIT_INDEX_FILE: indexFile });
|
|
1509
|
+
const candidateTree = (await runCandidateGit(repositoryRoot, ["write-tree"], void 0, { GIT_INDEX_FILE: indexFile })).stdout.toString("utf8").trim();
|
|
1510
|
+
if (candidateTree !== code.candidateTree) throw new Error(`git patch materialized tree ${candidateTree} does not match ${code.candidateTree}`);
|
|
1511
|
+
await assertSafeTree(repositoryRoot, candidateTree);
|
|
1512
|
+
return candidateTree;
|
|
1513
|
+
} finally {
|
|
1514
|
+
await rm(temporary, {
|
|
1515
|
+
recursive: true,
|
|
1516
|
+
force: true
|
|
1517
|
+
});
|
|
1518
|
+
}
|
|
1519
|
+
}
|
|
1520
|
+
async function readCandidateGitHubResource(resource, repositories) {
|
|
1521
|
+
const repositoryRoot = await verifiedRepositoryRoot(resource.repository, repositories);
|
|
1522
|
+
if ((await runCandidateGit(repositoryRoot, [
|
|
1523
|
+
"cat-file",
|
|
1524
|
+
"-t",
|
|
1525
|
+
resource.commit
|
|
1526
|
+
])).stdout.toString("utf8").trim() !== "commit") throw new Error(`GitHub resource commit is not a commit object: ${resource.commit}`);
|
|
1527
|
+
const listing = (await runCandidateGit(repositoryRoot, [
|
|
1528
|
+
"ls-tree",
|
|
1529
|
+
"-z",
|
|
1530
|
+
resource.commit,
|
|
1531
|
+
"--",
|
|
1532
|
+
resource.path
|
|
1533
|
+
])).stdout;
|
|
1534
|
+
const entries = parseTreeEntries(listing);
|
|
1535
|
+
if (entries.length !== 1 || entries[0]?.path !== resource.path) throw new Error(`GitHub resource path is not one exact file: ${resource.path}`);
|
|
1536
|
+
const entry = entries[0];
|
|
1537
|
+
if (entry?.type !== "blob" || entry.mode !== "100644" && entry.mode !== "100755") throw new Error(`GitHub resource path is not a regular Git blob: ${resource.path}`);
|
|
1538
|
+
const bytes = (await runCandidateGit(repositoryRoot, [
|
|
1539
|
+
"cat-file",
|
|
1540
|
+
"blob",
|
|
1541
|
+
entry.object
|
|
1542
|
+
])).stdout;
|
|
1543
|
+
verifyBytes(bytes, resource.sha256, resource.byteLength, `GitHub resource ${resource.path}`);
|
|
1544
|
+
return Uint8Array.from(bytes);
|
|
1545
|
+
}
|
|
1546
|
+
async function verifyTaskCheckout(taskRoot, expected) {
|
|
1547
|
+
const root = resolve(taskRoot);
|
|
1548
|
+
const head = (await runCandidateGit(root, ["rev-parse", "HEAD"])).stdout.toString("utf8").trim();
|
|
1549
|
+
if (head !== expected.baseCommit) throw new Error(`task checkout HEAD ${head} does not match ${expected.baseCommit}`);
|
|
1550
|
+
const tree = (await runCandidateGit(root, ["rev-parse", "HEAD^{tree}"])).stdout.toString("utf8").trim();
|
|
1551
|
+
if (tree !== expected.baseTree) throw new Error(`task checkout base tree ${tree} does not match ${expected.baseTree}`);
|
|
1552
|
+
}
|
|
1553
|
+
/**
|
|
1554
|
+
* Apply an evaluator-captured binary diff in a detached object database and
|
|
1555
|
+
* prove its result tree exactly matches the captured after-state manifest.
|
|
1556
|
+
*/
|
|
1557
|
+
async function verifyTaskOutcomePatch(input) {
|
|
1558
|
+
const repositoryRoot = resolve(input.repositoryRoot);
|
|
1559
|
+
await verifyTaskCheckout(repositoryRoot, input);
|
|
1560
|
+
const gitDir = resolve((await runCandidateGit(repositoryRoot, ["rev-parse", "--absolute-git-dir"])).stdout.toString("utf8").trim());
|
|
1561
|
+
if (await realpath(gitDir) !== gitDir || gitDir.includes(":")) throw new Error("task Git object store has an unsupported path");
|
|
1562
|
+
await assertNoGitIndirection(repositoryRoot, gitDir, "task repository");
|
|
1563
|
+
const temporary = await mkdtemp(join(tmpdir(), "agent-candidate-task-outcome-"));
|
|
1564
|
+
try {
|
|
1565
|
+
const objectDirectory = join(temporary, "objects");
|
|
1566
|
+
const indexFile = join(temporary, "index");
|
|
1567
|
+
await mkdir(objectDirectory);
|
|
1568
|
+
const gitEnvironment = {
|
|
1569
|
+
GIT_INDEX_FILE: indexFile,
|
|
1570
|
+
GIT_OBJECT_DIRECTORY: objectDirectory,
|
|
1571
|
+
GIT_ALTERNATE_OBJECT_DIRECTORIES: join(gitDir, "objects")
|
|
1572
|
+
};
|
|
1573
|
+
await runCandidateGit(repositoryRoot, ["read-tree", input.baseTree], void 0, gitEnvironment);
|
|
1574
|
+
if (input.patch.byteLength > 0) await runCandidateGit(repositoryRoot, [
|
|
1575
|
+
"apply",
|
|
1576
|
+
"--cached",
|
|
1577
|
+
"--binary",
|
|
1578
|
+
"--whitespace=nowarn",
|
|
1579
|
+
"-"
|
|
1580
|
+
], input.patch, gitEnvironment);
|
|
1581
|
+
const resultTree = (await runCandidateGit(repositoryRoot, ["write-tree"], void 0, gitEnvironment)).stdout.toString("utf8").trim();
|
|
1582
|
+
if (resultTree !== input.resultTree) throw new Error(`task outcome patch materialized tree ${resultTree} does not match ${input.resultTree}`);
|
|
1583
|
+
await assertSafeTree(repositoryRoot, resultTree, gitEnvironment);
|
|
1584
|
+
const observed = await workspaceManifestFromGitTree(repositoryRoot, resultTree, gitEnvironment);
|
|
1585
|
+
if (!Buffer.from(canonicalCandidateBytes$1(observed)).equals(Buffer.from(canonicalCandidateBytes$1(input.afterState)))) throw new Error("task outcome after-state does not match the materialized result tree");
|
|
1586
|
+
const resultCommit = (await runCandidateGit(repositoryRoot, [
|
|
1587
|
+
"commit-tree",
|
|
1588
|
+
resultTree,
|
|
1589
|
+
"-p",
|
|
1590
|
+
input.baseCommit
|
|
1591
|
+
], Buffer.from("candidate task outcome\n", "utf8"), {
|
|
1592
|
+
...gitEnvironment,
|
|
1593
|
+
GIT_AUTHOR_NAME: "Tangle Evaluator",
|
|
1594
|
+
GIT_AUTHOR_EMAIL: "evaluator@tangle.tools",
|
|
1595
|
+
GIT_AUTHOR_DATE: "2000-01-01T00:00:00Z",
|
|
1596
|
+
GIT_COMMITTER_NAME: "Tangle Evaluator",
|
|
1597
|
+
GIT_COMMITTER_EMAIL: "evaluator@tangle.tools",
|
|
1598
|
+
GIT_COMMITTER_DATE: "2000-01-01T00:00:00Z"
|
|
1599
|
+
})).stdout.toString("utf8").trim();
|
|
1600
|
+
if ((await runCandidateGit(repositoryRoot, ["rev-parse", `${resultCommit}^{tree}`], void 0, gitEnvironment)).stdout.toString("utf8").trim() !== resultTree) throw new Error("task outcome evaluator commit does not bind the verified result tree");
|
|
1601
|
+
return {
|
|
1602
|
+
resultTree,
|
|
1603
|
+
resultCommit
|
|
1604
|
+
};
|
|
1605
|
+
} finally {
|
|
1606
|
+
await rm(temporary, {
|
|
1607
|
+
recursive: true,
|
|
1608
|
+
force: true
|
|
1609
|
+
});
|
|
1610
|
+
}
|
|
1611
|
+
}
|
|
1612
|
+
async function verifiedRepositoryRoot(repository, repositories) {
|
|
1613
|
+
const repositoryRoot = resolve(await repositories.resolve(repository));
|
|
1614
|
+
if (!(await stat(repositoryRoot)).isDirectory()) throw new Error("candidate repository path is not a directory");
|
|
1615
|
+
const origin = (await runCandidateGit(repositoryRoot, [
|
|
1616
|
+
"remote",
|
|
1617
|
+
"get-url",
|
|
1618
|
+
"origin"
|
|
1619
|
+
])).stdout.toString("utf8").trim();
|
|
1620
|
+
const actual = parseGitHubRemote(origin);
|
|
1621
|
+
if (!actual || actual.owner !== repository.owner || actual.repo !== repository.repo) throw new Error(`local repository origin ${origin || "<missing>"} does not match github.com/${repository.owner}/${repository.repo}`);
|
|
1622
|
+
await assertNoGitIndirection(repositoryRoot, resolve((await runCandidateGit(repositoryRoot, ["rev-parse", "--absolute-git-dir"])).stdout.toString("utf8").trim()), "candidate repository");
|
|
1623
|
+
return repositoryRoot;
|
|
1624
|
+
}
|
|
1625
|
+
async function assertNoGitIndirection(repositoryRoot, gitDir, label) {
|
|
1626
|
+
if ((await runCandidateGit(repositoryRoot, [
|
|
1627
|
+
"for-each-ref",
|
|
1628
|
+
"--format=%(refname)",
|
|
1629
|
+
"refs/replace"
|
|
1630
|
+
])).stdout.toString("utf8").trim()) throw new Error(`${label} contains Git replace refs`);
|
|
1631
|
+
const commonDir = await realpath(resolve(repositoryRoot, (await runCandidateGit(repositoryRoot, ["rev-parse", "--git-common-dir"])).stdout.toString("utf8").trim()));
|
|
1632
|
+
if (commonDir.includes(":")) throw new Error(`${label} Git common directory has an unsupported path`);
|
|
1633
|
+
for (const objectRoot of /* @__PURE__ */ new Set([gitDir, commonDir])) for (const name of ["alternates", "http-alternates"]) {
|
|
1634
|
+
const path = join(objectRoot, "objects", "info", name);
|
|
1635
|
+
try {
|
|
1636
|
+
if ((await readFile(path, "utf8")).trim()) throw new Error(`${label} uses forbidden Git ${name}`);
|
|
1637
|
+
} catch (error) {
|
|
1638
|
+
if (!isNoEntry(error)) throw error;
|
|
1639
|
+
}
|
|
1640
|
+
}
|
|
1641
|
+
}
|
|
1642
|
+
async function assertCommitAndBaseTree(repositoryRoot, commit, expectedTree) {
|
|
1643
|
+
if ((await runCandidateGit(repositoryRoot, [
|
|
1644
|
+
"cat-file",
|
|
1645
|
+
"-t",
|
|
1646
|
+
commit
|
|
1647
|
+
])).stdout.toString("utf8").trim() !== "commit") throw new Error(`candidate base object is not a commit: ${commit}`);
|
|
1648
|
+
const actualTree = (await runCandidateGit(repositoryRoot, ["rev-parse", `${commit}^{tree}`])).stdout.toString("utf8").trim();
|
|
1649
|
+
if (actualTree !== expectedTree) throw new Error(`candidate base commit tree ${actualTree} does not match ${expectedTree}`);
|
|
1650
|
+
}
|
|
1651
|
+
async function assertSafeTree(repositoryRoot, tree, environment = {}) {
|
|
1202
1652
|
const listing = (await runCandidateGit(repositoryRoot, [
|
|
1203
1653
|
"ls-tree",
|
|
1204
1654
|
"-rz",
|
|
@@ -1269,14 +1719,7 @@ function parseTreeEntries(bytes) {
|
|
|
1269
1719
|
});
|
|
1270
1720
|
}
|
|
1271
1721
|
function assertSafeGitPath(path) {
|
|
1272
|
-
if (!path || path.startsWith("/") || path.includes("\\") || path.includes("\0") || hasControlCharacter
|
|
1273
|
-
}
|
|
1274
|
-
function hasControlCharacter$1(value) {
|
|
1275
|
-
for (let index = 0; index < value.length; index++) {
|
|
1276
|
-
const code = value.charCodeAt(index);
|
|
1277
|
-
if (code < 32 || code === 127) return true;
|
|
1278
|
-
}
|
|
1279
|
-
return false;
|
|
1722
|
+
if (!path || path.startsWith("/") || path.includes("\\") || path.includes("\0") || hasControlCharacter(path) || path.split("/").some((part) => !part || part === "." || part === "..") || path.split("/")[0]?.toLowerCase() === ".git") throw new Error(`candidate Git tree contains an unsafe path: ${path}`);
|
|
1280
1723
|
}
|
|
1281
1724
|
function parseGitHubRemote(value) {
|
|
1282
1725
|
const match = value.match(/^(?:https?:\/\/github\.com\/|ssh:\/\/git@github\.com\/|git@github\.com:)([^/]+)\/([^/]+?)(?:\.git)?$/);
|
|
@@ -1371,91 +1814,21 @@ function isNoEntry(error) {
|
|
|
1371
1814
|
return typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT";
|
|
1372
1815
|
}
|
|
1373
1816
|
//#endregion
|
|
1374
|
-
//#region src/candidate-execution/
|
|
1375
|
-
/** Persist evaluator evidence, read it back, and bind the returned locator to the exact bytes. */
|
|
1376
|
-
async function persistCandidateOutputArtifact(port, input) {
|
|
1377
|
-
input.signal?.throwIfAborted();
|
|
1378
|
-
const bytes = Uint8Array.from(input.bytes);
|
|
1379
|
-
const expectedDigest = sha256Bytes$1(bytes);
|
|
1380
|
-
const ref = agentCandidateArtifactRefSchema.parse(await port.put({
|
|
1381
|
-
executionId: input.executionId,
|
|
1382
|
-
purpose: input.purpose,
|
|
1383
|
-
bytes: Uint8Array.from(bytes),
|
|
1384
|
-
...input.signal ? { signal: input.signal } : {}
|
|
1385
|
-
}));
|
|
1386
|
-
input.signal?.throwIfAborted();
|
|
1387
|
-
if (ref.sha256 !== expectedDigest || ref.byteLength !== bytes.byteLength) throw new Error("candidate output locator does not identify the submitted bytes");
|
|
1388
|
-
const stored = await port.read(ref);
|
|
1389
|
-
input.signal?.throwIfAborted();
|
|
1390
|
-
verifyBytes(stored, expectedDigest, bytes.byteLength, "persisted candidate output");
|
|
1391
|
-
return immutableCandidateValue(ref);
|
|
1392
|
-
}
|
|
1393
|
-
//#endregion
|
|
1394
|
-
//#region src/candidate-execution/workspace-archive.ts
|
|
1395
|
-
const archiveKind = "agent-candidate-workspace-archive";
|
|
1396
|
-
const workspaceEntryPrefix = "workspace/";
|
|
1397
|
-
const repositoryMetadataEntry = "metadata/repository.json";
|
|
1398
|
-
const repositoryBundleEntry = "metadata/repository.bundle";
|
|
1399
|
-
const repositoryIndexEntry = "metadata/repository.index.json";
|
|
1400
|
-
const repositoryIndexPrefix = "index/";
|
|
1401
|
-
const fixedTarTime = /* @__PURE__ */ new Date(0);
|
|
1402
|
-
const defaultLimits = Object.freeze({
|
|
1403
|
-
maxArchiveBytes: 512 * 1024 * 1024,
|
|
1404
|
-
maxEmbeddedArtifactBytes: 1024 * 1024,
|
|
1405
|
-
maxFiles: 5e4,
|
|
1406
|
-
maxFileBytes: 128 * 1024 * 1024,
|
|
1407
|
-
maxTotalFileBytes: 256 * 1024 * 1024,
|
|
1408
|
-
maxPathBytes: 4096,
|
|
1409
|
-
maxRepositoryBundleBytes: 128 * 1024 * 1024
|
|
1410
|
-
});
|
|
1817
|
+
//#region src/candidate-execution/workspace-archive-local.ts
|
|
1411
1818
|
/** Capture one exact regular-file workspace for immutable candidate execution. */
|
|
1412
|
-
async function captureAgentCandidateWorkspace(rootInput, options = {}) {
|
|
1413
|
-
const root = resolve(rootInput);
|
|
1414
|
-
const limits = workspaceLimits(options.limits);
|
|
1415
|
-
if (options.repositoryContents !== void 0 && options.repositoryContents !== "head" && options.repositoryContents !== "working-tree") throw new Error("candidate repositoryContents is invalid");
|
|
1416
|
-
if (options.repositoryContents !== void 0 && !options.includeRepository) throw new Error("candidate repositoryContents requires includeRepository");
|
|
1417
|
-
const captured = options.includeRepository ? await captureRepository(root, limits, options.repositoryContents === "working-tree") : await captureMaterializedWorkspace(root, { limits: {
|
|
1418
|
-
maxFiles: limits.maxFiles,
|
|
1419
|
-
maxFileBytes: limits.maxFileBytes,
|
|
1420
|
-
maxTotalFileBytes: limits.maxTotalFileBytes
|
|
1421
|
-
} });
|
|
1422
|
-
assertWorkspaceFilesWithinLimits(captured.files, limits);
|
|
1423
|
-
const repository = "repository" in captured ? captured.repository : void 0;
|
|
1424
|
-
return captureWorkspaceFiles(captured.files, repository, limits, options.artifactPersistence);
|
|
1425
|
-
}
|
|
1426
|
-
/** Capture detached files returned by a remote executor into the standard archive. */
|
|
1427
|
-
async function captureAgentCandidateWorkspaceFiles(input, options = {}) {
|
|
1428
|
-
const limits = workspaceLimits(options.limits);
|
|
1429
|
-
return captureWorkspaceFiles(normalizeWorkspaceFiles(input, limits), void 0, limits, options.artifactPersistence);
|
|
1430
|
-
}
|
|
1431
|
-
async function captureWorkspaceFiles(files, repository, limits, artifactPersistence) {
|
|
1432
|
-
const material = candidateWorkspaceManifest(files);
|
|
1433
|
-
const manifest = canonicalCandidateBytes$1(material);
|
|
1434
|
-
const archive = await encodeWorkspaceArchive(files, repository, limits.maxArchiveBytes);
|
|
1435
|
-
if (!artifactPersistence && (manifest.byteLength > limits.maxEmbeddedArtifactBytes || archive.byteLength > limits.maxEmbeddedArtifactBytes)) throw new Error("candidate workspace artifacts exceed maxEmbeddedArtifactBytes; artifactPersistence is required");
|
|
1436
|
-
const manifestArtifact = await captureWorkspaceArtifact("manifest", manifest, artifactPersistence);
|
|
1437
|
-
const archiveArtifact = await captureWorkspaceArtifact("archive", archive, artifactPersistence);
|
|
1438
|
-
const snapshot = deepFreezeCandidate({
|
|
1439
|
-
kind: "agent-candidate-workspace-snapshot",
|
|
1440
|
-
digest: canonicalCandidateDigest$1(material),
|
|
1441
|
-
material,
|
|
1442
|
-
manifest: manifestArtifact,
|
|
1443
|
-
archive: archiveArtifact
|
|
1444
|
-
});
|
|
1445
|
-
return Object.freeze({
|
|
1446
|
-
snapshot,
|
|
1447
|
-
archive
|
|
1448
|
-
});
|
|
1449
|
-
}
|
|
1450
|
-
async function captureWorkspaceArtifact(kind, bytes, persistence) {
|
|
1451
|
-
if (!persistence) return embeddedCandidateArtifact(bytes);
|
|
1452
|
-
if (!persistence.executionId.trim()) throw new Error("candidate workspace artifact persistence requires an executionId");
|
|
1453
|
-
return persistCandidateOutputArtifact(persistence.outputArtifacts, {
|
|
1454
|
-
executionId: persistence.executionId,
|
|
1455
|
-
purpose: kind === "manifest" ? "candidate-workspace-manifest" : "candidate-workspace-archive",
|
|
1456
|
-
bytes,
|
|
1457
|
-
...persistence.signal ? { signal: persistence.signal } : {}
|
|
1458
|
-
});
|
|
1819
|
+
async function captureAgentCandidateWorkspace(rootInput, options = {}) {
|
|
1820
|
+
const root = resolve(rootInput);
|
|
1821
|
+
const limits = workspaceLimits(options.limits);
|
|
1822
|
+
if (options.repositoryContents !== void 0 && options.repositoryContents !== "head" && options.repositoryContents !== "working-tree") throw new Error("candidate repositoryContents is invalid");
|
|
1823
|
+
if (options.repositoryContents !== void 0 && !options.includeRepository) throw new Error("candidate repositoryContents requires includeRepository");
|
|
1824
|
+
const captured = options.includeRepository ? await captureRepository(root, limits, options.repositoryContents === "working-tree") : await captureMaterializedWorkspace(root, { limits: {
|
|
1825
|
+
maxFiles: limits.maxFiles,
|
|
1826
|
+
maxFileBytes: limits.maxFileBytes,
|
|
1827
|
+
maxTotalFileBytes: limits.maxTotalFileBytes
|
|
1828
|
+
} });
|
|
1829
|
+
assertWorkspaceFilesWithinLimits(captured.files, limits);
|
|
1830
|
+
const repository = "repository" in captured ? captured.repository : void 0;
|
|
1831
|
+
return captureWorkspaceFiles(captured.files, repository, limits, options.artifactPersistence);
|
|
1459
1832
|
}
|
|
1460
1833
|
/** Create the standard bounded materializer for candidate execution ports. */
|
|
1461
1834
|
function createAgentCandidateWorkspacePort(options = {}) {
|
|
@@ -1495,20 +1868,6 @@ async function materializeAgentCandidateWorkspace(input) {
|
|
|
1495
1868
|
throw error;
|
|
1496
1869
|
}
|
|
1497
1870
|
}
|
|
1498
|
-
/** Verify a portable archive before its source environment may be discarded. */
|
|
1499
|
-
async function verifyAgentCandidateWorkspaceArchive(input) {
|
|
1500
|
-
await decodeVerifiedWorkspaceArchive({
|
|
1501
|
-
...input,
|
|
1502
|
-
limits: workspaceLimits(input.limits)
|
|
1503
|
-
});
|
|
1504
|
-
}
|
|
1505
|
-
async function decodeVerifiedWorkspaceArchive(input) {
|
|
1506
|
-
verifyBytes(input.archive, input.snapshot.archive.sha256, input.snapshot.archive.byteLength, "candidate workspace archive");
|
|
1507
|
-
const decoded = await parseWorkspaceArchive(input.archive, input.limits);
|
|
1508
|
-
if (decoded.repository && input.role !== "task") throw new Error("only task workspaces may carry a Git repository");
|
|
1509
|
-
assertArchiveMatchesSnapshot(decoded.files, input.snapshot);
|
|
1510
|
-
return decoded;
|
|
1511
|
-
}
|
|
1512
1871
|
async function captureRepository(requestedRoot, limits, workingTree) {
|
|
1513
1872
|
const requestedStats = await lstat(requestedRoot);
|
|
1514
1873
|
if (!requestedStats.isDirectory() || requestedStats.isSymbolicLink()) throw new Error("candidate repository root must be a real directory");
|
|
@@ -1611,309 +1970,78 @@ async function readRepositoryWorkingState(root, limits) {
|
|
|
1611
1970
|
if (size > limits.maxFileBytes) throw new Error(`candidate Git index file exceeds maxFileBytes: ${entry.path}`);
|
|
1612
1971
|
if (size > limits.maxTotalFileBytes - totalBytes) throw new Error("candidate Git index exceeds maxTotalFileBytes");
|
|
1613
1972
|
totalBytes += size;
|
|
1614
|
-
return size;
|
|
1615
|
-
});
|
|
1616
|
-
const files = [];
|
|
1617
|
-
for (const [index, entry] of entries.entries()) {
|
|
1618
|
-
const bytes = (await runCandidateGit(root, [
|
|
1619
|
-
"cat-file",
|
|
1620
|
-
"blob",
|
|
1621
|
-
entry.object
|
|
1622
|
-
], void 0, env, { maxOutputBytes: limits.maxFileBytes })).stdout;
|
|
1623
|
-
if (bytes.byteLength !== byteLengths[index]) throw new Error("candidate Git index blob size changed");
|
|
1624
|
-
files.push({
|
|
1625
|
-
path: entry.path,
|
|
1626
|
-
mode: entry.mode,
|
|
1627
|
-
bytes: Uint8Array.from(bytes)
|
|
1628
|
-
});
|
|
1629
|
-
}
|
|
1630
|
-
files.sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0);
|
|
1631
|
-
assertWorkspaceFilesWithinLimits(files, limits);
|
|
1632
|
-
const defaultExcludes = join(process.env.XDG_CONFIG_HOME || join(homedir(), ".config"), "git", "ignore");
|
|
1633
|
-
const excludes = new TextDecoder("utf-8", { fatal: true }).decode((await runCandidateGit(root, [
|
|
1634
|
-
"config",
|
|
1635
|
-
"--includes",
|
|
1636
|
-
"--path",
|
|
1637
|
-
"--default",
|
|
1638
|
-
defaultExcludes,
|
|
1639
|
-
"--get",
|
|
1640
|
-
"core.excludesFile"
|
|
1641
|
-
], void 0, {}, {
|
|
1642
|
-
maxOutputBytes: limits.maxPathBytes,
|
|
1643
|
-
readUserExclusions: true
|
|
1644
|
-
})).stdout).replace(/\n$/u, "");
|
|
1645
|
-
const paths = new TextDecoder("utf-8", { fatal: true }).decode((await runCandidateGit(root, [
|
|
1646
|
-
"-c",
|
|
1647
|
-
`core.excludesFile=${excludes}`,
|
|
1648
|
-
"ls-files",
|
|
1649
|
-
"--cached",
|
|
1650
|
-
"--others",
|
|
1651
|
-
"--exclude-standard",
|
|
1652
|
-
"-z"
|
|
1653
|
-
], void 0, env, { maxOutputBytes: listingLimit })).stdout);
|
|
1654
|
-
for (const path of paths.split("\0").filter(Boolean)) safeArchivePath(path, limits.maxPathBytes);
|
|
1655
|
-
return {
|
|
1656
|
-
paths,
|
|
1657
|
-
index,
|
|
1658
|
-
files
|
|
1659
|
-
};
|
|
1660
|
-
}
|
|
1661
|
-
async function captureRepositoryWorkingTree(root, limits) {
|
|
1662
|
-
const state = await readRepositoryWorkingState(root, limits);
|
|
1663
|
-
return {
|
|
1664
|
-
state,
|
|
1665
|
-
files: [...(await captureMaterializedWorkspace(root, {
|
|
1666
|
-
ignoredProtectedRootEntries: [".git"],
|
|
1667
|
-
selectedPaths: await existingRepositoryPaths(root, state.paths, limits),
|
|
1668
|
-
limits
|
|
1669
|
-
})).files].sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0)
|
|
1670
|
-
};
|
|
1671
|
-
}
|
|
1672
|
-
async function existingRepositoryPaths(root, listing, limits) {
|
|
1673
|
-
const paths = [...new Set(listing.split("\0").filter(Boolean))].sort();
|
|
1674
|
-
if (paths.length > limits.maxFiles) throw new Error("candidate workspace exceeds maxFiles");
|
|
1675
|
-
const selectedPaths = [];
|
|
1676
|
-
for (const path of paths) {
|
|
1677
|
-
const safe = safeArchivePath(path, limits.maxPathBytes);
|
|
1678
|
-
try {
|
|
1679
|
-
await lstat(workspacePath(root, safe));
|
|
1680
|
-
selectedPaths.push(safe);
|
|
1681
|
-
} catch (error) {
|
|
1682
|
-
if (!(error instanceof Error && "code" in error && error.code === "ENOENT")) throw error;
|
|
1683
|
-
}
|
|
1684
|
-
}
|
|
1685
|
-
return selectedPaths;
|
|
1686
|
-
}
|
|
1687
|
-
async function encodeWorkspaceArchive(files, repository, maxArchiveBytes) {
|
|
1688
|
-
const archive = pack();
|
|
1689
|
-
const output = collectStream(archive, maxArchiveBytes, "candidate workspace archive");
|
|
1690
|
-
try {
|
|
1691
|
-
await writeWorkspaceArchiveEntries(archive, files, repository);
|
|
1692
|
-
archive.finalize();
|
|
1693
|
-
return await output;
|
|
1694
|
-
} catch (error) {
|
|
1695
|
-
archive.destroy(error instanceof Error ? error : new Error(String(error)));
|
|
1696
|
-
await output.catch(() => void 0);
|
|
1697
|
-
throw error;
|
|
1698
|
-
}
|
|
1699
|
-
}
|
|
1700
|
-
async function verifyCanonicalWorkspaceArchive(files, repository, expected, maxArchiveBytes) {
|
|
1701
|
-
const archive = pack();
|
|
1702
|
-
const comparison = streamEqualsBytes(archive, expected, maxArchiveBytes, "candidate workspace archive");
|
|
1703
|
-
try {
|
|
1704
|
-
await writeWorkspaceArchiveEntries(archive, files, repository);
|
|
1705
|
-
archive.finalize();
|
|
1706
|
-
if (!await comparison) throw new Error("candidate workspace tar is not canonical");
|
|
1707
|
-
} catch (error) {
|
|
1708
|
-
archive.destroy(error instanceof Error ? error : new Error(String(error)));
|
|
1709
|
-
await comparison.catch(() => void 0);
|
|
1710
|
-
throw error;
|
|
1711
|
-
}
|
|
1712
|
-
}
|
|
1713
|
-
async function writeWorkspaceArchiveEntries(archive, files, repository) {
|
|
1714
|
-
for (const file of files) await writeTarEntry(archive, `${workspaceEntryPrefix}${file.path}`, file.mode, file.bytes);
|
|
1715
|
-
if (!repository) return;
|
|
1716
|
-
const indexManifest = repository.workingTree ? canonicalCandidateBytes$1(candidateWorkspaceManifest(repository.workingTree.files)) : void 0;
|
|
1717
|
-
const metadata = canonicalCandidateBytes$1({
|
|
1718
|
-
kind: archiveKind,
|
|
1719
|
-
headCommit: repository.headCommit,
|
|
1720
|
-
headTree: repository.headTree,
|
|
1721
|
-
bundle: {
|
|
1722
|
-
sha256: repository.bundle.sha256,
|
|
1723
|
-
byteLength: repository.bundle.byteLength
|
|
1724
|
-
},
|
|
1725
|
-
...indexManifest ? { workingTree: { indexManifest: {
|
|
1726
|
-
sha256: sha256Bytes$1(indexManifest),
|
|
1727
|
-
byteLength: indexManifest.byteLength
|
|
1728
|
-
} } } : {}
|
|
1729
|
-
});
|
|
1730
|
-
await writeTarEntry(archive, repositoryMetadataEntry, 384, metadata);
|
|
1731
|
-
await writeTarEntry(archive, repositoryBundleEntry, 384, repository.bundle.bytes);
|
|
1732
|
-
if (repository.workingTree && indexManifest) {
|
|
1733
|
-
await writeTarEntry(archive, repositoryIndexEntry, 384, indexManifest);
|
|
1734
|
-
for (const file of repository.workingTree.files) await writeTarEntry(archive, `${repositoryIndexPrefix}${file.path}`, file.mode, file.bytes);
|
|
1735
|
-
}
|
|
1736
|
-
}
|
|
1737
|
-
async function parseWorkspaceArchive(bytes, limits) {
|
|
1738
|
-
if (bytes.byteLength > limits.maxArchiveBytes) throw new Error("candidate workspace archive exceeds maxArchiveBytes");
|
|
1739
|
-
const parser = extract();
|
|
1740
|
-
const files = [];
|
|
1741
|
-
const observedEntryNames = /* @__PURE__ */ new Set();
|
|
1742
|
-
const observedPaths = /* @__PURE__ */ new Set();
|
|
1743
|
-
let totalBytes = 0;
|
|
1744
|
-
let retainedEntryBytes = 0;
|
|
1745
|
-
let previousPath;
|
|
1746
|
-
let repositoryMetadata;
|
|
1747
|
-
let repositoryBundle;
|
|
1748
|
-
let repositoryIndex;
|
|
1749
|
-
const indexFiles = [];
|
|
1750
|
-
const indexPaths = /* @__PURE__ */ new Set();
|
|
1751
|
-
let previousIndexPath;
|
|
1752
|
-
let indexBytes = 0;
|
|
1753
|
-
const decoded = (async () => {
|
|
1754
|
-
for await (const entry of parser) {
|
|
1755
|
-
const name = entry.header.name;
|
|
1756
|
-
if (entry.header.type !== "file" || typeof name !== "string" || observedEntryNames.has(name)) throw new Error("candidate workspace tar contains an invalid entry");
|
|
1757
|
-
observedEntryNames.add(name);
|
|
1758
|
-
if (name.startsWith(workspaceEntryPrefix)) {
|
|
1759
|
-
if (files.length >= limits.maxFiles) throw new Error("candidate workspace archive has an invalid file count");
|
|
1760
|
-
const path = safeArchivePath(name.slice(10), limits.maxPathBytes);
|
|
1761
|
-
if (!isWorkspaceFileMode(entry.header.mode)) throw new Error(`candidate workspace archive has an unsupported mode: ${path}`);
|
|
1762
|
-
assertRetainedArchiveSize(bytes.byteLength, retainedEntryBytes, entry.header.size, limits);
|
|
1763
|
-
const fileBytes = await readTarEntry(entry, limits.maxFileBytes, `workspace file ${path}`);
|
|
1764
|
-
retainedEntryBytes += fileBytes.byteLength;
|
|
1765
|
-
assertWorkspacePathOrder(path, previousPath, observedPaths, "candidate workspace archive paths must be unique and sorted");
|
|
1766
|
-
previousPath = path;
|
|
1767
|
-
if (fileBytes.byteLength > limits.maxTotalFileBytes - totalBytes) throw new Error("candidate workspace archive exceeds maxTotalFileBytes");
|
|
1768
|
-
totalBytes += fileBytes.byteLength;
|
|
1769
|
-
files.push({
|
|
1770
|
-
path,
|
|
1771
|
-
mode: entry.header.mode,
|
|
1772
|
-
bytes: fileBytes
|
|
1773
|
-
});
|
|
1774
|
-
} else if (name === repositoryMetadataEntry) {
|
|
1775
|
-
if (entry.header.mode !== 384 || repositoryMetadata) throw new Error("candidate workspace archive repository metadata is invalid");
|
|
1776
|
-
assertRetainedArchiveSize(bytes.byteLength, retainedEntryBytes, entry.header.size, limits);
|
|
1777
|
-
const metadataBytes = await readTarEntry(entry, limits.maxPathBytes, "candidate repository metadata");
|
|
1778
|
-
retainedEntryBytes += metadataBytes.byteLength;
|
|
1779
|
-
repositoryMetadata = parseRepositoryMetadata(metadataBytes, limits);
|
|
1780
|
-
} else if (name === repositoryBundleEntry) {
|
|
1781
|
-
if (entry.header.mode !== 384 || repositoryBundle) throw new Error("candidate workspace archive repository bundle is invalid");
|
|
1782
|
-
assertRetainedArchiveSize(bytes.byteLength, retainedEntryBytes, entry.header.size, limits);
|
|
1783
|
-
repositoryBundle = await readTarEntry(entry, limits.maxRepositoryBundleBytes, "candidate Git bundle");
|
|
1784
|
-
retainedEntryBytes += repositoryBundle.byteLength;
|
|
1785
|
-
} else if (name === repositoryIndexEntry) {
|
|
1786
|
-
if (entry.header.mode !== 384 || repositoryIndex) throw new Error("candidate workspace archive repository index is invalid");
|
|
1787
|
-
assertRetainedArchiveSize(bytes.byteLength, retainedEntryBytes, entry.header.size, limits);
|
|
1788
|
-
repositoryIndex = await readTarEntry(entry, limits.maxArchiveBytes, "candidate Git index manifest");
|
|
1789
|
-
retainedEntryBytes += repositoryIndex.byteLength;
|
|
1790
|
-
} else if (name.startsWith(repositoryIndexPrefix)) {
|
|
1791
|
-
if (!repositoryMetadata?.workingTree || !repositoryIndex || indexFiles.length >= limits.maxFiles) throw new Error("candidate Git index evidence is incomplete or exceeds maxFiles");
|
|
1792
|
-
const path = safeArchivePath(name.slice(6), limits.maxPathBytes);
|
|
1793
|
-
if (entry.header.mode !== 420 && entry.header.mode !== 493) throw new Error("candidate Git index contains an unsupported mode");
|
|
1794
|
-
assertWorkspacePathOrder(path, previousIndexPath, indexPaths, "candidate Git index paths must be unique and sorted");
|
|
1795
|
-
previousIndexPath = path;
|
|
1796
|
-
assertRetainedArchiveSize(bytes.byteLength, retainedEntryBytes, entry.header.size, limits);
|
|
1797
|
-
if (entry.header.size === void 0 || entry.header.size > limits.maxTotalFileBytes - indexBytes) throw new Error("candidate Git index exceeds maxTotalFileBytes");
|
|
1798
|
-
if (entry.header.size > limits.maxFileBytes) throw new Error("candidate Git index exceeds maxFileBytes");
|
|
1799
|
-
const fileBytes = await readTarEntry(entry, limits.maxFileBytes, `Git index file ${path}`);
|
|
1800
|
-
retainedEntryBytes += fileBytes.byteLength;
|
|
1801
|
-
indexBytes += fileBytes.byteLength;
|
|
1802
|
-
indexFiles.push({
|
|
1803
|
-
path,
|
|
1804
|
-
mode: entry.header.mode,
|
|
1805
|
-
bytes: fileBytes
|
|
1806
|
-
});
|
|
1807
|
-
} else throw new Error(`candidate workspace tar contains an unsupported entry: ${name}`);
|
|
1808
|
-
}
|
|
1809
|
-
if (Boolean(repositoryMetadata) !== Boolean(repositoryBundle)) throw new Error("candidate workspace archive repository evidence is incomplete");
|
|
1810
|
-
if (Boolean(repositoryMetadata?.workingTree) !== Boolean(repositoryIndex)) throw new Error("candidate workspace archive repository index evidence is incomplete");
|
|
1811
|
-
const repository = repositoryMetadata && repositoryBundle ? repositoryFromTar(repositoryMetadata, repositoryBundle, repositoryIndex, indexFiles) : void 0;
|
|
1812
|
-
return {
|
|
1813
|
-
files,
|
|
1814
|
-
...repository ? { repository } : {}
|
|
1815
|
-
};
|
|
1816
|
-
})();
|
|
1817
|
-
parser.end(Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength));
|
|
1818
|
-
const result = await decoded;
|
|
1819
|
-
await verifyCanonicalWorkspaceArchive(result.files, result.repository, bytes, limits.maxArchiveBytes);
|
|
1820
|
-
return result;
|
|
1821
|
-
}
|
|
1822
|
-
function assertRetainedArchiveSize(archiveBytes, retainedEntryBytes, entryBytes, limits) {
|
|
1823
|
-
if (!Number.isSafeInteger(entryBytes) || entryBytes === void 0 || entryBytes < 0 || entryBytes > limits.maxArchiveBytes - archiveBytes - retainedEntryBytes) throw new Error("candidate workspace archive exceeds maxArchiveBytes while decoding");
|
|
1824
|
-
}
|
|
1825
|
-
function parseRepositoryMetadata(bytes, limits) {
|
|
1826
|
-
let value;
|
|
1827
|
-
try {
|
|
1828
|
-
value = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes));
|
|
1829
|
-
} catch (error) {
|
|
1830
|
-
throw new Error("candidate workspace archive repository metadata is invalid", { cause: error });
|
|
1831
|
-
}
|
|
1832
|
-
if (!isRecord$1(value) || !["bundle,headCommit,headTree,kind", "bundle,headCommit,headTree,kind,workingTree"].includes(Object.keys(value).sort().join(",")) || value.kind !== archiveKind || typeof value.headCommit !== "string" || typeof value.headTree !== "string" || !isRecord$1(value.bundle) || Object.keys(value.bundle).sort().join(",") !== "byteLength,sha256" || typeof value.bundle.sha256 !== "string" || !/^sha256:[a-f0-9]{64}$/.test(value.bundle.sha256) || !Number.isSafeInteger(value.bundle.byteLength) || value.bundle.byteLength <= 0 || value.bundle.byteLength > limits.maxRepositoryBundleBytes) throw new Error("candidate workspace archive repository is invalid");
|
|
1833
|
-
if (!Buffer.from(canonicalCandidateBytes$1(value)).equals(Buffer.from(bytes))) throw new Error("candidate workspace archive repository metadata is not canonical");
|
|
1834
|
-
assertGitObjectId(value.headCommit, "repository HEAD");
|
|
1835
|
-
assertGitObjectId(value.headTree, "repository HEAD tree");
|
|
1836
|
-
if (value.headCommit.length !== value.headTree.length) throw new Error("candidate repository HEAD and tree use different object formats");
|
|
1837
|
-
let workingTree;
|
|
1838
|
-
if ("workingTree" in value) {
|
|
1839
|
-
const working = value.workingTree;
|
|
1840
|
-
if (!isRecord$1(working) || Object.keys(working).join(",") !== "indexManifest" || !isRecord$1(working.indexManifest) || Object.keys(working.indexManifest).sort().join(",") !== "byteLength,sha256" || typeof working.indexManifest.sha256 !== "string" || !/^sha256:[a-f0-9]{64}$/.test(working.indexManifest.sha256) || !Number.isSafeInteger(working.indexManifest.byteLength) || working.indexManifest.byteLength < 0 || working.indexManifest.byteLength > limits.maxArchiveBytes) throw new Error("candidate workspace archive repository index is invalid");
|
|
1841
|
-
workingTree = { indexManifest: {
|
|
1842
|
-
sha256: working.indexManifest.sha256,
|
|
1843
|
-
byteLength: working.indexManifest.byteLength
|
|
1844
|
-
} };
|
|
1973
|
+
return size;
|
|
1974
|
+
});
|
|
1975
|
+
const files = [];
|
|
1976
|
+
for (const [index, entry] of entries.entries()) {
|
|
1977
|
+
const bytes = (await runCandidateGit(root, [
|
|
1978
|
+
"cat-file",
|
|
1979
|
+
"blob",
|
|
1980
|
+
entry.object
|
|
1981
|
+
], void 0, env, { maxOutputBytes: limits.maxFileBytes })).stdout;
|
|
1982
|
+
if (bytes.byteLength !== byteLengths[index]) throw new Error("candidate Git index blob size changed");
|
|
1983
|
+
files.push({
|
|
1984
|
+
path: entry.path,
|
|
1985
|
+
mode: entry.mode,
|
|
1986
|
+
bytes: Uint8Array.from(bytes)
|
|
1987
|
+
});
|
|
1845
1988
|
}
|
|
1989
|
+
files.sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0);
|
|
1990
|
+
assertWorkspaceFilesWithinLimits(files, limits);
|
|
1991
|
+
const defaultExcludes = join(process.env.XDG_CONFIG_HOME || join(homedir(), ".config"), "git", "ignore");
|
|
1992
|
+
const excludes = new TextDecoder("utf-8", { fatal: true }).decode((await runCandidateGit(root, [
|
|
1993
|
+
"config",
|
|
1994
|
+
"--includes",
|
|
1995
|
+
"--path",
|
|
1996
|
+
"--default",
|
|
1997
|
+
defaultExcludes,
|
|
1998
|
+
"--get",
|
|
1999
|
+
"core.excludesFile"
|
|
2000
|
+
], void 0, {}, {
|
|
2001
|
+
maxOutputBytes: limits.maxPathBytes,
|
|
2002
|
+
readUserExclusions: true
|
|
2003
|
+
})).stdout).replace(/\n$/u, "");
|
|
2004
|
+
const paths = new TextDecoder("utf-8", { fatal: true }).decode((await runCandidateGit(root, [
|
|
2005
|
+
"-c",
|
|
2006
|
+
`core.excludesFile=${excludes}`,
|
|
2007
|
+
"ls-files",
|
|
2008
|
+
"--cached",
|
|
2009
|
+
"--others",
|
|
2010
|
+
"--exclude-standard",
|
|
2011
|
+
"-z"
|
|
2012
|
+
], void 0, env, { maxOutputBytes: listingLimit })).stdout);
|
|
2013
|
+
for (const path of paths.split("\0").filter(Boolean)) safeArchivePath(path, limits.maxPathBytes);
|
|
1846
2014
|
return {
|
|
1847
|
-
|
|
1848
|
-
|
|
1849
|
-
|
|
1850
|
-
bundle: {
|
|
1851
|
-
sha256: value.bundle.sha256,
|
|
1852
|
-
byteLength: value.bundle.byteLength
|
|
1853
|
-
},
|
|
1854
|
-
...workingTree ? { workingTree } : {}
|
|
2015
|
+
paths,
|
|
2016
|
+
index,
|
|
2017
|
+
files
|
|
1855
2018
|
};
|
|
1856
2019
|
}
|
|
1857
|
-
function
|
|
1858
|
-
|
|
1859
|
-
if (metadata.workingTree && indexManifest) {
|
|
1860
|
-
verifyBytes(indexManifest, metadata.workingTree.indexManifest.sha256, metadata.workingTree.indexManifest.byteLength, "candidate Git index manifest");
|
|
1861
|
-
if (!Buffer.from(indexManifest).equals(Buffer.from(canonicalCandidateBytes$1(candidateWorkspaceManifest(indexFiles))))) throw new Error("candidate Git index files do not match the captured manifest");
|
|
1862
|
-
}
|
|
2020
|
+
async function captureRepositoryWorkingTree(root, limits) {
|
|
2021
|
+
const state = await readRepositoryWorkingState(root, limits);
|
|
1863
2022
|
return {
|
|
1864
|
-
|
|
1865
|
-
|
|
1866
|
-
|
|
1867
|
-
|
|
1868
|
-
|
|
1869
|
-
},
|
|
1870
|
-
...metadata.workingTree && indexManifest ? { workingTree: { files: indexFiles } } : {}
|
|
2023
|
+
state,
|
|
2024
|
+
files: [...(await captureMaterializedWorkspace(root, {
|
|
2025
|
+
ignoredProtectedRootEntries: [".git"],
|
|
2026
|
+
selectedPaths: await existingRepositoryPaths(root, state.paths, limits),
|
|
2027
|
+
limits
|
|
2028
|
+
})).files].sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0)
|
|
1871
2029
|
};
|
|
1872
2030
|
}
|
|
1873
|
-
async function
|
|
1874
|
-
|
|
1875
|
-
|
|
1876
|
-
|
|
1877
|
-
|
|
1878
|
-
|
|
1879
|
-
|
|
1880
|
-
|
|
1881
|
-
|
|
1882
|
-
|
|
1883
|
-
|
|
1884
|
-
}
|
|
1885
|
-
async function collectStream(stream, maxBytes, label) {
|
|
1886
|
-
const chunks = [];
|
|
1887
|
-
let totalBytes = 0;
|
|
1888
|
-
for await (const chunk of stream) {
|
|
1889
|
-
if (!(chunk instanceof Uint8Array)) throw new Error(`${label} emitted a non-byte chunk`);
|
|
1890
|
-
if (chunk.byteLength > maxBytes - totalBytes) {
|
|
1891
|
-
const error = /* @__PURE__ */ new Error(`${label} exceeds its size limit`);
|
|
1892
|
-
if ("destroy" in stream && typeof stream.destroy === "function") stream.destroy(error);
|
|
1893
|
-
throw error;
|
|
1894
|
-
}
|
|
1895
|
-
const bytes = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
|
|
1896
|
-
chunks.push(bytes);
|
|
1897
|
-
totalBytes += bytes.byteLength;
|
|
1898
|
-
}
|
|
1899
|
-
return Buffer.concat(chunks, totalBytes);
|
|
1900
|
-
}
|
|
1901
|
-
async function streamEqualsBytes(stream, expected, maxBytes, label) {
|
|
1902
|
-
const expectedBuffer = Buffer.from(expected.buffer, expected.byteOffset, expected.byteLength);
|
|
1903
|
-
let equal = true;
|
|
1904
|
-
let offset = 0;
|
|
1905
|
-
for await (const chunk of stream) {
|
|
1906
|
-
if (!(chunk instanceof Uint8Array)) throw new Error(`${label} emitted a non-byte chunk`);
|
|
1907
|
-
if (chunk.byteLength > maxBytes - offset) {
|
|
1908
|
-
const error = /* @__PURE__ */ new Error(`${label} exceeds its size limit`);
|
|
1909
|
-
if ("destroy" in stream && typeof stream.destroy === "function") stream.destroy(error);
|
|
1910
|
-
throw error;
|
|
2031
|
+
async function existingRepositoryPaths(root, listing, limits) {
|
|
2032
|
+
const paths = [...new Set(listing.split("\0").filter(Boolean))].sort();
|
|
2033
|
+
if (paths.length > limits.maxFiles) throw new Error("candidate workspace exceeds maxFiles");
|
|
2034
|
+
const selectedPaths = [];
|
|
2035
|
+
for (const path of paths) {
|
|
2036
|
+
const safe = safeArchivePath(path, limits.maxPathBytes);
|
|
2037
|
+
try {
|
|
2038
|
+
await lstat(workspacePath(root, safe));
|
|
2039
|
+
selectedPaths.push(safe);
|
|
2040
|
+
} catch (error) {
|
|
2041
|
+
if (!(error instanceof Error && "code" in error && error.code === "ENOENT")) throw error;
|
|
1911
2042
|
}
|
|
1912
|
-
const observed = Buffer.from(chunk.buffer, chunk.byteOffset, chunk.byteLength);
|
|
1913
|
-
if (offset + observed.byteLength > expectedBuffer.byteLength || !observed.equals(expectedBuffer.subarray(offset, offset + observed.byteLength))) equal = false;
|
|
1914
|
-
offset += observed.byteLength;
|
|
1915
2043
|
}
|
|
1916
|
-
return
|
|
2044
|
+
return selectedPaths;
|
|
1917
2045
|
}
|
|
1918
2046
|
async function prepareEmptyDestination(destination, options = {}) {
|
|
1919
2047
|
await mkdir(options.createDestination === false ? dirname(destination) : destination, {
|
|
@@ -2033,143 +2161,11 @@ async function materializeRepository(repository, destination, limits, signal) {
|
|
|
2033
2161
|
});
|
|
2034
2162
|
}
|
|
2035
2163
|
}
|
|
2036
|
-
function assertArchiveMatchesSnapshot(files, snapshot) {
|
|
2037
|
-
const material = candidateWorkspaceManifest(files);
|
|
2038
|
-
const materialBytes = canonicalCandidateBytes$1(material);
|
|
2039
|
-
verifyBytes(materialBytes, snapshot.manifest.sha256, snapshot.manifest.byteLength, "candidate workspace manifest");
|
|
2040
|
-
if (canonicalCandidateDigest$1(material) !== snapshot.digest || !Buffer.from(materialBytes).equals(Buffer.from(canonicalCandidateBytes$1(snapshot.material)))) throw new Error("candidate workspace archive does not match its snapshot manifest");
|
|
2041
|
-
}
|
|
2042
|
-
function assertWorkspaceFilesWithinLimits(files, limits) {
|
|
2043
|
-
if (files.length > limits.maxFiles) throw new Error("candidate workspace exceeds maxFiles");
|
|
2044
|
-
let totalBytes = 0;
|
|
2045
|
-
let previousPath;
|
|
2046
|
-
const observedPaths = /* @__PURE__ */ new Set();
|
|
2047
|
-
for (const file of files) {
|
|
2048
|
-
const path = safeArchivePath(file.path, limits.maxPathBytes);
|
|
2049
|
-
assertWorkspacePathOrder(path, previousPath, observedPaths, "candidate workspace paths must be unique and sorted");
|
|
2050
|
-
previousPath = path;
|
|
2051
|
-
if (!isWorkspaceFileMode(file.mode)) throw new Error(`candidate workspace file has unsupported mode: ${path}`);
|
|
2052
|
-
if (file.bytes.byteLength > limits.maxFileBytes) throw new Error(`candidate workspace file exceeds maxFileBytes: ${path}`);
|
|
2053
|
-
totalBytes += file.bytes.byteLength;
|
|
2054
|
-
if (totalBytes > limits.maxTotalFileBytes) throw new Error("candidate workspace exceeds maxTotalFileBytes");
|
|
2055
|
-
}
|
|
2056
|
-
}
|
|
2057
|
-
function normalizeWorkspaceFiles(input, limits) {
|
|
2058
|
-
if (!Array.isArray(input)) throw new Error("candidate workspace files must be an array");
|
|
2059
|
-
const fileCount = input.length;
|
|
2060
|
-
if (fileCount > limits.maxFiles) throw new Error("candidate workspace exceeds maxFiles");
|
|
2061
|
-
let totalBytes = 0;
|
|
2062
|
-
const files = [];
|
|
2063
|
-
for (let index = 0; index < fileCount; index++) {
|
|
2064
|
-
const inputFile = input[index];
|
|
2065
|
-
if (!isRecord$1(inputFile) || Object.keys(inputFile).sort().join(",") !== "bytes,mode,path") throw new Error(`candidate workspace file ${index} is invalid`);
|
|
2066
|
-
const descriptors = Object.getOwnPropertyDescriptors(inputFile);
|
|
2067
|
-
if (!("value" in (descriptors.path ?? {})) || !("value" in (descriptors.mode ?? {})) || !("value" in (descriptors.bytes ?? {}))) throw new Error(`candidate workspace file ${index} must use fixed values`);
|
|
2068
|
-
const path = safeArchivePath(descriptors.path?.value, limits.maxPathBytes);
|
|
2069
|
-
const mode = descriptors.mode?.value;
|
|
2070
|
-
const inputBytes = descriptors.bytes?.value;
|
|
2071
|
-
if (!isWorkspaceFileMode(mode)) throw new Error(`candidate workspace file has unsupported mode: ${path}`);
|
|
2072
|
-
const view = inspectWorkspaceBytes(inputBytes, path);
|
|
2073
|
-
if (view.byteLength > limits.maxFileBytes) throw new Error(`candidate workspace file exceeds maxFileBytes: ${path}`);
|
|
2074
|
-
if (view.byteLength > limits.maxTotalFileBytes - totalBytes) throw new Error("candidate workspace exceeds maxTotalFileBytes");
|
|
2075
|
-
if (view.byteLength > Math.max(0, limits.maxArchiveBytes - 1024)) throw new Error("candidate workspace archive exceeds maxArchiveBytes");
|
|
2076
|
-
totalBytes += view.byteLength;
|
|
2077
|
-
files.push({
|
|
2078
|
-
path,
|
|
2079
|
-
mode,
|
|
2080
|
-
bytes: detachWorkspaceBytes(view)
|
|
2081
|
-
});
|
|
2082
|
-
}
|
|
2083
|
-
files.sort((left, right) => left.path < right.path ? -1 : left.path > right.path ? 1 : 0);
|
|
2084
|
-
assertWorkspaceFilesWithinLimits(files, limits);
|
|
2085
|
-
return files;
|
|
2086
|
-
}
|
|
2087
|
-
function isWorkspaceFileMode(value) {
|
|
2088
|
-
return Number.isSafeInteger(value) && value >= 0 && value <= 511;
|
|
2089
|
-
}
|
|
2090
|
-
function workspaceLimits(overrides) {
|
|
2091
|
-
const limits = {
|
|
2092
|
-
...defaultLimits,
|
|
2093
|
-
...overrides
|
|
2094
|
-
};
|
|
2095
|
-
for (const [name, value] of Object.entries(limits)) if (!Number.isSafeInteger(value) || value <= 0) throw new Error(`candidate workspace ${name} must be a positive safe integer`);
|
|
2096
|
-
return Object.freeze(limits);
|
|
2097
|
-
}
|
|
2098
|
-
function safeArchivePath(value, maxPathBytes) {
|
|
2099
|
-
if (typeof value !== "string" || !value || !isWellFormedUnicode(value) || Buffer.byteLength(value, "utf8") > maxPathBytes || isAbsolute(value) || win32.isAbsolute(value) || value.includes("\\") || value.includes("\0") || hasControlCharacter(value) || value.split("/").some((part) => !part || part === "." || part === "..") || [".git", ".sidecar"].includes(value.split("/")[0]?.toLowerCase() ?? "")) throw new Error(`candidate workspace archive contains an unsafe path: ${String(value)}`);
|
|
2100
|
-
return value;
|
|
2101
|
-
}
|
|
2102
|
-
function assertWorkspacePathOrder(path, previousPath, observedPaths, errorMessage) {
|
|
2103
|
-
if (previousPath !== void 0 && previousPath >= path) throw new Error(errorMessage);
|
|
2104
|
-
for (let slash = path.indexOf("/"); slash !== -1; slash = path.indexOf("/", slash + 1)) if (observedPaths.has(path.slice(0, slash))) throw new Error(errorMessage);
|
|
2105
|
-
observedPaths.add(path);
|
|
2106
|
-
}
|
|
2107
|
-
function inspectWorkspaceBytes(input, path) {
|
|
2108
|
-
let buffer;
|
|
2109
|
-
let byteOffset;
|
|
2110
|
-
let byteLength;
|
|
2111
|
-
try {
|
|
2112
|
-
buffer = typedArrayBufferGetter.call(input);
|
|
2113
|
-
byteOffset = typedArrayByteOffsetGetter.call(input);
|
|
2114
|
-
byteLength = typedArrayByteLengthGetter.call(input);
|
|
2115
|
-
} catch {
|
|
2116
|
-
throw new Error(`candidate workspace file bytes are invalid: ${path}`);
|
|
2117
|
-
}
|
|
2118
|
-
if (isSharedArrayBuffer(buffer)) throw new Error(`candidate workspace file uses shared bytes: ${path}`);
|
|
2119
|
-
if (!isAnyArrayBuffer(buffer)) throw new Error(`candidate workspace file bytes are invalid: ${path}`);
|
|
2120
|
-
return {
|
|
2121
|
-
buffer,
|
|
2122
|
-
byteOffset,
|
|
2123
|
-
byteLength
|
|
2124
|
-
};
|
|
2125
|
-
}
|
|
2126
|
-
function detachWorkspaceBytes(input) {
|
|
2127
|
-
const { buffer, byteOffset, byteLength } = input;
|
|
2128
|
-
const copy = new Uint8Array(byteLength);
|
|
2129
|
-
Uint8Array.prototype.set.call(copy, new Uint8Array(buffer, byteOffset, byteLength));
|
|
2130
|
-
return copy;
|
|
2131
|
-
}
|
|
2132
2164
|
function workspacePath(root, relativePath) {
|
|
2133
2165
|
const path = resolve(root, relativePath);
|
|
2134
2166
|
if (!path.startsWith(`${root}${sep}`)) throw new Error(`candidate workspace archive path escapes its destination: ${relativePath}`);
|
|
2135
2167
|
return path;
|
|
2136
2168
|
}
|
|
2137
|
-
function assertGitObjectId(value, label) {
|
|
2138
|
-
if (!/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(value)) throw new Error(`candidate repository ${label} is not a Git object id`);
|
|
2139
|
-
}
|
|
2140
|
-
function hasControlCharacter(value) {
|
|
2141
|
-
for (let index = 0; index < value.length; index++) {
|
|
2142
|
-
const code = value.charCodeAt(index);
|
|
2143
|
-
if (code < 32 || code === 127) return true;
|
|
2144
|
-
}
|
|
2145
|
-
return false;
|
|
2146
|
-
}
|
|
2147
|
-
function isRecord$1(value) {
|
|
2148
|
-
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
2149
|
-
}
|
|
2150
|
-
function requireTypedArrayGetter(name) {
|
|
2151
|
-
const typedArrayPrototype = Object.getPrototypeOf(Uint8Array.prototype);
|
|
2152
|
-
const getter = Object.getOwnPropertyDescriptor(typedArrayPrototype, name)?.get;
|
|
2153
|
-
if (!getter) throw new Error(`typed array intrinsic ${name} accessor is unavailable`);
|
|
2154
|
-
return getter;
|
|
2155
|
-
}
|
|
2156
|
-
const typedArrayBufferGetter = requireTypedArrayGetter("buffer");
|
|
2157
|
-
const typedArrayByteOffsetGetter = requireTypedArrayGetter("byteOffset");
|
|
2158
|
-
const typedArrayByteLengthGetter = requireTypedArrayGetter("byteLength");
|
|
2159
|
-
/** Shared canonical header for both archive encoders. */
|
|
2160
|
-
function workspaceTarHeader(name, mode, size) {
|
|
2161
|
-
return {
|
|
2162
|
-
name,
|
|
2163
|
-
mode,
|
|
2164
|
-
uid: 0,
|
|
2165
|
-
gid: 0,
|
|
2166
|
-
size,
|
|
2167
|
-
mtime: fixedTarTime,
|
|
2168
|
-
type: "file",
|
|
2169
|
-
uname: "",
|
|
2170
|
-
gname: ""
|
|
2171
|
-
};
|
|
2172
|
-
}
|
|
2173
2169
|
//#endregion
|
|
2174
2170
|
//#region src/candidate-execution/workspace-streams.ts
|
|
2175
2171
|
/**
|
|
@@ -2533,10 +2529,7 @@ function refuseNonPublicConfigValues(values, path, context) {
|
|
|
2533
2529
|
function refuseSandboxProfileField(field, context = "candidate profile") {
|
|
2534
2530
|
throw new ValidationError(`${context} field ${field} is refused: Sandbox's Interface 4.0.0 cannot carry it yet, and Runtime does not drop it`);
|
|
2535
2531
|
}
|
|
2536
|
-
function isRecord(value) {
|
|
2537
|
-
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
2538
|
-
}
|
|
2539
2532
|
//#endregion
|
|
2540
|
-
export {
|
|
2533
|
+
export { hasCompleteCacheBreakdown as $, verifyMaterializedWorkspace as A, teardownExecutor as At, omitTopLevelDigest as B, candidateWorkspaceManifest as C, DEFAULT_SUCCESSFUL_SHUTDOWN_MS as Ct, scanMaterializedWorkspaceManifest as D, checkInIdleMs as Dt, readVerifiedArtifact as E, boundedChildDeadlineAt as Et, canonicalCandidateDigest$1 as F, addSpend as G, verifyCanonicalCandidateDocument as H, canonicalCandidateDocument as I, cloneSpend as J, addTokenUsage as K, deepFreezeCandidate as L, markPutStreamVerified as M, verifiedArtifactChunks as N, verifyBytes as O, isDeadlineAbortReason as Ot, canonicalCandidateBytes$1 as P, fnv1a32Hex as Q, embeddedCandidateArtifact as R, artifactCacheKey as S, DEFAULT_CHECK_IN_IDLE_MS as St, readMaterializedWorkspaceFiles as T, armDeadlineTimer as Tt, hasControlCharacter as U, sha256Bytes$1 as V, abortError as W, deleteBoxSafe as X, cloneTokenUsage as Y, errorMessage as Z, workspaceLimits as _, resourceTelemetry as _t, materializeAgentCandidateWorkspaceFromArtifacts as a, randomUuid as at, isWellFormedUnicode as b, CHILD_DEADLINE_REASON as bt, verifyAgentCandidateWorkspaceTree as c, stringifySafe as ct, readCandidateGitHubResource as d, unmeteredSpend as dt, isAbortError as et, verifyCandidateCode as f, withTimeout as ft, verifyAgentCandidateWorkspaceArchive as g, assertResources as gt, captureAgentCandidateWorkspaceFiles as h, addResourceSpend as ht, captureAgentCandidateWorkspaceTreeToArtifacts as i, randomSuffix as it, verifyWorkspaceSnapshotArtifacts as j, teardownSurfaces as jt, verifyMaterializedProfileWorkspace as k, singleFlightTeardown as kt, captureAgentCandidateWorkspace as l, throwAbort as lt, verifyTaskOutcomePatch as m, zeroTokenUsage as mt, refuseSandboxProfileField as n, mapWithConcurrency as nt, readAgentCandidateWorkspaceArtifactFiles as o, roundBoxMinutes as ot, verifyTaskCheckout as p, zeroSpend as pt, chargedTokens as q, captureAgentCandidateWorkspaceToArtifacts as r, promptCacheTokenClasses as rt, verifyAgentCandidateWorkspaceArtifacts as s, sleep as st, assertSandboxProfileCompatibility as t, isAsyncIterable as tt, createAgentCandidateWorkspacePort as u, throwIfAborted as ut, persistCandidateOutputArtifact as v, withBudgetResources as vt, captureMaterializedWorkspace as w, ROOT_DEADLINE_REASON as wt, WorkspaceScanLimitError as x, DEADLINE_CHECK_IN_MESSAGE as xt, assertExactObjectKeys as y, ACCEPTED_RESULT_GRACE_MS as yt, immutableCandidateValue as z };
|
|
2541
2534
|
|
|
2542
|
-
//# sourceMappingURL=sandbox-profile-compat-
|
|
2535
|
+
//# sourceMappingURL=sandbox-profile-compat-xSoVtdWw.js.map
|