UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

1,046 lines • 81.9 kB
/**
 * Remote execution seam (design/48 §5) — the type-only contract a **remote/containerised** `ExecutionEnv`
 * implementation (E2B/Firecracker, owned by the service control plane) must satisfy so the agent's "hand"
 * (design/44) can act inside an isolated, *stateful*, *suspendable* workspace instead of the in-process
 * `NodeExecutionEnv`.
 *
 * **This file is a SEAM, not an implementation.** The real `RemoteContainerExecutionEnv` (E2B SDK, warm
 * pools, snapshot lifecycle) lives in the service and is driven by real integration needs —
 * exactly like `CheckpointStore` (design/45). Core owns the seam shape; service owns the backend.
 *
 * Design rulings folded in (design/48 §10/§11 DeepSeek council):
 * - **#1 [blocker] interface extension, not capability probing**: `RemoteExecutionEnv extends ExecutionEnv` with
 *   the lifecycle and streaming METHODS a remote workspace has; a consumer that only needs buffered fs/shell keeps
 *   accepting the base type. What an environment can DO is not part of this extension: it is the base type's own
 *   required block ({@link ExecutionEnvCapabilities}, #2891), declared by every environment, local or remote, and
 *   read through the readers at the end of this file. The interface answers only whether the remote methods can be
 *   called ({@link isRemoteExecutionEnv}); it never answers a capability.
 * - **#3 [major] do not overload `exec`**: `exec()` stays buffered; streaming is a NEW {@link execStream}.
 * - **#4 [major] suspend × in-flight exec must not hang**: see {@link suspendVM}.
 * - **#8 [major] post-resume consistency**: see {@link postResumeInit}.
 * - **#16 suspend/resume disambiguation**: the VM-lifecycle methods are `suspendVM`/`resumeVM` to keep them
 *   distinct from the Runner gate-resume and design/45 wake/resume semantics.
 *
 * **Deferred (NOT modelled here — they are runtime, not seam):** actually suspending a running task and
 * persisting the {@link WorkspaceHandle} into a design/45 `Checkpoint`; the `status:"suspended"` orchestrator
 * mapping — both are service/design-45 implementation-time concerns. Core only declares the seam those will plug into.
 */
import type { ExecutionEnv, ExecutionEnvCapabilities } from "../internal/harness-types.js";
/** Snapshot identifier returned by {@link RemoteExecutionEnv.suspendVM}; opaque to core, resolved by the provider. */
export type SnapshotId = string;
/**
 * Token identifying a still-running remote session, used by {@link RemoteExecutionEnv.reconnect} to re-attach
 * the control plane's transport after a control-plane replica crash/failover. The underlying VM state lives
 * independently of any single control-plane TCP connection (a Firecracker process survives a dropped client),
 * so reconnect re-binds rather than re-creates.
 */
export type SessionToken = string;
/**
 * Serializable identity of a remote workspace (design/48 §5 gap 1). The control plane persists this into its
 * durable state (and design/45 `Checkpoint`) so a *different* replica can reconnect/resume the same workspace.
 */
export interface WorkspaceHandle {
    /** Provider/VM/sandbox id (e.g. an E2B sandbox id). */
    sandboxId: string;
    /** Provider identifier (e.g. `"e2b"`), so the control plane routes reconnect/destroy to the right backend. */
    provider: string;
    /** Absolute mount path of the workspace root inside the remote env; remote paths normalize against this. */
    mountPath: string;
    /** Set when this env was produced by resuming a snapshot ({@link RemoteExecutionEnv.resumeVM}), else undefined. */
    snapshotId?: SnapshotId;
    /** Token for {@link RemoteExecutionEnv.reconnect} when the VM is still running (vs suspended to a snapshot). */
    sessionToken?: SessionToken;
    /** How a checkpointed workspace is restored on resume (1.257.2 hardening):
     *  `"park_only"` = durable-park-only suspend degrade (non-suspendable env; workspace persists on the
     *  target, resume skips `resumeVM`). Absent = legacy/snapshot handle — resume treats a MISSING
     *  `snapshotId` as corruption (fail-closed) unless the resumed env is itself non-suspendable
     *  (tolerance for park handles minted by 1.257.1 before this field existed). */
    restoreMode?: "park_only";
    /**
     * design/380 O1④ — explicit identity of the physical/target device this workspace lives on
     * (device lane; an SSH/ADB adapter MAY also stamp it). MINTER-STATED: consumers read this field,
     * never parse an identity out of `sandboxId`. Plain string → rides CheckpointState.workspaceHandle
     * (all-string whitelist) with zero schema movement.
     */
    deviceId?: string;
}
/** The one list of what a {@link WorkspaceHandle} is: every member the interface declares. */
export declare const WORKSPACE_HANDLE_MEMBERS: ReadonlyArray<keyof WorkspaceHandle>;
/**
 * A frozen copy of `handle` holding exactly the declared members it carries as strings: shallow-frozen, which is deep here
 * because every member is a string (a decoration or a function member of the source never reaches the copy), and no
 * structured-clone step to fail on an exotic value. Each member is read the way the engine's own handle comparison reads it.
 *
 * ONE copy per live handle: a second call for the same object answers the copy the first call made (the members are read
 * once), so every place the engine hands a checkpointed handle to the outside — the resume preflight's facts, the env
 * factory's {@link ExecutionEnvFactoryContext.priorHandle} and the restore's {@link VmLifecycleOptions.priorHandle} —
 * delivers the same object, not three renderings of one fact; the row judge reads the handle through this copy too, and
 * the factory's {@link ExecutionEnvFactoryContext.placementTarget} is folded from it ({@link placementTargetOf}).
 */
export declare function frozenHandleCopy(handle: WorkspaceHandle): Readonly<WorkspaceHandle>;
/**
 * Which target a leg's environment is on: the backend (`provider`) and, when the target states one, the physical device
 * (`deviceId`) — the two members of a {@link WorkspaceHandle} that NAME a target, and nothing that reconnects to or restores
 * one (a sandbox id, a reconnect token, a snapshot id). The value of {@link ExecutionEnvFactoryContext.placementTarget}.
 */
export type PlacementTarget = Readonly<{
    provider: string;
    deviceId?: string;
}>;
/** The target `handle` names NOW: its `provider` and `deviceId` read as strings at this call (never through
 *  {@link frozenHandleCopy}'s per-object copy — an env may answer one handle object and update it in place, and a receipt
 *  must see what the env reports at the moment it is read), frozen; `undefined` when it names no provider (an empty
 *  string names none). */
export declare function placementTargetOf(handle: WorkspaceHandle): PlacementTarget | undefined;
/**
 * The target an environment reports for itself, read ONCE per leg — at the point the leg's workspace settles: its
 * `workspaceHandle()`'s {@link placementTargetOf}. `undefined` when there is nothing to read: the environment is not a
 * remote one, or its handle cannot answer yet (a lazy-connect adapter that is still unconnected — its establishment at
 * the leg's restore seat failed in a way the run starts past — throws). That leg has no target of its own, so what it
 * spawns carries no fence.
 */
export declare function reportedPlacementTarget(env: ExecutionEnv | undefined): PlacementTarget | undefined;
/**
 * The ONE receipt every fenced leg is checked with: the target its environment reported honors `fence` when the fence names
 * no device, or the report names that same device. A report that could not be read (`undefined`) names none, so it honors
 * no device. `provider` is no part of it: only a durable resume leg also requires the checkpointed backend.
 */
export declare function placementHonored(fence: PlacementTarget | undefined, report: PlacementTarget | undefined): boolean;
/**
 * A reference to a secret injected at {@link RemoteExecutionEnv.connect}/{@link RemoteExecutionEnv.postResumeInit}
 * time (design/48 §5 gap 7) — never baked into the image. The control plane resolves {@link ref} to a value out of
 * band; only the reference travels through core.
 */
export interface SecretRef {
    /** Logical name the secret is exposed under (an env-var name in the remote env for `destination:"remote"`). */
    name: string;
    /** Opaque locator the control plane resolves to a value (vault path, KMS key id, …). */
    ref: string;
    /**
     * Where the resolved secret is consumed (design/61 §9 B, council). Default `"remote"` (the original
     * semantics): injected **into the remote env** as `name` (E2B env-var) — visible to code running there.
     * `"adapter"`: used by the **adapter itself** to establish/authenticate the connection (an SSH private key,
     * an ADB token) and **MUST NOT be injected into the target machine/device** — a credential that reaches an
     * un-isolated target's environment is the lethal trifecta (design/53 §C). An adapter MUST honor this.
     */
    destination?: "remote" | "adapter";
}
/** Configuration for {@link RemoteExecutionEnv.connect}. */
export interface RemoteConnectConfig {
    /** Resume from this snapshot instead of provisioning a fresh workspace. */
    snapshotId?: SnapshotId;
    /** Secrets to inject at connect time (design/48 §5 gap 7). */
    secrets?: SecretRef[];
    /** Abort provisioning/connection. */
    abortSignal?: AbortSignal;
    /**
     * The repository this workspace is a checkout of, when it is one ({@link RepositoryWorkspace}). Handed by the deployment
     * to its own adapter (its factory's connect call); the engine neither reads nor fills it — the connect the engine makes
     * at a leg's restore seat carries `abortSignal` alone, as it always has.
     */
    workspace?: RepositoryWorkspace;
}
/**
 * A repository workspace, as a deployment declares it to its adapter: which repository, where the checkout starts, and
 * where the workspace's changes go back. Every member is the deployment's own spelling, passed to the adapter as written —
 * the engine interprets none of them and never sees the credential. What the adapter does with it at a sync
 * ({@link RemoteExecutionEnv.syncWorkspace}) is the adapter's.
 */
