@tangle-network/agent-provider-tangle 3.1.3 → 3.2.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 CHANGED
@@ -40,6 +40,16 @@ Runtime resolves child source files through this reader without copying their co
40
40
  Paths keep the control-plane limit.
41
41
  Live reads require the selected Sandbox workspace capability.
42
42
 
43
+ Evidence capture batches workspace reads into requests of at most 100 files and 8 MiB of declared file bytes.
44
+ A file larger than that batch target gets its own request.
45
+ Responses must account for every requested path exactly once; missing, duplicate, or unrelated paths fail capture.
46
+ Cancellation stops further batches after the current request returns.
47
+ Evidence capture retains full workspace files that exceed the Sandbox JSON read limit through bounded binary downloads.
48
+ This requires a Sandbox SDK whose filesystem advertises `supportsBoundedDownload`.
49
+ Capture verifies the downloaded size and SHA-256 receipt before adding bytes to the archive.
50
+ Aggregate limits, credential exclusions, and exact native-session proof remain enforced.
51
+ An unsupported downloader or incomplete transfer fails capture and preserves the source environment.
52
+
43
53
  ## Named model credentials at creation
44
54
 
45
55
  `modelCredentials` sends a stored credential reference and explicit endpoint before Sandbox provisions the backend.
@@ -168,6 +178,34 @@ The adapter requires this idempotency key before starting the command.
168
178
  Only a successfully decoded public reference can reach Sandbox creation.
169
179
  Timeouts, cancellation, nonzero exit, and malformed or oversized output refuse creation with sanitized errors.
170
180
 
181
+ ### A remote account owner
182
+
183
+ The Node subpath also provides `createHttpModelCredentialResolver`.
184
+ Use a narrow resolve-only grant and the owner's maintained HTTPS endpoint.
185
+ HTTP is accepted only on loopback for local forwarding.
186
+ The client never follows redirects or sends private account-owner credentials.
187
+
188
+ ```ts
189
+ import { createHttpModelCredentialResolver } from "@tangle-network/agent-provider-tangle/node";
190
+
191
+ const modelCredentials = createHttpModelCredentialResolver({
192
+ url: process.env.ACCOUNT_RESOLVER_URL!,
193
+ bearer: process.env.ACCOUNT_RESOLVER_GRANT!,
194
+ minimumValidUntil: persistedRunDeadline,
195
+ });
196
+ const provider = createTangleProvider({ client, modelCredentials });
197
+ ```
198
+
199
+ Managed profiles skip the remote call.
200
+ Subscription roots and descendants send the same exact `{ input, minimumValidUntil? }` contract as the command transport.
201
+ The owner must bind the grant to a pool and fixed Sandbox namespace before accepting a request.
202
+ A caller-supplied namespace is never sufficient authorization.
203
+ The response contains only the selected stored reference.
204
+ Errors, redirects, invalid references, cancellation, and bounded response time refuse provisioning.
205
+ The client makes one request; recovery may retry the same immutable dispatch identity through the account owner's durable binding.
206
+ `parseModelCredentialResolverRequest` validates this public wire envelope without normalizing the authored profile.
207
+ Requests are bounded at 64 MiB and responses at 64 KiB.
208
+
171
209
  The account owner retains authority over registration, namespace verification, holds, quota, selection, and trusted renewal.
172
210
  Updating a stored secret does not refresh credentials already injected into a live Sandbox.
173
211
  Creation-time validity and the selected host's native credential lifecycle still bound long-running work.
@@ -618,3 +656,12 @@ Capture validates those coordinates before reading files.
618
656
  A reconstructed environment does not need the original in-memory session cache.
619
657
  The returned provenance retains both identities and reports incomplete native coverage explicitly.
620
658
  Missing native session evidence preserves the source under Runtime's complete-provenance policy.
