@tangle-network/agent-provider-tangle 4.5.6 → 5.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -66,12 +66,17 @@ Aggregate limits, credential exclusions, and exact native-session proof remain e
66
66
  Capture lists no directory below a credential directory such as `.opencode` or `.config`: it records the directory as excluded and accounts for its subtree with one complete usage scan, so the workspace totals still reconcile.
67
67
  An unsupported downloader or incomplete transfer fails capture and preserves the source environment.
68
68
 
69
+ ## Profile credentials
70
+
71
+ Declare proxy-held credentials in `profile.proxySecrets` or create input `proxySecrets` using the same `ProxySecretsSchema`. The Provider forwards the full declaration unchanged, including aliases, destinations, methods, paths, presentation and expiry. Trusted Sandbox resolution owns tenant authorization, stored identity and proxy installation. The SDK transport must support the top-level canonical field.
72
+
73
+ Legacy stored names, `"all"` and host objects retain their delivery selection. The API binds known hosts or preserves prior delivery for unbound names; explicit canonical scope governs protected names. Explicit readable requests use the existing `{name, exposeInBox:true}` consent and `metadata.reason` or a retained store reason. A mapper cannot replace authored custody or erase its reason. Source and local HTTP proof do not establish deployed proxy enforcement.
74
+
69
75
  ## Named model credentials at creation
70
76
 
71
77
  `modelCredentials` sends a stored credential reference and explicit endpoint before Sandbox provisions the backend.
72
78
  This uses Sandbox's existing caller-owned model credential path instead of requesting a managed Router credential.
73
- The provider does not create, copy, or renew stored secrets.
74
- The Provider grants the selected reference at create, alongside unrelated caller-requested secrets. Qualified native selectors also grant their selected reference before each fresh turn.
79
+ The provider does not create, copy, or renew stored secrets. The Provider forwards the selected reference at create, alongside unrelated caller-requested secrets. Qualified native selectors also grant their selected reference before each fresh turn.
75
80
 
76
81
  ```ts
77
82
  const provider = createTangleProvider({
@@ -86,8 +91,7 @@ const environment = await provider.create({
86
91
  });
87
92
  ```
88
93
 
89
- The configuration accepts only the reference and endpoint, not credential values or model selection.
90
- The authored profile, selected backend, runtime attachments, and create identity remain unchanged.
94
+ The configuration accepts only the reference and endpoint, not credential values or model selection. The authored profile, selected backend, runtime attachments, and create identity remain unchanged.
91
95
  The provider snapshots this configuration when constructed and refuses combining it with `mapCreateInput`.
92
96
  Omitting it preserves managed creation.
93
97
  The endpoint must use HTTP or HTTPS without credentials, query parameters, or fragments.
@@ -147,20 +151,16 @@ The Provider validates native channels with the maintained CLI Registry before p
147
151
  Each selector must use the exact profile harness.
148
152
  Native execution also requires the selected container to report `cliAuthReferences: true`.
149
153
  A missing or unreadable capability refuses creation or dispatch before inference.
150
- A selector grants its one selected stored secret automatically, alongside unrelated secrets requested by the caller.
154
+ Native selectors retain their existing selected stored name beside unrelated requests; the native owner controls resolution and bundle delivery.
151
155
  Keep pool-wide account credentials out of the create input's `secrets` list.
152
- Static native references grant their selected secret only for subscription profiles.
153
- Static API references grant their selected secret for unmarked legacy profiles and subscription profiles.
154
- Inline environment values cannot shadow the selected stored secret.
155
- Undefined, malformed, unsupported, or failed subscription selections stop before Sandbox creation.
156
+ Static native references select their credential only for subscription profiles. Static API references grant their selected secret for unmarked legacy profiles and subscription profiles.
157
+ Inline environment values cannot shadow the selected stored secret. Undefined, malformed, unsupported, or failed subscription selections stop before Sandbox creation.
156
158
  Subscription failures never fall back to managed Router access.
157
159
 
158
- Sandbox metadata records the public selection under `modelCredentials`.
159
- This metadata key is reserved for the Provider selection.
160
+ Sandbox metadata records the public selection under `modelCredentials`. This metadata key is reserved for the Provider selection.
160
161
  Account labels are supplied bindings, not verified native principals.
161
162
  Token values and native credential files never enter that selection or receipt.
162
- A static native reference stays bound to its creation account and harness on every turn.
163
- Reconstructed environments recover that reference from persisted metadata and the observed backend.
163
+ A static native reference stays bound to its creation account and harness on every turn. Reconstructed environments recover that reference from persisted metadata and the observed backend.
164
164
 
