import { SandboxInstance, AgentProfileMcpServer, ProvisionEvent, AgentProfileFileMount, AgentProfile, StorageConfig, ScopedTokenScope, TurnDriveResult, Sandbox } from '@tangle-network/sandbox';
export { StorageConfig } from '@tangle-network/sandbox';
import { T as ToolHeaderNames } from '../auth-anc7mv2W.js';
import { b as AppToolName, a as AppToolContext } from '../types-BCxK0wyS.js';
import { Harness } from '../harness/index.js';
import { a as TangleExecutionEnvironment } from '../model-CdCDfBA9.js';
import { b as ProfileFingerprint, C as ComposeProfileBudget } from '../budget-BOucfcb_.js';
import '@tangle-network/agent-interface';

/** Represent success or failure of an operation with corresponding value or error information */
type Outcome<T> = {
    succeeded: true;
    value: T;
} | {
    succeeded: false;
    error: Error;
};

/**
 * Reading arbitrary bytes out of a sandbox over an exec channel that only
 * speaks text.
 *
 * `box.exec` returns stdout as a string, so a binary file has to be encoded to
 * survive the trip: `wc -c` gives the on-disk length, `base64` gives the
 * payload, and the decoded byte count is checked against the stat. That last
 * check is the point of the module — an exec channel that caps or clips its
 * output still reports `exitCode: 0` with a short buffer, which decodes into a
 * perfectly valid but TRUNCATED file. Verifying the length turns that silent
 * corruption into a loud failure at the boundary.
 *
 * Both helpers return typed outcomes; callers must inspect `succeeded` before
 * touching `value`.
 */
/** The `box.exec` surface these helpers use — structural, so a caller can pass
 *  the sandbox SDK's `SandboxInstance` directly or a narrower test double. */
interface SandboxExecChannel {
    exec(command: string, options?: {
        sessionId?: string;
    }): Promise<{
        stdout: string;
        stderr: string;
        exitCode: number;
    }>;
}
/** Define options to execute code within a sandbox environment with optional session control */
interface SandboxExecOptions {
    /** Run inside a named session rather than the box's default one. */
    sessionId?: string;
}
/** Resolve the outcome of a sandbox file size check with success status and value or error message */
type SandboxFileSizeOutcome = {
    succeeded: true;
    value: number;
} | {
    succeeded: false;
    error: string;
};
/** Represent the outcome of reading sandbox file bytes with success status and corresponding data or error */
type SandboxFileBytesOutcome = {
    succeeded: true;
    value: {
        bytes: Uint8Array;
        size: number;
    };
} | {
    succeeded: false;
    error: string;
};
/** Wraps a value in single quotes for `sh`, closing and reopening the quote
 *  around each embedded quote (`'` → `'"'"'`). Every path these helpers
 *  interpolate into a command goes through this — in-box filenames are
 *  arbitrary, so spaces, quotes and `$` are ordinary content, not syntax. */
declare function shellQuote(value: string): string;
/** Stats a sandbox file's byte length via `wc -c`. A caller enforcing a size
 *  cap must check this BEFORE {@link readSandboxBinaryBytes}, so an oversize
 *  file is rejected without paying for a base64 round trip of it. */
declare function statSandboxFileSize(box: SandboxExecChannel, absolutePath: string, options?: SandboxExecOptions): Promise<SandboxFileSizeOutcome>;
/** Reads a sandbox file as base64 and decodes it, verifying the decoded byte
 *  length against `expectedSize` (from a prior {@link statSandboxFileSize}). A
 *  mismatch is reported, never returned as a short buffer. */
declare function readSandboxBinaryBytes(box: SandboxExecChannel, absolutePath: string, expectedSize: number, options?: SandboxExecOptions): Promise<SandboxFileBytesOutcome>;

/** Define identity details for a terminal proxy including user, workspace, and sandbox identifiers */
interface TerminalProxyIdentity {
    userId: string;
    workspaceId: string;
    sandboxId: string;
}
/** Generate a signed token for TerminalProxyIdentity with an expiration based on TTL milliseconds */
declare function mintTerminalProxyToken(secret: string, identity: TerminalProxyIdentity, ttlMs?: number, now?: () => number): Promise<Outcome<{
    token: string;
    expiresAt: Date;
}>>;
/** Verify the authenticity and validity of a terminal proxy token against expected identity and timestamp */
declare function verifyTerminalProxyToken(secret: string, token: string, expected: TerminalProxyIdentity, now?: () => number): Promise<boolean>;

