@tangle-network/agent-provider-tangle 4.5.2 → 4.5.4

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
@@ -7,6 +7,8 @@ Terminal `result` and `done` events use the Sandbox SDK's `projectAgentTerminalR
7
7
 
8
8
  Per-turn backend options use the SDK's `normalizeRuntimeBackendConfig` for current model/auth fields and turn-scoped `runtimeSecrets`. Unknown options remain rejected, and native credentials still require the exact profile's subscription intent. Retained request identity excludes credential values, matching Sandbox message admission; Sandbox separately keys the executing backend by secret values so rotation cannot reuse stale authority.
9
9
 
10
+ Fresh environments without an authored `workspace.cwd` or Git checkout start in the SDK's relative `workspace` child before profile files or repository setup. Explicit working directories, SDK Git checkout roots and checkpoint restores retain their requested placement. Secret-bearing turns create an isolated session without persisting `runtimeSecrets`, then use the SDK's native preparation receipt before execution; cursor replay reads its existing execution without preparing another profile.
11
+
10
12
  Runtime MCP bindings travel through `CreateAgentEnvironmentInput.runtimeAttachments` to Sandbox's `backend.runtimeAttachments`.
11
13
  They remain separate from the authored profile and its digest.
12
14
  The adapter checks the selected backend catalog before provisioning and refuses missing attachment support.
@@ -41,6 +43,10 @@ Use the typed field for large profiles; generic provider metadata keeps its exis
41
43
 
42
44
  Exact execution replay preserves the admitted request and its digest.
43
45
  An explicit replay override cannot replace the selected account, credential channel, or harness.
46
+ Before dispatch admission, replay the original `create` and turn with their original idempotency keys.
47
+ Native-capture `get()` requires an already selected backend; it is not the entrypoint for an intent whose first dispatch was refused.
48
+ A backend 404 alone does not prove that a prior execution ran nothing or authorize replacing it under new keys.
49
+ When an older SDK's reuse receipt omits the exact control reference, the adapter reads the session's authoritative status and validates its echoed reference against the original session, execution, environment and request digest. Missing or conflicting authority still refuses recovery.
44
50
 
45
51
  ## Workspace file reads
46
52
 
