import { AgentProfileFileMount, AgentProfileMcpServer, AgentProfile, StorageConfig, SandboxInstance, ScopedTokenScope, PromptResult, Sandbox } from '@tangle-network/sandbox';
export { StorageConfig } from '@tangle-network/sandbox';
import { a as AppToolName, c as ToolHeaderNames } from '../auth-BlS9GWfL.js';
import { b as AppToolContext } from '../types-2rOJo8Hc.js';
import { Harness } from '../harness/index.js';
import { f as TangleExecutionEnvironment } from '../model-dF2h4xT9.js';

type Outcome<T> = {
    succeeded: true;
    value: T;
} | {
    succeeded: false;
    error: Error;
};

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;
}
interface SandboxBuildContext {
    workspaceId: string;
    connectedIntegrationIds: string[];
    userId?: string;
}

interface SandboxScope {
    workspaceId: string;
    userId?: string;
}
interface SandboxRestoreSpec {
    fromSnapshot: string;
    fromSandboxId: string;
}
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;
    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;
}
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[];
};
declare function writeProfileFilesToBox(box: SandboxInstance, files: AgentProfileFileMount[]): Promise<Outcome<void>>;
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;
declare function flattenHistory(message: string, history?: Array<{
    role: 'user' | 'assistant';
    content: string;
}>): string;
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;
    disallowQuestions?: boolean;
}
declare function streamSandboxPrompt(shell: SandboxRuntimeConfig, box: SandboxInstance, message: string, options?: StreamSandboxPromptOptions): AsyncGenerator<unknown>;
declare function runSandboxPrompt(shell: SandboxRuntimeConfig, box: SandboxInstance, message: string, 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>>;
declare function driveSandboxTurn(shell: SandboxRuntimeConfig, box: SandboxInstance, message: string, options: StreamSandboxPromptOptions & {
    sessionId: string;
}): Promise<Outcome<PromptResult>>;
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 EnsureWorkspaceSandboxOptions, type LivenessProbeConfig, type MemberSyncSeam, type Outcome, type ProfileComposeOptions, type ProviderResolutionConfig, type ResolveSandboxClientCredentialsOptions, type ResolvedModel, type SandboxApiCredentials, type SandboxBuildContext, type SandboxClientCredentials, type SandboxCredentialEnvironment, type SandboxPermissionLevel, type SandboxResourceConfig, type SandboxRestoreSpec, 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 StreamSandboxPromptOptions, type TerminalProxyIdentity, type WorkspaceSandboxConnectionArgs, type WorkspaceSandboxConnectionHandlerOptions, type WorkspaceSandboxEnsureContext, type WorkspaceSandboxInstanceLike, type WorkspaceSandboxManager, type WorkspaceSandboxManagerOptions, type WorkspaceSandboxRuntimeProxyArgs, type WorkspaceSandboxRuntimeProxyHandlerOptions, type WorkspaceSandboxTerminalUpgradeHandlerOptions, attachReasoningEffort, bearerSubprotocolToken, bearerToken, buildAppToolMcpServers, buildSandboxRuntimeProxyHeaders, buildSandboxToolFileMounts, buildSandboxToolPathSetupScript, classifySeveredStream, createSandboxTerminalToken, createWorkspaceSandboxConnectionHandler, createWorkspaceSandboxManager, createWorkspaceSandboxRuntimeProxyHandler, createWorkspaceSandboxTerminalUpgradeHandler, deleteSecret, detectInteractiveQuestion, driveSandboxTurn, encodeSandboxRuntimePath, ensureWorkspaceSandbox, flattenHistory, getClient, isSandboxTerminalWsUpgrade, isTerminalPromptEvent, matchSandboxTerminalWsPath, mergeExtraMcp, mintSandboxScopedToken, mintTerminalProxyToken, readSecret, resetClientCache, resolveModel, resolveSandboxClientCredentials, runSandboxPrompt, runSandboxToolPathSetup, sandboxToolBinDir, sandboxToolPath, sandboxToolRootDir, secretStoreFromClient, splitDeferredProfileFiles, storeSecret, streamSandboxPrompt, syncSandboxMemberAdd, syncSandboxMemberRemove, syncSandboxMemberRole, terminalTokenFromRequest, verifySandboxTerminalToken, verifyTerminalProxyToken, writeProfileFilesToBox };