/** Define the shape of a workspace sandbox instance including its connection details and status */
interface WorkspaceSandboxInstanceLike {
    id: string;
    name?: string;
    status?: string;
    connection?: {
        runtimeUrl?: string;
        sidecarUrl?: string;
        authToken?: string;
        sidecarToken?: string;
        authTokenExpiresAt?: string;
    } | null;
}
/** Define the context containing workspace and user identifiers for sandbox environment operations */
interface WorkspaceSandboxEnsureContext {
    workspaceId: string;
    userId: string;
}
/** Define configuration options for managing and interacting with workspace sandboxes */
interface WorkspaceSandboxManagerOptions<TClient, TBox extends WorkspaceSandboxInstanceLike, TEnsureOptions = void> {
    getClient: (ctx: WorkspaceSandboxEnsureContext) => Promise<TClient> | TClient;
    nameForWorkspace: (workspaceId: string, ctx: WorkspaceSandboxEnsureContext) => string;
    listSandboxes: (client: TClient, ctx: WorkspaceSandboxEnsureContext) => Promise<TBox[]>;
    createSandbox: (args: {
        client: TClient;
        ctx: WorkspaceSandboxEnsureContext;
        name: string;
        options: TEnsureOptions;
        listError?: unknown;
    }) => Promise<TBox>;
    waitForRunning?: (box: TBox, ctx: WorkspaceSandboxEnsureContext) => Promise<void>;
    prepareExisting?: (box: TBox, ctx: WorkspaceSandboxEnsureContext, options: TEnsureOptions) => Promise<TBox | void>;
    prepareCreated?: (box: TBox, ctx: WorkspaceSandboxEnsureContext, options: TEnsureOptions) => Promise<TBox | void>;
    onListError?: (error: unknown, ctx: WorkspaceSandboxEnsureContext) => void;
}
/** Manage workspace sandboxes by ensuring their creation and retrieval for specified users */
interface WorkspaceSandboxManager<TBox extends WorkspaceSandboxInstanceLike, TEnsureOptions = void> {
    ensureWorkspaceSandbox: (workspaceId: string, userId: string, options?: TEnsureOptions) => Promise<TBox>;
}
/** Create a manager to handle workspace sandbox instances with client and options configuration */
declare function createWorkspaceSandboxManager<TClient, TBox extends WorkspaceSandboxInstanceLike, TEnsureOptions = void>(opts: WorkspaceSandboxManagerOptions<TClient, TBox, TEnsureOptions>): WorkspaceSandboxManager<TBox, TEnsureOptions>;
/** Define options for generating a sandbox terminal token including secret and expiration settings */
interface SandboxTerminalTokenOptions {
    secret?: string;
    expiresInMs?: number;
    now?: () => number;
}
/** Resolve the identity type used for sandbox terminal token subjects */
type SandboxTerminalTokenSubject = TerminalProxyIdentity;
/** Provide token and expiration details for a sandbox terminal session */
interface SandboxTerminalTokenResult {
    token: string;
    expiresAt: Date;
}
/** Generate a sandbox terminal token for a given subject with specified options */
declare function createSandboxTerminalToken(subject: SandboxTerminalTokenSubject, opts: SandboxTerminalTokenOptions): Promise<SandboxTerminalTokenResult>;
/** Verify the validity of a sandbox terminal token against the expected identity and options */
declare function verifySandboxTerminalToken(token: string, expected: SandboxTerminalTokenSubject, opts: SandboxTerminalTokenOptions): Promise<boolean>;
/** Represent an authenticated user within a sandbox environment with a unique identifier */
interface AuthenticatedSandboxUser {
    id: string;
}
/** Define options to handle workspace sandbox connections with user authentication and access control */
interface WorkspaceSandboxConnectionHandlerOptions<TBox extends WorkspaceSandboxInstanceLike> {
    requireUser: (request: Request) => Promise<AuthenticatedSandboxUser>;
    requireWorkspaceAccess: (args: {
        request: Request;
        userId: string;
        workspaceId: string;
    }) => Promise<void>;
    ensureWorkspaceSandbox: (workspaceId: string, userId: string) => Promise<TBox>;
    tokenSecret: string | (() => string | undefined);
    tokenExpiresInMs?: number;
    proxyRuntimeUrl?: (args: {
        request: Request;
        workspaceId: string;
        sandboxId: string;
        box: TBox;
    }) => string;
    exposeDirectSidecar?: boolean;
}
/** Define arguments required to establish a workspace sandbox connection */
interface WorkspaceSandboxConnectionArgs {
    request: Request;
    params: {
        workspaceId?: string;
    };
}
/** Create a handler to resolve workspace sandbox connections with user and access validation */
declare function createWorkspaceSandboxConnectionHandler<TBox extends WorkspaceSandboxInstanceLike>(opts: WorkspaceSandboxConnectionHandlerOptions<TBox>): ({ request, params }: WorkspaceSandboxConnectionArgs) => Promise<Response>;
/** Define credentials required to access the sandbox API environment */
interface SandboxApiCredentials {
    baseUrl: string;
    apiKey: string;
}
/** Define a connection configuration for sandbox runtime including URL and optional server-side auth token */
interface SandboxRuntimeConnection {
    runtimeUrl: string;
    /** Server-side sidecar bearer. Must authorize terminal routes; never expose it to browser code. */
    authToken?: string;
}
/** Define options for handling workspace sandbox runtime proxy including user, access, credentials, and connection retrieval */
interface WorkspaceSandboxRuntimeProxyHandlerOptions {
    requireUser: (request: Request) => Promise<AuthenticatedSandboxUser>;
    requireWorkspaceAccess: (args: {
        request: Request;
        userId: string;
        workspaceId: string;
        sandboxId: string;
    }) => Promise<void>;
    getSandboxApiCredentials: (args: {
        request: Request;
        userId: string;
        workspaceId: string;
        sandboxId: string;
    }) => Promise<SandboxApiCredentials>;
    getSandboxRuntimeConnection?: (args: {
        request: Request;
        userId: string;
        workspaceId: string;
        sandboxId: string;
    }) => Promise<SandboxRuntimeConnection | null | undefined>;
    tokenSecret: string | (() => string | undefined);
    fetch?: typeof fetch;
    forwardHeaders?: string[];
}
/** Define arguments for proxying runtime requests within a workspace sandbox environment */
interface WorkspaceSandboxRuntimeProxyArgs {
    request: Request;
    params: {
        workspaceId?: string;
        sandboxId?: string;
        '*'?: string;
    };
}
/** Create a proxy handler to resolve sandbox runtime requests with user and workspace access validation */
declare function createWorkspaceSandboxRuntimeProxyHandler(opts: WorkspaceSandboxRuntimeProxyHandlerOptions): ({ request, params }: WorkspaceSandboxRuntimeProxyArgs) => Promise<Response>;
/** Define the structure for matching a sandbox terminal WebSocket with workspace and path details */
interface SandboxTerminalWsMatch {
    workspaceId: string;
    sandboxId: string;
    subPath: string;
}
/**
 * Parse a same-origin terminal-WS pathname into its parts, or `null` when the
 * path is not a sandbox terminal WebSocket. Matches the default `runtimeUrl`
 * convention emitted by {@link createWorkspaceSandboxConnectionHandler}
 * (`/api/workspaces/:workspaceId/sandbox/runtime/:sandboxId`) with a canonical
 * `terminals/:id/ws` sub-path. `subPath` is left URL-encoded for re-use in the
 * upstream URL; the ids are decoded for auth checks.
 */
