@tangle-network/agent-provider-tangle 3.0.0 → 3.1.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.
package/README.md CHANGED
@@ -1,8 +1,8 @@
1
1
  # @tangle-network/agent-provider-tangle
2
2
 
3
3
  Wraps `@tangle-network/sandbox` as an `AgentEnvironmentProvider`.
4
- The Sandbox peer range is `>=0.58.4 <1.0.0`.
5
- The floor includes runtime MCP attachment transport and preservation across per-turn model credential overrides.
4
+ The Sandbox peer range is `>=0.58.7 <1.0.0`.
5
+ The floor includes native credential reference validation, per-container capability parsing, and runtime MCP transport.
6
6
 
7
7
  Runtime MCP bindings travel through `CreateAgentEnvironmentInput.runtimeAttachments` to Sandbox's `backend.runtimeAttachments`.
8
8
  They remain separate from the authored profile and its digest.
@@ -34,8 +34,8 @@ Set `TANGLE_SANDBOX_URL` to use another deployment.
34
34
 
35
35
  `modelCredentials` sends a stored credential reference and explicit endpoint before Sandbox provisions the backend.
36
36
  This uses Sandbox's existing caller-owned model credential path instead of requesting a managed Router credential.
37
- The provider does not create, grant, copy, or renew secrets.
38
- Each create must list the named secret explicitly.
37
+ The provider does not create, copy, or renew stored secrets.
38
+ The Provider grants the selected reference per create, alongside unrelated caller-requested secrets.
39
39
 
40
40
  ```ts
41
41
  const provider = createTangleProvider({
@@ -47,7 +47,6 @@ const provider = createTangleProvider({
47
47
  });
48
48
  const environment = await provider.create({
49
49
  profile: researchProfile,
50
- secrets: ["RESEARCH_ROUTER_KEY"],
51
50
  });
52
51
  ```
53
52
 
@@ -61,6 +60,103 @@ Credential-only turns retain the created SDK handle's endpoint and attachments.
61
60
  Reconstructed handles leave omitted model settings to Sandbox's durable backend configuration.
62
61
  Keep the stored secret available and valid throughout execution and recovery.
63
62
 
63
+ ## Per-profile subscription credentials
64
+
65
+ The exact profile chooses access through `model.metadata.credentialSource`.
66
+ Use `"subscription"` to request an enrolled account.
67
+ Omitting this field or using `"managed"` preserves managed access.
68
+ Unknown or malformed intent fails before provisioning.
69
+ `profileCredentialSource(profile)` exports this strict intent reader.
70
+
71
+ `modelCredentials` resolves only profiles that request subscription access.
72
+ Managed profiles skip the selector and configured native references.
73
+ Explicit `"managed"` intent also skips configured static API references.
74
+ Unmarked legacy profiles retain their existing static API configuration; mark mixed profiles explicitly or use a selector.
75
+ The same Provider can create a managed parent and subscription child, or a subscription parent and managed child.
76
+ A subscription profile requires a configured reference or successful selector result before Sandbox creation.
77
+ The selector receives a frozen copy of the exact create input, including its profile and idempotency key.
78
+ It returns one public native reference or the API reference described above.
79
+ It cannot change the profile, harness, model, reasoning controls, or runtime attachments.
80
+
81
+ ```ts
82
+ const provider = createTangleProvider({
83
+ client,
84
+ modelCredentials: async (input) => accountOwner.resolve(input),
85
+ });
86
+ const environment = await provider.create({
87
+ profile: {
88
+ ...researchProfile,
89
+ model: {
90
+ ...researchProfile.model,
91
+ metadata: { ...researchProfile.model?.metadata, credentialSource: "subscription" },
92
+ },
93
+ },
94
+ idempotencyKey: persistedNodeIdentity,
95
+ });
96
+ ```
97
+
98
+ A native result has this shape:
99
+
100
+ ```ts
101
+ {
102
+ cliAuth: {
103
+ account: "research-account",
104
+ secretEnv: "RESEARCH_CLAUDE",
105
+ format: "token", // Or "bundle" / "files", as supported by the selected harness.
106
+ },
107
+ }
108
+ ```
109
+
110
+ The Provider validates native channels with the maintained CLI Registry before provisioning.
111
+ Each selector must use the exact profile harness.
112
+ Native execution also requires the selected container to report `cliAuthReferences: true`.
113
+ A missing or unreadable capability refuses creation or dispatch before inference.
114
+ A selector grants its one selected stored secret automatically, alongside unrelated secrets requested by the caller.
115
+ Keep pool-wide account credentials out of the create input's `secrets` list.
116
+ Static native references grant their selected secret only for subscription profiles.
117
+ Static API references grant their selected secret for unmarked legacy profiles and subscription profiles.
118
+ Inline environment values cannot shadow the selected stored secret.
119
+ Undefined, malformed, unsupported, or failed subscription selections stop before Sandbox creation.
120
+ Subscription failures never fall back to managed Router access.
121
+
122
+ Sandbox metadata records the public selection under `modelCredentials`.
123
+ This metadata key is reserved for the Provider selection.
124
+ Account labels are supplied bindings, not verified native principals.
125
+ Token values and native credential files never enter that selection or receipt.
126
+ The same public native reference can travel in a per-turn `backend.model.cliAuth` with an explicit matching backend type.
127
+ A turn carrying a profile must preserve its environment's credential source, including after recovery.
128
+ Changing credential sources requires a separate environment because retained Sandbox defaults cannot safely clear a native binding.
129
+
130
+ ### A command owned by the account system
131
+
132
+ The Node subpath provides direct process transport for an existing account resolver.
133
+ It executes arguments without a shell and discards subprocess stderr.
134
+
135
+ ```ts
136
+ import { createCommandModelCredentialResolver } from "@tangle-network/agent-provider-tangle/node";
137
+
138
+ const modelCredentials = createCommandModelCredentialResolver({
139
+ command: ["acct", "sandbox", "resolve", "--key-env", "TANGLE_SANDBOX_API_KEY"],
140
+ minimumValidUntil: persistedRunDeadline,
141
+ timeoutMs: 30_000,
142
+ });
143
+ const provider = createTangleProvider({ client, modelCredentials });
144
+ ```
145
+
146
+ Managed profiles do not start the command or require an account binding.
147
+ For subscription profiles, the command receives JSON `{ input, minimumValidUntil? }` on stdin.
148
+ `input` contains the exact create fields with `signal` omitted.
149
+ The command must return only `{ cliAuth }` or `{ apiKeyEnv, baseUrl }` on stdout.
150
+ It must bind selection durably to `input.idempotencyKey`; quota changes cannot switch an existing assignment during retry.
151
+ The adapter requires this idempotency key before starting the command.
152
+ `minimumValidityMs` can compute one fixed deadline at factory construction; recovery should use the persisted absolute deadline.
153
+ Only a successfully decoded public reference can reach Sandbox creation.
154
+ Timeouts, cancellation, nonzero exit, and malformed or oversized output refuse creation with sanitized errors.
155
+
156
+ The account owner retains authority over registration, namespace verification, holds, quota, selection, and trusted renewal.
157
+ Updating a stored secret does not refresh credentials already injected into a live Sandbox.
158
+ Creation-time validity and the selected host's native credential lifecycle still bound long-running work.
159
+
64
160
  ## `create()` returns a ready environment
65
161
 
66
162
  `provider.create()` does not return until the sandbox reports `running`.
