@tangle-network/agent-provider-tangle 5.0.11 → 5.0.13

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.
@@ -1,26 +1,18 @@
1
+ import type { AgentTurnFailure } from "@tangle-network/agent-interface";
2
+ import { type CredentialValidityOptions } from "./model-credential-resolver.js";
1
3
  import type { TangleModelCredentialResolver } from "./tangle-types.js";
2
- export interface CommandModelCredentialResolverOptions {
3
- /** Executable and arguments, invoked directly without a shell. */
4
+ export interface CommandModelCredentialResolverOptions extends CredentialValidityOptions {
4
5
  command: readonly string[];
5
- /** Additional private process environment; never included in public receipts. */
6
+ /** Owner's read-only validator, e.g. the configured acct --validate-only command. */
7
+ validationCommand?: readonly string[];
6
8
  env?: Readonly<Record<string, string>>;
7
9
  timeoutMs?: number;
8
- /** Fixed absolute run deadline, retained across controller recovery. */
9
- minimumValidUntil?: string;
10
- /** Compute a fixed deadline once at factory construction. */
11
- minimumValidityMs?: number;
12
10
  }
13
- /**
14
- * The resolver refused the binding itself — a deterministic refusal named on the error
15
- * (bounded, from the command's last stderr line). Carries the same machine code as every
16
- * credential route refusal, so a consumer classifies it terminal instead of retrying a
17
- * refusal no retry can satisfy (#475).
18
- */
11
+ /** Legacy owners report these permanent refusals only on stderr; retain until typed78 is served. */
19
12
  export declare class TangleCommandCredentialRefusalError extends Error {
20
- readonly code: "model_credential_refused";
21
- /** The resolver's own bounded reason, safe to journal. */
22
13
  readonly resolutionReason: string;
23
- constructor(reason: string);
14
+ readonly code: "model_credential_refused";
15
+ readonly failure: AgentTurnFailure;
16
+ constructor(resolutionReason: string);
24
17
  }
25
- /** The account owner selects, binds, refreshes, and stores credentials; this transport reads references. */
26
18
  export declare function createCommandModelCredentialResolver(options: CommandModelCredentialResolverOptions): TangleModelCredentialResolver;
@@ -1,194 +1,73 @@
1
- import { parseCredentialCapacity, parseCredentialRefusal } from "./model-credential-capacity.js";
2
1
  import { spawn } from "node:child_process";
3
- import { profileCredentialSource } from "./model-credential-source.js";
4
- import { captureModelCredentials } from "./tangle-create-options.js";
5
- const MAX_COMMAND_OUTPUT_BYTES = 64 * 1024;
6
- /** How much of the command's stderr is retained, and how much of its last line can surface. */
7
- const MAX_COMMAND_STDERR_BYTES = 8 * 1024;
8
- const MAX_STDERR_TAIL_CHARACTERS = 300;
9
- /**
10
- * The resolver refused the binding itself — a deterministic refusal named on the error
11
- * (bounded, from the command's last stderr line). Carries the same machine code as every
12
- * credential route refusal, so a consumer classifies it terminal instead of retrying a
13
- * refusal no retry can satisfy (#475).
14
- */
2
+ import { TangleCredentialCommandError } from "./model-credential-capacity.js";
3
+ import { credentialDeadline, ownerCredentialResolver } from "./model-credential-resolver.js";
4
+ /** Legacy owners report these permanent refusals only on stderr; retain until typed78 is served. */
15
5
  export class TangleCommandCredentialRefusalError extends Error {
16
- code = "model_credential_refused";
17
- /** The resolver's own bounded reason, safe to journal. */
18
6
  resolutionReason;
19
- constructor(reason) {
20
- super(`Tangle credential command refused the route: ${reason}`);
7
+ code = "model_credential_refused";
8
+ failure = { kind: "caller", code: this.code };
9
+ constructor(resolutionReason) {
10
+ super(`Tangle credential command refused the route: ${resolutionReason}`);
11
+ this.resolutionReason = resolutionReason;
21
12
  this.name = "TangleCredentialRefusalError";
22
- this.resolutionReason = reason;
23
13
  }
24
14
  }
25
- /**
26
- * Resolver refusals a retry cannot satisfy, from `acct sandbox resolve`'s ResolutionError lines.
27
- * The list is deliberately narrow: anything unmatched stays the generic failure with its
28
- * `stderrTail`, and the resolver can later grow an exit-code contract beside exit 75's capacity.
29
- */
30
15
  const RESOLUTION_REFUSAL = /(?:resume seat conflicts|already bound to a different (?:dispatch|profile)|not enrolled for the exact stage profile)/iu;
31
- /** The account owner selects, binds, refreshes, and stores credentials; this transport reads references. */
32
16
  export function createCommandModelCredentialResolver(options) {
33
- if (!Array.isArray(options.command) || options.command.length === 0 || options.command.length > 128 ||
34
- options.command.some((part) => typeof part !== "string" || part.length === 0 || part.length > 4096 || part.includes("\0"))) {
35
- throw new Error("Tangle credential command must contain an executable and bounded arguments");
36
- }
37
- const command = Object.freeze([...options.command]);
38
17
  const timeoutMs = options.timeoutMs ?? 30_000;
39
- if (!Number.isSafeInteger(timeoutMs) || timeoutMs <= 0 || timeoutMs > 2_147_483_647) {
18
+ if (!Number.isSafeInteger(timeoutMs) || timeoutMs <= 0 || timeoutMs > 2_147_483_647)
40
19
  throw new Error("Tangle credential command timeoutMs must be a positive timer bound");
41
- }
42
- if (options.minimumValidityMs !== undefined && options.minimumValidUntil !== undefined) {
43
- throw new Error("Tangle credential command accepts one validity deadline");
44
- }
45
- if (options.minimumValidityMs !== undefined &&
46
- (!Number.isSafeInteger(options.minimumValidityMs) || options.minimumValidityMs <= 0)) {
47
- throw new Error("Tangle credential command minimumValidityMs must be a positive integer");
48
- }
49
- if (options.minimumValidUntil !== undefined &&
50
- (typeof options.minimumValidUntil !== "string" || options.minimumValidUntil.length > 128)) {
51
- throw new Error("Tangle credential command validity deadline must be a valid timestamp");
52
- }
53
- const deadline = options.minimumValidUntil === undefined
54
- ? options.minimumValidityMs === undefined ? undefined : new Date(Date.now() + options.minimumValidityMs)
55
- : new Date(options.minimumValidUntil);
56
- if (deadline !== undefined && !Number.isFinite(deadline.getTime())) {
57
- throw new Error("Tangle credential command validity deadline must be a valid timestamp");
58
- }
59
- const minimumValidUntil = deadline?.toISOString();
60
20
  if (options.env !== undefined && (!options.env || typeof options.env !== "object" || Array.isArray(options.env) ||
61
- Object.entries(options.env).some(([key, value]) => !/^[A-Za-z_][A-Za-z0-9_]*$/.test(key) ||
62
- typeof value !== "string" || value.includes("\0")))) {
21
+ Object.entries(options.env).some(([key, value]) => !/^[A-Za-z_][A-Za-z0-9_]*$/.test(key) || typeof value !== "string" || value.includes("\0"))))
63
22
  throw new Error("Tangle credential command env must contain valid private process variables");
64
- }
65
23
  const environment = { ...process.env, ...options.env };
66
- return (input) => {
67
- if (typeof input.profile === "string")
68
- throw new Error("Tangle credential command requires an inline profile");
69
- if (profileCredentialSource(input.profile) === "router")
70
- return undefined;
71
- if (typeof input.idempotencyKey !== "string" || input.idempotencyKey.length === 0) {
72
- throw new Error("Tangle credential command requires a stable create idempotencyKey");
73
- }
74
- input.signal?.throwIfAborted();
75
- const { signal, ...data } = input;
76
- const request = JSON.stringify({ input: data, ...(minimumValidUntil === undefined ? {} : { minimumValidUntil }) });
77
- return new Promise((resolve, reject) => {
78
- let child;
79
- try {
80
- child = spawn(command[0], command.slice(1), {
81
- env: environment,
82
- shell: false,
83
- stdio: ["pipe", "pipe", "pipe"],
84
- });
85
- }
86
- catch {
87
- reject(new Error("Tangle credential command could not start"));
88
- return;
89
- }
90
- // Consume and discard private diagnostics without retaining their content.
91
- child.stderr.resume();
92
- let settled = false;
93
- let outputBytes = 0;
24
+ const transport = (argv) => {
25
+ if (!Array.isArray(argv) || !argv.length || argv.length > 128 || argv.some(p => typeof p !== "string" || !p || p.length > 4096 || p.includes("\0")))
26
+ throw new Error("Tangle credential command must contain an executable and bounded arguments");
27
+ const command = Object.freeze([...argv]);
28
+ return (request, signal) => new Promise((resolve, reject) => {
29
+ signal?.throwIfAborted();
30
+ const child = spawn(command[0], command.slice(1), { env: environment, shell: false, stdio: ["pipe", "pipe", "pipe"] });
31
+ let settled = false, bytes = 0, stderr = "";
94
32
  const chunks = [];
95
- // The resolver's refusal reason travels on stderr, one line. Keep the tail bounded; the
96
- // stdout bound governs the public reference, not this private diagnostic channel.
97
- const stderrTail = [];
98
- let stderrBytes = 0;
99
- const lastStderrLine = () => {
100
- const text = Buffer.concat(stderrTail).toString("utf8");
101
- const line = text
102
- .split("\n")
103
- .map((value) => value.trimEnd())
104
- .filter((value) => value.trim().length > 0)
105
- // A fatal exit appends Node's own banner and stack lines after the program's output; the
106
- // resolver's reason is its own prose line, never a runtime stack frame.
107
- .filter((value) => !/^Node\.js v\d/u.test(value.trim()) && !/^\s+at\s/u.test(value))
108
- .at(-1);
109
- if (line === undefined)
110
- return undefined;
111
- return line.length > MAX_STDERR_TAIL_CHARACTERS ? line.slice(0, MAX_STDERR_TAIL_CHARACTERS) : line;
112
- };
113
- const cleanup = () => {
114
- clearTimeout(timer);
115
- signal?.removeEventListener("abort", onAbort);
116
- };
117
- const fail = (error) => {
118
- if (settled)
119
- return;
120
- settled = true;
121
- cleanup();
122
- child.kill("SIGKILL");
123
- reject(error);
124
- };
125
- const onAbort = () => fail(signal?.reason ?? new Error("Tangle credential command aborted"));
126
- const timer = setTimeout(() => fail(new Error("Tangle credential command timed out")), timeoutMs);
127
- signal?.addEventListener("abort", onAbort, { once: true });
128
- child.on("error", () => fail(new Error("Tangle credential command could not start")));
129
- child.stdin.on("error", () => fail(new Error("Tangle credential command could not accept its request")));
130
- child.stdout.on("data", (chunk) => {
131
- outputBytes += chunk.length;
132
- if (outputBytes > MAX_COMMAND_OUTPUT_BYTES) {
133
- fail(new Error("Tangle credential command exceeded its public-output bound"));
134
- return;
135
- }
136
- chunks.push(chunk);
137
- });
138
- child.stderr.on("data", (chunk) => {
139
- stderrBytes += chunk.length;
140
- stderrTail.push(chunk);
141
- // Keep only the bounded tail: the reason is the LAST line a resolver prints.
142
- while (stderrBytes > MAX_COMMAND_STDERR_BYTES && stderrTail.length > 1) {
143
- stderrBytes -= stderrTail[0].length;
144
- stderrTail.shift();
145
- }
146
- });
33
+ const cleanup = () => { clearTimeout(timer); signal?.removeEventListener("abort", abort); };
34
+ const fail = (error) => { if (settled)
35
+ return; settled = true; cleanup(); child.kill("SIGKILL"); reject(error); };
36
+ const abort = () => fail(signal?.reason ?? new Error("Tangle credential command aborted"));
37
+ const timer = setTimeout(() => fail(new TangleCredentialCommandError(null, null)), timeoutMs);
38
+ signal?.addEventListener("abort", abort, { once: true });
39
+ child.on("error", () => fail(new TangleCredentialCommandError(null, null)));
40
+ child.stdin.on("error", () => fail(new TangleCredentialCommandError(null, null)));
41
+ child.stdout.on("data", (chunk) => { bytes += chunk.length; if (bytes > 64 * 1024)
42
+ fail(new TangleCredentialCommandError(null, null));
43
+ else
44
+ chunks.push(chunk); });
45
+ child.stderr.on("data", (chunk) => { stderr = (stderr + chunk.toString("utf8")).slice(-8 * 1024); });
147
46
  child.on("close", (code, terminationSignal) => {
148
47
  if (settled)
149
48
  return;
150
- if (code !== 0) {
151
- if (code === 75 || code === 78) {
152
- let refusal;
153
- try {
154
- const payload = JSON.parse(Buffer.concat(chunks).toString("utf8"));
155
- refusal = code === 75 ? parseCredentialCapacity(payload) : parseCredentialRefusal(payload);
156
- }
157
- catch { /* Malformed command output stays a sanitized generic refusal. */ }
158
- if (refusal !== undefined) {
159
- fail(refusal);
160
- return;
161
- }
162
- }
163
- const stderrTailLine = lastStderrLine();
164
- if (stderrTailLine !== undefined && RESOLUTION_REFUSAL.test(stderrTailLine)) {
165
- fail(new TangleCommandCredentialRefusalError(stderrTailLine));
166
- return;
167
- }
168
- fail(Object.assign(new Error(`Tangle credential command failed (${code === null ? `signal ${terminationSignal}` : `exit ${code}`})`), {
169
- exitCode: code,
170
- terminationSignal,
171
- ...(stderrTailLine === undefined ? {} : { stderrTail: stderrTailLine }),
172
- }));
49
+ if (code !== 0 && code !== 75 && code !== 78) {
50
+ const reason = stderr.split("\n").map(v => v.trimEnd()).filter(v => v.trim() && !/^Node\.js v\d/u.test(v.trim()) && !/^\s+at\s/u.test(v)).at(-1)?.slice(0, 300);
51
+ fail(reason && RESOLUTION_REFUSAL.test(reason) ? new TangleCommandCredentialRefusalError(reason) : new TangleCredentialCommandError(code, terminationSignal));
173
52
  return;
174
53
  }
54
+ let body;
175
55
  try {
176
- const selected = captureModelCredentials(JSON.parse(Buffer.concat(chunks).toString("utf8")));
177
- if (selected === undefined)
178
- throw new Error();
179
- settled = true;
180
- cleanup();
181
- resolve(selected);
56
+ body = JSON.parse(Buffer.concat(chunks).toString("utf8"));
182
57
  }
183
58
  catch {
184
- fail(new Error("Tangle credential command returned an invalid public reference"));
59
+ fail(new TangleCredentialCommandError(code, null));
60
+ return;
185
61
  }
62
+ settled = true;
63
+ cleanup();
64
+ resolve({ ok: code === 0, status: code === 0 ? 200 : code === 75 ? 503 : 400, body });
186
65
  });
187
- if (signal?.aborted) {
188
- onAbort();
189
- return;
190
- }
191
- child.stdin.end(request + "\n");
66
+ if (signal?.aborted)
67
+ abort();
68
+ else
69
+ child.stdin.end(JSON.stringify(request) + "\n");
192
70
  });
193
71
  };
72
+ return ownerCredentialResolver(transport(options.command), credentialDeadline(options), "command", options.validationCommand === undefined ? undefined : transport(options.validationCommand));
194
73
  }
@@ -1,12 +1,12 @@
1
+ import { type CredentialValidityOptions } from "./model-credential-resolver.js";
1
2
  import type { TangleModelCredentialResolver } from "./tangle-types.js";
2
- export interface HttpModelCredentialResolverOptions {
3
- /** HTTPS broker endpoint, or HTTP on loopback for private local transport. */
3
+ export interface HttpModelCredentialResolverOptions extends CredentialValidityOptions {
4
+ /** HTTPS owner endpoint, or HTTP on loopback for a private local transport. */
4
5
  url: string;
5
- /** Narrow resolve-only grant. Never use a Bridge launch bearer here. */
6
+ /** Separate read-only owner route validation endpoint; never resolves credentials. */
7
+ validationUrl?: string;
6
8
  bearer: string;
7
9
  timeoutMs?: number;
8
- minimumValidUntil?: string;
9
- minimumValidityMs?: number;
10
10
  }
11
- /** Send exact profile intent to the trusted account owner, without exporting owner credentials. */
11
+ /** The owner broker keeps private account credentials behind its narrow resolve-only grant. */
12
12
  export declare function createHttpModelCredentialResolver(options: HttpModelCredentialResolverOptions): TangleModelCredentialResolver;
@@ -1,10 +1,5 @@
1
- import { parseCredentialCapacity, parseCredentialRefusal } 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";
1
+ import { credentialDeadline, ownerCredentialResolver } from "./model-credential-resolver.js";
5
2
  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
3
  async function publicResponse(response) {
9
4
  if (!response.body)
10
5
  throw new Error("Tangle credential broker returned an empty public response");
@@ -34,109 +29,44 @@ async function publicResponse(response) {
34
29
  reader.releaseLock();
35
30
  }
36
31
  }
37
- /** Send exact profile intent to the trusted account owner, without exporting owner credentials. */
32
+ /** The owner broker keeps private account credentials behind its narrow resolve-only grant. */
38
33
  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)) {
34
+ if (typeof options.bearer !== "string" || options.bearer.length < 32 || options.bearer.length > 4096 || /\s/.test(options.bearer))
52
35
  throw new Error("Tangle credential broker requires a bounded narrow bearer grant");
53
- }
54
36
  const bearer = options.bearer;
55
- const url = endpoint.href;
56
37
  const timeoutMs = options.timeoutMs ?? 30_000;
57
- if (!Number.isSafeInteger(timeoutMs) || timeoutMs <= 0 || timeoutMs > 2_147_483_647) {
38
+ if (!Number.isSafeInteger(timeoutMs) || timeoutMs <= 0 || timeoutMs > 2_147_483_647)
58
39
  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) === "router")
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);
40
+ const transport = (url) => {
41
+ let endpoint;
91
42
  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
- let refusal;
106
- try {
107
- const payload = await publicResponse(response);
108
- capacity = parseCredentialCapacity(payload, response.status);
109
- refusal = parseCredentialRefusal(payload, response.status);
110
- const detail = payload && typeof payload === "object" && "error" in payload ? payload.error : undefined;
111
- if (detail && typeof detail === "object" && "exitCode" in detail &&
112
- typeof detail.exitCode === "number" && Number.isSafeInteger(detail.exitCode) && detail.exitCode >= 0 && detail.exitCode <= 255) {
113
- exitCode = detail.exitCode;
114
- }
115
- }
116
- catch {
117
- // Upstream bodies and diagnostics are private; only a bounded numeric exit status is public.
118
- }
119
- if (capacity !== undefined)
120
- throw capacity;
121
- if (refusal !== undefined)
122
- throw refusal;
123
- throw Object.assign(new Error(`Tangle credential broker refused resolution (HTTP ${response.status}${exitCode === undefined ? "" : `, owner exit ${exitCode}`})`), {
124
- status: response.status, ...(exitCode === undefined ? {} : { exitCode }),
125
- });
126
- }
43
+ endpoint = new URL(url);
44
+ }
45
+ catch {
46
+ throw new Error("Tangle credential broker URL is invalid");
47
+ }
48
+ if (typeof url !== "string" || url.length > 2048 || /\s/.test(url) || endpoint.username || endpoint.password || endpoint.search || endpoint.hash ||
49
+ (endpoint.protocol !== "https:" && !(endpoint.protocol === "http:" && ["localhost", "127.0.0.1", "[::1]"].includes(endpoint.hostname))))
50
+ throw new Error("Tangle credential broker requires HTTPS or loopback HTTP without URL credentials");
51
+ return async (request, signal) => {
52
+ const body = JSON.stringify(request);
53
+ if (Buffer.byteLength(body) > 8 * 1024 * 1024)
54
+ throw new Error("Tangle credential broker request exceeds the profile limit");
55
+ const controller = new AbortController();
56
+ const abort = () => controller.abort();
57
+ signal?.addEventListener("abort", abort, { once: true });
58
+ if (signal?.aborted)
59
+ abort();
60
+ const timer = setTimeout(abort, timeoutMs);
127
61
  try {
128
- const selected = captureModelCredentials(await publicResponse(response));
129
- if (selected === undefined)
130
- throw new Error();
131
- return selected;
62
+ const response = await fetch(endpoint.href, { body, method: "POST", headers: { Authorization: `Bearer ${bearer}`, "Content-Type": "application/json" }, redirect: "error", credentials: "omit", signal: controller.signal });
63
+ return { ok: response.ok, status: response.status, body: await publicResponse(response) };
132
64
  }
133
- catch {
134
- throw new Error("Tangle credential broker returned an invalid public reference");
65
+ finally {
66
+ clearTimeout(timer);
67
+ signal?.removeEventListener("abort", abort);
135
68
  }
136
- }
137
- finally {
138
- clearTimeout(timer);
139
- signal?.removeEventListener("abort", onAbort);
140
- }
69
+ };
141
70
  };