declare function matchSandboxTerminalWsPath(pathname: string): SandboxTerminalWsMatch | null;
/** True when `request` is a WebSocket upgrade for a sandbox terminal path. */
declare function isSandboxTerminalWsUpgrade(request: Request): boolean;
/** Define options to handle user authentication, workspace access, and sandbox API credential retrieval */
interface WorkspaceSandboxTerminalUpgradeHandlerOptions {
    requireUser: (request: Request) => Promise<AuthenticatedSandboxUser>;
    requireWorkspaceAccess: (args: {
        request: Request;
        userId: string;
        workspaceId: string;
        sandboxId: string;
    }) => Promise<void>;
    getSandboxApiCredentials: (args: {
        request: Request;
        userId: string;
        workspaceId: string;
        sandboxId: string;
    }) => Promise<SandboxApiCredentials>;
    getSandboxRuntimeConnection?: (args: {
        request: Request;
        userId: string;
        workspaceId: string;
        sandboxId: string;
    }) => Promise<SandboxRuntimeConnection | null | undefined>;
    tokenSecret: string | (() => string | undefined);
    fetch?: typeof fetch;
}
/**
 * Build a Worker-entry handler that proxies a sandbox terminal WebSocket
 * upgrade to the sandbox API runtime proxy. Returns `null` when the request is
 * not a terminal WS upgrade, so the caller can fall through to its normal
 * request handler:
 *
 * ```ts
 * const handled = await handleSandboxTerminalUpgrade(request)
 * if (handled) return handled
 * ```
 */
declare function createWorkspaceSandboxTerminalUpgradeHandler(opts: WorkspaceSandboxTerminalUpgradeHandlerOptions): (request: Request) => Promise<Response | null>;
/** Build proxy headers for sandbox runtime including authorization and forwarded headers */
declare function buildSandboxRuntimeProxyHeaders(source: Headers, sandboxApiKey: string, forwardHeaders?: string[]): Headers;
/** Encode a runtime path by URI-encoding each valid segment and returning null for invalid segments */
declare function encodeSandboxRuntimePath(runtimePath: string): string | null;
/** Extract the token from a bearer authorization string or return null if invalid or missing */
declare function bearerToken(value: string | null): string | null;
/** Resolve and decode a bearer token from a comma-separated subprotocol string or return null */
declare function bearerSubprotocolToken(value: string | null): string | null;
/** Resolve the terminal token from request headers using Authorization or Sec-WebSocket-Protocol fields */
declare function terminalTokenFromRequest(headers: Headers): string | null;

/** Define client credentials for accessing the sandbox environment with API key and base URL */
interface SandboxClientCredentials {
    apiKey: string;
    baseUrl: string;
}
/**
 * Sandbox credential policy reuses the canonical execution-environment union
 * (development/test/staging/production) so env classification stays in one place
 * (see resolveTangleExecutionEnvironment in runtime/model).
 */
type SandboxCredentialEnvironment = TangleExecutionEnvironment;
/** Resolve options for obtaining sandbox client credentials from environment variables and classification */
interface ResolveSandboxClientCredentialsOptions {
    /**
     * Environment object to read from. Defaults to process.env when available.
     */
    env?: Record<string, string | undefined>;
    /**
     * Explicit environment classification. Defaults to APP_ENV/NODE_ENV derived
     * behavior: local/development/test use direct env credentials; staging/prod
     * require the provision callback unless allowDirectEnvCredentials opts in.
     */
    environment?: SandboxCredentialEnvironment;
    /**
     * Env names that may carry a sandbox-compatible bearer. The first non-empty
     * value wins when direct env credentials are allowed.
     */
    directKeyNames?: readonly string[];
    /**
     * Env names that may carry the sandbox gateway URL. The first non-empty value
     * wins, then defaultBaseUrl.
     */
    baseUrlNames?: readonly string[];
    /**
     * Base URL used when none of baseUrlNames are present.
     */
    defaultBaseUrl?: string;
    /**
     * Whether direct env credentials are allowed for this environment. Defaults
     * to true in development/test and false in staging/production.
     */
    allowDirectEnvCredentials?: boolean | ((environment: SandboxCredentialEnvironment) => boolean);
    /**
     * Product-owned provision path, usually minting a per-user sandbox key from a
     * linked platform account. Called before direct env credentials in
     * staging/production and after direct env credentials in development/test.
     */
    provision?: (context: {
        environment: SandboxCredentialEnvironment;
        env: Record<string, string | undefined>;
    }) => SandboxClientCredentials | null | undefined | Promise<SandboxClientCredentials | null | undefined>;
}
/** Resolve sandbox client credentials based on environment and provided options asynchronously */
declare function resolveSandboxClientCredentials(options?: ResolveSandboxClientCredentialsOptions): Promise<SandboxClientCredentials>;
/** Define configuration parameters for sandbox resource allocation and lifecycle management */
interface SandboxResourceConfig {
    image: string;
    cpuCores: number;
    memoryMB: number;
    diskGB: number;
    maxLifetimeSeconds: number;
    idleTimeoutSeconds: number;
}
/** Define configuration options for resolving a provider and its model with optional API keys and routing details */
interface ProviderResolutionConfig {
    routerBaseUrl?: string;
    apiKey?: string;
    providerName?: string;
    modelName?: string;
    defaultModel?: string;
    openaiApiKey?: string;
    allowKeylessModel?: boolean;
}
/** Define the context for building a sandbox including workspace, integrations, and optional user ID */
interface SandboxBuildContext {
    workspaceId: string;
    connectedIntegrationIds: string[];
    userId?: string;
}

