@tangle-network/agent-provider-tangle 4.5.7 → 5.0.1

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.
@@ -2,7 +2,7 @@ import { randomUUID } from "node:crypto";
2
2
  import { normalizeRuntimeBackendConfig } from "@tangle-network/sandbox";
3
3
  import { projectAgentTerminalRecord } from "@tangle-network/sandbox/runtime";
4
4
  import { assertCliAuthReferenceSupported, cliAuthReferenceSchema, } from "@tangle-network/sandbox/auth";
5
- import { agentProfileSchema, canonicalAgentProfileDigest, canonicalCandidateDigest, boundedEventContentRecordSchema, AgentExactRunControlRefSchema, AgentTurnInputSchema, ContextTransferReceiptSchema, contextTransferResultMatchesRequest, } from "@tangle-network/agent-interface";
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
7
  import { TangleCredentialCapacityError } from "./model-credential-capacity.js";
8
8
  import { assertBoundedJson, awaitWithSignal, boundedString, PROFILE_AT_PROFILE, } from "./tangle-contract-safety.js";
@@ -66,67 +66,100 @@ export function promptOptionsFromTurnInput(input, target) {
66
66
  ...(input.detach !== undefined ? { detach: input.detach } : {}),
67
67
  };
68
68
  }
69
- /** The SDK owns isolated session creation and the executor's private admission receipt. */
70
- export async function preparePromptOptions(box, options, provider) {
71
- if (options.lastEventId !== undefined ||
72
- (options.backend?.runtimeSecrets === undefined &&
73
- options.backend?.metadata?.profileSecretIsolation !== true))
69
+ export function proxySecretReceiptFromSandbox(box) {
70
+ if (box.proxySecretReceipt === undefined)
71
+ return undefined;
72
+ const receipt = ProxySecretReceiptSchema.parse(box.proxySecretReceipt);
73
+ if (receipt.sandboxId !== box.id)
74
+ throw new Error("Tangle proxy receipt names another sandbox");
75
+ return deepFreeze(receipt);
76
+ }
77
+ function requireProxyReceipt(receipt, bindings, installed) {
78
+ if (!receipt || receipt.status === "revoked" || (installed && receipt.status !== "installed") ||
79
+ receipt.bindings.some(({ grant }) => Date.parse(grant.expiresAt) <= Date.now()) ||
80
+ bindings.some((binding) => !receipt.bindings.some(({ envName, secretRef, grant }) => envName === binding.envName && canonicalCandidateDigest(secretRef) === canonicalCandidateDigest(binding.secretRef) &&
81
+ isProxySecretScopeAttenuation(binding, grant.scope) && proxySecretPresentationsEqual(binding.presentation, grant.presentation) &&
82
+ grant.placeholderFormat === (binding.placeholderFormat ?? "opaque") &&
83
+ (binding.ttlSeconds === undefined || Date.parse(grant.expiresAt) - Date.parse(grant.issuedAt) <= binding.ttlSeconds * 1000)))) {
84
+ throw new Error("Tangle canonical launch requires a current matching installed proxy receipt");
85
+ }
86
+ return receipt;
87
+ }
88
+ function containsProxyReceipt(full, subset) {
89
+ return full.sandboxId === subset.sandboxId && full.generation === subset.generation &&
90
+ subset.bindings.every((binding) => full.bindings.some((member) => canonicalCandidateDigest(member) === canonicalCandidateDigest(binding)));
91
+ }
92
+ /** Prepare one exact launch; legacy and cursor replay retain their existing path. */
93
+ export async function preparePromptOptions(box, options, provider, bindings) {
94
+ if (options.lastEventId !== undefined)
95
+ return options;
96
+ const selected = bindings ?? [];
97
+ const canonical = selected.length > 0;
98
+ const isolated = options.backend?.runtimeSecrets !== undefined || options.backend?.metadata?.profileSecretIsolation === true;
99
+ const native = canonical ? options.backend?.model?.cliAuth : undefined;
100
+ if (!canonical && !isolated)
74
101
  return options;
75
- if (!box?.createSession || !box.prepareSecretProfileRevision) {
76
- throw new Error("Tangle secret turns require Sandbox isolated-session preparation support");
102
+ if (canonical && !box.refresh)
103
+ throw new Error("Tangle canonical launch requires current sandbox information");
104
+ if (canonical)
105
+ await awaitWithSignal(box.refresh?.(options.signal), options.signal);
106
+ const before = canonical ? requireProxyReceipt(proxySecretReceiptFromSandbox(box), selected, false) : undefined;
107
+ if (isolated || native !== undefined) {
108
+ if (!box.createSession || (isolated ? !box.prepareSecretProfileRevision : !box.preparePublicProfileRevision))
109
+ throw new Error("Tangle profile preparation is unsupported by this Sandbox client");
110
+ options.signal?.throwIfAborted();
111
+ const sessionId = options.sessionId ?? sessionPromptSessionId(provider, box.id, options.turnId ?? options.executionId) ?? randomUUID();
112
+ const backend = isolated ? { ...options.backend, metadata: { ...options.backend?.metadata, profileSecretIsolation: true } } : options.backend ?? {};
113
+ const { runtimeSecrets: _turnOnly, ...persisted } = backend;
114
+ const created = await awaitWithSignal(box.createSession({ sessionId, retention: "workspace", backend: persisted }), options.signal);
115
+ if (created.session.id !== sessionId || created.info.id !== sessionId)
116
+ throw new Error("Tangle profile preparation changed its exact session identity");
117
+ const args = { sessionId, backend, ...(options.model === undefined ? {} : { model: options.model }) };
118
+ if (isolated) {
119
+ const prepared = await awaitWithSignal(box.prepareSecretProfileRevision(args), options.signal);
120
+ options = { ...options, sessionId, backend, expectedPublicProfileRequestDigest: prepared.expectedPublicProfileRequestDigest, expectedSecretProfileReceipt: prepared.expectedSecretProfileReceipt };
121
+ if (canonical)
122
+ validatePrepared(prepared.proxySecretReceipt);
123
+ }
124
+ else {
125
+ const prepared = await awaitWithSignal(box.preparePublicProfileRevision(args), options.signal);
126
+ options = { ...options, sessionId, backend, expectedPublicProfileRequestDigest: prepared.expectedPublicProfileRequestDigest, expectedPublicProfileRevision: prepared.expectedPublicProfileRevision };
127
+ validatePrepared(prepared.proxySecretReceipt);
128
+ }
77
129
  }
78
- options.signal?.throwIfAborted();
79
- const sessionId = options.sessionId ??
80
- sessionPromptSessionId(provider, box.id, options.turnId ?? options.executionId) ??
81
- randomUUID();
82
- const backend = {
83
- ...options.backend,
84
- metadata: { ...options.backend?.metadata, profileSecretIsolation: true },
85
- };
86
- const { runtimeSecrets: _turnOnly, ...persisted } = backend;
87
- const created = await awaitWithSignal(box.createSession({ sessionId, retention: "workspace", backend: persisted }), options.signal);
88
- if (created.session.id !== sessionId || created.info.id !== sessionId) {
89
- throw new Error("Tangle isolated session creation changed its exact identity");
130
+ if (before !== undefined) {
131
+ // First join any pre-ACK read; the second refresh necessarily begins after that ACK.
132
+ await awaitWithSignal(box.refresh?.(options.signal), options.signal);
133
+ await awaitWithSignal(box.refresh?.(options.signal), options.signal);
134
+ const current = requireProxyReceipt(proxySecretReceiptFromSandbox(box), selected, true);
135
+ if (!containsProxyReceipt(current, before) || current.bindings.length !== before.bindings.length)
136
+ throw new Error("Tangle proxy custody changed during profile preparation");
90
137
  }
91
138
  options.signal?.throwIfAborted();
92
- const { expectedPublicProfileRequestDigest, expectedSecretProfileReceipt } = await awaitWithSignal(box.prepareSecretProfileRevision({
93
- sessionId, backend,
94
- ...(options.model === undefined ? {} : { model: options.model }),
95
- }), options.signal);
96
- options.signal?.throwIfAborted();
97
- return { ...options, sessionId, backend, expectedPublicProfileRequestDigest, expectedSecretProfileReceipt };
139
+ return options;
140
+ function validatePrepared(raw) {
141
+ if (raw === undefined && native === undefined)
142
+ return;
143
+ const subset = ProxySecretReceiptSchema.parse(raw);
144
+ const expectedGroup = before?.bindings.filter(({ secretRef }) => secretRef.key === native?.secretEnv);
145
+ if (!before || subset.status !== "installed" || !subset.bindings.length || !containsProxyReceipt(before, subset) ||
146
+ (native !== undefined && (subset.bindings.length !== expectedGroup?.length ||
147
+ subset.bindings.some(({ secretRef }) => secretRef.key !== native.secretEnv))))
148
+ throw new Error("Tangle native HOME acknowledgement does not match current custody");
149
+ }
98
150
  }
99
- /** Canonical backend controls plus the legacy model aliases folded below. */
100
151
  const SANDBOX_BACKEND_FIELD_LIST = [
101
152
  "runtimeAttachments", "runtimeSecrets", "type", "profile", "model", "server", "interactions", "metadata",
102
153
  ];
103
154
  const SANDBOX_BACKEND_MODEL_FIELD_LIST = [
104
- "provider",
105
- "model",
106
- "apiKey",
107
- "baseUrl",
108
- "maxThinkingTokens",
109
- "mode",
110
- "apiKeyEnv",
111
- "cliAuth",
112
- "authMode",
113
- "authFiles",
114
- // Creation-only: the SDK normalizer refuses it on a turn.
115
- "routing",
155
+ "provider", "model", "apiKey", "baseUrl", "maxThinkingTokens", "mode",
156
+ "apiKeyEnv", "cliAuth", "authMode", "authFiles", "routing",
116
157
  ];
117
158
  const SANDBOX_BACKEND_MODEL_FIELDS = new Set(SANDBOX_BACKEND_MODEL_FIELD_LIST);
118
159
  const SANDBOX_BACKEND_FIELDS = new Set([...SANDBOX_BACKEND_FIELD_LIST,
119
160
  ...SANDBOX_BACKEND_MODEL_FIELD_LIST.map((field) => field === "model" ? "modelId" : field)]);
120
161
  const SANDBOX_AUTH_FILE_FIELD_LIST = ["path", "content", "mode"];
121
- /**
122
- * Read the per-turn backend options a caller sent through `providerOptions`.
123
- *
124
- * `AgentTurnInput.providerOptions.backend` is the exact shape agent-runtime
125
- * emits for a per-turn backend or model override, so refusing it dropped the
126
- * caller's model, profile, and session credential bundle at the adapter
127
- * boundary. Every field is checked against what the Sandbox prompt options
128
- * declare, and the result is bounded JSON the SDK reads once.
129
- */
162
+ /** Validate the exact per-turn backend projection. */
130
163
  export function backendFromTurnProviderOptions(providerOptions) {
131
164
  if (providerOptions === undefined)
132
165
  return undefined;
@@ -163,9 +196,7 @@ function sandboxPromptBackend(value) {
163
196
  ...(present.type === undefined
164
197
  ? {}
165
198
  : { type: boundedString(present.type, "Tangle prompt backend type") }),
166
- // The profile decides tools, permissions, mounts, and the security policy
167
- // of the turn, so it is read by the schema that owns those rules rather
168
- // than passed through as bounded JSON.
199
+ // The profile schema owns payload and security policy.
169
200
  ...(present.profile === undefined
170
201
  ? {}
171
202
  : { profile: agentProfileSchema.parse(present.profile) }),
@@ -287,7 +318,6 @@ function sandboxPromptInteractions(value) {
287
318
  }
288
319
  return interactions;
289
320
  }
290
- /** Sandbox caps trace attributes, and its own documentation forbids secrets there. */
291
321
  const MAX_TRACE_ATTRIBUTES = 32;
292
322
  const MAX_TRACE_ATTRIBUTE_KEY_LENGTH = 128;
293
323
  const MAX_TRACE_ATTRIBUTE_VALUE_LENGTH = 1_024;
@@ -359,22 +389,12 @@ function plainRecord(value, label) {
359
389
  }
360
390
  return value;
361
391
  }
362
- /**
363
- * The part of the backend options that decides which work a turn is.
364
- *
365
- * Bearer material is deliberately absent. A rotated seat token is the same
366
- * seat running the same work, so digesting the token bytes would make an
367
- * ordinary refresh conflict with the run it is continuing. The auth files are
368
- * reduced to the paths and modes they install, which states that the turn
369
- * carries a credential bundle and which slots it fills, without binding the
370
- * identity to the secret inside.
371
- */
392
+ /** Request identity excludes bearer bytes; auth files contribute only paths and modes. */
372
393
  export function backendRequestIdentity(backend) {
373
394
  if (backend === undefined)
374
395
  return undefined;
375
396
  const normalized = (normalizeRuntimeBackendConfig(backend, { allowRuntimeSecrets: true }) ?? {});
376
- // Sandbox message admission omits turn-only credentials from request identity;
377
- // the SDK/sidecar independently keys the executing backend by their values.
397
+ // Admission omits turn credentials; the executor independently binds their values.
378
398
  const { runtimeSecrets: _runtimeSecrets, ...identity } = normalized;
379
399
  const model = normalized.model;
380
400
  if (model === undefined)
@@ -395,7 +415,6 @@ export function backendRequestIdentity(backend) {
395
415
  },
396
416
  };
397
417
  }
398
- /** Project the exact turn profile once for both dispatch and retained identity. */
399
418
  export function backendFromTurnInput(input) {
400
419
  const declared = backendFromTurnProviderOptions(input.providerOptions);
401
420
  let backend = declared;
@@ -407,21 +426,12 @@ export function backendFromTurnInput(input) {
407
426
  if (declared?.type !== undefined && input.profile.harness !== undefined && declared.type !== input.profile.harness) {
408
427
  throw new Error("Tangle turn profile conflicts with its backend harness");
409
428
  }
410
- // Validate the complete projected backend, including the existing file/inline
411
- // payload bounds. The typed profile never becomes provider metadata.
429
+ // Validate payload bounds without turning the typed profile into metadata.
412
430
  backend = sandboxPromptBackend({ ...declared, profile: input.profile });
413
431
  }
414
432
  return backend;
415
433
  }
416
- /**
417
- * Combine the turn's requested interaction posture with its backend options.
418
- *
419
- * agent-runtime emits both: it maps `backend.interactions` onto the canonical
420
- * `AgentTurnInput.interactions` and carries the whole backend block through
421
- * `providerOptions`. The two must agree, and a disagreement is refused rather
422
- * than resolved by preference, because either answer would run the turn on a
423
- * posture the caller did not ask for.
424
- */
434
+ /** Canonical interaction controls and backend controls must agree. */
425
435
  function turnBackendOptions(input) {
426
436
  const backend = backendFromTurnInput(input);
427
437
  const backendModel = backend?.model?.model;
@@ -466,16 +476,13 @@ export function validatedSandboxPromptResult(result) {
466
476
  source.contextTransferReceipt === undefined) {
467
477
  throw new Error("Tangle prompt result returned a context receipt for a turn that requested no transfer");
468
478
  }
469
- // The Sandbox SDK materializes absent optional response fields as
470
- // `undefined`. They were absent on the JSON wire and must stay absent in the
471
- // provider-neutral result before the strict JSON check runs.
479
+ // Keep absent SDK fields absent through the strict JSON check.
472
480
  const record = projectAgentTerminalRecord(Object.fromEntries(Object.entries(source).filter(([field, value]) => value !== undefined || !SANDBOX_OPTIONAL_RESULT_FIELDS.has(field))));
473
481
  const content = boundedEventContentRecordSchema.safeParse(record);
474
482
  if (!content.success) {
475
483
  throw new Error("Tangle prompt result exceeded its JSON bound", { cause: content.error });
476
484
  }
477
- // Text is content. Identity, accounting and interaction state retain their
478
- // stricter metadata bounds. The projection does not mutate the native source.
485
+ // Content and metadata have separate bounds; source remains untouched.
479
486
  assertBoundedJson(Object.fromEntries(Object.entries(record).filter(([field]) => field !== "response" &&
480
487
  field !== "text" &&
481
488
  field !== "finalText")), "Tangle prompt result");
@@ -521,7 +528,6 @@ export function validatedSandboxPromptResult(result) {
521
528
  tokenUsageFromData(record);
522
529
  return record;
523
530
  }
524
- /** Statuses that mean the run is waiting for a human, not that it failed. */
525
531
  const AWAITING_STATUSES = new Set([
526
532
  "blocked_on_approval",
527
533
  "awaiting_question",
@@ -548,8 +554,7 @@ export function agentTurnResultFromPromptRecord(record, options = {}) {
548
554
  : typeof record.finalText === "string"
549
555
  ? record.finalText
550
556
  : "";
551
- // A receipt with no transfer behind it would let the caller record a handoff
552
- // that never happened, so it is refused rather than passed through.
557
+ // An unsolicited transfer receipt cannot establish a handoff.
553
558
  const hasContextTransferReceipt = Object.hasOwn(record, "contextTransferReceipt");
554
559
  if (hasContextTransferReceipt && options.contextTransferRequested !== true) {
555
560
  throw new Error("Tangle prompt result returned a context receipt for a turn that requested no transfer");
@@ -566,8 +571,7 @@ export function agentTurnResultFromPromptRecord(record, options = {}) {
566
571
  !contextTransferResultMatchesRequest(options.contextTransferRequest, contextTransferReceipt.data)) {
567
572
  throw new Error("Tangle prompt result context receipt does not match its request");
568
573
  }
569
- // The harness's own subscription quota is spent: the same typed refusal the
570
- // credential owner gives before dispatch, with when it resets.
574
+ // Preserve the credential owner's typed quota refusal and reset time.
571
575
  if (!record.success && record.errorCode === "provider_quota_exhausted") {
572
576
  const resetAt = record.resetAt;
573
577
  throw new TangleCredentialCapacityError("provider_quota_exhausted", "exhausted", typeof resetAt === "string" && new Date(resetAt).toISOString() === resetAt ? resetAt : undefined, 429);
@@ -580,9 +584,7 @@ export function agentTurnResultFromPromptRecord(record, options = {}) {
580
584
  ...(options.sessionId ? { sessionId: options.sessionId } : {}),
581
585
  ...(typeof record.error === "string" ? { error: record.error } : {}),
582
586
  ...(usage ? { usage } : {}),
583
- // A waiting run is not a terminal failure. Dropping the status here made
584
- // "the agent is asking you something" indistinguishable from "the turn
585
- // failed", while the sandbox stayed alive waiting for an answer.
587
+ // Waiting for a human retains its live status.
586
588
  metadata: {
587
589
  ...(controlRef
588
590
  ? {
@@ -1,12 +1,12 @@
1
1
  import { AgentEnvironmentCapabilitiesSchema, AgentEnvironmentGetOptionsSchema, createAgentEnvironmentWithIdempotency, } from "@tangle-network/agent-interface/environment-provider";
2
2
  import { canonicalCandidateDigest, deepFreeze, harnessTypeSchema } from "@tangle-network/agent-interface";
3
- import { createTangleExactProcessProvider, } from "./exact-process.js";
3
+ import { createTangleExactProcessProvider } from "./exact-process.js";
4
4
  import { capabilitiesForClient, defaultTangleSandboxCapabilities, narrowTangleCapabilitiesToBackend, } from "./tangle-capabilities.js";
5
5
  import { sandboxInstanceAsEnvironment } from "./tangle-environment.js";
6
6
  import { tangleProfileValidator } from "./tangle-profile-validation.js";
7
7
  import { confidentialVerifierOption, createTangleWorkspaceBranching, } from "./tangle-workspace-branching.js";
8
8
  import { assertCreateInputShape, assertMappedCreateOptions, assertMappedSecretNames, assertNoInlineSecretValues, captureModelCredentials, createRoutingFromProviderOptions, NATIVE_RESUME_CHECKPOINT_METADATA_KEY, sandboxOptionsFromCreateInput, sandboxRestoreFromCheckpoint } from "./tangle-create-options.js";
9
- import { captureProxySecrets, mergeProxySecrets, proxySecretsFromInput, sandboxSecretBindingIdentity, sandboxSecretBindings, PROXY_SECRETS_METADATA_KEY } from "./tangle-proxy-secrets.js";
9
+ import { captureProxySecrets, mergeProxySecrets, proxySecretsFromInput, assertProxySecretAliases, sandboxSecretBindingIdentity, PROXY_SECRETS_METADATA_KEY } from "./tangle-proxy-secrets.js";
10
10
  import { statusFromUnknown } from "./tangle-environment-values.js";
11
11
  import { normalizeTangleBackend } from "./tangle-prompt.js";
12
12
  import { requireNativeCaptureCapability, requireNativeCaptureProof } from "./tangle-native-capture-proof.js";
@@ -72,9 +72,6 @@ export function createTangleProvider(options) {
72
72
  configured = { ...configured, profile: { ...configured.profile },
73
73
  ...(configured.create === undefined ? {} : { create: { ...configured.create } }),
74
74
  };
75
- delete configured.profile.proxySecrets;
76
- if (configured.create !== undefined)
77
- delete configured.create.proxySecrets;
78
75
  if (configured.create?.workspaceSnapshot === true) {
79
76
  throw new Error("Tangle provider does not support portable workspace snapshots in this receiver deployment");
80
77
  }
@@ -112,7 +109,9 @@ export function createTangleProvider(options) {
112
109
  throw new Error("Tangle owns metadata.tangleProxySecrets");
113
110
  }
114
111
  const requestedProxySecrets = proxySecretsFromInput(input);
115
- const requestedSecrets = structuredClone(sandboxSecretBindings(input.secrets, requestedProxySecrets, input.env));
112
+ assertProxySecretAliases(requestedProxySecrets, input.env, input.secrets);
113
+ const requestedSecrets = structuredClone(Array.isArray(input.secrets) ? input.secrets : undefined);
114
+ const requestedReason = requestedSecrets?.some((entry) => typeof entry !== "string" && "exposeInBox" in entry) ? input.metadata?.reason : undefined;
116
115
  const credentialSource = typeof input.profile === "string" ? "managed" : profileCredentialSource(input.profile);
117
116
  const subscription = credentialSource === "subscription";
118
117
  if (Object.hasOwn(input.metadata ?? {}, "modelCredentials")) {
@@ -140,12 +139,13 @@ export function createTangleProvider(options) {
140
139
  const mappedInput = mapCreateInput?.(input) ??
141
140
  (subscription && resolveModelCredentials !== undefined ? sandboxOptionsFromCreateInput(input, options.defaultBackend, parsedWorkspace, selectedCredentials, true) : defaultOptions);
142
141
  const selectedProxySecrets = mergeProxySecrets(requestedProxySecrets, selectedCredentials?.proxySecrets);
143
- if (mappedInput.proxySecrets !== undefined && canonicalCandidateDigest(mappedInput.proxySecrets) !== canonicalCandidateDigest(selectedProxySecrets)) {
142
+ const mappedProxySecrets = mergeProxySecrets(selectedProxySecrets, proxySecretsFromInput({ profile: mappedInput.backend?.profile ?? {}, proxySecrets: mappedInput.proxySecrets }));
143
+ if (canonicalCandidateDigest(mappedProxySecrets ?? []) !== canonicalCandidateDigest(selectedProxySecrets ?? []))
144
144
  throw new Error("Tangle mapped proxy-secret declarations differ from the requested bindings");
145
- }
146
- const { proxySecrets: _legacy, secrets: selection, ...mapped } = { ...mappedInput, backend: normalizeTangleBackend(mappedInput.backend, true) };
147
- const secrets = sandboxSecretBindings(selection, selectedProxySecrets, mapped.env);
148
- const mappedOptions = { ...mapped, ...(secrets === undefined ? {} : { secrets }) };
145
+ const mappedOptions = { ...mappedInput, backend: normalizeTangleBackend(mappedInput.backend, true), ...(selectedProxySecrets === undefined ? {} : { proxySecrets: selectedProxySecrets }) };
146
+ assertProxySecretAliases(selectedProxySecrets, mappedOptions.env, mappedOptions.secrets);
147
+ if (input.secrets === "all" && mappedOptions.secrets !== "all")
148
+ throw new Error("Tangle mapped secrets must preserve all selection");
149
149
  for (const entry of requestedSecrets ?? []) {
150
150
  if (typeof entry === "string")
151
151
  continue;
@@ -153,6 +153,8 @@ export function createTangleProvider(options) {
153
153
  throw new Error("Tangle mapped secrets must preserve the requested delivery selection");
154
154
  }
155
155
  }
156
+ if (requestedReason !== undefined && canonicalCandidateDigest(mappedOptions.metadata?.reason ?? null) !== canonicalCandidateDigest(requestedReason))
157
+ throw new Error("Tangle mapped raw consent must preserve its named reason");
156
158
  assertMappedCreateOptions(mappedOptions);
157
159
  const mappedRouting = mappedOptions.backend?.model?.routing;
158
160
  if (canonicalCandidateDigest(mappedRouting ?? null) !== canonicalCandidateDigest(requestedRouting ?? null)) {
@@ -1,11 +1,9 @@
1
1
  import { type CreateAgentEnvironmentInput, type ProxySecretBinding } from "@tangle-network/agent-interface/environment-provider";
2
- import type { TangleCreateSandboxOptions } from "./tangle-types.js";
3
2
  /** Provider-owned public declarations bind recovery; they contain no authority or values. */
4
3
  export declare const PROXY_SECRETS_METADATA_KEY = "tangleProxySecrets";
5
4
  export declare function captureProxySecrets(value: unknown): ProxySecretBinding[];
6
5
  export declare function proxySecretsFromInput(input: CreateAgentEnvironmentInput): ProxySecretBinding[] | undefined;
7
6
  export declare function mergeProxySecrets(requested: ProxySecretBinding[] | undefined, selected: ProxySecretBinding[] | undefined): ProxySecretBinding[] | undefined;
8
7
  export declare function assertProxySecretAliases(bindings: ProxySecretBinding[] | undefined, env: Record<string, string> | undefined, secrets: unknown): void;
9
- /** Lower portable declarations to the single host binding actually served by Sandbox. */
10
- export declare function sandboxSecretBindings(secrets: CreateAgentEnvironmentInput["secrets"] | "all", bindings?: readonly ProxySecretBinding[], env?: Record<string, string>): Exclude<TangleCreateSandboxOptions["secrets"], "all">;
8
+ /** Legacy selection identity stays at the compatibility boundary. */
11
9
  export declare const sandboxSecretBindingIdentity: (entry: Extract<CreateAgentEnvironmentInput["secrets"], unknown[]>[number]) => string;
@@ -1,6 +1,5 @@
1
1
  import { ProxySecretsSchema, mergeProxySecretBindings } from "@tangle-network/agent-interface/environment-provider";
2
2
  import { canonicalCandidateDigest, deepFreeze } from "@tangle-network/agent-interface";
3
- import { boundedIdentifier, MAX_ARRAY_LENGTH } from "./tangle-contract-safety.js";
4
3
  /** Provider-owned public declarations bind recovery; they contain no authority or values. */
5
4
  export const PROXY_SECRETS_METADATA_KEY = "tangleProxySecrets";
6
5
  export function captureProxySecrets(value) {
@@ -17,52 +16,23 @@ export function mergeProxySecrets(requested, selected) {
17
16
  ? undefined : deepFreeze(mergeProxySecretBindings(requested, selected));
18
17
  }
19
18
  export function assertProxySecretAliases(bindings, env, secrets) {
20
- if (bindings !== undefined && secrets !== undefined && !Array.isArray(secrets))
21
- throw new Error("Tangle proxy-secret custody cannot use all or raw readable secret selection");
22
19
  for (const binding of bindings ?? []) {
23
20
  for (const alias of [binding.envName, binding.secretRef.key]) {
24
- if (Object.hasOwn(env ?? {}, alias) || (Array.isArray(secrets) && secrets.some((entry) => typeof entry === "string" ? entry === alias : entry?.name === alias && "exposeInBox" in entry))) {
25
- throw new Error("Tangle proxy-secret reference or alias cannot receive raw readable secret delivery");
21
+ if (Object.hasOwn(env ?? {}, alias) || (Array.isArray(secrets) && secrets.some((entry) => {
22
+ if (typeof entry === "string" || entry?.name !== alias)
23
+ return false;
24
+ if ("exposeInBox" in entry)
25
+ return true;
26
+ if (!("host" in entry))
27
+ return false;
28
+ const header = (entry.header ?? "Authorization").toLowerCase();
29
+ return !binding.hosts.includes(entry.host) || binding.presentation.type === "query" ||
30
+ header !== (binding.presentation.type === "header" ? binding.presentation.name.toLowerCase() : "authorization");
31
+ }))) {
32
+ throw new Error("Tangle proxy-secret scope conflicts with readable or legacy delivery");
26
33
  }
27
34
  }
28
35
  }
29
36
  }
30
- /** Lower portable declarations to the single host binding actually served by Sandbox. */
31
- export function sandboxSecretBindings(secrets, bindings, env) {
32
- assertProxySecretAliases(bindings === undefined ? undefined : [...bindings], env, secrets);
33
- const lowered = (bindings ?? []).map((binding) => {
34
- if (binding.hosts.length !== 1 || binding.methods !== undefined || binding.paths !== undefined ||
35
- binding.presentation.type === "query" || binding.placeholderFormat === "jwt" ||
36
- binding.ttlSeconds !== undefined || binding.envName !== binding.secretRef.key) {
37
- throw new Error("Tangle host bindings cannot enforce aliases, multiple hosts, methods, paths, query, jwt or expiry");
38
- }
39
- return { name: binding.secretRef.key, host: binding.hosts[0],
40
- header: binding.presentation.type === "header" ? binding.presentation.name : "Authorization" };
41
- });
42
- if (secrets === undefined && bindings === undefined)
43
- return undefined;
44
- if (secrets !== undefined && !Array.isArray(secrets))
45
- throw new Error("Tangle secrets must be stored names or host bindings");
46
- const entries = new Map();
47
- for (const entry of [...(secrets ?? []), ...lowered]) {
48
- const name = typeof entry === "string" ? entry : entry.name;
49
- boundedIdentifier(name, "Tangle stored-secret name");
50
- if (typeof entry !== "string") {
51
- if (("host" in entry ? Object.keys(entry).some((key) => !["name", "host", "header"].includes(key)) ||
52
- typeof entry.host !== "string" || entry.host.length > 253 ||
53
- !/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z](?:[a-z0-9-]{0,61}[a-z0-9])?$/.test(entry.host) ||
54
- (entry.header !== undefined && (typeof entry.header !== "string" || !/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/.test(entry.header))) :
55
- Object.keys(entry).some((key) => !["name", "exposeInBox"].includes(key)) || entry.exposeInBox !== true) ||
56
- Object.hasOwn(env ?? {}, name))
57
- throw new Error("Invalid or shadowed Tangle secret selection");
58
- }
59
- const previous = entries.get(name);
60
- if (previous !== undefined && sandboxSecretBindingIdentity(previous) !== sandboxSecretBindingIdentity(entry))
61
- throw new Error("Conflicting Tangle secret delivery");
62
- entries.set(name, entry);
63
- }
64
- if (entries.size > MAX_ARRAY_LENGTH)
65
- throw new Error("Tangle stored-secret selection exceeds its bound");
66
- return [...entries.values()];
67
- }
37
+ /** Legacy selection identity stays at the compatibility boundary. */
68
38
  export const sandboxSecretBindingIdentity = (entry) => canonicalCandidateDigest(typeof entry !== "string" && "host" in entry ? { ...entry, header: (entry.header ?? "Authorization").toLowerCase() } : entry);
@@ -1,7 +1,7 @@
1
1
  import type { CliAuthReference } from "@tangle-network/sandbox/auth";
2
2
  import type { BackendConfig, BackendRegistryEntry, BackendRegistryResponse, BackendType, CreateSandboxOptions, ExecResult as SandboxExecResult, PromptOptions, PromptResult, SandboxInstance, SandboxEvent } from "@tangle-network/sandbox";
3
3
  import type { AgentRunCancellationAcknowledgement, AgentRunCancellationRequest, AgentInteractiveSessionControlClaim, AgentInteractiveSessionControlClaimAcknowledgement, AgentInteractiveSessionControlClaimRequest, AgentInteractiveSessionAttach, AgentInteractiveSessionPromptAcknowledgement, AgentInteractiveSessionPromptCommand, AgentInteractiveSessionRef, AgentInteractiveSessionStart, AgentInteractiveSessionStatus, AgentInteractiveSessionStopAcknowledgement, AgentInteractiveSessionStopCommand, AgentInteractiveTerminalSession, ConfidentialAttestation, ConfidentialExecutionEnvironment, InputPart, InteractionRequest, InteractionResponseCommand } from "@tangle-network/agent-interface";
4
- import type { AgentEnvironmentCapabilities, AgentEnvironmentProvider, CreateAgentEnvironmentInput, ProxySecretBinding, ProxySecretCapabilities, ProxySecretReceipt } from "@tangle-network/agent-interface/environment-provider";
4
+ import type { AgentEnvironmentCapabilities, AgentEnvironmentProvider, CreateAgentEnvironmentInput, ProxySecretBinding, ProxySecretCapabilities } from "@tangle-network/agent-interface/environment-provider";
5
5
  /**
6
6
  * The platform verdict for the create call that returned a sandbox.
7
7
  * `created` means the call allocated the sandbox; `idempotent_replay` means an
@@ -19,17 +19,16 @@ export interface SandboxCreateReceiptLike {
19
19
  outcome: "created" | "idempotent_replay" | "unknown";
20
20
  idempotencyKeyApplied: boolean;
21
21
  captureProof?: NativeCaptureProofLike;
22
- proxySecretReceipt?: ProxySecretReceipt;
23
22
  }
24
23
  export interface TangleExactProcessOptions {
25
24
  teamId?: string;
26
25
  }
27
- export type TangleCreateSandboxOptions = Omit<CreateSandboxOptions, "secrets" | "backend"> & {
26
+ export type TangleCreateSandboxOptions = Omit<CreateSandboxOptions, "secrets" | "backend" | "proxySecrets"> & {
28
27
  backend?: BackendConfig & Omit<NonNullable<BackendConfig["model"]>, "model"> & {
29
28
  modelId?: string;
30
29
  };
31
30
  secrets?: "all" | Extract<CreateAgentEnvironmentInput["secrets"], unknown[]>;
32
- proxySecrets?: ProxySecretBinding[];
31
+ proxySecrets?: CreateAgentEnvironmentInput["proxySecrets"];
33
32
  };
34
33
  export interface SandboxClientLike {
35
34
  readonly secrets?: AgentEnvironmentProvider["secrets"];
@@ -85,14 +84,7 @@ export interface SandboxAccountUsageLike {
85
84
  periodStart: Date | string;
86
85
  periodEnd: Date | string;
87
86
  }
88
- /**
89
- * The subscription fields the observation reads.
90
- *
91
- * `creditsAvailableUsd` can be negative on an overage plan, and
92
- * `maxConcurrentSandboxes` is 0 when the account has no ceiling. Neither value
93
- * fits the contract's non-negative credit and quota shapes, so the observation
94
- * reports those two cases as unavailable instead of clamping them.
95
- */
87
+ /** Observation omits negative credit and unlimited concurrency instead of clamping them. */
96
88
  export interface SandboxSubscriptionLike {
97
89
  plan: string;
98
90
  creditsAvailableUsd: number;
@@ -417,6 +409,8 @@ export interface SandboxInteractiveSessionLike {
417
409
  export interface SandboxInstanceLike {
418
410
  id: string;
419
411
  createSession?: SandboxInstance["createSession"];
412
+ readonly proxySecretReceipt?: SandboxInstance["proxySecretReceipt"];
413
+ preparePublicProfileRevision?: SandboxInstance["preparePublicProfileRevision"];
420
414
  prepareSecretProfileRevision?: SandboxInstance["prepareSecretProfileRevision"];
421
415
  name?: string;
422
416
  status?: unknown;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tangle-network/agent-provider-tangle",
3
- "version": "4.5.7",
3
+ "version": "5.0.1",
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.7"
36
+ "@tangle-network/agent-interface": "^5.10.9"
37
37
  },
38
38
  "peerDependencies": {
39
- "@tangle-network/sandbox": ">=0.60.88 <2.0.0"
39
+ "@tangle-network/sandbox": ">=1.0.125 <2.0.0"
40
40
  },
41
41
  "peerDependenciesMeta": {
42
42
  "@tangle-network/sandbox": {
@@ -46,7 +46,7 @@
46
46
  "devDependencies": {
47
47
  "@tangle-network/agent-provider-testkit": "0.12.1",
48
48
  "@tangle-network/agent-runtime": "0.349.0",
49
- "@tangle-network/sandbox": "0.66.4",
49
+ "@tangle-network/sandbox": "1.0.125",
50
50
  "@types/node": "26.6.5",
51
51
  "typescript": "6.0.3",
52
52
  "vitest": "5.0.5"