export interface RepositoryWorkspace {
    /** The repository: a clone URL or the deployment's own locator for one. */
    repository: string;
    /** The ref the checkout starts from when the workspace is first provisioned (a branch, tag or commit); absent = the
     *  repository's default. */
    ref?: string;
    /** Where the workspace's changes are written back: a branch name, or the deployment's own rule for one (one branch per
     *  session, a prefix); absent = the adapter writes nothing back to the repository. */
    branchRule?: string;
    /** The credential the adapter fetches and writes back with. Typed to the `"adapter"` destination only: its value is
     *  the adapter's to use and is never placed in the workspace's environment, where the model's commands run. */
    credential?: SecretRef & {
        destination: "adapter";
    };
}
/**
 * Why the engine calls {@link RemoteExecutionEnv.syncWorkspace}: `"turn_end"` — a stretch of work on the workspace stopped
 * (a turn ended where the agent would otherwise stop, the leg parked, or the leg ended without its env being destroyed);
 * `"destroy"` — the engine is about to call this env's `destroy()`.
 */
export type WorkspaceSyncReason = "turn_end" | "destroy";
/** The closed set of {@link WorkspaceSyncReason} words, frozen. */
export declare const WORKSPACE_SYNC_REASONS: readonly WorkspaceSyncReason[];
/** What the engine hands {@link RemoteExecutionEnv.syncWorkspace} besides the reason. */
export interface WorkspaceSyncOptions {
    /** Fires when the engine stops waiting for this sync: its bound passed, (a `"turn_end"` sync) the run was cut, or (any sync)
     *  a `"destroy"` sync of the same workspace stopped waiting for it — always before the engine calls that env's `destroy()`.
     *  Settle soon after it fires: the next sync of the same workspace waits for this one within its own bound, and only when that
     *  whole wait runs out with this one not returned does the engine abandon it — every later sync of that workspace in this
     *  process is then not made (`command_in_flight`) until it settles. */
    abortSignal: AbortSignal;
}
/** What {@link RemoteExecutionEnv.syncWorkspace} answers: the seam's never-throw result shape. */
export type WorkspaceSyncAnswer = {
    ok: true;
    value: void;
} | {
    ok: false;
    error: RemoteExecutionError;
};
/**
 * Options for the VM-lifecycle ops {@link RemoteExecutionEnv.suspendVM} / {@link RemoteExecutionEnv.resumeVM}
 * (design/49 v1.5, code-ready council BUG#2). Parity with {@link RemoteConnectConfig.abortSignal} /
 * {@link ExecStreamOptions.signal}: without an abort hook a hung provider pause/restore (network partition)
 * would pin the calling worker forever. The implementation races the op against this signal + an internal
 * timeout; on abort it returns `{ok:false}` with code `"aborted"`.
 */
export interface VmLifecycleOptions {
    /** Abort a hung pause/restore. */
    abortSignal?: AbortSignal;
    /**
     * (resume workspace-root fidelity) — the CHECKPOINTED {@link WorkspaceHandle} of the workspace
     * being restored, passed by the engine on the `resumeVM` leg. An adapter SHOULD bind the restored
     * workspace root (cwd / mount) to `priorHandle.mountPath` rather than its CURRENT deployment
     * configuration: across a config-knob change window (e.g. a mount-path rotation) the resumed task's
     * execs and artifacts must land in the root the task was checkpointed under, not the new one. An
     * adapter that cannot honor the prior root MUST still return its ACTUAL `mountPath` in the restored
     * handle (never echo `priorHandle.mountPath` unhonored) — the engine compares the two and surfaces a
     * divergence observation. Absent on non-resume ops and from pre-1.360 engines (adapters treat absence
     * as the legacy current-config behavior).
     *
     * A frozen copy holding exactly the declared members ({@link WORKSPACE_HANDLE_MEMBERS}) the checkpoint row carries
     * as strings ({@link frozenHandleCopy}: the SAME object the resume preflight's facts and the env factory's
     * {@link ExecutionEnvFactoryContext.priorHandle} carry, for the same row) — not the stored row's own object: writing to
     * it throws, and a decoration on the stored handle is absent.
     */
    priorHandle?: Readonly<WorkspaceHandle>;
}
/**
 * One chunk streamed from {@link RemoteExecutionEnv.execStream} (design/48 §5 gap 3, council BUG#3). A run is a
 * sequence of `stdout`/`stderr` chunks terminated by exactly one `exit` chunk carrying the typed exit code.
 *
 * The async iterator THROWS a {@link RemoteExecutionError} if the stream fails before an `exit` chunk arrives
 * (transport loss, or a {@link RemoteExecutionEnv.suspendVM} that aborts the in-flight command) — that is the
 * streaming analogue of the base {@link ExecutionEnv}'s never-throw `Result` contract, and it guarantees a
 * consumer is never left awaiting a chunk that will never come.
 */
export type OutputChunk = {
    type: "stdout";
    data: string;
} | {
    type: "stderr";
    data: string;
} | {
    type: "exit";
    exitCode: number;
};
/** Options for {@link RemoteExecutionEnv.execStream}. */
export interface ExecStreamOptions {
    /** Working directory; relative paths resolve against the workspace root. */
    cwd?: string;
    /** Extra environment variables for the command. */
    env?: Record<string, string>;
    /**
     * Total command wall-clock timeout in seconds. **🔴 Per-command — independent of the env/sandbox lifetime.**
     * A remote adapter MUST NOT fall back to the sandbox lifetime when this is unset (service [45]: an E2B adapter
     * that defaulted a missing per-command timeout to `cfg.timeoutMs` = the sandbox lifetime made a seconds-long
     * command wait the *whole sandbox lifetime*, ~30 min, on a provider RPC hang). "No `timeout`" means "no
     * wall-clock cap on a *making-progress* command" — NOT "wait until the env dies"; liveness is still bounded by
     * {@link readTimeoutMs} (see below). Distinct concerns: `timeout` caps a slow-but-progressing command;
     * `readTimeoutMs` catches a *hung/unreachable* one.
     */
    timeout?: number;
    /** Abort the command. Aborting ends the stream with a {@link RemoteExecutionError} (code `"aborted"`, no `exit` chunk). */
    signal?: AbortSignal;
    /**
     * Idle/liveness read timeout (ms). If no {@link OutputChunk} arrives within this window, `execStream` ends
     * with a {@link RemoteExecutionError} (code `"liveness_no_output"`) instead of hanging. **Needed in practice for remote
     * backends** (design/48 §5, service [7]): E2B issue #1128 — a *streaming* call sets no read timeout (only unary
     * does), so an unreachable sandbox hangs the worker forever. Distinct from `timeout` (total wall-clock).
     *
     * 🔴 **Liveness contract (service [45]/[59]):** a remote adapter SHOULD enforce a default liveness bound even
     * when this is unset (a missing idle timeout MUST NOT mean "wait forever / until the env dies"), and that bound
     * MUST cover the **command-creation/handshake RPC**, not only the post-first-chunk loop — a provider hang
     * typically occurs at creation, before any chunk arrives, so an idle timer started only after the first chunk
     * misses it. On trigger, throw {@link RemoteExecutionError} with code `"liveness_no_output"` (retryable by the
     * caller per the command's idempotency — the adapter MUST NOT blind-retry). The wall-clock {@link timeout}
     * keeps `"timeout"`: the two cuts are different words because they explain themselves with different numbers.
     */
    readTimeoutMs?: number;
    /** Per-call output cap (design/48 §5 gap 8): stop streaming after this many bytes to avoid a `find /` flooding the control plane. */
    maxOutputBytes?: number;
}
/** Stable error codes for the remote seam's lifecycle/streaming operations (design/48 §5/§11 BUG#2). */
export type RemoteExecutionErrorCode = 
/** A lifecycle/exec op failed because the workspace is (or became) suspended. */
"suspended"
/** An op not done because an earlier one on the workspace is still in flight: {@link RemoteExecutionEnv.suspendVM} refused
 *  while a command ran (council #4); a workspace sync the engine did not make because an earlier sync of the same workspace is
 *  still in flight and abandoned ({@link WorkspaceSyncOptions.abortSignal}) — on a `remoteEnvFailures` row `attempts` tells
 *  the two apart: 0 = the engine did not make the call, 1 = the adapter answered it. */
 | "command_in_flight"
/** Connect/resume/reconnect failed to reach or provision the remote workspace. */
 | "connect_failed"
/** A post-resume consistency step failed (design/48 §5/#8) — caller must destroy the env. */
 | "post_resume_failed"
/** The command/stream was aborted via its `AbortSignal`. */
 | "aborted"
/**
 * A bound on elapsed time was exceeded: a command's wall-clock {@link ExecStreamOptions.timeout}, or the idle
 * bound of a lifecycle / filesystem RPC (service [45]/[59]). **Retryable** by the caller per the op's
 * idempotency (the adapter MUST NOT blind-retry). Distinct from `"aborted"` (a caller-driven `AbortSignal`),
 * `"connect_failed"` (workspace provisioning, not a per-command hang) and `"liveness_no_output"` (an exec
 * stream's silence window — below).
 */
 | "timeout"
