@tangle-network/sandbox 0.60.78-develop.20261017090901.9326d18 → 0.60.78-develop.20261021201434.3bcd5ef

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.
Files changed (66) hide show
  1. package/README.md +61 -0
  2. package/dist/agent/index.d.ts +4 -4
  3. package/dist/agent/index.js +5 -5
  4. package/dist/agent/preview.d.ts +1 -1
  5. package/dist/agent/preview.js +2 -2
  6. package/dist/{agent-run-outcome-CTEpjCEZ.d.ts → agent-run-outcome-brwJbH5S.d.ts} +1 -1
  7. package/dist/auth/index.d.ts +2 -2
  8. package/dist/auth/index.js +5 -5
  9. package/dist/{backend-types-D6bYbvMB.js → backend-types-CLvdSX8V.js} +41 -1
  10. package/dist/{browser-interactive-control-controller-rpTbyvAS.d.ts → browser-interactive-control-controller-CvObO_Kf.d.ts} +1 -1
  11. package/dist/{browser-interactive-control-controller-BJf0P_J4.js → browser-interactive-control-controller-DHx53yre.js} +16 -1
  12. package/dist/{chunked-upload-DtIvkKNo.js → chunked-upload-DN2twsUu.js} +2 -59
  13. package/dist/{chunked-upload-file-DnsHEjg0.js → chunked-upload-file-Dpv1YsoA.js} +2 -1
  14. package/dist/{cli-auth-bundle-cSJjPeFF.js → cli-auth-bundle-CFeHsq-5.js} +23 -11
  15. package/dist/{client-R1tw-4Px.js → client-CgtR203z.js} +3349 -3341
  16. package/dist/client-Dr8qasCR.d.ts +6076 -0
  17. package/dist/collaboration/index.d.ts +1 -1
  18. package/dist/collaboration/index.js +1 -1
  19. package/dist/{collaboration-DaJU5O0E.js → collaboration-g_HzXa6f.js} +5 -5
  20. package/dist/core.d.ts +7 -7
  21. package/dist/core.js +7 -6
  22. package/dist/direct-http2-Dar5erTH.js +99 -0
  23. package/dist/{errors-DSJBKmGZ.js → errors-BfbOP_rx.js} +171 -22
  24. package/dist/{index-DO7GVpk_.d.ts → index-C8VSFtWl.d.ts} +1 -1
  25. package/dist/{index-DZ27pdB8.d.ts → index-CVjTnRWP.d.ts} +1 -1
  26. package/dist/{sandbox-CoIGxzm_.d.ts → index-D5dVNm76.d.ts} +2117 -1519
  27. package/dist/index.d.ts +12 -4704
  28. package/dist/index.js +40 -15
  29. package/dist/intelligence/index.js +1 -1
  30. package/dist/interactive-control.d.ts +1 -1
  31. package/dist/interactive-control.js +1 -1
  32. package/dist/{interactive-controller-CJ24g8Va.js → interactive-controller-OAsASPd_.js} +662 -620
  33. package/dist/interactive-controller-nMhGqXxq.d.ts +41 -0
  34. package/dist/keep-alive-fetch-BBzJDWyt.js +247 -0
  35. package/dist/{lines-DodQslsf.d.ts → lines-C5CPSg8n.d.ts} +21 -17
  36. package/dist/lines-C5ER4aN_.js +298 -0
  37. package/dist/lines.d.ts +1 -1
  38. package/dist/lines.js +1 -295
  39. package/dist/{local-cli-auth-CBV7Vjk5.js → local-cli-auth-D-CQ0-ub.js} +1 -1
  40. package/dist/{mcp-local-DjryqUiY.js → mcp-local-BjLG7VHY.js} +1 -1
  41. package/dist/{preview-wpGGk0bu.d.ts → preview-COO7TSBk.d.ts} +3 -3
  42. package/dist/public-templates-BDrchm0J.d.ts +80 -0
  43. package/dist/public-templates.d.ts +2 -0
  44. package/dist/public-templates.js +173 -0
  45. package/dist/{raw-evidence-archive-Br5a3xZ_.js → raw-evidence-archive-CDYDqHNv.js} +161 -69
  46. package/dist/runtime.d.ts +49 -41
  47. package/dist/runtime.js +8 -8
  48. package/dist/{sandbox-C7Tk62qn.js → sandbox-BrZxAq11.js} +9048 -8939
  49. package/dist/{secp256k1-Dx2XABHz.js → secp256k1-CmLpsmWl.js} +1 -1
  50. package/dist/session-gateway/index.d.ts +23 -67
  51. package/dist/session-gateway/index.js +578 -451
  52. package/dist/tangle/index.d.ts +1 -1
  53. package/dist/tangle/index.js +1 -1
  54. package/dist/{tangle-Ba4Kz5zT.js → tangle-GiPBak5X.js} +176 -169
  55. package/dist/terminal-stream-types-ClZCArRg.d.ts +662 -0
  56. package/dist/{types-B_QF-iHm.d.ts → types-CtH0GRql.d.ts} +6161 -5812
  57. package/package.json +12 -7
  58. package/dist/client-Lhxo82x1.d.ts +0 -1261
  59. package/dist/errors-mPL-qvgF.d.ts +0 -347
  60. package/dist/index-DRto9Ijb.d.ts +0 -579
  61. package/dist/managed-process-B7WfqKmi.d.ts +0 -15
  62. package/dist/terminal-stream-jdYomM1m.d.ts +0 -389
  63. /package/dist/{cli-auth-bundle-ODe06Ts7.d.ts → cli-auth-bundle-Dyw3hCGx.d.ts} +0 -0
  64. /package/dist/{line-application-Cq6dJLBD.js → line-application-DY9ZTdgF.js} +0 -0
  65. /package/dist/{preview-operations-DqSo-IBm.js → preview-operations-Ca02vPDJ.js} +0 -0
  66. /package/dist/{utils-B7_9Hl_z.js → utils-BGvM02yJ.js} +0 -0
@@ -1,11 +1,12 @@
1
- import { t as CliAuthReference } from "./cli-auth-bundle-ODe06Ts7.js";
2
- import { $a as WriteManyOptions, $i as SendSessionMessageOptions, $t as ForkIdempotency, A as CommitTaskSessionOptions, Aa as TaskSessionChanges, An as ListMessagesOptions, Br as SandboxEvent, C as BranchOptions, Ca as SnapshotResult, Ci as SandboxOperationInfo, Cn as InstalledTool, Cr as ResumeOptions, D as CodeExecutionResult, Da as StopOptions, E as CodeExecutionOptions, Ei as SandboxPortBinding, En as IntelligenceReportCompareTo, Er as RolloutOptions, Fa as TeeAttestationOptions, Fr as SandboxDeleteAcknowledgement, H as CreateTaskSessionOptions, Ha as TurnBackendConfig, Ir as SandboxDeleteOptions, Ja as WaitForOptions, La as TeeAttestationResponse, Li as SandboxStatus, M as ConversationTurnOptions, Mi as SandboxRuntimeCapabilities, Mr as SSHCredentials, N as ConversationTurnResult, Na as TaskSessionInfo, Ni as SandboxRuntimeHealth, O as CodeLanguage, On as IntelligenceReportWindow, Or as RolloutStartResult, Ot as FileSystem, Pi as SandboxShape, Pr as SandboxConnection, Pt as FileWriteResult, Q as DispatchedSession, Qa as WriteManyFile, Qt as ForkCounts, Ri as SandboxTerminalAttachOptions, Sn as HttpClient, Sr as RestoreSnapshotOptions, Ta as StartupDiagnostics, Ti as SandboxOperationState, Tn as IntelligenceReportBudget, Ua as TurnDriveResult, Ui as SandboxTerminals, V as CreateSessionOptions, Wi as SandboxTraceBundle, Wn as NetworkManager, Xa as WorkspaceOperationLookup, Xi as SearchOptions, Ya as WaitForRolloutOptions, Yi as SearchMatch, Yn as PreviewLinkManager, Z as DispatchPromptOptions, Za as WriteFileOptions, ar as PromptInputPart, ba as SnapshotOptions, bt as ExecOptions, ca as SessionInfo, cn as GpuLease, cr as ProvisionEvent, ct as DurablePlanDecisionResult, d as BackendConfig, da as SessionMessage, di as SandboxFleetTraceBundle, do as WorkspaceImagePublishResult$1, ea as SendSessionMessageRequest, en as ForkLookupOptions, fa as SessionMessageAdmission, fo as InteractionResolutionAcknowledgement, fr as PublicProfileConflict, ga as SnapshotDeleteAcknowledgement, ht as EgressManager, ia as SessionExecutionInfo, in as GitCommit, io as SandboxEnvRecoveryView, it as DriverInfo, j as CompletedTurnResult, ja as TaskSessionCommitResult, jr as SSHCommandDescriptor, ki as SandboxResourceUsage, kn as JsonValue, la as SessionInterruptOptions, lr as ProvisionResult, ma as SessionResultOptions, no as SandboxCreateReceipt, nt as DriveTurnOptions, on as GitDiff, oo as RawEvidenceDirectoryExport, or as PromptOptions, ot as DurablePlan, p as BackendManager, pn as GpuLeaseManager, qi as SandboxTraceOptions, qn as PermissionsManager, ra as SessionEventStreamOptions, rn as GitBranch, ro as SandboxEnvRecovery, sa as SessionForkOptions, sn as GitStatus, so as RawEvidenceExportOptions, sr as PromptResult, st as DurablePlanDecisionOptions, ta as SentSessionMessage, tr as ProcessManager, ua as SessionListOptions, vt as EventStreamOptions, wi as SandboxOperationKind, wn as IntelligenceReport, wr as Rollout, xa as SnapshotProvenance, xi as SandboxInfo, xt as ExecResult, ya as SnapshotInfo, za as TeePublicKeyResponse } from "./types-B_QF-iHm.js";
3
- import { c as TerminalStreamReconnectAuthority, f as MintScopedTokenOptions, n as TerminalStream, o as TerminalStreamHandlers, p as ScopedToken, y as TerminalReadyInfo } from "./terminal-stream-jdYomM1m.js";
4
- import { f as InteractiveAttachOptions, g as InteractiveSessionStatus, h as InteractiveRequestOptions, m as InteractiveControlClaimOptions, p as InteractiveControlClaimAcknowledgement } from "./browser-interactive-control-controller-rpTbyvAS.js";
5
- import { E as InteractiveAttachRequest, h as SandboxError } from "./errors-mPL-qvgF.js";
6
- import { z as SandboxLines } from "./lines-DodQslsf.js";
1
+ import { F as SandboxError, G as SandboxCreateReceipt, g as TerminalReadyInfo, i as TerminalStreamHandlers, l as MintScopedTokenOptions, o as TerminalStreamReconnectAuthority, u as ScopedToken } from "./terminal-stream-types-ClZCArRg.js";
2
+ import { $i as DurablePlan, $r as SearchOptions, Bi as ForkLookupOptions, Bn as SandboxPortBinding, C as WorkspaceOperationLookup, Ct as SessionMessageAdmission, D as ProvisionResult, Dt as TaskSessionCommitResult, E as ProvisionEvent, Ei as CodeExecutionResult, En as SandboxFleetTraceBundle, Et as TaskSessionChanges, Fi as JsonValue, G as GitBranch, Ha as WorkspaceImagePublishResult, Hi as RolloutOptions, In as SSHCommandDescriptor, J as GitStatus, Ja as SandboxEnvRecovery, K as GitCommit, Li as BranchOptions, Ln as SSHCredentials, Lr as FileSystem, N as WaitForOptions, Pi as HttpClient, Q as CommitTaskSessionOptions, Qn as TeeAttestationOptions, Qr as SearchMatch, Ri as ForkCounts, Rn as SandboxConnection, S as StopOptions, Sa as BackendConfig, St as SessionMessage, Ti as CodeExecutionOptions, Tt as SessionResultOptions, U as PreviewLinkManager, Ua as CodeLanguage, Ui as RolloutStartResult, Un as SandboxRuntimeHealth, Ur as FileWriteResult, Va as WorkspaceImagePublishInput, Vi as Rollout, Wi as WaitForRolloutOptions, Wn as SandboxTerminalAttachOptions, Xn as StartupDiagnostics, Xr as WriteManyFile, Ya as SandboxEnvRecoveryView, Yn as SandboxTerminals, Yr as WriteFileOptions, Zr as WriteManyOptions, _ as SnapshotInfo, aa as IntelligenceReport, ar as CreateSandboxOptions, at as DispatchPromptOptions, ba as TurnBackendConfig, bt as SessionInterruptOptions, c as SandboxDeleteOptions, cr as SandboxShape, ct as ListMessagesOptions, d as SandboxOperationKind, da as PromptOptions, dr as SandboxStatus, dt as SendSessionMessageRequest, ea as DurablePlanDecisionOptions, ei as ExecOptions, eo as RawEvidenceBoxDirectoryExport, er as TeeAttestationResponse, et as CompletedTurnResult, f as SandboxOperationState, fa as PromptResult, fi as DriverInfo, ft as SentSessionMessage, gr as EgressManager, ha as SandboxTraceBundle, ht as SessionExecutionInfo, ia as EventStreamOptions, it as CreateTaskSessionOptions, jt as TurnDriveResult, k as ResumeOptions, kt as TaskSessionInfo, la as IntelligenceReportWindow, lt as PublicProfileConflict, m as SnapshotDeleteAcknowledgement, mi as GpuLease, mr as SandboxRuntimeCapabilities, mt as SessionEventStreamOptions, no as RawEvidenceDirectoryExport, nr as TeePublicKeyResponse, nt as ConversationTurnResult, o as RestoreSnapshotOptions, oa as IntelligenceReportBudget, ot as DispatchedSession, pa as SandboxEvent, pr as SandboxResourceUsage, q as GitDiff, ro as RawEvidenceExportOptions, rr as TerminalStream, rt as CreateSessionOptions, s as SandboxDeleteAcknowledgement, sa as IntelligenceReportCompareTo, so as InteractionResolutionAcknowledgement, st as DriveTurnOptions, ta as DurablePlanDecisionResult, ti as ExecResult, to as RawEvidenceBoxExportOptions, tt as ConversationTurnOptions, u as SandboxOperationInfo, ua as PromptInputPart, ut as SendSessionMessageOptions, v as SnapshotOptions, va as SandboxTraceOptions, vr as NetworkManager, vt as SessionForkOptions, wa as BackendManager, x as SnapshotResult, xt as SessionListOptions, y as SnapshotProvenance, yi as GpuLeaseManager, yt as SessionInfo, z as ProcessManager, zi as ForkIdempotency, zn as SandboxInfo } from "./types-CtH0GRql.js";
3
+ import { t as CliAuthReference } from "./cli-auth-bundle-Dyw3hCGx.js";
4
+ import { n as SandboxLines } from "./lines-C5CPSg8n.js";
5
+ import { f as InteractiveAttachOptions, g as InteractiveSessionStatus, h as InteractiveRequestOptions, m as InteractiveControlClaimOptions, p as InteractiveControlClaimAcknowledgement } from "./browser-interactive-control-controller-CvObO_Kf.js";
6
+ import { r as InteractiveAttachRequest } from "./interactive-controller-nMhGqXxq.js";
7
7
  import { z } from "zod";
8
- import { AgentInteractiveSessionAttach, AgentInteractiveSessionControlClaim, AgentInteractiveSessionControlClaimAcknowledgement, AgentInteractiveSessionControlClaimRequest, AgentInteractiveSessionPromptAcknowledgement, AgentInteractiveSessionPromptCommand, AgentInteractiveSessionRef, AgentInteractiveSessionStart, AgentInteractiveSessionStopAcknowledgement, AgentInteractiveSessionStopCommand, AgentInteractiveTerminalSession, AgentInteractiveTerminalSession as AgentInteractiveTerminalSession$1, AgentProfile, AgentProfileFileMount, AgentRunCancellationAcknowledgement, AgentRunCancellationRequest, InteractionAcknowledgement, InteractionData, InteractionRequest, InteractionResponseCommand, TerminalOutputEvent, TerminalReplayWindow, agentInteractiveSessionPromptRequestDigest } from "@tangle-network/agent-interface";
8
+ import * as Agent from "@tangle-network/agent-interface";
9
+ import { AgentInteractiveSessionAttach, AgentInteractiveSessionControlClaim, AgentInteractiveSessionControlClaimRequest, AgentInteractiveSessionPromptAcknowledgement, AgentInteractiveSessionPromptCommand, AgentInteractiveSessionRef, AgentInteractiveSessionStart, AgentInteractiveSessionStopAcknowledgement, AgentInteractiveSessionStopCommand, AgentInteractiveTerminalSession, AgentInteractiveTerminalSession as AgentInteractiveTerminalSession$1, AgentProfile, AgentProfileFileMount, AgentRunCancellationAcknowledgement, AgentRunCancellationRequest, InteractionAcknowledgement, InteractionData, InteractionRequest, InteractionResponseCommand, TerminalOutputEvent, TerminalReplayWindow, agentInteractiveSessionPromptRequestDigest } from "@tangle-network/agent-interface";
9
10
 
10
11
  //#region src/mcp.d.ts