@@ -157,7 +157,9 @@ export function sandboxOptionsFromCreateInput(input, defaultBackend, parsedWorks
157
157
  if (workspace.providerOptions && Object.keys(workspace.providerOptions).length > 0) {
158
158
  throw new Error("Tangle workspace providerOptions are not supported");
159
159
  }
160
- const workspaceCwd = workspaceCwdPathForBase(workspace.cwd, "repository", "Tangle");
160
+ const workspaceCwd = workspaceCwdPathForBase(workspace.cwd ?? (workspace.checkpoint === undefined && workspace.repoUrl === undefined
161
+ ? { base: "repository", path: "workspace" }
162
+ : undefined), "repository", "Tangle");
161
163
  const restore = sandboxRestoreFromCheckpoint(workspace.checkpoint);
162
164
  if (input.resources?.providerOptions && Object.keys(input.resources.providerOptions).length > 0) {
163
165
  throw new Error("Tangle resource providerOptions are not supported");
@@ -175,9 +177,7 @@ export function sandboxOptionsFromCreateInput(input, defaultBackend, parsedWorks
175
177
  // record and dropping it would create an environment with no credentials and
176
178
  // no error, surfacing later as an unexplained tool failure.
177
179
  const environment = workspace.image ?? workspace.environment;
178
- const base = {};
179
180
  const mapped = {
180
- ...base,
181
181
  ...(environment !== undefined ? { environment } : {}),
182
182
  ...(workspaceCwd === undefined ? {} : { cwd: workspaceCwd }),
183
183
  ...(workspace.repoUrl
@@ -199,7 +199,6 @@ export function sandboxOptionsFromCreateInput(input, defaultBackend, parsedWorks
199
199
  ...(input.name === undefined ? {} : { name: input.name }),
200
200
  ...(input.idempotencyKey === undefined ? {} : { idempotencyKey: input.idempotencyKey }),
201
201
  backend: {
202
- ...(base.backend ?? {}),
203
202
  type: backend,
204
203
  profile,
205
204
  ...(modelCredentials === undefined ? {} : {
@@ -1,37 +1,19 @@
1
- import { AgentExactRunControlRefSchema, AgentTurnInputSchema, } from "@tangle-network/agent-interface";
2
- import { promptFromTurnInput, promptOptionsFromTurnInput, } from "./tangle-prompt.js";
1
+ import { promptFromTurnInput, promptOptionsFromTurnInput, preparePromptOptions, } from "./tangle-prompt.js";
3
2
  import { retainedSessionControlRef, sessionPromptExecutionId, sessionPromptSessionId, sessionRefFromSandboxDispatch, } from "./tangle-session-control.js";
4
3
  import { awaitWithSignal } from "./tangle-contract-safety.js";
5
4
  import { interruptAfterAbort, sessionPromptRequestDigest, } from "./tangle-environment-control.js";
6
5
  export function dispatchEnvironmentRun(box, provider, environmentId) {
7
6
  return async (input) => {
8
- AgentTurnInputSchema.parse(input);
9
7
  input.signal?.throwIfAborted();
10
- const callerControlRef = input.controlRef === undefined
11
- ? undefined
12
- : AgentExactRunControlRefSchema.parse(input.controlRef);
13
- if (callerControlRef !== undefined) {
14
- if (callerControlRef.provider !== provider ||
15
- callerControlRef.environmentId !== environmentId) {
16
- throw new Error("Tangle control reference does not match this environment");
17
- }
18
- if (input.sessionId !== undefined &&
19
- input.sessionId !== callerControlRef.sessionId) {
20
- throw new Error("Tangle sessionId conflicts with the control reference");
21
- }
22
- if (input.executionId !== undefined &&
23
- input.executionId !== callerControlRef.executionId) {
24
- throw new Error("Tangle executionId conflicts with the control reference");
25
- }
26
- }
27
- const expectedSessionId = input.sessionId ??
28
- callerControlRef?.sessionId ??
8
+ const options = promptOptionsFromTurnInput(input, { provider, environmentId });
9
+ const callerControlRef = options.runControlRef;
10
+ const expectedSessionId = options.sessionId ??
29
11
  sessionPromptSessionId(provider, environmentId, input.turnId);
30
12
  if (expectedSessionId === undefined) {
31
13
  throw new Error("Tangle detached dispatch requires an exact sessionId or turnId");
32
14
  }
33
15
  const exactInput = { ...input, sessionId: expectedSessionId };
34
- const requestedExecutionId = input.executionId ?? callerControlRef?.executionId;
16
+ const requestedExecutionId = options.executionId;
35
17
  const baseRequestDigest = sessionPromptRequestDigest(exactInput, provider, environmentId, expectedSessionId);
36
18
  const expectedExecutionId = requestedExecutionId ?? sessionPromptExecutionId(baseRequestDigest);
37
19
  const requestDigest = sessionPromptRequestDigest(exactInput, provider, environmentId, expectedSessionId, { executionId: expectedExecutionId });
@@ -41,12 +23,12 @@ export function dispatchEnvironmentRun(box, provider, environmentId) {
41
23
  }
42
24
  }
43
25
  const runControlRef = retainedSessionControlRef(expectedSessionId, expectedExecutionId, provider, environmentId, requestDigest, callerControlRef?.runId);
44
- const dispatchInput = {
45
- ...exactInput,
26
+ const promise = box.dispatchPrompt?.(promptFromTurnInput(input), await preparePromptOptions(box, {
27
+ ...options,
28
+ sessionId: expectedSessionId,
46
29
  executionId: expectedExecutionId,
47
- controlRef: runControlRef,
48
- };
49
- const promise = box.dispatchPrompt?.(promptFromTurnInput(dispatchInput), promptOptionsFromTurnInput(dispatchInput, { provider, environmentId }));
30
+ runControlRef,
31
+ }, provider));
50
32
  let dispatched;
51
33
  try {
52
34
  dispatched = await awaitWithSignal(promise, input.signal);
@@ -62,6 +44,16 @@ export function dispatchEnvironmentRun(box, provider, environmentId) {
62
44
  }
63
45
  throw error;
64
46
  }
47
+ const receipt = dispatched;
48
+ if (receipt?.dispatched === false && receipt.alreadyExisted === true &&
49
+ receipt.sessionId === expectedSessionId && receipt.executionId === expectedExecutionId &&
50
+ receipt.runControlRef === undefined && callerControlRef === undefined && box.session) {
51
+ // Recover an older SDK's omitted reuse reference from server status; validate every binding below.
52
+ const status = await awaitWithSignal(box.session(expectedSessionId).status({ signal: input.signal }), input.signal);
53
+ const echoedRef = status && typeof status === "object" && !Array.isArray(status) && "runControlRef" in status ? status.runControlRef : undefined;
54
+ if (echoedRef !== undefined)
55
+ dispatched = { ...receipt, runControlRef: echoedRef };
56
+ }
65
57
  let reference;
66
58
  try {
67
59
  reference = sessionRefFromSandboxDispatch(dispatched, provider, environmentId, expectedExecutionId, requestDigest, expectedSessionId, callerControlRef);
@@ -79,12 +71,10 @@ export function dispatchEnvironmentRun(box, provider, environmentId) {
79
71
  }
80
72
  throw error;
81
73
  }
82
- const boundReference = reference;
83
74
  if (input.signal?.aborted && input.detach !== true) {
84
- await interruptAfterAbort(box, boundReference);
85
- input.signal.throwIfAborted();
75
+ await interruptAfterAbort(box, reference);
86
76
  }
87
77
  input.signal?.throwIfAborted();
88
- return boundReference;
78
+ return reference;
89
79
  };
90
80
  }
@@ -1,7 +1,7 @@
1
1
  import type { AgentSession, AgentSessionRef, AgentTurnInput } from "@tangle-network/agent-interface/environment-provider";
2
2
  import type { AgentExactRunControlRef, AgentRunControlRef } from "@tangle-network/agent-interface";
3
3
  import type { SandboxEvent } from "@tangle-network/sandbox";
4
- import type { SandboxSessionLike } from "./tangle-types.js";
4
+ import type { SandboxInstanceLike, SandboxSessionLike } from "./tangle-types.js";
5
5
  import type { ExecutionUsageLog } from "./tangle-usage-log.js";
6
6
  type ExactExecutionEventStream = (options: {
7
7
  sessionId: string;
@@ -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, beforePrompt?: (input: AgentTurnInput) => AgentTurnInput | void | Promise<AgentTurnInput | void>, 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) => AgentTurnInput | void | Promise<AgentTurnInput | void>, onExecution?: (executionId: string) => void, box?: SandboxInstanceLike): AgentSession;
27
27
  export {};
@@ -4,7 +4,7 @@ import { AgentRunCancellationAcknowledgementSchema, AgentRunCancellationRequestS
4
4
  import { NativeContextContinuationRequestSchema, nativeContextContinuationTurnDigest, } from "@tangle-network/agent-interface";
5
5
  import { createStepUsageFold } from "./tangle-step-usage.js";
6
6
  import { carriedSessionIds, environmentEventFromSandboxEvent, isSandboxConnectionMarker, sandboxEventIdentity, } from "./tangle-events.js";
7
- import { agentTurnResultFromPromptRecord, promptFromTurnInput, promptOptionsFromTurnInput, validatedSandboxPromptResult, } from "./tangle-prompt.js";
7
+ import { agentTurnResultFromPromptRecord, promptFromTurnInput, promptOptionsFromTurnInput, preparePromptOptions, validatedSandboxPromptResult, } from "./tangle-prompt.js";
8
8
  import { retainedSessionControlRef, resolveRetainedSessionControlRef, sameRunControlRef, sessionPromptExecutionId, } from "./tangle-session-control.js";
9
9
  import { executionBoundSessionStatus, sessionStatusFromUnknown, } from "./tangle-environment-values.js";
10
10
  import { awaitWithSignal, boundedIdentifier, } from "./tangle-contract-safety.js";
@@ -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, beforePrompt, onExecution) {
27
+ export function sandboxSessionAsAgentSession(session, controlRef, provider, environmentId, dispatch, exactExecutionEvents, retainedControl, interactionResponses, usageLog, nativeContinuation = false, beforePrompt, onExecution, box) {
28
28
  const measured = (executionId, result) => {
29
29
  usageLog?.record(executionId, result.usage);
30
30
  return result;
@@ -435,11 +435,11 @@ export function sandboxSessionAsAgentSession(session, controlRef, provider, envi
435
435
  controlRef: targetControlRef,
436
436
  };
437
437
  const prompt = promptFromTurnInput(input);
438
- const promptOptions = promptOptionsFromTurnInput(promptInput, {
438
+ const promptOptions = await preparePromptOptions(box, promptOptionsFromTurnInput(promptInput, {
439
439
  provider,
440
440
  environmentId,
441
441
  sessionId: session.id,
442
- });
442
+ }), provider);
443
443
  onExecution?.(executionId);
444
444
  try {
445
445
  const result = await awaitWithSignal(session.prompt(prompt, promptOptions), input.signal);
@@ -449,11 +449,10 @@ export function sandboxSessionAsAgentSession(session, controlRef, provider, envi
449
449
  void interruptExecutionAfterAbort(session, session.id, executionId);
450
450
  throw new Error("Tangle session prompt did not confirm its exact executionId");
451
451
  }
452
- const nextControlRef = targetControlRef;
453
- activeControlRef = nextControlRef;
452
+ activeControlRef = targetControlRef;
454
453
  return measured(executionId, agentTurnResultFromPromptRecord(resultRecord, {
455
454
  sessionId: session.id,
456
- controlRef: nextControlRef,
455
+ controlRef: targetControlRef,
457
456
  ...(input.contextTransfer
458
457
  ? { contextTransferRequest: input.contextTransfer }
459
458
  : {}),
@@ -5,7 +5,7 @@ import { captureModelCredentials, NATIVE_RESUME_CHECKPOINT_METADATA_KEY } from "
5
5
  import { AgentTurnInputSchema, deepFreeze } from "@tangle-network/agent-interface";
6
6
  import { AgentEnvironmentCapabilitiesSchema } from "@tangle-network/agent-interface/environment-provider";
7
7
  import { environmentEventFromSandboxEvent } from "./tangle-events.js";
8
- import { executionIdFromTurnInput, promptFromTurnInput, promptOptionsFromTurnInput, } from "./tangle-prompt.js";
8
+ import { executionIdFromTurnInput, promptFromTurnInput, promptOptionsFromTurnInput, preparePromptOptions, } from "./tangle-prompt.js";
9
9
  import { creationFromSandboxCreateReceipt, placementInfoFromLoopPlacement, statusFromUnknown, } from "./tangle-environment-values.js";
10
10
  import { execResultFromSandboxExecResult } from "./tangle-result-values.js";
11
11
  import { capabilitiesForSandbox, frozenCapabilityDocument, sandboxCapabilitySupport, } from "./tangle-capabilities.js";
@@ -309,16 +309,14 @@ export async function sandboxInstanceAsEnvironment(box, providerName, client, de
309
309
  input.signal?.throwIfAborted();
310
310
  input = await prepareTurn(input);
311
311
  const expectedExecutionId = executionIdFromTurnInput(input);
312
- const expectedSessionId = input.sessionId ?? input.controlRef?.sessionId;
312
+ const promptOptions = await preparePromptOptions(box, promptOptionsFromTurnInput(input, { provider: providerName, environmentId }), providerName);
313
+ const expectedSessionId = promptOptions.sessionId;
313
314
  if (expectedSessionId)
314
315
  noteTangleSession(environment, expectedSessionId, expectedExecutionId);
315
316
  // A turn resumed after a cursor starts past its first steps, so it cannot
316
317
  // report the execution's running total.
317
318
  const stepUsage = input.lastEventId === undefined ? createStepUsageFold() : undefined;
318
- const iterator = box.streamPrompt(promptFromTurnInput(input), promptOptionsFromTurnInput(input, {
319
- provider: providerName,
320
- environmentId,
321
- }))[Symbol.asyncIterator]();
319
+ const iterator = box.streamPrompt(promptFromTurnInput(input), promptOptions)[Symbol.asyncIterator]();
322
320
  let completed = false;
323
321
  try {
324
322
  while (true) {
@@ -380,7 +378,7 @@ export async function sandboxInstanceAsEnvironment(box, providerName, client, de
380
378
  if (session.id !== id) {
381
379
  throw new Error("sandbox session(id) returned an unrelated session");
382
380
  }
383
- const agentSession = sandboxSessionAsAgentSession(session, options?.controlRef, providerName, environmentId, dispatchRun, exactExecutionEvents, retainedControl, interactionResponses, usageLog, capabilities.nativeContinuation !== undefined, prepareTurn, (executionId) => noteTangleSession(environment, id, executionId));
381
+ const agentSession = sandboxSessionAsAgentSession(session, options?.controlRef, providerName, environmentId, dispatchRun, exactExecutionEvents, retainedControl, interactionResponses, usageLog, capabilities.nativeContinuation !== undefined, prepareTurn, (executionId) => noteTangleSession(environment, id, executionId), box);
384
382
  // sessions.continue was granted from the probe session and the
385
383
  // deployment document together; this backstop holds every
386
384
  // concrete session to that grant, so a client whose sessions
@@ -137,7 +137,13 @@ export function environmentEventFromSandboxEvent(event, expected = {}) {
137
137
  const terminal = record.type === "result" || record.type === "done";
138
138
  const sourceData = record.data;
139
139
  const data = terminal ? projectAgentTerminalRecord(sourceData) : sourceData;
140
- assertBoundedRecord(terminal ? { ...record, data } : record);
140
+ const descriptors = Object.getOwnPropertyDescriptors(record);
141
+ if (descriptors.id && "value" in descriptors.id && descriptors.id.value === undefined)
142
+ delete descriptors.id;
143
+ if (terminal)
144
+ descriptors.data = { value: data, enumerable: true, configurable: true, writable: true };
145
+ const providerEvent = Object.create(Object.getPrototypeOf(record), descriptors);
146
+ assertBoundedRecord(providerEvent);
141
147
  if (Object.prototype.hasOwnProperty.call(data, "contextTransferReceipt")) {
142
148
  throw new Error("Tangle Sandbox emitted an unsolicited context transfer receipt");
143
149
  }
@@ -194,7 +200,7 @@ export function environmentEventFromSandboxEvent(event, expected = {}) {
194
200
  ...(usageMode === undefined ? {} : { usageMode }),
195
201
  // A terminal projection is not the complete native event. The source is
196
202
  // available through exact session/execution evidence, including tool history.
197
- ...(!terminal ? { providerEvent: event } : {}),
203
+ ...(!terminal ? { providerEvent } : {}),
198
204
  };
199
205
  }
200
206
  function normalizeSandboxEvent(type, data, identity) {
@@ -1,6 +1,7 @@
1
1
  import type { BackendConfig, PromptOptions, PromptResult } from "@tangle-network/sandbox";
2
2
  import type { AgentTurnInput, AgentTurnResult } from "@tangle-network/agent-interface/environment-provider";
3
3
  import type { AgentExactRunControlRef, InputPart } from "@tangle-network/agent-interface";
4
+ import type { SandboxInstanceLike } from "./tangle-types.js";
4
5
  export declare function promptFromTurnInput(input: AgentTurnInput): string | InputPart[];
5
6
  export declare function executionIdFromTurnInput(input: AgentTurnInput): string | undefined;
6
7
  export declare function promptOptionsFromTurnInput(input: AgentTurnInput, target: {
@@ -8,6 +9,8 @@ export declare function promptOptionsFromTurnInput(input: AgentTurnInput, target
8
9
  environmentId: string;
9
10
  sessionId?: string;
10
11
  }): PromptOptions;
12
+ /** The SDK owns isolated session creation and the executor's private admission receipt. */
13
+ export declare function preparePromptOptions(box: SandboxInstanceLike | undefined, options: PromptOptions, provider: string): Promise<PromptOptions>;
11
14
  /**
12
15
  * The `BackendConfig` fields this adapter forwards to Sandbox prompt options.
13
16
  *
@@ -34,23 +37,10 @@ declare const SANDBOX_BACKEND_MODEL_FIELD_LIST: readonly ["provider", "model", "
34
37
  */
35
38
  type Exhaustive<T extends never> = T;
36
39
  type SandboxBackendModel = NonNullable<BackendConfig["model"]>;
37
- type UncoveredBackendField = Exhaustive<Exclude<keyof BackendConfig, (typeof SANDBOX_BACKEND_FIELD_LIST)[number]>>;
38
- type StaleBackendField = Exhaustive<Exclude<(typeof SANDBOX_BACKEND_FIELD_LIST)[number], keyof BackendConfig>>;
39
- type UncoveredBackendModelField = Exhaustive<Exclude<keyof SandboxBackendModel, (typeof SANDBOX_BACKEND_MODEL_FIELD_LIST)[number]>>;
40
- type StaleBackendModelField = Exhaustive<Exclude<(typeof SANDBOX_BACKEND_MODEL_FIELD_LIST)[number], keyof SandboxBackendModel>>;
41
40
  declare const SANDBOX_AUTH_FILE_FIELD_LIST: readonly ["path", "content", "mode"];
42
41
  type SandboxAuthFile = NonNullable<SandboxBackendModel["authFiles"]>[number];
43
- type UncoveredAuthFileField = Exhaustive<Exclude<keyof SandboxAuthFile, (typeof SANDBOX_AUTH_FILE_FIELD_LIST)[number]>>;
44
- type StaleAuthFileField = Exhaustive<Exclude<(typeof SANDBOX_AUTH_FILE_FIELD_LIST)[number], keyof SandboxAuthFile>>;
45
- type SandboxBackendFieldCoverage = [
46
- UncoveredBackendField,
47
- StaleBackendField,
48
- UncoveredBackendModelField,
49
- StaleBackendModelField,
50
- UncoveredAuthFileField,
51
- StaleAuthFileField
52
- ];
53
- export type { SandboxBackendFieldCoverage };
42
+ type FieldDifference<T, Fields extends readonly PropertyKey[]> = Exclude<keyof T, Fields[number]> | Exclude<Fields[number], keyof T>;
43
+ export type SandboxBackendFieldCoverage = Exhaustive<FieldDifference<BackendConfig, typeof SANDBOX_BACKEND_FIELD_LIST> | FieldDifference<SandboxBackendModel, typeof SANDBOX_BACKEND_MODEL_FIELD_LIST> | FieldDifference<SandboxAuthFile, typeof SANDBOX_AUTH_FILE_FIELD_LIST>>;
54
44
  type SandboxPromptBackend = NonNullable<PromptOptions["backend"]>;
55
45
  /**
56
46
  * Read the per-turn backend options a caller sent through `providerOptions`.
@@ -89,3 +79,4 @@ export declare function agentTurnResultFromPromptRecord(record: ValidatedSandbox
89
79
  sessionId?: string;
90
80
  controlRef?: AgentExactRunControlRef;
91
81
  }): AgentTurnResult;
82
+ export {};
@@ -1,12 +1,14 @@
1
+ import { randomUUID } from "node:crypto";
1
2
  import { normalizeRuntimeBackendConfig } from "@tangle-network/sandbox";
2
3
  import { projectAgentTerminalRecord } from "@tangle-network/sandbox/runtime";
3
4
  import { assertCliAuthReferenceSupported, cliAuthReferenceSchema, } from "@tangle-network/sandbox/auth";
4
5
  import { agentProfileSchema, canonicalAgentProfileDigest, boundedEventContentRecordSchema, AgentExactRunControlRefSchema, AgentTurnInputSchema, ContextTransferReceiptSchema, contextTransferResultMatchesRequest, } from "@tangle-network/agent-interface";
5
6
  import { tokenUsageFromData } from "./tangle-result-values.js";
6
7
  import { TangleCredentialCapacityError } from "./model-credential-capacity.js";
7
- import { assertBoundedJson, boundedString, PROFILE_AT_PROFILE, } from "./tangle-contract-safety.js";
8
+ import { assertBoundedJson, awaitWithSignal, boundedString, PROFILE_AT_PROFILE, } from "./tangle-contract-safety.js";
8
9
  import { profileCredentialSource } from "./model-credential-source.js";
9
10
  import { tangleRuntimeAttachments } from "./tangle-runtime-attachments.js";
11
+ import { sessionPromptSessionId } from "./tangle-session-control.js";
10
12
  export function promptFromTurnInput(input) {
11
13
  AgentTurnInputSchema.parse(input);
12
14
  if (input.parts)
@@ -64,6 +66,36 @@ export function promptOptionsFromTurnInput(input, target) {
64
66
  ...(input.detach !== undefined ? { detach: input.detach } : {}),
65
67
  };
66
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))
74
+ return options;
75
+ if (!box?.createSession || !box.prepareSecretProfileRevision) {
76
+ throw new Error("Tangle secret turns require Sandbox isolated-session preparation support");
77
+ }
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, 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");
90
+ }
91
+ 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 };
98
+ }
67
99
  /**
68
100
  * The `BackendConfig` fields this adapter forwards to Sandbox prompt options.
69
101
  *
@@ -1,5 +1,5 @@
1
1
  import type { CliAuthReference } from "@tangle-network/sandbox/auth";
2
- import type { BackendRegistryEntry, BackendRegistryResponse, BackendType, CreateSandboxOptions, ExecResult as SandboxExecResult, PromptOptions, PromptResult, SandboxEvent } from "@tangle-network/sandbox";
2
+ import type { BackendRegistryEntry, BackendRegistryResponse, BackendType, CreateSandboxOptions, ExecResult as SandboxExecResult, PromptOptions, PromptResult, SandboxInstance, SandboxEvent } from "@tangle-network/sandbox";
3
3
  import type { AgentRunCancellationAcknowledgement, AgentRunCancellationRequest, AgentInteractiveSessionControlClaim, AgentInteractiveSessionControlClaimAcknowledgement, AgentInteractiveSessionControlClaimRequest, AgentInteractiveSessionAttach, AgentInteractiveSessionPromptAcknowledgement, AgentInteractiveSessionPromptCommand, AgentInteractiveSessionRef, AgentInteractiveSessionStart, AgentInteractiveSessionStatus, AgentInteractiveSessionStopAcknowledgement, AgentInteractiveSessionStopCommand, AgentInteractiveTerminalSession, ConfidentialAttestation, ConfidentialExecutionEnvironment, InputPart, InteractionRequest, InteractionResponseCommand } from "@tangle-network/agent-interface";
4
4
  import type { AgentEnvironmentCapabilities, AgentEnvironmentProvider, CreateAgentEnvironmentInput, ProxySecretBinding, ProxySecretCapabilities, ProxySecretReceipt } from "@tangle-network/agent-interface/environment-provider";
5
5
  /**
@@ -412,6 +412,8 @@ export interface SandboxInteractiveSessionLike {
412
412
  }
413
413
  export interface SandboxInstanceLike {
414
414
  id: string;
415
+ createSession?: SandboxInstance["createSession"];
416
+ prepareSecretProfileRevision?: SandboxInstance["prepareSecretProfileRevision"];
415
417
  name?: string;
416
418
  status?: unknown;
417
419
  metadata?: Record<string, unknown>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tangle-network/agent-provider-tangle",
3
- "version": "4.5.2",
3
+ "version": "4.5.4",
4
4
  "description": "AgentEnvironmentProvider adapter for Tangle sandboxes",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -33,7 +33,7 @@
33
33
  "LICENSE"
34
34
  ],
35
35
  "dependencies": {
36
- "@tangle-network/agent-interface": "^5.10.2"
36
+ "@tangle-network/agent-interface": "^5.10.3"
37
37
  },
38
38
  "peerDependencies": {
39
39
  "@tangle-network/sandbox": ">=0.60.88 <2.0.0"