@tangle-network/agent-provider-tangle 2.0.0 → 3.1.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
@@ -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`.
@@ -455,12 +551,19 @@ The adapter rejects ordinary sandboxes during create, recovery, and list operati
455
551
 
456
552
  ## Private session evidence
457
553
 
458
- Call `readTangleEvidenceCapabilities(client)` before creating a sandbox when complete evidence is required.
459
- It requires workspace capture, an explicit native capture harness list, and the next-create sidecar image digest.
460
- A global capture flag cannot admit a profile whose harness is absent from that list.
461
- Unprofiled exact-process and checkpoint restores retain the stricter global guarantee.
462
- Apply `assertTangleEvidenceProfileCapability(proof, profile)` to the exact profile in each create hook.
463
- An unavailable or unproven capability fails before the sandbox spends resources.
554
+ Set `requireNativeSessionCapture: true` when the provider must retain complete native evidence.
555
+ Sandbox selects a host with fresh capture proof and returns proof for the created container.
556
+ The provider matches that proof to the create receipt before returning the environment.
557
+ Agent creation and reconnect check the selected container's capture protocol and exact backend through `box.capabilities()`.
558
+ Unsupported agent capture refuses before a model turn.
559
+ A newly created container is cleaned up when its required proof is missing.
560
+ An unrelated host or pending fleet update does not determine this container's admission.
561
+
562
+ Exact-process creation retains its container proof and existing managed-process output and terminal contracts.
563
+ Checkpoint restoration requires its container proof and exact source/checkpoint identity.
564
+ A restored agent environment verifies its actual backend when reconnected.
565
+ The capture requirement also reaches checkpoint operations exposed by an environment.
566
+ Fleet capability summaries are diagnostic observations, not placement admission.
464
567
 
465
568
  Call `captureTangleEnvironmentEvidence(environment, options)` before destroying a provider environment.
466
569
  For a Runtime-owned box, call `captureTangleSandboxEvidence(box, options)` with exact session and execution IDs.
@@ -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
+ }
@@ -1,7 +1,7 @@
1
1
  import { assertBoundedJson, attachCleanupHandle, awaitWithSignal, boundedIdentifier, boundedString, exactProcessRequestDigest, isBoundedJson, MAX_LIST_RESULTS, SANDBOX_LIST_PAGE_SIZE, } from "./tangle-contract-safety.js";
2
2
  import { sandboxInstanceAsExactProcessEnvironment } from "./tangle-exact-process-environment.js";
3
3
  import { awaitSandboxRunning } from "./tangle-readiness.js";
4
- import { requireNativeCaptureCapability, requireNativeCaptureProof } from "./tangle-native-capture-proof.js";
4
+ import { requireNativeCaptureProof } from "./tangle-native-capture-proof.js";
5
5
  import { assertExactProcessSandbox, assertSupportedProviderOptions, assertUnreservedMetadata, EXACT_PROCESS_METADATA_KEY, isExactProcessRequestConflict, isExactProcessSandbox, metadataMatches, assertSignalOptions, } from "./tangle-exact-process-validation.js";
6
6
  const IMMUTABLE_TANGLE_IMAGE = /^(?:sha256:[a-f0-9]{64}|\S+@sha256:[a-f0-9]{64})$/i;
7
7
  export function createTangleExactProcessProvider(input) {
@@ -22,8 +22,6 @@ export function createTangleExactProcessProvider(input) {
22
22
  assertUnreservedMetadata(createInput.metadata);
23
23
  const identityDigest = exactProcessRequestDigest(createInput, providerName, options);
24
24
  createInput.signal?.throwIfAborted();
25
- if (input.requireNativeSessionCapture)
26
- await requireNativeCaptureCapability(client);
27
25
  const createPromise = client.create({
28
26
  ...exactSandboxOptions(createInput, options, providerName, identityDigest),
29
27
  ...(input.requireNativeSessionCapture ? { requireNativeSessionCapture: true } : {}),
@@ -41,7 +39,7 @@ export function createTangleExactProcessProvider(input) {
41
39
  if (createInput.signal?.aborted) {
42
40
  void createPromise
43
41
  .then(async (lateBox) => {
44
- if (!lateBox.delete) {
42
+ if (lateBox.createReceipt?.()?.outcome !== "created" || !lateBox.delete) {
45
43
  attachCleanupHandle(error, lateBox);
46
44
  return;
47
45
  }
@@ -80,6 +78,10 @@ export function createTangleExactProcessProvider(input) {
80
78
  if (isExactProcessRequestConflict(box, providerName, options.teamId, createInput.idempotencyKey, identityDigest)) {
81
79
  throw new Error("Tangle exact process idempotency key conflicts with an existing request", { cause: error });
82
80
  }
81
+ if (box.createReceipt?.()?.outcome !== "created") {
82
+ attachCleanupHandle(error, box);
83
+ throw error;
84
+ }
83
85
  if (!box.delete) {
84
86
  const baseError = error instanceof Error ? error : new Error(String(error));
85
87
  throw Object.assign(baseError, {
package/dist/index.d.ts CHANGED
@@ -3,8 +3,8 @@ export { JsonBoundError, MAX_INLINE_PAYLOAD_BYTES, MAX_PAYLOAD_STRING_BYTES, MAX
3
3
  export type { JsonBoundRule, JsonBoundViolation } from "./tangle-contract-safety.js";
4
4
  export * from "./tangle-types.js";
5
5
  export { createTangleProvider } from "./tangle-provider.js";
6
- export { assertTangleEvidenceCapability, assertTangleEvidenceProfileCapability, readTangleEvidenceCapabilities, captureTangleEnvironmentEvidence, captureTangleSandboxEvidence } from "./tangle-evidence.js";
7
- export type { TangleEvidenceCapabilities, TangleEnvironmentEvidence, TangleEnvironmentEvidenceOptions, TangleSandboxEvidenceOptions } from "./tangle-evidence.js";
6
+ export { captureTangleEnvironmentEvidence, captureTangleSandboxEvidence } from "./tangle-evidence.js";
7
+ export type { TangleEnvironmentEvidence, TangleEnvironmentEvidenceOptions, TangleSandboxEvidenceOptions } from "./tangle-evidence.js";
8
8
  export { DEFAULT_TANGLE_READY_TIMEOUT_MS } from "./tangle-readiness.js";
9
9
  export { defaultTangleSandboxCapabilities } from "./tangle-capabilities.js";
10
10
  export { createTangleWorkspaceBranching, supportsWorkspaceBranching, } from "./tangle-workspace-branching.js";
@@ -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
@@ -1,9 +1,10 @@
1
1
  export { JsonBoundError, MAX_INLINE_PAYLOAD_BYTES, MAX_PAYLOAD_STRING_BYTES, MAX_TOTAL_PAYLOAD_BYTES, } from "./tangle-contract-safety.js";
2
2
  export * from "./tangle-types.js";
3
3
  export { createTangleProvider } from "./tangle-provider.js";
4
- export { assertTangleEvidenceCapability, assertTangleEvidenceProfileCapability, readTangleEvidenceCapabilities, captureTangleEnvironmentEvidence, captureTangleSandboxEvidence } from "./tangle-evidence.js";
4
+ export { captureTangleEnvironmentEvidence, captureTangleSandboxEvidence } from "./tangle-evidence.js";
5
5
  export { DEFAULT_TANGLE_READY_TIMEOUT_MS } from "./tangle-readiness.js";
6
6
  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 &&
@@ -23,5 +23,5 @@ type ExactExecutionEventStream = (options: {
23
23
  * environment observation reads it, because Sandbox reports usage per
24
24
  * execution result and never for the environment.
25
25
  */
26
- export declare function sandboxSessionAsAgentSession(session: SandboxSessionLike, controlRef: AgentRunControlRef | undefined, provider: string, environmentId: string, dispatch: ((input: AgentTurnInput) => Promise<AgentSessionRef>) | undefined, exactExecutionEvents: ExactExecutionEventStream | undefined, retainedControl: boolean, interactionResponses: boolean, usageLog?: ExecutionUsageLog, nativeContinuation?: boolean, onExecution?: (executionId: string) => void): AgentSession;
26
+ export declare function sandboxSessionAsAgentSession(session: SandboxSessionLike, controlRef: AgentRunControlRef | undefined, provider: string, environmentId: string, dispatch: ((input: AgentTurnInput) => Promise<AgentSessionRef>) | undefined, exactExecutionEvents: ExactExecutionEventStream | undefined, retainedControl: boolean, interactionResponses: boolean, usageLog?: ExecutionUsageLog, nativeContinuation?: boolean, beforePrompt?: (input: AgentTurnInput) => void, onExecution?: (executionId: string) => void): AgentSession;
27
27
  export {};
@@ -24,7 +24,7 @@ import { hasReplayPayload, interruptExecutionAfterAbort, sessionPromptRequestDig
24
24
  * environment observation reads it, because Sandbox reports usage per
25
25
  * execution result and never for the environment.
26
26
  */
27
- export function sandboxSessionAsAgentSession(session, controlRef, provider, environmentId, dispatch, exactExecutionEvents, retainedControl, interactionResponses, usageLog, nativeContinuation = false, onExecution) {
27
+ export function sandboxSessionAsAgentSession(session, controlRef, provider, environmentId, dispatch, exactExecutionEvents, retainedControl, interactionResponses, usageLog, nativeContinuation = false, beforePrompt, onExecution) {
28
28
  const measured = (executionId, result) => {
29
29
  usageLog?.record(executionId, result.usage);
30
30
  return result;
@@ -317,6 +317,7 @@ export function sandboxSessionAsAgentSession(session, controlRef, provider, envi
317
317
  }));
318
318
  },
319
319
  async prompt(input) {
320
+ beforePrompt?.(input);
320
321
  AgentTurnInputSchema.parse(input);
321
322
  input.signal?.throwIfAborted();
322
323
  if (promptInFlight) {
@@ -1,5 +1,6 @@
1
1
  import type { AgentEnvironment, AgentEnvironmentCapabilities, ResourceProfile } from "@tangle-network/agent-interface/environment-provider";
2
- import type { SandboxClientLike, SandboxInstanceLike } from "./tangle-types.js";
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.
@@ -29,4 +30,9 @@ export declare function sandboxInstanceAsEnvironment(box: SandboxInstanceLike, p
29
30
  }, request?: {
30
31
  resources?: ResourceProfile;
31
32
  confidentialAttestationVerifier?: TangleConfidentialAttestationVerifier;
33
+ requireNativeSessionCapture?: boolean;
34
+ requireCliAuthReferences?: boolean;
35
+ credentialSource?: ProfileCredentialSource;
36
+ captureCapabilities?: SandboxRuntimeCapabilityDocument;
37
+ captureHarness?: string;
32
38
  }): Promise<AgentEnvironment>;
@@ -5,7 +5,8 @@ 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 { readDeploymentCapabilitySupport } from "./tangle-deployment-capabilities.js";
8
+ import { profileCredentialSource } from "./model-credential-source.js";
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";
11
12
  import { interruptExecutionAfterAbort, } from "./tangle-environment-control.js";
@@ -19,6 +20,7 @@ import { createTangleTerminalRegistry } from "./tangle-terminal.js";
19
20
  import { createTangleInteractiveAgentRegistry } from "./tangle-interactive.js";
20
21
  import { confidentialVerifierOption, createTangleWorkspaceBranching, } from "./tangle-workspace-branching.js";
21
22
  import { bindTangleEvidenceEnvironment, noteTangleSession } from "./tangle-evidence.js";
23
+ import { assertNativeCaptureHarness } from "./tangle-native-capture-proof.js";
22
24
  /**
23
25
  * Compose one concrete sandbox into an environment.
24
26
  *
@@ -52,7 +54,17 @@ export async function sandboxInstanceAsEnvironment(box, providerName, client, de
52
54
  assertBoundedJson(box.metadata, "Tangle environment metadata");
53
55
  }
54
56
  const support = sandboxCapabilitySupport(box, client, request?.resources);
55
- const deployment = await readDeploymentCapabilitySupport(box, operation);
57
+ const deployment = request?.captureCapabilities === undefined
58
+ ? await readDeploymentCapabilitySupport(box, operation)
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");
56
68
  const capabilities = frozenCapabilityDocument(AgentEnvironmentCapabilitiesSchema.parse(capabilitiesForSandbox(declaredCapabilities, support, deployment, confidentialVerifierOption(request?.confidentialAttestationVerifier))));
57
69
  const workspaceBranching = capabilities.branching.checkpoint &&
58
70
  capabilities.branching.fork &&
@@ -63,6 +75,7 @@ export async function sandboxInstanceAsEnvironment(box, providerName, client, de
63
75
  client,
64
76
  provider: providerName,
65
77
  ...confidentialVerifierOption(request?.confidentialAttestationVerifier),
78
+ ...(request?.requireNativeSessionCapture ? { requireNativeSessionCapture: true } : {}),
66
79
  })
67
80
  : undefined;
68
81
  // The published document is the single source for what this environment
@@ -72,6 +85,28 @@ export async function sandboxInstanceAsEnvironment(box, providerName, client, de
72
85
  // Usage is measured per execution, so the log collects what runs through
73
86
  // this handle and the observation reports the newest record it holds.
74
87
  const usageLog = createExecutionUsageLog();
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
+ }
100
+ if (!request?.requireNativeSessionCapture)
101
+ return;
102
+ if (!request.captureCapabilities)
103
+ throw new Error("Tangle native capture has no measured container capability document");
104
+ const profileHarness = typeof backend?.profile === "object" ? backend.profile.harness : undefined;
105
+ if (backend?.type !== undefined && profileHarness !== undefined && backend.type !== profileHarness) {
106
+ throw new Error("Tangle native capture turn backend differs from its exact profile harness");
107
+ }
108
+ assertNativeCaptureHarness(request.captureCapabilities, backend?.type ?? profileHarness ?? request.captureHarness);
109
+ };
75
110
  // The single destroy this handle performs, once it has been asked for.
76
111
  let destruction;
77
112
  const terminals = capabilities.interactiveTerminal?.attach === true
@@ -81,9 +116,13 @@ export async function sandboxInstanceAsEnvironment(box, providerName, client, de
81
116
  capabilities.interactiveAgent.control === true
82
117
  ? createTangleInteractiveAgentRegistry(box, providerName, environmentId)
83
118
  : undefined;
84
- const dispatch = capabilities.streaming.detach && box.dispatchPrompt
119
+ const dispatchRun = capabilities.streaming.detach && box.dispatchPrompt
85
120
  ? dispatchEnvironmentRun(box, providerName, environmentId)
86
121
  : undefined;
122
+ const dispatch = dispatchRun === undefined ? undefined : (input) => {
123
+ assertCaptureInput(input);
124
+ return dispatchRun(input);
125
+ };
87
126
  const exactExecutionEvents = (options) => box.streamPrompt("", {
88
127
  sessionId: options.sessionId,
89
128
  executionId: options.executionId,
@@ -112,6 +151,7 @@ export async function sandboxInstanceAsEnvironment(box, providerName, client, de
112
151
  async *stream(input) {
113
152
  AgentTurnInputSchema.parse(input);
114
153
  input.signal?.throwIfAborted();
154
+ assertCaptureInput(input);
115
155
  const expectedExecutionId = executionIdFromTurnInput(input);
116
156
  const expectedSessionId = input.sessionId ?? input.controlRef?.sessionId;
117
157
  if (expectedSessionId)
@@ -184,7 +224,7 @@ export async function sandboxInstanceAsEnvironment(box, providerName, client, de
184
224
  if (session.id !== id) {
185
225
  throw new Error("sandbox session(id) returned an unrelated session");
186
226
  }
187
- const agentSession = sandboxSessionAsAgentSession(session, options?.controlRef, providerName, environmentId, dispatch, exactExecutionEvents, retainedControl, interactionResponses, usageLog, capabilities.nativeContinuation !== undefined, (executionId) => noteTangleSession(environment, id, executionId));
227
+ const agentSession = sandboxSessionAsAgentSession(session, options?.controlRef, providerName, environmentId, dispatch, exactExecutionEvents, retainedControl, interactionResponses, usageLog, capabilities.nativeContinuation !== undefined, assertCaptureInput, (executionId) => noteTangleSession(environment, id, executionId));
188
228
  // sessions.continue was granted from the probe session and the
189
229
  // deployment document together; this backstop holds every
190
230
  // concrete session to that grant, so a client whose sessions
@@ -1,19 +1,6 @@
1
- import type { AgentProfile, HarnessType } from "@tangle-network/agent-interface";
1
+ import type { AgentProfile } from "@tangle-network/agent-interface";
2
2
  import type { AgentEnvironment } from "@tangle-network/agent-interface/environment-provider";
3
- import type { NativeCaptureProofLike, SandboxClientLike, SandboxInstanceLike, TangleEvidenceAttemptLike, TangleEvidenceSourceLike } from "./tangle-types.js";
4
- export interface TangleEvidenceCapabilities {
5
- readonly workspaceCaptureV1: true;
6
- readonly nativeSessionCaptureV1: boolean;
7
- readonly nativeSessionCaptureVersion: 2;
8
- readonly nativeSessionCaptureHarnesses: readonly HarnessType[];
9
- readonly sidecarImageDigest: string;
10
- }
11
- /** Read a deployment guarantee once, before Runtime starts creating environments. */
12
- export declare function readTangleEvidenceCapabilities(client: SandboxClientLike): Promise<TangleEvidenceCapabilities>;
13
- /** Require the exact profile harness in the deployment's verified admission list. */
14
- export declare function assertTangleEvidenceProfileCapability(document: TangleEvidenceCapabilities, profile: AgentProfile): void;
15
- /** Refuse unsupported or unproven native trace retention before Sandbox create. */
16
- export declare function assertTangleEvidenceCapability(client: SandboxClientLike, profile: AgentProfile): Promise<void>;
3
+ import type { NativeCaptureProofLike, SandboxInstanceLike, TangleEvidenceAttemptLike, TangleEvidenceSourceLike } from "./tangle-types.js";
17
4
  interface WorkspaceEntryMetadata {
18
5
  path: string;
19
6
  type: "file" | "directory" | "symlink";
@@ -1,47 +1,9 @@
1
1
  import { createHash } from "node:crypto";
2
- import { parseBackendType } from "@tangle-network/sandbox";
3
- import { nativeCaptureHarnesses, requireNativeCaptureProof } from "./tangle-native-capture-proof.js";
2
+ import { requireNativeCaptureProof } from "./tangle-native-capture-proof.js";
4
3
  const handles = new WeakMap();
5
4
  const blockedNames = new Set([".ssh", ".config", ".claude", ".codex", ".opencode", ".env", ".env.local", ".npmrc", ".sidecar"]);
6
5
  const MAX_ENTRIES = 100_000;
7
6
  const MAX_EVENTS = 100_000;
8
- const verifiedCapabilities = new WeakSet();
9
- /** Read a deployment guarantee once, before Runtime starts creating environments. */
10
- export async function readTangleEvidenceCapabilities(client) {
11
- if (typeof client.evidenceCapabilities !== "function")
12
- throw new Error("Tangle deployment has no pre-create evidence capability query");
13
- const document = await client.evidenceCapabilities();
14
- if (document?.workspaceCaptureV1 !== true || typeof document.nativeSessionCaptureV1 !== "boolean" ||
15
- document.nativeSessionCaptureVersion !== 2 ||
16
- !/^sha256:[0-9a-f]{64}$/.test(document.sidecarImageDigest ?? "")) {
17
- throw new Error("Tangle deployment has not proven complete workspace and native session capture for next-create placement");
18
- }
19
- const verified = Object.freeze({
20
- workspaceCaptureV1: true,
21
- nativeSessionCaptureV1: document.nativeSessionCaptureV1,
22
- nativeSessionCaptureVersion: 2,
23
- nativeSessionCaptureHarnesses: nativeCaptureHarnesses(document.nativeSessionCaptureHarnesses),
24
- sidecarImageDigest: document.sidecarImageDigest,
25
- });
26
- verifiedCapabilities.add(verified);
27
- return verified;
28
- }
29
- /** Require the exact profile harness in the deployment's verified admission list. */
30
- export function assertTangleEvidenceProfileCapability(document, profile) {
31
- if (!verifiedCapabilities.has(document))
32
- throw new Error("Tangle evidence capability was not read from the deployment");
33
- if (!profile.harness)
34
- throw new Error("Tangle complete native session capture requires an exact profile harness");
35
- parseBackendType(profile.harness);
36
- if (!document.nativeSessionCaptureHarnesses.includes(profile.harness)) {
37
- throw new Error(`Tangle deployment has not proven native session capture for harness ${JSON.stringify(profile.harness)}`);
38
- }
39
- }
40
- /** Refuse unsupported or unproven native trace retention before Sandbox create. */
41
- export async function assertTangleEvidenceCapability(client, profile) {
42
- const document = await readTangleEvidenceCapabilities(client);
43
- assertTangleEvidenceProfileCapability(document, profile);
44
- }
45
7
  export function bindTangleEvidenceEnvironment(environment, box) {
46
8
  handles.set(environment, { box, sessions: new Map() });
47
9
  }
@@ -1,9 +1,10 @@
1
1
  import { type HarnessType } from "@tangle-network/agent-interface";
2
- import type { NativeCaptureProofLike, SandboxClientLike, SandboxInstanceLike } from "./tangle-types.js";
2
+ import type { NativeCaptureProofLike, SandboxInstanceLike, SandboxRuntimeCapabilityDocument } from "./tangle-types.js";
3
3
  /** Require a current host proof; a create must also prove its receipt names that same container. */
4
4
  export declare function requireNativeCaptureProof(box: SandboxInstanceLike, create?: boolean): NativeCaptureProofLike;
5
5
  /** Parse the deployment's explicit per-harness admission without inferring from a global flag. */
6
6
  export declare function nativeCaptureHarnesses(raw: unknown): readonly HarnessType[];
7
- /** Refuse an unsupported deployment before creating a billable sandbox.
8
- * Unprofiled exact-process and checkpoint restores retain the stricter universal guarantee. */
9
- export declare function requireNativeCaptureCapability(client: SandboxClientLike, harness?: string): Promise<void>;
7
+ /** Require the selected container's native protocol and exact agent backend before dispatch. */
8
+ export declare function requireNativeCaptureCapability(box: SandboxInstanceLike, harness: string): Promise<SandboxRuntimeCapabilityDocument>;
9
+ /** Validate each newly dispatched backend against this container's measured document. */
10
+ export declare function assertNativeCaptureHarness(document: SandboxRuntimeCapabilityDocument, harness: string | undefined): void;
@@ -33,24 +33,23 @@ export function nativeCaptureHarnesses(raw) {
33
33
  }
34
34
  return Object.freeze(parsed.data);
35
35
  }
36
- /** Refuse an unsupported deployment before creating a billable sandbox.
37
- * Unprofiled exact-process and checkpoint restores retain the stricter universal guarantee. */
38
- export async function requireNativeCaptureCapability(client, harness) {
39
- if (!client.evidenceCapabilities) {
40
- throw new Error("Tangle deployment has not proven native session capture for next-create placement");
36
+ /** Require the selected container's native protocol and exact agent backend before dispatch. */
37
+ export async function requireNativeCaptureCapability(box, harness) {
38
+ requireNativeCaptureProof(box);
39
+ if (!box.capabilities) {
40
+ throw new Error("Tangle selected container has no native capture capability document");
41
41
  }
42
- const document = await client.evidenceCapabilities();
43
- if (document.nativeSessionCaptureVersion !== 2) {
44
- throw new Error("Tangle deployment has not proven native session capture protocol 2 for next-create placement");
45
- }
46
- if (harness === undefined) {
47
- if (document.nativeSessionCaptureV1 !== true) {
48
- throw new Error("Tangle deployment has not proven native session capture for unprofiled next-create placement");
49
- }
50
- return;
42
+ const document = await box.capabilities();
43
+ if (document?.schema !== 1 || document.nativeSessionCaptureVersion !== 2) {
44
+ throw new Error("Tangle selected container has not proven native session capture protocol 2");
51
45
  }
46
+ assertNativeCaptureHarness(document, harness);
47
+ return document;
48
+ }
49
+ /** Validate each newly dispatched backend against this container's measured document. */
50
+ export function assertNativeCaptureHarness(document, harness) {
52
51
  const selected = harnessTypeSchema.safeParse(harness);
53
52
  if (!selected.success || !nativeCaptureHarnesses(document.nativeSessionCaptureHarnesses).includes(selected.data)) {
54
- throw new Error(`Tangle deployment has not proven native session capture for harness ${JSON.stringify(harness)}`);
53
+ throw new Error(`Tangle selected container has not proven native session capture for harness ${JSON.stringify(harness)}`);
55
54
  }
56
55
  }
@@ -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 } : {}),
@@ -113,14 +153,14 @@ export function createTangleProvider(options) {
113
153
  }
114
154
  }
115
155
  input.signal?.throwIfAborted();
156
+ const captureHarness = options.requireNativeSessionCapture ? createOptions.backend?.type : undefined;
116
157
  if (options.requireNativeSessionCapture) {
117
- if (createOptions.backend?.type === undefined) {
158
+ if (captureHarness === undefined) {
118
159
  throw new Error("Tangle complete native session capture requires an explicit selected backend before create");
119
160
  }
120
- if (typeof input.profile !== "string" && input.profile.harness !== undefined && input.profile.harness !== createOptions.backend.type) {
161
+ if (typeof input.profile !== "string" && input.profile.harness !== undefined && input.profile.harness !== captureHarness) {
121
162
  throw new Error("Tangle native capture selected backend differs from the exact profile harness");
122
163
  }
123
- await requireNativeCaptureCapability(options.client, createOptions.backend.type);
124
164
  }
125
165
  const createPromise = options.client.create(createOptions, input.signal ? { signal: input.signal } : undefined);
126
166
  let box;
@@ -131,7 +171,7 @@ export function createTangleProvider(options) {
131
171
  if (input.signal?.aborted) {
132
172
  void createPromise
133
173
  .then(async (lateBox) => {
134
- if (!lateBox.delete) {
174
+ if (lateBox.createReceipt?.()?.outcome !== "created" || !lateBox.delete) {
135
175
  attachCleanupHandle(error, lateBox);
136
176
  return;
137
177
  }
@@ -160,17 +200,28 @@ export function createTangleProvider(options) {
160
200
  input.signal?.throwIfAborted();
161
201
  if (options.requireNativeSessionCapture)
162
202
  requireNativeCaptureProof(box, true);
203
+ const captureCapabilities = captureHarness === undefined ? undefined
204
+ : await awaitWithSignal(requireNativeCaptureCapability(box, captureHarness), input.signal);
163
205
  const requestedResources = requestedResourceProfile(input.resources);
164
206
  const environment = await sandboxInstanceAsEnvironment(box, providerName, options.client, declaredCapabilities, input.signal ? { signal: input.signal } : undefined, {
165
207
  ...(requestedResources === undefined
166
208
  ? {}
167
209
  : { resources: requestedResources }),
210
+ credentialSource,
211
+ ...(createOptions.backend?.model?.cliAuth === undefined ? {} : { requireCliAuthReferences: true }),
212
+ ...(options.requireNativeSessionCapture ? { requireNativeSessionCapture: true } : {}),
213
+ ...(captureCapabilities === undefined ? {} : { captureCapabilities }),
214
+ ...(captureHarness === undefined ? {} : { captureHarness }),
168
215
  ...confidentialVerifierOption(options.confidentialAttestationVerifier),
169
216
  });
170
217
  input.signal?.throwIfAborted();
171
218
  return environment;
172
219
  }
173
220
  catch (error) {
221
+ if (box.createReceipt?.()?.outcome !== "created") {
222
+ attachCleanupHandle(error, box);
223
+ throw error;
224
+ }
174
225
  if (!box.delete) {
175
226
  const baseError = error instanceof Error ? error : new Error(String(error));
176
227
  throw Object.assign(baseError, { cleanupHandle: box });
@@ -256,8 +307,19 @@ export function createTangleProvider(options) {
256
307
  operation?.signal?.throwIfAborted();
257
308
  }
258
309
  }
310
+ let captureCapabilities;
311
+ if (options.requireNativeSessionCapture) {
312
+ if (backendType === undefined)
313
+ throw new Error("Tangle native capture requires the current selected backend before reconnect");
314
+ captureCapabilities = await awaitWithSignal(requireNativeCaptureCapability(box, backendType), operation?.signal);
315
+ }
259
316
  const declaredCapabilities = await resolveDeclaredCapabilities(backendType);
260
- return await sandboxInstanceAsEnvironment(box, providerName, options.client, declaredCapabilities, operation?.signal ? { signal: operation.signal } : undefined, confidentialVerifierOption(options.confidentialAttestationVerifier));
317
+ return await sandboxInstanceAsEnvironment(box, providerName, options.client, declaredCapabilities, operation?.signal ? { signal: operation.signal } : undefined, {
318
+ ...confidentialVerifierOption(options.confidentialAttestationVerifier),
319
+ ...(options.requireNativeSessionCapture ? { requireNativeSessionCapture: true } : {}),
320
+ ...(captureCapabilities === undefined ? {} : { captureCapabilities }),
321
+ ...(backendType === undefined ? {} : { captureHarness: backendType }),
322
+ });
261
323
  },
262
324
  }
263
325
  : {}),
@@ -1,5 +1,6 @@
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
- import type { AgentRunCancellationAcknowledgement, AgentRunCancellationRequest, AgentInteractiveSessionControlClaim, AgentInteractiveSessionControlClaimAcknowledgement, AgentInteractiveSessionControlClaimRequest, AgentInteractiveSessionAttach, AgentInteractiveSessionPromptAcknowledgement, AgentInteractiveSessionPromptCommand, AgentInteractiveSessionRef, AgentInteractiveSessionStart, AgentInteractiveSessionStatus, AgentInteractiveSessionStopAcknowledgement, AgentInteractiveSessionStopCommand, AgentInteractiveTerminalSession, ConfidentialAttestation, ConfidentialExecutionEnvironment, HarnessType, InputPart, InteractionRequest, InteractionResponseCommand } from "@tangle-network/agent-interface";
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";
4
5
  /**
5
6
  * The platform verdict for the create call that returned a sandbox.
@@ -23,14 +24,6 @@ export interface TangleExactProcessOptions {
23
24
  teamId?: string;
24
25
  }
25
26
  export interface SandboxClientLike {
26
- /** Deployment-scoped evidence guarantees for a new sandbox on this client. */
27
- evidenceCapabilities?(): Promise<{
28
- nativeSessionCaptureV1?: boolean;
29
- nativeSessionCaptureVersion?: number;
30
- nativeSessionCaptureHarnesses?: readonly HarnessType[];
31
- workspaceCaptureV1?: boolean;
32
- sidecarImageDigest?: string;
33
- }>;
34
27
  create(options?: CreateSandboxOptions, requestOptions?: {
35
28
  signal?: AbortSignal;
36
29
  timeoutMs?: number;
@@ -109,6 +102,10 @@ export interface SandboxSubscriptionLike {
109
102
  */
110
103
  export interface SandboxRuntimeCapabilityDocument {
111
104
  schema?: number;
105
+ /** The selected runtime resolves stored-secret native authentication references. */
106
+ cliAuthReferences?: boolean;
107
+ nativeSessionCaptureVersion?: number;
108
+ nativeSessionCaptureHarnesses?: readonly string[];
112
109
  agentInterface?: string;
113
110
  sidecarVersion?: string;
114
111
  image?: string;
@@ -752,6 +749,14 @@ export interface SandboxInteractionCommandResultLike {
752
749
  [key: string]: unknown;
753
750
  };
754
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>;
755
760
  export interface TangleProviderOptions {
756
761
  client: SandboxClientLike;
757
762
  name?: string;
@@ -760,14 +765,13 @@ export interface TangleProviderOptions {
760
765
  /** Require the selected Sandbox host to prove native session capture for every create. */
761
766
  requireNativeSessionCapture?: boolean;
762
767
  /**
763
- * Stored model credential and endpoint used by the default create mapping.
764
- * Each create must explicitly list apiKeyEnv in its secrets.
765
- * 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.
766
773
  */
767
- modelCredentials?: {
768
- apiKeyEnv: string;
769
- baseUrl: string;
770
- };
774
+ modelCredentials?: TangleModelCredentials | TangleModelCredentialResolver;
771
775
  capabilities?: AgentEnvironmentCapabilities | (() => AgentEnvironmentCapabilities | Promise<AgentEnvironmentCapabilities>);
772
776
  validateProfile?: AgentEnvironmentProvider["validateProfile"];
773
777
  /** Replaces the default mapping, including its backend and profile selection. */
@@ -1,4 +1,4 @@
1
- import { requireNativeCaptureCapability, requireNativeCaptureProof } from "./tangle-native-capture-proof.js";
1
+ import { requireNativeCaptureProof } from "./tangle-native-capture-proof.js";
2
2
  import { ConfidentialAttestationSchema, ConfidentialExecutionRequestSchema, ForkedEnvironmentRefSchema, WorkspaceCheckpointRequestSchema, WorkspaceCleanupAcknowledgementSchema, WorkspaceCleanupRequestSchema, WorkspaceForkRequestSchema, WorkspaceOperationLookupRequestSchema, WorkspaceCheckpointResultSchema, WorkspaceCheckpointLookupResultSchema, WorkspaceForkResultSchema, WorkspaceForkLookupResultSchema, canonicalCandidateDigest, confidentialExecutionVerified, sha256Bytes, } from "@tangle-network/agent-interface";
3
3
  import { awaitWithSignal, boundedIdentifier, boundedString, MAX_STRING_LENGTH, cloneJson, safeIdentifier, safeString, } from "./tangle-contract-safety.js";
4
4
  import { encodeTangleConfidentialAttestationQuote } from "./tangle-confidential-attestation.js";
@@ -314,8 +314,6 @@ export function createTangleWorkspaceBranching(options) {
314
314
  : "Sandbox checkpoint inventory is unavailable", true);
315
315
  }
316
316
  const metadata = forkMarkerMetadata(request);
317
- if (options.requireNativeSessionCapture)
318
- await requireNativeCaptureCapability(client);
319
317
  let returnedChild;
320
318
  let outcome;
321
319
  try {
@@ -331,8 +329,6 @@ export function createTangleWorkspaceBranching(options) {
331
329
  }, operation?.signal === undefined
332
330
  ? undefined
333
331
  : { signal: operation.signal }), operation?.signal);
334
- if (options.requireNativeSessionCapture)
335
- requireNativeCaptureProof(returnedChild, true);
336
332
  const receipt = returnedChild.createReceipt?.();
337
333
  if (!receipt ||
338
334
  receipt.idempotencyKeyApplied !== true ||
@@ -346,6 +342,16 @@ export function createTangleWorkspaceBranching(options) {
346
342
  }
347
343
  outcome =
348
344
  receipt.outcome === "idempotent_replay" ? "replayed" : "created";
345
+ if (options.requireNativeSessionCapture) {
346
+ try {
347
+ requireNativeCaptureProof(returnedChild, true);
348
+ }
349
+ catch (error) {
350
+ const compensation = await compensateCreatedForkChild(returnedChild, outcome, operation?.signal);
351
+ const removed = compensation === "destroyed" || compensation === "already_absent";
352
+ return forkUnknown(request, `Sandbox snapshot restore capture proof failed: ${safeError(error)}; cleanup ${compensation}`, !removed);
353
+ }
354
+ }
349
355
  }
350
356
  catch (error) {
351
357
  operation?.signal?.throwIfAborted();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tangle-network/agent-provider-tangle",
3
- "version": "2.0.0",
3
+ "version": "3.1.0",
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"