@@ -497,3 +593,13 @@ The caller's attempt projection includes only its known execution IDs.
497
593
  The capture records the running sidecar image digest and the served Sidecar bundle revision.
498
594
  The image digest can be compared with the pre-create proof only when that proof identifies the actual placement image.
499
595
  An incomplete inventory, missing stream, unrelated backend, or mismatched digest does not produce complete evidence.
596
+
597
+ ## Exact retained workspace capture
598
+
599
+ Pass the admitted `controlRef` to `captureTangleEnvironmentEvidence`.
600
+ Keep `executionId` as the Runtime artifact identity.
601
+ The control reference supplies the exact native environment, session, and execution identifiers.
602
+ Capture validates those coordinates before reading files.
603
+ A reconstructed environment does not need the original in-memory session cache.
604
+ The returned provenance retains both identities and reports incomplete native coverage explicitly.
605
+ Missing native session evidence preserves the source under Runtime's complete-provenance policy.
@@ -0,0 +1,14 @@
1
+ import type { TangleModelCredentialResolver } from "./tangle-types.js";
2
+ export interface CommandModelCredentialResolverOptions {
3
+ /** Executable and arguments, invoked directly without a shell. */
4
+ command: readonly string[];
5
+ /** Additional private process environment; never included in public receipts. */
6
+ env?: Readonly<Record<string, string>>;
7
+ timeoutMs?: number;
8
+ /** Fixed absolute run deadline, retained across controller recovery. */
9
+ minimumValidUntil?: string;
10
+ /** Compute a fixed deadline once at factory construction. */
11
+ minimumValidityMs?: number;
12
+ }
13
+ /** The account owner selects, binds, refreshes, and stores credentials; this transport reads references. */
14
+ export declare function createCommandModelCredentialResolver(options: CommandModelCredentialResolverOptions): TangleModelCredentialResolver;
@@ -0,0 +1,123 @@
1
+ import { spawn } from "node:child_process";
2
+ import { profileCredentialSource } from "./model-credential-source.js";
3
+ import { captureModelCredentials } from "./tangle-create-options.js";
4
+ const MAX_COMMAND_OUTPUT_BYTES = 64 * 1024;
5
+ /** The account owner selects, binds, refreshes, and stores credentials; this transport reads references. */
6
+ export function createCommandModelCredentialResolver(options) {
7
+ if (!Array.isArray(options.command) || options.command.length === 0 || options.command.length > 128 ||
8
+ options.command.some((part) => typeof part !== "string" || part.length === 0 || part.length > 4096 || part.includes("\0"))) {
9
+ throw new Error("Tangle credential command must contain an executable and bounded arguments");
10
+ }
11
+ const command = Object.freeze([...options.command]);
12
+ const timeoutMs = options.timeoutMs ?? 30_000;
13
+ if (!Number.isSafeInteger(timeoutMs) || timeoutMs <= 0 || timeoutMs > 2_147_483_647) {
14
+ throw new Error("Tangle credential command timeoutMs must be a positive timer bound");
15
+ }
16
+ if (options.minimumValidityMs !== undefined && options.minimumValidUntil !== undefined) {
17
+ throw new Error("Tangle credential command accepts one validity deadline");
18
+ }
19
+ if (options.minimumValidityMs !== undefined &&
20
+ (!Number.isSafeInteger(options.minimumValidityMs) || options.minimumValidityMs <= 0)) {
21
+ throw new Error("Tangle credential command minimumValidityMs must be a positive integer");
22
+ }
23
+ if (options.minimumValidUntil !== undefined &&
24
+ (typeof options.minimumValidUntil !== "string" || options.minimumValidUntil.length > 128)) {
25
+ throw new Error("Tangle credential command validity deadline must be a valid timestamp");
26
+ }
27
+ const deadline = options.minimumValidUntil === undefined
28
+ ? options.minimumValidityMs === undefined ? undefined : new Date(Date.now() + options.minimumValidityMs)
29
+ : new Date(options.minimumValidUntil);
30
+ if (deadline !== undefined && !Number.isFinite(deadline.getTime())) {
31
+ throw new Error("Tangle credential command validity deadline must be a valid timestamp");
32
+ }
33
+ const minimumValidUntil = deadline?.toISOString();
34
+ if (options.env !== undefined && (!options.env || typeof options.env !== "object" || Array.isArray(options.env) ||
35
+ Object.entries(options.env).some(([key, value]) => !/^[A-Za-z_][A-Za-z0-9_]*$/.test(key) ||
36
+ typeof value !== "string" || value.includes("\0")))) {
37
+ throw new Error("Tangle credential command env must contain valid private process variables");
38
+ }
39
+ const environment = { ...process.env, ...options.env };
40
+ return (input) => {
41
+ if (typeof input.profile === "string")
42
+ throw new Error("Tangle credential command requires an inline profile");
43
+ if (profileCredentialSource(input.profile) === "managed")
44
+ return undefined;
45
+ if (typeof input.idempotencyKey !== "string" || input.idempotencyKey.length === 0) {
46
+ throw new Error("Tangle credential command requires a stable create idempotencyKey");
47
+ }
48
+ input.signal?.throwIfAborted();
49
+ const { signal, ...data } = input;
50
+ const request = JSON.stringify({ input: data, ...(minimumValidUntil === undefined ? {} : { minimumValidUntil }) });
51
+ return new Promise((resolve, reject) => {
52
+ let child;
53
+ try {
54
+ child = spawn(command[0], command.slice(1), {
55
+ env: environment,
56
+ shell: false,
57
+ stdio: ["pipe", "pipe", "pipe"],
58
+ });
59
+ }
60
+ catch {
61
+ reject(new Error("Tangle credential command could not start"));
62
+ return;
63
+ }
64
+ // Consume and discard private diagnostics without retaining their content.
65
+ child.stderr.resume();
66
+ let settled = false;
67
+ let outputBytes = 0;
68
+ const chunks = [];
69
+ const cleanup = () => {
70
+ clearTimeout(timer);
71
+ signal?.removeEventListener("abort", onAbort);
72
+ };
73
+ const fail = (error) => {
74
+ if (settled)
75
+ return;
76
+ settled = true;
77
+ cleanup();
78
+ child.kill("SIGKILL");
79
+ reject(error);
80
+ };
81
+ const onAbort = () => fail(signal?.reason ?? new Error("Tangle credential command aborted"));
82
+ const timer = setTimeout(() => fail(new Error("Tangle credential command timed out")), timeoutMs);
83
+ signal?.addEventListener("abort", onAbort, { once: true });
84
+ child.on("error", () => fail(new Error("Tangle credential command could not start")));
85
+ child.stdin.on("error", () => fail(new Error("Tangle credential command could not accept its request")));
86
+ child.stdout.on("data", (chunk) => {
87
+ outputBytes += chunk.length;
88
+ if (outputBytes > MAX_COMMAND_OUTPUT_BYTES) {
89
+ fail(new Error("Tangle credential command exceeded its public-output bound"));
90
+ return;
91
+ }
92
+ chunks.push(chunk);
93
+ });
94
+ child.on("close", (code, terminationSignal) => {
95
+ if (settled)
96
+ return;
97
+ if (code !== 0) {
98
+ fail(Object.assign(new Error(`Tangle credential command failed (${code === null ? `signal ${terminationSignal}` : `exit ${code}`})`), {
99
+ exitCode: code,
100
+ terminationSignal,
101
+ }));
102
+ return;
103
+ }
104
+ try {
105
+ const selected = captureModelCredentials(JSON.parse(Buffer.concat(chunks).toString("utf8")));
106
+ if (selected === undefined)
107
+ throw new Error();
108
+ settled = true;
109
+ cleanup();
110
+ resolve(selected);
111
+ }
112
+ catch {
113
+ fail(new Error("Tangle credential command returned an invalid public reference"));
114
+ }
115
+ });
116
+ if (signal?.aborted) {
117
+ onAbort();
118
+ return;
119
+ }
120
+ child.stdin.end(request + "\n");
121
+ });
122
+ };
123
+ }
package/dist/index.d.ts CHANGED
@@ -12,3 +12,5 @@ export type { TangleWorkspaceBranchingOptions } from "./tangle-workspace-branchi
12
12
  export { decodeTangleConfidentialAttestationQuote, encodeTangleConfidentialAttestationQuote, MAX_TEE_EVIDENCE_BYTES, MAX_TEE_MEASUREMENT_BYTES, TANGLE_CONFIDENTIAL_ATTESTATION_QUOTE_KIND, TANGLE_CONFIDENTIAL_ATTESTATION_QUOTE_VERSION, } from "./tangle-confidential-attestation.js";