/** Define a scope containing workspace and optional user identifiers for sandbox environments */
interface SandboxScope {
    workspaceId: string;
    userId?: string;
}
/** Define the specification for restoring a sandbox from a snapshot or another sandbox ID */
interface SandboxRestoreSpec {
    fromSnapshot: string;
    fromSandboxId: string;
}
/** Describe the failure details when resuming a stopped sandbox instance */
interface StoppedSandboxResumeFailure {
    box: SandboxInstance;
    error: Error;
    scope: SandboxScope;
    boxKey: string;
}
/** Define the structure for resuming a stopped sandbox with replacement key and optional restore options */
interface StoppedSandboxResumeRecovery {
    replacementBoxKey: string;
    restore?: SandboxRestoreSpec | null;
}
/** Define configuration for liveness probes including sidecar process pattern and optional timeouts */
interface LivenessProbeConfig {
    sidecarProcessPattern: (harness: Harness) => string;
    execTimeoutMs?: number;
    psTimeoutMs?: number;
}
/** Define options for composing a user profile including prompts, files, servers, and name */
interface ProfileComposeOptions {
    systemPrompt?: string;
    extraFiles?: AgentProfileFileMount[];
    extraMcp?: Record<string, AgentProfileMcpServer>;
    name?: string;
    /**
     * The harness this profile is being composed for.
     *
     * Where a resource lands is harness-specific — skills resolve to
     * `.opencode/skills/`, `.claude/skills/`, `.pi/skills/`, and so on
     * (`skillDirForHarness`), and some harnesses take no cwd skills at all.
     * Without this, an app composing a profile cannot place a harness-native
     * resource and is pushed into hardcoding one harness's path, which then
     * silently disagrees with the path its own prompt cites: the agent is told
     * to read a directory nothing was written to and its skills are invisible.
     * Prefer declaring `resources.skills` and letting the platform place them;
     * use this when composing paths directly.
     */
    harness: Harness;
}
/** Define runtime configuration methods for sandbox environments including credentials, metadata, and permissions */
interface SandboxRuntimeConfig {
    credentials: (scope?: SandboxScope) => SandboxClientCredentials | null | Promise<SandboxClientCredentials | null>;
    name: (workspaceId: string) => string;
    metadata: (harness: Harness) => Record<string, unknown>;
    connectedIntegrationIds: (workspaceId: string) => Promise<string[]>;
    env: (ctx: SandboxBuildContext) => Promise<Record<string, string>>;
    files: (ctx: SandboxBuildContext) => Promise<AgentProfileFileMount[]>;
    secrets: (workspaceId: string) => Promise<string[]>;
    profile: (options: ProfileComposeOptions) => AgentProfile;
    permissionRole?: (workspaceRole: string) => SandboxPermissionLevel;
    resources?: SandboxResourceConfig;
    provider?: ProviderResolutionConfig;
    storage?: (ctx: SandboxBuildContext) => StorageConfig | undefined;
    restore?: (ctx: SandboxBuildContext) => SandboxRestoreSpec | undefined;
    boxKey?: (scope: SandboxScope) => string;
    childKeyMint?: (scope: SandboxScope) => Promise<Outcome<string>>;
    bootstrap?: (box: SandboxInstance, scope: SandboxScope) => Promise<Outcome<void>>;
    livenessProbe?: LivenessProbeConfig;
    webTerminalEnabled?: boolean;
    resumeStopped?: boolean;
    recoverStoppedSandbox?: (failure: StoppedSandboxResumeFailure) => Promise<Outcome<StoppedSandboxResumeRecovery | null>>;
    backendModelAtCreate?: boolean;
    deferProfileFiles?: boolean;
    promptBudget?: ComposeProfileBudget;
}
/** Define default resource limits and settings for sandbox environments */
declare const DEFAULT_SANDBOX_RESOURCES: SandboxResourceConfig;
/** Resolve a synchronous sandbox client from provided runtime configuration credentials */
declare function getClient(shell: SandboxRuntimeConfig): Sandbox;
/** Reset the client cache to clear stored data and force fresh retrieval */
declare function resetClientCache(): void;
/** Describe an application tool with its name, unique key, and description */
interface AppToolDescriptor {
    tool: AppToolName;
    key: string;
    description: string;
}
/** Define options for building MCP server configurations in the app tool environment */
interface BuildAppToolMcpServersOptions {
    tools: AppToolDescriptor[];
    baseUrl: string;
    token: string;
    ctx: AppToolContext;
    headerNames?: ToolHeaderNames;
}
/** Build a mapping of MCP server profiles keyed by tool identifiers from provided options */
declare function buildAppToolMcpServers(options: BuildAppToolMcpServersOptions): Record<string, AgentProfileMcpServer>;
/** Define options for ensuring a workspace sandbox with provisioning and progress handling */
interface EnsureWorkspaceSandboxOptions {
    workspaceId: string;
    userId?: string;
    harness: Harness;
    forceNew?: boolean;
    onProgress?: (event: ProvisionEvent) => void;
    billingOwnerId?: string;
}
/** Define the specification for a sandbox tool including its name, content, and optional executability */
interface SandboxToolSpec {
    name: string;
    content: string;
    executable?: boolean;
}
/** Define options for resolving sandbox tool paths including appName, baseDir, and binDir */
interface SandboxToolPathOptions {
    appName: string;
    baseDir?: string;
    binDir?: string;
}
/** Define options for building sandbox tool file mounts including tool specifications and paths */
interface BuildSandboxToolFileMountsOptions extends SandboxToolPathOptions {
    tools: readonly SandboxToolSpec[];
}
/** Resolve the root directory path for a sandbox tool based on provided options */
declare function sandboxToolRootDir(options: SandboxToolPathOptions): string;
/** Resolve the binary directory path for a sandbox tool based on provided options */
declare function sandboxToolBinDir(options: SandboxToolPathOptions): string;
/** Resolve the file system path to a specified sandbox tool based on given options */
declare function sandboxToolPath(options: SandboxToolPathOptions & {
    toolName: string;
}): string;
/** Build file mounts for sandbox tools based on provided options and tool configurations */
declare function buildSandboxToolFileMounts(options: BuildSandboxToolFileMountsOptions): AgentProfileFileMount[];
/** Build a shell script that sets up and exports the sandbox tool binary directory in user profiles */
declare function buildSandboxToolPathSetupScript(options: SandboxToolPathOptions): string;
/** Resolve the sandbox environment PATH setup by executing the configuration script with given options */
declare function runSandboxToolPathSetup(box: SandboxInstance, options: SandboxToolPathOptions): Promise<Outcome<void>>;
/** Split profile files into inline deferred files and a lean profile without them */
declare function splitDeferredProfileFiles(profile: AgentProfile): {
    leanProfile: AgentProfile;
    deferredFiles: AgentProfileFileMount[];
};
type ExistingBoxStage = 'reused' | 'resumed';
/** Represent an error thrown when sandbox runtime authentication refresh fails for a specific stage and name */
declare class SandboxRuntimeAuthRefreshError extends Error {
    constructor(stage: ExistingBoxStage, name: string, detail: string, cause?: unknown);
}
/** Define options to control execution timeout, pacing, and retry behavior when writing profile files */
interface WriteProfileFilesOptions {
    execTimeoutMs?: number;
    paceMs?: number;
    maxRetries?: number;
}
/** Write profile files to a sandbox with pacing, retries, and optional execution timeout handling */
declare function writeProfileFilesToBox(box: SandboxInstance, files: AgentProfileFileMount[], options?: WriteProfileFilesOptions): Promise<Outcome<void>>;
/** Stable content hash of the deferred file corpus (path + inline content).
 *  Unchanged corpus ⇒ same hash; a new/edited/removed skill ⇒ different hash.
 *  Exported for the reuse-skip test. */
