@tangle-network/agent-provider-tangle 5.0.15 → 5.0.17

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
@@ -731,6 +731,17 @@ An incomplete inventory, missing stream, unrelated backend, or mismatched digest
731
731
 
732
732
  ## Exact retained workspace capture
733
733
 
734
+ For a new file-output registration, the original created and dispatched environment can expose
735
+ `retainFileOutput({controlRef, policy})`. `policy.path` is relative to the managed workspace root;
736
+ declare generated output outside its source repository. The adapter uses the Sandbox SDK's
737
+ `stop({retain: {paths, publication: true}, wait: true})` overload, preserving existing retained paths.
738
+ Sandbox owns writer exclusion, stopped-snapshot capture, regular-file kind, immutable storage and custody.
739
+ The adapter retains the actual SDK receipt and verifies raw/stored length and SHA-256 equality.
740
+ It never uploads an archive or substitutes text. A reconstructed environment without the original
741
+ creation/dispatch authority, a lost stop response or a changed source returns unavailable.
742
+ Consumers persist the original positive association before acknowledgment and recover that record;
743
+ they must not retry capture after another invocation or treat unavailable delivery as a failed task.
744
+
734
745
  Pass the admitted `controlRef` to `captureTangleEnvironmentEvidence`.
735
746
  Keep `executionId` as the Runtime artifact identity.
736
747
  The control reference supplies the exact native environment, session, and execution identifiers.
