@tangle-network/agent-provider-tangle 1.3.1 → 1.4.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.
@@ -46,6 +46,16 @@ export function defaultTangleSandboxCapabilities(harness) {
46
46
  // together over one Sandbox surface, and the capability schema refuses
47
47
  // a partial block, so they stand or fall on the same fact set.
48
48
  sessions: { continue: true, list: false, messages: false },
49
+ // Same-session continuation is declared as intent and stripped by
50
+ // narrowing with retained control, because it is built on the same
51
+ // facts: an exact run identity to bind the boundary to, and a session
52
+ // whose prompts the sandbox serializes. The boundary is the executing
53
+ // run's identity, and a competing prompt on the session is refused by
54
+ // the sandbox rather than interleaved, so a check-then-dispatch on one
55
+ // handle cannot be split by another turn. `admissionControl` is not
56
+ // claimed: the adapter learns the continued run's identity from the
57
+ // prompt result, not before it.
58
+ nativeContinuation: { atomicBoundary: true, requestIdempotency: true },
49
59
  // Answering an ask is declared as intent and stripped by narrowing unless
50
60
  // the session exposes the command route and the deployment discloses its
51
61
  // durable response record. Three claims are bounded by what the adapter
@@ -400,9 +410,10 @@ export function narrowedTangleCapabilities(declared, support, deployment, option
400
410
  if (!tangleInteractionResponsesSupported(declared, support, deployment)) {
401
411
  delete narrowed.interactions;
402
412
  }
403
- delete narrowed.nativeContinuation;
404
- if (!supportsRetainedControl)
413
+ if (!supportsRetainedControl) {
405
414
  delete narrowed.retainedControl;
415
+ delete narrowed.nativeContinuation;
416
+ }
406
417
  if (narrowed.confidential &&
407
418
  (!support.confidentialAttestation ||
408
419
  typeof options?.confidentialAttestationVerifier !== "function")) {
@@ -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): 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): AgentSession;
27
27
  export {};
@@ -1,6 +1,7 @@
1
1
  import { randomUUID } from "node:crypto";
2
2
  import { AgentTurnInputSchema } from "@tangle-network/agent-interface";
3
3
  import { AgentRunCancellationAcknowledgementSchema, AgentRunCancellationRequestSchema, agentRunCancellationAcknowledgementMatchesRequest, } from "@tangle-network/agent-interface";
4
+ import { NativeContextContinuationRequestSchema, nativeContextContinuationTurnDigest, } from "@tangle-network/agent-interface";
4
5
  import { createStepUsageFold } from "./tangle-step-usage.js";
5
6
  import { carriedSessionIds, environmentEventFromSandboxEvent, isSandboxConnectionMarker, sandboxEventIdentity, } from "./tangle-events.js";
6
7
  import { agentTurnResultFromPromptRecord, promptFromTurnInput, promptOptionsFromTurnInput, validatedSandboxPromptResult, } from "./tangle-prompt.js";
@@ -23,7 +24,7 @@ import { hasReplayPayload, interruptExecutionAfterAbort, sessionPromptRequestDig
23
24
  * environment observation reads it, because Sandbox reports usage per
24
25
  * execution result and never for the environment.
25
26
  */
26
- export function sandboxSessionAsAgentSession(session, controlRef, provider, environmentId, dispatch, exactExecutionEvents, retainedControl, interactionResponses, usageLog) {
27
+ export function sandboxSessionAsAgentSession(session, controlRef, provider, environmentId, dispatch, exactExecutionEvents, retainedControl, interactionResponses, usageLog, nativeContinuation = false) {
27
28
  const measured = (executionId, result) => {
28
29
  usageLog?.record(executionId, result.usage);
29
30
  return result;
@@ -62,7 +63,134 @@ export function sandboxSessionAsAgentSession(session, controlRef, provider, envi
62
63
  return exactAcknowledgement;
63
64
  }
64
65
  : undefined;
65
- return {
66
+ // One record per continuation operation. The sandbox already caches a
67
+ // prompt by its turnId, and continueNative sets turnId to the operationId,
68
+ // so a retry after a lost response replays the same dispatch on the wire.
69
+ // This map lets the retry return the same acknowledgement and result with
70
+ // no dispatch at all, and turns a changed turn under a reused operationId
71
+ // into a conflict instead of a second run.
72
+ const nativeOperations = new Map();
73
+ const currentBoundary = () => {
74
+ if (activeControlRef === undefined)
75
+ return null;
76
+ return {
77
+ runId: activeControlRef.runId,
78
+ provider: activeControlRef.provider,
79
+ environmentId: activeControlRef.environmentId,
80
+ sessionId: activeControlRef.sessionId,
81
+ executionId: activeControlRef.executionId,
82
+ requestDigest: activeControlRef.requestDigest,
83
+ // The conversation's boundary is the run that last extended it. A
84
+ // continuation is verified against exactly that run, so a turn that
85
+ // landed in between moves the boundary and the continuation is refused
86
+ // rather than appended to a conversation the caller has not seen.
87
+ boundary: { kind: "revision", revision: activeControlRef.executionId },
88
+ observedAt: new Date().toISOString(),
89
+ };
90
+ };
91
+ const contextBoundary = async (options) => {
92
+ assertOptionKeys(options, ["signal"], "Tangle native context boundary");
93
+ options?.signal?.throwIfAborted();
94
+ return currentBoundary();
95
+ };
96
+ const continueNative = async (request, continuationOptions) => {
97
+ const exactRequest = NativeContextContinuationRequestSchema.parse(request);
98
+ if (nativeContextContinuationTurnDigest(continuationOptions.turn) !==
99
+ exactRequest.turnDigest) {
100
+ throw new Error("Tangle native continuation turn does not match its request digest");
101
+ }
102
+ if (continuationOptions.onAdmission !== undefined) {
103
+ throw new Error("Tangle native continuation does not advertise early admission control");
104
+ }
105
+ continuationOptions.signal?.throwIfAborted();
106
+ // A retry names the run the conversation had BEFORE the continuation it
107
+ // is retrying, so the operation record is consulted before the request is
108
+ // bound to the current run; a replay must answer even though the run has
109
+ // since advanced past it.
110
+ const prior = nativeOperations.get(exactRequest.operationId);
111
+ if (prior !== undefined) {
112
+ if (prior.requestDigest === exactRequest.requestDigest) {
113
+ return {
114
+ ...prior.outcome,
115
+ acknowledgement: { ...prior.outcome.acknowledgement, status: "replayed" },
116
+ };
117
+ }
118
+ return {
119
+ acknowledgement: {
120
+ operationId: exactRequest.operationId,
121
+ requestDigest: exactRequest.requestDigest,
122
+ status: "conflict",
123
+ historyMessagesSent: 0,
124
+ existingRequestDigest: prior.requestDigest,
125
+ },
126
+ };
127
+ }
128
+ const expectedRun = activeControlRef;
129
+ if (expectedRun === undefined) {
130
+ throw new Error("Tangle native continuation requires an exact run control reference");
131
+ }
132
+ if (!sameRunControlRef(exactRequest.run, expectedRun)) {
133
+ throw new Error("Tangle native continuation targets another retained run");
134
+ }
135
+ const actual = currentBoundary();
136
+ const expected = exactRequest.expectedBoundary.boundary;
137
+ const boundaryMatches = actual !== null &&
138
+ actual.boundary.kind === "revision" &&
139
+ expected.kind === "revision" &&
140
+ actual.boundary.revision === expected.revision;
141
+ if (!boundaryMatches) {
142
+ return {
143
+ acknowledgement: {
144
+ operationId: exactRequest.operationId,
145
+ requestDigest: exactRequest.requestDigest,
146
+ status: "boundary_mismatch",
147
+ historyMessagesSent: 0,
148
+ ...(actual === null ? {} : { actualBoundary: actual }),
149
+ },
150
+ };
151
+ }
152
+ const turn = continuationOptions.turn;
153
+ // The adapter's own prompt path mints the continued run's identity from
154
+ // the turn and its turnId, binds the control reference, and records usage.
155
+ const result = await agentSession.prompt({
156
+ ...(turn.prompt === undefined ? {} : { prompt: turn.prompt }),
157
+ ...(turn.parts === undefined ? {} : { parts: turn.parts }),
158
+ ...(turn.model === undefined ? {} : { model: turn.model }),
159
+ ...(turn.context === undefined ? {} : { context: turn.context }),
160
+ ...(turn.providerOptions === undefined
161
+ ? {}
162
+ : { providerOptions: turn.providerOptions }),
163
+ sessionId: session.id,
164
+ turnId: exactRequest.operationId,
165
+ ...(continuationOptions.timeoutMs === undefined
166
+ ? {}
167
+ : { timeoutMs: continuationOptions.timeoutMs }),
168
+ ...(continuationOptions.signal === undefined
169
+ ? {}
170
+ : { signal: continuationOptions.signal }),
171
+ });
172
+ const controlRef = activeControlRef;
173
+ if (controlRef === undefined || sameRunControlRef(controlRef, expectedRun)) {
174
+ throw new Error("Tangle native continuation did not advance the run control reference");
175
+ }
176
+ const outcome = {
177
+ acknowledgement: {
178
+ operationId: exactRequest.operationId,
179
+ requestDigest: exactRequest.requestDigest,
180
+ status: "accepted",
181
+ historyMessagesSent: 0,
182
+ actualBoundary: actual,
183
+ },
184
+ result,
185
+ controlRef: { ...controlRef },
186
+ };
187
+ nativeOperations.set(exactRequest.operationId, {
188
+ requestDigest: exactRequest.requestDigest,
189
+ outcome,
190
+ });
191
+ return outcome;
192
+ };
193
+ const agentSession = {
66
194
  id: session.id,
67
195
  get controlRef() {
68
196
  return activeControlRef === undefined ? undefined : { ...activeControlRef };
@@ -147,11 +275,19 @@ export function sandboxSessionAsAgentSession(session, controlRef, provider, envi
147
275
  sessionId: session.id,
148
276
  ...(useExactExecutionStream ? { streamBound: true } : {}),
149
277
  });
150
- if (converted.id === undefined)
151
- throw new Error("Tangle session event arrived without a stable id");
152
- if (seenEventIds.has(converted.id))
153
- continue;
154
- seenEventIds.add(converted.id);
278
+ // The sidecar stamps `id:` only on frames that have a replay-buffer position
279
+ // (agent-dev-container apps/sidecar/src/routes/agents-events.ts). A frame with no
280
+ // position carries no id by the SSE contract, so a reconnect resumes from the last
281
+ // frame that had one. Refusing such a frame ended the whole stream, and with it the
282
+ // terminal receipt that carries the execution's token usage: three long pi turns on
283
+ // 2026-09-15 settled at 0 tokens over 846-1693 s each for exactly this reason. An
284
+ // id-less frame cannot be replayed, so it cannot arrive twice; deliver it without
285
+ // dedup and leave the cursor where it was.
286
+ if (converted.id !== undefined) {
287
+ if (seenEventIds.has(converted.id))
288
+ continue;
289
+ seenEventIds.add(converted.id);
290
+ }
155
291
  options?.signal?.throwIfAborted();
156
292
  yield stepUsage?.observe(converted) ?? converted;
157
293
  }
@@ -342,5 +478,7 @@ export function sandboxSessionAsAgentSession(session, controlRef, provider, envi
342
478
  },
343
479
  ...(cancelRun ? { cancelRun } : {}),
344
480
  ...(respondToInteraction ? { respondToInteraction } : {}),
481
+ ...(nativeContinuation ? { contextBoundary, continueNative } : {}),
345
482
  };
483
+ return agentSession;
346
484
  }
@@ -175,7 +175,7 @@ export async function sandboxInstanceAsEnvironment(box, providerName, client, de
175
175
  if (session.id !== id) {
176
176
  throw new Error("sandbox session(id) returned an unrelated session");
177
177
  }
178
- const agentSession = sandboxSessionAsAgentSession(session, resolveRetainedSessionControlRef(options?.controlRef, id, providerName, environmentId), providerName, environmentId, dispatch, exactExecutionEvents, retainedControl, interactionResponses, usageLog);
178
+ const agentSession = sandboxSessionAsAgentSession(session, resolveRetainedSessionControlRef(options?.controlRef, id, providerName, environmentId), providerName, environmentId, dispatch, exactExecutionEvents, retainedControl, interactionResponses, usageLog, capabilities.nativeContinuation !== undefined);
179
179
  // sessions.continue was granted from the probe session and the
180
180
  // deployment document together; this backstop holds every
181
181
  // concrete session to that grant, so a client whose sessions
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tangle-network/agent-provider-tangle",
3
- "version": "1.3.1",
3
+ "version": "1.4.0",
4
4
  "description": "AgentEnvironmentProvider adapter for Tangle sandboxes",
5
5
  "type": "module",
6
6
  "license": "MIT",