13
13
  export type { TangleConfidentialAttestationReport } from "./tangle-confidential-attestation.js";
14
14
  export { safeEndpointFromConnection } from "./tangle-observation.js";
15
+ export { profileCredentialSource } from "./model-credential-source.js";
16
+ export type { ProfileCredentialSource } from "./model-credential-source.js";
package/dist/index.js CHANGED
@@ -7,3 +7,4 @@ export { defaultTangleSandboxCapabilities } from "./tangle-capabilities.js";
7
7
  export { createTangleWorkspaceBranching, supportsWorkspaceBranching, } from "./tangle-workspace-branching.js";
8
8
  export { decodeTangleConfidentialAttestationQuote, encodeTangleConfidentialAttestationQuote, MAX_TEE_EVIDENCE_BYTES, MAX_TEE_MEASUREMENT_BYTES, TANGLE_CONFIDENTIAL_ATTESTATION_QUOTE_KIND, TANGLE_CONFIDENTIAL_ATTESTATION_QUOTE_VERSION, } from "./tangle-confidential-attestation.js";
9
9
  export { safeEndpointFromConnection } from "./tangle-observation.js";
10
+ export { profileCredentialSource } from "./model-credential-source.js";
@@ -0,0 +1,4 @@
1
+ import type { AgentProfile } from "@tangle-network/agent-interface";
2
+ export type ProfileCredentialSource = "managed" | "subscription";
3
+ /** Authored profile intent is independent of the harness, vendor, and available accounts. */
4
+ export declare function profileCredentialSource(profile: AgentProfile): ProfileCredentialSource;
@@ -0,0 +1,20 @@
1
+ /** Authored profile intent is independent of the harness, vendor, and available accounts. */
2
+ export function profileCredentialSource(profile) {
3
+ if (!profile || typeof profile !== "object" || Array.isArray(profile)) {
4
+ throw new Error("Tangle credential intent requires an inline AgentProfile");
5
+ }
6
+ const model = profile.model;
7
+ if (model !== undefined && (!model || typeof model !== "object" || Array.isArray(model))) {
8
+ throw new Error("Tangle profile model must be an object");
9
+ }
10
+ const metadata = model?.metadata;
11
+ if (metadata !== undefined && (!metadata || typeof metadata !== "object" || Array.isArray(metadata))) {
12
+ throw new Error("Tangle profile model metadata must be an object");
13
+ }
14
+ const source = metadata?.credentialSource;
15
+ if (source === undefined || source === "managed")
16
+ return "managed";
17
+ if (source === "subscription")
18
+ return "subscription";
19
+ throw new Error('Tangle profile model.metadata.credentialSource must be "managed" or "subscription"');
20
+ }
package/dist/node.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ export { createCommandModelCredentialResolver } from "./command-model-credentials.js";
2
+ export type { CommandModelCredentialResolverOptions } from "./command-model-credentials.js";
package/dist/node.js ADDED
@@ -0,0 +1 @@
1
+ export { createCommandModelCredentialResolver } from "./command-model-credentials.js";
@@ -1,8 +1,8 @@
1
1
  import { type BackendType, type CreateSandboxOptions } from "@tangle-network/sandbox";
2
2
  import type { CreateAgentEnvironmentInput, WorkspaceRequest } from "@tangle-network/agent-interface/environment-provider";
