@tangle-network/sandbox 0.63.15 → 0.63.16

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.
@@ -1940,37 +1940,6 @@ interface BackendArtifact {
1940
1940
  sizeBytes?: number;
1941
1941
  updatedAt?: string;
1942
1942
  }
1943
- //#endregion
1944
- //#region src/types/sessions.d.ts
1945
- /**
1946
- * Lifecycle state of an agent session inside a sandbox.
1947
- */
1948
- type SessionStatus = "queued" | "running" | "completed" | "failed" | "cancelled";
1949
- /** Lifecycle state of an execution retained in the session replay ledger. */
1950
- type SessionExecutionStatus = "active" | "completed" | "failed" | "cancelled";
1951
- /**
1952
- * Durable metadata for one session execution.
1953
- *
1954
- * The values come from the runtime replay ledger, not from a provider
1955
- * response or an inferred model result.
1956
- */
1957
- interface SessionExecutionInfo {
1958
- executionId: string;
1959
- sessionId: string;
1960
- status: SessionExecutionStatus;
1961
- startedAt: number;
1962
- completedAt?: number;
1963
- eventCount: number;
1964
- lastEventId: string;
1965
- }
1966
- /** Admission identity survives replay retention; unavailable never means completed. */
1967
- interface SessionMessageAdmission {
1968
- sessionId: string;
1969
- turnId: string;
1970
- executionId: string;
1971
- status: SessionExecutionStatus | "unavailable";
1972
- runControlRef?: AgentExactRunControlRef;
1973
- }
1974
1943
  /** Secret-free model tuple selected by the sandbox runtime. */
1975
1944
  /**
1976
1945
  * Which layer supplied the model id that executed. `request` means the model
@@ -1991,1169 +1960,594 @@ interface EffectiveBackend {
1991
1960
  /** Identity of the agent profile bound to the turn. */
1992
1961
  profile?: EffectiveBackendProfile;
1993
1962
  }
1963
+ //#endregion
1964
+ //#region src/types/agents.d.ts
1994
1965
  /**
1995
- * Why a session reached `status: "failed"` — the runtime's verbatim cause,
1996
- * not a bucketed label. A dispatched (detached) turn stops reading its SSE
1997
- * stream the moment the sandbox admits the execution, so a spawn, profile
1998
- * materialization or provider auth failure lands after the caller is gone;
1999
- * this is how that caller learns what happened without replaying events.
1966
+ * Result of an agent prompt.
2000
1967
  */
2001
- interface SessionFailureReason {
2002
- /** The runtime's error message, unmodified. */
2003
- message: string;
2004
- /** Machine-readable code when the runtime classified the failure. */
2005
- code?: string;
2006
- /** Native HTTP failure status when the provider reported it. */
2007
- statusCode?: number;
2008
- /** Execution whose failure this describes. */
2009
- executionId?: string;
2010
- }
2011
1968
  /**
2012
- * Snapshot of a session's state at the moment it was queried. Returned
2013
- * by `box.session(id).status()` and `box.sessions()`.
1969
+ * Granular outcome of an agent run.
1970
+ * - `success` — reached a successful terminal event. Failed tool calls remain
1971
+ * available in `toolInvocations` because an agent can recover from them.
1972
+ * - `failed` — a run-level error, a failed terminal, a malformed terminal, or
1973
+ * a stream that ended with no terminal event.
1974
+ * - `blocked_on_approval` — a tool hit a hub approval gate; resolve it, then
1975
+ * re-run. See {@link AgentApprovalRequirement}.
1976
+ * - `awaiting_question` — the agent asked a question and the turn ended without
1977
+ * an answer. See {@link AgentQuestionRequest}.
1978
+ * - `awaiting_interaction` — the agent emitted another canonical interaction
1979
+ * request and the turn ended without a response.
2014
1980
  */
2015
- interface SessionInfo {
2016
- /** Stable session id assigned by the sandbox runtime. */
2017
- id: string;
2018
- /** Parent session id when this session was forked from another session. */
2019
- parentId?: string;
2020
- /** Current lifecycle state. */
2021
- status: SessionStatus;
2022
- /** Present when `status` is `"failed"` — the cause the runtime recorded. */
2023
- failureReason?: SessionFailureReason;
2024
- /** Execution currently running, when one is active. */
2025
- activeExecutionId?: string;
2026
- /** Most recent execution id, retained after completion for event replay. */
2027
- latestExecutionId?: string;
2028
- /** Exact identity of the latest admitted run, retained for canonical control. */
2029
- runControlRef?: AgentExactRunControlRef;
2030
- /** Backend identifier (e.g. provider name). */
2031
- backend?: string;
2032
- /** Provider/model selected after request normalization and environment fallback. */
2033
- effectiveBackend?: EffectiveBackend;
2034
- /** Model id the session was created with. */
2035
- model?: string;
2036
- /** Number of prompts the session has processed. */
2037
- promptCount?: number;
2038
- /** When the session was created in the sandbox. */
2039
- createdAt?: Date;
2040
- /** When the session began executing. */
2041
- startedAt?: Date;
2042
- /** When the session reached a terminal state. */
2043
- endedAt?: Date;
2044
- /** Raw payload from the sidecar — stable subset above; this carries
2045
- * everything else for forward-compatibility. */
2046
- raw?: Record<string, unknown>;
2047
- }
1981
+ type AgentRunStatus = "success" | "failed" | "blocked_on_approval" | "awaiting_question" | "awaiting_interaction" | "awaiting_plan_decision"
2048
1982
  /**
2049
- * Options for `box.sessions()` listing.
1983
+ * The stream ended before the run's terminal event and could not rejoin
1984
+ * (`errorCode` `STREAM_INTERRUPTED`). The run may still be running; rejoin
1985
+ * it with `streamPrompt(message, { executionId, lastEventId, sessionId })`
1986
+ * or read its session status.
2050
1987
  */