165
165
  A resolver selects a bootstrap credential at creation and a durable binding for each fresh turn.
166
166
  Fresh turns require the exact inline subscription profile and a stable `turnId`.
@@ -1,4 +1,4 @@
1
- import { type BackendType, type CreateSandboxOptions, type RouterRoutingOptions } from "@tangle-network/sandbox";
1
+ import { type BackendType, type RouterRoutingOptions } from "@tangle-network/sandbox";
2
2
  import type { CreateAgentEnvironmentInput, WorkspaceRequest } from "@tangle-network/agent-interface/environment-provider";
3
3
  import type { TangleCreateSandboxOptions, TangleModelCredentials } from "./tangle-types.js";
4
4
  /** Immutable create evidence used to bind a later native resume to its restored snapshot. */
@@ -30,8 +30,11 @@ export declare function sandboxRestoreFromCheckpoint(checkpoint: WorkspaceReques
30
30
  } | undefined;
31
31
  /** Reject value-bearing secret maps before any custom mapper can drop them. */
32
32
  export declare function assertNoInlineSecretValues(input: CreateAgentEnvironmentInput, parsedWorkspace?: WorkspaceRequest): void;
33
- /** Validate mapped stored names and bindings without resolving their values. */
34
- export declare function assertMappedSecretNames(options: CreateSandboxOptions): void;
33
+ /** Preserve legacy stored selections while canonical declarations travel separately. */
34
+ export declare function assertMappedSecretNames(options: {
35
+ secrets?: unknown;
36
+ env?: Record<string, string>;
37
+ }): void;
35
38
  export declare function assertCreateInputShape(input: CreateAgentEnvironmentInput, parsedWorkspace?: WorkspaceRequest): WorkspaceRequest | undefined;
36
39
  export declare function assertMappedCreateOptions(options: TangleCreateSandboxOptions): void;
37
40
  export {};
@@ -6,7 +6,7 @@ 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
8
  import { deepFreeze } from "@tangle-network/agent-interface";