declare function deferredCorpusHash(files: AgentProfileFileMount[]): string;
/** Gate on the provision body: the platform orchestrator caps the create
 *  payload at 256 KiB; 240 KB leaves headroom for transport framing. An
 *  over-cap payload fails provisioning 100% of the time (a 282 KB payload
 *  shipped once and no sandbox could ever be created). */
declare const PROVISION_PAYLOAD_MAX_BYTES = 240000;
/** Per-variable env gate: the kernel rejects any single `NAME=value` env entry
 *  over MAX_ARG_STRLEN (131072 bytes) with E2BIG, killing every exec inside
 *  the box. 120 KB leaves headroom for the name and framing. */
declare const ENV_VALUE_MAX_BYTES = 120000;
/** Total env gate: the whole environment block shares the payload budget with
 *  the profile; past 200 KB the provision body cannot stay under the cap. */
declare const ENV_TOTAL_MAX_BYTES = 200000;
/** Structural slice of the profile the payload gate reads: it only measures
 *  the profile's serialized size and names `resources.files` in the breakdown,
 *  so callers composing a payload outside the SDK (products, tests) can pass a
 *  plain object without casting through `AgentProfile`. */
interface ProvisionProfileSection {
    resources?: {
        files?: readonly unknown[];
    };
}
/** The provision-payload sections the size gates need to see. Structural so
 *  the gate is testable without the SDK's (unexported) create-payload type. */
interface ProvisionPayloadSections {
    env?: Record<string, string>;
    secrets?: readonly string[];
    /** `profile` may also be a named-profile string ref (the SDK's
     *  `BackendConfig` union) — a string ref is tiny and has no files channel. */
    backend?: {
        profile?: string | ProvisionProfileSection;
    };
}
/**
 * Throw when the serialized provision payload exceeds
 * {@link PROVISION_PAYLOAD_MAX_BYTES}. The error carries a per-section byte
 * breakdown (profile/files/env/secrets) so the offending channel is named, not
 * guessed.
 */
