@tangle-network/agent-provider-tangle 3.5.0 → 3.5.2

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
@@ -674,8 +674,10 @@ Partial capture retains the readable native files, process frames, and events in
674
674
  Its missing reasons prevent a complete receipt and keep the source available for recovery.
675
675
  An unknown attempt outcome or native session identity remains explicit.
676
676
  Reconnecting uses the execution ID from the validated durable control reference.
677
- Earlier executions without retained caller attribution stay in the raw manifest with explicit gaps.
678
- The caller's attempt projection includes only its known execution IDs.
677
+ Earlier callers are recovered from retained server `execution.started` records only when the current exact control reference matches its recorded admission.
678
+ Recovery validates the provider, environment, session and execution, and preserves each original reference and request digest in `sessions[].controlRefs`.
679
+ Missing, malformed or conflicting historical admissions stay in the raw manifest with explicit gaps.
680
+ The attempt projection includes only caller-known or admission-verified execution IDs.
679
681
  The capture records the running sidecar image digest and the served Sidecar bundle revision.
680
682
  The image digest can be compared with the pre-create proof only when that proof identifies the actual placement image.
681
683
  An incomplete inventory, missing stream, unrelated backend, or mismatched digest does not produce complete evidence.
@@ -68,6 +68,8 @@ export interface TangleEnvironmentEvidence {
68
68
  id: string;
69
69
  executionId: string;
70
70
  executionIds: string[];
71
+ /** Original admitted references recovered from retained server frames. */
72
+ controlRefs?: AgentExactRunControlRef[];
71
73
  eventCountsByExecutionId: Record<string, number>;
72
74
  backendType: string;
73
75
  sidecarImageDigest: string | null;
@@ -4,6 +4,7 @@ import { createDirectoryEvidenceWriter, createMemoryEvidenceWriter } from "./tan
4
4
  import { prepareNativeDirectoryEvidence, nativePayloadChunks } from "./tangle-evidence-native-files.js";
5
5
  import { AgentExactRunControlRefSchema } from "@tangle-network/agent-interface";
6
6
  import { requireNativeCaptureProof } from "./tangle-native-capture-proof.js";
7
+ import { retainedCaptureAttribution } from "./tangle-retained-attribution.js";
7
8
  const handles = new WeakMap();
8
9
  const blockedNames = new Set([".ssh", ".config", ".claude", ".codex", ".opencode", ".env", ".env.local", ".npmrc", ".sidecar"]);
9
10
  const MAX_ENTRIES = 100_000;
@@ -230,52 +231,6 @@ async function captureSandboxEvidence(box, options, writer) {
230
231
  missing.push(`Sandbox session ${id} no longer exists`);
231
232
  continue;
232
233
  }
233
- const executionIds = options.sessionExecutionIds?.[id] ?? [options.executionId];
234
- if (!executionIds.length || new Set(executionIds).size !== executionIds.length ||
235
- executionIds.some((executionId) => !safeIdentifier(executionId))) {
236
- throw new Error("Tangle evidence has invalid session execution attribution");
237
- }
238
- const counts = { events: 0, messages: 0 };
239
- const eventCountsByExecutionId = {};
240
- const events = new EvidenceJsonArray(undefined, async function* () {
241
- for (const executionId of executionIds) {
242
- eventCountsByExecutionId[executionId] = 0;
243
- for await (const event of session.events({ since: "0", executionId, signal: options.signal })) {
244
- options.signal?.throwIfAborted();
245
- if (counts.events >= MAX_EVENTS)
246
- throw new Error("Tangle event replay limit exceeded");
247
- if (typeof event.data?.executionId === "string" && event.data.executionId !== executionId) {
248
- throw new Error("Tangle event replay returned an unrelated execution");
249
- }
250
- if (typeof event.data?.runtimeSessionId === "string" && event.data.runtimeSessionId !== id) {
251
- throw new Error("Tangle event replay returned an unrelated session");
252
- }
253
- counts.events++;
254
- eventCountsByExecutionId[executionId] += 1;
255
- yield { executionId, event };
256
- }
257
- }
258
- });
259
- const messages = new EvidenceJsonArray(undefined, async function* () {
260
- const pageSize = 100;
261
- for (let offset = 0;; offset += pageSize) {
262
- options.signal?.throwIfAborted();
263
- if (offset >= MAX_EVENTS)
264
- throw new Error("Tangle message pagination limit exceeded");
265
- const page = await session.messages({ limit: pageSize, offset });
266
- if (!Array.isArray(page) || page.length > pageSize)
267
- throw new Error("Tangle session message page is malformed");
268
- for (const message of page) {
269
- counts.messages++;
270
- yield message;
271
- }
272
- if (page.length < pageSize)
273
- break;
274
- }
275
- });
276
- await writer.writeChunks(`__retention__/sessions/${id}.json`, 0o600, evidenceJsonChunks({ kind: "tangle-session-transport.v1", environmentId: box.id, sessionId: id,
277
- executionIds, status, events, messages, messageScope: "session" }));
278
- capturedBytes = writer.byteLength;
279
234
  const prepared = writer.directory === undefined ? undefined :
280
235
  await prepareNativeDirectoryEvidence(session, options.maxBytes - capturedBytes, options.signal);
281
236
  try {
@@ -307,6 +262,66 @@ async function captureSandboxEvidence(box, options, writer) {
307
262
  const nativeEvents = {
308
263
  scope: "execution", complete: false, count: 0,
309
264
  };
265
+ const executionIds = [...(options.sessionExecutionIds?.[id] ?? [options.executionId])];
266
+ if (!executionIds.length || new Set(executionIds).size !== executionIds.length ||
267
+ executionIds.some((executionId) => !safeIdentifier(executionId))) {
268
+ throw new Error("Tangle evidence has invalid session execution attribution");
269
+ }
270
+ let recoveredControlRefs = [];
271
+ let admissionMissing = [];
272
+ if (controlRef && native && (native.status === "captured" || native.status === "partial") &&
273
+ Array.isArray(native.attempts) && Array.isArray(native.events) &&
274
+ native.attempts.some(attempt => isEvidenceAttempt(attempt) && !executionIds.includes(attempt.executionId))) {
275
+ const recovered = await retainedCaptureAttribution(native.events, controlRef, options.signal);
276
+ recoveredControlRefs = recovered.controlRefs;
277
+ admissionMissing = recovered.missing;
278
+ for (const ref of recoveredControlRefs) {
279
+ if (!executionIds.includes(ref.executionId))
280
+ executionIds.push(ref.executionId);
281
+ }
282
+ missing.push(...admissionMissing);
283
+ }
284
+ const counts = { events: 0, messages: 0 };
285
+ const eventCountsByExecutionId = {};
286
+ const events = new EvidenceJsonArray(undefined, async function* () {
287
+ for (const executionId of executionIds) {
288
+ eventCountsByExecutionId[executionId] = 0;
289
+ for await (const event of session.events({ since: "0", executionId, signal: options.signal })) {
290
+ options.signal?.throwIfAborted();
291
+ if (counts.events >= MAX_EVENTS)
292
+ throw new Error("Tangle event replay limit exceeded");
293
+ if (typeof event.data?.executionId === "string" && event.data.executionId !== executionId) {
294
+ throw new Error("Tangle event replay returned an unrelated execution");
295
+ }
296
+ if (typeof event.data?.runtimeSessionId === "string" && event.data.runtimeSessionId !== id) {
297
+ throw new Error("Tangle event replay returned an unrelated session");
298
+ }
299
+ counts.events++;
300
+ eventCountsByExecutionId[executionId] += 1;
301
+ yield { executionId, event };
302
+ }
303
+ }
304
+ });
305
+ const messages = new EvidenceJsonArray(undefined, async function* () {
306
+ const pageSize = 100;
307
+ for (let offset = 0;; offset += pageSize) {
308
+ options.signal?.throwIfAborted();
309
+ if (offset >= MAX_EVENTS)
310
+ throw new Error("Tangle message pagination limit exceeded");
311
+ const page = await session.messages({ limit: pageSize, offset });
312
+ if (!Array.isArray(page) || page.length > pageSize)
313
+ throw new Error("Tangle session message page is malformed");
314
+ for (const message of page) {
315
+ counts.messages++;
316
+ yield message;
317
+ }
318
+ if (page.length < pageSize)
319
+ break;
320
+ }
321
+ });
322
+ await writer.writeChunks(`__retention__/sessions/${id}.json`, 0o600, evidenceJsonChunks({ kind: "tangle-session-transport.v1", environmentId: box.id, sessionId: id,
323
+ executionIds, status, events, messages, messageScope: "session" }));
324
+ capturedBytes = writer.byteLength;
310
325
  let nativeSessionId = null;
311
326
  let sidecarImageDigest = null;
312
327
  let sidecarBundleRevision = null;
@@ -324,7 +339,7 @@ async function captureSandboxEvidence(box, options, writer) {
324
339
  nativeSessionId = native.nativeSessionId ?? null;
325
340
  if (native.status === "captured" || native.status === "partial") {
326
341
  const declaredPartial = native.status === "partial";
327
- let partial = declaredPartial;
342
+ let partial = declaredPartial || admissionMissing.length > 0;
328
343
  if (captureProof && (native.proofStatus !== "verified" ||
329
344
  native.containerId !== captureProof.containerId ||
330
345
  native.sidecarImageDigest !== captureProof.imageId ||
@@ -393,7 +408,7 @@ async function captureSandboxEvidence(box, options, writer) {
393
408
  let processAttributionComplete = sourceCoverage;
394
409
  const nativeEventCoverage = nativeEventsMatch(native.events, id, executionIds, partial);
395
410
  attempts.push(...sessionAttempts.filter((attempt) => executionIds.includes(attempt.executionId)));
396
- if (partial)
411
+ if (declaredPartial)
397
412
  missing.push(`Sandbox session ${id} declared partial raw capture`);
398
413
  for (const reason of native.missingReasons)
399
414
  missing.push(`Sandbox session ${id}: ${reason}`);
@@ -675,6 +690,7 @@ async function captureSandboxEvidence(box, options, writer) {
675
690
  }
676
691
  sessions.push({
677
692
  id, executionId: artifactExecutionId, executionIds: [...executionIds], eventCountsByExecutionId,
693
+ ...(recoveredControlRefs.length ? { controlRefs: recoveredControlRefs } : {}),
678
694
  backendType: options.harness, sidecarImageDigest, sidecarBundleRevision,
679
695
  transportEvents: executionIds.every((executionId) => eventCountsByExecutionId[executionId] > 0) ? "complete" : "unavailable",
680
696
  eventCount: counts.events, messageCount: counts.messages, messageScope: "session",
@@ -299,22 +299,31 @@ export function createTangleProvider(options) {
299
299
  operation?.signal?.throwIfAborted();
300
300
  if (!box || boundedIdentifier(box.id, "Tangle environment id") !== id)
301
301
  return null;
302
- if (options.requireNativeSessionCapture)
302
+ if (options.requireNativeSessionCapture) {
303
303
  requireNativeCaptureProof(box);
304
+ // Native capture admits only the backend the live container reports, so a
305
+ // suspended sandbox must run again before anything can reconnect to it.
306
+ await resumeForReconnect(box, options.client, readyTimeoutMs, operation?.signal);
307
+ }
304
308
  let backendType;
309
+ let backendReadError;
305
310
  if (box.status === "running" && box.backend) {
306
311
  try {
307
312
  const status = await awaitWithSignal(box.backend.status(), operation?.signal);
308
313
  backendType = boundedIdentifier(status.type, "Tangle current backend");
309
314
  }
310
- catch {
315
+ catch (error) {
311
316
  operation?.signal?.throwIfAborted();
317
+ backendReadError = error;
312
318
  }
313
319
  }
314
320
  let captureCapabilities;
315
321
  if (options.requireNativeSessionCapture) {
316
- if (backendType === undefined)
317
- throw new Error("Tangle native capture requires the current selected backend before reconnect");
322
+ if (backendType === undefined) {
323
+ // The read's own failure (a 429 or 503 while the platform suspends the box)
324
+ // stays the cause, so a caller classifies it as the transport fault it is.
325
+ throw new Error("Tangle native capture requires the current selected backend before reconnect", backendReadError === undefined ? undefined : { cause: backendReadError });
326
+ }
318
327
  captureCapabilities = await awaitWithSignal(requireNativeCaptureCapability(box, backendType), operation?.signal);
319
328
  }
320
329
  const declaredCapabilities = await resolveDeclaredCapabilities(backendType);
@@ -400,6 +409,38 @@ export function createTangleProvider(options) {
400
409
  : {}),
401
410
  };
402
411
  }
412
+ /**
413
+ * Bring a suspended sandbox back before a reconnect reads its container.
414
+ *
415
+ * The platform suspends a sandbox after its idle timeout (30 minutes by
416
+ * default) and nothing resumes it on access. A root turn stalled on an
417
+ * upstream 429 for that long comes back to a stopped box; without a resume,
418
+ * every later reconnect finds no live backend and refuses identically until
419
+ * the driver exhausts its attempts. After the resume the sidecar reports the
420
+ * interrupted execution as a terminal failure, so the caller settles that
421
+ * execution and replaces it once instead of dispatching beside it.
422
+ */
423
+ async function resumeForReconnect(box, client, timeoutMs, signal) {
424
+ if (box.status === "running")
425
+ return;
426
+ if (box.status === "stopped") {
427
+ if (!box.resume) {
428
+ throw new Error(`Tangle sandbox ${box.id} is stopped and the linked client cannot resume it`);
429
+ }
430
+ try {
431
+ await awaitWithSignal(box.resume({ timeoutMs, ...(signal ? { signal } : {}) }), signal);
432
+ }
433
+ catch (error) {
434
+ signal?.throwIfAborted();
435
+ // Another reconnect may have resumed the same box first; its state decides.
436
+ await box.refresh?.(signal).catch(() => undefined);
437
+ const after = statusFromUnknown(box.status);
438
+ if (after !== "running" && after !== "pending" && after !== "provisioning")
439
+ throw error;
440
+ }
441
+ }
442
+ await awaitSandboxRunning(box, client, { timeoutMs, ...(signal ? { signal } : {}) });
443
+ }
403
444
  async function resolveBackend(client, backendType) {
404
445
  if (backendType === undefined)
405
446
  return undefined;
@@ -0,0 +1,6 @@
1
+ import { type AgentExactRunControlRef } from "@tangle-network/agent-interface";
2
+ /** Recover callers from server admission frames, never from bare native attempt IDs. */
3
+ export declare function retainedCaptureAttribution(events: readonly unknown[], anchor: AgentExactRunControlRef, signal?: AbortSignal): Promise<{
4
+ controlRefs: AgentExactRunControlRef[];
5
+ missing: string[];
6
+ }>;
@@ -0,0 +1,62 @@
1
+ import { AgentExactRunControlRefSchema } from "@tangle-network/agent-interface";
2
+ import { EvidenceJsonArray } from "./tangle-evidence-json.js";
3
+ import { sameRunControlRef } from "./tangle-session-control.js";
4
+ function record(value) {
5
+ return value !== null && typeof value === "object" && !Array.isArray(value)
6
+ ? value : undefined;
7
+ }
8
+ /** Recover callers from server admission frames, never from bare native attempt IDs. */
9
+ export async function retainedCaptureAttribution(events, anchor, signal) {
10
+ const refs = new Map();
11
+ const invalid = new Set();
12
+ const missing = [];
13
+ let count = 0;
14
+ const reject = (id, reason) => {
15
+ invalid.add(id);
16
+ refs.delete(id);
17
+ missing.push(`Retained caller attribution for execution ${id}: ${reason}`);
18
+ };
19
+ for (const value of events) {
20
+ const entry = record(value);
21
+ const metadata = record(entry?.metadata);
22
+ if (!entry || !metadata || typeof metadata.executionId !== "string" ||
23
+ metadata.sessionId !== anchor.sessionId)
24
+ throw new Error("Retained admission buffer names another session");
25
+ const executionId = metadata.executionId;
26
+ const frames = entry.frames instanceof EvidenceJsonArray ? entry.frames.entries() : entry.frames;
27
+ if (!frames || (!Array.isArray(frames) && !(entry.frames instanceof EvidenceJsonArray))) {
28
+ throw new Error("Retained admission frames are unavailable");
29
+ }
30
+ for await (const value of frames) {
31
+ signal?.throwIfAborted();
32
+ if (++count > 100_000)
33
+ throw new Error("Retained admission frame limit exceeded");
34
+ const frame = record(value);
35
+ if (frame?.type !== "execution.started")
36
+ continue;
37
+ const data = record(frame.data);
38
+ const parsed = AgentExactRunControlRefSchema.safeParse(data?.runControlRef);
39
+ if (frame.sessionId !== anchor.sessionId || frame.executionId !== executionId ||
40
+ data?.sessionId !== anchor.sessionId || data.executionId !== executionId || !parsed.success ||
41
+ parsed.data.provider !== anchor.provider || parsed.data.environmentId !== anchor.environmentId ||
42
+ parsed.data.sessionId !== anchor.sessionId || parsed.data.executionId !== executionId) {
43
+ reject(executionId, "missing or mismatched server admission reference");
44
+ continue;
45
+ }
46
+ if (invalid.has(executionId))
47
+ continue;
48
+ const previous = refs.get(executionId);
49
+ if (previous && !sameRunControlRef(previous, parsed.data)) {
50
+ reject(executionId, "conflicting server admission references");
51
+ continue;
52
+ }
53
+ refs.set(executionId, parsed.data);
54
+ }
55
+ }
56
+ const admittedAnchor = refs.get(anchor.executionId);
57
+ if (!admittedAnchor || !sameRunControlRef(admittedAnchor, anchor)) {
58
+ missing.push("Retained server admissions do not match the current exact control reference");
59
+ return { controlRefs: [], missing };
60
+ }
61
+ return { controlRefs: [...refs.values()], missing };
62
+ }
@@ -537,6 +537,14 @@ export interface SandboxInstanceLike {
537
537
  signal?: AbortSignal;
538
538
  }): Promise<void>;
539
539
  refresh?(signal?: AbortSignal): Promise<void>;
540
+ /**
541
+ * Resume a stopped sandbox. An idle or lifetime suspend stops the container
542
+ * and preserves the workspace; nothing resumes it on access.
543
+ */
544
+ resume?(options?: {
545
+ timeoutMs?: number;
546
+ signal?: AbortSignal;
547
+ }): Promise<void>;
540
548
  delete?(options?: {
541
549
  signal?: AbortSignal;
542
550
  }): Promise<unknown>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tangle-network/agent-provider-tangle",
3
- "version": "3.5.0",
3
+ "version": "3.5.2",
4
4
  "description": "AgentEnvironmentProvider adapter for Tangle sandboxes",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -62,6 +62,8 @@
62
62
  "dist/tangle-evidence-json.d.ts",
63
63
  "dist/tangle-evidence-native-files.js",
64
64
  "dist/tangle-evidence-native-files.d.ts",
65
+ "dist/tangle-retained-attribution.js",
66
+ "dist/tangle-retained-attribution.d.ts",
65
67
  "dist/tangle-native-capture-proof.d.ts",
66
68
  "dist/tangle-native-capture-proof.js",
67
69
  "dist/tangle-environment-dispatch.d.ts",