@tangle-network/agent-provider-tangle 3.1.4 → 3.3.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 +61 -9
- package/dist/command-model-credentials.js +12 -0
- package/dist/http-model-credentials.d.ts +12 -0
- package/dist/http-model-credentials.js +138 -0
- package/dist/model-credential-capacity.d.ts +12 -0
- package/dist/model-credential-capacity.js +45 -0
- package/dist/model-credential-request.d.ts +7 -0
- package/dist/model-credential-request.js +35 -0
- package/dist/node.d.ts +6 -0
- package/dist/node.js +3 -0
- package/dist/tangle-deployment-capabilities.d.ts +1 -0
- package/dist/tangle-deployment-capabilities.js +3 -0
- package/dist/tangle-environment-session.d.ts +1 -1
- package/dist/tangle-environment-session.js +2 -1
- package/dist/tangle-environment.d.ts +2 -1
- package/dist/tangle-environment.js +45 -6
- package/dist/tangle-evidence.js +72 -23
- package/dist/tangle-provider.js +2 -0
- package/dist/tangle-types.d.ts +12 -1
- package/package.json +9 -3
package/README.md
CHANGED
|
@@ -40,6 +40,10 @@ 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.
|
|
43
47
|
Evidence capture retains full workspace files that exceed the Sandbox JSON read limit through bounded binary downloads.
|
|
44
48
|
This requires a Sandbox SDK whose filesystem advertises `supportsBoundedDownload`.
|
|
45
49
|
Capture verifies the downloaded size and SHA-256 receipt before adding bytes to the archive.
|
|
@@ -51,7 +55,7 @@ An unsupported downloader or incomplete transfer fails capture and preserves the
|
|
|
51
55
|
`modelCredentials` sends a stored credential reference and explicit endpoint before Sandbox provisions the backend.
|
|
52
56
|
This uses Sandbox's existing caller-owned model credential path instead of requesting a managed Router credential.
|
|
53
57
|
The provider does not create, copy, or renew stored secrets.
|
|
54
|
-
The Provider grants the selected reference
|
|
58
|
+
The Provider grants the selected reference at create, alongside unrelated caller-requested secrets. Qualified native selectors also grant their selected reference before each fresh turn.
|
|
55
59
|
|
|
56
60
|
```ts
|
|
57
61
|
const provider = createTangleProvider({
|
|
@@ -90,7 +94,7 @@ Explicit `"managed"` intent also skips configured static API references.
|
|
|
90
94
|
Unmarked legacy profiles retain their existing static API configuration; mark mixed profiles explicitly or use a selector.
|
|
91
95
|
The same Provider can create a managed parent and subscription child, or a subscription parent and managed child.
|
|
92
96
|
A subscription profile requires a configured reference or successful selector result before Sandbox creation.
|
|
93
|
-
The selector receives a frozen copy of the exact create input, including its profile and idempotency key.
|
|
97
|
+
The selector receives a frozen copy of the exact create input, including its profile and idempotency key. Fresh-turn calls carry the exact profile, stable binding key, and public `metadata.nativeCredentialTurn` coordinates.
|
|
94
98
|
It returns one public native reference or the API reference described above.
|
|
95
99
|
It cannot change the profile, harness, model, reasoning controls, or runtime attachments.
|
|
96
100
|
|
|
@@ -139,14 +143,25 @@ Sandbox metadata records the public selection under `modelCredentials`.
|
|
|
139
143
|
This metadata key is reserved for the Provider selection.
|
|
140
144
|
Account labels are supplied bindings, not verified native principals.
|
|
141
145
|
Token values and native credential files never enter that selection or receipt.
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
146
|
+
A static native reference stays bound to its creation account and harness on every turn.
|
|
147
|
+
Reconstructed environments recover that reference from persisted metadata and the observed backend.
|
|
148
|
+
|
|
149
|
+
A resolver selects a bootstrap credential at creation and a durable binding for each fresh turn.
|
|
150
|
+
Fresh turns require the exact inline subscription profile and a stable `turnId`.
|
|
151
|
+
Runtime supplies that profile through its maintained provider turn mapping; older Runtime callers can supply it through `taskToTurn`.
|
|
152
|
+
The binding key includes environment, session, and turn identity, so retrying the same operation retains its account after reconnect.
|
|
153
|
+
A deliberate new turn can select another eligible account. The selected reference enters the admitted request digest before dispatch.
|
|
154
|
+
The Provider grants only that named secret through the authenticated Sandbox API before native execution.
|
|
155
|
+
|
|
156
|
+
This handoff requires the SDK's `grantNativeCredential` operation and a container reporting `claudeTokenContinuations: true`.
|
|
157
|
+
Only Claude token references are qualified. Other harnesses, bundles, and files refuse dynamic handoff before inference.
|
|
158
|
+
The Sidecar retires the idle adapter, preserves its original transcript HOME and native session, and acquires the newly selected credential.
|
|
159
|
+
An active credential lease refuses replacement.
|
|
160
|
+
Exact event/result replay never selects or installs credentials and leaves the admitted request unchanged.
|
|
161
|
+
After a runtime restart, the next fresh turn grants its selected named reference before adapter acquisition.
|
|
162
|
+
The account owner must keep retry bindings and the original validity deadline durable; an unavailable grant never authorizes a paid fallback.
|
|
148
163
|
A turn carrying a profile must preserve its environment's credential source, including after recovery.
|
|
149
|
-
Changing credential sources requires a separate environment
|
|
164
|
+
Changing credential sources or harnesses requires a separate environment.
|
|
150
165
|
|
|
151
166
|
### A command owned by the account system
|
|
152
167
|
|
|
@@ -174,6 +189,34 @@ The adapter requires this idempotency key before starting the command.
|
|
|
174
189
|
Only a successfully decoded public reference can reach Sandbox creation.
|
|
175
190
|
Timeouts, cancellation, nonzero exit, and malformed or oversized output refuse creation with sanitized errors.
|
|
176
191
|
|
|
192
|
+
### A remote account owner
|
|
193
|
+
|
|
194
|
+
The Node subpath also provides `createHttpModelCredentialResolver`.
|
|
195
|
+
Use a narrow resolve-only grant and the owner's maintained HTTPS endpoint.
|
|
196
|
+
HTTP is accepted only on loopback for local forwarding.
|
|
197
|
+
The client never follows redirects or sends private account-owner credentials.
|
|
198
|
+
|
|
199
|
+
```ts
|
|
200
|
+
import { createHttpModelCredentialResolver } from "@tangle-network/agent-provider-tangle/node";
|
|
201
|
+
|
|
202
|
+
const modelCredentials = createHttpModelCredentialResolver({
|
|
203
|
+
url: process.env.ACCOUNT_RESOLVER_URL!,
|
|
204
|
+
bearer: process.env.ACCOUNT_RESOLVER_GRANT!,
|
|
205
|
+
minimumValidUntil: persistedRunDeadline,
|
|
206
|
+
});
|
|
207
|
+
const provider = createTangleProvider({ client, modelCredentials });
|
|
208
|
+
```
|
|
209
|
+
|
|
210
|
+
Managed profiles skip the remote call.
|
|
211
|
+
Subscription roots and descendants send the same exact `{ input, minimumValidUntil? }` contract as the command transport.
|
|
212
|
+
The owner must bind the grant to a pool and fixed Sandbox namespace before accepting a request.
|
|
213
|
+
A caller-supplied namespace is never sufficient authorization.
|
|
214
|
+
The response contains only the selected stored reference.
|
|
215
|
+
Errors, redirects, invalid references, cancellation, and bounded response time refuse provisioning.
|
|
216
|
+
The client makes one request; recovery may retry the same immutable dispatch identity through the account owner's durable binding.
|
|
217
|
+
`parseModelCredentialResolverRequest` validates this public wire envelope without normalizing the authored profile.
|
|
218
|
+
Requests are bounded at 64 MiB and responses at 64 KiB.
|
|
219
|
+
|
|
177
220
|
The account owner retains authority over registration, namespace verification, holds, quota, selection, and trusted renewal.
|
|
178
221
|
Updating a stored secret does not refresh credentials already injected into a live Sandbox.
|
|
179
222
|
Creation-time validity and the selected host's native credential lifecycle still bound long-running work.
|
|
@@ -624,3 +667,12 @@ Capture validates those coordinates before reading files.
|
|
|
624
667
|
A reconstructed environment does not need the original in-memory session cache.
|
|
625
668
|
The returned provenance retains both identities and reports incomplete native coverage explicitly.
|
|
626
669
|
Missing native session evidence preserves the source under Runtime's complete-provenance policy.
|
|
670
|
+
|
|
671
|
+
The remote request is bounded to 8 MiB; public replies are bounded to 64 KiB.
|
|
672
|
+
A genuine HTTP 429 or 503 may return `{ error: { code, reason, resetAt? } }`.
|
|
673
|
+
Supported codes are `provider_quota_exhausted` for exhausted quota and `upstream_unavailable` for unknown, held, or busy capacity.
|
|
674
|
+
The adapter exposes these as `TangleCredentialCapacityError`, preserving the actual HTTP status and known reset timestamp.
|
|
675
|
+
Authentication failures and malformed metadata do not become typed quota refusals.
|
|
676
|
+
The command transport accepts the same public capacity body only with exit code 75.
|
|
677
|
+
Its typed error has no HTTP status.
|
|
678
|
+
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";
|
|
@@ -11,6 +11,7 @@ import type { SandboxInstanceLike, SandboxRuntimeCapabilityDocument } from "./ta
|
|
|
11
11
|
export interface DeploymentCapabilitySupport {
|
|
12
12
|
/** The selected runtime explicitly supports named native credential references. */
|
|
13
13
|
readonly cliAuthReferences: boolean;
|
|
14
|
+
readonly claudeTokenContinuations: boolean;
|
|
14
15
|
/**
|
|
15
16
|
* Run requests carry the caller's exact `runControlRef`, and admission
|
|
16
17
|
* echoes the executionId. Detached dispatch needs both: it sends the
|
|
@@ -10,6 +10,7 @@ import { awaitWithSignal } from "./tangle-contract-safety.js";
|
|
|
10
10
|
*/
|
|
11
11
|
export const UNPROVEN_DEPLOYMENT = {
|
|
12
12
|
cliAuthReferences: false,
|
|
13
|
+
claudeTokenContinuations: false,
|
|
13
14
|
exactDispatch: false,
|
|
14
15
|
canonicalCancellation: false,
|
|
15
16
|
eventReplay: false,
|
|
@@ -34,6 +35,7 @@ export const UNPROVEN_DEPLOYMENT = {
|
|
|
34
35
|
*/
|
|
35
36
|
export const ADAPTER_CEILING_DEPLOYMENT = {
|
|
36
37
|
cliAuthReferences: true,
|
|
38
|
+
claudeTokenContinuations: true,
|
|
37
39
|
exactDispatch: true,
|
|
38
40
|
canonicalCancellation: true,
|
|
39
41
|
eventReplay: true,
|
|
@@ -50,6 +52,7 @@ export function deploymentCapabilitySupport(document) {
|
|
|
50
52
|
return UNPROVEN_DEPLOYMENT;
|
|
51
53
|
return {
|
|
52
54
|
cliAuthReferences: document.cliAuthReferences === true,
|
|
55
|
+
claudeTokenContinuations: document.claudeTokenContinuations === true,
|
|
53
56
|
exactDispatch: document.dispatch?.runControlRef === true &&
|
|
54
57
|
document.dispatch?.executionIdOnAdmission === true,
|
|
55
58
|
canonicalCancellation: document.cancel?.canonicalRunCancellation === true &&
|
|
@@ -23,5 +23,5 @@ type ExactExecutionEventStream = (options: {
|
|
|
23
23
|
* environment observation reads it, because Sandbox reports usage per
|
|
24
24
|
* execution result and never for the environment.
|
|
25
25
|
*/
|
|
26
|
-
export declare function sandboxSessionAsAgentSession(session: SandboxSessionLike, controlRef: AgentRunControlRef | undefined, provider: string, environmentId: string, dispatch: ((input: AgentTurnInput) => Promise<AgentSessionRef>) | undefined, exactExecutionEvents: ExactExecutionEventStream | undefined, retainedControl: boolean, interactionResponses: boolean, usageLog?: ExecutionUsageLog, nativeContinuation?: boolean, beforePrompt?: (input: AgentTurnInput) => AgentTurnInput | void
|
|
26
|
+
export declare function sandboxSessionAsAgentSession(session: SandboxSessionLike, controlRef: AgentRunControlRef | undefined, provider: string, environmentId: string, dispatch: ((input: AgentTurnInput) => Promise<AgentSessionRef>) | undefined, exactExecutionEvents: ExactExecutionEventStream | undefined, retainedControl: boolean, interactionResponses: boolean, usageLog?: ExecutionUsageLog, nativeContinuation?: boolean, beforePrompt?: (input: AgentTurnInput) => AgentTurnInput | void | Promise<AgentTurnInput | void>, onExecution?: (executionId: string) => void): AgentSession;
|
|
27
27
|
export {};
|
|
@@ -317,7 +317,6 @@ export function sandboxSessionAsAgentSession(session, controlRef, provider, envi
|
|
|
317
317
|
}));
|
|
318
318
|
},
|
|
319
319
|
async prompt(input) {
|
|
320
|
-
input = beforePrompt?.(input) ?? input;
|
|
321
320
|
AgentTurnInputSchema.parse(input);
|
|
322
321
|
input.signal?.throwIfAborted();
|
|
323
322
|
if (promptInFlight) {
|
|
@@ -328,6 +327,8 @@ export function sandboxSessionAsAgentSession(session, controlRef, provider, envi
|
|
|
328
327
|
if (input.sessionId !== undefined && input.sessionId !== session.id) {
|
|
329
328
|
throw new Error("Tangle sessionId conflicts with this session");
|
|
330
329
|
}
|
|
330
|
+
input = await beforePrompt?.({ ...input, sessionId: session.id }) ?? input;
|
|
331
|
+
input.signal?.throwIfAborted();
|
|
331
332
|
const requestedControlRef = resolveRetainedSessionControlRef(input.controlRef, session.id, provider, environmentId);
|
|
332
333
|
if (activeControlRef &&
|
|
333
334
|
requestedControlRef &&
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { type CliAuthReference } from "@tangle-network/sandbox/auth";
|
|
2
2
|
import type { AgentEnvironment, AgentEnvironmentCapabilities, ResourceProfile } from "@tangle-network/agent-interface/environment-provider";
|
|
3
|
-
import type { SandboxClientLike, SandboxInstanceLike, SandboxRuntimeCapabilityDocument } from "./tangle-types.js";
|
|
3
|
+
import type { SandboxClientLike, SandboxInstanceLike, SandboxRuntimeCapabilityDocument, TangleModelCredentialResolver } from "./tangle-types.js";
|
|
4
4
|
import { type ProfileCredentialSource } from "./model-credential-source.js";
|
|
5
5
|
import type { TangleConfidentialAttestationVerifier } from "./tangle-types.js";
|
|
6
6
|
/**
|
|
@@ -39,6 +39,7 @@ export declare function sandboxInstanceAsEnvironment(box: SandboxInstanceLike, p
|
|
|
39
39
|
harness: string;
|
|
40
40
|
cliAuth: CliAuthReference;
|
|
41
41
|
};
|
|
42
|
+
resolveModelCredentials?: TangleModelCredentialResolver;
|
|
42
43
|
captureCapabilities?: SandboxRuntimeCapabilityDocument;
|
|
43
44
|
captureHarness?: string;
|
|
44
45
|
}): Promise<AgentEnvironment>;
|
|
@@ -121,7 +121,9 @@ export async function sandboxInstanceAsEnvironment(box, providerName, client, de
|
|
|
121
121
|
}
|
|
122
122
|
assertNativeCaptureHarness(request.captureCapabilities, backend?.type ?? profileHarness ?? request.captureHarness);
|
|
123
123
|
};
|
|
124
|
-
const prepareTurn = (input) => {
|
|
124
|
+
const prepareTurn = async (input) => {
|
|
125
|
+
AgentTurnInputSchema.parse(input);
|
|
126
|
+
input.signal?.throwIfAborted();
|
|
125
127
|
assertCaptureInput(input);
|
|
126
128
|
if (nativeReference === undefined)
|
|
127
129
|
return input;
|
|
@@ -140,7 +142,44 @@ export async function sandboxInstanceAsEnvironment(box, providerName, client, de
|
|
|
140
142
|
canonicalCandidateDigest(model.cliAuth) !== canonicalCandidateDigest(nativeReference)) {
|
|
141
143
|
throw new Error("Tangle native credential turn cannot replace its selected account reference");
|
|
142
144
|
}
|
|
143
|
-
|
|
145
|
+
assertCliAuthReferenceSupported(harness, { ...model, cliAuth: nativeReference });
|
|
146
|
+
let selectedReference = nativeReference;
|
|
147
|
+
// Exact reads retain the admitted execution. A new operation obtains a new durable
|
|
148
|
+
// account-owner binding; retries of that operation present the same key after restart.
|
|
149
|
+
if (!replay && request?.resolveModelCredentials !== undefined) {
|
|
150
|
+
if (!deployment.claudeTokenContinuations || box.grantNativeCredential === undefined ||
|
|
151
|
+
harness !== "claude-code" || nativeReference.format !== "token") {
|
|
152
|
+
throw new Error("Tangle fresh subscription turns require proven Claude token continuation and named-grant support");
|
|
153
|
+
}
|
|
154
|
+
const profile = backend?.profile;
|
|
155
|
+
if (profile === undefined || profileCredentialSource(profile) !== "subscription") {
|
|
156
|
+
throw new Error("Tangle subscription turn selection requires its exact inline profile");
|
|
157
|
+
}
|
|
158
|
+
const turnId = boundedIdentifier(input.turnId, "Tangle subscription turn id");
|
|
159
|
+
const binding = {
|
|
160
|
+
kind: "native-turn-credentials.v1",
|
|
161
|
+
environmentId,
|
|
162
|
+
sessionId: input.sessionId ?? null,
|
|
163
|
+
turnId,
|
|
164
|
+
};
|
|
165
|
+
const selected = captureModelCredentials(await awaitWithSignal(Promise.resolve(request.resolveModelCredentials(Object.freeze({
|
|
166
|
+
...deepFreeze({
|
|
167
|
+
profile,
|
|
168
|
+
idempotencyKey: canonicalCandidateDigest(binding),
|
|
169
|
+
metadata: { nativeCredentialTurn: binding },
|
|
170
|
+
}),
|
|
171
|
+
...(input.signal ? { signal: input.signal } : {}),
|
|
172
|
+
}))), input.signal));
|
|
173
|
+
if (selected === undefined || !("cliAuth" in selected) || selected.cliAuth.format !== "token") {
|
|
174
|
+
throw new Error("Tangle subscription turn resolver must select a stored Claude token reference");
|
|
175
|
+
}
|
|
176
|
+
selectedReference = selected.cliAuth;
|
|
177
|
+
assertCliAuthReferenceSupported(harness, { ...model, cliAuth: selectedReference });
|
|
178
|
+
input.signal?.throwIfAborted();
|
|
179
|
+
await awaitWithSignal(box.grantNativeCredential({ harness, cliAuth: selectedReference }, input.signal ? { signal: input.signal } : undefined), input.signal);
|
|
180
|
+
input.signal?.throwIfAborted();
|
|
181
|
+
}
|
|
182
|
+
const selectedModel = { ...model, cliAuth: selectedReference };
|
|
144
183
|
assertCliAuthReferenceSupported(harness, selectedModel);
|
|
145
184
|
// Validate explicit substitutions even on replay, without rewriting its admitted digest.
|
|
146
185
|
if (replay)
|
|
@@ -165,8 +204,8 @@ export async function sandboxInstanceAsEnvironment(box, providerName, client, de
|
|
|
165
204
|
const dispatchRun = capabilities.streaming.detach && box.dispatchPrompt
|
|
166
205
|
? dispatchEnvironmentRun(box, providerName, environmentId)
|
|
167
206
|
: undefined;
|
|
168
|
-
const dispatch = dispatchRun === undefined ? undefined : (input) => {
|
|
169
|
-
return dispatchRun(prepareTurn(input));
|
|
207
|
+
const dispatch = dispatchRun === undefined ? undefined : async (input) => {
|
|
208
|
+
return dispatchRun(await prepareTurn(input));
|
|
170
209
|
};
|
|
171
210
|
const exactExecutionEvents = (options) => box.streamPrompt("", {
|
|
172
211
|
sessionId: options.sessionId,
|
|
@@ -196,7 +235,7 @@ export async function sandboxInstanceAsEnvironment(box, providerName, client, de
|
|
|
196
235
|
async *stream(input) {
|
|
197
236
|
AgentTurnInputSchema.parse(input);
|
|
198
237
|
input.signal?.throwIfAborted();
|
|
199
|
-
input = prepareTurn(input);
|
|
238
|
+
input = await prepareTurn(input);
|
|
200
239
|
const expectedExecutionId = executionIdFromTurnInput(input);
|
|
201
240
|
const expectedSessionId = input.sessionId ?? input.controlRef?.sessionId;
|
|
202
241
|
if (expectedSessionId)
|
|
@@ -269,7 +308,7 @@ export async function sandboxInstanceAsEnvironment(box, providerName, client, de
|
|
|
269
308
|
if (session.id !== id) {
|
|
270
309
|
throw new Error("sandbox session(id) returned an unrelated session");
|
|
271
310
|
}
|
|
272
|
-
const agentSession = sandboxSessionAsAgentSession(session, options?.controlRef, providerName, environmentId,
|
|
311
|
+
const agentSession = sandboxSessionAsAgentSession(session, options?.controlRef, providerName, environmentId, dispatchRun, exactExecutionEvents, retainedControl, interactionResponses, usageLog, capabilities.nativeContinuation !== undefined, prepareTurn, (executionId) => noteTangleSession(environment, id, executionId));
|
|
273
312
|
// sessions.continue was granted from the probe session and the
|
|
274
313
|
// deployment document together; this backstop holds every
|
|
275
314
|
// concrete session to that grant, so a client whose sessions
|
package/dist/tangle-evidence.js
CHANGED
|
@@ -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,35 +165,19 @@ export async function captureTangleSandboxEvidence(box, options) {
|
|
|
149
165
|
excludedPaths.push({ ...item, reason: "credential-path" });
|
|
150
166
|
continue;
|
|
151
167
|
}
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
throw new Error("Tangle evidence exceeds byte limit");
|
|
155
|
-
const result = await fs.readBatch([sourcePath], { encoding: "base64" });
|
|
156
|
-
let bytes;
|
|
157
|
-
if (result.files.length === 0 && result.errors.length === 1 &&
|
|
158
|
-
result.errors[0]?.path === sourcePath && result.errors[0]?.code === "FILE_TOO_LARGE") {
|
|
159
|
-
bytes = await downloadWorkspaceEvidenceFile(fs, sourcePath, entry.size, remainingBytes, options.signal);
|
|
160
|
-
}
|
|
161
|
-
else {
|
|
162
|
-
if (result.errors.length || result.files.length !== 1 || result.files[0]?.path !== sourcePath || result.files[0]?.encoding !== "base64") {
|
|
163
|
-
throw new Error(`Tangle evidence could not read workspace file ${path}`);
|
|
164
|
-
}
|
|
165
|
-
const read = result.files[0];
|
|
166
|
-
bytes = Buffer.from(read.content, "base64");
|
|
167
|
-
if (bytes.byteLength !== entry.size || read.size !== entry.size || bytes.toString("base64") !== read.content) {
|
|
168
|
-
throw new Error(`Tangle evidence workspace file changed or was truncated: ${path}`);
|
|
169
|
-
}
|
|
170
|
-
if (read.hash && read.hash.replace(/^sha256:/, "") !== createHash("sha256").update(bytes).digest("hex")) {
|
|
171
|
-
throw new Error(`Tangle evidence workspace file hash mismatch: ${path}`);
|
|
172
|
-
}
|
|
168
|
+
if (pending.length && (pending.length >= WORKSPACE_BATCH_FILES || pendingBytes + entry.size > WORKSPACE_BATCH_BYTES)) {
|
|
169
|
+
await flushWorkspaceFiles();
|
|
173
170
|
}
|
|
174
|
-
|
|
175
|
-
|
|
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;
|
|
176
175
|
}
|
|
177
176
|
}
|
|
178
177
|
if (scannedFiles !== usage.fileCount || scannedDirectories !== usage.directoryCount || scannedSize !== usage.sizeBytes) {
|
|
179
178
|
throw new Error("Tangle workspace inventory does not match the complete usage scan");
|
|
180
179
|
}
|
|
180
|
+
await flushWorkspaceFiles();
|
|
181
181
|
const sessionIds = new Set(options.sandboxSessionIds);
|
|
182
182
|
const sessions = [];
|
|
183
183
|
const attempts = [];
|
|
@@ -674,6 +674,55 @@ export async function captureTangleSandboxEvidence(box, options) {
|
|
|
674
674
|
files.push({ path: "__retention__/provenance.json", bytes: provenanceBytes, mode: 0o600 });
|
|
675
675
|
return { files: files.sort((a, b) => a.path.localeCompare(b.path)), provenance };
|
|
676
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
|
+
}
|
|
677
726
|
/** The JSON reader has a smaller transport cap than an evidence archive. */
|
|
678
727
|
async function downloadWorkspaceEvidenceFile(fs, sourcePath, expectedSize, maxBytes, signal) {
|
|
679
728
|
if (fs.supportsBoundedDownload !== true || !fs.download) {
|
package/dist/tangle-provider.js
CHANGED
|
@@ -208,6 +208,7 @@ export function createTangleProvider(options) {
|
|
|
208
208
|
? {}
|
|
209
209
|
: { resources: requestedResources }),
|
|
210
210
|
credentialSource,
|
|
211
|
+
...(resolveModelCredentials === undefined ? {} : { resolveModelCredentials }),
|
|
211
212
|
...(createOptions.backend?.model?.cliAuth === undefined ? {} : {
|
|
212
213
|
nativeAuth: { harness: createOptions.backend.type, cliAuth: createOptions.backend.model.cliAuth },
|
|
213
214
|
}),
|
|
@@ -319,6 +320,7 @@ export function createTangleProvider(options) {
|
|
|
319
320
|
const declaredCapabilities = await resolveDeclaredCapabilities(backendType);
|
|
320
321
|
return await sandboxInstanceAsEnvironment(box, providerName, options.client, declaredCapabilities, operation?.signal ? { signal: operation.signal } : undefined, {
|
|
321
322
|
...confidentialVerifierOption(options.confidentialAttestationVerifier),
|
|
323
|
+
...(resolveModelCredentials === undefined ? {} : { resolveModelCredentials }),
|
|
322
324
|
...(options.requireNativeSessionCapture ? { requireNativeSessionCapture: true } : {}),
|
|
323
325
|
...(captureCapabilities === undefined ? {} : { captureCapabilities }),
|
|
324
326
|
...(backendType === undefined ? {} : { captureHarness: backendType, credentialHarness: backendType }),
|
package/dist/tangle-types.d.ts
CHANGED
|
@@ -104,6 +104,7 @@ export interface SandboxRuntimeCapabilityDocument {
|
|
|
104
104
|
schema?: number;
|
|
105
105
|
/** The selected runtime resolves stored-secret native authentication references. */
|
|
106
106
|
cliAuthReferences?: boolean;
|
|
107
|
+
claudeTokenContinuations?: boolean;
|
|
107
108
|
nativeSessionCaptureVersion?: number;
|
|
108
109
|
nativeSessionCaptureHarnesses?: readonly string[];
|
|
109
110
|
agentInterface?: string;
|
|
@@ -424,6 +425,13 @@ export interface SandboxInstanceLike {
|
|
|
424
425
|
session?(id: string, options?: {
|
|
425
426
|
signal?: AbortSignal;
|
|
426
427
|
}): SandboxSessionLike;
|
|
428
|
+
/** Owner-authorized named grant; material never crosses this consumer boundary. */
|
|
429
|
+
grantNativeCredential?(grant: {
|
|
430
|
+
harness: "claude-code";
|
|
431
|
+
cliAuth: CliAuthReference;
|
|
432
|
+
}, options?: {
|
|
433
|
+
signal?: AbortSignal;
|
|
434
|
+
}): Promise<void>;
|
|
427
435
|
read?(path: string, options?: {
|
|
428
436
|
sessionId?: string;
|
|
429
437
|
signal?: AbortSignal;
|
|
@@ -765,7 +773,7 @@ export type TangleModelCredentials = {
|
|
|
765
773
|
} | {
|
|
766
774
|
cliAuth: CliAuthReference;
|
|
767
775
|
};
|
|
768
|
-
/** Select one public stored-secret reference for
|
|
776
|
+
/** Select one public stored-secret reference for a stable create or fresh-turn identity. */
|
|
769
777
|
export type TangleModelCredentialResolver = (input: Readonly<CreateAgentEnvironmentInput>) => TangleModelCredentials | undefined | Promise<TangleModelCredentials | undefined>;
|
|
770
778
|
export interface TangleProviderOptions {
|
|
771
779
|
client: SandboxClientLike;
|
|
@@ -779,6 +787,9 @@ export interface TangleProviderOptions {
|
|
|
779
787
|
* Managed profiles skip selectors and native references; explicit managed intent skips all references.
|
|
780
788
|
* Unmarked legacy profiles retain their static API reference and grant only its selected secret.
|
|
781
789
|
* Subscription selections grant only their selected secret and record its public reference.
|
|
790
|
+
* A resolver is called again for each fresh native turn with the exact profile and a stable
|
|
791
|
+
* environment/session/turn key. Exact execution replay never selects again. Turn selection
|
|
792
|
+
* requires a runtime proving Claude token continuity and the SDK named-grant method.
|
|
782
793
|
* Cannot be combined with mapCreateInput; never accepts credential values or model overrides.
|
|
783
794
|
*/
|
|
784
795
|
modelCredentials?: TangleModelCredentials | TangleModelCredentialResolver;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tangle-network/agent-provider-tangle",
|
|
3
|
-
"version": "3.
|
|
3
|
+
"version": "3.3.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"
|
|
@@ -126,7 +132,7 @@
|
|
|
126
132
|
},
|
|
127
133
|
"devDependencies": {
|
|
128
134
|
"@tangle-network/agent-provider-testkit": "0.10.0",
|
|
129
|
-
"@tangle-network/agent-runtime": "0.
|
|
135
|
+
"@tangle-network/agent-runtime": "0.292.3",
|
|
130
136
|
"@tangle-network/sandbox": "0.58.7",
|
|
131
137
|
"@types/node": "26.6.3",
|
|
132
138
|
"typescript": "7.0.2",
|