declare function assertProvisionPayloadWithinCap(payload: ProvisionPayloadSections): void;
/**
 * Throw when any single env value exceeds {@link ENV_VALUE_MAX_BYTES} or the
 * whole env block exceeds {@link ENV_TOTAL_MAX_BYTES}, naming the offending
 * variable. This is the E2BIG incident class: the box may even provision, but
 * every exec inside it dies on the oversized entry.
 */
declare function assertEnvWithinLimits(env: Record<string, string>): void;
/** What a peek can find. `not-running` carries the platform's own state string
 *  (`stopped`, `starting`, `failed`, …) — narrowing it to a union here would
 *  drop states the platform adds later, and every caller wants it for a log. */
type PeekWorkspaceSandboxOutcome = {
    status: 'running';
    box: SandboxInstance;
} | {
    status: 'not-running';
    state: string;
    box: SandboxInstance;
} | {
    status: 'absent';
};
/**
 * Read-only twin of {@link ensureWorkspaceSandbox}: report whether a
 * workspace's box exists and is running, WITHOUT provisioning, resuming, or
 * bootstrapping anything.
 *
 * This is what a read-mostly path needs — a file-index route's `authorize`
 * seam, a stale-lock reconciliation, a status badge. Calling `ensure` from one
 * of those spins a box up as a side effect of a read (legal-agent #509), and
 * costs the caller a cold start it never asked for.
 *
 * Matching is on BOTH the box key and the display name, IN THAT ORDER.
 * `client.get(id)` keys on the platform's opaque sandbox id, not the
 * deterministic key a product derives from a workspace, and is itself a
 * `list().find` underneath — so a lookup by identity has to list and match.
 * Provisioning here always stamps `name` with the box key, so the key is the
 * authoritative match; the display-name pass exists only to adopt boxes on a
 * host that predates that convention. The order matters: a single unordered
 * `find` returns whichever the platform happens to list first, so a stopped
 * display-name box could shadow a running box-key one and report
 * `not-running` for a live workspace.
 *
 * Unlike `ensure`, this lists ALL statuses in one call: distinguishing "no box"
 * from "box is stopped" is the whole point, and a status-filtered list cannot.
 *
 * A `client.list()` rejection propagates RAW, unlike the `Outcome`-wrapping
 * helpers `ensure` uses internally. That is deliberate: there is no honest
 * outcome to map a listing failure onto — it is not `absent` and not
 * `not-running`, and inventing one would have callers act on a status the
 * platform never reported. Callers that must tolerate it say so explicitly
 * (the stale-turn-lock policy documents "a throw is treated as unreachable").
 */
declare function peekWorkspaceSandbox(shell: SandboxRuntimeConfig, options: {
    workspaceId: string;
    userId?: string;
}): Promise<PeekWorkspaceSandboxOutcome>;
/** Resolve or create a workspace sandbox instance with optional reuse and progress tracking */
declare function ensureWorkspaceSandbox(shell: SandboxRuntimeConfig, options: EnsureWorkspaceSandboxOptions): Promise<SandboxInstance>;
/** Represent a fully configured model with optional API key and base URL for sandbox platform integration */
interface ResolvedModel {
    model: string;
    provider: string;
    apiKey?: string;
    baseUrl?: string;
}
/** Resolve and return the appropriate model configuration based on provider settings and optional overrides */
declare function resolveModel(config: ProviderResolutionConfig | undefined, override?: {
    model?: string;
    modelApiKey?: string;
}): ResolvedModel | undefined;
/** Extract a single element type from the array parameter of SandboxInstance's streamPrompt method */
type PromptInputPart = Extract<Parameters<SandboxInstance['streamPrompt']>[0], readonly unknown[]>[number];
/** Build a single string combining conversation history and the current user message */
declare function flattenHistory(message: string, history?: Array<{
    role: 'user' | 'assistant';
    content: string;
}>): string;
/**
 * History-aware equivalent of flattenHistory for multimodal prompt parts: the
 * transcript is folded into the first text part (image/file parts carry no
 * text to prepend to) rather than replacing the message wholesale.
 */
