@tangle-network/sandbox 0.9.4-develop.20260710231333.22d131b → 0.9.4-develop.20260711192548.3c9ec78

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.
@@ -794,6 +794,110 @@ interface SandboxInfo {
794
794
  /** Source of the egress policy */
795
795
  egressPolicySource?: "sandbox" | "team" | "platform";
796
796
  }
797
+ /** Basic health reported by the runtime inside a sandbox. */
798
+ interface SandboxRuntimeHealth {
799
+ status: string;
800
+ docker: {
801
+ enabled: boolean;
802
+ status: string;
803
+ dockerHost?: string;
804
+ error?: string;
805
+ };
806
+ backends: {
807
+ total: number;
808
+ byType: Record<string, number>;
809
+ pending: number;
810
+ };
811
+ timestamp: string;
812
+ }
813
+ /** Public preview link associated with a listening runtime port. */
814
+ interface SandboxPortPreviewLink {
815
+ previewId: string;
816
+ url: string;
817
+ status: string;
818
+ }
819
+ /** One process listening on a port inside a sandbox. */
820
+ interface SandboxPortBinding {
821
+ pid: number;
822
+ processName: string;
823
+ commandPath: string;
824
+ port: number;
825
+ protocol: "tcp" | "udp";
826
+ localAddress: string;
827
+ family: "tcp4" | "tcp6" | "udp4" | "udp6";
828
+ allowlisted: boolean;
829
+ firstSeenAt: string;
830
+ lastSeenAt: string;
831
+ previewLink?: SandboxPortPreviewLink;
832
+ }
833
+ /** Options for creating an interactive terminal. */
834
+ interface SandboxTerminalCreateOptions {
835
+ name?: string;
836
+ description?: string;
837
+ shell?: string;
838
+ cwd?: string;
839
+ cols?: number;
840
+ rows?: number;
841
+ }
842
+ /** Runtime request context used to attribute terminal events to an agent session. */
843
+ interface SandboxTerminalRequestOptions {
844
+ sessionId?: string;
845
+ }
846
+ /** Interactive terminal metadata returned by the runtime. */
847
+ interface SandboxTerminalInfo {
848
+ sessionId: string;
849
+ connectionId?: string;
850
+ name?: string;
851
+ description?: string;
852
+ shell?: string;
853
+ command?: string;
854
+ cwd?: string;
855
+ cols?: number;
856
+ rows?: number;
857
+ createdAt?: string;
858
+ lastActivityAt?: string;
859
+ isRunning?: boolean;
860
+ exitCode?: number;
861
+ exitSignal?: string;
862
+ /** WebSocket path for terminal input/output. */
863
+ streamUrl?: string;
864
+ history?: unknown[];
865
+ }
866
+ /** Interactive terminal operations. Input/output flows over `streamUrl`. */
867
+ interface SandboxTerminalManager {
868
+ create(options?: SandboxTerminalCreateOptions, request?: SandboxTerminalRequestOptions): Promise<SandboxTerminalInfo>;
869
+ /** Send input through the runtime's HTTP fallback for an existing terminal. */
870
+ input(terminalId: string, data: string, request?: SandboxTerminalRequestOptions): Promise<void>;
871
+ list(): Promise<SandboxTerminalInfo[]>;
872
+ get(sessionId: string): Promise<SandboxTerminalInfo | null>;
873
+ }
874
+ /** Runtime-local agent profile. */
875
+ interface SandboxRuntimeProfile {
876
+ name: string;
877
+ description?: string;
878
+ systemPrompt?: string;
879
+ tools?: string[];
880
+ mcpServers?: string[];
881
+ env?: Record<string, string>;
882
+ model?: {
883
+ provider?: string;
884
+ model?: string;
885
+ };
886
+ }
887
+ /** Runtime-local profile listing and selected default. */
888
+ interface SandboxRuntimeProfileList {
889
+ profiles: SandboxRuntimeProfile[];
890
+ defaultProfile?: string;
891
+ }
892
+ /** Profile summary returned before a sandbox runtime exists. */
893
+ interface SandboxProfileSummary {
894
+ id: string;
895
+ name: string;
896
+ description?: string;
897
+ model?: string;
898
+ tags?: string[];
899
+ extends?: string;
900
+ }
797
901
  /**
798
902
  * Raw TEE attestation evidence returned by the sandbox runtime.
799
903
  *
@@ -1618,6 +1722,136 @@ interface SessionListOptions {
1618
1722
  /** Filter by backend identifier. */
1619
1723
  backend?: string;
1620
1724
  }
1725
+ /** Options for creating a runtime agent session. */
1726
+ interface CreateSessionOptions {
1727
+ title?: string;
1728
+ parentId?: string;
1729
+ backend: BackendConfig;
1730
+ }
1731
+ /** Backend credentials forwarded to the platform if a sandbox must restart. */
1732
+ interface SessionBackendCredentials {
1733
+ apiKey: string;
1734
+ baseUrl?: string;
1735
+ }
1736
+ /** One content part accepted by the runtime session message endpoint. */
1737
+ type SessionMessageInputPart = PromptInputPart | {
1738
+ type: "reasoning";
1739
+ text: string;
1740
+ } | {
1741
+ type: "tool";
1742
+ tool: string;
1743
+ state: {
1744
+ status: "pending" | "running" | "completed" | "failed";
1745
+ input?: unknown;
1746
+ output?: unknown;
1747
+ };
1748
+ } | {
1749
+ type: "step-start";
1750
+ } | {
1751
+ type: "step-finish";
1752
+ reason?: string;
1753
+ tokens?: {
1754
+ total?: number;
1755
+ input?: number;
1756
+ output?: number;
1757
+ reasoning?: number;
1758
+ cache?: {
1759
+ write?: number;
1760
+ read?: number;
1761
+ };
1762
+ };
1763
+ cost?: number;
1764
+ };
1765
+ /** Message body accepted by `SandboxSession.sendMessage`. */
1766
+ interface SendSessionMessageRequest {
1767
+ messageId?: string;
1768
+ parts: SessionMessageInputPart[];
1769
+ system?: string;
1770
+ agent?: string;
1771
+ model?: {
1772
+ providerId: string;
1773
+ modelId: string;
1774
+ };
1775
+ reasoningEffort?: "low" | "medium" | "high";
1776
+ turnId?: string;
1777
+ interactions?: BackendConfig["interactions"];
1778
+ }
1779
+ /** Per-call controls for `SandboxSession.sendMessage`. */
1780
+ interface SendSessionMessageOptions {
1781
+ credentials?: SessionBackendCredentials;
1782
+ timeoutMs?: number;
1783
+ signal?: AbortSignal;
1784
+ }
1785
+ /** Response returned after a session message finishes processing. */
1786
+ interface SentSessionMessage {
1787
+ info: {
1788
+ id: string;
1789
+ role: "user" | "assistant" | "system";
1790
+ timestamp?: string;
1791
+ };
1792
+ parts: unknown[];
1793
+ }
1794
+ /** Canonical portable profile attached to a task session. */
1795
+ type TaskSessionProfile = AgentProfile & {
1796
+ name: string;
1797
+ };
1798
+ /** Options for creating an isolated background task session. */
1799
+ interface CreateTaskSessionOptions {
1800
+ sessionId: string;
1801
+ backend: BackendConfig;
1802
+ title: string;
1803
+ profile?: TaskSessionProfile;
1804
+ parentSessionId?: string;
1805
+ isolateFileWrites?: boolean;
1806
+ }
1807
+ /** Task-session metadata returned at creation time. */
1808
+ interface TaskSessionInfo {
1809
+ id: string;
1810
+ title?: string;
1811
+ parentSessionId?: string;
1812
+ worktreeInfo?: {
1813
+ worktreePath: string;
1814
+ branchName: string;
1815
+ baseCommitSha: string;
1816
+ };
1817
+ profile?: TaskSessionProfile;
1818
+ }
1819
+ /** One changed file in an isolated task session. */
1820
+ interface TaskSessionFileChange {
1821
+ file: string;
1822
+ operation: "added" | "modified" | "deleted";
1823
+ additions: number;
1824
+ deletions: number;
1825
+ }
1826
+ /** Current diff and commit history for an isolated task session. */
1827
+ interface TaskSessionChanges {
1828
+ sessionId: string;
1829
+ files: TaskSessionFileChange[];
1830
+ diff: string;
1831
+ commits: Array<{
1832
+ sha: string;
1833
+ message: string;
1834
+ date: string;
1835
+ }>;
1836
+ worktreeInfo: {
1837
+ worktreePath: string;
1838
+ branchName: string;
1839
+ baseCommitSha: string;
1840
+ headCommitSha?: string;
1841
+ };
1842
+ }
1843
+ /** Options for merging task-session changes into the main workspace. */
1844
+ interface CommitTaskSessionOptions {
1845
+ message?: string;
1846
+ files?: string[];
1847
+ }
1848
+ /** Result of merging task-session changes into the main workspace. */
1849
+ interface TaskSessionCommitResult {
1850
+ success: true;
1851
+ commitSha?: string;
1852
+ conflicts?: string[];
1853
+ appliedFiles: number;
1854
+ }
1621
1855
  /**
1622
1856
  * Options for `SandboxSession.events()` streaming.
1623
1857
  */
@@ -1784,10 +2018,11 @@ type TurnDriveResult = {
1784
2018
  error: string;
1785
2019
  };
1786
2020
  /**
1787
- * Scope of a `box.mintScopedToken()` request. Each value narrows the
1788
- * token's authority compared to the full sandbox bearer.
2021
+ * Scope of a `box.mintScopedToken()` request. Each value narrows the token's
2022
+ * authority compared to the full sandbox bearer. `session-runtime` permits
2023
+ * only typed message, workspace-file, and terminal operations for one session.
1789
2024
  */
1790
- type ScopedTokenScope = "session" | "project" | "read-only";
2025
+ type ScopedTokenScope = "session" | "session-runtime" | "project" | "read-only";
1791
2026
  /**
1792
2027
  * Options for `box.mintScopedToken()`.
1793
2028
  */
@@ -1796,7 +2031,7 @@ interface MintScopedTokenOptions {
1796
2031
  * grants read access to the whole sandbox; `read-only` is a project
1797
2032
  * scope without prompt-dispatch capabilities. */
1798
2033
  scope: ScopedTokenScope;
1799
- /** Required when `scope === "session"`. */
2034
+ /** Required when `scope` is `session` or `session-runtime`. */
1800
2035
  sessionId?: string;
1801
2036
  /** TTL in minutes. Default 5; clamped to [1, 15]. Browser-side
1802
2037
  * bearers must be short-lived; pair with `client.onTokenRefresh()`
@@ -1887,6 +2122,10 @@ interface BatchTask {
1887
2122
  /** Per-task timeout in milliseconds */
1888
2123
  timeoutMs?: number;
1889
2124
  }
2125
+ /** Backend configuration accepted by batch execution, including named profiles. */
2126
+ type BatchBackend = Omit<Partial<BackendConfig>, "type"> & {
2127
+ type?: BackendType | `${BackendType}:${string}`;
2128
+ };
1890
2129
  /**
1891
2130
  * Options for batch execution.
1892
2131
  */
@@ -1901,11 +2140,38 @@ interface BatchOptions {
1901
2140
  * Use `backend.profile` with a string for a named profile or a provider-neutral
1902
2141
  * `AgentProfile` object for inline profile configuration.
1903
2142
  */
1904
- backend?: Partial<BackendConfig>;
2143
+ backend?: BatchBackend;
2144
+ /** Run every task against each backend for comparison. */
2145
+ backends?: BatchBackend[];
2146
+ /** User identifier attached to the batch for platform attribution. */
2147
+ userId?: string;
2148
+ /** Partner identifier attached to the batch for credit attribution. */
2149
+ partnerId?: string;
2150
+ /** Request identifier used in events and metrics. */
2151
+ identifier?: string;
2152
+ /** Workload class used by capacity and lifecycle policy. */
2153
+ executionClass?: "project" | "simulation" | "background";
2154
+ /** Capacity to provision before execution starts. */
2155
+ desiredCapacity?: number;
2156
+ /** Maximum time to wait for requested capacity. */
2157
+ provisionTimeoutMs?: number;
1905
2158
  /** Keep sandboxes alive after completion (default: false) */
1906
2159
  persistent?: boolean;
2160
+ /** Lifecycle policy for persistent batch sandboxes. */
2161
+ lifecycle?: {
2162
+ idleTimeoutMs?: number;
2163
+ coldTimeoutMs?: number;
2164
+ };
2165
+ /** Use deterministic mock model responses. Intended for tests. */
2166
+ mock?: boolean;
1907
2167
  /** Milliseconds to keep non-persistent batch sandboxes alive after completion. */
1908
2168
  graceMs?: number;
2169
+ /** Repository cloned into persistent batch workspaces. */
2170
+ git?: GitConfig;
2171
+ /** Full replacement for the default agent system prompt. */
2172
+ systemPrompt?: string;
2173
+ /** Instructions appended to the default agent system prompt. */
2174
+ instructions?: string;
1909
2175
  /**
1910
2176
  * AbortSignal to cancel the batch mid-stream. When aborted, the HTTP
1911
2177
  * request to `/batch/run` is torn down; the SSE generator stops
@@ -1917,6 +2183,14 @@ interface BatchOptions {
1917
2183
  */
1918
2184
  signal?: AbortSignal;
1919
2185
  }