71
+ return ownerCredentialResolver(transport(options.url), credentialDeadline(options), "broker", options.validationUrl === undefined ? undefined : transport(options.validationUrl));
142
72
  }
package/dist/index.d.ts CHANGED
@@ -15,3 +15,4 @@ export type { TangleConfidentialAttestationReport } from "./tangle-confidential-
15
15
  export { safeEndpointFromConnection } from "./tangle-observation.js";
16
16
  export { profileCredentialSource } from "./model-credential-source.js";
17
17
  export type { ProfileCredentialSource } from "./model-credential-source.js";
18
+ export { TangleCredentialCapacityError, TangleCredentialRefusalError, TangleCredentialCommandError } from "./model-credential-capacity.js";
package/dist/index.js CHANGED
@@ -9,3 +9,4 @@ export { createTangleWorkspaceBranching, supportsWorkspaceBranching, } from "./t
9
9
  export { decodeTangleConfidentialAttestationQuote, encodeTangleConfidentialAttestationQuote, MAX_TEE_EVIDENCE_BYTES, MAX_TEE_MEASUREMENT_BYTES, TANGLE_CONFIDENTIAL_ATTESTATION_QUOTE_KIND, TANGLE_CONFIDENTIAL_ATTESTATION_QUOTE_VERSION, } from "./tangle-confidential-attestation.js";