/**
 * An exec stream produced no {@link OutputChunk} for its liveness window ({@link ExecStreamOptions.readTimeoutMs},
 * or the adapter's default bound) — including a provider RPC hang at command creation, before the first chunk
 * (service [45]/[59]). A hang detector, not a budget: it is the word for the cut that used to share `"timeout"`
 * with the wall-clock budget, and the two explain themselves with different numbers (the window versus the
 * budget the caller asked for), so a consumer must be able to tell them apart by code. **Retryable** by the
 * caller per the command's idempotency (the adapter MUST NOT blind-retry), exactly as `"timeout"` is.
 */
 | "liveness_no_output"
/**
 * The op is not supported by this adapter's capabilities (design/61 §9 A) — e.g. `suspendVM`/`resumeVM` on a
 * non-suspendable SSH/ADB env. Permanent for this env; check its declaration ({@link declaredSuspend}) first.
 */
 | "unsupported"
/**
 * A **transient** authentication step that is expected to succeed on a retry (design/61 §9 C) — e.g. an ADB
 * device awaiting first-time authorization (connect once → user authorizes → connect again succeeds).
 * **Retryable** (typically retry-exactly-once). Distinct from {@link "auth_failed"} so a real rejection isn't
 * retried and a bounded ADB retry doesn't false-kill an SSH transient.
 */
 | "auth_transient"
/**
 * **Permanent** authentication failure (design/61 §9 C) — wrong/rejected SSH key, revoked token. **NEVER
 * retry** (retrying burns the whole attempt budget and can lock accounts). The caller must surface it.
 */
 | "auth_failed"
/**
 * The transport connection dropped mid-session (TCP RST, network partition, peer close) — design/61 §9 C/#14.
 * **Retryable** by re-establishing the connection (idempotent for a persistent SSH/ADB session). An adapter
 * MUST map raw transport errors (DNS `ENOTFOUND`, TCP RST) onto a typed code, not leave them as `"unknown"`,
 * else a retry whitelist misses them.
 */
 | "transport_lost"
/**
 * design/380 O12 — the op was COMMITTED to the remote target and its outcome is UNKNOWABLE (the target
 * went unreachable / restarted / was revoked after dispatch-commit; an execStream cut where the target
 * protocol's own server has ruled the outcome unknowable). NEVER auto-retried and deliberately NOT in
 * {@link RETRYABLE_REMOTE_ERROR_CODES}: the command may have already executed — a retry whitelist that
 * contained it would re-drive committed side effects. Distinct from `transport_lost` (connection story
 * known, idempotency-gated retry after reconnect). A lifecycle op's message carries the verify-first sentence ("may have
 * already executed on the target; verify its effect before re-running"): the leg's restore seat shows it as written. An
 * adapter that builds its buffered `exec` from {@link execStream} does NOT copy that advice into the `ExecutionError` it
 * answers — there every engine reader adds it once (`ExecutionErrorCode` `outcome_unknown`, `src/core/exec-outcome.ts`).
 */
 | "outcome_unknown"
/**
 * The four NEVER-STARTED words of {@link execStream} — the same names and meanings as on the buffered `ExecutionErrorCode`, so an
 * adapter that builds its `exec` from its stream carries the word across unchanged: `spawn_error` (the OS-level spawn failed:
 * dead cwd, missing binary), `shell_unavailable` (the shell could not be resolved), `target_unavailable` (the target refused
 * before commit: offline, busy, not bound — a retry is safe once it is back), `refused` (the target judged the command by its
 * own policy and said no). **Only before the stream's first chunk**: they are the `never_started` rows of the one failure table
 * (`EXEC_FAILURE_WORDS`, `src/core/exec-outcome.ts`) that are stream words, and the engine's stream reader judges them by that
 * table, not by a list of its own. A command that delivered a chunk started, so a failure after it is `transport_lost` /
 * `outcome_unknown` (or an `exit` chunk). A stream that throws one of these words after a chunk breaks this contract; the
 * engine reads that failure as `outcome_unknown` and announces it (`config.execution_env_failure_contract_broken`). `suspended`
 * and `auth_failed` are the table's `state` rows: they may arrive after a chunk (a workspace paused, a credential revoked while
 * the command ran) and keep their word — no breach. None of the four is in {@link RETRYABLE_REMOTE_ERROR_CODES}.
 */
 | "spawn_error" | "shell_unavailable" | "target_unavailable" | "refused"
/** Unclassified provider/transport failure. */
 | "unknown";
/** {@link RemoteExecutionErrorCode} as a value — every word once (the `satisfies` row set does not compile without each). */
export declare const REMOTE_EXECUTION_ERROR_CODES: readonly RemoteExecutionErrorCode[];
/** Is `code` a deployment's own `env.` code, spelled as the namespace takes it — the environment refusing itself? Any other string,
 *  `env.`-prefixed free text included, is not. */
export declare function isDeploymentEnvCode(code: unknown): code is `env.${string}`;
/** Is `code` a word a stream may fail with — one of {@link REMOTE_EXECUTION_ERROR_CODES}, or a deployment's `env.` code? A reader
 *  that records the stream's word (the exit oracle's row) reads anything else as `unknown` and announces the breach. */
export declare function isStreamFailureWord(code: unknown): boolean;
/**
 * The RETRYABLE half of {@link RemoteExecutionErrorCode} — the codes whose own contract above says a retry
 * can succeed (`auth_transient`: retry-exactly-once after the device is authorized; `connect_failed`: the
 * workspace could not be reached/provisioned this attempt; `timeout` / `liveness_no_output`: a time bound
 * tripped; `transport_lost`: re-establish the connection). Every OTHER code is permanent for this attempt
 * (`auth_failed`/`unsupported`), caller-driven (`aborted`), unclassifiable (`unknown`), or
 * outcome-unknowable (`outcome_unknown` — design/380 O12: the op may have ALREADY executed, so a retry
 * re-drives committed side effects) — retrying them burns budget or, worse, re-drives a rejected
 * credential or a committed op.
 *
 * ONE list, three consumers, so a caller's retry decision, its DISCLOSURE and whether the run starts at all can
 * never disagree: the engine retries only IDEMPOTENT ops on these codes (see {@link withRetry}'s red line — a
 * snapshot-taking `suspendVM` is never retried); it stamps `retryable` on the failure it reports to the caller for
 * the ops it does NOT retry, so a deployment can decide (refresh the credential and re-resume vs give up) without
 * parsing prose; and the leg's restore seat reads it when the environment answers its establishment call
 * ({@link RemoteExecutionEnv.connect}, or `resumeVM` on a leg that restores a snapshot). Starting the run past a
 * failed establishment IS a retry — the first operation establishes again — so the seat starts it only on a code
 * this list holds, on `unknown` (it says nothing about the environment) and on `aborted` the run's own cancel did
 * not cause; any other code is this environment's standing refusal and fails the run before it starts, with that code.
 * Past a `connect` code this list holds, the seat makes that second establishment itself, before the run's first
 * operation; in its answer only a deployment's `env.` code is a standing refusal (any other answer lets the run start).
 * An `env.`-namespaced code ({@link RemoteExecutionError.code}) is never in this list.
 */
export declare const RETRYABLE_REMOTE_ERROR_CODES: readonly RemoteExecutionErrorCode[];
/** Is `code` in the {@link RETRYABLE_REMOTE_ERROR_CODES} family? A deployment's `env.` code never is. */
export declare function isRetryableRemoteErrorCode(code: RemoteExecutionError["code"]): boolean;
/**
 * Error surfaced by {@link RemoteExecutionEnv} lifecycle ops and by {@link RemoteExecutionEnv.execStream}'s
 * iterator. Mirrors the vendored `ExecutionError` shape but carries the remote-specific code set; it is kept
 * separate from the vendored `ExecutionErrorCode` union deliberately — those codes only need to widen once the
 * design/45 suspend/resume *runtime* lands and the Runner/orchestrator layer must thread `"suspended"`.
 *
 * `message` is the adapter's own sentence for what failed. Where the engine writes it into a sentence of its own — the terminal of a
 * refused start (`<verb> refused (<code>): …`) among them — it is read as one line and cut at `ENV_ERROR_DETAIL_MAX` code points (a
 * root export) with one `…`, so put the way out FIRST: what follows the bound is not shown.
 */