9
- import { assertProxySecretAliases, captureProxySecrets, mergeProxySecrets, proxySecretsFromInput, sandboxSecretBindings } from "./tangle-proxy-secrets.js";
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";
12
12
  export function captureModelCredentials(value) {
@@ -99,9 +99,8 @@ export function sandboxOptionsFromCreateInput(input, defaultBackend, parsedWorks
99
99
  ? parseBackendType(defaultBackend ?? profile.harness ?? "opencode")
100
100
  : input.backend;
101
101
  assertNoInlineSecretValues(input, workspace);
102
- const selectedSecret = modelCredentials === undefined ? undefined
103
- : "cliAuth" in modelCredentials ? modelCredentials.cliAuth?.secretEnv : modelCredentials.apiKeyEnv;
104
102
  const nativeCredentials = modelCredentials !== undefined && "cliAuth" in modelCredentials;
103
+ const selectedSecret = nativeCredentials ? modelCredentials.cliAuth?.secretEnv : modelCredentials?.apiKeyEnv;
105
104
  const proxySecrets = mergeProxySecrets(proxySecretsFromInput(input), modelCredentials?.proxySecrets);
106
105
  assertProxySecretAliases(proxySecrets, input.env, input.secrets);
107
106
  const proxySelected = proxySecrets?.some((binding) => binding.envName === selectedSecret || binding.secretRef.key === selectedSecret) === true ||
@@ -123,13 +122,11 @@ export function sandboxOptionsFromCreateInput(input, defaultBackend, parsedWorks
123
122
  throw new Error("Tangle modelCredentials cannot shadow a stored secret with inline environment data");
124
123
  }
125
124
  const requestedSecrets = Array.isArray(input.secrets) ? input.secrets : undefined;
126
- const requestedSelection = selectedSecret !== undefined && !proxySelected
125
+ const secrets = input.secrets === "all" ? "all" : selectedSecret !== undefined && !proxySelected
127
126
  ? [...new Set([...(requestedSecrets ?? []), selectedSecret])]
128
127
  : requestedSecrets ?? (proxySecrets === undefined ? undefined : []);
129
- const secrets = sandboxSecretBindings(requestedSelection, proxySecrets, input.env);
130
- if (secrets !== undefined && secrets.length > MAX_ARRAY_LENGTH) {
128
+ if (Array.isArray(secrets) && secrets.length > MAX_ARRAY_LENGTH)
131
129
  throw new Error("Tangle selected credential exceeds the stored-secret grant bound");
132
- }
133
130
  const recordsCredential = nativeCredentials || subscriptionSelection;
134
131
  if (recordsCredential && Object.hasOwn(input.metadata ?? {}, "modelCredentials")) {
135
132
  throw new Error("Tangle credential selection owns metadata.modelCredentials");
@@ -193,7 +190,8 @@ export function sandboxOptionsFromCreateInput(input, defaultBackend, parsedWorks
193
190
  ...(resources ? { resources } : {}),
194
191
  ...(restore ?? {}),
195
192
  ...(input.env ? { env: input.env } : {}),
196
- ...(Array.isArray(secrets) ? { secrets } : {}),
193
+ ...(secrets === undefined ? {} : { secrets }),
194
+ ...(proxySecrets === undefined ? {} : { proxySecrets }),
197
195
  ...(input.egress === undefined ? {} : { egressPolicy: sandboxEgressPolicy(input.egress) }),
198
196
  ...(input.billingOwner === undefined ? {} : { billingOwnerId: input.billingOwner }),
199
197
  ...(Object.keys(metadata).length > 0 ? { metadata } : {}),
@@ -228,18 +226,7 @@ export function sandboxRestoreFromCheckpoint(checkpoint) {
228
226
  fromSandboxId: boundedIdentifier(checkpoint.source.environmentId, "Tangle workspace checkpoint source"),
229
227
  };
230
228
  }
231
- /**
232
- * Project the portable egress policy onto the Sandbox policy.
233
- *
234
- * The schema is a strict discriminated union, so a domain list outside `strict` is refused rather
235
- * than sent: Sandbox IGNORES `allowDomains` in `open` and `blocked` mode, and a silently ignored
236
- * allowlist is a policy the caller believes is in force and is not.
237
- *
238
- * `includeImplicitDomains` stays unset, which is the Sandbox default of false. A strict policy
239
- * therefore reaches the named domains plus the model endpoints the platform provisioned, matching
240
- * what {@link AgentEnvironmentEgressPolicy} states; opting in would silently add ~40 hosts,
241
- * including public source hosts.
242
- */
229
+ /** Strict allowlists remain exact; implicit domains stay disabled. */
243
230
  function sandboxEgressPolicy(policy) {
244
231
  const parsed = AgentEnvironmentEgressPolicySchema.parse(policy);
245
232
  if (parsed.mode !== "strict")
@@ -267,13 +254,31 @@ export function assertNoInlineSecretValues(input, parsedWorkspace) {
267
254
  throw new Error("Tangle resource providerOptions are not supported");
268
255
  }
269
256
  }
270
- sandboxSecretBindings(input.secrets, undefined, input.env);
257
+ assertMappedSecretNames(input);
271
258
  }
272
- /** Validate mapped stored names and bindings without resolving their values. */
259
+ /** Preserve legacy stored selections while canonical declarations travel separately. */
273
260
  export function assertMappedSecretNames(options) {
274
- if (options.secrets === "all")
275
- throw new Error("Tangle mapped secrets require explicit selection");
276
- sandboxSecretBindings(options.secrets, undefined, options.env);
261
+ const { secrets, env } = options;
262
+ if (secrets === undefined || secrets === "all")
263
+ return;
264
+ if (!Array.isArray(secrets) || secrets.length > MAX_ARRAY_LENGTH)
265
+ throw new Error("Tangle secrets require bounded explicit stored selection");
266
+ const selected = new Map();
267
+ for (const entry of secrets) {
268
+ const name = typeof entry === "string" ? entry : entry?.name;
269
+ boundedIdentifier(name, "Tangle stored-secret name");
270
+ if (typeof entry !== "string" && (!entry || Object.hasOwn(env ?? {}, name) || ("host" in entry
271
+ ? Object.keys(entry).some((key) => !["name", "host", "header"].includes(key)) ||
272
+ typeof entry.host !== "string" || entry.host.length > 253 ||
273
+ !/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z](?:[a-z0-9-]{0,61}[a-z0-9])?$/.test(entry.host) ||
274
+ (entry.header !== undefined && (typeof entry.header !== "string" || !/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/.test(entry.header)))
275
+ : Object.keys(entry).some((key) => !["name", "exposeInBox"].includes(key)) || entry.exposeInBox !== true)))
276
+ throw new Error("Invalid or shadowed Tangle secret selection");
277
+ const identity = sandboxSecretBindingIdentity(entry);
278
+ if (selected.has(name) && selected.get(name) !== identity)
279
+ throw new Error("Conflicting Tangle stored-secret selection");
280
+ selected.set(name, identity);
281
+ }
277
282
  }
278
283
  export function assertCreateInputShape(input, parsedWorkspace) {
279
284
  if (!input || typeof input !== "object" || Array.isArray(input)) {
@@ -345,9 +350,9 @@ export function assertMappedCreateOptions(options) {
345
350
  throw new Error("Tangle mapped native credentials must use the exact profile harness");
346
351
  }
347
352
  const selectedSecret = options.backend.model.cliAuth.secretEnv;
348
- if (!Array.isArray(options.secrets) || !options.secrets.some((entry) => (typeof entry === "string" ? entry : entry.name) === selectedSecret)) {
349
- throw new Error("Tangle mapped native credential must be explicitly listed in create secrets");
350
- }
353
+ if (options.secrets !== "all" && !(Array.isArray(options.secrets) && options.secrets.some((entry) => (typeof entry === "string" ? entry : entry.name) === selectedSecret)) &&
354
+ !options.proxySecrets?.some((binding) => binding.envName === selectedSecret || binding.secretRef.key === selectedSecret))
355
+ throw new Error("Tangle mapped native credential must retain its stored selection");
351
356
  if (Object.hasOwn(options.env ?? {}, selectedSecret)) {
352
357
  throw new Error("Tangle mapped native credential cannot shadow a stored secret with inline environment data");
353
358
  }
@@ -11,36 +11,16 @@ export declare function promptOptionsFromTurnInput(input: AgentTurnInput, target
11
11
  }): PromptOptions;
12
12
  /** The SDK owns isolated session creation and the executor's private admission receipt. */
13
13
  export declare function preparePromptOptions(box: SandboxInstanceLike | undefined, options: PromptOptions, provider: string): Promise<PromptOptions>;
14
- /**
15
- * The `BackendConfig` fields this adapter forwards to Sandbox prompt options.
16
- *
17
- * A turn may carry any of them and nothing else. An undeclared field is
18
- * refused instead of forwarded, because the SDK drops what it does not
19
- * declare: the turn would then run on different settings with no error
20
- * anywhere, which is the silent substitution the SDK's own `model` field
21
- * exists to prevent.
22
- */
23
- declare const SANDBOX_BACKEND_FIELD_LIST: readonly ["runtimeAttachments", "runtimeSecrets", "modelId", "provider", "apiKey", "baseUrl", "maxThinkingTokens", "mode", "apiKeyEnv", "cliAuth", "authMode", "authFiles", "type", "profile", "model", "server", "interactions", "metadata", "routing"];
24
- /**
25
- * The `BackendConfig["model"]` fields the Sandbox prompt options declare.
26
- *
27
- * This is the block that carries per-turn credentials — `authMode: "oauth"`
28
- * with `authFiles` for a subscription seat — so it is checked field by field
29
- * rather than passed through as opaque JSON.
30
- */
14
+ /** Canonical backend controls plus the legacy model aliases folded below. */
15
+ declare const SANDBOX_BACKEND_FIELD_LIST: readonly ["runtimeAttachments", "runtimeSecrets", "type", "profile", "model", "server", "interactions", "metadata"];
31
16
  declare const SANDBOX_BACKEND_MODEL_FIELD_LIST: readonly ["provider", "model", "apiKey", "baseUrl", "maxThinkingTokens", "mode", "apiKeyEnv", "cliAuth", "authMode", "authFiles", "routing"];
32
- /**
33
- * These lists cover the SDK's field sets, restated as values because a
34
- * TypeScript type cannot be read at run time. This pin keeps them exact in
35
- * both directions: a field the SDK adds, renames, or removes fails the build
36
- * here rather than reaching a caller as a wrong refusal or a silent drop.
37
- */
17
+ /** SDK canonical fields stay exhaustive; legacy aliases are explicitly projected into model. */
38
18
  type Exhaustive<T extends never> = T;
39
19
  type SandboxBackendModel = NonNullable<BackendConfig["model"]>;
40
20
  declare const SANDBOX_AUTH_FILE_FIELD_LIST: readonly ["path", "content", "mode"];
41
21
  type SandboxAuthFile = NonNullable<SandboxBackendModel["authFiles"]>[number];
42
22
  type FieldDifference<T, Fields extends readonly PropertyKey[]> = Exclude<keyof T, Fields[number]> | Exclude<Fields[number], keyof T>;
43
- export type SandboxBackendFieldCoverage = Exhaustive<FieldDifference<BackendConfig, typeof SANDBOX_BACKEND_FIELD_LIST> | FieldDifference<SandboxBackendModel, typeof SANDBOX_BACKEND_MODEL_FIELD_LIST> | FieldDifference<SandboxAuthFile, typeof SANDBOX_AUTH_FILE_FIELD_LIST>>;
23
+ export type SandboxBackendFieldCoverage = Exhaustive<FieldDifference<Omit<BackendConfig, Exclude<(typeof SANDBOX_BACKEND_MODEL_FIELD_LIST)[number], "model"> | "modelId">, typeof SANDBOX_BACKEND_FIELD_LIST> | FieldDifference<SandboxBackendModel, typeof SANDBOX_BACKEND_MODEL_FIELD_LIST> | FieldDifference<SandboxAuthFile, typeof SANDBOX_AUTH_FILE_FIELD_LIST>>;
44
24
  type SandboxPromptBackend = NonNullable<PromptOptions["backend"]>;
45
25
  /**
46
26
  * Read the per-turn backend options a caller sent through `providerOptions`.
@@ -52,6 +32,7 @@ type SandboxPromptBackend = NonNullable<PromptOptions["backend"]>;
52
32
  * declare, and the result is bounded JSON the SDK reads once.
53
33
  */
54
34
  export declare function backendFromTurnProviderOptions(providerOptions: Record<string, unknown> | undefined): SandboxPromptBackend | undefined;
35
+ export declare function normalizeTangleBackend(value: unknown, allowRouting?: boolean): BackendConfig | undefined;
55
36
  /**
56
37
  * The part of the backend options that decides which work a turn is.
57
38
  *
@@ -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, boundedEventContentRecordSchema, AgentExactRunControlRefSchema, AgentTurnInputSchema, ContextTransferReceiptSchema, contextTransferResultMatchesRequest, } from "@tangle-network/agent-interface";
5
+ import { agentProfileSchema, canonicalAgentProfileDigest, canonicalCandidateDigest, boundedEventContentRecordSchema, AgentExactRunControlRefSchema, AgentTurnInputSchema, ContextTransferReceiptSchema, 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";
@@ -96,45 +96,10 @@ export async function preparePromptOptions(box, options, provider) {
96
96
  options.signal?.throwIfAborted();
97
97
  return { ...options, sessionId, backend, expectedPublicProfileRequestDigest, expectedSecretProfileReceipt };
98
98
  }
99
- /**
100
- * The `BackendConfig` fields this adapter forwards to Sandbox prompt options.
101
- *
102
- * A turn may carry any of them and nothing else. An undeclared field is
103
- * refused instead of forwarded, because the SDK drops what it does not
104
- * declare: the turn would then run on different settings with no error
105
- * anywhere, which is the silent substitution the SDK's own `model` field
106
- * exists to prevent.
107
- */
99
+ /** Canonical backend controls plus the legacy model aliases folded below. */
108
100
  const SANDBOX_BACKEND_FIELD_LIST = [
109
- "runtimeAttachments",
110
- "runtimeSecrets",
111
- "modelId",
112
- "provider",
113
- "apiKey",
114
- "baseUrl",
115
- "maxThinkingTokens",
116
- "mode",
117
- "apiKeyEnv",
118
- "cliAuth",
119
- "authMode",
120
- "authFiles",
121
- "type",
122
- "profile",
123
- "model",
124
- "server",
125
- "interactions",
126
- "metadata",
127
- // Creation-only: the SDK normalizer refuses it on a turn.
128
- "routing",
101
+ "runtimeAttachments", "runtimeSecrets", "type", "profile", "model", "server", "interactions", "metadata",
129
102
  ];
130
- const SANDBOX_BACKEND_FIELDS = new Set(SANDBOX_BACKEND_FIELD_LIST);
131
- /**
132
- * The `BackendConfig["model"]` fields the Sandbox prompt options declare.
133
- *
134
- * This is the block that carries per-turn credentials — `authMode: "oauth"`
135
- * with `authFiles` for a subscription seat — so it is checked field by field
136
- * rather than passed through as opaque JSON.
137
- */
138
103
  const SANDBOX_BACKEND_MODEL_FIELD_LIST = [
139
104
  "provider",
140
105
  "model",
@@ -150,6 +115,8 @@ const SANDBOX_BACKEND_MODEL_FIELD_LIST = [
150
115
  "routing",
151
116
  ];
152
117
  const SANDBOX_BACKEND_MODEL_FIELDS = new Set(SANDBOX_BACKEND_MODEL_FIELD_LIST);
118
+ const SANDBOX_BACKEND_FIELDS = new Set([...SANDBOX_BACKEND_FIELD_LIST,
119
+ ...SANDBOX_BACKEND_MODEL_FIELD_LIST.map((field) => field === "model" ? "modelId" : field)]);
153
120
  const SANDBOX_AUTH_FILE_FIELD_LIST = ["path", "content", "mode"];
154
121
  /**
155
122
  * Read the per-turn backend options a caller sent through `providerOptions`.
@@ -168,19 +135,30 @@ export function backendFromTurnProviderOptions(providerOptions) {
168
135
  return undefined;
169
136
  return sandboxPromptBackend(providerOptions.backend);
170
137
  }
138
+ export function normalizeTangleBackend(value, allowRouting = false) {
139
+ if (value === undefined)
140
+ return undefined;
141
+ const source = plainRecord(value, "Tangle backend options"), canonical = { ...source };
142
+ assertDeclaredFields(source, SANDBOX_BACKEND_FIELDS, "Tangle backend options");
143
+ const model = source.model === undefined ? {} : { ...plainRecord(source.model, "Tangle backend model") };
144
+ assertDeclaredFields(model, SANDBOX_BACKEND_MODEL_FIELDS, "Tangle backend model");
145
+ for (const field of SANDBOX_BACKEND_MODEL_FIELD_LIST) {
146
+ const alias = field === "model" ? "modelId" : field, selected = source[alias];
147
+ if (selected === undefined)
148
+ continue;
149
+ if (model[field] !== undefined && canonicalCandidateDigest(model[field]) !== canonicalCandidateDigest(selected))
150
+ throw new Error(`Tangle backend ${alias} conflicts with model.${field}`);
151
+ model[field] = selected;
152
+ delete canonical[alias];
153
+ }
154
+ if (source.model !== undefined || Object.keys(model).length)
155
+ canonical.model = model;
156
+ if (canonical.server !== undefined)
157
+ plainRecord(canonical.server, "Tangle backend server");
158
+ return normalizeRuntimeBackendConfig(canonical, { allowRuntimeSecrets: true, allowRouting });
159
+ }
171
160
  function sandboxPromptBackend(value) {
172
- const source = plainRecord(value, "Tangle prompt backend options");
173
- assertDeclaredFields(source, SANDBOX_BACKEND_FIELDS, "Tangle prompt backend options");
174
- // Normalization can omit falsy nested values or replace them with flat fields.
175
- // Reject malformed declarations before that loses the caller's input.
176
- for (const field of ["model", "server"]) {
177
- if (source[field] !== undefined) {
178
- plainRecord(source[field], `Tangle prompt backend ${field} options`);
179
- }
180
- }
181
- const present = normalizeRuntimeBackendConfig(source, {
182
- allowRuntimeSecrets: true,
183
- }) ?? {};
161
+ const present = normalizeTangleBackend(value) ?? {};
184
162
  const backend = {
185
163
  ...(present.type === undefined
186
164
  ? {}
@@ -1,13 +1,14 @@
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 { assertProxySecretAliases, captureProxySecrets, mergeProxySecrets, proxySecretsFromInput, 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
+ import { normalizeTangleBackend } from "./tangle-prompt.js";
11
12
  import { requireNativeCaptureCapability, requireNativeCaptureProof } from "./tangle-native-capture-proof.js";
12
13
  import { awaitSandboxRunning, DEFAULT_TANGLE_READY_TIMEOUT_MS, } from "./tangle-readiness.js";
13
14
  import { profileCredentialSource } from "./model-credential-source.js";
@@ -71,9 +72,6 @@ export function createTangleProvider(options) {
71
72
  configured = { ...configured, profile: { ...configured.profile },
72
73
  ...(configured.create === undefined ? {} : { create: { ...configured.create } }),
73
74
  };
74
- delete configured.profile.proxySecrets;
75
- if (configured.create !== undefined)
76
- delete configured.create.proxySecrets;
77
75
  if (configured.create?.workspaceSnapshot === true) {
78
76
  throw new Error("Tangle provider does not support portable workspace snapshots in this receiver deployment");
79
77
  }
@@ -112,6 +110,8 @@ export function createTangleProvider(options) {
112
110
  }
113
111
  const requestedProxySecrets = proxySecretsFromInput(input);
114
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;
115
115
  const credentialSource = typeof input.profile === "string" ? "managed" : profileCredentialSource(input.profile);
116
116
  const subscription = credentialSource === "subscription";
117
117
  if (Object.hasOwn(input.metadata ?? {}, "modelCredentials")) {
@@ -139,22 +139,24 @@ export function createTangleProvider(options) {
139
139
  const mappedInput = mapCreateInput?.(input) ??
140
140
  (subscription && resolveModelCredentials !== undefined ? sandboxOptionsFromCreateInput(input, options.defaultBackend, parsedWorkspace, selectedCredentials, true) : defaultOptions);
141
141
  const selectedProxySecrets = mergeProxySecrets(requestedProxySecrets, selectedCredentials?.proxySecrets);
142
- 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 ?? []))
143
144
  throw new Error("Tangle mapped proxy-secret declarations differ from the requested bindings");
144
- }
145
- const { proxySecrets: _legacy, secrets: selection, ...mapped } = mappedInput;
146
- const secrets = sandboxSecretBindings(selection, selectedProxySecrets, mapped.env);
147
- const mappedOptions = { ...mapped, ...(secrets === undefined ? {} : { secrets }) };
148
- for (const entry of sandboxSecretBindings(input.secrets, selectedProxySecrets, input.env) ?? []) {
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
+ for (const entry of requestedSecrets ?? []) {
149
150
  if (typeof entry === "string")
150
151
  continue;
151
- if (!Array.isArray(mappedOptions.secrets) || !mappedOptions.secrets.some((selected) => canonicalCandidateDigest(selected) === canonicalCandidateDigest(entry))) {
152
- throw new Error("Tangle mapped secrets must preserve the requested host bindings");
152
+ if (!Array.isArray(mappedOptions.secrets) || !mappedOptions.secrets.some((selected) => sandboxSecretBindingIdentity(selected) === sandboxSecretBindingIdentity(entry))) {
153
+ throw new Error("Tangle mapped secrets must preserve the requested delivery selection");
153
154
  }
154
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");
155
158
  assertMappedCreateOptions(mappedOptions);
156
- // A custom mapper builds its own backend; requested routing must survive it.
157
- const mappedRouting = mappedOptions.backend?.routing ?? mappedOptions.backend?.model?.routing;
159
+ const mappedRouting = mappedOptions.backend?.model?.routing;
158
160
  if (canonicalCandidateDigest(mappedRouting ?? null) !== canonicalCandidateDigest(requestedRouting ?? null)) {
159
161
  throw new Error("Tangle mapped create options must carry exactly the requested providerOptions.routing");
160
162
  }
@@ -341,7 +343,7 @@ export function createTangleProvider(options) {
341
343
  return {
342
344
  name: providerName,
343
345
  ...(exactProcess ? { exactProcess } : {}),
344
- ...(options.client.secrets === undefined ? {} : { secrets: options.client.secrets }),
346
+ ...(typeof options.client.secrets?.update !== "function" ? {} : { secrets: options.client.secrets }),
345
347
  ...(workspaceBranching === undefined ? {} : { workspaceBranching }),
346
348
  capabilities: resolveCapabilities,
347
349
  validateProfile: tangleProfileValidator(options.validateProfile),
@@ -1,10 +1,9 @@
1
1
  import { type CreateAgentEnvironmentInput, type ProxySecretBinding } from "@tangle-network/agent-interface/environment-provider";
2
- import type { CreateSandboxOptions } from "@tangle-network/sandbox";
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<CreateSandboxOptions["secrets"], "all">;
8
+ /** Legacy selection identity stays at the compatibility boundary. */
9
+ export declare const sandboxSecretBindingIdentity: (entry: Extract<CreateAgentEnvironmentInput["secrets"], unknown[]>[number]) => string;
@@ -1,6 +1,5 @@
1
- import { ProxySecretsSchema, mergeProxySecretBindings, } from "@tangle-network/agent-interface/environment-provider";
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,53 +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
- }
23
19
  for (const binding of bindings ?? []) {
24
20
  for (const alias of [binding.envName, binding.secretRef.key]) {
25
- if (Object.hasOwn(env ?? {}, alias) || (Array.isArray(secrets) && secrets.includes(alias))) {
26
- 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");
27
33
  }
28
34
  }
29
35
  }
30
36
  }
31
- /** Lower portable declarations to the single host binding actually served by Sandbox. */
32
- export function sandboxSecretBindings(secrets, bindings, env) {
33
- assertProxySecretAliases(bindings === undefined ? undefined : [...bindings], env, secrets);
34
- const lowered = (bindings ?? []).map((binding) => {
35
- if (binding.hosts.length !== 1 || binding.methods !== undefined || binding.paths !== undefined ||
36
- binding.presentation.type === "query" || binding.placeholderFormat === "jwt" ||
37
- binding.ttlSeconds !== undefined || binding.envName !== binding.secretRef.key) {
38
- throw new Error("Tangle host bindings cannot enforce aliases, multiple hosts, methods, paths, query, jwt or expiry");
39
- }
40
- return { name: binding.secretRef.key, host: binding.hosts[0],
41
- header: binding.presentation.type === "header" ? binding.presentation.name : "Authorization" };
42
- });
43
- if (secrets === undefined && bindings === undefined)
44
- return undefined;
45
- if (secrets !== undefined && !Array.isArray(secrets))
46
- throw new Error("Tangle secrets must be stored names or host bindings");
47
- const entries = new Map();
48
- for (const entry of [...(secrets ?? []), ...lowered]) {
49
- const name = typeof entry === "string" ? entry : entry.name;
50
- boundedIdentifier(name, "Tangle stored-secret name");
51
- if (typeof entry !== "string") {
52
- if (Object.keys(entry).some((key) => !["name", "host", "header"].includes(key)) ||
53
- typeof entry.host !== "string" || entry.host.length > 253 ||
54
- !/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z](?:[a-z0-9-]{0,61}[a-z0-9])?$/.test(entry.host) ||
55
- (entry.header !== undefined && (typeof entry.header !== "string" || !/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/.test(entry.header))) ||
56
- Object.hasOwn(env ?? {}, name))
57
- throw new Error("Invalid or shadowed Tangle host binding");
58
- }
59
- const previous = entries.get(name);
60
- const identity = (value) => typeof value === "string" ? value :
61
- { name: value.name, host: value.host, header: (value.header ?? "Authorization").toLowerCase() };
62
- if (previous !== undefined && canonicalCandidateDigest(identity(previous)) !== canonicalCandidateDigest(identity(entry)))
63
- throw new Error("Conflicting Tangle secret delivery");
64
- entries.set(name, entry);
65
- }
66
- if (entries.size > MAX_ARRAY_LENGTH)
67
- throw new Error("Tangle stored-secret selection exceeds its bound");
68
- return [...entries.values()];
69
- }
37
+ /** Legacy selection identity stays at the compatibility boundary. */
38
+ export const sandboxSecretBindingIdentity = (entry) => canonicalCandidateDigest(typeof entry !== "string" && "host" in entry ? { ...entry, header: (entry.header ?? "Authorization").toLowerCase() } : entry);
@@ -1,5 +1,5 @@
1
1
  import type { CliAuthReference } from "@tangle-network/sandbox/auth";
