@tangle-network/agent-app 0.60.227 → 0.60.228

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.
@@ -1,959 +1,13 @@
1
- import { Sandbox } from '@tangle-network/sandbox/core';
2
- import type { EgressPolicy, MintScopedTokenOptions, SandboxInstance, ScopedTokenScope, StorageConfig, TurnDriveResult, ProvisionEvent } from '@tangle-network/sandbox';
3
- import type { AgentProfile, AgentProfileFileMount, AgentProfileMcpServer, ReasoningEffort } from '@tangle-network/agent-interface';
4
- import { type AppToolName, type AppToolContext, type ToolHeaderNames } from '../tools/index';
5
- import { type Harness } from '../harness/index';
6
- import { type TangleExecutionEnvironment } from '../runtime/model';
7
- import { type Outcome } from './outcome';
8
- import type { TurnSpan, TurnTrace } from '../turn-trace/recorder';
9
1
  export { traceSandboxPromptEvents, type TraceSandboxPromptOptions } from './prompt-trace';
10
- import { type ReuseStateStore } from './reuse-state';
11
- export { createCacheReuseStore, type ReuseCacheLike, type ReuseChecks, type ReuseStateStore, type SharedReuseState } from './reuse-state';
12
- import { type ProfileFingerprint } from '../profile/fingerprint';
13
- import { type ComposeProfileBudget } from '../profile/budget';
14
- import { resolveModel, resolveModelSelection, backendModelFields, requireTransportableModel, SandboxModelResolutionError, type ProviderResolutionConfig, type ResolvedModel, type ModelSelection, type ModelSelectionFailure, type ModelSelectionError, type ModelSelectionSource } from './model';
2
+ export { createCacheReuseStore, type ReuseCacheLike, type ReuseChecks, type ReuseStateStore, type SharedReuseState, } from './reuse-state';
15
3
  export type { Outcome } from './outcome';
16
4
  export * from './binary-read';
17
5
  export * from './transient-failure';