export declare class RemoteExecutionError extends Error {
    /**
     * A {@link RemoteExecutionErrorCode}, or a deployment's own `env.`-namespaced code for a refusal of this environment
     * that the closed set has no word for (the namespace the terminal code table reads as the execution environment's,
     * `env.` ⇒ `config`). Either is read through {@link RETRYABLE_REMOTE_ERROR_CODES}: an `env.` code is never in it, so
     * answered by the restore seat's establishment call (its first answer, or the one reconnect the seat makes past a table
     * code) it fails the run before it starts, carried to the terminal verbatim.
     */
    readonly code: RemoteExecutionErrorCode | `env.${string}`;
    constructor(code: RemoteExecutionError["code"], message: string, cause?: Error);
}
/**
 * A remote, stateful, suspendable {@link ExecutionEnv} (design/48 §5). Extends the base with workspace identity,
 * connection lifecycle, streaming exec, and post-resume reconciliation. Every method follows the base contract:
 * **never throw/reject** — encode failures in the returned `Result` (the one exception is {@link execStream},
 * whose iterator may throw mid-stream; see {@link OutputChunk}).
 *
 * Lifecycle methods are typed but their RUNTIME wiring (task suspension, `Checkpoint` persistence of the
 * {@link WorkspaceHandle}, cross-replica resume) is implemented with design/45 — see the file header.
 *
 * 🔴 **Universal liveness contract (service [45]/[59] class-fix) — applies to EVERY remote RPC**, not just
 * `execStream`: the inherited {@link ExecutionEnv} filesystem ops (`readTextFile`/`writeFile`/`listDir`/…), the
 * streaming/buffered exec, AND the VM-lifecycle ops below (`connect`/`reconnect`/`suspendVM`/`resumeVM`/
 * `postResumeInit`/`destroy`). Each is a network round-trip to a provider that can hang. The contract:
 * 1. **Every remote RPC SHOULD enforce a bounded default liveness/idle timeout** even when no `abortSignal`/
 *    timeout is given — a hung provider call MUST NOT wait until the env/sandbox lifetime expires (the
 *    service [45] bug, but generalized: it was found on `exec`, and `files.read`/`resumeVM`/etc. share the
 *    exact exposure). An optional `abortSignal` (where present) composes with, but does not replace, this default.
 * 2. **🔴 Bound on LIVENESS (no progress), not a fixed short wall-clock** — distinguish *hung* from *slow but
 *    progressing* (search [60] / service [50] data-transfer sharpening). A **data-transfer** op — a large-workspace
 *    `suspendVM` snapshot, a big `writeFile`/`readTextFile` — may legitimately run for minutes; a fixed short
 *    wall-clock would false-kill the (durable-checkpoint *命门*) path. So such ops bound on an **idle/no-heartbeat**
 *    window (reset by observable progress), not total elapsed time. Cheap control RPCs (`isRunning`, a small
 *    `connect` handshake) may use a short wall-clock. The adapter sizes the bound per op class.
 * 3. **A liveness breach surfaces as a typed, retryable error**: `RemoteExecutionError` code `"liveness_no_output"`
 *    for an exec stream's silence window and `"timeout"` for the lifecycle ops' idle bound; for the inherited filesystem ops (which return the vendored `Result<_, FileError>`),
 *    a `FileError` — but still **bounded, never an unbounded wait**. Retry is the caller's decision per the op's
 *    idempotency; the adapter MUST NOT blind-retry.
 */
export interface RemoteExecutionEnv extends ExecutionEnv {
    /**
     * Identity of the connected workspace (design/48 §5 gap 1). Synchronous: it is data the env already holds.
     *
     * The engine reads it once per leg, when the leg's workspace settles — after the leg's restore seat established the
     * environment ({@link connect} / {@link resumeVM}) — to learn which target the leg is on ({@link reportedPlacementTarget}):
     * the fence every agent the leg spawns or wakes is minted under. A target-bound adapter (one whose handle states
     * `deviceId`) answers it from construction on; an adapter that cannot answer even after the establishment call (it
     * throws) gives its leg no target, and that leg's agents carry no fence.
     */
    workspaceHandle(): WorkspaceHandle;
    /**
     * Provision/attach the remote workspace and inject secrets. Returns the resulting {@link WorkspaceHandle}.
     *
     * The engine calls this at the leg's restore seat, on an environment its factory minted for that leg — every leg that
     * does not restore a snapshot (a leg that restores one calls {@link resumeVM} there instead) — with the run's cancel
     * signal as `abortSignal`: once, and when that call answers a code of {@link RETRYABLE_REMOTE_ERROR_CODES} once more at
     * once (the reconnect the run's first operation would make, made before it; in its answer a deployment's `env.` code fails the run
     * before it starts, as in the first, and any other answer lets the run start). It MUST be
     * idempotent: on an environment that is already connected it answers
     * the current handle and provisions nothing (the seat is commonly NOT the first connection: a delegated child, a
     * factory that writes into the environment before handing it over, a parked leg's reconnected environment). A connect
     * that answers a failure has either provisioned nothing, or left what it provisioned where the next connect finds and
     * reuses it — never a second workspace beside the first. How the engine reads a failure is
     * {@link RETRYABLE_REMOTE_ERROR_CODES}: a code in it, `unknown` or `aborted` lets the run start (past a code in it,
     * after the one reconnect above, unless that reconnect answered an `env.` code), and its first operation meets the environment
     * as it would have; any other code in the first answer is this environment's standing refusal and fails the run before it
     * starts, with that code. A connect that throws, or answers anything but this method's result shape
     * (an `error` with a string `code`), is read as `unknown`.
     */
    connect(config?: RemoteConnectConfig): Promise<{
        ok: true;
        value: WorkspaceHandle;
    } | {
        ok: false;
        error: RemoteExecutionError;
    }>;
    /**
     * Snapshot the workspace and (provider permitting) stop billing; returns the {@link SnapshotId} to resume from.
     *
     * **Council #4 — must not leave an in-flight command hung.** If a {@link Shell.exec}/{@link execStream} is in
     * flight, an implementation MUST either (a) refuse with `RemoteExecutionError("command_in_flight")`, or (b)
     * abort the in-flight command — buffered `exec` then resolves an `Err` and an in-flight {@link execStream}
     * iterator throws `RemoteExecutionError("suspended")`. It must NOT silently snapshot and leave the command's
     * promise/iterator pending forever.
     *
     * **🔴 Atomicity contract (design/49 v1.5, code-ready council BUG#1/#13).** This is the FIRST durable side
     * effect of a remote durable-suspend, so its all-or-nothing semantics are load-bearing for the Runner's
     * commit ordering:
     * - `{ok:true}` ⇒ the VM is paused at `value` (a `SnapshotId`); the caller may now persist a checkpoint.
     * - `{ok:false}` ⇒ the VM is left in its ORIGINAL (running) state, untouched — the caller can safely fall
     *   back to the synchronous `onAsk` gate as if no suspend was attempted (Runner: design/49 §4①).
     * An implementation MUST NOT return `{ok:false}` after it has already paused/snapshotted the VM. The gate
     * path means no command is in flight (the batch's prior calls are awaited, the gated call has not run), so
     * `command_in_flight` should not arise; if it does, the Runner treats it as an ordinary `{ok:false}` and
     * falls back to `onAsk` — see {@link RemoteExecutionErrorCode}.
     */
    suspendVM(options?: VmLifecycleOptions): Promise<{
        ok: true;
        value: SnapshotId;
    } | {
        ok: false;
        error: RemoteExecutionError;
    }>;
    /** Restore the workspace from a snapshot. Idempotent + re-entrant (a replica that crashed mid-suspend can be
     *  superseded by another resuming the same {@link SnapshotId} without corruption — aligns with design/45 resolve-CAS).
     *  Pass `options.abortSignal` so a hung restore cannot pin the resuming worker (design/49 BUG#2). */
    resumeVM(snapshotId: SnapshotId, options?: VmLifecycleOptions): Promise<{
        ok: true;
        value: WorkspaceHandle;
    } | {
        ok: false;
        error: RemoteExecutionError;
    }>;
    /** Re-attach the control-plane transport to a still-running VM after a control-plane reconnect (design/48 §5 gap 4). */
    reconnect(sessionToken: SessionToken): Promise<{
        ok: true;
        value: WorkspaceHandle;
    } | {
        ok: false;
        error: RemoteExecutionError;
    }>;
    /**
     * Re-establish consistency AFTER {@link resumeVM}/{@link reconnect} (design/48 §5 gap, council #8): re-fetch git
     * remote refs + invalidate stale package/index caches, and re-inject secrets (short-lived credentials may have
     * expired while suspended). Any failed step → `Err("post_resume_failed")` and the caller MUST destroy the env.
     *
     * Note: a resumed guest's network/long-lived connections (git remote / API / registry) are NOT guaranteed to
     * survive the snapshot (decision 2), so this is also where the VM-internal agent rebuilds those.
     *
     * 🔴 Ordering red line (design/48 §5/#6): at-rest encryption of the memory snapshot must be ensured BEFORE
     * secrets are injected — never let plaintext credentials land in an unencrypted snapshot. That encryption is a
     * service-side property of the snapshot store; this method must fail-and-clean if it cannot be guaranteed.
     *
     * `opts.abortSignal` (design/384 slice 2, ADDITIVE — implementations are not forced to change): an
     * early-release channel for a caller whose wait on this init is bounded (the park fence's paused-VM
     * compensation). Best-effort exactly like {@link suspendVM}'s — an implementation may ignore it; the
     * caller bounds its own wait and treats a deaf adapter as failed.
     */
    postResumeInit(opts?: {
        abortSignal?: AbortSignal;
    }): Promise<{
        ok: true;
        value: void;
    } | {
        ok: false;
        error: RemoteExecutionError;
    }>;
    /**
     * Stream a command's output (design/48 §5 gap 3) — the standard path for long build/test runs. Distinct from
     * the buffered base `exec()` (council #3: no overload). Yields `stdout`/`stderr` chunks then exactly one `exit`
     * chunk; the iterator throws {@link RemoteExecutionError} if the stream fails before `exit` (see {@link OutputChunk}).
     *
     * 🔴 **Timeout/liveness contract (service [45]/[59]) — applies to BOTH `execStream` and the base `exec`:** a
     * per-command timeout is **independent of the env/sandbox lifetime** and an adapter MUST NOT fall back to the
     * lifetime when none is given (else a hung provider RPC pins the worker for the whole sandbox lifetime). An
     * adapter SHOULD enforce a bounded default liveness/idle timeout that also covers the command-creation RPC, and
     * surface a silence breach as a typed, retryable {@link RemoteExecutionError} code `"liveness_no_output"` and a
     * wall-clock breach as `"timeout"`. See
     * {@link ExecStreamOptions.timeout} / {@link ExecStreamOptions.readTimeoutMs}.
     */
    execStream(command: string, options?: ExecStreamOptions): AsyncIterable<OutputChunk>;
    /**
     * Tear down the workspace and release provider resources. Best-effort; must never throw (like `cleanup`).
     * **Must be idempotent** — safe to call more than once (the second call is a no-op). The Runner calls it
     * once on task end, and `prepareTask` calls it on a prepare-time throw; a remote impl may also be reaped,
     * so a defensive double-call must not error or double-bill. One leg is not torn down: a leg handed
     * {@link ExecutionEnvFactoryContext.priorHandle} that ends before its approved action starts, while its
     * checkpoint row is pending again (or cannot be proven otherwise) — see that member, and {@link releaseToRow}.
     *
     * contract note: on a NON-isolated env (no `capabilities.isolation` — host lane, SSH host),
     * destroy() is workspace/object-level cleanup and must NOT reap still-running background processes —
     * that is `disposeBackgroundShells`' job, which honours the timeout/session keep-alive except-list
     * (monitor timeout anchor). An isolated env (container/VM) naturally takes everything down;
     * the Runner's envDying settle accounts for that with an accurate killed receipt beforehand.
     */
    destroy(): Promise<void>;
    /**
     * Keep what the workspace holds now (a snapshot, a push — the adapter's own means). OPTIONAL: an env without it is never
     * asked, and its workspace is kept exactly as before (by whatever its `destroy()` or its host does). Present ⇒ the engine
     * calls it on the env a leg works in, at each moment a stretch of work on it stops:
     *  · `"turn_end"` — once per turn, where the agent would otherwise stop (before the follow-up drain and the stop gate);
     *    when the leg parks durably (before `suspendVM`, or before the park-only identity capture); and at the leg's end when
     *    its env is not destroyed and a turn ran since the last sync the adapter answered;
     *  · `"destroy"` — before the engine destroys a leg's own env at the leg's end, and before `Runner.rewindFiles` lets go of
     *    the env it rewound (a rewind that moved a file).
     * Never twice at once for one workspace — one env object, or handles naming one provider and sandbox id, both read when the
     * engine checks (what it can tell; an adapter whose connections re-mint the sandbox id, or whose handle cannot be read at that
     * moment, stops writing once `abortSignal` fires, or serializes by its own storage key): a call waits for the one before it,
     * unless the engine abandoned that one ({@link WorkspaceSyncOptions.abortSignal}) — then it is not made, and nothing starts
     * beside the abandoned call until it settles. Each wait is bounded; at the bound, at a run's cut (a `"turn_end"` sync) or on a
     * failure, the engine goes on as if the sync had answered: no failure changes the run's result (the time a sync takes counts
     * toward the run's walltime, as every wait does). Before `destroy()`, every sync of that workspace still running has had its
     * `abortSignal` fired; a `destroy()` waits for or cancels it. A failure (an `{ ok: false }` answer, a throw or another shape —
     * read as `unknown` —, a bound passed — `timeout` —, the run cut — `aborted` —, not made beside an abandoned sync —
     * `command_in_flight`, told once per run) is told to the operator (`workspace.sync_failed`) and, when the run's result is still
     * open, recorded on `TaskResult.remoteEnvFailures` (`op: "syncWorkspace"`; `attempts` 1, or 0 for a sync not made). A turn's
     * end whose sync the adapter did not answer (its bound, the cut, not made) is owed again at the leg's end on an env the engine
     * does not destroy — a whole bound of its own, not cut by the run's cut, after `done` and before `result()`. Never throw; the
     * engine does not retry an answered sync.
     */
    syncWorkspace?(reason: WorkspaceSyncReason, options: WorkspaceSyncOptions): Promise<WorkspaceSyncAnswer>;
    /**
     * Let go of an env the engine leaves to its checkpoint row. OPTIONAL: an adapter without it gets no {@link destroy} on such an
     * env and no other call in its place — the engine drops its reference, and reclaiming the env is the adapter's own. Present ⇒
     * the engine calls it exactly once, on the env of a leg handed {@link ExecutionEnvFactoryContext.priorHandle} that ended by a
     * throw before the row's pending action started (the approved tool absent or replaced; a prepare refusal that keeps the env —
     * that member names the refusals that destroy it), once the row is pending again or its state cannot be proven. A leg that ends
     * by a returned result (cancelled or out of time before the action) is not asked. The row is reopened FIRST and its next retry
     * is not held back: that retry — in this process or another, on this object or another — may establish or wake the workspace
     * while this call runs. Act only on what this env object itself established (the instance its own restore made, the wake it was
     * handed): never on a workspace a later leg established or woke, never ending the workspace the row recorded. A snapshot adapter
     * frees the instance it restored (the snapshot stays); one that pauses in place and pauses again here fences that pause by its
     * own wake generation — one that cannot leaves this member out. Bounded like a teardown; its answer, a throw or no answer never
     * changes the leg's result. The engine makes no other call on this object for this leg; a factory may hand it to a later leg,
     * which establishes it at its restore seat, and this process's paused-env record may still {@link destroy} it when the row ends.
     */
    releaseToRow?(): Promise<void>;
}
/**
 * Why the engine asks an {@link ExecutionEnvFactory} for an env ({@link ExecutionEnvFactoryContext.purpose}):
 *  · `"run"` — a leg's own env (one per leg, destroyed when the leg ends unless left to its row: `priorHandle`); every leg, a delegated child's included;
 *  · `"rewind_files"` — `Runner.rewindFiles`, out of any run; writes only the session's tracked files;
 *  · `"read_changes"` — read-only readings outside any run (`Runner.readSessionChanges`, `Runner.previewInstructions`); writes nothing.
 */