2051
- interface SessionListOptions {
2052
- /** Filter by status. */
2053
- status?: SessionStatus;
2054
- /** Filter by backend identifier. */
2055
- backend?: BackendType;
2056
- }
2057
- /** Options for creating a runtime agent session. */
2058
- interface CreateSessionOptions {
2059
- /** Existing agent-owned direct child of the box volume's `workspaces` directory, independent of runtime cwd. */
2060
- workspaceRoot?: string;
2061
- /** Complete ordered visible transcript imported into a new isolated runtime session. */
2062
- conversationHistory?: Array<{
2063
- id: string;
2064
- role: "user" | "assistant";
2065
- parts: Array<{
2066
- type: "text";
2067
- text: string;
2068
- }>;
2069
- timestamp: string;
2070
- }>;
2071
- /** Import the complete native transcript from another OpenCode session in this box. */
2072
- importFromSessionId?: string;
2073
- /** Workspace conversations survive idle-session collection until explicitly deleted. */
2074
- retention?: "idle" | "workspace";
2075
- /** Stable caller-supplied idempotency key. Repeating create with the same
2076
- * id returns the existing session without creating another workspace or
2077
- * backend session. Omit to let the runtime mint a random id. */
2078
- sessionId?: string;
1988
+ | "unknown";
1989
+ interface DurablePlanSnapshot {
1990
+ id: string;
1991
+ revision: number;
2079
1992
  title?: string;
2080
- parentId?: string;
2081
- /** Optional backend override. An omitted or type-less config uses the
2082
- * runtime's configured default backend. */
2083
- backend?: BackendConfig;
2084
- }
2085
- /** Backend credentials forwarded to the platform if a sandbox must restart. */
2086
- interface SessionBackendCredentials {
2087
- apiKey: string;
2088
- baseUrl?: string;
1993
+ body: string;
1994
+ submittedAt: string;
2089
1995
  }
2090
- /** One content part accepted by the runtime session message endpoint. */
2091
- type SessionMessageInputPart = PromptInputPart | {
2092
- type: "reasoning";
2093
- text: string;
1996
+ type DurablePlan = DurablePlanSnapshot & {
1997
+ /** Canonical original source turn of this exact authenticated plan revision. */sourceTurnId: string;
1998
+ } & ({
1999
+ status: "pending";
2094
2000
  } | {
2095
- type: "tool";
2096
- tool: string;
2097
- state: {
2098
- status: "pending" | "running" | "completed" | "failed";
2099
- input?: unknown;
2100
- output?: unknown;
2101
- };
2001
+ status: "approved";
2002
+ decidedAt: string;
2102
2003
  } | {
2103
- type: "step-start";
2004
+ status: "rejected";
2005
+ decidedAt: string;
2006
+ feedback: string;
2104
2007
  } | {
2105
- type: "step-finish";
2106
- reason?: string;
2107
- tokens?: {
2108
- total?: number;
2109
- input?: number;
2110
- output?: number;
2111
- reasoning?: number;
2112
- cache?: {
2113
- write?: number;
2114
- read?: number;
2115
- };
2008
+ status: "superseded";
2009
+ supersededAt: string;
2010
+ supersededByPlanId: string;
2011
+ } | {
2012
+ status: "withdrawn";
2013
+ withdrawnAt: string;
2014
+ reason: string;
2015
+ });
2016
+ interface DurablePlanDecisionOptions {
2017
+ /** Caller prepares and dispatches the existing follow-up with fresh grants and pins. */
2018
+ followUp?: {
2019
+ mode: "caller";
2116
2020
  };
2117
- cost?: number;
2021
+ }
2022
+ interface DurablePlanFollowUpResume {
2023
+ /** Original native source turn; join immutable caller profile context using this ID. */
2024
+ sourceTurnId: string;
2025
+ continuation: PlanContinuation;
2026
+ /** Transient existing lease-bound admission nonce; never persist or log it. */
2027
+ credential: string;
2028
+ callbackUrl: string;
2029
+ expiresAt: string;
2030
+ }
2031
+ /** Fields accepted only on a message/preparation, never on session creation. */
2032
+ type TurnBackendConfig = Partial<BackendConfig> & {
2033
+ planContinuation?: PlanContinuation;
2118
2034
  };
2119
- /** Message body accepted by `SandboxSession.sendMessage`. */
2120
- interface SendSessionMessageRequest {
2121
- messageId?: string;
2122
- /** Per-turn overrides within the session's native backend. */
2123
- backend?: TurnBackendConfig;
2124
- /** Caller pin for the exact public backend request before native dispatch. */
2125
- expectedPublicProfileRequestDigest?: `sha256:${string}`;
2126
- /** Provider-composed native revision prepared for this public turn. */
2127
- expectedPublicProfileRevision?: {
2128
- workspacePlanDigest: `sha256:${string}`;
2129
- materializedDigest: `sha256:${string}`;
2130
- launchDigest: string;
2131
- };
2132
- /** Executor-only opaque receipt for a secret-bearing native revision. */
2133
- expectedSecretProfileReceipt?: `hmac-sha256:${string}`;
2134
- /** Router quote for a warm OpenCode turn with a total output ceiling. */
2135
- managedQuoteVersion?: string;
2136
- /** Use the sandbox's managed model credential for this turn only. */
2137
- managedModelCredential?: true;
2138
- /** Exact caller-owned execution identity for canonical cancellation. */
2139
- runControlRef?: AgentExactRunControlRef;
2140
- /** Absolute UTC deadline for admitting the first native provider call. */
2141
- admissionDeadline?: string;
2142
- /** Execution time limit in milliseconds; a positive integer bounded by the runtime deployment ceiling. */
2143
- ttlMs?: number;
2144
- parts: SessionMessageInputPart[];
2145
- system?: string;
2146
- agent?: string;
2147
- model?: {
2148
- providerId: string;
2149
- modelId: string;
2035
+ interface DurablePlanDecisionResult {
2036
+ plan: DurablePlan;
2037
+ followUp: {
2038
+ turnId: string;
2039
+ state: "awaiting_caller" | "queued" | "leased" | "started" | "completed" | "failed";
2040
+ mode?: "caller";
2041
+ executionId?: string;
2042
+ resume?: DurablePlanFollowUpResume;
2150
2043
  };
2151
- reasoningEffort?: ReasoningEffort;
2152
- turnId?: string;
2153
- interactions?: BackendConfig["interactions"];
2154
- /** Run this turn with every provider tool disabled (OpenCode). */
2155
- disableTools?: true;
2156
- /**
2157
- * Bound this turn to N upstream model calls (1-64). The runtime's model
2158
- * proxy counts and enforces them; a turn it cannot count is refused. The
2159
- * completed result reports `modelCalls`.
2160
- */
2161
- maxModelCalls?: number;
2044
+ /** True when the server replayed a decision it had already recorded. */
2045
+ idempotent: boolean;
2162
2046
  }
2163
- /** Per-call controls for `SandboxSession.sendMessage`. */
2164
- interface SendSessionMessageOptions {
2165
- /** Existing decision admission proof; used only for a caller-owned prepared follow-up. */
2166
- planFollowUp?: DurablePlanFollowUpResume;
2167
- credentials?: SessionBackendCredentials;
2168
- timeoutMs?: number;
2169
- signal?: AbortSignal;
2170
- /** Trace id sent as `x-tangle-trace-id`; see `PromptOptions.traceId`. */
2171
- traceId?: string;
2172
- }
2173
- /** Receipt returned after a session message is accepted for processing. */
2174
- interface SentSessionMessage {
2175
- info: {
2176
- id: string;
2177
- role: "assistant";
2178
- timestamp: string;
2179
- };
2180
- parts: [];
2181
- userMessageId: string;
2182
- processing: true;
2183
- runControlRef?: AgentExactRunControlRef;
2184
- }
2185
- /** Canonical portable profile attached to a task session. */
2186
- type TaskSessionProfile = AgentProfile & {
2187
- name: string;
2188
- };
2189
- /** Options for creating an isolated background task session. */
2190
- interface CreateTaskSessionOptions {
2191
- sessionId: string;
2192
- backend: BackendConfig;
2193
- title: string;
2194
- profile?: TaskSessionProfile;
2195
- parentSessionId?: string;
2196
- isolateFileWrites?: boolean;
2197
- }
2198
- /** Task-session metadata returned at creation time. */
2199
- interface TaskSessionInfo {
2200
- id: string;
2201
- title?: string;
2202
- parentSessionId?: string;
2203
- worktreeInfo?: {
2204
- worktreePath: string;
2205
- branchName: string;
2206
- baseCommitSha: string;
2207
- };
2208
- profile?: TaskSessionProfile;
2209
- }
2210
- /** One changed file in an isolated task session. */
2211
- interface TaskSessionFileChange {
2212
- file: string;
2213
- operation: "added" | "modified" | "deleted";
2214
- additions: number;
2215
- deletions: number;
2216
- }
2217
- /** Current diff and commit history for an isolated task session. */
2218
- interface TaskSessionChanges {
2219
- sessionId: string;
2220
- files: TaskSessionFileChange[];
2221
- diff: string;
2222
- commits: Array<{
2223
- sha: string;
2224
- message: string;
2225
- date: string;
2226
- }>;
2227
- worktreeInfo: {
2228
- worktreePath: string;
2229
- branchName: string;
2230
- baseCommitSha: string;
2231
- headCommitSha?: string;
2232
- };
2047
+ /**
2048
+ * A tool the agent invoked during a run. `isError` flags a failed call
2049
+ * (errored, timed out, or rejected — e.g. a hub approval gate). Failed tools
2050
+ * are recorded, not dropped, so callers can inspect what the agent attempted.
2051
+ */
2052
+ interface AgentToolInvocation {
2053
+ toolName: string;
2054
+ input?: unknown;
2055
+ result?: unknown;
2056
+ isError?: boolean;
2233
2057
  }
2234
- /** Options for merging task-session changes into the main workspace. */
2235
- interface CommitTaskSessionOptions {
2058
+ /**
2059
+ * A hub approval gate the agent hit mid-run. Present on a result when
2060
+ * `status === "blocked_on_approval"`. Approve with the CLI
2061
+ * (`tangle hub approvals approve <approvalId>`) or the hub SDK, then re-run.
2062
+ */
2063
+ interface AgentApprovalRequirement {
2064
+ /**
2065
+ * Approval id to act on. `undefined` when the in-sandbox hub bridge did not
2066
+ * preserve the structured approval object — surfaced honestly rather than
2067
+ * invented; inspect `message` in that case.
2068
+ */
2069
+ approvalId?: string;
2070
+ /** Hub connection the gated tool belongs to, when known. */
2071
+ connectionId?: string;
2072
+ /** The tool error message that surfaced the gate. */
2236
2073
  message?: string;
2237
- files?: string[];
2238
2074
  }
2239
- /** Result of merging task-session changes into the main workspace. */
2240
- interface TaskSessionCommitResult {
2241
- success: true;
2242
- commitSha?: string;
2243
- conflicts?: string[];
2244
- appliedFiles: number;
2075
+ /**
2076
+ * A question the agent asked mid-run. Present on a result when
2077
+ * `status === "awaiting_question"`. Answer via
2078
+ * `box.session(id).answer(questionId, { [field]: value })`, then re-run.
2079
+ */
2080
+ interface AgentQuestionRequest {
2081
+ /** Exact interaction id to pass as the first argument to `session.answer`. */
2082
+ questionId: string;
2083
+ /** The questions payload the agent emitted (prompt + options per entry). */
2084
+ questions: unknown;
2245
2085
  }
2246
2086
  /**
2247
- * Options for `SandboxSession.events()` streaming.
2087
+ * Token usage counts for a single agent run. All counts are whole and
2088
+ * non-negative; a runtime that reports only one side leaves the other at 0.
2089
+ *
2090
+ * The three prompt-side fields are DISJOINT and additive:
2091
+ * `inputTokens + cacheReadTokens + cacheWriteTokens` is the size of the prompt
2092
+ * the model saw, and each term bills at its own rate. `inputTokens` alone is
2093
+ * the freshly billed tail — on a warm agent loop with a stable prefix it is a
2094
+ * small fraction of the context, so reading it as "context size" understates
2095
+ * the prompt by the cached share, and pricing it as the whole prompt
2096
+ * overcharges by the same amount.
2097
+ *
2098
+ * The cache fields are optional because absence is meaningful: a runtime that
2099
+ * reported no cache information at all is UNMETERED, which is not the same
2100
+ * fact as a measured zero.
2248
2101
  */
2249
- interface SessionEventStreamOptions {
2250
- /** Replay strictly after this event id. Omit to start at the live tail. */
2251
- since?: string;
2252
- /** Restrict replay to one execution within the session. Required with
2253
- * `since` when attaching after a server-dispatched turn has already begun. */
2254
- executionId?: string;
2255
- /** Cancel the stream by aborting this signal. */
2256
- signal?: AbortSignal;
2102
+ interface TokenUsage {
2103
+ /** Prompt tokens billed at the full input rate: the uncached tail. */
2104
+ inputTokens: number;
2105
+ outputTokens: number;
2106
+ /** Prompt tokens served from the provider's prompt cache. */
2107
+ cacheReadTokens?: number;
2108
+ /** Prompt tokens written into the provider's prompt cache on this run. */
2109
+ cacheWriteTokens?: number;
2257
2110
  }
2258
- /** Select one exact execution when awaiting a session result. */
2259
- interface SessionResultOptions {
2111
+ interface PromptResult {
2260
2112
  /**
2261
- * Runtime execution to replay and aggregate.
2262
- *
2263
- * When omitted, `result()` retains its existing behavior and selects the
2264
- * session's latest execution at call time.
2113
+ * Whether the run succeeded. Shorthand for `status === "success"`: true only
2114
+ * when the run reached a terminal event with no run-level error and no failed
2115
+ * tool. Text presence is not required unless `requireVisibleAssistantOutput`
2116
+ * is set and no visible output was produced.
2265
2117
  */
2266
- executionId?: string;
2267
- }
2268
- /** Select one exact execution when interrupting a session. */
2269
- interface SessionInterruptOptions {
2118
+ success: boolean;
2119
+ /** Granular run outcome. */
2120
+ status: AgentRunStatus;
2270
2121
  /**
2271
- * Runtime execution to cancel.
2122
+ * Runtime execution that produced this result.
2272
2123
  *
2273
- * When supplied, a newer execution on the same session is never cancelled.
2274
- * When omitted, `interrupt()` selects the current execution.
2124
+ * Preserve this value when a session may receive another turn: passing it
2125
+ * to `session.result({ executionId })` or
2126
+ * `session.interrupt({ executionId })` keeps the later operation bound to
2127
+ * this run instead of whichever run is newest at call time.
2275
2128
  */
2276
2129
  executionId?: string;
2130
+ /** Agent's response text */
2131
+ response?: string;
2132
+ /** Error message when the run did not succeed */
2133
+ error?: string;
2134
+ /** Machine-readable error code from the runtime, e.g. `empty_visible_output`. */
2135
+ errorCode?: string;
2136
+ /** Native HTTP failure status when the provider reported it. */
2137
+ statusCode?: number;
2138
+ /** Tool calls the agent made this run, including failures (`isError`). */
2139
+ toolInvocations?: AgentToolInvocation[];
2140
+ /** Set when `status === "blocked_on_approval"`. */
2141
+ approval?: AgentApprovalRequirement;
2142
+ /** Set when `status === "awaiting_question"`. */
2143
+ question?: AgentQuestionRequest;
2144
+ /** Canonical request for any interaction that still needs a response. */
2145
+ interaction?: _$_tangle_network_agent_interface0.InteractionRequest;
2146
+ /** Set when `status === "awaiting_plan_decision"`. */
2147
+ plan?: DurablePlanSnapshot;
2148
+ /**
2149
+ * Trace id this prompt sent as `x-tangle-trace-id`: the caller's
2150
+ * `PromptOptions.traceId`, or one the SDK minted. The Sandbox API, the
2151
+ * orchestrator's proxy log, the runtime and the router's dispatch rows all
2152
+ * record the same value, so it finds every hop of this turn.
2153
+ */
2154
+ traceId?: string;
2155
+ /** Duration in milliseconds */
2156
+ durationMs: number;
2157
+ /** Token usage */
2158
+ usage?: TokenUsage;
2159
+ /** Provider-reported model cost in USD, when the runtime emitted it. */
2160
+ costUsd?: number;
2161
+ /**
2162
+ * A bounded turn's upstream model calls as the runtime's model proxy
2163
+ * relayed them (`maxModelCalls`), never the harness's own report.
2164
+ */
2165
+ modelCalls?: {
2166
+ limit: number;
2167
+ count: number;
2168
+ /**
2169
+ * The model each counted call's upstream response named, in call order;
2170
+ * shorter than `count` when a response named none. The requested model
2171
+ * is `effectiveBackend.model`, a separate value.
2172
+ */
2173
+ observedModels?: string[];
2174
+ };
2277
2175
  }
2176
+ type PromptInputPart = {
2177
+ type: "text";
2178
+ text: string;
2179
+ } | {
2180
+ type: "image";
2181
+ filename?: string;
2182
+ mediaType?: string;
2183
+ url?: string;
2184
+ path?: string;
2185
+ } | {
2186
+ type: "file";
2187
+ filename: string;
2188
+ mediaType?: string;
2189
+ url: string;
2190
+ };
2278
2191
  /**
2279
- * Options for `box.dispatchPrompt()` — fire-and-detach prompt semantics.
2192
+ * Options for sending a prompt.
2280
2193
  */
2281
- interface DispatchPromptOptions extends PromptOptions {
2282
- /** Client-supplied session id. Re-dispatching with the same id while
2283
- * that session is in flight is a lookup, not a second run — a
2284
- * concurrency guard, not a retry key. Once the turn finishes (or if the
2285
- * session was evicted) the same call dispatches again; pass `turnId` for
2286
- * retry safety that outlives the turn. */
2194
+ interface PromptOptions {
2195
+ /** Session ID for conversation continuity */
2287
2196
  sessionId?: string;
2288
- }
2289
- /**
2290
- * Options for `box.messages()` — list messages on a session including
2291
- * mid-turn partial assistant content.
2292
- */
2293
- interface ListMessagesOptions {
2294
- /** Session id whose messages to return (required). */
2295
- sessionId: string;
2296
- /** Max entries, default 100. Server caps at 1000. */
2297
- limit?: number;
2298
- /** Skip this many entries from the start. */
2299
- offset?: number;
2300
- /** Only return messages newer than this Unix-ms timestamp. */
2301
- since?: number;
2302
- }
2303
- /**
2304
- * Options for `box.session(id).fork()` — create a new session from an
2305
- * existing conversation, optionally at a message boundary.
2306
- */
2307
- interface SessionForkOptions {
2308
- /** Fork at this message boundary. */
2309
- messageId?: string;
2310
- /** Target backend type for cross-backend forks. Defaults to parent backend. */
2311
- targetBackend?: BackendType;
2312
- /** Model override for the target backend. */
2313
- targetModel?: {
2314
- provider?: string;
2315
- model?: string;
2316
- apiKey?: string;
2317
- baseUrl?: string;
2197
+ /** Resume one native conversation from the verified source snapshot. */
2198
+ nativeResume?: {
2199
+ harness: "claude-code" | "codex";
2200
+ nativeSessionId: string;
2201
+ sourceCheckpointId: string;
2318
2202
  };
2319
2203
  /**
2320
- * Files to include. The runtime currently rejects non-empty file lists;
2321
- * exposed here so the SDK type tracks the wire contract exactly.
2204
+ * Per-turn model id, forwarded to the runtime as `backend.model.model`.
2205
+ * Accepts a provider-prefixed slug ("zai/glm-4.7", "openai/gpt-5-mini")
2206
+ * or a bare id ("gpt-5-mini") the router resolves against the sandbox's
2207
+ * configured provider.
2208
+ *
2209
+ * This field exists because its absence produced silent model
2210
+ * substitution: `{ model: "gpt-5-mini" }` was an unknown option, the SDK
2211
+ * dropped it before the request left the process, and the sandbox served
2212
+ * the turn on its provisioned default model with no error anywhere.
2213
+ * A per-turn model request must either reach the wire or fail loud —
2214
+ * so a conflict with an explicit `backend.model.model` throws
2215
+ * `ValidationError` instead of silently preferring one.
2216
+ *
2217
+ * Equivalent to `backend: { model: { model } }`; use `backend.model` when
2218
+ * you also need provider/apiKey/baseUrl.
2219
+ */
2220
+ model?: string;
2221
+ /**
2222
+ * Per-run backend override.
2223
+ *
2224
+ * Set `backend.model` for a model override and `backend.profile` for an
2225
+ * inline provider-neutral `AgentProfile`.
2226
+ * Same-runtime overrides retain unspecified defaults. Changing the harness,
2227
+ * provider, or base URL replaces the default backend configuration.
2322
2228
  */
2323
- files?: string[];
2324
- }
2325
- /**
2326
- * One message on a session — user, assistant, or system. The metadata
2327
- * field carries the durability marker set by the sidecar:
2328
- * - `status: "streaming"` and no `completed`/`interrupted` flag → turn
2329
- * is in flight, OR the sidecar died before stamping a marker
2330
- * (SIGKILL, OOM). The partial parts are the partial assistant
2331
- * content the recorder flushed before death.
2332
- * - `completed: true` + `completedAt` → turn finished normally. If a
2333
- * `turnId` was supplied, its result is cached for idempotent retry.
2334
- * - `interrupted: true` + `interruptedAt` + `interruptReason` → graceful
2335
- * abort, timeout, or upstream error. Partial content is preserved
2336
- * but not billable as a completion.
2337
- */
2338
- interface SessionMessage {
2339
- id: string;
2340
- role: "user" | "assistant" | "system";
2341
- /** ISO timestamp string. */
2342
- timestamp: string;
2343
- /** Message parts (text, tool calls, reasoning, files). Same shape as
2344
- * events emitted by `streamPrompt`. */
2345
- parts: unknown[];
2346
- /** Durability + idempotency metadata. See class doc above. */
2347
- metadata?: {
2348
- status?: "streaming" | "completed" | "interrupted";
2349
- completed?: boolean;
2350
- completedAt?: string;
2351
- interrupted?: boolean;
2352
- interruptedAt?: string;
2353
- interruptReason?: string;
2354
- turnId?: string;
2355
- startedAt?: string;
2356
- [extra: string]: unknown;
2357
- };
2358
- }
2359
- /**
2360
- * Returned by `box.findCompletedTurn()` — the cached result of a
2361
- * previously-completed turn, keyed on the caller's `turnId`.
2362
- */
2363
- interface CompletedTurnResult {
2364
- turnId: string;
2365
- sessionId: string;
2366
- /** ISO timestamp when the turn finished. */
2367
- completedAt: string;
2368
- /** The cached AgentExecutionResult-shape payload (text, toolInvocations,
2369
- * sessionId, tokenUsage, etc.). */
2370
- result: CompletedTurnPayload;
2371
- }
2372
- /**
2373
- * The cached result of a completed turn. `effectiveBackend` is the provider
2374
- * and model that served the turn, the same field the live `result` and `done`
2375
- * events carry. It is absent when the runtime did not record it, for example
2376
- * on a record written before the runtime stored attribution: treat that as
2377
- * unknown, never as the session's default model.
2378
- */
2379
- type CompletedTurnPayload = Record<string, unknown> & {
2380
- effectiveBackend?: EffectiveBackend;
2381
- };
2382
- /**
2383
- * Returned by `box.dispatchPrompt()` — minimum the caller needs to track
2384
- * the session afterward. The sandbox keeps running the prompt; use
2385
- * `box.session(sessionId)` to follow it.
2386
- */
2387
- interface DispatchedSession {
2388
- /** Session id (either the one the caller supplied or one the sandbox
2389
- * minted). */
2390
- sessionId: string;
2391
- /** Runtime execution id when the admission event supplied one. */
2392
- executionId?: string;
2393
- /** Exact run identity accepted by the runtime for canonical cancellation. */
2394
- runControlRef?: AgentExactRunControlRef;
2395
- /** Lifecycle state at the moment dispatch returned. */
2396
- status: SessionStatus;
2397
- /** True when a session with the supplied id already existed. On its own
2398
- * this says nothing about whether the prompt ran — an existing terminal
2399
- * session still accepts a new turn. Read `dispatched` for that. */
2400
- alreadyExisted: boolean;
2401
- /** Whether this call actually dispatched the prompt. `false` means the
2402
- * call was a no-op because the turn is already in flight (session
2403
- * `queued`/`running`) or already finished (`turnId` hit the completed-
2404
- * turn cache) — the prompt was deliberately not sent, and no new events
2405
- * will appear on the session bus for it. */
2406
- dispatched: boolean;
2407
- }
2408
- /**
2409
- * Options for `box.driveTurn()` — one settle/poll/admit pass over a detached
2410
- * turn. The first pass creates a session with the requested backend and admits
2411
- * the turn through `SandboxSession.sendMessage()`. The session owns execution
2412
- * and gateway replay after the request returns.
2413
- */
2414
- /** Repeated messages in one native session, unlike the one-session-per-task driver. */
2415
- interface ConversationTurnOptions {
2416
- sessionId: string;
2417
- turnId: string;
2418
- /** Router quote included in the durable admission request. */
2419
- managedQuoteVersion?: string;
2420
- /** Use the sandbox's managed model credential for this turn only. */
2421
- managedModelCredential?: true;
2422
- /** Per-turn backend, profile, runtime attachments, and interaction settings. */
2423
2229
  backend?: Partial<BackendConfig>;
2424
- /** Caller pin for the exact public backend request before native dispatch. */
2230
+ /** Public digest returned by prepareSecretProfileRevision for this run. */
2425
2231
  expectedPublicProfileRequestDigest?: `sha256:${string}`;
2426
- /** Provider-composed native revision prepared for this public turn. */
2427
- expectedPublicProfileRevision?: {
2428
- workspacePlanDigest: `sha256:${string}`;
2429
- materializedDigest: `sha256:${string}`;
2430
- launchDigest: string;
2431
- };
2432
- /** Executor-only opaque receipt for a secret-bearing native revision. */
2232
+ /** Private native revision receipt for an isolated secret profile run. */
2433
2233
  expectedSecretProfileReceipt?: `hmac-sha256:${string}`;
2434
- /** Model shorthand; conflicts with backend.model.model are rejected. */
2435
- model?: string;
2436
- /** Exact execution identity retained by admission and cancellation. */
2437
- runControlRef?: AgentExactRunControlRef;
2438
- /** Absolute UTC deadline for admitting the first native provider call. */
2439
- admissionDeadline?: string;
2440
- /** False is a passive settlement/cancellation lookup; never admits new work. */
2441
- allowDispatch?: boolean;
2442
- /** Run this turn with every provider tool disabled (OpenCode). */
2443
- disableTools?: true;
2444
2234
  /**
2445
- * Bound this turn to N upstream model calls (1-64). The runtime's model
2446
- * proxy counts and enforces them; a turn it cannot count is refused. The
2447
- * completed result reports `modelCalls`.
2235
+ * Per-run budget in milliseconds. Bounds the client-side stream and is
2236
+ * forwarded to the runtime, where the backend's first-output watchdog
2237
+ * honors it. It sets the execution's time limit only when `ttlMs` is unset,
2238
+ * and is then subject to the same deployment maximum as `ttlMs`.
2448
2239
  */
2449
- maxModelCalls?: number;
2450
2240
  timeoutMs?: number;
2241
+ /**
2242
+ * Execution time limit in milliseconds. A positive integer; the runtime
2243
+ * cancels the execution when it elapses and the terminal error names the
2244
+ * limit. A value above the deployment's maximum (six hours by default) is
2245
+ * refused with `EXECUTION_TTL_EXCEEDS_LIMIT` before the run starts, by the
2246
+ * sandbox API on proxied calls and by the runtime itself on every call. The
2247
+ * code is the same from both; the surrounding error body follows each
2248
+ * service's own envelope, so read the code rather than the shape. Unset, the
2249
+ * runtime falls back to `timeoutMs`, then to its one-hour default.
2250
+ *
2251
+ * This limit governs how long the run may LIVE. A blocking call that waits
2252
+ * for the run is separately bounded by the runtime's one-hour request
2253
+ * timeout; a longer limit needs a streaming or session-message call, which
2254
+ * answers before the run finishes.
2255
+ */
2256
+ ttlMs?: number;
2257
+ /** Additional context */
2258
+ context?: Record<string, unknown>;
2259
+ /**
2260
+ * Exact run identity bound to this first dispatch. The runtime stores this
2261
+ * reference with the live execution so delayed control operations cannot
2262
+ * target a newer run that reused the same execution id.
2263
+ */
2264
+ runControlRef?: AgentExactRunControlRef;
2265
+ /** Fail chat-like runs that finish with no text or renderable interaction. */
2266
+ requireVisibleAssistantOutput?: boolean;
2267
+ /** AbortSignal for cancellation */
2451
2268
  signal?: AbortSignal;
2452
- wallCapMs?: number;
2453
2269
  /**
2454
- * Trace id sent as `x-tangle-trace-id` on this pass's runtime requests.
2455
- * Defaults to `turnId` when it is 8-200 letters, digits, `_` or `-`, so
2456
- * every pass over one turn shares one trace; otherwise the SDK mints one.
2270
+ * Trace id sent as `x-tangle-trace-id` on every request this prompt makes,
2271
+ * including reconnects. Pass your own turn or request id (8-200 letters,
2272
+ * digits, `_` or `-`) to join platform records to yours; omit it and the
2273
+ * SDK mints one. `PromptResult.traceId` returns the value used.
2457
2274
  */
2458
2275
  traceId?: string;
2459
- }
2460
- type ConversationTurnResult = ((TurnDriveResult & {
2276
+ /**
2277
+ * Stable execution id for tracing a first dispatch or selecting an existing
2278
+ * execution for replay. Forwarded as `X-Execution-ID` on a first dispatch.
2279
+ * When combined with `lastEventId`, the SDK replays the existing execution
2280
+ * without sending the prompt again. An execution ID alone does not make a
2281
+ * repeated POST idempotent; use `turnId` for application-level retries.
2282
+ * Omit to let the SDK read the id from `execution.started` for in-call
2283
+ * reconnects.
2284
+ */
2461
2285
  executionId?: string;
2462
- }) | {
2463
- state: "not_admitted";
2464
- } | {
2465
- state: "awaiting_input";
2466
- executionId: string;
2467
- requests: _$_tangle_network_agent_interface0.InteractionRequest[];
2468
- }) & {
2469
- /** Trace id this pass sent as `x-tangle-trace-id`. */traceId?: string;
2470
- };
2471
- interface DriveTurnOptions {
2472
- /** Deterministic session id — required, it is the resume key. Every
2473
- * tick for the same logical turn MUST pass the same id so a re-invoke
2474
- * after a crash finds the in-flight session instead of starting a
2475
- * second agent run. */
2476
- sessionId: string;
2477
- /** Turn idempotency key for the platform's completed-turn cache.
2478
- * Defaults to `sessionId`, which is correct for the one-turn-per-
2479
- * session shape detached drivers use. */
2286
+ /**
2287
+ * Last event id the caller has already acknowledged. Requires `executionId`;
2288
+ * the SDK replays strictly after this id without dispatching a new prompt.
2289
+ * Omit on the first attempt.
2290
+ */
2291
+ lastEventId?: string;
2292
+ /**
2293
+ * Caller-supplied turn idempotency key. When set, a retry with the
2294
+ * same `turnId` on the same `sessionId` short-circuits to the cached
2295
+ * result instead of re-issuing the upstream LLM call. Generate a
2296
+ * fresh `turnId` per logical attempt (a different user message gets
2297
+ * a new id) and reuse it only for retries of the same intent
2298
+ * (Stripe-style idempotency). Combine with `box.findCompletedTurn`
2299
+ * to check completion before re-dispatching.
2300
+ */
2480
2301
  turnId?: string;
2481
- /** Backend bound to the session when the first pass creates it. */
2482
- backend?: Partial<BackendConfig>;
2483
- /** Model shorthand folded into `backend.model.model` at session creation. */
2484
- model?: string;
2485
- /** Admission request timeout in milliseconds. */
2486
- timeoutMs?: number;
2487
- /** Abort the admission request before the sandbox accepts it. */
2488
- signal?: AbortSignal;
2489
- /** Wall-clock cap in milliseconds, measured from the session's
2490
- * `startedAt` (falling back to `createdAt`). When a still-running
2491
- * session exceeds it, `driveTurn` cancels the session and reports
2492
- * `state: "failed"` — bounding unattended runs that would otherwise
2493
- * stall forever (e.g. an interactive question nothing will answer).
2494
- * Omit for no cap. */
2495
- wallCapMs?: number;
2496
- }
2497
- /** Public side copy paths relative to the immutable profile revision workspace. */
2498
- interface PublicProfileConflict {
2499
- relPath: string;
2500
- copyRelPath: string;
2501
- reason: "existing" | "symlink";
2302
+ /**
2303
+ * Detach the run from this stream's lifetime. When true, the run never
2304
+ * ends because a reader went away: closing the generator does not cancel
2305
+ * it, and the platform keeps executing it and buffering its events so a
2306
+ * later reconnect can replay. Use for batch or queue workloads.
2307
+ *
2308
+ * Without it, ending the stream early (breaking out of the loop, aborting
2309
+ * `signal`, or letting `timeoutMs` elapse) cancels the run. A dropped
2310
+ * connection does not: the platform keeps an interactive run through a
2311
+ * disconnect grace window so this stream can rejoin it.
2312
+ * `dispatchPrompt` always sets this so fire-and-detach is safe by
2313
+ * construction.
2314
+ */
2315
+ detach?: boolean;
2316
+ /**
2317
+ * How long the SDK keeps rejoining this execution while it is unreachable,
2318
+ * in milliseconds. A dropped stream is a transport event, not an outcome:
2319
+ * the SDK reconnects with capped exponential backoff (1s doubling to 30s)
2320
+ * and resumes after the last delivered event, without duplicates. Each
2321
+ * replay connection that reaches the execution restarts the window, so a
2322
+ * long run survives any number of platform deploys. When the window
2323
+ * elapses, or the sandbox stops, the stream ends with an `error` event
2324
+ * whose `code` is `STREAM_INTERRUPTED` and `outcome` is `unknown`, and no
2325
+ * `done`: rejoin later with `executionId` + `lastEventId`.
2326
+ * Default six hours; 0 disables reconnection.
2327
+ */
2328
+ reconnectWindowMs?: number;
2502
2329
  }
2503
2330
  /**
2504
- * Returned by `box.driveTurn()` — where the detached turn stands after
2505
- * one pass. Discriminated on `state`:
2506
- * - `completed` — the turn finished with a text payload; `result` is
2507
- * the full cached AgentExecutionResult-shape record.
2508
- * - Waiting states preserve the response request and original result.
2509
- * - `running` — the session is queued or executing; re-invoke after a
2510
- * delay of your choosing.
2511
- * - `failed` — terminal and deterministic: a failed/cancelled session,
2512
- * a wall-cap cancellation, or an invalid terminal result.
2513
- * Re-invoking will not change the outcome.
2331
+ * SSE event from sandbox streaming.
2514
2332
  */
2515
- type TurnDriveResult = {
2516
- state: "completed"; /** Final assistant text of the turn. */
2517
- text: string; /** The full turn payload (text, toolInvocations, tokenUsage, etc.). */
2518
- result: Record<string, unknown>; /** Executor-observed public native profile revision for this turn. */
2519
- publicProfileRevision?: {
2520
- workspacePlanDigest: string;
2521
- materializedDigest: string;
2522
- launchDigest: string; /** Absent for a result written before collision receipts existed. */
2523
- conflicts?: PublicProfileConflict[];
2333
+ interface SandboxEvent {
2334
+ /** Event type */
2335
+ type: string;
2336
+ /** Event data */
2337
+ data: Record<string, unknown> & {
2338
+ effectiveBackend?: EffectiveBackend; /** Stable sidecar session used by runtime interaction routes. */
2339
+ runtimeSessionId?: string; /** Sandbox that produced this event, stamped by the SDK at intake. */
2340
+ sandboxId?: string;
2524
2341
  };
2342
+ /** Event ID */
2343
+ id?: string;
2344
+ }
2345
+ interface SandboxTraceEvent {
2346
+ type: "sandbox.lifecycle.snapshot" | "sandbox.runtime.snapshot" | "sandbox.usage.snapshot" | "sandbox.insight.summary";
2347
+ timestamp: string;
2348
+ sandboxId: string;
2349
+ durationMs?: number;
2350
+ attributes: Record<string, unknown>;
2351
+ }
2352
+ interface SandboxTraceExport {
2353
+ schemaVersion: "sandbox.trace.v1";
2354
+ traceId: string;
2355
+ sandboxId: string;
2356
+ exportedAt: string;
2357
+ timings: {
2358
+ observedLifecycleMs: number;
2359
+ observedRuntimeMs: number;
2360
+ idleObservedMs: number;
2361
+ };
2362
+ criticalPath: {
2363
+ durationMs: number;
2364
+ phases: Array<{
2365
+ name: string;
2366
+ durationMs: number;
2367
+ }>;
2368
+ };
2369
+ events: SandboxTraceEvent[];
2370
+ }
2371
+ interface SandboxIntelligenceEnvelope {
2372
+ schemaVersion: "sandbox.intelligence.v1";
2373
+ source: "sandbox-api";
2374
+ subject: {
2375
+ type: "sandbox";
2376
+ sandboxId: string;
2377
+ };
2378
+ billing: {
2379
+ billable: false;
2380
+ billedTo: "platform";
2381
+ costUsd: 0;
2382
+ reason: "deterministic_platform_insight";
2383
+ };
2384
+ metrics: Record<string, number>;
2385
+ signals: Array<{
2386
+ name: string;
2387
+ value: string | number | boolean;
2388
+ severity: "info" | "warn" | "critical";
2389
+ rationale: string;
2390
+ }>;
2391
+ recommendedActions: string[];
2392
+ }
2393
+ interface SandboxTraceBundle {
2394
+ trace: SandboxTraceExport;
2395
+ intelligence?: SandboxIntelligenceEnvelope;
2396
+ }
2397
+ interface SandboxTraceOptions {
2525
2398
  /**
2526
- * Token usage the turn reported, when the payload carried it. Typed
2527
- * access to the counts otherwise buried untyped inside `result`.
2528
- */
2529
- usage?: TokenUsage;
2530
- /**
2531
- * A bounded turn's upstream model calls as the runtime's model proxy
2532
- * relayed them (`maxModelCalls`), never the harness's own report.
2399
+ * Include the platform-generated intelligence envelope. Defaults to false.
2400
+ * Set true when a customer wants generated insight with the raw trace export.
2533
2401
  */
2534
- modelCalls?: {
2535
- limit: number;
2536
- count: number;
2537
- /**
2538
- * The model each counted call's upstream response named, in call order;
2539
- * shorter than `count` when a response named none. The requested model
2540
- * is `effectiveBackend.model`, a separate value.
2541
- */
2542
- observedModels?: string[];
2543
- };
2544
- } | {
2545
- state: "awaiting_plan_decision";
2546
- plan: DurablePlanSnapshot;
2547
- result: Record<string, unknown>;
2548
- } | {
2549
- state: "blocked_on_approval";
2550
- approval: AgentApprovalRequirement;
2551
- result: Record<string, unknown>;
2552
- } | {
2553
- state: "awaiting_question";
2554
- question: AgentQuestionRequest;
2555
- interaction?: _$_tangle_network_agent_interface0.InteractionRequest;
2556
- result: Record<string, unknown>;
2557
- } | {
2558
- state: "awaiting_interaction";
2559
- interaction: _$_tangle_network_agent_interface0.InteractionRequest;
2560
- result: Record<string, unknown>;
2561
- } | {
2562
- state: "running"; /** When the session began executing, if the runtime reported it. */
2563
- startedAt?: Date; /** Milliseconds since `startedAt` at the moment of the poll. */
2564
- elapsedMs?: number;
2565
- } | {
2566
- state: "failed"; /** Human-readable reason the turn is deterministically failed. */
2567
- error: string;
2568
- };
2569
- //#endregion
2570
- //#region src/types/agents.d.ts
2402
+ includeIntelligence?: boolean;
2403
+ }
2571
2404
  /**
2572
- * Result of an agent prompt.
2405
+ * Subject types for an Intelligence Report.
2406
+ *
2407
+ * - `sandbox`: one container's run.
2408
+ * - `fleet`: one managed grouping of sandboxes. Add `subject.dispatchId`
2409
+ * to narrow to a single coordinated command within the fleet
2410
+ * (previously a standalone `dispatch` subject type — now expressed
2411
+ * as a fleet refinement).
2573
2412
  */
2413
+ type IntelligenceReportSubjectType = "sandbox" | "fleet";
2414
+ interface IntelligenceReport {
2415
+ jobId: string;
2416
+ subject: {
2417
+ type: IntelligenceReportSubjectType;
2418
+ id: string; /** Present when the report was narrowed to a single fleet dispatch. */
2419
+ dispatchId?: string;
2420
+ };
2421
+ mode: "deterministic" | "agentic";
2422
+ status: "queued" | "running" | "completed" | "failed";
2423
+ billing: {
2424
+ billable: boolean;
2425
+ billedTo: "platform" | "customer";
2426
+ costUsd: number;
2427
+ reason: string;
2428
+ budgetMaxUsd?: number;
2429
+ };
2430
+ result: Record<string, unknown> | null;
2431
+ error?: string;
2432
+ createdAt: string;
2433
+ updatedAt: string;
2434
+ completedAt?: string;
2435
+ }
2436
+ interface IntelligenceReportBudget {
2437
+ maxUsd?: number;
2438
+ billTo?: "customer" | "platform";
2439
+ }
2574
2440
  /**
2575
- * Granular outcome of an agent run.
2576
- * - `success` — reached a successful terminal event. Failed tool calls remain
2577
- * available in `toolInvocations` because an agent can recover from them.
2578
- * - `failed` — a run-level error, a failed terminal, a malformed terminal, or
2579
- * a stream that ended with no terminal event.
2580
- * - `blocked_on_approval` — a tool hit a hub approval gate; resolve it, then
2581
- * re-run. See {@link AgentApprovalRequirement}.
2582
- * - `awaiting_question` — the agent asked a question and the turn ended without
2583
- * an answer. See {@link AgentQuestionRequest}.
2584
- * - `awaiting_interaction` — the agent emitted another canonical interaction
2585
- * request and the turn ended without a response.
2441
+ * Time window for an intelligence report. Both bounds are millisecond
2442
+ * epochs. Omit `since` to mean "from the subject's first observation";
2443
+ * omit `until` to mean "now". `since` must be <= `until` when both are
2444
+ * set; the server enforces this at the schema layer.
2586
2445
  */
2587
- type AgentRunStatus = "success" | "failed" | "blocked_on_approval" | "awaiting_question" | "awaiting_interaction" | "awaiting_plan_decision"
2446
+ interface IntelligenceReportWindow {
2447
+ since?: number;
2448
+ until?: number;
2449
+ }
2588
2450
  /**
2589
- * The stream ended before the run's terminal event and could not rejoin
2590
- * (`errorCode` `STREAM_INTERRUPTED`). The run may still be running; rejoin
2591
- * it with `streamPrompt(message, { executionId, lastEventId, sessionId })`
2592
- * or read its session status.
2451
+ * Comparison baseline. When present, the report includes an explicit
2452
+ * delta between the primary subject and this baseline. Must be the
2453
+ * same `type` as the primary subject — the analyzer rejects mixed
2454
+ * subject-type comparisons because the delta would be meaningless.
2455
+ *
2456
+ * `dispatchId` is only valid when `type === "fleet"`.
2593
2457
  */
2594
- | "unknown";
2595
- interface DurablePlanSnapshot {
2458
+ interface IntelligenceReportCompareTo {
2459
+ type: IntelligenceReportSubjectType;
2596
2460
  id: string;
2597
- revision: number;
2598
- title?: string;
2599
- body: string;
2600
- submittedAt: string;
2461
+ /** Narrow the baseline to a single dispatch within the fleet. */
2462
+ dispatchId?: string;
2601
2463
  }
2602
- type DurablePlan = DurablePlanSnapshot & {
2603
- /** Canonical original source turn of this exact authenticated plan revision. */sourceTurnId: string;
2604
- } & ({
2605
- status: "pending";
2606
- } | {
2607
- status: "approved";
2608
- decidedAt: string;
2609
- } | {
2610
- status: "rejected";
2611
- decidedAt: string;
2612
- feedback: string;
2613
- } | {
2614
- status: "superseded";
2615
- supersededAt: string;
2616
- supersededByPlanId: string;
2617
- } | {
2618
- status: "withdrawn";
2619
- withdrawnAt: string;
2620
- reason: string;
2621
- });
2622
- interface DurablePlanDecisionOptions {
2623
- /** Caller prepares and dispatches the existing follow-up with fresh grants and pins. */
2624
- followUp?: {
2625
- mode: "caller";
2626
- };
2627
- }
2628
- interface DurablePlanFollowUpResume {
2629
- /** Original native source turn; join immutable caller profile context using this ID. */
2630
- sourceTurnId: string;
2631
- continuation: PlanContinuation;
2632
- /** Transient existing lease-bound admission nonce; never persist or log it. */
2633
- credential: string;
2634
- callbackUrl: string;
2635
- expiresAt: string;
2636
- }
2637
- /** Fields accepted only on a message/preparation, never on session creation. */
2638
- type TurnBackendConfig = Partial<BackendConfig> & {
2639
- planContinuation?: PlanContinuation;
2640
- };
2641
- interface DurablePlanDecisionResult {
2642
- plan: DurablePlan;
2643
- followUp: {
2644
- turnId: string;
2645
- state: "awaiting_caller" | "queued" | "leased" | "started" | "completed" | "failed";
2646
- mode?: "caller";
2647
- executionId?: string;
2648
- resume?: DurablePlanFollowUpResume;
2464
+ interface CreateIntelligenceReportOptions {
2465
+ subject: {
2466
+ type: IntelligenceReportSubjectType;
2467
+ id: string;
2468
+ /**
2469
+ * Narrow the analysis to a single coordinated command within a
2470
+ * fleet. Only valid when `type === "fleet"`.
2471
+ */
2472
+ dispatchId?: string; /** Bound the analysis to a time window. */
2473
+ window?: IntelligenceReportWindow; /** Compare the primary subject against a same-type baseline. */
2474
+ compareTo?: IntelligenceReportCompareTo;
2649
2475
  };
2650
- /** True when the server replayed a decision it had already recorded. */
2651
- idempotent: boolean;
2476
+ mode?: "deterministic" | "agentic";
2477
+ acknowledgeCost?: boolean;
2478
+ budget?: IntelligenceReportBudget;
2479
+ metadata?: Record<string, unknown>;
2652
2480
  }
2653
2481
  /**
2654
- * A tool the agent invoked during a run. `isError` flags a failed call
2655
- * (errored, timed out, or rejected — e.g. a hub approval gate). Failed tools
2656
- * are recorded, not dropped, so callers can inspect what the agent attempted.
2482
+ * Options for event streaming.
2657
2483
  */
2658
- interface AgentToolInvocation {
2659
- toolName: string;
2660
- input?: unknown;
2661
- result?: unknown;
2662
- isError?: boolean;
2484
+ interface EventStreamOptions {
2485
+ /** AbortSignal for cancellation */
2486
+ signal?: AbortSignal;
2487
+ /** Filter to specific event types */
2488
+ eventTypes?: string[];
2663
2489
  }
2664
- /**
2665
- * A hub approval gate the agent hit mid-run. Present on a result when
2666
- * `status === "blocked_on_approval"`. Approve with the CLI
2667
- * (`tangle hub approvals approve <approvalId>`) or the hub SDK, then re-run.
2668
- */
2669
- interface AgentApprovalRequirement {
2490
+ //#endregion
2491
+ //#region src/types/batch.d.ts
2492
+ /** A single task in a batch execution. */
2493
+ type BatchTask = BatchTaskInput;
2494
+ /** Backend configuration accepted by batch execution. */
2495
+ type BatchBackend = BatchBackendInput;
2496
+ /** Complete request accepted by `runBatch` and `streamBatch`. */
2497
+ type BatchRunRequest = PublicBatchRunRequestInput;
2498
+ /** Per-call controls that are not serialized into a batch request. */
2499
+ interface BatchRunOptions {
2670
2500
  /**
2671
- * Approval id to act on. `undefined` when the in-sandbox hub bridge did not
2672
- * preserve the structured approval object — surfaced honestly rather than
2673
- * invented; inspect `message` in that case.
2501
+ * Retry identity for this exact request body. Reuse it only when retrying the
2502
+ * same logical batch. Keyed batches continue after a client disconnect so a
2503
+ * later call can join them. Unkeyed batches stop when the client disconnects.
2674
2504
  */
2675
- approvalId?: string;
2676
- /** Hub connection the gated tool belongs to, when known. */
2677
- connectionId?: string;
2678
- /** The tool error message that surfaced the gate. */
2679
- message?: string;
2505
+ idempotencyKey?: string;
2506
+ /**
2507
+ * Cancels this client stream. An unkeyed cancellation also stops server
2508
+ * execution; a keyed cancellation detaches while the shared run continues.
2509
+ */
2510
+ signal?: AbortSignal;
2680
2511
  }
2681
2512
  /**
2682
- * A question the agent asked mid-run. Present on a result when
2683
- * `status === "awaiting_question"`. Answer via
2684
- * `box.session(id).answer(questionId, { [field]: value })`, then re-run.
2513
+ * Result of a single task in a batch.
2685
2514
  */
2686
- interface AgentQuestionRequest {
2687
- /** Exact interaction id to pass as the first argument to `session.answer`. */
2688
- questionId: string;
2689
- /** The questions payload the agent emitted (prompt + options per entry). */
2690
- questions: unknown;
2691
- }
2515
+ type BatchTaskResult = BatchTaskResult$1;
2516
+ /** Complete validated batch result. */
2517
+ type BatchResult = BatchResult$1;
2518
+ //#endregion
2519
+ //#region src/types/branch.d.ts
2692
2520
  /**
2693
- * Token usage counts for a single agent run. All counts are whole and
2694
- * non-negative; a runtime that reports only one side leaves the other at 0.
2695
- *
2696
- * The three prompt-side fields are DISJOINT and additive:
2697
- * `inputTokens + cacheReadTokens + cacheWriteTokens` is the size of the prompt
2698
- * the model saw, and each term bills at its own rate. `inputTokens` alone is
2699
- * the freshly billed tail — on a warm agent loop with a stable prefix it is a
2700
- * small fraction of the context, so reading it as "context size" understates
2701
- * the prompt by the cached share, and pricing it as the whole prompt
2702
- * overcharges by the same amount.
2521
+ * Options for branching a running sandbox into N copy-on-write children.
2703
2522
  *
2704
- * The cache fields are optional because absence is meaningful: a runtime that
2705
- * reported no cache information at all is UNMETERED, which is not the same
2706
- * fact as a measured zero.
2523
+ * Branch forks a LIVE VM's memory into many children at once (Firecracker
2524
+ * UFFD copy-on-write): the children share the parent's clean pages and the
2525
+ * parent stays running. For durable filesystem state use snapshots instead.
2707
2526
  */
2708
- interface TokenUsage {
2709
- /** Prompt tokens billed at the full input rate: the uncached tail. */
2710
- inputTokens: number;
2711
- outputTokens: number;
2712
- /** Prompt tokens served from the provider's prompt cache. */
2713
- cacheReadTokens?: number;
2714
- /** Prompt tokens written into the provider's prompt cache on this run. */
2715
- cacheWriteTokens?: number;
2716
- }
2717
- interface PromptResult {
2718
- /**
2719
- * Whether the run succeeded. Shorthand for `status === "success"`: true only
2720
- * when the run reached a terminal event with no run-level error and no failed
2721
- * tool. Text presence is not required unless `requireVisibleAssistantOutput`
2722
- * is set and no visible output was produced.
2723
- */
2724
- success: boolean;
2725
- /** Granular run outcome. */
2726
- status: AgentRunStatus;
2527
+ interface BranchOptions {
2528
+ /** Override environment variables in every child. */
2529
+ env?: Record<string, string>;
2727
2530
  /**
2728
- * Runtime execution that produced this result.
2531
+ * Custom metadata applied to every child.
2729
2532
  *
2730
- * Preserve this value when a session may receive another turn: passing it
2731
- * to `session.result({ executionId })` or
2732
- * `session.interrupt({ executionId })` keeps the later operation bound to
2733
- * this run instead of whichever run is newest at call time.
2734
- */
2735
- executionId?: string;
2736
- /** Agent's response text */
2737
- response?: string;
2738
- /** Error message when the run did not succeed */
2739
- error?: string;
2740
- /** Machine-readable error code from the runtime, e.g. `empty_visible_output`. */
2741
- errorCode?: string;
2742
- /** Native HTTP failure status when the provider reported it. */
2743
- statusCode?: number;
2744
- /** Tool calls the agent made this run, including failures (`isError`). */
2745
- toolInvocations?: AgentToolInvocation[];
2746
- /** Set when `status === "blocked_on_approval"`. */
2747
- approval?: AgentApprovalRequirement;
2748
- /** Set when `status === "awaiting_question"`. */
2749
- question?: AgentQuestionRequest;
2750
- /** Canonical request for any interaction that still needs a response. */
2751
- interaction?: _$_tangle_network_agent_interface0.InteractionRequest;
2752
- /** Set when `status === "awaiting_plan_decision"`. */
2753
- plan?: DurablePlanSnapshot;
2754
- /**
2755
- * Trace id this prompt sent as `x-tangle-trace-id`: the caller's
2756
- * `PromptOptions.traceId`, or one the SDK minted. The Sandbox API, the
2757
- * orchestrator's proxy log, the runtime and the router's dispatch rows all
2758
- * record the same value, so it finds every hop of this turn.
2533
+ * Resource overrides are intentionally NOT accepted: a live branch restores
2534
+ * the parent's memory copy-on-write into each child, which requires
2535
+ * matching resources — children always inherit the parent's.
2759
2536
  */
2760
- traceId?: string;
2761
- /** Duration in milliseconds */
2762
- durationMs: number;
2763
- /** Token usage */
2764
- usage?: TokenUsage;
2765
- /** Provider-reported model cost in USD, when the runtime emitted it. */
2766
- costUsd?: number;
2537
+ metadata?: Record<string, unknown>;
2767
2538
  /**
2768
- * A bounded turn's upstream model calls as the runtime's model proxy
2769
- * relayed them (`maxModelCalls`), never the harness's own report.
2539
+ * Retry identity for this fan-out. A retry with the same key and the same
2540
+ * options returns the children the first request materialized and creates
2541
+ * none; the same key with different options is refused.
2770
2542
  */
2771
- modelCalls?: {
2772
- limit: number;
2773
- count: number;
2774
- /**
2775
- * The model each counted call's upstream response named, in call order;
2776
- * shorter than `count` when a response named none. The requested model
2777
- * is `effectiveBackend.model`, a separate value.
2778
- */
2779
- observedModels?: string[];
2780
- };
2543
+ idempotencyKey?: string;
2781
2544
  }
2782
- type PromptInputPart = {
2783
- type: "text";
2784
- text: string;
2785
- } | {
2786
- type: "image";
2787
- filename?: string;
2788
- mediaType?: string;
2789
- url?: string;
2790
- path?: string;
2791
- } | {
2792
- type: "file";
2793
- filename: string;
2794
- mediaType?: string;
2795
- url: string;
2796
- };
2797
2545
  /**
2798
- * Options for sending a prompt.
2799
- */
2800
- interface PromptOptions {
2801
- /** Session ID for conversation continuity */
2802
- sessionId?: string;
2803
- /** Resume one native conversation from the verified source snapshot. */
2804
- nativeResume?: {
2805
- harness: "claude-code" | "codex";
2806
- nativeSessionId: string;
2807
- sourceCheckpointId: string;
2808
- };
2809
- /**
2810
- * Per-turn model id, forwarded to the runtime as `backend.model.model`.
2811
- * Accepts a provider-prefixed slug ("zai/glm-4.7", "openai/gpt-5-mini")
2812
- * or a bare id ("gpt-5-mini") the router resolves against the sandbox's
2813
- * configured provider.
2814
- *
2815
- * This field exists because its absence produced silent model
2816
- * substitution: `{ model: "gpt-5-mini" }` was an unknown option, the SDK
2817
- * dropped it before the request left the process, and the sandbox served
2818
- * the turn on its provisioned default model with no error anywhere.
2819
- * A per-turn model request must either reach the wire or fail loud —
2820
- * so a conflict with an explicit `backend.model.model` throws
2821
- * `ValidationError` instead of silently preferring one.
2822
- *
2823
- * Equivalent to `backend: { model: { model } }`; use `backend.model` when
2824
- * you also need provider/apiKey/baseUrl.
2825
- */
2826
- model?: string;
2827
- /**
2828
- * Per-run backend override.
2829
- *
2830
- * Set `backend.model` for a model override and `backend.profile` for an
2831
- * inline provider-neutral `AgentProfile`.
2832
- * Same-runtime overrides retain unspecified defaults. Changing the harness,
2833
- * provider, or base URL replaces the default backend configuration.
2834
- */
2835
- backend?: Partial<BackendConfig>;
2836
- /** Public digest returned by prepareSecretProfileRevision for this run. */
2837
- expectedPublicProfileRequestDigest?: `sha256:${string}`;
2838
- /** Private native revision receipt for an isolated secret profile run. */
2839
- expectedSecretProfileReceipt?: `hmac-sha256:${string}`;
2840
- /**
2841
- * Per-run budget in milliseconds. Bounds the client-side stream and is
2842
- * forwarded to the runtime, where the backend's first-output watchdog
2843
- * honors it. It sets the execution's time limit only when `ttlMs` is unset,
2844
- * and is then subject to the same deployment maximum as `ttlMs`.
2845
- */
2846
- timeoutMs?: number;
2847
- /**
2848
- * Execution time limit in milliseconds. A positive integer; the runtime
2849
- * cancels the execution when it elapses and the terminal error names the
2850
- * limit. A value above the deployment's maximum (six hours by default) is
2851
- * refused with `EXECUTION_TTL_EXCEEDS_LIMIT` before the run starts, by the
2852
- * sandbox API on proxied calls and by the runtime itself on every call. The
2853
- * code is the same from both; the surrounding error body follows each
2854
- * service's own envelope, so read the code rather than the shape. Unset, the
2855
- * runtime falls back to `timeoutMs`, then to its one-hour default.
2856
- *
2857
- * This limit governs how long the run may LIVE. A blocking call that waits
2858
- * for the run is separately bounded by the runtime's one-hour request
2859
- * timeout; a longer limit needs a streaming or session-message call, which
2860
- * answers before the run finishes.
2861
- */
2862
- ttlMs?: number;
2863
- /** Additional context */
2864
- context?: Record<string, unknown>;
2865
- /**
2866
- * Exact run identity bound to this first dispatch. The runtime stores this
2867
- * reference with the live execution so delayed control operations cannot
2868
- * target a newer run that reused the same execution id.
2869
- */
2870
- runControlRef?: AgentExactRunControlRef;
2871
- /** Fail chat-like runs that finish with no text or renderable interaction. */
2872
- requireVisibleAssistantOutput?: boolean;
2873
- /** AbortSignal for cancellation */
2874
- signal?: AbortSignal;
2875
- /**
2876
- * Trace id sent as `x-tangle-trace-id` on every request this prompt makes,
2877
- * including reconnects. Pass your own turn or request id (8-200 letters,
2878
- * digits, `_` or `-`) to join platform records to yours; omit it and the
2879
- * SDK mints one. `PromptResult.traceId` returns the value used.
2880
- */
2881
- traceId?: string;
2882
- /**
2883
- * Stable execution id for tracing a first dispatch or selecting an existing
2884
- * execution for replay. Forwarded as `X-Execution-ID` on a first dispatch.
2885
- * When combined with `lastEventId`, the SDK replays the existing execution
2886
- * without sending the prompt again. An execution ID alone does not make a
2887
- * repeated POST idempotent; use `turnId` for application-level retries.
2888
- * Omit to let the SDK read the id from `execution.started` for in-call
2889
- * reconnects.
2890
- */
2891
- executionId?: string;
2892
- /**
2893
- * Last event id the caller has already acknowledged. Requires `executionId`;
2894
- * the SDK replays strictly after this id without dispatching a new prompt.
2895
- * Omit on the first attempt.
2896
- */
2897
- lastEventId?: string;
2898
- /**
2899
- * Caller-supplied turn idempotency key. When set, a retry with the
2900
- * same `turnId` on the same `sessionId` short-circuits to the cached
2901
- * result instead of re-issuing the upstream LLM call. Generate a
2902
- * fresh `turnId` per logical attempt (a different user message gets
2903
- * a new id) and reuse it only for retries of the same intent
2904
- * (Stripe-style idempotency). Combine with `box.findCompletedTurn`
2905
- * to check completion before re-dispatching.
2906
- */
2907
- turnId?: string;
2908
- /**
2909
- * Detach the run from this stream's lifetime. When true, the run never
2910
- * ends because a reader went away: closing the generator does not cancel
2911
- * it, and the platform keeps executing it and buffering its events so a
2912
- * later reconnect can replay. Use for batch or queue workloads.
2913
- *
2914
- * Without it, ending the stream early (breaking out of the loop, aborting
2915
- * `signal`, or letting `timeoutMs` elapse) cancels the run. A dropped
2916
- * connection does not: the platform keeps an interactive run through a
2917
- * disconnect grace window so this stream can rejoin it.
2918
- * `dispatchPrompt` always sets this so fire-and-detach is safe by
2919
- * construction.
2920
- */
2921
- detach?: boolean;
2922
- /**
2923
- * How long the SDK keeps rejoining this execution while it is unreachable,
2924
- * in milliseconds. A dropped stream is a transport event, not an outcome:
2925
- * the SDK reconnects with capped exponential backoff (1s doubling to 30s)
2926
- * and resumes after the last delivered event, without duplicates. Each
2927
- * replay connection that reaches the execution restarts the window, so a
2928
- * long run survives any number of platform deploys. When the window
2929
- * elapses, or the sandbox stops, the stream ends with an `error` event
2930
- * whose `code` is `STREAM_INTERRUPTED` and `outcome` is `unknown`, and no
2931
- * `done`: rejoin later with `executionId` + `lastEventId`.
2932
- * Default six hours; 0 disables reconnection.
2933
- */
2934
- reconnectWindowMs?: number;
2935
- }
2936
- /**
2937
- * SSE event from sandbox streaming.
2938
- */
2939
- interface SandboxEvent {
2940
- /** Event type */
2941
- type: string;
2942
- /** Event data */
2943
- data: Record<string, unknown> & {
2944
- effectiveBackend?: EffectiveBackend; /** Stable sidecar session used by runtime interaction routes. */
2945
- runtimeSessionId?: string; /** Sandbox that produced this event, stamped by the SDK at intake. */
2946
- sandboxId?: string;
2947
- };
2948
- /** Event ID */
2949
- id?: string;
2950
- }
2951
- interface SandboxTraceEvent {
2952
- type: "sandbox.lifecycle.snapshot" | "sandbox.runtime.snapshot" | "sandbox.usage.snapshot" | "sandbox.insight.summary";
2953
- timestamp: string;
2954
- sandboxId: string;
2955
- durationMs?: number;
2956
- attributes: Record<string, unknown>;
2957
- }
2958
- interface SandboxTraceExport {
2959
- schemaVersion: "sandbox.trace.v1";
2960
- traceId: string;
2961
- sandboxId: string;
2962
- exportedAt: string;
2963
- timings: {
2964
- observedLifecycleMs: number;
2965
- observedRuntimeMs: number;
2966
- idleObservedMs: number;
2967
- };
2968
- criticalPath: {
2969
- durationMs: number;
2970
- phases: Array<{
2971
- name: string;
2972
- durationMs: number;
2973
- }>;
2974
- };
2975
- events: SandboxTraceEvent[];
2976
- }
2977
- interface SandboxIntelligenceEnvelope {
2978
- schemaVersion: "sandbox.intelligence.v1";
2979
- source: "sandbox-api";
2980
- subject: {
2981
- type: "sandbox";
2982
- sandboxId: string;
2983
- };
2984
- billing: {
2985
- billable: false;
2986
- billedTo: "platform";
2987
- costUsd: 0;
2988
- reason: "deterministic_platform_insight";
2989
- };
2990
- metrics: Record<string, number>;
2991
- signals: Array<{
2992
- name: string;
2993
- value: string | number | boolean;
2994
- severity: "info" | "warn" | "critical";
2995
- rationale: string;
2996
- }>;
2997
- recommendedActions: string[];
2998
- }
2999
- interface SandboxTraceBundle {
3000
- trace: SandboxTraceExport;
3001
- intelligence?: SandboxIntelligenceEnvelope;
3002
- }
3003
- interface SandboxTraceOptions {
3004
- /**
3005
- * Include the platform-generated intelligence envelope. Defaults to false.
3006
- * Set true when a customer wants generated insight with the raw trace export.
3007
- */
3008
- includeIntelligence?: boolean;
3009
- }
3010
- /**
3011
- * Subject types for an Intelligence Report.
3012
- *
3013
- * - `sandbox`: one container's run.
3014
- * - `fleet`: one managed grouping of sandboxes. Add `subject.dispatchId`
3015
- * to narrow to a single coordinated command within the fleet
3016
- * (previously a standalone `dispatch` subject type — now expressed
3017
- * as a fleet refinement).
3018
- */
3019
- type IntelligenceReportSubjectType = "sandbox" | "fleet";
3020
- interface IntelligenceReport {
3021
- jobId: string;
3022
- subject: {
3023
- type: IntelligenceReportSubjectType;
3024
- id: string; /** Present when the report was narrowed to a single fleet dispatch. */
3025
- dispatchId?: string;
3026
- };
3027
- mode: "deterministic" | "agentic";
3028
- status: "queued" | "running" | "completed" | "failed";
3029
- billing: {
3030
- billable: boolean;
3031
- billedTo: "platform" | "customer";
3032
- costUsd: number;
3033
- reason: string;
3034
- budgetMaxUsd?: number;
3035
- };
3036
- result: Record<string, unknown> | null;
3037
- error?: string;
3038
- createdAt: string;
3039
- updatedAt: string;
3040
- completedAt?: string;
3041
- }
3042
- interface IntelligenceReportBudget {
3043
- maxUsd?: number;
3044
- billTo?: "customer" | "platform";
3045
- }
3046
- /**
3047
- * Time window for an intelligence report. Both bounds are millisecond
3048
- * epochs. Omit `since` to mean "from the subject's first observation";
3049
- * omit `until` to mean "now". `since` must be <= `until` when both are
3050
- * set; the server enforces this at the schema layer.
3051
- */
3052
- interface IntelligenceReportWindow {
3053
- since?: number;
3054
- until?: number;
3055
- }
3056
- /**
3057
- * Comparison baseline. When present, the report includes an explicit
3058
- * delta between the primary subject and this baseline. Must be the
3059
- * same `type` as the primary subject — the analyzer rejects mixed
3060
- * subject-type comparisons because the delta would be meaningless.
3061
- *
3062
- * `dispatchId` is only valid when `type === "fleet"`.
3063
- */
3064
- interface IntelligenceReportCompareTo {
3065
- type: IntelligenceReportSubjectType;
3066
- id: string;
3067
- /** Narrow the baseline to a single dispatch within the fleet. */
3068
- dispatchId?: string;
3069
- }
3070
- interface CreateIntelligenceReportOptions {
3071
- subject: {
3072
- type: IntelligenceReportSubjectType;
3073
- id: string;
3074
- /**
3075
- * Narrow the analysis to a single coordinated command within a
3076
- * fleet. Only valid when `type === "fleet"`.
3077
- */
3078
- dispatchId?: string; /** Bound the analysis to a time window. */
3079
- window?: IntelligenceReportWindow; /** Compare the primary subject against a same-type baseline. */
3080
- compareTo?: IntelligenceReportCompareTo;
3081
- };
3082
- mode?: "deterministic" | "agentic";
3083
- acknowledgeCost?: boolean;
3084
- budget?: IntelligenceReportBudget;
3085
- metadata?: Record<string, unknown>;
3086
- }
3087
- /**
3088
- * Options for event streaming.
3089
- */
3090
- interface EventStreamOptions {
3091
- /** AbortSignal for cancellation */
3092
- signal?: AbortSignal;
3093
- /** Filter to specific event types */
3094
- eventTypes?: string[];
3095
- }
3096
- //#endregion
3097
- //#region src/types/batch.d.ts
3098
- /** A single task in a batch execution. */
3099
- type BatchTask = BatchTaskInput;
3100
- /** Backend configuration accepted by batch execution. */
3101
- type BatchBackend = BatchBackendInput;
3102
- /** Complete request accepted by `runBatch` and `streamBatch`. */
3103
- type BatchRunRequest = PublicBatchRunRequestInput;
3104
- /** Per-call controls that are not serialized into a batch request. */
3105
- interface BatchRunOptions {
3106
- /**
3107
- * Retry identity for this exact request body. Reuse it only when retrying the
3108
- * same logical batch. Keyed batches continue after a client disconnect so a
3109
- * later call can join them. Unkeyed batches stop when the client disconnects.
3110
- */
3111
- idempotencyKey?: string;
3112
- /**
3113
- * Cancels this client stream. An unkeyed cancellation also stops server
3114
- * execution; a keyed cancellation detaches while the shared run continues.
3115
- */
3116
- signal?: AbortSignal;
3117
- }
3118
- /**
3119
- * Result of a single task in a batch.
3120
- */
3121
- type BatchTaskResult = BatchTaskResult$1;
3122
- /** Complete validated batch result. */
3123
- type BatchResult = BatchResult$1;
3124
- //#endregion
3125
- //#region src/types/branch.d.ts
3126
- /**
3127
- * Options for branching a running sandbox into N copy-on-write children.
3128
- *
3129
- * Branch forks a LIVE VM's memory into many children at once (Firecracker
3130
- * UFFD copy-on-write): the children share the parent's clean pages and the
3131
- * parent stays running. For durable filesystem state use snapshots instead.
3132
- */
3133
- interface BranchOptions {
3134
- /** Override environment variables in every child. */
3135
- env?: Record<string, string>;
3136
- /**
3137
- * Custom metadata applied to every child.
3138
- *
3139
- * Resource overrides are intentionally NOT accepted: a live branch restores
3140
- * the parent's memory copy-on-write into each child, which requires
3141
- * matching resources — children always inherit the parent's.
3142
- */
3143
- metadata?: Record<string, unknown>;
3144
- /**
3145
- * Retry identity for this fan-out. A retry with the same key and the same
3146
- * options returns the children the first request materialized and creates
3147
- * none; the same key with different options is refused.
3148
- */
3149
- idempotencyKey?: string;
3150
- }
3151
- /**
3152
- * How a keyed fork resolved.
3153
- *
3154
- * `created` ran this fan-out. `replayed` returned the children an earlier
3155
- * request under the same key and options already materialized. Absent when the
3156
- * request carried no key, or when the API predates the field.
2546
+ * How a keyed fork resolved.
2547
+ *
2548
+ * `created` ran this fan-out. `replayed` returned the children an earlier
2549
+ * request under the same key and options already materialized. Absent when the
2550
+ * request carried no key, or when the API predates the field.
3157
2551
  */
3158
2552
  interface ForkIdempotency {
3159
2553
  outcome: "created" | "replayed";
@@ -5773,1231 +5167,1837 @@ interface CreateSandboxOptions {
5773
5167
  * before provisioning. When omitted the sandbox is personal
5774
5168
  * (accessible only to the creator).
5775
5169
  */
5776
- teamId?: string;
5170
+ teamId?: string;
5171
+ /**
5172
+ * Sidecar capabilities to enable at boot. Each capability boots an
5173
+ * additional subsystem inside the sandbox; absent capabilities incur
5174
+ * zero startup cost.
5175
+ *
5176
+ * Currently supported:
5177
+ * - `"computer_use"` — boots Xvfb, dbus, AT-SPI, and an MCP server
5178
+ * exposing mouse/keyboard/screenshot via the Anthropic + OpenAI
5179
+ * Responses computer-use surface. Required if you plan to call
5180
+ * {@link SandboxInstance.getMcpAccessToken | `getMcpAccessToken`}
5181
+ * with `capabilities: ["computer_use"]`.
5182
+ *
5183
+ * The capability is enforced at two layers:
5184
+ * 1. The sidecar refuses to start if a capability's binaries are
5185
+ * missing (`computer_use` needs the mounted Nix profile with
5186
+ * Xvfb, dbus, xdotool, and scrot available at runtime).
5187
+ * 2. The MCP token endpoint refuses to mint a `cap: ["computer_use"]`
5188
+ * JWT for a sandbox that wasn't created with that capability.
5189
+ *
5190
+ * **Sizing note:** `computer_use` boots an always-on Xvfb + dbus
5191
+ * stack costing roughly **~100 MB resident memory** inside the
5192
+ * container. Billing is by reserved capacity (not measured RSS), so
5193
+ * this comes out of your sandbox's RAM envelope rather than adding
5194
+ * a separate line item. On a 1 GB sandbox that is ~10% of your
5195
+ * workload's headroom; bump `resources.memoryMB` to 1.5–2 GB if
5196
+ * the agent will run anything memory-hungry alongside it.
5197
+ *
5198
+ * @example
5199
+ * ```typescript
5200
+ * const box = await client.create({
5201
+ * capabilities: ["computer_use"],
5202
+ * });
5203
+ * const { token } = await box.getMcpAccessToken({
5204
+ * capabilities: ["computer_use"],
5205
+ * });
5206
+ * ```
5207
+ */
5208
+ capabilities?: ReadonlyArray<"computer_use">;
5209
+ /**
5210
+ * Privacy controls for the sandbox. Two independent layers:
5211
+ *
5212
+ * - **`egress`** — what happens when the sandbox sends a request to a
5213
+ * model vendor (Anthropic, OpenAI, your own router, etc.):
5214
+ * - `"redact"` — PII spans are masked before the request leaves
5215
+ * the sandbox. Emails, JWTs, API keys, credit cards (Luhn-
5216
+ * validated), SSNs, phone numbers, IPv4 addresses are caught
5217
+ * today; names / postal addresses / DOBs land when the OPF
5218
+ * model service is enabled. The agent receives normal
5219
+ * responses; the vendor sees masked input.
5220
+ * - `"block"` — PII presence fails the egress request closed.
5221
+ * For high-compliance flows that prefer fail-closed to leak.
5222
+ * - `"off"` — no egress filtering. Default for free tier; opt-in
5223
+ * for tasks that genuinely need raw PII (form-filling,
5224
+ * customer-support agents reading customer details).
5225
+ *
5226
+ * - **`logs`** — whether infrastructure logs / telemetry / Sentry
5227
+ * redact PII before recording. This is OUR side, not the model
5228
+ * vendor's, and there's basically never a reason to leak PII into
5229
+ * our own logs. Default `"on"`.
5230
+ *
5231
+ * Note: privacy controls operate at the boundary between the
5232
+ * sandbox and external systems. They do NOT redact contents inside
5233
+ * the sandbox workspace itself — files / code / database fixtures
5234
+ * the customer puts there are the customer's data and stay
5235
+ * unmodified. Snapshots preserve those contents verbatim.
5236
+ *
5237
+ * @example
5238
+ * ```typescript
5239
+ * const box = await client.create({
5240
+ * privacy: { egress: "redact", logs: "on" },
5241
+ * });
5242
+ * ```
5243
+ */
5244
+ privacy?: {
5245
+ egress?: "redact" | "block" | "off";
5246
+ logs?: "on" | "off";
5247
+ };
5248
+ /**
5249
+ * Stable idempotency key for this logical create. Sent as the
5250
+ * `Idempotency-Key` header so the API derives a deterministic sandbox
5251
+ * identity from (owner, key): a retried create resolves to the SAME
5252
+ * provisioning sandbox and joins the in-flight provision instead of
5253
+ * starting a fresh cold start per retry. When omitted, the SDK
5254
+ * generates one per `create()` call and reuses it across its own
5255
+ * timeout-driven retries.
5256
+ */
5257
+ idempotencyKey?: string;
5258
+ /**
5259
+ * Platform user id whose wallet funds managed model usage for this sandbox.
5260
+ *
5261
+ * Use only from a trusted first-party service acting for an authenticated
5262
+ * user. The Sandbox API honors this field only when the caller's exact
5263
+ * verified API key ID is allow-listed; otherwise strict deployments reject
5264
+ * the create.
5265
+ * It never grants the caller permission to charge arbitrary users.
5266
+ *
5267
+ * This option applies to the HTTP Sandbox API client. Direct Tangle job
5268
+ * creation does not support delegated billing.
5269
+ */
5270
+ billingOwnerId?: string;
5271
+ /**
5272
+ * What pays this sandbox's compute. `"referral_credit"` spends the
5273
+ * account's referral Sandbox-compute credit only: it runs on spare capacity,
5274
+ * never falls back to the wallet, and stops with `scoped_credit_exhausted`
5275
+ * when the credit runs out or `scoped_credit_held` while its campaign is on
5276
+ * hold. Fixed for the sandbox's life. Personal sandboxes only. Defaults to
5277
+ * the wallet.
5278
+ */
5279
+ funding?: "wallet" | "referral_credit";
5280
+ /**
5281
+ * Place this sandbox only on spare capacity.
5282
+ *
5283
+ * For first-party delegated creates only: the Sandbox API accepts it only
5284
+ * together with `billingOwnerId` from an allow-listed first-party service
5285
+ * key, and refuses every other create with 403 `CAPACITY_CLASS_FORBIDDEN`.
5286
+ * It restricts placement and is not a priority: no host outside the spare
5287
+ * pool takes the sandbox, and the create is refused with 503
5288
+ * `SPARE_CAPACITY_UNAVAILABLE` when no spare pool admits it. It also skips
5289
+ * the warm pool. The class is fixed at create; resume keeps it.
5290
+ */
5291
+ capacityClass?: "spare_only";
5292
+ /**
5293
+ * Auto-split inline file mounts out of an inline `backend.profile` object
5294
+ * at create time, send the lean profile (mount refs stripped) in the
5295
+ * create request, then write the deferred files back once the sandbox is
5296
+ * running.
5297
+ *
5298
+ * When `true` (the default), a profile with sizeable inline mounts (e.g.
5299
+ * skills, tool scripts) does not bloat the create POST; the SDK
5300
+ * materializes those files via {@link FileSystem.writeMany} /
5301
+ * {@link FileSystem.uploadData} after the sandbox reaches `running`. A batch
5302
+ * write answered 502, 503 or 504, or lost with its connection, is sent again
5303
+ * for up to 10 seconds before create() raises `PartialFailureError`. Only
5304
+ * applies to an inline `AgentProfile` object on `backend.profile`; a
5305
+ * named-profile string is never split. Set `false` to send the full profile
5306
+ * in the create request without a post-create materialization step.
5307
+ *
5308
+ * @default true
5309
+ */
5310
+ autoMaterializeProfileFiles?: boolean;
5311
+ /**
5312
+ * Auto-defer an inline `backend.profile`'s static corpus so it is delivered
5313
+ * once instead of on every turn. At create time the SDK strips inline
5314
+ * `resources.skills` from the create request (keeping the create body under
5315
+ * its wire cap), then primes the running sandbox with the full profile and
5316
+ * references it by hash (`backend.profileSha256`) on subsequent turns. The
5317
+ * handle still holds the full profile, so a cache miss transparently resends
5318
+ * it.
5319
+ *
5320
+ * When `false`, the full profile, including skills, travels with the create
5321
+ * request and every turn. This applies only to an inline `AgentProfile`
5322
+ * object on `backend.profile` and is independent of
5323
+ * {@link autoMaterializeProfileFiles}.
5324
+ *
5325
+ * A turn only substitutes the hash reference when the outgoing profile's
5326
+ * content still matches what was primed: mutate the profile (or pass a
5327
+ * changed per-turn `backend.profile`) and that turn sends the full profile
5328
+ * inline again, so the runtime always runs the profile you passed.
5329
+ *
5330
+ * @default true
5331
+ */
5332
+ autoDeferProfile?: boolean;
5333
+ }
5334
+ /**
5335
+ * Per-call overrides for {@link Sandbox.create}.
5336
+ */
5337
+ interface CreateRequestOptions {
5338
+ /**
5339
+ * Time budget for the whole create-and-reach-running flow, in
5340
+ * milliseconds. Cold provisions routinely take ~25–40s, so this
5341
+ * defaults high (120000). If the initial POST rides the deadline the
5342
+ * SDK polls the sandbox to `running` rather than re-POSTing.
5343
+ */
5344
+ timeoutMs?: number;
5345
+ /** Abort the create + poll early. */
5346
+ signal?: AbortSignal;
5347
+ }
5348
+ //#endregion
5349
+ //#region src/types/sandbox-info.d.ts
5350
+ /**
5351
+ * SSH connection credentials.
5352
+ */
5353
+ interface SSHCredentials {
5354
+ /** Username for SSH authentication */
5355
+ username: string;
5356
+ /** SSH server port */
5357
+ port: number;
5358
+ /** ProxyCommand for sandbox API tunnel-based SSH. */
5359
+ proxyCommand: string;
5360
+ }
5361
+ interface SSHCommandDescriptor {
5362
+ command: string;
5363
+ env: Record<string, string>;
5364
+ }
5365
+ /**
5366
+ * Connection information for a sandbox.
5367
+ *
5368
+ * Most code should use `SandboxInstance` methods (`exec`, `prompt`, etc.).
5369
+ * The raw `runtimeUrl` and `authToken` are surfaced only for advanced
5370
+ * lower-level use cases such as custom protocol clients.
5371
+ */
5372
+ interface SandboxConnection {
5373
+ /** Sandbox runtime API URL for programmatic access */
5374
+ runtimeUrl?: string;
5375
+ /** Cell exec origin. Direct requests select this sandbox by header. */
5376
+ execHost?: string;
5377
+ /** Short command-only credential; refreshed through the Sandbox API. */
5378
+ execToken?: string;
5379
+ execTokenExpiresAt?: string;
5380
+ /** Access token for authenticating directly with the runtime (Bearer token) */
5381
+ authToken?: string;
5382
+ /** Token expiration timestamp (ISO 8601). Refresh before this time. */
5383
+ authTokenExpiresAt?: string;
5384
+ /** Public inbound edge attachment state for `runtimeUrl`. */
5385
+ edgeStatus?: "pending" | "ready" | "failed" | "skipped";
5386
+ /** Timestamp when the public edge reached this sandbox. */
5387
+ edgeReadyAt?: string;
5388
+ /** Last public edge attachment error message. */
5389
+ edgeError?: string;
5390
+ /** SSH connection info if `sshEnabled` was true during creation */
5391
+ ssh?: SSHCredentials;
5392
+ /** Web terminal URL if `webTerminalEnabled` was true during creation */
5393
+ webTerminalUrl?: string;
5394
+ }
5395
+ /**
5396
+ * One attributed step in a sandbox cold-start, as emitted by the
5397
+ * platform startup pipeline. Mirrors the platform
5398
+ * `StartupOperationTiming` shape one-to-one.
5399
+ *
5400
+ * - `operation` is by convention `<service>.<phase>`
5401
+ * (e.g. `host-agent.container_create`).
5402
+ * - `durationMs` is wall-clock time the step took. The platform
5403
+ * marks it optional on `skipped` steps, so it is optional here too.
5404
+ */
5405
+ interface StartupOperation {
5406
+ /** `<service>.<phase>` operation name. */
5407
+ operation: string;
5408
+ /** Service that performed the step, when attributed. */
5409
+ service?: string;
5410
+ /** Terminal status of the step (e.g. `completed`, `skipped`, `error`). */
5411
+ status?: string;
5412
+ /** Wall-clock duration of the step in milliseconds, when measured. */
5413
+ durationMs?: number;
5414
+ /**
5415
+ * `operation` of the step whose wall CONTAINS this one; absent means the
5416
+ * step hangs directly under the flow total. Add only the steps that no
5417
+ * other step names as its parent — a parent re-measures the time its
5418
+ * children already report, so summing both over-counts the flow.
5419
+ */
5420
+ parent?: string;
5421
+ /** PII-scrubbed step detail (counts, ids, error codes). */
5422
+ metadata?: Record<string, unknown>;
5423
+ }
5424
+ /**
5425
+ * The startup breakdown for a sandbox cold-start. Returned by
5426
+ * {@link SandboxInstance.startupDiagnostics} so a customer can read where
5427
+ * provisioning time went (host selection, container create/start, health
5428
+ * checks, runtime readiness, workspace setup, etc.).
5429
+ *
5430
+ * `operations` is the raw ordered list from the platform. `phases`
5431
+ * is a derived convenience map of operation name → `durationMs` for the
5432
+ * steps that reported a duration; steps without a measured duration are
5433
+ * omitted from `phases` but still present in `operations`.
5434
+ *
5435
+ * `phases` mixes containing steps with the steps they contain, so its values
5436
+ * do NOT add up to the flow wall. To add durations, filter `operations` to
5437
+ * those no other operation names as its `parent`.
5438
+ */
5439
+ interface StartupDiagnostics {
5440
+ /** Ordered startup steps exactly as the platform emitted them. */
5441
+ operations: StartupOperation[];
5442
+ /** Derived map of operation name → measured duration in milliseconds. */
5443
+ phases: Record<string, number>;
5444
+ }
5445
+ /**
5446
+ * Full sandbox information returned from the API.
5447
+ */
5448
+ interface SandboxInfo {
5449
+ /** Unique sandbox identifier */
5450
+ id: string;
5451
+ /** Human-readable name */
5452
+ name?: string;
5453
+ /** Control-plane identity of the currently published filesystem contents. */
5454
+ filesystemIncarnationId?: string;
5455
+ /** How the current filesystem contents were acquired. */
5456
+ filesystemIncarnationProvenance?: "fresh" | "restored" | "unknown";
5457
+ /** Whether this incarnation is safe for consumers to treat as authoritative. */
5458
+ filesystemIncarnationReadiness?: "transitioning" | "ready";
5459
+ /** Current status */
5460
+ status: SandboxStatus;
5461
+ /** Connection information */
5462
+ connection?: SandboxConnection;
5463
+ /** Custom metadata */
5464
+ metadata?: Record<string, unknown>;
5465
+ /** Verified current container identity, available on create and get. */
5466
+ captureProof?: SandboxCreateReceipt["captureProof"];
5777
5467
  /**
5778
- * Sidecar capabilities to enable at boot. Each capability boots an
5779
- * additional subsystem inside the sandbox; absent capabilities incur
5780
- * zero startup cost.
5781
- *
5782
- * Currently supported:
5783
- * - `"computer_use"` — boots Xvfb, dbus, AT-SPI, and an MCP server
5784
- * exposing mouse/keyboard/screenshot via the Anthropic + OpenAI
5785
- * Responses computer-use surface. Required if you plan to call
5786
- * {@link SandboxInstance.getMcpAccessToken | `getMcpAccessToken`}
5787
- * with `capabilities: ["computer_use"]`.
5788
- *
5789
- * The capability is enforced at two layers:
5790
- * 1. The sidecar refuses to start if a capability's binaries are
5791
- * missing (`computer_use` needs the mounted Nix profile with
5792
- * Xvfb, dbus, xdotool, and scrot available at runtime).
5793
- * 2. The MCP token endpoint refuses to mint a `cap: ["computer_use"]`
5794
- * JWT for a sandbox that wasn't created with that capability.
5795
- *
5796
- * **Sizing note:** `computer_use` boots an always-on Xvfb + dbus
5797
- * stack costing roughly **~100 MB resident memory** inside the
5798
- * container. Billing is by reserved capacity (not measured RSS), so
5799
- * this comes out of your sandbox's RAM envelope rather than adding
5800
- * a separate line item. On a 1 GB sandbox that is ~10% of your
5801
- * workload's headroom; bump `resources.memoryMB` to 1.5–2 GB if
5802
- * the agent will run anything memory-hungry alongside it.
5803
- *
5804
- * @example
5805
- * ```typescript
5806
- * const box = await client.create({
5807
- * capabilities: ["computer_use"],
5808
- * });
5809
- * const { token } = await box.getMcpAccessToken({
5810
- * capabilities: ["computer_use"],
5811
- * });
5812
- * ```
5468
+ * Server-derived compliance echo (HIPAA), read-only: present only as the
5469
+ * positive claim `{ hipaa: true }`, pinned from verified Platform
5470
+ * attribution at provision. There is deliberately NO create option for
5471
+ * this — a caller-asserted compliance flag would let a tenant either
5472
+ * dodge the observability gates or claim protection the platform never
5473
+ * granted. Absent means the platform made no claim; `hipaa: false` is
5474
+ * never emitted.
5813
5475
  */
5814
- capabilities?: ReadonlyArray<"computer_use">;
5476
+ readonly compliance?: {
5477
+ readonly hipaa: true;
5478
+ };
5479
+ /** When the sandbox was created */
5480
+ createdAt: Date;
5481
+ /** When the sandbox started running */
5482
+ startedAt?: Date;
5483
+ /** Last activity timestamp */
5484
+ lastActivityAt?: Date;
5485
+ /** When the sandbox will expire */
5486
+ expiresAt?: Date;
5487
+ /** Error message if status is 'failed' */
5488
+ error?: string;
5489
+ /** GPU lease attached during sandbox creation, when requested. */
5490
+ gpuLease?: GpuLease;
5815
5491
  /**
5816
- * Privacy controls for the sandbox. Two independent layers:
5817
- *
5818
- * - **`egress`** — what happens when the sandbox sends a request to a
5819
- * model vendor (Anthropic, OpenAI, your own router, etc.):
5820
- * - `"redact"` — PII spans are masked before the request leaves
5821
- * the sandbox. Emails, JWTs, API keys, credit cards (Luhn-
5822
- * validated), SSNs, phone numbers, IPv4 addresses are caught
5823
- * today; names / postal addresses / DOBs land when the OPF
5824
- * model service is enabled. The agent receives normal
5825
- * responses; the vendor sees masked input.
5826
- * - `"block"` — PII presence fails the egress request closed.
5827
- * For high-compliance flows that prefer fail-closed to leak.
5828
- * - `"off"` — no egress filtering. Default for free tier; opt-in
5829
- * for tasks that genuinely need raw PII (form-filling,
5830
- * customer-support agents reading customer details).
5831
- *
5832
- * - **`logs`** — whether infrastructure logs / telemetry / Sentry
5833
- * redact PII before recording. This is OUR side, not the model
5834
- * vendor's, and there's basically never a reason to leak PII into
5835
- * our own logs. Default `"on"`.
5836
- *
5837
- * Note: privacy controls operate at the boundary between the
5838
- * sandbox and external systems. They do NOT redact contents inside
5839
- * the sandbox workspace itself — files / code / database fixtures
5840
- * the customer puts there are the customer's data and stay
5841
- * unmodified. Snapshots preserve those contents verbatim.
5842
- *
5843
- * @example
5844
- * ```typescript
5845
- * const box = await client.create({
5846
- * privacy: { egress: "redact", logs: "on" },
5847
- * });
5848
- * ```
5492
+ * The shape the sandbox was granted. Always present on the create response
5493
+ * and on a `get` whose billing record could be read; absent on a list row
5494
+ * and when the platform has no record to read, where it reports no grant
5495
+ * rather than a default the box may not be running at. A sandbox created
5496
+ * before the platform recorded shapes reports what its billing row holds,
5497
+ * which for such a row is the repair value the ledger charges.
5849
5498
  */
5850
- privacy?: {
5851
- egress?: "redact" | "block" | "off";
5852
- logs?: "on" | "off";
5853
- };
5499
+ resources?: SandboxShape;
5854
5500
  /**
5855
- * Stable idempotency key for this logical create. Sent as the
5856
- * `Idempotency-Key` header so the API derives a deterministic sandbox
5857
- * identity from (owner, key): a retried create resolves to the SAME
5858
- * provisioning sandbox and joins the in-flight provision instead of
5859
- * starting a fresh cold start per retry. When omitted, the SDK
5860
- * generates one per `create()` call and reuses it across its own
5861
- * timeout-driven retries.
5501
+ * Startup phase breakdown, present only on the create response (the
5502
+ * platform emits it once, at provision time). Use
5503
+ * {@link SandboxInstance.startupDiagnostics} rather than reading this
5504
+ * directly.
5862
5505
  */
5863
- idempotencyKey?: string;
5506
+ startupDiagnostics?: StartupDiagnostics;
5864
5507
  /**
5865
- * Platform user id whose wallet funds managed model usage for this sandbox.
5866
- *
5867
- * Use only from a trusted first-party service acting for an authenticated
5868
- * user. The Sandbox API honors this field only when the caller's exact
5869
- * verified API key ID is allow-listed; otherwise strict deployments reject
5870
- * the create.
5871
- * It never grants the caller permission to charge arbitrary users.
5872
- *
5873
- * This option applies to the HTTP Sandbox API client. Direct Tangle job
5874
- * creation does not support delegated billing.
5508
+ * The platform verdict for the create call that returned this sandbox.
5509
+ * Present only on the create response. An absent value means the platform
5510
+ * reported no receipt: treat it as `unknown`, never as `created`. Use
5511
+ * {@link SandboxInstance.createReceipt} rather than reading this directly.
5875
5512
  */
5876
- billingOwnerId?: string;
5513
+ createReceipt?: SandboxCreateReceipt;
5514
+ /** Resolved egress policy */
5515
+ egressPolicy?: EgressPolicy;
5516
+ /** Source of the egress policy */
5517
+ egressPolicySource?: "sandbox" | "team" | "platform";
5518
+ }
5519
+ /** Basic health reported by the runtime inside a sandbox. */
5520
+ interface SandboxRuntimeHealth {
5521
+ status: string;
5522
+ docker: {
5523
+ enabled: boolean;
5524
+ status: string;
5525
+ dockerHost?: string;
5526
+ error?: string;
5527
+ };
5528
+ backends: {
5529
+ total: number;
5530
+ byType: Record<string, number>;
5531
+ pending: number;
5532
+ };
5533
+ timestamp: string;
5534
+ }
5535
+ /** Public preview link associated with a listening runtime port. */
5536
+ interface SandboxPortPreviewLink {
5537
+ previewId: string;
5538
+ url: string;
5539
+ status: string;
5540
+ }
5541
+ /** One process listening on a port inside a sandbox. */
5542
+ interface SandboxPortBinding {
5543
+ pid: number;
5544
+ processName: string;
5545
+ commandPath: string;
5546
+ port: number;
5547
+ protocol: "tcp" | "udp";
5548
+ localAddress: string;
5549
+ family: "tcp4" | "tcp6" | "udp4" | "udp6";
5550
+ allowlisted: boolean;
5551
+ firstSeenAt: string;
5552
+ lastSeenAt: string;
5553
+ previewLink?: SandboxPortPreviewLink;
5554
+ }
5555
+ /** Options for creating an interactive terminal. */
5556
+ interface SandboxTerminalCreateOptions {
5557
+ name?: string;
5558
+ description?: string;
5559
+ shell?: string;
5560
+ cwd?: string;
5561
+ cols?: number;
5562
+ rows?: number;
5563
+ }
5564
+ /** Runtime request context used to attribute terminal events to an agent session. */
5565
+ interface SandboxTerminalRequestOptions {
5566
+ sessionId?: string;
5567
+ }
5568
+ /** Interactive terminal metadata returned by the runtime. */
5569
+ interface SandboxTerminalInfo {
5570
+ sessionId: string;
5571
+ connectionId?: string;
5572
+ name?: string;
5573
+ description?: string;
5574
+ shell?: string;
5575
+ command?: string;
5576
+ cwd?: string;
5577
+ cols?: number;
5578
+ rows?: number;
5579
+ createdAt?: string;
5580
+ lastActivityAt?: string;
5581
+ isRunning?: boolean;
5582
+ exitCode?: number;
5583
+ exitSignal?: string;
5584
+ /** WebSocket path for terminal input/output. */
5585
+ streamUrl?: string;
5586
+ history?: unknown[];
5587
+ }
5588
+ /** Interactive terminal operations. Input/output flows over `streamUrl`. */
5589
+ interface SandboxTerminalManager {
5590
+ create(options?: SandboxTerminalCreateOptions, request?: SandboxTerminalRequestOptions): Promise<SandboxTerminalInfo>;
5591
+ /** Send input through the runtime's HTTP fallback for an existing terminal. */
5592
+ input(terminalId: string, data: string, request?: SandboxTerminalRequestOptions): Promise<void>;
5593
+ list(): Promise<SandboxTerminalInfo[]>;
5594
+ get(sessionId: string): Promise<SandboxTerminalInfo | null>;
5595
+ }
5596
+ /** Options for `box.terminals.attach()`. */
5597
+ interface SandboxTerminalAttachOptions {
5598
+ /** Initial PTY geometry reported in the attach init frame. */
5599
+ cols?: number;
5600
+ rows?: number;
5601
+ /** Command to run when the connection id has no live PTY (default: shell). */
5602
+ command?: string;
5603
+ cwd?: string;
5604
+ env?: Record<string, string>;
5877
5605
  /**
5878
- * What pays this sandbox's compute. `"referral_credit"` spends the
5879
- * account's referral Sandbox-compute credit only: it runs on spare capacity,
5880
- * never falls back to the wallet, and stops with `scoped_credit_exhausted`
5881
- * when the credit runs out or `scoped_credit_held` while its campaign is on
5882
- * hold. Fixed for the sandbox's life. Personal sandboxes only. Defaults to
5883
- * the wallet.
5606
+ * Stream callbacks, bound before the socket opens. Register `onData` here:
5607
+ * a reattached PTY replays its buffered screen immediately after the
5608
+ * attach acknowledgement, so a handler added after `attach()` resolves
5609
+ * would miss the replayed frames.
5884
5610
  */
5885
- funding?: "wallet" | "referral_credit";
5611
+ handlers?: TerminalStreamHandlers;
5612
+ }
5613
+ /**
5614
+ * `box.terminals` — the REST terminal manager plus the live PTY attach
5615
+ * surface. `attach()` opens the terminal WebSocket through the secured
5616
+ * sidecar proxy — a Node caller sends its API key on the upgrade, a browser a
5617
+ * short-lived scoped token minted per dial — as a
5618
+ * {@link TerminalStream}: reusing a connection id reattaches the existing
5619
+ * PTY and replays its history; a new id spawns a fresh shell (or `command`).
5620
+ */
5621
+ interface SandboxTerminals extends SandboxTerminalManager {
5622
+ attach(connectionId: string, options?: SandboxTerminalAttachOptions): Promise<TerminalStream>;
5623
+ }
5624
+ /**
5625
+ * Raw TEE attestation evidence returned by the sandbox runtime.
5626
+ *
5627
+ * Pass this object to `@tangle-network/tcloud-attestation` for caller-side
5628
+ * policy checks and hardware verification.
5629
+ */
5630
+ interface TeeAttestationReport {
5631
+ /** TEE backend that produced the report, e.g. `Tdx`, `Sev`, or `Nitro`. */
5632
+ tee_type: string;
5633
+ /** Raw vendor evidence bytes. */
5634
+ evidence: number[];
5635
+ /** Runtime measurement bytes. */
5636
+ measurement: number[];
5637
+ /** Unix timestamp when the report was generated. */
5638
+ timestamp: number;
5639
+ }
5640
+ /**
5641
+ * Response from a sandbox TEE attestation request.
5642
+ */
5643
+ interface TeeAttestationResponse {
5644
+ /** Sandbox identifier the attestation belongs to. */
5645
+ sandbox_id: string;
5646
+ /** Raw TEE attestation report. */
5647
+ attestation: TeeAttestationReport;
5648
+ /** Caller nonce used for this report, when supplied. */
5649
+ attestationNonce?: string;
5650
+ }
5651
+ /**
5652
+ * TEE-bound public key used for sealed-secret encryption.
5653
+ */
5654
+ interface TeePublicKey {
5655
+ /** Key agreement/encryption algorithm, e.g. `x25519-hkdf-sha256`. */
5656
+ algorithm: string;
5657
+ /** Raw public key bytes. */
5658
+ public_key_bytes: number[];
5659
+ /** Attestation report binding this key to the enclave. */
5660
+ attestation: TeeAttestationReport;
5661
+ }
5662
+ /**
5663
+ * Response from a sandbox TEE public-key request.
5664
+ */
5665
+ interface TeePublicKeyResponse {
5666
+ /** Sandbox identifier the public key belongs to. */
5667
+ sandbox_id: string;
5668
+ /** TEE-bound public key and its attestation proof. */
5669
+ public_key: TeePublicKey;
5670
+ }
5671
+ /**
5672
+ * Options for requesting fresh TEE attestation evidence.
5673
+ */
5674
+ interface TeeAttestationOptions {
5886
5675
  /**
5887
- * Place this sandbox only on spare capacity.
5888
- *
5889
- * For first-party delegated creates only: the Sandbox API accepts it only
5890
- * together with `billingOwnerId` from an allow-listed first-party service
5891
- * key, and refuses every other create with 403 `CAPACITY_CLASS_FORBIDDEN`.
5892
- * It restricts placement and is not a priority: no host outside the spare
5893
- * pool takes the sandbox, and the create is refused with 503
5894
- * `SPARE_CAPACITY_UNAVAILABLE` when no spare pool admits it. It also skips
5895
- * the warm pool. The class is fixed at create; resume keeps it.
5676
+ * Hex-encoded 32-64 byte caller nonce. When supported by the selected TEE
5677
+ * backend, the runtime binds this to report data so the caller can reject
5678
+ * replayed quotes.
5896
5679
  */
5897
- capacityClass?: "spare_only";
5680
+ attestationNonce?: string;
5681
+ }
5682
+ /**
5683
+ * Options for listing sandboxes.
5684
+ */
5685
+ interface ListSandboxOptions {
5686
+ /** Filter by status */
5687
+ status?: SandboxStatus | SandboxStatus[];
5688
+ /** Filter personal/team visibility scope */
5689
+ scope?: "personal" | "team" | "all" | `team:${string}`;
5690
+ /** Maximum number of results */
5691
+ limit?: number;
5692
+ /** Offset for pagination */
5693
+ offset?: number;
5694
+ /** Only sandboxes created with this `metadata.run` (the caller's run id). */
5695
+ run?: string;
5696
+ }
5697
+ /**
5698
+ * One compute generation of a sandbox created for a caller run
5699
+ * (`metadata.run`). Deleted sandboxes keep theirs.
5700
+ */
5701
+ interface SandboxRunGeneration {
5702
+ sandboxId: string;
5703
+ /** The sandbox's own compute generation id, not the caller run. */
5704
+ generation: string;
5705
+ generationSeq: number;
5706
+ orgId: string;
5707
+ state: string;
5708
+ startedAt: number;
5709
+ closedAt: number | null;
5710
+ closedReason: string | null;
5711
+ }
5712
+ //#endregion
5713
+ //#region src/types/fleet.d.ts
5714
+ /**
5715
+ * Stable worker identifier inside a sandbox fleet.
5716
+ *
5717
+ * Machine IDs are intentionally narrower than sandbox names so agents
5718
+ * can route work without smuggling shell metacharacters or path-like
5719
+ * values through tool calls.
5720
+ */
5721
+ type FleetMachineId = string;
5722
+ /** Stable id of one agent in a fleet. It is also the agent's session id on its sandbox. */
5723
+ type FleetAgentId = string;
5724
+ /**
5725
+ * Where one agent runs. `shared` agents share a sandbox's filesystem, CPU and
5726
+ * memory with other agents of the same fleet; `dedicated` gives the agent a
5727
+ * sandbox of its own (repository writes, untrusted code).
5728
+ */
5729
+ type FleetAgentPlacement = "shared" | "dedicated";
5730
+ /**
5731
+ * A saved profile from the Platform agent-profile catalog
5732
+ * (`GET /v1/agent-profiles/:id`). With `revision`, create refuses the fleet
5733
+ * unless the catalog still holds exactly that revision.
5734
+ */
5735
+ interface SandboxFleetProfileRef {
5736
+ profileId: string;
5737
+ revision?: number;
5738
+ }
5739
+ interface SandboxFleetAgentSpec {
5740
+ /** Defaults to `agent-<index>`. */
5741
+ agentId?: FleetAgentId;
5742
+ /** Defaults to `shared`. */
5743
+ placement?: FleetAgentPlacement;
5744
+ /** Harness this agent runs. Defaults to `profile.harness`, then `defaults.backend.type`. */
5745
+ harness?: BackendType;
5898
5746
  /**
5899
- * Auto-split inline file mounts out of an inline `backend.profile` object
5900
- * at create time, send the lean profile (mount refs stripped) in the
5901
- * create request, then write the deferred files back once the sandbox is
5902
- * running.
5903
- *
5904
- * When `true` (the default), a profile with sizeable inline mounts (e.g.
5905
- * skills, tool scripts) does not bloat the create POST; the SDK
5906
- * materializes those files via {@link FileSystem.writeMany} /
5907
- * {@link FileSystem.uploadData} after the sandbox reaches `running`. A batch
5908
- * write answered 502, 503 or 504, or lost with its connection, is sent again
5909
- * for up to 10 seconds before create() raises `PartialFailureError`. Only
5910
- * applies to an inline `AgentProfile` object on `backend.profile`; a
5911
- * named-profile string is never split. Set `false` to send the full profile
5912
- * in the create request without a post-create materialization step.
5913
- *
5914
- * @default true
5747
+ * Model this agent runs: a model id, or a model config (`provider`,
5748
+ * `baseUrl`, `apiKeyEnv` naming a sandbox env var that holds the key).
5749
+ * Defaults to `profile.model.default`, then `defaults.backend.model`.
5915
5750
  */
5916
- autoMaterializeProfileFiles?: boolean;
5751
+ model?: string | NonNullable<BackendConfig["model"]>;
5917
5752
  /**
5918
- * Auto-defer an inline `backend.profile`'s static corpus so it is delivered
5919
- * once instead of on every turn. At create time the SDK strips inline
5920
- * `resources.skills` from the create request (keeping the create body under
5921
- * its wire cap), then primes the running sandbox with the full profile and
5922
- * references it by hash (`backend.profileSha256`) on subsequent turns. The
5923
- * handle still holds the full profile, so a cache miss transparently resends
5924
- * it.
5925
- *
5926
- * When `false`, the full profile, including skills, travels with the create
5927
- * request and every turn. This applies only to an inline `AgentProfile`
5928
- * object on `backend.profile` and is independent of
5929
- * {@link autoMaterializeProfileFiles}.
5930
- *
5931
- * A turn only substitutes the hash reference when the outgoing profile's
5932
- * content still matches what was primed: mutate the profile (or pass a
5933
- * changed per-turn `backend.profile`) and that turn sends the full profile
5934
- * inline again, so the runtime always runs the profile you passed.
5935
- *
5936
- * @default true
5753
+ * The agent's profile: an inline `AgentProfile`, or a saved profile by id.
5754
+ * Every turn sends it as `backend.profile`, so the runtime materializes its
5755
+ * skills, instructions, MCP servers and files into the agent's own harness
5756
+ * session. Defaults to `defaults.backend.profile`.
5937
5757
  */
5938
- autoDeferProfile?: boolean;
5758
+ profile?: AgentProfile | SandboxFleetProfileRef;
5759
+ /** Runtime MCP bindings for this agent, separate from its profile. */
5760
+ runtimeAttachments?: AgentRuntimeAttachments;
5761
+ /** The agent's own task. `run()` sends it when called without a message. */
5762
+ task?: string | PromptInputPart[];
5939
5763
  }
5940
5764
  /**
5941
- * Per-call overrides for {@link Sandbox.create}.
5765
+ * How a fleet packs agents onto sandboxes.
5766
+ *
5767
+ * - `auto` (default): as many agents per sandbox as its memory holds, from
5768
+ * the measured footprint of an idle sandbox and of one agent.
5769
+ * - `dedicated`: one sandbox per agent.
5770
+ * - `{ agentsPerSandbox }`: exactly that many shared agents per sandbox.
5942
5771
  */
5943
- interface CreateRequestOptions {
5944
- /**
5945
- * Time budget for the whole create-and-reach-running flow, in
5946
- * milliseconds. Cold provisions routinely take ~25–40s, so this
5947
- * defaults high (120000). If the initial POST rides the deadline the
5948
- * SDK polls the sandbox to `running` rather than re-POSTing.
5949
- */
5950
- timeoutMs?: number;
5951
- /** Abort the create + poll early. */
5952
- signal?: AbortSignal;
5772
+ type SandboxFleetPlacement = "auto" | "dedicated" | {
5773
+ agentsPerSandbox: number;
5774
+ };
5775
+ /** The fleet and agent that spawned a child fleet. */
5776
+ interface SandboxFleetParent {
5777
+ fleetId: string;
5778
+ agentId: FleetAgentId;
5779
+ }
5780
+ /** One agent of a fleet and the sandbox that hosts it. */
5781
+ interface SandboxFleetAgent {
5782
+ agentId: FleetAgentId;
5783
+ machineId: FleetMachineId;
5784
+ sandboxId: string;
5785
+ /** Session the agent's turns run in; equal to `agentId`. */
5786
+ sessionId: string;
5787
+ /** Harness the agent runs; unset means the sandbox's default backend. */
5788
+ harness?: BackendType;
5789
+ /** Model the agent runs; unset means the sandbox's default model. */
5790
+ model?: string;
5791
+ /** Name of the agent's profile, when it has one. */
5792
+ profileName?: string;
5953
5793
  }
5954
- //#endregion
5955
- //#region src/types/sandbox-info.d.ts
5956
- /**
5957
- * SSH connection credentials.
5958
- */
5959
- interface SSHCredentials {
5960
- /** Username for SSH authentication */
5961
- username: string;
5962
- /** SSH server port */
5963
- port: number;
5964
- /** ProxyCommand for sandbox API tunnel-based SSH. */
5965
- proxyCommand: string;
5794
+ interface FleetRunOptions extends Pick<PromptOptions, "timeoutMs" | "context"> {
5795
+ /** Agents to run. Defaults to every agent in the fleet. */
5796
+ agents?: FleetAgentId[];
5797
+ /** Aborts every agent turn this run started. */
5798
+ signal?: AbortSignal;
5966
5799
  }
5967
- interface SSHCommandDescriptor {
5968
- command: string;
5969
- env: Record<string, string>;
5800
+ type FleetAgentRunStatus = "completed" | "failed" | "cancelled" | "budget_exhausted";
5801
+ interface FleetAgentResult extends SandboxFleetAgent {
5802
+ /**
5803
+ * `budget_exhausted`: the Platform refused the turn's model or compute
5804
+ * charge because the fleet's key budget is spent.
5805
+ */
5806
+ status: FleetAgentRunStatus;
5807
+ /** The agent's turn result: response text, token usage, trace id. */
5808
+ result?: PromptResult;
5809
+ /** Model cost the runtime reported for this turn, when it reported one. */
5810
+ costUsd?: number;
5811
+ durationMs: number;
5812
+ error?: string;
5970
5813
  }
5814
+ type FleetRunEvent = ({
5815
+ type: "agent.started";
5816
+ traceId: string;
5817
+ } & SandboxFleetAgent) | {
5818
+ type: "agent.finished";
5819
+ result: FleetAgentResult;
5820
+ } | {
5821
+ type: "fleet.finished";
5822
+ results: FleetAgentResult[]; /** Metered spend when it could be read; the results never depend on it. */
5823
+ spend?: SandboxFleetSpend;
5824
+ spendError?: string;
5825
+ durationMs: number;
5826
+ };
5971
5827
  /**
5972
- * Connection information for a sandbox.
5973
- *
5974
- * Most code should use `SandboxInstance` methods (`exec`, `prompt`, etc.).
5975
- * The raw `runtimeUrl` and `authToken` are surfaced only for advanced
5976
- * lower-level use cases such as custom protocol clients.
5828
+ * Spend of a capped fleet, metered by the Platform on the fleet's budgeted
5829
+ * key: every router call and compute charge of every sandbox the fleet
5830
+ * created, whichever process or handle drove it. A child fleet's cap is
5831
+ * reserved from its parent's budget when the child is created.
5977
5832
  */
5978
- interface SandboxConnection {
5979
- /** Sandbox runtime API URL for programmatic access */
5980
- runtimeUrl?: string;
5981
- /** Cell exec origin. Direct requests select this sandbox by header. */
5982
- execHost?: string;
5983
- /** Short command-only credential; refreshed through the Sandbox API. */
5984
- execToken?: string;
5985
- execTokenExpiresAt?: string;
5986
- /** Access token for authenticating directly with the runtime (Bearer token) */
5987
- authToken?: string;
5988
- /** Token expiration timestamp (ISO 8601). Refresh before this time. */
5989
- authTokenExpiresAt?: string;
5990
- /** Public inbound edge attachment state for `runtimeUrl`. */
5991
- edgeStatus?: "pending" | "ready" | "failed" | "skipped";
5992
- /** Timestamp when the public edge reached this sandbox. */
5993
- edgeReadyAt?: string;
5994
- /** Last public edge attachment error message. */
5995
- edgeError?: string;
5996
- /** SSH connection info if `sshEnabled` was true during creation */
5997
- ssh?: SSHCredentials;
5998
- /** Web terminal URL if `webTerminalEnabled` was true during creation */
5999
- webTerminalUrl?: string;
5833
+ interface SandboxFleetSpend {
5834
+ capUsd: number;
5835
+ /** Charges the Platform has settled against the fleet's key. */
5836
+ spentUsd: number;
5837
+ /** Budget held for child fleets' caps. */
5838
+ reservedForChildrenUsd: number;
5839
+ /** What the fleet may still spend or allocate: cap minus spent minus reserved. */
5840
+ remainingUsd: number;
6000
5841
  }
5842
+ type SandboxFleetMachineRole = "coordinator" | "worker";
6001
5843
  /**
6002
- * One attributed step in a sandbox cold-start, as emitted by the
6003
- * platform startup pipeline. Mirrors the platform
6004
- * `StartupOperationTiming` shape one-to-one.
5844
+ * Resource policy for a single fleet create call.
6005
5845
  *
6006
- * - `operation` is by convention `<service>.<phase>`
6007
- * (e.g. `host-agent.container_create`).
6008
- * - `durationMs` is wall-clock time the step took. The platform
6009
- * marks it optional on `skipped` steps, so it is optional here too.
5846
+ * These caps are enforced client-side before any sandbox is created.
5847
+ * Server-side plan quotas still apply and remain the source of truth.
6010
5848
  */
6011
- interface StartupOperation {
6012
- /** `<service>.<phase>` operation name. */
6013
- operation: string;
6014
- /** Service that performed the step, when attributed. */
6015
- service?: string;
6016
- /** Terminal status of the step (e.g. `completed`, `skipped`, `error`). */
6017
- status?: string;
6018
- /** Wall-clock duration of the step in milliseconds, when measured. */
6019
- durationMs?: number;
5849
+ interface SandboxFleetPolicy {
5850
+ /** Maximum number of machines in this create call. Defaults to machines.length. */
5851
+ maxMachines?: number;
5852
+ /** Maximum sandbox create fanout allowed for this fleet request. */
5853
+ maxConcurrentCreates?: number;
5854
+ /** Maximum total requested CPU cores across machines with explicit resources. */
5855
+ maxTotalCpu?: number;
5856
+ /** Maximum total requested memory across machines with explicit resources. */
5857
+ maxTotalMemoryMb?: number;
5858
+ /** Maximum total requested storage across machines with explicit resources. */
5859
+ maxTotalStorageMb?: number;
5860
+ /** Maximum total requested accelerator devices across machines. */
5861
+ maxTotalAccelerators?: number;
5862
+ /** Maximum lifetime in seconds for any machine in this fleet. */
5863
+ maxLifetimeSeconds?: number;
6020
5864
  /**
6021
- * `operation` of the step whose wall CONTAINS this one; absent means the
6022
- * step hangs directly under the flow total. Add only the steps that no
6023
- * other step names as its parent — a parent re-measures the time its
6024
- * children already report, so summing both over-counts the flow.
5865
+ * The fleet's spend cap in USD, enforced by the Platform: the fleet's
5866
+ * sandboxes are created with a key budgeted at the cap, so model and compute
5867
+ * charges past it are refused for every process that drives the fleet. A
5868
+ * child fleet's cap is reserved from its parent's remaining budget.
6025
5869
  */
6026
- parent?: string;
6027
- /** PII-scrubbed step detail (counts, ids, error codes). */
6028
- metadata?: Record<string, unknown>;
5870
+ maxSpendUsd?: number;
5871
+ /** Allowed infrastructure drivers for fleet machines. */
5872
+ allowedDrivers?: DriverType[];
5873
+ /** Allowed environments for fleet machines. */
5874
+ allowedEnvironments?: string[];
5875
+ /** Allowed personal or public template identifiers for fleet machines. */
5876
+ allowedTemplateIds?: string[];
5877
+ /** Whether machines may request accelerator devices. Defaults to allowed. */
5878
+ allowAccelerators?: boolean;
6029
5879
  }
6030
- /**
6031
- * The startup breakdown for a sandbox cold-start. Returned by
6032
- * {@link SandboxInstance.startupDiagnostics} so a customer can read where
6033
- * provisioning time went (host selection, container create/start, health
6034
- * checks, runtime readiness, workspace setup, etc.).
6035
- *
6036
- * `operations` is the raw ordered list from the platform. `phases`
6037
- * is a derived convenience map of operation name → `durationMs` for the
6038
- * steps that reported a duration; steps without a measured duration are
6039
- * omitted from `phases` but still present in `operations`.
6040
- *
6041
- * `phases` mixes containing steps with the steps they contain, so its values
6042
- * do NOT add up to the flow wall. To add durations, filter `operations` to
6043
- * those no other operation names as its `parent`.
6044
- */
6045
- interface StartupDiagnostics {
6046
- /** Ordered startup steps exactly as the platform emitted them. */
6047
- operations: StartupOperation[];
6048
- /** Derived map of operation name → measured duration in milliseconds. */
6049
- phases: Record<string, number>;
5880
+ interface SandboxFleetWorkspace {
5881
+ mode: "isolated" | "shared";
5882
+ id?: string;
5883
+ quotaMb?: number;
5884
+ mountPath?: string;
5885
+ snapshotId?: string;
6050
5886
  }
6051
5887
  /**
6052
- * Full sandbox information returned from the API.
5888
+ * Per-machine create spec for a sandbox fleet.
6053
5889
  */
6054
- interface SandboxInfo {
6055
- /** Unique sandbox identifier */
6056
- id: string;
6057
- /** Human-readable name */
5890
+ interface SandboxFleetMachineSpec extends Omit<CreateSandboxOptions, "metadata" | "name"> {
5891
+ /** Stable agent-facing machine id, e.g. "coordinator" or "worker-1". */
5892
+ machineId: FleetMachineId;
5893
+ /** Optional display name. Defaults to `${fleetId}-${machineId}`. */
6058
5894
  name?: string;
6059
- /** Control-plane identity of the currently published filesystem contents. */
6060
- filesystemIncarnationId?: string;
6061
- /** How the current filesystem contents were acquired. */
6062
- filesystemIncarnationProvenance?: "fresh" | "restored" | "unknown";
6063
- /** Whether this incarnation is safe for consumers to treat as authoritative. */
6064
- filesystemIncarnationReadiness?: "transitioning" | "ready";
6065
- /** Current status */
6066
- status: SandboxStatus;
6067
- /** Connection information */
6068
- connection?: SandboxConnection;
6069
- /** Custom metadata */
5895
+ /** Machine-specific metadata. Fleet tags are added automatically. */
6070
5896
  metadata?: Record<string, unknown>;
6071
- /** Verified current container identity, available on create and get. */
6072
- captureProof?: SandboxCreateReceipt["captureProof"];
5897
+ /** Optional orchestration role. Defaults to worker. */
5898
+ role?: SandboxFleetMachineRole;
5899
+ }
5900
+ /**
5901
+ * Create a named set of sandboxes for one workload.
5902
+ */
5903
+ interface CreateSandboxFleetOptions {
5904
+ /** Stable fleet id. Generated when omitted. */
5905
+ fleetId?: string;
5906
+ /** Shared defaults applied to every machine before per-machine overrides. */
5907
+ defaults?: Omit<CreateSandboxOptions, "metadata" | "name">;
6073
5908
  /**
6074
- * Server-derived compliance echo (HIPAA), read-only: present only as the
6075
- * positive claim `{ hipaa: true }`, pinned from verified Platform
6076
- * attribution at provision. There is deliberately NO create option for
6077
- * this — a caller-asserted compliance flag would let a tenant either
6078
- * dodge the observability gates or claim protection the platform never
6079
- * granted. Absent means the platform made no claim; `hipaa: false` is
6080
- * never emitted.
5909
+ * Machines to create, for fleets driven by `dispatchExec`. Set either
5910
+ * `machines` or `agents`.
6081
5911
  */
6082
- readonly compliance?: {
6083
- readonly hipaa: true;
6084
- };
6085
- /** When the sandbox was created */
6086
- createdAt: Date;
6087
- /** When the sandbox started running */
6088
- startedAt?: Date;
6089
- /** Last activity timestamp */
6090
- lastActivityAt?: Date;
6091
- /** When the sandbox will expire */
6092
- expiresAt?: Date;
6093
- /** Error message if status is 'failed' */
6094
- error?: string;
6095
- /** GPU lease attached during sandbox creation, when requested. */
6096
- gpuLease?: GpuLease;
5912
+ machines?: SandboxFleetMachineSpec[];
5913
+ /**
5914
+ * Agents to run: a count, or specs with ids and per-agent placement. The
5915
+ * fleet creates the sandboxes `placement` asks for, from `defaults`.
5916
+ */
5917
+ agents?: number | SandboxFleetAgentSpec[];
5918
+ /** How agents are packed onto sandboxes. Defaults to `auto`. */
5919
+ placement?: SandboxFleetPlacement;
5920
+ /**
5921
+ * A budget in USD the Platform enforces. The fleet mints a Platform key
5922
+ * with this budget and creates its sandboxes and drives its turns with it,
5923
+ * so every charge made through the fleet counts against the budget and a
5924
+ * charge past it is refused. Only the client that created the fleet holds
5925
+ * the key: other processes can read, cancel and delete the fleet but not
5926
+ * run its agents. Without it, `policy.maxSpendUsd` stays a create-time
5927
+ * estimate check. A turn driven on a fleet sandbox with another key is
5928
+ * billed to that key, outside the budget.
5929
+ */
5930
+ budgetUsd?: number;
5931
+ /**
5932
+ * The fleet and agent spawning this fleet. The API checks that the parent
5933
+ * exists and that this fleet's `policy.maxSpendUsd` fits in the parent's
5934
+ * unallocated cap; deleting or cancelling the parent reaches this fleet.
5935
+ */
5936
+ parent?: SandboxFleetParent;
5937
+ /** Fleet-level metadata copied to each sandbox under stable tags. */
5938
+ metadata?: Record<string, unknown>;
5939
+ /** Workspace policy for isolated or driver-supported shared mounts. */
5940
+ workspace?: SandboxFleetWorkspace;
5941
+ /**
5942
+ * Client-side safety caps for this create call. These do not replace
5943
+ * server-side quota enforcement.
5944
+ */
5945
+ policy?: SandboxFleetPolicy;
6097
5946
  /**
6098
- * The shape the sandbox was granted. Always present on the create response
6099
- * and on a `get` whose billing record could be read; absent on a list row
6100
- * and when the platform has no record to read, where it reports no grant
6101
- * rather than a default the box may not be running at. A sandbox created
6102
- * before the platform recorded shapes reports what its billing row holds,
6103
- * which for such a row is the repair value the ledger charges.
5947
+ * Delete already-created machines if a later machine fails to create.
5948
+ * Defaults to true so partial fleets do not silently burn quota.
6104
5949
  */
6105
- resources?: SandboxShape;
5950
+ cleanupOnFailure?: boolean;
6106
5951
  /**
6107
- * Startup phase breakdown, present only on the create response (the
6108
- * platform emits it once, at provision time). Use
6109
- * {@link SandboxInstance.startupDiagnostics} rather than reading this
6110
- * directly.
5952
+ * Sandbox creates in flight at once. Defaults to 8: every create and delete
5953
+ * mints or revokes two Platform keys, and about 25 in flight has locked the
5954
+ * Platform key store for every customer (2026-09-15).
6111
5955
  */
6112
- startupDiagnostics?: StartupDiagnostics;
5956
+ maxConcurrentCreates?: number;
6113
5957
  /**
6114
- * The platform verdict for the create call that returned this sandbox.
6115
- * Present only on the create response. An absent value means the platform
6116
- * reported no receipt: treat it as `unknown`, never as `created`. Use
6117
- * {@link SandboxInstance.createReceipt} rather than reading this directly.
5958
+ * Idempotency key for the server-backed fleet record. Defaults to fleetId.
6118
5959
  */
6119
- createReceipt?: SandboxCreateReceipt;
6120
- /** Resolved egress policy */
6121
- egressPolicy?: EgressPolicy;
6122
- /** Source of the egress policy */
6123
- egressPolicySource?: "sandbox" | "team" | "platform";
5960
+ idempotencyKey?: string;
6124
5961
  }
6125
- /** Basic health reported by the runtime inside a sandbox. */
6126
- interface SandboxRuntimeHealth {
6127
- status: string;
6128
- docker: {
6129
- enabled: boolean;
6130
- status: string;
6131
- dockerHost?: string;
6132
- error?: string;
5962
+ interface CreateSandboxFleetWithCoordinatorOptions extends Omit<CreateSandboxFleetOptions, "machines" | "agents" | "placement"> {
5963
+ /** Coordinator machine. Defaults to machineId "coordinator". */
5964
+ coordinator?: Omit<SandboxFleetMachineSpec, "machineId" | "role"> & {
5965
+ machineId?: FleetMachineId;
6133
5966
  };
6134
- backends: {
6135
- total: number;
6136
- byType: Record<string, number>;
6137
- pending: number;
5967
+ /** Worker machines attached to the same fleet. */
5968
+ workers: SandboxFleetMachineSpec[];
5969
+ }
5970
+ /**
5971
+ * A sandbox with its fleet-local machine id.
5972
+ */
5973
+ interface SandboxFleetMachine {
5974
+ machineId: FleetMachineId;
5975
+ sandbox: SandboxInfo;
5976
+ role?: SandboxFleetMachineRole;
5977
+ }
5978
+ /**
5979
+ * Fleet create/list result.
5980
+ */
5981
+ interface SandboxFleetInfo {
5982
+ fleetId: string;
5983
+ machines: SandboxFleetMachine[];
5984
+ policy?: SandboxFleetPolicy;
5985
+ parent?: SandboxFleetParent;
5986
+ createdAt?: string;
5987
+ /** Id of the budgeted Platform key a capped fleet's sandboxes charge. */
5988
+ keyId?: string;
5989
+ }
5990
+ interface FleetExecDispatchOptions extends Pick<ExecOptions, "cwd" | "env" | "timeoutMs"> {
5991
+ machines?: FleetMachineId[];
5992
+ /**
5993
+ * Branches in flight at once. Defaults to every selected machine. The API
5994
+ * runs on a Cloudflare Worker, which keeps at most six upstream connections
5995
+ * open per request, so branches past six queue (measured 2026-09-25: twelve
5996
+ * 8 s commands took 17.8 s, six took 9.7 s).
5997
+ */
5998
+ maxConcurrent?: number;
5999
+ retry?: {
6000
+ attempts?: number;
6138
6001
  };
6139
- timestamp: string;
6002
+ /** Caller-supplied dispatch id for idempotency/result lookup when supported by the API. */
6003
+ dispatchId?: string;
6004
+ /** Ask the API to retain branch results for later `dispatchResults` calls. */
6005
+ bufferResults?: boolean;
6140
6006
  }
6141
- /** Public preview link associated with a listening runtime port. */
6142
- interface SandboxPortPreviewLink {
6143
- previewId: string;
6144
- url: string;
6145
- status: string;
6007
+ interface FleetExecDispatchResult {
6008
+ machineId: FleetMachineId;
6009
+ sandboxId: string;
6010
+ ok: boolean;
6011
+ durationMs: number;
6012
+ attempts?: number;
6013
+ result?: ExecResult;
6014
+ error?: {
6015
+ message: string;
6016
+ status?: number;
6017
+ failureClass?: SandboxFleetDispatchFailureClass;
6018
+ retryAfterMs?: number;
6019
+ };
6146
6020
  }
6147
- /** One process listening on a port inside a sandbox. */
6148
- interface SandboxPortBinding {
6149
- pid: number;
6150
- processName: string;
6151
- commandPath: string;
6152
- port: number;
6153
- protocol: "tcp" | "udp";
6154
- localAddress: string;
6155
- family: "tcp4" | "tcp6" | "udp4" | "udp6";
6156
- allowlisted: boolean;
6157
- firstSeenAt: string;
6158
- lastSeenAt: string;
6159
- previewLink?: SandboxPortPreviewLink;
6021
+ interface FleetPromptDispatchOptions extends Pick<PromptOptions, "sessionId" | "backend" | "model" | "timeoutMs" | "context"> {
6022
+ machines?: FleetMachineId[];
6023
+ maxConcurrent?: number;
6024
+ retry?: {
6025
+ attempts?: number;
6026
+ };
6027
+ /** Caller-supplied dispatch id for idempotency/result lookup when supported by the API. */
6028
+ dispatchId?: string;
6029
+ /** Ask the API to retain branch results for later `dispatchResults` calls. */
6030
+ bufferResults?: boolean;
6160
6031
  }
6161
- /** Options for creating an interactive terminal. */
6162
- interface SandboxTerminalCreateOptions {
6163
- name?: string;
6164
- description?: string;
6165
- shell?: string;
6166
- cwd?: string;
6167
- cols?: number;
6168
- rows?: number;
6032
+ interface FleetPromptDispatchResult {
6033
+ machineId: FleetMachineId;
6034
+ sandboxId: string;
6035
+ ok: boolean;
6036
+ durationMs: number;
6037
+ attempts?: number;
6038
+ prompt?: PromptResult & {
6039
+ metadata?: Record<string, unknown>;
6040
+ };
6041
+ error?: {
6042
+ message: string;
6043
+ status?: number;
6044
+ failureClass?: SandboxFleetDispatchFailureClass;
6045
+ retryAfterMs?: number;
6046
+ };
6169
6047
  }
6170
- /** Runtime request context used to attribute terminal events to an agent session. */
6171
- interface SandboxTerminalRequestOptions {
6172
- sessionId?: string;
6048
+ type SandboxFleetDispatchFailureClass = "oom" | "timeout" | "dependency" | "infra" | "model" | "user_code";
6049
+ interface FleetDispatchStreamOptions {
6050
+ signal?: AbortSignal;
6173
6051
  }
6174
- /** Interactive terminal metadata returned by the runtime. */
6175
- interface SandboxTerminalInfo {
6176
- sessionId: string;
6177
- connectionId?: string;
6178
- name?: string;
6179
- description?: string;
6180
- shell?: string;
6181
- command?: string;
6182
- cwd?: string;
6183
- cols?: number;
6184
- rows?: number;
6052
+ interface FleetDispatchResultBufferOptions {
6053
+ cursor?: string;
6054
+ limit?: number;
6055
+ machines?: FleetMachineId[];
6056
+ }
6057
+ interface FleetDispatchResultBuffer<T = FleetExecDispatchResult> {
6058
+ fleetId: string;
6059
+ dispatchId: string;
6060
+ results: T[];
6061
+ cursor?: string;
6062
+ nextCursor?: string;
6063
+ done?: boolean;
6064
+ truncated?: boolean;
6065
+ trace?: SandboxFleetTraceExport;
6066
+ intelligence?: SandboxFleetIntelligenceEnvelope;
6067
+ }
6068
+ interface FleetDispatchCancelResult {
6069
+ fleetId: string;
6070
+ dispatchId: string;
6071
+ cancelled: boolean;
6072
+ status?: string;
6073
+ }
6074
+ interface SandboxFleetArtifactSpec {
6075
+ machineId: FleetMachineId;
6076
+ /**
6077
+ * Absolute path under /workspace. Fleet artifact collection intentionally
6078
+ * rejects host/system paths so caller-provided manifests cannot turn artifact
6079
+ * collection into arbitrary sandbox file reads.
6080
+ */
6081
+ path: string;
6082
+ label?: string;
6083
+ /** Maximum allowed artifact content size in bytes. Defaults to 10 MiB. */
6084
+ maxBytes?: number;
6085
+ }
6086
+ interface SandboxFleetArtifact extends SandboxFleetArtifactSpec {
6087
+ sandboxId: string;
6088
+ content: string;
6089
+ }
6090
+ interface SandboxFleetDriverTimings {
6091
+ queueMs?: number;
6092
+ placementMs?: number;
6093
+ provisionMs?: number;
6094
+ startupMs?: number;
6095
+ cleanupMs?: number;
6096
+ }
6097
+ interface SandboxFleetMachineMeteredUsage {
6098
+ runtimeMs: number;
6099
+ updatedAt: string;
6100
+ }
6101
+ interface AttachSandboxFleetMachineOptions {
6102
+ machineId: FleetMachineId;
6103
+ sandboxId: string;
6104
+ status?: string;
6105
+ role?: SandboxFleetMachineRole;
6106
+ driverType?: DriverType;
6107
+ environment?: string;
6108
+ templateId?: string;
6109
+ publicTemplateId?: string;
6110
+ acceleratorCount?: number;
6111
+ driverTimings?: SandboxFleetDriverTimings;
6112
+ }
6113
+ interface SandboxFleetMachineRecord extends AttachSandboxFleetMachineOptions {
6114
+ workspaceMountPath?: string;
6115
+ meteredUsage?: SandboxFleetMachineMeteredUsage;
6185
6116
  createdAt?: string;
6186
- lastActivityAt?: string;
6187
- isRunning?: boolean;
6188
- exitCode?: number;
6189
- exitSignal?: string;
6190
- /** WebSocket path for terminal input/output. */
6191
- streamUrl?: string;
6192
- history?: unknown[];
6117
+ updatedAt?: string;
6193
6118
  }
6194
- /** Interactive terminal operations. Input/output flows over `streamUrl`. */
6195
- interface SandboxTerminalManager {
6196
- create(options?: SandboxTerminalCreateOptions, request?: SandboxTerminalRequestOptions): Promise<SandboxTerminalInfo>;
6197
- /** Send input through the runtime's HTTP fallback for an existing terminal. */
6198
- input(terminalId: string, data: string, request?: SandboxTerminalRequestOptions): Promise<void>;
6199
- list(): Promise<SandboxTerminalInfo[]>;
6200
- get(sessionId: string): Promise<SandboxTerminalInfo | null>;
6119
+ interface SandboxFleetManifestMachine {
6120
+ machineId: FleetMachineId;
6121
+ sandboxId: string;
6122
+ role?: SandboxFleetMachineRole;
6123
+ status?: string;
6124
+ driverType?: DriverType;
6125
+ environment?: string;
6126
+ templateId?: string;
6127
+ publicTemplateId?: string;
6128
+ acceleratorCount?: number;
6129
+ workspaceMountPath?: string;
6130
+ driverTimings?: SandboxFleetDriverTimings;
6131
+ meteredUsage?: SandboxFleetMachineMeteredUsage;
6132
+ createdAt?: string;
6133
+ updatedAt?: string;
6201
6134
  }
6202
- /** Options for `box.terminals.attach()`. */
6203
- interface SandboxTerminalAttachOptions {
6204
- /** Initial PTY geometry reported in the attach init frame. */
6205
- cols?: number;
6206
- rows?: number;
6207
- /** Command to run when the connection id has no live PTY (default: shell). */
6208
- command?: string;
6209
- cwd?: string;
6210
- env?: Record<string, string>;
6211
- /**
6212
- * Stream callbacks, bound before the socket opens. Register `onData` here:
6213
- * a reattached PTY replays its buffered screen immediately after the
6214
- * attach acknowledgement, so a handler added after `attach()` resolves
6215
- * would miss the replayed frames.
6216
- */
6217
- handlers?: TerminalStreamHandlers;
6135
+ interface SandboxFleetManifest {
6136
+ fleetId?: string;
6137
+ id?: string;
6138
+ metadata?: Record<string, unknown>;
6139
+ policy?: SandboxFleetPolicy;
6140
+ resources?: Record<string, unknown>;
6141
+ workspace?: SandboxFleetWorkspace & {
6142
+ status?: string;
6143
+ createdAt?: string;
6144
+ updatedAt?: string;
6145
+ deletedAt?: string;
6146
+ };
6147
+ machines: SandboxFleetManifestMachine[];
6148
+ createdAt?: string;
6149
+ updatedAt?: string;
6218
6150
  }
6219
- /**
6220
- * `box.terminals` — the REST terminal manager plus the live PTY attach
6221
- * surface. `attach()` opens the terminal WebSocket through the secured
6222
- * sidecar proxy — a Node caller sends its API key on the upgrade, a browser a
6223
- * short-lived scoped token minted per dial — as a
6224
- * {@link TerminalStream}: reusing a connection id reattaches the existing
6225
- * PTY and replays its history; a new id spawns a fresh shell (or `command`).
6226
- */
6227
- interface SandboxTerminals extends SandboxTerminalManager {
6228
- attach(connectionId: string, options?: SandboxTerminalAttachOptions): Promise<TerminalStream>;
6151
+ interface SandboxFleetDispatchResponse<T = FleetExecDispatchResult> {
6152
+ fleetId: string;
6153
+ dispatchId: string;
6154
+ type: "exec" | "prompt";
6155
+ results: T[];
6156
+ durationMs: number;
6157
+ trace?: SandboxFleetTraceExport;
6158
+ intelligence?: SandboxFleetIntelligenceEnvelope;
6229
6159
  }
6230
- /**
6231
- * Raw TEE attestation evidence returned by the sandbox runtime.
6232
- *
6233
- * Pass this object to `@tangle-network/tcloud-attestation` for caller-side
6234
- * policy checks and hardware verification.
6235
- */
6236
- interface TeeAttestationReport {
6237
- /** TEE backend that produced the report, e.g. `Tdx`, `Sev`, or `Nitro`. */
6238
- tee_type: string;
6239
- /** Raw vendor evidence bytes. */
6240
- evidence: number[];
6241
- /** Runtime measurement bytes. */
6242
- measurement: number[];
6243
- /** Unix timestamp when the report was generated. */
6244
- timestamp: number;
6160
+ interface SandboxFleetWorkspaceSnapshotResult {
6161
+ snapshotId?: string;
6162
+ id?: string;
6163
+ status?: string;
6164
+ createdAt?: string;
6165
+ [key: string]: JsonValue | undefined;
6245
6166
  }
6246
- /**
6247
- * Response from a sandbox TEE attestation request.
6248
- */
6249
- interface TeeAttestationResponse {
6250
- /** Sandbox identifier the attestation belongs to. */
6251
- sandbox_id: string;
6252
- /** Raw TEE attestation report. */
6253
- attestation: TeeAttestationReport;
6254
- /** Caller nonce used for this report, when supplied. */
6255
- attestationNonce?: string;
6167
+ interface SandboxFleetWorkspaceRestoreResult {
6168
+ restored?: boolean;
6169
+ snapshotId?: string;
6170
+ status?: string;
6171
+ [key: string]: JsonValue | undefined;
6256
6172
  }
6257
- /**
6258
- * TEE-bound public key used for sealed-secret encryption.
6259
- */
6260
- interface TeePublicKey {
6261
- /** Key agreement/encryption algorithm, e.g. `x25519-hkdf-sha256`. */
6262
- algorithm: string;
6263
- /** Raw public key bytes. */
6264
- public_key_bytes: number[];
6265
- /** Attestation report binding this key to the enclave. */
6266
- attestation: TeeAttestationReport;
6173
+ interface SandboxFleetWorkspaceReconcileResult {
6174
+ fleetId: string;
6175
+ workspaceId?: string;
6176
+ checked: number;
6177
+ orphanedMounts: number;
6178
+ machines: Array<{
6179
+ machineId: string;
6180
+ sandboxId: string;
6181
+ mounted: boolean;
6182
+ }>;
6267
6183
  }
6268
- /**
6269
- * Response from a sandbox TEE public-key request.
6270
- */
6271
- interface TeePublicKeyResponse {
6272
- /** Sandbox identifier the public key belongs to. */
6273
- sandbox_id: string;
6274
- /** TEE-bound public key and its attestation proof. */
6275
- public_key: TeePublicKey;
6184
+ interface SandboxFleetDriverCapability {
6185
+ driverType: DriverType;
6186
+ sharedWorkspace: boolean;
6187
+ accelerators: boolean;
6188
+ queueTimings: boolean;
6276
6189
  }
6277
- /**
6278
- * Options for requesting fresh TEE attestation evidence.
6279
- */
6280
- interface TeeAttestationOptions {
6281
- /**
6282
- * Hex-encoded 32-64 byte caller nonce. When supported by the selected TEE
6283
- * backend, the runtime binds this to report data so the caller can reject
6284
- * replayed quotes.
6285
- */
6286
- attestationNonce?: string;
6190
+ interface SandboxFleetOperationsSummary {
6191
+ capacity: {
6192
+ fleets: number;
6193
+ machines: number;
6194
+ runningMachines: number;
6195
+ failedMachines: number;
6196
+ requestedCpu: number;
6197
+ requestedMemoryMb: number;
6198
+ requestedStorageMb: number;
6199
+ requestedAccelerators: number;
6200
+ };
6201
+ alerts: Array<{
6202
+ name: string;
6203
+ severity: "info" | "warn" | "critical";
6204
+ fleetId?: string;
6205
+ machineId?: string;
6206
+ message: string;
6207
+ runbook: string[];
6208
+ }>;
6287
6209
  }
6288
- /**
6289
- * Options for listing sandboxes.
6290
- */
6291
- interface ListSandboxOptions {
6292
- /** Filter by status */
6293
- status?: SandboxStatus | SandboxStatus[];
6294
- /** Filter personal/team visibility scope */
6295
- scope?: "personal" | "team" | "all" | `team:${string}`;
6296
- /** Maximum number of results */
6297
- limit?: number;
6298
- /** Offset for pagination */
6299
- offset?: number;
6300
- /** Only sandboxes created with this `metadata.run` (the caller's run id). */
6301
- run?: string;
6210
+ interface ReconcileSandboxFleetsOptions {
6211
+ dryRun?: boolean;
6302
6212
  }
6303
- /**
6304
- * One compute generation of a sandbox created for a caller run
6305
- * (`metadata.run`). Deleted sandboxes keep theirs.
6306
- */
6307
- interface SandboxRunGeneration {
6308
- sandboxId: string;
6309
- /** The sandbox's own compute generation id, not the caller run. */
6310
- generation: string;
6311
- generationSeq: number;
6312
- orgId: string;
6313
- state: string;
6314
- startedAt: number;
6315
- closedAt: number | null;
6316
- closedReason: string | null;
6213
+ interface ReconcileSandboxFleetsResult {
6214
+ dryRun: boolean;
6215
+ checked: number;
6216
+ orphaned: number;
6217
+ removed: number;
6218
+ machines: Array<{
6219
+ fleetId: string;
6220
+ machineId: string;
6221
+ sandboxId: string;
6222
+ removed: boolean;
6223
+ status?: number;
6224
+ error?: string;
6225
+ }>;
6317
6226
  }
6318
- //#endregion
6319
- //#region src/types/fleet.d.ts
6320
- /**
6321
- * Stable worker identifier inside a sandbox fleet.
6322
- *
6323
- * Machine IDs are intentionally narrower than sandbox names so agents
6324
- * can route work without smuggling shell metacharacters or path-like
6325
- * values through tool calls.
6326
- */
6327
- type FleetMachineId = string;
6328
- /** Stable id of one agent in a fleet. It is also the agent's session id on its sandbox. */
6329
- type FleetAgentId = string;
6330
- /**
6331
- * Where one agent runs. `shared` agents share a sandbox's filesystem, CPU and
6332
- * memory with other agents of the same fleet; `dedicated` gives the agent a
6333
- * sandbox of its own (repository writes, untrusted code).
6334
- */
6335
- type FleetAgentPlacement = "shared" | "dedicated";
6336
- /**
6337
- * A saved profile from the Platform agent-profile catalog
6338
- * (`GET /v1/agent-profiles/:id`). With `revision`, create refuses the fleet
6339
- * unless the catalog still holds exactly that revision.
6340
- */
6341
- interface SandboxFleetProfileRef {
6342
- profileId: string;
6343
- revision?: number;
6227
+ interface SandboxFleetUsage {
6228
+ usage: {
6229
+ fleetId: string;
6230
+ status: string;
6231
+ machineCount: number;
6232
+ coordinatorCount: number;
6233
+ workerCount: number;
6234
+ runningMachines: number;
6235
+ failedMachines: number;
6236
+ resources?: {
6237
+ machines: number;
6238
+ totalCpu: number;
6239
+ totalMemoryMb: number;
6240
+ totalStorageMb: number;
6241
+ totalAccelerators: number;
6242
+ maxLifetimeSeconds?: number;
6243
+ };
6244
+ meteredUsage?: {
6245
+ runtimeMs: number;
6246
+ machineRuntimeMs: Record<string, number>;
6247
+ updatedAt: string;
6248
+ };
6249
+ createdAt: string;
6250
+ updatedAt: string;
6251
+ };
6252
+ insights: {
6253
+ reliabilityScore: number;
6254
+ parallelismEfficiencyScore: number;
6255
+ failureRate: number;
6256
+ recommendedActions: string[];
6257
+ };
6258
+ trace: SandboxFleetTraceExport;
6259
+ intelligence: SandboxFleetIntelligenceEnvelope;
6344
6260
  }
6345
- interface SandboxFleetAgentSpec {
6346
- /** Defaults to `agent-<index>`. */
6347
- agentId?: FleetAgentId;
6348
- /** Defaults to `shared`. */
6349
- placement?: FleetAgentPlacement;
6350
- /** Harness this agent runs. Defaults to `profile.harness`, then `defaults.backend.type`. */
6351
- harness?: BackendType;
6352
- /**
6353
- * Model this agent runs: a model id, or a model config (`provider`,
6354
- * `baseUrl`, `apiKeyEnv` naming a sandbox env var that holds the key).
6355
- * Defaults to `profile.model.default`, then `defaults.backend.model`.
6356
- */
6357
- model?: string | NonNullable<BackendConfig["model"]>;
6358
- /**
6359
- * The agent's profile: an inline `AgentProfile`, or a saved profile by id.
6360
- * Every turn sends it as `backend.profile`, so the runtime materializes its
6361
- * skills, instructions, MCP servers and files into the agent's own harness
6362
- * session. Defaults to `defaults.backend.profile`.
6363
- */
6364
- profile?: AgentProfile | SandboxFleetProfileRef;
6365
- /** Runtime MCP bindings for this agent, separate from its profile. */
6366
- runtimeAttachments?: AgentRuntimeAttachments;
6367
- /** The agent's own task. `run()` sends it when called without a message. */
6368
- task?: string | PromptInputPart[];
6261
+ interface SandboxFleetTraceEvent {
6262
+ type: "fleet.lifecycle.snapshot" | "fleet.machine.lifecycle.snapshot" | "fleet.workspace.lifecycle.snapshot" | "fleet.usage.snapshot" | "fleet.dispatch.result" | "fleet.insight.summary";
6263
+ timestamp: string;
6264
+ fleetId: string;
6265
+ machineId?: string;
6266
+ durationMs?: number;
6267
+ attributes: Record<string, unknown>;
6369
6268
  }
6370
- /**
6371
- * How a fleet packs agents onto sandboxes.
6372
- *
6373
- * - `auto` (default): as many agents per sandbox as its memory holds, from
6374
- * the measured footprint of an idle sandbox and of one agent.
6375
- * - `dedicated`: one sandbox per agent.
6376
- * - `{ agentsPerSandbox }`: exactly that many shared agents per sandbox.
6377
- */
6378
- type SandboxFleetPlacement = "auto" | "dedicated" | {
6379
- agentsPerSandbox: number;
6380
- };
6381
- /** The fleet and agent that spawned a child fleet. */
6382
- interface SandboxFleetParent {
6269
+ interface SandboxFleetTraceExport {
6270
+ schemaVersion: "fleet.trace.v1";
6271
+ traceId: string;
6383
6272
  fleetId: string;
6384
- agentId: FleetAgentId;
6273
+ exportedAt: string;
6274
+ timings: {
6275
+ observedLifecycleMs: number;
6276
+ machineObservedLifecycleMs: number;
6277
+ dispatchFanoutMs: number;
6278
+ dispatchRuntimeMs: number;
6279
+ cleanupObservedMs: number;
6280
+ driverQueueMs: number;
6281
+ driverPlacementMs: number;
6282
+ driverProvisionMs: number;
6283
+ driverStartupMs: number;
6284
+ driverCleanupMs: number;
6285
+ };
6286
+ criticalPath: {
6287
+ durationMs: number;
6288
+ phases: Array<{
6289
+ name: string;
6290
+ durationMs: number;
6291
+ machineId?: string;
6292
+ }>;
6293
+ };
6294
+ events: SandboxFleetTraceEvent[];
6385
6295
  }
6386
- /** One agent of a fleet and the sandbox that hosts it. */
6387
- interface SandboxFleetAgent {
6388
- agentId: FleetAgentId;
6389
- machineId: FleetMachineId;
6390
- sandboxId: string;
6391
- /** Session the agent's turns run in; equal to `agentId`. */
6392
- sessionId: string;
6393
- /** Harness the agent runs; unset means the sandbox's default backend. */
6394
- harness?: BackendType;
6395
- /** Model the agent runs; unset means the sandbox's default model. */
6396
- model?: string;
6397
- /** Name of the agent's profile, when it has one. */
6398
- profileName?: string;
6296
+ interface SandboxFleetIntelligenceEnvelope {
6297
+ schemaVersion: "fleet.intelligence.v1";
6298
+ source: "sandbox-api";
6299
+ subject: {
6300
+ type: "sandbox_fleet";
6301
+ fleetId: string;
6302
+ };
6303
+ billing: {
6304
+ billable: false;
6305
+ billedTo: "platform";
6306
+ costUsd: 0;
6307
+ reason: "deterministic_platform_insight";
6308
+ };
6309
+ metrics: Record<string, number>;
6310
+ signals: Array<{
6311
+ name: string;
6312
+ value: string | number | boolean;
6313
+ severity: "info" | "warn" | "critical";
6314
+ rationale: string;
6315
+ }>;
6316
+ recommendedActions: string[];
6399
6317
  }
6400
- interface FleetRunOptions extends Pick<PromptOptions, "timeoutMs" | "context"> {
6401
- /** Agents to run. Defaults to every agent in the fleet. */
6402
- agents?: FleetAgentId[];
6403
- /** Aborts every agent turn this run started. */
6404
- signal?: AbortSignal;
6318
+ interface SandboxFleetTraceBundle {
6319
+ trace: SandboxFleetTraceExport;
6320
+ intelligence?: SandboxFleetIntelligenceEnvelope;
6405
6321
  }
6406
- type FleetAgentRunStatus = "completed" | "failed" | "cancelled" | "budget_exhausted";
6407
- interface FleetAgentResult extends SandboxFleetAgent {
6322
+ interface SandboxFleetTraceOptions {
6408
6323
  /**
6409
- * `budget_exhausted`: the Platform refused the turn's model or compute
6410
- * charge because the fleet's key budget is spent.
6324
+ * Include the platform-generated intelligence envelope. Defaults to false.
6325
+ * Set true when a customer wants generated insight with the raw trace export.
6411
6326
  */
6412
- status: FleetAgentRunStatus;
6413
- /** The agent's turn result: response text, token usage, trace id. */
6414
- result?: PromptResult;
6415
- /** Model cost the runtime reported for this turn, when it reported one. */
6416
- costUsd?: number;
6417
- durationMs: number;
6418
- error?: string;
6327
+ includeIntelligence?: boolean;
6419
6328
  }
6420
- type FleetRunEvent = ({
6421
- type: "agent.started";
6422
- traceId: string;
6423
- } & SandboxFleetAgent) | {
6424
- type: "agent.finished";
6425
- result: FleetAgentResult;
6426
- } | {
6427
- type: "fleet.finished";
6428
- results: FleetAgentResult[]; /** Metered spend when it could be read; the results never depend on it. */
6429
- spend?: SandboxFleetSpend;
6430
- spendError?: string;
6431
- durationMs: number;
6432
- };
6433
- /**
6434
- * Spend of a capped fleet, metered by the Platform on the fleet's budgeted
6435
- * key: every router call and compute charge of every sandbox the fleet
6436
- * created, whichever process or handle drove it. A child fleet's cap is
6437
- * reserved from its parent's budget when the child is created.
6438
- */
6439
- interface SandboxFleetSpend {
6440
- capUsd: number;
6441
- /** Charges the Platform has settled against the fleet's key. */
6442
- spentUsd: number;
6443
- /** Budget held for child fleets' caps. */
6444
- reservedForChildrenUsd: number;
6445
- /** What the fleet may still spend or allocate: cap minus spent minus reserved. */
6446
- remainingUsd: number;
6329
+ interface SandboxFleetCostEstimate {
6330
+ plan: "free" | "pro" | "enterprise";
6331
+ currency: "USD";
6332
+ hourlyUsd: number;
6333
+ maxLifetimeSeconds: number;
6334
+ estimatedMaxLifetimeUsd: number;
6335
+ requestedResources: {
6336
+ machines: number;
6337
+ totalCpu: number;
6338
+ totalMemoryMb: number;
6339
+ totalStorageMb: number;
6340
+ totalAccelerators: number;
6341
+ maxLifetimeSeconds?: number;
6342
+ };
6343
+ rates: {
6344
+ cpuPerHr: number;
6345
+ ramPerGbHr: number;
6346
+ diskPerGbHr: number;
6347
+ acceleratorPerDeviceHr: number;
6348
+ minChargePerHr: number;
6349
+ entDiscount: number;
6350
+ };
6447
6351
  }
6448
- type SandboxFleetMachineRole = "coordinator" | "worker";
6449
- /**
6450
- * Resource policy for a single fleet create call.
6451
- *
6452
- * These caps are enforced client-side before any sandbox is created.
6453
- * Server-side plan quotas still apply and remain the source of truth.
6454
- */
6455
- interface SandboxFleetPolicy {
6456
- /** Maximum number of machines in this create call. Defaults to machines.length. */
6457
- maxMachines?: number;
6458
- /** Maximum sandbox create fanout allowed for this fleet request. */
6459
- maxConcurrentCreates?: number;
6460
- /** Maximum total requested CPU cores across machines with explicit resources. */
6461
- maxTotalCpu?: number;
6462
- /** Maximum total requested memory across machines with explicit resources. */
6463
- maxTotalMemoryMb?: number;
6464
- /** Maximum total requested storage across machines with explicit resources. */
6465
- maxTotalStorageMb?: number;
6466
- /** Maximum total requested accelerator devices across machines. */
6467
- maxTotalAccelerators?: number;
6468
- /** Maximum lifetime in seconds for any machine in this fleet. */
6469
- maxLifetimeSeconds?: number;
6470
- /**
6471
- * The fleet's spend cap in USD, enforced by the Platform: the fleet's
6472
- * sandboxes are created with a key budgeted at the cap, so model and compute
6473
- * charges past it are refused for every process that drives the fleet. A
6474
- * child fleet's cap is reserved from its parent's remaining budget.
6475
- */
6476
- maxSpendUsd?: number;
6477
- /** Allowed infrastructure drivers for fleet machines. */
6478
- allowedDrivers?: DriverType[];
6479
- /** Allowed environments for fleet machines. */
6480
- allowedEnvironments?: string[];
6481
- /** Allowed personal or public template identifiers for fleet machines. */
6482
- allowedTemplateIds?: string[];
6483
- /** Whether machines may request accelerator devices. Defaults to allowed. */
6484
- allowAccelerators?: boolean;
6352
+ type SandboxFleetTokenAction = "list" | "create" | "delete" | "exec" | "prompt" | "read" | "write";
6353
+ interface CreateSandboxFleetTokenOptions {
6354
+ /** Allowed fleet actions. Defaults to read/list/exec. */
6355
+ actions?: SandboxFleetTokenAction[];
6356
+ /** Optional token-side policy caps enforced by the Sandbox API. */
6357
+ policy?: SandboxFleetPolicy;
6358
+ /** Token lifetime in minutes. API clamps to its server-side maximum. */
6359
+ ttlMinutes?: number;
6485
6360
  }
6486
- interface SandboxFleetWorkspace {
6487
- mode: "isolated" | "shared";
6488
- id?: string;
6489
- quotaMb?: number;
6490
- mountPath?: string;
6491
- snapshotId?: string;
6361
+ interface SandboxFleetToken {
6362
+ token: string;
6363
+ expiresAt: number;
6364
+ fleetId: string;
6365
+ actions: SandboxFleetTokenAction[];
6366
+ policy?: SandboxFleetPolicy;
6367
+ }
6368
+ interface ReapExpiredSandboxFleetsOptions {
6369
+ dryRun?: boolean;
6370
+ }
6371
+ interface ReapExpiredSandboxFleetsResult {
6372
+ dryRun: boolean;
6373
+ expired: number;
6374
+ deleted: number;
6375
+ fleets: Array<{
6376
+ fleetId: string;
6377
+ expiredAt: string;
6378
+ deleted: boolean;
6379
+ machines: Array<{
6380
+ machineId: string;
6381
+ sandboxId: string;
6382
+ ok: boolean;
6383
+ status?: number;
6384
+ error?: string;
6385
+ }>;
6386
+ }>;
6387
+ }
6388
+ /**
6389
+ * Options for listing fleet machines.
6390
+ */
6391
+ interface ListSandboxFleetOptions extends ListSandboxOptions {
6392
+ /** Fleet id to filter by. */
6393
+ fleetId: string;
6492
6394
  }
6395
+ //#endregion
6396
+ //#region src/types/sessions.d.ts
6493
6397
  /**
6494
- * Per-machine create spec for a sandbox fleet.
6398
+ * Lifecycle state of an agent session inside a sandbox.
6495
6399
  */
6496
- interface SandboxFleetMachineSpec extends Omit<CreateSandboxOptions, "metadata" | "name"> {
6497
- /** Stable agent-facing machine id, e.g. "coordinator" or "worker-1". */
6498
- machineId: FleetMachineId;
6499
- /** Optional display name. Defaults to `${fleetId}-${machineId}`. */
6500
- name?: string;
6501
- /** Machine-specific metadata. Fleet tags are added automatically. */
6502
- metadata?: Record<string, unknown>;
6503
- /** Optional orchestration role. Defaults to worker. */
6504
- role?: SandboxFleetMachineRole;
6505
- }
6400
+ type SessionStatus = "queued" | "running" | "completed" | "failed" | "cancelled";
6401
+ /** Lifecycle state of an execution retained in the session replay ledger. */
6402
+ type SessionExecutionStatus = "active" | "completed" | "failed" | "cancelled";
6506
6403
  /**
6507
- * Create a named set of sandboxes for one workload.
6404
+ * Durable metadata for one session execution.
6405
+ *
6406
+ * The values come from the runtime replay ledger, not from a provider
6407
+ * response or an inferred model result.
6508
6408
  */
6509
- interface CreateSandboxFleetOptions {
6510
- /** Stable fleet id. Generated when omitted. */
6511
- fleetId?: string;
6512
- /** Shared defaults applied to every machine before per-machine overrides. */
6513
- defaults?: Omit<CreateSandboxOptions, "metadata" | "name">;
6514
- /**
6515
- * Machines to create, for fleets driven by `dispatchExec`. Set either
6516
- * `machines` or `agents`.
6517
- */
6518
- machines?: SandboxFleetMachineSpec[];
6519
- /**
6520
- * Agents to run: a count, or specs with ids and per-agent placement. The
6521
- * fleet creates the sandboxes `placement` asks for, from `defaults`.
6522
- */
6523
- agents?: number | SandboxFleetAgentSpec[];
6524
- /** How agents are packed onto sandboxes. Defaults to `auto`. */
6525
- placement?: SandboxFleetPlacement;
6526
- /**
6527
- * A budget in USD the Platform enforces. The fleet mints a Platform key
6528
- * with this budget and creates its sandboxes and drives its turns with it,
6529
- * so every charge made through the fleet counts against the budget and a
6530
- * charge past it is refused. Only the client that created the fleet holds
6531
- * the key: other processes can read, cancel and delete the fleet but not
6532
- * run its agents. Without it, `policy.maxSpendUsd` stays a create-time
6533
- * estimate check. A turn driven on a fleet sandbox with another key is
6534
- * billed to that key, outside the budget.
6535
- */
6536
- budgetUsd?: number;
6537
- /**
6538
- * The fleet and agent spawning this fleet. The API checks that the parent
6539
- * exists and that this fleet's `policy.maxSpendUsd` fits in the parent's
6540
- * unallocated cap; deleting or cancelling the parent reaches this fleet.
6541
- */
6542
- parent?: SandboxFleetParent;
6543
- /** Fleet-level metadata copied to each sandbox under stable tags. */
6544
- metadata?: Record<string, unknown>;
6545
- /** Workspace policy for isolated or driver-supported shared mounts. */
6546
- workspace?: SandboxFleetWorkspace;
6547
- /**
6548
- * Client-side safety caps for this create call. These do not replace
6549
- * server-side quota enforcement.
6550
- */
6551
- policy?: SandboxFleetPolicy;
6552
- /**
6553
- * Delete already-created machines if a later machine fails to create.
6554
- * Defaults to true so partial fleets do not silently burn quota.
6555
- */
6556
- cleanupOnFailure?: boolean;
6557
- /**
6558
- * Sandbox creates in flight at once. Defaults to 8: every create and delete
6559
- * mints or revokes two Platform keys, and about 25 in flight has locked the
6560
- * Platform key store for every customer (2026-09-15).
6561
- */
6562
- maxConcurrentCreates?: number;
6563
- /**
6564
- * Idempotency key for the server-backed fleet record. Defaults to fleetId.
6565
- */
6566
- idempotencyKey?: string;
6409
+ interface SessionExecutionInfo {
6410
+ executionId: string;
6411
+ sessionId: string;
6412
+ status: SessionExecutionStatus;
6413
+ startedAt: number;
6414
+ completedAt?: number;
6415
+ eventCount: number;
6416
+ lastEventId: string;
6567
6417
  }
6568
- interface CreateSandboxFleetWithCoordinatorOptions extends Omit<CreateSandboxFleetOptions, "machines" | "agents" | "placement"> {
6569
- /** Coordinator machine. Defaults to machineId "coordinator". */
6570
- coordinator?: Omit<SandboxFleetMachineSpec, "machineId" | "role"> & {
6571
- machineId?: FleetMachineId;
6572
- };
6573
- /** Worker machines attached to the same fleet. */
6574
- workers: SandboxFleetMachineSpec[];
6418
+ /** Admission identity survives replay retention; unavailable never means completed. */
6419
+ interface SessionMessageAdmission {
6420
+ sessionId: string;
6421
+ turnId: string;
6422
+ executionId: string;
6423
+ status: SessionExecutionStatus | "unavailable";
6424
+ runControlRef?: AgentExactRunControlRef;
6575
6425
  }
6576
6426
  /**
6577
- * A sandbox with its fleet-local machine id.
6427
+ * Why a session reached `status: "failed"` — the runtime's verbatim cause,
6428
+ * not a bucketed label. A dispatched (detached) turn stops reading its SSE
6429
+ * stream the moment the sandbox admits the execution, so a spawn, profile
6430
+ * materialization or provider auth failure lands after the caller is gone;
6431
+ * this is how that caller learns what happened without replaying events.
6578
6432
  */
6579
- interface SandboxFleetMachine {
6580
- machineId: FleetMachineId;
6581
- sandbox: SandboxInfo;
6582
- role?: SandboxFleetMachineRole;
6433
+ interface SessionFailureReason {
6434
+ /** The runtime's error message, unmodified. */
6435
+ message: string;
6436
+ /** Machine-readable code when the runtime classified the failure. */
6437
+ code?: string;
6438
+ /** Native HTTP failure status when the provider reported it. */
6439
+ statusCode?: number;
6440
+ /** Execution whose failure this describes. */
6441
+ executionId?: string;
6583
6442
  }
6584
6443
  /**
6585
- * Fleet create/list result.
6444
+ * Snapshot of a session's state at the moment it was queried. Returned
6445
+ * by `box.session(id).status()` and `box.sessions()`.
6586
6446
  */
6587
- interface SandboxFleetInfo {
6588
- fleetId: string;
6589
- machines: SandboxFleetMachine[];
6590
- policy?: SandboxFleetPolicy;
6591
- parent?: SandboxFleetParent;
6592
- createdAt?: string;
6593
- /** Id of the budgeted Platform key a capped fleet's sandboxes charge. */
6594
- keyId?: string;
6447
+ interface SessionInfo {
6448
+ /** Stable session id assigned by the sandbox runtime. */
6449
+ id: string;
6450
+ /** Parent session id when this session was forked from another session. */
6451
+ parentId?: string;
6452
+ /** Current lifecycle state. */
6453
+ status: SessionStatus;
6454
+ /** Present when `status` is `"failed"` — the cause the runtime recorded. */
6455
+ failureReason?: SessionFailureReason;
6456
+ /** Execution currently running, when one is active. */
6457
+ activeExecutionId?: string;
6458
+ /** Most recent execution id, retained after completion for event replay. */
6459
+ latestExecutionId?: string;
6460
+ /** Exact identity of the latest admitted run, retained for canonical control. */
6461
+ runControlRef?: AgentExactRunControlRef;
6462
+ /** Backend identifier (e.g. provider name). */
6463
+ backend?: string;
6464
+ /** Provider/model selected after request normalization and environment fallback. */
6465
+ effectiveBackend?: EffectiveBackend;
6466
+ /** Model id the session was created with. */
6467
+ model?: string;
6468
+ /** Number of prompts the session has processed. */
6469
+ promptCount?: number;
6470
+ /** When the session was created in the sandbox. */
6471
+ createdAt?: Date;
6472
+ /** When the session began executing. */
6473
+ startedAt?: Date;
6474
+ /** When the session reached a terminal state. */
6475
+ endedAt?: Date;
6476
+ /** Raw payload from the sidecar — stable subset above; this carries
6477
+ * everything else for forward-compatibility. */
6478
+ raw?: Record<string, unknown>;
6595
6479
  }
6596
- interface FleetExecDispatchOptions extends Pick<ExecOptions, "cwd" | "env" | "timeoutMs"> {
6597
- machines?: FleetMachineId[];
6598
- /**
6599
- * Branches in flight at once. Defaults to every selected machine. The API
6600
- * runs on a Cloudflare Worker, which keeps at most six upstream connections
6601
- * open per request, so branches past six queue (measured 2026-09-25: twelve
6602
- * 8 s commands took 17.8 s, six took 9.7 s).
6603
- */
6604
- maxConcurrent?: number;
6605
- retry?: {
6606
- attempts?: number;
6607
- };
6608
- /** Caller-supplied dispatch id for idempotency/result lookup when supported by the API. */
6609
- dispatchId?: string;
6610
- /** Ask the API to retain branch results for later `dispatchResults` calls. */
6611
- bufferResults?: boolean;
6480
+ /**
6481
+ * Options for `box.sessions()` listing.
6482
+ */
6483
+ interface SessionListOptions {
6484
+ /** Filter by status. */
6485
+ status?: SessionStatus;
6486
+ /** Filter by backend identifier. */
6487
+ backend?: BackendType;
6612
6488
  }
6613
- interface FleetExecDispatchResult {
6614
- machineId: FleetMachineId;
6615
- sandboxId: string;
6616
- ok: boolean;
6617
- durationMs: number;
6618
- attempts?: number;
6619
- result?: ExecResult;
6620
- error?: {
6621
- message: string;
6622
- status?: number;
6623
- failureClass?: SandboxFleetDispatchFailureClass;
6624
- retryAfterMs?: number;
6625
- };
6489
+ /** Options for creating a runtime agent session. */
6490
+ interface CreateSessionOptions {
6491
+ /** Existing agent-owned direct child of the box volume's `workspaces` directory, independent of runtime cwd. */
6492
+ workspaceRoot?: string;
6493
+ /** Complete ordered visible transcript imported into a new isolated runtime session. */
6494
+ conversationHistory?: Array<{
6495
+ id: string;
6496
+ role: "user" | "assistant";
6497
+ parts: Array<{
6498
+ type: "text";
6499
+ text: string;
6500
+ }>;
6501
+ timestamp: string;
6502
+ }>;
6503
+ /** Import the complete native transcript from another OpenCode session in this box. */
6504
+ importFromSessionId?: string;
6505
+ /** Workspace conversations survive idle-session collection until explicitly deleted. */
6506
+ retention?: "idle" | "workspace";
6507
+ /** Stable caller-supplied idempotency key. Repeating create with the same
6508
+ * id returns the existing session without creating another workspace or
6509
+ * backend session. Omit to let the runtime mint a random id. */
6510
+ sessionId?: string;
6511
+ title?: string;
6512
+ parentId?: string;
6513
+ /** Optional backend override. An omitted or type-less config uses the
6514
+ * runtime's configured default backend. */
6515
+ backend?: BackendConfig;
6626
6516
  }
6627
- interface FleetPromptDispatchOptions extends Pick<PromptOptions, "sessionId" | "backend" | "model" | "timeoutMs" | "context"> {
6628
- machines?: FleetMachineId[];
6629
- maxConcurrent?: number;
6630
- retry?: {
6631
- attempts?: number;
6517
+ /** Backend credentials forwarded to the platform if a sandbox must restart. */
6518
+ interface SessionBackendCredentials {
6519
+ apiKey: string;
6520
+ baseUrl?: string;
6521
+ }
6522
+ /** One content part accepted by the runtime session message endpoint. */
6523
+ type SessionMessageInputPart = PromptInputPart | {
6524
+ type: "reasoning";
6525
+ text: string;
6526
+ } | {
6527
+ type: "tool";
6528
+ tool: string;
6529
+ state: {
6530
+ status: "pending" | "running" | "completed" | "failed";
6531
+ input?: unknown;
6532
+ output?: unknown;
6533
+ };
6534
+ } | {
6535
+ type: "step-start";
6536
+ } | {
6537
+ type: "step-finish";
6538
+ reason?: string;
6539
+ tokens?: {
6540
+ total?: number;
6541
+ input?: number;
6542
+ output?: number;
6543
+ reasoning?: number;
6544
+ cache?: {
6545
+ write?: number;
6546
+ read?: number;
6547
+ };
6632
6548
  };
6633
- /** Caller-supplied dispatch id for idempotency/result lookup when supported by the API. */
6634
- dispatchId?: string;
6635
- /** Ask the API to retain branch results for later `dispatchResults` calls. */
6636
- bufferResults?: boolean;
6637
- }
6638
- interface FleetPromptDispatchResult {
6639
- machineId: FleetMachineId;
6640
- sandboxId: string;
6641
- ok: boolean;
6642
- durationMs: number;
6643
- attempts?: number;
6644
- prompt?: PromptResult & {
6645
- metadata?: Record<string, unknown>;
6549
+ cost?: number;
6550
+ };
6551
+ /** Message body accepted by `SandboxSession.sendMessage`. */
6552
+ interface SendSessionMessageRequest {
6553
+ messageId?: string;
6554
+ /** Per-turn overrides within the session's native backend. */
6555
+ backend?: TurnBackendConfig;
6556
+ /** Caller pin for the exact public backend request before native dispatch. */
6557
+ expectedPublicProfileRequestDigest?: `sha256:${string}`;
6558
+ /** Provider-composed native revision prepared for this public turn. */
6559
+ expectedPublicProfileRevision?: {
6560
+ workspacePlanDigest: `sha256:${string}`;
6561
+ materializedDigest: `sha256:${string}`;
6562
+ launchDigest: string;
6646
6563
  };
6647
- error?: {
6648
- message: string;
6649
- status?: number;
6650
- failureClass?: SandboxFleetDispatchFailureClass;
6651
- retryAfterMs?: number;
6564
+ /** Executor-only opaque receipt for a secret-bearing native revision. */
6565
+ expectedSecretProfileReceipt?: `hmac-sha256:${string}`;
6566
+ /** Router quote for a warm OpenCode turn with a total output ceiling. */
6567
+ managedQuoteVersion?: string;
6568
+ /** Use the sandbox's managed model credential for this turn only. */
6569
+ managedModelCredential?: true;
6570
+ /** Exact caller-owned execution identity for canonical cancellation. */
6571
+ runControlRef?: AgentExactRunControlRef;
6572
+ /** Absolute UTC deadline for admitting the first native provider call. */
6573
+ admissionDeadline?: string;
6574
+ /** Execution time limit in milliseconds; a positive integer bounded by the runtime deployment ceiling. */
6575
+ ttlMs?: number;
6576
+ parts: SessionMessageInputPart[];
6577
+ system?: string;
6578
+ agent?: string;
6579
+ model?: {
6580
+ providerId: string;
6581
+ modelId: string;
6652
6582
  };
6653
- }
6654
- type SandboxFleetDispatchFailureClass = "oom" | "timeout" | "dependency" | "infra" | "model" | "user_code";
6655
- interface FleetDispatchStreamOptions {
6656
- signal?: AbortSignal;
6657
- }
6658
- interface FleetDispatchResultBufferOptions {
6659
- cursor?: string;
6660
- limit?: number;
6661
- machines?: FleetMachineId[];
6662
- }
6663
- interface FleetDispatchResultBuffer<T = FleetExecDispatchResult> {
6664
- fleetId: string;
6665
- dispatchId: string;
6666
- results: T[];
6667
- cursor?: string;
6668
- nextCursor?: string;
6669
- done?: boolean;
6670
- truncated?: boolean;
6671
- trace?: SandboxFleetTraceExport;
6672
- intelligence?: SandboxFleetIntelligenceEnvelope;
6673
- }
6674
- interface FleetDispatchCancelResult {
6675
- fleetId: string;
6676
- dispatchId: string;
6677
- cancelled: boolean;
6678
- status?: string;
6679
- }
6680
- interface SandboxFleetArtifactSpec {
6681
- machineId: FleetMachineId;
6583
+ reasoningEffort?: ReasoningEffort;
6584
+ turnId?: string;
6585
+ interactions?: BackendConfig["interactions"];
6586
+ /** Run this turn with every provider tool disabled (OpenCode). */
6587
+ disableTools?: true;
6682
6588
  /**
6683
- * Absolute path under /workspace. Fleet artifact collection intentionally
6684
- * rejects host/system paths so caller-provided manifests cannot turn artifact
6685
- * collection into arbitrary sandbox file reads.
6589
+ * Bound this turn to N upstream model calls (1-64). The runtime's model
6590
+ * proxy counts and enforces them; a turn it cannot count is refused. The
6591
+ * completed result reports `modelCalls`.
6686
6592
  */
6687
- path: string;
6688
- label?: string;
6689
- /** Maximum allowed artifact content size in bytes. Defaults to 10 MiB. */
6690
- maxBytes?: number;
6691
- }
6692
- interface SandboxFleetArtifact extends SandboxFleetArtifactSpec {
6693
- sandboxId: string;
6694
- content: string;
6593
+ maxModelCalls?: number;
6695
6594
  }
6696
- interface SandboxFleetDriverTimings {
6697
- queueMs?: number;
6698
- placementMs?: number;
6699
- provisionMs?: number;
6700
- startupMs?: number;
6701
- cleanupMs?: number;
6595
+ /** Per-call controls for `SandboxSession.sendMessage`. */
6596
+ interface SendSessionMessageOptions {
6597
+ /** Existing decision admission proof; used only for a caller-owned prepared follow-up. */
6598
+ planFollowUp?: DurablePlanFollowUpResume;
6599
+ credentials?: SessionBackendCredentials;
6600
+ timeoutMs?: number;
6601
+ signal?: AbortSignal;
6602
+ /** Trace id sent as `x-tangle-trace-id`; see `PromptOptions.traceId`. */
6603
+ traceId?: string;
6702
6604
  }
6703
- interface SandboxFleetMachineMeteredUsage {
6704
- runtimeMs: number;
6705
- updatedAt: string;
6605
+ /** Receipt returned after a session message is accepted for processing. */
6606
+ interface SentSessionMessage {
6607
+ info: {
6608
+ id: string;
6609
+ role: "assistant";
6610
+ timestamp: string;
6611
+ };
6612
+ parts: [];
6613
+ userMessageId: string;
6614
+ processing: true;
6615
+ runControlRef?: AgentExactRunControlRef;
6706
6616
  }
6707
- interface AttachSandboxFleetMachineOptions {
6708
- machineId: FleetMachineId;
6709
- sandboxId: string;
6710
- status?: string;
6711
- role?: SandboxFleetMachineRole;
6712
- driverType?: DriverType;
6713
- environment?: string;
6714
- templateId?: string;
6715
- publicTemplateId?: string;
6716
- acceleratorCount?: number;
6717
- driverTimings?: SandboxFleetDriverTimings;
6617
+ /** Canonical portable profile attached to a task session. */
6618
+ type TaskSessionProfile = AgentProfile & {
6619
+ name: string;
6620
+ };
6621
+ /** Options for creating an isolated background task session. */
6622
+ interface CreateTaskSessionOptions {
6623
+ sessionId: string;
6624
+ backend: BackendConfig;
6625
+ title: string;
6626
+ profile?: TaskSessionProfile;
6627
+ parentSessionId?: string;
6628
+ isolateFileWrites?: boolean;
6718
6629
  }
6719
- interface SandboxFleetMachineRecord extends AttachSandboxFleetMachineOptions {
6720
- workspaceMountPath?: string;
6721
- meteredUsage?: SandboxFleetMachineMeteredUsage;
6722
- createdAt?: string;
6723
- updatedAt?: string;
6630
+ /** Task-session metadata returned at creation time. */
6631
+ interface TaskSessionInfo {
6632
+ id: string;
6633
+ title?: string;
6634
+ parentSessionId?: string;
6635
+ worktreeInfo?: {
6636
+ worktreePath: string;
6637
+ branchName: string;
6638
+ baseCommitSha: string;
6639
+ };
6640
+ profile?: TaskSessionProfile;
6724
6641
  }
6725
- interface SandboxFleetManifestMachine {
6726
- machineId: FleetMachineId;
6727
- sandboxId: string;
6728
- role?: SandboxFleetMachineRole;
6729
- status?: string;
6730
- driverType?: DriverType;
6731
- environment?: string;
6732
- templateId?: string;
6733
- publicTemplateId?: string;
6734
- acceleratorCount?: number;
6735
- workspaceMountPath?: string;
6736
- driverTimings?: SandboxFleetDriverTimings;
6737
- meteredUsage?: SandboxFleetMachineMeteredUsage;
6738
- createdAt?: string;
6739
- updatedAt?: string;
6642
+ /** One changed file in an isolated task session. */
6643
+ interface TaskSessionFileChange {
6644
+ file: string;
6645
+ operation: "added" | "modified" | "deleted";
6646
+ additions: number;
6647
+ deletions: number;
6740
6648
  }
6741
- interface SandboxFleetManifest {
6742
- fleetId?: string;
6743
- id?: string;
6744
- metadata?: Record<string, unknown>;
6745
- policy?: SandboxFleetPolicy;
6746
- resources?: Record<string, unknown>;
6747
- workspace?: SandboxFleetWorkspace & {
6748
- status?: string;
6749
- createdAt?: string;
6750
- updatedAt?: string;
6751
- deletedAt?: string;
6649
+ /** Current diff and commit history for an isolated task session. */
6650
+ interface TaskSessionChanges {
6651
+ sessionId: string;
6652
+ files: TaskSessionFileChange[];
6653
+ diff: string;
6654
+ commits: Array<{
6655
+ sha: string;
6656
+ message: string;
6657
+ date: string;
6658
+ }>;
6659
+ worktreeInfo: {
6660
+ worktreePath: string;
6661
+ branchName: string;
6662
+ baseCommitSha: string;
6663
+ headCommitSha?: string;
6752
6664
  };
6753
- machines: SandboxFleetManifestMachine[];
6754
- createdAt?: string;
6755
- updatedAt?: string;
6756
- }
6757
- interface SandboxFleetDispatchResponse<T = FleetExecDispatchResult> {
6758
- fleetId: string;
6759
- dispatchId: string;
6760
- type: "exec" | "prompt";
6761
- results: T[];
6762
- durationMs: number;
6763
- trace?: SandboxFleetTraceExport;
6764
- intelligence?: SandboxFleetIntelligenceEnvelope;
6765
6665
  }
6766
- interface SandboxFleetWorkspaceSnapshotResult {
6767
- snapshotId?: string;
6768
- id?: string;
6769
- status?: string;
6770
- createdAt?: string;
6771
- [key: string]: JsonValue | undefined;
6666
+ /** Options for merging task-session changes into the main workspace. */
6667
+ interface CommitTaskSessionOptions {
6668
+ message?: string;
6669
+ files?: string[];
6772
6670
  }
6773
- interface SandboxFleetWorkspaceRestoreResult {
6774
- restored?: boolean;
6775
- snapshotId?: string;
6776
- status?: string;
6777
- [key: string]: JsonValue | undefined;
6671
+ /** Result of merging task-session changes into the main workspace. */
6672
+ interface TaskSessionCommitResult {
6673
+ success: true;
6674
+ commitSha?: string;
6675
+ conflicts?: string[];
6676
+ appliedFiles: number;
6778
6677
  }
6779
- interface SandboxFleetWorkspaceReconcileResult {
6780
- fleetId: string;
6781
- workspaceId?: string;
6782
- checked: number;
6783
- orphanedMounts: number;
6784
- machines: Array<{
6785
- machineId: string;
6786
- sandboxId: string;
6787
- mounted: boolean;
6788
- }>;
6678
+ /**
6679
+ * Options for `SandboxSession.events()` streaming.
6680
+ */
6681
+ interface SessionEventStreamOptions {
6682
+ /** Replay strictly after this event id. Omit to start at the live tail. */
6683
+ since?: string;
6684
+ /** Restrict replay to one execution within the session. Required with
6685
+ * `since` when attaching after a server-dispatched turn has already begun. */
6686
+ executionId?: string;
6687
+ /** Cancel the stream by aborting this signal. */
6688
+ signal?: AbortSignal;
6789
6689
  }
6790
- interface SandboxFleetDriverCapability {
6791
- driverType: DriverType;
6792
- sharedWorkspace: boolean;
6793
- accelerators: boolean;
6794
- queueTimings: boolean;
6690
+ /** Select one exact execution when awaiting a session result. */
6691
+ interface SessionResultOptions {
6692
+ /**
6693
+ * Runtime execution to replay and aggregate.
6694
+ *
6695
+ * When omitted, `result()` retains its existing behavior and selects the
6696
+ * session's latest execution at call time.
6697
+ */
6698
+ executionId?: string;
6795
6699
  }
6796
- interface SandboxFleetOperationsSummary {
6797
- capacity: {
6798
- fleets: number;
6799
- machines: number;
6800
- runningMachines: number;
6801
- failedMachines: number;
6802
- requestedCpu: number;
6803
- requestedMemoryMb: number;
6804
- requestedStorageMb: number;
6805
- requestedAccelerators: number;
6806
- };
6807
- alerts: Array<{
6808
- name: string;
6809
- severity: "info" | "warn" | "critical";
6810
- fleetId?: string;
6811
- machineId?: string;
6812
- message: string;
6813
- runbook: string[];
6814
- }>;
6700
+ /** Select one exact execution when interrupting a session. */
6701
+ interface SessionInterruptOptions {
6702
+ /**
6703
+ * Runtime execution to cancel.
6704
+ *
6705
+ * When supplied, a newer execution on the same session is never cancelled.
6706
+ * When omitted, `interrupt()` selects the current execution.
6707
+ */
6708
+ executionId?: string;
6815
6709
  }
6816
- interface ReconcileSandboxFleetsOptions {
6817
- dryRun?: boolean;
6710
+ /**
6711
+ * Options for `box.dispatchPrompt()` — fire-and-detach prompt semantics.
6712
+ */
6713
+ interface DispatchPromptOptions extends PromptOptions {
6714
+ /** Client-supplied session id. Re-dispatching with the same id while
6715
+ * that session is in flight is a lookup, not a second run — a
6716
+ * concurrency guard, not a retry key. Once the turn finishes (or if the
6717
+ * session was evicted) the same call dispatches again; pass `turnId` for
6718
+ * retry safety that outlives the turn. */
6719
+ sessionId?: string;
6818
6720
  }
6819
- interface ReconcileSandboxFleetsResult {
6820
- dryRun: boolean;
6821
- checked: number;
6822
- orphaned: number;
6823
- removed: number;
6824
- machines: Array<{
6825
- fleetId: string;
6826
- machineId: string;
6827
- sandboxId: string;
6828
- removed: boolean;
6829
- status?: number;
6830
- error?: string;
6831
- }>;
6721
+ /**
6722
+ * Options for `box.messages()` — list messages on a session including
6723
+ * mid-turn partial assistant content.
6724
+ */
6725
+ interface ListMessagesOptions {
6726
+ /** Session id whose messages to return (required). */
6727
+ sessionId: string;
6728
+ /** Max entries, default 100. Server caps at 1000. */
6729
+ limit?: number;
6730
+ /** Skip this many entries from the start. */
6731
+ offset?: number;
6732
+ /** Only return messages newer than this Unix-ms timestamp. */
6733
+ since?: number;
6832
6734
  }
6833
- interface SandboxFleetUsage {
6834
- usage: {
6835
- fleetId: string;
6836
- status: string;
6837
- machineCount: number;
6838
- coordinatorCount: number;
6839
- workerCount: number;
6840
- runningMachines: number;
6841
- failedMachines: number;
6842
- resources?: {
6843
- machines: number;
6844
- totalCpu: number;
6845
- totalMemoryMb: number;
6846
- totalStorageMb: number;
6847
- totalAccelerators: number;
6848
- maxLifetimeSeconds?: number;
6849
- };
6850
- meteredUsage?: {
6851
- runtimeMs: number;
6852
- machineRuntimeMs: Record<string, number>;
6853
- updatedAt: string;
6854
- };
6855
- createdAt: string;
6856
- updatedAt: string;
6857
- };
6858
- insights: {
6859
- reliabilityScore: number;
6860
- parallelismEfficiencyScore: number;
6861
- failureRate: number;
6862
- recommendedActions: string[];
6735
+ /**
6736
+ * Options for `box.session(id).fork()` — create a new session from an
6737
+ * existing conversation, optionally at a message boundary.
6738
+ */
6739
+ interface SessionForkOptions {
6740
+ /** Fork at this message boundary. */
6741
+ messageId?: string;
6742
+ /** Target backend type for cross-backend forks. Defaults to parent backend. */
6743
+ targetBackend?: BackendType;
6744
+ /** Model override for the target backend. */
6745
+ targetModel?: {
6746
+ provider?: string;
6747
+ model?: string;
6748
+ apiKey?: string;
6749
+ baseUrl?: string;
6863
6750
  };
6864
- trace: SandboxFleetTraceExport;
6865
- intelligence: SandboxFleetIntelligenceEnvelope;
6751
+ /**
6752
+ * Files to include. The runtime currently rejects non-empty file lists;
6753
+ * exposed here so the SDK type tracks the wire contract exactly.
6754
+ */
6755
+ files?: string[];
6866
6756
  }
6867
- interface SandboxFleetTraceEvent {
6868
- type: "fleet.lifecycle.snapshot" | "fleet.machine.lifecycle.snapshot" | "fleet.workspace.lifecycle.snapshot" | "fleet.usage.snapshot" | "fleet.dispatch.result" | "fleet.insight.summary";
6757
+ /**
6758
+ * One message on a session — user, assistant, or system. The metadata
6759
+ * field carries the durability marker set by the sidecar:
6760
+ * - `status: "streaming"` and no `completed`/`interrupted` flag → turn
6761
+ * is in flight, OR the sidecar died before stamping a marker
6762
+ * (SIGKILL, OOM). The partial parts are the partial assistant
6763
+ * content the recorder flushed before death.
6764
+ * - `completed: true` + `completedAt` → turn finished normally. If a
6765
+ * `turnId` was supplied, its result is cached for idempotent retry.
6766
+ * - `interrupted: true` + `interruptedAt` + `interruptReason` → graceful
6767
+ * abort, timeout, or upstream error. Partial content is preserved
6768
+ * but not billable as a completion.
6769
+ */
6770
+ interface SessionMessage {
6771
+ id: string;
6772
+ role: "user" | "assistant" | "system";
6773
+ /** ISO timestamp string. */
6869
6774
  timestamp: string;
6870
- fleetId: string;
6871
- machineId?: string;
6872
- durationMs?: number;
6873
- attributes: Record<string, unknown>;
6874
- }
6875
- interface SandboxFleetTraceExport {
6876
- schemaVersion: "fleet.trace.v1";
6877
- traceId: string;
6878
- fleetId: string;
6879
- exportedAt: string;
6880
- timings: {
6881
- observedLifecycleMs: number;
6882
- machineObservedLifecycleMs: number;
6883
- dispatchFanoutMs: number;
6884
- dispatchRuntimeMs: number;
6885
- cleanupObservedMs: number;
6886
- driverQueueMs: number;
6887
- driverPlacementMs: number;
6888
- driverProvisionMs: number;
6889
- driverStartupMs: number;
6890
- driverCleanupMs: number;
6891
- };
6892
- criticalPath: {
6893
- durationMs: number;
6894
- phases: Array<{
6895
- name: string;
6896
- durationMs: number;
6897
- machineId?: string;
6898
- }>;
6775
+ /** Message parts (text, tool calls, reasoning, files). Same shape as
6776
+ * events emitted by `streamPrompt`. */
6777
+ parts: unknown[];
6778
+ /** Durability + idempotency metadata. See class doc above. */
6779
+ metadata?: {
6780
+ status?: "streaming" | "completed" | "interrupted";
6781
+ completed?: boolean;
6782
+ completedAt?: string;
6783
+ interrupted?: boolean;
6784
+ interruptedAt?: string;
6785
+ interruptReason?: string;
6786
+ turnId?: string;
6787
+ startedAt?: string;
6788
+ [extra: string]: unknown;
6899
6789
  };
6900
- events: SandboxFleetTraceEvent[];
6901
6790
  }
6902
- interface SandboxFleetIntelligenceEnvelope {
6903
- schemaVersion: "fleet.intelligence.v1";
6904
- source: "sandbox-api";
6905
- subject: {
6906
- type: "sandbox_fleet";
6907
- fleetId: string;
6908
- };
6909
- billing: {
6910
- billable: false;
6911
- billedTo: "platform";
6912
- costUsd: 0;
6913
- reason: "deterministic_platform_insight";
6791
+ /**
6792
+ * Returned by `box.findCompletedTurn()` — the cached result of a
6793
+ * previously-completed turn, keyed on the caller's `turnId`.
6794
+ */
6795
+ interface CompletedTurnResult {
6796
+ turnId: string;
6797
+ sessionId: string;
6798
+ /** ISO timestamp when the turn finished. */
6799
+ completedAt: string;
6800
+ /** The cached AgentExecutionResult-shape payload (text, toolInvocations,
6801
+ * sessionId, tokenUsage, etc.). */
6802
+ result: CompletedTurnPayload;
6803
+ }
6804
+ /**
6805
+ * The cached result of a completed turn. `effectiveBackend` is the provider
6806
+ * and model that served the turn, the same field the live `result` and `done`
6807
+ * events carry. It is absent when the runtime did not record it, for example
6808
+ * on a record written before the runtime stored attribution: treat that as
6809
+ * unknown, never as the session's default model.
6810
+ */
6811
+ type CompletedTurnPayload = Record<string, unknown> & {
6812
+ effectiveBackend?: EffectiveBackend;
6813
+ };
6814
+ /**
6815
+ * Returned by `box.dispatchPrompt()` — minimum the caller needs to track
6816
+ * the session afterward. The sandbox keeps running the prompt; use
6817
+ * `box.session(sessionId)` to follow it.
6818
+ */
6819
+ interface DispatchedSession {
6820
+ /** Session id (either the one the caller supplied or one the sandbox
6821
+ * minted). */
6822
+ sessionId: string;
6823
+ /** Runtime execution id when the admission event supplied one. */
6824
+ executionId?: string;
6825
+ /** Exact run identity accepted by the runtime for canonical cancellation. */
6826
+ runControlRef?: AgentExactRunControlRef;
6827
+ /** Lifecycle state at the moment dispatch returned. */
6828
+ status: SessionStatus;
6829
+ /** True when a session with the supplied id already existed. On its own
6830
+ * this says nothing about whether the prompt ran — an existing terminal
6831
+ * session still accepts a new turn. Read `dispatched` for that. */
6832
+ alreadyExisted: boolean;
6833
+ /** Whether this call actually dispatched the prompt. `false` means the
6834
+ * call was a no-op because the turn is already in flight (session
6835
+ * `queued`/`running`) or already finished (`turnId` hit the completed-
6836
+ * turn cache) — the prompt was deliberately not sent, and no new events
6837
+ * will appear on the session bus for it. */
6838
+ dispatched: boolean;
6839
+ }
6840
+ /**
6841
+ * Options for `box.driveTurn()` — one settle/poll/admit pass over a detached
6842
+ * turn. The first pass creates a session with the requested backend and admits
6843
+ * the turn through `SandboxSession.sendMessage()`. The session owns execution
6844
+ * and gateway replay after the request returns.
6845
+ */
6846
+ /** Repeated messages in one native session, unlike the one-session-per-task driver. */
6847
+ interface ConversationTurnOptions {
6848
+ sessionId: string;
6849
+ turnId: string;
6850
+ /** Router quote included in the durable admission request. */
6851
+ managedQuoteVersion?: string;
6852
+ /** Use the sandbox's managed model credential for this turn only. */
6853
+ managedModelCredential?: true;
6854
+ /** Per-turn backend, profile, runtime attachments, and interaction settings. */
6855
+ backend?: Partial<BackendConfig>;
6856
+ /** Caller pin for the exact public backend request before native dispatch. */
6857
+ expectedPublicProfileRequestDigest?: `sha256:${string}`;
6858
+ /** Provider-composed native revision prepared for this public turn. */
6859
+ expectedPublicProfileRevision?: {
6860
+ workspacePlanDigest: `sha256:${string}`;
6861
+ materializedDigest: `sha256:${string}`;
6862
+ launchDigest: string;
6914
6863
  };
6915
- metrics: Record<string, number>;
6916
- signals: Array<{
6917
- name: string;
6918
- value: string | number | boolean;
6919
- severity: "info" | "warn" | "critical";
6920
- rationale: string;
6921
- }>;
6922
- recommendedActions: string[];
6923
- }
6924
- interface SandboxFleetTraceBundle {
6925
- trace: SandboxFleetTraceExport;
6926
- intelligence?: SandboxFleetIntelligenceEnvelope;
6927
- }
6928
- interface SandboxFleetTraceOptions {
6864
+ /** Executor-only opaque receipt for a secret-bearing native revision. */
6865
+ expectedSecretProfileReceipt?: `hmac-sha256:${string}`;
6866
+ /** Model shorthand; conflicts with backend.model.model are rejected. */
6867
+ model?: string;
6868
+ /** Exact execution identity retained by admission and cancellation. */
6869
+ runControlRef?: AgentExactRunControlRef;
6870
+ /** Absolute UTC deadline for admitting the first native provider call. */
6871
+ admissionDeadline?: string;
6872
+ /** False is a passive settlement/cancellation lookup; never admits new work. */
6873
+ allowDispatch?: boolean;
6874
+ /** Run this turn with every provider tool disabled (OpenCode). */
6875
+ disableTools?: true;
6929
6876
  /**
6930
- * Include the platform-generated intelligence envelope. Defaults to false.
6931
- * Set true when a customer wants generated insight with the raw trace export.
6877
+ * Bound this turn to N upstream model calls (1-64). The runtime's model
6878
+ * proxy counts and enforces them; a turn it cannot count is refused. The
6879
+ * completed result reports `modelCalls`.
6932
6880
  */
6933
- includeIntelligence?: boolean;
6934
- }
6935
- interface SandboxFleetCostEstimate {
6936
- plan: "free" | "pro" | "enterprise";
6937
- currency: "USD";
6938
- hourlyUsd: number;
6939
- maxLifetimeSeconds: number;
6940
- estimatedMaxLifetimeUsd: number;
6941
- requestedResources: {
6942
- machines: number;
6943
- totalCpu: number;
6944
- totalMemoryMb: number;
6945
- totalStorageMb: number;
6946
- totalAccelerators: number;
6947
- maxLifetimeSeconds?: number;
6948
- };
6949
- rates: {
6950
- cpuPerHr: number;
6951
- ramPerGbHr: number;
6952
- diskPerGbHr: number;
6953
- acceleratorPerDeviceHr: number;
6954
- minChargePerHr: number;
6955
- entDiscount: number;
6956
- };
6957
- }
6958
- type SandboxFleetTokenAction = "list" | "create" | "delete" | "exec" | "prompt" | "read" | "write";
6959
- interface CreateSandboxFleetTokenOptions {
6960
- /** Allowed fleet actions. Defaults to read/list/exec. */
6961
- actions?: SandboxFleetTokenAction[];
6962
- /** Optional token-side policy caps enforced by the Sandbox API. */
6963
- policy?: SandboxFleetPolicy;
6964
- /** Token lifetime in minutes. API clamps to its server-side maximum. */
6965
- ttlMinutes?: number;
6966
- }
6967
- interface SandboxFleetToken {
6968
- token: string;
6969
- expiresAt: number;
6970
- fleetId: string;
6971
- actions: SandboxFleetTokenAction[];
6972
- policy?: SandboxFleetPolicy;
6881
+ maxModelCalls?: number;
6882
+ timeoutMs?: number;
6883
+ signal?: AbortSignal;
6884
+ wallCapMs?: number;
6885
+ /**
6886
+ * Trace id sent as `x-tangle-trace-id` on this pass's runtime requests.
6887
+ * Defaults to `turnId` when it is 8-200 letters, digits, `_` or `-`, so
6888
+ * every pass over one turn shares one trace; otherwise the SDK mints one.
6889
+ */
6890
+ traceId?: string;
6973
6891
  }
6974
- interface ReapExpiredSandboxFleetsOptions {
6975
- dryRun?: boolean;
6892
+ type ConversationTurnResult = ((TurnDriveResult & {
6893
+ executionId?: string;
6894
+ }) | {
6895
+ state: "not_admitted";
6896
+ } | {
6897
+ state: "awaiting_input";
6898
+ executionId: string;
6899
+ requests: _$_tangle_network_agent_interface0.InteractionRequest[];
6900
+ }) & {
6901
+ /** Trace id this pass sent as `x-tangle-trace-id`. */traceId?: string;
6902
+ };
6903
+ interface DriveTurnOptions {
6904
+ /** Deterministic session id — required, it is the resume key. Every
6905
+ * tick for the same logical turn MUST pass the same id so a re-invoke
6906
+ * after a crash finds the in-flight session instead of starting a
6907
+ * second agent run. */
6908
+ sessionId: string;
6909
+ /** Turn idempotency key for the platform's completed-turn cache.
6910
+ * Defaults to `sessionId`, which is correct for the one-turn-per-
6911
+ * session shape detached drivers use. */
6912
+ turnId?: string;
6913
+ /** Backend bound to the session when the first pass creates it. */
6914
+ backend?: Partial<BackendConfig>;
6915
+ /** Model shorthand folded into `backend.model.model` at session creation. */
6916
+ model?: string;
6917
+ /** Admission request timeout in milliseconds. */
6918
+ timeoutMs?: number;
6919
+ /** Abort the admission request before the sandbox accepts it. */
6920
+ signal?: AbortSignal;
6921
+ /** Wall-clock cap in milliseconds, measured from the session's
6922
+ * `startedAt` (falling back to `createdAt`). When a still-running
6923
+ * session exceeds it, `driveTurn` cancels the session and reports
6924
+ * `state: "failed"` — bounding unattended runs that would otherwise
6925
+ * stall forever (e.g. an interactive question nothing will answer).
6926
+ * Omit for no cap. */
6927
+ wallCapMs?: number;
6976
6928
  }
6977
- interface ReapExpiredSandboxFleetsResult {
6978
- dryRun: boolean;
6979
- expired: number;
6980
- deleted: number;
6981
- fleets: Array<{
6982
- fleetId: string;
6983
- expiredAt: string;
6984
- deleted: boolean;
6985
- machines: Array<{
6986
- machineId: string;
6987
- sandboxId: string;
6988
- ok: boolean;
6989
- status?: number;
6990
- error?: string;
6991
- }>;
6992
- }>;
6929
+ /** Public side copy paths relative to the immutable profile revision workspace. */
6930
+ interface PublicProfileConflict {
6931
+ relPath: string;
6932
+ copyRelPath: string;
6933
+ reason: "existing" | "symlink";
6993
6934
  }
6994
6935
  /**
6995
- * Options for listing fleet machines.
6936
+ * Returned by `box.driveTurn()` — where the detached turn stands after
6937
+ * one pass. Discriminated on `state`:
6938
+ * - `completed` — the turn finished with a text payload; `result` is
6939
+ * the full cached AgentExecutionResult-shape record.
6940
+ * - Waiting states preserve the response request and original result.
6941
+ * - `running` — the session is queued or executing; re-invoke after a
6942
+ * delay of your choosing.
6943
+ * - `failed` — terminal and deterministic: a failed/cancelled session,
6944
+ * a wall-cap cancellation, or an invalid terminal result.
6945
+ * Re-invoking will not change the outcome.
6996
6946
  */
6997
- interface ListSandboxFleetOptions extends ListSandboxOptions {
6998
- /** Fleet id to filter by. */
6999
- fleetId: string;
7000
- }
6947
+ type TurnDriveResult = {
6948
+ state: "completed"; /** Final assistant text of the turn. */
6949
+ text: string; /** The full turn payload (text, toolInvocations, tokenUsage, etc.). */
6950
+ result: Record<string, unknown>; /** Executor-observed public native profile revision for this turn. */
6951
+ publicProfileRevision?: {
6952
+ workspacePlanDigest: string;
6953
+ materializedDigest: string;
6954
+ launchDigest: string; /** Absent for a result written before collision receipts existed. */
6955
+ conflicts?: PublicProfileConflict[];
6956
+ };
6957
+ /**
6958
+ * Token usage the turn reported, when the payload carried it. Typed
6959
+ * access to the counts otherwise buried untyped inside `result`.
6960
+ */
6961
+ usage?: TokenUsage;
6962
+ /**
6963
+ * A bounded turn's upstream model calls as the runtime's model proxy
6964
+ * relayed them (`maxModelCalls`), never the harness's own report.
6965
+ */
6966
+ modelCalls?: {
6967
+ limit: number;
6968
+ count: number;
6969
+ /**
6970
+ * The model each counted call's upstream response named, in call order;
6971
+ * shorter than `count` when a response named none. The requested model
6972
+ * is `effectiveBackend.model`, a separate value.
6973
+ */
6974
+ observedModels?: string[];
6975
+ };
6976
+ } | {
6977
+ state: "awaiting_plan_decision";
6978
+ plan: DurablePlanSnapshot;
6979
+ result: Record<string, unknown>;
6980
+ } | {
6981
+ state: "blocked_on_approval";
6982
+ approval: AgentApprovalRequirement;
6983
+ result: Record<string, unknown>;
6984
+ } | {
6985
+ state: "awaiting_question";
6986
+ question: AgentQuestionRequest;
6987
+ interaction?: _$_tangle_network_agent_interface0.InteractionRequest;
6988
+ result: Record<string, unknown>;
6989
+ } | {
6990
+ state: "awaiting_interaction";
6991
+ interaction: _$_tangle_network_agent_interface0.InteractionRequest;
6992
+ result: Record<string, unknown>;
6993
+ } | {
6994
+ state: "running"; /** When the session began executing, if the runtime reported it. */
6995
+ startedAt?: Date; /** Milliseconds since `startedAt` at the moment of the poll. */
6996
+ elapsedMs?: number;
6997
+ } | {
6998
+ state: "failed"; /** Human-readable reason the turn is deterministically failed. */
6999
+ error: string;
7000
+ };
7001
7001
  //#endregion
7002
7002
  //#region src/types/fleet-turns.d.ts
7003
7003
  /**
@@ -8234,4 +8234,4 @@ interface InstalledTool {
8234
8234
  active: boolean;
8235
8235
  }
8236
8236
  //#endregion
8237
- export { BackendManager as $, BackendInfo as $a, IntelligenceReportCompareTo as $i, NetworkConfig as $n, GpuLeaseManager as $r, SandboxFleetOperationsSummary as $t, ProvisionStatus as A, SentSessionMessage as Aa, RolloutStartResult as Ai, StartupDiagnostics as An, parseBackendType as Ao, WriteManyOptions as Ar, FleetRunOptions as At, Process as B, SessionMessage as Ba, AgentApprovalRequirement as Bi, SandboxResources as Bn, AcceleratorKind as Br, SandboxFleetCostEstimate as Bt, StopOptions as C, EffectiveBackend as Ca, ForkCounts as Ci, SandboxRuntimeHealth as Cn, BatchBackendStats as Co, ListOptions as Cr, FleetDispatchStreamOptions as Ct, SshKeysManager as D, PublicProfileConflict as Da, RolloutChildResult as Di, SandboxTerminalManager as Dn, BatchTaskUsage as Do, UploadProgress as Dr, FleetPromptDispatchOptions as Dt, SecretsManager as E, ListMessagesOptions as Ea, Rollout as Ei, SandboxTerminalInfo as En, BatchSidecarGroup as Eo, UploadOptions as Er, FleetMachineId as Et, UsageInfo as F, SessionFailureReason as Fa, BatchResult as Fi, TeePublicKey as Fn, PublicTemplateInfo as Fr, ReconcileSandboxFleetsResult as Ft, ProcessSignal as G, TaskSessionChanges as Ga, DurablePlan as Gi, SecretBinding as Gn, DriverInfo as Gr, SandboxFleetInfo as Gt, ProcessListOptions as H, SessionMessageInputPart as Ha, AgentRunStatus as Hi, SandboxShapePreset as Hn, CreateGpuLeaseOptions as Hr, SandboxFleetDispatchResponse as Ht, WaitForOptions as I, SessionForkOptions as Ia, BatchRunOptions as Ii, TeePublicKeyResponse as In, PublicTemplateVersionInfo as Ir, SandboxFleetAgent as It, PreviewLinkInfo as J, TaskSessionInfo as Ja, DurablePlanFollowUpResume as Ji, StorageConfig as Jn, GpuLease as Jr, SandboxFleetMachineMeteredUsage as Jt, ProcessSpawnOptions as K, TaskSessionCommitResult as Ka, DurablePlanDecisionOptions as Ki, SandboxResourceUsage as Kn, DriverType as Kr, SandboxFleetIntelligenceEnvelope as Kt, DevServerInfo as L, SessionInfo as La, BatchRunRequest as Li, CreateRequestOptions as Ln, PublishPublicTemplateOptions as Lr, SandboxFleetAgentSpec as Lt, ResumeOptions as M, SessionEventStreamOptions as Ma, RolloutTurnPart as Mi, TeeAttestationOptions as Mn, SearchOptions as Mr, ReapExpiredSandboxFleetsOptions as Mt, SandboxIdentity as N, SessionExecutionInfo as Na, WaitForRolloutOptions as Ni, TeeAttestationReport as Nn, ExecOptions as Nr, ReapExpiredSandboxFleetsResult as Nt, ProvisionEvent as O, SendSessionMessageOptions as Oa, RolloutOptions as Oi, SandboxTerminalRequestOptions as On, ALL_BACKEND_TYPES as Oo, WriteFileOptions as Or, FleetPromptDispatchResult as Ot, SubscriptionInfo as P, SessionExecutionStatus as Pa, BatchBackend as Pi, TeeAttestationResponse as Pn, ExecResult as Pr, ReconcileSandboxFleetsOptions as Pt, AddUserOptions as Q, BackendConfig as Qa, IntelligenceReportBudget as Qi, MAX_EGRESS_DENIALS_LIMIT as Qn, GpuLeaseExecResult as Qr, SandboxFleetManifestMachine as Qt, EnsureDevServerOptions as R, SessionInterruptOptions as Ra, BatchTask as Ri, CreateSandboxOptions as Rn, PublishPublicTemplateVersionOptions as Rr, SandboxFleetArtifact as Rt, SnapshotResult as S, DriveTurnOptions as Sa, BranchOptions as Si, SandboxRunGeneration as Sn, PublicBatchRunRequest as So, FileWriteResult as Sr, FleetDispatchResultBufferOptions as St, SecretInfo as T, EffectiveBackendSource as Ta, ForkLookupOptions as Ti, SandboxTerminalCreateOptions as Tn, BatchEventDataMap as To, RenameOptions as Tr, FleetExecDispatchResult as Tt, ProcessLogEntry as U, SessionResultOptions as Ua, AgentToolInvocation as Ui, SandboxShapesInfo as Un, DockerDriverConfig as Ur, SandboxFleetDriverCapability as Ut, ProcessInfo as V, SessionMessageAdmission as Va, AgentQuestionRequest as Vi, SandboxShape as Vn, AttachGpuLeaseOptions as Vr, SandboxFleetDispatchFailureClass as Vt, ProcessManager as W, SessionStatus as Wa, CreateIntelligenceReportOptions as Wi, SandboxStatus as Wn, DriverConfig as Wr, SandboxFleetDriverTimings as Wt, PreviewLinkWaitOptions as X, TurnDriveResult as Xa, EventStreamOptions as Xi, EgressManager as Xn, GpuLeaseCommandResult as Xr, SandboxFleetMachineSpec as Xt, PreviewLinkManager as Y, TaskSessionProfile as Ya, DurablePlanSnapshot as Yi, EgressDenial as Yn, GpuLeaseBilling as Yr, SandboxFleetMachineRecord as Yt, AccessPolicyRule as Z, BackendCapabilities as Za, IntelligenceReport as Zi, EgressPolicy as Zn, GpuLeaseExecOptions as Zr, SandboxFleetManifest as Zt, SnapshotIdempotency as _, ConversationTurnResult as _a, ManagedProcessSpec as _i, SSHCredentials as _n, RawEvidenceExportOptions as _o, FileTreeFile as _r, FleetAgentPlacement as _t, DeleteMatchingSandboxesOptions as a, SandboxEvent as aa, GpuLeaseStatus as ai, SandboxFleetToken as an, SandboxCreateOutcome as ao, ChunkedUploadResult as ar, GitBranch as at, SnapshotProvenance as b, DispatchPromptOptions as ba, JsonValue as bi, SandboxPortBinding as bn, RawEvidenceRecordsFile as bo, FileUsageOptions as br, FleetDispatchCancelResult as bt, SandboxDeleteAcknowledgement as c, SandboxTraceEvent as ca, NonHostAgentDriverConfig as ci, SandboxFleetTraceExport as cn, SandboxEnvRecovery as co, DownloadProgress as cr, GitStatus as ct, SandboxOperationInfo as d, TokenUsage as da, CodeLanguage as di, SandboxFleetWorkspace as dn, RawEvidenceArchiveManifest as do, FileReadBatchOptions as dr, TokenRefreshHandler as dt, IntelligenceReportSubjectType as ea, GpuLeaseProviderName as ei, SandboxFleetParent as en, BackendMcpServerStatus as eo, NetworkManager as er, DirectoryPermission as et, SandboxOperationKind as f, TurnBackendConfig as fa, CodeResultPart as fi, SandboxFleetWorkspaceReconcileResult as fn, RawEvidenceArchiveManifestNative as fo, FileReadBatchResult as fr, AttachSandboxFleetMachineOptions as ft, SnapshotDeleteOutcome as g, ConversationTurnOptions as ga, ManagedProcessResumeOptions as gi, SSHCommandDescriptor as gn, RawEvidenceDirectoryExport as go, FileSystem as gr, FleetAgentId as gt, SnapshotDeleteAcknowledgement as h, CompletedTurnResult as ha, ManagedProcessRecord as hi, ListSandboxOptions as hn, RawEvidenceBoxExportOptions as ho, FileRenameResult as hr, CreateSandboxFleetWithCoordinatorOptions as ht, DeleteMatchingSandboxesFilter as i, PromptResult as ia, GpuLeaseProvidersOptions as ii, SandboxFleetSpend as in, RouterRoutingOptions as io, ChunkedUploadOptions as ir, UpdateUserOptions as it, ProvisionStep as j, SessionBackendCredentials as ja, RolloutStatus as ji, StartupOperation as jn, SearchMatch as jr, ListSandboxFleetOptions as jt, ProvisionResult as k, SendSessionMessageRequest as ka, RolloutScorer as ki, SandboxTerminals as kn, BackendType as ko, WriteManyFile as kr, FleetRunEvent as kt, SandboxDeleteOptions as l, SandboxTraceExport as la, CodeExecutionOptions as li, SandboxFleetTraceOptions as ln, SandboxEnvRecoveryView as lo, DownloadResult as lr, FleetDriveTurnOutcome as lt, SandboxRemovalState as m, CompletedTurnPayload as ma, ManagedProcessOptions as mi, SandboxFleetWorkspaceSnapshotResult as mn, RawEvidenceBoxDirectoryExport as mo, FileReadResult as mr, CreateSandboxFleetTokenOptions as mt, DeleteMatchingSandboxOutcome as n, PromptInputPart as na, GpuLeaseProviderStatus as ni, SandboxFleetPolicy as nn, BackendStatus as no, GitAuth as nr, PermissionsManager as nt, DeleteMatchingSandboxesResult as o, SandboxIntelligenceEnvelope as oa, HostAgentDriverConfig as oi, SandboxFleetTraceBundle as on, SandboxCreateReceipt as oo, DeleteOptions as or, GitCommit as ot, SandboxOperationState as p, CommitTaskSessionOptions as pa, ManagedProcessJobs as pi, SandboxFleetWorkspaceRestoreResult as pn, RawEvidenceBoxArchiveManifest as po, FileReadError as pr, CreateSandboxFleetOptions as pt, ProcessStatus as q, TaskSessionFileChange as qa, DurablePlanDecisionResult as qi, SandboxRuntimeCapabilities as qn, GPU_LEASE_PROVIDER_NAMES as qr, SandboxFleetMachine as qt, DeleteMatchingSandboxResult as r, PromptOptions as ra, GpuLeaseProviders as ri, SandboxFleetProfileRef as rn, McpServerConfig as ro, GitConfig as rr, SandboxUser as rt, RestoreSnapshotOptions as s, SandboxTraceBundle as sa, HostAgentRuntimeBackend as si, SandboxFleetTraceEvent as sn, WorkspaceImagePublishResult as so, DownloadOptions as sr, GitDiff as st, InstalledTool as t, IntelligenceReportWindow as ta, GpuLeaseProviderState as ti, SandboxFleetPlacement as tn, BackendRuntimeConfigUpdate as to, SandboxEgressUsage as tr, PermissionLevel as tt, SandboxDeleteOutcome as u, SandboxTraceOptions as ua, CodeExecutionResult as ui, SandboxFleetUsage as un, NativeStoreHomeCopy as uo, FileInfo as ur, FleetDriveTurnRequest as ut, SnapshotInfo as v, CreateSessionOptions as va, ManagedProcessState as vi, SandboxConnection as vn, RawEvidenceNativeFile as vo, FileTreeOptions as vr, FleetAgentResult as vt, WorkspaceOperationLookup as w, EffectiveBackendProfile as wa, ForkIdempotency as wi, SandboxTerminalAttachOptions as wn, BatchEvent as wo, MkdirOptions as wr, FleetExecDispatchOptions as wt, SnapshotRemoteSync as x, DispatchedSession as xa, SdkTimingHook as xi, SandboxPortPreviewLink as xn, InteractionResolutionAcknowledgement as xo, FileUsageResult as xr, FleetDispatchResultBuffer as xt, SnapshotOptions as y, CreateTaskSessionOptions as ya, HttpClient as yi, SandboxInfo as yn, RawEvidencePayloadFile as yo, FileTreeResult as yr, FleetAgentRunStatus as yt, ExactProcessSpawnOptions as z, SessionListOptions as za, BatchTaskResult as zi, SandboxConfig as zn, SandboxEnvironment as zr, SandboxFleetArtifactSpec as zt };
8237
+ export { BackendManager as $, BackendStatus as $a, ManagedProcessState as $i, SandboxConnection as $n, FileTreeOptions as $r, FleetAgentResult as $t, ProvisionStatus as A, DurablePlanSnapshot as Aa, GpuLeaseBilling as Ai, SandboxFleetMachineRecord as An, parseBackendType as Ao, EgressDenial as Ar, SessionExecutionStatus as At, Process as B, SandboxEvent as Ba, GpuLeaseStatus as Bi, SandboxFleetToken as Bn, ChunkedUploadResult as Br, SessionStatus as Bt, StopOptions as C, AgentRunStatus as Ca, CreateGpuLeaseOptions as Ci, SandboxFleetDispatchResponse as Cn, BatchBackendStats as Co, SandboxShapePreset as Cr, PublicProfileConflict as Ct, SshKeysManager as D, DurablePlanDecisionOptions as Da, DriverType as Di, SandboxFleetIntelligenceEnvelope as Dn, BatchTaskUsage as Do, SandboxResourceUsage as Dr, SessionBackendCredentials as Dt, SecretsManager as E, DurablePlan as Ea, DriverInfo as Ei, SandboxFleetInfo as En, BatchSidecarGroup as Eo, SecretBinding as Er, SentSessionMessage as Et, UsageInfo as F, IntelligenceReportSubjectType as Fa, GpuLeaseProviderName as Fi, SandboxFleetParent as Fn, NetworkManager as Fr, SessionListOptions as Ft, ProcessSignal as G, SandboxTraceOptions as Ga, CodeExecutionResult as Gi, SandboxFleetUsage as Gn, FileInfo as Gr, TaskSessionProfile as Gt, ProcessListOptions as H, SandboxTraceBundle as Ha, HostAgentRuntimeBackend as Hi, SandboxFleetTraceEvent as Hn, DownloadOptions as Hr, TaskSessionCommitResult as Ht, WaitForOptions as I, IntelligenceReportWindow as Ia, GpuLeaseProviderState as Ii, SandboxFleetPlacement as In, SandboxEgressUsage as Ir, SessionMessage as It, PreviewLinkInfo as J, BackendCapabilities as Ja, ManagedProcessJobs as Ji, SandboxFleetWorkspaceRestoreResult as Jn, FileReadError as Jr, CreateSandboxFleetOptions as Jt, ProcessSpawnOptions as K, TokenUsage as Ka, CodeLanguage as Ki, SandboxFleetWorkspace as Kn, FileReadBatchOptions as Kr, TurnDriveResult as Kt, DevServerInfo as L, PromptInputPart as La, GpuLeaseProviderStatus as Li, SandboxFleetPolicy as Ln, GitAuth as Lr, SessionMessageAdmission as Lt, ResumeOptions as M, IntelligenceReport as Ma, GpuLeaseExecOptions as Mi, SandboxFleetManifest as Mn, EgressPolicy as Mr, SessionForkOptions as Mt, SandboxIdentity as N, IntelligenceReportBudget as Na, GpuLeaseExecResult as Ni, SandboxFleetManifestMachine as Nn, MAX_EGRESS_DENIALS_LIMIT as Nr, SessionInfo as Nt, ProvisionEvent as O, DurablePlanDecisionResult as Oa, GPU_LEASE_PROVIDER_NAMES as Oi, SandboxFleetMachine as On, ALL_BACKEND_TYPES as Oo, SandboxRuntimeCapabilities as Or, SessionEventStreamOptions as Ot, SubscriptionInfo as P, IntelligenceReportCompareTo as Pa, GpuLeaseManager as Pi, SandboxFleetOperationsSummary as Pn, NetworkConfig as Pr, SessionInterruptOptions as Pt, AddUserOptions as Q, BackendRuntimeConfigUpdate as Qa, ManagedProcessSpec as Qi, SSHCredentials as Qn, FileTreeFile as Qr, FleetAgentPlacement as Qt, EnsureDevServerOptions as R, PromptOptions as Ra, GpuLeaseProviders as Ri, SandboxFleetProfileRef as Rn, GitConfig as Rr, SessionMessageInputPart as Rt, SnapshotResult as S, AgentQuestionRequest as Sa, AttachGpuLeaseOptions as Si, SandboxFleetDispatchFailureClass as Sn, PublicBatchRunRequest as So, SandboxShape as Sr, ListMessagesOptions as St, SecretInfo as T, CreateIntelligenceReportOptions as Ta, DriverConfig as Ti, SandboxFleetDriverTimings as Tn, BatchEventDataMap as To, SandboxStatus as Tr, SendSessionMessageRequest as Tt, ProcessLogEntry as U, SandboxTraceEvent as Ua, NonHostAgentDriverConfig as Ui, SandboxFleetTraceExport as Un, DownloadProgress as Ur, TaskSessionFileChange as Ut, ProcessInfo as V, SandboxIntelligenceEnvelope as Va, HostAgentDriverConfig as Vi, SandboxFleetTraceBundle as Vn, DeleteOptions as Vr, TaskSessionChanges as Vt, ProcessManager as W, SandboxTraceExport as Wa, CodeExecutionOptions as Wi, SandboxFleetTraceOptions as Wn, DownloadResult as Wr, TaskSessionInfo as Wt, PreviewLinkWaitOptions as X, BackendInfo as Xa, ManagedProcessRecord as Xi, ListSandboxOptions as Xn, FileRenameResult as Xr, CreateSandboxFleetWithCoordinatorOptions as Xt, PreviewLinkManager as Y, BackendConfig as Ya, ManagedProcessOptions as Yi, SandboxFleetWorkspaceSnapshotResult as Yn, FileReadResult as Yr, CreateSandboxFleetTokenOptions as Yt, AccessPolicyRule as Z, BackendMcpServerStatus as Za, ManagedProcessResumeOptions as Zi, SSHCommandDescriptor as Zn, FileSystem as Zr, FleetAgentId as Zt, SnapshotIdempotency as _, BatchRunOptions as _a, PublicTemplateVersionInfo as _i, SandboxFleetAgent as _n, RawEvidenceExportOptions as _o, TeePublicKeyResponse as _r, CreateSessionOptions as _t, DeleteMatchingSandboxesOptions as a, ForkIdempotency as aa, MkdirOptions as ai, FleetExecDispatchOptions as an, SandboxCreateOutcome as ao, SandboxTerminalAttachOptions as ar, GitBranch as at, SnapshotProvenance as b, BatchTaskResult as ba, SandboxEnvironment as bi, SandboxFleetArtifactSpec as bn, RawEvidenceRecordsFile as bo, SandboxConfig as br, DispatchedSession as bt, SandboxDeleteAcknowledgement as c, RolloutChildResult as ca, UploadProgress as ci, FleetPromptDispatchOptions as cn, SandboxEnvRecovery as co, SandboxTerminalManager as cr, GitStatus as ct, SandboxOperationInfo as d, RolloutStartResult as da, WriteManyOptions as di, FleetRunOptions as dn, RawEvidenceArchiveManifest as do, StartupDiagnostics as dr, TokenRefreshHandler as dt, HttpClient as ea, FileTreeResult as ei, FleetAgentRunStatus as en, EffectiveBackend as eo, SandboxInfo as er, DirectoryPermission as et, SandboxOperationKind as f, RolloutStatus as fa, SearchMatch as fi, ListSandboxFleetOptions as fn, RawEvidenceArchiveManifestNative as fo, StartupOperation as fr, CommitTaskSessionOptions as ft, SnapshotDeleteOutcome as g, BatchResult as ga, PublicTemplateInfo as gi, ReconcileSandboxFleetsResult as gn, RawEvidenceDirectoryExport as go, TeePublicKey as gr, ConversationTurnResult as gt, SnapshotDeleteAcknowledgement as h, BatchBackend as ha, ExecResult as hi, ReconcileSandboxFleetsOptions as hn, RawEvidenceBoxExportOptions as ho, TeeAttestationResponse as hr, ConversationTurnOptions as ht, DeleteMatchingSandboxesFilter as i, ForkCounts as ia, ListOptions as ii, FleetDispatchStreamOptions as in, RouterRoutingOptions as io, SandboxRuntimeHealth as ir, UpdateUserOptions as it, ProvisionStep as j, EventStreamOptions as ja, GpuLeaseCommandResult as ji, SandboxFleetMachineSpec as jn, EgressManager as jr, SessionFailureReason as jt, ProvisionResult as k, DurablePlanFollowUpResume as ka, GpuLease as ki, SandboxFleetMachineMeteredUsage as kn, BackendType as ko, StorageConfig as kr, SessionExecutionInfo as kt, SandboxDeleteOptions as l, RolloutOptions as la, WriteFileOptions as li, FleetPromptDispatchResult as ln, SandboxEnvRecoveryView as lo, SandboxTerminalRequestOptions as lr, FleetDriveTurnOutcome as lt, SandboxRemovalState as m, WaitForRolloutOptions as ma, ExecOptions as mi, ReapExpiredSandboxFleetsResult as mn, RawEvidenceBoxDirectoryExport as mo, TeeAttestationReport as mr, CompletedTurnResult as mt, DeleteMatchingSandboxOutcome as n, SdkTimingHook as na, FileUsageResult as ni, FleetDispatchResultBuffer as nn, EffectiveBackendSource as no, SandboxPortPreviewLink as nr, PermissionsManager as nt, DeleteMatchingSandboxesResult as o, ForkLookupOptions as oa, RenameOptions as oi, FleetExecDispatchResult as on, SandboxCreateReceipt as oo, SandboxTerminalCreateOptions as or, GitCommit as ot, SandboxOperationState as p, RolloutTurnPart as pa, SearchOptions as pi, ReapExpiredSandboxFleetsOptions as pn, RawEvidenceBoxArchiveManifest as po, TeeAttestationOptions as pr, CompletedTurnPayload as pt, ProcessStatus as q, TurnBackendConfig as qa, CodeResultPart as qi, SandboxFleetWorkspaceReconcileResult as qn, FileReadBatchResult as qr, AttachSandboxFleetMachineOptions as qt, DeleteMatchingSandboxResult as r, BranchOptions as ra, FileWriteResult as ri, FleetDispatchResultBufferOptions as rn, McpServerConfig as ro, SandboxRunGeneration as rr, SandboxUser as rt, RestoreSnapshotOptions as s, Rollout as sa, UploadOptions as si, FleetMachineId as sn, WorkspaceImagePublishResult as so, SandboxTerminalInfo as sr, GitDiff as st, InstalledTool as t, JsonValue as ta, FileUsageOptions as ti, FleetDispatchCancelResult as tn, EffectiveBackendProfile as to, SandboxPortBinding as tr, PermissionLevel as tt, SandboxDeleteOutcome as u, RolloutScorer as ua, WriteManyFile as ui, FleetRunEvent as un, NativeStoreHomeCopy as uo, SandboxTerminals as ur, FleetDriveTurnRequest as ut, SnapshotInfo as v, BatchRunRequest as va, PublishPublicTemplateOptions as vi, SandboxFleetAgentSpec as vn, RawEvidenceNativeFile as vo, CreateRequestOptions as vr, CreateTaskSessionOptions as vt, WorkspaceOperationLookup as w, AgentToolInvocation as wa, DockerDriverConfig as wi, SandboxFleetDriverCapability as wn, BatchEvent as wo, SandboxShapesInfo as wr, SendSessionMessageOptions as wt, SnapshotRemoteSync as x, AgentApprovalRequirement as xa, AcceleratorKind as xi, SandboxFleetCostEstimate as xn, InteractionResolutionAcknowledgement as xo, SandboxResources as xr, DriveTurnOptions as xt, SnapshotOptions as y, BatchTask as ya, PublishPublicTemplateVersionOptions as yi, SandboxFleetArtifact as yn, RawEvidencePayloadFile as yo, CreateSandboxOptions as yr, DispatchPromptOptions as yt, ExactProcessSpawnOptions as z, PromptResult as za, GpuLeaseProvidersOptions as zi, SandboxFleetSpend as zn, ChunkedUploadOptions as zr, SessionResultOptions as zt };