18
- export { resolveModel, resolveModelSelection, backendModelFields, requireTransportableModel, SandboxModelResolutionError, };
19
- export type { ProviderResolutionConfig, ResolvedModel, ModelSelection, ModelSelectionFailure, ModelSelectionError, ModelSelectionSource, };
20
- /** Define client credentials for accessing the sandbox environment with API key and base URL */
21
- export interface SandboxClientCredentials {
22
- apiKey: string;
23
- baseUrl: string;
24
- }
25
- /**
26
- * Sandbox credential policy reuses the canonical execution-environment union
27
- * (development/test/staging/production) so env classification stays in one place
28
- * (see resolveTangleExecutionEnvironment in runtime/model).
29
- */
30
- export type SandboxCredentialEnvironment = TangleExecutionEnvironment;
31
- /** Resolve options for obtaining sandbox client credentials from environment variables and classification */
32
- export interface ResolveSandboxClientCredentialsOptions {
33
- /**
34
- * Environment object to read from. Defaults to process.env when available.
35
- */
36
- env?: Record<string, string | undefined>;
37
- /**
38
- * Explicit environment classification. Defaults to APP_ENV/NODE_ENV derived
39
- * behavior: local/development/test use direct env credentials; staging/prod
40
- * require the provision callback unless allowDirectEnvCredentials opts in.
41
- */
42
- environment?: SandboxCredentialEnvironment;
43
- /**
44
- * Env names that may carry a sandbox-compatible bearer. The first non-empty
45
- * value wins when direct env credentials are allowed.
46
- */
47
- directKeyNames?: readonly string[];
48
- /**
49
- * Env names that may carry the sandbox gateway URL. The first non-empty value
50
- * wins, then defaultBaseUrl.
51
- */
52
- baseUrlNames?: readonly string[];
53
- /**
54
- * Base URL used when none of baseUrlNames are present.
55
- */
56
- defaultBaseUrl?: string;
57
- /**
58
- * Whether direct env credentials are allowed for this environment. Defaults
59
- * to true in development/test and false in staging/production.
60
- */
61
- allowDirectEnvCredentials?: boolean | ((environment: SandboxCredentialEnvironment) => boolean);
62
- /**
63
- * Product-owned provision path, usually minting a per-user sandbox key from a
64
- * linked platform account. Called before direct env credentials in
65
- * staging/production and after direct env credentials in development/test.
66
- */
67
- provision?: (context: {
68
- environment: SandboxCredentialEnvironment;
69
- env: Record<string, string | undefined>;
70
- }) => SandboxClientCredentials | null | undefined | Promise<SandboxClientCredentials | null | undefined>;
71
- }
72
- /** Resolve sandbox client credentials based on environment and provided options asynchronously */
73
- export declare function resolveSandboxClientCredentials(options?: ResolveSandboxClientCredentialsOptions): Promise<SandboxClientCredentials>;
74
- /**
75
- * Configure sandbox resources and lifecycle limits.
76
- * Set `advisory` for application defaults that the Sandbox API may clamp to account limits.
77
- * Omit it when the requested allocation must be honored or rejected.
78
- */
79
- export interface SandboxResourceConfig {
80
- image: string;
81
- cpuCores: number;
82
- memoryMB: number;
83
- diskGB: number;
84
- /** Let the Sandbox API clamp these resource defaults to the account's limits. */
85
- advisory?: boolean;
86
- maxLifetimeSeconds: number;
87
- idleTimeoutSeconds: number;
88
- }
89
- /** Define the context for building a sandbox including workspace, integrations, and optional user ID */
90
- export interface SandboxBuildContext {
91
- workspaceId: string;
92
- connectedIntegrationIds: string[];
93
- userId?: string;
94
- }
95
- /** Hosts required when a product installs its pinned Python tooling at boot. */
96
- export declare const PYPI_EGRESS_DOMAINS: readonly ['pypi.org', 'files.pythonhosted.org', 'pypi.python.org'];
97
- export declare function buildProductEgressPolicy(publicOrigin: string | URL, extraDomains?: readonly string[]): EgressPolicy;
98
- export type { StorageConfig };
99
- /** Define a scope containing workspace and optional user identifiers for sandbox environments */
100
- export interface SandboxScope {
101
- workspaceId: string;
102
- userId?: string;
103
- }
104
- /** Define the specification for restoring a sandbox from a snapshot or another sandbox ID */
105
- export interface SandboxRestoreSpec {
106
- fromSnapshot: string;
107
- fromSandboxId: string;
108
- }
109
- /** Describe the failure details when resuming a stopped sandbox instance */
110
- export interface StoppedSandboxResumeFailure {
111
- box: SandboxInstance;
112
- error: Error;
113
- scope: SandboxScope;
114
- boxKey: string;
115
- }
116
- /** Describe a sandbox that disappeared after the platform listed it. */
117
- export interface MissingSandboxFailure extends StoppedSandboxResumeFailure {
118
- stage: SandboxExistingBoxStage;
119
- }
120
- /** Define the structure for resuming a stopped sandbox with replacement key and optional restore options */
121
- export interface StoppedSandboxResumeRecovery {
122
- replacementBoxKey: string;
123
- restore?: SandboxRestoreSpec | null;
124
- }
125
- /** Configure runtime exec verification before reusing a sandbox. */
126
- export interface LivenessProbeConfig {
127
- /** Process timeout passed to the Sandbox SDK. Defaults to 5 seconds.
128
- * SDK readiness and transport deadlines also apply. */
129
- execTimeoutMs?: number;
130
- /**
131
- * Reuse a successful liveness result for this many milliseconds for the
132
- * same box id and identity (start time and filesystem incarnation). Defaults to 10 minutes; set to 0 to probe on
133
- * every reuse.
134
- *
135
- * Only the exec probe is cached. Runtime readiness, deferred-file
136
- * materialization, and bootstrap still run on every reuse, and the egress
137
- * policy and runtime environment are checked as {@link SandboxRuntimeConfig.egressPolicy}
138
- * and {@link SandboxRuntimeConfig.runtimeEnv} describe. A box that dies during
139
- * this window is surfaced by the first call on it: a caller whose first call
140
- * fails passes the box to {@link dropTrustedBox} and ensures once more, which
141
- * probes it and restarts it in place. The cache never triggers box deletion.
142
- */
143
- cacheTtlMs?: number;
144
- }
145
- /** Define options for composing a user profile including prompts, files, servers, and name */
146
- export interface ProfileComposeOptions {
147
- systemPrompt?: string;
148
- extraFiles?: AgentProfileFileMount[];
149
- extraMcp?: Record<string, AgentProfileMcpServer>;
150
- name?: string;
151
- /**
152
- * The harness this profile is being composed for.
153
- *
154
- * Where a resource lands is harness-specific — skills resolve to
155
- * `.opencode/skills/`, `.claude/skills/`, `.pi/skills/`, and so on
156
- * (`skillDirForHarness`), and some harnesses take no cwd skills at all.
157
- * Without this, an app composing a profile cannot place a harness-native
158
- * resource and is pushed into hardcoding one harness's path, which then
159
- * silently disagrees with the path its own prompt cites: the agent is told
160
- * to read a directory nothing was written to and its skills are invisible.
161
- * Prefer declaring `resources.skills` and letting the platform place them;
162
- * use this when composing paths directly.
163
- */
164
- harness: Harness;
165
- }
166
- /** Define runtime configuration methods for sandbox environments including credentials, metadata, and permissions */
167
- export interface SandboxRuntimeConfig {
168
- credentials: (scope?: SandboxScope) => SandboxClientCredentials | null | Promise<SandboxClientCredentials | null>;
169
- name: (workspaceId: string) => string;
170
- metadata: (harness: Harness) => Record<string, unknown>;
171
- connectedIntegrationIds: (workspaceId: string) => Promise<string[]>;
172
- /**
173
- * Creation-only environment. Use runtimeEnv for expiring app credentials.
174
- * Values remain private; profiles reference their names through secret-ref.
175
- * Workspace-wide values cannot carry per-user or per-resource authority.
176
- */
177
- env: (ctx: SandboxBuildContext) => Promise<Record<string, string>>;
178
- /**
179
- * Workspace app credentials resolved on creation and before every reuse,
180
- * resume, or recovery. Fresh values override env in the creation payload.
181
- * The SDK updates retained runtimes before bootstrap and refuses runtime-managed keys.
182
- * A resume receives only the keys the platform names as required to rebuild a runtime.
183
- * Throw when required credentials cannot be minted; renewal failure preserves
184
- * the sandbox and prevents dispatch. Requires the matching Sandbox runtime.
185
- * Values equal to the last ones delivered to the same box identity, within
186
- * 10 minutes, are resolved again but not sent again.
187
- */
188
- runtimeEnv?: (scope: SandboxScope) => Promise<Record<string, string>>;
189
- files: (ctx: SandboxBuildContext) => Promise<AgentProfileFileMount[]>;
190
- secrets: (workspaceId: string) => Promise<string[]>;
191
- profile: (options: ProfileComposeOptions) => AgentProfile;
192
- permissionRole?: (workspaceRole: string) => SandboxPermissionLevel;
193
- resources?: SandboxResourceConfig;
194
- provider?: ProviderResolutionConfig;
195
- /**
196
- * Portable directory where the sandbox starts its agent processes.
197
- *
198
- * The value is relative to the sandbox workspace. The sandbox platform
199
- * validates it and applies it when the box is created.
200
- */
201
- cwd?: string;
202
- /**
203
- * Product-declared outbound network policy. Applied when a sandbox is
204
- * created. A reused or resumed sandbox is returned only when its explicit
205
- * policy already matches; existing mismatches are rejected without updating
206
- * or deleting the sandbox unless migration is explicitly enabled below.
207
- * A match read within 10 minutes stands for the same box identity, except
208
- * that a `strict` or `blocked` policy is read again whenever a reuse would send
209
- * the box credentials (a changed {@link runtimeEnv}, or a {@link bootstrap}).
210
- */
211
- egressPolicy?: EgressPolicy;
212
- /**
213
- * Update an existing box to {@link egressPolicy} before reuse when its
214
- * recorded policy is absent or different. This is an explicit fleet
215
- * migration switch: the updated policy is read back and must match before
216
- * the box is returned. It never deletes the box.
217
- */
218
- migrateEgressPolicy?: boolean;
219
- /**
220
- * Where Worker isolates share what a reuse last checked on a box (its id, the
221
- * exec probe, the egress read, the runtime environment delivered). A request is
222
- * not promised the isolate that served the last one, so without a shared store
223
- * a reuse often finds nothing to trust. Default: the runtime's Cache API when
224
- * it has one; `null` keeps the state in the isolate. Holds ids, times and
225
- * digests only.
226
- */
227
- reuseState?: ReuseStateStore | null;
228
- storage?: (ctx: SandboxBuildContext) => StorageConfig | undefined;
229
- restore?: (ctx: SandboxBuildContext) => SandboxRestoreSpec | undefined | Promise<SandboxRestoreSpec | undefined>;
230
- boxKey?: (scope: SandboxScope) => string;
231
- childKeyMint?: (scope: SandboxScope) => Promise<Outcome<string>>;
232
- bootstrap?: (box: SandboxInstance, scope: SandboxScope) => Promise<Outcome<void>>;
233
- livenessProbe?: LivenessProbeConfig;
234
- webTerminalEnabled?: boolean;
235
- resumeStopped?: boolean;
236
- /**
237
- * How long to wait for a box to reach `running`, in ms. Default 120_000.
238
- *
239
- * Raise it when a cold create legitimately takes longer than that — a large
240
- * vault restore, a heavy image, a loaded fleet. The failure it prevents is
241
- * ugly: every attempt burns the full wait, times out, and the NEXT attempt
242
- * starts the same slow create from scratch, so a workspace whose provision
243
- * takes 130s never succeeds no matter how many times a user retries.
244
- */
245
- provisionTimeoutMs?: number;
246
- replaceUnbringableBox?: boolean;
247
- recoverStoppedSandbox?: (failure: StoppedSandboxResumeFailure) => Promise<Outcome<StoppedSandboxResumeRecovery | null>>;
248
- /**
249
- * Replace a sandbox resource or backing container that disappears after listing.
250
- *
251
- * The shell calls this for a sandbox resource 404 or an exact resume 500 that
252
- * wraps a host-agent container 404. It excludes runtime 404 and unrelated
253
- * reuse failures. Return a fresh key without deleting the stale sandbox record.
254
- */
255
- recoverMissingSandbox?: (failure: MissingSandboxFailure) => Promise<Outcome<StoppedSandboxResumeRecovery | null>>;
256
- backendModelAtCreate?: boolean;
257
- deferProfileFiles?: boolean;
258
- promptBudget?: ComposeProfileBudget;
259
- }
260
- /** Define default resource limits and settings for sandbox environments */
261
- export declare const DEFAULT_SANDBOX_RESOURCES: SandboxResourceConfig;
262
- /**
263
- * Forget what this isolate trusts about a box after the first real call on it
264
- * failed. Returns true when the ensure handed the box out without probing it, so
265
- * the caller may ensure once more and get the full verification; false when the
266
- * ensure had probed it and the failure is the box's own.
267
- */
268
- export declare function dropTrustedBox(box: SandboxInstance): boolean;
269
- /** Resolve a synchronous sandbox client from provided runtime configuration credentials */
270
- export declare function getClient(shell: SandboxRuntimeConfig): Sandbox;
271
- /** Reset the process-local sandbox client and liveness-verification caches. */
272
- export declare function resetClientCache(): void;
273
- /** Describe an application tool with its name, unique key, and description */
274
- export interface AppToolDescriptor {
275
- tool: AppToolName;
276
- key: string;
277
- description: string;
278
- }
279
- /** Define options for building MCP server configurations in the app tool environment */
280
- export interface BuildAppToolMcpServersOptions {
281
- tools: AppToolDescriptor[];
282
- baseUrl: string;
283
- /**
284
- * NAME of the box-environment variable holding the capability token — never
285
- * the token itself. Every emitted `Authorization` header is a `secret-ref` to
286
- * this key, which the sandbox resolves privately; see
287
- * `BuildHttpMcpServerOptions.tokenEnvKey` in `../tools/mcp`.
288
- *
289
- * The key must name a variable the box carries — placed by
290
- * {@link SandboxRuntimeConfig.env} at creation, refreshed by
291
- * {@link SandboxRuntimeConfig.runtimeEnv} before retained-box bootstrap, or
292
- * injected from the platform secret store via
293
- * {@link SandboxRuntimeConfig.secrets}.
294
- */
295
- tokenEnvKey: string;
296
- ctx: AppToolContext;
297
- headerNames?: ToolHeaderNames;
298
- }
299
- /** Build a mapping of MCP server profiles keyed by tool identifiers from provided options */
300
- export declare function buildAppToolMcpServers(options: BuildAppToolMcpServersOptions): Record<string, AgentProfileMcpServer>;
301
- /** Define options for ensuring a workspace sandbox with provisioning and progress handling */
302
- export interface EnsureWorkspaceSandboxOptions {
303
- workspaceId: string;
304
- userId?: string;
305
- harness: Harness;
306
- forceNew?: boolean;
307
- onProgress?: (event: ProvisionEvent) => void;
308
- billingOwnerId?: string;
309
- spend?: SandboxSpendHooks;
310
- /** Optional stage timing for the steps of an ensure (`sandbox.ensure.*`), so a
311
- * product can see which round trip a slow acquisition spent its time in.
312
- * Omitted, nothing is measured. */
313
- measure?: <T>(stage: string, operation: () => Promise<T>) => Promise<T>;
314
- /**
315
- * The turn's trace. The ensure is recorded as one `sandbox.claim` span whose children are the
316
- * `sandbox.ensure.*` steps (`credentials`, `get_running` or `list_running`, `finalize` for a reused box,
317
- * with `egress` and `liveness` unless a recent check stood in for them; `list_stopped`,
318
- * `resume` for a stopped one; `create`, `wait_running`, `bootstrap` for a new one), so a slow claim names
319
- * the step it waited on. The spend seam's two calls are recorded beside the claim as
320
- * `sandbox.spend.before_provision` and `sandbox.spend.observe`. Omitted, nothing is recorded;
321
- * `measure` is unchanged and still called.
322
- */
323
- trace?: TurnTrace;
324
- /** The span the claim hangs from. Default: the trace's root. */
325
- traceParent?: TurnSpan;
326
- }
327
- /** What `/sandbox` reports once a box is provisioned, reused, or resumed. */
328
- export interface SandboxProvisionedObservation {
329
- readonly workspaceId: string;
330
- readonly userId?: string;
331
- /** The platform's sandbox id — the join key to every settlement row. */
332
- readonly sandboxId: string;
333
- /** The deterministic box key this workspace resolves to. */
334
- readonly boxKey?: string | undefined;
335
- /** The idle timeout this box was asked to run with, seconds. */
336
- readonly idleTimeoutSeconds: number;
337
- /** The max lifetime it was asked to run with, seconds, when one was asked for. */
338
- readonly maxLifetimeSeconds?: number | undefined;
339
- readonly at: number;
340
- }
341
- /**
342
- * Optional spend-verification seam on `ensureWorkspaceSandbox`.
343
- *
344
- * The two halves have deliberately opposite failure contracts.
345
- * `beforeProvision` is a GATE: it runs before anything is created and its throw
346
- * propagates, because refusing to provision is the whole point of a budget cap.
347
- * `onProvisioned` is an OBSERVER: its failures are swallowed, because
348
- * bookkeeping must never take down the provisioning it is bookkeeping.
349
- */
350
- export interface SandboxSpendHooks {
351
- /**
352
- * Runs before any create, resume, restart or deletion of a box, and before a
353
- * reuse unless this isolate probed that box recently (10 minutes by default,
354
- * {@link LivenessProbeConfig.cacheTtlMs}): a reuse of a box it has been using
355
- * is gated when its probe expires, not on every turn. Throw to refuse provisioning.
356
- */
357
- beforeProvision?(input: {
358
- workspaceId: string;
359
- userId?: string;
360
- }): Promise<void> | void;
361
- /**
362
- * Runs after a box is available, except for a reuse that trusted a recent
363
- * probe: the ensure that ran that probe reported the box, and `onActivity`
364
- * carries its use since. Throwing here cannot fail the provision.
365
- */
366
- onProvisioned?(observation: SandboxProvisionedObservation): Promise<void> | void;
367
- /**
368
- * The box is doing work. Fired by the turn primitives at the start of a turn
369
- * and again when it settles.
370
- *
371
- * Deliberately SYNCHRONOUS and unawaited — this sits on the turn path, and a
372
- * store write must not add latency to it or hold a stream open. An
373
- * implementation that persists should enqueue and return; errors are
374
- * swallowed here as they are for `onProvisioned`.
375
- *
376
- * Wiring it is what keeps the expectation ceiling honest for long turns:
377
- * without it, `lastActivityAt` only advances when a box is provisioned, so a
378
- * three-hour turn leaves the ceiling three hours too tight and manufactures a
379
- * discrepancy out of the product's own silence.
380
- */
381
- onActivity?(input: {
382
- sandboxId: string;
383
- at: number;
384
- }): void;
385
- }
386
- /** Define the specification for a sandbox tool including its name, content, and optional executability */
387
- export interface SandboxToolSpec {
388
- name: string;
389
- content: string;
390
- executable?: boolean;
391
- }
392
- /** Define options for resolving sandbox tool paths including appName, baseDir, and binDir */
393
- export interface SandboxToolPathOptions {
394
- appName: string;
395
- baseDir?: string;
396
- binDir?: string;
397
- }
398
- /** Define options for building sandbox tool file mounts including tool specifications and paths */
399
- export interface BuildSandboxToolFileMountsOptions extends SandboxToolPathOptions {
400
- tools: readonly SandboxToolSpec[];
401
- }
402
- /** Resolve the root directory path for a sandbox tool based on provided options */
403
- export declare function sandboxToolRootDir(options: SandboxToolPathOptions): string;
404
- /** Resolve the binary directory path for a sandbox tool based on provided options */
405
- export declare function sandboxToolBinDir(options: SandboxToolPathOptions): string;
406
- /** Resolve the file system path to a specified sandbox tool based on given options */
407
- export declare function sandboxToolPath(options: SandboxToolPathOptions & {
408
- toolName: string;
409
- }): string;
410
- /** Build file mounts for sandbox tools based on provided options and tool configurations */
411
- export declare function buildSandboxToolFileMounts(options: BuildSandboxToolFileMountsOptions): AgentProfileFileMount[];
412
- /**
413
- * Build the `SANDBOX_TOOL_BIN_DIRS` entry that puts these apps' tool bin dirs on
414
- * a sandbox PATH. Declare it in the same box env as the mounts from
415
- * {@link buildSandboxToolFileMounts}: the mounts place the executables, this
416
- * places the directory that makes a bare tool name resolve.
417
- *
418
- * Every sandbox PATH builder appends these directories at the TAIL, after the
419
- * Nix, npm, and image entries, so a tool never shadows a platform or system
420
- * binary of the same name. That placement is identical for a non-interactive
421
- * exec, a sidecar-spawned CLI, and an SSH shell, which is why this variable and
422
- * not a shell rc file is the mechanism: an exec reads no rc file, and the SSH
423
- * shell environment assigns PATH absolutely.
424
- *
425
- * Entries come from {@link sandboxToolBinDir}, so the value can never name a
426
- * directory the mounts did not use — a caller that hand-writes the literal
427
- * instead drifts silently the moment a base dir changes. Order is preserved,
428
- * and two apps that resolve to one directory collapse to the FIRST position it
429
- * appeared in.
430
- *
431
- * A `:` in a resolved bin dir throws here. The character separates entries both
432
- * in this variable and in PATH itself, so such a directory is unrepresentable
433
- * rather than merely awkward: joining it would split one absolute path into a
434
- * leading path and a relative remainder, and the runtime rejects a relative
435
- * segment by failing the whole box. Throwing names the offending directory
436
- * instead.
437
- *
438
- * The consuming half lives in agent-container: `resolveSandboxToolBinDirs`
439
- * parses this value and every PATH builder appends it at the tail — sidecar
440
- * exec and PTY through `packages/shared/src/cache-env.ts`, an SSH session
441
- * through `packages/shared/src/ssh-bootstrap.ts`, and a spawned CLI through
442
- * `packages/sdk-cli-runner/src/cli-process.ts`, each with its own tests. This
443
- * package has no sandbox runtime, so tail placement is pinned there, not here.
444
- */
445
- export declare function buildSandboxToolBinDirsEnv(apps: readonly SandboxToolPathOptions[]): {
446
- SANDBOX_TOOL_BIN_DIRS: string;
447
- };
448
- /**
449
- * Build a shell script that creates the sandbox tool binary directory.
450
- * {@link buildSandboxToolBinDirsEnv}, not this script, puts that directory on a
451
- * sandbox PATH.
452
- *
453
- * The `mkdir -p` makes the directory exist before a tool mount lands in it.
454
- */
455
- export declare function buildSandboxToolBinDirScript(options: SandboxToolPathOptions): string;
456
- /** Build a shell script that creates the sandbox tool binary directory.
457
- *
458
- * @deprecated Renamed to {@link buildSandboxToolBinDirScript}, and the script
459
- * no longer appends the bin dir to PATH in `~/.profile`, `~/.bashrc` and
460
- * `~/.zshrc`. Those edits never reached the contexts that run a tool: an exec
461
- * and a spawned CLI read no rc file, and the SSH shell assigns PATH
462
- * absolutely, which discards an appended entry. Put the directory on PATH with
463
- * {@link buildSandboxToolBinDirsEnv} instead. This name forwards to the new
464
- * one so an existing import keeps resolving; removal is a major.
465
- */
466
- export declare function buildSandboxToolPathSetupScript(options: SandboxToolPathOptions): string;
467
- /**
468
- * Create the sandbox tool binary directory in a running box.
469
- * {@link buildSandboxToolBinDirsEnv}, not this call, puts it on a sandbox PATH.
470
- */
471
- export declare function ensureSandboxToolBinDir(box: SandboxInstance, options: SandboxToolPathOptions): Promise<Outcome<void>>;
472
- /** Create the sandbox tool binary directory in a running box.
473
- *
474
- * @deprecated Renamed to {@link ensureSandboxToolBinDir}, and the call no
475
- * longer appends the bin dir to PATH in `~/.profile`, `~/.bashrc` and
476
- * `~/.zshrc`. Those edits never reached the contexts that run a tool: an exec
477
- * and a spawned CLI read no rc file, and the SSH shell assigns PATH
478
- * absolutely, which discards an appended entry. Put the directory on PATH with
479
- * {@link buildSandboxToolBinDirsEnv} instead. This name forwards to the new
480
- * one so an existing import keeps resolving; removal is a major.
481
- */
482
- export declare function runSandboxToolPathSetup(box: SandboxInstance, options: SandboxToolPathOptions): Promise<Outcome<void>>;
483
- /** Split profile files into inline deferred files and a lean profile without them */
484
- export declare function splitDeferredProfileFiles(profile: AgentProfile): {
485
- leanProfile: AgentProfile;
486
- deferredFiles: AgentProfileFileMount[];
487
- };
488
- export type SandboxExistingBoxStage = 'reused' | 'resumed';
489
- export type SandboxEgressPolicySource = Awaited<ReturnType<SandboxInstance['egress']['get']>>['source'];
490
- /**
491
- * Thrown when an existing sandbox cannot be proven to have the requested
492
- * outbound network policy. The sandbox is preserved and its policy is not
493
- * changed. The caller explicitly decides whether to preserve, migrate, or
494
- * replace the sandbox.
495
- */
496
- export declare class SandboxEgressPolicyMismatchError extends Error {
497
- readonly stage: SandboxExistingBoxStage;
498
- readonly boxName: string;
499
- readonly currentPolicy: EgressPolicy;
500
- readonly currentSource: SandboxEgressPolicySource;
501
- readonly desiredPolicy: EgressPolicy;
502
- constructor(stage: SandboxExistingBoxStage, boxName: string, currentPolicy: EgressPolicy, currentSource: SandboxEgressPolicySource, desiredPolicy: EgressPolicy);
503
- }
6
+ export { resolveModel, resolveModelSelection, backendModelFields, requireTransportableModel, SandboxModelResolutionError, } from './model';
7
+ export type { ProviderResolutionConfig, ResolvedModel, ModelSelection, ModelSelectionFailure, ModelSelectionError, ModelSelectionSource, } from './model';
8
+ export type { StorageConfig } from '@tangle-network/sandbox';
504
9
  export * from './recovery';