export type ExecutionEnvPurpose = "run" | "rewind_files" | "read_changes";
/** The closed set of {@link ExecutionEnvPurpose} words, frozen. */
export declare const EXECUTION_ENV_PURPOSES: readonly ExecutionEnvPurpose[];
/**
 * The code of the refusal a factory throws for a {@link ExecutionEnvFactoryContext.purpose} it does not serve — the one
 * factory refusal the engine itself answers: as no hands (`Runner.rewindFiles` ⇒ `rewind.files_env_unsupported`). Read as the
 * thrown value's OWN `code`: any other refusal a factory throws reaches the caller unchanged, one that wraps this one in its
 * `cause` chain included.
 */
export declare const ENV_PURPOSE_UNSUPPORTED = "env.purpose_unsupported";
/** Context handed to an {@link ExecutionEnvFactory} for each task (design/48 §5 / §7 Q7). Deliberately minimal:
 *  per-task identity is enough to allocate/route a per-task container; richer routing (tenant/principal) is
 *  captured in the factory closure by the trusted control plane that builds it. */
export interface ExecutionEnvFactoryContext {
    /**
     * Why the engine asks for this env — always present. `"run"`: a leg's own env (one per leg, destroyed when the leg ends unless left to its row: {@link priorHandle}) —
     * the meaning every factory call had before this member; every leg, a delegated child's included. `"rewind_files"`:
     * `Runner.rewindFiles`, out of any run; writes only the session's tracked files. `"read_changes"`: read-only readings
     * outside any run (`Runner.readSessionChanges`, `Runner.previewInstructions`); writes nothing — asked only of a factory the
     * deployment declares answers it (`RunnerDeps.executionEnvFactoryHonorsReadChanges`).
     *
     * For a purpose other than `"run"` a factory ATTACHES to the workspace the session's runs use (the same directory / host /
     * device) and never mints one — or refuses: a refusal coded {@link ENV_PURPOSE_UNSUPPORTED} when it does not serve the
     * purpose (the engine answers it as no hands; a purpose word the factory does not know is refused the same way), or its own
     * refusal when it serves the purpose but holds no workspace for this session (none registered and none requested; the
     * requested directory is not one), passed to the caller unchanged. The Runner destroys every factory env it gets; for a
     * purpose other than `"run"` that `destroy()` only detaches, and the env writes only what its purpose requires
     * (`"read_changes"`: nothing).
     */
    purpose: ExecutionEnvPurpose;
    /**
     * The directory this env must stand at, when its caller requires one: an Agent call's explicit `cwd` (also handed as
     * {@link parentCwd}, unchanged), or the `cwd` a `Runner.rewindFiles` caller states. An absolute host path
     * (`isAbsoluteHostPath`, `@sema-agent/primitives`) — a Windows drive or UNC path included, which the engine admits by shape
     * and leaves to the factory to resolve. A factory MUST root the env there or refuse (its own refusal, passed through); the
     * engine refuses an env that stands elsewhere (`config.cwd_not_honored`) and a directory outside a declared
     * `RunnerDeps.rootPath` (`config.cwd_outside_root`) before using it. The env MUST stand on an absolute path of its own family,
     * and this directory must be one there — its `absolutePath` answers each as written; a path the env reads as relative (a drive
     * or UNC path handed to a posix env) is refused the same way (`config.cwd_not_honored`), so a factory refuses such a directory
     * itself, before creating anything for it. ABSENT (not an `undefined` value) ⇒ none required.
     */
    requestedCwd?: string;
    /** Resolved session id for the task — the stable identity of its per-task workspace. */
    sessionId: string;
    /**
     * design/380 O1① — the run TREE's placement root (fixed point), minted by prepare AFTER session
     * resolution as `internals.placementRoot ?? internals.rootSessionId ?? sessionId` — a top-level
     * run's own resolved sessionId, every descendant's inherited root, verbatim (delegation and
     * workflow spawn chains re-thread an explicit `placementRoot` — C12; a bare DURABLE RESUME crosses
     * too since design/380 O1③: the suspend mint stamps the fixed point on the checkpoint and the
     * resume restores it into trusted internals — formerly the pinned residual). A target-bound
     * factory (device lane) keys its placement lookup on THIS, never on `sessionId` (a child's fresh
     * session id must not read as a new placement). Always present and non-empty — an empty value is
     * an assembly error the engine refuses loudly where the run's internals are composed (`config.placement_root_invalid`) and a
     * factory MUST refuse loudly too (loud-bad-value posture), never default around.
     */
    placementRootSessionId: string;
    /**
     * Caller-supplied task id: present only on a leg whose caller set `TaskSpec.taskId`. A child spec the engine builds (a
     * delegated agent of any kind, a revival) never carries one — such a leg's task id IS its session id — so a factory
     * MUST NOT identify a descendant by this key; the tree is {@link placementRootSessionId}, the leg {@link sessionId}.
     */
    taskId?: string;
    /**
     * design/97 CORE-6 — per-task ISOLATION request threaded from the workflow's `ctx.agent({ isolation })` via
     * the TRUSTED `RunInternals` channel (never from the untrusted `TaskSpec`). When `"worktree"`, a
     * control-plane factory **MUST either mint a git-worktree-rooted env for this agent (e.g. via
     * {@link addWorktree}) WITH a `destroy()` that removes the worktree, or THROW.** It MUST NOT silently
     * return a non-isolated env (the shared base env, or a child rooted at `parentCwd`): the spawn may be
     * governed by a relaxed write baseline (`WorkflowGovernanceBaseline.worktreeBase`) that is safe ONLY
     * inside a worktree — a silent degrade would point those writes at the shared working tree. A factory
     * throw fails the spawn (fail-closed: the child never starts) — the honest outcome. The engine
     * additionally rejects the observable degrade shapes at its consumption point (no factory configured;
     * the shared static env returned as-is; an in-process env rooted at the base root or the parent's cwd),
     * but full worktree verification is the factory's contract — there is no receipt field on
     * {@link ExecutionEnv}. Unset = default (the factory's normal per-task env).
     */
    isolation?: "worktree";
    /**
     * Field-reported (sub-agents landing in an EMPTY sandbox): the PARENT task's
     * effective working root, threaded (like `isolation`) via the TRUSTED `RunInternals` channel when this
     * task is a sub-agent (workflow `ctx.agent` / Task delegation). CC parity: a Task sub-agent inherits the
     * main session's cwd. A single-user/TOC factory SHOULD root the child env here (unless `isolation`
     * requests a worktree — that wins); a multi-tenant/TOB factory minting isolated containers may ignore
     * it. When the same directory also arrives as {@link requestedCwd} (an Agent call's explicit `cwd`) it is a requirement:
     * the env must stand on it as an absolute path of its own family, or the engine refuses (`config.cwd_not_honored`). Absent on top-level tasks. Static shared-`executionEnv` deployments need nothing — the child
     * already shares the parent env (and its cwd). When the parent works in a managed tree (a session's own
     * tree), the child MUST be rooted at this hint or inside that tree: an env the factory roots elsewhere on
     * the host — the base checkout the tree isolates, another tree — is refused before the child's first turn
     * (`workspace.isolation_unavailable`, `factory_ignored_hint`); a declared sandbox off the host's disk
     * (`hostLocalPaths: false` with `isolation: true`) is another namespace and is not judged.
     */
    parentCwd?: string;
    /**
     * The placement FENCE — this context's one answer to "on which target must THIS leg's env be minted". Every leg
     * learns its own target once, when its workspace settles (what its env reports, {@link reportedPlacementTarget});
     * that one value is the fence of every leg it hands work to:
     *  · an agent it spawns (a delegated child of any kind, a workflow agent) or wakes (a retained or revived agent: the
     *    WAKING leg's target, never one remembered from the spawn);
     *  · a later leg of the same piece of work — a cascade rung after the first, a verification gate's verifier and fix
     *    legs — carries the FIRST leg's target;
     *  · a durable resume leg carries its checkpoint row's target, member by member over the one its waking leg hands it
     *    (a member the row states wins; a row recorded without `deviceId` takes the waking leg's).
     * The key is ABSENT (not an `undefined` value) on a top-level first leg its host gave no fence
     * (`RunInternals.placementTarget`), and on a leg whose spawning leg has no target of its own (its env is not remote,
     * or could not answer `workspaceHandle()` when its workspace settled). A frozen value; mutating it reaches nothing.
     *
     * A factory bound to a target (the device lane) **MUST** mint the env on the device `placementTarget.deviceId` names
     * and, when it cannot (offline, busy, the placement moved to another device), **THROW** a typed refusal. It **MUST
     * NOT** connect some other device and leave the engine to notice, and it **MUST NOT** choose the target by the
     * current binding of {@link placementRootSessionId}: it may read that binding only to find that it differs from the
     * fence, and then refuse. A fence without `deviceId` states no device to honor; the factory then follows its
     * ordinary routing.
     *
     * The minted env's `workspaceHandle()` **MUST** report the device its connection actually reached; it is never
     * copied from the fence. The engine checks every fenced leg with one receipt ({@link placementHonored}: the report
     * names the fence's `deviceId` whenever the fence carries one, and a report that cannot be read names none): a leg
     * restoring a checkpointed workspace that fails it is refused `resume.env_failed` (that restore also requires the
     * checkpointed `provider`), any other leg `config.placement_not_honored`, before it runs. The receipt TRUSTS the report: a factory that connected elsewhere and
     * reports so is refused, only after the wrong connection was made, but one that echoes the fence while connecting
     * elsewhere defeats its own protection and passes. On a resume leg the fence moves no refusal earlier than it was:
     * it runs after the claim, so what a deployment can still catch BEFORE the claim is `RunnerDeps.resumePreflight`
     * alone.
     */
    placementTarget?: PlacementTarget;
    /**
     * The workspace THIS leg must go back to. Present exactly on a leg that resumes a checkpoint row which recorded one
     * (`CheckpointState.workspaceHandle` — a park-only row and a snapshot row alike), as that handle's one frozen copy
     * ({@link frozenHandleCopy}: the SAME object the resume preflight's facts and the restore's
     * {@link VmLifecycleOptions.priorHandle} carry): exactly the declared members the row carries as strings — `sandboxId`,
     * `provider`, `mountPath`, and `snapshotId` / `sessionToken` / `restoreMode` / `deviceId` when recorded; writing to it
     * throws. Only the row this leg itself resumes: no leg it spawns, wakes or hands work to inherits it.
     *
     * Present ⇒ the factory **MUST** go back to that workspace — a park-only row (`restoreMode: "park_only"`, no
     * `snapshotId`): attach to it where it persists (the same container / directory / device, at its `mountPath`); a
     * snapshot row: mint an env whose `resumeVM` restores into it — or **THROW** its own refusal (an `env.` code spelled as
     * {@link isDeploymentEnvCode} reads it ends the leg as the environment refusing itself, and the row returns to pending under
     * `config_refused`, taking a fresh decision — unless it was already a replay-only reopen, or the code is the engine's own
     * `env.lifetime_expired`: then `env_failed`, replay only). It **MUST NOT** mint a fresh workspace in its place: the
     * engine does not compare `sandboxId` (an adapter that reconnects may mint a new one per connection), so a fresh
     * workspace at the same `mountPath` is not caught. On which target to mint is still {@link placementTarget}'s answer
     * alone (folded from this same copy: a member the row states wins), never this member's.
     *
     * ABSENT (not an `undefined` value) ⇒ no workspace was recorded for this leg — a first leg, a delegated child, a
     * retained agent woken from its in-process snapshot (no checkpoint row), a later leg of a composition, a resume of a row
     * that recorded none, a purpose other than `"run"` — and the factory mints as usual. A parked agent revived through its
     * checkpoint row, a workflow's parked child driven on, a resume in this process or another: each resumes a row, so each
     * carries its own row's handle.
     *
     * The env minted for this member belongs to that row until the leg's approved action starts. A leg that ends before then
     * leaves the env as the row's outcome says: the row pending again, or its state unprovable ⇒ the engine drops its reference
     * and does NOT call `destroy()` — on a thrown exit, after the reopen, it calls {@link RemoteExecutionEnv.releaseToRow} once when
     * the env carries it, and nothing in its place when not (the workspace is what the row's retry goes back to; the adapter reclaims an env no retry
     * comes for); the row not coming back ⇒ `destroy()`, as on every other leg's end. Destroyed at the refusal itself, whatever
     * the row: an env whose own report disproves the recorded workspace (another `provider`; another `deviceId` where the row
     * recorded one; on a park-only row, a root the env resolves to another directory) and one whose `postResumeInit` failed.
     */
    priorHandle?: Readonly<WorkspaceHandle>;
}
/**
 * A **trusted control-plane** factory that mints a per-task {@link ExecutionEnv} (design/48 §5 answers core
 * gap-a / §7 Q7). Lives on `RunnerDeps` (deployment-level) — NOT on `TaskSpec` — so an untrusted caller can
 * never inject its own env and escape the sandbox (design/44 §7 Q4 red line; decision 3: the Docker
 * fast-lane must be control-plane-assigned, never task-selectable).
 *
 * The remote model is "one container per task", so the factory is invoked once per task. The Runner owns the
 * lifetime of a factory-produced env: if it implements {@link RemoteExecutionEnv.destroy} (see {@link hasDestroy}),
 * the Runner calls it when the task ends — save on a resume leg that ends before its approved action while its row comes
 * back ({@link ExecutionEnvFactoryContext.priorHandle}).
 */
