@parcha/agentrun-serve 0.1.0-beta.52 → 0.1.0-beta.53
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +122 -1
- package/README.md +213 -24
- package/dist/agent-delete.d.ts +5 -6
- package/dist/agent-delete.js +30 -67
- package/dist/agent-package.d.ts +71 -0
- package/dist/agent-package.js +345 -0
- package/dist/agents-store.d.ts +26 -20
- package/dist/agents-store.js +41 -33
- package/dist/api-only.d.ts +26 -6
- package/dist/api-only.js +35 -13
- package/dist/claude-login.d.ts +1 -0
- package/dist/claude-login.js +1 -1
- package/dist/cli-learning/cli.d.ts +3 -0
- package/dist/cli-learning/cli.js +17 -3
- package/dist/cli-learning/connections.js +3 -2
- package/dist/cli-learning/schema.js +2 -1
- package/dist/cli.js +70 -7
- package/dist/composio-preset.d.ts +2 -1
- package/dist/composio-preset.js +4 -3
- package/dist/composio-triggers.d.ts +4 -0
- package/dist/composio-triggers.js +4 -1
- package/dist/computer-needs.d.ts +32 -0
- package/dist/computer-needs.js +80 -0
- package/dist/computer-setting.d.ts +1 -0
- package/dist/computer-setting.js +8 -1
- package/dist/console/assets/index-BFgyZzF_.js +734 -0
- package/dist/console/assets/index-DbilxljH.css +1 -0
- package/dist/console/index.html +2 -2
- package/dist/console-links.d.ts +1 -0
- package/dist/console-links.js +2 -0
- package/dist/env-switch.d.ts +14 -0
- package/dist/env-switch.js +23 -0
- package/dist/errors.d.ts +1 -0
- package/dist/errors.js +3 -0
- package/dist/eval-previous.js +4 -3
- package/dist/fal-price.js +10 -13
- package/dist/handed-secret.d.ts +4 -0
- package/dist/handed-secret.js +10 -0
- package/dist/harness-archive.d.ts +15 -5
- package/dist/harness-archive.js +71 -34
- package/dist/harness-check.d.ts +2 -1
- package/dist/harness-check.js +36 -95
- package/dist/harness-egress.d.ts +23 -0
- package/dist/harness-egress.js +69 -0
- package/dist/harness-recipe-entry.d.ts +71 -0
- package/dist/harness-recipe-entry.js +184 -0
- package/dist/harness-recipe.d.ts +73 -6
- package/dist/harness-recipe.js +185 -31
- package/dist/harness-sign-in.d.ts +29 -0
- package/dist/harness-sign-in.js +122 -0
- package/dist/harness-table.d.ts +21 -0
- package/dist/harness-table.js +58 -3
- package/dist/harness-zip.d.ts +6 -0
- package/dist/harness-zip.js +203 -0
- package/dist/ids.d.ts +11 -0
- package/dist/ids.js +36 -0
- package/dist/learn/commit.d.ts +14 -1
- package/dist/learn/commit.js +156 -1
- package/dist/learn/compile.js +22 -8
- package/dist/learn/folder.d.ts +5 -0
- package/dist/learn/folder.js +10 -1
- package/dist/learn/learning.sh +15 -3
- package/dist/learn/promote.d.ts +2 -2
- package/dist/learn/secrets.js +30 -7
- package/dist/learning-routes.d.ts +23 -11
- package/dist/learning-routes.js +110 -20
- package/dist/learning.d.ts +9 -6
- package/dist/learning.js +9 -4
- package/dist/mcp-gateway.js +15 -2
- package/dist/mcp-probe.d.ts +3 -0
- package/dist/mcp-probe.js +7 -2
- package/dist/mcp-resources.d.ts +44 -0
- package/dist/mcp-resources.js +100 -0
- package/dist/mcp-servers-store.d.ts +16 -12
- package/dist/model.d.ts +4 -4
- package/dist/model.js +6 -6
- package/dist/native/cli.js +9 -2
- package/dist/native/connection.d.ts +2 -2
- package/dist/native/connection.js +5 -2
- package/dist/native/discovery.d.ts +2 -0
- package/dist/native/discovery.js +10 -6
- package/dist/native/remote-worker-bridge.js +36 -4
- package/dist/native/remote.d.ts +18 -1
- package/dist/native/remote.js +126 -37
- package/dist/native/schema.d.ts +6 -0
- package/dist/native/schema.js +31 -6
- package/dist/native/source-account.d.ts +13 -0
- package/dist/native/source-account.js +114 -0
- package/dist/native/source-capture-hooks.d.ts +5 -0
- package/dist/native/source-capture-hooks.js +102 -0
- package/dist/native/source-mcp-selection.d.ts +13 -0
- package/dist/native/source-mcp-selection.js +72 -0
- package/dist/native/source-runtime-tools.d.ts +19 -0
- package/dist/native/source-runtime-tools.js +103 -0
- package/dist/native/source-snapshot-types.d.ts +138 -0
- package/dist/native/source-snapshot-types.js +12 -0
- package/dist/native/source-snapshot.d.ts +8 -0
- package/dist/native/source-snapshot.js +1201 -0
- package/dist/observation/learning.js +3 -2
- package/dist/openapi.js +167 -36
- package/dist/print.js +1 -1
- package/dist/purged-workflow.d.ts +12 -0
- package/dist/purged-workflow.js +43 -0
- package/dist/run-keys.d.ts +46 -0
- package/dist/run-keys.js +109 -0
- package/dist/run-launch.d.ts +16 -1
- package/dist/run-launch.js +30 -1
- package/dist/run-learning-served.d.ts +2 -2
- package/dist/run-model-key.d.ts +2 -2
- package/dist/run-model-key.js +5 -5
- package/dist/run-secrets.d.ts +2 -0
- package/dist/run-secrets.js +7 -4
- package/dist/run-view.d.ts +17 -0
- package/dist/run-view.js +25 -1
- package/dist/runner/adapter-loop.d.ts +11 -3
- package/dist/runner/adapter-loop.js +138 -22
- package/dist/runner/adapter-run-spec.js +25 -12
- package/dist/runner/audit.d.ts +2 -0
- package/dist/runner/audit.js +9 -1
- package/dist/runner/beside.js +2 -1
- package/dist/runner/claim-secrets.d.ts +29 -3
- package/dist/runner/claim-secrets.js +38 -4
- package/dist/runner/cli-run-spec.js +23 -12
- package/dist/runner/harness-loops.d.ts +6 -0
- package/dist/runner/harness-loops.js +11 -1
- package/dist/runner/held.d.ts +4 -0
- package/dist/runner/journal-kinds.d.ts +2 -0
- package/dist/runner/learned-first.d.ts +2 -0
- package/dist/runner/learned-first.js +1 -1
- package/dist/runner/learning-end.d.ts +7 -2
- package/dist/runner/learning-end.js +22 -10
- package/dist/runner/learning-seed.d.ts +9 -3
- package/dist/runner/learning-seed.js +2 -2
- package/dist/runner/main.d.ts +1 -0
- package/dist/runner/main.js +20 -13
- package/dist/runner/mcp-claim.js +6 -1
- package/dist/runner/mcp-run.d.ts +10 -7
- package/dist/runner/mcp-run.js +3 -5
- package/dist/runner/monid-run.js +9 -11
- package/dist/runner/project-checkpoint.d.ts +35 -0
- package/dist/runner/project-checkpoint.js +116 -0
- package/dist/runner/project-drain.d.ts +8 -0
- package/dist/runner/project-drain.js +25 -0
- package/dist/runner/project-host.d.ts +10 -0
- package/dist/runner/project-host.js +52 -0
- package/dist/runner/promotion.d.ts +14 -6
- package/dist/runner/promotion.js +98 -41
- package/dist/runner/redact.d.ts +13 -0
- package/dist/runner/redact.js +67 -1
- package/dist/runner/run-channel.d.ts +9 -0
- package/dist/runner/run-channel.js +15 -2
- package/dist/runner/run-child-host.d.ts +8 -4
- package/dist/runner/run-child-host.js +171 -41
- package/dist/runner/run-errors.js +2 -2
- package/dist/runner/runner-check.js +5 -2
- package/dist/runner/runner.js +26 -9
- package/dist/runner/store-secrets.js +7 -3
- package/dist/runner/workflow-first.d.ts +4 -0
- package/dist/runner/workflow-first.js +13 -0
- package/dist/runner/workflow-loop.d.ts +2 -1
- package/dist/runner/workflow-loop.js +2 -1
- package/dist/runner/workflow-spec.js +1 -1
- package/dist/runs-over-store.d.ts +34 -6
- package/dist/runs-over-store.js +133 -25
- package/dist/sdk/runs.d.ts +11 -1
- package/dist/sdk/runs.js +117 -26
- package/dist/sdk/schema.js +12 -2
- package/dist/sdk/workflows.d.ts +1 -1
- package/dist/server.d.ts +68 -32
- package/dist/server.js +600 -110
- package/dist/skills/agentrun-serve/SKILL.md +2 -1
- package/dist/source-sync/adoption.d.ts +15 -0
- package/dist/source-sync/adoption.js +36 -0
- package/dist/source-sync/auxiliary.d.ts +23 -0
- package/dist/source-sync/auxiliary.js +64 -0
- package/dist/source-sync/capture-git.d.ts +5 -0
- package/dist/source-sync/capture-git.js +272 -0
- package/dist/source-sync/capture-project.d.ts +53 -0
- package/dist/source-sync/capture-project.js +206 -0
- package/dist/source-sync/capture-refusal.d.ts +7 -0
- package/dist/source-sync/capture-refusal.js +16 -0
- package/dist/source-sync/capture.d.ts +11 -0
- package/dist/source-sync/capture.js +22 -0
- package/dist/source-sync/checkpoint-gate.d.ts +21 -0
- package/dist/source-sync/checkpoint-gate.js +52 -0
- package/dist/source-sync/checkpoints.d.ts +66 -0
- package/dist/source-sync/checkpoints.js +168 -0
- package/dist/source-sync/claim.d.ts +11 -0
- package/dist/source-sync/claim.js +48 -0
- package/dist/source-sync/destination.d.ts +47 -0
- package/dist/source-sync/destination.js +239 -0
- package/dist/source-sync/io.d.ts +15 -0
- package/dist/source-sync/io.js +52 -0
- package/dist/source-sync/local.d.ts +43 -0
- package/dist/source-sync/local.js +229 -0
- package/dist/source-sync/prepare.d.ts +59 -0
- package/dist/source-sync/prepare.js +93 -0
- package/dist/source-sync/projects.d.ts +61 -0
- package/dist/source-sync/projects.js +130 -0
- package/dist/source-sync/registry.d.ts +95 -0
- package/dist/source-sync/registry.js +226 -0
- package/dist/source-sync/service.d.ts +33 -0
- package/dist/source-sync/service.js +118 -0
- package/dist/source-sync/skill-edits.d.ts +12 -0
- package/dist/source-sync/skill-edits.js +122 -0
- package/dist/source-sync/snapshots.d.ts +48 -0
- package/dist/source-sync/snapshots.js +448 -0
- package/dist/source-sync/types.d.ts +9 -0
- package/dist/source-sync/types.js +14 -0
- package/dist/source-sync/workspace.d.ts +66 -0
- package/dist/source-sync/workspace.js +273 -0
- package/dist/store/agent-body.d.ts +4 -0
- package/dist/store/agent-body.js +16 -5
- package/dist/store/index.d.ts +2 -2
- package/dist/store/index.js +1 -1
- package/dist/store/schema.d.ts +2 -1
- package/dist/store/schema.js +2 -1
- package/dist/store/seal.d.ts +5 -1
- package/dist/store/seal.js +12 -3
- package/dist/store/sqlite/project-checkpoints.d.ts +11 -0
- package/dist/store/sqlite/project-checkpoints.js +70 -0
- package/dist/store/sqlite/run-launch.d.ts +4 -12
- package/dist/store/sqlite/run-launch.js +5 -19
- package/dist/store/sqlite/store.js +224 -170
- package/dist/store/store.d.ts +116 -39
- package/dist/store/store.js +14 -1
- package/dist/store-reads/learning.d.ts +2 -2
- package/dist/store-view.d.ts +3 -1
- package/dist/store-view.js +17 -5
- package/dist/template-import.d.ts +10 -2
- package/dist/template-import.js +116 -13
- package/dist/templates.d.ts +26 -5
- package/dist/templates.js +62 -10
- package/dist/timeline/index.d.ts +1 -1
- package/dist/timeline/index.js +1 -1
- package/dist/timeline/timeline.d.ts +5 -0
- package/dist/timeline/timeline.js +8 -0
- package/dist/tool-plane.d.ts +12 -12
- package/dist/tools.d.ts +8 -8
- package/dist/trigger-launch-hook.d.ts +47 -0
- package/dist/trigger-launch-hook.js +90 -0
- package/dist/trigger-targets.d.ts +14 -1
- package/dist/trigger-targets.js +20 -0
- package/dist/triggers.d.ts +54 -5
- package/dist/triggers.js +143 -8
- package/dist/uploads-archil.js +1 -1
- package/dist/uploads.js +1 -1
- package/dist/validate.js +1 -2
- package/dist/workspace/computer-for-claim.d.ts +2 -0
- package/dist/workspace/computer-for-claim.js +43 -0
- package/dist/workspace/paths.d.ts +6 -0
- package/dist/workspace/paths.js +6 -0
- package/dist/workspace/resolve-computer.d.ts +1 -0
- package/dist/workspace/run-tools.d.ts +2 -0
- package/dist/workspace/run-tools.js +8 -0
- package/launcher/agentrun-serve +1 -1
- package/package.json +10 -10
- package/skills/agentrun-serve/SKILL.md +2 -1
- package/templates/README.md +5 -2
- package/dist/console/assets/index-B-D0EM3j.js +0 -733
- package/dist/console/assets/index-DlQepP2J.css +0 -1
|
@@ -0,0 +1,1201 @@
|
|
|
1
|
+
/** Source-side exporter. No service, native CLI, model or network calls; credentials are never copied/exported. */
|
|
2
|
+
import { constants } from "node:fs";
|
|
3
|
+
import { open, opendir, mkdtemp, mkdir, rm, writeFile } from "node:fs/promises";
|
|
4
|
+
import { createHash } from "node:crypto";
|
|
5
|
+
import { spawn } from "node:child_process";
|
|
6
|
+
import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
|
|
7
|
+
import { tmpdir } from "node:os";
|
|
8
|
+
import { parse as toml } from "smol-toml";
|
|
9
|
+
import { parseDocument } from "yaml";
|
|
10
|
+
import { secretsIn, keyShaped } from "../secret-cut.js";
|
|
11
|
+
import { secretShapes } from "../learn/secrets.js";
|
|
12
|
+
import { removeOwnedCaptureHooks } from "./source-capture-hooks.js";
|
|
13
|
+
import { NATIVE_RUNTIME_FACTS } from "./runtimes.js";
|
|
14
|
+
import { SOURCE_CODEX_FEATURES, sourceNativeTools } from "./source-runtime-tools.js";
|
|
15
|
+
import { claudeMcpSelector, nativeToolNames, selectedMcpServer, sourceMcpSelection } from "./source-mcp-selection.js";
|
|
16
|
+
import { sourceSnapshotDigest } from "./source-snapshot-types.js";
|
|
17
|
+
import { sourceAccountContainsSecret, sourceAccountMetadata } from "./source-account.js";
|
|
18
|
+
export { sourceSnapshotDigest } from "./source-snapshot-types.js";
|
|
19
|
+
const SYSTEM_POLICY_PATHS = ["/etc/codex/config.toml", "/etc/codex/requirements.toml", "/etc/codex/managed_config.toml"];
|
|
20
|
+
const hash = (value) => createHash("sha256").update(value).digest("hex");
|
|
21
|
+
const object = (value) => value !== null && typeof value === "object" && !Array.isArray(value) ? value : {};
|
|
22
|
+
const canonical = (value) => JSON.stringify(value, function (_key, item) {
|
|
23
|
+
return item && typeof item === "object" && !Array.isArray(item) ? Object.fromEntries(Object.keys(item).sort().map(key => [key, item[key]])) : item;
|
|
24
|
+
});
|
|
25
|
+
const within = (root, path) => path === root || path.startsWith(root + sep);
|
|
26
|
+
const credentialPath = (path) => path.split(/[\\/]/).some(part => /^(?:\.env(?:\..*)?|auth\.json|credentials(?:\.json)?|\.credentials\.json|\.claude\.json|id_(?:rsa|ed25519)|\.netrc|\.npmrc|\.pypirc|\.ssh|\.aws|\.gnupg)$/i.test(part)) || /\.(?:pem|p12|pfx|key)$/i.test(path);
|
|
27
|
+
const portable = (path) => path.length > 0 && Buffer.byteLength(path) <= 4096 && !path.includes("\\") && !/[\x00-\x1f\x7f]/.test(path)
|
|
28
|
+
&& !isAbsolute(path) && path.split("/").every(part => part && part !== "." && part !== "..");
|
|
29
|
+
const text = (bytes) => new TextDecoder("utf-8", { fatal: true }).decode(bytes);
|
|
30
|
+
const signature = (s) => [s.dev, s.ino, s.size, s.mode, s.mtimeMs, s.ctimeMs].join(":");
|
|
31
|
+
export class SourceSnapshotError extends Error {
|
|
32
|
+
code;
|
|
33
|
+
constructor(code, message) {
|
|
34
|
+
super(message);
|
|
35
|
+
this.code = code;
|
|
36
|
+
this.name = "SourceSnapshotError";
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
/** Open every component with NOFOLLOW, including the authorized root. /proc fd paths anchor subsequent
|
|
40
|
+
* reads to already-open directories: swapping a parent for a link cannot redirect a read outside the grant. */
|
|
41
|
+
async function noLinks(path, expectedRoots = []) {
|
|
42
|
+
const parts = resolve(path).split(sep).filter(Boolean);
|
|
43
|
+
let handle = await open("/", constants.O_RDONLY | constants.O_DIRECTORY);
|
|
44
|
+
const checkIdentity = async (opened) => {
|
|
45
|
+
const expected = expectedRoots.find(root => root.path === opened);
|
|
46
|
+
if (!expected)
|
|
47
|
+
return;
|
|
48
|
+
const info = await handle.stat({ bigint: true });
|
|
49
|
+
if (!info.isDirectory() || info.dev.toString() !== expected.device || info.ino.toString() !== expected.inode)
|
|
50
|
+
throw new SourceSnapshotError("source_changed", "An approved source folder was replaced; reconnect it on the source machine.");
|
|
51
|
+
};
|
|
52
|
+
try {
|
|
53
|
+
await checkIdentity("/");
|
|
54
|
+
for (let i = 0; i < parts.length; i++) {
|
|
55
|
+
const opened = sep + parts.slice(0, i + 1).join(sep);
|
|
56
|
+
let next;
|
|
57
|
+
try {
|
|
58
|
+
next = await open(`/proc/self/fd/${handle.fd}/${parts[i]}`, constants.O_RDONLY | constants.O_NONBLOCK | constants.O_NOFOLLOW | (i < parts.length - 1 ? constants.O_DIRECTORY : 0));
|
|
59
|
+
}
|
|
60
|
+
catch (error) {
|
|
61
|
+
if (expectedRoots.some(root => within(root.path, resolve(path)) && within(opened, root.path)))
|
|
62
|
+
throw new SourceSnapshotError("source_changed", "An approved source folder is no longer safely available.");
|
|
63
|
+
throw error;
|
|
64
|
+
}
|
|
65
|
+
await handle.close();
|
|
66
|
+
handle = next;
|
|
67
|
+
// Check the descriptor before opening any descendant. A path restored after export cannot
|
|
68
|
+
// retroactively authorize bytes read through a different directory inode.
|
|
69
|
+
await checkIdentity(opened);
|
|
70
|
+
}
|
|
71
|
+
return handle;
|
|
72
|
+
}
|
|
73
|
+
catch (error) {
|
|
74
|
+
await handle.close();
|
|
75
|
+
throw error;
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
class Reader {
|
|
79
|
+
options;
|
|
80
|
+
records = new Map();
|
|
81
|
+
policyStamps = new Map();
|
|
82
|
+
accountStamps = new Map();
|
|
83
|
+
checkedContents = new Map();
|
|
84
|
+
checkedContentBytes = 0;
|
|
85
|
+
objectStamps = new Map();
|
|
86
|
+
deadline;
|
|
87
|
+
limits;
|
|
88
|
+
readBytes = 0;
|
|
89
|
+
isolatedGit;
|
|
90
|
+
constructor(options) {
|
|
91
|
+
this.options = options;
|
|
92
|
+
this.limits = { files: 10_000, bytes: 64 * 1024 * 1024, fileBytes: 8 * 1024 * 1024, gitBytes: 32 * 1024 * 1024, timeoutMs: 30_000, ...options.limits };
|
|
93
|
+
for (const value of Object.values(this.limits))
|
|
94
|
+
if (!Number.isSafeInteger(value) || value <= 0)
|
|
95
|
+
throw new SourceSnapshotError("limit", "Snapshot limits must be positive safe integers.");
|
|
96
|
+
if (options.expectedRoots && (options.expectedRoots.some(root => !isAbsolute(root.path) || resolve(root.path) !== root.path
|
|
97
|
+
|| !/^\d+$/.test(root.device) || !/^\d+$/.test(root.inode))
|
|
98
|
+
|| new Set(options.expectedRoots.map(root => root.path)).size !== options.expectedRoots.length
|
|
99
|
+
|| options.authorizedRoots.some(path => !options.expectedRoots.some(root => root.path === resolve(path)))))
|
|
100
|
+
throw new SourceSnapshotError("source_unavailable", "Source consent must bind every authorized root exactly.");
|
|
101
|
+
this.deadline = Date.now() + this.limits.timeoutMs;
|
|
102
|
+
}
|
|
103
|
+
async verifyRoots() {
|
|
104
|
+
for (const root of this.options.expectedRoots ?? []) {
|
|
105
|
+
this.check();
|
|
106
|
+
const handle = await noLinks(root.path, this.options.expectedRoots);
|
|
107
|
+
await handle.close();
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
check() { this.options.signal?.throwIfAborted(); if (Date.now() > this.deadline)
|
|
111
|
+
throw new SourceSnapshotError("limit", "The source snapshot exceeded its time limit."); }
|
|
112
|
+
granted(path) { return this.options.authorizedRoots.some(root => isAbsolute(root) && within(resolve(root), resolve(path))); }
|
|
113
|
+
async read(path, fresh = false, fileLimit = this.limits.fileBytes) {
|
|
114
|
+
this.check();
|
|
115
|
+
path = resolve(path);
|
|
116
|
+
if (this.options.secretValues?.some(secret => secret && path.includes(secret)))
|
|
117
|
+
throw new SourceSnapshotError("source_unavailable", "A source path contains a held credential and cannot be exported.");
|
|
118
|
+
if (!this.granted(path))
|
|
119
|
+
throw new SourceSnapshotError("source_unavailable", "A required source path is outside the authorized roots.");
|
|
120
|
+
if (!fresh && this.records.has(path))
|
|
121
|
+
return this.records.get(path);
|
|
122
|
+
if (!fresh && this.records.size >= this.limits.files * 3)
|
|
123
|
+
throw new SourceSnapshotError("limit", "The source snapshot contains too many paths.");
|
|
124
|
+
let handle;
|
|
125
|
+
try {
|
|
126
|
+
handle = await noLinks(path, this.options.expectedRoots);
|
|
127
|
+
}
|
|
128
|
+
catch (error) {
|
|
129
|
+
if (error instanceof SourceSnapshotError)
|
|
130
|
+
throw error;
|
|
131
|
+
if (error.code === "ENOENT") {
|
|
132
|
+
if (!fresh)
|
|
133
|
+
this.records.set(path, null);
|
|
134
|
+
return null;
|
|
135
|
+
}
|
|
136
|
+
throw new SourceSnapshotError("source_unavailable", "A source path cannot be read safely; links and special files need an explicit portable equivalent.");
|
|
137
|
+
}
|
|
138
|
+
try {
|
|
139
|
+
const before = await handle.stat();
|
|
140
|
+
let value;
|
|
141
|
+
if (before.isDirectory()) {
|
|
142
|
+
const names = [], dir = await opendir(`/proc/self/fd/${handle.fd}`, { bufferSize: 16 });
|
|
143
|
+
try {
|
|
144
|
+
for (;;) {
|
|
145
|
+
const entry = await dir.read();
|
|
146
|
+
if (!entry)
|
|
147
|
+
break;
|
|
148
|
+
names.push(entry.name);
|
|
149
|
+
if (names.length > this.limits.files)
|
|
150
|
+
throw new SourceSnapshotError("limit", "A source directory exceeds the file limit.");
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
finally {
|
|
154
|
+
await dir.close();
|
|
155
|
+
}
|
|
156
|
+
value = { stamp: signature(before), names: names.sort() };
|
|
157
|
+
}
|
|
158
|
+
else {
|
|
159
|
+
if (!before.isFile() || before.nlink !== 1 || (before.mode & 0o6000))
|
|
160
|
+
throw new SourceSnapshotError("source_unavailable", "Special, linked or privileged files need an explicit portable equivalent.");
|
|
161
|
+
if (before.size > fileLimit)
|
|
162
|
+
throw new SourceSnapshotError("limit", "A source file exceeds the per-file byte limit.");
|
|
163
|
+
if (!fresh) {
|
|
164
|
+
if (this.readBytes + before.size > this.limits.bytes)
|
|
165
|
+
throw new SourceSnapshotError("limit", "Source reads exceed the total byte limit.");
|
|
166
|
+
this.readBytes += before.size;
|
|
167
|
+
}
|
|
168
|
+
const bytes = Buffer.alloc(before.size + 1);
|
|
169
|
+
let offset = 0;
|
|
170
|
+
while (offset < bytes.length) {
|
|
171
|
+
const read = await handle.read(bytes, offset, bytes.length - offset, offset);
|
|
172
|
+
if (!read.bytesRead)
|
|
173
|
+
break;
|
|
174
|
+
offset += read.bytesRead;
|
|
175
|
+
this.check();
|
|
176
|
+
}
|
|
177
|
+
if (offset !== before.size)
|
|
178
|
+
throw new SourceSnapshotError("source_changed", "A source file changed while it was read.");
|
|
179
|
+
value = { stamp: signature(before), bytes: bytes.subarray(0, offset) };
|
|
180
|
+
}
|
|
181
|
+
if (signature(await handle.stat()) !== value.stamp)
|
|
182
|
+
throw new SourceSnapshotError("source_changed", "A source path changed while it was read.");
|
|
183
|
+
if (!fresh)
|
|
184
|
+
this.records.set(path, value);
|
|
185
|
+
return value;
|
|
186
|
+
}
|
|
187
|
+
finally {
|
|
188
|
+
await handle.close();
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
/** Presence-only probes for required native policy. Fixed system paths are inspected without
|
|
192
|
+
* reading content or broadening the project's export grant; account files stay opaque too. */
|
|
193
|
+
async policyPresent(path, fresh = false) {
|
|
194
|
+
this.check();
|
|
195
|
+
if (!this.granted(path) && !SYSTEM_POLICY_PATHS.includes(path))
|
|
196
|
+
throw new SourceSnapshotError("source_unavailable", "A required policy path is outside the source grant.");
|
|
197
|
+
let handle, stamp = null;
|
|
198
|
+
try {
|
|
199
|
+
handle = await noLinks(path, this.options.expectedRoots);
|
|
200
|
+
stamp = signature(await handle.stat());
|
|
201
|
+
}
|
|
202
|
+
catch (error) {
|
|
203
|
+
if (error instanceof SourceSnapshotError)
|
|
204
|
+
throw error;
|
|
205
|
+
if (error.code !== "ENOENT")
|
|
206
|
+
throw new SourceSnapshotError("source_unavailable", "Required native policy could not be checked safely.");
|
|
207
|
+
}
|
|
208
|
+
finally {
|
|
209
|
+
await handle?.close();
|
|
210
|
+
}
|
|
211
|
+
if (!fresh)
|
|
212
|
+
this.policyStamps.set(path, stamp);
|
|
213
|
+
else if (this.policyStamps.get(path) !== stamp)
|
|
214
|
+
throw new SourceSnapshotError("source_changed", "Native policy changed during export.");
|
|
215
|
+
return stamp !== null;
|
|
216
|
+
}
|
|
217
|
+
keepSecretCheck(bytes) {
|
|
218
|
+
const id = hash(bytes);
|
|
219
|
+
if (this.checkedContents.has(id))
|
|
220
|
+
return;
|
|
221
|
+
this.checkedContentBytes += bytes.length;
|
|
222
|
+
if (this.checkedContentBytes > this.limits.bytes + this.limits.gitBytes)
|
|
223
|
+
throw new SourceSnapshotError("limit", "Source credential checks exceed the snapshot byte limit.");
|
|
224
|
+
this.checkedContents.set(id, bytes.toString("utf8"));
|
|
225
|
+
}
|
|
226
|
+
async verify(metadata) {
|
|
227
|
+
await this.verifyRoots();
|
|
228
|
+
for (const path of this.policyStamps.keys())
|
|
229
|
+
await this.policyPresent(path, true);
|
|
230
|
+
for (const path of this.accountStamps.keys())
|
|
231
|
+
await this.accountMetadata(path, true, metadata);
|
|
232
|
+
for (const [path, stamp] of this.objectStamps) {
|
|
233
|
+
this.check();
|
|
234
|
+
let handle;
|
|
235
|
+
try {
|
|
236
|
+
handle = await noLinks(path, this.options.expectedRoots);
|
|
237
|
+
if (signature(await handle.stat()) !== stamp)
|
|
238
|
+
throw new Error();
|
|
239
|
+
}
|
|
240
|
+
catch {
|
|
241
|
+
throw new SourceSnapshotError("source_changed", "Git objects changed during export.");
|
|
242
|
+
}
|
|
243
|
+
finally {
|
|
244
|
+
await handle?.close();
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
for (const [path, old] of this.records) {
|
|
248
|
+
let current;
|
|
249
|
+
try {
|
|
250
|
+
current = await this.read(path, true, Math.max(this.limits.fileBytes, old?.bytes?.length ?? 0));
|
|
251
|
+
}
|
|
252
|
+
catch (error) {
|
|
253
|
+
if (error instanceof SourceSnapshotError && error.code === "limit")
|
|
254
|
+
throw error;
|
|
255
|
+
throw new SourceSnapshotError("source_changed", "Source paths changed during export; retry from fresh discovery.");
|
|
256
|
+
}
|
|
257
|
+
if (!old !== !current || (old && current && (old.stamp !== current.stamp || (old.bytes ? !current.bytes?.equals(old.bytes) : canonical(old.names) !== canonical(current.names)))))
|
|
258
|
+
throw new SourceSnapshotError("source_changed", "Source content changed during export; retry from fresh discovery.");
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
/** A separate private read: never puts credentials in records, blobs, provenance or diagnostics.
|
|
262
|
+
* The descriptor, bytes fingerprint and classification are checked again before publication. */
|
|
263
|
+
async accountMetadata(path, fresh = false, metadata) {
|
|
264
|
+
this.check();
|
|
265
|
+
if (!this.granted(path))
|
|
266
|
+
throw new SourceSnapshotError("source_unavailable", "Source account metadata is outside the source grant.");
|
|
267
|
+
let handle, bytes, stamp = "missing", projection = sourceAccountMetadata(null);
|
|
268
|
+
try {
|
|
269
|
+
handle = await noLinks(path, this.options.expectedRoots);
|
|
270
|
+
const before = await handle.stat();
|
|
271
|
+
if (!before.isFile() || before.nlink !== 1 || (before.mode & 0o6000))
|
|
272
|
+
throw new SourceSnapshotError("source_unavailable", "Source account metadata cannot be inspected safely.");
|
|
273
|
+
stamp = signature(before);
|
|
274
|
+
if (before.size <= 65_536) {
|
|
275
|
+
bytes = Buffer.alloc(before.size + 1);
|
|
276
|
+
let offset = 0;
|
|
277
|
+
while (offset < bytes.length) {
|
|
278
|
+
const read = await handle.read(bytes, offset, bytes.length - offset, offset);
|
|
279
|
+
if (!read.bytesRead)
|
|
280
|
+
break;
|
|
281
|
+
offset += read.bytesRead;
|
|
282
|
+
this.check();
|
|
283
|
+
}
|
|
284
|
+
if (offset !== before.size || signature(await handle.stat()) !== stamp)
|
|
285
|
+
throw new SourceSnapshotError("source_changed", "Source account metadata changed during export.");
|
|
286
|
+
projection = sourceAccountMetadata(bytes.subarray(0, offset));
|
|
287
|
+
stamp += ":" + hash(bytes.subarray(0, offset));
|
|
288
|
+
if (fresh && this.accountStamps.get(path) !== stamp + ":" + canonical(projection))
|
|
289
|
+
throw new SourceSnapshotError("source_changed", "Source account metadata changed during export.");
|
|
290
|
+
if (fresh && sourceAccountContainsSecret(bytes.subarray(0, offset), function* (contents) { if (metadata)
|
|
291
|
+
yield metadata; yield* contents; }(this.checkedContents.values())))
|
|
292
|
+
throw new SourceSnapshotError("source_unavailable", "Source content contains a native credential and cannot be exported.");
|
|
293
|
+
}
|
|
294
|
+
else
|
|
295
|
+
projection = sourceAccountMetadata(new Uint8Array(65_537));
|
|
296
|
+
}
|
|
297
|
+
catch (error) {
|
|
298
|
+
if (error instanceof SourceSnapshotError)
|
|
299
|
+
throw error;
|
|
300
|
+
if (error.code !== "ENOENT")
|
|
301
|
+
throw new SourceSnapshotError("source_unavailable", "Source account metadata cannot be inspected safely.");
|
|
302
|
+
}
|
|
303
|
+
finally {
|
|
304
|
+
bytes?.fill(0);
|
|
305
|
+
await handle?.close();
|
|
306
|
+
}
|
|
307
|
+
const state = stamp + ":" + canonical(projection);
|
|
308
|
+
if (!fresh)
|
|
309
|
+
this.accountStamps.set(path, state);
|
|
310
|
+
else if (this.accountStamps.get(path) !== state)
|
|
311
|
+
throw new SourceSnapshotError("source_changed", "Source account metadata changed during export.");
|
|
312
|
+
return projection;
|
|
313
|
+
}
|
|
314
|
+
/** Git never consumes live source configuration or path indirections. Copy only its bounded data database
|
|
315
|
+
* through the same no-link reader, synthesize safe config, and inherit an already-open worktree descriptor. */
|
|
316
|
+
async isolateGit(directory, common) {
|
|
317
|
+
const temporary = await mkdtemp(join(tmpdir(), "agentrun-source-git-"));
|
|
318
|
+
let worktree, copied = 0;
|
|
319
|
+
try {
|
|
320
|
+
worktree = await noLinks(this.options.target.project, this.options.expectedRoots);
|
|
321
|
+
const copy = async (source, target) => {
|
|
322
|
+
const value = await this.read(source, false, this.limits.gitBytes);
|
|
323
|
+
if (!value)
|
|
324
|
+
return;
|
|
325
|
+
if (value.names) {
|
|
326
|
+
await mkdir(target, { recursive: true, mode: 0o700 });
|
|
327
|
+
for (const name of value.names)
|
|
328
|
+
await copy(join(source, name), join(target, name));
|
|
329
|
+
}
|
|
330
|
+
else if (value.bytes) {
|
|
331
|
+
copied += value.bytes.length;
|
|
332
|
+
if (copied > this.limits.gitBytes)
|
|
333
|
+
throw new SourceSnapshotError("limit", "The private Git database exceeds the snapshot bound.");
|
|
334
|
+
await mkdir(dirname(target), { recursive: true, mode: 0o700 });
|
|
335
|
+
await writeFile(target, value.bytes, { mode: 0o600, flag: "wx" });
|
|
336
|
+
}
|
|
337
|
+
};
|
|
338
|
+
for (const name of ["objects", "refs", "packed-refs", "shallow", "info/exclude"])
|
|
339
|
+
await copy(join(common, name), join(temporary, name));
|
|
340
|
+
for (const name of ["HEAD", "index"])
|
|
341
|
+
await copy(join(directory, name), join(temporary, name));
|
|
342
|
+
await copy(join(this.options.home, ".config", "git", "ignore"), join(temporary, "source-ignore"));
|
|
343
|
+
await writeFile(join(temporary, "config"), "[core]\n repositoryformatversion = 0\n bare = false\n filemode = true\n", { mode: 0o600, flag: "wx" });
|
|
344
|
+
this.isolatedGit = { directory: temporary, worktree };
|
|
345
|
+
}
|
|
346
|
+
catch (error) {
|
|
347
|
+
await worktree?.close();
|
|
348
|
+
await rm(temporary, { recursive: true, force: true });
|
|
349
|
+
throw error;
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
async closeGit() {
|
|
353
|
+
const held = this.isolatedGit;
|
|
354
|
+
this.isolatedGit = undefined;
|
|
355
|
+
if (held) {
|
|
356
|
+
try {
|
|
357
|
+
await held.worktree.close();
|
|
358
|
+
}
|
|
359
|
+
finally {
|
|
360
|
+
await rm(held.directory, { recursive: true, force: true });
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
}
|
|
364
|
+
async inspectObjects(path) {
|
|
365
|
+
this.check();
|
|
366
|
+
if (!this.granted(path))
|
|
367
|
+
throw new SourceSnapshotError("source_unavailable", "Git objects are outside the source grant.");
|
|
368
|
+
const handle = await noLinks(path, this.options.expectedRoots);
|
|
369
|
+
try {
|
|
370
|
+
const stat = await handle.stat();
|
|
371
|
+
if (!stat.isDirectory() && !stat.isFile())
|
|
372
|
+
throw new SourceSnapshotError("source_unavailable", "Git has an unsupported object path.");
|
|
373
|
+
if (this.objectStamps.size >= this.limits.files)
|
|
374
|
+
throw new SourceSnapshotError("limit", "Git object paths exceed the snapshot bound.");
|
|
375
|
+
this.objectStamps.set(path, signature(stat));
|
|
376
|
+
if (stat.isDirectory()) {
|
|
377
|
+
const directory = await opendir(`/proc/self/fd/${handle.fd}`, { bufferSize: 16 });
|
|
378
|
+
try {
|
|
379
|
+
for (;;) {
|
|
380
|
+
const entry = await directory.read();
|
|
381
|
+
if (!entry)
|
|
382
|
+
break;
|
|
383
|
+
await this.inspectObjects(join(path, entry.name));
|
|
384
|
+
}
|
|
385
|
+
}
|
|
386
|
+
finally {
|
|
387
|
+
await directory.close();
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
finally {
|
|
392
|
+
await handle.close();
|
|
393
|
+
}
|
|
394
|
+
}
|
|
395
|
+
}
|
|
396
|
+
/** stdout is bounded while streaming, and the entire process group is killed on timeout/overflow. Git
|
|
397
|
+
* receives no inherited credentials or runtime environment. No fetch, checkout, filters or native hooks run. */
|
|
398
|
+
async function git(reader, args, max = reader.limits.gitBytes) {
|
|
399
|
+
reader.check();
|
|
400
|
+
const isolated = reader.isolatedGit;
|
|
401
|
+
if (!isolated)
|
|
402
|
+
throw new SourceSnapshotError("source_unavailable", "Git source data was not safely isolated.");
|
|
403
|
+
return new Promise((accept, reject) => {
|
|
404
|
+
const child = spawn("git", ["--no-optional-locks", "-c", "core.fsmonitor=false", "-c", "core.untrackedCache=false", "-c", "core.hooksPath=/dev/null", "-c", "core.attributesFile=/dev/null", "-c", "protocol.allow=never", "-c", "pack.threads=1", "-c", `core.excludesFile=${join(isolated.directory, "source-ignore")}`, "--git-dir", isolated.directory, "--work-tree", "/proc/self/fd/3", "-C", "/proc/self/fd/3", ...args], {
|
|
405
|
+
env: { PATH: "/usr/bin:/bin", HOME: reader.options.home, GIT_CONFIG_NOSYSTEM: "1", GIT_ATTR_NOSYSTEM: "1", GIT_CONFIG_GLOBAL: "/dev/null", GIT_OPTIONAL_LOCKS: "0", GIT_TERMINAL_PROMPT: "0", GIT_NO_LAZY_FETCH: "1" },
|
|
406
|
+
detached: true, stdio: ["ignore", "pipe", "ignore", isolated.worktree.fd],
|
|
407
|
+
});
|
|
408
|
+
const chunks = [];
|
|
409
|
+
let length = 0, settled = false, failure;
|
|
410
|
+
const finish = (error, closed = false) => {
|
|
411
|
+
if (settled)
|
|
412
|
+
return;
|
|
413
|
+
if (error && !failure) {
|
|
414
|
+
failure = error;
|
|
415
|
+
try {
|
|
416
|
+
if (child.pid)
|
|
417
|
+
process.kill(-child.pid, "SIGKILL");
|
|
418
|
+
}
|
|
419
|
+
catch { }
|
|
420
|
+
}
|
|
421
|
+
// Keep the fd and private Git database alive until no process can still use them.
|
|
422
|
+
if (!closed)
|
|
423
|
+
return;
|
|
424
|
+
settled = true;
|
|
425
|
+
clearTimeout(timer);
|
|
426
|
+
reader.options.signal?.removeEventListener("abort", abort);
|
|
427
|
+
if (failure)
|
|
428
|
+
reject(failure);
|
|
429
|
+
else
|
|
430
|
+
accept(Buffer.concat(chunks));
|
|
431
|
+
};
|
|
432
|
+
const abort = () => finish(new SourceSnapshotError("source_unavailable", "Source snapshot was cancelled."));
|
|
433
|
+
const timer = setTimeout(() => finish(new SourceSnapshotError("limit", "Git snapshot exceeded its time limit.")), Math.max(1, reader.deadline - Date.now()));
|
|
434
|
+
reader.options.signal?.addEventListener("abort", abort, { once: true });
|
|
435
|
+
if (reader.options.signal?.aborted)
|
|
436
|
+
abort();
|
|
437
|
+
child.stdout.on("data", (chunk) => { length += chunk.length; if (length > max)
|
|
438
|
+
finish(new SourceSnapshotError("limit", "Git snapshot exceeded its byte limit."));
|
|
439
|
+
else
|
|
440
|
+
chunks.push(chunk); });
|
|
441
|
+
child.once("error", () => finish(new SourceSnapshotError("source_unavailable", "Git snapshot could not be read.")));
|
|
442
|
+
child.once("close", code => finish(code === 0 ? undefined : new SourceSnapshotError("source_unavailable", "Git snapshot command failed; source history was not exported."), true));
|
|
443
|
+
});
|
|
444
|
+
}
|
|
445
|
+
export async function exportSourceSnapshot(options) {
|
|
446
|
+
if (process.platform !== "linux")
|
|
447
|
+
throw new SourceSnapshotError("unsupported_platform", "Safe source snapshots currently require Linux fd-relative reads.");
|
|
448
|
+
if (![options.target.project, options.home, ...options.authorizedRoots].every(isAbsolute))
|
|
449
|
+
throw new SourceSnapshotError("source_unavailable", "Snapshot roots must be explicit absolute paths.");
|
|
450
|
+
const reader = new Reader(options), target = options.target;
|
|
451
|
+
reader.check();
|
|
452
|
+
try {
|
|
453
|
+
await reader.verifyRoots();
|
|
454
|
+
const sourceIdentity = { runtime: target.runtime, machine_id: target.machine_id, project: target.project, selector: target.selector };
|
|
455
|
+
if (options.secretValues?.some(secret => secret && JSON.stringify(sourceIdentity).includes(secret)))
|
|
456
|
+
throw new SourceSnapshotError("source_unavailable", "Source identity contains a held credential and cannot be exported.");
|
|
457
|
+
const result = {
|
|
458
|
+
version: 1, source: { runtime: target.runtime, machine_id: target.machine_id, project: target.project, selector: target.selector }, entries: [], blobs: {},
|
|
459
|
+
instructions: { text: "", layers: [] }, skills: [], configuration: { model: target.model, tools: [], permissions: {}, credentials: ["model-provider"] }, project: { git: null }, blockers: [], transforms: [],
|
|
460
|
+
};
|
|
461
|
+
const block = (code, message, path) => { if (path && (options.secretValues?.some(secret => secret && path.includes(secret)) || secretShapes(path).length))
|
|
462
|
+
path = undefined; if (!result.blockers.some(x => x.code === code && x.path === path))
|
|
463
|
+
result.blockers.push({ code, message, ...(path ? { path } : {}) }); };
|
|
464
|
+
const runtimeConfiguration = {};
|
|
465
|
+
let modelCache, selectedAgentModel = false;
|
|
466
|
+
let bytes = 0, expandedBytes = 0;
|
|
467
|
+
const blob = (body) => { const sha = hash(body); if (!Object.hasOwn(result.blobs, sha)) {
|
|
468
|
+
if (bytes + body.length > reader.limits.bytes)
|
|
469
|
+
throw new SourceSnapshotError("limit", "Snapshot exceeds its total byte limit.");
|
|
470
|
+
bytes += body.length;
|
|
471
|
+
result.blobs[sha] = body.toString("base64");
|
|
472
|
+
} return sha; };
|
|
473
|
+
const safe = async (body, path) => {
|
|
474
|
+
reader.keepSecretCheck(body);
|
|
475
|
+
reader.keepSecretCheck(Buffer.from(path));
|
|
476
|
+
const content = body.toString("utf8");
|
|
477
|
+
// Refuse structured literal credentials even when they have no provider-specific token shape.
|
|
478
|
+
// References name a destination requirement; they never expose a source environment value.
|
|
479
|
+
const reference = (value) => /^(?:Bearer )?\$\{[A-Z_][A-Z_0-9]*\}$/.test(value);
|
|
480
|
+
const literal = (value, key = "", parent = "") => {
|
|
481
|
+
if (typeof value === "string")
|
|
482
|
+
return !!value && !reference(value) && (keyShaped(key) || /^(?:authorization|bearer|oauth|accessToken|refreshToken)$/i.test(key) || ["env", "headers", "http_headers"].includes(parent));
|
|
483
|
+
if (Array.isArray(value))
|
|
484
|
+
return value.some(item => literal(item, key, parent));
|
|
485
|
+
return value !== null && typeof value === "object" && Object.entries(value).some(([name, item]) => literal(item, name, key));
|
|
486
|
+
};
|
|
487
|
+
let structuredSecret = false;
|
|
488
|
+
try {
|
|
489
|
+
if (/\.json$/i.test(path) || /^\s*[\[{]/.test(content))
|
|
490
|
+
structuredSecret = literal(JSON.parse(content));
|
|
491
|
+
else if (/\.toml$/i.test(path))
|
|
492
|
+
structuredSecret = literal(toml(content));
|
|
493
|
+
else if (/\.ya?ml$/i.test(path))
|
|
494
|
+
structuredSecret = literal(parseDocument(content).toJS({ maxAliasCount: 0 }));
|
|
495
|
+
}
|
|
496
|
+
catch { /* Invalid source configuration is separately a blocker when it is active policy. */ }
|
|
497
|
+
if (credentialPath(path) || structuredSecret || options.secretValues?.some(secret => secret && (content.includes(secret) || path.includes(secret) || content.includes(JSON.stringify(secret).slice(1, -1)))) || secretShapes(content).length || (await secretsIn(content)).length) {
|
|
498
|
+
block("secret_content", "Credential-bearing content was withheld. Resolve the destination secret through its owner-authorized sign-in flow.", path);
|
|
499
|
+
return false;
|
|
500
|
+
}
|
|
501
|
+
return true;
|
|
502
|
+
};
|
|
503
|
+
const read = async (source, label) => {
|
|
504
|
+
try {
|
|
505
|
+
return await reader.read(source);
|
|
506
|
+
}
|
|
507
|
+
catch (error) {
|
|
508
|
+
if (error instanceof SourceSnapshotError && error.code === "source_changed")
|
|
509
|
+
throw error;
|
|
510
|
+
block(error instanceof SourceSnapshotError ? error.code : "source_unavailable", "Required source content could not be captured safely and completely.", label);
|
|
511
|
+
return null;
|
|
512
|
+
}
|
|
513
|
+
};
|
|
514
|
+
const add = async (source, path, role) => {
|
|
515
|
+
if (!portable(path)) {
|
|
516
|
+
block("path", "A source filename is not portable.");
|
|
517
|
+
return;
|
|
518
|
+
}
|
|
519
|
+
const value = await read(source, path);
|
|
520
|
+
if (!value)
|
|
521
|
+
return;
|
|
522
|
+
if (result.entries.some(entry => entry.path === path))
|
|
523
|
+
return value.bytes;
|
|
524
|
+
if (result.entries.length >= reader.limits.files) {
|
|
525
|
+
block("limit", "The source file count exceeds the snapshot limit.");
|
|
526
|
+
return;
|
|
527
|
+
}
|
|
528
|
+
const mode = Number(value.stamp.split(":")[3]) & 0o777;
|
|
529
|
+
if (value.names) {
|
|
530
|
+
if (!await safe(Buffer.alloc(0), path))
|
|
531
|
+
return;
|
|
532
|
+
result.entries.push({ path, role, type: "directory", mode, bytes: 0 });
|
|
533
|
+
return;
|
|
534
|
+
}
|
|
535
|
+
if (!value.bytes || !await safe(value.bytes, path))
|
|
536
|
+
return;
|
|
537
|
+
const discovered = target.configuration.find(file => file.path === source);
|
|
538
|
+
if (discovered && hash(value.bytes) !== discovered.sha256)
|
|
539
|
+
throw new SourceSnapshotError("source_changed", "A source policy or authored skill changed after discovery.");
|
|
540
|
+
if (expandedBytes + value.bytes.length > reader.limits.bytes) {
|
|
541
|
+
block("limit", "Expanded destination files exceed the snapshot byte limit.", path);
|
|
542
|
+
return;
|
|
543
|
+
}
|
|
544
|
+
expandedBytes += value.bytes.length;
|
|
545
|
+
result.entries.push({ path, role, type: "file", mode, bytes: value.bytes.length, sha256: blob(value.bytes) });
|
|
546
|
+
return value.bytes;
|
|
547
|
+
};
|
|
548
|
+
const tree = async (source, path, role) => {
|
|
549
|
+
const value = await read(source, path);
|
|
550
|
+
if (!value)
|
|
551
|
+
return;
|
|
552
|
+
await add(source, path, role);
|
|
553
|
+
if (value.names)
|
|
554
|
+
for (const name of value.names) {
|
|
555
|
+
if (name === ".git") {
|
|
556
|
+
block("nested_git", "Nested repositories require their own complete Git export.", path);
|
|
557
|
+
continue;
|
|
558
|
+
}
|
|
559
|
+
await tree(join(source, name), `${path}/${name}`, role);
|
|
560
|
+
}
|
|
561
|
+
};
|
|
562
|
+
const instructionTexts = [];
|
|
563
|
+
const instruction = async (source, contents) => {
|
|
564
|
+
const path = `instructions/${String(result.instructions.layers.length).padStart(3, "0")}/${basename(source)}`;
|
|
565
|
+
const body = contents === undefined ? await add(source, path, "instruction") : Buffer.from(contents);
|
|
566
|
+
if (!body)
|
|
567
|
+
return;
|
|
568
|
+
if (contents !== undefined) {
|
|
569
|
+
if (!await safe(body, path))
|
|
570
|
+
return;
|
|
571
|
+
if (expandedBytes + body.length > reader.limits.bytes) {
|
|
572
|
+
block("limit", "Expanded destination files exceed the snapshot byte limit.", path);
|
|
573
|
+
return;
|
|
574
|
+
}
|
|
575
|
+
expandedBytes += body.length;
|
|
576
|
+
result.entries.push({ path, role: "instruction", type: "file", mode: 0o644, bytes: body.length, sha256: blob(body) });
|
|
577
|
+
}
|
|
578
|
+
let decoded;
|
|
579
|
+
try {
|
|
580
|
+
decoded = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(body);
|
|
581
|
+
}
|
|
582
|
+
catch {
|
|
583
|
+
block("instruction_encoding", "Instructions must be valid UTF-8.", path);
|
|
584
|
+
return;
|
|
585
|
+
}
|
|
586
|
+
if (NATIVE_RUNTIME_FACTS[target.runtime].protocol === "claude-json" && /(^|\s)@[^\s]/m.test(decoded))
|
|
587
|
+
block("instruction_import", "Claude instruction imports require explicit closure and approval; they were not silently omitted.", path);
|
|
588
|
+
result.instructions.layers.push({ path, precedence: result.instructions.layers.length, source });
|
|
589
|
+
if (decoded.length)
|
|
590
|
+
instructionTexts.push(decoded);
|
|
591
|
+
};
|
|
592
|
+
const config = async (path) => {
|
|
593
|
+
const value = await read(path, "configuration");
|
|
594
|
+
if (!value?.bytes)
|
|
595
|
+
return {};
|
|
596
|
+
const expected = target.configuration.find(x => x.path === path)?.sha256;
|
|
597
|
+
if (expected && hash(value.bytes) !== expected)
|
|
598
|
+
throw new SourceSnapshotError("source_changed", "Configuration changed after discovery; discover the selected target again.");
|
|
599
|
+
try {
|
|
600
|
+
return object(path.endsWith(".toml") ? toml(text(value.bytes)) : JSON.parse(text(value.bytes)));
|
|
601
|
+
}
|
|
602
|
+
catch {
|
|
603
|
+
block("configuration_parse", "Required configuration could not be parsed.", basename(path));
|
|
604
|
+
return {};
|
|
605
|
+
}
|
|
606
|
+
};
|
|
607
|
+
const captureHooks = async (path, value) => {
|
|
608
|
+
if (!Object.keys(object(value.hooks)).length)
|
|
609
|
+
return value;
|
|
610
|
+
const receiptPath = join(target.project, ".agentrun", "cli-learning", `${target.runtime}.json`);
|
|
611
|
+
const receipt = await read(receiptPath, "configuration/capture-receipt"), original = await read(path, "configuration/hooks");
|
|
612
|
+
if (!receipt?.bytes || !original?.bytes)
|
|
613
|
+
return value;
|
|
614
|
+
try {
|
|
615
|
+
const transformed = removeOwnedCaptureHooks(original.bytes, receipt.bytes, result.source);
|
|
616
|
+
const expected = join(transformed.configRoot, NATIVE_RUNTIME_FACTS[target.runtime].protocol === "codex-json" ? ".codex/hooks.json" : ".claude/settings.local.json");
|
|
617
|
+
if (resolve(path) !== resolve(expected) || transformed.configRoot !== target.project && (!gitCommonDirectory || resolve(transformed.configRoot) !== dirname(gitCommonDirectory)))
|
|
618
|
+
return value;
|
|
619
|
+
const projectPath = within(resolve(target.project), resolve(path)) ? `project/${relative(target.project, path).split(sep).join("/")}` : undefined;
|
|
620
|
+
const sourceEntry = projectPath ?? `instructions/capture-hooks/${hash(path).slice(0, 12)}/${basename(path)}`;
|
|
621
|
+
const receiptEntry = `project/.agentrun/cli-learning/${target.runtime}.json`;
|
|
622
|
+
for (const directory of [".agentrun", ".agentrun/cli-learning"])
|
|
623
|
+
await add(join(target.project, directory), `project/${directory}`, "project");
|
|
624
|
+
if (!await add(receiptPath, receiptEntry, "project") || !await add(path, sourceEntry, projectPath ? "project" : "instruction"))
|
|
625
|
+
return value;
|
|
626
|
+
const originalEntry = result.entries.find(entry => entry.path === sourceEntry);
|
|
627
|
+
const heldReceipt = result.entries.find(entry => entry.path === receiptEntry);
|
|
628
|
+
if (!await safe(transformed.bytes, sourceEntry) || transformed.bytes.length > reader.limits.fileBytes)
|
|
629
|
+
return value;
|
|
630
|
+
if (expandedBytes + transformed.bytes.length > reader.limits.bytes) {
|
|
631
|
+
block("limit", "Transformed capture metadata exceeds the snapshot byte limit.");
|
|
632
|
+
return value;
|
|
633
|
+
}
|
|
634
|
+
expandedBytes += transformed.bytes.length;
|
|
635
|
+
const transformedHash = blob(transformed.bytes);
|
|
636
|
+
result.transforms.push({ kind: "agentrun-capture-hooks", path: sourceEntry, original_sha256: originalEntry.sha256, original_bytes: originalEntry.bytes,
|
|
637
|
+
destination_sha256: transformedHash, destination_bytes: transformed.bytes.length, receipt: { path: receiptEntry, sha256: heldReceipt.sha256 } });
|
|
638
|
+
return object(JSON.parse(text(transformed.bytes)));
|
|
639
|
+
}
|
|
640
|
+
catch {
|
|
641
|
+
return value;
|
|
642
|
+
} // An unproven installation remains required source policy, never an exemption.
|
|
643
|
+
};
|
|
644
|
+
const toolDefinitions = new Map(), handledTools = new Set();
|
|
645
|
+
const codexTools = NATIVE_RUNTIME_FACTS[target.runtime].protocol === "codex-json";
|
|
646
|
+
const mergeTable = (prior, next) => {
|
|
647
|
+
const merged = Object.assign(Object.create(null), prior);
|
|
648
|
+
for (const [key, value] of Object.entries(next))
|
|
649
|
+
merged[key] = value && typeof value === "object" && !Array.isArray(value)
|
|
650
|
+
? mergeTable(object(Object.hasOwn(prior, key) ? prior[key] : undefined), value) : value;
|
|
651
|
+
return merged;
|
|
652
|
+
};
|
|
653
|
+
const tools = async (servers, label) => {
|
|
654
|
+
for (const [name, raw] of Object.entries(object(servers))) {
|
|
655
|
+
if (!await safe(Buffer.alloc(0), `${label}/${name}`))
|
|
656
|
+
continue;
|
|
657
|
+
handledTools.add(name);
|
|
658
|
+
// Codex config tables merge from lower to higher precedence. Claude scope entries are
|
|
659
|
+
// selected whole before reaching this function, rather than merging credentials across scopes.
|
|
660
|
+
const value = codexTools ? { ...toolDefinitions.get(name), ...object(raw) } : object(raw), credentials = [];
|
|
661
|
+
toolDefinitions.set(name, value);
|
|
662
|
+
if (codexTools && value.enabled === false) {
|
|
663
|
+
result.configuration.tools = result.configuration.tools.filter(tool => tool.name !== name);
|
|
664
|
+
continue;
|
|
665
|
+
}
|
|
666
|
+
const supported = new Set(["url", "type", "env_vars", "required_env_vars", "bearer_token_env_var", "env", "headers", "http_headers", "command", ...(codexTools ? ["enabled", "enabled_tools", "disabled_tools"] : [])]);
|
|
667
|
+
if (Object.keys(value).some(key => !supported.has(key)) || value.type !== undefined && value.type !== "http"
|
|
668
|
+
|| codexTools && value.enabled !== undefined && typeof value.enabled !== "boolean"
|
|
669
|
+
|| ["env_vars", "required_env_vars"].some(key => value[key] !== undefined && (!Array.isArray(value[key]) || value[key].some((item) => typeof item !== "string")))
|
|
670
|
+
|| value.bearer_token_env_var !== undefined && typeof value.bearer_token_env_var !== "string")
|
|
671
|
+
block("tool_configuration", "A tool has capability, transport or policy settings without a supported destination equivalent.", `${label}/${name}`);
|
|
672
|
+
for (const key of ["headers", "http_headers"])
|
|
673
|
+
for (const [header, setting] of Object.entries(object(value[key]))) {
|
|
674
|
+
if (header.toLowerCase() !== "authorization" || typeof setting !== "string" || !/^Bearer \$\{[A-Z_][A-Z_0-9]*\}$/.test(setting))
|
|
675
|
+
block("tool_configuration", "A custom tool header needs an explicit destination equivalent.", `${label}/${name}`);
|
|
676
|
+
}
|
|
677
|
+
for (const field of ["env_vars", "required_env_vars"])
|
|
678
|
+
if (Array.isArray(value[field]))
|
|
679
|
+
for (const name of value[field])
|
|
680
|
+
if (typeof name === "string")
|
|
681
|
+
credentials.push(name);
|
|
682
|
+
if (typeof value.bearer_token_env_var === "string")
|
|
683
|
+
credentials.push(value.bearer_token_env_var);
|
|
684
|
+
let literalCredential = false;
|
|
685
|
+
for (const [key, setting] of Object.entries({ ...object(value.env), ...object(value.headers ?? value.http_headers) })) {
|
|
686
|
+
const reference = typeof setting === "string" && setting.match(/^(?:Bearer )?\$\{([A-Z_][A-Z_0-9]*)\}$/);
|
|
687
|
+
if (reference)
|
|
688
|
+
credentials.push(reference[1]);
|
|
689
|
+
else
|
|
690
|
+
literalCredential = true;
|
|
691
|
+
}
|
|
692
|
+
if (literalCredential || Object.keys(value).some(key => keyShaped(key) && key !== "bearer_token_env_var"))
|
|
693
|
+
block("tool_secret", "A tool has literal environment/authentication settings. Use destination secret setup; source values were not exported.", `${label}/${name}`);
|
|
694
|
+
const transport = value.command ? "stdio" : "http";
|
|
695
|
+
if (transport === "stdio")
|
|
696
|
+
block("stdio_tool", "A required stdio tool needs a supported destination equivalent.", `${label}/${name}`);
|
|
697
|
+
let url;
|
|
698
|
+
if (typeof value.url === "string")
|
|
699
|
+
try {
|
|
700
|
+
const parsed = new URL(value.url);
|
|
701
|
+
if (!["http:", "https:"].includes(parsed.protocol) || parsed.username || parsed.password || parsed.search || parsed.hash || !await safe(Buffer.from(value.url), `${label}/${name}`))
|
|
702
|
+
throw new Error();
|
|
703
|
+
url = parsed.toString();
|
|
704
|
+
}
|
|
705
|
+
catch {
|
|
706
|
+
block("tool_url", "The tool URL cannot be exported without preserving or exposing unsupported authentication.", `${label}/${name}`);
|
|
707
|
+
}
|
|
708
|
+
if (transport === "http" && !url)
|
|
709
|
+
block("tool_transport", "A tool endpoint could not be resolved.", `${label}/${name}`);
|
|
710
|
+
const selection = { dialect: "exact", allow: value.enabled_tools === undefined ? null : value.enabled_tools, deny: value.disabled_tools ?? [] };
|
|
711
|
+
if (codexTools && !sourceMcpSelection(selection))
|
|
712
|
+
block("tool_selection", "An MCP tool allow/deny list needs valid exact names.", `${label}/${name}`);
|
|
713
|
+
const tool = { name, transport, ...(url ? { url } : {}), credentials: [...new Set(credentials)].sort(),
|
|
714
|
+
...(codexTools && sourceMcpSelection(selection) ? { selection: { ...selection, allow: selection.allow === null ? null : [...selection.allow].sort(), deny: [...selection.deny].sort() }, resources: ["list", "templates", "read"] } : {}) };
|
|
715
|
+
const existing = result.configuration.tools.findIndex(x => x.name === name);
|
|
716
|
+
if (existing >= 0)
|
|
717
|
+
result.configuration.tools[existing] = tool;
|
|
718
|
+
else
|
|
719
|
+
result.configuration.tools.push(tool);
|
|
720
|
+
}
|
|
721
|
+
};
|
|
722
|
+
// Discover the working tree from explicit authorized paths; .git pointers outside the grant block Git reads.
|
|
723
|
+
let root = resolve(target.project), gitRoot, gitControl, gitDirectory, gitCommonDirectory;
|
|
724
|
+
for (let cursor = root; reader.granted(cursor); cursor = dirname(cursor)) {
|
|
725
|
+
const control = await read(join(cursor, ".git"), "project/.git");
|
|
726
|
+
if (control) {
|
|
727
|
+
gitRoot = cursor;
|
|
728
|
+
gitControl = join(cursor, ".git");
|
|
729
|
+
gitDirectory = gitControl;
|
|
730
|
+
if (control.bytes) {
|
|
731
|
+
const match = text(control.bytes).match(/^gitdir: (.+)\r?\n?$/);
|
|
732
|
+
if (!match)
|
|
733
|
+
block("git_control", "Git worktree control could not be resolved.");
|
|
734
|
+
else {
|
|
735
|
+
const dir = resolve(cursor, match[1]);
|
|
736
|
+
gitDirectory = dir;
|
|
737
|
+
if (!reader.granted(dir) || !(await read(dir, "project/.git"))?.names)
|
|
738
|
+
block("git_control", "The Git directory is outside the source grant or cannot be read safely.");
|
|
739
|
+
}
|
|
740
|
+
}
|
|
741
|
+
break;
|
|
742
|
+
}
|
|
743
|
+
if (dirname(cursor) === cursor)
|
|
744
|
+
break;
|
|
745
|
+
}
|
|
746
|
+
// Check Git's own path indirections before invoking it. No hooks, filters, external object alternates,
|
|
747
|
+
// included configuration or ungranted common worktree database may silently enlarge the source grant.
|
|
748
|
+
if (gitDirectory && !result.blockers.some(x => x.code === "git_control"))
|
|
749
|
+
try {
|
|
750
|
+
const common = await reader.read(join(gitDirectory, "commondir"));
|
|
751
|
+
const commonDirectory = common?.bytes ? resolve(gitDirectory, text(common.bytes).trim()) : gitDirectory;
|
|
752
|
+
gitCommonDirectory = commonDirectory;
|
|
753
|
+
if (!reader.granted(commonDirectory))
|
|
754
|
+
throw new Error();
|
|
755
|
+
for (const directory of new Set([gitDirectory, commonDirectory])) {
|
|
756
|
+
for (const name of ["HEAD", "packed-refs", "index", "shallow", "config", "config.worktree"]) {
|
|
757
|
+
const file = await reader.read(join(directory, name));
|
|
758
|
+
if (name.startsWith("config") && file?.bytes && /^\s*\[\s*(?:include|includeIf|filter|extensions|submodule)(?:\s|\]|\")/mi.test(text(file.bytes)))
|
|
759
|
+
throw new Error();
|
|
760
|
+
if (name.startsWith("config") && file?.bytes && /^\s*(?:worktree\s*=|bare\s*=\s*true|excludesfile\s*=|sparsecheckout\s*=)/mi.test(text(file.bytes)))
|
|
761
|
+
throw new Error();
|
|
762
|
+
}
|
|
763
|
+
for (const name of ["refs", "objects"])
|
|
764
|
+
if (await reader.read(join(directory, name)))
|
|
765
|
+
await reader.inspectObjects(join(directory, name));
|
|
766
|
+
for (const name of ["alternates", "http-alternates"])
|
|
767
|
+
if ((await reader.read(join(directory, "objects", "info", name)))?.bytes?.length)
|
|
768
|
+
throw new Error();
|
|
769
|
+
}
|
|
770
|
+
await reader.isolateGit(gitDirectory, commonDirectory);
|
|
771
|
+
}
|
|
772
|
+
catch (error) {
|
|
773
|
+
if (error instanceof SourceSnapshotError && error.code === "source_changed")
|
|
774
|
+
throw error;
|
|
775
|
+
block("git_control", "Git links, filters, included settings, extensions or external object stores need an explicit safe export.");
|
|
776
|
+
}
|
|
777
|
+
let gitStart;
|
|
778
|
+
const gitState = async () => {
|
|
779
|
+
let head = null;
|
|
780
|
+
try {
|
|
781
|
+
head = text(await git(reader, ["rev-parse", "--verify", "HEAD"])).trim();
|
|
782
|
+
}
|
|
783
|
+
catch { /* unborn HEAD is handled explicitly */ }
|
|
784
|
+
return { head, status: text(await git(reader, ["status", "--porcelain=v1", "-z", "--untracked-files=all", "--ignore-submodules=all"])), index: text(await git(reader, ["ls-files", "--stage", "-z"])), untracked: text(await git(reader, ["ls-files", "--others", "--exclude-standard", "-z"])) };
|
|
785
|
+
};
|
|
786
|
+
if (gitRoot && gitControl && !result.blockers.some(x => x.code === "git_control")) {
|
|
787
|
+
if (gitRoot !== root)
|
|
788
|
+
block("git_subdirectory", "Select the repository root so its history and working tree have the same portable paths.");
|
|
789
|
+
else
|
|
790
|
+
try {
|
|
791
|
+
gitStart = await gitState();
|
|
792
|
+
let branch = null;
|
|
793
|
+
try {
|
|
794
|
+
branch = text(await git(reader, ["symbolic-ref", "--short", "HEAD"])).trim();
|
|
795
|
+
}
|
|
796
|
+
catch { /* detached HEAD */ }
|
|
797
|
+
if (branch !== null && !await safe(Buffer.from(branch), "Git branch"))
|
|
798
|
+
branch = null;
|
|
799
|
+
result.project.git = { head: gitStart.head, branch, dirty: !!gitStart.status, deleted: [], history: "unavailable" };
|
|
800
|
+
const files = new Set();
|
|
801
|
+
for (const record of gitStart.index.split("\0").filter(Boolean)) {
|
|
802
|
+
const match = record.match(/^(\d+) ([a-f0-9]+) (\d)\t([\s\S]+)$/);
|
|
803
|
+
if (!match || match[3] !== "0") {
|
|
804
|
+
block("git_index", "An unresolved Git index cannot be exported faithfully.");
|
|
805
|
+
continue;
|
|
806
|
+
}
|
|
807
|
+
if (match[1] === "160000") {
|
|
808
|
+
block("git_submodule", "Submodule history and worktrees need an explicit export.", `project/${match[4]}`);
|
|
809
|
+
continue;
|
|
810
|
+
}
|
|
811
|
+
files.add(match[4]);
|
|
812
|
+
}
|
|
813
|
+
for (const path of gitStart.untracked.split("\0").filter(Boolean))
|
|
814
|
+
files.add(path);
|
|
815
|
+
await add(root, "project", "project");
|
|
816
|
+
for (const path of [...files].sort()) {
|
|
817
|
+
if (!portable(path)) {
|
|
818
|
+
block("path", "A Git path is not portable.");
|
|
819
|
+
continue;
|
|
820
|
+
}
|
|
821
|
+
const parts = path.split("/");
|
|
822
|
+
for (let index = 1; index < parts.length; index++) {
|
|
823
|
+
const parent = parts.slice(0, index).join("/");
|
|
824
|
+
await add(join(root, parent), `project/${parent}`, "project");
|
|
825
|
+
}
|
|
826
|
+
if (!await read(join(root, path), `project/${path}`))
|
|
827
|
+
result.project.git.deleted.push(path);
|
|
828
|
+
else
|
|
829
|
+
await add(join(root, path), `project/${path}`, "project");
|
|
830
|
+
}
|
|
831
|
+
// Staged content differs from both HEAD and the current worktree in general. Do not claim index fidelity.
|
|
832
|
+
if (gitStart.status.split("\0").some(line => line && ![" ", "?"].includes(line[0])))
|
|
833
|
+
block("git_staging", "Commit or unstage index changes before moving; the working files are captured but index staging is not portable yet.");
|
|
834
|
+
const localConfig = text(await git(reader, ["config", "--local", "--null", "--list"]));
|
|
835
|
+
if (/(?:^|\0)(?:filter\.|include(?:if)?\.|extensions\.|core\.(?:worktree|sparsecheckout)|submodule\.)/i.test(localConfig))
|
|
836
|
+
block("git_configuration", "Git filters, includes, extensions or submodules need an explicit portable configuration.");
|
|
837
|
+
if (!gitStart.head)
|
|
838
|
+
block("git_unborn", "A Git repository with no commit needs an initial commit before its history can be exported.");
|
|
839
|
+
else {
|
|
840
|
+
const objects = text(await git(reader, ["rev-list", "--objects", "HEAD"])).split("\n").filter(Boolean);
|
|
841
|
+
let historyBytes = 0, historySafe = true;
|
|
842
|
+
for (const row of objects) {
|
|
843
|
+
const match = row.match(/^([a-f0-9]{40,64})(?: (.*))?$/);
|
|
844
|
+
if (!match || (match[2] && (!portable(match[2]) || credentialPath(match[2])))) {
|
|
845
|
+
historySafe = false;
|
|
846
|
+
break;
|
|
847
|
+
}
|
|
848
|
+
const body = await git(reader, ["cat-file", "-p", match[1]], reader.limits.fileBytes);
|
|
849
|
+
historyBytes += body.length;
|
|
850
|
+
// Tree records name every historical path, even when rev-list chose another path for a shared blob.
|
|
851
|
+
const historicalCredential = body.toString("utf8").split("\n").some(line => { const entry = line.match(/^\d{6} (?:blob|tree|commit) [a-f0-9]+\t(.+)$/); return entry && credentialPath(entry[1]); });
|
|
852
|
+
if (historyBytes > reader.limits.gitBytes || historicalCredential || !await safe(body, match[2] ? `Git history/${match[2]}` : "Git history")) {
|
|
853
|
+
historySafe = false;
|
|
854
|
+
break;
|
|
855
|
+
}
|
|
856
|
+
if (text(await git(reader, ["cat-file", "-t", match[1]])).trim() === "commit") {
|
|
857
|
+
// Pretty tree output quotes non-ASCII names, and rev-list names shared blobs once.
|
|
858
|
+
// Inspect every commit's actual unquoted paths before its compressed bundle can leave.
|
|
859
|
+
const listing = await git(reader, ["ls-tree", "-r", "-z", match[1]], reader.limits.fileBytes);
|
|
860
|
+
historyBytes += listing.length;
|
|
861
|
+
if (historyBytes > reader.limits.gitBytes) {
|
|
862
|
+
historySafe = false;
|
|
863
|
+
break;
|
|
864
|
+
}
|
|
865
|
+
reader.keepSecretCheck(listing);
|
|
866
|
+
for (const entry of text(listing).split("\0").filter(Boolean)) {
|
|
867
|
+
const found = /^(100644|100755) blob [a-f0-9]{40,64}\t([\s\S]+)$/.exec(entry);
|
|
868
|
+
if (!found || !portable(found[2]) || credentialPath(found[2])) {
|
|
869
|
+
historySafe = false;
|
|
870
|
+
break;
|
|
871
|
+
}
|
|
872
|
+
reader.keepSecretCheck(Buffer.from(found[2]));
|
|
873
|
+
}
|
|
874
|
+
if (!historySafe)
|
|
875
|
+
break;
|
|
876
|
+
}
|
|
877
|
+
}
|
|
878
|
+
if (historySafe) {
|
|
879
|
+
// A temporary owned directory is the only exporter write; stdout streaming bounds the bundle itself.
|
|
880
|
+
const temp = await mkdtemp(join(tmpdir(), "agentrun-source-bundle-"));
|
|
881
|
+
try {
|
|
882
|
+
const bundle = await git(reader, ["bundle", "create", "-", "HEAD"]);
|
|
883
|
+
if (expandedBytes + bundle.length > reader.limits.bytes)
|
|
884
|
+
throw new SourceSnapshotError("limit", "Expanded project and Git history exceed the snapshot byte limit.");
|
|
885
|
+
await writeFile(join(temp, "repository.bundle"), bundle, { mode: 0o600 });
|
|
886
|
+
expandedBytes += bundle.length;
|
|
887
|
+
result.project.git.bundle = { sha256: blob(bundle), bytes: bundle.length };
|
|
888
|
+
result.project.git.history = "complete";
|
|
889
|
+
}
|
|
890
|
+
finally {
|
|
891
|
+
await rm(temp, { recursive: true, force: true });
|
|
892
|
+
}
|
|
893
|
+
}
|
|
894
|
+
else
|
|
895
|
+
block("git_history", "Git history contains excluded credentials, unsupported paths, or exceeds the export limit; no bundle was exported.");
|
|
896
|
+
}
|
|
897
|
+
}
|
|
898
|
+
catch (error) {
|
|
899
|
+
if (error instanceof SourceSnapshotError && error.code === "source_changed")
|
|
900
|
+
throw error;
|
|
901
|
+
block("git_export", "The complete Git project could not be exported within its safe bounds.");
|
|
902
|
+
}
|
|
903
|
+
}
|
|
904
|
+
else if (!gitRoot)
|
|
905
|
+
await tree(root, "project", "project");
|
|
906
|
+
const ancestors = [];
|
|
907
|
+
for (let path = root;; path = dirname(path)) {
|
|
908
|
+
ancestors.unshift(path);
|
|
909
|
+
if (path === (gitRoot ?? root) || dirname(path) === path)
|
|
910
|
+
break;
|
|
911
|
+
}
|
|
912
|
+
if (NATIVE_RUNTIME_FACTS[target.runtime].protocol === "codex-json") {
|
|
913
|
+
const home = options.codexHome ?? join(options.home, ".codex");
|
|
914
|
+
for (const path of SYSTEM_POLICY_PATHS)
|
|
915
|
+
if (await reader.policyPresent(path))
|
|
916
|
+
block("native_managed_policy", "This source has managed system policy that needs a verified destination equivalent before Move.", "configuration/managed_policy");
|
|
917
|
+
// Only fixed, nonsecret labels leave the private auth reader. Saved claims establish source
|
|
918
|
+
// policy eligibility, never destination authentication; managed/unknown accounts still block.
|
|
919
|
+
const account = await reader.accountMetadata(join(home, "auth.json"));
|
|
920
|
+
result.configuration.native_account = account;
|
|
921
|
+
if (account.plan === "managed" || account.plan === "unknown")
|
|
922
|
+
block("native_account_policy", "The source account policy is managed or unresolved. Resolve it locally before Move; native sign-in is never copied.", "configuration/account_policy");
|
|
923
|
+
const accountPaths = [join(home, "cloud-config-bundle-cache.json")];
|
|
924
|
+
const homeNames = (await reader.read(home))?.names ?? [];
|
|
925
|
+
accountPaths.push(...homeNames.filter(name => /^managed-config-.*\.json$/.test(name)).map(name => join(home, name)));
|
|
926
|
+
for (const path of accountPaths)
|
|
927
|
+
if (await reader.policyPresent(path))
|
|
928
|
+
block("native_account_policy", "The source account may supply managed policy. Resolve its effective policy without copying native sign-in before Move.", "configuration/account_policy");
|
|
929
|
+
for (const dir of [home, ...ancestors]) {
|
|
930
|
+
const override = join(dir, "AGENTS.override.md"), normal = join(dir, "AGENTS.md");
|
|
931
|
+
if ((await read(override, "instructions"))?.bytes)
|
|
932
|
+
await instruction(override);
|
|
933
|
+
else if ((await read(normal, "instructions"))?.bytes)
|
|
934
|
+
await instruction(normal);
|
|
935
|
+
}
|
|
936
|
+
const receiptMetadata = await config(join(root, ".agentrun", "cli-learning", `${target.runtime}.json`));
|
|
937
|
+
const sharedHooks = receiptMetadata.version === 2 && typeof receiptMetadata.configRoot === "string" && isAbsolute(receiptMetadata.configRoot)
|
|
938
|
+
? [join(receiptMetadata.configRoot, ".codex", "hooks.json")] : [];
|
|
939
|
+
for (const path of new Set([join(home, "hooks.json"), ...ancestors.map(dir => join(dir, ".codex", "hooks.json")), ...sharedHooks])) {
|
|
940
|
+
const hooks = await captureHooks(path, await config(path));
|
|
941
|
+
if (Object.keys(hooks).length)
|
|
942
|
+
block("hooks", "Source hooks need an explicit destination equivalent; they were not silently dropped.", "configuration/hooks");
|
|
943
|
+
}
|
|
944
|
+
const configs = [join(home, "config.toml"), ...ancestors.map(dir => join(dir, ".codex", "config.toml")), ...(target.selector.kind === "profile" ? [join(home, `${target.selector.name}.config.toml`)] : [])];
|
|
945
|
+
for (const file of target.configuration)
|
|
946
|
+
if (basename(file.path) === "config.toml" && !configs.includes(file.path))
|
|
947
|
+
block("configuration_precedence", "A discovered configuration layer has unresolved precedence or lies outside the selected project scope.", "configuration");
|
|
948
|
+
const userConfig = await config(join(home, "config.toml"));
|
|
949
|
+
const selectedTrust = object(object(userConfig.projects)[root]).trust_level;
|
|
950
|
+
for (const path of configs) {
|
|
951
|
+
const value = path === join(home, "config.toml") ? userConfig : await config(path);
|
|
952
|
+
// Codex gates project layers using trusted configuration, before loading the layer itself.
|
|
953
|
+
// A project cannot make its own disabling settings effective by declaring itself trusted.
|
|
954
|
+
if (ancestors.some(dir => path === join(dir, ".codex", "config.toml")) && Object.keys(value).length && selectedTrust !== "trusted") {
|
|
955
|
+
block("project_configuration_trust", "The selected project's configuration needs a verified source trust decision before it can be applied.", "configuration/project_trust");
|
|
956
|
+
continue;
|
|
957
|
+
}
|
|
958
|
+
for (const [key, setting] of Object.entries(value)) {
|
|
959
|
+
if (key === "model" && typeof setting === "string")
|
|
960
|
+
result.configuration.model = setting;
|
|
961
|
+
else if (key === "projects") {
|
|
962
|
+
const projects = object(setting), selected = projects[root];
|
|
963
|
+
// Trust belongs to the selected project, not every unrelated checkout in the user's file.
|
|
964
|
+
if (selected !== undefined) {
|
|
965
|
+
const policy = object(selected);
|
|
966
|
+
if (Object.keys(policy).some(name => name !== "trust_level") || !["trusted", "untrusted"].includes(policy.trust_level))
|
|
967
|
+
block("project_trust", "The selected project's trust policy needs an explicit supported interpretation.", "configuration/project_trust");
|
|
968
|
+
else
|
|
969
|
+
result.configuration.permissions.project_trust = policy.trust_level;
|
|
970
|
+
}
|
|
971
|
+
}
|
|
972
|
+
else if (key === "features") {
|
|
973
|
+
const features = object(setting);
|
|
974
|
+
if (Object.keys(features).some(name => !SOURCE_CODEX_FEATURES.includes(name) || typeof features[name] !== "boolean"))
|
|
975
|
+
block("native_features", "A source runtime feature needs verified capability resolution.", "configuration/features");
|
|
976
|
+
runtimeConfiguration.features = { ...object(runtimeConfiguration.features), ...features };
|
|
977
|
+
}
|
|
978
|
+
else if (key === "tools") {
|
|
979
|
+
const settings = object(setting);
|
|
980
|
+
if (Object.keys(settings).some(name => !["update_plan", "experimental_request_user_input"].includes(name) || Object.keys(object(settings[name])).some(field => field !== "enabled") || typeof settings[name]?.enabled !== "boolean"))
|
|
981
|
+
block("native_tools", "A builtin tool setting needs verified capability resolution.", "configuration/tools");
|
|
982
|
+
runtimeConfiguration.tools = { ...object(runtimeConfiguration.tools), ...settings };
|
|
983
|
+
}
|
|
984
|
+
else if (key === "agents") {
|
|
985
|
+
const agents = object(setting);
|
|
986
|
+
if (Object.keys(agents).some(name => name !== "enabled") || typeof agents.enabled !== "boolean")
|
|
987
|
+
block("native_agents", "A source subagent setting needs verified capability resolution.", "configuration/agents");
|
|
988
|
+
runtimeConfiguration.agents = agents;
|
|
989
|
+
}
|
|
990
|
+
else if (key === "cloud") {
|
|
991
|
+
const cloud = object(setting);
|
|
992
|
+
if (Object.keys(cloud).some(name => name !== "skills") || Object.keys(object(cloud.skills)).some(name => name !== "enabled") || typeof cloud.skills?.enabled !== "boolean")
|
|
993
|
+
block("native_cloud", "A source cloud integration needs verified capability resolution.", "configuration/cloud");
|
|
994
|
+
runtimeConfiguration.cloud = cloud;
|
|
995
|
+
}
|
|
996
|
+
else if (["approval_policy", "sandbox_mode", "sandbox_workspace_write", "web_search"].includes(key)) {
|
|
997
|
+
if (await safe(Buffer.from(canonical(setting)), `configuration/${key}`))
|
|
998
|
+
result.configuration.permissions[key] = setting;
|
|
999
|
+
}
|
|
1000
|
+
else if (key === "mcp_servers") {
|
|
1001
|
+
for (const [name, value] of Object.entries(object(setting)))
|
|
1002
|
+
toolDefinitions.set(name, mergeTable(toolDefinitions.get(name) ?? {}, object(value)));
|
|
1003
|
+
}
|
|
1004
|
+
else if (key === "cli_auth_credentials_store" && setting === "file") { /* supported private metadata projection; never exported credentials */ }
|
|
1005
|
+
else if (key === "developer_instructions" && typeof setting === "string")
|
|
1006
|
+
await instruction(path, setting);
|
|
1007
|
+
else
|
|
1008
|
+
block("unsupported_setting", "This Codex setting needs an explicit managed equivalent.", `configuration/${key}`);
|
|
1009
|
+
}
|
|
1010
|
+
}
|
|
1011
|
+
await tools(Object.fromEntries(toolDefinitions), "tools");
|
|
1012
|
+
modelCache = await config(join(home, "models_cache.json"));
|
|
1013
|
+
if (target.version === "0.171.0" && result.configuration.permissions.web_search === undefined)
|
|
1014
|
+
result.configuration.permissions.web_search = "cached";
|
|
1015
|
+
if (target.selector.kind === "agent")
|
|
1016
|
+
block("selector", "Codex agent selectors are not supported by this exporter.");
|
|
1017
|
+
}
|
|
1018
|
+
else {
|
|
1019
|
+
const home = options.claudeHome ?? join(options.home, ".claude");
|
|
1020
|
+
const disabledProjectMcp = new Set();
|
|
1021
|
+
for (const path of [join(home, "CLAUDE.md"), ...ancestors.flatMap(dir => [join(dir, "CLAUDE.md"), join(dir, ".claude", "CLAUDE.md"), join(dir, "CLAUDE.local.md")])])
|
|
1022
|
+
if ((await read(path, "instructions"))?.bytes)
|
|
1023
|
+
await instruction(path);
|
|
1024
|
+
let selected = target.selector.kind === "agent" ? target.selector.name : undefined;
|
|
1025
|
+
for (const path of [join(home, "settings.json"), join(root, ".claude", "settings.json"), join(root, ".claude", "settings.local.json")]) {
|
|
1026
|
+
const value = await captureHooks(path, await config(path));
|
|
1027
|
+
for (const [key, setting] of Object.entries(value)) {
|
|
1028
|
+
if (key === "model" && typeof setting === "string")
|
|
1029
|
+
result.configuration.model = setting;
|
|
1030
|
+
else if (key === "agent" && typeof setting === "string") {
|
|
1031
|
+
if (target.selector.kind === "project")
|
|
1032
|
+
selected = setting;
|
|
1033
|
+
}
|
|
1034
|
+
else if (["enabledMcpjsonServers", "disabledMcpjsonServers"].includes(key) && Array.isArray(setting) && setting.every(name => typeof name === "string")) {
|
|
1035
|
+
if (key === "disabledMcpjsonServers")
|
|
1036
|
+
for (const name of setting)
|
|
1037
|
+
disabledProjectMcp.add(name);
|
|
1038
|
+
}
|
|
1039
|
+
else if (key === "enableAllProjectMcpServers" && typeof setting === "boolean") { /* destination account choice is still explicit */ }
|
|
1040
|
+
else if (key === "permissions" && await safe(Buffer.from(canonical(setting)), "configuration/permissions")) {
|
|
1041
|
+
for (const [name, policy] of Object.entries(object(setting))) {
|
|
1042
|
+
// Modern Claude ignores these privileged modes in project/local settings. Until the
|
|
1043
|
+
// installed resolver proves the effective fallback, never widen the user policy here.
|
|
1044
|
+
if (name === "defaultMode" && path !== join(home, "settings.json") && ["bypassPermissions", "auto"].includes(String(policy))) {
|
|
1045
|
+
block("permission_scope", "This project permission mode needs the source runtime's effective user policy before Move.", "configuration/permissions/defaultMode");
|
|
1046
|
+
continue;
|
|
1047
|
+
}
|
|
1048
|
+
if (["allow", "deny", "ask"].includes(name) && Array.isArray(policy)) {
|
|
1049
|
+
const prior = result.configuration.permissions[name];
|
|
1050
|
+
result.configuration.permissions[name] = [...new Set([...(Array.isArray(prior) ? prior : []), ...policy])];
|
|
1051
|
+
}
|
|
1052
|
+
else
|
|
1053
|
+
result.configuration.permissions[name] = policy;
|
|
1054
|
+
}
|
|
1055
|
+
}
|
|
1056
|
+
else
|
|
1057
|
+
block("unsupported_setting", "This Claude setting needs an explicit managed equivalent.", `configuration/${key}`);
|
|
1058
|
+
}
|
|
1059
|
+
}
|
|
1060
|
+
const user = await config(join(options.home, ".claude.json")), local = object(user.projects?.[root]);
|
|
1061
|
+
// Claude uses a whole server entry from local > project > user; fields never merge across scopes.
|
|
1062
|
+
const effective = Object.assign(Object.create(null), object(user.mcpServers));
|
|
1063
|
+
for (const dir of ancestors)
|
|
1064
|
+
for (const [name, value] of Object.entries(object((await config(join(dir, ".mcp.json"))).mcpServers))) {
|
|
1065
|
+
handledTools.add(name);
|
|
1066
|
+
if (!disabledProjectMcp.has(name))
|
|
1067
|
+
effective[name] = value;
|
|
1068
|
+
}
|
|
1069
|
+
Object.assign(effective, object(local.mcpServers));
|
|
1070
|
+
if (local.disabledMcpServers !== undefined && (!Array.isArray(local.disabledMcpServers) || local.disabledMcpServers.some((name) => typeof name !== "string")))
|
|
1071
|
+
block("tool_configuration", "Source MCP enable/disable policy needs a valid server list.", "configuration/tools");
|
|
1072
|
+
for (const name of Array.isArray(local.disabledMcpServers) ? local.disabledMcpServers : []) {
|
|
1073
|
+
handledTools.add(name);
|
|
1074
|
+
delete effective[name];
|
|
1075
|
+
}
|
|
1076
|
+
if (local.enabledMcpServers !== undefined && (!Array.isArray(local.enabledMcpServers) || local.enabledMcpServers.some((name) => typeof name !== "string" || !Object.hasOwn(effective, name))))
|
|
1077
|
+
block("tool_configuration", "An enabled builtin MCP integration needs an explicit destination equivalent.", "configuration/tools");
|
|
1078
|
+
await tools(effective, "tools");
|
|
1079
|
+
if (selected) {
|
|
1080
|
+
let chosen;
|
|
1081
|
+
for (const file of target.configuration.filter(x => basename(dirname(x.path)) === "agents" && x.path.endsWith(".md"))) {
|
|
1082
|
+
const value = await read(file.path, "agent");
|
|
1083
|
+
if (!value?.bytes)
|
|
1084
|
+
continue;
|
|
1085
|
+
if (hash(value.bytes) !== file.sha256)
|
|
1086
|
+
throw new SourceSnapshotError("source_changed", "Selected agent configuration changed after discovery.");
|
|
1087
|
+
const body = text(value.bytes), match = body.match(/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/);
|
|
1088
|
+
const document = parseDocument(match?.[1] ?? "");
|
|
1089
|
+
if (document.errors.length) {
|
|
1090
|
+
block("agent_frontmatter", "An agent definition cannot be parsed safely.");
|
|
1091
|
+
continue;
|
|
1092
|
+
}
|
|
1093
|
+
const front = object(document.toJS({ maxAliasCount: 0 }));
|
|
1094
|
+
if ((front.name ?? basename(file.path, ".md")) === selected)
|
|
1095
|
+
chosen = { path: file.path, body: body.slice(match?.[0].length ?? 0), front };
|
|
1096
|
+
}
|
|
1097
|
+
if (!chosen)
|
|
1098
|
+
block("selector", "The selected Claude agent definition was not captured.");
|
|
1099
|
+
else {
|
|
1100
|
+
await instruction(chosen.path, chosen.body);
|
|
1101
|
+
for (const [key, value] of Object.entries(chosen.front)) {
|
|
1102
|
+
if (["name", "description"].includes(key))
|
|
1103
|
+
continue;
|
|
1104
|
+
if (key === "model" && typeof value === "string" && value !== "inherit") {
|
|
1105
|
+
result.configuration.model = value;
|
|
1106
|
+
selectedAgentModel = true;
|
|
1107
|
+
}
|
|
1108
|
+
else if (["tools", "disallowedTools", "permissionMode"].includes(key) && await safe(Buffer.from(canonical(value)), `agent/${key}`))
|
|
1109
|
+
result.configuration.permissions[key] = value;
|
|
1110
|
+
else if (key !== "model")
|
|
1111
|
+
block("agent_setting", "A selected agent setting needs an explicit managed equivalent.", `agent/${key}`);
|
|
1112
|
+
}
|
|
1113
|
+
}
|
|
1114
|
+
}
|
|
1115
|
+
const allowed = nativeToolNames(result.configuration.permissions.tools), denied = nativeToolNames(result.configuration.permissions.disallowedTools) ?? [];
|
|
1116
|
+
const selection = { dialect: "claude", allow: allowed === undefined ? null : [...new Set(allowed.filter(claudeMcpSelector))].sort(), deny: [...new Set(denied.filter(claudeMcpSelector))].sort() };
|
|
1117
|
+
if (!sourceMcpSelection(selection))
|
|
1118
|
+
block("tool_selection", "The native MCP tool selection exceeds its supported bounds.", "configuration/tools");
|
|
1119
|
+
const resources = [];
|
|
1120
|
+
for (const [name, operation] of [["ListMcpResourcesTool", "list"], ["ReadMcpResourceTool", "read"]])
|
|
1121
|
+
if (allowed?.includes(name) && !denied.includes(name))
|
|
1122
|
+
resources.push(operation);
|
|
1123
|
+
for (const tool of result.configuration.tools) {
|
|
1124
|
+
tool.selection = structuredClone(selection);
|
|
1125
|
+
tool.resources = [...resources];
|
|
1126
|
+
}
|
|
1127
|
+
// An explicit builtin-only agent has no use for these MCP connections. Its captured config
|
|
1128
|
+
// remains intact, but no destination account or credential is granted merely because it exists.
|
|
1129
|
+
result.configuration.tools = result.configuration.tools.filter(tool => resources.length > 0 || selectedMcpServer(selection, tool.name));
|
|
1130
|
+
if (target.selector.kind === "profile")
|
|
1131
|
+
block("selector", "Claude profile selectors are not supported by this exporter.");
|
|
1132
|
+
}
|
|
1133
|
+
const environment = options.environment ?? {};
|
|
1134
|
+
if (NATIVE_RUNTIME_FACTS[target.runtime].protocol === "claude-json") {
|
|
1135
|
+
const model = environment.ANTHROPIC_MODEL || (!result.configuration.model ? environment.ANTHROPIC_DEFAULT_MODEL : undefined);
|
|
1136
|
+
if (model) {
|
|
1137
|
+
if (selectedAgentModel && model !== result.configuration.model)
|
|
1138
|
+
block("native_environment", "The selected agent and source environment disagree on the model; resolve the native selection before Move.");
|
|
1139
|
+
else
|
|
1140
|
+
result.configuration.model = model;
|
|
1141
|
+
}
|
|
1142
|
+
if (["ANTHROPIC_BASE_URL", "CLAUDE_CODE_USE_BEDROCK", "CLAUDE_CODE_USE_VERTEX", "CLAUDE_CODE_USE_FOUNDRY", "CLAUDE_CODE_PROVIDER_MANAGED_BY_HOST", "CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS", "CLAUDE_CODE_SUBAGENT_MODEL", "CLAUDE_CODE_ENABLE_TASKS"].some(name => environment[name] && environment[name] !== "0" && environment[name] !== "false"))
|
|
1143
|
+
block("native_environment", "An enabled source provider or tool environment override needs verified destination equivalence.");
|
|
1144
|
+
}
|
|
1145
|
+
else if (environment.OPENAI_BASE_URL)
|
|
1146
|
+
block("native_environment", "The source model endpoint needs verified destination equivalence before Move.");
|
|
1147
|
+
const native = sourceNativeTools({ runtime: target.runtime, version: target.version, model: result.configuration.model,
|
|
1148
|
+
config: runtimeConfiguration, permissions: result.configuration.permissions, mcp: result.configuration.tools.length > 0, modelCache });
|
|
1149
|
+
result.configuration.native_tools = native.tools;
|
|
1150
|
+
for (const reason of native.blockers)
|
|
1151
|
+
block(reason.code, reason.message, reason.path);
|
|
1152
|
+
const skillNames = new Set(), skillSources = new Set(target.configuration.filter(file => basename(file.path) === "SKILL.md").map(file => dirname(file.path)));
|
|
1153
|
+
const skillRoots = NATIVE_RUNTIME_FACTS[target.runtime].protocol === "codex-json"
|
|
1154
|
+
? [join(options.codexHome ?? join(options.home, ".codex"), "skills"), join(options.home, ".agents", "skills"), ...ancestors.flatMap(dir => [join(dir, ".agents", "skills"), join(dir, ".codex", "skills")])]
|
|
1155
|
+
: [join(options.claudeHome ?? join(options.home, ".claude"), "skills"), ...ancestors.map(dir => join(dir, ".claude", "skills"))];
|
|
1156
|
+
for (const directory of new Set(skillRoots)) {
|
|
1157
|
+
const value = await read(directory, "skills");
|
|
1158
|
+
for (const name of value?.names ?? [])
|
|
1159
|
+
if ((await read(join(directory, name, "SKILL.md"), "skills"))?.bytes)
|
|
1160
|
+
skillSources.add(join(directory, name));
|
|
1161
|
+
}
|
|
1162
|
+
for (const source of [...skillSources].sort()) {
|
|
1163
|
+
if (options.secretValues?.some(secret => secret && source.includes(secret))) {
|
|
1164
|
+
block("secret_content", "A skill path contains a held credential and was withheld.");
|
|
1165
|
+
continue;
|
|
1166
|
+
}
|
|
1167
|
+
const name = basename(source), path = `skills/${hash(source).slice(0, 12)}/${name}`;
|
|
1168
|
+
if (skillNames.has(name))
|
|
1169
|
+
block("skill_precedence", "Multiple authored skills have the same name; choose an explicit managed precedence.", `skills/${name}`);
|
|
1170
|
+
skillNames.add(name);
|
|
1171
|
+
result.skills.push({ name, path, source });
|
|
1172
|
+
await tree(source, path, "skill");
|
|
1173
|
+
}
|
|
1174
|
+
for (const name of target.skills)
|
|
1175
|
+
if (!skillNames.has(name))
|
|
1176
|
+
block("skill_missing", "A discovered authored skill is missing from the complete source closure.", `skills/${name}`);
|
|
1177
|
+
for (const name of target.mcp_servers)
|
|
1178
|
+
if (!handledTools.has(name))
|
|
1179
|
+
block("tool_missing", "A discovered tool was not captured by the supported configuration resolver.", `tools/${name}`);
|
|
1180
|
+
// Discovery already reports managed/plugin/rules sources it cannot resolve. Never turn that uncertainty into ready.
|
|
1181
|
+
if (!target.capabilities.learning)
|
|
1182
|
+
block("policy_unresolved", "Discovery could not establish complete source policy; resolve its policy prerequisites before moving.");
|
|
1183
|
+
result.instructions.text = instructionTexts.join("\n\n");
|
|
1184
|
+
if (result.configuration.model !== null && !await safe(Buffer.from(result.configuration.model), "configuration/model"))
|
|
1185
|
+
result.configuration.model = null;
|
|
1186
|
+
if (gitStart && canonical(await gitState()) !== canonical(gitStart))
|
|
1187
|
+
throw new SourceSnapshotError("source_changed", "Git HEAD, index or working-tree inventory changed during export.");
|
|
1188
|
+
reader.check();
|
|
1189
|
+
await reader.verify(JSON.stringify({ ...result, blobs: {} }));
|
|
1190
|
+
result.entries.sort((a, b) => a.path.localeCompare(b.path));
|
|
1191
|
+
result.skills.sort((a, b) => a.path.localeCompare(b.path));
|
|
1192
|
+
result.configuration.tools.sort((a, b) => a.name.localeCompare(b.name));
|
|
1193
|
+
result.transforms.sort((a, b) => a.path.localeCompare(b.path));
|
|
1194
|
+
result.blockers.sort((a, b) => `${a.code}:${a.path ?? ""}`.localeCompare(`${b.code}:${b.path ?? ""}`));
|
|
1195
|
+
const complete = result.blockers.length === 0;
|
|
1196
|
+
return { ...result, complete, digest: sourceSnapshotDigest({ ...result, complete }) };
|
|
1197
|
+
}
|
|
1198
|
+
finally {
|
|
1199
|
+
await reader.closeGit();
|
|
1200
|
+
}
|
|
1201
|
+
}
|