505
10
  export { serializeSandboxProvisioningError, formatSandboxProvisioningSupportDetails, formatSandboxProvisioningUserMessage, isSandboxAuthFailure, isSandboxApiBearerAuthFailure, isSandboxApiSandboxMissingFailure, isSandboxApiTransientFailure, SANDBOX_BACKING_CONTAINER_MISSING_CODE, isSandboxHostCapacityFailure, type SafeSandboxErrorCause, type SafeSandboxErrorDiagnostics, } from './diagnostics';
506
- /** Represent an error thrown when sandbox runtime authentication refresh fails for a specific stage and name */
507
- export declare class SandboxRuntimeAuthRefreshError extends Error {
508
- constructor(stage: SandboxExistingBoxStage, name: string, detail: string, cause?: unknown);
509
- }
510
- /** Which step of the state-preserving stop→resume recovery failed. `stop` with a
511
- * driver-unsupported cause means the platform cannot restart this box (the
512
- * `tangle` driver exposes create/delete only); `probe` means the box restarted
513
- * but is still unresponsive. */
514
- export type SandboxRecoveryPhase = 'stop' | 'resume' | 'probe';
515
- /**
516
- * Thrown when an unresponsive box could not be recovered by a state-preserving
517
- * restart. Contract: this error is only ever thrown with the workspace intact —
518
- * recovery never deletes. The caller decides what to do next (retry, surface to
519
- * the user, or explicitly replace via `forceNew`).
520
- */
521
- export declare class SandboxRecoveryFailedError extends Error {
522
- readonly boxKey: string;
523
- readonly stage: SandboxExistingBoxStage;
524
- readonly phase: SandboxRecoveryPhase;
525
- constructor(stage: SandboxExistingBoxStage, boxKey: string, phase: SandboxRecoveryPhase, detail: string, cause?: unknown);
526
- }
527
- /**
528
- * Thrown instead of restarting a box that failed the reuse gate because it is
529
- * not connectable (runtime URL missing or edge readiness failed) while its
530
- * runtime reports running sessions. A restart would end those sessions, so the
531
- * box is left running and only the request that asked for it fails. The box is
532
- * not replaced either; retry once its sessions finish.
533
- */
534
- export declare class SandboxBoxBusyError extends Error {
535
- readonly boxKey: string;
536
- readonly stage: SandboxExistingBoxStage;
537
- readonly runningSessions: number;
538
- constructor(stage: SandboxExistingBoxStage, boxKey: string, runningSessions: number, detail: string);
539
- }
540
- /** Define options to control execution timeout, pacing, and retry behavior when writing profile files */
541
- export interface WriteProfileFilesOptions {
542
- execTimeoutMs?: number;
543
- paceMs?: number;
544
- maxRetries?: number;
545
- }
546
- /** Write profile files to a sandbox with pacing, retries, and optional execution timeout handling */
547
- export declare function writeProfileFilesToBox(box: SandboxInstance, files: AgentProfileFileMount[], options?: WriteProfileFilesOptions): Promise<Outcome<void>>;
548
- /** Stable content hash of the deferred file corpus (path + inline content).
549
- * Unchanged corpus ⇒ same hash; a new/edited/removed skill ⇒ different hash.
550
- * Exported for the reuse-skip test. */
551
- export declare function deferredCorpusHash(files: AgentProfileFileMount[]): string;
552
- /** Gate on the provision body: the platform orchestrator caps the create
553
- * payload at 256 KiB; 240 KB leaves headroom for transport framing. An
554
- * over-cap payload fails provisioning 100% of the time (a 282 KB payload
555
- * shipped once and no sandbox could ever be created). */
556
- export declare const PROVISION_PAYLOAD_MAX_BYTES = 240000;
557
- /** Per-variable env gate: the kernel rejects any single `NAME=value` env entry
558
- * over MAX_ARG_STRLEN (131072 bytes) with E2BIG, killing every exec inside
559
- * the box. 120 KB leaves headroom for the name and framing. */
560
- export declare const ENV_VALUE_MAX_BYTES = 120000;
561
- /** Default wait for a box to reach `running`. Overridable per shell via
562
- * {@link SandboxRuntimeConfig.provisionTimeoutMs}. */
563
- export declare const DEFAULT_PROVISION_TIMEOUT_MS = 120000;
564
- /** Total env gate: the whole environment block shares the payload budget with
565
- * the profile; past 200 KB the provision body cannot stay under the cap. */
566
- export declare const ENV_TOTAL_MAX_BYTES = 200000;
567
- /** Structural slice of the profile the payload gate reads: it only measures
568
- * the profile's serialized size and names `resources.files` in the breakdown,
569
- * so callers composing a payload outside the SDK (products, tests) can pass a
570
- * plain object without casting through `AgentProfile`. */
571
- export interface ProvisionProfileSection {
572
- resources?: {
573
- files?: readonly unknown[];
574
- };
575
- }
576
- /** The provision-payload sections the size gates need to see. Structural so
577
- * the gate is testable without the SDK's (unexported) create-payload type. */
578
- export interface ProvisionPayloadSections {
579
- env?: Record<string, string>;
580
- secrets?: readonly string[] | 'all';
581
- /** `profile` may also be a named-profile string ref (the SDK's
582
- * `BackendConfig` union) — a string ref is tiny and has no files channel. */
583
- backend?: {
584
- profile?: string | ProvisionProfileSection;
585
- };
586
- }
587
- /**
588
- * Throw when the serialized provision payload exceeds
589
- * {@link PROVISION_PAYLOAD_MAX_BYTES}. The error carries a per-section byte
590
- * breakdown (profile/files/env/secrets) so the offending channel is named, not
591
- * guessed.
592
- */
593
- export declare function assertProvisionPayloadWithinCap(payload: ProvisionPayloadSections): void;
594
- /**
595
- * Throw when any single env value exceeds {@link ENV_VALUE_MAX_BYTES} or the
596
- * whole env block exceeds {@link ENV_TOTAL_MAX_BYTES}, naming the offending
597
- * variable. This is the E2BIG incident class: the box may even provision, but
598
- * every exec inside it dies on the oversized entry.
599
- */
600
- export declare function assertEnvWithinLimits(env: Record<string, string>): void;
601
- /** What a peek can find. `warming` means the control plane is running while
602
- * the filesystem incarnation is still transitioning. `not-running` carries
603
- * the platform's own state string (`stopped`, `starting`, `failed`, …) —
604
- * narrowing it to a union here would drop states the platform adds later,
605
- * and every caller wants it for a log. */
606
- export type PeekWorkspaceSandboxOutcome = {
607
- status: 'running';
608
- box: SandboxInstance;
609
- } | {
610
- status: 'warming';
611
- readiness: 'transitioning';
612
- box: SandboxInstance;
613
- } | {
614
- status: 'not-running';
615
- state: string;
616
- box: SandboxInstance;
617
- } | {
618
- status: 'absent';
619
- };
620
- /**
621
- * Read-only twin of {@link ensureWorkspaceSandbox}: report whether a
622
- * workspace's box exists and is fully ready, WITHOUT provisioning, resuming,
623
- * or bootstrapping anything.
624
- *
625
- * This is what a read-mostly path needs — a file-index route's `authorize`
626
- * seam, a stale-lock reconciliation, a status badge. Calling `ensure` from one
627
- * of those spins a box up as a side effect of a read (legal-agent #509), and
628
- * costs the caller a cold start it never asked for.
629
- *
630
- * Matching is on BOTH the box key and the display name, IN THAT ORDER.
631
- * `client.get(id)` is a direct read by the platform's opaque sandbox id, not by
632
- * the deterministic key a product derives from a workspace, so a lookup that
633
- * has not seen the box before has to list and match (`ensureWorkspaceSandbox`
634
- * reads a box it has seen by id).
635
- * Provisioning here always stamps `name` with the box key, so the key is the
636
- * authoritative match; the display-name pass exists only to adopt boxes on a
637
- * host that predates that convention. The order matters: a single unordered
638
- * `find` returns whichever the platform happens to list first, so a stopped
639
- * display-name box could shadow a running box-key one and report
640
- * `not-running` for a live workspace.
641
- *
642
- * Unlike `ensure`, this lists ALL statuses in one call: distinguishing "no box"
643
- * from "box is stopped" is the whole point, and a status-filtered list cannot.
644
- *
645
- * A `client.list()` rejection propagates RAW, unlike the `Outcome`-wrapping
646
- * helpers `ensure` uses internally. That is deliberate: there is no honest
647
- * outcome to map a listing failure onto — it is not `absent` and not
648
- * `not-running`, and inventing one would have callers act on a status the
649
- * platform never reported. Callers that must tolerate it say so explicitly
650
- * (the stale-turn-lock policy documents "a throw is treated as unreachable").
651
- */
652
- export declare function peekWorkspaceSandbox(shell: SandboxRuntimeConfig, options: {
653
- workspaceId: string;
654
- userId?: string;
655
- }): Promise<PeekWorkspaceSandboxOutcome>;
656
- /** Reuse a workspace sandbox, or remove its previous runtime before provisioning a replacement. */
657
- export declare function ensureWorkspaceSandbox(shell: SandboxRuntimeConfig, options: EnsureWorkspaceSandboxOptions): Promise<SandboxInstance>;
658
- /**
659
- * Reuse the workspace's running box if this isolate used it recently, or return
660
- * undefined. It never creates, resumes, restarts, replaces or deletes a box, so
661
- * a caller can run it without the provisioning lease that serializes those
662
- * steps (see `runForegroundSandboxSingleFlight`'s `reuse`); undefined means the
663
- * box needs one of them (or this isolate has no recent probe of it), and the
664
- * caller takes the lease and calls {@link ensureWorkspaceSandbox}.
665
- */
666
- export declare function reuseWorkspaceSandbox(shell: SandboxRuntimeConfig, options: EnsureWorkspaceSandboxOptions): Promise<SandboxInstance | undefined>;
667
- /** Extract a single element type from the array parameter of SandboxInstance's streamPrompt method */
668
- export type PromptInputPart = Extract<Parameters<SandboxInstance['streamPrompt']>[0], readonly unknown[]>[number];
669
- /** Build a single string combining conversation history and the current user message */
670
- export declare function flattenHistory(message: string, history?: Array<{
671
- role: 'user' | 'assistant';
672
- content: string;
673
- }>): string;
674
- /**
675
- * History-aware equivalent of flattenHistory for multimodal prompt parts: the
676
- * transcript is folded into the first text part (image/file parts carry no
677
- * text to prepend to) rather than replacing the message wholesale.
678
- */
679
- export declare function mergeHistoryIntoParts(parts: PromptInputPart[], history?: Array<{
680
- role: 'user' | 'assistant';
681
- content: string;
682
- }>): PromptInputPart[];
683
- /** Resolve conflicts and merge extra MCP profiles into the app tool MCP without overwriting existing keys */
684
- export declare function mergeExtraMcp(appToolMcp: Record<string, AgentProfileMcpServer>, baseProfileMcp: Record<string, AgentProfileMcpServer>, extra: Record<string, AgentProfileMcpServer> | undefined): Record<string, AgentProfileMcpServer>;
685
- /** Attach explicit effort through the portable model contract consumed by providers. */
686
- export declare function attachReasoningEffort(profile: AgentProfile, _harness: Harness, effort: 'auto' | ReasoningEffort | undefined): AgentProfile;
687
- export interface SandboxPromptTokenLimits {
688
- maxVisibleOutputTokens?: number;
689
- maxReasoningTokens?: number;
690
- maxTotalOutputTokens?: number;
691
- }
692
- /** Tighten the profile's provider-enforced token ceilings for one prompt. */
693
- export declare function applyPromptTokenLimits(profile: AgentProfile, limits: SandboxPromptTokenLimits): AgentProfile;
694
- /** Define options for configuring and controlling a streaming sandbox prompt session */
695
- export interface StreamSandboxPromptOptions {
696
- /** Complete server-owned profile for this turn. Skips the shell's default composer.
697
- * Credentials, admission, session identity, and interactions remain execution options.
698
- * Explicit turn selections override this profile; otherwise its model and harness win
699
- * over shell defaults. Never populate this field from an untrusted request body. */
700
- profile?: AgentProfile;
701
- sessionId?: string;
702
- executionId?: string;
703
- /** Stable idempotency key for one logical dispatch. Reuse it with the same
704
- * `sessionId` when a caller may retry the initial request. */
705
- turnId?: string;
706
- lastEventId?: string;
707
- systemPrompt?: string;
708
- model?: string;
709
- modelApiKey?: string;
710
- history?: Array<{
711
- role: 'user' | 'assistant';
712
- content: string;
713
- }>;
714
- harness?: Harness;
715
- effort?: 'auto' | ReasoningEffort;
716
- /** Provider-enforced visible answer ceiling for this turn. */
717
- maxOutputTokens?: number;
718
- /** Provider-enforced hidden reasoning ceiling for this turn. */
719
- maxReasoningTokens?: number;
720
- /** Provider-enforced combined answer and reasoning ceiling for this turn. */
721
- maxTotalOutputTokens?: number;
722
- appToolMcp?: Record<string, AgentProfileMcpServer>;
723
- baseProfileMcp?: Record<string, AgentProfileMcpServer>;
724
- extraMcp?: Record<string, AgentProfileMcpServer>;
725
- /** Runtime-owned MCP tools for this turn, outside the authored profile. */
726
- runtimeAttachments?: {
727
- mcp: Record<string, AgentProfileMcpServer>;
728
- };
729
- /** Per-turn secret values used by runtime attachments; never stored in the profile or sandbox environment. */
730
- runtimeSecrets?: Record<string, string>;
731
- /** Mark a backend prepared for a secret-isolated native session. The caller creates
732
- * that session and prepares its exact backend before dispatch. */
733
- secretProfileIsolation?: true;
734
- /** SDK-issued digest of the prepared public backend request. */
735
- expectedPublicProfileRequestDigest?: `sha256:${string}`;
736
- /** SDK-issued receipt for the prepared secret native profile revision. */
737
- expectedSecretProfileReceipt?: `hmac-sha256:${string}`;
738
- signal?: AbortSignal;
739
- timeoutMs?: number;
740
- /**
741
- * Execution time limit for this run, in milliseconds. Unset, the runtime
742
- * falls back to `timeoutMs`, then to its one-hour default, so a turn that
743
- * must run longer than an hour names it here. The runtime refuses a value
744
- * above its deployment maximum before the run starts. `timeoutMs` stays the
745
- * shorter first-output budget.
746
- */
747
- ttlMs?: number;
748
- requireVisibleAssistantOutput?: boolean;
749
- disallowQuestions?: boolean;
750
- interactions?: {
751
- question?: boolean;
752
- permission?: boolean;
753
- plan?: boolean;
754
- };
755
- detach?: boolean;
756
- onProfileResolved?: (fingerprint: ProfileFingerprint) => void;
757
- spend?: SandboxSpendHooks;
758
- /**
759
- * The turn's trace (`@tangle-network/agent-app/turn-trace`). Its id is sent as `traceId`, the
760
- * `x-tangle-trace-id` the Sandbox API, orchestrator, sidecar and the Router's dispatch rows all record, and
761
- * the stream is recorded as a `sandbox.prompt` span: the sidecar's first-text phases, the generation and
762
- * each tool the box agent ran. Omitted, the SDK mints a trace id the app does not keep.
763
- */
764
- trace?: TurnTrace;
765
- /** The span the prompt hangs from. Default: the trace's root. */
766
- traceParent?: TurnSpan;
767
- }
768
- /**
769
- * The small event shape consumed by agent-gateway's streaming adapters.
770
- *
771
- * Sandbox providers can add fields to their event payloads over time. This
772
- * adapter deliberately copies only the fields the gateway understands so
773
- * consumers do not each have to maintain a provider-to-gateway cast.
774
- */
775
- export interface SandboxStreamEvent {
776
- type?: string;
777
- data?: {
778
- part?: {
779
- type?: string;
780
- text?: string;
781
- };
782
- delta?: string;
783
- finalText?: string;
784
- code?: string;
785
- message?: string;
786
- details?: Record<string, unknown>;
787
- inputRequired?: {
788
- prompt?: string;
789
- };
790
- usage?: {
791
- inputTokens?: number;
792
- outputTokens?: number;
793
- reasoningTokens?: number;
794
- toolTokens?: number;
795
- toolCallCount?: number;
796
- providerCostUsd?: number;
797
- budgetEnforced?: boolean;
798
- };
799
- tool?: {
800
- name?: string;
801
- inputTokens?: number;
802
- outputTokens?: number;
803
- };
804
- reasoning?: {
805
- tokens?: number;
806
- };
807
- };
808
- }
809
- /** Normalize raw sandbox events for shared agent-gateway consumers. */
810
- export declare function adaptSandboxStream(events: AsyncIterable<unknown>): AsyncGenerator<SandboxStreamEvent>;
811
- /** Configuration needed to prepare a turn without provisioning a workspace. */
812
- export type SandboxPromptConfig = Pick<SandboxRuntimeConfig, 'provider' | 'deferProfileFiles' | 'promptBudget'> & Partial<Pick<SandboxRuntimeConfig, 'profile'>>;
813
- /** Prepare one effective backend for SDK dispatch or product-specific transport.
814
- * Supply a server-owned profile, or a shell composer for the default profile.
815
- * Reuse the returned backend for preflight and dispatch so they inspect identical configuration.
816
- */
817
- export declare function resolveSandboxPromptBackend(shell: SandboxPromptConfig, options: StreamSandboxPromptOptions, operation?: string): Promise<{
818
- model?: {
819
- model: string;
820
- provider: string;
821
- apiKey?: string;
822
- apiKeyEnv?: string;
823
- baseUrl?: string;
824
- } | undefined;
825
- type: Harness;
826
- profile: AgentProfile;
827
- runtimeAttachments?: {
828
- mcp: Record<string, AgentProfileMcpServer>;
829
- } | undefined;
830
- runtimeSecrets?: Record<string, string> | undefined;
831
- metadata?: {
832
- profileSecretIsolation: true;
833
- } | undefined;
834
- interactions?: {
835
- question?: boolean;
836
- permission?: boolean;
837
- plan?: boolean;
838
- } | undefined;
839
- }>;
840
- /**
841
- * How long a refused dispatch is resent. Shorter than the completion
842
- * Workflow's 10-minute wait for a dispatch to appear, so the request gives up
843
- * before that Workflow reports the dispatch missing.
844
- */
845
- export declare const SANDBOX_DISPATCH_TRANSIENT_DEADLINE_MS: number;
846
- /** Resolve and stream AI-generated responses from a sandboxed environment based on input messages and options */
847
- export declare function streamSandboxPrompt(shell: SandboxRuntimeConfig, box: SandboxInstance, message: string | PromptInputPart[], options?: StreamSandboxPromptOptions): AsyncGenerator<unknown>;
848
- /**
849
- * Aggregate a sandbox prompt event stream down to the turn's one final answer.
850
- *
851
- * Exported SEPARATELY from `runSandboxPrompt` because the aggregation is pure —
852
- * `AsyncIterable<event> -> string` — while the streaming half is not: a product
853
- * that mounts per-turn MCP servers or resolves its harness per workspace wraps
854
- * `streamSandboxPrompt` in its own generator. Binding this logic to one stream
855
- * function is exactly what pushed three products into forking the whole thing,
856
- * bug and all. Take this over a local copy no matter whose generator you drive.
857
- *
858
- * Two rules earn their keep, and both were learned from the naive version:
859
- *
860
- * - Text accumulates PER PART ID, never into one running buffer, so two
861
- * concurrent text parts cannot overwrite each other.
862
- * - A prompt echo is identified by CONTENT, never by arrival position. The
863
- * "skip whichever text part arrives first" shortcut is wrong on both sandbox
864
- * lanes: on the delta lane (`box.streamPrompt`, explicit deltas) the first
865
- * part is the answer's opening token, so the answer silently loses it; and
866
- * when the echo arrives AFTER the answer, the function returns the caller's
867
- * own prompt as the agent's reply. Both failures produce a plausible-looking
868
- * string, the worst shape for the unattended cron/judge turns this exists for.
869
- *
870
- * A blank-but-present `result.finalText` is ignored in favour of the streamed
871
- * text rather than overwriting a real answer with whitespace.
872
- *
873
- * @param events raw sandbox turn events, in order
874
- * @param message the prompt as handed to the stream, so an echo of it is dropped
875
- * @param history folded into the dispatched prompt by `streamSandboxPrompt`;
876
- * pass whatever was passed there, since the echo replays the FOLDED text
877
- */
878
- export declare function collectSandboxPromptText(events: AsyncIterable<unknown>, message: string | PromptInputPart[], history?: StreamSandboxPromptOptions['history']): Promise<string>;
879
- /**
880
- * Resolve a sandbox prompt by streaming it and aggregating the turn down to one
881
- * final string. The shell's profile / model / MCP resolution and severed-stream
882
- * fail-loud come from `streamSandboxPrompt`; the aggregation is
883
- * `collectSandboxPromptText`, which products driving their own generator should
884
- * import directly.
885
- */
886
- export declare function runSandboxPrompt(shell: SandboxRuntimeConfig, box: SandboxInstance, message: string | PromptInputPart[], options?: StreamSandboxPromptOptions): Promise<string>;
887
- /** Define permission levels for sandbox access and control */
888
- export type SandboxPermissionLevel = 'owner' | 'admin' | 'developer' | 'viewer';
889
- /** Map workspace roles to corresponding sandbox permission levels */
890
- export interface MemberSyncSeam {
891
- roleToSandboxRole: (workspaceRole: string) => SandboxPermissionLevel;
892
- }
893
- /** Resolve adding a user with a specific role to a sandbox and return the operation outcome */
894
- export declare function syncSandboxMemberAdd(box: SandboxInstance, seam: MemberSyncSeam, userId: string, role: string): Promise<Outcome<void>>;
895
- /** Remove a member from the sandbox while preserving their home directory and handle the outcome */
896
- export declare function syncSandboxMemberRemove(box: SandboxInstance, userId: string): Promise<Outcome<void>>;
897
- /** Synchronize a sandbox member's role by updating permissions based on the provided role mapping */
898
- export declare function syncSandboxMemberRole(box: SandboxInstance, seam: MemberSyncSeam, userId: string, role: string): Promise<Outcome<void>>;
899
- /**
900
- * Write-only secret port: create, replace, and delete a secret by name.
901
- *
902
- * There is no read method. The platform's secrets API returns names and
903
- * timestamps only — a stored value is never served back, it is injected into
904
- * the sandbox as an environment variable. A `get` here could only ever return
905
- * a value this process already held, so the port does not offer one.
906
- */
907
- export interface SecretStore {
908
- create: (name: string, value: string) => Promise<void>;
909
- update: (name: string, value: string) => Promise<void>;
910
- delete: (name: string) => Promise<void>;
911
- }
912
- /** Resolve a SecretStore interface using the provided SandboxRuntimeConfig shell */
913
- export declare function secretStoreFromClient(shell: SandboxRuntimeConfig): SecretStore;
914
- /** Resolve storing a secret by creating it, or replacing it when it exists */
915
- export declare function storeSecret(store: SecretStore, name: string, value: string): Promise<Outcome<void>>;
916
- /** Delete a secret by name from the given secret store and return the operation outcome */
917
- export declare function deleteSecret(store: SecretStore, name: string): Promise<Outcome<void>>;
918
- /** Represent a token with its expiration date and associated scope */
919
- export interface ScopedTokenResult {
920
- token: string;
921
- expiresAt: Date;
922
- scope: ScopedTokenScope;
923
- }
924
- /**
925
- * Mint a scoped token for an already-provisioned box (e.g. to hand a terminal
926
- * proxy a narrowed credential). Uses the SDK's native `box.mintScopedToken`,
927
- * which normalizes `expiresAt` to a Date — no hand-rolled wire call.
928
- */
929
- export declare function mintSandboxScopedToken(box: SandboxInstance, options: MintScopedTokenOptions): Promise<Outcome<ScopedTokenResult>>;
930
- /** Define options to manage deterministic session resumption and turn idempotency in sandboxed drive turns */
931
- export interface DriveSandboxTurnOptions extends StreamSandboxPromptOptions {
932
- /** Deterministic resume key — required. Every tick for the same logical turn
933
- * MUST reuse it so a crash + re-drive finds the in-flight session instead of
934
- * starting a second agent run. */
935
- sessionId: string;
936
- /** Wall-clock cap in ms from the session's start. A still-running session past
937
- * the cap is cancelled and reported `failed` — bounds an unattended run, such as
938
- * a turn stalled on an interactive question with no consumer. Omit for no cap. */
939
- wallCapMs?: number;
940
- }
941
- /** Resolve a sandbox turn by processing a message with given configuration and options */
942
- export declare function driveSandboxTurn(shell: SandboxRuntimeConfig, box: SandboxInstance, message: string | PromptInputPart[], options: DriveSandboxTurnOptions): Promise<Outcome<TurnDriveResult>>;
943
- /** Define transitions marking the start or finish of a sandbox step with associated details */
944
- export type SandboxStepTransition = {
945
- kind: 'step-start';
946
- } | {
947
- kind: 'step-finish';
948
- reason: string;
949
- severed: boolean;
950
- };
951
- /** Resolve the severed stream event to a corresponding sandbox step transition or null */
952
- export declare function classifySeveredStream(event: unknown): SandboxStepTransition | null;
953
- /** Determine if an event is a terminal prompt event with type 'result' or 'done */
954
- export declare function isTerminalPromptEvent(event: unknown): boolean;
955
- /** Resolve the interactive question text from a structured event or return null if none found */
956
- export declare function detectInteractiveQuestion(event: unknown): string | null;
957
11
  export * from './workspace-sandbox-manager';