declare function mergeHistoryIntoParts(parts: PromptInputPart[], history?: Array<{
    role: 'user' | 'assistant';
    content: string;
}>): PromptInputPart[];
/** Resolve conflicts and merge extra MCP profiles into the app tool MCP without overwriting existing keys */
declare function mergeExtraMcp(appToolMcp: Record<string, AgentProfileMcpServer>, baseProfileMcp: Record<string, AgentProfileMcpServer>, extra: Record<string, AgentProfileMcpServer> | undefined): Record<string, AgentProfileMcpServer>;
/** Attach a specified reasoning effort level to an agent profile for a given harness */
declare function attachReasoningEffort(profile: AgentProfile, harness: Harness, effort: 'auto' | 'low' | 'medium' | 'high' | undefined): AgentProfile;
/** Define options for configuring and controlling a streaming sandbox prompt session */
interface StreamSandboxPromptOptions {
    sessionId?: string;
    executionId?: string;
    lastEventId?: string;
    systemPrompt?: string;
    model?: string;
    modelApiKey?: string;
    history?: Array<{
        role: 'user' | 'assistant';
        content: string;
    }>;
    harness?: Harness;
    effort?: 'auto' | 'low' | 'medium' | 'high';
    appToolMcp?: Record<string, AgentProfileMcpServer>;
    baseProfileMcp?: Record<string, AgentProfileMcpServer>;
    extraMcp?: Record<string, AgentProfileMcpServer>;
    signal?: AbortSignal;
    timeoutMs?: number;
    requireVisibleAssistantOutput?: boolean;
    disallowQuestions?: boolean;
    interactions?: {
        question?: boolean;
        permission?: boolean;
        plan?: boolean;
    };
    detach?: boolean;
    onProfileResolved?: (fingerprint: ProfileFingerprint) => void;
}
/** Resolve and stream AI-generated responses from a sandboxed environment based on input messages and options */
declare function streamSandboxPrompt(shell: SandboxRuntimeConfig, box: SandboxInstance, message: string | PromptInputPart[], options?: StreamSandboxPromptOptions): AsyncGenerator<unknown>;
/**
 * Aggregate a sandbox prompt event stream down to the turn's one final answer.
 *
 * Exported SEPARATELY from `runSandboxPrompt` because the aggregation is pure —
 * `AsyncIterable<event> -> string` — while the streaming half is not: a product
 * that mounts per-turn MCP servers or resolves its harness per workspace wraps
 * `streamSandboxPrompt` in its own generator. Binding this logic to one stream
 * function is exactly what pushed three products into forking the whole thing,
 * bug and all. Take this over a local copy no matter whose generator you drive.
 *
 * Two rules earn their keep, and both were learned from the naive version:
 *
 * - Text accumulates PER PART ID, never into one running buffer, so two
 *   concurrent text parts cannot overwrite each other.
 * - A prompt echo is identified by CONTENT, never by arrival position. The
 *   "skip whichever text part arrives first" shortcut is wrong on both sandbox
 *   lanes: on the delta lane (`box.streamPrompt`, explicit deltas) the first
 *   part is the answer's opening token, so the answer silently loses it; and
 *   when the echo arrives AFTER the answer, the function returns the caller's
 *   own prompt as the agent's reply. Both failures produce a plausible-looking
 *   string, the worst shape for the unattended cron/judge turns this exists for.
 *
 * A blank-but-present `result.finalText` is ignored in favour of the streamed
 * text rather than overwriting a real answer with whitespace.
 *
 * @param events raw sandbox turn events, in order
 * @param message the prompt as handed to the stream, so an echo of it is dropped
 * @param history folded into the dispatched prompt by `streamSandboxPrompt`;
 *        pass whatever was passed there, since the echo replays the FOLDED text
 */
declare function collectSandboxPromptText(events: AsyncIterable<unknown>, message: string | PromptInputPart[], history?: StreamSandboxPromptOptions['history']): Promise<string>;
/**
 * Resolve a sandbox prompt by streaming it and aggregating the turn down to one
 * final string. The shell's profile / model / MCP resolution and severed-stream
 * fail-loud come from `streamSandboxPrompt`; the aggregation is
 * `collectSandboxPromptText`, which products driving their own generator should
 * import directly.
 */
declare function runSandboxPrompt(shell: SandboxRuntimeConfig, box: SandboxInstance, message: string | PromptInputPart[], options?: StreamSandboxPromptOptions): Promise<string>;
/** Define permission levels for sandbox access and control */
type SandboxPermissionLevel = 'owner' | 'admin' | 'developer' | 'viewer';
/** Map workspace roles to corresponding sandbox permission levels */
interface MemberSyncSeam {
    roleToSandboxRole: (workspaceRole: string) => SandboxPermissionLevel;
}
/** Resolve adding a user with a specific role to a sandbox and return the operation outcome */
declare function syncSandboxMemberAdd(box: SandboxInstance, seam: MemberSyncSeam, userId: string, role: string): Promise<Outcome<void>>;
/** Remove a member from the sandbox while preserving their home directory and handle the outcome */
declare function syncSandboxMemberRemove(box: SandboxInstance, userId: string): Promise<Outcome<void>>;
/** Synchronize a sandbox member's role by updating permissions based on the provided role mapping */
declare function syncSandboxMemberRole(box: SandboxInstance, seam: MemberSyncSeam, userId: string, role: string): Promise<Outcome<void>>;
/** Define methods to create, update, retrieve, and delete secrets asynchronously */
interface SecretStore {
    create: (name: string, value: string) => Promise<void>;
    update: (name: string, value: string) => Promise<void>;
    get: (name: string) => Promise<string>;
    delete: (name: string) => Promise<void>;
}
/** Resolve a SecretStore interface using the provided SandboxRuntimeConfig shell */
declare function secretStoreFromClient(shell: SandboxRuntimeConfig): SecretStore;
/** Resolve storing a secret by creating or updating it in the given SecretStore */
declare function storeSecret(store: SecretStore, name: string, value: string): Promise<Outcome<void>>;
/** Resolve a secret value from the store by its name and return the outcome asynchronously */
declare function readSecret(store: SecretStore, name: string): Promise<Outcome<string>>;
/** Delete a secret by name from the given secret store and return the operation outcome */
declare function deleteSecret(store: SecretStore, name: string): Promise<Outcome<void>>;
/** Represent a token with its expiration date and associated scope */
interface ScopedTokenResult {
    token: string;
    expiresAt: Date;
    scope: ScopedTokenScope;
}
/**
 * Mint a scoped token for an already-provisioned box (e.g. to hand a terminal
 * proxy a narrowed credential). Uses the SDK's native `box.mintScopedToken`,
 * which normalizes `expiresAt` to a Date — no hand-rolled wire call.
 */