2
- import type { BackendRegistryEntry, BackendRegistryResponse, BackendType, CreateSandboxOptions, ExecResult as SandboxExecResult, PromptOptions, PromptResult, SandboxInstance, SandboxEvent } from "@tangle-network/sandbox";
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
4
  import type { AgentEnvironmentCapabilities, AgentEnvironmentProvider, CreateAgentEnvironmentInput, ProxySecretBinding, ProxySecretCapabilities, ProxySecretReceipt } from "@tangle-network/agent-interface/environment-provider";
5
5
  /**
@@ -24,8 +24,12 @@ export interface SandboxCreateReceiptLike {
24
24
  export interface TangleExactProcessOptions {
25
25
  teamId?: string;
26
26
  }
27
- export type TangleCreateSandboxOptions = CreateSandboxOptions & {
28
- proxySecrets?: ProxySecretBinding[];
27
+ export type TangleCreateSandboxOptions = Omit<CreateSandboxOptions, "secrets" | "backend" | "proxySecrets"> & {
28
+ backend?: BackendConfig & Omit<NonNullable<BackendConfig["model"]>, "model"> & {
29
+ modelId?: string;
30
+ };
31
+ secrets?: "all" | Extract<CreateAgentEnvironmentInput["secrets"], unknown[]>;
32
+ proxySecrets?: CreateAgentEnvironmentInput["proxySecrets"];
29
33
  };
30
34
  export interface SandboxClientLike {
31
35
  readonly secrets?: AgentEnvironmentProvider["secrets"];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tangle-network/agent-provider-tangle",
3
- "version": "4.5.6",
3
+ "version": "5.0.0",
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.5"
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.111 <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.111",
50
50
  "@types/node": "26.6.5",
51
51
  "typescript": "6.0.3",
52
52
  "vitest": "5.0.5"