3
- import type { TangleProviderOptions } from "./tangle-types.js";
4
- export declare function captureModelCredentials(value: TangleProviderOptions["modelCredentials"]): TangleProviderOptions["modelCredentials"];
5
- export declare function sandboxOptionsFromCreateInput(input: CreateAgentEnvironmentInput, defaultBackend?: BackendType, parsedWorkspace?: WorkspaceRequest, modelCredentials?: TangleProviderOptions["modelCredentials"]): CreateSandboxOptions;
3
+ import type { TangleModelCredentials } from "./tangle-types.js";
4
+ export declare function captureModelCredentials(value: TangleModelCredentials | undefined): TangleModelCredentials | undefined;
5
+ export declare function sandboxOptionsFromCreateInput(input: CreateAgentEnvironmentInput, defaultBackend?: BackendType, parsedWorkspace?: WorkspaceRequest, modelCredentials?: TangleModelCredentials, subscriptionSelection?: boolean): CreateSandboxOptions;
6
6
  /**
7
7
  * Project a portable workspace checkpoint onto the Sandbox restore fields.
8
8
  *
@@ -1,12 +1,23 @@
1
+ import { assertCliAuthReferenceSupported, cliAuthReferenceSchema, } from "@tangle-network/sandbox/auth";
1
2
  import { parseBackendType, } from "@tangle-network/sandbox";
2
3
  import { AgentEnvironmentEgressPolicySchema, WorkspaceRequestSchema, workspaceCwdPathForBase, } from "@tangle-network/agent-interface/environment-provider";
3
4
  import { assertBoundedJson, boundedIdentifier, boundedString, MAX_ARRAY_LENGTH, MAX_MAP_ENTRIES, PROFILE_AT_BACKEND_PROFILE, PROFILE_AT_ROOT, } from "./tangle-contract-safety.js";
5
+ import { profileCredentialSource } from "./model-credential-source.js";
4
6
  import { sandboxResourcesFromResourceRequest } from "./tangle-resources.js";
5
7
  import { tangleRuntimeAttachments } from "./tangle-runtime-attachments.js";
6
8
  export function captureModelCredentials(value) {
7
9
  if (value === undefined)
8
10
  return undefined;
9
11
  assertBoundedJson(value, "Tangle modelCredentials");
12
+ if (value && typeof value === "object" && !Array.isArray(value) && "cliAuth" in value) {
13
+ if (Object.keys(value).some((key) => key !== "cliAuth")) {
14
+ throw new Error("Tangle native modelCredentials accepts only cliAuth");
15
+ }
16
+ const parsed = cliAuthReferenceSchema.safeParse(value.cliAuth);
17
+ if (!parsed.success)
18
+ throw new Error("Tangle modelCredentials cliAuth must be a valid stored-secret reference");
19
+ return Object.freeze({ cliAuth: Object.freeze(parsed.data) });
20
+ }
10
21
  if (!value || typeof value !== "object" || Array.isArray(value) ||
11
22
  Object.keys(value).some((key) => key !== "apiKeyEnv" && key !== "baseUrl")) {
12
23
  throw new Error("Tangle modelCredentials accepts only apiKeyEnv and baseUrl");
@@ -30,17 +41,46 @@ export function captureModelCredentials(value) {
30
41
  }
31
42
  return Object.freeze({ apiKeyEnv, baseUrl });
32
43
  }
33
- export function sandboxOptionsFromCreateInput(input, defaultBackend, parsedWorkspace, modelCredentials) {
44
+ export function sandboxOptionsFromCreateInput(input, defaultBackend, parsedWorkspace, modelCredentials, subscriptionSelection = false) {
34
45
  const workspace = assertCreateInputShape(input, parsedWorkspace) ?? {};
35
46
  const profile = inlineAgentProfile(input.profile);
36
47
  const backend = input.backend === undefined
37
48
  ? parseBackendType(defaultBackend ?? profile.harness ?? "opencode")
38
49
  : input.backend;
39
50
  assertNoInlineSecretValues(input, workspace);
40
- if (modelCredentials !== undefined &&
41
- (!Array.isArray(input.secrets) || !input.secrets.includes(modelCredentials.apiKeyEnv))) {
42
- throw new Error("Tangle modelCredentials apiKeyEnv must be explicitly listed in create secrets");
51
+ const selectedSecret = modelCredentials === undefined ? undefined
52
+ : "cliAuth" in modelCredentials ? modelCredentials.cliAuth?.secretEnv : modelCredentials.apiKeyEnv;
53
+ const nativeCredentials = modelCredentials !== undefined && "cliAuth" in modelCredentials;
54
+ if (modelCredentials !== undefined && selectedSecret === undefined) {
55
+ throw new Error("Tangle modelCredentials must select a stored secret");
56
+ }
57
+ if ((nativeCredentials || subscriptionSelection) &&
58
+ (profile.harness === undefined || profile.harness !== backend)) {
59
+ throw new Error("Tangle selected modelCredentials must use the exact profile harness");
60
+ }
61
+ if (nativeCredentials) {
62
+ if (profileCredentialSource(profile) !== "subscription") {
63
+ throw new Error("Tangle native credentials require subscription intent in the exact profile");
64
+ }
65
+ assertCliAuthReferenceSupported(backend, modelCredentials);
66
+ }
67
+ if (selectedSecret !== undefined && Object.hasOwn(input.env ?? {}, selectedSecret)) {
68
+ throw new Error("Tangle modelCredentials cannot shadow a stored secret with inline environment data");
43
69
  }
70
+ const requestedSecrets = Array.isArray(input.secrets) ? input.secrets : undefined;
71
+ const secrets = selectedSecret !== undefined
72
+ ? [...new Set([...(requestedSecrets ?? []), selectedSecret])]
73
+ : requestedSecrets;
74
+ if (secrets !== undefined && secrets.length > MAX_ARRAY_LENGTH) {
75
+ throw new Error("Tangle selected credential exceeds the stored-secret grant bound");
76
+ }
77
+ const recordsCredential = nativeCredentials || subscriptionSelection;
78
+ if (recordsCredential && Object.hasOwn(input.metadata ?? {}, "modelCredentials")) {
79
+ throw new Error("Tangle credential selection owns metadata.modelCredentials");
80
+ }
81
+ const metadata = recordsCredential
82
+ ? { ...input.metadata, modelCredentials }
83
+ : input.metadata;
44
84
  if (input.providerOptions && Object.keys(input.providerOptions).length > 0) {
45
85
  throw new Error("Tangle create providerOptions are not supported");
46
86
  }
@@ -94,17 +134,20 @@ export function sandboxOptionsFromCreateInput(input, defaultBackend, parsedWorks
94
134
  ...(resources ? { resources } : {}),
95
135
  ...(restore ?? {}),
96
136
  ...(input.env ? { env: input.env } : {}),
97
- ...(Array.isArray(input.secrets) ? { secrets: input.secrets } : {}),
137
+ ...(Array.isArray(secrets) ? { secrets } : {}),
98
138
  ...(input.egress === undefined ? {} : { egressPolicy: sandboxEgressPolicy(input.egress) }),
99
139
  ...(input.billingOwner === undefined ? {} : { billingOwnerId: input.billingOwner }),
100
- ...(input.metadata ? { metadata: input.metadata } : {}),
140
+ ...(metadata ? { metadata } : {}),
101
141
  ...(input.name === undefined ? {} : { name: input.name }),
102
142
  ...(input.idempotencyKey === undefined ? {} : { idempotencyKey: input.idempotencyKey }),
103
143
  backend: {
104
144
  ...(base.backend ?? {}),
105
145
  type: backend,
106
146
  profile,
107
- ...(modelCredentials === undefined ? {} : { model: modelCredentials }),
147
+ ...(modelCredentials === undefined ? {} : {
148
+ model: "cliAuth" in modelCredentials
149
+ ? { ...modelCredentials, authMode: "oauth" } : modelCredentials,
150
+ }),
108
151
  ...(input.runtimeAttachments === undefined ? {} : {
109
152
  runtimeAttachments: tangleRuntimeAttachments(input.runtimeAttachments, profile),
110
153
  }),
@@ -254,6 +297,25 @@ export function assertMappedCreateOptions(options) {
254
297
  throw new Error("Tangle mapped create options must be an object");
255
298
  }
256
299
  assertBoundedJson(options, "Tangle mapped create options", PROFILE_AT_BACKEND_PROFILE);
300
+ if (options.backend?.model?.cliAuth !== undefined) {
301
+ if (options.backend.type === undefined) {
302
+ throw new Error("Tangle mapped native credentials require the selected backend type");
303
+ }
304
+ assertCliAuthReferenceSupported(options.backend.type, options.backend.model);
305
+ if (options.backend.profile === undefined || profileCredentialSource(options.backend.profile) !== "subscription") {
306
+ throw new Error("Tangle mapped native credentials require subscription intent in the exact profile");
307
+ }
308
+ if (options.backend.profile?.harness !== undefined && options.backend.profile.harness !== options.backend.type) {
309
+ throw new Error("Tangle mapped native credentials must use the exact profile harness");
310
+ }
311
+ const selectedSecret = options.backend.model.cliAuth.secretEnv;
312
+ if (!Array.isArray(options.secrets) || !options.secrets.includes(selectedSecret)) {
313
+ throw new Error("Tangle mapped native credential must be explicitly listed in create secrets");
314
+ }
315
+ if (Object.hasOwn(options.env ?? {}, selectedSecret)) {
316
+ throw new Error("Tangle mapped native credential cannot shadow a stored secret with inline environment data");
317
+ }
318
+ }
257
319
  if (options.backend?.runtimeAttachments !== undefined) {
258
320
  tangleRuntimeAttachments(options.backend.runtimeAttachments, options.backend.profile);
259
321
  }
@@ -9,6 +9,8 @@ import type { SandboxInstanceLike, SandboxRuntimeCapabilityDocument } from "./ta
9
9
  * unreadable, or partial document leaves every fact false.
10
10
  */