export type ExecutionEnvFactory = (ctx: ExecutionEnvFactoryContext) => ExecutionEnv | Promise<ExecutionEnv>;
/** True when `env` exposes a lifecycle {@link RemoteExecutionEnv.destroy} the Runner should call on task end. */
export declare function hasDestroy(env: ExecutionEnv): env is ExecutionEnv & Pick<RemoteExecutionEnv, "destroy">;
/** True when `env` carries the {@link RemoteExecutionEnv.syncWorkspace} seat — the one reading of its presence. A member
 *  that cannot be read, or is not a function, is no seat (the run's admission census announces such a value). */
export declare function hasWorkspaceSync(env: ExecutionEnv): env is ExecutionEnv & Required<Pick<RemoteExecutionEnv, "syncWorkspace">>;
/** True when `env` carries the {@link RemoteExecutionEnv.releaseToRow} seat — the one reading of its presence, read as
 *  {@link hasWorkspaceSync} reads its seat (the run's admission census announces a present non-function). */
export declare function hasReleaseToRow(env: ExecutionEnv): env is ExecutionEnv & Required<Pick<RemoteExecutionEnv, "releaseToRow">>;
/** Structural check that `env` implements the remote seam (lifecycle + streaming surface), answering only whether
 *  those methods can be called — never a capability. The block conjunct keeps an adapter that carries no capability
 *  block at all (a JS adapter the compiler never saw) off the remote paths, as before the block moved to the base; it
 *  is read off the block's one receipt ({@link capabilityReceiptOf}), never off the adapter again. */
