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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -182,8 +182,8 @@ Changing credential sources or harnesses requires a separate environment.
182
182
 
183
183
  ### A command owned by the account system
184
184
 
185
- The Node subpath provides direct process transport for an existing account resolver.
186
- It executes arguments without a shell and discards subprocess stderr.
185
+ The Node subpath uses the Sandbox command transport, with fresh `env` overrides on each invocation.
186
+ Arguments run without a shell; subprocess stderr is discarded.
187
187
 
188
188
  ```ts
189
189
  import { createCommandModelCredentialResolver } from "@tangle-network/agent-provider-tangle/node";
@@ -210,6 +210,7 @@ Timeouts, cancellation, nonzero exit, and malformed or oversized output refuse c
210
210
 
211
211
  The Node subpath also provides `createHttpModelCredentialResolver`.
212
212
  Use a narrow resolve-only grant and the owner's maintained HTTPS endpoint.
213
+ Pass a `bearer` callback when that grant rotates.
213
214
  HTTP is accepted only on loopback for local forwarding.
214
215
  The client never follows redirects or sends private account-owner credentials.
215
216
 
@@ -232,7 +233,7 @@ The response contains only the selected stored reference.
232
233
  Errors, redirects, invalid references, cancellation, and bounded response time refuse provisioning.
233
234
  The client makes one request; recovery may retry the same immutable dispatch identity through the account owner's durable binding.
234
235
  `parseModelCredentialResolverRequest` validates this public wire envelope without normalizing the authored profile.
235
- Requests are bounded at 64 MiB and responses at 64 KiB.
236
+ Request and response bounds come from the Sandbox transport.
236
237
 
237
238
  The account owner retains authority over registration, namespace verification, holds, quota, selection, and trusted renewal.
238
239
  Updating a stored secret does not refresh credentials already injected into a live Sandbox.
@@ -1,4 +1,3 @@
1
- import type { AgentTurnFailure } from "@tangle-network/agent-interface";
2
1
  import { type CredentialValidityOptions } from "./model-credential-resolver.js";
3
2
  import type { TangleModelCredentialResolver } from "./tangle-types.js";
4
3
  export interface CommandModelCredentialResolverOptions extends CredentialValidityOptions {
@@ -8,11 +7,4 @@ export interface CommandModelCredentialResolverOptions extends CredentialValidit
8
7
  env?: Readonly<Record<string, string>>;
9
8
  timeoutMs?: number;
10
9
  }
11
- /** Legacy owners report these permanent refusals only on stderr; retain until typed78 is served. */
12
- export declare class TangleCommandCredentialRefusalError extends Error {
13
- readonly resolutionReason: string;
14
- readonly code: "model_credential_refused";
15
- readonly failure: AgentTurnFailure;
16
- constructor(resolutionReason: string);
17
- }
18
10
  export declare function createCommandModelCredentialResolver(options: CommandModelCredentialResolverOptions): TangleModelCredentialResolver;
@@ -1,73 +1,22 @@
1
- import { spawn } from "node:child_process";
1
+ import { commandSeatTransport, SeatOwnerCommandError } from "@tangle-network/sandbox/select-seat/command";
2
2
  import { TangleCredentialCommandError } from "./model-credential-capacity.js";
3
3
  import { credentialDeadline, ownerCredentialResolver } from "./model-credential-resolver.js";
4
- /** Legacy owners report these permanent refusals only on stderr; retain until typed78 is served. */
5
- export class TangleCommandCredentialRefusalError extends Error {
6
- resolutionReason;
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;
12
- this.name = "TangleCredentialRefusalError";
13
- }
14
- }
15
- const RESOLUTION_REFUSAL = /(?:resume seat conflicts|already bound to a different (?:dispatch|profile)|not enrolled for the exact stage profile)/iu;
16
4
  export function createCommandModelCredentialResolver(options) {
17
- const timeoutMs = options.timeoutMs ?? 30_000;
18
- if (!Number.isSafeInteger(timeoutMs) || timeoutMs <= 0 || timeoutMs > 2_147_483_647)
19
- throw new Error("Tangle credential command timeoutMs must be a positive timer bound");
20
- if (options.env !== undefined && (!options.env || typeof options.env !== "object" || Array.isArray(options.env) ||
21
- Object.entries(options.env).some(([key, value]) => !/^[A-Za-z_][A-Za-z0-9_]*$/.test(key) || typeof value !== "string" || value.includes("\0"))))
22
- throw new Error("Tangle credential command env must contain valid private process variables");
23
- const environment = { ...process.env, ...options.env };
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 = "";
32
- const chunks = [];
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); });
46
- child.on("close", (code, terminationSignal) => {
47
- if (settled)
48
- return;
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));
52
- return;
53
- }
54
- let body;
55
- try {
56
- body = JSON.parse(Buffer.concat(chunks).toString("utf8"));
57
- }
58
- catch {
59
- fail(new TangleCredentialCommandError(code, null));
60
- return;
61
- }
62
- settled = true;
63
- cleanup();
64
- resolve({ ok: code === 0, status: code === 0 ? 200 : code === 75 ? 503 : 400, body });
65
- });
66
- if (signal?.aborted)
67
- abort();
68
- else
69
- child.stdin.end(JSON.stringify(request) + "\n");
5
+ const transport = (command) => {
6
+ const owner = commandSeatTransport({
7
+ command, timeoutMs: options.timeoutMs, env: () => ({ ...process.env, ...options.env }),
70
8
  });
9
+ return async (request, signal) => {
10
+ try {
11
+ return await owner(request, signal);
12
+ }
13
+ catch (error) {
14
+ signal?.throwIfAborted();
15
+ if (error instanceof SeatOwnerCommandError)
16
+ throw new TangleCredentialCommandError(error.exitCode, error.terminationSignal);
17
+ throw error;
18
+ }
19
+ };
71
20
  };
72
21
  return ownerCredentialResolver(transport(options.command), credentialDeadline(options), "command", options.validationCommand === undefined ? undefined : transport(options.validationCommand));
73
22
  }
@@ -5,7 +5,7 @@ export interface HttpModelCredentialResolverOptions extends CredentialValidityOp
5
5
  url: string;
6
6
  /** Separate read-only owner route validation endpoint; never resolves credentials. */
7
7
  validationUrl?: string;
8
- bearer: string;
8
+ bearer: string | (() => string);
9
9
  timeoutMs?: number;
10
10
  }
11
11
  /** The owner broker keeps private account credentials behind its narrow resolve-only grant. */
@@ -1,72 +1,9 @@
1
+ import { gatewaySeatTransport } from "@tangle-network/sandbox";
1
2
  import { credentialDeadline, ownerCredentialResolver } from "./model-credential-resolver.js";
2
- const MAX_PUBLIC_RESPONSE_BYTES = 64 * 1024;
3
- async function publicResponse(response) {
4
- if (!response.body)
5
- throw new Error("Tangle credential broker returned an empty public response");
6
- const reader = response.body.getReader();
7
- const chunks = [];
8
- let bytes = 0;
9
- try {
10
- for (;;) {
11
- const { done, value } = await reader.read();
12
- if (done)
13
- break;
14
- bytes += value.byteLength;
15
- if (bytes > MAX_PUBLIC_RESPONSE_BYTES) {
16
- await reader.cancel();
17
- throw new Error("Tangle credential broker exceeded its public-output bound");
18
- }
19
- chunks.push(value);
20
- }
21
- try {
22
- return JSON.parse(Buffer.concat(chunks).toString("utf8"));
23
- }
24
- catch {
25
- throw new Error("Tangle credential broker returned an invalid public reference");
26
- }
27
- }
28
- finally {
29
- reader.releaseLock();
30
- }
31
- }
32
3
  /** The owner broker keeps private account credentials behind its narrow resolve-only grant. */
33
4
  export function createHttpModelCredentialResolver(options) {
34
- if (typeof options.bearer !== "string" || options.bearer.length < 32 || options.bearer.length > 4096 || /\s/.test(options.bearer))
35
- throw new Error("Tangle credential broker requires a bounded narrow bearer grant");
36
- const bearer = options.bearer;
37
- const timeoutMs = options.timeoutMs ?? 30_000;
38
- if (!Number.isSafeInteger(timeoutMs) || timeoutMs <= 0 || timeoutMs > 2_147_483_647)
39
- throw new Error("Tangle credential broker timeoutMs must be a positive timer bound");
40
- const transport = (url) => {
41
- let endpoint;
42
- try {
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);
61
- try {
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) };
64
- }
65
- finally {
66
- clearTimeout(timer);
67
- signal?.removeEventListener("abort", abort);
68
- }
69
- };
70
- };
5
+ const transport = (url) => gatewaySeatTransport({
6
+ url, bearer: options.bearer, timeoutMs: options.timeoutMs,
7
+ });
71
8
  return ownerCredentialResolver(transport(options.url), credentialDeadline(options), "broker", options.validationUrl === undefined ? undefined : transport(options.validationUrl));
72
9
  }
@@ -41,10 +41,12 @@ export function ownerCredentialResolver(transport, minimumValidUntil, kind, vali
41
41
  input.signal?.throwIfAborted();
42
42
  const body = request(input);
43
43
  return transport(body, input.signal).catch(error => {
44
+ input.signal?.throwIfAborted();
44
45
  if (kind === "command")
45
46
  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
+ throw new Error("Tangle credential broker request failed or returned an invalid public reference");
47
48
  }).then(reply => {
49
+ input.signal?.throwIfAborted();
48
50
  if (!reply.ok)
49
51
  rejectReply(reply);
50
52
  try {
@@ -6,7 +6,8 @@ export function tangleProfileValidator(supplied, resolver) {
6
6
  if (result && !result.ok)
7
7
  return result;
8
8
  const candidate = result?.normalizedProfile ?? profile;
9
- const verdict = typeof candidate !== "string" && candidate.harness ? validateProfileForCreate(candidate, candidate.harness) : undefined;
9
+ // Without a harness the SDK still runs create's inline-mount and size checks; it skips only materialization.
10
+ const verdict = typeof candidate !== "string" ? validateProfileForCreate(candidate, candidate.harness) : undefined;
10
11
  const issues = verdict && !verdict.ok ? [{ level: "error", code: verdict.error.code, message: verdict.error.message }] : [];
11
12
  if (issues.length)
12
13
  return { ok: false, issues };
@@ -80,12 +80,6 @@ async function checkpointOperationLookupByKey(box, idempotencyKey, signal) {
80
80
  signal?.throwIfAborted();
81
81
  return await awaitWithSignal(box.getSnapshotOperation?.(idempotencyKey), signal);
82
82
  }
83
- async function checkpointOperationSucceeded(box, marker, signal) {
84
- const lookup = await checkpointOperationLookup(box, marker, signal);
85
- return (lookup?.outcome === "found" &&
86
- lookup.kind === "checkpoint" &&
87
- lookup.state === "succeeded");
88
- }
89
83
  /** Confirm a fork child through its marker or the legacy fork ledger. */
90
84
  async function forkOperationLookup(box, marker, signal) {
91
85
  if (marker.materialization === "snapshot") {
@@ -143,8 +137,8 @@ async function findCheckpointByKey(box, provider, key, signal) {
143
137
  if (lookup?.outcome === "found" &&
144
138
  lookup.kind === "checkpoint" &&
145
139
  lookup.state === "succeeded") {
146
- const authoritative = snapshotFromOperationResult(snapshot, lookup);
147
- if (authoritative === undefined)
140
+ const authoritative = snapshotFromOperationResult(snapshot, lookup, marker);
141
+ if (authoritative === undefined || snapshots.filter((candidate) => snapshotHasId(candidate, authoritative.snapshotId) !== false).length !== 1)
148
142
  return undefined;
149
143
  if (found !== undefined)
150
144
  return undefined;
@@ -186,17 +180,18 @@ async function findCheckpointByKey(box, provider, key, signal) {
186
180
  return { state: "retired" };
187
181
  if (!validTaggedSnapshotOperationResult(lookup.result))
188
182
  return undefined;
189
- const live = snapshots.filter((snapshot) => snapshot.snapshotId === lookup.result?.snapshotId);
183
+ const result = lookup.result;
184
+ const live = snapshots.filter((snapshot) => snapshotHasId(snapshot, result.snapshotId) !== false);
190
185
  if (live.length === 0)
191
186
  return { state: "retired" };
192
- if (live.length !== 1)
187
+ if (live.length !== 1 || snapshotHasId(live[0], lookup.result.snapshotId) !== true)
193
188
  return undefined;
194
189
  const marker = checkpointMarkerFromTags(lookup.result.tags, key);
195
190
  if (!marker ||
196
191
  !checkpointMarkerBelongsToSource(marker, provider, box.id)) {
197
192
  return undefined;
198
193
  }
199
- const authoritative = snapshotFromOperationResult(live[0], lookup);
194
+ const authoritative = snapshotFromOperationResult(live[0], lookup, marker);
200
195
  return authoritative === undefined
201
196
  ? undefined
202
197
  : { state: "found", snapshot: authoritative, marker };
@@ -222,22 +217,29 @@ export async function reconcileCheckpoint(box, provider, request, signal) {
222
217
  ? { state: "undecided", reason: "metadata_invalid" }
223
218
  : { state: "found", record };
224
219
  }
225
- /**
226
- * Prefer the durable operation result over inventory metadata.
227
- *
228
- * Snapshot inventory and the operation ledger can expose different creation
229
- * timestamps. The ledger result is the acknowledgement returned by the
230
- * idempotent operation, so recovery must rebuild the exact checkpoint ref
231
- * from it when the service provides that result.
232
- */
233
- function snapshotFromOperationResult(snapshot, lookup) {
220
+ /** Sandbox lists a sealed capture by its physical id, retaining the acknowledged id in its native seal tag. */
221
+ function snapshotHasId(snapshot, id) {
222
+ if (snapshot.snapshotId === id)
223
+ return true;
224
+ const seals = snapshot.tags.filter((tag) => tag.startsWith("seal."));
225
+ if (!seals.includes(`seal.${id}`))
226
+ return false;
227
+ return seals.length === 1 ? true : "unknown";
228
+ }
229
+ /** Recover the exact acknowledged id/time, with a marked live inventory witness. */
230
+ function snapshotFromOperationResult(snapshot, lookup, marker) {
234
231
  if (lookup.result === undefined)
235
232
  return snapshot;
236
- if (!validSnapshotOperationResult(lookup.result) ||
237
- lookup.result.snapshotId !== snapshot.snapshotId) {
233
+ if (!validSnapshotOperationResult(lookup.result) || snapshotHasId(snapshot, lookup.result.snapshotId) !== true)
238
234
  return undefined;
235
+ if (lookup.result.snapshotId !== snapshot.snapshotId) {
236
+ if (!validTaggedSnapshotOperationResult(lookup.result))
237
+ return undefined;
238
+ const operationMarker = checkpointMarkerFromTags(lookup.result.tags, marker.idempotencyKey);
239
+ if (!operationMarker || canonicalCandidateDigest(operationMarker.request) !== canonicalCandidateDigest(marker.request))
240
+ return undefined;
239
241
  }
240
- return { ...snapshot, createdAt: lookup.result.createdAt };
242
+ return { ...snapshot, snapshotId: lookup.result.snapshotId, createdAt: lookup.result.createdAt };
241
243
  }
242
244
  /**
243
245
  * Confirm that one snapshot id is a settled checkpoint this provider created.
@@ -252,10 +254,16 @@ export async function findManagedCheckpoint(box, provider, id, expected, signal)
252
254
  if (!Array.isArray(snapshots) || snapshots.length > MAX_LIST_RESULTS) {
253
255
  return "unknown";
254
256
  }
255
- const snapshot = snapshots.find((candidate) => candidate.snapshotId === id);
256
- if (!snapshot)
257
+ const candidates = snapshots.filter((candidate) => snapshotHasId(candidate, id) !== false);
258
+ if (candidates.length === 0)
257
259
  return false;
258
- if (!validSnapshotInfo(snapshot, box.id))
260
+ if (candidates.length !== 1)
261
+ return "unknown";
262
+ const snapshot = candidates[0];
263
+ if (!validSnapshotInfo(snapshot, box.id) || snapshotHasId(snapshot, id) !== true)
264
+ return "unknown";
265
+ // An expected reference can prove a fork source; an alias alone never authorizes cleanup.
266
+ if (snapshot.snapshotId !== id && expected === undefined)
259
267
  return "unknown";
260
268
  const marker = checkpointMarkerFromTags(snapshot.tags, expected?.idempotencyKey);
261
269
  if (!marker)
@@ -270,9 +278,10 @@ export async function findManagedCheckpoint(box, provider, id, expected, signal)
270
278
  canonicalCandidateDigest(expected.source))) {
271
279
  return false;
272
280
  }
273
- return (await checkpointOperationSucceeded(box, marker, signal))
274
- ? true
275
- : "unknown";
281
+ const lookup = await checkpointOperationLookup(box, marker, signal);
282
+ if (lookup?.outcome !== "found" || lookup.kind !== "checkpoint" || lookup.state !== "succeeded")
283
+ return "unknown";
284
+ return snapshot.snapshotId === id || snapshotFromOperationResult(snapshot, lookup, marker)?.snapshotId === id ? true : "unknown";
276
285
  }
277
286
  catch {
278
287
  signal?.throwIfAborted();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tangle-network/agent-provider-tangle",
3
- "version": "5.0.13",
3
+ "version": "5.0.15",
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.19"
36
+ "@tangle-network/agent-interface": "^5.10.20"
37
37
  },
38
38
  "peerDependencies": {
39
- "@tangle-network/sandbox": ">=1.0.216 <2.0.0"
39
+ "@tangle-network/sandbox": ">=1.0.242 <2.0.0"
40
40
  },
41
41
  "peerDependenciesMeta": {
42
42
  "@tangle-network/sandbox": {
@@ -44,9 +44,9 @@
44
44
  }
45
45
  },
46
46
  "devDependencies": {
47
- "@tangle-network/agent-provider-testkit": "0.12.4",
47
+ "@tangle-network/agent-provider-testkit": "0.12.5",
48
48
  "@tangle-network/agent-runtime": "0.349.0",
49
- "@tangle-network/sandbox": "1.0.216",
49
+ "@tangle-network/sandbox": "^1.0.242",
50
50
  "@types/node": "26.6.5",
51
51
  "typescript": "6.0.3",
52
52
  "vitest": "5.0.5"