import { AgentProfileMcpServer, ProvisionEvent, SandboxInstance, AgentProfileFileMount, AgentProfile, StorageConfig, ScopedTokenScope, TurnDriveResult, Sandbox } from '@tangle-network/sandbox';
export { StorageConfig } from '@tangle-network/sandbox';
import { a as ToolHeaderNames } from '../auth-DuptSkWh.js';
import { f as AppToolName, c as AppToolContext } from '../types-BEOvc_ue.js';
import { Harness } from '../harness/index.js';
import { f as TangleExecutionEnvironment } from '../model-dF2h4xT9.js';
import '@tangle-network/agent-interface';

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;
    }>;
}
interface SandboxExecOptions {
    /** Run inside a named session rather than the box's default one. */
    sessionId?: string;
}
type SandboxFileSizeOutcome = {
    succeeded: true;
    value: number;
} | {
    succeeded: false;
    error: string;
};
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>;

interface TerminalProxyIdentity {
    userId: string;
    workspaceId: string;
    sandboxId: string;
}
declare function mintTerminalProxyToken(secret: string, identity: TerminalProxyIdentity, ttlMs?: number, now?: () => number): Promise<Outcome<{
    token: string;
    expiresAt: Date;
}>>;
declare function verifyTerminalProxyToken(secret: string, token: string, expected: TerminalProxyIdentity, now?: () => number): Promise<boolean>;

interface WorkspaceSandboxInstanceLike {
    id: string;
    name?: string;
    status?: string;
    connection?: {
        runtimeUrl?: string;
        sidecarUrl?: string;
        authToken?: string;
        sidecarToken?: string;
        authTokenExpiresAt?: string;
    } | null;
}
interface WorkspaceSandboxEnsureContext {
    workspaceId: string;
    userId: string;
}
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;
}
interface WorkspaceSandboxManager<TBox extends WorkspaceSandboxInstanceLike, TEnsureOptions = void> {
    ensureWorkspaceSandbox: (workspaceId: string, userId: string, options?: TEnsureOptions) => Promise<TBox>;
}
declare function createWorkspaceSandboxManager<TClient, TBox extends WorkspaceSandboxInstanceLike, TEnsureOptions = void>(opts: WorkspaceSandboxManagerOptions<TClient, TBox, TEnsureOptions>): WorkspaceSandboxManager<TBox, TEnsureOptions>;
interface SandboxTerminalTokenOptions {
    secret?: string;
    expiresInMs?: number;
    now?: () => number;
}
type SandboxTerminalTokenSubject = TerminalProxyIdentity;
interface SandboxTerminalTokenResult {
    token: string;
    expiresAt: Date;
}
declare function createSandboxTerminalToken(subject: SandboxTerminalTokenSubject, opts: SandboxTerminalTokenOptions): Promise<SandboxTerminalTokenResult>;
declare function verifySandboxTerminalToken(token: string, expected: SandboxTerminalTokenSubject, opts: SandboxTerminalTokenOptions): Promise<boolean>;
interface AuthenticatedSandboxUser {
    id: string;
}
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;
}
interface WorkspaceSandboxConnectionArgs {
    request: Request;
    params: {
        workspaceId?: string;
    };
}
declare function createWorkspaceSandboxConnectionHandler<TBox extends WorkspaceSandboxInstanceLike>(opts: WorkspaceSandboxConnectionHandlerOptions<TBox>): ({ request, params }: WorkspaceSandboxConnectionArgs) => Promise<Response>;
interface SandboxApiCredentials {
    baseUrl: string;
    apiKey: string;
}
interface SandboxRuntimeConnection {
    runtimeUrl: string;
    /** Server-side sidecar bearer. Must authorize terminal routes; never expose it to browser code. */
    authToken?: string;
}
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[];
}
interface WorkspaceSandboxRuntimeProxyArgs {
    request: Request;
    params: {
        workspaceId?: string;
        sandboxId?: string;
        '*'?: string;
    };
}
declare function createWorkspaceSandboxRuntimeProxyHandler(opts: WorkspaceSandboxRuntimeProxyHandlerOptions): ({ request, params }: WorkspaceSandboxRuntimeProxyArgs) => Promise<Response>;
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;
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>;
declare function buildSandboxRuntimeProxyHeaders(source: Headers, sandboxApiKey: string, forwardHeaders?: string[]): Headers;
declare function encodeSandboxRuntimePath(runtimePath: string): string | null;
declare function bearerToken(value: string | null): string | null;
declare function bearerSubprotocolToken(value: string | null): string | null;
declare function terminalTokenFromRequest(headers: Headers): string | null;

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;
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>;
}
declare function resolveSandboxClientCredentials(options?: ResolveSandboxClientCredentialsOptions): Promise<SandboxClientCredentials>;
interface SandboxResourceConfig {
    image: string;
    cpuCores: number;
    memoryMB: number;
    diskGB: number;
    maxLifetimeSeconds: number;
    idleTimeoutSeconds: number;
}
interface ProviderResolutionConfig {
    routerBaseUrl?: string;
    apiKey?: string;
    providerName?: string;
    modelName?: string;
    defaultModel?: string;
    openaiApiKey?: string;
    allowKeylessModel?: boolean;
}
interface SandboxBuildContext {
    workspaceId: string;
    connectedIntegrationIds: string[];
    userId?: string;
}