2186
+ /** Complete request accepted by `runBatch` and `streamBatch`. */
2187
+ interface BatchRunRequest extends Omit<BatchOptions, "signal"> {
2188
+ tasks: BatchTask[];
2189
+ }
2190
+ /** Per-call controls that are not serialized into a batch request. */
2191
+ interface BatchRunOptions {
2192
+ signal?: AbortSignal;
2193
+ }
1920
2194
  /**
1921
2195
  * Result of a single task in a batch.
1922
2196
  */
@@ -1935,6 +2209,16 @@ interface BatchTaskResult {
1935
2209
  retries: number;
1936
2210
  /** Token usage if available */
1937
2211
  tokensUsed?: number;
2212
+ /** Backend identifier for multi-backend batches. */
2213
+ backend?: string;
2214
+ /** Human-readable backend label emitted by the server. */
2215
+ backendLabel?: string;
2216
+ /** Model identifier emitted by the server. */
2217
+ backendModel?: string;
2218
+ /** Runtime session created for this task execution. */
2219
+ sessionId?: string;
2220
+ /** Sandbox used for this task execution. */
2221
+ sandboxId?: string;
1938
2222
  }
1939
2223
  /**
1940
2224
  * Summary of batch execution.
@@ -1953,23 +2237,145 @@ interface BatchResult {
1953
2237
  /** Individual task results */
1954
2238
  results: BatchTaskResult[];
1955
2239
  }
1956
- /**
1957
- * SSE event from batch streaming.
1958
- */
1959
- interface BatchEvent {
1960
- /** Event type (batch.started, task.completed, etc.) */
1961
- type: string;
1962
- /** Event data */
1963
- data: Record<string, unknown>;
1964
- /**
1965
- * Optional `id:` from the SSE frame. Present at runtime whenever
1966
- * the server emits an `id:` line (used by EventSource-style
1967
- * reconnection). Declared optional because the batch protocol
1968
- * doesn't currently emit it — downstream consumers that want to
1969
- * implement resume should feature-detect.
1970
- */
1971
- id?: string;
2240
+ /** Token and tool usage emitted when one batch task completes. */
2241
+ interface BatchTaskUsage {
2242
+ inputTokens: number;
2243
+ outputTokens: number;
2244
+ cacheReadTokens?: number;
2245
+ cacheWriteTokens?: number;
2246
+ toolCallCount?: number;
2247
+ }
2248
+ /** Per-backend aggregate emitted by `batch.completed`. */
2249
+ interface BatchBackendStats {
2250
+ backend: string;
2251
+ backendLabel?: string;
2252
+ backendModel?: string;
2253
+ success: number;
2254
+ failure: number;
2255
+ retries: number;
2256
+ successRate: number;
2257
+ }
2258
+ /** Sidecars allocated to one backend configuration. */
2259
+ interface BatchSidecarGroup {
2260
+ backend: string;
2261
+ sidecarIds: string[];
2262
+ }
2263
+ interface BatchTaskEventIdentity {
2264
+ taskId: string;
2265
+ backend: string;
2266
+ backendLabel?: string;
2267
+ backendModel?: string;
2268
+ }
2269
+ /** Data payloads keyed by the SSE event name emitted by `/batch/run`. */
2270
+ interface BatchEventDataMap {
2271
+ "batch.provisioning": {
2272
+ desiredCapacity: number;
2273
+ currentCapacity: number;
2274
+ provisionTimeoutMs: number;
2275
+ };
2276
+ "batch.provisioned": {
2277
+ capacity: number;
2278
+ };
2279
+ "batch.started": {
2280
+ taskCount: number;
2281
+ backendCount: number;
2282
+ totalExecutions: number;
2283
+ maxConcurrent: number;
2284
+ scalingMode: string;
2285
+ backends: string[];
2286
+ };
2287
+ "sidecars.allocated": {
2288
+ count: number;
2289
+ groups: BatchSidecarGroup[];
2290
+ };
2291
+ "batch.completed": {
2292
+ taskCount: number;
2293
+ backendCount: number;
2294
+ totalExecutions: number;
2295
+ totalSuccess: number;
2296
+ totalFailure: number;
2297
+ totalRetries: number;
2298
+ successRate: number;
2299
+ byBackend: BatchBackendStats[];
2300
+ };
2301
+ "batch.failed": {
2302
+ error: string;
2303
+ backends?: string[];
2304
+ };
2305
+ "batch.persistent": {
2306
+ message: string;
2307
+ sidecarCount: number;
2308
+ };
2309
+ "batch.grace_period": {
2310
+ message: string;
2311
+ sidecarCount: number;
2312
+ graceMs: number;
2313
+ sidecarIds: string[];
2314
+ };
2315
+ "task.started": BatchTaskEventIdentity & {
2316
+ sidecarId: string;
2317
+ projectRef?: string;
2318
+ attempt: number;
2319
+ };
2320
+ "task.message.delta": BatchTaskEventIdentity & {
2321
+ sidecarId: string;
2322
+ projectRef?: string;
2323
+ value: string;
2324
+ part: Record<string, unknown>;
2325
+ };
2326
+ "task.reasoning": BatchTaskEventIdentity & {
2327
+ sidecarId: string;
2328
+ projectRef?: string;
2329
+ value: string;
2330
+ part: Record<string, unknown>;
2331
+ };
2332
+ "task.tool.updated": BatchTaskEventIdentity & {
2333
+ sidecarId: string;
2334
+ projectRef?: string;
2335
+ part: Record<string, unknown>;
2336
+ };
2337
+ "task.completed": BatchTaskEventIdentity & {
2338
+ durationMs: number;
2339
+ attempt: number;
2340
+ retries: number;
2341
+ sidecarId: string;
2342
+ projectRef?: string;
2343
+ resultSummary?: string;
2344
+ sessionId?: string;
2345
+ usage: BatchTaskUsage;
2346
+ };
2347
+ "task.failed": BatchTaskEventIdentity & {
2348
+ durationMs: number;
2349
+ attempt: number;
2350
+ retries: number;
2351
+ error: string;
2352
+ sidecarId?: string;
2353
+ };
2354
+ "task.retry": BatchTaskEventIdentity & {
2355
+ attempt: number;
2356
+ maxRetries: number;
2357
+ error: string;
2358
+ delayMs: number;
2359
+ };
2360
+ "backend.completed": {
2361
+ backend: string;
2362
+ backendLabel?: string;
2363
+ backendModel?: string;
2364
+ success: number;
2365
+ failure: number;
2366
+ retries: number;
2367
+ successRate: number;
2368
+ };
2369
+ "sidecar.releasing": {
2370
+ sidecarId: string;
2371
+ };
1972
2372
  }
2373
+ /** Discriminated SSE event from a batch execution. */
2374
+ type BatchEvent = { [K in keyof BatchEventDataMap]: {
2375
+ type: K;
2376
+ data: BatchEventDataMap[K]; /** Optional SSE id used by reconnecting consumers. */
2377
+ id?: string;
2378
+ } }[keyof BatchEventDataMap];
1973
2379
  /**
1974
2380
  * Stable worker identifier inside a sandbox fleet.
1975
2381
  *
@@ -2869,6 +3275,18 @@ interface BackendConfig {
2869
3275
  question?: boolean;
2870
3276
  plan?: boolean;
2871
3277
  };
3278
+ /** Runtime session metadata used for attribution and workspace selection. */
3279
+ metadata?: {
3280
+ containerType?: string;
3281
+ telemetry?: {
3282
+ otlp: {
3283
+ endpoint: string;
3284
+ headers: string;
3285
+ };
3286
+ resourceAttributes: Record<string, string>;
3287
+ };
3288
+ [key: string]: unknown;
3289
+ };
2872
3290
  }
2873
3291
  /**
2874
3292
  * Backend capabilities.
@@ -3842,6 +4260,71 @@ interface FileInfo {
3842
4260
  /** Last access time */
3843
4261
  accessTime: Date;
3844
4262
  }
4263
+ /** File metadata returned by the recursive workspace tree endpoint. */
4264
+ interface FileTreeFile {
4265
+ path: string;
4266
+ size: number;
4267
+ /** File modification time as Unix milliseconds. */
4268
+ mtime: number;
4269
+ }
4270
+ /** Options for recursively scanning a workspace tree. */
4271
+ interface FileTreeOptions {
4272
+ sessionId?: string;
4273
+ maxDepth?: number;
4274
+ }
4275
+ /** Recursive workspace tree with scan statistics. */
4276
+ interface FileTreeResult {
4277
+ root: string;
4278
+ directories: string[];
4279
+ files: FileTreeFile[];
4280
+ stats: {
4281
+ totalDirectories: number;
4282
+ totalFiles: number;
4283
+ scanDurationMs: number;
4284
+ truncated: boolean;
4285
+ };
4286
+ }
4287
+ /** File content and metadata returned by a batch read. */
4288
+ interface FileReadResult {
4289
+ path: string;
4290
+ content: string;
4291
+ encoding: "utf8" | "base64";
4292
+ hash: string;
4293
+ size: number;
4294
+ /** File modification time as Unix milliseconds. */
4295
+ mtime: number;
4296
+ }
4297
+ /** One file that could not be read during a partial-success batch. */
4298
+ interface FileReadError {
4299
+ path: string;
4300
+ error: string;
4301
+ code?: string;
4302
+ }
4303
+ /** Options for reading files in a batch. */
4304
+ interface FileReadBatchOptions {
4305
+ encoding?: "utf8" | "base64";
4306
+ sessionId?: string;
4307
+ }
4308
+ /** Partial-success result from a batch file read. */
4309
+ interface FileReadBatchResult {
4310
+ files: FileReadResult[];
4311
+ errors: FileReadError[];
4312
+ stats: {
4313
+ requested: number;
4314
+ succeeded: number;
4315
+ failed: number;
4316
+ };
4317
+ }
4318
+ /** Metadata returned after a successful file write. */
4319
+ interface FileWriteResult {
4320
+ path: string;
4321
+ hash: string;
4322
+ size: number;
4323
+ /** File modification time as Unix milliseconds. */
4324
+ mtime: number;
4325
+ /** Encoding echoed by runtimes that include it in write responses. */
4326
+ encoding?: "utf8" | "base64";
4327
+ }
3845
4328
  /**
3846
4329
  * Options for uploading files.
3847
4330
  */
@@ -3910,6 +4393,8 @@ interface MkdirOptions {
3910
4393
  interface DeleteOptions {
3911
4394
  /** Recursively delete directories (like rm -rf) */
3912
4395
  recursive?: boolean;
4396
+ /** Agent session whose workspace and change history receive the deletion. */
4397
+ sessionId?: string;
3913
4398
  }
3914
4399
  /**
3915
4400
  * File system operations for sandboxes. Access via `sandbox.fs`.
@@ -3974,6 +4459,10 @@ interface WriteManyFile {
3974
4459
  interface WriteFileOptions {
3975
4460
  /** Unix mode bits applied after write, e.g. 0o755. */
3976
4461
  mode?: number;
4462
+ /** Encoding of `content` on the wire. */
4463
+ encoding?: "utf8" | "base64";
4464
+ /** Agent session whose workspace and change history receive the write. */
4465
+ sessionId?: string;
3977
4466
  }
3978
4467
  /** Options for {@link FileSystem.writeMany}. */