export declare function isRemoteExecutionEnv(env: ExecutionEnv): env is RemoteExecutionEnv;
/**
 * The RESTORE half of the suspend contract — the methods the RESUME leg calls after a `suspendVM`
 * ({@link RemoteExecutionEnv.resumeVM} + {@link RemoteExecutionEnv.postResumeInit}). Returns the names an
 * adapter is MISSING (empty = complete).
 *
 * Split out from {@link isRemoteExecutionEnv} deliberately: that predicate answers "can this env be driven
 * as a remote env at all" (a park-only SSH/ADB host legitimately never restores a VM and is checked with
 * it), while THIS one answers "if I snapshot this env now, will the resume leg find a way back". Naming the
 * missing methods lets the suspend-time guard say WHICH part of the adapter is absent instead of failing on
 * the resume leg — a different process, hours later — with a bare `env.resumeVM is not a function`.
 */
export declare function missingRestoreSurface(env: ExecutionEnv): readonly ("resumeVM" | "postResumeInit")[];
/**
 * The capability readers (#2891). Every key of {@link ExecutionEnvCapabilities} is read through exactly one of the
 * functions below, on every environment — a local one declares the block as a remote one does, so no reader asks the
 * remote INTERFACE first and none gives a non-remote environment a fixed answer.
 *
 * Each reader takes only the boolean the adapter declared, off the block's one receipt ({@link capabilityReceiptOf}):
 * the adapter's block is read once and every reader reads that frozen copy. A value that is absent, not a boolean, or
 * cannot be received (a throwing getter, a Proxy) is no declaration, and the reader answers that key's SAFE side, one
 * row per key in {@link UNDECLARED_CAPABILITY_READING}. The readers never throw and never announce: the admission
 * census does, once per run per finding (`config.execution_env_capability_invalid`).
 */
export declare const UNDECLARED_CAPABILITY_READING: {
    readonly isolation: {
        readonly reads: false;
        readonly so: "no reader treats the environment as a sandbox: autonomy, the policy tiers and the read boundary's containment legs stay on their checking side";
    };
    readonly suspendable: {
        readonly reads: "undeclared";
        readonly so: "the snapshot reader takes only a declared `true` and the park-only lane only a declared `false`, so the environment is neither snapshot nor parked, and a run on it cannot suspend durably";
    };
    readonly sharesProcessTable: {
        readonly reads: "undeclared";
        readonly so: "whether the commands it runs are processes on this engine's own process table has no default, so the Bash tool refuses every pattern kill that needs the question (`pkill`, `killall`, a `kill` fed by `pgrep`; `pkill -P $$`, the shell's own children, runs) on this environment — declare `true` when its commands run on a table that holds the engine (a host lane, or a PID namespace that contains the engine's), `false` only when they run where the engine is not (another machine, a PID namespace that does not contain it)";
    };
    readonly canonicalPathAuthoritative: {
        readonly reads: true;
        readonly so: "its resolver's silence is read as a failure, so a command chain it cannot answer at all is refused at the read boundary's execute-time recheck instead of passing on its written spelling";
    };
    readonly hostLocalPaths: {
        readonly reads: "undeclared";
        readonly so: "the engine does not treat a path this environment names as the host's own file, and a worktree child on it is refused (its tree can be neither compared nor exempted)";
    };
    readonly externalContentTarget: {
        readonly reads: "undeclared";
        readonly so: "what it produces is treated as content from outside the deployment's trust boundary (the memory session mark), and a call that reaches it owes what reaching the target and what leaving it both owe (the cross-boundary taint)";
    };
    readonly io: {
        readonly reads: "undeclared";
        readonly so: "no shell face mounts on it, and what it names is still read through it (the project marker), never past its own read limits";
    };
    readonly keepsReadFloor: {
        readonly reads: false;
        readonly so: "it is read as not keeping the byte floor, so a run whose read-deny table is non-empty is refused at prepare when the deployment sets `readDenyFloorRequired`, and otherwise announced as such (`config.read_deny_floor_unkept`) when the caller brought rows of its own";
    };
    readonly commandSandbox: {
        readonly reads: false;
        readonly so: "it is read as keeping no command sandbox, so a run that requires one (`TaskSpec.sandbox.enabled`) is refused at prepare, or — under `failIfUnavailable: false` — announced (`config.command_sandbox_unavailable`) and run unsandboxed";
    };
};
/** The keys of {@link ExecutionEnvCapabilities}, in declaration order — the census walks exactly these. */
export declare const CAPABILITY_KEYS: ReadonlyArray<keyof ExecutionEnvCapabilities>;
/** One finding of a block's receipt: a key of the block not declared as a boolean (`expected: "boolean"`), the block itself
 *  when it is not an object or cannot be received (`key: "capabilities"`, `expected: "object"`), or a member the block carries
 *  that is no capability (`expected: "absent"`: a misspelled or retired key, whose value no reader takes). */
export interface CapabilityBlockFinding {
    readonly key: string;
    /** The type the member carries (`"undefined"` where it is absent), or `"unreadable"` where it could not be received. */
    readonly valueType: string;
    readonly expected: "boolean" | "object" | "absent";
}
/** What the engine holds of an environment's capability block: the booleans it declares (the nine keys only, frozen), whether the block is
 *  an object at all (the remote predicate's block conjunct), and the receipt's findings, in key order and then member order. */
export interface CapabilityReceipt {
    readonly declared: Readonly<Partial<Record<keyof ExecutionEnvCapabilities, boolean>>>;
    readonly blockIsObject: boolean;
    readonly findings: readonly CapabilityBlockFinding[];
}
/**
 * The ONE receipt of an environment's capability block: read off the adapter once per environment object — at its first read,
 * which for a run's environment is the run's admission census — and held frozen; every reader, the census and the remote
 * predicate read this receipt and never the adapter again, so what the census announced is what every reader acts on, and a
 * block the host changes afterwards changes nothing the engine reads. A value that is not an object (a JS caller's `null`) has
 * no block and is not remembered. Total: it never throws.
 */
export declare function capabilityReceiptOf(env: Pick<ExecutionEnv, "capabilities">): CapabilityReceipt;
/**
 * What this environment declares about snapshots, in three states: `true` (it can be snapshot and restored), `false`
 * (it cannot — and, on a remote environment, its workspace is externally durable, the park-only degrade's premise), or
 * `"undeclared"` (absent, not a boolean, unreadable). The snapshot reader ({@link isSuspendable}) takes only `true`, the
 * suspend paths' park-only lane only `false`; an undeclared environment is in neither, so a run on it cannot suspend
 * durably.
 */
export declare function declaredSuspend(env: Pick<ExecutionEnv, "capabilities">): boolean | "undeclared";
/**
 * Can this env be durably suspended/snapshotted (design/61 §9 A)? Use this — NOT the structural
 * {@link isRemoteExecutionEnv} — before calling `suspendVM` (a non-suspendable SSH/ADB env declares
 * `capabilities.suspendable: false` but still has the method, which returns `"unsupported"`). An environment
 * without the remote interface has no `suspendVM` to call, whatever it declares.
 *
 * A composite type guard (declaration AND interface AND restore surface) so a `suspendVM` call site narrowed by THIS
 * predicate gets the {@link RemoteExecutionEnv} type without a cast — `true` always implies the structural check too.
 * The declaration is read through {@link declaredSuspend}: only the boolean `true` counts.
 *
 * It also requires the RESTORE surface ({@link missingRestoreSurface}). A suspend is only durable
 * if something can undo it; an adapter that offers `suspendVM` but no `resumeVM` used to pass this guard,
 * take a real snapshot, commit a real checkpoint — and then blow up on the resume leg with an untyped
 * TypeError. "Suspendable" now means the whole round trip, so a half-adapter is rejected at the suspend site
 * where the deployment can still be told which method it owes.
 *
 * ⚠️ A capability-DECLARING but restore-incomplete adapter must NOT be re-routed to the durable-park-only
 * degrade by this predicate returning false — park-only rests on the workspace being externally durable
 * (see `ExecutionEnvCapabilities.suspendable`), which a snapshot backend does not have. Call
 * sites split the two cases on the DECLARED `capabilities.suspendable` flag ({@link declaredSuspend}), not on this predicate alone.
 */