10
10
  export { safeEndpointFromConnection } from "./tangle-observation.js";
11
11
  export { profileCredentialSource } from "./model-credential-source.js";
12
+ export { TangleCredentialCapacityError, TangleCredentialRefusalError, TangleCredentialCommandError } from "./model-credential-capacity.js";
@@ -1,3 +1,4 @@
1
+ import { type AgentTurnFailure } from "@tangle-network/agent-interface";
1
2
  export type CredentialCapacityCode = "provider_quota_exhausted" | "upstream_unavailable";
2
3
  export type CredentialCapacityReason = "exhausted" | "unknown" | "held" | "busy";
3
4
  /** The account owner could not admit a fresh dispatch. HTTP status exists only for an HTTP response. */
@@ -5,6 +6,7 @@ export declare class TangleCredentialCapacityError extends Error {
5
6
  readonly code: CredentialCapacityCode;
6
7
  readonly reason: CredentialCapacityReason;
7
8
  readonly resetAt?: string;
9
+ readonly failure: AgentTurnFailure;
8
10
  readonly status?: number;
9
11
  constructor(code: CredentialCapacityCode, reason: CredentialCapacityReason, resetAt?: string, httpStatus?: number);
10
12
  }
@@ -12,10 +14,19 @@ export declare class TangleCredentialCapacityError extends Error {
12
14
  export declare class TangleCredentialRefusalError extends Error {
13
15
  readonly code = "model_credential_refused";
14
16
  readonly reason = "unsupported_route";
17
+ readonly failure: AgentTurnFailure;
15
18
  readonly status?: number;
16
19
  constructor(httpStatus?: number);
17
20
  }
18
- /** The fixed public route refusal shares the bounded capacity transport, never private diagnostics. */
19
21
  export declare function parseCredentialRefusal(value: unknown, httpStatus?: number): TangleCredentialRefusalError | undefined;
20
- /** Only fixed public fields survive parsing; upstream messages and private diagnostics do not. */
21
22
  export declare function parseCredentialCapacity(value: unknown, httpStatus?: number): TangleCredentialCapacityError | undefined;
23
+ /** Classify existing machine codes only; never infer a mechanism from diagnostics. */
24
+ export declare function tangleTurnFailure(record: Record<string, unknown>): AgentTurnFailure | undefined;
25
+ /** A credential-owner process failed without a valid public refusal envelope. */
26
+ export declare class TangleCredentialCommandError extends Error {
27
+ readonly exitCode: number | null;
28
+ readonly terminationSignal: string | null;
29
+ readonly code: "credential_command_failed";
30
+ readonly failure: AgentTurnFailure;
31
+ constructor(exitCode: number | null, terminationSignal: string | null);
32
+ }
@@ -1,8 +1,10 @@
1
+ import { AgentTurnFailureSchema } from "@tangle-network/agent-interface";
1
2
  /** The account owner could not admit a fresh dispatch. HTTP status exists only for an HTTP response. */
2
3
  export class TangleCredentialCapacityError extends Error {
3
4
  code;
4
5
  reason;
5
6
  resetAt;
7
+ failure;
6
8
  constructor(code, reason, resetAt, httpStatus) {
7
9
  super("Subscription account capacity is unavailable");
8
10
  this.name = "TangleCredentialCapacityError";
@@ -10,6 +12,7 @@ export class TangleCredentialCapacityError extends Error {
10
12
  this.reason = reason;
11
13
  if (resetAt !== undefined)
12
14
  this.resetAt = resetAt;
15
+ this.failure = { kind: "capacity", code, ...(resetAt === undefined ? {} : { resetAt }) };
13
16
  if (httpStatus !== undefined) {
14
17
  if (httpStatus !== 429 && httpStatus !== 503)
15
18
  throw new Error("Credential capacity requires a real capacity response");
@@ -21,6 +24,7 @@ export class TangleCredentialCapacityError extends Error {
21
24
  export class TangleCredentialRefusalError extends Error {
22
25
  code = "model_credential_refused";
23
26
  reason = "unsupported_route";
27
+ failure = { kind: "caller", code: this.code };
24
28
  constructor(httpStatus) {
25
29
  super("Subscription credential route is unsupported");
26
30
  this.name = "TangleCredentialRefusalError";
@@ -35,7 +39,6 @@ function record(value) {
35
39
  return value !== null && typeof value === "object" && !Array.isArray(value)
36
40
  ? value : undefined;
37
41
  }
38
- /** The fixed public route refusal shares the bounded capacity transport, never private diagnostics. */
39
42
  export function parseCredentialRefusal(value, httpStatus) {
40
43
  if (httpStatus !== undefined && httpStatus !== 400)
41
44
  return undefined;
@@ -49,7 +52,6 @@ export function parseCredentialRefusal(value, httpStatus) {
49
52
  return undefined;
50
53
  return new TangleCredentialRefusalError(httpStatus);
51
54
  }
52
- /** Only fixed public fields survive parsing; upstream messages and private diagnostics do not. */
53
55
  export function parseCredentialCapacity(value, httpStatus) {
54
56
  if (httpStatus !== undefined && httpStatus !== 429 && httpStatus !== 503)
55
57
  return undefined;
@@ -71,3 +73,31 @@ export function parseCredentialCapacity(value, httpStatus) {
71
73
  return undefined;
72
74
  return new TangleCredentialCapacityError(code, reason, resetAt, httpStatus);
73
75
  }
76
+ /** Classify existing machine codes only; never infer a mechanism from diagnostics. */
77
+ export function tangleTurnFailure(record) {
78
+ if (record.failure !== undefined)
79
+ return AgentTurnFailureSchema.parse(record.failure);
80
+ const code = record.errorCode;
81
+ if (typeof code !== "string")
82
+ return undefined;
83
+ const kind = ["provider_quota_exhausted", "upstream_unavailable", "CAPACITY_EXHAUSTED", "HOST_PRESSURE", "PROVISIONING_PAUSED"].includes(code) ? "capacity"
84
+ : ["model_credential_refused", "PROFILE_UNSUPPORTED", "INVALID_INPUT", "AUTH_FAILED"].includes(code) ? "caller"
85
+ : ["EXECUTION_INTERRUPTED", "NATIVE_CAPTURE_NOT_CONFIRMED", "TRANSPORT_LOST", "SANDBOX_UNREACHABLE"].includes(code) ? "infra" : undefined;
86
+ if (!kind)
87
+ return undefined;
88
+ return AgentTurnFailureSchema.parse({ kind, code, ...(record.resetAt === undefined ? {} : { resetAt: record.resetAt }),
89
+ ...(record.retryAfterMs === undefined ? {} : { retryAfterMs: record.retryAfterMs }) });
90
+ }
91
+ /** A credential-owner process failed without a valid public refusal envelope. */
92
+ export class TangleCredentialCommandError extends Error {
93
+ exitCode;
94
+ terminationSignal;
95
+ code = "credential_command_failed";
96
+ failure = { kind: "infra", code: this.code };
97
+ constructor(exitCode, terminationSignal) {
98
+ super(`Tangle credential command failed (${exitCode === null ? `signal ${terminationSignal ?? "unknown"}` : `exit ${exitCode}`})`);
99
+ this.exitCode = exitCode;
100
+ this.terminationSignal = terminationSignal;
101
+ this.name = "TangleCredentialCommandError";
102
+ }
103
+ }
@@ -18,12 +18,11 @@ export function parseModelCredentialResolverRequest(value) {
18
18
  assertBoundedJson(profile, "Tangle credential request profile", []);
19
19
  if ("signal" in data || typeof data.idempotencyKey !== "string" ||
20
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");
21
+ throw new Error("Tangle credential request requires a stable create identity (idempotencyKey) without a serialized signal");
22
22
  }
23
23
  if (!agentProfileSchema.safeParse(data.profile).success || typeof data.profile === "string") {
24
24
  throw new Error("Tangle credential request requires an inline AgentProfile");
25
25
  }
26
- // The wire carries JSON. Schema parsing validates it, but must not normalize the caller's profile.
27
26
  const acceptedInput = input;
28
27
  profileCredentialSource(acceptedInput.profile);
29
28
  const deadline = request.minimumValidUntil;
@@ -0,0 +1,11 @@
1
+ import type { SeatOwnerReply } from "@tangle-network/sandbox";
2
+ import { type ModelCredentialResolverRequest } from "./model-credential-request.js";
3
+ import type { TangleModelCredentialResolver } from "./tangle-types.js";
4
+ type CredentialTransport = (request: ModelCredentialResolverRequest, signal?: AbortSignal) => Promise<SeatOwnerReply>;
5
+ export interface CredentialValidityOptions {
6
+ minimumValidUntil?: string;
7
+ minimumValidityMs?: number;
8
+ }
9
+ export declare function credentialDeadline(options: CredentialValidityOptions): string | undefined;
10
+ export declare function ownerCredentialResolver(transport: CredentialTransport, minimumValidUntil: string | undefined, kind: "command" | "broker", validation?: CredentialTransport): TangleModelCredentialResolver;
11
+ export {};
@@ -0,0 +1,80 @@
1
+ import { parseCredentialCapacity, parseCredentialRefusal, TangleCredentialCommandError } 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
+ export function credentialDeadline(options) {
6
+ if (options.minimumValidUntil !== undefined && options.minimumValidityMs !== undefined)
7
+ throw new Error("Tangle credential resolver accepts one validity deadline");
8
+ if (options.minimumValidityMs !== undefined && (!Number.isSafeInteger(options.minimumValidityMs) || options.minimumValidityMs <= 0))
9
+ throw new Error("Tangle credential resolver minimumValidityMs must be a positive integer");
10
+ const deadline = options.minimumValidUntil === undefined
11
+ ? options.minimumValidityMs === undefined ? undefined : new Date(Date.now() + options.minimumValidityMs)
12
+ : typeof options.minimumValidUntil === "string" && options.minimumValidUntil.length <= 128 ? new Date(options.minimumValidUntil) : new Date(NaN);
13
+ if (deadline !== undefined && !Number.isFinite(deadline.getTime()))
14
+ throw new Error("Tangle credential resolver validity deadline must be a valid timestamp");
15
+ return deadline?.toISOString();
16
+ }
17
+ export function ownerCredentialResolver(transport, minimumValidUntil, kind, validation) {
18
+ const request = (input) => {
19
+ const { signal: _, ...data } = input;
20
+ return parseModelCredentialResolverRequest({ input: data, ...(minimumValidUntil === undefined ? {} : { minimumValidUntil }) });
21
+ };
22
+ const rejectReply = (reply) => {
23
+ const status = kind === "broker" ? reply.status : undefined;
24
+ const typed = ([429, 503].includes(reply.status) ? parseCredentialCapacity(reply.body, status) : undefined) ??
25
+ (reply.status === 400 ? parseCredentialRefusal(reply.body, status) : undefined);
26
+ if (typed)
27
+ throw typed;
28
+ if (kind === "command")
29
+ throw new TangleCredentialCommandError(reply.status === 200 ? 0 : reply.status === 400 ? 78 : reply.status === 503 ? 75 : null, null);
30
+ const detail = reply.body && typeof reply.body === "object" && "error" in reply.body ? reply.body.error : undefined;
31
+ const exitCode = detail && typeof detail === "object" && "exitCode" in detail ? detail.exitCode : undefined;
32
+ throw Object.assign(new Error(`Tangle credential broker refused resolution (HTTP ${reply.status})`), {
33
+ status: reply.status, ...(typeof exitCode === "number" && Number.isInteger(exitCode) && exitCode >= 0 && exitCode <= 255 ? { exitCode } : {}),
34
+ });
35
+ };
36
+ const resolver = (input) => {
37
+ if (typeof input.profile === "string")
38
+ throw new Error(`Tangle credential ${kind} requires an inline profile`);
39
+ if (profileCredentialSource(input.profile) === "router")
40
+ return undefined;
41
+ input.signal?.throwIfAborted();
42
+ const body = request(input);
43
+ return transport(body, input.signal).catch(error => {
44
+ if (kind === "command")
45
+ throw error;
46
+ throw new Error(input.signal?.aborted ? "Tangle credential broker request aborted" : "Tangle credential broker request failed or returned an invalid public reference");
47
+ }).then(reply => {
48
+ if (!reply.ok)
49
+ rejectReply(reply);
50
+ try {
51
+ const selected = captureModelCredentials(reply.body);
52
+ if (selected === undefined)
53
+ throw new Error();
54
+ return selected;
55
+ }
56
+ catch {
57
+ throw kind === "command" ? new TangleCredentialCommandError(0, null)
58
+ : new Error("Tangle credential broker returned an invalid public reference");
59
+ }
60
+ });
61
+ };
62
+ if (validation) {
63
+ resolver.validate = async (profile) => {
64
+ if (typeof profile === "string")
65
+ return { ok: false, issues: [{ level: "error", code: "PROFILE_UNSUPPORTED", message: "Subscription route validation requires an inline profile" }] };
66
+ if (profileCredentialSource(profile) === "router")
67
+ return { ok: true, issues: [] };
68
+ const reply = await validation(request({ profile, idempotencyKey: "profile-preflight" }));
69
+ const body = reply.body;
70
+ if (reply.ok && body?.supported === true && Object.keys(body).length === 1)
71
+ return { ok: true, issues: [] };
72
+ const refusal = reply.status === 400 && body?.supported === false && Object.keys(body).every(k => k === "supported" || k === "error")
73
+ ? parseCredentialRefusal({ error: body.error }, kind === "broker" ? reply.status : undefined) : undefined;
74
+ if (!refusal)
75
+ return rejectReply(reply);
76
+ return { ok: false, issues: [{ level: "error", code: refusal.code, message: refusal.message }] };
77
+ };
78
+ }
79
+ return kind === "broker" ? Object.assign(async (input) => resolver(input), { validate: resolver.validate }) : resolver;
80
+ }
package/dist/node.d.ts CHANGED
@@ -4,7 +4,7 @@ export { createHttpModelCredentialResolver } from "./http-model-credentials.js";
4
4
  export type { HttpModelCredentialResolverOptions } from "./http-model-credentials.js";
5
5
  export { parseModelCredentialResolverRequest } from "./model-credential-request.js";
6
6
  export type { ModelCredentialResolverRequest } from "./model-credential-request.js";
7
- export { TangleCredentialCapacityError, TangleCredentialRefusalError } from "./model-credential-capacity.js";
7
+ export { TangleCredentialCapacityError, TangleCredentialRefusalError, TangleCredentialCommandError } from "./model-credential-capacity.js";
8
8
  export type { CredentialCapacityCode, CredentialCapacityReason } from "./model-credential-capacity.js";
9
9
  export { captureTangleEnvironmentEvidenceToDirectory, captureTangleSandboxEvidenceToDirectory } from "./tangle-evidence.js";
10
10
  export type { TangleDirectoryEvidence } from "./tangle-evidence.js";
package/dist/node.js CHANGED
@@ -1,5 +1,5 @@
1
1
  export { createCommandModelCredentialResolver } from "./command-model-credentials.js";
2
2
  export { createHttpModelCredentialResolver } from "./http-model-credentials.js";
3
3
  export { parseModelCredentialResolverRequest } from "./model-credential-request.js";
4
- export { TangleCredentialCapacityError, TangleCredentialRefusalError } from "./model-credential-capacity.js";
4
+ export { TangleCredentialCapacityError, TangleCredentialRefusalError, TangleCredentialCommandError } from "./model-credential-capacity.js";
5
5
  export { captureTangleEnvironmentEvidenceToDirectory, captureTangleSandboxEvidenceToDirectory } from "./tangle-evidence.js";
@@ -36,5 +36,5 @@ export declare function assertMappedSecretNames(options: {
36
36
  env?: Record<string, string>;
37
37
  }): void;
38
38
  export declare function assertCreateInputShape(input: CreateAgentEnvironmentInput, parsedWorkspace?: WorkspaceRequest): WorkspaceRequest | undefined;
39
- export declare function assertMappedCreateOptions(options: TangleCreateSandboxOptions): void;
39
+ export declare function assertMappedCreateOptions(options: TangleCreateSandboxOptions, input?: CreateAgentEnvironmentInput): void;
40
40
  export {};
@@ -5,7 +5,7 @@ import { assertBoundedJson, boundedIdentifier, boundedString, MAX_ARRAY_LENGTH,
5
5
  import { profileCredentialSource } from "./model-credential-source.js";
6
6
  import { sandboxResourcesFromResourceRequest } from "./tangle-resources.js";
7
7
  import { tangleRuntimeAttachments } from "./tangle-runtime-attachments.js";
8
- import { deepFreeze } from "@tangle-network/agent-interface";
8
+ import { canonicalCandidateDigest, deepFreeze } from "@tangle-network/agent-interface";
9
9
  import { assertProxySecretAliases, captureProxySecrets, mergeProxySecrets, proxySecretsFromInput, sandboxSecretBindingIdentity } from "./tangle-proxy-secrets.js";
10
10
  /** Immutable create evidence used to bind a later native resume to its restored snapshot. */
11
11
  export const NATIVE_RESUME_CHECKPOINT_METADATA_KEY = "tangleNativeResumeCheckpointId";
@@ -173,6 +173,8 @@ export function sandboxOptionsFromCreateInput(input, defaultBackend, parsedWorks
173
173
  }
174
174
  const maxLifetimeSeconds = wholeSecondsOf(input.maxLifetimeMs, "maxLifetimeMs");
175
175
  const idleTimeoutSeconds = wholeSecondsOf(input.idleTimeoutMs, "idleTimeoutMs");
176
+ const deleteAfterStoppedSeconds = wholeSecondsOf(input.deleteAfterStoppedMs, "deleteAfterStoppedMs");
177
+ const retain = input.retain;
176
178
  const resources = sandboxResourcesFromResourceRequest(input.resources);
177
179
  // Sandbox injects secrets by name from its own store. Accepting a name/value
178
180
  // record and dropping it would create an environment with no credentials and
@@ -194,6 +196,8 @@ export function sandboxOptionsFromCreateInput(input, defaultBackend, parsedWorks
194
196
  ...(input.env ? { env: input.env } : {}),
195
197
  ...(maxLifetimeSeconds === undefined ? {} : { maxLifetimeSeconds }),
196
198
  ...(idleTimeoutSeconds === undefined ? {} : { idleTimeoutSeconds }),
199
+ ...(deleteAfterStoppedSeconds === undefined ? {} : { deleteAfterStoppedSeconds }),
200
+ ...(retain === undefined ? {} : { retain: { paths: [...retain.paths] } }),
197
201
  ...(secrets === undefined ? {} : { secrets }),
198
202
  ...(proxySecrets === undefined ? {} : { proxySecrets }),
199
203
  ...(input.egress === undefined ? {} : { egressPolicy: sandboxEgressPolicy(input.egress) }),
@@ -309,6 +313,8 @@ export function assertCreateInputShape(input, parsedWorkspace) {
309
313
  "billingOwner",
310
314
  "maxLifetimeMs",
311
315
  "idleTimeoutMs",
316
+ "deleteAfterStoppedMs",
317
+ "retain",
312
318
  "metadata",
313
319
  "name",
314
320
  "idempotencyKey",
@@ -342,17 +348,26 @@ export function assertCreateInputShape(input, parsedWorkspace) {
342
348
  if (resourceKeys.size > 0)
343
349
  throw new Error("Tangle resources contain unsupported fields");
344
350
  }
351
+ const retain = input.retain;
352
+ if (retain !== undefined && (!retain || typeof retain !== "object" ||
353
+ Object.keys(retain).some(key => key !== "paths") || !Array.isArray(retain.paths) ||
354
+ retain.paths.length > MAX_ARRAY_LENGTH || retain.paths.some(path => typeof path !== "string" || !path || path.length > 4096 || path.includes("\0"))))
355
+ throw new Error("Tangle retain must contain bounded paths");
345
356
  if (input.workspace === undefined)
346
357
  return undefined;
347
358
  const workspace = parsedWorkspace ?? WorkspaceRequestSchema.parse(input.workspace);
348
359
  workspaceCwdPathForBase(workspace.cwd, "repository", "Tangle");
349
360
  return workspace;
350
361
  }
351
- export function assertMappedCreateOptions(options) {
362
+ export function assertMappedCreateOptions(options, input) {
352
363
  if (!options || typeof options !== "object" || Array.isArray(options)) {
353
364
  throw new Error("Tangle mapped create options must be an object");
354
365
  }
355
366
  assertBoundedJson(options, "Tangle mapped create options", PROFILE_AT_BACKEND_PROFILE);
367
+ if (input?.deleteAfterStoppedMs !== undefined && options.deleteAfterStoppedSeconds !== wholeSecondsOf(input.deleteAfterStoppedMs, "deleteAfterStoppedMs"))
368
+ throw new Error("Tangle mapped create options must preserve requested deleteAfterStoppedMs");
369
+ if (input?.retain !== undefined && canonicalCandidateDigest(options.retain ?? null) !== canonicalCandidateDigest(input.retain))
370
+ throw new Error("Tangle mapped create options must preserve requested retain");
356
371
  if (options.backend?.model?.cliAuth !== undefined) {
357
372
  if (options.backend.type === undefined) {
358
373
  throw new Error("Tangle mapped native credentials require the selected backend type");
@@ -1,5 +1,6 @@
1
1
  import type { AgentEnvironmentProvider } from "@tangle-network/agent-interface/environment-provider";
2
+ import type { TangleModelCredentialResolver } from "./tangle-types.js";
2
3
  type ProfileValidator = NonNullable<AgentEnvironmentProvider["validateProfile"]>;
3
- /** The provider's validateProfile: the Sandbox mount check and pre-box verdict, then any caller-supplied validator. */
4
- export declare function tangleProfileValidator(supplied?: ProfileValidator): ProfileValidator;
4
+ /** Validate the normalized profile once through the SDK and account owner's read-only route check. */
5
+ export declare function tangleProfileValidator(supplied?: ProfileValidator, resolver?: TangleModelCredentialResolver): ProfileValidator;
5
6
  export {};
@@ -1,44 +1,17 @@
1
- import * as Sandbox from "@tangle-network/sandbox";
2
- import { splitInlineProfileFileMounts, validateDeferredProfileFileMounts } from "@tangle-network/sandbox";
3
- /** The Sandbox SDK's create-time check of a profile's inline file mounts, run before any box exists. */
4
- function profileFileMountIssues(profile) {
5
- if (typeof profile === "string")
6
- return [];
7
- const { deferredFiles } = splitInlineProfileFileMounts(profile);
8
- if (!deferredFiles.length)
9
- return [];
10
- try {
11
- validateDeferredProfileFileMounts(deferredFiles);
12
- return [];
13
- }
14
- catch (error) {
15
- const detail = error;
16
- return [{
17
- level: "error",
18
- code: typeof detail.code === "string" ? detail.code : "PROFILE_FILE_MOUNT_INVALID",
19
- message: typeof detail.message === "string" ? detail.message : String(error),
20
- ...(typeof detail.path === "string" ? { path: detail.path } : {}),
21
- }];
22
- }
23
- }
24
- /** Sandbox's pre-box verdict where the SDK ships it: create sends the whole profile, so oversize refuses too (a live 1.5 MB create answered 413). */
25
- function profileVerdictIssues(profile) {
26
- const verdict = Sandbox.validateProfileForCreate;
27
- const harness = typeof profile === "string" ? undefined : profile.harness;
28
- const result = verdict && harness ? verdict(profile, harness) : undefined;
29
- if (!result || result.ok || !result.error)
30
- return [];
31
- return [{ level: "error", code: result.error.code ?? "PROFILE_UNSUPPORTED", message: result.error.message }];
32
- }
33
- /** The provider's validateProfile: the Sandbox mount check and pre-box verdict, then any caller-supplied validator. */
34
- export function tangleProfileValidator(supplied) {
1
+ import { validateProfileForCreate } from "@tangle-network/sandbox";
2
+ /** Validate the normalized profile once through the SDK and account owner's read-only route check. */
3
+ export function tangleProfileValidator(supplied, resolver) {
35
4
  return async (profile) => {
36
- const issues = [...profileFileMountIssues(profile), ...profileVerdictIssues(profile)];
37
- const result = supplied ? await supplied(profile) : undefined;
38
- return {
39
- ok: !issues.some((issue) => issue.level === "error") && (result?.ok ?? true),
40
- issues: [...issues, ...(result?.issues ?? [])],
41
- ...(result?.normalizedProfile ? { normalizedProfile: result.normalizedProfile } : {}),
42
- };
5
+ const result = await supplied?.(profile);
6
+ if (result && !result.ok)
7
+ return result;
8
+ const candidate = result?.normalizedProfile ?? profile;
9
+ const verdict = typeof candidate !== "string" && candidate.harness ? validateProfileForCreate(candidate, candidate.harness) : undefined;
10
+ const issues = verdict && !verdict.ok ? [{ level: "error", code: verdict.error.code, message: verdict.error.message }] : [];
11
+ if (issues.length)
12
+ return { ok: false, issues };
13
+ const route = await resolver?.validate?.(candidate);
14
+ return { ok: route?.ok ?? true, issues: [...(route?.issues ?? []), ...(result?.issues ?? [])],
15
+ ...(result?.normalizedProfile ? { normalizedProfile: result.normalizedProfile } : {}) };
43
16
  };
44
17
  }
@@ -4,7 +4,7 @@ import { projectAgentTerminalRecord } from "@tangle-network/sandbox/runtime";
4
4
  import { assertCliAuthReferenceSupported, cliAuthReferenceSchema, } from "@tangle-network/sandbox/auth";
5
5
  import { agentProfileSchema, canonicalAgentProfileDigest, canonicalCandidateDigest, boundedEventContentRecordSchema, AgentExactRunControlRefSchema, AgentTurnInputSchema, ContextTransferReceiptSchema, ProxySecretReceiptSchema, deepFreeze, isProxySecretScopeAttenuation, proxySecretPresentationsEqual, contextTransferResultMatchesRequest, } from "@tangle-network/agent-interface";
6
6
  import { tokenUsageFromData } from "./tangle-result-values.js";
7
- import { TangleCredentialCapacityError } from "./model-credential-capacity.js";
7
+ import { TangleCredentialCapacityError, tangleTurnFailure } from "./model-credential-capacity.js";
8
8
  import { assertBoundedJson, awaitWithSignal, boundedString, MAX_INLINE_PAYLOAD_BYTES, PROFILE_AT_PROFILE, } from "./tangle-contract-safety.js";
9
9
  import { profileCredentialSource } from "./model-credential-source.js";
10
10
  import { tangleRuntimeAttachments } from "./tangle-runtime-attachments.js";
@@ -576,16 +576,16 @@ export function agentTurnResultFromPromptRecord(record, options = {}) {
576
576
  !contextTransferResultMatchesRequest(options.contextTransferRequest, contextTransferReceipt.data)) {
577
577
  throw new Error("Tangle prompt result context receipt does not match its request");
578
578
  }
579
- // Preserve the credential owner's typed quota refusal and reset time.
580
- if (!record.success && record.errorCode === "provider_quota_exhausted") {
581
- const resetAt = record.resetAt;
582
- throw new TangleCredentialCapacityError("provider_quota_exhausted", "exhausted", typeof resetAt === "string" && new Date(resetAt).toISOString() === resetAt ? resetAt : undefined, 429);
583
- }
579
+ const failure = !record.success ? tangleTurnFailure(record) : undefined;
580
+ // Old Runtime consumes this legacy rejection; typed producers carry failure on the returned result.
581
+ if (record.failure === undefined && failure?.code === "provider_quota_exhausted")
582
+ throw new TangleCredentialCapacityError("provider_quota_exhausted", "exhausted", failure.resetAt, 429);
584
583
  const usage = tokenUsageFromData(record);
585
584
  const awaiting = AWAITING_STATUSES.has(record.status);
586
585
  return {
587
586
  text,
588
587
  success: record.success,
588
+ ...(failure ? { failure } : {}),
589
589
  ...(options.sessionId ? { sessionId: options.sessionId } : {}),
590
590
  ...(typeof record.error === "string" ? { error: record.error } : {}),
591
591
  ...(usage ? { usage } : {}),
@@ -155,7 +155,7 @@ export function createTangleProvider(options) {
155
155
  }
156
156
  if (requestedReason !== undefined && canonicalCandidateDigest(mappedOptions.metadata?.reason ?? null) !== canonicalCandidateDigest(requestedReason))
157
157
  throw new Error("Tangle mapped raw consent must preserve its named reason");
158
- assertMappedCreateOptions(mappedOptions);
158
+ assertMappedCreateOptions(mappedOptions, input);
159
159
  const mappedRouting = mappedOptions.backend?.model?.routing;
160
160
  if (canonicalCandidateDigest(mappedRouting ?? null) !== canonicalCandidateDigest(requestedRouting ?? null)) {
161
161
  throw new Error("Tangle mapped create options must carry exactly the requested providerOptions.routing");
@@ -346,7 +346,7 @@ export function createTangleProvider(options) {
346
346
  ...(typeof options.client.secrets?.update !== "function" ? {} : { secrets: options.client.secrets }),
347
347
  ...(workspaceBranching === undefined ? {} : { workspaceBranching }),
348
348
  capabilities: resolveCapabilities,
349
- validateProfile: tangleProfileValidator(options.validateProfile),
349
+ validateProfile: tangleProfileValidator(options.validateProfile, resolveModelCredentials),
350
350
  async create(input) {
351
351
  const { signal, ...material } = input;
352
352
  signal?.throwIfAborted();
@@ -823,7 +823,10 @@ export type TangleModelCredentials = {
823
823
  proxySecrets?: ProxySecretBinding[];
824
824
  };
825
825
  /** Select one public stored-secret reference for a stable create or fresh-turn identity. */
826
- export type TangleModelCredentialResolver = (input: Readonly<CreateAgentEnvironmentInput>) => TangleModelCredentials | undefined | Promise<TangleModelCredentials | undefined>;
826
+ export type TangleModelCredentialResolver = ((input: Readonly<CreateAgentEnvironmentInput>) => TangleModelCredentials | undefined | Promise<TangleModelCredentials | undefined>) & {
827
+ /** Read-only owner route check; no seat selection, binding or secret access. */
828
+ validate?: NonNullable<AgentEnvironmentProvider["validateProfile"]>;
829
+ };
827
830
  export interface TangleProviderOptions {
828
831
  client: SandboxClientLike;
829
832
  name?: string;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tangle-network/agent-provider-tangle",
3
- "version": "5.0.11",
3
+ "version": "5.0.13",
4
4
  "description": "AgentEnvironmentProvider adapter for Tangle sandboxes",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -33,10 +33,10 @@
33
33
  "LICENSE"
34
34
  ],
35
35
  "dependencies": {
36
- "@tangle-network/agent-interface": "^5.10.18"
36
+ "@tangle-network/agent-interface": "^5.10.19"
37
37
  },
38
38
  "peerDependencies": {
39
- "@tangle-network/sandbox": ">=1.0.151 <2.0.0"
39
+ "@tangle-network/sandbox": ">=1.0.216 <2.0.0"
40
40
  },
41
41
  "peerDependenciesMeta": {
42
42
  "@tangle-network/sandbox": {