11
12
  /**
@@ -118,40 +119,36 @@ declare function buildControlPlaneMcpConfig(options: BuildControlPlaneMcpConfigO
118
119
  config: SandboxMcpConfig;
119
120
  };
120
121
  //#endregion
121
- //#region src/direct-read-route.d.ts
122
- type DirectReadFallbackReason = "expired" | "refused" | "unreachable" | "timeout" | "malformed" | "cooldown";
123
- /** What the route has done, for the caller and for the probe. */
124
- interface DirectReadStats {
125
- /** Reads offered to this route. */
126
- attempts: number;
127
- /** Direct reads that proved the state had not moved; no API call followed. */
128
- unchanged: number;
129
- /** Direct reads that saw a change and sent the caller to the API. */
130
- changed: number;
131
- /** Reads that went to the API because the direct route could NOT serve. */
132
- fallbacks: number;
133
- /** Why the last fallback happened; null until one does. */
134
- lastReason: DirectReadFallbackReason | null;
122
+ //#region src/operation.d.ts
123
+ /** An accepted operation ended in failure. `code` names why. */
124
+ declare class SandboxOperationFailedError extends SandboxError {
125
+ readonly operation: SandboxOperationInfo;
126
+ constructor(operation: SandboxOperationInfo);
135
127
  }
136
- //#endregion
137
- //#region src/interaction-response.d.ts
138
- declare const REFUSED_INTERACTION_STATUS: z.ZodEnum<{
139
- already_resolved_different: "already_resolved_different";
140
- binding_mismatch: "binding_mismatch";
141
- }>;
142
- type SandboxInteractionResolution = InteractionResolutionAcknowledgement;
143
- type SandboxInteractionConflict = {
144
- status: z.infer<typeof REFUSED_INTERACTION_STATUS>;
145
- message: string;
146
- existingResponseDigest?: `sha256:${string}`;
147
- existingOperationId?: string;
148
- resolvedAt?: string;
149
- };
150
- type SandboxInteractionResult = SandboxInteractionResolution | SandboxInteractionConflict;
151
- /** Canonical acknowledgement and the exact durable server result, when one exists. */
152
- interface SandboxInteractionCommandResult {
153
- acknowledgement: InteractionAcknowledgement;
154
- serverResult?: SandboxInteractionResult;
128
+ declare class SandboxOperation {
129
+ #private;
130
+ /**
131
+ * @param client - null for a verb that already finished synchronously.
132
+ * @param onSettled - runs once when the operation is first seen succeeded.
133
+ */
134
+ constructor(info: SandboxOperationInfo, client: HttpClient | null, onSettled?: (info: SandboxOperationInfo) => void | Promise<void>);
135
+ /** A verb the API finished synchronously, as a succeeded operation. */
136
+ static completed(kind: SandboxOperationKind, sandboxId: string, result?: SandboxOperationInfo["result"]): SandboxOperation;
137
+ get id(): string;
138
+ get state(): SandboxOperationState;
139
+ /** The last state read. */
140
+ get info(): SandboxOperationInfo;
141
+ /** Read the operation's current state. */
142
+ refresh(): Promise<SandboxOperationInfo>;
143
+ /**
144
+ * Poll until the operation is terminal (250 ms, doubling to 2 s). Resolves
145
+ * with a succeeded operation; throws {@link SandboxOperationFailedError} on
146
+ * a failed one and {@link TimeoutError} past `timeoutMs` (default 10 min).
147
+ */
148
+ wait(options?: {
149
+ timeoutMs?: number;
150
+ signal?: AbortSignal;
151
+ }): Promise<SandboxOperationInfo>;
155
152
  }
156
153
  //#endregion
157
154
  //#region src/interactive-terminal-session.d.ts
@@ -332,39 +329,33 @@ declare class InteractiveSessionHandle {
332
329
  stopLifecycle(options?: InteractiveRequestOptions): Promise<AgentInteractiveSessionStopAcknowledgement>;
333
330
  }
334
331
  //#endregion
335
- //#region src/operation.d.ts
336
- /** An accepted operation ended in failure. `code` names why. */
337
- declare class SandboxOperationFailedError extends SandboxError {
338
- readonly operation: SandboxOperationInfo;
339
- constructor(operation: SandboxOperationInfo);
332
+ //#region src/interaction-response.d.ts
333
+ declare const REFUSED_INTERACTION_STATUS: z.ZodEnum<{
334
+ already_resolved_different: "already_resolved_different";
335
+ binding_mismatch: "binding_mismatch";
336
+ }>;
337
+ type SandboxInteractionResolution = InteractionResolutionAcknowledgement;
338
+ type SandboxInteractionConflict = {
339
+ status: z.infer<typeof REFUSED_INTERACTION_STATUS>;
340
+ message: string;
341
+ existingResponseDigest?: `sha256:${string}`;
342
+ existingOperationId?: string;
343
+ resolvedAt?: string;
344
+ };
345
+ type SandboxInteractionResult = SandboxInteractionResolution | SandboxInteractionConflict;
346
+ /** Canonical acknowledgement and the exact durable server result, when one exists. */
347
+ interface SandboxInteractionCommandResult {
348
+ acknowledgement: InteractionAcknowledgement;
349
+ serverResult?: SandboxInteractionResult;
340
350
  }
341
- declare class SandboxOperation {
342
- #private;
343
- /**
344
- * @param client - null for a verb that already finished synchronously.
345
- * @param onSettled - runs once when the operation is first seen succeeded.
346
- */
347
- constructor(info: SandboxOperationInfo, client: HttpClient | null, onSettled?: (info: SandboxOperationInfo) => void | Promise<void>);
348
- /** A verb the API finished synchronously, as a succeeded operation. */
349
- static completed(kind: SandboxOperationKind, sandboxId: string, result?: SandboxOperationInfo["result"]): SandboxOperation;
350
- get id(): string;
351
- get state(): SandboxOperationState;
352
- /** The last state read. */
353
- get info(): SandboxOperationInfo;
354
- /** Read the operation's current state. */
355
- refresh(): Promise<SandboxOperationInfo>;
356
- /**
357
- * Poll until the operation is terminal (250 ms, doubling to 2 s). Resolves
358
- * with a succeeded operation; throws {@link SandboxOperationFailedError} on
359
- * a failed one and {@link TimeoutError} past `timeoutMs` (default 10 min).
360
- */
361
- wait(options?: {
362
- timeoutMs?: number;
363
- signal?: AbortSignal;
364
- }): Promise<SandboxOperationInfo>;
351
+ interface SandboxInteractionTransport {
352
+ /** Public sandbox id used by InteractionBinding.environmentId. */
353
+ environmentId: string;
354
+ ensureRunning(): Promise<void>;
355
+ fetch(endpoint: string, request: RequestInit): Promise<Response>;
365
356
  }
366
357
  //#endregion
367
- //#region src/profile-file-mounts.d.ts
358
+ //#region src/profile-file-preparation.d.ts
368
359
  interface SplitInlineProfileFileMountsResult {
369
360
  leanProfile: AgentProfile;
370
361
  deferredFiles: AgentProfileFileMount[];
@@ -421,8 +412,16 @@ type ProfileFileMountBox = {
421
412
  * client-detectable bad input (traversal paths, control characters,
422
413
  * non-string content) fails without paying for a sandbox that would only be
423
414
  * orphaned by the post-provision throw.
415
+ *
416
+ * A path the sidecar file API refuses (an absolute path outside
417
+ * `SANDBOX_FILE_API_ABSOLUTE_ROOTS`) follows the profile's resource policy:
418
+ * with `failOnError` true (the default) it throws
419
+ * {@link ProfileFileMountPathError} (422); with `failOnError: false` the
420
+ * mount is dropped with a warning. Returns the mounts to deliver.
424
421
  */
425
- declare function validateDeferredProfileFileMounts(files: readonly AgentProfileFileMount[]): void;
422
+ declare function validateDeferredProfileFileMounts(files: readonly AgentProfileFileMount[], options?: {
423
+ /** The profile's `resources.failOnError`; false drops refused mounts. */failOnError?: boolean;
424
+ }): AgentProfileFileMount[];
426
425
  interface SplitInlineProfileSkillsResult {
427
426
  /** Profile with inline skill refs removed (github refs kept — they resolve
428
427
  * server-side). Suitable for the create body, whose wire cap the full skill
@@ -442,7 +441,6 @@ interface SplitInlineProfileSkillsResult {
442
441
  */
443
442
  declare function splitInlineProfileSkills(profile: AgentProfile): SplitInlineProfileSkillsResult;
444
443
  declare function splitInlineProfileFileMounts(profile: AgentProfile): SplitInlineProfileFileMountsResult;
445
- declare function materializeProfileFileMounts(box: ProfileFileMountBox, files: readonly AgentProfileFileMount[], options?: MaterializeProfileFileMountsOptions): Promise<MaterializeProfileFileMountsResult>;
446
444
  //#endregion
447
445
  //#region src/profile-file-delivery.d.ts
448
446
  /**
@@ -461,320 +459,23 @@ interface ProfileFileDeliveryReport {
461
459
  durationMs: number;
462
460
  }
463
461
  //#endregion
464
- //#region src/session.d.ts
465
- type RawEvidenceAttempt = {
466
- executionId: string;
467
- ordinal: number;
468
- providerSessionId: string;
469
- nativeSessionIds: string[];
470
- processIds: string[];
471
- outcome: "succeeded" | "failed" | "cancelled" | "unknown";
472
- missingReasons: string[];
473
- };
474
- type RawEvidenceExport = ({
475
- status: "captured" | "partial";
476
- sessionId: string;
477
- backendType: string;
478
- nativeSessionId: string | null;
479
- proofStatus: "verified" | "unverified";
480
- containerId?: string;
481
- sidecarImageDigest: string;
482
- sidecarBundleRevision: string;
483
- sidecarBundleChecksum?: string;
484
- nativeRoots: Array<{
485
- sourceId?: string;
486
- rootScope: "session-home" | "workspace-session";
487
- path: string;
488
- }>;
489
- files: Array<Record<string, unknown>>;
490
- excluded: Array<Record<string, unknown>>;
491
- skipped: Array<{
492
- sourceId?: string;
493
- rootScope: "session-home" | "workspace-session";
494
- path: string;
495
- reason: string;
496
- }>;
497
- inventory: Record<string, number>;
498
- processIo: Array<Record<string, unknown>>;
499
- processTerminals: Array<Record<string, unknown>>; /** Exact raw spool for every readable provider HOME. */
500
- processSources: Array<{
501
- sourceId: string;
502
- contentBase64: string;
503
- sizeBytes: number;
504
- sha256: string;
505
- }>;
506
- events: Array<Record<string, unknown>>;
507
- attempts: RawEvidenceAttempt[];
508
- evidenceSources: Array<{
509
- executionId: string;
510
- sourceId: string;
511
- backendType: string;
512
- runtimeHome: string;
513
- credentialPaths: string[];
514
- }>;
515
- completeness: {
516
- nativeStore: boolean;
517
- processIo: boolean;
518
- events: boolean;
519
- };
520
- coverageComplete: boolean;
521
- missingReasons: string[];
522
- } & ({
523
- status: "captured";
524
- nativeSessionId: string | null;
525
- completeness: {
526
- nativeStore: true;
527
- processIo: true;
528
- events: true;
529
- };
530
- coverageComplete: true;
531
- missingReasons: [];
532
- } | {
533
- status: "partial";
534
- coverageComplete: false;
535
- })) | {
536
- status: "unavailable";
537
- sessionId: string;
538
- backendType: string;
539
- reason: string;
540
- };
541
- /**
542
- * The subset of `SandboxInstance` a `SandboxSession` drives. Declared here
543
- * (rather than importing the concrete class) so `session.ts` stays a leaf
544
- * of `sandbox.ts` — `sandbox.ts` constructs `SandboxSession`, so the reverse
545
- * import would form a cycle. `SandboxInstance` satisfies this structurally.
546
- */
547
- interface SandboxSessionHost extends InteractiveSessionHost {
548
- prompt(message: string | PromptInputPart[], options?: PromptOptions): Promise<PromptResult>;
549
- _sessionStatus(id: string): Promise<SessionInfo | null>;
550
- _sessionEvents(id: string, opts?: SessionEventStreamOptions): AsyncGenerator<SandboxEvent>;
551
- _sessionRuns(id: string): Promise<SessionExecutionInfo[]>;
552
- _sessionRawEvidence(id: string): Promise<RawEvidenceExport>;
553
- _sessionExportRawEvidence(id: string, destination: string, options: RawEvidenceExportOptions): Promise<RawEvidenceDirectoryExport>;
554
- _sessionAdmission(id: string, turnId: string, options?: {
555
- signal?: AbortSignal;
556
- }): Promise<SessionMessageAdmission | null>;
557
- _sessionResult(id: string, options?: SessionResultOptions, session?: SessionInfo): Promise<PromptResult>;
558
- _sessionDelete(id: string): Promise<void>;
559
- _sessionSendMessage(id: string, request: SendSessionMessageRequest, options?: SendSessionMessageOptions): Promise<SentSessionMessage>;
560
- messages(opts: ListMessagesOptions): Promise<SessionMessage[]>;
561
- _sessionFork(id: string, opts?: SessionForkOptions): Promise<SessionInfo>;
562
- _respondToPermission(id: string, permissionID: string, options: RespondToPermissionOptions): Promise<SandboxInteractionResult>;
563
- _listInteractions(id: string, options?: {
564
- signal?: AbortSignal;
565
- }): Promise<InteractionRequest[]>;
566
- _respondToInteraction(id: string, command: InteractionResponseCommand, options?: {
567
- signal?: AbortSignal;
568
- }): Promise<SandboxInteractionCommandResult>;
569
- _interrupt(id: string, options?: SessionInterruptOptions): Promise<InterruptResult>;
570
- _cancelRun(id: string, request: AgentRunCancellationRequest, options?: {
571
- signal?: AbortSignal;
572
- }): Promise<AgentRunCancellationAcknowledgement>;
573
- _answerQuestion(id: string, interactionId: string, answers: InteractionData, options?: {
574
- signal?: AbortSignal;
575
- }): Promise<SandboxInteractionResult>;
576
- _currentPlan(id: string): Promise<DurablePlan | null>;
577
- _decidePlan(id: string, planId: string, decision: {
578
- outcome: "approved";
579
- } | {
580
- outcome: "rejected";
581
- feedback: string;
582
- }, options?: DurablePlanDecisionOptions): Promise<DurablePlanDecisionResult>;
462
+ //#region src/direct-read-route.d.ts
463
+ type DirectReadFallbackReason = "expired" | "refused" | "unreachable" | "timeout" | "malformed" | "cooldown";
464
+ /** What the route has done, for the caller and for the probe. */
465
+ interface DirectReadStats {
466
+ /** Reads offered to this route. */
467
+ attempts: number;
468
+ /** Direct reads that proved the state had not moved; no API call followed. */
469
+ unchanged: number;
470
+ /** Direct reads that saw a change and sent the caller to the API. */
471
+ changed: number;
472
+ /** Reads that went to the API because the direct route could NOT serve. */
473
+ fallbacks: number;
474
+ /** Why the last fallback happened; null until one does. */
475
+ lastReason: DirectReadFallbackReason | null;
583
476
  }
584
- /**
585
- * A single agent session inside a sandbox. Created via
586
- * `box.session(id)` — does not hit the network until a method is called.
587
- */
588
- declare class SandboxSession {
589
- private readonly box;
590
- /** Stable session id assigned by the sandbox runtime. */
591
- readonly id: string;
592
- /**
593
- * @internal SDK-internal constructor — apps should call `box.session(id)`.
594
- */
595
- constructor(box: SandboxSessionHost, /** Stable session id assigned by the sandbox runtime. */
596
-
597
- id: string);
598
- /**
599
- * Fetch the current session state from the sandbox. Includes status,
600
- * model, prompt count, token usage if known, and timing metadata.
601
- *
602
- * Throws on transport error; returns `null` if the session id is not
603
- * known to the sandbox (e.g. it ended and was reaped, or the id is
604
- * invalid).
605
- */
606
- status(): Promise<SessionInfo | null>;
607
- /**
608
- * Stream events from this session as they arrive. With no `since`,
609
- * starts at the live tail; with `since`, replays strictly after that
610
- * event id — useful for reconnect-after-disconnect flows.
611
- *
612
- * The async iterator terminates when the session reaches a terminal
613
- * state (`completed`, `failed`, `cancelled`) and the corresponding
614
- * terminal event has been yielded, OR when the caller's signal aborts.
615
- */
616
- events(opts?: SessionEventStreamOptions): AsyncGenerator<SandboxEvent>;
617
- /**
618
- * List the durable executions recorded for this session, newest first.
619
- *
620
- * This is the runtime's authoritative execution ledger. It lets callers
621
- * count provider runs without inferring execution from model-written files.
622
- */
623
- runs(): Promise<SessionExecutionInfo[]>;
624
- /** Capture the complete attributed native store and process stream before deletion. */
625
- /** Export verified native evidence into a new local directory with bounded memory. */
626
- exportRawEvidence(destination: string, options: RawEvidenceExportOptions): Promise<RawEvidenceDirectoryExport>;
627
- rawEvidence(): Promise<RawEvidenceExport>;
628
- /** Read the exact execution admitted for a turn, including server-owned plan follow-ups.
629
- * This never admits work or verifies the input of a proposed retry.
630
- */
631
- admission(turnId: string, options?: {
632
- signal?: AbortSignal;
633
- }): Promise<SessionMessageAdmission | null>;
634
- /**
635
- * Await a terminal result. With `executionId`, drains only that execution;
636
- * without it, reads status and selects the latest execution. Event replay
637
- * makes either form safe after the execution has already finished.
638
- *
639
- * Use this to wait for a session that was started by another caller
640
- * (e.g. `dispatchPrompt`).
641
- */
642
- result(options?: SessionResultOptions): Promise<PromptResult>;
643
- /**
644
- * List persisted messages for this session, including in-flight assistant
645
- * content when the runtime has flushed partial output.
646
- */
647
- messages(opts?: Omit<ListMessagesOptions, "sessionId">): Promise<SessionMessage[]>;
648
- /**
649
- * Continue this session with an additional prompt. Equivalent to
650
- * `box.prompt(message, { ...opts, sessionId: this.id })` but reads
651
- * naturally on a Session reference.
652
- */
653
- prompt(message: string | PromptInputPart[], opts?: PromptOptions): Promise<PromptResult>;
654
- /**
655
- * Submit a structured message through the session message endpoint. The
656
- * returned receipt confirms admission; follow progress with `events()` or
657
- * await the terminal response with `result()`. Model and message identifiers
658
- * are translated to the runtime's wire names by the SDK.
659
- */
660
- sendMessage(request: SendSessionMessageRequest, options?: SendSessionMessageOptions): Promise<SentSessionMessage>;
661
- /** Delete this session and its persisted runtime state. */
662
- delete(): Promise<void>;
663
- /**
664
- * Fork this session into a new queued session. The fork shares the
665
- * parent workspace and copies conversation history up to `messageId`
666
- * when supplied.
667
- */
668
- fork(opts?: SessionForkOptions): Promise<{
669
- session: SandboxSession;
670
- info: SessionInfo;
671
- }>;
672
- /**
673
- * Drive this session's harness in INTERACTIVE mode: spawn its native TUI,
674
- * stream the live framebuffer, and inject prompts as keystrokes. Distinct
675
- * from the headless `prompt()`/`events()` surface above. Lazy — does not hit
676
- * the network until a handle method is called.
677
- */
678
- interactive(options?: InteractiveSessionHandleOptions): InteractiveSessionHandle;
679
- /**
680
- * Resolve a pending permission interaction the agent raised mid-turn,
681
- * forwarding `allow`/`deny` to the blocked agent through the unified
682
- * interaction channel. Throws if no matching permission is outstanding.
683
- */
684
- respondToPermission(permissionID: string, options: RespondToPermissionOptions): Promise<SandboxInteractionResult>;
685
- /** Return every interaction that still awaits a response on this session. */
686
- interactions(options?: {
687
- signal?: AbortSignal;
688
- }): Promise<InteractionRequest[]>;
689
- /** Respond to one exact interaction with a retry-safe command. */
690
- respondToInteraction(command: InteractionResponseCommand, options?: {
691
- signal?: AbortSignal;
692
- }): Promise<SandboxInteractionCommandResult>;
693
- /**
694
- * Interrupt an execution without deleting the session. Pass `executionId`
695
- * to make the cancellation exact: a newer run on the same session is never
696
- * touched. Without it, the current execution is selected. Returns
697
- * `{ cancelled: false }` when the selected execution is not running.
698
- */
699
- interrupt(options?: SessionInterruptOptions): Promise<InterruptResult>;
700
- /**
701
- * Cancel one exact run through the durable operation contract. Reusing the
702
- * same request after a lost response returns the sidecar's replayed
703
- * acknowledgement instead of issuing a second cancellation.
704
- */
705
- cancelRun(request: AgentRunCancellationRequest, options?: {
706
- signal?: AbortSignal;
707
- }): Promise<AgentRunCancellationAcknowledgement>;
708
- /** Answer one exact question without selecting another outstanding ask. */
709
- answer(interactionId: string, answers: InteractionData, options?: {
710
- signal?: AbortSignal;
711
- }): Promise<SandboxInteractionResult>;
712
- /** Return the newest plan awaiting a decision for this session. */
713
- plan(): Promise<DurablePlan | null>;
714
- /** Approve a durable plan; caller mode returns admission for fresh preparation. */
715
- approvePlan(planId?: string, options?: DurablePlanDecisionOptions): Promise<DurablePlanDecisionResult>;
716
- /** Reject a durable plan with feedback; caller mode prepares the revision turn. */
717
- rejectPlan(feedback: string, planId?: string, options?: DurablePlanDecisionOptions): Promise<DurablePlanDecisionResult>;
718
- private requireCurrentPlan;
719
- }
720
- //#endregion
721
- //#region src/task-session.d.ts
722
- /** @internal Operations implemented by `SandboxInstance`. */
723
- interface SandboxTaskSessionHost extends SandboxSessionHost {
724
- _taskSessionChanges(id: string): Promise<TaskSessionChanges>;
725
- _taskSessionCommit(id: string, options?: CommitTaskSessionOptions): Promise<TaskSessionCommitResult>;
726
- }
727
- /** A background task session with isolated changeset operations. */
728
- declare class SandboxTaskSession extends SandboxSession {
729
- private readonly taskBox;
730
- /** @internal Apps should call `box.taskSession(id)`. */
731
- constructor(taskBox: SandboxTaskSessionHost, id: string);
732
- /** Read the task's isolated file changes. */
733
- changes(): Promise<TaskSessionChanges>;
734
- /** Apply all or a selected subset of the task's isolated file changes. */
735
- commit(options?: CommitTaskSessionOptions): Promise<TaskSessionCommitResult>;
736
- }
737
- //#endregion
738
- //#region src/trace-exporter.d.ts
739
- type JsonObject = {
740
- [key: string]: JsonValue;
741
- };
742
- type TraceExportFormat = "tangle" | "otel-json";
743
- type TraceExportBundle = SandboxTraceBundle | SandboxFleetTraceBundle;
744
- interface TraceExportSink {
745
- url: string;
746
- headers?: Record<string, string>;
747
- format?: TraceExportFormat;
748
- serviceName?: string;
749
- timeoutMs?: number;
750
- fetch?: typeof fetch;
751
- }
752
- interface TraceExportResult {
753
- status: number;
754
- ok: boolean;
755
- body: string;
756
- }
757
- declare function buildTraceExportPayload(bundle: TraceExportBundle, format?: TraceExportFormat, serviceName?: string): TraceExportBundle | JsonObject;
758
- declare function exportTraceBundle(bundle: TraceExportBundle, sink: TraceExportSink): Promise<TraceExportResult>;
759
- declare function toOtelJson(bundle: TraceExportBundle, serviceName?: string): JsonObject;
760
- declare function otelTraceIdForTangleTrace(traceId: string): string;
761
477
  //#endregion
762
478
  //#region src/workspace-images.d.ts
763
- interface WorkspaceImagePublishInput {
764
- /** Workspace-relative build context. */
765
- contextPath?: string;
766
- /** Dockerfile path relative to the build context. */
767
- dockerfilePath?: string;
768
- /** Registry host and repository path, without a scheme, tag, or digest. */
769
- repository: string;
770
- /** Registry credential used only by the trusted image publisher. */
771
- auth: {
772
- username: string;
773
- password: string;
774
- };
775
- platform?: "linux/amd64" | "linux/arm64";
776
- }
777
- type WorkspaceImagePublishResult = WorkspaceImagePublishResult$1;
778
479
  interface WorkspaceImageHttpClient {
779
480
  fetch(path: string, options?: RequestInit, fetchOptions?: {
780
481
  timeoutMs?: number;
@@ -797,117 +498,8 @@ declare class WorkspaceImages {
797
498
  publish(input: WorkspaceImagePublishInput, options?: WorkspaceImagePublishRequestOptions): Promise<WorkspaceImagePublishResult>;
798
499
  }
799
500
  //#endregion
800
- //#region src/sandbox.d.ts
801
- /**
802
- * Result of registering a sidecar session mapping. `reprovisionRequired` is
803
- * true when the server reports the mapped sidecar is stale (HTTP 410) and the
804
- * caller must reprovision the sandbox before retrying.
805
- */
806
- interface SessionMappingResult {
807
- success: boolean;
808
- sessionId: string;
809
- sidecarSessionId?: string;
810
- reprovisionRequired: boolean;
811
- code?: string;
812
- }
813
- /**
814
- * Git capability for repository operations.
815
- */
816
- interface GitCapability {
817
- /** Get repository status */
818
- status(): Promise<GitStatus>;
819
- /** Get commit log */
820
- log(limit?: number): Promise<GitCommit[]>;
821
- /** Get diff (optionally against a ref) */
822
- diff(ref?: string): Promise<GitDiff>;
823
- /** Stage files */
824
- add(paths: string[]): Promise<void>;
825
- /** Create a commit */
826
- commit(message: string, options?: {
827
- amend?: boolean;
828
- }): Promise<GitCommit>;
829
- /** Push to remote */
830
- push(options?: {
831
- force?: boolean;
832
- }): Promise<void>;
833
- /** Pull from remote */
834
- pull(options?: {
835
- rebase?: boolean;
836
- }): Promise<void>;
837
- /** List branches */
838
- branches(): Promise<GitBranch[]>;
839
- /** Checkout a branch or ref */
840
- checkout(ref: string, options?: {
841
- create?: boolean;
842
- }): Promise<void>;
843
- }
844
- /**
845
- * Tools capability for managing language runtimes via mise.
846
- */
847
- interface ToolsCapability {
848
- /** Install a tool version */
849
- install(tool: string, version: string): Promise<void>;
850
- /** Activate a tool version for the session */
851
- use(tool: string, version: string): Promise<void>;
852
- /** List installed tools */
853
- list(): Promise<InstalledTool[]>;
854
- /** Run a command with a specific tool */
855
- run(tool: string, args: string[]): Promise<ExecResult>;
856
- }
857
- /**
858
- * One fork of a running sandbox, reported with its fan-out accounting.
859
- *
860
- * `children` holds the sandboxes that exist. A partial fan-out is never
861
- * reported as a whole one: `complete` is false whenever `materializedCount` is
862
- * below `requestedCount`, and the caller decides what to do about the
863
- * shortfall.
864
- */
865
- interface ForkAcknowledgement extends ForkCounts {
866
- children: SandboxInstance[];
867
- /** Present only for a keyed fork against an API that reports it. */
868
- idempotency?: ForkIdempotency;
869
- }
870
- /**
871
- * A sandbox instance with methods for interaction.
872
- */
873
- declare class SandboxInstance {
874
- #private;
875
- private readonly client;
876
- private info;
877
- private refreshInFlight?;
878
- private readonly defaultRuntimeBackend?;
879
- private readonly runtime;
880
- private readonly workspaceImages;
881
- private readonly interactiveOperations;
882
- private readonly interactiveTerminalOperations;
883
- /** @internal Test seam for terminal attach unit tests. */
884
- private _terminalStreamConnect;
885
- /**
886
- * A profile the runtime has cached (create-time priming), letting turns
887
- * send `backend.profileSha256` instead of re-shipping the profile's static
888
- * corpus. Set only when priming succeeded; when unset every turn sends the
889
- * transport profile. `snapshot` is the canonicalized
890
- * content at prime time — a turn substitutes the reference only when the
891
- * outgoing profile has identical canonical content, so a caller that mutates the
892
- * profile in place (or passes an equivalent object) is compared by CONTENT,
893
- * never by object identity, and a changed profile is sent inline.
894
- */
895
- private deferredProfileReference?;
896
- private readonly profileFiles;
897
- /**
898
- * The profile provenance receipt carried from create-time. Set when the
899
- * sandbox was created with a profile (inline or catalog); carried forward
900
- * to every snapshot so the snapshot answers "what configuration produced
901
- * this state?" without requiring a live profile read.
902
- */
903
- private profileProvenance?;
904
- /**
905
- * Direct regional status reads for THIS sandbox. Inert until the API
906
- * relays a grant, and it retreats to the API path on any failure — see
907
- * direct-read-route.ts.
908
- */
909
- private readonly directRead;
910
- constructor(client: HttpClient, info: SandboxInfo, defaultRuntimeBackend?: BackendConfig);
501
+ //#region src/sandbox-info.d.ts
502
+ declare abstract class SandboxInfoCapabilities {
911
503
  /** Unique sandbox identifier */
912
504
  get id(): string;
913
505
  /** Human-readable name */
@@ -930,6 +522,10 @@ declare class SandboxInstance {
930
522
  get startedAt(): Date | undefined;
931
523
  /** Last activity timestamp */
932
524
  get lastActivityAt(): Date | undefined;
525
+ /** Stop phase under `stopped`; see {@link T.SandboxInfo.lifecycleState}. */
526
+ get lifecycleState(): SandboxInfo["lifecycleState"];
527
+ /** When the sandbox entered its current stop. */
528
+ get suspendedAt(): SandboxInfo["suspendedAt"];
933
529
  /** When the sandbox will expire */
934
530
  get expiresAt(): Date | undefined;
935
531
  /** Error message if status is 'failed' */
@@ -1004,288 +600,305 @@ declare class SandboxInstance {
1004
600
  includeSecrets?: boolean;
1005
601
  }): SandboxInfo;
1006
602
  /**
1007
- * Create an advanced direct-runtime view of this sandbox.
1008
- *
1009
- * Runtime methods on the returned instance talk to the sandbox runtime
1010
- * directly using `connection.runtimeUrl` and `connection.authToken`.
1011
- * Lifecycle methods still go through the parent SDK client.
603
+ * Refresh sandbox information from the server.
1012
604
  */
1013
- direct(): SandboxInstance;
605
+ refresh(signal?: AbortSignal): Promise<void>;
606
+ protected refreshFor(reason: RefreshReason, signal?: AbortSignal): Promise<void>;
607
+ protected refreshInfo(reason: RefreshReason): Promise<void>;
608
+ protected readStatus(reason: RefreshReason): Promise<void>;
1014
609
  /**
1015
- * Get an MCP endpoint for this sandbox. Returns a paste-able config
1016
- * for any MCP-capable host (Claude Desktop, Cursor, claude-code,
1017
- * codex, opencode, …) plus a freshly-minted, capability-scoped JWT.
610
+ * What the direct regional read route has done for this sandbox: attempts,
611
+ * reads it served, reads that fell back to the API, and the last reason.
612
+ * Read by the lifecycle probe; safe for a caller to read too.
613
+ */
614
+ directReadStats(): DirectReadStats;
615
+ /**
616
+ * Arm the direct regional read from an API payload this instance did not
617
+ * fetch itself. @internal — called by `createSandboxInstanceFromResponse`.
618
+ */
619
+ adoptDirectRead(payload: Record<string, unknown>): void;
620
+ /**
621
+ * Read a lifecycle response body once.
1018
622
  *
1019
- * The token is short-lived and limited to the requested capabilities
1020
- * — it cannot be used against admin endpoints (`/exec`, `/files`,
1021
- * etc.) on the sandbox. Call `getMcpEndpoint()` again to rotate.
1022
- *
1023
- * Requires the sandbox to have been created with `capabilities`
1024
- * including the requested capability (default: `computer_use`).
1025
- *
1026
- * @example
1027
- * ```typescript
1028
- * const ep = await box.getMcpEndpoint();
1029
- * // Save ep.config to your IDE's mcp.json — that's it.
1030
- * fs.writeFileSync("mcp.json", JSON.stringify(ep.config, null, 2));
1031
- * ```
1032
- */
1033
- getMcpEndpoint(options?: {
1034
- capabilities?: ReadonlyArray<"computer_use">; /** Override server entry name (default: "tangle-sandbox"). */
1035
- serverName?: string; /** Token TTL in minutes (server clamps to its policy). */
1036
- ttlMinutes?: number;
1037
- }): Promise<SandboxMcpEndpoint>;
1038
- /**
1039
- * Refresh sandbox information from the server.
623
+ * Current APIs return the complete sandbox state. Older APIs return an empty
624
+ * body, so callers refresh when this method cannot recover a state payload.
1040
625
  */
1041
- refresh(signal?: AbortSignal): Promise<void>;
1042
- private refreshFor;
1043
- private refreshInfo;
1044
- private readStatus;
626
+ protected readLifecycleResponse(response: Response): Promise<Record<string, unknown> | null>;
627
+ protected applyLifecycleResponse(data: Record<string, unknown> | null): boolean;
628
+ protected hasFreshStatus(): boolean;
1045
629
  /**
1046
- * What the direct regional read route has done for this sandbox: attempts,
1047
- * reads it served, reads that fell back to the API, and the last reason.
1048
- * Read by the lifecycle probe; safe for a caller to read too.
630
+ * The check before a runtime call. A handle that has seen the sandbox
631
+ * running and ready dispatches at once: the authenticated runtime route
632
+ * checks current sandbox state itself, so a status GET before every call was
633
+ * a whole round trip through the Worker that only moved the same refusal
634
+ * earlier. A stale cache surfaces as the call's own answer, which the
635
+ * direct client and the prompt stream turn into a typed `StateError`. A
636
+ * handle that has not seen the status, or saw one that is not runnable,
637
+ * reads it first.
1049
638
  */
1050
- directReadStats(): DirectReadStats;
639
+ protected ensureRunning(signal?: AbortSignal): Promise<void>;
640
+ /** Why the status must be read before a runtime call, or undefined to trust the cache. */
641
+ protected statusReadReason(): RefreshReason | undefined;
642
+ protected assertRunnable(): void;
643
+ protected assertFilesystemIncarnationReady(): void;
1051
644
  /**
1052
- * Arm the direct regional read from an API payload this instance did not
1053
- * fetch itself. @internal — called by `createSandboxInstanceFromResponse`.
645
+ * One authenticated runtime HTTP call for this sandbox, relative endpoint
646
+ * (`/agents/...`), scoped to the current filesystem incarnation. This is
647
+ * the transport `/agents/profiles` rides and the box surface mount
648
+ * delivery uses for profile-bundle cache claim/publish.
1054
649
  */
1055
- adoptDirectRead(payload: Record<string, unknown>): void;
650
+ runtimeFetch(path: string, options?: RequestInit, fetchOptions?: {
651
+ timeoutMs?: number;
652
+ }): Promise<Response>;
1056
653
  /**
1057
- * Fetch fresh TEE attestation evidence for this sandbox.
654
+ * Parse a sandbox API payload into `SandboxInfo`.
1058
655
  *
1059
- * When `attestationNonce` is supplied, the runtime must return evidence bound
1060
- * to that challenge or fail closed if the selected TEE backend cannot support
1061
- * nonce-bound report data. *
1062
- * Throws `CapabilityError` (`TEE_UNSUPPORTED`) when the deployment does not
1063
- * serve the TEE intercept — these paths are answered by a Tangle
1064
- * confidential operator ahead of the sandbox API, which registers no route
1065
- * for them. That refusal is recognised from the API's own unmatched-route
1066
- * answer, so an intermediary that rewrites 404 bodies leaves the ordinary
1067
- * `NotFoundError` in its place rather than the named refusal.
656
+ * `carryCreateFacts` supplies the create-time facts a refresh must keep:
657
+ * the GPU lease, the startup diagnostics, and the create receipt each arrive
658
+ * once on the create response and are absent from every later payload. They
659
+ * describe ONE environment's creation, so they travel only when the payload
660
+ * describes that same environment. A payload for a different sandbox — a
661
+ * branch child parsed through its parent — passes no carry, or the child
662
+ * would report its parent's create verdict.
1068
663
  */
1069
- getTeeAttestation(options?: TeeAttestationOptions): Promise<TeeAttestationResponse>;
664
+ protected parseInfo(data: Record<string, unknown>, carryCreateFacts?: Pick<SandboxInfo, "gpuLease" | "startupDiagnostics" | "createReceipt">): SandboxInfo;
665
+ }
666
+ /**
667
+ * Why a status read was sent: the `sdk.refresh` span's `desc` and the value of
668
+ * the `x-tangle-refresh-reason` header, so a status GET that costs a round
669
+ * trip is attributable instead of anonymous.
670
+ *
671
+ * - `caller`: the caller asked (`refresh()`).
672
+ * - `poll`, `lifecycle`: a wait loop, or a lifecycle verb that needs the state.
673
+ * - `unobserved`: this handle has never seen the sandbox's status.
674
+ * - `not-running`: the cached status is not a runnable one, so it may have moved.
675
+ * - `bearer-refused`, `runtime-refused`: the runtime refused the call, which is
676
+ * the only evidence that a cached `running` went stale.
677
+ */
678
+ type RefreshReason = "caller" | "poll" | "lifecycle" | "unobserved" | "not-running" | "bearer-refused" | "runtime-refused";
679
+ //#endregion
680
+ //#region src/sandbox-workspace-git.d.ts
681
+ /**
682
+ * Git capability for repository operations.
683
+ */
684
+ interface GitCapability {
685
+ /** Get repository status */
686
+ status(): Promise<GitStatus>;
687
+ /** Get commit log */
688
+ log(limit?: number): Promise<GitCommit[]>;
689
+ /** Get diff (optionally against a ref) */
690
+ diff(ref?: string): Promise<GitDiff>;
691
+ /** Stage files */
692
+ add(paths: string[]): Promise<void>;
693
+ /** Create a commit */
694
+ commit(message: string, options?: {
695
+ amend?: boolean;
696
+ }): Promise<GitCommit>;
697
+ /** Push to remote */
698
+ push(options?: {
699
+ force?: boolean;
700
+ }): Promise<void>;
701
+ /** Pull from remote */
702
+ pull(options?: {
703
+ rebase?: boolean;
704
+ }): Promise<void>;
705
+ /** List branches */
706
+ branches(): Promise<GitBranch[]>;
707
+ /** Checkout a branch or ref */
708
+ checkout(ref: string, options?: {
709
+ create?: boolean;
710
+ }): Promise<void>;
711
+ }
712
+ declare abstract class SandboxGitCapabilities extends SandboxInfoCapabilities {
1070
713
  /**
1071
- * Fetch the TEE-bound public key used for sealed-secret encryption.
714
+ * Git capability object for repository operations.
1072
715
  *
1073
- * The returned key includes an attestation report. Verify that report before
1074
- * encrypting secrets to the key. *
1075
- * Throws `CapabilityError` (`TEE_UNSUPPORTED`) when the deployment does not
1076
- * serve the TEE intercept — these paths are answered by a Tangle
1077
- * confidential operator ahead of the sandbox API, which registers no route
1078
- * for them. That refusal is recognised from the API's own unmatched-route
1079
- * answer, so an intermediary that rewrites 404 bodies leaves the ordinary
1080
- * `NotFoundError` in its place rather than the named refusal.
1081
- */
1082
- getTeePublicKey(): Promise<TeePublicKeyResponse>;
1083
- /**
1084
- * Bootstrap a real-time collaboration session for a file.
1085
- * Returns the WebSocket URL and auth token needed to connect a
1086
- * Hocuspocus/Yjs provider for live multi-user editing.
716
+ * All git operations are executed in the sandbox workspace.
1087
717
  *
1088
- * @example
718
+ * @example Check status and commit
1089
719
  * ```typescript
1090
- * const collab = await box.collaborate("src/index.ts")
1091
- * // Use collab.transport.websocketUrl + collab.transport.token
1092
- * // with @hocuspocus/provider to connect
720
+ * const status = await box.git.status();
721
+ * if (status.isDirty) {
722
+ * await box.git.add(["."]);
723
+ * await box.git.commit("Update files");
724
+ * await box.git.push();
725
+ * }
1093
726
  * ```
1094
727
  */
1095
- collaborate(path: string, options?: {
1096
- access?: "read" | "write";
1097
- }): Promise<{
1098
- documentId: string;
1099
- transport: {
1100
- websocketUrl: string;
1101
- token: string;
1102
- expiresAt: number;
1103
- };
1104
- permissions: {
1105
- access: "read" | "write";
1106
- canSnapshot: boolean;
1107
- };
1108
- }>;
1109
- /**
1110
- * Refresh a collaboration token for an existing document session.
1111
- */
1112
- /**
1113
- * Refresh a collaboration token. Access level is preserved from the original
1114
- * token — cannot be escalated (read stays read, write stays write).
1115
- */
1116
- refreshCollaborationToken(documentId: string, currentToken: string): Promise<{
1117
- token: string;
1118
- expiresAt: number;
1119
- access: "read" | "write";
1120
- }>;
1121
- /**
1122
- * Get SSH credentials for connecting to the sandbox.
1123
- * Throws if SSH is not enabled or sandbox is not running.
1124
- */
1125
- ssh(): Promise<SSHCredentials>;
1126
- sshCommand(): Promise<SSHCommandDescriptor>;
1127
- /**
1128
- * Execute a command in the sandbox through a non-login POSIX shell.
1129
- * The command inherits the sandbox runtime environment.
1130
- */
1131
- exec(command: string, options?: ExecOptions): Promise<ExecResult>;
728
+ get git(): GitCapability;
729
+ private gitStatus;
730
+ private gitLog;
731
+ private gitDiff;
732
+ private gitAdd;
733
+ private gitCommit;
734
+ private gitPush;
735
+ private gitPull;
736
+ private gitBranches;
737
+ private gitCheckout;
738
+ }
739
+ //#endregion
740
+ //#region src/sandbox-workspace-backend.d.ts
741
+ declare abstract class SandboxBackendCapabilities extends SandboxGitCapabilities {
1132
742
  /**
1133
- * Run code in a persistent language kernel.
1134
- *
1135
- * Each `(sessionId, language)` pair gets its own long-lived kernel that
1136
- * keeps variable state across calls — like Jupyter cells. Without a
1137
- * `sessionId`, calls share a process-wide kernel per language.
1138
- *
1139
- * Returns typed results: stdout/stderr text plus a `results` array of
1140
- * structured outputs (matplotlib images as base64 PNG, pandas DataFrames,
1141
- * explicit `display(value)` calls as JSON/HTML, errors with traceback).
743
+ * Backend manager for runtime agent configuration.
1142
744
  *
1143
- * @example Persistent Python session
1144
- * ```ts
1145
- * await box.runCode("python", "import pandas as pd; df = pd.DataFrame({'x': range(5)})", { sessionId: "s1" });
1146
- * const r = await box.runCode("python", "df.describe()", { sessionId: "s1" });
1147
- * // r.results[0] is a `dataframe` part with columns + rows from the describe()
745
+ * @example Check backend status
746
+ * ```typescript
747
+ * const status = await box.backend.status();
748
+ * console.log(`Backend: ${status.type}, Status: ${status.status}`);
1148
749
  * ```
1149
750
  *
1150
- * @example Matplotlib chart
1151
- * ```ts
1152
- * const r = await box.runCode("python",
1153
- * "import matplotlib.pyplot as plt; plt.plot([1,2,3,4]); plt.show()",
1154
- * { sessionId: "s1" });
1155
- * const png = r.results.find(p => p.type === "image");
1156
- * // png.data is a base64 PNG ready to render or hand back to an LLM
751
+ * @example Point the backend at a different model
752
+ * ```typescript
753
+ * await box.backend.updateConfig({ model: "openai/gpt-5-mini" });
1157
754
  * ```
1158
- */
1159
- runCode(language: CodeLanguage, source: string, options?: CodeExecutionOptions): Promise<CodeExecutionResult>;
1160
- /**
1161
- * Read a file from the sandbox.
1162
- *
1163
- * @param path - Path to the file. Relative paths resolve from the workspace root.
1164
- * Absolute paths (e.g., `/tmp/output.json`) access the container filesystem directly.
1165
- * @returns File content as string
1166
755
  *
1167
- * @example
756
+ * @example Read provider-native Cursor metadata
1168
757
  * ```typescript
1169
- * const content = await box.read("src/index.ts");
1170
- * const report = await box.read("/output/report.json");
758
+ * const models = await box.backend.models();
759
+ * const agents = await box.backend.agents({ limit: 20 });
760
+ * const runs = await box.backend.runs(agents.items[0].agentId);
1171
761
  * ```
1172
762
  */
1173
- read(path: string, options?: {
1174
- sessionId?: string;
1175
- }): Promise<string>;
763
+ get backend(): BackendManager;
764
+ private backendStatus;
765
+ private backendGetMcpStatus;
766
+ private backendUpdateConfig;
767
+ private backendControlData;
768
+ private backendControlAction;
769
+ private backendListSearch;
770
+ private backendAccount;
771
+ private backendModels;
772
+ private backendRepositories;
773
+ private backendAgents;
774
+ private backendAgent;
775
+ private backendArchiveAgent;
776
+ private backendUnarchiveAgent;
777
+ private backendDeleteAgent;
778
+ private backendRuns;
779
+ private backendRun;
780
+ private backendAgentMessages;
781
+ private backendArtifacts;
782
+ private backendDownloadArtifact;
783
+ private backendRestart;
784
+ }
785
+ //#endregion
786
+ //#region src/sandbox-workspace-process.d.ts
787
+ declare abstract class SandboxProcessCapabilities extends SandboxBackendCapabilities {
1176
788
  /**
1177
- * Write content to a file in the sandbox.
789
+ * Process manager for spawning and controlling processes.
1178
790
  *
1179
- * @param path - Path to the file. Relative paths resolve from the workspace root.
1180
- * Absolute paths (e.g., `/tmp/cases.json`) write to the container filesystem directly.
1181
- * @param content - Content to write
791
+ * Provides non-blocking process execution with real-time log streaming,
792
+ * ideal for long-running tasks like ML training or dev servers.
1182
793
  *
1183
- * @example
794
+ * @example Non-blocking process
1184
795
  * ```typescript
1185
- * await box.write("src/fix.ts", "export const fix = () => {}");
1186
- * await box.write("/tmp/config.json", JSON.stringify(config));
796
+ * const proc = await box.process.spawn("python train.py", {
797
+ * cwd: "/workspace",
798
+ * env: { "CUDA_VISIBLE_DEVICES": "0" }
799
+ * });
800
+ *
801
+ * // Stream logs
802
+ * for await (const entry of proc.logs()) {
803
+ * console.log(`[${entry.type}] ${entry.data}`);
804
+ * }
805
+ *
806
+ * // Check status
807
+ * const status = await proc.status();
808
+ * console.log(`Running: ${status.running}`);
809
+ *
810
+ * // Kill if needed
811
+ * await proc.kill();
1187
812
  * ```
813
+ *
1188
814
  */
1189
- write(path: string, content: string, options?: WriteFileOptions): Promise<FileWriteResult>;
1190
- private writeFileRequest;
1191
- private assertWritePreconditions;
1192
- private writeBatchRequest;
1193
- private writeManySequential;
1194
- /**
1195
- * Write many files through the runtime batch endpoint. Older runtimes that
1196
- * return 404 use the sequential write path with the same retry policy.
1197
- */
1198
- writeMany(files: WriteManyFile[], options?: WriteManyOptions): Promise<void>;
1199
- /**
1200
- * Send a prompt to the agent running in the sandbox.
1201
- * Returns the complete response after the agent finishes.
1202
- */
1203
- prompt(message: string | PromptInputPart[], options?: PromptOptions): Promise<PromptResult>;
1204
- private logStreamCheckpoint;
815
+ get process(): ProcessManager;
816
+ private processEnsureDevServer;
817
+ private processSpawn;
818
+ private processSpawnExact;
819
+ private processList;
820
+ private processGet;
821
+ private createProcessHandle;
822
+ private parseProcessLogStream;
823
+ }
824
+ //#endregion
825
+ //#region src/sandbox-workspace-network.d.ts
826
+ declare abstract class SandboxNetworkCapabilities extends SandboxProcessCapabilities {
1205
827
  /**
1206
- * Stream events from an agent prompt.
1207
- * Use this for real-time updates during agent execution.
828
+ * Port exposure and runtime network state.
1208
829
  *
1209
- * Guarantees terminal completion on every non-cancelled path. A clean run
1210
- * emits a `result` summary and ends with `done`. A failure is an in-band
1211
- * `error` followed by `done`, never a thrown generator. Caller cancellation
1212
- * ends the stream silently with no synthetic terminal.
830
+ * Outbound restrictions are on {@link SandboxInstance.egress}: `update()`
831
+ * here rejects every policy field rather than recording one nothing
832
+ * enforces.
1213
833
  *
1214
- * Automatically reconnects via the runtime event replay endpoint if the
1215
- * SSE stream drops before a terminal event (`done` or `error`) is
1216
- * received. Reconnection is transparent — replayed events that were
1217
- * already yielded (based on event ID tracking) are deduplicated.
1218
- */
1219
- /**
1220
- * Record that the runtime already holds `profile` under `sha256`, so
1221
- * subsequent turns whose profile has the same canonical content send
1222
- * `backend.profileSha256` instead of the inline corpus. Use this to hydrate
1223
- * a freshly-fetched instance (`get()`/`list()`) from caller-persisted state
1224
- * — the reference otherwise lives only on the instance that primed it.
1225
- * Captures a content snapshot, so mutating the object afterwards is
1226
- * detected and that turn falls back to sending the profile inline.
1227
- */
1228
- attachProfileReference(profile: object, sha256: string, name?: string): void;
1229
- /**
1230
- * Deliver inline file mounts separately, then upload the remaining profile
1231
- * to the runtime (`POST /agents/profiles`) and record
1232
- * the returned transport-profile hash via {@link attachProfileReference}, so subsequent turns
1233
- * reference it by `profileSha256` instead of re-sending the corpus.
1234
- * `create()` calls this automatically for its inline profile when
1235
- * `autoDeferProfile` is on; call it directly when the profile only exists
1236
- * per-turn, or when the instance was fetched rather than created. Persist
1237
- * the returned sha256 alongside a content hash of the profile to
1238
- * re-attach on later instances without re-priming. Throws on transport/HTTP
1239
- * failure — the caller decides whether that is fatal (it is not: turns fall
1240
- * back to sending the file-free profile inline).
834
+ * @example Expose ports dynamically
835
+ * ```typescript
836
+ * const url = await box.network.exposePort(8000);
837
+ * console.log(`Service available at: ${url}`);
838
+ * ```
839
+ *
840
+ * @example Restrict outbound traffic
841
+ * ```typescript
842
+ * await box.egress.update({ mode: "blocked" });
843
+ * ```
1241
844
  */
1242
- primeProfile(profile: object): Promise<string>;
845
+ get network(): NetworkManager;
846
+ private networkUpdate;
847
+ private networkExposePort;
848
+ private networkListUrls;
849
+ private networkGetConfig;
1243
850
  /**
1244
- * Build the run request's `backend` body. When the outgoing profile's CONTENT
1245
- * matches the one the runtime already holds (and we are not resending after a
1246
- * cache miss), swap the inline `profile` for its `profileSha256` so a large
1247
- * static corpus does not ride every turn. The match is by serialized content,
1248
- * not object identity, so a mutated-in-place profile — or an equivalent
1249
- * object passed as a per-turn override — is compared correctly: unchanged
1250
- * content references by hash, changed content sends inline.
851
+ * Validate CIDR notation (IPv4 and IPv6)
1251
852
  */
853
+ private isValidCidr;
854
+ }
855
+ //#endregion
856
+ //#region src/sandbox-workspace-gpu.d.ts
857
+ declare abstract class SandboxGpuCapabilities extends SandboxNetworkCapabilities {
1252
858
  /**
1253
- * How this handle's most recent profile file preparation was satisfied
1254
- * (host cache hit, partial, miss, legacy delivery, or a held receipt) and
1255
- * how long it took. Undefined until a profile with file mounts is prepared.
859
+ * On-demand GPU leases attached to this sandbox.
860
+ *
861
+ * The base sandbox stays cheap; `attach` starts a temporary external GPU
862
+ * worker with an explicit spend cap, and `detach` destroys it.
1256
863
  */
1257
- get lastProfileFileDelivery(): ProfileFileDeliveryReport | undefined;
1258
- /** @internal Shared create/turn delivery; caller policy decides how to expose failures. */
1259
- materializeProfileFiles(profile: AgentProfile, signal?: AbortSignal, existingFiles?: "replace" | "allow-identical"): Promise<AgentProfile>;
1260
- private buildRunBackendBody;
1261
- streamPrompt(message: string | PromptInputPart[], requestedOptions?: PromptOptions): AsyncGenerator<SandboxEvent>;
864
+ get gpu(): GpuLeaseManager;
865
+ private gpuProviders;
866
+ private gpuAttach;
867
+ private gpuList;
868
+ private gpuExec;
869
+ private gpuDetach;
870
+ }
871
+ //#endregion
872
+ //#region src/sandbox-workspace-preview.d.ts
873
+ declare abstract class SandboxPreviewCapabilities extends SandboxGpuCapabilities {
1262
874
  /**
1263
- * Inner prompt stream: opens the SSE connection and rejoins the execution's
1264
- * event log on silent drops. May throw (pre-stream HTTP error, timeout, or
1265
- * `StreamInterruptedError` when it cannot rejoin); the public
1266
- * `streamPrompt` wrapper converts those throws into in-band events so
1267
- * callers never see a thrown generator.
875
+ * Preview link management.
876
+ *
877
+ * Create publicly accessible HTTPS URLs for TCP ports inside the sandbox.
878
+ *
879
+ * @example
880
+ * ```typescript
881
+ * const link = await box.previewLinks.create(3000);
882
+ * console.log(link.url);
883
+ *
884
+ * const links = await box.previewLinks.list();
885
+ * await box.previewLinks.remove(link.previewId);
886
+ * ```
1268
887
  */
1269
- private streamPromptInner;
888
+ get previewLinks(): PreviewLinkManager;
889
+ private previewLinkCreate;
890
+ private previewLinkList;
891
+ private previewLinkGet;
892
+ private previewLinkWaitUntilReady;
893
+ private previewLinkRemove;
894
+ }
895
+ //#endregion
896
+ //#region src/sandbox-lifecycle-events.d.ts
897
+ declare abstract class SandboxLifecycleEventsCapabilities extends SandboxPreviewCapabilities {
1270
898
  /**
1271
899
  * Stream sandbox lifecycle and activity events.
1272
900
  */
1273
901
  events(options?: EventStreamOptions): AsyncGenerator<SandboxEvent>;
1274
- trace(options?: SandboxTraceOptions): Promise<SandboxTraceBundle>;
1275
- intelligence(): Promise<NonNullable<SandboxTraceBundle["intelligence"]>>;
1276
- createIntelligenceReport(options?: {
1277
- mode?: "deterministic" | "agentic";
1278
- acknowledgeCost?: boolean;
1279
- budget?: IntelligenceReportBudget;
1280
- metadata?: Record<string, unknown>; /** Bound the analysis to a time window. */
1281
- window?: IntelligenceReportWindow; /** Compare this sandbox against a same-type baseline sandbox. */
1282
- compareTo?: IntelligenceReportCompareTo;
1283
- }): Promise<IntelligenceReport>;
1284
- createAgenticIntelligenceReport(options: {
1285
- maxUsd: number;
1286
- metadata?: Record<string, unknown>;
1287
- }): Promise<IntelligenceReport>;
1288
- exportTrace(sink: TraceExportSink): Promise<TraceExportResult>;
1289
902
  /**
1290
903
  * Stream real-time provisioning progress events.
1291
904
  *
@@ -1310,73 +923,149 @@ declare class SandboxInstance {
1310
923
  signal?: AbortSignal;
1311
924
  }): AsyncGenerator<ProvisionEvent, ProvisionResult | undefined>;
1312
925
  /**
1313
- * Search for text patterns in files using ripgrep.
926
+ * Delegates to the shared `parseSSEStream` in `lib/sse-parser.ts`
927
+ * — one canonical SSE implementation for the whole SDK. The
928
+ * shared parser throws `AbortError` on cancellation, while agent and task
929
+ * streams inspect the signal after iteration to decide whether to reconnect.
930
+ * This adapter converts cancellation to that local control flow and lets one
931
+ * malformed output frame be skipped without losing later valid output.
932
+ */
933
+ protected parseSSEStream(response: Response, signal?: AbortSignal): AsyncGenerator<SandboxEvent>;
934
+ /**
935
+ * Wait for the sandbox to reach a specific status.
1314
936
  *
1315
- * This is a first-class code search capability, not a shell wrapper.
1316
- * Ripgrep is pre-installed in all managed sandboxes.
937
+ * A sandbox is not considered `running` until its filesystem incarnation is
938
+ * complete and ready.
1317
939
  *
1318
- * @param pattern - Regular expression pattern to search for
1319
- * @param options - Search options
1320
- * @returns Async iterator of search matches
940
+ * When `onProgress` is provided and the sandbox is still provisioning,
941
+ * uses SSE events for real-time progress instead of polling. Falls back
942
+ * to polling if the SSE connection fails or is unavailable.
1321
943
  *
1322
- * @example Search for task-marker comments
944
+ * @example Basic wait
1323
945
  * ```typescript
1324
- * for await (const match of box.search("TASK:", { glob: "**\/*.ts" })) {
1325
- * console.log(`${match.path}:${match.line}: ${match.text}`);
1326
- * }
946
+ * await box.waitFor("running");
1327
947
  * ```
1328
948
  *
1329
- * @example Collect all matches
949
+ * @example Wait with progress tracking
1330
950
  * ```typescript
1331
- * const matches = [];
1332
- * for await (const match of box.search("function.*async")) {
1333
- * matches.push(match);
1334
- * }
951
+ * await box.waitFor("running", {
952
+ * onProgress: (event) => {
953
+ * console.log(`[${event.step}] ${event.status} — ${event.message}`);
954
+ * if (event.percent !== undefined) {
955
+ * updateProgressBar(event.percent);
956
+ * }
957
+ * },
958
+ * });
1335
959
  * ```
1336
960
  */
1337
- search(pattern: string, options?: SearchOptions): AsyncGenerator<SearchMatch>;
1338
- /** Basic health reported by the runtime inside this sandbox. */
1339
- runtimeHealth(): Promise<SandboxRuntimeHealth>;
961
+ waitFor(status: SandboxStatus | SandboxStatus[], options?: WaitForOptions): Promise<void>;
1340
962
  /**
1341
- * Merge application variables into the running sandbox before dispatch.
1342
- * New child processes and profile secret references use these values.
1343
- * Existing processes retain their environment.
1344
- *
1345
- * These values do not change the durable creation configuration.
1346
- * Refresh expiring credentials after each resume and before new work.
1347
- * Requires owner runtime access; runtime-reserved variables are rejected.
1348
- * Managed credentials such as TANGLE_API_KEY use their dedicated installation path.
1349
- * Older runtimes without app-variable registration fail this call.
1350
- * Credential values must stay outside profiles, receipts, and logs.
963
+ * SSE-based wait implementation. Subscribes to provisioning events and
964
+ * delivers progress callbacks while waiting for a target status.
1351
965
  */
1352
- setRuntimeEnv(env: Record<string, string>, options?: {
1353
- ttlMs?: number;
1354
- }): Promise<void>;
966
+ protected waitForWithSSE(statuses: SandboxStatus[], timeoutMs: number, onProgress: (event: ProvisionEvent) => void, signal?: AbortSignal): Promise<boolean>;
967
+ protected hasReachedWaitTarget(statuses: SandboxStatus[]): boolean;
1355
968
  /**
1356
- * Return the runtime's current listening-port snapshot.
1357
- *
1358
- * An empty array means the runtime scanned and found no listeners. A runtime
1359
- * whose port watcher is switched off throws (503 `PORT_WATCHER_DISABLED`)
1360
- * rather than reporting an empty snapshot it never collected.
969
+ * A running filesystem is not enough to serve a consumer. The API can
970
+ * expose `running` while the public edge is still pending, or after edge
971
+ * attachment failed. Keep that distinction in the SDK so every caller gets
972
+ * the same wait and error semantics.
1361
973
  */
1362
- ports(): Promise<SandboxPortBinding[]>;
974
+ protected consumerConnectionReady(): boolean;
975
+ protected sleep(ms: number): Promise<void>;
976
+ }
977
+ //#endregion
978
+ //#region src/sandbox-lifecycle.d.ts
979
+ declare abstract class SandboxLifecycleCapabilities extends SandboxLifecycleEventsCapabilities {
980
+ #private;
1363
981
  /**
1364
- * Interactive terminal operations for this runtime: the REST manager
1365
- * (create/input/list/get) plus `attach()`, which opens the live terminal
1366
- * WebSocket as a {@link TerminalStream}.
982
+ * Stop the sandbox (keeps state for resume).
983
+ *
984
+ * The stop response carries the orchestrator's per-phase stop breakdown
985
+ * (`stop_metering` / `container_kill` / `stop_complete` /
986
+ * `stop_unaccounted`); after this resolves, {@link startupDiagnostics}
987
+ * returns it (replacing the create breakdown).
1367
988
  */
1368
- get terminals(): SandboxTerminals;
989
+ stop(): Promise<void>;
1369
990
  /**
1370
- * Live whole-sandbox resource usage (memory + CPU) from the container cgroup.
1371
- *
1372
- * Returns `null` when cgroup stats are unavailable (non-Linux host). Memory is
1373
- * in MB; `memoryPeakMb` is the high-water mark since the sandbox started. CPU
1374
- * is a cumulative microsecond counter — sample twice and compute
1375
- * `cpu% = ΔcpuUsageUsec / (ΔsampledAtMs * 10)` for utilization.
1376
- *
1377
- * @example
1378
- * ```typescript
1379
- * const r = await box.resourceUsage();
991
+ * With `wait: false`, answers as soon as the stop is durably accepted and
992
+ * returns the {@link SandboxOperation}; `await op.wait()` resolves once the
993
+ * sandbox is stopped. A stop the API finished synchronously comes back as an
994
+ * operation that is already `succeeded`.
995
+ */
996
+ stop(options: StopOptions & {
997
+ wait: false;
998
+ }): Promise<SandboxOperation>;
999
+ stop(options?: StopOptions): Promise<void>;
1000
+ /** Read an operation a `wait: false` stop or snapshot of this sandbox returned. */
1001
+ getOperation(operationId: string): Promise<SandboxOperation>;
1002
+ /** Read credential recovery metadata without changing sandbox lifecycle. */
1003
+ getEnvRecovery(): Promise<SandboxEnvRecoveryView>;
1004
+ /** Replace a stopped sandbox's policy, or inspect a proposed change with dryRun. */
1005
+ setEnvRecovery(envRecovery: SandboxEnvRecovery, options?: {
1006
+ dryRun?: boolean;
1007
+ }): Promise<SandboxEnvRecoveryView>;
1008
+ /** Resume a stopped sandbox; cold recovery may require caller env values. */
1009
+ resume(options?: ResumeOptions): Promise<void>;
1010
+ /** Rebuild a stopped sandbox from its durable snapshot under the same ID. */
1011
+ rebuild(options?: ResumeOptions): Promise<void>;
1012
+ protected resumeRuntime(operation: "resume" | "rebuild", options: ResumeOptions): Promise<void>;
1013
+ /**
1014
+ * Delete the sandbox permanently. This is how a forked child is destroyed.
1015
+ *
1016
+ * `outcome` separates `destroyed` from `already_absent`, so a retry after an
1017
+ * uncertain failure reports what really happened instead of raising.
1018
+ *
1019
+ * The call answers once the runtime is killed and billed; the container,
1020
+ * volume and network are reclaimed behind it and `removal` says
1021
+ * `"pending"`. Pass `until: "removed"` to wait for that reclaim instead.
1022
+ *
1023
+ * The delete response carries the orchestrator's per-phase delete breakdown
1024
+ * (`runtime_kill` / `tombstone_persist` / `delete_complete` /
1025
+ * `delete_unaccounted`); after this resolves, {@link startupDiagnostics}
1026
+ * returns it for post-mortem reads on the now-gone sandbox.
1027
+ */
1028
+ delete(options?: SandboxDeleteOptions): Promise<SandboxDeleteAcknowledgement>;
1029
+ }
1030
+ //#endregion
1031
+ //#region src/sandbox-runtime.d.ts
1032
+ declare abstract class SandboxRuntimeOperations extends SandboxLifecycleCapabilities {
1033
+ /** Basic health reported by the runtime inside this sandbox. */
1034
+ runtimeHealth(): Promise<SandboxRuntimeHealth>;
1035
+ /**
1036
+ * Merge application variables into the running sandbox before dispatch.
1037
+ * New child processes and profile secret references use these values.
1038
+ * Existing processes retain their environment.
1039
+ *
1040
+ * These values do not change the durable creation configuration.
1041
+ * Refresh expiring credentials after each resume and before new work.
1042
+ * Requires owner runtime access; runtime-reserved variables are rejected.
1043
+ * Managed credentials such as TANGLE_API_KEY use their dedicated installation path.
1044
+ * Older runtimes without app-variable registration fail this call.
1045
+ * Credential values must stay outside profiles, receipts, and logs.
1046
+ */
1047
+ setRuntimeEnv(env: Record<string, string>, options?: {
1048
+ ttlMs?: number;
1049
+ }): Promise<void>;
1050
+ /**
1051
+ * Return the runtime's current listening-port snapshot.
1052
+ *
1053
+ * An empty array means the runtime scanned and found no listeners. A runtime
1054
+ * whose port watcher is switched off throws (503 `PORT_WATCHER_DISABLED`)
1055
+ * rather than reporting an empty snapshot it never collected.
1056
+ */
1057
+ ports(): Promise<SandboxPortBinding[]>;
1058
+ /**
1059
+ * Live whole-sandbox resource usage (memory + CPU) from the container cgroup.
1060
+ *
1061
+ * Returns `null` when cgroup stats are unavailable (non-Linux host). Memory is
1062
+ * in MB; `memoryPeakMb` is the high-water mark since the sandbox started. CPU
1063
+ * is a cumulative microsecond counter — sample twice and compute
1064
+ * `cpu% = ΔcpuUsageUsec / (ΔsampledAtMs * 10)` for utilization.
1065
+ *
1066
+ * @example
1067
+ * ```typescript
1068
+ * const r = await box.resourceUsage();
1380
1069
  * if (r) console.log(`peak ${r.memoryPeakMb} MB`);
1381
1070
  * ```
1382
1071
  */
@@ -1417,43 +1106,131 @@ declare class SandboxInstance {
1417
1106
  }): Promise<void>;
1418
1107
  capabilities(): Promise<SandboxRuntimeCapabilities | null>;
1419
1108
  /**
1420
- * Git capability object for repository operations.
1109
+ * Get information about the infrastructure driver for this sandbox.
1421
1110
  *
1422
- * All git operations are executed in the sandbox workspace.
1111
+ * @example
1112
+ * ```typescript
1113
+ * const info = await box.getDriverInfo();
1114
+ * console.log(`Driver: ${info.type}, CRIU: ${info.capabilities.criu}`);
1115
+ * ```
1116
+ */
1117
+ getDriverInfo(): Promise<DriverInfo>;
1118
+ }
1119
+ //#endregion
1120
+ //#region src/sandbox-exec.d.ts
1121
+ declare abstract class SandboxExecCapabilities extends SandboxRuntimeOperations {
1122
+ /**
1123
+ * Execute a command in the sandbox through a non-login POSIX shell.
1124
+ * The command inherits the sandbox runtime environment.
1125
+ */
1126
+ exec(command: string, options?: ExecOptions): Promise<ExecResult>;
1127
+ /**
1128
+ * Run code in a persistent language kernel.
1423
1129
  *
1424
- * @example Check status and commit
1130
+ * Each `(sessionId, language)` pair gets its own long-lived kernel that
1131
+ * keeps variable state across calls — like Jupyter cells. Without a
1132
+ * `sessionId`, calls share a process-wide kernel per language.
1133
+ *
1134
+ * Returns typed results: stdout/stderr text plus a `results` array of
1135
+ * structured outputs (matplotlib images as base64 PNG, pandas DataFrames,
1136
+ * explicit `display(value)` calls as JSON/HTML, errors with traceback).
1137
+ *
1138
+ * @example Persistent Python session
1139
+ * ```ts
1140
+ * await box.runCode("python", "import pandas as pd; df = pd.DataFrame({'x': range(5)})", { sessionId: "s1" });
1141
+ * const r = await box.runCode("python", "df.describe()", { sessionId: "s1" });
1142
+ * // r.results[0] is a `dataframe` part with columns + rows from the describe()
1143
+ * ```
1144
+ *
1145
+ * @example Matplotlib chart
1146
+ * ```ts
1147
+ * const r = await box.runCode("python",
1148
+ * "import matplotlib.pyplot as plt; plt.plot([1,2,3,4]); plt.show()",
1149
+ * { sessionId: "s1" });
1150
+ * const png = r.results.find(p => p.type === "image");
1151
+ * // png.data is a base64 PNG ready to render or hand back to an LLM
1152
+ * ```
1153
+ */
1154
+ runCode(language: CodeLanguage, source: string, options?: CodeExecutionOptions): Promise<CodeExecutionResult>;
1155
+ /**
1156
+ * Search for text patterns in files using ripgrep.
1157
+ *
1158
+ * This is a first-class code search capability, not a shell wrapper.
1159
+ * Ripgrep is pre-installed in all managed sandboxes.
1160
+ *
1161
+ * @param pattern - Regular expression pattern to search for
1162
+ * @param options - Search options
1163
+ * @returns Async iterator of search matches
1164
+ *
1165
+ * @example Search for task-marker comments
1425
1166
  * ```typescript
1426
- * const status = await box.git.status();
1427
- * if (status.isDirty) {
1428
- * await box.git.add(["."]);
1429
- * await box.git.commit("Update files");
1430
- * await box.git.push();
1167
+ * for await (const match of box.search("TASK:", { glob: "**\/*.ts" })) {
1168
+ * console.log(`${match.path}:${match.line}: ${match.text}`);
1169
+ * }
1170
+ * ```
1171
+ *
1172
+ * @example Collect all matches
1173
+ * ```typescript
1174
+ * const matches = [];
1175
+ * for await (const match of box.search("function.*async")) {
1176
+ * matches.push(match);
1431
1177
  * }
1432
1178
  * ```
1433
1179
  */
1434
- get git(): GitCapability;
1435
- private gitStatus;
1436
- private gitLog;
1437
- private gitDiff;
1438
- private gitAdd;
1439
- private gitCommit;
1440
- private gitPush;
1441
- private gitPull;
1442
- private gitBranches;
1443
- private gitCheckout;
1180
+ search(pattern: string, options?: SearchOptions): AsyncGenerator<SearchMatch>;
1181
+ /**
1182
+ * Upload a local directory to the sandbox via tar.
1183
+ * @param localPath - Local directory path to upload
1184
+ * @param remotePath - Destination path in the sandbox (default: /home/user)
1185
+ */
1186
+ uploadDirectory(localPath: string, remotePath?: string): Promise<void>;
1187
+ }
1188
+ //#endregion
1189
+ //#region src/sandbox-file-write.d.ts
1190
+ declare abstract class SandboxFileWriteCapabilities extends SandboxExecCapabilities {
1191
+ /**
1192
+ * Read a file from the sandbox.
1193
+ *
1194
+ * @param path - Path to the file. Relative paths resolve from the workspace root.
1195
+ * Absolute paths (e.g., `/tmp/output.json`) access the container filesystem directly.
1196
+ * @returns File content as string
1197
+ *
1198
+ * @example
1199
+ * ```typescript
1200
+ * const content = await box.read("src/index.ts");
1201
+ * const report = await box.read("/output/report.json");
1202
+ * ```
1203
+ */
1204
+ read(path: string, options?: {
1205
+ sessionId?: string;
1206
+ traceId?: string;
1207
+ }): Promise<string>;
1444
1208
  /**
1445
- * Tools capability object for managing language runtimes.
1209
+ * Write content to a file in the sandbox.
1446
1210
  *
1447
- * Uses mise (polyglot version manager) to install and manage tools.
1211
+ * @param path - Path to the file. Relative paths resolve from the workspace root.
1212
+ * Absolute paths (e.g., `/tmp/cases.json`) write to the container filesystem directly.
1213
+ * @param content - Content to write
1448
1214
  *
1449
- * @example Install and use Node.js
1215
+ * @example
1450
1216
  * ```typescript
1451
- * await box.tools.install("node", "22");
1452
- * await box.tools.use("node", "22");
1453
- * const list = await box.tools.list();
1217
+ * await box.write("src/fix.ts", "export const fix = () => {}");
1218
+ * await box.write("/tmp/config.json", JSON.stringify(config));
1454
1219
  * ```
1455
1220
  */
1456
- get tools(): ToolsCapability;
1221
+ write(path: string, content: string, options?: WriteFileOptions): Promise<FileWriteResult>;
1222
+ protected writeFileRequest(path: string, content: string, options?: WriteFileOptions): Promise<FileWriteResult>;
1223
+ protected assertWritePreconditions(result: FileWriteResult, requested: {
1224
+ expectedHash?: string;
1225
+ ifAbsent?: boolean;
1226
+ }): void;
1227
+ protected writeBatchRequest(files: WriteManyWireFile[], body: string): Promise<boolean>;
1228
+ protected writeManySequential(files: WriteManyFile[], paceMs: number, maxRetries: number): Promise<void>;
1229
+ /**
1230
+ * Write many files through the runtime batch endpoint. Older runtimes that
1231
+ * return 404 use the sequential write path with the same retry policy.
1232
+ */
1233
+ writeMany(files: WriteManyFile[], options?: WriteManyOptions): Promise<void>;
1457
1234
  /**
1458
1235
  * File system operations beyond basic read/write:
1459
1236
  * - Binary upload/download
@@ -1484,239 +1261,74 @@ declare class SandboxInstance {
1484
1261
  * ```
1485
1262
  */
1486
1263
  get fs(): FileSystem;
1487
- private fsReadBatch;
1488
- private fsTree;
1489
- private fsUsage;
1490
- private fsUpload;
1491
- /** See {@link FileSystem.uploadData}. Delegates to the shared, browser-safe
1492
- * chunked-upload flow in `lib/chunked-upload.ts`, wired to this sandbox's
1493
- * runtime endpoint (works over the gateway proxy or a direct connection —
1494
- * both are transparent through `runtimeFetch`). */
1495
- private fsUploadData;
1496
- private fsDownload;
1497
- private fsUploadDir;
1498
- private fsDownloadArchive;
1499
- private fsOpenArchive;
1500
- private fsDownloadDir;
1501
- private fsList;
1502
- private fsStat;
1503
- private fsDelete;
1504
- private fsRename;
1505
- private fsMkdir;
1506
- private fsExists;
1507
- /**
1508
- * Permissions manager for multi-user access control.
1509
- *
1510
- * @example List users
1511
- * ```typescript
1512
- * const users = await box.permissions.list();
1513
- * for (const user of users) {
1514
- * console.log(`${user.username}: ${user.role}`);
1515
- * }
1516
- * ```
1517
- *
1518
- * @example Add a developer
1519
- * ```typescript
1520
- * await box.permissions.add({
1521
- * userId: "user_abc",
1522
- * role: "developer",
1523
- * sshKeys: ["ssh-ed25519 AAAA..."],
1524
- * });
1525
- * ```
1526
- */
1527
- get permissions(): PermissionsManager;
1528
- private permissionsList;
1529
- private permissionsGet;
1530
- private permissionsAdd;
1531
- private permissionsUpdate;
1532
- private permissionsRemove;
1533
- private permissionsSetAccessPolicies;
1534
- private permissionsGetAccessPolicies;
1535
- private permissionsCheckAccess;
1264
+ }
1265
+ interface WriteManyWireFile {
1266
+ path: string;
1267
+ content: string;
1268
+ mode?: number;
1269
+ encoding?: "utf8" | "base64";
1270
+ expectedHash?: string;
1271
+ ifAbsent?: boolean;
1272
+ }
1273
+ //#endregion
1274
+ //#region src/sandbox-profile.d.ts
1275
+ declare abstract class SandboxProfileCapabilities extends SandboxFileWriteCapabilities {
1536
1276
  /**
1537
- * Backend manager for runtime agent configuration.
1538
- *
1539
- * @example Check backend status
1540
- * ```typescript
1541
- * const status = await box.backend.status();
1542
- * console.log(`Backend: ${status.type}, Status: ${status.status}`);
1543
- * ```
1277
+ * Stream events from an agent prompt.
1278
+ * Use this for real-time updates during agent execution.
1544
1279
  *
1545
- * @example Point the backend at a different model
1546
- * ```typescript
1547
- * await box.backend.updateConfig({ model: "openai/gpt-5-mini" });
1548
- * ```
1280
+ * Guarantees terminal completion on every non-cancelled path. A clean run
1281
+ * emits a `result` summary and ends with `done`. A failure is an in-band
1282
+ * `error` followed by `done`, never a thrown generator. Caller cancellation
1283
+ * ends the stream silently with no synthetic terminal.
1549
1284
  *
1550
- * @example Read provider-native Cursor metadata
1551
- * ```typescript
1552
- * const models = await box.backend.models();
1553
- * const agents = await box.backend.agents({ limit: 20 });
1554
- * const runs = await box.backend.runs(agents.items[0].agentId);
1555
- * ```
1285
+ * Automatically reconnects via the runtime event replay endpoint if the
1286
+ * SSE stream drops before a terminal event (`done` or `error`) is
1287
+ * received. Reconnection is transparent — replayed events that were
1288
+ * already yielded (based on event ID tracking) are deduplicated.
1556
1289
  */
1557
- get backend(): BackendManager;
1558
- private backendStatus;
1559
- private backendGetMcpStatus;
1560
- private backendUpdateConfig;
1561
- private backendControlData;
1562
- private backendControlAction;
1563
- private backendListSearch;
1564
- private backendAccount;
1565
- private backendModels;
1566
- private backendRepositories;
1567
- private backendAgents;
1568
- private backendAgent;
1569
- private backendArchiveAgent;
1570
- private backendUnarchiveAgent;
1571
- private backendDeleteAgent;
1572
- private backendRuns;
1573
- private backendRun;
1574
- private backendAgentMessages;
1575
- private backendArtifacts;
1576
- private backendDownloadArtifact;
1577
- private backendRestart;
1578
1290
  /**
1579
- * Process manager for spawning and controlling processes.
1580
- *
1581
- * Provides non-blocking process execution with real-time log streaming,
1582
- * ideal for long-running tasks like ML training or dev servers.
1583
- *
1584
- * @example Non-blocking process
1585
- * ```typescript
1586
- * const proc = await box.process.spawn("python train.py", {
1587
- * cwd: "/workspace",
1588
- * env: { "CUDA_VISIBLE_DEVICES": "0" }
1589
- * });
1590
- *
1591
- * // Stream logs
1592
- * for await (const entry of proc.logs()) {
1593
- * console.log(`[${entry.type}] ${entry.data}`);
1594
- * }
1595
- *
1596
- * // Check status
1597
- * const status = await proc.status();
1598
- * console.log(`Running: ${status.running}`);
1599
- *
1600
- * // Kill if needed
1601
- * await proc.kill();
1602
- * ```
1603
- *
1604
- */
1605
- get process(): ProcessManager;
1606
- private processEnsureDevServer;
1607
- private processSpawn;
1608
- private processSpawnExact;
1609
- private processList;
1610
- private processGet;
1611
- private createProcessHandle;
1612
- private parseProcessLogStream;
1613
- /**
1614
- * Port exposure and runtime network state.
1615
- *
1616
- * Outbound restrictions are on {@link SandboxInstance.egress}: `update()`
1617
- * here rejects every policy field rather than recording one nothing
1618
- * enforces.
1619
- *
1620
- * @example Expose ports dynamically
1621
- * ```typescript
1622
- * const url = await box.network.exposePort(8000);
1623
- * console.log(`Service available at: ${url}`);
1624
- * ```
1625
- *
1626
- * @example Restrict outbound traffic
1627
- * ```typescript
1628
- * await box.egress.update({ mode: "blocked" });
1629
- * ```
1630
- */
1631
- get network(): NetworkManager;
1632
- /**
1633
- * Egress policy manager for controlling outbound internet access.
1634
- *
1635
- * @example Read current egress policy
1636
- * ```typescript
1637
- * const { policy, source } = await box.egress.get();
1638
- * console.log(policy.mode, source);
1639
- * ```
1640
- *
1641
- * @example Update egress policy at runtime
1642
- * ```typescript
1643
- * // strict reaches these plus the sandbox's own model endpoint, nothing else.
1644
- * await box.egress.update({ mode: "strict", allowDomains: ["api.github.com"] });
1645
- * ```
1646
- */
1647
- get egress(): EgressManager;
1648
- /**
1649
- * On-demand GPU leases attached to this sandbox.
1650
- *
1651
- * The base sandbox stays cheap; `attach` starts a temporary external GPU
1652
- * worker with an explicit spend cap, and `detach` destroys it.
1653
- */
1654
- get gpu(): GpuLeaseManager;
1655
- private networkUpdate;
1656
- private networkExposePort;
1657
- private networkListUrls;
1658
- private networkGetConfig;
1659
- private egressGet;
1660
- private egressUpdate;
1661
- private egressDenials;
1662
- /**
1663
- * This sandbox's egress for one calendar month, from the billing meter. A
1664
- * malformed answer is a typed `ServerError`, never a defaulted zero: a
1665
- * caller budgeting on it must not read a broken reply as no usage.
1666
- */
1667
- private egressUsage;
1668
- /**
1669
- * What the sandbox reached, and whether that is decidable.
1670
- *
1671
- * Every malformed answer leaves as a typed `ServerError` rather than a
1672
- * defaulted record. That matters more here than on `denials()`: a caller uses
1673
- * this to establish a NEGATIVE claim, so inventing a `complete: true` record
1674
- * from a broken response would manufacture the very proof it came for.
1291
+ * Record that the runtime already holds `profile` under `sha256`, so
1292
+ * subsequent turns whose profile has the same canonical content send
1293
+ * `backend.profileSha256` instead of the inline corpus. Use this to hydrate
1294
+ * a freshly-fetched instance (`get()`/`list()`) from caller-persisted state
1295
+ * — the reference otherwise lives only on the instance that primed it.
1296
+ * Captures a content snapshot, so mutating the object afterwards is
1297
+ * detected and that turn falls back to sending the profile inline.
1675
1298
  */
1676
- private egressActivity;
1677
- private gpuProviders;
1678
- private gpuAttach;
1679
- private gpuList;
1680
- private gpuExec;
1681
- private gpuDetach;
1299
+ attachProfileReference(profile: object, sha256: string, name?: string): void;
1682
1300
  /**
1683
- * Validate CIDR notation (IPv4 and IPv6)
1301
+ * Deliver inline file mounts separately, then upload the remaining profile
1302
+ * to the runtime (`POST /agents/profiles`) and record
1303
+ * the returned transport-profile hash via {@link attachProfileReference}, so subsequent turns
1304
+ * reference it by `profileSha256` instead of re-sending the corpus.
1305
+ * `create()` calls this automatically for its inline profile when
1306
+ * `autoDeferProfile` is on; call it directly when the profile only exists
1307
+ * per-turn, or when the instance was fetched rather than created. Persist
1308
+ * the returned sha256 alongside a content hash of the profile to
1309
+ * re-attach on later instances without re-priming. Throws on transport/HTTP
1310
+ * failure — the caller decides whether that is fatal (it is not: turns fall
1311
+ * back to sending the file-free profile inline).
1684
1312
  */
1685
- private isValidCidr;
1313
+ primeProfile(profile: object): Promise<string>;
1686
1314
  /**
1687
- * Preview link management.
1688
- *
1689
- * Create publicly accessible HTTPS URLs for TCP ports inside the sandbox.
1690
- *
1691
- * @example
1692
- * ```typescript
1693
- * const link = await box.previewLinks.create(3000);
1694
- * console.log(link.url);
1695
- *
1696
- * const links = await box.previewLinks.list();
1697
- * await box.previewLinks.remove(link.previewId);
1698
- * ```
1315
+ * Build the run request's `backend` body. When the outgoing profile's CONTENT
1316
+ * matches the one the runtime already holds (and we are not resending after a
1317
+ * cache miss), swap the inline `profile` for its `profileSha256` so a large
1318
+ * static corpus does not ride every turn. The match is by serialized content,
1319
+ * not object identity, so a mutated-in-place profile — or an equivalent
1320
+ * object passed as a per-turn override — is compared correctly: unchanged
1321
+ * content references by hash, changed content sends inline.
1699
1322
  */
1700
- get previewLinks(): PreviewLinkManager;
1701
- private previewLinkCreate;
1702
- private previewLinkList;
1703
- private previewLinkGet;
1704
- private previewLinkWaitUntilReady;
1705
- private previewLinkRemove;
1706
1323
  /**
1707
- * Get information about the infrastructure driver for this sandbox.
1708
- *
1709
- * @example
1710
- * ```typescript
1711
- * const info = await box.getDriverInfo();
1712
- * console.log(`Driver: ${info.type}, CRIU: ${info.capabilities.criu}`);
1713
- * ```
1324
+ * How this handle's most recent profile file preparation was satisfied
1325
+ * (host cache hit, partial, miss, legacy delivery, or a held receipt) and
1326
+ * how long it took. Undefined until a profile with file mounts is prepared.
1714
1327
  */
1715
- getDriverInfo(): Promise<DriverInfo>;
1716
- private toolsInstall;
1717
- private toolsUse;
1718
- private toolsList;
1719
- private toolsRun;
1328
+ get lastProfileFileDelivery(): ProfileFileDeliveryReport | undefined;
1329
+ /** @internal Shared create/turn delivery; caller policy decides how to expose failures. */
1330
+ materializeProfileFiles(profile: AgentProfile, signal?: AbortSignal, existingFiles?: "replace" | "allow-identical"): Promise<AgentProfile>;
1331
+ protected buildRunBackendBody(overrideBackend: Partial<BackendConfig> | undefined, forceFullProfile: boolean, requestedModel?: string, signal?: AbortSignal, preserveManagedProfile?: boolean): Promise<Record<string, unknown> | undefined>;
1720
1332
  /**
1721
1333
  * Create a snapshot of the sandbox state.
1722
1334
  * Snapshots can be used to save workspace state for later restoration.
@@ -1782,85 +1394,708 @@ declare class SandboxInstance {
1782
1394
  noChanges: boolean;
1783
1395
  };
1784
1396
  /**
1785
- * Export the agent's conversation history from the sandbox filesystem.
1786
- *
1787
- * Each harness stores conversations in its own files:
1788
- * Claude Code: ~/.claude/projects/<session-id>/ (JSONL)
1789
- * Codex: ~/.codex/sessions/ (JSON)
1790
- * OpenCode: ~/.local/share/opencode/storage/ (SQLite)
1791
- *
1792
- * This reads those files and returns them as a map of session-id to
1793
- * conversation content, so the caller can persist them before deleting
1794
- * the sandbox. Without this, conversation history dies with the sandbox.
1795
- */
1796
- exportConversations(): Promise<Map<string, {
1797
- format: string;
1798
- content: string;
1799
- }>>;
1800
- snapshot(options: SnapshotOptions & {
1801
- wait: false;
1802
- }): Promise<SandboxOperation>;
1803
- snapshot(options?: SnapshotOptions): Promise<SnapshotResult>;
1804
- /**
1805
- * List all snapshots for this sandbox.
1806
- *
1807
- * If `storage` is provided (BYOS3), lists snapshots from customer-provided
1808
- * S3 storage.
1809
- *
1810
- * @param storage - Optional customer storage config for BYOS3
1811
- * @returns Array of snapshot metadata
1812
- *
1813
- * @example List from our storage
1814
- * ```typescript
1815
- * const snapshots = await box.listSnapshots();
1816
- * for (const snap of snapshots) {
1817
- * console.log(`${snap.snapshotId}: ${snap.createdAt}`);
1818
- * }
1819
- * ```
1820
- *
1821
- * @example List from customer S3 (BYOS3)
1822
- * ```typescript
1823
- * const snapshots = await box.listSnapshots({
1824
- * type: "s3",
1825
- * bucket: "my-snapshots",
1826
- * credentials: { accessKeyId: "...", secretAccessKey: "..." },
1827
- * });
1828
- * ```
1829
- */
1830
- listSnapshots(storage?: SnapshotOptions["storage"]): Promise<SnapshotInfo[]>;
1831
- revertToSnapshot(snapshotId: string): Promise<SnapshotResult>;
1832
- /**
1833
- * Replace selected workspace-relative paths from a whole-workspace snapshot.
1834
- * Files outside the requested paths are left untouched.
1397
+ * Ask the initialized provider to prepare this turn's public native profile
1398
+ * before admission. Pass both returned expected digests to driveConversationTurn.
1835
1399
  */
1836
- restorePaths(snapshotId: string, paths: string[]): Promise<SnapshotResult>;
1837
- private waitForSnapshotRestore;
1838
- private waitForSnapshotVisible;
1400
+ preparePublicProfileRevision(opts: {
1401
+ sessionId: string;
1402
+ backend: Partial<BackendConfig>;
1403
+ model?: ConversationTurnOptions["model"];
1404
+ }): Promise<{
1405
+ expectedPublicProfileRequestDigest: `sha256:${string}`;
1406
+ expectedPublicProfileRevision: {
1407
+ workspacePlanDigest: `sha256:${string}`;
1408
+ materializedDigest: `sha256:${string}`;
1409
+ launchDigest: string;
1410
+ };
1411
+ conflicts: PublicProfileConflict[];
1412
+ }>;
1413
+ /** Prepare a secret-bearing native revision without starting a model turn. */
1414
+ prepareSecretProfileRevision(opts: {
1415
+ sessionId: string;
1416
+ backend: TurnBackendConfig;
1417
+ model?: ConversationTurnOptions["model"];
1418
+ }): Promise<{
1419
+ expectedPublicProfileRequestDigest: `sha256:${string}`;
1420
+ expectedSecretProfileReceipt: `hmac-sha256:${string}`;
1421
+ workspacePlanDigest: `sha256:${string}`;
1422
+ conflicts: Array<{
1423
+ relPath: string;
1424
+ copyRelPath: string;
1425
+ reason: "existing" | "symlink";
1426
+ }>;
1427
+ }>;
1428
+ }
1429
+ //#endregion
1430
+ //#region src/sandbox-session-admission.d.ts
1431
+ declare abstract class SandboxSessionAdmissionCapabilities extends SandboxProfileCapabilities {
1839
1432
  /**
1840
- * Delete a snapshot.
1433
+ * List messages for a session, including in-flight assistant content
1434
+ * the agent is still streaming. Each entry's `metadata` carries the
1435
+ * durability marker — `status: "streaming" | "completed" | "interrupted"`,
1436
+ * `completed/interrupted` booleans, and the caller-supplied `turnId`
1437
+ * when one was set. See `SessionMessage` for the full contract.
1841
1438
  *
1842
- * Deleting a snapshot that is already gone succeeds and reports
1843
- * `already_absent`, so a retry after an uncertain failure does not raise. A
1844
- * 404 means this sandbox is unknown, not that the snapshot was missing.
1439
+ * Polling this is the right way to detect "did the sidecar die mid-
1440
+ * turn?" — a SIGKILL leaves the assistant message with `status:
1441
+ * "streaming"` and no `completed`/`interrupted` marker; a graceful
1442
+ * abort stamps `interrupted: true` explicitly.
1845
1443
  */
1846
- deleteSnapshot(snapshotId: string, options?: {
1847
- /**
1848
- * Deadline for this one request. The client aborts the request itself at
1849
- * the deadline, so a caller retrying a stalled delete does not leave the
1850
- * previous attempt in flight. Omit it to use the client's own timeout;
1851
- * a supplied value that no timer can hold (not a positive integer of at
1852
- * most 2,147,483,647ms) throws `RangeError` rather than silently
1853
- * widening to that default.
1854
- */
1855
- timeoutMs?: number;
1856
- }): Promise<SnapshotDeleteAcknowledgement>;
1857
- /**
1858
- * Ask whether the snapshot bound to an idempotency key is decided.
1444
+ messages(opts: ListMessagesOptions): Promise<SessionMessage[]>;
1445
+ /** @internal — invoked by SandboxSession.sendMessage(). */
1446
+ _sessionSendMessage(id: string, request: SendSessionMessageRequest, options?: SendSessionMessageOptions): Promise<SentSessionMessage>;
1447
+ /** @internal — invoked by SandboxSession.delete(). */
1448
+ _sessionDelete(id: string): Promise<void>;
1449
+ /** @internal — invoked by SandboxTaskSession.changes(). */
1450
+ _taskSessionChanges(id: string): Promise<TaskSessionChanges>;
1451
+ /** @internal — invoked by SandboxTaskSession.commit(). */
1452
+ _taskSessionCommit(id: string, options?: CommitTaskSessionOptions): Promise<TaskSessionCommitResult>;
1453
+ _sessionFork(id: string, opts?: SessionForkOptions): Promise<SessionInfo>;
1454
+ /** @internal — invoked by SandboxSession.status(). */
1455
+ _sessionStatus(id: string): Promise<SessionInfo | null>;
1456
+ /** @internal — invoked by SandboxSession.runs(). */
1457
+ _sessionRuns(id: string): Promise<SessionExecutionInfo[]>;
1458
+ /** @internal — invoked by SandboxSession.admission(). */
1459
+ _sessionAdmission(id: string, turnId: string, options?: {
1460
+ signal?: AbortSignal;
1461
+ }): Promise<SessionMessageAdmission | null>;
1462
+ /** @internal — invoked by SandboxSession.interrupt(). */
1463
+ _interrupt(id: string, options?: SessionInterruptOptions): Promise<InterruptResult>;
1464
+ protected interactionTransport(): SandboxInteractionTransport;
1465
+ /** @internal — invoked by SandboxSession.interactions(). */
1466
+ _listInteractions(id: string, options?: {
1467
+ signal?: AbortSignal;
1468
+ }): Promise<InteractionRequest[]>;
1469
+ /** @internal — invoked by SandboxSession.respondToInteraction(). */
1470
+ _respondToInteraction(id: string, command: InteractionResponseCommand, options?: {
1471
+ signal?: AbortSignal;
1472
+ }): Promise<SandboxInteractionCommandResult>;
1473
+ /** @internal — invoked by SandboxSession.respondToPermission(). */
1474
+ _respondToPermission(id: string, permissionID: string, options: RespondToPermissionOptions): Promise<SandboxInteractionResult>;
1475
+ /** @internal — invoked by SandboxSession.cancelRun(). */
1476
+ _cancelRun(id: string, request: AgentRunCancellationRequest, options?: {
1477
+ signal?: AbortSignal;
1478
+ }): Promise<AgentRunCancellationAcknowledgement>;
1479
+ /** @internal — invoked by SandboxSession.answer(). */
1480
+ _answerQuestion(id: string, interactionId: string, answers: InteractionData, options?: {
1481
+ signal?: AbortSignal;
1482
+ }): Promise<SandboxInteractionResult>;
1483
+ /** @internal — invoked by SandboxSession.plan(). */
1484
+ _currentPlan(sessionId: string): Promise<DurablePlan | null>;
1485
+ /** @internal — invoked by SandboxSession.approvePlan()/rejectPlan(). */
1486
+ _decidePlan(sessionId: string, planId: string, decision: {
1487
+ outcome: "approved";
1488
+ } | {
1489
+ outcome: "rejected";
1490
+ feedback: string;
1491
+ }, options?: DurablePlanDecisionOptions): Promise<DurablePlanDecisionResult>;
1492
+ }
1493
+ //#endregion
1494
+ //#region src/sandbox-prompt-transport.d.ts
1495
+ declare abstract class SandboxPromptTransportCapabilities extends SandboxSessionAdmissionCapabilities {
1496
+ protected logStreamCheckpoint(checkpoint: string, data?: Record<string, unknown>): void;
1497
+ /**
1498
+ * Inner prompt stream: opens the SSE connection and rejoins the execution's
1499
+ * event log on silent drops. May throw (pre-stream HTTP error, timeout, or
1500
+ * `StreamInterruptedError` when it cannot rejoin); the public
1501
+ * `streamPrompt` wrapper converts those throws into in-band events so
1502
+ * callers never see a thrown generator.
1503
+ */
1504
+ protected streamPromptInner(message: string | PromptInputPart[], options?: PromptOptions, internal?: {
1505
+ forceFullProfile?: boolean;
1506
+ replaySessionId?: string;
1507
+ }): AsyncGenerator<SandboxEvent>;
1508
+ }
1509
+ //#endregion
1510
+ //#region src/sandbox-prompt.d.ts
1511
+ declare abstract class SandboxPromptCapabilities extends SandboxPromptTransportCapabilities {
1512
+ /**
1513
+ * Send a prompt to the agent running in the sandbox.
1514
+ * Returns the complete response after the agent finishes.
1515
+ */
1516
+ prompt(message: string | PromptInputPart[], options?: PromptOptions): Promise<PromptResult>;
1517
+ streamPrompt(message: string | PromptInputPart[], requestedOptions?: PromptOptions): AsyncGenerator<SandboxEvent>;
1518
+ }
1519
+ //#endregion
1520
+ //#region src/sandbox-interactive-operations.d.ts
1521
+ declare abstract class SandboxInteractiveCapabilities extends SandboxPromptCapabilities {
1522
+ /**
1523
+ * Interactive terminal operations for this runtime: the REST manager
1524
+ * (create/input/list/get) plus `attach()`, which opens the live terminal
1525
+ * WebSocket as a {@link TerminalStream}.
1526
+ */
1527
+ get terminals(): SandboxTerminals;
1528
+ /**
1529
+ * Mint a scoped, time-bounded JWT for browser access (Issue #913 Gap 1).
1530
+ * Authority is the caller's `TANGLE_API_KEY` (sk-tan-*); signing secrets
1531
+ * stay server-side. Session/project scopes work with SessionGatewayClient,
1532
+ * while session-runtime/read-only scopes work with SandboxRuntimeClient.
1533
+ */
1534
+ mintScopedToken(opts: MintScopedTokenOptions): Promise<ScopedToken>;
1535
+ /** @internal — delegated to the native interactive operations module. */
1536
+ _startInteractive(id: string, options: InteractiveSessionStartOptions, requestOptions?: InteractiveRequestOptions): Promise<InteractiveSessionStartResult>;
1537
+ /** @internal — delegated to the native interactive operations module. */
1538
+ _sendInteractivePrompt(id: string, command: InteractivePromptCommand, options?: InteractiveRequestOptions): Promise<Agent.AgentInteractiveSessionPromptAcknowledgement>;
1539
+ /** @internal — delegated to the native interactive operations module. */
1540
+ _claimInteractiveControl(id: string, request: Agent.AgentInteractiveSessionControlClaimRequest, options?: InteractiveControlClaimOptions): Promise<Agent.AgentInteractiveSessionControlClaimAcknowledgement>;
1541
+ /** @internal — delegated to the native interactive operations module. */
1542
+ _releaseInteractiveControl(id: string, ref: Agent.AgentInteractiveSessionRef, control: Agent.AgentInteractiveSessionControlClaim, options?: InteractiveRequestOptions): Promise<void>;
1543
+ /** @internal — delegated to the native interactive operations module. */
1544
+ _validateInteractiveControl(id: string, ref: Agent.AgentInteractiveSessionRef, control: Agent.AgentInteractiveSessionControlClaim, options?: InteractiveRequestOptions): Promise<void>;
1545
+ /** @internal — delegated to the native interactive operations module. */
1546
+ _interactiveStatus(id: string, incarnationId: string, options?: InteractiveRequestOptions): Promise<InteractiveSessionStatus | null>;
1547
+ /** @internal — delegated to the native interactive operations module. */
1548
+ _attachInteractive(id: string, ref: Agent.AgentInteractiveSessionRef, request: InteractiveAttachOptions, options?: InteractiveRequestOptions, reconnectAuthority?: TerminalStreamReconnectAuthority): Promise<TerminalStream>;
1549
+ /** @internal — read exact terminal facts from the runtime-owned manager. */
1550
+ _interactiveTerminalInfo(environmentId: string, terminalId: string, options?: InteractiveRequestOptions): Promise<InteractiveTerminalMetadata | null>;
1551
+ /** @internal — delegated to the native interactive operations module. */
1552
+ _attachTerminal(connectionId: string, options?: SandboxTerminalAttachOptions): Promise<TerminalStream>;
1553
+ /** @internal — delegated to the native interactive operations module. */
1554
+ _stopInteractive(id: string, command: InteractiveStopCommand, options?: InteractiveRequestOptions): Promise<Agent.AgentInteractiveSessionStopAcknowledgement>;
1555
+ /** @internal — delegated to the native interactive operations module. */
1556
+ _stopInteractiveLifecycle(id: string, ref: Agent.AgentInteractiveSessionRef, options?: InteractiveRequestOptions): Promise<Agent.AgentInteractiveSessionStopAcknowledgement>;
1557
+ }
1558
+ //#endregion
1559
+ //#region src/session.d.ts
1560
+ type RawEvidenceAttempt = {
1561
+ executionId: string;
1562
+ ordinal: number;
1563
+ providerSessionId: string;
1564
+ nativeSessionIds: string[];
1565
+ processIds: string[];
1566
+ outcome: "succeeded" | "failed" | "cancelled" | "unknown";
1567
+ missingReasons: string[];
1568
+ };
1569
+ type RawEvidenceExport = ({
1570
+ status: "captured" | "partial";
1571
+ sessionId: string;
1572
+ backendType: string;
1573
+ nativeSessionId: string | null;
1574
+ proofStatus: "verified" | "unverified";
1575
+ containerId?: string;
1576
+ sidecarImageDigest: string;
1577
+ sidecarBundleRevision: string;
1578
+ sidecarBundleChecksum?: string;
1579
+ nativeRoots: Array<{
1580
+ sourceId?: string;
1581
+ rootScope: "session-home" | "workspace-session";
1582
+ path: string;
1583
+ }>;
1584
+ files: Array<Record<string, unknown>>;
1585
+ excluded: Array<Record<string, unknown>>;
1586
+ skipped: Array<{
1587
+ sourceId?: string;
1588
+ rootScope: "session-home" | "workspace-session";
1589
+ path: string;
1590
+ reason: string;
1591
+ }>;
1592
+ inventory: Record<string, number>;
1593
+ processIo: Array<Record<string, unknown>>;
1594
+ processTerminals: Array<Record<string, unknown>>; /** Exact raw spool for every readable provider HOME. */
1595
+ processSources: Array<{
1596
+ sourceId: string;
1597
+ contentBase64: string;
1598
+ sizeBytes: number;
1599
+ sha256: string;
1600
+ }>;
1601
+ events: Array<Record<string, unknown>>;
1602
+ attempts: RawEvidenceAttempt[];
1603
+ evidenceSources: Array<{
1604
+ executionId: string;
1605
+ sourceId: string;
1606
+ backendType: string;
1607
+ runtimeHome: string;
1608
+ credentialPaths: string[];
1609
+ }>;
1610
+ completeness: {
1611
+ nativeStore: boolean;
1612
+ processIo: boolean;
1613
+ events: boolean;
1614
+ };
1615
+ coverageComplete: boolean;
1616
+ missingReasons: string[];
1617
+ } & ({
1618
+ status: "captured";
1619
+ nativeSessionId: string | null;
1620
+ completeness: {
1621
+ nativeStore: true;
1622
+ processIo: true;
1623
+ events: true;
1624
+ };
1625
+ coverageComplete: true;
1626
+ missingReasons: [];
1627
+ } | {
1628
+ status: "partial";
1629
+ coverageComplete: false;
1630
+ })) | {
1631
+ status: "unavailable";
1632
+ sessionId: string;
1633
+ backendType: string;
1634
+ reason: string;
1635
+ };
1636
+ /**
1637
+ * The subset of `SandboxInstance` a `SandboxSession` drives. Declared here
1638
+ * (rather than importing the concrete class) so `session.ts` stays a leaf
1639
+ * of `sandbox.ts` — `sandbox.ts` constructs `SandboxSession`, so the reverse
1640
+ * import would form a cycle. `SandboxInstance` satisfies this structurally.
1641
+ */
1642
+ interface SandboxSessionHost extends InteractiveSessionHost {
1643
+ prompt(message: string | PromptInputPart[], options?: PromptOptions): Promise<PromptResult>;
1644
+ _sessionStatus(id: string): Promise<SessionInfo | null>;
1645
+ _sessionEvents(id: string, opts?: SessionEventStreamOptions): AsyncGenerator<SandboxEvent>;
1646
+ _sessionRuns(id: string): Promise<SessionExecutionInfo[]>;
1647
+ _sessionRawEvidence(id: string): Promise<RawEvidenceExport>;
1648
+ _sessionExportRawEvidence(id: string, destination: string, options: RawEvidenceExportOptions): Promise<RawEvidenceDirectoryExport>;
1649
+ _sessionAdmission(id: string, turnId: string, options?: {
1650
+ signal?: AbortSignal;
1651
+ }): Promise<SessionMessageAdmission | null>;
1652
+ _sessionResult(id: string, options?: SessionResultOptions, session?: SessionInfo): Promise<PromptResult>;
1653
+ _sessionDelete(id: string): Promise<void>;
1654
+ _sessionSendMessage(id: string, request: SendSessionMessageRequest, options?: SendSessionMessageOptions): Promise<SentSessionMessage>;
1655
+ messages(opts: ListMessagesOptions): Promise<SessionMessage[]>;
1656
+ _sessionFork(id: string, opts?: SessionForkOptions): Promise<SessionInfo>;
1657
+ _respondToPermission(id: string, permissionID: string, options: RespondToPermissionOptions): Promise<SandboxInteractionResult>;
1658
+ _listInteractions(id: string, options?: {
1659
+ signal?: AbortSignal;
1660
+ }): Promise<InteractionRequest[]>;
1661
+ _respondToInteraction(id: string, command: InteractionResponseCommand, options?: {
1662
+ signal?: AbortSignal;
1663
+ }): Promise<SandboxInteractionCommandResult>;
1664
+ _interrupt(id: string, options?: SessionInterruptOptions): Promise<InterruptResult>;
1665
+ _cancelRun(id: string, request: AgentRunCancellationRequest, options?: {
1666
+ signal?: AbortSignal;
1667
+ }): Promise<AgentRunCancellationAcknowledgement>;
1668
+ _answerQuestion(id: string, interactionId: string, answers: InteractionData, options?: {
1669
+ signal?: AbortSignal;
1670
+ }): Promise<SandboxInteractionResult>;
1671
+ _currentPlan(id: string): Promise<DurablePlan | null>;
1672
+ _decidePlan(id: string, planId: string, decision: {
1673
+ outcome: "approved";
1674
+ } | {
1675
+ outcome: "rejected";
1676
+ feedback: string;
1677
+ }, options?: DurablePlanDecisionOptions): Promise<DurablePlanDecisionResult>;
1678
+ }
1679
+ /**
1680
+ * A single agent session inside a sandbox. Created via
1681
+ * `box.session(id)` — does not hit the network until a method is called.
1682
+ */
1683
+ declare class SandboxSession {
1684
+ private readonly box;
1685
+ /** Stable session id assigned by the sandbox runtime. */
1686
+ readonly id: string;
1687
+ /**
1688
+ * @internal SDK-internal constructor — apps should call `box.session(id)`.
1689
+ */
1690
+ constructor(box: SandboxSessionHost, /** Stable session id assigned by the sandbox runtime. */
1691
+
1692
+ id: string);
1693
+ /**
1694
+ * Fetch the current session state from the sandbox. Includes status,
1695
+ * model, prompt count, token usage if known, and timing metadata.
1696
+ *
1697
+ * Throws on transport error; returns `null` if the session id is not
1698
+ * known to the sandbox (e.g. it ended and was reaped, or the id is
1699
+ * invalid).
1700
+ */
1701
+ status(): Promise<SessionInfo | null>;
1702
+ /**
1703
+ * Stream events from this session as they arrive. With no `since`,
1704
+ * starts at the live tail; with `since`, replays strictly after that
1705
+ * event id — useful for reconnect-after-disconnect flows.
1706
+ *
1707
+ * The async iterator terminates when the session reaches a terminal
1708
+ * state (`completed`, `failed`, `cancelled`) and the corresponding
1709
+ * terminal event has been yielded, OR when the caller's signal aborts.
1710
+ */
1711
+ events(opts?: SessionEventStreamOptions): AsyncGenerator<SandboxEvent>;
1712
+ /**
1713
+ * List the durable executions recorded for this session, newest first.
1714
+ *
1715
+ * This is the runtime's authoritative execution ledger. It lets callers
1716
+ * count provider runs without inferring execution from model-written files.
1717
+ */
1718
+ runs(): Promise<SessionExecutionInfo[]>;
1719
+ /** Capture the complete attributed native store and process stream before deletion. */
1720
+ /** Export verified native evidence into a new local directory with bounded memory. */
1721
+ exportRawEvidence(destination: string, options: RawEvidenceExportOptions): Promise<RawEvidenceDirectoryExport>;
1722
+ rawEvidence(): Promise<RawEvidenceExport>;
1723
+ /** Read the exact execution admitted for a turn, including server-owned plan follow-ups.
1724
+ * This never admits work or verifies the input of a proposed retry.
1725
+ */
1726
+ admission(turnId: string, options?: {
1727
+ signal?: AbortSignal;
1728
+ }): Promise<SessionMessageAdmission | null>;
1729
+ /**
1730
+ * Await a terminal result. With `executionId`, drains only that execution;
1731
+ * without it, reads status and selects the latest execution. Event replay
1732
+ * makes either form safe after the execution has already finished.
1733
+ *
1734
+ * Use this to wait for a session that was started by another caller
1735
+ * (e.g. `dispatchPrompt`).
1736
+ */
1737
+ result(options?: SessionResultOptions): Promise<PromptResult>;
1738
+ /**
1739
+ * List persisted messages for this session, including in-flight assistant
1740
+ * content when the runtime has flushed partial output.
1741
+ */
1742
+ messages(opts?: Omit<ListMessagesOptions, "sessionId">): Promise<SessionMessage[]>;
1743
+ /**
1744
+ * Continue this session with an additional prompt. Equivalent to
1745
+ * `box.prompt(message, { ...opts, sessionId: this.id })` but reads
1746
+ * naturally on a Session reference.
1747
+ */
1748
+ prompt(message: string | PromptInputPart[], opts?: PromptOptions): Promise<PromptResult>;
1749
+ /**
1750
+ * Submit a structured message through the session message endpoint. The
1751
+ * returned receipt confirms admission; follow progress with `events()` or
1752
+ * await the terminal response with `result()`. Model and message identifiers
1753
+ * are translated to the runtime's wire names by the SDK.
1754
+ */
1755
+ sendMessage(request: SendSessionMessageRequest, options?: SendSessionMessageOptions): Promise<SentSessionMessage>;
1756
+ /** Delete this session and its persisted runtime state. */
1757
+ delete(): Promise<void>;
1758
+ /**
1759
+ * Fork this session into a new queued session. The fork shares the
1760
+ * parent workspace and copies conversation history up to `messageId`
1761
+ * when supplied.
1762
+ */
1763
+ fork(opts?: SessionForkOptions): Promise<{
1764
+ session: SandboxSession;
1765
+ info: SessionInfo;
1766
+ }>;
1767
+ /**
1768
+ * Drive this session's harness in INTERACTIVE mode: spawn its native TUI,
1769
+ * stream the live framebuffer, and inject prompts as keystrokes. Distinct
1770
+ * from the headless `prompt()`/`events()` surface above. Lazy — does not hit
1771
+ * the network until a handle method is called.
1772
+ */
1773
+ interactive(options?: InteractiveSessionHandleOptions): InteractiveSessionHandle;
1774
+ /**
1775
+ * Resolve a pending permission interaction the agent raised mid-turn,
1776
+ * forwarding `allow`/`deny` to the blocked agent through the unified
1777
+ * interaction channel. Throws if no matching permission is outstanding.
1778
+ */
1779
+ respondToPermission(permissionID: string, options: RespondToPermissionOptions): Promise<SandboxInteractionResult>;
1780
+ /** Return every interaction that still awaits a response on this session. */
1781
+ interactions(options?: {
1782
+ signal?: AbortSignal;
1783
+ }): Promise<InteractionRequest[]>;
1784
+ /** Respond to one exact interaction with a retry-safe command. */
1785
+ respondToInteraction(command: InteractionResponseCommand, options?: {
1786
+ signal?: AbortSignal;
1787
+ }): Promise<SandboxInteractionCommandResult>;
1788
+ /**
1789
+ * Interrupt an execution without deleting the session. Pass `executionId`
1790
+ * to make the cancellation exact: a newer run on the same session is never
1791
+ * touched. Without it, the current execution is selected. Returns
1792
+ * `{ cancelled: false }` when the selected execution is not running.
1793
+ */
1794
+ interrupt(options?: SessionInterruptOptions): Promise<InterruptResult>;
1795
+ /**
1796
+ * Cancel one exact run through the durable operation contract. Reusing the
1797
+ * same request after a lost response returns the sidecar's replayed
1798
+ * acknowledgement instead of issuing a second cancellation.
1799
+ */
1800
+ cancelRun(request: AgentRunCancellationRequest, options?: {
1801
+ signal?: AbortSignal;
1802
+ }): Promise<AgentRunCancellationAcknowledgement>;
1803
+ /** Answer one exact question without selecting another outstanding ask. */
1804
+ answer(interactionId: string, answers: InteractionData, options?: {
1805
+ signal?: AbortSignal;
1806
+ }): Promise<SandboxInteractionResult>;
1807
+ /** Return the newest plan awaiting a decision for this session. */
1808
+ plan(): Promise<DurablePlan | null>;
1809
+ /** Approve a durable plan; caller mode returns admission for fresh preparation. */
1810
+ approvePlan(planId?: string, options?: DurablePlanDecisionOptions): Promise<DurablePlanDecisionResult>;
1811
+ /** Reject a durable plan with feedback; caller mode prepares the revision turn. */
1812
+ rejectPlan(feedback: string, planId?: string, options?: DurablePlanDecisionOptions): Promise<DurablePlanDecisionResult>;
1813
+ private requireCurrentPlan;
1814
+ }
1815
+ //#endregion
1816
+ //#region src/sandbox-session-evidence.d.ts
1817
+ declare abstract class SandboxSessionEvidenceCapabilities extends SandboxInteractiveCapabilities {
1818
+ /** @internal — invoked before the sandbox is deleted. */
1819
+ _sessionExportRawEvidence(id: string, destination: string, options: RawEvidenceExportOptions): Promise<RawEvidenceDirectoryExport>;
1820
+ /**
1821
+ * Export every native session store on this box into a new local
1822
+ * directory: each runtime HOME's Claude Code, Codex, OpenCode and other
1823
+ * harness stores (transcripts and SQLite databases), and every settled
1824
+ * copy. The box-level twin of `box.session(id).exportRawEvidence`, for a
1825
+ * box about to be deleted, including one restored from a snapshot whose
1826
+ * session listing is empty. Only files a harness contract declares as its
1827
+ * session store are read; credentials and config never leave the box.
1828
+ *
1829
+ * The destination must not exist. Payload digests, the manifest digest
1830
+ * and the byte and file bounds are verified before the directory appears.
1831
+ */
1832
+ exportRawEvidence(destination: string, options: RawEvidenceBoxExportOptions): Promise<RawEvidenceBoxDirectoryExport>;
1833
+ _sessionRawEvidence(id: string): Promise<RawEvidenceExport>;
1834
+ /** @internal — invoked by SandboxSession.events(). */
1835
+ _sessionEvents(id: string, opts?: SessionEventStreamOptions, stopOnTurnTerminal?: boolean): AsyncGenerator<SandboxEvent>;
1836
+ /** Replay one execution without subscribing to other runs on its session. */
1837
+ protected _executionEvents(sessionId: string, executionId: string): AsyncGenerator<SandboxEvent>;
1838
+ /** @internal — invoked by SandboxSession.result(). */
1839
+ _sessionResult(id: string, options?: SessionResultOptions, knownSession?: SessionInfo): Promise<PromptResult>;
1840
+ }
1841
+ //#endregion
1842
+ //#region src/task-session.d.ts
1843
+ /** @internal Operations implemented by `SandboxInstance`. */
1844
+ interface SandboxTaskSessionHost extends SandboxSessionHost {
1845
+ _taskSessionChanges(id: string): Promise<TaskSessionChanges>;
1846
+ _taskSessionCommit(id: string, options?: CommitTaskSessionOptions): Promise<TaskSessionCommitResult>;
1847
+ }
1848
+ /** A background task session with isolated changeset operations. */
1849
+ declare class SandboxTaskSession extends SandboxSession {
1850
+ private readonly taskBox;
1851
+ /** @internal Apps should call `box.taskSession(id)`. */
1852
+ constructor(taskBox: SandboxTaskSessionHost, id: string);
1853
+ /** Read the task's isolated file changes. */
1854
+ changes(): Promise<TaskSessionChanges>;
1855
+ /** Apply all or a selected subset of the task's isolated file changes. */
1856
+ commit(options?: CommitTaskSessionOptions): Promise<TaskSessionCommitResult>;
1857
+ }
1858
+ //#endregion
1859
+ //#region src/sandbox-sessions.d.ts
1860
+ /**
1861
+ * Result of registering a sidecar session mapping. `reprovisionRequired` is
1862
+ * true when the server reports the mapped sidecar is stale (HTTP 410) and the
1863
+ * caller must reprovision the sandbox before retrying.
1864
+ */
1865
+ interface SessionMappingResult {
1866
+ success: boolean;
1867
+ sessionId: string;
1868
+ sidecarSessionId?: string;
1869
+ reprovisionRequired: boolean;
1870
+ code?: string;
1871
+ }
1872
+ declare abstract class SandboxSessionCapabilities extends SandboxSessionEvidenceCapabilities {
1873
+ /**
1874
+ * Associate a session ID with this sandbox so the Sandbox API can route
1875
+ * subsequent WebSocket connections.
1876
+ *
1877
+ * @param opts - Session and sandbox routing identifiers
1878
+ *
1879
+ * @example
1880
+ * ```typescript
1881
+ * await box.registerSessionMapping({
1882
+ * sessionId: "sess_abc",
1883
+ * runtimeSessionId: "runtime_abc",
1884
+ * });
1885
+ * ```
1886
+ */
1887
+ registerSessionMapping(opts: {
1888
+ sessionId: string; /** The runtime (sidecar) session id this agent session routes to. */
1889
+ runtimeSessionId: string; /** Optional container id for direct routing. */
1890
+ sidecarId?: string; /** Optional projectRef so the server can detect a stale sidecar. */
1891
+ projectRef?: string;
1892
+ }): Promise<SessionMappingResult>;
1893
+ /**
1894
+ * Remove the sidecar session mapping for an agent session. Sandbox deletion
1895
+ * also cleans mappings, so this is only needed to release a mapping while the
1896
+ * sandbox stays alive.
1897
+ */
1898
+ unregisterSessionMapping(opts: {
1899
+ sessionId: string;
1900
+ }): Promise<{
1901
+ success: boolean;
1902
+ sessionId: string;
1903
+ }>;
1904
+ /**
1905
+ * Get a session reference bound to this sandbox. Lazy: does not hit the
1906
+ * network until you call a method on the returned `SandboxSession`.
1907
+ * Use {@link sessions} to discover existing session ids.
1908
+ */
1909
+ session(id: string): SandboxSession;
1910
+ /**
1911
+ * Lines attached to this sandbox. `attach()` binds a line so Hub runs each
1912
+ * member's messages here, one session per member.
1913
+ */
1914
+ get lines(): SandboxLines;
1915
+ /** Create an agent session and return both its handle and initial metadata. */
1916
+ createSession(options: CreateSessionOptions): Promise<{
1917
+ session: SandboxSession;
1918
+ info: SessionInfo;
1919
+ }>;
1920
+ /** Delete an agent session by id. */
1921
+ deleteSession(id: string): Promise<void>;
1922
+ /** Get a lazy background-task session reference. */
1923
+ taskSession(id: string): SandboxTaskSession;
1924
+ /** Create a background task session. Dispatch work with `session.sendMessage()`. */
1925
+ createTaskSession(options: CreateTaskSessionOptions): Promise<{
1926
+ session: SandboxTaskSession;
1927
+ info: TaskSessionInfo;
1928
+ }>;
1929
+ /**
1930
+ * List sessions on this sandbox, optionally filtering by status. Returns
1931
+ * `SandboxSession` instances paired with their last-known
1932
+ * {@link SessionInfo} so callers can avoid an extra round-trip per
1933
+ * session for status.
1934
+ */
1935
+ sessions(opts?: SessionListOptions): Promise<Array<{
1936
+ session: SandboxSession;
1937
+ info: SessionInfo;
1938
+ }>>;
1939
+ /**
1940
+ * Dispatch a prompt and return immediately with the session id (Issue
1941
+ * #913 Gap 2). The sandbox keeps running the prompt after this call
1942
+ * returns; reconnect via `box.session(id).events()` or wait for
1943
+ * completion with `box.session(id).result()`.
1944
+ *
1945
+ * Skips the dispatch only on positive evidence that this work is
1946
+ * already in flight or already finished — never on the mere existence
1947
+ * of a session with the same id:
1948
+ *
1949
+ * 1. `opts.turnId` is set and the completed-turn cache has it → the
1950
+ * turn already finished; return `dispatched: false`. This is the
1951
+ * only durable idempotency key, and it outlives the session (the
1952
+ * cache survives session eviction, see `findCompletedTurn`).
1953
+ * 2. Otherwise, the session is in flight — `running`, or `queued` with a
1954
+ * `latestExecutionId` — → a second dispatch would run two agents
1955
+ * against one session, so return the live status with
1956
+ * `dispatched: false`.
1957
+ *
1958
+ * Anything else dispatches. Two cases in particular:
1959
+ *
1960
+ * - A `queued` session with no `latestExecutionId` was created or
1961
+ * forked and has never run anything — the runtime writes exactly
1962
+ * that state on `POST /agents/sessions` and on fork, and sets
1963
+ * `latestExecutionId` at execution START. Refusing here would leave
1964
+ * a pre-created session permanently undispatchable.
1965
+ * - A terminal session is a finished conversation, and a new prompt
1966
+ * into it is a new turn, not a retry.
1967
+ *
1968
+ * A caller that needs a completed dispatch to stay a no-op across
1969
+ * retries MUST pass `turnId`; session existence cannot stand in for it,
1970
+ * because an evicted session makes the same retry dispatch anyway.
1971
+ *
1972
+ * Read `dispatched`, not `alreadyExisted`, to tell "the prompt ran"
1973
+ * from "we found prior work and did nothing".
1974
+ */
1975
+ dispatchPrompt(message: string | PromptInputPart[], opts?: DispatchPromptOptions): Promise<DispatchedSession>;
1976
+ /**
1977
+ * Look up a cached turn result by idempotency key. Returns the cached
1978
+ * payload if a turn with this `turnId` previously completed on the
1979
+ * given session; returns `null` if no such turn has finished yet
1980
+ * (either it never started, or it interrupted before completion).
1981
+ *
1982
+ * Call this before re-issuing a `streamPrompt` / `prompt` / `task`
1983
+ * that you might be retrying — a non-null result means the original
1984
+ * attempt finished and you can return that to your caller instead of
1985
+ * running the agent a second time. Only turns that reach the
1986
+ * `completed` terminal state are cached; interrupted turns are not.
1987
+ */
1988
+ findCompletedTurn(turnId: string, opts: {
1989
+ sessionId: string;
1990
+ }): Promise<CompletedTurnResult | null>;
1991
+ }
1992
+ //#endregion
1993
+ //#region src/sandbox-turns.d.ts
1994
+ declare abstract class SandboxTurnCapabilities extends SandboxSessionCapabilities {
1995
+ /**
1996
+ * Drive a detached turn forward by exactly one settle → poll → dispatch
1997
+ * pass and report where it stands. Built for tick-based callers —
1998
+ * Cloudflare Workflows steps, queue consumers, crons — that re-invoke
1999
+ * on their own schedule instead of holding a stream open.
2000
+ * The pass does not poll repeatedly or keep a connection alive.
2001
+ * Session admission may retry one classified pre-dispatch credential refusal.
2002
+ *
2003
+ * The pass resolves to the first of:
2004
+ * 1. The completed-turn cache has `turnId` → `completed`, or `failed`
2005
+ * when the cached payload carries no text — that result is final,
2006
+ * so a retry cannot improve it.
2007
+ * 2. The session is queued/running → `running`, after enforcing
2008
+ * `wallCapMs`: a session past the cap is cancelled and reported
2009
+ * `failed`.
2010
+ * 3. The session is terminal without a cached turn → settle from the
2011
+ * session result; an unsuccessful result is `failed`.
2012
+ * 4. No session exists, or one exists that was created/forked but never
2013
+ * ran (`queued` with no `latestExecutionId`) → dispatch
2014
+ * fire-and-detach → `running`.
2015
+ *
2016
+ * `failed` is always deterministic: re-invoking with the same ids
2017
+ * returns the same outcome rather than starting a second agent run, so
2018
+ * callers can treat it as terminal without their own retry bookkeeping.
2019
+ */
2020
+ driveTurn(message: string | PromptInputPart[], opts: DriveTurnOptions): Promise<TurnDriveResult>;
2021
+ /** Advance exactly the named turn while retaining the native conversation.
2022
+ * Admission receipts are independent of expiring event logs. A previous
2023
+ * turn's terminal session status cannot settle a newly submitted message. */
2024
+ driveConversationTurn(message: string | PromptInputPart[], opts: ConversationTurnOptions): Promise<ConversationTurnResult>;
2025
+ protected driveConversationTurnPass(message: string | PromptInputPart[], opts: ConversationTurnOptions, traceId: string): Promise<ConversationTurnResult>;
2026
+ }
2027
+ //#endregion
2028
+ //#region src/sandbox-snapshots.d.ts
2029
+ interface SnapshotRestoreAcceptedResponse {
2030
+ jobId: string;
2031
+ status: "pending";
2032
+ }
2033
+ declare abstract class SandboxSnapshotCapabilities extends SandboxTurnCapabilities {
2034
+ #private;
2035
+ snapshot(options: SnapshotOptions & {
2036
+ wait: false;
2037
+ }): Promise<SandboxOperation>;
2038
+ snapshot(options?: SnapshotOptions): Promise<SnapshotResult>;
2039
+ /**
2040
+ * List all snapshots for this sandbox.
2041
+ *
2042
+ * If `storage` is provided (BYOS3), lists snapshots from customer-provided
2043
+ * S3 storage.
2044
+ *
2045
+ * @param storage - Optional customer storage config for BYOS3
2046
+ * @returns Array of snapshot metadata
2047
+ *
2048
+ * @example List from our storage
2049
+ * ```typescript
2050
+ * const snapshots = await box.listSnapshots();
2051
+ * for (const snap of snapshots) {
2052
+ * console.log(`${snap.snapshotId}: ${snap.createdAt}`);
2053
+ * }
2054
+ * ```
2055
+ *
2056
+ * @example List from customer S3 (BYOS3)
2057
+ * ```typescript
2058
+ * const snapshots = await box.listSnapshots({
2059
+ * type: "s3",
2060
+ * bucket: "my-snapshots",
2061
+ * credentials: { accessKeyId: "...", secretAccessKey: "..." },
2062
+ * });
2063
+ * ```
2064
+ */
2065
+ listSnapshots(storage?: SnapshotOptions["storage"]): Promise<SnapshotInfo[]>;
2066
+ /**
2067
+ * Delete a snapshot.
2068
+ *
2069
+ * Deleting a snapshot that is already gone succeeds and reports
2070
+ * `already_absent`, so a retry after an uncertain failure does not raise. A
2071
+ * 404 means this sandbox is unknown, not that the snapshot was missing.
2072
+ */
2073
+ deleteSnapshot(snapshotId: string, options?: {
2074
+ /**
2075
+ * Deadline for this one request. The client aborts the request itself at
2076
+ * the deadline, so a caller retrying a stalled delete does not leave the
2077
+ * previous attempt in flight. Omit it to use the client's own timeout;
2078
+ * a supplied value that no timer can hold (not a positive integer of at
2079
+ * most 2,147,483,647ms) throws `RangeError` rather than silently
2080
+ * widening to that default.
2081
+ */
2082
+ timeoutMs?: number;
2083
+ }): Promise<SnapshotDeleteAcknowledgement>;
2084
+ /**
2085
+ * Ask whether the snapshot bound to an idempotency key is decided.
1859
2086
  *
1860
2087
  * Pass the same options the create carried for an exact-body lookup. Omit
1861
2088
  * options to read the operation bound to this owner-scoped key.
1862
2089
  */
1863
2090
  getSnapshotOperation(idempotencyKey: string, options?: Pick<SnapshotOptions, "tags">): Promise<WorkspaceOperationLookup>;
2091
+ revertToSnapshot(snapshotId: string): Promise<SnapshotResult>;
2092
+ /**
2093
+ * Replace selected workspace-relative paths from a whole-workspace snapshot.
2094
+ * Files outside the requested paths are left untouched.
2095
+ */
2096
+ restorePaths(snapshotId: string, paths: string[]): Promise<SnapshotResult>;
2097
+ protected waitForSnapshotRestore(snapshotId: string, accepted: SnapshotRestoreAcceptedResponse): Promise<SnapshotResult>;
2098
+ protected waitForSnapshotVisible(snapshotId: string, fallback?: Partial<SnapshotResult>): Promise<SnapshotResult>;
1864
2099
  /**
1865
2100
  * Restore from the latest snapshot in customer-provided storage.
1866
2101
  * Only available when using BYOS3 (calls the runtime directly).
@@ -1885,45 +2120,10 @@ declare class SandboxInstance {
1885
2120
  * ```
1886
2121
  */
1887
2122
  restoreFromStorage(storage: SnapshotOptions["storage"], options?: RestoreSnapshotOptions): Promise<SnapshotResult | null>;
1888
- /**
1889
- * Branch this RUNNING sandbox into `count` copy-on-write children
1890
- * (Morph Infinibranch parity). Branch forks the live VM's memory into many
1891
- * children at once via Firecracker UFFD copy-on-write: the children share the
1892
- * parent's clean pages instead of each copying full guest memory. The parent
1893
- * stays running.
1894
- *
1895
- * Returns only the children. A fan-out that materialized fewer than `count`
1896
- * still resolves — the children are real — so compare the array length, or
1897
- * call {@link fork} for the explicit `complete` flag.
1898
- *
1899
- * @param count - Number of children to create (must be >= 1).
1900
- * @param options - Per-child overrides.
1901
- * @returns The new sandbox instances that materialized.
1902
- *
1903
- * @example
1904
- * ```typescript
1905
- * const [a, b, c] = await box.branch(3);
1906
- * // a, b, c each share box's memory state at branch time
1907
- * ```
1908
- */
1909
- branch(count: number, options?: BranchOptions): Promise<SandboxInstance[]>;
1910
- /**
1911
- * Branch this RUNNING sandbox and report the fan-out, not only the children.
1912
- *
1913
- * `complete` is false when fewer children materialized than were requested,
1914
- * so a partial fan-out is never read as a whole one. With an
1915
- * `idempotencyKey`, a retry of the same key and options returns exactly the
1916
- * children the first request materialized and creates none.
1917
- *
1918
- * @example
1919
- * ```typescript
1920
- * const forked = await box.fork(5, { idempotencyKey: "run-42" });
1921
- * if (!forked.complete) {
1922
- * console.warn(`${forked.materializedCount} of ${forked.requestedCount}`);
1923
- * }
1924
- * ```
1925
- */
1926
- fork(count: number, options?: BranchOptions): Promise<ForkAcknowledgement>;
2123
+ }
2124
+ //#endregion
2125
+ //#region src/sandbox-branches.d.ts
2126
+ declare abstract class SandboxBranchCapabilities extends SandboxSnapshotCapabilities {
1927
2127
  /**
1928
2128
  * Ask whether the fork bound to an idempotency key is decided.
1929
2129
  *
@@ -1970,435 +2170,833 @@ declare class SandboxInstance {
1970
2170
  * exceptions. Throws {@link TimeoutError} on deadline or abort.
1971
2171
  */
1972
2172
  waitForRollout(rolloutId: string, options?: WaitForRolloutOptions): Promise<Rollout>;
2173
+ }
2174
+ //#endregion
2175
+ //#region src/sandbox-access.d.ts
2176
+ declare abstract class SandboxAccessCapabilities extends SandboxBranchCapabilities {
1973
2177
  /**
1974
- * Stop the sandbox (keeps state for resume).
1975
- *
1976
- * The stop response carries the orchestrator's per-phase stop breakdown
1977
- * (`stop_metering` / `container_kill` / `stop_complete` /
1978
- * `stop_unaccounted`); after this resolves, {@link startupDiagnostics}
1979
- * returns it (replacing the create breakdown).
1980
- */
1981
- stop(): Promise<void>;
1982
- /**
1983
- * With `wait: false`, answers as soon as the stop is durably accepted and
1984
- * returns the {@link SandboxOperation}; `await op.wait()` resolves once the
1985
- * sandbox is stopped. A stop the API finished synchronously comes back as an
1986
- * operation that is already `succeeded`.
1987
- */
1988
- stop(options: StopOptions & {
1989
- wait: false;
1990
- }): Promise<SandboxOperation>;
1991
- stop(options?: StopOptions): Promise<void>;
1992
- /** Read an operation a `wait: false` stop or snapshot of this sandbox returned. */
1993
- getOperation(operationId: string): Promise<SandboxOperation>;
1994
- /** Read credential recovery metadata without changing sandbox lifecycle. */
1995
- getEnvRecovery(): Promise<SandboxEnvRecoveryView>;
1996
- /** Replace a stopped sandbox's policy, or inspect a proposed change with dryRun. */
1997
- setEnvRecovery(envRecovery: SandboxEnvRecovery, options?: {
1998
- dryRun?: boolean;
1999
- }): Promise<SandboxEnvRecoveryView>;
2000
- /** Resume a stopped sandbox; cold recovery may require caller env values. */
2001
- resume(options?: ResumeOptions): Promise<void>;
2002
- /** Rebuild a stopped sandbox from its durable snapshot under the same ID. */
2003
- rebuild(options?: ResumeOptions): Promise<void>;
2004
- private resumeRuntime;
2005
- /**
2006
- * Delete the sandbox permanently. This is how a forked child is destroyed.
2007
- *
2008
- * `outcome` separates `destroyed` from `already_absent`, so a retry after an
2009
- * uncertain failure reports what really happened instead of raising.
2010
- *
2011
- * The call answers once the runtime is killed and billed; the container,
2012
- * volume and network are reclaimed behind it and `removal` says
2013
- * `"pending"`. Pass `until: "removed"` to wait for that reclaim instead.
2014
- *
2015
- * The delete response carries the orchestrator's per-phase delete breakdown
2016
- * (`runtime_kill` / `tombstone_persist` / `delete_complete` /
2017
- * `delete_unaccounted`); after this resolves, {@link startupDiagnostics}
2018
- * returns it for post-mortem reads on the now-gone sandbox.
2019
- */
2020
- delete(options?: SandboxDeleteOptions): Promise<SandboxDeleteAcknowledgement>;
2021
- /**
2022
- * Read a lifecycle response body once.
2023
- *
2024
- * Current APIs return the complete sandbox state. Older APIs return an empty
2025
- * body, so callers refresh when this method cannot recover a state payload.
2026
- */
2027
- private readLifecycleResponse;
2028
- private applyLifecycleResponse;
2029
- /**
2030
- * Upload a local directory to the sandbox via tar.
2031
- * @param localPath - Local directory path to upload
2032
- * @param remotePath - Destination path in the sandbox (default: /home/user)
2033
- */
2034
- uploadDirectory(localPath: string, remotePath?: string): Promise<void>;
2035
- /**
2036
- * Wait for the sandbox to reach a specific status.
2037
- *
2038
- * A sandbox is not considered `running` until its filesystem incarnation is
2039
- * complete and ready.
2040
- *
2041
- * When `onProgress` is provided and the sandbox is still provisioning,
2042
- * uses SSE events for real-time progress instead of polling. Falls back
2043
- * to polling if the SSE connection fails or is unavailable.
2044
- *
2045
- * @example Basic wait
2046
- * ```typescript
2047
- * await box.waitFor("running");
2048
- * ```
2178
+ * Get an MCP endpoint for this sandbox. Returns a paste-able config
2179
+ * for any MCP-capable host (Claude Desktop, Cursor, claude-code,
2180
+ * codex, opencode, …) plus a freshly-minted, capability-scoped JWT.
2049
2181
  *
2050
- * @example Wait with progress tracking
2051
- * ```typescript
2052
- * await box.waitFor("running", {
2053
- * onProgress: (event) => {
2054
- * console.log(`[${event.step}] ${event.status} — ${event.message}`);
2055
- * if (event.percent !== undefined) {
2056
- * updateProgressBar(event.percent);
2057
- * }
2058
- * },
2059
- * });
2060
- * ```
2061
- */
2062
- waitFor(status: SandboxStatus | SandboxStatus[], options?: WaitForOptions): Promise<void>;
2063
- /**
2064
- * SSE-based wait implementation. Subscribes to provisioning events and
2065
- * delivers progress callbacks while waiting for a target status.
2066
- */
2067
- private waitForWithSSE;
2068
- private hasReachedWaitTarget;
2069
- /**
2070
- * A running filesystem is not enough to serve a consumer. The API can
2071
- * expose `running` while the public edge is still pending, or after edge
2072
- * attachment failed. Keep that distinction in the SDK so every caller gets
2073
- * the same wait and error semantics.
2074
- */
2075
- private consumerConnectionReady;
2076
- private hasFreshStatus;
2077
- /**
2078
- * The check before a runtime call. A handle that has seen the sandbox
2079
- * running and ready dispatches at once: the authenticated runtime route
2080
- * checks current sandbox state itself, so a status GET before every call was
2081
- * a whole round trip through the Worker that only moved the same refusal
2082
- * earlier. A stale cache surfaces as the call's own answer, which the
2083
- * direct client and the prompt stream turn into a typed `StateError`. A
2084
- * handle that has not seen the status, or saw one that is not runnable,
2085
- * reads it first.
2182
+ * The token is short-lived and limited to the requested capabilities
2183
+ * — it cannot be used against admin endpoints (`/exec`, `/files`,
2184
+ * etc.) on the sandbox. Call `getMcpEndpoint()` again to rotate.
2185
+ *
2186
+ * Requires the sandbox to have been created with `capabilities`
2187
+ * including the requested capability (default: `computer_use`).
2188
+ *
2189
+ * @example
2190
+ * ```typescript
2191
+ * const ep = await box.getMcpEndpoint();
2192
+ * // Save ep.config to your IDE's mcp.json — that's it.
2193
+ * fs.writeFileSync("mcp.json", JSON.stringify(ep.config, null, 2));
2194
+ * ```
2086
2195
  */
2087
- private ensureRunning;
2088
- /** Why the status must be read before a runtime call, or undefined to trust the cache. */
2089
- private statusReadReason;
2090
- private assertRunnable;
2091
- private assertFilesystemIncarnationReady;
2196
+ getMcpEndpoint(options?: {
2197
+ capabilities?: ReadonlyArray<"computer_use">; /** Override server entry name (default: "tangle-sandbox"). */
2198
+ serverName?: string; /** Token TTL in minutes (server clamps to its policy). */
2199
+ ttlMinutes?: number;
2200
+ }): Promise<SandboxMcpEndpoint>;
2092
2201
  /**
2093
- * One authenticated runtime HTTP call for this sandbox, relative endpoint
2094
- * (`/agents/...`), scoped to the current filesystem incarnation. This is
2095
- * the transport `/agents/profiles` rides and the box surface mount
2096
- * delivery uses for profile-bundle cache claim/publish.
2202
+ * Fetch fresh TEE attestation evidence for this sandbox.
2203
+ *
2204
+ * When `attestationNonce` is supplied, the runtime must return evidence bound
2205
+ * to that challenge or fail closed if the selected TEE backend cannot support
2206
+ * nonce-bound report data. *
2207
+ * Throws `CapabilityError` (`TEE_UNSUPPORTED`) when the deployment does not
2208
+ * serve the TEE intercept — these paths are answered by a Tangle
2209
+ * confidential operator ahead of the sandbox API, which registers no route
2210
+ * for them. That refusal is recognised from the API's own unmatched-route
2211
+ * answer, so an intermediary that rewrites 404 bodies leaves the ordinary
2212
+ * `NotFoundError` in its place rather than the named refusal.
2097
2213
  */
2098
- runtimeFetch(path: string, options?: RequestInit, fetchOptions?: {
2099
- timeoutMs?: number;
2100
- }): Promise<Response>;
2214
+ getTeeAttestation(options?: TeeAttestationOptions): Promise<TeeAttestationResponse>;
2101
2215
  /**
2102
- * Delegates to the shared `parseSSEStream` in `lib/sse-parser.ts`
2103
- * — one canonical SSE implementation for the whole SDK. The
2104
- * shared parser throws `AbortError` on cancellation, while agent and task
2105
- * streams inspect the signal after iteration to decide whether to reconnect.
2106
- * This adapter converts cancellation to that local control flow and lets one
2107
- * malformed output frame be skipped without losing later valid output.
2216
+ * Fetch the TEE-bound public key used for sealed-secret encryption.
2217
+ *
2218
+ * The returned key includes an attestation report. Verify that report before
2219
+ * encrypting secrets to the key. *
2220
+ * Throws `CapabilityError` (`TEE_UNSUPPORTED`) when the deployment does not
2221
+ * serve the TEE intercept — these paths are answered by a Tangle
2222
+ * confidential operator ahead of the sandbox API, which registers no route
2223
+ * for them. That refusal is recognised from the API's own unmatched-route
2224
+ * answer, so an intermediary that rewrites 404 bodies leaves the ordinary
2225
+ * `NotFoundError` in its place rather than the named refusal.
2108
2226
  */
2109
- private parseSSEStream;
2227
+ getTeePublicKey(): Promise<TeePublicKeyResponse>;
2110
2228
  /**
2111
- * Associate a session ID with this sandbox so the Sandbox API can route
2112
- * subsequent WebSocket connections.
2113
- *
2114
- * @param opts - Session and sandbox routing identifiers
2229
+ * Bootstrap a real-time collaboration session for a file.
2230
+ * Returns the WebSocket URL and auth token needed to connect a
2231
+ * Hocuspocus/Yjs provider for live multi-user editing.
2115
2232
  *
2116
2233
  * @example
2117
2234
  * ```typescript
2118
- * await box.registerSessionMapping({
2119
- * sessionId: "sess_abc",
2120
- * runtimeSessionId: "runtime_abc",
2121
- * });
2235
+ * const collab = await box.collaborate("src/index.ts")
2236
+ * // Use collab.transport.websocketUrl + collab.transport.token
2237
+ * // with @hocuspocus/provider to connect
2122
2238
  * ```
2123
2239
  */
2124
- registerSessionMapping(opts: {
2125
- sessionId: string; /** The runtime (sidecar) session id this agent session routes to. */
2126
- runtimeSessionId: string; /** Optional container id for direct routing. */
2127
- sidecarId?: string; /** Optional projectRef so the server can detect a stale sidecar. */
2128
- projectRef?: string;
2129
- }): Promise<SessionMappingResult>;
2130
- /**
2131
- * Remove the sidecar session mapping for an agent session. Sandbox deletion
2132
- * also cleans mappings, so this is only needed to release a mapping while the
2133
- * sandbox stays alive.
2134
- */
2135
- unregisterSessionMapping(opts: {
2136
- sessionId: string;
2240
+ collaborate(path: string, options?: {
2241
+ access?: "read" | "write";
2137
2242
  }): Promise<{
2138
- success: boolean;
2139
- sessionId: string;
2243
+ documentId: string;
2244
+ transport: {
2245
+ websocketUrl: string;
2246
+ token: string;
2247
+ expiresAt: number;
2248
+ };
2249
+ permissions: {
2250
+ access: "read" | "write";
2251
+ canSnapshot: boolean;
2252
+ };
2140
2253
  }>;
2141
2254
  /**
2142
- * Parse a sandbox API payload into `SandboxInfo`.
2143
- *
2144
- * `carryCreateFacts` supplies the create-time facts a refresh must keep:
2145
- * the GPU lease, the startup diagnostics, and the create receipt each arrive
2146
- * once on the create response and are absent from every later payload. They
2147
- * describe ONE environment's creation, so they travel only when the payload
2148
- * describes that same environment. A payload for a different sandbox — a
2149
- * branch child parsed through its parent — passes no carry, or the child
2150
- * would report its parent's create verdict.
2255
+ * Refresh a collaboration token for an existing document session.
2151
2256
  */
2152
- private parseInfo;
2153
- private sleep;
2154
2257
  /**
2155
- * Get a session reference bound to this sandbox. Lazy: does not hit the
2156
- * network until you call a method on the returned `SandboxSession`.
2157
- * Use {@link sessions} to discover existing session ids.
2258
+ * Refresh a collaboration token. Access level is preserved from the original
2259
+ * token — cannot be escalated (read stays read, write stays write).
2158
2260
  */
2159
- session(id: string): SandboxSession;
2261
+ refreshCollaborationToken(documentId: string, currentToken: string): Promise<{
2262
+ token: string;
2263
+ expiresAt: number;
2264
+ access: "read" | "write";
2265
+ }>;
2160
2266
  /**
2161
- * Lines attached to this sandbox. `attach()` binds a line so Hub runs each
2162
- * member's messages here, one session per member.
2267
+ * Get SSH credentials for connecting to the sandbox.
2268
+ * Throws if SSH is not enabled or sandbox is not running.
2163
2269
  */
2164
- get lines(): SandboxLines;
2165
- /** Create an agent session and return both its handle and initial metadata. */
2166
- createSession(options: CreateSessionOptions): Promise<{
2167
- session: SandboxSession;
2168
- info: SessionInfo;
2169
- }>;
2170
- /** Delete an agent session by id. */
2171
- deleteSession(id: string): Promise<void>;
2172
- /** Get a lazy background-task session reference. */
2173
- taskSession(id: string): SandboxTaskSession;
2174
- /** Create a background task session. Dispatch work with `session.sendMessage()`. */
2175
- createTaskSession(options: CreateTaskSessionOptions): Promise<{
2176
- session: SandboxTaskSession;
2177
- info: TaskSessionInfo;
2178
- }>;
2270
+ ssh(): Promise<SSHCredentials>;
2271
+ sshCommand(): Promise<SSHCommandDescriptor>;
2272
+ }
2273
+ //#endregion
2274
+ //#region src/trace-exporter.d.ts
2275
+ type JsonObject = {
2276
+ [key: string]: JsonValue;
2277
+ };
2278
+ type TraceExportFormat = "tangle" | "otel-json";
2279
+ type TraceExportBundle = SandboxTraceBundle | SandboxFleetTraceBundle;
2280
+ interface TraceExportSink {
2281
+ url: string;
2282
+ headers?: Record<string, string>;
2283
+ format?: TraceExportFormat;
2284
+ serviceName?: string;
2285
+ timeoutMs?: number;
2286
+ fetch?: typeof fetch;
2287
+ }
2288
+ interface TraceExportResult {
2289
+ status: number;
2290
+ ok: boolean;
2291
+ body: string;
2292
+ }
2293
+ declare function buildTraceExportPayload(bundle: TraceExportBundle, format?: TraceExportFormat, serviceName?: string): TraceExportBundle | JsonObject;
2294
+ declare function exportTraceBundle(bundle: TraceExportBundle, sink: TraceExportSink): Promise<TraceExportResult>;
2295
+ declare function toOtelJson(bundle: TraceExportBundle, serviceName?: string): JsonObject;
2296
+ declare function otelTraceIdForTangleTrace(traceId: string): string;
2297
+ //#endregion
2298
+ //#region src/sandbox-trace.d.ts
2299
+ declare abstract class SandboxTraceCapabilities extends SandboxAccessCapabilities {
2300
+ trace(options?: SandboxTraceOptions): Promise<SandboxTraceBundle>;
2301
+ intelligence(): Promise<NonNullable<SandboxTraceBundle["intelligence"]>>;
2302
+ createIntelligenceReport(options?: {
2303
+ mode?: "deterministic" | "agentic";
2304
+ acknowledgeCost?: boolean;
2305
+ budget?: IntelligenceReportBudget;
2306
+ metadata?: Record<string, unknown>; /** Bound the analysis to a time window. */
2307
+ window?: IntelligenceReportWindow; /** Compare this sandbox against a same-type baseline sandbox. */
2308
+ compareTo?: IntelligenceReportCompareTo;
2309
+ }): Promise<IntelligenceReport>;
2310
+ createAgenticIntelligenceReport(options: {
2311
+ maxUsd: number;
2312
+ metadata?: Record<string, unknown>;
2313
+ }): Promise<IntelligenceReport>;
2314
+ exportTrace(sink: TraceExportSink): Promise<TraceExportResult>;
2179
2315
  /**
2180
- * List sessions on this sandbox, optionally filtering by status. Returns
2181
- * `SandboxSession` instances paired with their last-known
2182
- * {@link SessionInfo} so callers can avoid an extra round-trip per
2183
- * session for status.
2316
+ * Export the agent's conversation history from the sandbox filesystem.
2317
+ *
2318
+ * Each harness stores conversations in its own files:
2319
+ * Claude Code: ~/.claude/projects/<session-id>/ (JSONL)
2320
+ * Codex: ~/.codex/sessions/ (JSON)
2321
+ * OpenCode: ~/.local/share/opencode/storage/ (SQLite)
2322
+ *
2323
+ * This reads those files and returns them as a map of session-id to
2324
+ * conversation content, so the caller can persist them before deleting
2325
+ * the sandbox. Without this, conversation history dies with the sandbox.
2184
2326
  */
2185
- sessions(opts?: SessionListOptions): Promise<Array<{
2186
- session: SandboxSession;
2187
- info: SessionInfo;
2327
+ exportConversations(): Promise<Map<string, {
2328
+ format: string;
2329
+ content: string;
2188
2330
  }>>;
2331
+ }
2332
+ //#endregion
2333
+ //#region src/sandbox-egress.d.ts
2334
+ declare abstract class SandboxEgressCapabilities extends SandboxTraceCapabilities {
2189
2335
  /**
2190
- * Dispatch a prompt and return immediately with the session id (Issue
2191
- * #913 Gap 2). The sandbox keeps running the prompt after this call
2192
- * returns; reconnect via `box.session(id).events()` or wait for
2193
- * completion with `box.session(id).result()`.
2194
- *
2195
- * Skips the dispatch only on positive evidence that this work is
2196
- * already in flight or already finished — never on the mere existence
2197
- * of a session with the same id:
2336
+ * Egress policy manager for controlling outbound internet access.
2198
2337
  *
2199
- * 1. `opts.turnId` is set and the completed-turn cache has it → the
2200
- * turn already finished; return `dispatched: false`. This is the
2201
- * only durable idempotency key, and it outlives the session (the
2202
- * cache survives session eviction, see `findCompletedTurn`).
2203
- * 2. Otherwise, the session is in flight — `running`, or `queued` with a
2204
- * `latestExecutionId` — → a second dispatch would run two agents
2205
- * against one session, so return the live status with
2206
- * `dispatched: false`.
2338
+ * @example Read current egress policy
2339
+ * ```typescript
2340
+ * const { policy, source } = await box.egress.get();
2341
+ * console.log(policy.mode, source);
2342
+ * ```
2207
2343
  *
2208
- * Anything else dispatches. Two cases in particular:
2344
+ * @example Update egress policy at runtime
2345
+ * ```typescript
2346
+ * // strict reaches these plus the sandbox's own model endpoint, nothing else.
2347
+ * await box.egress.update({ mode: "strict", allowDomains: ["api.github.com"] });
2348
+ * ```
2349
+ */
2350
+ get egress(): EgressManager;
2351
+ }
2352
+ //#endregion
2353
+ //#region src/sandbox.d.ts
2354
+ /**
2355
+ * One fork of a running sandbox, reported with its fan-out accounting.
2356
+ *
2357
+ * `children` holds the sandboxes that exist. A partial fan-out is never
2358
+ * reported as a whole one: `complete` is false whenever `materializedCount` is
2359
+ * below `requestedCount`, and the caller decides what to do about the
2360
+ * shortfall.
2361
+ */
2362
+ interface ForkAcknowledgement extends ForkCounts {
2363
+ children: SandboxInstance[];
2364
+ /** Present only for a keyed fork against an API that reports it. */
2365
+ idempotency?: ForkIdempotency;
2366
+ }
2367
+ /**
2368
+ * A sandbox instance with methods for interaction.
2369
+ */
2370
+ declare class SandboxInstance extends SandboxEgressCapabilities {
2371
+ constructor(client: HttpClient, info: SandboxInfo, defaultRuntimeBackend?: BackendConfig);
2372
+ /**
2373
+ * Branch this RUNNING sandbox into `count` copy-on-write children
2374
+ * (Morph Infinibranch parity). Branch forks the live VM's memory into many
2375
+ * children at once via Firecracker UFFD copy-on-write: the children share the
2376
+ * parent's clean pages instead of each copying full guest memory. The parent
2377
+ * stays running.
2209
2378
  *
2210
- * - A `queued` session with no `latestExecutionId` was created or
2211
- * forked and has never run anything — the runtime writes exactly
2212
- * that state on `POST /agents/sessions` and on fork, and sets
2213
- * `latestExecutionId` at execution START. Refusing here would leave
2214
- * a pre-created session permanently undispatchable.
2215
- * - A terminal session is a finished conversation, and a new prompt
2216
- * into it is a new turn, not a retry.
2379
+ * Returns only the children. A fan-out that materialized fewer than `count`
2380
+ * still resolves — the children are real — so compare the array length, or
2381
+ * call {@link fork} for the explicit `complete` flag.
2217
2382
  *
2218
- * A caller that needs a completed dispatch to stay a no-op across
2219
- * retries MUST pass `turnId`; session existence cannot stand in for it,
2220
- * because an evicted session makes the same retry dispatch anyway.
2383
+ * @param count - Number of children to create (must be >= 1).
2384
+ * @param options - Per-child overrides.
2385
+ * @returns The new sandbox instances that materialized.
2221
2386
  *
2222
- * Read `dispatched`, not `alreadyExisted`, to tell "the prompt ran"
2223
- * from "we found prior work and did nothing".
2387
+ * @example
2388
+ * ```typescript
2389
+ * const [a, b, c] = await box.branch(3);
2390
+ * // a, b, c each share box's memory state at branch time
2391
+ * ```
2224
2392
  */
2225
- dispatchPrompt(message: string | PromptInputPart[], opts?: DispatchPromptOptions): Promise<DispatchedSession>;
2393
+ branch(count: number, options?: BranchOptions): Promise<SandboxInstance[]>;
2226
2394
  /**
2227
- * List messages for a session, including in-flight assistant content
2228
- * the agent is still streaming. Each entry's `metadata` carries the
2229
- * durability marker — `status: "streaming" | "completed" | "interrupted"`,
2230
- * `completed/interrupted` booleans, and the caller-supplied `turnId`
2231
- * when one was set. See `SessionMessage` for the full contract.
2395
+ * Branch this RUNNING sandbox and report the fan-out, not only the children.
2232
2396
  *
2233
- * Polling this is the right way to detect "did the sidecar die mid-
2234
- * turn?" — a SIGKILL leaves the assistant message with `status:
2235
- * "streaming"` and no `completed`/`interrupted` marker; a graceful
2236
- * abort stamps `interrupted: true` explicitly.
2397
+ * `complete` is false when fewer children materialized than were requested,
2398
+ * so a partial fan-out is never read as a whole one. With an
2399
+ * `idempotencyKey`, a retry of the same key and options returns exactly the
2400
+ * children the first request materialized and creates none.
2401
+ *
2402
+ * @example
2403
+ * ```typescript
2404
+ * const forked = await box.fork(5, { idempotencyKey: "run-42" });
2405
+ * if (!forked.complete) {
2406
+ * console.warn(`${forked.materializedCount} of ${forked.requestedCount}`);
2407
+ * }
2408
+ * ```
2237
2409
  */
2238
- messages(opts: ListMessagesOptions): Promise<SessionMessage[]>;
2239
- /** @internal — invoked by SandboxSession.sendMessage(). */
2240
- _sessionSendMessage(id: string, request: SendSessionMessageRequest, options?: SendSessionMessageOptions): Promise<SentSessionMessage>;
2241
- /** @internal — invoked by SandboxSession.delete(). */
2242
- _sessionDelete(id: string): Promise<void>;
2243
- /** @internal — invoked by SandboxTaskSession.changes(). */
2244
- _taskSessionChanges(id: string): Promise<TaskSessionChanges>;
2245
- /** @internal — invoked by SandboxTaskSession.commit(). */
2246
- _taskSessionCommit(id: string, options?: CommitTaskSessionOptions): Promise<TaskSessionCommitResult>;
2247
- _sessionFork(id: string, opts?: SessionForkOptions): Promise<SessionInfo>;
2410
+ fork(count: number, options?: BranchOptions): Promise<ForkAcknowledgement>;
2248
2411
  /**
2249
- * Look up a cached turn result by idempotency key. Returns the cached
2250
- * payload if a turn with this `turnId` previously completed on the
2251
- * given session; returns `null` if no such turn has finished yet
2252
- * (either it never started, or it interrupted before completion).
2412
+ * Create an advanced direct-runtime view of this sandbox.
2253
2413
  *
2254
- * Call this before re-issuing a `streamPrompt` / `prompt` / `task`
2255
- * that you might be retrying — a non-null result means the original
2256
- * attempt finished and you can return that to your caller instead of
2257
- * running the agent a second time. Only turns that reach the
2258
- * `completed` terminal state are cached; interrupted turns are not.
2414
+ * Runtime methods on the returned instance talk to the sandbox runtime
2415
+ * directly using `connection.execHost` when supplied, otherwise
2416
+ * `connection.runtimeUrl`, and the scoped `connection.authToken`.
2417
+ * Lifecycle methods still go through the parent SDK client.
2259
2418
  */
2260
- findCompletedTurn(turnId: string, opts: {
2261
- sessionId: string;
2262
- }): Promise<CompletedTurnResult | null>;
2419
+ direct(): SandboxInstance;
2420
+ }
2421
+ //#endregion
2422
+ //#region ../../../packages/runtime-contracts/dist/tangle-blueprint-abi.d.ts
2423
+ /**
2424
+ * Tangle blueprint wire contract shared by the orchestrator's Tangle driver and
2425
+ * the published sandbox SDK's Tangle client: job indices and the ABI
2426
+ * definitions for encoding/decoding the AgentSandbox blueprint's job inputs
2427
+ * and outputs, plus its contract views/events.
2428
+ */
2429
+ /** Job indices matching the blueprint's job IDs. */
2430
+ declare const JOB_SANDBOX_CREATE = 0;
2431
+ declare const JOB_SANDBOX_DELETE = 1;
2432
+ declare const SandboxCreateParamTypes: readonly [{
2433
+ readonly name: "request";
2434
+ readonly type: "tuple";
2435
+ readonly components: readonly [{
2436
+ readonly name: "name";
2437
+ readonly type: "string";
2438
+ }, {
2439
+ readonly name: "image";
2440
+ readonly type: "string";
2441
+ }, {
2442
+ readonly name: "stack";
2443
+ readonly type: "string";
2444
+ }, {
2445
+ readonly name: "agent_identifier";
2446
+ readonly type: "string";
2447
+ }, {
2448
+ readonly name: "env_json";
2449
+ readonly type: "string";
2450
+ }, {
2451
+ readonly name: "metadata_json";
2452
+ readonly type: "string";
2453
+ }, {
2454
+ readonly name: "ssh_enabled";
2455
+ readonly type: "bool";
2456
+ }, {
2457
+ readonly name: "ssh_public_key";
2458
+ readonly type: "string";
2459
+ }, {
2460
+ readonly name: "web_terminal_enabled";
2461
+ readonly type: "bool";
2462
+ }, {
2463
+ readonly name: "max_lifetime_seconds";
2464
+ readonly type: "uint64";
2465
+ }, {
2466
+ readonly name: "idle_timeout_seconds";
2467
+ readonly type: "uint64";
2468
+ }, {
2469
+ readonly name: "cpu_cores";
2470
+ readonly type: "uint64";
2471
+ }, {
2472
+ readonly name: "memory_mb";
2473
+ readonly type: "uint64";
2474
+ }, {
2475
+ readonly name: "disk_gb";
2476
+ readonly type: "uint64";
2477
+ }, {
2478
+ readonly name: "tee_required";
2479
+ readonly type: "bool";
2480
+ }, {
2481
+ readonly name: "tee_type";
2482
+ readonly type: "uint8";
2483
+ }, {
2484
+ readonly name: "attestation_nonce";
2485
+ readonly type: "string";
2486
+ }, {
2487
+ readonly name: "capabilities_json";
2488
+ readonly type: "string";
2489
+ }];
2490
+ }];
2491
+ declare const SandboxIdParamTypes: readonly [{
2492
+ readonly name: "request";
2493
+ readonly type: "tuple";
2494
+ readonly components: readonly [{
2495
+ readonly name: "sandbox_id";
2496
+ readonly type: "string";
2497
+ }];
2498
+ }];
2499
+ declare const SandboxCreateResponseParamTypes: readonly [{
2500
+ readonly name: "response";
2501
+ readonly type: "tuple";
2502
+ readonly components: readonly [{
2503
+ readonly name: "sandboxId";
2504
+ readonly type: "string";
2505
+ }, {
2506
+ readonly name: "json";
2507
+ readonly type: "string";
2508
+ }];
2509
+ }];
2510
+ declare const JsonResponseParamTypes: readonly [{
2511
+ readonly name: "response";
2512
+ readonly type: "tuple";
2513
+ readonly components: readonly [{
2514
+ readonly name: "json";
2515
+ readonly type: "string";
2516
+ }];
2517
+ }];
2518
+ declare const AgentSandboxBlueprintAbi: readonly [{
2519
+ readonly type: "function";
2520
+ readonly name: "getAvailableCapacity";
2521
+ readonly inputs: readonly [];
2522
+ readonly outputs: readonly [{
2523
+ readonly name: "available";
2524
+ readonly type: "uint32";
2525
+ }];
2526
+ readonly stateMutability: "view";
2527
+ }, {
2528
+ readonly type: "function";
2529
+ readonly name: "getServiceStats";
2530
+ readonly inputs: readonly [];
2531
+ readonly outputs: readonly [{
2532
+ readonly name: "totalSandboxes";
2533
+ readonly type: "uint32";
2534
+ }, {
2535
+ readonly name: "totalCapacity";
2536
+ readonly type: "uint32";
2537
+ }];
2538
+ readonly stateMutability: "view";
2539
+ }, {
2540
+ readonly type: "function";
2541
+ readonly name: "getOperatorLoad";
2542
+ readonly inputs: readonly [{
2543
+ readonly name: "operator";
2544
+ readonly type: "address";
2545
+ }];
2546
+ readonly outputs: readonly [{
2547
+ readonly name: "active";
2548
+ readonly type: "uint32";
2549
+ }, {
2550
+ readonly name: "max";
2551
+ readonly type: "uint32";
2552
+ }];
2553
+ readonly stateMutability: "view";
2554
+ }, {
2555
+ readonly type: "function";
2556
+ readonly name: "getSandboxOperator";
2557
+ readonly inputs: readonly [{
2558
+ readonly name: "sandboxId";
2559
+ readonly type: "string";
2560
+ }];
2561
+ readonly outputs: readonly [{
2562
+ readonly name: "";
2563
+ readonly type: "address";
2564
+ }];
2565
+ readonly stateMutability: "view";
2566
+ }, {
2567
+ readonly type: "function";
2568
+ readonly name: "isSandboxActive";
2569
+ readonly inputs: readonly [{
2570
+ readonly name: "sandboxId";
2571
+ readonly type: "string";
2572
+ }];
2573
+ readonly outputs: readonly [{
2574
+ readonly name: "";
2575
+ readonly type: "bool";
2576
+ }];
2577
+ readonly stateMutability: "view";
2578
+ }, {
2579
+ readonly type: "event";
2580
+ readonly name: "OperatorAssigned";
2581
+ readonly inputs: readonly [{
2582
+ readonly name: "serviceId";
2583
+ readonly type: "uint64";
2584
+ readonly indexed: true;
2585
+ }, {
2586
+ readonly name: "callId";
2587
+ readonly type: "uint64";
2588
+ readonly indexed: true;
2589
+ }, {
2590
+ readonly name: "operator";
2591
+ readonly type: "address";
2592
+ readonly indexed: true;
2593
+ }];
2594
+ }, {
2595
+ readonly type: "event";
2596
+ readonly name: "OperatorRouted";
2597
+ readonly inputs: readonly [{
2598
+ readonly name: "serviceId";
2599
+ readonly type: "uint64";
2600
+ readonly indexed: true;
2601
+ }, {
2602
+ readonly name: "callId";
2603
+ readonly type: "uint64";
2604
+ readonly indexed: true;
2605
+ }, {
2606
+ readonly name: "operator";
2607
+ readonly type: "address";
2608
+ readonly indexed: true;
2609
+ }];
2610
+ }, {
2611
+ readonly type: "event";
2612
+ readonly name: "SandboxCreated";
2613
+ readonly inputs: readonly [{
2614
+ readonly name: "sandboxHash";
2615
+ readonly type: "bytes32";
2616
+ readonly indexed: true;
2617
+ }, {
2618
+ readonly name: "operator";
2619
+ readonly type: "address";
2620
+ readonly indexed: true;
2621
+ }];
2622
+ }, {
2623
+ readonly type: "event";
2624
+ readonly name: "SandboxDeleted";
2625
+ readonly inputs: readonly [{
2626
+ readonly name: "sandboxHash";
2627
+ readonly type: "bytes32";
2628
+ readonly indexed: true;
2629
+ }, {
2630
+ readonly name: "operator";
2631
+ readonly type: "address";
2632
+ readonly indexed: true;
2633
+ }];
2634
+ }];
2635
+ //#endregion
2636
+ //#region src/tangle/abi.d.ts
2637
+ /**
2638
+ * Tangle Contract ABI Definitions
2639
+ *
2640
+ * Viem-compatible ABI for the ITangleJobs precompile.
2641
+ */
2642
+ declare const ITangleJobsAbi: readonly [{
2643
+ readonly type: "function";
2644
+ readonly name: "submitJob";
2645
+ readonly inputs: readonly [{
2646
+ readonly name: "serviceId";
2647
+ readonly type: "uint64";
2648
+ }, {
2649
+ readonly name: "jobIndex";
2650
+ readonly type: "uint8";
2651
+ }, {
2652
+ readonly name: "inputs";
2653
+ readonly type: "bytes";
2654
+ }];
2655
+ readonly outputs: readonly [{
2656
+ readonly name: "callId";
2657
+ readonly type: "uint64";
2658
+ }];
2659
+ readonly stateMutability: "payable";
2660
+ }, {
2661
+ readonly type: "function";
2662
+ readonly name: "getJobCall";
2663
+ readonly inputs: readonly [{
2664
+ readonly name: "serviceId";
2665
+ readonly type: "uint64";
2666
+ }, {
2667
+ readonly name: "callId";
2668
+ readonly type: "uint64";
2669
+ }];
2670
+ readonly outputs: readonly [{
2671
+ readonly name: "";
2672
+ readonly type: "tuple";
2673
+ readonly components: readonly [{
2674
+ readonly name: "jobIndex";
2675
+ readonly type: "uint8";
2676
+ }, {
2677
+ readonly name: "caller";
2678
+ readonly type: "address";
2679
+ }, {
2680
+ readonly name: "createdAt";
2681
+ readonly type: "uint64";
2682
+ }, {
2683
+ readonly name: "resultCount";
2684
+ readonly type: "uint32";
2685
+ }, {
2686
+ readonly name: "payment";
2687
+ readonly type: "uint256";
2688
+ }, {
2689
+ readonly name: "completed";
2690
+ readonly type: "bool";
2691
+ }];
2692
+ }];
2693
+ readonly stateMutability: "view";
2694
+ }, {
2695
+ readonly type: "event";
2696
+ readonly name: "JobSubmitted";
2697
+ readonly inputs: readonly [{
2698
+ readonly name: "serviceId";
2699
+ readonly type: "uint64";
2700
+ readonly indexed: true;
2701
+ }, {
2702
+ readonly name: "callId";
2703
+ readonly type: "uint64";
2704
+ readonly indexed: true;
2705
+ }, {
2706
+ readonly name: "jobIndex";
2707
+ readonly type: "uint8";
2708
+ readonly indexed: false;
2709
+ }, {
2710
+ readonly name: "caller";
2711
+ readonly type: "address";
2712
+ readonly indexed: false;
2713
+ }, {
2714
+ readonly name: "inputs";
2715
+ readonly type: "bytes";
2716
+ readonly indexed: false;
2717
+ }];
2718
+ }, {
2719
+ readonly type: "event";
2720
+ readonly name: "JobResultSubmitted";
2721
+ readonly inputs: readonly [{
2722
+ readonly name: "serviceId";
2723
+ readonly type: "uint64";
2724
+ readonly indexed: true;
2725
+ }, {
2726
+ readonly name: "callId";
2727
+ readonly type: "uint64";
2728
+ readonly indexed: true;
2729
+ }, {
2730
+ readonly name: "operator";
2731
+ readonly type: "address";
2732
+ readonly indexed: true;
2733
+ }, {
2734
+ readonly name: "result";
2735
+ readonly type: "bytes";
2736
+ readonly indexed: false;
2737
+ }];
2738
+ }];
2739
+ //#endregion
2740
+ //#region src/tangle/types.d.ts
2741
+ /**
2742
+ * Tangle Sandbox Client types and constants.
2743
+ */
2744
+ /** Tangle mainnet chain ID. */
2745
+ declare const TANGLE_CHAIN_ID = 5845;
2746
+ /** ITangleJobs precompile contract address. */
2747
+ declare const TANGLE_JOBS_CONTRACT: "0x0000000000000000000000000000000000000808";
2748
+ interface TangleSandboxClientConfig {
2749
+ /** Tangle service instance ID for the sandbox blueprint. */
2750
+ serviceId: bigint;
2751
+ /** viem WalletClient for browser environments. Mutually exclusive with privateKey. */
2752
+ wallet?: unknown;
2753
+ /** Hex-encoded private key for Node.js environments. Mutually exclusive with wallet. */
2754
+ privateKey?: `0x${string}`;
2755
+ /**
2756
+ * HTTP JSON-RPC endpoint for the Tangle chain. Required for both the
2757
+ * privateKey and wallet paths: the SDK ships no default endpoint because the
2758
+ * legacy public host was retired.
2759
+ */
2760
+ rpcUrl: string;
2761
+ /** Blueprint contract address for view calls (getAvailableCapacity, etc). */
2762
+ blueprintContractAddress?: `0x${string}`;
2763
+ /** ITangleJobs precompile address. Defaults to 0x...0808. */
2764
+ contractAddress?: `0x${string}`;
2765
+ /** Max time to wait for a job to complete. No hard limit — agent jobs can run hours. Default: 14400000 (4h). */
2766
+ jobTimeoutMs?: number;
2767
+ /** Interval between job completion polls. Default: 5000 (5s). */
2768
+ pollIntervalMs?: number;
2769
+ /**
2770
+ * Operator API base URL for routes that must be handled by the Blueprint
2771
+ * operator rather than the sidecar directly, such as nonce-bound TEE
2772
+ * attestation.
2773
+ */
2774
+ operatorApiUrl?: string;
2775
+ /** Bearer token for the operator API session. */
2776
+ operatorApiToken?: string;
2777
+ }
2778
+ //#endregion
2779
+ //#region src/tangle/client.d.ts
2780
+ declare class TangleSandboxClient implements HttpClient {
2781
+ #private;
2782
+ private readonly chain;
2783
+ private readonly operatorApiUrl?;
2784
+ private operatorSession;
2785
+ constructor(config: TangleSandboxClientConfig);
2263
2786
  /**
2264
- * Drive a detached turn forward by exactly one settle → poll → dispatch
2265
- * pass and report where it stands. Built for tick-based callers —
2266
- * Cloudflare Workflows steps, queue consumers, crons — that re-invoke
2267
- * on their own schedule instead of holding a stream open.
2268
- * The pass does not poll repeatedly or keep a connection alive.
2269
- * Session admission may retry one classified pre-dispatch credential refusal.
2787
+ * Create a sandbox via on-chain job submission.
2270
2788
  *
2271
- * The pass resolves to the first of:
2272
- * 1. The completed-turn cache has `turnId` → `completed`, or `failed`
2273
- * when the cached payload carries no text — that result is final,
2274
- * so a retry cannot improve it.
2275
- * 2. The session is queued/running → `running`, after enforcing
2276
- * `wallCapMs`: a session past the cap is cancelled and reported
2277
- * `failed`.
2278
- * 3. The session is terminal without a cached turn → settle from the
2279
- * session result; an unsuccessful result is `failed`.
2280
- * 4. No session exists, or one exists that was created/forked but never
2281
- * ran (`queued` with no `latestExecutionId`) → dispatch
2282
- * fire-and-detach → `running`.
2789
+ * Secrets never ride the chain: `options.tangleSecrets` is delivered to the
2790
+ * operator's 2-phase provisioning endpoint over an EIP-191-authenticated
2791
+ * session after the job completes (requires `operatorApiUrl`). Everything
2792
+ * in `options.env` IS published on-chain in the job calldata — secret-shaped
2793
+ * keys there trigger a warning pointing at `tangleSecrets`.
2794
+ */
2795
+ create(options?: CreateSandboxOptions): Promise<SandboxInstance>;
2796
+ /**
2797
+ * Get a sandbox by id. Rehydrates from the operator API when configured so
2798
+ * app servers can resolve sandboxes created by earlier requests.
2799
+ */
2800
+ get(id: string): Promise<SandboxInstance | null>;
2801
+ /**
2802
+ * Route interception for SandboxInstance lifecycle calls.
2283
2803
  *
2284
- * `failed` is always deterministic: re-invoking with the same ids
2285
- * returns the same outcome rather than starting a second agent run, so
2286
- * callers can treat it as terminal without their own retry bookkeeping.
2804
+ * SandboxInstance calls this.client.fetch() for:
2805
+ * - GET /v1/sandboxes/:id → return from local tracking
2806
+ * - POST /v1/sandboxes/:id/stop → unsupported until blueprint exposes stop
2807
+ * - POST /v1/sandboxes/:id/resume → unsupported until blueprint exposes resume
2808
+ * - DELETE /v1/sandboxes/:id → on-chain JOB_SANDBOX_DELETE
2287
2809
  */
2288
- driveTurn(message: string | PromptInputPart[], opts: DriveTurnOptions): Promise<TurnDriveResult>;
2810
+ fetch(path: string, options?: RequestInit): Promise<Response>;
2811
+ private fetchRuntime;
2289
2812
  /**
2290
- * Ask the initialized provider to prepare this turn's public native profile
2291
- * before admission. Pass both returned expected digests to driveConversationTurn.
2813
+ * Get available capacity from the blueprint contract.
2814
+ * Requires blueprintContractAddress in config.
2292
2815
  */
2293
- preparePublicProfileRevision(opts: {
2294
- sessionId: string;
2295
- backend: Partial<BackendConfig>;
2296
- model?: ConversationTurnOptions["model"];
2297
- }): Promise<{
2298
- expectedPublicProfileRequestDigest: `sha256:${string}`;
2299
- expectedPublicProfileRevision: {
2300
- workspacePlanDigest: `sha256:${string}`;
2301
- materializedDigest: `sha256:${string}`;
2302
- launchDigest: string;
2303
- };
2304
- conflicts: PublicProfileConflict[];
2816
+ getAvailableCapacity(): Promise<number>;
2817
+ /**
2818
+ * Get service stats from the blueprint contract.
2819
+ * Requires blueprintContractAddress in config.
2820
+ */
2821
+ getServiceStats(): Promise<{
2822
+ totalSandboxes: number;
2823
+ totalCapacity: number;
2305
2824
  }>;
2306
- /** Prepare a secret-bearing native revision without starting a model turn. */
2307
- prepareSecretProfileRevision(opts: {
2308
- sessionId: string;
2309
- backend: TurnBackendConfig;
2310
- model?: ConversationTurnOptions["model"];
2311
- }): Promise<{
2312
- expectedPublicProfileRequestDigest: `sha256:${string}`;
2313
- expectedSecretProfileReceipt: `hmac-sha256:${string}`;
2314
- workspacePlanDigest: `sha256:${string}`;
2315
- conflicts: Array<{
2316
- relPath: string;
2317
- copyRelPath: string;
2318
- reason: "existing" | "symlink";
2319
- }>;
2825
+ /**
2826
+ * Mint or reuse the EIP-191 session for the operator API.
2827
+ *
2828
+ * The session is signed by the SAME key that submits jobs (`chain.signMessage`),
2829
+ * so the operator binds it to every sandbox this client created.
2830
+ */
2831
+ private getOperatorSession;
2832
+ /**
2833
+ * Deliver secrets to a sandbox via the operator's 2-phase provisioning
2834
+ * endpoint (`POST /api/sandboxes/:id/secrets`).
2835
+ *
2836
+ * Unlike `env`, these values never appear on-chain: they ride TLS to the
2837
+ * operator, which validates the session's recovered address against the
2838
+ * sandbox's on-chain creator before injecting.
2839
+ */
2840
+ injectSecrets(sandboxId: string, secrets: Record<string, string>): Promise<void>;
2841
+ /** Read a sandbox's provisioned secret keys and credential availability. */
2842
+ getSecrets(sandboxId: string): Promise<{
2843
+ sandboxId: string;
2844
+ envJson: Record<string, unknown>;
2845
+ credentialsAvailable: boolean;
2320
2846
  }>;
2321
- /** Advance exactly the named turn while retaining the native conversation.
2322
- * Admission receipts are independent of expiring event logs. A previous
2323
- * turn's terminal session status cannot settle a newly submitted message. */
2324
- driveConversationTurn(message: string | PromptInputPart[], opts: ConversationTurnOptions): Promise<ConversationTurnResult>;
2325
- private driveConversationTurnPass;
2326
2847
  /**
2327
- * Mint a scoped, time-bounded JWT for browser access (Issue #913 Gap 1).
2328
- * Authority is the caller's `TANGLE_API_KEY` (sk-tan-*); signing secrets
2329
- * stay server-side. Session/project scopes work with SessionGatewayClient,
2330
- * while session-runtime/read-only scopes work with SandboxRuntimeClient.
2848
+ * Run an operator-API request with a session, retrying once with a fresh
2849
+ * session on 401 (expired PASETO). Any other failure names the sandbox so
2850
+ * the caller can retry without losing the ID.
2331
2851
  */
2332
- mintScopedToken(opts: MintScopedTokenOptions): Promise<ScopedToken>;
2333
- /** @internal — invoked by SandboxSession.status(). */
2334
- _sessionStatus(id: string): Promise<SessionInfo | null>;
2335
- /** @internal — invoked before the sandbox is deleted. */
2336
- _sessionExportRawEvidence(id: string, destination: string, options: RawEvidenceExportOptions): Promise<RawEvidenceDirectoryExport>;
2337
- _sessionRawEvidence(id: string): Promise<RawEvidenceExport>;
2338
- /** @internal — invoked by SandboxSession.runs(). */
2339
- _sessionRuns(id: string): Promise<SessionExecutionInfo[]>;
2340
- /** @internal — invoked by SandboxSession.admission(). */
2341
- _sessionAdmission(id: string, turnId: string, options?: {
2342
- signal?: AbortSignal;
2343
- }): Promise<SessionMessageAdmission | null>;
2344
- /** @internal — invoked by SandboxSession.events(). */
2345
- _sessionEvents(id: string, opts?: SessionEventStreamOptions, stopOnTurnTerminal?: boolean): AsyncGenerator<SandboxEvent>;
2346
- /** Replay one execution without subscribing to other runs on its session. */
2347
- private _executionEvents;
2348
- /** @internal — invoked by SandboxSession.result(). */
2349
- _sessionResult(id: string, options?: SessionResultOptions, knownSession?: SessionInfo): Promise<PromptResult>;
2350
- /** @internal — delegated to the native interactive operations module. */
2351
- _startInteractive(id: string, options: InteractiveSessionStartOptions, requestOptions?: InteractiveRequestOptions): Promise<InteractiveSessionStartResult>;
2352
- /** @internal — delegated to the native interactive operations module. */
2353
- _sendInteractivePrompt(id: string, command: InteractivePromptCommand, options?: InteractiveRequestOptions): Promise<AgentInteractiveSessionPromptAcknowledgement>;
2354
- /** @internal — delegated to the native interactive operations module. */
2355
- _claimInteractiveControl(id: string, request: AgentInteractiveSessionControlClaimRequest, options?: InteractiveControlClaimOptions): Promise<AgentInteractiveSessionControlClaimAcknowledgement>;
2356
- /** @internal — delegated to the native interactive operations module. */
2357
- _releaseInteractiveControl(id: string, ref: AgentInteractiveSessionRef, control: AgentInteractiveSessionControlClaim, options?: InteractiveRequestOptions): Promise<void>;
2358
- /** @internal — delegated to the native interactive operations module. */
2359
- _validateInteractiveControl(id: string, ref: AgentInteractiveSessionRef, control: AgentInteractiveSessionControlClaim, options?: InteractiveRequestOptions): Promise<void>;
2360
- /** @internal — delegated to the native interactive operations module. */
2361
- _interactiveStatus(id: string, incarnationId: string, options?: InteractiveRequestOptions): Promise<InteractiveSessionStatus | null>;
2362
- /** @internal — delegated to the native interactive operations module. */
2363
- _attachInteractive(id: string, ref: AgentInteractiveSessionRef, request: InteractiveAttachOptions, options?: InteractiveRequestOptions, reconnectAuthority?: TerminalStreamReconnectAuthority): Promise<TerminalStream>;
2364
- /** @internal — read exact terminal facts from the runtime-owned manager. */
2365
- _interactiveTerminalInfo(environmentId: string, terminalId: string, options?: InteractiveRequestOptions): Promise<InteractiveTerminalMetadata | null>;
2366
- /** @internal — delegated to the native interactive operations module. */
2367
- _attachTerminal(connectionId: string, options?: SandboxTerminalAttachOptions): Promise<TerminalStream>;
2368
- /** @internal — delegated to the native interactive operations module. */
2369
- _stopInteractive(id: string, command: InteractiveStopCommand, options?: InteractiveRequestOptions): Promise<AgentInteractiveSessionStopAcknowledgement>;
2370
- /** @internal — delegated to the native interactive operations module. */
2371
- _stopInteractiveLifecycle(id: string, ref: AgentInteractiveSessionRef, options?: InteractiveRequestOptions): Promise<AgentInteractiveSessionStopAcknowledgement>;
2372
- private interactionTransport;
2373
- /** @internal — invoked by SandboxSession.interactions(). */
2374
- _listInteractions(id: string, options?: {
2375
- signal?: AbortSignal;
2376
- }): Promise<InteractionRequest[]>;
2377
- /** @internal — invoked by SandboxSession.respondToInteraction(). */
2378
- _respondToInteraction(id: string, command: InteractionResponseCommand, options?: {
2379
- signal?: AbortSignal;
2380
- }): Promise<SandboxInteractionCommandResult>;
2381
- /** @internal — invoked by SandboxSession.respondToPermission(). */
2382
- _respondToPermission(id: string, permissionID: string, options: RespondToPermissionOptions): Promise<SandboxInteractionResult>;
2383
- /** @internal — invoked by SandboxSession.interrupt(). */
2384
- _interrupt(id: string, options?: SessionInterruptOptions): Promise<InterruptResult>;
2385
- /** @internal — invoked by SandboxSession.cancelRun(). */
2386
- _cancelRun(id: string, request: AgentRunCancellationRequest, options?: {
2387
- signal?: AbortSignal;
2388
- }): Promise<AgentRunCancellationAcknowledgement>;
2389
- /** @internal — invoked by SandboxSession.answer(). */
2390
- _answerQuestion(id: string, interactionId: string, answers: InteractionData, options?: {
2391
- signal?: AbortSignal;
2392
- }): Promise<SandboxInteractionResult>;
2393
- /** @internal — invoked by SandboxSession.plan(). */
2394
- _currentPlan(sessionId: string): Promise<DurablePlan | null>;
2395
- /** @internal — invoked by SandboxSession.approvePlan()/rejectPlan(). */
2396
- _decidePlan(sessionId: string, planId: string, decision: {
2397
- outcome: "approved";
2398
- } | {
2399
- outcome: "rejected";
2400
- feedback: string;
2401
- }, options?: DurablePlanDecisionOptions): Promise<DurablePlanDecisionResult>;
2852
+ private withOperatorSession;
2853
+ private fetchOperatorApi;
2854
+ }
2855
+ //#endregion
2856
+ //#region src/tangle/operator-auth.d.ts
2857
+ /**
2858
+ * Operator API session auth — the client half of the operator's EIP-191
2859
+ * challenge-response flow (`sandbox-runtime/src/session_auth`).
2860
+ *
2861
+ * Flow (matches the operator exactly):
2862
+ * 1. `POST /api/auth/challenge` → `{ nonce, message, expires_at }`
2863
+ * 2. Sign `message` with the job submitter's key (EIP-191 personal_sign,
2864
+ * 65-byte `r ‖ s ‖ v`)
2865
+ * 3. `POST /api/auth/session` `{ nonce, signature }` →
2866
+ * `{ token, address, expires_at }` (PASETO bearer, 1h)
2867
+ * 4. `Authorization: Bearer <token>`
2868
+ *
2869
+ * The operator recovers the signer address from the signature and binds every
2870
+ * sandbox operation to it: `require_sandbox_owner` rejects any session whose
2871
+ * address is not the sandbox's on-chain creator. So a session minted from the
2872
+ * same key that submitted the create job can read/inject that sandbox's
2873
+ * secrets — and nothing else.
2874
+ */
2875
+ /** Challenge payload served by `POST /api/auth/challenge`. */
2876
+ interface OperatorChallenge {
2877
+ nonce: string;
2878
+ message: string;
2879
+ expires_at: number;
2880
+ }
2881
+ /** Session payload served by `POST /api/auth/session`. */
2882
+ interface OperatorSessionToken {
2883
+ token: string;
2884
+ address: string;
2885
+ expires_at: number;
2886
+ }
2887
+ /** Signs an arbitrary message with EIP-191 personal_sign semantics. */
2888
+ type SignMessage = (message: string) => Promise<`0x${string}`>;
2889
+ declare class OperatorSessionError extends Error {
2890
+ readonly status?: number | undefined;
2891
+ constructor(message: string, status?: number | undefined);
2892
+ }
2893
+ /**
2894
+ * A bearer session with the blueprint operator API, minted by proving control
2895
+ * of the job submitter's key. Establish lazily and reuse until near expiry;
2896
+ * the caller retries with a fresh session on 401.
2897
+ */
2898
+ declare class OperatorSession {
2899
+ #private;
2900
+ private readonly address;
2901
+ private readonly expiresAtMs;
2902
+ private constructor();
2903
+ get signerAddress(): string;
2904
+ /** True when the token is within the refresh margin of expiry. */
2905
+ needsRefresh(nowMs?: number): boolean;
2906
+ authorizationHeader(): string;
2907
+ /**
2908
+ * Run the challenge-response flow against an operator API base URL.
2909
+ *
2910
+ * `signMessage` must implement EIP-191 personal_sign with the SAME key that
2911
+ * submitted the sandbox create job — the operator binds ownership to the
2912
+ * recovered address, so any other key yields a session that owns nothing.
2913
+ */
2914
+ static establish(baseUrl: string, signMessage: SignMessage, fetchImpl?: typeof fetch): Promise<OperatorSession>;
2915
+ }
2916
+ //#endregion
2917
+ //#region src/tangle/rfq.d.ts
2918
+ /**
2919
+ * RFQ quote primitives for tnt-core's `JobsRFQ` marketplace flow.
2920
+ *
2921
+ * These helpers fetch, hash, and validate operator quotes. Callers remain
2922
+ * responsible for preparing and submitting on-chain transactions.
2923
+ *
2924
+ * The EIP-712 hashing here is pinned byte-for-byte against the Rust SDK
2925
+ * (blueprint `tangle-extra::job_quote`, digest fixture in
2926
+ * `tangle-rfq.test.ts`) and against `SignatureLib` in tnt-core. Never change
2927
+ * the typed-data shape without regenerating all three.
2928
+ */
2929
+ type Address = `0x${string}`;
2930
+ type Hash = `0x${string}`;
2931
+ /** EIP-712 domain — identical to tnt-core `Base.sol`: name "TangleQuote", version "1". */
2932
+ interface QuoteDomain {
2933
+ chainId: number;
2934
+ verifyingContract: Address;
2935
+ }
2936
+ /** Mirrors `JobQuoteDetails` in tnt-core `SignatureLib` (field-for-field). */
2937
+ interface JobQuoteDetails {
2938
+ requester: Address;
2939
+ serviceId: bigint;
2940
+ jobIndex: number;
2941
+ /** Price in the chain native unit's smallest denomination; wire values use
2942
+ * decimal strings to survive JSON transport without precision loss. */
2943
+ price: bigint;
2944
+ timestamp: bigint;
2945
+ expiry: bigint;
2946
+ /** tnt-core `ConfidentialityPolicy`: 0 Any, 1 TEE required, 2 Standard required, 3 TEE preferred. */
2947
+ confidentiality: 0 | 1 | 2 | 3;
2948
+ inputsHash: Hash;
2402
2949
  }
2950
+ /** A signed quote as served by the operator's `/api/quote`. */
2951
+ interface SignedQuote {
2952
+ details: JobQuoteDetails;
2953
+ /** 65-byte `r ‖ s ‖ v` hex — exactly what `submitJobFromQuote` expects. */
2954
+ signature: `0x${string}`;
2955
+ operator: Address;
2956
+ /** Operator-reported live capacity at quote time (informational). */
2957
+ capacity?: {
2958
+ active: number;
2959
+ max: number;
2960
+ };
2961
+ }
2962
+ declare class QuoteError extends Error {
2963
+ readonly code: "QUOTE_REJECTED" | "QUOTE_SIGNATURE_INVALID" | "QUOTE_EXPIRED" | "QUOTE_MISMATCH";
2964
+ constructor(message: string, code: "QUOTE_REJECTED" | "QUOTE_SIGNATURE_INVALID" | "QUOTE_EXPIRED" | "QUOTE_MISMATCH");
2965
+ }
2966
+ /**
2967
+ * The EIP-712 digest of a quote — matches
2968
+ * `job_quote_digest_eip712` (Rust SDK) and `computeJobQuoteDigest` (tnt-core).
2969
+ */
2970
+ declare function jobQuoteDigest(details: JobQuoteDetails, domain: QuoteDomain): Hash;
2971
+ /** Parse the operator's `/api/quote` JSON without fabricating missing values. */
2972
+ declare function parseQuoteResponse(raw: Record<string, unknown>): SignedQuote;
2973
+ /** keccak256 of the exact ABI-encoded job inputs — what quotes bind to. */
2974
+ declare function inputsHashOf(encodedInputs: `0x${string}`): Hash;
2975
+ /**
2976
+ * Validate a quote before paying for it: fresh (not expired), addressed to
2977
+ * the buyer, for the exact inputs about to be submitted, on the expected
2978
+ * service/job, and signed by the operator it names.
2979
+ *
2980
+ * Signature verification uses viem's offline EOA recovery and compares the
2981
+ * signer against the same digest the chain checks.
2982
+ */
2983
+ declare function validateQuote(args: {
2984
+ quote: SignedQuote;
2985
+ domain: QuoteDomain; /** The buyer's address — must equal `details.requester`. */
2986
+ buyer: Address;
2987
+ serviceId: bigint;
2988
+ jobIndex: number;
2989
+ inputsHash: Hash;
2990
+ now?: number;
2991
+ }): Promise<void>;
2992
+ /** Query one operator for a quote over HTTP. */
2993
+ declare function fetchQuote(operatorApiUrl: string, params: {
2994
+ requester: Address;
2995
+ jobIndex: number; /** 0x-hex ABI-encoded job inputs, or a precomputed keccak256 hash. */
2996
+ inputs?: `0x${string}`;
2997
+ inputsHash?: Hash;
2998
+ confidentiality?: JobQuoteDetails["confidentiality"];
2999
+ fetchImpl?: typeof fetch;
3000
+ }): Promise<SignedQuote>;
2403
3001
  //#endregion
2404
- export { BuildControlPlaneMcpConfigOptions as $, InteractivePromptCommand as A, InteractiveStopCommand as B, splitInlineProfileFileMounts as C, SandboxOperationFailedError as D, SandboxOperation as E, InteractiveSessionIncarnationId as F, InteractiveTerminalFrameLog as G, RespondToPermissionOptions as H, InteractiveSessionInfo as I, createInteractiveTerminalSession as J, InteractiveTerminalMetadata as K, InteractiveSessionRef as L, InteractiveSessionHandle as M, InteractiveSessionHandleOptions as N, AgentInteractiveTerminalSession$1 as O, InteractiveSessionHost as P, SandboxInteractionResult as Q, InteractiveSessionStartOptions as R, materializeProfileFileMounts as S, validateDeferredProfileFileMounts as T, agentInteractiveSessionPromptRequestDigest as U, InterruptResult as V, InteractiveTerminalCapture as W, SandboxInteractionConflict as X, SandboxInteractionCommandResult as Y, SandboxInteractionResolution as Z, ProfileFileDeliveryReport as _, WorkspaceImagePublishResult as a, SandboxMcpServerEntry as at, SplitInlineProfileFileMountsResult as b, TraceExportResult as c, exportTraceBundle as d, BuildSandboxMcpConfigOptions as et, otelTraceIdForTangleTrace as f, SandboxSession as g, RawEvidenceExport as h, WorkspaceImagePublishRequestOptions as i, SandboxMcpEndpoint as it, InteractiveSessionControlClaim as j, InteractiveControlClaimRequest as k, TraceExportSink as l, SandboxTaskSession as m, SandboxInstance as n, SANDBOX_MCP_SERVER_NAME as nt, WorkspaceImages as o, buildControlPlaneMcpConfig as ot, toOtelJson as p, createInteractiveTerminalCapture as q, WorkspaceImagePublishInput as r, SandboxMcpConfig as rt, TraceExportFormat as s, buildSandboxMcpConfig as st, ForkAcknowledgement as t, CONTROL_PLANE_MCP_SERVER_NAME as tt, buildTraceExportPayload as u, MaterializeProfileFileMountsOptions as v, splitInlineProfileSkills as w, SplitInlineProfileSkillsResult as x, MaterializeProfileFileMountsResult as y, InteractiveSessionStartResult as z };
3002
+ export { SandboxInteractionResult as $, TraceExportResult as A, buildControlPlaneMcpConfig as At, WorkspaceImages as B, JsonResponseParamTypes as C, BuildControlPlaneMcpConfigOptions as Ct, ForkAcknowledgement as D, SandboxMcpConfig as Dt, SandboxIdParamTypes as E, SANDBOX_MCP_SERVER_NAME as Et, toOtelJson as F, SplitInlineProfileFileMountsResult as G, MaterializeProfileFileMountsOptions as H, SandboxTaskSession as I, splitInlineProfileSkills as J, SplitInlineProfileSkillsResult as K, RawEvidenceExport as L, buildTraceExportPayload as M, exportTraceBundle as N, SandboxInstance as O, SandboxMcpEndpoint as Ot, otelTraceIdForTangleTrace as P, SandboxInteractionResolution as Q, SandboxSession as R, JOB_SANDBOX_DELETE as S, SandboxOperationFailedError as St, SandboxCreateResponseParamTypes as T, CONTROL_PLANE_MCP_SERVER_NAME as Tt, MaterializeProfileFileMountsResult as U, ProfileFileDeliveryReport as V, ProfileFileMountBox as W, SandboxInteractionCommandResult as X, validateDeferredProfileFileMounts as Y, SandboxInteractionConflict as Z, TANGLE_JOBS_CONTRACT as _, InteractiveTerminalFrameLog as _t, fetchQuote as a, InteractiveSessionHandleOptions as at, AgentSandboxBlueprintAbi as b, createInteractiveTerminalSession as bt, parseQuoteResponse as c, InteractiveSessionInfo as ct, OperatorSession as d, InteractiveSessionStartResult as dt, AgentInteractiveTerminalSession$1 as et, OperatorSessionError as f, InteractiveStopCommand as ft, TANGLE_CHAIN_ID as g, InteractiveTerminalCapture as gt, TangleSandboxClient as h, agentInteractiveSessionPromptRequestDigest as ht, SignedQuote as i, InteractiveSessionHandle as it, TraceExportSink as j, buildSandboxMcpConfig as jt, TraceExportFormat as k, SandboxMcpServerEntry as kt, validateQuote as l, InteractiveSessionRef as lt, SignMessage as m, RespondToPermissionOptions as mt, QuoteDomain as n, InteractivePromptCommand as nt, inputsHashOf as o, InteractiveSessionHost as ot, OperatorSessionToken as p, InterruptResult as pt, splitInlineProfileFileMounts as q, QuoteError as r, InteractiveSessionControlClaim as rt, jobQuoteDigest as s, InteractiveSessionIncarnationId as st, JobQuoteDetails as t, InteractiveControlClaimRequest as tt, OperatorChallenge as u, InteractiveSessionStartOptions as ut, TangleSandboxClientConfig as v, InteractiveTerminalMetadata as vt, SandboxCreateParamTypes as w, BuildSandboxMcpConfigOptions as wt, JOB_SANDBOX_CREATE as x, SandboxOperation as xt, ITangleJobsAbi as y, createInteractiveTerminalCapture as yt, WorkspaceImagePublishRequestOptions as z };