659
+
660
+ The remote request is bounded to 8 MiB; public replies are bounded to 64 KiB.
661
+ A genuine HTTP 429 or 503 may return `{ error: { code, reason, resetAt? } }`.
662
+ Supported codes are `provider_quota_exhausted` for exhausted quota and `upstream_unavailable` for unknown, held, or busy capacity.
663
+ The adapter exposes these as `TangleCredentialCapacityError`, preserving the actual HTTP status and known reset timestamp.
664
+ Authentication failures and malformed metadata do not become typed quota refusals.
665
+ The command transport accepts the same public capacity body only with exit code 75.
666
+ Its typed error has no HTTP status.
667
+ The caller's execution owner decides whether and when to retry.
@@ -1,3 +1,4 @@
1
+ import { parseCredentialCapacity } from "./model-credential-capacity.js";
1
2
  import { spawn } from "node:child_process";
2
3
  import { profileCredentialSource } from "./model-credential-source.js";
3
4
  import { captureModelCredentials } from "./tangle-create-options.js";
@@ -95,6 +96,17 @@ export function createCommandModelCredentialResolver(options) {
95
96
  if (settled)
96
97
  return;
97
98
  if (code !== 0) {
99
+ if (code === 75) {
100
+ let capacity;
101
+ try {
102
+ capacity = parseCredentialCapacity(JSON.parse(Buffer.concat(chunks).toString("utf8")));
103
+ }
104
+ catch { /* Malformed command output stays a sanitized generic refusal. */ }
105
+ if (capacity !== undefined) {
106
+ fail(capacity);
107
+ return;
108
+ }
109
+ }
98
110
  fail(Object.assign(new Error(`Tangle credential command failed (${code === null ? `signal ${terminationSignal}` : `exit ${code}`})`), {
99
111
  exitCode: code,
100
112
  terminationSignal,
@@ -0,0 +1,12 @@
1
+ import type { TangleModelCredentialResolver } from "./tangle-types.js";
2
+ export interface HttpModelCredentialResolverOptions {
3
+ /** HTTPS broker endpoint, or HTTP on loopback for private local transport. */
4
+ url: string;
5
+ /** Narrow resolve-only grant. Never use a Bridge launch bearer here. */
6
+ bearer: string;
7
+ timeoutMs?: number;
8
+ minimumValidUntil?: string;
9
+ minimumValidityMs?: number;
10
+ }
11
+ /** Send exact profile intent to the trusted account owner, without exporting owner credentials. */
12
+ export declare function createHttpModelCredentialResolver(options: HttpModelCredentialResolverOptions): TangleModelCredentialResolver;
@@ -0,0 +1,138 @@
1
+ import { parseCredentialCapacity } from "./model-credential-capacity.js";
2
+ import { profileCredentialSource } from "./model-credential-source.js";
3
+ import { parseModelCredentialResolverRequest } from "./model-credential-request.js";
4
+ import { captureModelCredentials } from "./tangle-create-options.js";
5
+ const MAX_PUBLIC_RESPONSE_BYTES = 64 * 1024;
6
+ const MAX_REQUEST_BYTES = 8 * 1024 * 1024;
7
+ const LOOPBACK = new Set(["localhost", "127.0.0.1", "[::1]"]);
8
+ async function publicResponse(response) {
9
+ if (!response.body)
10
+ throw new Error("Tangle credential broker returned an empty public response");
11
+ const reader = response.body.getReader();
12
+ const chunks = [];
13
+ let bytes = 0;
14
+ try {
15
+ for (;;) {
16
+ const { done, value } = await reader.read();
17
+ if (done)
18
+ break;
19
+ bytes += value.byteLength;
20
+ if (bytes > MAX_PUBLIC_RESPONSE_BYTES) {
21
+ await reader.cancel();
22
+ throw new Error("Tangle credential broker exceeded its public-output bound");
23
+ }
24
+ chunks.push(value);
25
+ }
26
+ try {
27
+ return JSON.parse(Buffer.concat(chunks).toString("utf8"));
28
+ }
29
+ catch {
30
+ throw new Error("Tangle credential broker returned an invalid public reference");
31
+ }
32
+ }
33
+ finally {
34
+ reader.releaseLock();
35
+ }
36
+ }
37
+ /** Send exact profile intent to the trusted account owner, without exporting owner credentials. */
38
+ export function createHttpModelCredentialResolver(options) {
39
+ let endpoint;
40
+ try {
41
+ endpoint = new URL(options.url);
42
+ }
43
+ catch {
44
+ throw new Error("Tangle credential broker URL is invalid");
45
+ }
46
+ if (typeof options.url !== "string" || options.url.length > 2048 || /\s/.test(options.url) ||
47
+ endpoint.username || endpoint.password || endpoint.search || endpoint.hash ||
48
+ (endpoint.protocol !== "https:" && !(endpoint.protocol === "http:" && LOOPBACK.has(endpoint.hostname)))) {
49
+ throw new Error("Tangle credential broker requires HTTPS or loopback HTTP without URL credentials");
50
+ }
51
+ if (typeof options.bearer !== "string" || options.bearer.length < 32 || options.bearer.length > 4096 || /\s/.test(options.bearer)) {
52
+ throw new Error("Tangle credential broker requires a bounded narrow bearer grant");
53
+ }
54
+ const bearer = options.bearer;
55
+ const url = endpoint.href;
56
+ const timeoutMs = options.timeoutMs ?? 30_000;
57
+ if (!Number.isSafeInteger(timeoutMs) || timeoutMs <= 0 || timeoutMs > 2_147_483_647) {
58
+ throw new Error("Tangle credential broker timeoutMs must be a positive timer bound");
59
+ }
60
+ if (options.minimumValidUntil !== undefined && options.minimumValidityMs !== undefined) {
61
+ throw new Error("Tangle credential broker accepts one validity deadline");
62
+ }
63
+ if (options.minimumValidityMs !== undefined && (!Number.isSafeInteger(options.minimumValidityMs) || options.minimumValidityMs <= 0)) {
64
+ throw new Error("Tangle credential broker minimumValidityMs must be a positive integer");
65
+ }
66
+ const deadline = options.minimumValidUntil === undefined
67
+ ? options.minimumValidityMs === undefined ? undefined : new Date(Date.now() + options.minimumValidityMs)
68
+ : typeof options.minimumValidUntil === "string" && options.minimumValidUntil.length <= 128
69
+ ? new Date(options.minimumValidUntil) : new Date(NaN);
70
+ if (deadline !== undefined && !Number.isFinite(deadline.getTime())) {
71
+ throw new Error("Tangle credential broker validity deadline must be a valid timestamp");
72
+ }
73
+ const minimumValidUntil = deadline?.toISOString();
74
+ return async (input) => {
75
+ if (typeof input.profile === "string")
76
+ throw new Error("Tangle credential broker requires an inline profile");
77
+ if (profileCredentialSource(input.profile) === "managed")
78
+ return undefined;
79
+ input.signal?.throwIfAborted();
80
+ const { signal, ...data } = input;
81
+ const request = parseModelCredentialResolverRequest({ input: data, ...(minimumValidUntil === undefined ? {} : { minimumValidUntil }) });
82
+ const body = JSON.stringify(request);
83
+ if (Buffer.byteLength(body) > MAX_REQUEST_BYTES)
84
+ throw new Error("Tangle credential broker request exceeds the profile limit");
85
+ const controller = new AbortController();
86
+ const onAbort = () => controller.abort();
87
+ signal?.addEventListener("abort", onAbort, { once: true });
88
+ if (signal?.aborted)
89
+ controller.abort();
90
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
91
+ try {
92
+ let response;
93
+ try {
94
+ response = await fetch(url, {
95
+ method: "POST", headers: { Authorization: `Bearer ${bearer}`, "Content-Type": "application/json" },
96
+ body, redirect: "error", credentials: "omit", signal: controller.signal,
97
+ });
98
+ }
99
+ catch {
100
+ throw new Error(controller.signal.aborted ? "Tangle credential broker request aborted or timed out" : "Tangle credential broker request failed");
101
+ }
102
+ if (!response.ok) {
103
+ let exitCode;
104
+ let capacity;
105
+ try {
106
+ const payload = await publicResponse(response);
107
+ capacity = parseCredentialCapacity(payload, response.status);
108
+ const detail = payload && typeof payload === "object" && "error" in payload ? payload.error : undefined;
109
+ if (detail && typeof detail === "object" && "exitCode" in detail &&
110
+ typeof detail.exitCode === "number" && Number.isSafeInteger(detail.exitCode) && detail.exitCode >= 0 && detail.exitCode <= 255) {
111
+ exitCode = detail.exitCode;
112
+ }
113
+ }
114
+ catch {
115
+ // Upstream bodies and diagnostics are private; only a bounded numeric exit status is public.
116
+ }
117
+ if (capacity !== undefined)
118
+ throw capacity;
119
+ throw Object.assign(new Error(`Tangle credential broker refused resolution (HTTP ${response.status}${exitCode === undefined ? "" : `, owner exit ${exitCode}`})`), {
120
+ status: response.status, ...(exitCode === undefined ? {} : { exitCode }),
121
+ });
122
+ }
123
+ try {
124
+ const selected = captureModelCredentials(await publicResponse(response));
125
+ if (selected === undefined)
126
+ throw new Error();
127
+ return selected;
128
+ }
129
+ catch {
130
+ throw new Error("Tangle credential broker returned an invalid public reference");
131
+ }
132
+ }
133
+ finally {
134
+ clearTimeout(timer);
135
+ signal?.removeEventListener("abort", onAbort);
136
+ }
137
+ };
138
+ }
@@ -0,0 +1,12 @@
1
+ export type CredentialCapacityCode = "provider_quota_exhausted" | "upstream_unavailable";
2
+ export type CredentialCapacityReason = "exhausted" | "unknown" | "held" | "busy";
3
+ /** The account owner could not admit a fresh dispatch. HTTP status exists only for an HTTP response. */
4
+ export declare class TangleCredentialCapacityError extends Error {
5
+ readonly code: CredentialCapacityCode;
6
+ readonly reason: CredentialCapacityReason;
7
+ readonly resetAt?: string;
8
+ readonly status?: number;
9
+ constructor(code: CredentialCapacityCode, reason: CredentialCapacityReason, resetAt?: string, httpStatus?: number);
10
+ }
11
+ /** Only fixed public fields survive parsing; upstream messages and private diagnostics do not. */
12
+ export declare function parseCredentialCapacity(value: unknown, httpStatus?: number): TangleCredentialCapacityError | undefined;
@@ -0,0 +1,45 @@
1
+ /** The account owner could not admit a fresh dispatch. HTTP status exists only for an HTTP response. */
2
+ export class TangleCredentialCapacityError extends Error {
3
+ code;
4
+ reason;
5
+ resetAt;
6
+ constructor(code, reason, resetAt, httpStatus) {
7
+ super("Subscription account capacity is unavailable");
8
+ this.name = "TangleCredentialCapacityError";
9
+ this.code = code;
10
+ this.reason = reason;
11
+ if (resetAt !== undefined)
12
+ this.resetAt = resetAt;
13
+ if (httpStatus !== undefined) {
14
+ if (httpStatus !== 429 && httpStatus !== 503)
15
+ throw new Error("Credential capacity requires a real capacity response");
16
+ Object.defineProperty(this, "status", { value: httpStatus, enumerable: true });
17
+ }
18
+ }
19
+ }
20
+ function record(value) {
21
+ return value !== null && typeof value === "object" && !Array.isArray(value)
22
+ ? value : undefined;
23
+ }
24
+ /** Only fixed public fields survive parsing; upstream messages and private diagnostics do not. */
25
+ export function parseCredentialCapacity(value, httpStatus) {
26
+ if (httpStatus !== undefined && httpStatus !== 429 && httpStatus !== 503)
27
+ return undefined;
28
+ const envelope = record(value);
29
+ if (!envelope || Object.keys(envelope).some((key) => key !== "error"))
30
+ return undefined;
31
+ const error = record(envelope.error);
32
+ if (!error || Object.keys(error).some((key) => !["code", "reason", "resetAt"].includes(key)))
33
+ return undefined;
34
+ const { code, reason, resetAt } = error;
35
+ if (code !== "provider_quota_exhausted" && code !== "upstream_unavailable")
36
+ return undefined;
37
+ if (reason !== "exhausted" && reason !== "unknown" && reason !== "held" && reason !== "busy")
38
+ return undefined;
39
+ if ((code === "provider_quota_exhausted") !== (reason === "exhausted"))
40
+ return undefined;
41
+ if (resetAt !== undefined && (typeof resetAt !== "string" || resetAt.length !== 24 ||
42
+ !Number.isFinite(Date.parse(resetAt)) || new Date(resetAt).toISOString() !== resetAt))
43
+ return undefined;
44
+ return new TangleCredentialCapacityError(code, reason, resetAt, httpStatus);
45
+ }
@@ -0,0 +1,7 @@
1
+ import type { CreateAgentEnvironmentInput } from "@tangle-network/agent-interface/environment-provider";
2
+ export interface ModelCredentialResolverRequest {
3
+ input: Readonly<CreateAgentEnvironmentInput>;
4
+ minimumValidUntil?: string;
5
+ }
6
+ /** Validate the public wire envelope while retaining the exact authored create input. */
7
+ export declare function parseModelCredentialResolverRequest(value: unknown): ModelCredentialResolverRequest;
@@ -0,0 +1,35 @@
1
+ import { agentProfileSchema } from "@tangle-network/agent-interface";
2
+ import { profileCredentialSource } from "./model-credential-source.js";
3
+ import { assertBoundedJson } from "./tangle-contract-safety.js";
4
+ /** Validate the public wire envelope while retaining the exact authored create input. */
5
+ export function parseModelCredentialResolverRequest(value) {
6
+ if (!value || typeof value !== "object" || Array.isArray(value) ||
7
+ Object.keys(value).some((key) => key !== "input" && key !== "minimumValidUntil")) {
8
+ throw new Error("Tangle credential request must contain an input and optional validity deadline");
9
+ }
10
+ const request = value;
11
+ const input = request.input;
12
+ if (!input || typeof input !== "object" || Array.isArray(input)) {
13
+ throw new Error("Tangle credential request input must be an object");
14
+ }
15
+ const data = input;
16
+ const { profile, ...createFields } = data;
17
+ assertBoundedJson(createFields, "Tangle credential request input");
18
+ assertBoundedJson(profile, "Tangle credential request profile", []);
19
+ if ("signal" in data || typeof data.idempotencyKey !== "string" ||
20
+ data.idempotencyKey.length === 0 || data.idempotencyKey.length > 512) {
21
+ throw new Error("Tangle credential request requires a stable create identity without a serialized signal");
22
+ }
23
+ if (!agentProfileSchema.safeParse(data.profile).success || typeof data.profile === "string") {
24
+ throw new Error("Tangle credential request requires an inline AgentProfile");
25
+ }
26
+ // The wire carries JSON. Schema parsing validates it, but must not normalize the caller's profile.
27
+ const acceptedInput = input;
28
+ profileCredentialSource(acceptedInput.profile);
29
+ const deadline = request.minimumValidUntil;
30
+ if (deadline !== undefined && (typeof deadline !== "string" || deadline.length > 128 ||
31
+ !Number.isFinite(new Date(deadline).getTime()))) {
32
+ throw new Error("Tangle credential request validity deadline must be a valid timestamp");
33
+ }
34
+ return { input: acceptedInput, ...(deadline === undefined ? {} : { minimumValidUntil: deadline }) };
35
+ }
package/dist/node.d.ts CHANGED
@@ -1,2 +1,8 @@
1
1
  export { createCommandModelCredentialResolver } from "./command-model-credentials.js";
2
2
  export type { CommandModelCredentialResolverOptions } from "./command-model-credentials.js";
3
+ export { createHttpModelCredentialResolver } from "./http-model-credentials.js";
4
+ export type { HttpModelCredentialResolverOptions } from "./http-model-credentials.js";
5
+ export { parseModelCredentialResolverRequest } from "./model-credential-request.js";
6
+ export type { ModelCredentialResolverRequest } from "./model-credential-request.js";
7
+ export { TangleCredentialCapacityError } from "./model-credential-capacity.js";
8
+ export type { CredentialCapacityCode, CredentialCapacityReason } from "./model-credential-capacity.js";
package/dist/node.js CHANGED
@@ -1 +1,4 @@
1
1
  export { createCommandModelCredentialResolver } from "./command-model-credentials.js";
2
+ export { createHttpModelCredentialResolver } from "./http-model-credentials.js";
3
+ export { parseModelCredentialResolverRequest } from "./model-credential-request.js";
4
+ export { TangleCredentialCapacityError } from "./model-credential-capacity.js";
@@ -5,6 +5,9 @@ const handles = new WeakMap();
5
5
  const blockedNames = new Set([".ssh", ".config", ".claude", ".codex", ".opencode", ".env", ".env.local", ".npmrc", ".sidecar"]);
6
6
  const MAX_ENTRIES = 100_000;
7
7
  const MAX_EVENTS = 100_000;
8
+ // Match the Sidecar request limit without accumulating 100 large JSON payloads.
9
+ const WORKSPACE_BATCH_FILES = 100;
10
+ const WORKSPACE_BATCH_BYTES = 8 * 1024 * 1024;
8
11
  export function bindTangleEvidenceEnvironment(environment, box) {
9
12
  handles.set(environment, { box, sessions: new Map() });
10
13
  }
@@ -101,6 +104,19 @@ export async function captureTangleSandboxEvidence(box, options) {
101
104
  let scannedEntries = 0;
102
105
  let scannedSize = 0;
103
106
  let capturedBytes = 0;
107
+ let pending = [];
108
+ let pendingBytes = 0;
109
+ const flushWorkspaceFiles = async () => {
110
+ if (!pending.length)
111
+ return;
112
+ const captured = await readWorkspaceEvidenceBatch(fs, pending, options.maxBytes - capturedBytes, options.signal);
113
+ for (const file of captured) {
114
+ files.push(file);
115
+ capturedBytes += file.bytes.byteLength;
116
+ }
117
+ pending = [];
118
+ pendingBytes = 0;
119
+ };
104
120
  while (stack.length) {
105
121
  options.signal?.throwIfAborted();
106
122
  const directory = stack.pop();
@@ -149,25 +165,19 @@ export async function captureTangleSandboxEvidence(box, options) {
149
165
  excludedPaths.push({ ...item, reason: "credential-path" });
150
166
  continue;
151
167
  }
152
- const result = await fs.readBatch([sourcePath], { encoding: "base64" });
153
- if (result.errors.length || result.files.length !== 1 || result.files[0]?.path !== sourcePath || result.files[0]?.encoding !== "base64") {
154
- throw new Error(`Tangle evidence could not read workspace file ${path}`);
155
- }
156
- const read = result.files[0];
157
- const bytes = Buffer.from(read.content, "base64");
158
- if (bytes.byteLength !== entry.size || read.size !== entry.size || bytes.toString("base64") !== read.content) {
159
- throw new Error(`Tangle evidence workspace file changed or was truncated: ${path}`);
160
- }
161
- if (read.hash && read.hash.replace(/^sha256:/, "") !== createHash("sha256").update(bytes).digest("hex")) {
162
- throw new Error(`Tangle evidence workspace file hash mismatch: ${path}`);
168
+ if (pending.length && (pending.length >= WORKSPACE_BATCH_FILES || pendingBytes + entry.size > WORKSPACE_BATCH_BYTES)) {
169
+ await flushWorkspaceFiles();
163
170
  }
164
- files.push({ path, bytes, mode: entry.permissions & 0o777 });
165
- capturedBytes += bytes.byteLength;
171
+ if (entry.size > options.maxBytes - capturedBytes - pendingBytes)
172
+ throw new Error("Tangle evidence exceeds byte limit");
173
+ pending.push({ sourcePath, path, size: entry.size, mode: entry.permissions & 0o777 });
174
+ pendingBytes += entry.size;
166
175
  }
167
176
  }
168
177
  if (scannedFiles !== usage.fileCount || scannedDirectories !== usage.directoryCount || scannedSize !== usage.sizeBytes) {
169
178
  throw new Error("Tangle workspace inventory does not match the complete usage scan");
170
179
  }
180
+ await flushWorkspaceFiles();
171
181
  const sessionIds = new Set(options.sandboxSessionIds);
172
182
  const sessions = [];
173
183
  const attempts = [];
@@ -664,6 +674,89 @@ export async function captureTangleSandboxEvidence(box, options) {
664
674
  files.push({ path: "__retention__/provenance.json", bytes: provenanceBytes, mode: 0o600 });
665
675
  return { files: files.sort((a, b) => a.path.localeCompare(b.path)), provenance };
666
676
  }
677
+ /** Match every response to exactly one request before accepting any file bytes. */
678
+ async function readWorkspaceEvidenceBatch(fs, entries, maxBytes, signal) {
679
+ signal?.throwIfAborted();
680
+ const result = await fs.readBatch(entries.map((entry) => entry.sourcePath), { encoding: "base64" });
681
+ signal?.throwIfAborted();
682
+ if (!result || !Array.isArray(result.files) || !Array.isArray(result.errors)) {
683
+ throw new Error("Tangle evidence workspace batch response is malformed");
684
+ }
685
+ const expected = new Set(entries.map((entry) => entry.sourcePath));
686
+ const returned = new Set();
687
+ for (const item of [...result.files, ...result.errors]) {
688
+ if (!expected.has(item.path) || returned.has(item.path)) {
689
+ throw new Error("Tangle evidence workspace batch contains an unexpected or repeated path");
690
+ }
691
+ returned.add(item.path);
692
+ }
693
+ if (returned.size !== expected.size)
694
+ throw new Error("Tangle evidence workspace batch omitted a requested path");
695
+ const reads = new Map(result.files.map((read) => [read.path, read]));
696
+ const errors = new Map(result.errors.map((error) => [error.path, error]));
697
+ const files = [];
698
+ let remainingBytes = maxBytes;
699
+ for (const entry of entries) {
700
+ signal?.throwIfAborted();
701
+ const read = reads.get(entry.sourcePath);
702
+ const error = errors.get(entry.sourcePath);
703
+ let bytes;
704
+ if (error?.code === "FILE_TOO_LARGE") {
705
+ bytes = await downloadWorkspaceEvidenceFile(fs, entry.sourcePath, entry.size, remainingBytes, signal);
706
+ }
707
+ else {
708
+ if (error || !read || read.encoding !== "base64") {
709
+ throw new Error(`Tangle evidence could not read workspace file ${entry.path}`);
710
+ }
711
+ bytes = Buffer.from(read.content, "base64");
712
+ if (bytes.byteLength !== entry.size || read.size !== entry.size || bytes.toString("base64") !== read.content) {
713
+ throw new Error(`Tangle evidence workspace file changed or was truncated: ${entry.path}`);
714
+ }
715
+ if (read.hash && read.hash.replace(/^sha256:/, "") !== createHash("sha256").update(bytes).digest("hex")) {
716
+ throw new Error(`Tangle evidence workspace file hash mismatch: ${entry.path}`);
717
+ }
718
+ }
719
+ if (bytes.byteLength > remainingBytes)
720
+ throw new Error("Tangle evidence exceeds byte limit");
721
+ files.push({ path: entry.path, bytes, mode: entry.mode });
722
+ remainingBytes -= bytes.byteLength;
723
+ }
724
+ return files;
725
+ }
726
+ /** The JSON reader has a smaller transport cap than an evidence archive. */
727
+ async function downloadWorkspaceEvidenceFile(fs, sourcePath, expectedSize, maxBytes, signal) {
728
+ if (fs.supportsBoundedDownload !== true || !fs.download) {
729
+ throw new Error(`Tangle evidence requires bounded binary download for workspace file ${sourcePath}`);
730
+ }
731
+ const local = await import("node:fs/promises");
732
+ const { tmpdir } = await import("node:os");
733
+ const { join } = await import("node:path");
734
+ signal?.throwIfAborted();
735
+ const directory = await local.mkdtemp(join(tmpdir(), "tangle-evidence-"));
736
+ try {
737
+ const target = join(directory, "content");
738
+ const receipt = await fs.download(sourcePath, target, { maxBytes, expectedSize, signal });
739
+ signal?.throwIfAborted();
740
+ if (!receipt || receipt.sizeBytes !== expectedSize || !/^[a-f0-9]{64}$/i.test(receipt.sha256)) {
741
+ throw new Error("Tangle evidence binary download omitted its exact size or digest receipt");
742
+ }
743
+ const metadata = await local.stat(target);
744
+ if (!metadata.isFile() || metadata.size !== expectedSize || metadata.size > maxBytes) {
745
+ throw new Error(`Tangle evidence workspace file changed or was truncated: ${sourcePath}`);
746
+ }
747
+ const bytes = await local.readFile(target, { signal });
748
+ if (bytes.byteLength !== expectedSize || bytes.byteLength > maxBytes) {
749
+ throw new Error(`Tangle evidence workspace file changed or was truncated: ${sourcePath}`);
750
+ }
751
+ if (createHash("sha256").update(bytes).digest("hex") !== receipt.sha256.toLowerCase()) {
752
+ throw new Error(`Tangle evidence workspace file hash mismatch: ${sourcePath}`);
753
+ }
754
+ return bytes;
755
+ }
756
+ finally {
757
+ await local.rm(directory, { recursive: true, force: true });
758
+ }
759
+ }
667
760
  /** Keep every source field; store validated binary content once in the archive. */
668
761
  function withoutNativeContent(source) {
669
762
  const metadata = { ...source };
@@ -435,6 +435,16 @@ export interface SandboxInstanceLike {
435
435
  exec?(command: string, options?: unknown): Promise<SandboxExecResult>;
436
436
  fs?: {
437
437
  supportsWriteMode?: true;
438
+ supportsBoundedDownload?: true;
439
+ download?(remotePath: string, localPath: string, options?: {
440
+ overwrite?: boolean;
441
+ maxBytes?: number;
442
+ expectedSize?: number;
443
+ signal?: AbortSignal;
444
+ }): Promise<void | {
445
+ sizeBytes: number;
446
+ sha256: string;
447
+ }>;
438
448
  stat(path: string): Promise<{
439
449
  size: number;
440
450
  isFile: boolean;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tangle-network/agent-provider-tangle",
3
- "version": "3.1.3",
3
+ "version": "3.2.0",
4
4
  "description": "AgentEnvironmentProvider adapter for Tangle sandboxes",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -111,7 +111,13 @@
111
111
  "dist/command-model-credentials.js",
112
112
  "dist/command-model-credentials.d.ts",
113
113
  "dist/model-credential-source.js",
114
- "dist/model-credential-source.d.ts"
114
+ "dist/model-credential-source.d.ts",
115
+ "dist/http-model-credentials.js",
116
+ "dist/http-model-credentials.d.ts",
117
+ "dist/model-credential-request.js",
118
+ "dist/model-credential-request.d.ts",
119
+ "dist/model-credential-capacity.js",
120
+ "dist/model-credential-capacity.d.ts"
115
121
  ],
116
122
  "dependencies": {
117
123
  "@tangle-network/agent-interface": "^2.15.0"