@tangle-network/agent-provider-tangle 3.4.1 → 3.5.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/README.md +17 -1
- package/dist/node.d.ts +2 -0
- package/dist/node.js +1 -0
- package/dist/tangle-environment.js +5 -2
- package/dist/tangle-evidence-json.d.ts +10 -0
- package/dist/tangle-evidence-json.js +82 -0
- package/dist/tangle-evidence-native-files.d.ts +27 -0
- package/dist/tangle-evidence-native-files.js +177 -0
- package/dist/tangle-evidence-writer.d.ts +29 -0
- package/dist/tangle-evidence-writer.js +144 -0
- package/dist/tangle-evidence.d.ts +12 -0
- package/dist/tangle-evidence.js +479 -435
- package/dist/tangle-types.d.ts +7 -0
- package/package.json +7 -1
package/README.md
CHANGED
|
@@ -160,7 +160,8 @@ A deliberate new turn can select another eligible account. The selected referenc
|
|
|
160
160
|
The Provider grants only that named secret through the authenticated Sandbox API before native execution.
|
|
161
161
|
|
|
162
162
|
This handoff requires the SDK's `grantNativeCredential` operation and a container reporting `claudeTokenContinuations: true`.
|
|
163
|
-
Only Claude token references are qualified.
|
|
163
|
+
Only Claude token references are qualified. A Claude bundle or files reference refuses dynamic handoff before inference.
|
|
164
|
+
Codex and Kimi references keep the account the resolver selected at creation on every turn; that admission already covered the run deadline.
|
|
164
165
|
The Sidecar retires the idle adapter, preserves its original transcript HOME and native session, and acquires the newly selected credential.
|
|
165
166
|
An active credential lease refuses replacement.
|
|
166
167
|
Exact event/result replay never selects or installs credentials and leaves the admitted request unchanged.
|
|
@@ -635,6 +636,21 @@ A restored agent environment verifies its actual backend when reconnected.
|
|
|
635
636
|
The capture requirement also reaches checkpoint operations exposed by an environment.
|
|
636
637
|
Fleet capability summaries are diagnostic observations, not placement admission.
|
|
637
638
|
|
|
639
|
+
For large captures, import `captureTangleEnvironmentEvidenceToDirectory` or `captureTangleSandboxEvidenceToDirectory` from `@tangle-network/agent-provider-tangle/node`.
|
|
640
|
+
Pass `destination` alongside the same capture options.
|
|
641
|
+
The destination must not exist; its parent must exist.
|
|
642
|
+
The result contains `directory` and `provenance`; callers own removal after durable persistence.
|
|
643
|
+
Failed captures remove their private destination and native-export staging.
|
|
644
|
+
|
|
645
|
+
Directory capture streams workspace files, native payloads, and event records into private files.
|
|
646
|
+
It requires Sandbox `session.exportRawEvidence()` and its dedicated server archive route.
|
|
647
|
+
It never falls back to the aggregate native JSON response.
|
|
648
|
+
Native metadata is limited to 32 MiB and 100,000 records; an individual event record is limited to 16 MiB.
|
|
649
|
+
Exceeding a bound refuses capture instead of reporting complete evidence.
|
|
650
|
+
Budget disk for the captured tree, archive persistence, and overlapping native export.
|
|
651
|
+
Use Runtime streamed workspace capture and restore to preserve bounded memory through persistence.
|
|
652
|
+
The directory preserves the existing retention manifest, exact payload bytes, modes, attribution, and completeness rules.
|
|
653
|
+
|
|
638
654
|
Call `captureTangleEnvironmentEvidence(environment, options)` before destroying a provider environment.
|
|
639
655
|
For a Runtime-owned box, call `captureTangleSandboxEvidence(box, options)` with exact session and execution IDs.
|
|
640
656
|
Set `workspaceRoot` to a canonical relative worker directory when the box is shared.
|
package/dist/node.d.ts
CHANGED
|
@@ -6,3 +6,5 @@ export { parseModelCredentialResolverRequest } from "./model-credential-request.
|
|
|
6
6
|
export type { ModelCredentialResolverRequest } from "./model-credential-request.js";
|
|
7
7
|
export { TangleCredentialCapacityError } from "./model-credential-capacity.js";
|
|
8
8
|
export type { CredentialCapacityCode, CredentialCapacityReason } from "./model-credential-capacity.js";
|
|
9
|
+
export { captureTangleEnvironmentEvidenceToDirectory, captureTangleSandboxEvidenceToDirectory } from "./tangle-evidence.js";
|
|
10
|
+
export type { TangleDirectoryEvidence } from "./tangle-evidence.js";
|
package/dist/node.js
CHANGED
|
@@ -2,3 +2,4 @@ export { createCommandModelCredentialResolver } from "./command-model-credential
|
|
|
2
2
|
export { createHttpModelCredentialResolver } from "./http-model-credentials.js";
|
|
3
3
|
export { parseModelCredentialResolverRequest } from "./model-credential-request.js";
|
|
4
4
|
export { TangleCredentialCapacityError } from "./model-credential-capacity.js";
|
|
5
|
+
export { captureTangleEnvironmentEvidenceToDirectory, captureTangleSandboxEvidenceToDirectory } from "./tangle-evidence.js";
|
|
@@ -146,9 +146,12 @@ export async function sandboxInstanceAsEnvironment(box, providerName, client, de
|
|
|
146
146
|
let selectedReference = nativeReference;
|
|
147
147
|
// Exact reads retain the admitted execution. A new operation obtains a new durable
|
|
148
148
|
// account-owner binding; retries of that operation present the same key after restart.
|
|
149
|
-
|
|
149
|
+
// Per-turn account selection exists for Claude setup tokens, whose named-grant continuation
|
|
150
|
+
// Sandbox proves. Other harnesses keep the account selected at creation, whose admission
|
|
151
|
+
// already covered the run deadline.
|
|
152
|
+
if (!replay && request?.resolveModelCredentials !== undefined && harness === "claude-code") {
|
|
150
153
|
if (!deployment.claudeTokenContinuations || box.grantNativeCredential === undefined ||
|
|
151
|
-
|
|
154
|
+
nativeReference.format !== "token") {
|
|
152
155
|
throw new Error("Tangle fresh subscription turns require proven Claude token continuation and named-grant support");
|
|
153
156
|
}
|
|
154
157
|
const profile = backend?.profile;
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/** A JSON array backed by a repeatable, bounded source rather than retained objects. */
|
|
2
|
+
export declare class EvidenceJsonArray {
|
|
3
|
+
readonly count: number | undefined;
|
|
4
|
+
readonly entries: () => AsyncIterable<unknown>;
|
|
5
|
+
constructor(count: number | undefined, entries: () => AsyncIterable<unknown>);
|
|
6
|
+
}
|
|
7
|
+
/** JSON.stringify's wire form for plain JSON data, emitted without aggregate arrays. */
|
|
8
|
+
export declare function evidenceJsonChunks(value: unknown): AsyncIterable<Uint8Array>;
|
|
9
|
+
/** Bound syscall and per-token allocation overhead without buffering the whole JSON value. */
|
|
10
|
+
export declare function coalesceEvidenceChunks(chunks: AsyncIterable<Uint8Array>): AsyncIterable<Uint8Array>;
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
/** A JSON array backed by a repeatable, bounded source rather than retained objects. */
|
|
2
|
+
export class EvidenceJsonArray {
|
|
3
|
+
count;
|
|
4
|
+
entries;
|
|
5
|
+
constructor(count, entries) {
|
|
6
|
+
this.count = count;
|
|
7
|
+
this.entries = entries;
|
|
8
|
+
}
|
|
9
|
+
}
|
|
10
|
+
/** JSON.stringify's wire form for plain JSON data, emitted without aggregate arrays. */
|
|
11
|
+
export async function* evidenceJsonChunks(value) {
|
|
12
|
+
const active = new Set();
|
|
13
|
+
async function* visit(item) {
|
|
14
|
+
if (item instanceof EvidenceJsonArray) {
|
|
15
|
+
yield Buffer.from("[");
|
|
16
|
+
let count = 0;
|
|
17
|
+
for await (const entry of item.entries()) {
|
|
18
|
+
if (count++ > 0)
|
|
19
|
+
yield Buffer.from(",");
|
|
20
|
+
yield* visit(entry);
|
|
21
|
+
}
|
|
22
|
+
if (item.count !== undefined && count !== item.count)
|
|
23
|
+
throw new Error("Tangle evidence JSON record count changed");
|
|
24
|
+
yield Buffer.from("]");
|
|
25
|
+
return;
|
|
26
|
+
}
|
|
27
|
+
if (item !== null && typeof item === "object") {
|
|
28
|
+
if (active.has(item))
|
|
29
|
+
throw new Error("Tangle evidence contains cyclic JSON");
|
|
30
|
+
active.add(item);
|
|
31
|
+
try {
|
|
32
|
+
const array = Array.isArray(item);
|
|
33
|
+
yield Buffer.from(array ? "[" : "{");
|
|
34
|
+
let count = 0;
|
|
35
|
+
if (array) {
|
|
36
|
+
for (const entry of item) {
|
|
37
|
+
if (count++ > 0)
|
|
38
|
+
yield Buffer.from(",");
|
|
39
|
+
yield* visit(entry);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
else {
|
|
43
|
+
for (const [key, entry] of Object.entries(item)) {
|
|
44
|
+
if (entry === undefined || typeof entry === "function" || typeof entry === "symbol")
|
|
45
|
+
continue;
|
|
46
|
+
if (count++ > 0)
|
|
47
|
+
yield Buffer.from(",");
|
|
48
|
+
yield Buffer.from(JSON.stringify(key) + ":");
|
|
49
|
+
yield* visit(entry);
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
yield Buffer.from(array ? "]" : "}");
|
|
53
|
+
}
|
|
54
|
+
finally {
|
|
55
|
+
active.delete(item);
|
|
56
|
+
}
|
|
57
|
+
return;
|
|
58
|
+
}
|
|
59
|
+
yield Buffer.from(JSON.stringify(item) ?? "null");
|
|
60
|
+
}
|
|
61
|
+
yield* visit(value);
|
|
62
|
+
}
|
|
63
|
+
/** Bound syscall and per-token allocation overhead without buffering the whole JSON value. */
|
|
64
|
+
export async function* coalesceEvidenceChunks(chunks) {
|
|
65
|
+
const buffer = Buffer.allocUnsafe(64 * 1024);
|
|
66
|
+
let used = 0;
|
|
67
|
+
for await (const chunk of chunks) {
|
|
68
|
+
let offset = 0;
|
|
69
|
+
while (offset < chunk.byteLength) {
|
|
70
|
+
const length = Math.min(buffer.byteLength - used, chunk.byteLength - offset);
|
|
71
|
+
buffer.set(chunk.subarray(offset, offset + length), used);
|
|
72
|
+
used += length;
|
|
73
|
+
offset += length;
|
|
74
|
+
if (used === buffer.byteLength) {
|
|
75
|
+
yield Buffer.from(buffer);
|
|
76
|
+
used = 0;
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
if (used)
|
|
81
|
+
yield Buffer.from(buffer.subarray(0, used));
|
|
82
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import type { SandboxSessionLike, TangleRawEvidenceLike } from "./tangle-types.js";
|
|
2
|
+
type Captured = Exclude<TangleRawEvidenceLike, {
|
|
3
|
+
status: "unavailable";
|
|
4
|
+
}>;
|
|
5
|
+
type WithoutInline<T> = Omit<T, "contentBase64"> & {
|
|
6
|
+
contentBase64?: string;
|
|
7
|
+
};
|
|
8
|
+
export type RetainedNativeEvidence = Exclude<TangleRawEvidenceLike, Captured> | (Omit<Captured, "processIo" | "processSources"> & {
|
|
9
|
+
processIo: Array<WithoutInline<Captured["processIo"][number]>>;
|
|
10
|
+
processSources: Array<WithoutInline<Captured["processSources"][number]>>;
|
|
11
|
+
});
|
|
12
|
+
export interface NativePayloadFile {
|
|
13
|
+
path: string;
|
|
14
|
+
sizeBytes: number;
|
|
15
|
+
sha256: string;
|
|
16
|
+
}
|
|
17
|
+
export interface PreparedNativeEvidence {
|
|
18
|
+
native: RetainedNativeEvidence | undefined;
|
|
19
|
+
payloads: WeakMap<object, NativePayloadFile>;
|
|
20
|
+
directory?: string;
|
|
21
|
+
remove(): Promise<void>;
|
|
22
|
+
}
|
|
23
|
+
/** Exact receipt validation is repeated while consuming, so a later local mutation fails capture. */
|
|
24
|
+
export declare function nativePayloadChunks(directory: string, ref: NativePayloadFile, signal?: AbortSignal): AsyncIterable<Uint8Array>;
|
|
25
|
+
/** The new route must never fall back to the legacy aggregate JSON request. */
|
|
26
|
+
export declare function prepareNativeDirectoryEvidence(session: SandboxSessionLike, maxBytes: number, signal?: AbortSignal): Promise<PreparedNativeEvidence>;
|
|
27
|
+
export {};
|
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { constants } from "node:fs";
|
|
3
|
+
import { mkdtemp, open, rm } from "node:fs/promises";
|
|
4
|
+
import { tmpdir } from "node:os";
|
|
5
|
+
import { join } from "node:path";
|
|
6
|
+
import { EvidenceJsonArray } from "./tangle-evidence-json.js";
|
|
7
|
+
const MAX_ENTRIES = 100_000;
|
|
8
|
+
const MAX_METADATA_BYTES = 32 * 1024 * 1024;
|
|
9
|
+
const MAX_RECORD_BYTES = 16 * 1024 * 1024;
|
|
10
|
+
function record(value) {
|
|
11
|
+
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
12
|
+
throw new Error("Tangle native export metadata is malformed");
|
|
13
|
+
return value;
|
|
14
|
+
}
|
|
15
|
+
function array(value) {
|
|
16
|
+
if (!Array.isArray(value) || value.length > MAX_ENTRIES)
|
|
17
|
+
throw new Error("Tangle native export metadata exceeds its record bound");
|
|
18
|
+
return value;
|
|
19
|
+
}
|
|
20
|
+
function payload(value, maxBytes) {
|
|
21
|
+
const item = record(value);
|
|
22
|
+
if (typeof item.path !== "string" || !item.path || item.path.startsWith("/") || item.path.includes("\\") || item.path.includes("\0") ||
|
|
23
|
+
item.path.split("/").some(part => !part || part === "." || part === "..") ||
|
|
24
|
+
!Number.isSafeInteger(item.sizeBytes) || Number(item.sizeBytes) < 0 || Number(item.sizeBytes) > maxBytes ||
|
|
25
|
+
typeof item.sha256 !== "string" || !/^sha256:[a-f0-9]{64}$/.test(item.sha256)) {
|
|
26
|
+
throw new Error("Tangle native export file reference is invalid");
|
|
27
|
+
}
|
|
28
|
+
return { path: item.path, sizeBytes: Number(item.sizeBytes), sha256: item.sha256 };
|
|
29
|
+
}
|
|
30
|
+
function recordsFile(value, maxBytes) {
|
|
31
|
+
const item = record(value);
|
|
32
|
+
if (item.format !== "ndjson" || !Number.isSafeInteger(item.records) || Number(item.records) < 0 || Number(item.records) > MAX_ENTRIES) {
|
|
33
|
+
throw new Error("Tangle native export record inventory is invalid");
|
|
34
|
+
}
|
|
35
|
+
return { ...payload(item, maxBytes), format: "ndjson", records: Number(item.records) };
|
|
36
|
+
}
|
|
37
|
+
/** Exact receipt validation is repeated while consuming, so a later local mutation fails capture. */
|
|
38
|
+
export async function* nativePayloadChunks(directory, ref, signal) {
|
|
39
|
+
const checked = payload(ref, ref.sizeBytes);
|
|
40
|
+
signal?.throwIfAborted();
|
|
41
|
+
const handle = await open(join(directory, checked.path), constants.O_RDONLY | constants.O_NOFOLLOW);
|
|
42
|
+
const hash = createHash("sha256");
|
|
43
|
+
let size = 0;
|
|
44
|
+
try {
|
|
45
|
+
const before = await handle.stat();
|
|
46
|
+
if (!before.isFile() || before.nlink !== 1 || before.size !== checked.sizeBytes)
|
|
47
|
+
throw new Error("Tangle native export file differs from its receipt");
|
|
48
|
+
for (;;) {
|
|
49
|
+
signal?.throwIfAborted();
|
|
50
|
+
const bytes = Buffer.allocUnsafe(64 * 1024);
|
|
51
|
+
const result = await handle.read(bytes, 0, bytes.length, null);
|
|
52
|
+
if (result.bytesRead === 0)
|
|
53
|
+
break;
|
|
54
|
+
size += result.bytesRead;
|
|
55
|
+
if (size > checked.sizeBytes)
|
|
56
|
+
throw new Error("Tangle native export file grew during capture");
|
|
57
|
+
const chunk = bytes.subarray(0, result.bytesRead);
|
|
58
|
+
hash.update(chunk);
|
|
59
|
+
yield chunk;
|
|
60
|
+
}
|
|
61
|
+
const after = await handle.stat();
|
|
62
|
+
if (size !== checked.sizeBytes || before.mtimeMs !== after.mtimeMs || before.ctimeMs !== after.ctimeMs ||
|
|
63
|
+
`sha256:${hash.digest("hex")}` !== checked.sha256)
|
|
64
|
+
throw new Error("Tangle native export file does not match its digest");
|
|
65
|
+
signal?.throwIfAborted();
|
|
66
|
+
}
|
|
67
|
+
finally {
|
|
68
|
+
await handle.close();
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
async function* nativeRecords(directory, ref, signal) {
|
|
72
|
+
const decoder = new TextDecoder("utf-8", { fatal: true });
|
|
73
|
+
let pending = "";
|
|
74
|
+
let count = 0;
|
|
75
|
+
for await (const chunk of nativePayloadChunks(directory, ref, signal)) {
|
|
76
|
+
pending += decoder.decode(chunk, { stream: true });
|
|
77
|
+
for (;;) {
|
|
78
|
+
const end = pending.indexOf("\n");
|
|
79
|
+
if (end < 0)
|
|
80
|
+
break;
|
|
81
|
+
const line = pending.slice(0, end);
|
|
82
|
+
pending = pending.slice(end + 1);
|
|
83
|
+
if (!line || Buffer.byteLength(line) > MAX_RECORD_BYTES || ++count > ref.records)
|
|
84
|
+
throw new Error("Tangle native export has an invalid record boundary");
|
|
85
|
+
yield JSON.parse(line);
|
|
86
|
+
}
|
|
87
|
+
if (Buffer.byteLength(pending) > MAX_RECORD_BYTES)
|
|
88
|
+
throw new Error("Tangle native export record exceeds its memory bound");
|
|
89
|
+
}
|
|
90
|
+
pending += decoder.decode();
|
|
91
|
+
if (pending || count !== ref.records)
|
|
92
|
+
throw new Error("Tangle native export is truncated or has a different record count");
|
|
93
|
+
}
|
|
94
|
+
/** The new route must never fall back to the legacy aggregate JSON request. */
|
|
95
|
+
export async function prepareNativeDirectoryEvidence(session, maxBytes, signal) {
|
|
96
|
+
if (!session.exportRawEvidence)
|
|
97
|
+
throw new Error("Tangle directory evidence requires bounded native export; aggregate capture is not a fallback");
|
|
98
|
+
const temporary = await mkdtemp(join(tmpdir(), "tangle-native-evidence-"));
|
|
99
|
+
const destination = join(temporary, "export");
|
|
100
|
+
const remove = () => rm(temporary, { recursive: true, force: true });
|
|
101
|
+
try {
|
|
102
|
+
const response = record(await session.exportRawEvidence(destination, { maxBytes, maxFiles: MAX_ENTRIES, signal }));
|
|
103
|
+
if (response.status === "unavailable") {
|
|
104
|
+
return { native: response, payloads: new WeakMap(), remove };
|
|
105
|
+
}
|
|
106
|
+
if ((response.status !== "captured" && response.status !== "partial") || response.directory !== destination ||
|
|
107
|
+
typeof response.manifestPath !== "string" || !response.manifestPath.startsWith(destination + "/") ||
|
|
108
|
+
typeof response.manifestSha256 !== "string" || !/^sha256:[a-f0-9]{64}$/.test(response.manifestSha256)) {
|
|
109
|
+
throw new Error("Tangle native export receipt has invalid identity");
|
|
110
|
+
}
|
|
111
|
+
// Read the authenticated on-disk metadata, not a second, potentially divergent object.
|
|
112
|
+
const manifestPath = response.manifestPath.slice(destination.length + 1);
|
|
113
|
+
payload({ path: manifestPath, sizeBytes: 0, sha256: response.manifestSha256 }, MAX_METADATA_BYTES);
|
|
114
|
+
const metadataHandle = await open(response.manifestPath, constants.O_RDONLY | constants.O_NOFOLLOW);
|
|
115
|
+
let metadataRef;
|
|
116
|
+
try {
|
|
117
|
+
const stat = await metadataHandle.stat();
|
|
118
|
+
if (!stat.isFile() || stat.nlink !== 1 || stat.size > MAX_METADATA_BYTES)
|
|
119
|
+
throw new Error("Tangle native metadata exceeds its memory bound");
|
|
120
|
+
metadataRef = payload({ path: manifestPath, sizeBytes: stat.size, sha256: response.manifestSha256 }, MAX_METADATA_BYTES);
|
|
121
|
+
}
|
|
122
|
+
finally {
|
|
123
|
+
await metadataHandle.close();
|
|
124
|
+
}
|
|
125
|
+
const metadataChunks = [];
|
|
126
|
+
for await (const chunk of nativePayloadChunks(destination, metadataRef, signal))
|
|
127
|
+
metadataChunks.push(chunk);
|
|
128
|
+
const metadataBytes = Buffer.concat(metadataChunks, metadataRef.sizeBytes);
|
|
129
|
+
const manifest = record(JSON.parse(metadataBytes.toString("utf8")));
|
|
130
|
+
if (manifest.schema !== "tangle.raw-evidence-archive.v1" || manifest.status !== response.status || manifest.sessionId !== session.id)
|
|
131
|
+
throw new Error("Tangle native export manifest names another session or protocol");
|
|
132
|
+
const payloads = new WeakMap();
|
|
133
|
+
const prepareContent = (value) => {
|
|
134
|
+
const item = record(value);
|
|
135
|
+
const { content, ...metadata } = item;
|
|
136
|
+
if (content !== undefined) {
|
|
137
|
+
const ref = payload(content, maxBytes);
|
|
138
|
+
if (item.contentBase64 !== undefined || item.sizeBytes !== ref.sizeBytes || item.sha256 !== ref.sha256)
|
|
139
|
+
throw new Error("Tangle native payload receipt differs from its metadata");
|
|
140
|
+
payloads.set(metadata, ref);
|
|
141
|
+
}
|
|
142
|
+
return metadata;
|
|
143
|
+
};
|
|
144
|
+
const files = array(manifest.files).map(prepareContent);
|
|
145
|
+
const processSources = array(manifest.processSources).map(prepareContent);
|
|
146
|
+
let metadataSize = metadataBytes.length;
|
|
147
|
+
const boundMetadata = (item) => {
|
|
148
|
+
metadataSize += Buffer.byteLength(JSON.stringify(item));
|
|
149
|
+
if (metadataSize > MAX_METADATA_BYTES)
|
|
150
|
+
throw new Error("Tangle native metadata exceeds its memory bound");
|
|
151
|
+
};
|
|
152
|
+
const processIo = [];
|
|
153
|
+
for await (const entry of nativeRecords(destination, recordsFile(manifest.processIo, maxBytes), signal)) {
|
|
154
|
+
const item = prepareContent(entry);
|
|
155
|
+
boundMetadata(item);
|
|
156
|
+
processIo.push(item);
|
|
157
|
+
}
|
|
158
|
+
const processTerminals = [];
|
|
159
|
+
for await (const entry of nativeRecords(destination, recordsFile(manifest.processTerminals, maxBytes), signal)) {
|
|
160
|
+
boundMetadata(entry);
|
|
161
|
+
processTerminals.push(entry);
|
|
162
|
+
}
|
|
163
|
+
const events = array(manifest.events).map(value => {
|
|
164
|
+
const entry = record(value);
|
|
165
|
+
const ref = recordsFile(entry.frames, maxBytes);
|
|
166
|
+
return { metadata: entry.metadata, frames: new EvidenceJsonArray(ref.records, () => nativeRecords(destination, ref, signal)) };
|
|
167
|
+
});
|
|
168
|
+
const { schema: _schema, ...legacyMetadata } = manifest;
|
|
169
|
+
// The existing evidence validator checks all identity, attribution and completeness fields.
|
|
170
|
+
const native = { ...legacyMetadata, files, processIo, processTerminals, processSources, events };
|
|
171
|
+
return { native, payloads, directory: destination, remove };
|
|
172
|
+
}
|
|
173
|
+
catch (error) {
|
|
174
|
+
await remove();
|
|
175
|
+
throw error;
|
|
176
|
+
}
|
|
177
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import type { SandboxInstanceLike } from "./tangle-types.js";
|
|
2
|
+
type FileSystem = NonNullable<SandboxInstanceLike["fs"]>;
|
|
3
|
+
type EvidenceFile = {
|
|
4
|
+
path: string;
|
|
5
|
+
bytes: Uint8Array;
|
|
6
|
+
mode: number;
|
|
7
|
+
};
|
|
8
|
+
export interface EvidenceWriter {
|
|
9
|
+
readonly byteLength: number;
|
|
10
|
+
readonly directory?: string;
|
|
11
|
+
write(file: EvidenceFile): Promise<void>;
|
|
12
|
+
writeChunks(path: string, mode: number, chunks: AsyncIterable<Uint8Array>): Promise<number>;
|
|
13
|
+
download?(fs: FileSystem, file: {
|
|
14
|
+
sourcePath: string;
|
|
15
|
+
path: string;
|
|
16
|
+
size: number;
|
|
17
|
+
mode: number;
|
|
18
|
+
}): Promise<void>;
|
|
19
|
+
}
|
|
20
|
+
/** Compatibility collector. Directory capture uses the streaming writer below. */
|
|
21
|
+
export declare function createMemoryEvidenceWriter(maxBytes: number, signal?: AbortSignal): EvidenceWriter & {
|
|
22
|
+
files: EvidenceFile[];
|
|
23
|
+
};
|
|
24
|
+
/** One fresh private tree, streamed writes and hash-verified bounded downloads. */
|
|
25
|
+
export declare function createDirectoryEvidenceWriter(destination: string, maxBytes: number, signal?: AbortSignal): Promise<EvidenceWriter & {
|
|
26
|
+
directory: string;
|
|
27
|
+
remove(): Promise<void>;
|
|
28
|
+
}>;
|
|
29
|
+
export {};
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { constants } from "node:fs";
|
|
3
|
+
import { chmod, mkdir, open, realpath, rm } from "node:fs/promises";
|
|
4
|
+
import { dirname, join, resolve } from "node:path";
|
|
5
|
+
import { coalesceEvidenceChunks } from "./tangle-evidence-json.js";
|
|
6
|
+
function limits(maxBytes) {
|
|
7
|
+
if (!Number.isSafeInteger(maxBytes) || maxBytes < 1)
|
|
8
|
+
throw new Error("Tangle evidence maxBytes must be positive");
|
|
9
|
+
}
|
|
10
|
+
function filePath(path, mode) {
|
|
11
|
+
if (!path || path.startsWith("/") || path.includes("\\") || path.includes("\0") ||
|
|
12
|
+
path.split("/").some(part => !part || part === "." || part === "..") ||
|
|
13
|
+
!Number.isSafeInteger(mode) || mode < 0 || mode > 0o777) {
|
|
14
|
+
throw new Error("Tangle evidence output has an unsafe path or mode");
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
async function* one(bytes) { yield bytes; }
|
|
18
|
+
/** Compatibility collector. Directory capture uses the streaming writer below. */
|
|
19
|
+
export function createMemoryEvidenceWriter(maxBytes, signal) {
|
|
20
|
+
limits(maxBytes);
|
|
21
|
+
let total = 0;
|
|
22
|
+
const files = [];
|
|
23
|
+
const seen = new Set();
|
|
24
|
+
const writer = {
|
|
25
|
+
files,
|
|
26
|
+
get byteLength() { return total; },
|
|
27
|
+
async write(file) { await writer.writeChunks(file.path, file.mode, one(file.bytes)); },
|
|
28
|
+
async writeChunks(path, mode, chunks) {
|
|
29
|
+
filePath(path, mode);
|
|
30
|
+
if (seen.has(path))
|
|
31
|
+
throw new Error("Tangle evidence repeats an output path");
|
|
32
|
+
seen.add(path);
|
|
33
|
+
const retained = [];
|
|
34
|
+
let size = 0;
|
|
35
|
+
for await (const bytes of coalesceEvidenceChunks(chunks)) {
|
|
36
|
+
signal?.throwIfAborted();
|
|
37
|
+
if (bytes.byteLength > maxBytes - total - size)
|
|
38
|
+
throw new Error("Tangle evidence exceeds byte limit");
|
|
39
|
+
retained.push(Buffer.from(bytes));
|
|
40
|
+
size += bytes.byteLength;
|
|
41
|
+
}
|
|
42
|
+
signal?.throwIfAborted();
|
|
43
|
+
files.push({ path, mode, bytes: Buffer.concat(retained, size) });
|
|
44
|
+
total += size;
|
|
45
|
+
return size;
|
|
46
|
+
},
|
|
47
|
+
};
|
|
48
|
+
return writer;
|
|
49
|
+
}
|
|
50
|
+
/** One fresh private tree, streamed writes and hash-verified bounded downloads. */
|
|
51
|
+
export async function createDirectoryEvidenceWriter(destination, maxBytes, signal) {
|
|
52
|
+
limits(maxBytes);
|
|
53
|
+
signal?.throwIfAborted();
|
|
54
|
+
if (!destination)
|
|
55
|
+
throw new Error("Tangle evidence destination is required");
|
|
56
|
+
const requested = resolve(destination);
|
|
57
|
+
await mkdir(requested, { mode: 0o700 });
|
|
58
|
+
const directory = await realpath(requested);
|
|
59
|
+
let total = 0;
|
|
60
|
+
const seen = new Set();
|
|
61
|
+
const prepare = async (path, mode) => {
|
|
62
|
+
signal?.throwIfAborted();
|
|
63
|
+
filePath(path, mode);
|
|
64
|
+
if (seen.has(path))
|
|
65
|
+
throw new Error("Tangle evidence repeats an output path");
|
|
66
|
+
seen.add(path);
|
|
67
|
+
const target = join(directory, path);
|
|
68
|
+
await mkdir(dirname(target), { recursive: true, mode: 0o700 });
|
|
69
|
+
return target;
|
|
70
|
+
};
|
|
71
|
+
const writer = {
|
|
72
|
+
directory,
|
|
73
|
+
get byteLength() { return total; },
|
|
74
|
+
async remove() { await rm(directory, { recursive: true, force: true }); },
|
|
75
|
+
async write(file) { await writer.writeChunks(file.path, file.mode, one(file.bytes)); },
|
|
76
|
+
async writeChunks(path, mode, chunks) {
|
|
77
|
+
const target = await prepare(path, mode);
|
|
78
|
+
const output = await open(target, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, mode);
|
|
79
|
+
let size = 0;
|
|
80
|
+
try {
|
|
81
|
+
for await (const bytes of coalesceEvidenceChunks(chunks)) {
|
|
82
|
+
signal?.throwIfAborted();
|
|
83
|
+
if (bytes.byteLength > maxBytes - total - size)
|
|
84
|
+
throw new Error("Tangle evidence exceeds byte limit");
|
|
85
|
+
let offset = 0;
|
|
86
|
+
while (offset < bytes.byteLength) {
|
|
87
|
+
const result = await output.write(bytes, offset, bytes.byteLength - offset);
|
|
88
|
+
if (result.bytesWritten === 0)
|
|
89
|
+
throw new Error("Tangle evidence output made no progress");
|
|
90
|
+
offset += result.bytesWritten;
|
|
91
|
+
}
|
|
92
|
+
size += bytes.byteLength;
|
|
93
|
+
}
|
|
94
|
+
signal?.throwIfAborted();
|
|
95
|
+
await output.chmod(mode);
|
|
96
|
+
await output.sync();
|
|
97
|
+
}
|
|
98
|
+
finally {
|
|
99
|
+
await output.close();
|
|
100
|
+
}
|
|
101
|
+
total += size;
|
|
102
|
+
return size;
|
|
103
|
+
},
|
|
104
|
+
async download(fs, file) {
|
|
105
|
+
if (fs.supportsBoundedDownload !== true || !fs.download)
|
|
106
|
+
throw new Error("Tangle evidence requires bounded binary download");
|
|
107
|
+
if (!Number.isSafeInteger(file.size) || file.size < 0 || file.size > maxBytes - total)
|
|
108
|
+
throw new Error("Tangle evidence exceeds byte limit");
|
|
109
|
+
const target = await prepare(file.path, file.mode);
|
|
110
|
+
const receipt = await fs.download(file.sourcePath, target, { maxBytes: maxBytes - total, expectedSize: file.size, signal });
|
|
111
|
+
signal?.throwIfAborted();
|
|
112
|
+
if (!receipt || receipt.sizeBytes !== file.size || !/^[a-f0-9]{64}$/i.test(receipt.sha256))
|
|
113
|
+
throw new Error("Tangle evidence binary download omitted its exact size or digest receipt");
|
|
114
|
+
const descriptor = await open(target, constants.O_RDONLY | constants.O_NOFOLLOW);
|
|
115
|
+
const hash = createHash("sha256");
|
|
116
|
+
let size = 0;
|
|
117
|
+
try {
|
|
118
|
+
const stat = await descriptor.stat();
|
|
119
|
+
if (!stat.isFile() || stat.nlink !== 1 || stat.size !== file.size)
|
|
120
|
+
throw new Error("Tangle evidence downloaded file differs from its receipt");
|
|
121
|
+
const buffer = Buffer.allocUnsafe(256 * 1024);
|
|
122
|
+
for (;;) {
|
|
123
|
+
signal?.throwIfAborted();
|
|
124
|
+
const { bytesRead } = await descriptor.read(buffer, 0, buffer.length, null);
|
|
125
|
+
if (bytesRead === 0)
|
|
126
|
+
break;
|
|
127
|
+
size += bytesRead;
|
|
128
|
+
if (size > file.size)
|
|
129
|
+
throw new Error("Tangle evidence downloaded file grew during verification");
|
|
130
|
+
hash.update(buffer.subarray(0, bytesRead));
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
finally {
|
|
134
|
+
await descriptor.close();
|
|
135
|
+
}
|
|
136
|
+
if (size !== file.size || hash.digest("hex") !== receipt.sha256.toLowerCase())
|
|
137
|
+
throw new Error("Tangle evidence downloaded file does not match its digest");
|
|
138
|
+
signal?.throwIfAborted();
|
|
139
|
+
await chmod(target, file.mode);
|
|
140
|
+
total += size;
|
|
141
|
+
},
|
|
142
|
+
};
|
|
143
|
+
return writer;
|
|
144
|
+
}
|
|
@@ -172,6 +172,18 @@ export declare function bindTangleEvidenceEnvironment(environment: AgentEnvironm
|
|
|
172
172
|
export declare function noteTangleSession(environment: AgentEnvironment, sessionId: string, executionId?: string): void;
|
|
173
173
|
/** Export an environment through its retained Sandbox handle. */
|
|
174
174
|
export declare function captureTangleEnvironmentEvidence(environment: AgentEnvironment, options: TangleEnvironmentEvidenceOptions): Promise<TangleEnvironmentEvidence>;
|
|
175
|
+
export interface TangleDirectoryEvidence {
|
|
176
|
+
directory: string;
|
|
177
|
+
provenance: TangleEnvironmentEvidence["provenance"];
|
|
178
|
+
}
|
|
179
|
+
/** Capture to a new private directory without accumulating workspace content in memory. */
|
|
180
|
+
export declare function captureTangleEnvironmentEvidenceToDirectory(environment: AgentEnvironment, options: TangleEnvironmentEvidenceOptions & {
|
|
181
|
+
destination: string;
|
|
182
|
+
}): Promise<TangleDirectoryEvidence>;
|
|
183
|
+
/** The caller owns a successful directory; incomplete captures are removed. */
|
|
184
|
+
export declare function captureTangleSandboxEvidenceToDirectory(box: SandboxInstanceLike, options: TangleSandboxEvidenceOptions & {
|
|
185
|
+
destination: string;
|
|
186
|
+
}): Promise<TangleDirectoryEvidence>;
|
|
175
187
|
/** Export exact Sandbox session and workspace evidence before its owning box is deleted. */
|
|
176
188
|
export declare function captureTangleSandboxEvidence(box: SandboxInstanceLike, options: TangleSandboxEvidenceOptions): Promise<TangleEnvironmentEvidence>;
|
|
177
189
|
export {};
|