declare function mintSandboxScopedToken(box: SandboxInstance, options: {
    scope: ScopedTokenScope;
    sessionId?: string;
    ttlMinutes?: number;
}): Promise<Outcome<ScopedTokenResult>>;
/** Define options to manage deterministic session resumption and turn idempotency in sandboxed drive turns */
interface DriveSandboxTurnOptions extends StreamSandboxPromptOptions {
    /** Deterministic resume key — required. Every tick for the same logical turn
     * MUST reuse it so a crash + re-drive finds the in-flight session instead of
     * starting a second agent run. */
    sessionId: string;
    /** Turn idempotency key for the platform's completed-turn cache. Defaults to
     * `sessionId` (correct for the one-turn-per-session shape detached drivers use). */
    turnId?: string;
    /** Wall-clock cap in ms from the session's start. A still-running session past
     * the cap is cancelled and reported `failed` — bounds an unattended run (e.g. a
     * turn that stalled on an interactive question nothing will answer). Omit for no cap. */
    wallCapMs?: number;
}
/** Resolve a sandbox turn by processing a message with given configuration and options */
declare function driveSandboxTurn(shell: SandboxRuntimeConfig, box: SandboxInstance, message: string | PromptInputPart[], options: DriveSandboxTurnOptions): Promise<Outcome<TurnDriveResult>>;
/** Define transitions marking the start or finish of a sandbox step with associated details */
type SandboxStepTransition = {
    kind: 'step-start';
} | {
    kind: 'step-finish';
    reason: string;
    severed: boolean;
};
/** Resolve the severed stream event to a corresponding sandbox step transition or null */
declare function classifySeveredStream(event: unknown): SandboxStepTransition | null;
/** Determine if an event is a terminal prompt event with type 'result' or 'done */
declare function isTerminalPromptEvent(event: unknown): boolean;
/** Resolve the interactive question text from a structured event or return null if none found */
declare function detectInteractiveQuestion(event: unknown): string | null;

export { type AppToolDescriptor, type AuthenticatedSandboxUser, type BuildAppToolMcpServersOptions, type BuildSandboxToolFileMountsOptions, DEFAULT_SANDBOX_RESOURCES, type DriveSandboxTurnOptions, ENV_TOTAL_MAX_BYTES, ENV_VALUE_MAX_BYTES, type EnsureWorkspaceSandboxOptions, type LivenessProbeConfig, type MemberSyncSeam, type Outcome, PROVISION_PAYLOAD_MAX_BYTES, type PeekWorkspaceSandboxOutcome, type ProfileComposeOptions, type PromptInputPart, type ProviderResolutionConfig, type ProvisionPayloadSections, type ProvisionProfileSection, type ResolveSandboxClientCredentialsOptions, type ResolvedModel, type SandboxApiCredentials, type SandboxBuildContext, type SandboxClientCredentials, type SandboxCredentialEnvironment, type SandboxExecChannel, type SandboxExecOptions, type SandboxFileBytesOutcome, type SandboxFileSizeOutcome, type SandboxPermissionLevel, type SandboxResourceConfig, type SandboxRestoreSpec, SandboxRuntimeAuthRefreshError, type SandboxRuntimeConfig, type SandboxRuntimeConnection, type SandboxScope, type SandboxStepTransition, type SandboxTerminalTokenOptions, type SandboxTerminalTokenResult, type SandboxTerminalTokenSubject, type SandboxTerminalWsMatch, type SandboxToolPathOptions, type SandboxToolSpec, type ScopedTokenResult, type SecretStore, type StoppedSandboxResumeFailure, type StoppedSandboxResumeRecovery, type StreamSandboxPromptOptions, type TerminalProxyIdentity, type WorkspaceSandboxConnectionArgs, type WorkspaceSandboxConnectionHandlerOptions, type WorkspaceSandboxEnsureContext, type WorkspaceSandboxInstanceLike, type WorkspaceSandboxManager, type WorkspaceSandboxManagerOptions, type WorkspaceSandboxRuntimeProxyArgs, type WorkspaceSandboxRuntimeProxyHandlerOptions, type WorkspaceSandboxTerminalUpgradeHandlerOptions, type WriteProfileFilesOptions, assertEnvWithinLimits, assertProvisionPayloadWithinCap, attachReasoningEffort, bearerSubprotocolToken, bearerToken, buildAppToolMcpServers, buildSandboxRuntimeProxyHeaders, buildSandboxToolFileMounts, buildSandboxToolPathSetupScript, classifySeveredStream, collectSandboxPromptText, createSandboxTerminalToken, createWorkspaceSandboxConnectionHandler, createWorkspaceSandboxManager, createWorkspaceSandboxRuntimeProxyHandler, createWorkspaceSandboxTerminalUpgradeHandler, deferredCorpusHash, deleteSecret, detectInteractiveQuestion, driveSandboxTurn, encodeSandboxRuntimePath, ensureWorkspaceSandbox, flattenHistory, getClient, isSandboxTerminalWsUpgrade, isTerminalPromptEvent, matchSandboxTerminalWsPath, mergeExtraMcp, mergeHistoryIntoParts, mintSandboxScopedToken, mintTerminalProxyToken, peekWorkspaceSandbox, readSandboxBinaryBytes, readSecret, resetClientCache, resolveModel, resolveSandboxClientCredentials, runSandboxPrompt, runSandboxToolPathSetup, sandboxToolBinDir, sandboxToolPath, sandboxToolRootDir, secretStoreFromClient, shellQuote, splitDeferredProfileFiles, statSandboxFileSize, storeSecret, streamSandboxPrompt, syncSandboxMemberAdd, syncSandboxMemberRemove, syncSandboxMemberRole, terminalTokenFromRequest, verifySandboxTerminalToken, verifyTerminalProxyToken, writeProfileFilesToBox };