11
11
  export interface DeploymentCapabilitySupport {
12
+ /** The selected runtime explicitly supports named native credential references. */
13
+ readonly cliAuthReferences: boolean;
12
14
  /**
13
15
  * Run requests carry the caller's exact `runControlRef`, and admission
14
16
  * echoes the executionId. Detached dispatch needs both: it sends the
@@ -9,6 +9,7 @@ import { awaitWithSignal } from "./tangle-contract-safety.js";
9
9
  * leaves a required flag unset.
10
10
  */
11
11
  export const UNPROVEN_DEPLOYMENT = {
12
+ cliAuthReferences: false,
12
13
  exactDispatch: false,
13
14
  canonicalCancellation: false,
14
15
  eventReplay: false,
@@ -32,6 +33,7 @@ export const UNPROVEN_DEPLOYMENT = {
32
33
  * document to decide whether to start one at all.
33
34
  */
34
35
  export const ADAPTER_CEILING_DEPLOYMENT = {
36
+ cliAuthReferences: true,
35
37
  exactDispatch: true,
36
38
  canonicalCancellation: true,
37
39
  eventReplay: true,
@@ -47,6 +49,7 @@ export function deploymentCapabilitySupport(document) {
47
49
  if (!document || typeof document !== "object")
48
50
  return UNPROVEN_DEPLOYMENT;
49
51
  return {
52
+ cliAuthReferences: document.cliAuthReferences === true,
50
53
  exactDispatch: document.dispatch?.runControlRef === true &&
51
54
  document.dispatch?.executionIdOnAdmission === true,
52
55
  canonicalCancellation: document.cancel?.canonicalRunCancellation === true &&
@@ -1,5 +1,6 @@
1
1
  import type { AgentEnvironment, AgentEnvironmentCapabilities, ResourceProfile } from "@tangle-network/agent-interface/environment-provider";
2
2
  import type { SandboxClientLike, SandboxInstanceLike, SandboxRuntimeCapabilityDocument } from "./tangle-types.js";
3
+ import { type ProfileCredentialSource } from "./model-credential-source.js";
3
4
  import type { TangleConfidentialAttestationVerifier } from "./tangle-types.js";
4
5
  /**
5
6
  * Compose one concrete sandbox into an environment.
@@ -30,6 +31,8 @@ export declare function sandboxInstanceAsEnvironment(box: SandboxInstanceLike, p
30
31
  resources?: ResourceProfile;
31
32
  confidentialAttestationVerifier?: TangleConfidentialAttestationVerifier;
32
33
  requireNativeSessionCapture?: boolean;
34
+ requireCliAuthReferences?: boolean;
35
+ credentialSource?: ProfileCredentialSource;
33
36
  captureCapabilities?: SandboxRuntimeCapabilityDocument;
34
37
  captureHarness?: string;
35
38
  }): Promise<AgentEnvironment>;
@@ -5,6 +5,7 @@ import { executionIdFromTurnInput, promptFromTurnInput, promptOptionsFromTurnInp
5
5
  import { creationFromSandboxCreateReceipt, placementInfoFromLoopPlacement, statusFromUnknown, } from "./tangle-environment-values.js";
6
6
  import { execResultFromSandboxExecResult } from "./tangle-result-values.js";
7
7
  import { capabilitiesForSandbox, frozenCapabilityDocument, sandboxCapabilitySupport, } from "./tangle-capabilities.js";
8
+ import { profileCredentialSource } from "./model-credential-source.js";
8
9
  import { deploymentCapabilitySupport, readDeploymentCapabilitySupport } from "./tangle-deployment-capabilities.js";
9
10
  import { awaitWithSignal, assertBoundedJson, boundedIdentifier, boundedString, } from "./tangle-contract-safety.js";
10
11
  import { assertExecOptions, assertOptionKeys, } from "./tangle-environment-validation.js";
@@ -56,6 +57,14 @@ export async function sandboxInstanceAsEnvironment(box, providerName, client, de
56
57
  const deployment = request?.captureCapabilities === undefined
57
58
  ? await readDeploymentCapabilitySupport(box, operation)
58
59
  : deploymentCapabilitySupport(request.captureCapabilities);
60
+ const recordedCredentials = box.metadata?.modelCredentials;
61
+ const recordedNativeReference = recordedCredentials !== null && typeof recordedCredentials === "object" &&
62
+ Object.hasOwn(recordedCredentials, "cliAuth");
63
+ if ((request?.requireCliAuthReferences || recordedNativeReference) && !deployment.cliAuthReferences) {
64
+ throw new Error("Tangle selected sandbox does not prove native credential reference support");
65
+ }
66
+ const boundCredentialSource = request?.credentialSource ??
67
+ (recordedCredentials !== undefined ? "subscription" : "managed");
59
68
  const capabilities = frozenCapabilityDocument(AgentEnvironmentCapabilitiesSchema.parse(capabilitiesForSandbox(declaredCapabilities, support, deployment, confidentialVerifierOption(request?.confidentialAttestationVerifier))));
60
69
  const workspaceBranching = capabilities.branching.checkpoint &&
61
70
  capabilities.branching.fork &&
@@ -77,11 +86,21 @@ export async function sandboxInstanceAsEnvironment(box, providerName, client, de
77
86
  // this handle and the observation reports the newest record it holds.
78
87
  const usageLog = createExecutionUsageLog();
79
88
  const assertCaptureInput = (input) => {
89
+ const backend = promptOptionsFromTurnInput(input, { provider: providerName, environmentId }).backend;
90
+ const turnSource = backend?.profile === undefined ? undefined : profileCredentialSource(backend.profile);
91
+ if (turnSource !== undefined && turnSource !== boundCredentialSource) {
92
+ throw new Error("Tangle turn credential source differs from its environment; create a separate environment for that profile");
93
+ }
94
+ if (backend?.model?.cliAuth !== undefined && boundCredentialSource !== "subscription") {
95
+ throw new Error("Tangle managed environment cannot inherit native subscription credentials");
96
+ }
97
+ if (backend?.model?.cliAuth !== undefined && !deployment.cliAuthReferences) {
98
+ throw new Error("Tangle selected sandbox does not prove native credential reference support");
99
+ }
80
100
  if (!request?.requireNativeSessionCapture)
81
101
  return;
82
102
  if (!request.captureCapabilities)
83
103
  throw new Error("Tangle native capture has no measured container capability document");
84
- const backend = promptOptionsFromTurnInput(input, { provider: providerName, environmentId }).backend;
85
104
  const profileHarness = typeof backend?.profile === "object" ? backend.profile.harness : undefined;
86
105
  if (backend?.type !== undefined && profileHarness !== undefined && backend.type !== profileHarness) {
87
106
  throw new Error("Tangle native capture turn backend differs from its exact profile harness");
@@ -1,4 +1,4 @@
1
- import type { AgentProfile } from "@tangle-network/agent-interface";
1
+ import { type AgentExactRunControlRef, type AgentProfile } from "@tangle-network/agent-interface";
2
2
  import type { AgentEnvironment } from "@tangle-network/agent-interface/environment-provider";
3
3
  import type { NativeCaptureProofLike, SandboxInstanceLike, TangleEvidenceAttemptLike, TangleEvidenceSourceLike } from "./tangle-types.js";
4
4
  interface WorkspaceEntryMetadata {
@@ -14,7 +14,10 @@ interface WorkspaceEntryMetadata {
14
14
  symlinkTarget: null;
15
15
  }
16
16
  export interface TangleEnvironmentEvidenceOptions {
17
+ /** Runtime artifact identity when controlRef is supplied; otherwise the native execution id. */
17
18
  executionId: string;
19
+ /** Durable admitted coordinates, including when a reconstructed environment has no session cache. */
20
+ controlRef?: AgentExactRunControlRef;
18
21
  harness: NonNullable<AgentProfile["harness"]>;
19
22
  /** Optional local image ID to compare with the running sidecar image. */
20
23
  expectedSidecarImageDigest?: string;
@@ -26,6 +29,8 @@ export interface TangleEnvironmentEvidenceOptions {
26
29
  signal?: AbortSignal;
27
30
  }
28
31
  export interface TangleSandboxEvidenceOptions extends Omit<TangleEnvironmentEvidenceOptions, "sandboxSessionId"> {
32
+ /** Runtime artifact identity; native executionId remains subject to path-safe validation. */
33
+ runtimeExecutionId?: string;
29
34
  sandboxSessionIds: readonly string[];
30
35
  /** Every observed execution on each retained Sandbox session. */
31
36
  sessionExecutionIds?: Readonly<Record<string, readonly string[]>>;
@@ -42,6 +47,7 @@ export interface TangleEnvironmentEvidence {
42
47
  provider: string;
43
48
  environmentId: string;
44
49
  executionId: string;
50
+ controlRef?: AgentExactRunControlRef;
45
51
  captureProof?: NativeCaptureProofLike;
46
52
  workspaceScope: "environment";
47
53
  workspaceRoot: string;
@@ -1,4 +1,5 @@
1
1
  import { createHash } from "node:crypto";
2
+ import { AgentExactRunControlRefSchema } from "@tangle-network/agent-interface";
2
3
  import { requireNativeCaptureProof } from "./tangle-native-capture-proof.js";
3
4
  const handles = new WeakMap();
4
5
  const blockedNames = new Set([".ssh", ".config", ".claude", ".codex", ".opencode", ".env", ".env.local", ".npmrc", ".sidecar"]);
@@ -20,19 +21,31 @@ export async function captureTangleEnvironmentEvidence(environment, options) {
20
21
  const state = handles.get(environment);
21
22
  if (!state || state.box.id !== environment.id)
22
23
  throw new Error("Tangle evidence requires a live provider environment handle");
23
- const sessionIds = new Set([...state.sessions.entries()]
24
- .filter(([, executions]) => executions.has(options.executionId))
24
+ const controlRef = options.controlRef === undefined ? undefined : AgentExactRunControlRefSchema.parse(options.controlRef);
25
+ if (controlRef && (controlRef.environmentId !== environment.id || controlRef.provider !== environment.provider ||
26
+ (options.sandboxSessionId != null && options.sandboxSessionId !== controlRef.sessionId))) {
27
+ throw new Error("Tangle evidence control reference names another environment or session");
28
+ }
29
+ const executionId = controlRef?.executionId ?? options.executionId;
30
+ const sessionIds = controlRef ? new Set([controlRef.sessionId]) : new Set([...state.sessions.entries()]
31
+ .filter(([, executions]) => executions.has(executionId))
25
32
  .map(([id]) => id));
26
33
  if (options.sandboxSessionId != null)
27
34
  sessionIds.add(options.sandboxSessionId);
35
+ const sessionExecutionIds = Object.fromEntries([...sessionIds].filter((id) => state.sessions.has(id))
36
+ .map((id) => [id, [...state.sessions.get(id)]]));
37
+ if (controlRef)
38
+ sessionExecutionIds[controlRef.sessionId] = [...new Set([
39
+ ...(sessionExecutionIds[controlRef.sessionId] ?? []), controlRef.executionId,
40
+ ])];
28
41
  return captureTangleSandboxEvidence(state.box, {
29
- executionId: options.executionId,
42
+ executionId,
43
+ ...(controlRef === undefined ? {} : { runtimeExecutionId: options.executionId, controlRef }),
30
44
  harness: options.harness,
31
45
  expectedSidecarImageDigest: options.expectedSidecarImageDigest,
32
46
  requireNativeSessionCapture: options.requireNativeSessionCapture,
33
47
  sandboxSessionIds: [...sessionIds],
34
- sessionExecutionIds: Object.fromEntries([...sessionIds].filter((id) => state.sessions.has(id))
35
- .map((id) => [id, [...state.sessions.get(id)]])),
48
+ sessionExecutionIds,
36
49
  maxBytes: options.maxBytes,
37
50
  signal: options.signal,
38
51
  });
@@ -41,6 +54,16 @@ export async function captureTangleEnvironmentEvidence(environment, options) {
41
54
  export async function captureTangleSandboxEvidence(box, options) {
42
55
  if (!safeIdentifier(box.id) || !safeIdentifier(options.executionId))
43
56
  throw new Error("Tangle evidence requires exact box and execution ids");
57
+ const controlRef = options.controlRef === undefined ? undefined : AgentExactRunControlRefSchema.parse(options.controlRef);
58
+ if (controlRef && (controlRef.environmentId !== box.id ||
59
+ controlRef.executionId !== options.executionId || !options.sandboxSessionIds?.includes(controlRef.sessionId))) {
60
+ throw new Error("Tangle evidence control reference does not bind the exact native capture");
61
+ }
62
+ if (options.runtimeExecutionId !== undefined && (!controlRef || typeof options.runtimeExecutionId !== "string" ||
63
+ !options.runtimeExecutionId.length || options.runtimeExecutionId.length > 2048 || /[\u0000-\u001f\u007f]/.test(options.runtimeExecutionId))) {
64
+ throw new Error("Tangle evidence Runtime artifact identity requires an exact admitted control reference");
65
+ }
66
+ const artifactExecutionId = options.runtimeExecutionId ?? options.executionId;
44
67
  if (!safeIdentifier(options.harness))
45
68
  throw new Error("Tangle evidence requires an exact profile harness");
46
69
  if (options.expectedSidecarImageDigest !== undefined &&
@@ -603,7 +626,7 @@ export async function captureTangleSandboxEvidence(box, options) {
603
626
  capturedBytes += manifest.byteLength;
604
627
  }
605
628
  sessions.push({
606
- id, executionId: options.executionId, executionIds: [...executionIds], eventCountsByExecutionId,
629
+ id, executionId: artifactExecutionId, executionIds: [...executionIds], eventCountsByExecutionId,
607
630
  backendType: options.harness, sidecarImageDigest, sidecarBundleRevision,
608
631
  transportEvents: executionIds.every((executionId) => eventCountsByExecutionId[executionId] > 0) ? "complete" : "unavailable",
609
632
  eventCount: events.length, messageCount: messages.length, messageScope: "session",
@@ -620,9 +643,10 @@ export async function captureTangleSandboxEvidence(box, options) {
620
643
  }
621
644
  }
622
645
  const provenance = {
623
- provider: "tangle-sandbox",
646
+ provider: controlRef?.provider ?? "tangle-sandbox",
624
647
  environmentId: box.id,
625
- executionId: options.executionId,
648
+ executionId: artifactExecutionId,
649
+ ...(controlRef === undefined ? {} : { controlRef }),
626
650
  ...(captureProof ? { captureProof } : {}),
627
651
  workspaceScope: "environment",
628
652
  workspaceRoot,
@@ -25,7 +25,7 @@ declare const SANDBOX_BACKEND_FIELD_LIST: readonly ["runtimeAttachments", "type"
25
25
  * with `authFiles` for a subscription seat — so it is checked field by field
26
26
  * rather than passed through as opaque JSON.
27
27
  */
28
- declare const SANDBOX_BACKEND_MODEL_FIELD_LIST: readonly ["provider", "model", "apiKey", "baseUrl", "maxThinkingTokens", "mode", "apiKeyEnv", "authMode", "authFiles"];
28
+ declare const SANDBOX_BACKEND_MODEL_FIELD_LIST: readonly ["provider", "model", "apiKey", "baseUrl", "maxThinkingTokens", "mode", "apiKeyEnv", "cliAuth", "authMode", "authFiles"];
29
29
  /**
30
30
  * The two lists above are the SDK's field sets, restated as values because a
31
31
  * TypeScript type cannot be read at run time. This pin keeps them exact in
@@ -1,6 +1,8 @@
1
+ import { assertCliAuthReferenceSupported, cliAuthReferenceSchema, } from "@tangle-network/sandbox/auth";
1
2
  import { agentProfileSchema, CONTRACT_MAX_JSON_BYTES, boundedEventContentRecordSchema, isBoundedEventContentJson, AgentExactRunControlRefSchema, AgentTurnInputSchema, ContextTransferReceiptSchema, contextTransferResultMatchesRequest, } from "@tangle-network/agent-interface";
2
3
  import { tokenUsageFromData } from "./tangle-result-values.js";
3
4
  import { assertBoundedJson, boundedString, PROFILE_AT_PROFILE, } from "./tangle-contract-safety.js";
5
+ import { profileCredentialSource } from "./model-credential-source.js";
4
6
  import { tangleRuntimeAttachments } from "./tangle-runtime-attachments.js";
5
7
  export function promptFromTurnInput(input) {
6
8
  AgentTurnInputSchema.parse(input);
@@ -92,6 +94,7 @@ const SANDBOX_BACKEND_MODEL_FIELD_LIST = [
92
94
  "maxThinkingTokens",
93
95
  "mode",
94
96
  "apiKeyEnv",
97
+ "cliAuth",
95
98
  "authMode",
96
99
  "authFiles",
97
100
  ];
@@ -140,6 +143,24 @@ function sandboxPromptBackend(value) {
140
143
  ? {}
141
144
  : { metadata: sandboxPromptBackendMetadata(present.metadata) }),
142
145
  };
146
+ if (backend.profile?.model?.metadata?.credentialSource === "managed" &&
147
+ (backend.model?.cliAuth !== undefined || backend.model?.authFiles !== undefined || backend.model?.authMode === "oauth")) {
148
+ throw new Error("Tangle explicit managed profile cannot receive native subscription credentials");
149
+ }
150
+ if (backend.profile !== undefined)
151
+ profileCredentialSource(backend.profile);
152
+ if (backend.model?.cliAuth !== undefined) {
153
+ if (backend.type === undefined) {
154
+ throw new Error("Tangle prompt cliAuth requires the selected backend type");
155
+ }
156
+ if (backend.profile !== undefined && profileCredentialSource(backend.profile) !== "subscription") {
157
+ throw new Error("Tangle prompt native credentials require subscription intent in the exact profile");
158
+ }
159
+ if (backend.profile?.harness !== undefined && backend.profile.harness !== backend.type) {
160
+ throw new Error("Tangle prompt cliAuth must use the exact profile harness");
161
+ }
162
+ assertCliAuthReferenceSupported(backend.type, backend.model);
163
+ }
143
164
  if (present.runtimeAttachments !== undefined) {
144
165
  Object.assign(backend, {
145
166
  runtimeAttachments: tangleRuntimeAttachments(present.runtimeAttachments, backend.profile),
@@ -182,6 +203,12 @@ function sandboxPromptBackendModel(value) {
182
203
  if (present.authFiles !== undefined) {
183
204
  model.authFiles = sandboxPromptAuthFiles(present.authFiles);
184
205
  }
206
+ if (present.cliAuth !== undefined) {
207
+ const parsed = cliAuthReferenceSchema.safeParse(present.cliAuth);
208
+ if (!parsed.success)
209
+ throw new Error("Tangle prompt cliAuth must be a valid stored-secret reference");
210
+ model.cliAuth = parsed.data;
211
+ }
185
212
  return model;
186
213
  }
187
214
  function sandboxPromptBackendServer(value) {
@@ -8,15 +8,20 @@ import { assertCreateInputShape, assertMappedCreateOptions, assertMappedSecretNa
8
8
  import { statusFromUnknown } from "./tangle-environment-values.js";
9
9
  import { requireNativeCaptureCapability, requireNativeCaptureProof } from "./tangle-native-capture-proof.js";
10
10
  import { awaitSandboxRunning, DEFAULT_TANGLE_READY_TIMEOUT_MS, } from "./tangle-readiness.js";
11
+ import { profileCredentialSource } from "./model-credential-source.js";
11
12
  import { requestedResourceProfile } from "./tangle-resources.js";
12
13
  import { assertBoundedJson, attachCleanupHandle, awaitWithSignal, boundedIdentifier, boundedString, MAX_LIST_RESULTS, PROFILE_AT_ROOT, SANDBOX_LIST_PAGE_SIZE, } from "./tangle-contract-safety.js";
13
14
  export function createTangleProvider(options) {
14
- const modelCredentials = captureModelCredentials(options.modelCredentials);
15
+ const resolveModelCredentials = typeof options.modelCredentials === "function"
16
+ ? options.modelCredentials : undefined;
17
+ const modelCredentials = resolveModelCredentials === undefined
18
+ ? captureModelCredentials(options.modelCredentials)
19
+ : undefined;
15
20
  if (options.requireNativeSessionCapture !== undefined && typeof options.requireNativeSessionCapture !== "boolean") {
16
21
  throw new Error("Tangle requireNativeSessionCapture must be a boolean");
17
22
  }
18
23
  const mapCreateInput = options.mapCreateInput;
19
- if (modelCredentials !== undefined && mapCreateInput !== undefined) {
24
+ if ((modelCredentials !== undefined || resolveModelCredentials !== undefined) && mapCreateInput !== undefined) {
20
25
  throw new Error("Tangle modelCredentials cannot be combined with mapCreateInput");
21
26
  }
22
27
  const providerName = options.name ?? "tangle-sandbox";
@@ -67,9 +72,44 @@ export function createTangleProvider(options) {
67
72
  if (input.providerOptions && Object.keys(input.providerOptions).length > 0) {
68
73
  throw new Error("Tangle create providerOptions are not supported");
69
74
  }
75
+ const credentialSource = typeof input.profile === "string" ? "managed" : profileCredentialSource(input.profile);
76
+ const subscription = credentialSource === "subscription";
77
+ if (Object.hasOwn(input.metadata ?? {}, "modelCredentials")) {
78
+ throw new Error("Tangle credential selection owns metadata.modelCredentials");
79
+ }
80
+ const explicitCredentialIntent = typeof input.profile !== "string" && input.profile.model?.metadata?.credentialSource !== undefined;
81
+ const availableStaticCredentials = modelCredentials !== undefined &&
82
+ (subscription || (!explicitCredentialIntent && !("cliAuth" in modelCredentials))) ? modelCredentials : undefined;
83
+ if (subscription && availableStaticCredentials === undefined && resolveModelCredentials === undefined) {
84
+ throw new Error("Tangle subscription profile requires configured modelCredentials before creation");
85
+ }
86
+ // Validate placement before contacting the account owner; managed profiles never contact it.
87
+ const defaultOptions = mapCreateInput === undefined
88
+ ? sandboxOptionsFromCreateInput(input, options.defaultBackend, parsedWorkspace, availableStaticCredentials, subscription)
89
+ : undefined;
90
+ let selectedCredentials = availableStaticCredentials;
91
+ if (subscription && resolveModelCredentials !== undefined) {
92
+ const selected = await awaitWithSignal(Promise.resolve(resolveModelCredentials(input)), input.signal);
93
+ if (selected === undefined) {
94
+ throw new Error("Tangle subscription modelCredentials resolver must return a selected stored-secret reference");
95
+ }
96
+ selectedCredentials = captureModelCredentials(selected);
97
+ }
98
+ input.signal?.throwIfAborted();
70
99
  const mappedOptions = mapCreateInput?.(input) ??
71
- sandboxOptionsFromCreateInput(input, options.defaultBackend, parsedWorkspace, modelCredentials);
100
+ (subscription && resolveModelCredentials !== undefined ? sandboxOptionsFromCreateInput(input, options.defaultBackend, parsedWorkspace, selectedCredentials, true) : defaultOptions);
72
101
  assertMappedCreateOptions(mappedOptions);
102
+ if (Object.hasOwn(mappedOptions.metadata ?? {}, "modelCredentials") &&
103
+ (!subscription || selectedCredentials === undefined ||
104
+ canonicalCandidateDigest(mappedOptions.metadata?.modelCredentials) !== canonicalCandidateDigest(selectedCredentials))) {
105
+ throw new Error("Tangle mapped metadata.modelCredentials must contain its selected subscription reference");
106
+ }
107
+ if (mappedOptions.backend?.profile !== undefined && profileCredentialSource(mappedOptions.backend.profile) !== credentialSource) {
108
+ throw new Error("Tangle mapped create options must preserve the exact profile credential source");
109
+ }
110
+ if (!subscription && mappedOptions.backend?.model?.cliAuth !== undefined) {
111
+ throw new Error("Tangle managed profile cannot provision native subscription credentials");
112
+ }
73
113
  const createOptions = deepFreeze(structuredClone({
74
114
  ...mappedOptions,
75
115
  ...(options.requireNativeSessionCapture ? { requireNativeSessionCapture: true } : {}),
@@ -167,6 +207,8 @@ export function createTangleProvider(options) {
167
207
  ...(requestedResources === undefined
168
208
  ? {}
169
209
  : { resources: requestedResources }),
210
+ credentialSource,
211
+ ...(createOptions.backend?.model?.cliAuth === undefined ? {} : { requireCliAuthReferences: true }),
170
212
  ...(options.requireNativeSessionCapture ? { requireNativeSessionCapture: true } : {}),
171
213
  ...(captureCapabilities === undefined ? {} : { captureCapabilities }),
172
214
  ...(captureHarness === undefined ? {} : { captureHarness }),
@@ -1,3 +1,4 @@
1
+ import type { CliAuthReference } from "@tangle-network/sandbox/auth";
1
2
  import type { BackendRegistryEntry, BackendRegistryResponse, BackendType, CreateSandboxOptions, ExecResult as SandboxExecResult, PromptOptions, PromptResult, SandboxEvent } from "@tangle-network/sandbox";
2
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";
3
4
  import type { AgentEnvironmentCapabilities, AgentEnvironmentProvider, CreateAgentEnvironmentInput } from "@tangle-network/agent-interface/environment-provider";
@@ -101,6 +102,8 @@ export interface SandboxSubscriptionLike {
101
102
  */
102
103
  export interface SandboxRuntimeCapabilityDocument {
103
104
  schema?: number;
105
+ /** The selected runtime resolves stored-secret native authentication references. */
106
+ cliAuthReferences?: boolean;
104
107
  nativeSessionCaptureVersion?: number;
105
108
  nativeSessionCaptureHarnesses?: readonly string[];
106
109
  agentInterface?: string;
@@ -746,6 +749,14 @@ export interface SandboxInteractionCommandResultLike {
746
749
  [key: string]: unknown;
747
750
  };
748
751
  }
752
+ export type TangleModelCredentials = {
753
+ apiKeyEnv: string;
754
+ baseUrl: string;
755
+ } | {
756
+ cliAuth: CliAuthReference;
757
+ };
758
+ /** Select one public stored-secret reference for this exact create identity. */
759
+ export type TangleModelCredentialResolver = (input: Readonly<CreateAgentEnvironmentInput>) => TangleModelCredentials | undefined | Promise<TangleModelCredentials | undefined>;
749
760
  export interface TangleProviderOptions {
750
761
  client: SandboxClientLike;
751
762
  name?: string;
@@ -754,14 +765,13 @@ export interface TangleProviderOptions {
754
765
  /** Require the selected Sandbox host to prove native session capture for every create. */
755
766
  requireNativeSessionCapture?: boolean;
756
767
  /**
757
- * Stored model credential and endpoint used by the default create mapping.
758
- * Each create must explicitly list apiKeyEnv in its secrets.
759
- * Cannot be combined with mapCreateInput; never accepts credential values.
768
+ * Available stored credentials selected through exact profile credential intent.
769
+ * Managed profiles skip selectors and native references; explicit managed intent skips all references.
770
+ * Unmarked legacy profiles retain their static API reference and grant only its selected secret.
771
+ * Subscription selections grant only their selected secret and record its public reference.
772
+ * Cannot be combined with mapCreateInput; never accepts credential values or model overrides.
760
773
  */
761
- modelCredentials?: {
762
- apiKeyEnv: string;
763
- baseUrl: string;
764
- };
774
+ modelCredentials?: TangleModelCredentials | TangleModelCredentialResolver;
765
775
  capabilities?: AgentEnvironmentCapabilities | (() => AgentEnvironmentCapabilities | Promise<AgentEnvironmentCapabilities>);
766
776
  validateProfile?: AgentEnvironmentProvider["validateProfile"];
767
777
  /** Replaces the default mapping, including its backend and profile selection. */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tangle-network/agent-provider-tangle",
3
- "version": "3.0.0",
3
+ "version": "3.1.1",
4
4
  "description": "AgentEnvironmentProvider adapter for Tangle sandboxes",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -11,6 +11,11 @@
11
11
  "import": "./dist/index.js",
12
12
  "types": "./dist/index.d.ts",
13
13
  "default": "./dist/index.js"
14
+ },
15
+ "./node": {
16
+ "import": "./dist/node.js",
17
+ "types": "./dist/node.d.ts",
18
+ "default": "./dist/node.js"
14
19
  }
15
20
  },
16
21
  "repository": {
@@ -100,13 +105,19 @@
100
105
  "dist/tangle-workspace-recovery.d.ts",
101
106
  "dist/tangle-workspace-recovery.js",
102
107
  "README.md",
103
- "LICENSE"
108
+ "LICENSE",
109
+ "dist/node.js",
110
+ "dist/node.d.ts",
111
+ "dist/command-model-credentials.js",
112
+ "dist/command-model-credentials.d.ts",
113
+ "dist/model-credential-source.js",
114
+ "dist/model-credential-source.d.ts"
104
115
  ],
105
116
  "dependencies": {
106
117
  "@tangle-network/agent-interface": "^2.15.0"
107
118
  },
108
119
  "peerDependencies": {
109
- "@tangle-network/sandbox": ">=0.58.4 <1.0.0"
120
+ "@tangle-network/sandbox": ">=0.58.7 <1.0.0"
110
121
  },
111
122
  "peerDependenciesMeta": {
112
123
  "@tangle-network/sandbox": {
@@ -116,7 +127,7 @@
116
127
  "devDependencies": {
117
128
  "@tangle-network/agent-provider-testkit": "0.10.0",
118
129
  "@tangle-network/agent-runtime": "0.286.0",
119
- "@tangle-network/sandbox": "0.58.4",
130
+ "@tangle-network/sandbox": "0.58.7",
120
131
  "@types/node": "26.6.3",
121
132
  "typescript": "7.0.2",
122
133
  "vitest": "5.0.2"