interface SandboxScope {
    workspaceId: string;
    userId?: string;
}
interface SandboxRestoreSpec {
    fromSnapshot: string;
    fromSandboxId: string;
}
interface StoppedSandboxResumeFailure {
    box: SandboxInstance;
    error: Error;
    scope: SandboxScope;
    boxKey: string;
}
interface StoppedSandboxResumeRecovery {
    replacementBoxKey: string;
    restore?: SandboxRestoreSpec | null;
}
interface LivenessProbeConfig {
    sidecarProcessPattern: (harness: Harness) => string;
    execTimeoutMs?: number;
    psTimeoutMs?: number;
}
interface ProfileComposeOptions {
    systemPrompt?: string;
    extraFiles?: AgentProfileFileMount[];
    extraMcp?: Record<string, AgentProfileMcpServer>;
    name?: string;
}
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;
}
declare const DEFAULT_SANDBOX_RESOURCES: SandboxResourceConfig;
declare function getClient(shell: SandboxRuntimeConfig): Sandbox;
declare function resetClientCache(): void;
interface AppToolDescriptor {
    tool: AppToolName;
    key: string;
    description: string;
}
interface BuildAppToolMcpServersOptions {
    tools: AppToolDescriptor[];
    baseUrl: string;
    token: string;
    ctx: AppToolContext;
    headerNames?: ToolHeaderNames;
}
declare function buildAppToolMcpServers(options: BuildAppToolMcpServersOptions): Record<string, AgentProfileMcpServer>;
interface EnsureWorkspaceSandboxOptions {
    workspaceId: string;
    userId?: string;
    harness: Harness;
    forceNew?: boolean;
    onProgress?: (event: ProvisionEvent) => void;
    billingOwnerId?: string;
}
interface SandboxToolSpec {
    name: string;
    content: string;
    executable?: boolean;
}
interface SandboxToolPathOptions {
    appName: string;
    baseDir?: string;
    binDir?: string;
}
interface BuildSandboxToolFileMountsOptions extends SandboxToolPathOptions {
    tools: readonly SandboxToolSpec[];
}
declare function sandboxToolRootDir(options: SandboxToolPathOptions): string;
declare function sandboxToolBinDir(options: SandboxToolPathOptions): string;
declare function sandboxToolPath(options: SandboxToolPathOptions & {
    toolName: string;
}): string;
declare function buildSandboxToolFileMounts(options: BuildSandboxToolFileMountsOptions): AgentProfileFileMount[];
declare function buildSandboxToolPathSetupScript(options: SandboxToolPathOptions): string;
declare function runSandboxToolPathSetup(box: SandboxInstance, options: SandboxToolPathOptions): Promise<Outcome<void>>;
declare function splitDeferredProfileFiles(profile: AgentProfile): {
    leanProfile: AgentProfile;
    deferredFiles: AgentProfileFileMount[];
};
type ExistingBoxStage = 'reused' | 'resumed';
declare class SandboxRuntimeAuthRefreshError extends Error {
    constructor(stage: ExistingBoxStage, name: string, detail: string, cause?: unknown);
}
interface WriteProfileFilesOptions {
    execTimeoutMs?: number;
    paceMs?: number;
    maxRetries?: number;
}
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>;
declare function ensureWorkspaceSandbox(shell: SandboxRuntimeConfig, options: EnsureWorkspaceSandboxOptions): Promise<SandboxInstance>;
interface ResolvedModel {
    model: string;
    provider: string;
    apiKey?: string;
    baseUrl?: string;
}
declare function resolveModel(config: ProviderResolutionConfig | undefined, override?: {
    model?: string;
    modelApiKey?: string;
}): ResolvedModel | undefined;
type PromptInputPart = Extract<Parameters<SandboxInstance['streamPrompt']>[0], readonly unknown[]>[number];
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[];
declare function mergeExtraMcp(appToolMcp: Record<string, AgentProfileMcpServer>, baseProfileMcp: Record<string, AgentProfileMcpServer>, extra: Record<string, AgentProfileMcpServer> | undefined): Record<string, AgentProfileMcpServer>;
declare function attachReasoningEffort(profile: AgentProfile, harness: Harness, effort: 'auto' | 'low' | 'medium' | 'high' | undefined): AgentProfile;
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;
}
declare function streamSandboxPrompt(shell: SandboxRuntimeConfig, box: SandboxInstance, message: string | PromptInputPart[], options?: StreamSandboxPromptOptions): AsyncGenerator<unknown>;
declare function runSandboxPrompt(shell: SandboxRuntimeConfig, box: SandboxInstance, message: string | PromptInputPart[], options?: StreamSandboxPromptOptions): Promise<string>;
type SandboxPermissionLevel = 'owner' | 'admin' | 'developer' | 'viewer';
interface MemberSyncSeam {
    roleToSandboxRole: (workspaceRole: string) => SandboxPermissionLevel;
}
declare function syncSandboxMemberAdd(box: SandboxInstance, seam: MemberSyncSeam, userId: string, role: string): Promise<Outcome<void>>;
declare function syncSandboxMemberRemove(box: SandboxInstance, userId: string): Promise<Outcome<void>>;
declare function syncSandboxMemberRole(box: SandboxInstance, seam: MemberSyncSeam, userId: string, role: string): Promise<Outcome<void>>;
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>;
}
declare function secretStoreFromClient(shell: SandboxRuntimeConfig): SecretStore;
declare function storeSecret(store: SecretStore, name: string, value: string): Promise<Outcome<void>>;
declare function readSecret(store: SecretStore, name: string): Promise<Outcome<string>>;
declare function deleteSecret(store: SecretStore, name: string): Promise<Outcome<void>>;
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>>;
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;
}
declare function driveSandboxTurn(shell: SandboxRuntimeConfig, box: SandboxInstance, message: string | PromptInputPart[], options: DriveSandboxTurnOptions): Promise<Outcome<TurnDriveResult>>;
type SandboxStepTransition = {
    kind: 'step-start';
} | {
    kind: 'step-finish';
    reason: string;
    severed: boolean;
};
declare function classifySeveredStream(event: unknown): SandboxStepTransition | null;
declare function isTerminalPromptEvent(event: unknown): boolean;
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, 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 };