3979
4468
  interface WriteManyOptions {
@@ -3995,6 +4484,10 @@ interface FileSystem {
3995
4484
  * @throws NotFoundError if file doesn't exist
3996
4485
  */
3997
4486
  read(path: string): Promise<string>;
4487
+ /** Read up to any number of files with content metadata and per-file errors. */
4488
+ readBatch(paths: string[], options?: FileReadBatchOptions): Promise<FileReadBatchResult>;
4489
+ /** Recursively scan the workspace and return file metadata. */
4490
+ tree(path: string, options?: FileTreeOptions): Promise<FileTreeResult>;
3998
4491
  /**
3999
4492
  * Write string content to a file.
4000
4493
  * For binary files, use upload() instead.
@@ -4003,7 +4496,7 @@ interface FileSystem {
4003
4496
  * @param path - Path to file (relative to workspace)
4004
4497
  * @param content - Content to write
4005
4498
  */
4006
- write(path: string, content: string, options?: WriteFileOptions): Promise<void>;
4499
+ write(path: string, content: string, options?: WriteFileOptions): Promise<FileWriteResult>;
4007
4500
  /**
4008
4501
  * Write many files in one paced, retry-aware batch.
4009
4502
  *
@@ -4256,1431 +4749,4 @@ interface CodeExecutionOptions {
4256
4749
  idempotencyKey?: string;
4257
4750
  }
4258
4751
  //#endregion
4259
- //#region src/mcp.d.ts
4260
- /**
4261
- * MCP (Model Context Protocol) helpers for sandbox capabilities.
4262
- *
4263
- * The sandbox exposes capabilities (currently `computer_use`, more
4264
- * later) as MCP tools over Streamable HTTP. Any MCP-capable client —
4265
- * Claude Desktop, Cursor, claude-code, codex, opencode, raw
4266
- * `@modelcontextprotocol/sdk` apps — can consume this surface by
4267
- * pasting the JSON returned from `Sandbox#getMcpEndpoint()` (or
4268
- * `buildSandboxMcpConfig` if you already have the URL + token) into
4269
- * the client's MCP config.
4270
- *
4271
- * Security model:
4272
- * - Tokens are capability-scoped JWTs (claim `cap: ["computer_use"]`).
4273
- * - Full sandbox runtime tokens are rejected on `/mcp`; only
4274
- * capability-scoped tokens work there.
4275
- * - A scoped token cannot pivot to admin endpoints (`/exec`, `/files`,
4276
- * etc.) — those routes reject scoped tokens.
4277
- * - Tokens are short-lived. Rotate via `Sandbox#getMcpEndpoint()`,
4278
- * which mints a fresh token each call.
4279
- */
4280
- /** Default name of the MCP server entry — surfaces in the host UI. */
4281
- declare const SANDBOX_MCP_SERVER_NAME = "tangle-sandbox";
4282
- /**
4283
- * MCP HTTP server entry — matches the Anthropic MCP HTTP transport
4284
- * schema (`type: "http"`, `url`, optional `headers`). Compatible with
4285
- * every MCP host that implements the spec.
4286
- */
4287
- interface SandboxMcpServerEntry {
4288
- type: "http";
4289
- url: string;
4290
- headers: Record<string, string>;
4291
- }
4292
- /**
4293
- * `.mcp.json`-shaped config any MCP host accepts. Drop the contents of
4294
- * `mcpServers` into your host's `mcpServers` block (Claude Desktop,
4295
- * Cursor, claude-code's `--mcp-config`, etc.) — no host-specific
4296
- * fields, no provider lock-in.
4297
- */
4298
- interface SandboxMcpConfig {
4299
- mcpServers: Record<string, SandboxMcpServerEntry>;
4300
- }
4301
- /**
4302
- * Endpoint payload returned by `GET /v1/sandboxes/:id/mcp`. Includes
4303
- * the canonical config plus token expiry so callers can plan
4304
- * refreshes.
4305
- */
4306
- interface SandboxMcpEndpoint {
4307
- /** MCP host config — paste this into Cursor/Claude Desktop/etc. */
4308
- config: SandboxMcpConfig;
4309
- /** Server entry name used inside `config.mcpServers`. */
4310
- serverName: string;
4311
- /** Reachable URL for the MCP HTTP transport. */
4312
- url: string;
4313
- /** Bearer token sent by the MCP host on every request. */
4314
- authToken: string;
4315
- /** ISO-8601 expiry — the host should refresh before this. */
4316
- expiresAt: string;
4317
- /** Capabilities the token is scoped to. */
4318
- capabilities: ReadonlyArray<"computer_use">;
4319
- }
4320
- interface BuildSandboxMcpConfigOptions {
4321
- /** Public sandbox URL where `/mcp` is reachable. No trailing slash. */
4322
- sandboxUrl: string;
4323
- /** Capability-scoped JWT minted by the Sandbox API. */
4324
- authToken: string;
4325
- /** Override the entry name. Defaults to SANDBOX_MCP_SERVER_NAME. */
4326
- serverName?: string;
4327
- }
4328
- /**
4329
- * Build the canonical `mcpServers` config for a sandbox MCP endpoint.
4330
- * Pure function — no I/O, no crypto. Use this when you already have a
4331
- * `{ url, authToken }` pair from the API and just want the JSON shape
4332
- * to paste into a host. Most callers should use
4333
- * `Sandbox#getMcpEndpoint()` instead, which fetches a freshly-minted
4334
- * token from the API.
4335
- */
4336
- declare function buildSandboxMcpConfig(options: BuildSandboxMcpConfigOptions): {
4337
- serverName: string;
4338
- config: SandboxMcpConfig;
4339
- };
4340
- /**
4341
- * Default name of the control-plane MCP server entry. Distinct from the per-
4342
- * sandbox runtime server (`SANDBOX_MCP_SERVER_NAME`): the sandbox surface
4343
- * operates INSIDE one sandbox (`run_code`/`exec`/`read`/`write`), while this one
4344
- * operates ACROSS the account (sandboxes, workflows, integrations, usage).
4345
- */
4346
- declare const CONTROL_PLANE_MCP_SERVER_NAME = "tangle-control-plane";
4347
- interface BuildControlPlaneMcpConfigOptions {
4348
- /** Public platform URL where `/mcp` is reachable. No trailing slash. */
4349
- platformUrl: string;
4350
- /**
4351
- * A Tangle account API key scoped to the control-plane operations you need
4352
- * (e.g. `read`, `workflows:write`). Sent on every request as a Bearer token.
4353
- */
4354
- apiKey: string;
4355
- /** Override the entry name. Defaults to CONTROL_PLANE_MCP_SERVER_NAME. */
4356
- serverName?: string;
4357
- }
4358
- /**
4359
- * Build the canonical `mcpServers` config for the public control-plane MCP
4360
- * endpoint — the JSON a user pastes into Claude Desktop / Cursor / claude-code
4361
- * to drive their Tangle account from their own agent. Pure function; mirrors
4362
- * `buildSandboxMcpConfig` but carries an account API key instead of a per-
4363
- * sandbox capability token.
4364
- */
4365
- declare function buildControlPlaneMcpConfig(options: BuildControlPlaneMcpConfigOptions): {
4366
- serverName: string;
4367
- config: SandboxMcpConfig;
4368
- };
4369
- //#endregion
4370
- //#region src/interactive.d.ts
4371
- /**
4372
- * Interactive harness sessions on the public SDK.
4373
- *
4374
- * `box.session(id).interactive()` returns a handle that spawns a coding
4375
- * harness's native interactive TUI in the sandbox (start), drives it with
4376
- * prompts (sendPrompt), and tears it down (stop). The live framebuffer is
4377
- * streamed over the WebSocket at the returned `streamUrl` (the secured
4378
- * `/terminals/:id/ws` pixel lane) — open it with your terminal/xterm client.
4379
- *
4380
- * This is the public SDK surface of the Session Protocol Gateway; it rides the
4381
- * same secured runtime routes as the rest of the SDK.
4382
- */
4383
- /** CLI auth file materialized into the harness's auth home before launch. */
4384
- interface InteractiveAuthFile {
4385
- path: string;
4386
- content: string;
4387
- mode?: number;
4388
- }
4389
- interface StartInteractiveOptions {
4390
- /** Harness with a native interactive TUI: "claude-code" | "codex" | "kimi-code". */
4391
- harness: string;
4392
- model?: string;
4393
- apiKey?: string;
4394
- authMode?: string;
4395
- baseUrl?: string;
4396
- /** Working directory; defaults to the sandbox workspace root. */
4397
- cwd?: string;
4398
- cols?: number;
4399
- rows?: number;
4400
- authFiles?: InteractiveAuthFile[];
4401
- }
4402
- interface InteractiveSessionInfo {
4403
- sessionId: string;
4404
- harness: string;
4405
- /** ISO timestamp of when the harness process was spawned. */
4406
- startedAt: string;
4407
- /**
4408
- * Sandbox-relative WebSocket path that streams the live framebuffer and
4409
- * accepts keystrokes (the mTLS- + capability-gated terminal socket).
4410
- */
4411
- streamUrl: string;
4412
- }
4413
- /** Decision passed to `respondToPermission`. */
4414
- interface RespondToPermissionOptions {
4415
- /** The human's decision for the awaiting permission interaction. */
4416
- response: "allow" | "deny";
4417
- }
4418
- /** Result of `interrupt`. */
4419
- interface InterruptResult {
4420
- /**
4421
- * True iff an execution was actively running and the abort signal reached
4422
- * it. `false` means there was nothing in flight to cancel — surfaced
4423
- * explicitly rather than as a silent success so callers can distinguish a
4424
- * real interruption from a no-op.
4425
- */
4426
- cancelled: boolean;
4427
- }
4428
- /**
4429
- * Host hooks the SDK box implements to drive interactive sessions. Kept
4430
- * separate from the prompt/session-event host so the interactive surface is an
4431
- * explicit, independently-mockable contract.
4432
- */
4433
- interface InteractiveSessionHost {
4434
- _startInteractive(id: string, options: StartInteractiveOptions): Promise<InteractiveSessionInfo>;
4435
- _sendInteractivePrompt(id: string, prompt: string): Promise<void>;
4436
- _stopInteractive(id: string): Promise<void>;
4437
- }
4438
- /**
4439
- * Handle for one session's interactive harness. Obtained via
4440
- * `box.session(id).interactive()`; does not hit the network until a method is
4441
- * called.
4442
- */
4443
- declare class InteractiveSessionHandle {
4444
- private readonly host;
4445
- private readonly sessionId;
4446
- constructor(host: InteractiveSessionHost, sessionId: string);
4447
- /**
4448
- * Spawn the harness's interactive TUI for this session. Returns the
4449
- * `streamUrl` to attach a terminal client to. Throws if the harness has no
4450
- * interactive entrypoint (e.g. opencode), the binary is not installed, or a
4451
- * session is already running for this id.
4452
- */
4453
- start(options: StartInteractiveOptions): Promise<InteractiveSessionInfo>;
4454
- /** Inject a prompt as keystrokes into the live harness (submitted on send). */
4455
- sendPrompt(prompt: string): Promise<void>;
4456
- /** Stop the interactive harness and reap its PTY. */
4457
- stop(): Promise<void>;
4458
- }
4459
- //#endregion
4460
- //#region src/session.d.ts
4461
- /**
4462
- * The subset of `SandboxInstance` a `SandboxSession` drives. Declared here
4463
- * (rather than importing the concrete class) so `session.ts` stays a leaf
4464
- * of `sandbox.ts` — `sandbox.ts` constructs `SandboxSession`, so the reverse
4465
- * import would form a cycle. `SandboxInstance` satisfies this structurally.
4466
- */
4467
- interface SandboxSessionHost extends InteractiveSessionHost {
4468
- prompt(message: string | PromptInputPart[], options?: PromptOptions): Promise<PromptResult>;
4469
- _sessionStatus(id: string): Promise<SessionInfo | null>;
4470
- _sessionEvents(id: string, opts?: SessionEventStreamOptions): AsyncGenerator<SandboxEvent>;
4471
- _sessionResult(id: string): Promise<PromptResult>;
4472
- _sessionCancel(id: string): Promise<void>;
4473
- messages(opts: ListMessagesOptions): Promise<SessionMessage[]>;
4474
- _sessionFork(id: string, opts?: SessionForkOptions): Promise<SessionInfo>;
4475
- _respondToPermission(id: string, permissionID: string, options: RespondToPermissionOptions): Promise<void>;
4476
- _interrupt(id: string): Promise<InterruptResult>;
4477
- _answerQuestion(id: string, answers: Record<string, string[]>): Promise<void>;
4478
- }
4479
- /**
4480
- * A single agent session inside a sandbox. Created via
4481
- * `box.session(id)` — does not hit the network until a method is called.
4482
- */
4483
- declare class SandboxSession {
4484
- private readonly box;
4485
- /** Stable session id assigned by the sandbox runtime. */
4486
- readonly id: string;
4487
- /**
4488
- * @internal SDK-internal constructor — apps should call `box.session(id)`.
4489
- */
4490
- constructor(box: SandboxSessionHost, /** Stable session id assigned by the sandbox runtime. */
4491
-
4492
- id: string);
4493
- /**
4494
- * Fetch the current session state from the sandbox. Includes status,
4495
- * model, prompt count, token usage if known, and timing metadata.
4496
- *
4497
- * Throws on transport error; returns `null` if the session id is not
4498
- * known to the sandbox (e.g. it ended and was reaped, or the id is
4499
- * invalid).
4500
- */
4501
- status(): Promise<SessionInfo | null>;
4502
- /**
4503
- * Stream events from this session as they arrive. With no `since`,
4504
- * starts at the live tail; with `since`, replays from that event id
4505
- * forward — useful for reconnect-after-disconnect flows.
4506
- *
4507
- * The async iterator terminates when the session reaches a terminal
4508
- * state (`completed`, `failed`, `cancelled`) and the corresponding
4509
- * terminal event has been yielded, OR when the caller's signal aborts.
4510
- */
4511
- events(opts?: SessionEventStreamOptions): AsyncGenerator<SandboxEvent>;
4512
- /**
4513
- * Await the session's terminal result. Polls status + drains events
4514
- * until the session reaches a terminal state, then returns the
4515
- * aggregated `PromptResult`.
4516
- *
4517
- * Use this to wait for a session that was started by another caller
4518
- * (e.g. `dispatchPrompt`).
4519
- */
4520
- result(): Promise<PromptResult>;
4521
- /**
4522
- * List persisted messages for this session, including in-flight assistant
4523
- * content when the runtime has flushed partial output.
4524
- */
4525
- messages(opts?: Omit<ListMessagesOptions, "sessionId">): Promise<SessionMessage[]>;
4526
- /**
4527
- * Continue this session with an additional prompt. Equivalent to
4528
- * `box.prompt(message, { ...opts, sessionId: this.id })` but reads
4529
- * naturally on a Session reference.
4530
- */
4531
- prompt(message: string | PromptInputPart[], opts?: PromptOptions): Promise<PromptResult>;
4532
- /**
4533
- * Abort the session's in-flight execution; the session and its messages
4534
- * are preserved (this does not delete the session). Void-returning alias
4535
- * of `interrupt()` — use `interrupt()` when you need to know whether an
4536
- * execution was actually running. Best-effort: an in-flight LLM call may
4537
- * still complete one more token before the abort takes effect. Idempotent —
4538
- * aborting a session with nothing in flight is a no-op.
4539
- */
4540
- cancel(): Promise<void>;
4541
- /**
4542
- * Fork this session into a new queued session. The fork shares the
4543
- * parent workspace and copies conversation history up to `messageId`
4544
- * when supplied.
4545
- */
4546
- fork(opts?: SessionForkOptions): Promise<{
4547
- session: SandboxSession;
4548
- info: SessionInfo;
4549
- }>;
4550
- /**
4551
- * Drive this session's harness in INTERACTIVE mode: spawn its native TUI,
4552
- * stream the live framebuffer, and inject prompts as keystrokes. Distinct
4553
- * from the headless `prompt()`/`events()` surface above. Lazy — does not hit
4554
- * the network until a handle method is called.
4555
- */
4556
- interactive(): InteractiveSessionHandle;
4557
- /**
4558
- * Resolve a pending permission interaction the agent raised mid-turn,
4559
- * forwarding `allow`/`deny` to the blocked agent through the unified
4560
- * interaction channel. Throws if no matching permission is outstanding.
4561
- */
4562
- respondToPermission(permissionID: string, options: RespondToPermissionOptions): Promise<void>;
4563
- /**
4564
- * Interrupt the session's current execution without deleting it. Returns
4565
- * `{ cancelled: false }` when nothing was running — the no-op is reported
4566
- * explicitly rather than masked as success.
4567
- */
4568
- interrupt(): Promise<InterruptResult>;
4569
- /**
4570
- * Answer a question the agent asked via a question tool invocation. `answers`
4571
- * maps each question id to the selected option(s). Backend-agnostic: works
4572
- * with any backend that raises kind:"question" interactions — OpenCode
4573
- * natively, or CLI backends with `BackendConfig.interactions.question`
4574
- * enabled. Backends with no question support reject loudly.
4575
- */
4576
- answer(answers: Record<string, string[]>): Promise<void>;
4577
- }
4578
- //#endregion
4579
- //#region src/trace-exporter.d.ts
4580
- type JsonObject = {
4581
- [key: string]: JsonValue;
4582
- };
4583
- type TraceExportFormat = "tangle" | "otel-json";
4584
- type TraceExportBundle = SandboxTraceBundle | SandboxFleetTraceBundle;
4585
- interface TraceExportSink {
4586
- url: string;
4587
- headers?: Record<string, string>;
4588
- format?: TraceExportFormat;
4589
- serviceName?: string;
4590
- timeoutMs?: number;
4591
- fetch?: typeof fetch;
4592
- }
4593
- interface TraceExportResult {
4594
- status: number;
4595
- ok: boolean;
4596
- body: string;
4597
- }
4598
- declare function buildTraceExportPayload(bundle: TraceExportBundle, format?: TraceExportFormat, serviceName?: string): TraceExportBundle | JsonObject;
4599
- declare function exportTraceBundle(bundle: TraceExportBundle, sink: TraceExportSink): Promise<TraceExportResult>;
4600
- declare function toOtelJson(bundle: TraceExportBundle, serviceName?: string): JsonObject;
4601
- declare function otelTraceIdForTangleTrace(traceId: string): string;
4602
- //#endregion
4603
- //#region src/sandbox.d.ts
4604
- /**
4605
- * Result of registering a sidecar session mapping. `reprovisionRequired` is
4606
- * true when the server reports the mapped sidecar is stale (HTTP 410) and the
4607
- * caller must reprovision the sandbox before retrying.
4608
- */
4609
- interface SessionMappingResult {
4610
- success: boolean;
4611
- sessionId: string;
4612
- sidecarSessionId?: string;
4613
- reprovisionRequired: boolean;
4614
- code?: string;
4615
- }
4616
- /**
4617
- * HTTP client interface for making requests.
4618
- */
4619
- interface HttpClient {
4620
- fetch(path: string, options?: RequestInit, fetchOptions?: {
4621
- timeoutMs?: number;
4622
- }): Promise<Response>;
4623
- getApiKey?(): string | undefined;
4624
- }
4625
- /**
4626
- * Git capability for repository operations.
4627
- */
4628
- interface GitCapability {
4629
- /** Get repository status */
4630
- status(): Promise<GitStatus>;
4631
- /** Get commit log */
4632
- log(limit?: number): Promise<GitCommit[]>;
4633
- /** Get diff (optionally against a ref) */
4634
- diff(ref?: string): Promise<GitDiff>;
4635
- /** Stage files */
4636
- add(paths: string[]): Promise<void>;
4637
- /** Create a commit */
4638
- commit(message: string, options?: {
4639
- amend?: boolean;
4640
- }): Promise<GitCommit>;
4641
- /** Push to remote */
4642
- push(options?: {
4643
- force?: boolean;
4644
- }): Promise<void>;
4645
- /** Pull from remote */
4646
- pull(options?: {
4647
- rebase?: boolean;
4648
- }): Promise<void>;
4649
- /** List branches */
4650
- branches(): Promise<GitBranch[]>;
4651
- /** Checkout a branch or ref */
4652
- checkout(ref: string, options?: {
4653
- create?: boolean;
4654
- }): Promise<void>;
4655
- }
4656
- /**
4657
- * Tools capability for managing language runtimes via mise.
4658
- */
4659
- interface ToolsCapability {
4660
- /** Install a tool version */
4661
- install(tool: string, version: string): Promise<void>;
4662
- /** Activate a tool version for the session */
4663
- use(tool: string, version: string): Promise<void>;
4664
- /** List installed tools */
4665
- list(): Promise<InstalledTool[]>;
4666
- /** Run a command with a specific tool */
4667
- run(tool: string, args: string[]): Promise<ExecResult>;
4668
- }
4669
- /**
4670
- * A sandbox instance with methods for interaction.
4671
- */
4672
- declare class SandboxInstance {
4673
- private readonly client;
4674
- private info;
4675
- private readonly defaultRuntimeBackend?;
4676
- constructor(client: HttpClient, info: SandboxInfo, defaultRuntimeBackend?: BackendConfig);
4677
- /** Unique sandbox identifier */
4678
- get id(): string;
4679
- /** Human-readable name */
4680
- get name(): string | undefined;
4681
- /** Current status */
4682
- get status(): SandboxStatus;
4683
- /** Connection information */
4684
- get connection(): SandboxConnection | undefined;
4685
- /** Custom metadata */
4686
- get metadata(): Record<string, unknown> | undefined;
4687
- /** When the sandbox was created */
4688
- get createdAt(): Date;
4689
- /** When the sandbox started running */
4690
- get startedAt(): Date | undefined;
4691
- /** Last activity timestamp */
4692
- get lastActivityAt(): Date | undefined;
4693
- /** When the sandbox will expire */
4694
- get expiresAt(): Date | undefined;
4695
- /** Error message if status is 'failed' */
4696
- get error(): string | undefined;
4697
- /** GPU lease attached during sandbox creation, when requested. */
4698
- get gpuLease(): GpuLease | undefined;
4699
- /** Web terminal URL for browser-based access */
4700
- get url(): string | undefined;
4701
- /**
4702
- * The 12-phase startup breakdown (storage_provision, host_select, edge_bind,
4703
- * edge_ready, egress_proxy, docker_pull/create/start, sidecar_boot,
4704
- * health_check, …) the platform emitted when this sandbox was provisioned.
4705
- *
4706
- * Present only on a freshly-created box; `null` for a box resolved by id or
4707
- * when the runtime did not report diagnostics. Use `.phases` for the
4708
- * operation-name → durationMs map.
4709
- *
4710
- * @example
4711
- * ```typescript
4712
- * const d = box.startupDiagnostics();
4713
- * if (d) console.log(`provision phases: ${JSON.stringify(d.phases)}`);
4714
- * ```
4715
- */
4716
- startupDiagnostics(): StartupDiagnostics | null;
4717
- /**
4718
- * Serialize to the public sandbox shape for logs and structured
4719
- * output. Secrets in `connection` (currently `authToken`) are
4720
- * redacted so that `JSON.stringify(box)` is safe to ship to log
4721
- * sinks. Use {@link toDebugJSON} when the bearer is required (e.g.
4722
- * one-off CLI commands that print credentials to the user).
4723
- */
4724
- toJSON(): SandboxInfo;
4725
- /**
4726
- * Serialize the sandbox **including secrets** when `includeSecrets`
4727
- * is true. The default behavior matches {@link toJSON} and redacts
4728
- * `connection.authToken`.
4729
- *
4730
- * Use only when the caller has an explicit need for the bearer
4731
- * (e.g. presenting it once to the human operator). Never wire the
4732
- * result of `toDebugJSON({ includeSecrets: true })` into a structured
4733
- * logger — the bearer will land in any log sink consuming that output.
4734
- */
4735
- toDebugJSON(options?: {
4736
- includeSecrets?: boolean;
4737
- }): SandboxInfo;
4738
- /**
4739
- * Create an advanced direct-runtime view of this sandbox.
4740
- *
4741
- * Runtime methods on the returned instance talk to the sandbox runtime
4742
- * directly using `connection.runtimeUrl` and `connection.authToken`.
4743
- * Lifecycle methods still go through the parent SDK client.
4744
- */
4745
- direct(): SandboxInstance;
4746
- /**
4747
- * Get an MCP endpoint for this sandbox. Returns a paste-able config
4748
- * for any MCP-capable host (Claude Desktop, Cursor, claude-code,
4749
- * codex, opencode, …) plus a freshly-minted, capability-scoped JWT.
4750
- *
4751
- * The token is short-lived and limited to the requested capabilities
4752
- * — it cannot be used against admin endpoints (`/exec`, `/files`,
4753
- * etc.) on the sandbox. Call `getMcpEndpoint()` again to rotate.
4754
- *
4755
- * Requires the sandbox to have been created with `capabilities`
4756
- * including the requested capability (default: `computer_use`).
4757
- *
4758
- * @example
4759
- * ```typescript
4760
- * const ep = await box.getMcpEndpoint();
4761
- * // Save ep.config to your IDE's mcp.json — that's it.
4762
- * fs.writeFileSync("mcp.json", JSON.stringify(ep.config, null, 2));
4763
- * ```
4764
- */
4765
- getMcpEndpoint(options?: {
4766
- capabilities?: ReadonlyArray<"computer_use">; /** Override server entry name (default: "tangle-sandbox"). */
4767
- serverName?: string; /** Token TTL in minutes (server clamps to its policy). */
4768
- ttlMinutes?: number;
4769
- }): Promise<SandboxMcpEndpoint>;
4770
- /**
4771
- * Refresh sandbox information from the server.
4772
- */
4773
- refresh(): Promise<void>;
4774
- /**
4775
- * Fetch fresh TEE attestation evidence for this sandbox.
4776
- *
4777
- * When `attestationNonce` is supplied, the runtime must return evidence bound
4778
- * to that challenge or fail closed if the selected TEE backend cannot support
4779
- * nonce-bound report data.
4780
- */
4781
- getTeeAttestation(options?: TeeAttestationOptions): Promise<TeeAttestationResponse>;
4782
- /**
4783
- * Fetch the TEE-bound public key used for sealed-secret encryption.
4784
- *
4785
- * The returned key includes an attestation report. Verify that report before
4786
- * encrypting secrets to the key.
4787
- */
4788
- getTeePublicKey(): Promise<TeePublicKeyResponse>;
4789
- /**
4790
- * Bootstrap a real-time collaboration session for a file.
4791
- * Returns the WebSocket URL and auth token needed to connect a
4792
- * Hocuspocus/Yjs provider for live multi-user editing.
4793
- *
4794
- * @example
4795
- * ```typescript
4796
- * const collab = await box.collaborate("src/index.ts")
4797
- * // Use collab.transport.websocketUrl + collab.transport.token
4798
- * // with @hocuspocus/provider to connect
4799
- * ```
4800
- */
4801
- collaborate(path: string, options?: {
4802
- access?: "read" | "write";
4803
- }): Promise<{
4804
- documentId: string;
4805
- transport: {
4806
- websocketUrl: string;
4807
- token: string;
4808
- expiresAt: number;
4809
- };
4810
- permissions: {
4811
- access: "read" | "write";
4812
- canSnapshot: boolean;
4813
- };
4814
- }>;
4815
- /**
4816
- * Refresh a collaboration token for an existing document session.
4817
- */
4818
- /**
4819
- * Refresh a collaboration token. Access level is preserved from the original
4820
- * token — cannot be escalated (read stays read, write stays write).
4821
- */
4822
- refreshCollaborationToken(documentId: string, currentToken: string): Promise<{
4823
- token: string;
4824
- expiresAt: number;
4825
- access: "read" | "write";
4826
- }>;
4827
- /**
4828
- * Get SSH credentials for connecting to the sandbox.
4829
- * Throws if SSH is not enabled or sandbox is not running.
4830
- */
4831
- ssh(): Promise<SSHCredentials>;
4832
- sshCommand(): Promise<SSHCommandDescriptor>;
4833
- /**
4834
- * Execute a command in the sandbox.
4835
- */
4836
- exec(command: string, options?: ExecOptions): Promise<ExecResult>;
4837
- /**
4838
- * Run code in a persistent language kernel.
4839
- *
4840
- * Each `(sessionId, language)` pair gets its own long-lived kernel that
4841
- * keeps variable state across calls — like Jupyter cells. Without a
4842
- * `sessionId`, calls share a process-wide kernel per language.
4843
- *
4844
- * Returns typed results: stdout/stderr text plus a `results` array of
4845
- * structured outputs (matplotlib images as base64 PNG, pandas DataFrames,
4846
- * explicit `display(value)` calls as JSON/HTML, errors with traceback).
4847
- *
4848
- * @example Persistent Python session
4849
- * ```ts
4850
- * await box.runCode("python", "import pandas as pd; df = pd.DataFrame({'x': range(5)})", { sessionId: "s1" });
4851
- * const r = await box.runCode("python", "df.describe()", { sessionId: "s1" });
4852
- * // r.results[0] is a `dataframe` part with columns + rows from the describe()
4853
- * ```
4854
- *
4855
- * @example Matplotlib chart
4856
- * ```ts
4857
- * const r = await box.runCode("python",
4858
- * "import matplotlib.pyplot as plt; plt.plot([1,2,3,4]); plt.show()",
4859
- * { sessionId: "s1" });
4860
- * const png = r.results.find(p => p.type === "image");
4861
- * // png.data is a base64 PNG ready to render or hand back to an LLM
4862
- * ```
4863
- */
4864
- runCode(language: CodeLanguage, source: string, options?: CodeExecutionOptions): Promise<CodeExecutionResult>;
4865
- /**
4866
- * Read a file from the sandbox.
4867
- *
4868
- * @param path - Path to the file. Relative paths resolve from the workspace root.
4869
- * Absolute paths (e.g., `/tmp/output.json`) access the container filesystem directly.
4870
- * @returns File content as string
4871
- *
4872
- * @example
4873
- * ```typescript
4874
- * const content = await box.read("src/index.ts");
4875
- * const report = await box.read("/output/report.json");
4876
- * ```
4877
- */
4878
- read(path: string, options?: {
4879
- sessionId?: string;
4880
- }): Promise<string>;
4881
- /**
4882
- * Write content to a file in the sandbox.
4883
- *
4884
- * @param path - Path to the file. Relative paths resolve from the workspace root.
4885
- * Absolute paths (e.g., `/tmp/cases.json`) write to the container filesystem directly.
4886
- * @param content - Content to write
4887
- *
4888
- * @example
4889
- * ```typescript
4890
- * await box.write("src/fix.ts", "export const fix = () => {}");
4891
- * await box.write("/tmp/config.json", JSON.stringify(config));
4892
- * ```
4893
- */
4894
- write(path: string, content: string, options?: WriteFileOptions): Promise<void>;
4895
- /**
4896
- * Write many files in one paced, retry-aware batch — see
4897
- * {@link FileSystem.writeMany}. Each file goes through {@link write}; a small
4898
- * pace between writes keeps a large corpus under the file-write rate limit,
4899
- * and transient failures (quota / server / network / timeout) retry with
4900
- * exponential backoff (honoring a server `retryAfterMs`). Fail-loud on the
4901
- * first file that cannot be written after its retries.
4902
- */
4903
- writeMany(files: WriteManyFile[], options?: WriteManyOptions): Promise<void>;
4904
- /**
4905
- * Send a prompt to the agent running in the sandbox.
4906
- * Returns the complete response after the agent finishes.
4907
- */
4908
- prompt(message: string | PromptInputPart[], options?: PromptOptions): Promise<PromptResult>;
4909
- private logStreamCheckpoint;
4910
- /**
4911
- * Stream events from an agent prompt.
4912
- * Use this for real-time updates during agent execution.
4913
- *
4914
- * Guarantees a terminal event on every non-cancelled path: a clean run
4915
- * ends with the runtime's `result`/`done`; a failure (pre-stream HTTP
4916
- * error, mid-stream network drop, timeout, or reconnect exhaustion) is
4917
- * surfaced as an in-band `error` event followed by a synthetic `done`,
4918
- * never a thrown generator. Caller-initiated cancellation (aborting
4919
- * `options.signal`) ends the stream silently with no synthetic terminal.
4920
- *
4921
- * Automatically reconnects via the runtime event replay endpoint if the
4922
- * SSE stream drops before a terminal event (`result` or `done`) is
4923
- * received. Reconnection is transparent — replayed events that were
4924
- * already yielded (based on event ID tracking) are deduplicated.
4925
- */
4926
- streamPrompt(message: string | PromptInputPart[], options?: PromptOptions): AsyncGenerator<SandboxEvent>;
4927
- /**
4928
- * Inner prompt stream: opens the SSE connection and reconnects on silent
4929
- * drops. May throw (pre-stream HTTP error, timeout, reconnect exhausted);
4930
- * the public `streamPrompt` wrapper converts those throws into a terminal
4931
- * `error` + `done` so callers never see a thrown generator.
4932
- */
4933
- private streamPromptInner;
4934
- /**
4935
- * Stream sandbox lifecycle and activity events.
4936
- */
4937
- events(options?: EventStreamOptions): AsyncGenerator<SandboxEvent>;
4938
- trace(options?: SandboxTraceOptions): Promise<SandboxTraceBundle>;
4939
- intelligence(): Promise<NonNullable<SandboxTraceBundle["intelligence"]>>;
4940
- createIntelligenceReport(options?: {
4941
- mode?: "deterministic" | "agentic";
4942
- acknowledgeCost?: boolean;
4943
- budget?: IntelligenceReportBudget;
4944
- metadata?: Record<string, unknown>; /** Bound the analysis to a time window. */
4945
- window?: IntelligenceReportWindow; /** Compare this sandbox against a same-type baseline sandbox. */
4946
- compareTo?: IntelligenceReportCompareTo;
4947
- }): Promise<IntelligenceReport>;
4948
- createAgenticIntelligenceReport(options: {
4949
- maxUsd: number;
4950
- metadata?: Record<string, unknown>;
4951
- }): Promise<IntelligenceReport>;
4952
- exportTrace(sink: TraceExportSink): Promise<TraceExportResult>;
4953
- /**
4954
- * Stream real-time provisioning progress events.
4955
- *
4956
- * Connects to the SSE events stream and yields typed `ProvisionEvent` objects
4957
- * for each provisioning step. The generator completes when provisioning
4958
- * finishes (success or failure) and returns the terminal result.
4959
- *
4960
- * @returns AsyncGenerator of ProvisionEvent, with a ProvisionResult return value
4961
- *
4962
- * @example
4963
- * ```typescript
4964
- * const box = await client.create({ image: "ethereum" });
4965
- *
4966
- * const stream = box.watchProvisioning();
4967
- * for await (const event of stream) {
4968
- * console.log(`[${event.step}] ${event.status} — ${event.message}`);
4969
- * }
4970
- * // stream.return value contains the terminal result
4971
- * ```
4972
- */
4973
- watchProvisioning(options?: {
4974
- signal?: AbortSignal;
4975
- }): AsyncGenerator<ProvisionEvent, ProvisionResult | undefined>;
4976
- /**
4977
- * Run an agentic task until completion.
4978
- *
4979
- * Unlike prompt(), task() is designed for autonomous agent work:
4980
- * - The agent works until it completes the task or hits an error
4981
- * - Session state is maintained for context continuity
4982
- * - Token usage is aggregated across the execution
4983
- *
4984
- * Note: The agent (OpenCode/Claude) handles multi-turn execution internally.
4985
- * Most tasks complete in a single call. The maxTurns option is for edge cases
4986
- * where the agent explicitly signals it needs additional input.
4987
- *
4988
- * @param prompt - Task description for the agent
4989
- * @param options - Task options
4990
- * @returns Task result with response and execution metadata
4991
- */
4992
- task(prompt: string, options?: TaskOptions): Promise<TaskResult>;
4993
- /**
4994
- * Stream events from a task execution.
4995
- *
4996
- * Use this for real-time updates as the agent works:
4997
- * - Tool calls and results
4998
- * - Thinking/reasoning steps
4999
- * - File operations
5000
- * - Final response
5001
- *
5002
- * @param prompt - Task description for the agent
5003
- * @param options - Task options
5004
- */
5005
- streamTask(prompt: string, options?: TaskOptions): AsyncGenerator<SandboxEvent>;
5006
- /**
5007
- * Search for text patterns in files using ripgrep.
5008
- *
5009
- * This is a first-class code search capability, not a shell wrapper.
5010
- * Ripgrep is pre-installed in all managed sandboxes.
5011
- *
5012
- * @param pattern - Regular expression pattern to search for
5013
- * @param options - Search options
5014
- * @returns Async iterator of search matches
5015
- *
5016
- * @example Search for task-marker comments
5017
- * ```typescript
5018
- * for await (const match of box.search("TASK:", { glob: "**\/*.ts" })) {
5019
- * console.log(`${match.path}:${match.line}: ${match.text}`);
5020
- * }
5021
- * ```
5022
- *
5023
- * @example Collect all matches
5024
- * ```typescript
5025
- * const matches = [];
5026
- * for await (const match of box.search("function.*async")) {
5027
- * matches.push(match);
5028
- * }
5029
- * ```
5030
- */
5031
- search(pattern: string, options?: SearchOptions): AsyncGenerator<SearchMatch>;
5032
- /**
5033
- * Live whole-sandbox resource usage (memory + CPU) from the container cgroup.
5034
- *
5035
- * Returns `null` when cgroup stats are unavailable (non-Linux host). Memory is
5036
- * in MB; `memoryPeakMb` is the high-water mark since the sandbox started. CPU
5037
- * is a cumulative microsecond counter — sample twice and compute
5038
- * `cpu% = ΔcpuUsageUsec / (ΔsampledAtMs * 10)` for utilization.
5039
- *
5040
- * @example
5041
- * ```typescript
5042
- * const r = await box.resourceUsage();
5043
- * if (r) console.log(`peak ${r.memoryPeakMb} MB`);
5044
- * ```
5045
- */
5046
- resourceUsage(): Promise<SandboxResourceUsage | null>;
5047
- /**
5048
- * Git capability object for repository operations.
5049
- *
5050
- * All git operations are executed in the sandbox workspace.
5051
- *
5052
- * @example Check status and commit
5053
- * ```typescript
5054
- * const status = await box.git.status();
5055
- * if (status.isDirty) {
5056
- * await box.git.add(["."]);
5057
- * await box.git.commit("Update files");
5058
- * await box.git.push();
5059
- * }
5060
- * ```
5061
- */
5062
- get git(): GitCapability;
5063
- private gitStatus;
5064
- private gitLog;
5065
- private gitDiff;
5066
- private gitAdd;
5067
- private gitCommit;
5068
- private gitPush;
5069
- private gitPull;
5070
- private gitBranches;
5071
- private gitCheckout;
5072
- /**
5073
- * Tools capability object for managing language runtimes.
5074
- *
5075
- * Uses mise (polyglot version manager) to install and manage tools.
5076
- *
5077
- * @example Install and use Node.js
5078
- * ```typescript
5079
- * await box.tools.install("node", "22");
5080
- * await box.tools.use("node", "22");
5081
- * const list = await box.tools.list();
5082
- * ```
5083
- */
5084
- get tools(): ToolsCapability;
5085
- /**
5086
- * File system operations beyond basic read/write:
5087
- * - Binary upload/download
5088
- * - Directory ops (uploadDir, downloadDir, list, mkdir)
5089
- * - Metadata (stat, exists)
5090
- * - Progress reporting for large files
5091
- *
5092
- * @example Upload and download
5093
- * ```typescript
5094
- * await box.fs.upload("./model.bin", "/workspace/models/model.bin");
5095
- * await box.fs.download("/workspace/results.zip", "./results.zip");
5096
- * ```
5097
- *
5098
- * @example Directory operations
5099
- * ```typescript
5100
- * await box.fs.uploadDir("./project", "/workspace/project");
5101
- * const files = await box.fs.list("/workspace");
5102
- * ```
5103
- *
5104
- * @example File management
5105
- * ```typescript
5106
- * if (await box.fs.exists("/workspace/config.json")) {
5107
- * const info = await box.fs.stat("/workspace/config.json");
5108
- * console.log(`Size: ${info.size}`);
5109
- * }
5110
- * await box.fs.mkdir("/workspace/output", { recursive: true });
5111
- * await box.fs.delete("/workspace/temp", { recursive: true });
5112
- * ```
5113
- */
5114
- get fs(): FileSystem;
5115
- private fsUpload;
5116
- private fsDownload;
5117
- private fsUploadDir;
5118
- private fsDownloadDir;
5119
- private fsList;
5120
- private fsStat;
5121
- private fsDelete;
5122
- private fsMkdir;
5123
- private fsExists;
5124
- /**
5125
- * Permissions manager for multi-user access control.
5126
- *
5127
- * @example List users
5128
- * ```typescript
5129
- * const users = await box.permissions.list();
5130
- * for (const user of users) {
5131
- * console.log(`${user.username}: ${user.role}`);
5132
- * }
5133
- * ```
5134
- *
5135
- * @example Add a developer
5136
- * ```typescript
5137
- * await box.permissions.add({
5138
- * userId: "user_abc",
5139
- * role: "developer",
5140
- * sshKeys: ["ssh-ed25519 AAAA..."],
5141
- * });
5142
- * ```
5143
- */
5144
- get permissions(): PermissionsManager;
5145
- private permissionsList;
5146
- private permissionsGet;
5147
- private permissionsAdd;
5148
- private permissionsUpdate;
5149
- private permissionsRemove;
5150
- private permissionsSetAccessPolicies;
5151
- private permissionsGetAccessPolicies;
5152
- private permissionsCheckAccess;
5153
- /**
5154
- * Backend manager for runtime agent configuration.
5155
- *
5156
- * @example Check backend status
5157
- * ```typescript
5158
- * const status = await box.backend.status();
5159
- * console.log(`Backend: ${status.type}, Status: ${status.status}`);
5160
- * ```
5161
- *
5162
- * @example Add MCP server at runtime
5163
- * ```typescript
5164
- * await box.backend.addMcp("web-search", {
5165
- * command: "npx",
5166
- * args: ["-y", "@anthropic/web-search"],
5167
- * });
5168
- * ```
5169
- *
5170
- * @example Read provider-native Cursor metadata
5171
- * ```typescript
5172
- * const models = await box.backend.models();
5173
- * const agents = await box.backend.agents({ limit: 20 });
5174
- * const runs = await box.backend.runs(agents.items[0].agentId);
5175
- * ```
5176
- */
5177
- get backend(): BackendManager;
5178
- private backendStatus;
5179
- private backendCapabilities;
5180
- private backendAddMcp;
5181
- private backendGetMcpStatus;
5182
- private backendUpdateConfig;
5183
- private backendControlData;
5184
- private backendControlAction;
5185
- private backendListSearch;
5186
- private backendAccount;
5187
- private backendModels;
5188
- private backendRepositories;
5189
- private backendAgents;
5190
- private backendAgent;
5191
- private backendArchiveAgent;
5192
- private backendUnarchiveAgent;
5193
- private backendDeleteAgent;
5194
- private backendRuns;
5195
- private backendRun;
5196
- private backendAgentMessages;
5197
- private backendArtifacts;
5198
- private backendDownloadArtifact;
5199
- private backendRestart;
5200
- /**
5201
- * Process manager for spawning and controlling processes.
5202
- *
5203
- * Provides non-blocking process execution with real-time log streaming,
5204
- * ideal for long-running tasks like ML training or dev servers.
5205
- *
5206
- * @example Non-blocking process
5207
- * ```typescript
5208
- * const proc = await box.process.spawn("python train.py", {
5209
- * cwd: "/workspace",
5210
- * env: { "CUDA_VISIBLE_DEVICES": "0" }
5211
- * });
5212
- *
5213
- * // Stream logs
5214
- * for await (const entry of proc.logs()) {
5215
- * console.log(`[${entry.type}] ${entry.data}`);
5216
- * }
5217
- *
5218
- * // Check status
5219
- * const status = await proc.status();
5220
- * console.log(`Running: ${status.running}`);
5221
- *
5222
- * // Kill if needed
5223
- * await proc.kill();
5224
- * ```
5225
- *
5226
- * @example Run Python code directly
5227
- * ```typescript
5228
- * const result = await box.process.runCode(`
5229
- * import numpy as np
5230
- * print(np.random.rand(10).mean())
5231
- * `);
5232
- * console.log(result.stdout);
5233
- * ```
5234
- */
5235
- get process(): ProcessManager;
5236
- private processSpawn;
5237
- private processRunCode;
5238
- private processList;
5239
- private processGet;
5240
- private createProcessHandle;
5241
- private parseProcessLogStream;
5242
- /**
5243
- * Network manager for runtime network configuration.
5244
- *
5245
- * @example Update network restrictions
5246
- * ```typescript
5247
- * // Block all outbound traffic
5248
- * await box.network.update({ blockOutbound: true });
5249
- *
5250
- * // Or switch to allowlist mode
5251
- * await box.network.update({
5252
- * allowList: ["192.168.1.0/24", "8.8.8.8/32"]
5253
- * });
5254
- * ```
5255
- *
5256
- * @example Expose ports dynamically
5257
- * ```typescript
5258
- * const url = await box.network.exposePort(8000);
5259
- * console.log(`Service available at: ${url}`);
5260
- * ```
5261
- */
5262
- get network(): NetworkManager;
5263
- /**
5264
- * Egress policy manager for controlling outbound internet access.
5265
- *
5266
- * @example Read current egress policy
5267
- * ```typescript
5268
- * const { policy, source } = await box.egress.get();
5269
- * console.log(policy.mode, source);
5270
- * ```
5271
- *
5272
- * @example Update egress policy at runtime
5273
- * ```typescript
5274
- * await box.egress.update({ mode: "strict", allowDomains: ["api.github.com"] });
5275
- * ```
5276
- */
5277
- get egress(): EgressManager;
5278
- /**
5279
- * On-demand GPU leases attached to this sandbox.
5280
- *
5281
- * The base sandbox stays cheap; `attach` starts a temporary external GPU
5282
- * worker with an explicit spend cap, and `detach` destroys it.
5283
- */
5284
- get gpu(): GpuLeaseManager;
5285
- private networkUpdate;
5286
- private networkExposePort;
5287
- private networkListUrls;
5288
- private networkGetConfig;
5289
- private egressGet;
5290
- private egressUpdate;
5291
- private gpuAttach;
5292
- private gpuList;
5293
- private gpuExec;
5294
- private gpuDetach;
5295
- /**
5296
- * Validate CIDR notation (IPv4 and IPv6)
5297
- */
5298
- private isValidCidr;
5299
- /**
5300
- * Preview link management.
5301
- *
5302
- * Create publicly accessible HTTPS URLs for TCP ports inside the sandbox.
5303
- *
5304
- * @example
5305
- * ```typescript
5306
- * const link = await box.previewLinks.create(3000);
5307
- * console.log(link.url);
5308
- *
5309
- * const links = await box.previewLinks.list();
5310
- * await box.previewLinks.remove(link.previewId);
5311
- * ```
5312
- */
5313
- get previewLinks(): PreviewLinkManager;
5314
- private previewLinkCreate;
5315
- private previewLinkList;
5316
- private previewLinkRemove;
5317
- /**
5318
- * Get information about the infrastructure driver for this sandbox.
5319
- *
5320
- * @example
5321
- * ```typescript
5322
- * const info = await box.getDriverInfo();
5323
- * console.log(`Driver: ${info.type}, CRIU: ${info.capabilities.criu}`);
5324
- * ```
5325
- */
5326
- getDriverInfo(): Promise<DriverInfo>;
5327
- private toolsInstall;
5328
- private toolsUse;
5329
- private toolsList;
5330
- private toolsRun;
5331
- /**
5332
- * Create a snapshot of the sandbox state.
5333
- * Snapshots can be used to save workspace state for later restoration.
5334
- *
5335
- * If `storage` is provided (BYOS3), the snapshot is created directly
5336
- * directly on the sandbox and uploaded to customer-provided S3 storage.
5337
- *
5338
- * @param options - Snapshot options (tags, paths, storage)
5339
- * @returns Snapshot result with ID and metadata
5340
- *
5341
- * @example Standard snapshot (our storage)
5342
- * ```typescript
5343
- * const snap = await box.snapshot({
5344
- * tags: ["v1.0", "stable"],
5345
- * });
5346
- * console.log(`Snapshot: ${snap.snapshotId}`);
5347
- * ```
5348
- *
5349
- * @example BYOS3 snapshot (customer storage)
5350
- * ```typescript
5351
- * const snap = await box.snapshot({
5352
- * tags: ["production"],
5353
- * storage: {
5354
- * type: "s3",
5355
- * bucket: "my-snapshots",
5356
- * credentials: { accessKeyId: "...", secretAccessKey: "..." },
5357
- * },
5358
- * });
5359
- * ```
5360
- */
5361
- snapshot(options?: SnapshotOptions): Promise<SnapshotResult>;
5362
- /**
5363
- * List all snapshots for this sandbox.
5364
- *
5365
- * If `storage` is provided (BYOS3), lists snapshots from customer-provided
5366
- * S3 storage.
5367
- *
5368
- * @param storage - Optional customer storage config for BYOS3
5369
- * @returns Array of snapshot metadata
5370
- *
5371
- * @example List from our storage
5372
- * ```typescript
5373
- * const snapshots = await box.listSnapshots();
5374
- * for (const snap of snapshots) {
5375
- * console.log(`${snap.snapshotId}: ${snap.createdAt}`);
5376
- * }
5377
- * ```
5378
- *
5379
- * @example List from customer S3 (BYOS3)
5380
- * ```typescript
5381
- * const snapshots = await box.listSnapshots({
5382
- * type: "s3",
5383
- * bucket: "my-snapshots",
5384
- * credentials: { accessKeyId: "...", secretAccessKey: "..." },
5385
- * });
5386
- * ```
5387
- */
5388
- listSnapshots(storage?: SnapshotOptions["storage"]): Promise<SnapshotInfo[]>;
5389
- revertToSnapshot(snapshotId: string): Promise<SnapshotResult>;
5390
- private waitForSnapshotRestore;
5391
- private waitForSnapshotVisible;
5392
- deleteSnapshot(snapshotId: string): Promise<void>;
5393
- /**
5394
- * Restore from the latest snapshot in customer-provided storage.
5395
- * Only available when using BYOS3 (calls the runtime directly).
5396
- *
5397
- * @param storage - Customer storage config (required)
5398
- * @param destinationPath - Optional path to restore to
5399
- * @returns Snapshot info if restored, null if no snapshot found
5400
- *
5401
- * @example Restore from customer S3
5402
- * ```typescript
5403
- * const result = await box.restoreFromStorage({
5404
- * type: "s3",
5405
- * bucket: "my-snapshots",
5406
- * credentials: { accessKeyId: "...", secretAccessKey: "..." },
5407
- * });
5408
- *
5409
- * if (result) {
5410
- * console.log(`Restored from ${result.snapshotId}`);
5411
- * } else {
5412
- * console.log("No snapshot found");
5413
- * }
5414
- * ```
5415
- */
5416
- restoreFromStorage(storage: SnapshotOptions["storage"], options?: RestoreSnapshotOptions): Promise<SnapshotResult | null>;
5417
- /**
5418
- * @deprecated CRIU checkpoints were removed. To branch live memory into
5419
- * copy-on-write children of a running sandbox use {@link branch}; for durable
5420
- * filesystem state use {@link snapshot}. This method now throws.
5421
- */
5422
- checkpoint(): never;
5423
- /**
5424
- * @deprecated CRIU checkpoints were removed. List durable filesystem state
5425
- * with {@link listSnapshots}. This method now throws.
5426
- */
5427
- listCheckpoints(): never;
5428
- /**
5429
- * @deprecated CRIU checkpoints were removed. This method now throws.
5430
- */
5431
- deleteCheckpoint(): never;
5432
- /**
5433
- * @deprecated Forking from a CRIU checkpoint was removed. Use {@link branch}
5434
- * to fork a running sandbox's live memory into copy-on-write children, or
5435
- * `client.create({ fromSnapshot })` to provision from durable disk state.
5436
- * This method now throws.
5437
- */
5438
- fork(): never;
5439
- /**
5440
- * Branch this RUNNING sandbox into `count` copy-on-write children
5441
- * (Morph Infinibranch parity). Unlike {@link fork} — which rehydrates one
5442
- * sandbox from a CRIU checkpoint — branch forks the live VM's memory into
5443
- * many children at once via Firecracker UFFD copy-on-write: the children
5444
- * share the parent's clean pages instead of each copying full guest
5445
- * memory. The parent stays running.
5446
- *
5447
- * @param count - Number of children to create (must be >= 1).
5448
- * @param options - Per-child overrides.
5449
- * @returns Exactly `count` new sandbox instances.
5450
- *
5451
- * @example
5452
- * ```typescript
5453
- * const [a, b, c] = await box.branch(3);
5454
- * // a, b, c each share box's memory state at branch time
5455
- * ```
5456
- */
5457
- branch(count: number, options?: BranchOptions): Promise<SandboxInstance[]>;
5458
- /**
5459
- * Stop the sandbox (keeps state for resume).
5460
- */
5461
- stop(): Promise<void>;
5462
- /**
5463
- * Resume a stopped sandbox.
5464
- */
5465
- resume(options?: ResumeOptions): Promise<void>;
5466
- /**
5467
- * Delete the sandbox permanently.
5468
- */
5469
- delete(): Promise<void>;
5470
- /**
5471
- * keepAlive is intentionally unavailable until the API exposes timeout updates.
5472
- * @param seconds - Reserved for future support
5473
- */
5474
- keepAlive(_seconds?: number): Promise<void>;
5475
- /**
5476
- * Upload a local directory to the sandbox via tar.
5477
- * @param localPath - Local directory path to upload
5478
- * @param remotePath - Destination path in the sandbox (default: /home/user)
5479
- */
5480
- uploadDirectory(localPath: string, remotePath?: string): Promise<void>;
5481
- /**
5482
- * Wait for the sandbox to reach a specific status.
5483
- *
5484
- * When `onProgress` is provided and the sandbox is still provisioning,
5485
- * uses SSE events for real-time progress instead of polling. Falls back
5486
- * to polling if the SSE connection fails or is unavailable.
5487
- *
5488
- * @example Basic wait
5489
- * ```typescript
5490
- * await box.waitFor("running");
5491
- * ```
5492
- *
5493
- * @example Wait with progress tracking
5494
- * ```typescript
5495
- * await box.waitFor("running", {
5496
- * onProgress: (event) => {
5497
- * console.log(`[${event.step}] ${event.status} — ${event.message}`);
5498
- * if (event.percent !== undefined) {
5499
- * updateProgressBar(event.percent);
5500
- * }
5501
- * },
5502
- * });
5503
- * ```
5504
- */
5505
- waitFor(status: SandboxStatus | SandboxStatus[], options?: WaitForOptions): Promise<void>;
5506
- /**
5507
- * SSE-based wait implementation. Subscribes to provisioning events and
5508
- * delivers progress callbacks while waiting for a target status.
5509
- */
5510
- private waitForWithSSE;
5511
- private ensureRunning;
5512
- private runtimeFetch;
5513
- /**
5514
- * Delegates to the shared `parseSSEStream` in `lib/sse-parser.ts`
5515
- * — one canonical SSE implementation for the whole SDK. The
5516
- * shared parser throws `AbortError` on cancellation (so consumers
5517
- * can distinguish cancel from clean EOF), but agent/task streaming
5518
- * callers of this method historically relied on a silent-return
5519
- * abort: they check `options?.signal?.aborted` AFTER the loop and
5520
- * decide whether to reconnect. The try/catch below preserves that
5521
- * legacy contract by swallowing AbortError at the delegate layer.
5522
- */
5523
- private parseSSEStream;
5524
- /**
5525
- * Associate a session ID with a user ID so the Sandbox API can route
5526
- * subsequent WebSocket connections to this sandbox.
5527
- *
5528
- * @param opts - Session and user identifiers
5529
- *
5530
- * @example
5531
- * ```typescript
5532
- * await box.registerSessionMapping({
5533
- * sessionId: "sess_abc",
5534
- * userId: "user_123",
5535
- * });
5536
- * ```
5537
- */
5538
- registerSessionMapping(opts: {
5539
- sessionId: string;
5540
- userId: string; /** The runtime (sidecar) session id this agent session routes to. */
5541
- runtimeSessionId: string; /** Optional container id for direct routing. */
5542
- sidecarId?: string; /** Optional projectRef so the server can detect a stale sidecar. */
5543
- projectRef?: string;
5544
- }): Promise<SessionMappingResult>;
5545
- /**
5546
- * Remove the sidecar session mapping for an agent session. Sandbox deletion
5547
- * also cleans mappings, so this is only needed to release a mapping while the
5548
- * sandbox stays alive.
5549
- */
5550
- unregisterSessionMapping(opts: {
5551
- sessionId: string;
5552
- userId: string;
5553
- }): Promise<{
5554
- success: boolean;
5555
- sessionId: string;
5556
- }>;
5557
- private parseInfo;
5558
- private sleep;
5559
- /**
5560
- * Get a session reference bound to this sandbox. Lazy: does not hit the
5561
- * network until you call a method on the returned `SandboxSession`.
5562
- * Use {@link sessions} to discover existing session ids.
5563
- */
5564
- session(id: string): SandboxSession;
5565
- /**
5566
- * List sessions on this sandbox, optionally filtering by status. Returns
5567
- * `SandboxSession` instances paired with their last-known
5568
- * {@link SessionInfo} so callers can avoid an extra round-trip per
5569
- * session for status.
5570
- */
5571
- sessions(opts?: SessionListOptions): Promise<Array<{
5572
- session: SandboxSession;
5573
- info: SessionInfo;
5574
- }>>;
5575
- /**
5576
- * Dispatch a prompt and return immediately with the session id (Issue
5577
- * #913 Gap 2). The sandbox keeps running the prompt after this call
5578
- * returns; reconnect via `box.session(id).events()` or wait for
5579
- * completion with `box.session(id).result()`.
5580
- *
5581
- * Idempotent on `opts.sessionId`: re-dispatching with the same id when
5582
- * the session is already running is a lookup, not a re-create. This
5583
- * lets queue retries and reconnect-after-Worker-restart be safe by
5584
- * construction.
5585
- */
5586
- dispatchPrompt(message: string | PromptInputPart[], opts?: DispatchPromptOptions): Promise<DispatchedSession>;
5587
- /**
5588
- * List messages for a session, including in-flight assistant content
5589
- * the agent is still streaming. Each entry's `metadata` carries the
5590
- * durability marker — `status: "streaming" | "completed" | "interrupted"`,
5591
- * `completed/interrupted` booleans, and the caller-supplied `turnId`
5592
- * when one was set. See `SessionMessage` for the full contract.
5593
- *
5594
- * Polling this is the right way to detect "did the sidecar die mid-
5595
- * turn?" — a SIGKILL leaves the assistant message with `status:
5596
- * "streaming"` and no `completed`/`interrupted` marker; a graceful
5597
- * abort stamps `interrupted: true` explicitly.
5598
- */
5599
- messages(opts: ListMessagesOptions): Promise<SessionMessage[]>;
5600
- _sessionFork(id: string, opts?: SessionForkOptions): Promise<SessionInfo>;
5601
- /**
5602
- * Look up a cached turn result by idempotency key. Returns the cached
5603
- * payload if a turn with this `turnId` previously completed on the
5604
- * given session; returns `null` if no such turn has finished yet
5605
- * (either it never started, or it interrupted before completion).
5606
- *
5607
- * Call this before re-issuing a `streamPrompt` / `prompt` / `task`
5608
- * that you might be retrying — a non-null result means the original
5609
- * attempt finished and you can return that to your caller instead of
5610
- * running the agent a second time. Only turns that reach the
5611
- * `completed` terminal state are cached; interrupted turns are not.
5612
- */
5613
- findCompletedTurn(turnId: string, opts: {
5614
- sessionId: string;
5615
- }): Promise<CompletedTurnResult | null>;
5616
- /**
5617
- * Drive a detached turn forward by exactly one settle → poll → dispatch
5618
- * pass and report where it stands. Built for tick-based callers —
5619
- * Cloudflare Workflows steps, queue consumers, crons — that re-invoke
5620
- * on their own schedule instead of holding a stream open. One
5621
- * invocation never loops, never sleeps, and never keeps a connection
5622
- * alive past the pass.
5623
- *
5624
- * The pass resolves to the first of:
5625
- * 1. The completed-turn cache has `turnId` → `completed`, or `failed`
5626
- * when the cached payload carries no text — that result is final,
5627
- * so a retry cannot improve it.
5628
- * 2. The session is queued/running → `running`, after enforcing
5629
- * `wallCapMs`: a session past the cap is cancelled and reported
5630
- * `failed`.
5631
- * 3. The session is terminal without a cached turn → settle from the
5632
- * session result; an unsuccessful result is `failed`.
5633
- * 4. No session exists → dispatch fire-and-detach (idempotent on
5634
- * `sessionId`, exactly like `dispatchPrompt`) → `running`.
5635
- *
5636
- * `failed` is always deterministic: re-invoking with the same ids
5637
- * returns the same outcome rather than starting a second agent run, so
5638
- * callers can treat it as terminal without their own retry bookkeeping.
5639
- */
5640
- driveTurn(message: string | PromptInputPart[], opts: DriveTurnOptions): Promise<TurnDriveResult>;
5641
- /**
5642
- * Mint a scoped, time-bounded JWT for direct browser access to this
5643
- * sandbox (Issue #913 Gap 1). Authority is the caller's
5644
- * `TANGLE_API_KEY` (sk-tan-*) — the Sandbox API mints the token;
5645
- * signing secrets stay server-side.
5646
- *
5647
- * Use this to give a browser direct read access to the sandbox without
5648
- * leaking the full bearer (`box.connection.authToken`). The returned
5649
- * token verifies against the same sidecar middleware that already
5650
- * gates ProductTokenIssuer-issued JWTs — no new sidecar surface.
5651
- */
5652
- mintScopedToken(opts: MintScopedTokenOptions): Promise<ScopedToken>;
5653
- /** @internal — invoked by SandboxSession.status(). */
5654
- _sessionStatus(id: string): Promise<SessionInfo | null>;
5655
- /** @internal — invoked by SandboxSession.events(). */
5656
- _sessionEvents(id: string, opts?: SessionEventStreamOptions): AsyncGenerator<SandboxEvent>;
5657
- /** @internal — invoked by SandboxSession.result(). */
5658
- _sessionResult(id: string): Promise<PromptResult>;
5659
- /**
5660
- * @internal — invoked by SandboxSession.cancel(). Void-returning alias of
5661
- * `_interrupt`: both abort the in-flight execution via `POST /{id}/abort`
5662
- * (the session and its messages are preserved). `cancel()` discards the
5663
- * `cancelled` flag; callers that need to distinguish a real interruption
5664
- * from a no-op should use `interrupt()`.
5665
- */
5666
- _sessionCancel(id: string): Promise<void>;
5667
- /** @internal — invoked by InteractiveSessionHandle.start(). */
5668
- _startInteractive(id: string, options: StartInteractiveOptions): Promise<InteractiveSessionInfo>;
5669
- /** @internal — invoked by InteractiveSessionHandle.sendPrompt(). */
5670
- _sendInteractivePrompt(id: string, prompt: string): Promise<void>;
5671
- /** @internal — invoked by InteractiveSessionHandle.stop(). */
5672
- _stopInteractive(id: string): Promise<void>;
5673
- /** @internal — invoked by SandboxSession.respondToPermission(). */
5674
- _respondToPermission(id: string, permissionID: string, options: RespondToPermissionOptions): Promise<void>;
5675
- /** @internal — invoked by SandboxSession.interrupt(). */
5676
- _interrupt(id: string): Promise<InterruptResult>;
5677
- /**
5678
- * @internal — invoked by SandboxSession.answer(). Resolves the session's
5679
- * outstanding question interaction and posts the answer through the
5680
- * interaction response route. The positional answer arrays map onto the
5681
- * question's `answerSpec` fields in order.
5682
- */
5683
- _answerQuestion(id: string, answers: Record<string, string[]>): Promise<void>;
5684
- }
5685
- //#endregion
5686
- export { CreateSandboxFleetOptions as $, SandboxFleetMachineRecord as $n, ToolsConfig as $r, ListMessagesOptions as $t, AttachGpuLeaseOptions as A, PublishPublicTemplateVersionOptions as An, SecretInfo as Ar, GitAuth as At, BatchResult as B, SandboxEnvironment as Bn, SshKeysManager as Br, GpuLeaseExecResult as Bt, SandboxMcpEndpoint as C, defineAgentProfile as Ci, ProvisionEvent as Cn, SandboxTraceExport as Cr, FleetDispatchStreamOptions as Ct, AcceleratorKind as D, PublicTemplateInfo as Dn, ScopedTokenScope as Dr, FleetPromptDispatchOptions as Dt, buildSandboxMcpConfig as E, mergeAgentProfiles as Ei, ProvisionStep as En, ScopedToken as Er, FleetMachineId as Et, BackendManager as F, RunCodeOptions as Fn, SessionMessage as Fr, GitStatus as Ft, CodeExecutionResult as G, SandboxFleetDispatchFailureClass as Gn, TaskOptions as Gr, HostAgentDriverConfig as Gt, BatchTaskResult as H, SandboxFleetArtifact as Hn, StartupOperation as Hr, GpuLeaseProviderName as Ht, BackendStatus as I, SSHCommandDescriptor as In, SessionStatus as Ir, GpuLease as It, CodeResultPart as J, SandboxFleetDriverTimings as Jn, TeeAttestationReport as Jr, IntelligenceReport as Jt, CodeLanguage as K, SandboxFleetDispatchResponse as Kn, TaskResult as Kr, HostAgentRuntimeBackend as Kt, BackendType as L, SSHCredentials as Ln, SnapshotInfo as Lr, GpuLeaseBilling as Lt, BackendCapabilities as M, ReapExpiredSandboxFleetsResult as Mn, SessionEventStreamOptions as Mr, GitCommit as Mt, BackendConfig as N, ReconcileSandboxFleetsOptions as Nn, SessionInfo as Nr, GitConfig as Nt, AccessPolicyRule as O, PublicTemplateVersionInfo as On, SearchMatch as Or, FleetPromptDispatchResult as Ot, BackendInfo as P, ReconcileSandboxFleetsResult as Pn, SessionListOptions as Pr, GitDiff as Pt, CreateRequestOptions as Q, SandboxFleetMachineMeteredUsage as Qn, TokenRefreshHandler as Qr, IntelligenceReportWindow as Qt, BatchEvent as R, SandboxClientConfig as Rn, SnapshotOptions as Rr, GpuLeaseCommandResult as Rt, SandboxMcpConfig as S, AgentSubagentProfile as Si, PromptResult as Sn, SandboxTraceEvent as Sr, FleetDispatchResultBufferOptions as St, buildControlPlaneMcpConfig as T, defineInlineResource as Ti, ProvisionStatus as Tn, SandboxUser as Tr, FleetExecDispatchResult as Tt, BranchOptions as U, SandboxFleetArtifactSpec as Un, StorageConfig as Ur, GpuLeaseStatus as Ut, BatchTask as V, SandboxEvent as Vn, StartupDiagnostics as Vr, GpuLeaseManager as Vt, CodeExecutionOptions as W, SandboxFleetCostEstimate as Wn, SubscriptionInfo as Wr, GpuType as Wt, CreateGpuLeaseOptions as X, SandboxFleetIntelligenceEnvelope as Xn, TeePublicKey as Xr, IntelligenceReportCompareTo as Xt, CompletedTurnResult as Y, SandboxFleetInfo as Yn, TeeAttestationResponse as Yr, IntelligenceReportBudget as Yt, CreateIntelligenceReportOptions as Z, SandboxFleetMachine as Zn, TeePublicKeyResponse as Zr, IntelligenceReportSubjectType as Zt, StartInteractiveOptions as _, AgentProfilePrompt as _i, ProcessSignal as _n, SandboxPermissionsConfig as _r, ExecResult as _t, TraceExportSink as a, WaitForOptions as ai, MkdirOptions as an, SandboxFleetToken as ar, DispatchPromptOptions as at, CONTROL_PLANE_MCP_SERVER_NAME as b, AgentProfileValidationIssue as bi, PromptInputPart as bn, SandboxStatus as br, FleetDispatchCancelResult as bt, otelTraceIdForTangleTrace as c, WriteManyOptions as ci, NonHostAgentDriverConfig as cn, SandboxFleetTraceExport as cr, DownloadProgress as ct, InteractiveAuthFile as d, AgentProfileConfidential as di, PreviewLinkInfo as dn, SandboxFleetWorkspace as dr, DriverInfo as dt, TurnDriveResult as ei, ListOptions as en, SandboxFleetMachineSpec as er, CreateSandboxFleetTokenOptions as et, InteractiveSessionHandle as f, AgentProfileConnection as fi, PreviewLinkManager as fn, SandboxFleetWorkspaceReconcileResult as fr, DriverType as ft, RespondToPermissionOptions as g, AgentProfilePermissionValue as gi, ProcessManager as gn, SandboxIntelligenceEnvelope as gr, ExecOptions as gt, InterruptResult as h, AgentProfileModelHints as hi, ProcessLogEntry as hn, SandboxInfo as hr, EventStreamOptions as ht, TraceExportResult as i, UsageInfo as ii, MintScopedTokenOptions as in, SandboxFleetPolicy as ir, DirectoryPermission as it, AttachSandboxFleetMachineOptions as j, ReapExpiredSandboxFleetsOptions as jn, SecretsManager as jr, GitBranch as jt, AddUserOptions as k, PublishPublicTemplateOptions as kn, SearchOptions as kr, GPU_LEASE_PROVIDER_NAMES as kt, toOtelJson as l, AgentProfile as li, PermissionLevel as ln, SandboxFleetTraceOptions as lr, DriveTurnOptions as lt, InteractiveSessionInfo as m, AgentProfileMcpServer as mi, ProcessInfo as mn, SandboxFleetWorkspaceSnapshotResult as mr, EgressPolicy as mt, SandboxInstance as n, UploadOptions as ni, ListSandboxOptions as nn, SandboxFleetManifestMachine as nr, CreateSandboxOptions as nt, buildTraceExportPayload as o, WriteFileOptions as oi, NetworkConfig as on, SandboxFleetTraceBundle as or, DispatchedSession as ot, InteractiveSessionHost as p, AgentProfileFileMount as pi, Process as pn, SandboxFleetWorkspaceRestoreResult as pr, EgressManager as pt, CodeResult as q, SandboxFleetDriverCapability as qn, TeeAttestationOptions as qr, InstalledTool as qt, TraceExportFormat as r, UploadProgress as ri, McpServerConfig as rn, SandboxFleetOperationsSummary as rr, DeleteOptions as rt, exportTraceBundle as s, WriteManyFile as si, NetworkManager as sn, SandboxFleetTraceEvent as sr, DownloadOptions as st, HttpClient as t, UpdateUserOptions as ti, ListSandboxFleetOptions as tn, SandboxFleetManifest as tr, CreateSandboxFleetWithCoordinatorOptions as tt, SandboxSession as u, AgentProfileCapabilities as ui, PermissionsManager as un, SandboxFleetUsage as ur, DriverConfig as ut, BuildControlPlaneMcpConfigOptions as v, AgentProfileResourceRef as vi, ProcessSpawnOptions as vn, SandboxResourceUsage as vr, FileInfo as vt, SandboxMcpServerEntry as w, defineGitHubResource as wi, ProvisionResult as wn, SandboxTraceOptions as wr, FleetExecDispatchOptions as wt, SANDBOX_MCP_SERVER_NAME as x, AgentProfileValidationResult as xi, PromptOptions as xn, SandboxTraceBundle as xr, FleetDispatchResultBuffer as xt, BuildSandboxMcpConfigOptions as y, AgentProfileResources as yi, ProcessStatus as yn, SandboxResources as yr, FileSystem as yt, BatchOptions as z, SandboxConnection as zn, SnapshotResult as zr, GpuLeaseExecOptions as zt };
4752
+ export { EventStreamOptions as $, SandboxFleetPolicy as $n, StartupOperation as $r, NetworkConfig as $t, CommitTaskSessionOptions as A, AgentProfileMcpServer as Ai, RunCodeOptions as An, SandboxUser as Ar, GpuLeaseCommandResult as At, CreateTaskSessionOptions as B, defineGitHubResource as Bi, SandboxFleetDispatchFailureClass as Bn, SessionBackendCredentials as Br, IntelligenceReport as Bt, BatchTaskUsage as C, WriteManyFile as Ci, PublishPublicTemplateVersionOptions as Cn, SandboxTerminalInfo as Cr, GitBranch as Ct, CodeLanguage as D, AgentProfileConfidential as Di, ReconcileSandboxFleetsResult as Dn, SandboxTraceEvent as Dr, GitStatus as Dt, CodeExecutionResult as E, AgentProfileCapabilities as Ei, ReconcileSandboxFleetsOptions as En, SandboxTraceBundle as Er, GitDiff as Et, CreateSandboxFleetOptions as F, AgentProfileResources as Fi, SandboxEnvironment as Fn, SecretInfo as Fr, GpuLeaseStatus as Ft, DownloadOptions as G, SandboxFleetIntelligenceEnvelope as Gn, SessionMessage as Gr, JsonValue as Gt, DirectoryPermission as H, mergeAgentProfiles as Hi, SandboxFleetDriverCapability as Hn, SessionForkOptions as Hr, IntelligenceReportCompareTo as Ht, CreateSandboxFleetTokenOptions as I, AgentProfileValidationIssue as Ii, SandboxEvent as In, SecretsManager as Ir, GpuType as It, DriverConfig as J, SandboxFleetMachineRecord as Jn, SnapshotInfo as Jr, ListSandboxFleetOptions as Jt, DownloadProgress as K, SandboxFleetMachine as Kn, SessionMessageInputPart as Kr, ListMessagesOptions as Kt, CreateSandboxFleetWithCoordinatorOptions as L, AgentProfileValidationResult as Li, SandboxFleetArtifact as Ln, SendSessionMessageOptions as Lr, HostAgentDriverConfig as Lt, CreateGpuLeaseOptions as M, AgentProfilePermissionValue as Mi, SSHCredentials as Mn, ScopedTokenScope as Mr, GpuLeaseExecResult as Mt, CreateIntelligenceReportOptions as N, AgentProfilePrompt as Ni, SandboxClientConfig as Nn, SearchMatch as Nr, GpuLeaseManager as Nt, CodeResult as O, AgentProfileConnection as Oi, RestoreSnapshotOptions as On, SandboxTraceExport as Or, GpuLease as Ot, CreateRequestOptions as P, AgentProfileResourceRef as Pi, SandboxConnection as Pn, SearchOptions as Pr, GpuLeaseProviderName as Pt, EgressPolicy as Q, SandboxFleetOperationsSummary as Qn, StartupDiagnostics as Qr, MkdirOptions as Qt, CreateSandboxOptions as R, AgentSubagentProfile as Ri, SandboxFleetArtifactSpec as Rn, SendSessionMessageRequest as Rr, HostAgentRuntimeBackend as Rt, BatchTaskResult as S, WriteFileOptions as Si, PublishPublicTemplateOptions as Sn, SandboxTerminalCreateOptions as Sr, GitAuth as St, CodeExecutionOptions as T, AgentProfile as Ti, ReapExpiredSandboxFleetsResult as Tn, SandboxTerminalRequestOptions as Tr, GitConfig as Tt, DispatchPromptOptions as U, SandboxFleetDriverTimings as Un, SessionInfo as Ur, IntelligenceReportSubjectType as Ut, DeleteOptions as V, defineInlineResource as Vi, SandboxFleetDispatchResponse as Vn, SessionEventStreamOptions as Vr, IntelligenceReportBudget as Vt, DispatchedSession as W, SandboxFleetInfo as Wn, SessionListOptions as Wr, IntelligenceReportWindow as Wt, DriverType as X, SandboxFleetManifest as Xn, SnapshotResult as Xr, McpServerConfig as Xt, DriverInfo as Y, SandboxFleetMachineSpec as Yn, SnapshotOptions as Yr, ListSandboxOptions as Yt, EgressManager as Z, SandboxFleetManifestMachine as Zn, SshKeysManager as Zr, MintScopedTokenOptions as Zt, BatchResult as _, UpdateUserOptions as _i, ProvisionResult as _n, SandboxResources as _r, FleetExecDispatchResult as _t, AttachSandboxFleetMachineOptions as a, TaskSessionCommitResult as ai, PreviewLinkManager as an, SandboxFleetUsage as ar, FileReadError as at, BatchSidecarGroup as b, UsageInfo as bi, PublicTemplateInfo as bn, SandboxRuntimeProfileList as br, FleetPromptDispatchResult as bt, BackendInfo as c, TaskSessionProfile as ci, ProcessLogEntry as cn, SandboxFleetWorkspaceRestoreResult as cr, FileTreeFile as ct, BackendType as d, TeeAttestationResponse as di, ProcessSpawnOptions as dn, SandboxIntelligenceEnvelope as dr, FileWriteResult as dt, StorageConfig as ei, NetworkManager as en, SandboxFleetToken as er, ExecOptions as et, BatchBackend as f, TeePublicKey as fi, ProcessStatus as fn, SandboxPermissionsConfig as fr, FleetDispatchCancelResult as ft, BatchOptions as g, TurnDriveResult as gi, ProvisionEvent as gn, SandboxResourceUsage as gr, FleetExecDispatchOptions as gt, BatchEventDataMap as h, ToolsConfig as hi, PromptResult as hn, SandboxProfileSummary as hr, FleetDispatchStreamOptions as ht, AttachGpuLeaseOptions as i, TaskSessionChanges as ii, PreviewLinkInfo as in, SandboxFleetTraceOptions as ir, FileReadBatchResult as it, CompletedTurnResult as j, AgentProfileModelHints as ji, SSHCommandDescriptor as jn, ScopedToken as jr, GpuLeaseExecOptions as jt, CodeResultPart as k, AgentProfileFileMount as ki, ResumeOptions as kn, SandboxTraceOptions as kr, GpuLeaseBilling as kt, BackendManager as l, TeeAttestationOptions as li, ProcessManager as ln, SandboxFleetWorkspaceSnapshotResult as lr, FileTreeOptions as lt, BatchEvent as m, TokenRefreshHandler as mi, PromptOptions as mn, SandboxPortPreviewLink as mr, FleetDispatchResultBufferOptions as mt, AccessPolicyRule as n, TaskOptions as ni, PermissionLevel as nn, SandboxFleetTraceEvent as nr, FileInfo as nt, BackendCapabilities as o, TaskSessionFileChange as oi, Process as on, SandboxFleetWorkspace as or, FileReadResult as ot, BatchBackendStats as p, TeePublicKeyResponse as pi, PromptInputPart as pn, SandboxPortBinding as pr, FleetDispatchResultBuffer as pt, DriveTurnOptions as q, SandboxFleetMachineMeteredUsage as qn, SessionStatus as qr, ListOptions as qt, AddUserOptions as r, TaskResult as ri, PermissionsManager as rn, SandboxFleetTraceExport as rr, FileReadBatchOptions as rt, BackendConfig as s, TaskSessionInfo as si, ProcessInfo as sn, SandboxFleetWorkspaceReconcileResult as sr, FileSystem as st, AcceleratorKind as t, SubscriptionInfo as ti, NonHostAgentDriverConfig as tn, SandboxFleetTraceBundle as tr, ExecResult as tt, BackendStatus as u, TeeAttestationReport as ui, ProcessSignal as un, SandboxInfo as ur, FileTreeResult as ut, BatchRunOptions as v, UploadOptions as vi, ProvisionStatus as vn, SandboxRuntimeHealth as vr, FleetMachineId as vt, BranchOptions as w, WriteManyOptions as wi, ReapExpiredSandboxFleetsOptions as wn, SandboxTerminalManager as wr, GitCommit as wt, BatchTask as x, WaitForOptions as xi, PublicTemplateVersionInfo as xn, SandboxStatus as xr, GPU_LEASE_PROVIDER_NAMES as xt, BatchRunRequest as y, UploadProgress as yi, ProvisionStep as yn, SandboxRuntimeProfile as yr, FleetPromptDispatchOptions as yt, CreateSessionOptions as z, defineAgentProfile as zi, SandboxFleetCostEstimate as zn, SentSessionMessage as zr, InstalledTool as zt };