@@ -186,7 +186,7 @@ function exactSandboxOptions(input, defaults, providerName, identityDigest) {
186
186
  return {
187
187
  environment: input.image,
188
188
  agent: false,
189
- driver: { type: "host-agent", runtimeBackend: "docker" },
189
+ runtime: "docker",
190
190
  ephemeral: true,
191
191
  sshEnabled: false,
192
192
  webTerminalEnabled: false,
@@ -89,6 +89,7 @@ export function defaultTangleSandboxCapabilities(harness) {
89
89
  git: false,
90
90
  upload: true,
91
91
  download: true,
92
+ retainFileOutput: true,
92
93
  cwdBases: { repository: true, host: false },
93
94
  },
94
95
  // The complete Sandbox SDK surface backs this contract. Narrowing below
@@ -8,6 +8,9 @@ export declare function sandboxInstanceAsEnvironment(box: SandboxInstanceLike, p
8
8
  signal?: AbortSignal;
9
9
  }, request?: {
10
10
  resources?: ResourceProfile;
11
+ retain?: {
12
+ paths: readonly string[];
13
+ };
11
14
  proxySecrets?: ProxySecretBinding[];
12
15
  confidentialAttestationVerifier?: TangleConfidentialAttestationVerifier;
13
16
  requireNativeSessionCapture?: boolean;
@@ -23,7 +23,8 @@ import { observeTangleEnvironment } from "./tangle-observation.js";
23
23
  import { createTangleTerminalRegistry } from "./tangle-terminal.js";
24
24
  import { createTangleInteractiveAgentRegistry } from "./tangle-interactive.js";
25
25
  import { confidentialVerifierOption, createTangleWorkspaceBranching, } from "./tangle-workspace-branching.js";
26
- import { bindTangleEvidenceEnvironment, noteTangleSession } from "./tangle-evidence.js";
26
+ import { bindTangleEvidenceEnvironment, clearTangleControlRef, noteTangleSession } from "./tangle-session-control.js";
27
+ import { retainTangleFileOutput } from "./tangle-retained-file.js";
27
28
  import { assertNativeCaptureHarness } from "./tangle-native-capture-proof.js";
28
29
  /** Compose measured sandbox operations; metadata records intent, never grant authority. */
29
30
  export async function sandboxInstanceAsEnvironment(box, providerName, client, declaredCapabilities, operation, request) {
@@ -65,7 +66,14 @@ export async function sandboxInstanceAsEnvironment(box, providerName, client, de
65
66
  const credentialHarness = request?.nativeAuth?.harness ?? request?.credentialHarness;
66
67
  const boundCredentialSource = request?.credentialSource ??
67
68
  (recordedCredentials !== undefined ? "subscription" : "router");
68
- const capabilities = frozenCapabilityDocument(AgentEnvironmentCapabilitiesSchema.parse(capabilitiesForSandbox(declaredCapabilities, support, deployment, confidentialVerifierOption(request?.confidentialAttestationVerifier))));
69
+ const creation = creationFromSandboxCreateReceipt(box.createReceipt?.());
70
+ const sourceCreatedAt = box.createdAt instanceof Date ? box.createdAt.toISOString() : box.createdAt;
71
+ const measuredCapabilities = capabilitiesForSandbox(declaredCapabilities, support, deployment, confidentialVerifierOption(request?.confidentialAttestationVerifier));
72
+ measuredCapabilities.workspace.retainFileOutput =
73
+ measuredCapabilities.workspace.retainFileOutput === true && typeof box.stop === "function" &&
74
+ creation !== undefined && typeof sourceCreatedAt === "string" && Number.isFinite(Date.parse(sourceCreatedAt)) &&
75
+ request?.ephemeral !== true && measuredCapabilities.retainedControl !== undefined;
76
+ const capabilities = frozenCapabilityDocument(AgentEnvironmentCapabilitiesSchema.parse(measuredCapabilities));
69
77
  const workspaceBranching = capabilities.branching.checkpoint &&
70
78
  capabilities.branching.fork &&
71
79
  capabilities.branching.lookup === true &&
@@ -99,7 +107,6 @@ export async function sandboxInstanceAsEnvironment(box, providerName, client, de
99
107
  ...(options.signal ? { signal: options.signal } : {}),
100
108
  ...(options.controlRef ? { runControlRef: options.controlRef } : {}),
101
109
  });
102
- const creation = creationFromSandboxCreateReceipt(box.createReceipt?.());
103
110
  const environment = {
104
111
  id: environmentId,
105
112
  provider: providerName,
@@ -108,6 +115,9 @@ export async function sandboxInstanceAsEnvironment(box, providerName, client, de
108
115
  ...(box.name ? { name: boundedString(box.name, "Tangle environment name") } : {}),
109
116
  ...(box.metadata ? { metadata: snapshotMetadata(box.metadata) } : {}),
110
117
  capabilities,
118
+ ...(capabilities.workspace.retainFileOutput === true && typeof sourceCreatedAt === "string" ? {
119
+ retainFileOutput: (input, operation) => retainTangleFileOutput(environment, box, sourceCreatedAt, request?.retain?.paths ?? [], input, operation),
120
+ } : {}),
111
121
  ...(workspaceBranching === undefined
112
122
  ? {}
113
123
  : { workspaceBranching }),
@@ -118,8 +128,9 @@ export async function sandboxInstanceAsEnvironment(box, providerName, client, de
118
128
  },
119
129
  stream: environmentTurnStream(box, providerName, environmentId, prepareTurn, prepareOptions, (sessionId, executionId) => noteTangleSession(environment, sessionId, executionId), usageLog),
120
130
  ...(dispatch ? { async dispatch(input) {
131
+ clearTangleControlRef(environment);
121
132
  const ref = await dispatch(input);
122
- noteTangleSession(environment, ref.id, input.executionId ?? input.controlRef?.executionId ?? ref.controlRef?.executionId);
133
+ noteTangleSession(environment, ref.id, input.executionId ?? input.controlRef?.executionId ?? ref.controlRef?.executionId, ref.controlRef ?? null);
123
134
  return ref;
124
135
  } } : {}),
125
136
  ...((capabilities.sessions.continue || capabilities.streaming.replay || capabilities.streaming.detach) &&
@@ -9,3 +9,4 @@ export declare function harnessContentOmission(rootScope: string, path: string):
9
9
  * 99 MB and 4-6 s with these bytes, 4.4 MB and under 0.6 s without them (2026-10-19, Beelink).
10
10
  */
11
11
  export declare const NATIVE_OMIT_CONTENT_DIRECTORIES: readonly string[];
12
+ export declare const tangleEvidenceCredentialPath: (path: string) => boolean;
@@ -28,3 +28,5 @@ for (const directory of NATIVE_OMIT_CONTENT_DIRECTORIES) {
28
28
  throw new Error(`Tangle evidence would omit ${directory} without keeping its files as metadata`);
29
29
  }
30
30
  }
31
+ const blockedNames = new Set([".ssh", ".config", ".claude", ".codex", ".opencode", ".env", ".env.local", ".npmrc", ".sidecar"]);
32
+ export const tangleEvidenceCredentialPath = (path) => path.split("/").some((part) => blockedNames.has(part) || /^\.env\./.test(part));
@@ -1,3 +1,4 @@
1
+ export { bindTangleEvidenceEnvironment, noteTangleSession } from "./tangle-session-control.js";
1
2
  import { type AgentExactRunControlRef, type AgentProfile } from "@tangle-network/agent-interface";
2
3
  import type { AgentEnvironment } from "@tangle-network/agent-interface/environment-provider";
3
4
  import type { NativeCaptureProofLike, SandboxInstanceLike, TangleEvidenceAttemptLike, TangleEvidenceSourceLike } from "./tangle-types.js";
@@ -197,8 +198,6 @@ export interface TangleEnvironmentEvidence {
197
198
  missing: string[];
198
199
  };
199
200
  }
200
- export declare function bindTangleEvidenceEnvironment(environment: AgentEnvironment, box: SandboxInstanceLike): void;
201
- export declare function noteTangleSession(environment: AgentEnvironment, sessionId: string, executionId?: string): void;
202
201
  /** Export an environment through its retained Sandbox handle. */
203
202
  export declare function captureTangleEnvironmentEvidence(environment: AgentEnvironment, options: TangleEnvironmentEvidenceOptions): Promise<TangleEnvironmentEvidence>;
204
203
  export interface TangleDirectoryEvidence {
@@ -211,4 +210,3 @@ export declare function captureTangleEnvironmentEvidenceToDirectory(environment:
211
210
  export declare function captureTangleSandboxEvidenceToDirectory(box: SandboxInstanceLike, options: TangleSandboxEvidenceOptions & TangleDirectoryEvidenceOptions): Promise<TangleDirectoryEvidence>;
212
211
  /** Export exact Sandbox session and workspace evidence before its owning box is deleted. */
213
212
  export declare function captureTangleSandboxEvidence(box: SandboxInstanceLike, options: TangleSandboxEvidenceOptions): Promise<TangleEnvironmentEvidence>;
214
- export {};
@@ -1,3 +1,5 @@
1
+ import { tangleEnvironmentHandle, safeNativeCaptureIdentifier as safeIdentifier } from "./tangle-session-control.js";
2
+ export { bindTangleEvidenceEnvironment, noteTangleSession } from "./tangle-session-control.js";
1
3
  import { createHash } from "node:crypto";
2
4
  import { EvidenceJsonArray, evidenceJsonChunks } from "./tangle-evidence-json.js";
3
5
  import { createDirectoryEvidenceWriter, createMemoryEvidenceWriter } from "./tangle-evidence-writer.js";
@@ -6,9 +8,7 @@ import { AgentExactRunControlRefSchema } from "@tangle-network/agent-interface";
6
8
  import { requireNativeCaptureProof } from "./tangle-native-capture-proof.js";
7
9
  import { retainedCaptureAttribution } from "./tangle-retained-attribution.js";
8
10
  import { readWorkspaceArchive } from "./tangle-evidence-tar.js";
9
- import { harnessContentOmission } from "./tangle-evidence-omission.js";
10
- const handles = new WeakMap();
11
- const blockedNames = new Set([".ssh", ".config", ".claude", ".codex", ".opencode", ".env", ".env.local", ".npmrc", ".sidecar"]);
11
+ import { harnessContentOmission, tangleEvidenceCredentialPath } from "./tangle-evidence-omission.js";
12
12
  const MAX_ENTRIES = 100_000;
13
13
  const MAX_EVENTS = 100_000;
14
14
  // How long a replay may go without its start marker once the stream is open. The Sidecar sends
@@ -66,17 +66,6 @@ const WORKSPACE_BATCH_BYTES = 8 * 1024 * 1024;
66
66
  const WORKSPACE_ARCHIVE_STREAMS = 4;
67
67
  // Tar header, PAX record and padding bytes an archive may add per member beyond its content.
68
68
  const WORKSPACE_ARCHIVE_ENTRY_OVERHEAD = 2048;
69
- export function bindTangleEvidenceEnvironment(environment, box) {
70
- handles.set(environment, { box, sessions: new Map() });
71
- }
72
- export function noteTangleSession(environment, sessionId, executionId) {
73
- const state = handles.get(environment);
74
- if (!state || !executionId || !safeIdentifier(sessionId) || !safeIdentifier(executionId))
75
- return;
76
- const executions = state.sessions.get(sessionId) ?? new Set();
77
- executions.add(executionId);
78
- state.sessions.set(sessionId, executions);
79
- }
80
69
  /** Export an environment through its retained Sandbox handle. */
81
70
  export async function captureTangleEnvironmentEvidence(environment, options) {
82
71
  const context = evidenceContext(environment, options);
@@ -100,7 +89,7 @@ export async function captureTangleSandboxEvidenceToDirectory(box, options) {
100
89
  }
101
90
  }
102
91
  function evidenceContext(environment, options) {
103
- const state = handles.get(environment);
92
+ const state = tangleEnvironmentHandle(environment);
104
93
  if (!state || state.box.id !== environment.id)
105
94
  throw new Error("Tangle evidence requires a live provider environment handle");
106
95
  const controlRef = options.controlRef === undefined ? undefined : AgentExactRunControlRefSchema.parse(options.controlRef);
@@ -245,7 +234,7 @@ async function captureSandboxEvidence(box, options, writer) {
245
234
  }
246
235
  if (item.type === "directory") {
247
236
  scannedDirectories++;
248
- if (parts.some((part) => blockedNames.has(part))) {
237
+ if (tangleEvidenceCredentialPath(path)) {
249
238
  excludedPaths.push({ ...item, reason: "credential-path" });
250
239
  return "blocked";
251
240
  }
@@ -259,7 +248,7 @@ async function captureSandboxEvidence(box, options, writer) {
259
248
  excludedPaths.push({ ...item, reason: "symlink" });
260
249
  return "omit";
261
250
  }
262
- if (parts.some((part) => blockedNames.has(part) || /^\.env\./.test(part))) {
251
+ if (tangleEvidenceCredentialPath(parts.join("/"))) {
263
252
  excludedPaths.push({ ...item, reason: "credential-path" });
264
253
  return "omit";
265
254
  }
@@ -368,7 +357,7 @@ async function captureSandboxEvidence(box, options, writer) {
368
357
  // The former walk never listed below a runtime-owned or credential directory; the
369
358
  // usage scan counted credential subtrees, so their members are counted, not admitted.
370
359
  const ancestors = path.split("/").slice(0, -1);
371
- const stop = ancestors.find((part) => blockedNames.has(part));
360
+ const stop = ancestors.find(tangleEvidenceCredentialPath);
372
361
  if (stop === ".sidecar") {
373
362
  // Never admitted or counted, but its declared bytes still bound the decompression.
374
363
  ignoredBytes += size;
@@ -1134,9 +1123,6 @@ function withoutNativeContent(source) {
1134
1123
  delete metadata.contentBase64;
1135
1124
  return metadata;
1136
1125
  }
1137
- function safeIdentifier(value) {
1138
- return typeof value === "string" && /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(value);
1139
- }
1140
1126
  function safeReason(value) {
1141
1127
  return typeof value === "string" && value.length > 0 && value.length <= 1024 && !/[\u0000-\u001f\u007f]/.test(value);
1142
1128
  }
@@ -1,4 +1,4 @@
1
- import { validateProfileForCreate } from "@tangle-network/sandbox";
1
+ import { splitInlineProfileFileMounts, validateDeferredProfileFileMounts, validateProfileForCreate } from "@tangle-network/sandbox";
2
2
  /** Validate the normalized profile once through the SDK and account owner's read-only route check. */
3
3
  export function tangleProfileValidator(supplied, resolver) {
4
4
  return async (profile) => {
@@ -6,8 +6,11 @@ export function tangleProfileValidator(supplied, resolver) {
6
6
  if (result && !result.ok)
7
7
  return result;
8
8
  const candidate = result?.normalizedProfile ?? profile;
9
- // Without a harness the SDK still runs create's inline-mount and size checks; it skips only materialization.
10
- const verdict = typeof candidate !== "string" ? validateProfileForCreate(candidate, candidate.harness) : undefined;
9
+ // Sandbox >= 1.0.393 refuses a missing harness; without one only create's inline-mount checks apply.
10
+ // The profile cast covers the SDK's bundled harness/seats union (https://github.com/tangle-network/agent-container/issues/18386).
11
+ const verdict = typeof candidate === "string" ? undefined
12
+ : candidate.harness ? validateProfileForCreate(candidate, candidate.harness)
13
+ : mountVerdict(candidate);
11
14
  const issues = verdict && !verdict.ok ? [{ level: "error", code: verdict.error.code, message: verdict.error.message }] : [];
12
15
  if (issues.length)
13
16
  return { ok: false, issues };
@@ -16,3 +19,16 @@ export function tangleProfileValidator(supplied, resolver) {
16
19
  ...(result?.normalizedProfile ? { normalizedProfile: result.normalizedProfile } : {}) };
17
20
  };
18
21
  }
22
+ function mountVerdict(profile) {
23
+ try {
24
+ const typed = profile;
25
+ const { deferredFiles } = splitInlineProfileFileMounts(typed);
26
+ validateDeferredProfileFileMounts(deferredFiles, { failOnError: typed.resources?.failOnError });
27
+ return { ok: true };
28
+ }
29
+ catch (error) {
30
+ const code = error.code;
31
+ const message = error instanceof Error ? error.message : String(error);
32
+ return { ok: false, error: { code: typeof code === "string" ? code : "VALIDATION_ERROR", message } };
33
+ }
34
+ }
@@ -40,6 +40,10 @@ function ephemeralCapabilityCeiling(capabilities, ephemeral) {
40
40
  create: { ...capabilities.create, workspaceCheckpoint: false },
41
41
  };
42
42
  }
43
+ // Provider-boundary document: client-stage facts only, validated before create or get effects.
44
+ function narrowedProviderCapabilities(declared, options) {
45
+ return AgentEnvironmentCapabilitiesSchema.parse(capabilitiesForClient(declared, options.client, confidentialVerifierOption(options.confidentialAttestationVerifier)));
46
+ }
43
47
  export function createTangleProvider(options) {
44
48
  const readyTimeoutMs = providerReadyTimeout(options);
45
49
  const resolveModelCredentials = typeof options.modelCredentials === "function"
@@ -92,10 +96,7 @@ export function createTangleProvider(options) {
92
96
  }
93
97
  : narrowed;
94
98
  };
95
- // Provider-boundary document: client-stage facts only. It also validates
96
- // the configured document, so create() and get() call it before any effect.
97
- const narrowedProviderCapabilities = (declared) => AgentEnvironmentCapabilitiesSchema.parse(capabilitiesForClient(declared, options.client, confidentialVerifierOption(options.confidentialAttestationVerifier)));
98
- const resolveCapabilities = async () => narrowedProviderCapabilities(await resolveDeclaredCapabilities(options.defaultBackend));
99
+ const resolveCapabilities = async () => narrowedProviderCapabilities(await resolveDeclaredCapabilities(options.defaultBackend), options);
99
100
  const createRecords = new Map();
100
101
  const createEnvironment = async (input) => {
101
102
  if (input.workspace?.snapshot !== undefined) {
@@ -217,7 +218,7 @@ export function createTangleProvider(options) {
217
218
  // Backend selection belongs to the create projection. The provider-wide
218
219
  // default cannot describe a sandbox that this projection routes elsewhere.
219
220
  const declaredCapabilities = await resolveDeclaredCapabilities(createOptions.backend?.type);
220
- narrowedProviderCapabilities(declaredCapabilities);
221
+ narrowedProviderCapabilities(declaredCapabilities, options);
221
222
  if (checkpoint !== undefined && declaredCapabilities.create?.workspaceCheckpoint !== true) {
222
223
  throw new Error("Tangle workspace checkpoint restore is not supported by the declared capabilities");
223
224
  }
@@ -278,6 +279,7 @@ export function createTangleProvider(options) {
278
279
  : await awaitWithSignal(requireNativeCaptureCapability(box, captureHarness), input.signal);
279
280
  const requestedResources = requestedResourceProfile(input.resources);
280
281
  const environment = await sandboxInstanceAsEnvironment(box, providerName, options.client, declaredCapabilities, input.signal ? { signal: input.signal } : undefined, {
282
+ ...(input.retain === undefined ? {} : { retain: input.retain }),
281
283
  ...(requestedResources === undefined
282
284
  ? {}
283
285
  : { resources: requestedResources }),
@@ -0,0 +1,8 @@
1
+ import { type AgentRetainedFileOutputRequest, type AgentRetainedFileOutputResult } from "@tangle-network/agent-interface/environment-provider";
2
+ import type { AgentEnvironment } from "@tangle-network/agent-interface/environment-provider";
3
+ import type { SandboxInstanceLike } from "./tangle-types.js";
4
+ /** References only: Sandbox performs the stopped capture and owns every byte and revision. */
5
+ export declare function retainTangleFileOutput(environment: AgentEnvironment, box: SandboxInstanceLike, sourceCreatedAt: string, retainedPaths: readonly string[], raw: AgentRetainedFileOutputRequest, options?: {
6
+ signal?: AbortSignal;
7
+ idempotencyKey?: string;
8
+ }): Promise<AgentRetainedFileOutputResult>;
@@ -0,0 +1,55 @@
1
+ import { AgentRetainedFileOutputRequestSchema, AgentRetainedFileOutputResultSchema, } from "@tangle-network/agent-interface/environment-provider";
2
+ import { tangleEvidenceCredentialPath } from "./tangle-evidence-omission.js";
3
+ import { currentTangleControlRef, sameRunControlRef } from "./tangle-session-control.js";
4
+ const unavailable = (reason) => ({ status: "unavailable", reason });
5
+ /** References only: Sandbox performs the stopped capture and owns every byte and revision. */
6
+ export async function retainTangleFileOutput(environment, box, sourceCreatedAt, retainedPaths, raw, options) {
7
+ const { controlRef, policy } = AgentRetainedFileOutputRequestSchema.parse(raw);
8
+ const current = currentTangleControlRef(environment);
9
+ if (!current || !sameRunControlRef(current, controlRef) ||
10
+ controlRef.environmentId !== box.id || controlRef.provider !== environment.provider)
11
+ return unavailable("The original execution is not this handle's current admitted source");
12
+ if (!box.stop || !environment.creation || tangleEvidenceCredentialPath(policy.path))
13
+ return unavailable("The declared output has no owned retained-stop publication authority");
14
+ options?.signal?.throwIfAborted();
15
+ try {
16
+ const publication = await box.stop({
17
+ retain: { paths: [...new Set([...retainedPaths, policy.path])], publication: true },
18
+ wait: true,
19
+ ...(options?.signal ? { signal: options.signal } : {}),
20
+ ...(options?.idempotencyKey ? { idempotencyKey: options.idempotencyKey } : {}),
21
+ });
22
+ const after = currentTangleControlRef(environment);
23
+ if (!after || !sameRunControlRef(after, current) || !publication ||
24
+ publication.sandboxId !== box.id ||
25
+ Date.parse(publication.sourceCreatedAt) !== Date.parse(sourceCreatedAt))
26
+ return unavailable("The stopped publication did not retain the original physical source");
27
+ const files = publication.files.filter((file) => file.sourcePath === policy.path);
28
+ const file = files[0];
29
+ if (files.length !== 1 || !file || file.runId !== publication.runId ||
30
+ file.sandboxId !== box.id || file.workspaceSnapshot !== publication.workspaceSnapshot ||
31
+ file.sourceKind !== "regular" || file.preserved !== true || !file.etag ||
32
+ file.sourceSha256 !== file.storedSha256 || file.sourceBytes !== file.storedBytes)
33
+ return unavailable("The declared file has no exact preserved regular-file revision");
34
+ return AgentRetainedFileOutputResultSchema.parse({
35
+ status: "published",
36
+ publication: {
37
+ controlRef: current,
38
+ policy,
39
+ source: {
40
+ environmentId: publication.sandboxId,
41
+ createdAt: publication.sourceCreatedAt,
42
+ filesystemIncarnationId: publication.filesystemIncarnationId,
43
+ workspaceSnapshot: publication.workspaceSnapshot,
44
+ },
45
+ file: { path: policy.path, kind: "regular", sha256: file.sourceSha256, byteLength: file.sourceBytes },
46
+ providerReference: { ...publication },
47
+ preserved: true,
48
+ },
49
+ });
50
+ }
51
+ catch {
52
+ // No retry here: a missing original acknowledgment cannot authorize capturing a later source.
53
+ return unavailable("The original stopped-file publication could not be verified");
54
+ }
55
+ }
@@ -1,5 +1,6 @@
1
+ import type { SandboxInstanceLike } from "./tangle-types.js";
1
2
  import type { AgentExactRunControlRef, AgentRunControlRef } from "@tangle-network/agent-interface";
2
- import type { AgentSessionRef } from "@tangle-network/agent-interface/environment-provider";
3
+ import type { AgentEnvironment, AgentSessionRef } from "@tangle-network/agent-interface/environment-provider";
3
4
  /**
4
5
  * Sandbox started nothing for this dispatch: it reported `dispatched: false`
5
6
  * and named another execution that owns the session or turn. That execution
@@ -35,3 +36,15 @@ export declare function sessionPromptExecutionId(requestDigest: `sha256:${string
35
36
  export declare function sessionPromptSessionId(provider: string, environmentId: string, turnId: string | undefined): string | undefined;
36
37
  export declare function sameRunControlRef(left: AgentRunControlRef, right: AgentRunControlRef): boolean;
37
38
  export declare function resolveRetainedSessionControlRef(candidate: AgentRunControlRef | undefined, sessionId: string, provider: string, environmentId: string): AgentExactRunControlRef | undefined;
39
+ export declare const tangleEnvironmentHandle: (environment: AgentEnvironment) => {
40
+ box: SandboxInstanceLike;
41
+ sessions: Map<string, Set<string>>;
42
+ currentControlRef?: AgentExactRunControlRef;
43
+ } | undefined;
44
+ export declare function bindTangleEvidenceEnvironment(environment: AgentEnvironment, box: SandboxInstanceLike): void;
45
+ export declare function noteTangleSession(environment: AgentEnvironment, sessionId: string, executionId?: string, controlRef?: AgentRunControlRef | null): void;
46
+ /** Actual dispatch identity retained by this handle; session hints never populate it. */
47
+ export declare const currentTangleControlRef: (environment: AgentEnvironment) => AgentExactRunControlRef | undefined;
48
+ /** A new dispatch invalidates the prior source even while its admission is unresolved. */
49
+ export declare function clearTangleControlRef(environment: AgentEnvironment): void;
50
+ export declare function safeNativeCaptureIdentifier(value: string): boolean;
@@ -149,3 +149,39 @@ export function resolveRetainedSessionControlRef(candidate, sessionId, provider,
149
149
  }
150
150
  return retainedSessionControlRef(sessionId, controlRef.executionId, provider, environmentId, controlRef.requestDigest, controlRef.runId);
151
151
  }
152
+ const handles = new WeakMap();
153
+ export const tangleEnvironmentHandle = (environment) => handles.get(environment);
154
+ export function bindTangleEvidenceEnvironment(environment, box) {
155
+ handles.set(environment, { box, sessions: new Map() });
156
+ }
157
+ export function noteTangleSession(environment, sessionId, executionId, controlRef) {
158
+ const state = handles.get(environment);
159
+ if (!state)
160
+ return;
161
+ if (executionId && safeNativeCaptureIdentifier(sessionId) && safeNativeCaptureIdentifier(executionId)) {
162
+ const executions = state.sessions.get(sessionId) ?? new Set();
163
+ executions.add(executionId);
164
+ state.sessions.set(sessionId, executions);
165
+ }
166
+ if (state.currentControlRef && (state.currentControlRef.sessionId !== sessionId ||
167
+ state.currentControlRef.executionId !== executionId))
168
+ state.currentControlRef = undefined;
169
+ if (controlRef !== undefined) {
170
+ state.currentControlRef = undefined;
171
+ const parsed = AgentExactRunControlRefSchema.safeParse(controlRef);
172
+ if (parsed.success && parsed.data.provider === environment.provider && parsed.data.environmentId === environment.id &&
173
+ parsed.data.sessionId === sessionId && parsed.data.executionId === executionId)
174
+ state.currentControlRef = Object.freeze(parsed.data);
175
+ }
176
+ }
177
+ /** Actual dispatch identity retained by this handle; session hints never populate it. */
178
+ export const currentTangleControlRef = (environment) => handles.get(environment)?.currentControlRef;
179
+ /** A new dispatch invalidates the prior source even while its admission is unresolved. */
180
+ export function clearTangleControlRef(environment) {
181
+ const state = handles.get(environment);
182
+ if (state)
183
+ state.currentControlRef = undefined;
184
+ }
185
+ export function safeNativeCaptureIdentifier(value) {
186
+ return typeof value === "string" && /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(value);
187
+ }
@@ -408,6 +408,8 @@ export interface SandboxInteractiveSessionLike {
408
408
  }
409
409
  export interface SandboxInstanceLike {
410
410
  id: string;
411
+ /** The linked SDK owns retained-stop request and publication response validation. */
412
+ stop?: SandboxInstance["stop"];
411
413
  createSession?: SandboxInstance["createSession"];
412
414
  readonly proxySecretReceipt?: SandboxInstance["proxySecretReceipt"];
413
415
  preparePublicProfileRevision?: SandboxInstance["preparePublicProfileRevision"];
@@ -246,10 +246,10 @@ export function createTangleWorkspaceBranching(options) {
246
246
  // rebuilds and re-sorts on every page; on a busy account a page failed or
247
247
  // repeated, deletion was never attempted, and the source was kept running.
248
248
  const known = await findManagedCheckpoint(box, provider, request.targetId, undefined, operation?.signal);
249
- if (known === "unknown") {
250
- return cleanupUnknown(request, "Sandbox checkpoint inventory is unavailable; deletion was not attempted", true);
249
+ if (known.state === "unknown") {
250
+ return cleanupUnknown(request, `Sandbox checkpoint lookup answered unknown (${known.reason}); deletion was not attempted`, true);
251
251
  }
252
- if (known === false) {
252
+ if (known.state === "absent") {
253
253
  const acknowledgement = cleanupAlreadyAbsent(request);
254
254
  cleanup.set(request.operationId, {
255
255
  requestDigest: request.requestDigest,
@@ -259,19 +259,19 @@ export function createTangleWorkspaceBranching(options) {
259
259
  }
260
260
  let result;
261
261
  try {
262
- result = await awaitWithSignal(box.deleteSnapshot?.(request.targetId), operation?.signal);
262
+ result = await awaitWithSignal(box.deleteSnapshot?.(known.snapshotId), operation?.signal);
263
263
  }
264
264
  catch (error) {
265
265
  operation?.signal?.throwIfAborted();
266
266
  return cleanupTransportFailure(request, `Sandbox checkpoint deletion failed: ${safeError(error)}`, true);
267
267
  }
268
268
  const outcome = result &&
269
- result.snapshotId === request.targetId &&
269
+ result.snapshotId === known.snapshotId &&
270
270
  (result.outcome === "deleted" || result.outcome === "already_absent")
271
271
  ? result.outcome
272
272
  : "unknown";
273
273
  if (outcome !== "deleted" && outcome !== "already_absent") {
274
- return cleanupUnknown(request, "Sandbox did not attest checkpoint deletion", true);
274
+ return cleanupUnknown(request, "Sandbox delete answered unknown (deletion not attested)", true);
275
275
  }
276
276
  const acknowledgement = outcome === "deleted"
277
277
  ? cleanupDeleted(request)
@@ -315,12 +315,12 @@ export function createTangleWorkspaceBranching(options) {
315
315
  }
316
316
  const checkpoint = [...checkpoints.values()].some((record) => canonicalCandidateDigest(record.checkpoint) ===
317
317
  canonicalCandidateDigest(request.checkpoint))
318
- ? true
318
+ ? undefined
319
319
  : await findManagedCheckpoint(box, provider, request.checkpoint.checkpointId, request.checkpoint, operation?.signal);
320
- if (checkpoint !== true) {
321
- return forkUnknown(request, checkpoint === false
320
+ if (checkpoint !== undefined && checkpoint.state !== "found") {
321
+ return forkUnknown(request, checkpoint.state === "absent"
322
322
  ? "Requested checkpoint is absent"
323
- : "Sandbox checkpoint inventory is unavailable", true);
323
+ : `Sandbox checkpoint lookup answered unknown (${checkpoint.reason})`, true);
324
324
  }
325
325
  const metadata = forkMarkerMetadata(request);
326
326
  let returnedChild;
@@ -30,13 +30,32 @@ export declare function validSnapshotResult(result: SandboxSnapshotResultLike |
30
30
  /** Normalize one remote checkpoint recovery attempt for every caller. */
31
31
  export declare function reconcileCheckpoint(box: SandboxInstanceLike, provider: string, request: Pick<WorkspaceCheckpointRequest, "idempotencyKey" | "requestDigest">, signal?: AbortSignal): Promise<CheckpointReconciliation>;
32
32
  /**
33
- * Confirm that one snapshot id is a settled checkpoint this provider created.
33
+ * One checkpoint id resolved against its source's inventory. `snapshotId` is
34
+ * the physical id Sandbox lists, which is the id a delete must name: a sealed
35
+ * checkpoint is listed under its physical id with the acknowledged id in its
36
+ * one `seal.<id>` tag. `unknown` names the step that could not decide.
37
+ */
38
+ export type ManagedCheckpoint = {
39
+ state: "found";
40
+ snapshotId: string;
41
+ } | {
42
+ state: "absent";
43
+ } | {
44
+ state: "unknown";
45
+ reason: "inventory unavailable" | "ambiguous seal alias" | "invalid snapshot metadata" | "not marked by this source" | "operation not confirmed";
46
+ };
47
+ /**
48
+ * Confirm that one checkpoint id is a settled checkpoint this provider created.
34
49
  *
35
- * `expected` binds the answer to a specific checkpoint reference. A reference
36
- * that does not match its marker is absent, not unknown: the caller supplied a
37
- * checkpoint this source never produced.
50
+ * Without `expected` (cleanup), a match by id or by its one seal alias is
51
+ * accepted only when the snapshot carries this source's own marker and the
52
+ * marker's operation succeeded; a seal alias also needs that operation's
53
+ * result to name this id with the same marker. Anything less is unknown,
54
+ * never absent. `expected` binds the answer to a specific checkpoint
55
+ * reference (fork): a reference that does not match its marker is absent, not
56
+ * unknown, because the caller supplied a checkpoint this source never produced.
38
57
  */
39
- export declare function findManagedCheckpoint(box: SandboxInstanceLike, provider: string, id: string, expected?: WorkspaceCheckpointRef, signal?: AbortSignal): Promise<true | false | "unknown">;
58
+ export declare function findManagedCheckpoint(box: SandboxInstanceLike, provider: string, id: string, expected?: WorkspaceCheckpointRef, signal?: AbortSignal): Promise<ManagedCheckpoint>;
40
59
  export declare function findForkByKey(client: SandboxClientLike, box: SandboxInstanceLike, provider: string, key: string, signal?: AbortSignal): Promise<(RecoveredForkChild & {
41
60
  marker: ForkMarker;
42
61
  }) | null | undefined>;
@@ -242,50 +242,59 @@ function snapshotFromOperationResult(snapshot, lookup, marker) {
242
242
  return { ...snapshot, snapshotId: lookup.result.snapshotId, createdAt: lookup.result.createdAt };
243
243
  }
244
244
  /**
245
- * Confirm that one snapshot id is a settled checkpoint this provider created.
245
+ * Confirm that one checkpoint id is a settled checkpoint this provider created.
246
246
  *
247
- * `expected` binds the answer to a specific checkpoint reference. A reference
248
- * that does not match its marker is absent, not unknown: the caller supplied a
249
- * checkpoint this source never produced.
247
+ * Without `expected` (cleanup), a match by id or by its one seal alias is
248
+ * accepted only when the snapshot carries this source's own marker and the
249
+ * marker's operation succeeded; a seal alias also needs that operation's
250
+ * result to name this id with the same marker. Anything less is unknown,
251
+ * never absent. `expected` binds the answer to a specific checkpoint
252
+ * reference (fork): a reference that does not match its marker is absent, not
253
+ * unknown, because the caller supplied a checkpoint this source never produced.
250
254
  */
251
255
  export async function findManagedCheckpoint(box, provider, id, expected, signal) {
256
+ const unknown = (reason) => ({ state: "unknown", reason });
257
+ const absent = { state: "absent" };
252
258
  try {
253
259
  const snapshots = await awaitWithSignal(box.listSnapshots?.(), signal);
254
260
  if (!Array.isArray(snapshots) || snapshots.length > MAX_LIST_RESULTS) {
255
- return "unknown";
261
+ return unknown("inventory unavailable");
256
262
  }
257
263
  const candidates = snapshots.filter((candidate) => snapshotHasId(candidate, id) !== false);
258
264
  if (candidates.length === 0)
259
- return false;
260
- if (candidates.length !== 1)
261
- return "unknown";
265
+ return absent;
266
+ if (candidates.length !== 1 || snapshotHasId(candidates[0], id) !== true)
267
+ return unknown("ambiguous seal alias");
262
268
  const snapshot = candidates[0];
263
- if (!validSnapshotInfo(snapshot, box.id) || snapshotHasId(snapshot, id) !== true)
264
- return "unknown";
265
- // An expected reference can prove a fork source; an alias alone never authorizes cleanup.
266
- if (snapshot.snapshotId !== id && expected === undefined)
267
- return "unknown";
269
+ if (!validSnapshotInfo(snapshot, box.id))
270
+ return unknown("invalid snapshot metadata");
268
271
  const marker = checkpointMarkerFromTags(snapshot.tags, expected?.idempotencyKey);
269
- if (!marker)
270
- return expected ? false : "unknown";
271
- if (marker.request.source.provider !== provider ||
272
- marker.request.source.environmentId !== box.id) {
273
- return expected ? false : "unknown";
272
+ if (!marker || !checkpointMarkerBelongsToSource(marker, provider, box.id)) {
273
+ return expected ? absent : unknown("not marked by this source");
274
274
  }
275
275
  if (expected &&
276
276
  (marker.requestDigest !== expected.requestDigest ||
277
277
  canonicalCandidateDigest(marker.request.source) !==
278
278
  canonicalCandidateDigest(expected.source))) {
279
- return false;
279
+ return absent;
280
+ }
281
+ let lookup;
282
+ try {
283
+ lookup = await checkpointOperationLookup(box, marker, signal);
284
+ }
285
+ catch {
286
+ signal?.throwIfAborted();
287
+ return unknown("operation not confirmed");
280
288
  }
281
- const lookup = await checkpointOperationLookup(box, marker, signal);
282
289
  if (lookup?.outcome !== "found" || lookup.kind !== "checkpoint" || lookup.state !== "succeeded")
283
- return "unknown";
284
- return snapshot.snapshotId === id || snapshotFromOperationResult(snapshot, lookup, marker)?.snapshotId === id ? true : "unknown";
290
+ return unknown("operation not confirmed");
291
+ return snapshot.snapshotId === id || snapshotFromOperationResult(snapshot, lookup, marker)?.snapshotId === id
292
+ ? { state: "found", snapshotId: snapshot.snapshotId }
293
+ : unknown("operation not confirmed");
285
294
  }
286
295
  catch {
287
296
  signal?.throwIfAborted();
288
- return "unknown";
297
+ return unknown("inventory unavailable");
289
298
  }
290
299
  }
291
300
  export async function findForkByKey(client, box, provider, key, signal) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tangle-network/agent-provider-tangle",
3
- "version": "5.0.15",
3
+ "version": "5.0.17",
4
4
  "description": "AgentEnvironmentProvider adapter for Tangle sandboxes",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -33,10 +33,10 @@
33
33
  "LICENSE"
34
34
  ],
35
35
  "dependencies": {
36
- "@tangle-network/agent-interface": "^5.10.20"
36
+ "@tangle-network/agent-interface": "^5.10.25"
37
37
  },
38
38
  "peerDependencies": {
39
- "@tangle-network/sandbox": ">=1.0.242 <2.0.0"
39
+ "@tangle-network/sandbox": ">=1.0.393 <2.0.0"
40
40
  },
41
41
  "peerDependenciesMeta": {
42
42
  "@tangle-network/sandbox": {
@@ -44,9 +44,9 @@
44
44
  }
45
45
  },
46
46
  "devDependencies": {
47
- "@tangle-network/agent-provider-testkit": "0.12.5",
47
+ "@tangle-network/agent-provider-testkit": "0.12.7",
48
48
  "@tangle-network/agent-runtime": "0.349.0",
49
- "@tangle-network/sandbox": "^1.0.242",
49
+ "@tangle-network/sandbox": "^1.0.393",
50
50
  "@types/node": "26.6.5",
51
51
  "typescript": "6.0.3",
52
52
  "vitest": "5.0.5"