958
12
  export * from './terminal-connection';
959
13
  export * from './prewarm';
@@ -965,3 +19,31 @@ export * from './foreground-single-flight';
965
19
  export * from './warm-lease';
966
20
  export * from './warm-lease-d1';
967
21
  export * from './escalation-speculator';
22
+ export { resolveSandboxClientCredentials } from './credentials';
23
+ export type { SandboxClientCredentials, SandboxCredentialEnvironment, ResolveSandboxClientCredentialsOptions, } from './credentials';
24
+ export { DEFAULT_SANDBOX_RESOURCES } from './configuration';
25
+ export type { SandboxResourceConfig, SandboxBuildContext, SandboxScope, SandboxRestoreSpec, StoppedSandboxResumeFailure, MissingSandboxFailure, StoppedSandboxResumeRecovery, LivenessProbeConfig, ProfileComposeOptions, SandboxRuntimeConfig, EnsureWorkspaceSandboxOptions, SandboxProvisionedObservation, SandboxSpendHooks, } from './configuration';
26
+ export { PYPI_EGRESS_DOMAINS, buildProductEgressPolicy } from './product-egress';
27
+ export { dropTrustedBox, getClient, resetClientCache } from './runtime-cache';
28
+ export { buildAppToolMcpServers, sandboxToolRootDir, sandboxToolBinDir, sandboxToolPath, buildSandboxToolFileMounts, buildSandboxToolBinDirsEnv, buildSandboxToolBinDirScript, buildSandboxToolPathSetupScript, ensureSandboxToolBinDir, runSandboxToolPathSetup, } from './app-tools';
29
+ export type { AppToolDescriptor, BuildAppToolMcpServersOptions, SandboxToolSpec, SandboxToolPathOptions, BuildSandboxToolFileMountsOptions, } from './app-tools';
30
+ export { splitDeferredProfileFiles, writeProfileFilesToBox } from './profile-files';
31
+ export type { WriteProfileFilesOptions } from './profile-files';
32
+ export { SandboxEgressPolicyMismatchError, SandboxRuntimeAuthRefreshError, SandboxRecoveryFailedError, SandboxBoxBusyError, } from './lifecycle-errors';
33
+ export type { SandboxExistingBoxStage, SandboxEgressPolicySource, SandboxRecoveryPhase } from './lifecycle-errors';
34
+ export { deferredCorpusHash } from './profile-corpus';
35
+ export { PROVISION_PAYLOAD_MAX_BYTES, ENV_VALUE_MAX_BYTES, DEFAULT_PROVISION_TIMEOUT_MS, ENV_TOTAL_MAX_BYTES, assertProvisionPayloadWithinCap, assertEnvWithinLimits, } from './payload-limits';
36
+ export type { ProvisionProfileSection, ProvisionPayloadSections } from './payload-limits';
37
+ export { peekWorkspaceSandbox } from './workspace-boxes';
38
+ export type { PeekWorkspaceSandboxOutcome } from './workspace-boxes';
39
+ export { ensureWorkspaceSandbox, reuseWorkspaceSandbox } from './workspace-claim';
40
+ export { flattenHistory, mergeHistoryIntoParts, mergeExtraMcp, attachReasoningEffort, applyPromptTokenLimits, resolveSandboxPromptBackend, } from './prompt-profile';
41
+ export type { PromptInputPart, SandboxPromptTokenLimits, SandboxPromptConfig } from './prompt-profile';
42
+ export type { StreamSandboxPromptOptions } from './prompt-options';
43
+ export { adaptSandboxStream, classifySeveredStream, isTerminalPromptEvent, detectInteractiveQuestion, } from './prompt-events';
44
+ export type { SandboxStreamEvent, SandboxStepTransition } from './prompt-events';
45
+ export { SANDBOX_DISPATCH_TRANSIENT_DEADLINE_MS, streamSandboxPrompt } from './prompt-dispatch';
46
+ export { collectSandboxPromptText, runSandboxPrompt, driveSandboxTurn } from './prompt-result';
47
+ export type { DriveSandboxTurnOptions } from './prompt-result';
48
+ export { syncSandboxMemberAdd, syncSandboxMemberRemove, syncSandboxMemberRole, secretStoreFromClient, storeSecret, deleteSecret, mintSandboxScopedToken, } from './access';
49
+ export type { SandboxPermissionLevel, MemberSyncSeam, SecretStore, ScopedTokenResult } from './access';