@sema-agent/core
Version:
Stateless, task-oriented AI agent core
415 lines (414 loc) • 26.5 kB
TypeScript
import { type CommandSandboxPlan } from "./command-sandbox-dispatch.js";
export type { CommandSandboxPlan } from "./command-sandbox-dispatch.js";
import { type EngineNotice } from "./engine-notice.js";
import { type AskClass, type PermissionMode } from "./ask-origin.js";
import type { AskRequest } from "./tool-policy.js";
import type { ExecutionEnv } from "../internal/harness-types.js";
/** A credential file the sandbox denies or masks (the reference's `credentials.files[]` entry). */
export interface TaskSandboxCredentialFile {
readonly path: string;
readonly mode: "deny" | "mask";
readonly extract?: string;
readonly onExtractNoMatch?: "warn" | "deny" | "error";
readonly decode?: "jwt";
readonly maskClaims?: readonly string[];
readonly maskDuplicates?: boolean;
readonly injectHosts?: readonly string[];
}
/** A credential environment variable the sandbox denies or masks (the reference's `credentials.envVars[]` entry). */
export interface TaskSandboxCredentialEnvVar {
readonly name: string;
readonly mode: "deny" | "mask";
readonly extract?: string;
readonly onExtractNoMatch?: "warn" | "deny" | "error";
readonly decode?: "jwt";
readonly maskClaims?: readonly string[];
readonly injectHosts?: readonly string[];
}
/** The reference's `credentials` block, member for member. */
export interface TaskSandboxCredentials {
readonly files?: readonly TaskSandboxCredentialFile[];
readonly envVars?: readonly TaskSandboxCredentialEnvVar[];
readonly allowPlaintextInject?: boolean;
readonly awsPairs?: readonly {
readonly accessKeyIdVar: string;
readonly secretAccessKeyVar: string;
readonly sessionTokenVar?: string;
}[];
readonly sigv4?: {
readonly streaming?: "deny" | "passthrough";
readonly presigned?: "deny" | "passthrough";
readonly sigv4a?: "deny" | "passthrough";
};
}
/** The reference's `network` block, but its merge-time key (`allowManagedDomainsOnly`, the host's to apply when it merges settings). */
export interface TaskSandboxNetwork {
readonly allowedDomains?: readonly string[];
readonly deniedDomains?: readonly string[];
readonly strictAllowlist?: boolean;
readonly allowUnixSockets?: readonly string[];
readonly allowAllUnixSockets?: boolean;
readonly allowLocalBinding?: boolean;
readonly allowMachLookup?: readonly string[];
readonly httpProxyPort?: number;
readonly socksProxyPort?: number;
readonly tlsTerminate?: {
readonly caCertPath?: string;
readonly caKeyPath?: string;
};
}
/** The reference's `filesystem` block, but its merge-time key (`allowManagedReadPathsOnly`). Paths are absolute or `~/`. */
export interface TaskSandboxFilesystem {
readonly allowWrite?: readonly string[];
readonly denyWrite?: readonly string[];
readonly denyRead?: readonly string[];
readonly allowRead?: readonly string[];
readonly disabled?: boolean;
}
/**
* A task's command sandbox requirement — the reference's `sandbox` settings, key for key (`M_r` cli316.js:260966), without the
* two merge-time keys a host applies when it merges settings sources. Every path is ABSOLUTE or starts with `~/` (read
* against the home directory of the environment the command runs in): the reference reads a relative path against the
* settings file it came from, which only the host knows, so a host resolves one before it sends it.
*/
export interface TaskSandboxSettings {
/** `true` ⇒ the requirement is in force. Absent or `false` ⇒ nothing below takes effect (each member is still judged). */
readonly enabled?: boolean;
/** The requirement cannot be met ⇒ the run is refused. Absent ⇒ `true` when `enabled` is (the reference's SDK form, `failIfUnavailable` cli316.js:288039). */
readonly failIfUnavailable?: boolean;
readonly autoAllowBashIfSandboxed?: boolean;
readonly allowUnsandboxedCommands?: boolean;
readonly excludedCommands?: readonly string[];
readonly ignoreViolations?: Readonly<Record<string, readonly string[]>>;
readonly filesystem?: TaskSandboxFilesystem;
readonly network?: TaskSandboxNetwork;
readonly credentials?: TaskSandboxCredentials;
readonly enableWeakerNestedSandbox?: boolean;
readonly allowNestedUserNamespaces?: boolean;
readonly enableWeakerNetworkIsolation?: boolean;
readonly allowAppleEvents?: boolean;
readonly ripgrep?: {
readonly command: string;
readonly args?: readonly string[];
};
readonly bwrapPath?: string;
readonly socatPath?: string;
}
/** What one command start may touch. Every path is absolute. `allowRead` re-opens reading only under `denyRead`, never under a
* row of the start's byte floor (`readFloor`). The environment may add the private directory its own mechanism needs for the
* start, and nothing else. */
export interface CommandSandboxBoundary {
readonly filesystem: {
readonly allowWrite: readonly string[];
readonly denyWrite: readonly string[];
readonly denyRead: readonly string[];
readonly allowRead: readonly string[];
};
readonly network: {
readonly allowedDomains: readonly string[];
readonly deniedDomains: readonly string[];
};
}
/** The requirement's members the environment's own mechanism interprets, as the task stated them (paths resolved). */
export interface CommandSandboxMechanism {
readonly filesystem?: {
readonly disabled?: boolean;
};
readonly network?: Omit<TaskSandboxNetwork, "allowedDomains" | "deniedDomains" | "strictAllowlist">;
readonly credentials?: TaskSandboxCredentials;
readonly enableWeakerNestedSandbox?: boolean;
readonly allowNestedUserNamespaces?: boolean;
readonly enableWeakerNetworkIsolation?: boolean;
readonly allowAppleEvents?: boolean;
readonly ripgrep?: {
readonly command: string;
readonly args?: readonly string[];
};
readonly bwrapPath?: string;
readonly socatPath?: string;
}
/**
* The instruction one command start carries (`ExecutionEnvExecOptions.sandbox`): the start runs with every entry of the
* boundary kept, under the mechanism as stated, or it does not start — refused `sandbox_unavailable`, saying which way
* (`refusedBy`: `"this_call"` = an entry of this boundary cannot be kept, another boundary may still start; `"environment"` =
* the sandbox itself cannot start, so no boundary can; a refusal that cannot tell reads `"environment"`). Never kept in part,
* never started without it.
*/
export interface CommandSandboxInstruction {
readonly boundary: CommandSandboxBoundary;
readonly mechanism: CommandSandboxMechanism;
/**
* The run's question about a host the command connects to that neither `boundary.network` list names: the environment asks
* it before it lets such a connection through and connects only on `true`; `false` (or a rejection) refuses the connection,
* reported as a violation (`deny network-outbound <host>…`). `host` is the host as a URL carries it (lower case, IDN in its
* ASCII form, no port, no trailing dot); a spelling that does not read back as itself is answered `false`. One question per
* host is put at a time (a second ask for the same host while one is open waits for the same answer); a host a person allowed
* is answered `true` for the rest of the run without asking. After the run ends every answer is `false`. Absent when the
* requirement says `network.strictAllowlist` (no host outside the lists is asked about) — the environment then refuses each
* such connection as it would on a `false`.
*/
readonly askHost?: (host: string) => Promise<boolean>;
}
/** Which way a start was refused because its confinement could not be had (`ExecutionError.refusedBy`). */
export type ConfinementRefusal = "this_call" | "environment";
/** The code a requirement that cannot be read refuses the run with. */
export declare const SANDBOX_SETTINGS_INVALID = "config.sandbox_settings_invalid";
/** The code of a requirement the environment cannot meet: the run's notice when `failIfUnavailable` is `false`, the prepare
* refusal otherwise — one fact, one word, two loudness dialects. */
export declare const COMMAND_SANDBOX_UNAVAILABLE = "config.command_sandbox_unavailable";
/**
* The requirement as the task stated it, judged and owned: a frozen plain copy of `value` whose every member is one the
* reference's settings carry, of its type, every path absolute or `~/`. `undefined` for an absent requirement. Throws
* {@link SANDBOX_SETTINGS_INVALID} naming the key. Paths are not resolved here — a child resolves the copy it inherits
* against its own environment's home.
*/
export declare function receiveTaskSandbox(value: unknown): TaskSandboxSettings | undefined;
/** A run's command sandbox, decided once at prepare: `off`, `unavailable` (announced; commands run unsandboxed), `armed` —
* the requirement as judged (its `~/` paths unread: each call's plan reads them, {@link commandSandboxPlan}) and the run's one
* {@link CommandSandboxLapse} — or `not_needed`: the requirement is in force and the leg stands in no environment, so it starts
* no command for a sandbox to hold. */
export type CommandSandboxRun = {
readonly state: "off";
} | {
readonly state: "not_needed";
} | {
readonly state: "unavailable";
readonly reason: string;
} | {
readonly state: "armed";
readonly requirement: TaskSandboxSettings;
readonly lapse: CommandSandboxLapse;
};
/** An armed run's one way out of its sandbox that nobody asked for: the environment refused a start because its sandbox itself
* cannot start (`refusedBy: "environment"`, or a refusal that cannot tell). Set once, never cleared; plans minted after it read
* it (`failIfUnavailable` ⇒ every start refused, otherwise every start unsandboxed), plans minted before it keep their
* boundary — the environment keeps it or refuses the start. */
export interface CommandSandboxLapse {
reason: string | undefined;
}
/** What {@link judgeCommandSandbox} reads. */
export interface CommandSandboxJudgment {
/** The task's requirement (`TaskSpec.sandbox`, under a resumed leg's recorded floor — {@link resumedSandbox}), as handed. */
readonly requirement: unknown;
/** The environment that stands under the leg (its own, or the deployment's static one); `undefined` ⇒ none stands (the leg
* is on the no-I/O stand-in, which starts no command). */
readonly env: Pick<ExecutionEnv, "capabilities"> | undefined;
readonly onNotice: ((notice: EngineNotice) => void) | undefined;
readonly attribution?: {
readonly sessionId?: string;
readonly runId?: string;
};
}
/**
* The requirement a resumed leg runs under: the one its parked leg ran under (`CheckpointState.commandSandbox`, judged again)
* as a floor under the one the resume states — {@link mergeChildSandbox}, the same law a child's requirement meets its
* parent's: a continuation never runs looser than what it continues.
*/
export declare function resumedSandbox(recorded: unknown, stated: unknown): TaskSandboxSettings | undefined;
/**
* The run's command sandbox: the requirement judged ({@link receiveTaskSandbox}), then — when it is in force — the capability
* read once. Armed ⇒ the requirement as judged (its paths are read per call, against the home of the environment that runs
* it). Unavailable ⇒ announced once ({@link COMMAND_SANDBOX_UNAVAILABLE}, the session user's) and the run proceeds
* unsandboxed; under `failIfUnavailable` the same word refuses the run. A leg that stands in no environment starts no
* command: `not_needed`, nothing read against it. Throws the coded refusals.
*/
export declare function judgeCommandSandbox(j: CommandSandboxJudgment): CommandSandboxRun;
/** Does a tool's parameter schema declare the escape — the face the model was handed it on (the full shell face of an armed run;
* never the read-only face or Monitor, which do not offer it). */
export declare function declaresSandboxEscape(parameters: unknown): boolean;
/** What a leg's plans read besides the run: the roots it writes (read at each mint — the active tree moves) and the home of the
* environment that runs its calls, which a `~/` path of the requirement is read against. */
export interface CommandSandboxLeg {
readonly writeRoots: () => readonly string[];
readonly home: string | undefined;
}
/**
* The plan of one call, by the call's wire name and the input the gate lets go. Only a call the environment's own shell face runs
* (`envHand` — the call dispatches to an engine hand the environment executes, never a caller's tool under the name), in an
* armed run, carries one, in this order: the run's sandbox has lapsed ⇒ every start refused under `failIfUnavailable`,
* unsandboxed otherwise; the input sets `dangerouslyDisableSandbox: true`, the escape is judged for this call (`escapeJudged`: its
* face declares the parameter and the decision that lets it go asks about leaving — the live gate's escape station reads this very
* plan; a resumed call's parked question did when it carried `sandbox_override`) and the requirement lets it take effect
* (`allowUnsandboxedCommands`, `true` unless the task says `false`) ⇒ unsandboxed by the escape; otherwise the requirement read
* now — its `~/` paths against the leg's home (none stated ⇒ this call's starts refused, naming the path) and the leg's write
* roots added to what it may write — the instruction carrying the run's host question for this call (`askHost`) unless the
* requirement says `network.strictAllowlist`. Every other call carries none.
*/
export declare function commandSandboxPlan(run: CommandSandboxRun, call: {
readonly toolName: string;
readonly envHand: boolean;
readonly args?: unknown;
readonly escapeJudged: boolean;
readonly askHost?: (host: string) => Promise<boolean>;
}, leg: CommandSandboxLeg): CommandSandboxPlan;
/** Which side of the run's sandbox a call's commands run on, as its plan says — what an approval request states
* (`AskRequest.commandSandbox`): `undefined` for a call the run does not sandbox. A refused plan runs nothing outside. */
export declare function commandSandboxSideOf(plan: CommandSandboxPlan): "inside" | "outside" | undefined;
/**
* A leg's plan port, over the leg's mounted hands and tools: `planOf` mints one call's plan by its wire name and the input let go —
* the escape judged where the mounted face declares it and the deciding question asked about it (the live gate's escape station
* always does; a resumed call's parked question did when its classes carry `sandbox_override`), its instruction asking the run's
* host questions (`hosts`, filled once the leg's approval seat exists) about that call — and `sideOf` is the side an ask about the
* call states.
*/
export declare function commandSandboxPlans(run: CommandSandboxRun, leg: CommandSandboxLeg, mounted: {
readonly envHandToolNames: ReadonlySet<string>;
readonly tools: readonly {
readonly name: string;
readonly parameters?: unknown;
}[];
}, hosts: {
readonly current?: SandboxHostQuestions;
}): {
planOf: (call: {
readonly toolName: string;
readonly toolCallId: string;
readonly args: unknown;
readonly parkedClasses?: readonly AskClass[];
}) => CommandSandboxPlan;
sideOf: (call: {
readonly toolName: string;
readonly toolCallId: string;
}, args: unknown) => {
commandSandbox?: "inside" | "outside";
};
};
/** The tool name the run's question about a sandboxed command's connection carries (the reference's `SandboxNetworkAccess`): an
* engine name, never a tool — nothing by it is mounted, and its card is the reserved `network` card. */
export declare const SANDBOX_NETWORK_TOOL_NAME = "SandboxNetworkAccess";
/** The run's question about a host, by the call whose command connects ({@link CommandSandboxInstruction.askHost}). */
export type SandboxHostQuestions = (toolCallId: string, host: string) => Promise<boolean>;
/** What the run's rule layers say about the run's own fetch of a host: `refused` — a layer denies it, or one could not say whether
* it would; otherwise the classes of the asks the layers hold (none: empty), whether one of them demands a real approval, whether
* an allow member of the run grants the fetch, and the card's offer (the fetch's own: `WebFetch(domain:<host>)`, where a rule lane
* can keep it). */
export type SandboxHostRules = {
readonly refused: true;
} | {
readonly refused: false;
readonly asks: readonly AskClass[];
readonly realApproval: boolean;
readonly allowed: () => Promise<boolean>;
readonly offers: Pick<AskRequest, "ruleOffers" | "ruleOffersAbsence">;
};
/** The card of one host question: what the approval seat is shown. */
export type SandboxNetworkCard = Pick<AskRequest, "toolName" | "toolCallId" | "args" | "message" | "askClass" | "classes" | "approvalCard" | "requiresRealApproval" | "ruleOffers" | "ruleOffersAbsence">;
/** What a run's host questions read, each read when a question is put (the reference reads its permission context per question):
* the rule layers, the mode, auto mode's classifier, the approval seat, and the run's signal. */
export interface SandboxNetworkSeat {
rules(host: string): Promise<SandboxHostRules>;
mode(): PermissionMode;
/** Auto mode's classifier on the question: `true` only for its allow; `undefined` when the run arms none (the question then goes
* to the approval seat, as an ask the classifier cannot take does). */
classify(question: {
readonly toolCallId: string;
readonly toolName: string;
readonly args: {
readonly host: string;
};
readonly message: string;
}): Promise<boolean | undefined>;
/** The card put to the run's approval seat: `true` only for an allow of the card as shown; a run with no live seat answers `false`. */
ask(card: SandboxNetworkCard): Promise<boolean>;
/** The run's signal: the leg ends it, and from then on every question is answered `false`. */
readonly signal: AbortSignal;
}
/**
* A run's host questions — one per host at a time, judged as the run judges its own fetch of the host: a deny of the rule layers
* (or a layer that could not answer) refuses; a host a person allowed in this run is allowed; then the question, of class
* `sandbox_network` with the classes of the asks the layers hold, meets the arbitration every ask meets — an allow member clears it
* where its row lets a rule, the mode releases or refuses it (`bypassPermissions` / `dontAsk`), auto mode's classifier answers it,
* and otherwise the run's approval seat is shown the reference's card ("Allow network connection to <host>?") — a yes allows the host
* for the rest of this run and writes no rule; the card's offer is how a person keeps it. A host that does not read back as itself
* is refused unasked. A yes is given only if it still holds when it is given: the run has not ended and the rule layers, read again
* then, do not refuse the host (a deny or the run's end that arrives while the question is open wins over the answer it reaches).
*/
export declare function sandboxHostQuestions(seat: SandboxNetworkSeat): SandboxHostQuestions;
/** Does a plan run the call outside the sandbox by the call's own escape — the gate's `sandbox_override` question. */
export declare function leavesByEscape(plan: CommandSandboxPlan): boolean;
/** What a shell face hands one start: the instruction (`sandbox`) the environment must keep, none (the plan runs the call outside
* the sandbox) — or `ok: false`, the start is refused, `reason` saying why ({@link sandboxRefusalText} `{ by: "plan" }`). */
export type CommandSandboxStart = {
readonly ok: true;
readonly sandbox: CommandSandboxInstruction;
readonly ignoreViolations?: Readonly<Record<string, readonly string[]>>;
} | {
readonly ok: true;
readonly sandbox?: undefined;
} | {
readonly ok: false;
readonly reason: string;
};
/** A shell face's seat on an armed run. */
export interface CommandSandboxSeat {
/** Asked at each start the face makes: the plan of the call being executed, read where its dispatch put it. */
start(): CommandSandboxStart;
/** The environment refused a start for its sandbox (`sandbox_unavailable`), saying which way: `"this_call"` changes nothing;
* `"environment"`, or a refusal that cannot tell, lapses the run — once, announced to the session's user — and the returned
* sentence tells the model what that means for its commands from here on. */
refused(by: ConfinementRefusal | undefined, detail: string): string | undefined;
}
/** The reference's sentence when the sandbox goes away mid-session (the model's half of a lapse), and its counterpart when the
* task requires the sandbox. */
export declare const SANDBOX_LAPSED_SENTENCE = "The Bash command sandbox has been disabled. Commands now run without sandbox restrictions; the earlier sandbox instructions no longer apply.";
export declare const SANDBOX_LAPSED_REQUIRED_SENTENCE = "The sandbox stopped working and this run requires it (sandbox.failIfUnavailable), so shell commands are refused for the rest of this run.";
/** The model's sentence for a lapsed armed run — what the refusal that lapsed it says, and what a later restatement says in place of
* the instructions; `undefined` while the run keeps its sandbox (or keeps none). */
export declare function lapseSentenceOf(run: CommandSandboxRun): string | undefined;
/** The seat of a run: off or unavailable ⇒ no seat (the starts carry nothing, as before the seat existed); armed ⇒ the plan of
* the call being executed, a start whose call carries no plan refused; the environment's refusals lapse the run as the seat says. */
export declare function commandSandboxSeat(run: CommandSandboxRun, announce?: Pick<CommandSandboxJudgment, "onNotice" | "attribution">): CommandSandboxSeat | undefined;
/** An environment's sandbox refusal met by the run's seat ({@link CommandSandboxSeat.refused}): the lapse sentence, when the
* refusal lapsed the run, for the refusal's own sentence to carry. */
export declare function lapsedBy(seat: CommandSandboxSeat | undefined, by: ConfinementRefusal | undefined, detail: string): {
lapsed?: string;
};
/** Why a shell start did not happen for its sandbox: its plan refused it (`plan` — no plan, a boundary that cannot be stated on
* this leg, a lapsed sandbox the task requires), or the environment did (`sandbox_unavailable`, with the environment's own
* reason, already read through the engine's one reading of a target's failure message, which way, and — when the refusal
* lapsed the run — the seat's sentence). */
export type SandboxRefusal = {
readonly by: "plan";
readonly reason: string;
} | {
readonly by: "environment";
readonly detail: string;
readonly refusedBy: ConfinementRefusal | undefined;
readonly lapsed?: string;
};
/** The model-facing sentence of a start that did not happen for its sandbox: nothing ran. Bounded by construction — the tool name
* to 64 characters, the plan's or the environment's reason to 600, the lapse sentence to 300, everything else fixed. */
export declare function sandboxRefusalText(toolName: string, refusal: SandboxRefusal): string;
/** What the environment says about a start it kept (`ExecResult.sandbox`): it kept every entry of the boundary (a start it cannot
* keep is refused instead, `sandbox_unavailable`), and what the sandbox stopped while the command ran. */
export interface CommandSandboxRecord {
readonly launch: "enforced";
readonly violations?: readonly CommandSandboxViolation[];
}
/** One thing the sandbox stopped, as one line in the reference's form (`deny file-write /etc/x`, `deny network-outbound host:443
* (reason)`). */
export interface CommandSandboxViolation {
readonly line: string;
}
/**
* The note a start's result carries about its sandbox, appended to the command's output — `""` for a start that carried none.
* A record ⇒ the violations it reports, but those `ignoreViolations` leaves unreported for this command, in the reference's
* `<sandbox_violations>` block (at most 50, each line one bounded untrusted line); no record ⇒ the environment did not confirm it
* kept the boundary, said as unverified — never as "it ran unsandboxed".
*/
export declare function sandboxResultNote(start: CommandSandboxStart, command: string, record: CommandSandboxRecord | undefined): string;
/**
* The requirement a child runs under, given its parent's (already judged) and the one the child states. The parent's is a
* floor: no parent ⇒ the child's as it is; no child ⇒ the parent's. Otherwise each member the child does not state is the
* parent's, and each it states is combined with the parent's toward the stricter side: a tightening switch (`enabled`,
* `failIfUnavailable`, `strictAllowlist`) is on when either is; a loosening one (`autoAllowBashIfSandboxed`,
* `allowUnsandboxedCommands`, the weakening switches) only when both are; the lists of what is denied join; the lists of
* what is allowed keep only the entries both write, as written; `ignoreViolations` keeps the patterns both write, each with the
* paths both write; in a credential list the child states, a credential named more than once (by both, or twice in the parent's
* list) is one entry with the stricter mode (`deny` over `mask`) and the stricter no-match word (`error` over `deny` over `warn`),
* its other members the parent's (for a name the parent's list repeats, its later entry's); a signing word (`sigv4.streaming` / `presigned` /
* `sigv4a`) is `deny` when either writes `deny`; the mechanism's settings (`httpProxyPort`, `socksProxyPort`, `tlsTerminate`,
* `ripgrep`, `bwrapPath`, `socatPath`, `awsPairs`) are the parent's, whatever the child states. The child's requirement is judged
* first ({@link receiveTaskSandbox}): one that cannot be read refuses the spawn, never merges in part.
*/
export declare function mergeChildSandbox(parent: TaskSandboxSettings | undefined, childValue: unknown): TaskSandboxSettings | undefined;