export declare function isSuspendable(env: ExecutionEnv): env is RemoteExecutionEnv;
/** The code a refusal carries for each clause of {@link suspendTargetGapRowOf} — one derivation, two projections (code / clause). */
export type SuspendTargetGapCode = "env_not_remote" | "env_suspend_undeclared" | "env_restore_incomplete";
/**
 * The ONE "no suspend target" fact for a per-task environment (`ownedEnv`), as a row (its `code` and the `clause`): the clause every suspend lane refuses on, so a lane
 * never has its own reading of "may this run pause here" — the tool-ask park, the plan-approval park and the resource lanes read this,
 * and the plan-exit tool's result is worded from it. A per-task env belongs to a suspend target by the remote seam and its
 * DECLARATION ({@link declaredSuspend}): `true` ⇒ snapshot, `false` ⇒ park-only. Every per-task env in neither is named here, where the
 * deployment can still be told what it owes: one without the remote seam (destroyed on suspend), one whose `suspendable` is no boolean
 * (named by the type it carries), and one declaring `true` without the whole restore surface. `undefined` with no per-task env, and for an
 * env that has a target.
 */
export declare function suspendTargetGapRowOf(ownedEnv: ExecutionEnv | undefined): {
    readonly code: SuspendTargetGapCode;
    readonly clause: string;
} | undefined;
/** The clause projection of {@link suspendTargetGapRowOf} (the sentence every suspend lane refuses with). */
export declare function suspendTargetGapOf(ownedEnv: ExecutionEnv | undefined): string | undefined;
/** The sentence an approval or question park refuses with over a {@link suspendTargetGapOf} clause — what the env lacks and which env would
 *  hold the park. One wording, two callers: the park closure's refusal, and the Runner's statement to its gate (`ToolGateInput.suspendTargetGap`),
 *  which the deny exit quotes when the gap alone made a delivery `close`. */
export declare function perTaskEnvParkRefusal(gap: string): string;
/**
 * Is this env an isolated sandbox (design/61 §9 A, design/53)? `false` for a real SSH host / ADB device AND
 * for an in-process env (the host process is not isolated: `NodeExecutionEnv` and `StubExecutionEnv` declare
 * `false`). The orchestrator tightens autonomy + the design/37 policy gate when this is `false` (zero-trust on an
 * un-isolated target). Isolation must be explicitly declared, never assumed, and that is why the flag is read
 * STRICTLY: every consumer of a `true` here RELAXES something (autonomy, a policy tier, a containment
 * leg that the sandbox is then answerable for), so a value that is not the boolean `true` — absent,
 * a string, a truthy object from a JS adapter the compiler never saw — is not a declaration and lands
 * on the checking side. This is the reading every consumer of the containment question comes through.
 * What no caller may do is infer isolation from the remote INTERFACE — implementing the seam is not
 * declaring containment, and a host-lane adapter drives the operator's own machine through it.
 */
export declare function isIsolated(env: Pick<ExecutionEnv, "capabilities">): boolean;
/**
 * Is CONTAINMENT this env's own job rather than the engine's — i.e. may a containment leg stop at the
 * written spelling and leave the rest to the target? True exactly for a DECLARED isolated sandbox: the
 * sandbox is the security boundary there, and its filesystem is not the one this process can resolve
 * (`canonicalPath` is an RPC into somebody else's namespace).
 *
 * The one question the `bash`/`bash_readonly` read boundary asks before deciding whether to re-resolve
 * a candidate through the filesystem, and the one both faces' DISCLOSURE reads, so a card can never
 * promise a refusal the leg does not issue (or omit one it does). Deliberately NOT the remote INTERFACE:
 * a non-isolated adapter (host lane, SSH host — see {@link RemoteExecutionEnv.destroy}'s contract note)
 * implements the whole seam while driving an ordinary machine whose paths its own `canonicalPath`
 * answers exactly, and reading the shape as containment made that deployment's boundary lexical-only.
 */
export declare function boundaryIsTheSandbox(env: ExecutionEnv): boolean;
/**
 * Does this env DECLARE that its `canonicalPath` is the authority on where a path lands?
 *
 * The question the execute-time read boundary asks about its own resolver's SILENCE. Resolving a
 * spelling walks it from the deepest answerable ancestor; when no ancestor answers at all, two
 * different worlds produce the same `undefined`: a resolver that is authoritative and is FAILING (an
 * RPC into the machine the command will run on, a transport that dropped), and an env that simply does
 * not answer path questions (an in-memory double, an adapter with no resolution surface). The first is
 * a question and the second is an absence, and reading both as the absence is what leaves a containment
 * leg silently open on an RPC-backed lane.
 *
 * So the adapter says which it is. Only a declared boolean is a declaration, and the undeclared reading is the
 * refusing one (`true`): an environment that does not say whether its silence is a failure has its silence read as
 * one, and is announced at its admission point — this reader does not validate. `NodeExecutionEnv` declares `true`,
 * which moves nothing on the local lane: its resolver answers `/`, so the arm this gates has no case to fire on.
 */
export declare function canonicalPathIsAuthoritative(env: Pick<ExecutionEnv, "capabilities">): boolean;
/**
 * Which process table this env's commands run on, as its adapter declares it
 * ({@link ExecutionEnvCapabilities.sharesProcessTable}):
 *  · `"this"` — a table that holds this process: an env that declares `true` (`NodeExecutionEnv`, whose commands are
 *    this process's children; a host lane);
 *  · `"other"` — an env that declares `false`;
 *  · `"undeclared"` — an env whose declaration is absent, not a boolean, or cannot be read (a throwing
 *    getter or Proxy trap). There is no default to fold it to, so the caller refuses what it cannot answer.
 * Total: it never throws. It does not announce — the admission census does, once per run.
 */
export declare function processTableOf(env: Pick<ExecutionEnv, "capabilities">): "this" | "other" | "undeclared";
/**
 * Where the paths this environment names land ({@link ExecutionEnvCapabilities.hostLocalPaths}), in three states: `true`
 * (the host's own files), `false` (somewhere the host does not mount at the same paths), `"undeclared"` — which each
 * consumer reads on ITS safe side: {@link pathsAreHostLocal} takes only `true`; the worktree child's exemption takes only
 * `false`. Total: it never throws.
 */
export declare function declaredHostLocalPaths(env: Pick<ExecutionEnv, "capabilities">): boolean | "undeclared";
/**
 * Is a path this environment names the same file on the engine host's filesystem? Only a declared `true` says so — the
 * engine never presents a path it cannot vouch for as a host path. Total: it never throws.
 */
export declare function pathsAreHostLocal(env: Pick<ExecutionEnv, "capabilities">): boolean;
/**
 * Is this environment a DECLARED sandbox off the host's disk — its paths another namespace's (`hostLocalPaths: false`) and its
 * containment its own job (`isolation: true`)? The one reading that exempts an environment from comparing its paths with the
 * caller's: the worktree request's guard and a delegated child's caller-tree floor both take it. Only the two declarations
 * together earn it; an undeclared or non-isolated environment off the host's disk (an SSH host, a device) does not. Total.
 */
export declare function isDeclaredSandboxOffHost(env: Pick<ExecutionEnv, "capabilities">): boolean;
/**
 * Does content this environment produces come from outside the deployment's trust boundary
 * ({@link ExecutionEnvCapabilities.externalContentTarget})? Three states: `true`, `false`, or `"undeclared"` (absent, not a
 * boolean, unreadable) — which each consumer reads on ITS safe side: the content fold as outside (`!== false`), the
 * cross-boundary lane as both the target and off it (the union of the two rows' obligations). Total: it never throws.
 */
export declare function targetIsExternal(env: Pick<ExecutionEnv, "capabilities">): boolean | "undeclared";
/**
 * Do this environment's filesystem and shell faces reach a target ({@link ExecutionEnvCapabilities.io})? Three states:
 * `true`, `false` (the placeholder every operation of which refuses, `StubExecutionEnv`), or `"undeclared"` — which each
 * consumer reads on ITS safe side: a shell face mounts only on `true`; the project marker is read through the environment
 * unless it is `false` (a host-side read would pass the environment's own read limits). Total: it never throws.
 */
export declare function performsIo(env: Pick<ExecutionEnv, "capabilities">): boolean | "undeclared";
/**
 * Does this environment keep the byte floor a command start carries, or refuse a start whose whole table it cannot
 * keep ({@link ExecutionEnvCapabilities.keepsReadFloor})? Only a declared `true` says so; undeclared ⇒ `false`. The
 * judgment that reads it is taken once per run, where the run's read-deny table is compiled. Total: it never throws.
 */
export declare function keepsReadFloor(env: Pick<ExecutionEnv, "capabilities">): boolean;
/**
 * Does this environment keep a command start inside the OS sandbox the start carries, or refuse the start
 * ({@link ExecutionEnvCapabilities.commandSandbox})? Only a declared `true` says so; undeclared ⇒ `false`. Read once per run,
 * where the run's command sandbox is judged. Total: it never throws.
 */
export declare function providesCommandSandbox(env: Pick<ExecutionEnv, "capabilities">): boolean;