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

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