Sandboxes
The sandbox packages: @chamvi/sandbox (contracts, rules, the workspace manager) and the three providers. See Workspaces & Coding for the behaviour.
@chamvi/sandbox
npm install @chamvi/sandbox @chamvi/core ai --save@chamvi/core and ai are peer dependencies.
createWorkspaceManager
function createWorkspaceManager(options: WorkspaceManagerOptions): IWorkspaceManager;
const MAX_WORKSPACES_PER_RUN: 3;
const GC_INTERVAL_MS: 600_000;
const CLOSE_TIMEOUT_MS: 30_000;
const CREDENTIAL_INSTALL_TIMEOUT_MS: 30_000;
const PUSH_LOG_MAX_COMMITS: 50;Throws InvalidAgentDefinitionError for a provider without create, find and collectGarbage, an empty image, invalid env or limits, a deployment that is no label value, an allowRepo, allowImage, isSettled or onError that is no function, a maxWorkspacesPerRun below 1, a negative gcIntervalMs, credentials that are no sources with get(), a depth below 1, an author without a non-empty name and email (no line break, < or >) or a malformed push.
With credentials the manager looks up a read credential for every checkout (checkout.credential of the create; a failing source fails the create with a SandboxError naming the repository) and hands out each workspace through a view whose exec results, file reads and errors carry [redacted] in place of every issued token and whose redact(text) does the same for text a tool decodes itself. Only the tokens this process issued are redacted, each until REDACT_GRACE_MS after its expiresAt (a static token without expiry stays); the credentials file of a workspace found again (after a restart or on another replica) is never read back, since the model can write it. The view also has readFileRaw(path), the unredacted text, and redactedSpans(text), which the edit tools use: they match oldString against the redacted text the model read (redactedSpans), refuse an edit that touches a [redacted] span and put every untouched token back byte for byte, so an oldString can neither probe a token nor write [redacted] back. Without an image allow-list (allowImage), and on the local provider, create_workspace has no image parameter and a requested image is a ValidationError before any create. It writes the credential helper and the credentials file of an https workspace after the create and before the first exec of a workspace this process has not written yet (one found again), and again before an exec once a token expires within CREDENTIAL_REFRESH_MS (at most once per CREDENTIAL_RETRY_MS while a source keeps answering a token inside that window); a failing write goes to onError and is tried again CREDENTIAL_RETRY_MS later, never failing the exec. The file holds the repository's write credential (else its read one, also when the write lookup fails, which goes to onError) and the host's (a request with an empty path).
On a miss (get without a held workspace that fits, acquire of a repository it does not hold) the manager asks provider.find(runId, { deployment }) once per run at a time and adopts what it finds, so a run reaches its workspaces after a restart or on another replica. With isSuspendable, collectGarbage() forgets (never disposes) the held workspaces of a run that waited long enough and passes isSuspendable to the provider, which suspends them; the next lookup gets them back (find with rebuild, the manager's env and limits). release(runId) (and attach for a settled run) disposes the held workspaces and every one find reports; release(runId, id) and dispose(runId, id?) (by id, or the only one; answers its id) dispose one; all of them ask find with restore: false and adopt nothing, so a suspended workspace is never rebuilt only to be removed; with isSettled, attach skips the find for a settled run this process neither holds nor looks up and starts a garbage collection instead (at most one per gcIntervalMs), which removes what other processes left for it; close() disposes nothing a live run holds, close({ dispose: true }) disposes those too.
/*
* Copyright (c) 2026.
* Author Peter Placzek (tada5hi)
* For the full copyright and license information,
* view the LICENSE file that was distributed with this source code.
*/
import type { ToolSet } from 'ai';
import type { IClock, IEngine, ToolContext } from '@chamvi/core';
import type {
GitAccess,
GitCredential,
IGitCredentials,
Redactor,
} from '../credentials/types.ts';
import type { RepositoryInstructions } from '../instructions/types.ts';
import type { ISandboxProvider, SandboxLimits } from '../provider/types.ts';
import type { IWorkspace } from '../workspace/types.ts';
/** The credential handling of one manager; only built when it has credential sources. */
export type CredentialSupport = {
readonly redactor: Redactor;
/**
* The first credential the sources answer for an https `url` (redacted
* from then on), else undefined; undefined for a `file://` repository.
* SandboxError for a failing source.
*/
lookup(url: string, access: GitAccess, runId: string, signal?: AbortSignal): Promise<GitCredential | undefined>;
/**
* Writes the credentials file of `workspace` (raw,
* not wrapped) when it has none from this process yet, or one of its
* credentials expires within `CREDENTIAL_REFRESH_MS`: the repository's
* write credential, else (none, or a failing write lookup, reported to
* `onError`) its read credential. A credential already inside that
* window is rewritten `CREDENTIAL_RETRY_MS` later at the earliest. A failure goes to
* `onError` and is retried `CREDENTIAL_RETRY_MS` later; it never throws.
* A workspace this process created anonymously (`fresh`) holds no file
* yet; one whose checkout was authenticated holds the read credential,
* and one it found again may hold an earlier process's: the first
* install overwrites (or clears) both. The file is never read back: it
* is writable from inside the workspace, so its content is no secret to
* redact. A failure while `released` answers true (the manager released,
* so disposed, the workspace meanwhile) is not reported.
*/
refresh(workspace: IWorkspace, options?: { fresh?: boolean; released?: () => boolean }): Promise<void>;
/** The workspace the manager hands out: redacting and refreshing before each call. One per raw workspace. */
wrap(workspace: IWorkspace): IWorkspace;
};
export type GitToolsContext = {
manager: Pick<IWorkspaceManager, 'get'>;
/** The credential of an https repository, or undefined (anonymous). */
lookup: (url: string, access: GitAccess, runId: string, signal?: AbortSignal) => Promise<GitCredential | undefined>;
/** `normalizeRepo` with the manager's rules (`allowFileRepos`, `allowRepo`). */
normalize: (repo: string) => string;
push: PushPolicy;
};
export type WorkspaceManagerOptions = {
provider: ISandboxProvider;
/** Passed to every `create`. */
image?: string;
/** Passed to every `create`. */
env?: Record<string, string>;
/** Passed to every `create`. */
limits?: SandboxLimits;
/** Accept `file:///absolute/path` repositories (local development and tests). Default false. */
allowFileRepos?: boolean;
/** Narrows the accepted repositories further; gets the normalized URL. */
allowRepo?: (url: string) => boolean;
/** Collect root repository guidance and offer path-scoped guidance tools. Default true. */
repositoryInstructions?: boolean;
/**
* The images `create_workspace` may ask for; gets the reference as
* requested. Without it, and on the local provider (it runs no images),
* `create_workspace` has no `image` parameter and a requested image is a
* `ValidationError`. Never asked for the manager's or the provider's own
* image.
*/
allowImage?: (image: string) => boolean;
/** Workspaces one run may hold at once. Default MAX_WORKSPACES_PER_RUN (3). */
maxWorkspacesPerRun?: number;
/** Minimum interval between the garbage collections `acquire` starts. Default GC_INTERVAL_MS; 0 disables them. */
gcIntervalMs?: number;
/**
* The deployment the workspaces belong to (a label value): `find` and the
* garbage collection only see their own. Default `DEFAULT_DEPLOYMENT`.
*/
deployment?: string;
/**
* True when a run settled or no longer exists; the garbage collection then
* disposes its workspaces, also ones another process created. Without
* it only expired workspaces are collected.
*/
isSettled?: (runId: string) => Promise<boolean>;
/**
* True when a run has waited long enough to give up its compute: the
* garbage collection forgets the run's held workspaces without disposing
* them and passes it to the provider, which may suspend them (their next
* `get` or `acquire` finds them again through `provider.find`). Without
* it nothing is suspended.
*/
isSuspendable?: (runId: string) => Promise<boolean>;
/**
* Git credentials for private repositories and pushes: the first source
* that answers wins, none answering is anonymous.
*/
credentials?: IGitCredentials | IGitCredentials[];
/** A shallow checkout of this many commits for huge repositories; default the full history. */
depth?: number;
/** The commit identity, set as `GIT_AUTHOR_*` and `GIT_COMMITTER_*` in every workspace's environment. */
author?: GitAuthor;
/** What `git_push` may push; default every branch but the default branch, no force, no approval. */
push?: PushPolicy;
clock?: IClock;
/** Background failures (disposal, garbage collection, credential refreshes). Default console.error. */
onError?: (error: unknown) => void;
};
export type GitAuthor = {
name: string;
email: string;
};
/** Applies to git_push only; other tools and shell commands can bypass it. */
export type PushPolicy = {
/** `auto` (default) pushes; `approve` asks the owner through `approve()` before every push. */
mode?: 'auto' | 'approve';
/** Allow `git_push({ force: true })` (always `--force-with-lease`). Default false. */
allowForce?: boolean;
/** The branches `git_push` may push to; default every branch but the repository's default branch. */
allowBranch?: (branch: string, ctx: ToolContext) => boolean | Promise<boolean>;
/** The channel an approval goes through; default the run's source channel when it has an `out`, else none (inbox only). */
channel?: string;
};
export type AcquireInput = {
/** `owner/name`, an https URL, or `file:///absolute/path` with `allowFileRepos`. */
repo?: string;
ref?: string;
/**
* An image reference (`assertImage`), only with `allowImage` and not on
* the local provider, checked by `allowImage`; default the manager's,
* else the provider's.
*/
image?: string;
signal?: AbortSignal;
};
export type CloseOptions = {
/** How long close() waits for disposals and creates in flight. Default CLOSE_TIMEOUT_MS (30 s). */
timeoutMs?: number;
/**
* Also dispose the workspaces of live runs (default false: they stay for
* their runs to find again). For in-memory run storage, nothing can resume after the process exits.
*/
dispose?: boolean;
};
export type AcquireResult = {
workspace: IWorkspace;
/** True when the run already held (or was creating) the workspace of this repository. */
reused: boolean;
};
/**
* Run-scoped workspaces: one per run and repository (or none), created
* through the provider and disposed when the run settles (`attach`).
*/
export interface IWorkspaceManager {
/**
* The run's workspace of `repo` (none: the repo-less one): held, else
* found through `provider.find` (adopted, `reused`), else created when
* missing, expired or gone (`IWorkspace.disposed`). Concurrent calls share one create. ValidationError for a
* repository, ref or image the rules refuse; SandboxError for another ref
* or image of a held repository, a reached per-run cap or a failed create.
*/
acquire(runId: string, input: AcquireInput): Promise<AcquireResult>;
/**
* The run's workspace by id, or its only live one when id is omitted
* (expired and gone ones are disposed first). A run that holds none that
* fits is looked up through `provider.find` (one lookup per run at a
* time) and the found ones adopted. SandboxError: unknown, expired or gone
* (disposed then), none, a failed lookup; ValidationError: several and no id.
*/
get(runId: string, workspaceId?: string): Promise<IWorkspace>;
/**
* Disposes one workspace (as `dispose`, SandboxError /not found/ for an id
* the run neither holds nor finds), or all of the run (never rejects for
* none): the held ones and every one `provider.find` reports for the run;
* this aborts the run's creates and lookups in flight and waits for the
* creates. Never restores a suspended workspace to remove it (`find` with
* `restore: false`).
*/
release(runId: string, workspaceId?: string): Promise<void>;
/**
* Disposes one workspace of the run and answers its id: by id, or its
* only one when id is omitted (the held ones, else what
* `provider.find(runId, { restore: false })` reports; nothing found is
* adopted, a suspended one is never restored). SandboxError: unknown id,
* none, a failed lookup or dispose; ValidationError: several and no id.
*/
dispose(runId: string, workspaceId?: string): Promise<string>;
/**
* Disposes a run's workspaces on completed | failed | cancelled (`release`,
* so also those other processes created). With `isSettled`, a run this
* process neither holds nor looks up is not looked up (no `provider.find`
* per settled run): it starts a garbage collection instead (at most one
* per `gcIntervalMs`), which removes what other processes left for it.
* Returns the unsubscribe; after close() it subscribes nothing.
*/
attach(engine: Pick<IEngine, 'on'>): () => void;
/** Workspace lifecycle, structured Git and (unless disabled) repository guidance tools (no bash tool). */
tools(): ToolSet;
/**
* Disposes the manager's expired workspaces and, with `isSettled`, the
* ones of settled runs; with `isSuspendable`, forgets (never disposes)
* the held workspaces of suspendable runs; then runs the provider's
* collection (deployment, `isSettled` and `isSuspendable` passed on);
* returns how many went.
*/
collectGarbage(): Promise<number>;
/**
* Unsubscribes every attach, aborts the creates in flight (disposing what
* they made) and forgets the held workspaces without disposing them: they
* belong to live runs, which find them again after a restart (with
* `dispose: true` it disposes them too). Waits for
* the creates, for disposals started earlier and for the creates in
* flight of runs released before (call after engine.drain()); afterwards
* acquire, get and lookups reject and attach subscribes nothing. Resolves
* after `timeoutMs` at the latest, reporting what is still being disposed
* to `onError`.
*/
close(options?: CloseOptions): Promise<void>;
}
export type WorkspaceToolResult = {
workspace: string;
root: '/workspace';
repo: string | null;
ref: string | null;
commit: string | null;
/** The remote's default branch, fetched as `origin/<name>` (the base to merge or rebase onto). */
defaultBranch: string | null;
/** The image of a container or pod workspace; null on local. */
image: string | null;
expiresAt: string;
reused: boolean;
/** Current root guidance; null without a repository, when collection is disabled or when it failed. */
instructions: RepositoryInstructions | null;
/**
* Why the guidance could not be collected (a missing utility, a stray
* line, an exec timeout); set only with `instructions: null` after a
* failure. The workspace is usable; `read_repository_instructions` retries.
*/
instructionsError?: string;
};
export type DisposeWorkspaceResult = {
workspace: string;
disposed: true;
};
/** What `git_fetch`, `git_pull` and `git_push` answer: the git call's outcome, redacted. */
export type GitToolResult = {
workspace: string;
/** The repository URL git talked to (never a remote name of the repository config). */
remote: string;
exitCode: number;
stdout: string;
stderr: string;
timedOut: boolean;
};
export type GitFetchResult = GitToolResult & {
refspec: string;
};
export type GitPullResult = GitToolResult & {
branch: string;
rebase: boolean;
/** The step the result is of: the fetch when it failed, else the merge or rebase. */
step: 'fetch' | 'merge' | 'rebase';
};
export type GitPushResult = GitToolResult & {
branch: string;
/** The commit pushed. */
commit: string;
pushed: boolean;
forced: boolean;
};Repository instructions
function readRepositoryInstructions(
workspace: IWorkspace,
paths?: readonly string[],
options?: ReadRepositoryInstructionsOptions,
): Promise<RepositoryInstructions>;
type ReadRepositoryInstructionsOptions = { signal?: AbortSignal; clock?: IClock };
type RepositoryInstructionSource = {
path: string;
sha256: string;
content: string;
scopes: string[];
includedBy: string[];
};
type RepositoryInstructionDiagnosticCode = 'missing-include' | 'unreadable' | 'invalid-utf8'
| 'outside-workspace' | 'unsupported-file' | 'cycle' | 'limit';
type RepositoryInstructionDiagnostic = {
path: string;
code: RepositoryInstructionDiagnosticCode;
message: string;
};
type RepositoryInstructions = {
commit: string | null;
paths: string[];
sources: RepositoryInstructionSource[];
diagnostics: RepositoryInstructionDiagnostic[];
complete: boolean;
};clock defaults to systemClock and measures the request deadline; signal cancels collection. The function works through IWorkspace.exec, without host filesystem reads or repository program execution. The manager's read_repository_instructions({ paths?, workspace? }) resolves the calling run's workspace and forwards its cancellation signal. Paths default to ['.'], follow workspace path normalization (relative or /workspace/...), and existing directories include themselves; files and missing targets use their parent.
create_workspace adds instructions: RepositoryInstructions | null to WorkspaceToolResult. Repository-backed creates, including reuse or adoption, collect root guidance afresh. Repo-less creates return null. A collection failure (a missing utility, a stray stderr line, an exec timeout) returns instructions: null plus instructionsError (the redacted reason) rather than failing the create; a cancelled run still rejects. With createWorkspaceManager({ provider, repositoryInstructions: false }), create_workspace returns instructions: null and the explicit tool is omitted; the default is true. sandboxModule({ repositoryInstructions: false }) forwards this manager option. There is no corresponding environment variable. The separate codingTools option controls text-read attachments independently.
Entrypoint discovery visits root and requested ancestors only, ordered by directory depth then JavaScript string order; explicit includes may reference permitted files elsewhere in the workspace. Each directory reads AGENTS.md before CLAUDE.md, each immediately followed by its included files in depth-first textual order. Only standalone @relative/path lines count, with surrounding whitespace allowed and none within the path. Ordinary links, inline @ text and fenced code are ignored. Fences use at least three backticks or tildes; a closing fence uses the same character with at least the opening length. Includes resolve relative to their source, allowing .. only inside the workspace and refusing absolute paths, home paths, URLs, NUL and escapes.
Sources are deduplicated by canonical workspace-relative path; scopes retains every applicable entrypoint directory (. for root) and includedBy every including parent. Included guides inherit their entrypoint's scope. sha256 hashes exact original bytes, before credential redaction; content is strictly decoded UTF-8 and redacted before include parsing. Outward paths and diagnostics are redacted too. The collector preserves provenance rather than resolving contradictory prose. commit is workspace.info.commit ?? null, the recorded checkout commit, not necessarily current HEAD; hashes identify the bytes actually read. There is no transactionally frozen snapshot and no cache across calls.
| Exported bound | Value |
|---|---|
INSTRUCTION_FILES | ['AGENTS.md', 'CLAUDE.md'] |
INSTRUCTION_SOURCE_MAX_BYTES | 32 768 (32 KiB), each source whole or omitted |
INSTRUCTION_TOTAL_MAX_BYTES | 131 072 (128 KiB), total source bytes |
INSTRUCTION_SOURCES_MAX | 32 distinct sources |
INSTRUCTION_INCLUDE_DEPTH_MAX | 8 include edges from an entrypoint |
INSTRUCTION_PATHS_MAX | 32 requested paths |
INSTRUCTION_DIRECTORIES_MAX | 64 distinct ancestor directories, root included |
INSTRUCTION_REFERENCES_MAX | 512 attempted inspections and include references |
INSTRUCTION_DIAGNOSTICS_MAX | 64 entries, including a closing limit diagnostic |
INSTRUCTION_DIAGNOSTICS_MAX_BYTES | 8192 UTF-8 bytes of diagnostic paths and messages together |
INSTRUCTION_PATH_MAX_BYTES | 4096 UTF-8 bytes per path |
INSTRUCTION_REQUEST_TIMEOUT_MS | 30 000 (30 s) per request |
INSTRUCTION_EXEC_TIMEOUT_MS | 5000 (5 s) per exec |
Missing optional entrypoints are normal. Missing explicit includes, unreadable files, invalid UTF-8, refused paths, cycles and bound exhaustion add diagnostics; any diagnostic makes complete: false. Sources are never silently truncated. Invalid input shapes throw ValidationError; cancellation, workspace lookup failures, transport errors, exec timeouts, missing inspection capabilities and malformed or truncated protocol responses reject through the existing error path, never a successful empty result. The overall request deadline produces a limit diagnostic with the sources collected so far.
Fixed discovery scripts run in the physical workspace cwd and resolve utilities on /usr/bin:/bin, excluding repository executables. Each read is bounded to 32 KiB + 1 byte with framed base64 output, checked against the 65 536-byte transport cap, exit status, timeout, truncation flags, lengths and completion marker. Missing utilities produce an explicit failure; there is no interpreter or image-contract expansion. Every observed symlink component (including aliases within the workspace), special file and .git component is refused. Checks are best-effort against the observed filesystem; concurrent changes can race them. Strict race-free confinement is deferred to #92.
Delivered context is ordinary tool output retained in model messages, steps and checkpoints across approval pauses and recovery. The next create, explicit context call or applicable file read collects current guidance, including changed files in a reused or recovered workspace, without replacing older messages. These tools are not effect tools. See Repository instructions for the pre-edit workflow and authorization boundaries.
Git credentials
function staticGitCredentials(entries: readonly StaticGitCredential[]): IGitCredentials;
const REDACTED: '[redacted]';
const CREDENTIAL_REFRESH_MS: 600_000;
const CREDENTIAL_RETRY_MS: 60_000;
const CREDENTIALS_FILE: '.chamvi/credentials'; // below $HOME, mode 0600
const REDACT_MIN_LENGTH: 4;
const REDACT_GRACE_MS: 3_600_000; // an expired token stays redacted this longstaticGitCredentials throws InvalidAgentDefinitionError for an entry without a host name (an optional port), a token or username with NUL, CR, LF or tab, or a path that is no owner or repository, naming the entry and never a token. A source's answer must be non-empty strings without those characters (expiresAt a Date), else the lookup is a SandboxError.
The structured Git tools run every remote call as git -c credential.helper= -c core.hooksPath=/dev/null ..., or with a credential as sh -c <script> sh <url> <origin> <path> <git args> with <username>\n<password>\n on stdin: the script hands the credential to git through a one-shot helper on fd 3 that answers only for that origin and path. A URL-specific key in the repository's or the global git config beats a generic -c, so the script cannot force settings on; it checks the config for the URL first and refuses (a SandboxError naming the keys, nothing sent) when it sets a proxy (http.proxy, remote.<name>.proxy), turns http.sslVerify off, names another CA (http.sslCAInfo, http.sslCAPath), overrides name resolution (http.curloptResolve) or rewrites URLs (url.<base>.insteadOf, pushInsteadOf). It also allows git only the https transport (GIT_ALLOW_PROTOCOL=https, which no config can override), so a transport the config names for the URL (remote.<url>.vcs) never starts and cannot read the credential git hands its helpers. The workspace helper ($HOME/.chamvi/git-credential, set as the global credential.helper with credential.useHttpPath) answers from the credentials file, the repository's line first, else the host's.
/*
* Copyright (c) 2026.
* Author Peter Placzek (tada5hi)
* For the full copyright and license information,
* view the LICENSE file that was distributed with this source code.
*/
export type GitAccess = 'read' | 'write';
/** What a credential source is asked: one repository (or, with an empty `path`, its host) and an access. */
export type GitCredentialRequest = {
/** The normalized repository URL (`https://host/owner/name.git`), or `https://host/` for the host itself. */
url: string;
/** Lower case, with the port when the URL names one. */
host: string;
/** Without leading or trailing `/` and without `.git`, e.g. `owner/name`; empty for the host itself. */
path: string;
access: GitAccess;
runId: string;
signal?: AbortSignal;
};
/** HTTP basic credentials for git; `expiresAt` for a short-lived token (refreshed before it runs out). */
export type GitCredential = {
username: string;
password: string;
expiresAt?: Date;
};
/**
* A source of git credentials. `get` answers credentials for the
* repository, or `undefined` to try the next source (none: anonymous).
*/
export interface IGitCredentials {
get(input: GitCredentialRequest): Promise<GitCredential | undefined>;
}
/** One token of `staticGitCredentials()`. */
export type StaticGitCredential = {
/** The host, e.g. `github.com` or `gitlab.example.com:8443`. */
host: string;
/** An owner, group or repository prefix (whole segments, case-insensitive), e.g. `octo` or `octo/demo`; default the whole host. */
path?: string;
/** Default `oauth2` on a host whose name contains `gitlab`, else `x-access-token` (GitHub). */
username?: string;
token: string;
};
/** Replaces issued credentials with `REDACTED`. */
/** A span of a text, `start` inclusive and `end` exclusive (UTF-16 code units). */
export type RedactedSpan = {
start: number;
end: number;
};
export type Redactor = {
/**
* Redacts `secret` from now on; with `expiresAt` only until
* `REDACT_GRACE_MS` after it (adding it again keeps the later expiry,
* none wins).
*/
add(secret: string, expiresAt?: Date): void;
redact(text: string): string;
/** The spans of `text` that `redact` replaces, in order and without overlap. */
redactedSpans(text: string): RedactedSpan[];
/** The same bytes when they hold no secret. */
redactBytes(bytes: Uint8Array): Uint8Array;
/** The same error when its message holds no secret, else a SandboxError with the redacted message and no cause. */
redactError(error: unknown): unknown;
};Workspaces and providers
/*
* Copyright (c) 2026.
* Author Peter Placzek (tada5hi)
* For the full copyright and license information,
* view the LICENSE file that was distributed with this source code.
*/
/** What a provider knows about a workspace; `commit` is set after the checkout. */
export type WorkspaceInfo = {
runId: string;
/** `ISandboxProvider.name` of the provider that created it. */
provider: string;
/** The normalized repository URL. */
repo?: string;
ref?: string;
/** HEAD after the checkout. */
commit?: string;
/** The remote's default branch (its HEAD), fetched next to `ref`: the base of a merge or rebase. */
defaultBranch?: string;
/** The image of a container or pod workspace. */
image?: string;
createdAt: Date;
expiresAt: Date;
};
export type ExecOptions = {
/** Relative to the workspace root or under `/workspace/`; default the root. */
cwd?: string;
/** Default `EXEC_TIMEOUT_MS`, at most `EXEC_TIMEOUT_MAX_MS`. */
timeoutMs?: number;
stdin?: string;
signal?: AbortSignal;
};
export type ExecResult = {
exitCode: number;
/** At most `OUTPUT_MAX_BYTES` bytes of UTF-8. */
stdout: string;
stderr: string;
stdoutTruncated: boolean;
stderrTruncated: boolean;
timedOut: boolean;
durationMs: number;
};
/**
* A disposable directory a run executes commands in. Exec takes argv only,
* never a shell string.
*/
export interface IWorkspace {
readonly id: string;
readonly info: WorkspaceInfo;
/**
* True after `dispose()`, or once the workspace found its container, pod
* or directory gone (stopped, killed or removed outside chamvi). Every
* call then rejects with SandboxError; the manager drops such a workspace
* and disposes it, which removes what is left of it.
*/
readonly disposed: boolean;
exec(argv: readonly string[], options?: ExecOptions): Promise<ExecResult>;
/** UTF-8 text of at most `FILE_MAX_BYTES`; SandboxError for a file that is not UTF-8. */
readFile(path: string): Promise<string>;
/** The raw bytes of a file of at most `FILE_MAX_BYTES`. */
readBytes(path: string): Promise<Uint8Array>;
/** A string is written as UTF-8, bytes as they are; at most `FILE_MAX_BYTES`. */
writeFile(path: string, content: string | Uint8Array): Promise<void>;
/** Idempotent. Every call after it rejects with SandboxError. */
dispose(): Promise<void>;
/**
* Replaces the git credentials issued for the workspace with
* `[redacted]`: set on the workspaces a manager with credentials hands
* out, whose results and errors are already redacted. A tool that decodes
* output itself (base64 from an exec) passes the decoded text through it.
*/
redact?(text: string): string;
/**
* The unredacted text of a file (as `readFile` without the redaction):
* set beside `redact` on the workspaces a manager with credentials hands
* out, for tools that write the text back (an edit), so a file holding
* an issued token never gets `[redacted]` written into it. Never for
* text shown to the model.
*/
readFileRaw?(path: string): Promise<string>;
/**
* The spans of `text` that `redact` replaces with `[redacted]`, in order
* and without overlap: set beside `redact`, so a tool working on the raw
* text (an edit of `readFileRaw`) can match what the model read and keep
* every issued token byte for byte.
*/
redactedSpans?(text: string): Array<{ start: number; end: number }>;
}/*
* Copyright (c) 2026.
* Author Peter Placzek (tada5hi)
* For the full copyright and license information,
* view the LICENSE file that was distributed with this source code.
*/
import type { CheckoutOptions } from '../repo/types.ts';
import type { IWorkspace } from '../workspace/types.ts';
export type SandboxLimits = {
/** Kubernetes quantity, e.g. `'1'`, `'500m'`. */
cpu?: string;
/** Bytes as a Kubernetes quantity, e.g. `'2Gi'`. */
memory?: string;
/** Disk of `/workspace`, e.g. `'4Gi'`. */
storage?: string;
pids?: number;
/**
* Hard cap of a workspace's lifetime (its `expiresAt`), from its creation,
* never renewed. Nothing kills a workspace earlier while its run lives;
* garbage collection removes it once expired or its run settled.
*/
maxLifetimeMs?: number;
};
export type WorkspaceCreateOptions = {
runId: string;
/** A normalized repository URL (`normalizeRepo`); without it the workspace is only `git init`-ed. */
repo?: string;
ref?: string;
/** Passed to `prepareWorkspace`: a shallow `depth`, the read `credential` of a private repository. */
checkout?: CheckoutOptions;
/** The image of a container or pod workspace; default the provider's. */
image?: string;
env?: Record<string, string>;
limits?: SandboxLimits;
/** The deployment the workspace belongs to; default `DEFAULT_DEPLOYMENT`. */
deployment?: string;
signal?: AbortSignal;
};
export type WorkspaceFindOptions = {
/** Only workspaces of this deployment; default `DEFAULT_DEPLOYMENT`. */
deployment?: string;
signal?: AbortSignal;
/**
* What a provider that rebuilds a suspended workspace (Kubernetes with
* persistence) needs of the create's configuration: the `env` and
* `limits` the manager passes to every `create`. Never stored with the
* workspace (the env may hold secrets), so a rebuild after a redeploy
* gets the current configuration.
*/
rebuild?: {
env?: Record<string, string>;
limits?: SandboxLimits;
};
/**
* False for a lookup that only removes what it finds (the manager's
* `release`): a provider that rebuilds a suspended workspace answers it
* as it is, a handle whose `dispose` removes it and whose commands fail.
* Default true.
*/
restore?: boolean;
};
export type GarbageCollectOptions = {
/** Only workspaces of this deployment; default `DEFAULT_DEPLOYMENT`. */
deployment?: string;
/**
* True when the run settled or no longer exists: its workspaces go too,
* expired or not. A rejection keeps them and counts as a failure.
*/
isSettled?(runId: string): Promise<boolean>;
/**
* True when the run has waited long enough: a provider that can suspend
* stops that run's running workspaces without removing them (their files
* stay, `find` brings them back), one that cannot ignores it. Removal
* (expiry, `isSettled`) wins over suspension. A rejection keeps them
* running and counts as a failure.
*/
isSuspendable?(runId: string): Promise<boolean>;
};
export interface ISandboxProvider {
readonly name: string;
/**
* A ready workspace (id `randomUUID()`), checked out when `repo` is given
* (via `prepareWorkspace` with `checkout`, then `info.commit` and
* `info.defaultBranch` from its result).
*/
create(options: WorkspaceCreateOptions): Promise<IWorkspace>;
/**
* Every live, unexpired workspace of the run in the deployment this
* provider can reach (labels, folders), reconnected: the instance this
* process holds, else a new one rebuilt from what lives with the
* workspace. Never creates a workspace; may restart one (a stopped
* Docker container) or rebuild its pod (Kubernetes persistence, with
* `rebuild`).
*/
find(runId: string, options?: WorkspaceFindOptions): Promise<IWorkspace[]>;
/**
* Deletes this provider's workspaces of the deployment past their expiry
* and, with `isSettled`, those whose run settled; returns how many. With
* `isSuspendable` it may suspend the running workspaces of long-waiting
* runs (not counted, never removed). One
* that cannot be removed never keeps the others: the pass goes on and
* rejects with one SandboxError at the end.
*/
collectGarbage(options?: GarbageCollectOptions): Promise<number>;
}/*
* Copyright (c) 2026.
* Author Peter Placzek (tada5hi)
* For the full copyright and license information,
* view the LICENSE file that was distributed with this source code.
*/
/** The workspace root as the model sees it, on every provider. */
export const WORKSPACE_ROOT = '/workspace';
/** Cap per output stream of one exec. */
export const OUTPUT_MAX_BYTES = 65_536;
/** Cap of `readFile`, `readBytes` and `writeFile`. */
export const FILE_MAX_BYTES = 16_777_216;
export const EXEC_TIMEOUT_MS = 300_000;
export const EXEC_TIMEOUT_MAX_MS = 1_800_000;
/**
* The HOME of a container or pod workspace: a disk-backed volume of its own
* (Docker: an anonymous volume, Kubernetes: an emptyDir), kept across a
* restart of a stopped container and removed with the workspace. Never
* `/tmp`, which is memory-backed and charged to the memory limit: the
* homes of cargo, rustup, Maven, Gradle and mise's global config and
* shims live here.
*/
export const WORKSPACE_HOME = '/home/sandbox';
/**
* The whole environment of a container or pod workspace (plus the configured
* `env`). `safe.directory` because `/workspace` is a root-owned volume.
*/
export const SANDBOX_ENV: Readonly<Record<string, string>> = Object.freeze({
HOME: WORKSPACE_HOME,
GIT_TERMINAL_PROMPT: '0',
GIT_CONFIG_NOSYSTEM: '1',
GIT_CONFIG_COUNT: '1',
GIT_CONFIG_KEY_0: 'safe.directory',
GIT_CONFIG_VALUE_0: WORKSPACE_ROOT,
NPM_CONFIG_UPDATE_NOTIFIER: 'false',
CI: 'true',
});/*
* Copyright (c) 2026.
* Author Peter Placzek (tada5hi)
* For the full copyright and license information,
* view the LICENSE file that was distributed with this source code.
*/
import type { SandboxLimits } from './types.ts';
export const DEFAULT_LIMITS: Readonly<Required<SandboxLimits>> = Object.freeze({
cpu: '1',
memory: '2Gi',
storage: '4Gi',
pids: 512,
maxLifetimeMs: 604_800_000,
});
/**
* The workspace image of Docker and Kubernetes: Debian with git, the build
* tools and mise, which installs toolchains at runtime (`images/sandbox-dev`).
*/
export const DEFAULT_SANDBOX_IMAGE = 'ghcr.io/chamvi/sandbox-dev:trixie';
/** Default size of the `/tmp` tmpfs of a container or pod workspace (toolchains go to the cache). */
export const TMP_SIZE = '1Gi';
/** Labels every container or pod workspace carries. */
export const SANDBOX_LABELS: Readonly<Record<string, string>> = Object.freeze({
'app.kubernetes.io/managed-by': 'chamvi',
'app.kubernetes.io/component': 'sandbox',
});
/** `SANDBOX_LABELS` as `key=value` selectors: a Docker label filter, joined by `,` a Kubernetes label selector. */
export const SANDBOX_LABEL_SELECTORS: readonly string[] = Object.freeze(Object.entries(SANDBOX_LABELS).map(([key, value]) => `${key}=${value}`));
export const RUN_LABEL = 'chamvi.dev/run';
export const WORKSPACE_LABEL = 'chamvi.dev/workspace';
/** The deployment a workspace belongs to (`find` and garbage collection see only their own). */
export const DEPLOYMENT_LABEL = 'chamvi.dev/deployment';
/** The deployment of a manager or provider call without one. */
export const DEFAULT_DEPLOYMENT = 'default';
/** `repoKey()` of the workspace's repository (a label value; the URL itself may be longer). */
export const REPO_KEY_LABEL = 'chamvi.dev/repo-key';
/** Expiry in epoch milliseconds: a Docker label, a Kubernetes annotation. */
export const EXPIRES_AT_KEY = 'chamvi.dev/expires-at';
/** Creation in epoch milliseconds: a Docker label, a Kubernetes annotation. */
export const CREATED_AT_KEY = 'chamvi.dev/created-at';
/** The normalized repository URL: a Docker label, a Kubernetes annotation. */
export const REPO_URL_KEY = 'chamvi.dev/repo';
/** The requested ref: a Docker label, a Kubernetes annotation. */
export const REF_KEY = 'chamvi.dev/ref';
/** The image: a Docker label, a Kubernetes annotation. */
export const IMAGE_KEY = 'chamvi.dev/image';
/**
* The command of a workspace container or pod (`sh -c` with the deadline,
* epoch seconds, as `$1`): it sleeps until the workspace's `expiresAt`,
* also when Docker starts the container again after a restart or a pod is
* scheduled late, and exits at once past it. An absolute deadline, since a
* fixed `sleep <lifetime>` would start over on every start.
*/
export const SLEEP_UNTIL_SCRIPT = 'd=$(( $1 - $(date +%s) )); if [ "$d" -gt 0 ]; then exec sleep "$d"; fi';Rules
function normalizeRepo(input: string, options?: NormalizeRepoOptions): string;
function assertGitRef(ref: string): void;
function resolveWorkspacePath(path: string): string;
function resolveLimits(...layers: Array<SandboxLimits | undefined>): Required<SandboxLimits>;
function parseCpu(value: string): number;
function parseMemory(value: string): number;
function assertSandboxEnv(env: Record<string, string> | undefined): void;
function prepareWorkspace(
workspace: IWorkspace,
input: { repo?: string; ref?: string; depth?: number; credential?: GitCredential; signal?: AbortSignal },
): Promise<{ commit?: string; defaultBranch?: string }>;
function readCheckout(workspace: IWorkspace, signal?: AbortSignal, clock?: IClock, options?: { failOnError?: boolean }): Promise<{ commit?: string; defaultBranch?: string } | undefined>;
function createOutputCollector(maxBytes: number): IOutputCollector;For provider authors, the workspace metadata find rebuilds the info from:
function assertDeployment(value: unknown): string; // DEFAULT_DEPLOYMENT for undefined, else a label value or ValidationError
function repoKey(repo: string): string; // 32 hex of the URL's sha256, a label value
function workspaceLabels(input: { id: string; runId: string; deployment: string; repo?: string }): Record<string, string>;
function workspaceMetadata(info: WorkspaceInfo): Record<string, string>; // created, expiry, repo, ref, image
function readWorkspaceInfo(values: Readonly<Record<string, string | undefined>>, provider: string): WorkspaceInfo | undefined;
function createSettledCheck(isSettled?: (runId: string) => Promise<boolean>): (runId: string) => Promise<boolean | SandboxError>;
function lifetimeSeconds(info: Pick<WorkspaceInfo, 'createdAt' | 'expiresAt'>): number; // whole seconds, rounded up, at least 1: how long a container or pod sleepsnormalizeRepo, assertGitRef and resolveWorkspacePath throw ValidationError (model input); resolveLimits, parseCpu, parseMemory and assertSandboxEnv throw InvalidAgentDefinitionError (configuration); prepareWorkspace throws SandboxError with git's stderr when a checkout step fails, records the default branch as git config chamvi.defaultBranch and, as its last step, the checkout as git config chamvi.checkout (the commit, or none without a repo). readCheckout reads both back: { commit, defaultBranch? }, {} for a repo-less workspace, undefined for a create that died before its checkout finished, which find must skip, and (after a few retries) for a workspace it cannot read; with failOnError that unreadable one is a SandboxError instead.
Images, privileges and the cache
function assertImage(value: unknown): string; // an image reference, else ValidationError (never echoed)
function probeImage(transport: IExecTransport, options: { image: string; clock?: IClock; signal?: AbortSignal }): Promise<void>;
function cacheEnv(dir: string): Record<string, string>; // CACHE_ENV's variables under another folder (local)
function isRootUser(user: string | number): boolean; // 0, '0:<gid>', 'root', 'root:<group>'
function assertTmpSizeOption(value: unknown): void; // a positive memory quantity, else InvalidAgentDefinitionError
const CACHE_DIR: '/cache';
const WORKSPACE_HOME: '/home/sandbox'; // HOME of a container or pod workspace, a disk-backed volume of its own
const CACHE_ENV: Readonly<Record<string, string>>; // XDG_CACHE_HOME, npm_config_cache, PIP_CACHE_DIR, GOMODCACHE, GOCACHE, COMPOSER_CACHE_DIR
const ROOT_CAPABILITIES: readonly string[]; // CHOWN, DAC_OVERRIDE, FOWNER, FSETID, SETUID, SETGID, KILL
const IMAGE_REQUIREMENTS: readonly string[]; // sh, git, timeout (with -k), head, base64, tr
const IMAGE_PROBE_TIMEOUT_MS: 30_000;probeImage runs one sh -c script straight on the transport (every workspace exec goes through timeout, which may be what is missing), right after the container or pod started and before the checkout: a SandboxError names what the image lacks (git, timeout, a timeout that supports -k, sh when the script cannot start, sh at /bin/sh, or head, base64 or tr missing from /usr/bin and /bin, the only directories the repository guidance collector resolves them in), or why the probe failed (no answer within IMAGE_PROBE_TIMEOUT_MS on the clock). Docker and Kubernetes add ROOT_CAPABILITIES back for a root user only and mount /cache with CACHE_ENV in every workspace.
Remote workspaces
function createRemoteWorkspace(input: RemoteWorkspaceInput): IWorkspace;
const TIMEOUT_KILL_AFTER_SECONDS: 5;
const EXEC_GRACE_MS: 15_000;
const ALIVE_PROBE_TIMEOUT_MS: 5_000;A provider that can run argv in a container implements IExecTransport: it runs argv, streams stdout and stderr into the sinks it is given and resolves the exit code. createRemoteWorkspace adds the rest: the sh -c script that enters the working directory, runs the command behind the timeout wrapper and reports its exit on stderr (so an exec returns about 2 s after the command exited, even when a background job holds its output), the guard, path checks, output caps, file reads and writes, dispose. After a failed exec it asks alive() (at most ALIVE_PROBE_TIMEOUT_MS); false marks the workspace gone (disposed).
/*
* Copyright (c) 2026.
* Author Peter Placzek (tada5hi)
* For the full copyright and license information,
* view the LICENSE file that was distributed with this source code.
*/
import type { IClock } from '@chamvi/core';
import type { IOutputSink } from '../output/types.ts';
import type { WorkspaceInfo } from '../workspace/types.ts';
export type TransportExecOptions = {
stdin?: Uint8Array;
/** Gets every stdout chunk as it arrives; the workspace caps and keeps it. */
stdout: IOutputSink;
/** Gets every stderr chunk as it arrives; the workspace caps and keeps it. */
stderr: IOutputSink;
/**
* Aborted on a caller abort, a dispose, the client-side guard, or once the
* workspace settled the exec itself (the command exited, a background job
* still holds its output): stop waiting and detach.
*/
signal: AbortSignal;
};
export type TransportExecResult = {
exitCode: number;
/**
* The connection closed before the stream ended (e.g. the daemon reset it
* after the command exited with stdin still queued): the output may be
* cut, so the workspace accepts the result only after the exit marker.
*/
closed?: boolean;
};
/**
* Runs argv in one container or pod. The remote workspace wraps argv itself
* (the working directory, GNU `timeout`, the exit status reported on
* stderr); a transport only executes and streams the output.
*/
export interface IExecTransport {
/** A command that cannot start reports exit 127. */
exec(argv: readonly string[], options: TransportExecOptions): Promise<TransportExecResult>;
/**
* Whether the container or pod still runs; asked after a failed exec. False
* marks the workspace gone. A rejection, or no answer within
* `ALIVE_PROBE_TIMEOUT_MS` (the signal then aborts), reads as alive.
*/
alive?(signal: AbortSignal): Promise<boolean>;
/** Deletes the container or pod; idempotent, a missing one is fine. */
remove(): Promise<void>;
}
export type RemoteWorkspaceInput = {
/** `randomUUID()`. */
id: string;
/** A mutable object the provider owns (it sets `commit` after the checkout). */
info: WorkspaceInfo;
transport: IExecTransport;
/** Default `systemClock`. */
clock?: IClock;
};Context
function provideSandboxContext(provider: IContextProvider, manager: IWorkspaceManager): void; // engine.provide under the key 'sandbox'
function injectSandboxContext(ctx: ToolContext): IWorkspaceManager; // else ContextNotProvidedErrorsandboxModule() provides its manager; with a hand-built engine call provideSandboxContext(engine, manager) after new Engine(). A tools factory then builds the workspace and coding tools per execution: tools: (ctx) => { const manager = injectSandboxContext(ctx); return { ...manager.tools(), ...codingTools(manager) }; }. See Context.
Module
// @chamvi/sandbox/module, needs @chamvi/app
function sandboxModule(options?: SandboxModuleOptions): SandboxModule; // name SANDBOX_MODULE_NAME 'chamvi:sandbox', .manager: IWorkspaceManager
const SANDBOX_PROVIDER_NAMES: readonly SandboxProviderName[]; // ['local', 'docker', 'kubernetes']
const SUSPEND_AFTER_MS: 1_800_000;Git credentials: the credentials option, then the tokens of SANDBOX_GIT_TOKENS (a JSON list of StaticGitCredential; an error names the variable and the entry, never a token), then every source other modules contribute to AppToken.GIT_CREDENTIALS (githubModule()'s App), asked on each lookup. The provider is SANDBOX_PROVIDER, else options.provider, else local, read from options.env ?? process.env when the factory is called; SANDBOX_NAMESPACE, SANDBOX_IMAGE and DEPLOYMENT (the manager's deployment) win over the options too. isSuspendable defaults to a run waiting for at least suspendAfterMs (SANDBOX_SUSPEND_AFTER_MS, default SUSPEND_AFTER_MS 30 minutes, 0 disables this default only: an isSuspendable option replaces it and still applies). On kubernetes, SANDBOX_PERSISTENCE (true/false, over whether persistence is set) and SANDBOX_STORAGE_CLASS (over persistence.storageClassName) build the provider's persistence; other providers ignore them. On docker, SANDBOX_DOCKER_SUSPEND (true/false, over the suspend option, default false) turns suspension on. isSettled defaults to the engine's getRun: a settled run's workspaces are collected, and a missing run's only with a named deployment (DEPLOYMENT or deployment), since in default an unknown run may be another app's on the same host; give each app sharing a host its own name. In start and job mode setup imports the provider package (@chamvi/sandbox-local, @chamvi/sandbox-docker or @chamvi/sandbox-k8s, installed beside @chamvi/sandbox and resolved from there; they are no declared peers, since every provider depends on @chamvi/sandbox and release-please refuses the cycle; a missing one throws InvalidAgentDefinitionError naming it, and under a strict layout that hides undeclared packages (Yarn PnP, pnpm with hoist=false) pass a built provider as options.provider), and the lifecycle hooks attach the manager to the engine, provide it (engineCreated; in start mode also starting the garbage collection every gcIntervalMs on the engine's clock) and close it after the engine drained (the collection timer stopped first); SANDBOX_IMAGES (a comma list of exact image references; an entry that is none is an InvalidAgentDefinitionError naming the variable) is the image allow-list and wins over allowImage; migrate mode does nothing. @chamvi/app is an optional peer: the main entry never imports it.
export type SandboxProviderName = 'local' | 'docker' | 'kubernetes';
/** The kubernetes provider's `persistence`, structurally (a claim per workspace). */
export type SandboxPersistence = {
/** A DNS-1123 subdomain; default the cluster's default storage class. */
storageClassName?: string;
/** The claim's storage request (a quantity); default the resolved `limits.storage`. */
size?: string;
};
/**
* `createWorkspaceManager()` options; the manager's `env` is `workspaceEnv`
* here, since `env` is the process env the factory reads. `deployment`:
* `DEPLOYMENT` wins; `isSettled` defaults to the engine's `getRun`
* (a settled run, and with a named deployment also a missing one), and
* `isSuspendable` to a run `waiting` for at least `suspendAfterMs` (a
* given `isSuspendable` replaces that default).
* `allowImage`: `SANDBOX_IMAGES` (a comma list of exact image
* references) wins; without either, `create_workspace` offers no `image`.
*/
export type SandboxModuleOptions = Omit<WorkspaceManagerOptions, 'provider' | 'env'> & {
/** A provider name (`SANDBOX_PROVIDER` wins) or an instance; default `'local'`. */
provider?: SandboxProviderName | ISandboxProvider;
/** Used as is; no provider is built then. */
manager?: IWorkspaceManager;
/** Kubernetes namespace of the workspace pods; `SANDBOX_NAMESPACE` wins. */
namespace?: string;
/** Docker and Kubernetes image; `SANDBOX_IMAGE` wins, default `DEFAULT_SANDBOX_IMAGE`. */
image?: string;
/**
* Kubernetes only: a claim per workspace keeping `/workspace` and
* `/home/sandbox`, so a suspended run's files survive its pod.
* `SANDBOX_PERSISTENCE` (`true`/`false`) wins over whether it is
* set, `SANDBOX_STORAGE_CLASS` over `storageClassName` (default
* the cluster's default class); `size` default the storage limit.
*/
persistence?: SandboxPersistence;
/**
* Docker only: stop the containers of long-waiting runs (files kept,
* `/tmp` and background jobs lost). `SANDBOX_DOCKER_SUSPEND`
* (`true`/`false`) wins; default false, since a sleeping container
* reserves nothing.
*/
suspend?: boolean;
/** Added to every workspace's environment. */
workspaceEnv?: Record<string, string>;
/**
* How long a run waits (status `waiting`, since its `updatedAt`) before
* the collection suspends its workspaces, in ms; `0` disables the
* default predicate only (a given `isSuspendable` replaces it and still
* applies). `SANDBOX_SUSPEND_AFTER_MS` wins, default `SUSPEND_AFTER_MS`.
* Takes effect with the start-mode collector, so up to `gcIntervalMs`
* later.
*/
suspendAfterMs?: number;
/** Default `process.env`, read when the factory is called. */
env?: Env;
};@chamvi/sandbox-local
function createLocalSandbox(options?: LocalSandboxOptions): ISandboxProvider; // name 'local'No isolation: development and tests only. Workspaces are folders under root (default <os tmpdir>/chamvi-workspaces); of the limits only maxLifetimeMs applies. The cache variables point into <root>/.cache (cache: false sets none). find rebuilds a workspace from its workspace.json, so a restarted process reaches it; the record holds the create's env on disk, so the folder is 0700 and the record 0600.
/*
* Copyright (c) 2026.
* Author Peter Placzek (tada5hi)
* For the full copyright and license information,
* view the LICENSE file that was distributed with this source code.
*/
import type { IClock, SandboxError } from '@chamvi/core';
import type { ExecOptions, SandboxLimits, WorkspaceInfo } from '@chamvi/sandbox';
export type LocalSandboxOptions = {
/** Directory holding one folder per workspace. Default `join(os.tmpdir(), 'chamvi-workspaces')`. */
root?: string;
/** Added to every workspace's environment (after the defaults, so it wins). */
env?: Record<string, string>;
/** The only limit local enforces: the workspace lifetime (expiry, `maxLifetimeMs`). */
limits?: Pick<SandboxLimits, 'maxLifetimeMs'>;
/**
* Point the package caches (`CACHE_ENV`'s variables) into `<root>/.cache`,
* shared by every workspace of the root. Default true.
*/
cache?: boolean;
clock?: IClock;
};
/** What `LocalWorkspace` is built from (internal). */
export type LocalWorkspaceInput = {
id: string;
/** The workspace folder `<root>/<id>`. */
dir: string;
info: WorkspaceInfo;
env: Record<string, string>;
clock: IClock;
/** Called once when the workspace starts disposing. */
onDispose: () => void;
};
/**
* `workspace.json` of a workspace folder (internal): what `find` rebuilds
* the workspace from and the garbage collection reads. Times are ISO strings.
*/
export type WorkspaceRecord = {
runId: string;
deployment: string;
repo?: string;
ref?: string;
/** The create's `env` (the provider's own is added again on every exec). */
env?: Record<string, string>;
createdAt: string;
expiresAt: string;
};
/** A readable workspace record (internal). */
export type ParsedRecord = {
runId: string;
deployment: string;
env?: Record<string, string>;
info: WorkspaceInfo;
};
/** An exec in flight of a `LocalWorkspace` (internal): the dispose fails it. */
export type LiveExec = { fail(error: SandboxError): void };
/** What `spawnLocalExec` runs (internal): the command and the workspace state it reports to. */
export type LocalExecInput = {
argv: readonly string[];
/** The real directory the command starts in. */
cwd: string;
timeoutMs: number;
options: ExecOptions;
env: Record<string, string>;
clock: IClock;
/** The workspace's execs in flight: the exec is in it until it settles. */
live: Set<LiveExec>;
/** Remembers the group of a command that exited while a job of it runs on. */
linger: (pid: number) => void;
};@chamvi/sandbox-docker
function createDockerSandbox(options?: DockerSandboxOptions): ISandboxProvider; // name 'docker'
const DEFAULT_NETWORK: 'bridge';
const CONTAINER_NAME_PREFIX: 'chamvi-ws-';
const DEFAULT_USER: '0:0';One container per workspace (sh -c sleeping until expiresAt, also after a restart, under docker-init, Init: true, which reaps orphans for any image, with the image's entrypoint replaced: it stops itself at expiresAt), removed with its volume on dispose or by the garbage collection. Root with a writable root and ROOT_CAPABILITIES by default; { user: '1000:1000', readOnlyRoot: true } is the hardened mode. /cache is an anonymous volume per workspace, or with cache: { volume } that named volume, shared by every workspace using it (a trust boundary). pull applies to every image, also one a run asked for. find lists a run's containers by label and starts a stopped one again (with restore: false it starts nothing). Only with suspend does the collection stop the containers of suspendable runs. Creating the provider contacts nothing.
/*
* Copyright (c) 2026.
* Author Peter Placzek (tada5hi)
* For the full copyright and license information,
* view the LICENSE file that was distributed with this source code.
*/
import type { IClock } from '@chamvi/core';
import type { SandboxLimits, WorkspaceInfo } from '@chamvi/sandbox';
import type Dockerode from 'dockerode';
export type DockerSandboxOptions = {
/** The Docker client; default `new Docker()` (`DOCKER_HOST` or `/var/run/docker.sock`). */
docker?: Dockerode;
/** Default `DEFAULT_SANDBOX_IMAGE`; pin a digest in production. */
image?: string;
/**
* Default `DEFAULT_NETWORK` (`'bridge'`); `'none'` (repo-less workspaces only,
* the clone runs inside) or any user-created network name, passed through.
*/
network?: string;
/**
* `'missing'` (default) pulls once when the image is not present, `'always'`
* before every create (a mutable tag then follows its rebuilds), `'never'`
* never. It covers every image: the provider's `image`, the manager's and
* one a run asked for (`create_workspace({ image })`).
*/
pull?: 'missing' | 'always' | 'never';
/** Added to every workspace's environment, after `SANDBOX_ENV` and `CACHE_ENV`. */
env?: Record<string, string>;
limits?: SandboxLimits;
/**
* The container user and the user of every command; default `DEFAULT_USER`
* (`'0:0'`, root with the `ROOT_CAPABILITIES`). `'1000:1000'` with
* `readOnlyRoot: true` is the hardened mode (no capability at all).
*/
user?: string;
/** A read-only root filesystem (only `/workspace`, `/cache` and `/tmp` writable). Default false. */
readOnlyRoot?: boolean;
/**
* The `/cache` mount. Default: an anonymous volume per workspace,
* removed with it. `{ volume }` mounts that named volume in every
* workspace instead: a trust boundary shared by every run and agent on
* the host (a package one run fetched can be used by another). Never
* point a non-root `user` at a volume a root workspace wrote to.
*/
cache?: { volume: string };
/**
* Stop the running container of a suspendable run in `collectGarbage`
* (its volume and root filesystem kept, `/tmp` and background jobs
* lost); `find` starts it again. Default false: a sleeping container
* reserves nothing on Docker, so it keeps running.
*/
suspend?: boolean;
/** Size of the `/tmp` tmpfs; default `TMP_SIZE` (`'1Gi'`). */
tmpSize?: string;
clock?: IClock;
};
export type ContainerOptionsInput = {
id: string;
deployment: string;
/** Run, image, repo, ref and times: labels a provider's `find` rebuilds the info from. */
info: WorkspaceInfo & { image: string };
network: string;
user: string;
readOnlyRoot: boolean;
/** The shared cache volume (`cache.volume`); undefined mounts an anonymous one per workspace. */
cacheVolume?: string;
tmpSize: string;
env: Record<string, string>;
limits: Required<SandboxLimits>;
};@chamvi/sandbox-k8s
function createKubernetesSandbox(options: KubernetesSandboxOptions): ISandboxProvider; // name 'k8s'
function createPodClient(input: CreatePodClientInput): IPodClient;
const CONTAINER_NAME: 'sandbox';
const POD_NAME_PREFIX: 'chamvi-ws-';
const START_TIMEOUT_MS: 120_000;
const POLL_MS: 1_000;
const FATAL_WAITING_REASONS: readonly string[];One pod per workspace, sleeping for its lifetime with that activeDeadlineSeconds (the image's entrypoint replaced), so it ends itself at expiresAt; imagePullPolicy applies to every image; find lists a run's running pods by label. Root with a writable root and ROOT_CAPABILITIES by default (Pod Security baseline); { user: { uid: 1000, gid: 1000 }, readOnlyRoot: true } is the hardened mode (restricted). /cache is the claim of cache.claimName or an emptyDir. With persistence each workspace gets a ReadWriteOnce claim chamvi-ws-<id> for /workspace and /home/sandbox: the collection suspends a waiting run's pod by deleting it (the claim stays) and find rebuilds it (a failed rebuild is a SandboxError); the claim goes with the workspace (dispose, expiry, a settled run). A node-local storage class pins the rebuilt pod to its node. The Role needs pods create, get, list, delete and pods/exec get and create in the sandbox namespace, with persistence also persistentvolumeclaims create, get, list, delete. See Kubernetes & Flux.
/*
* Copyright (c) 2026.
* Author Peter Placzek (tada5hi)
* For the full copyright and license information,
* view the LICENSE file that was distributed with this source code.
*/
import type { KubeConfig } from '@kubernetes/client-node';
import type { IClock } from '@chamvi/core';
import type { SandboxLimits, WorkspaceInfo } from '@chamvi/sandbox';
import type { IPodClient } from '../client/types.ts';
export type ImagePullPolicy = 'Always' | 'IfNotPresent';
export type PodUser = {
uid: number;
gid: number;
};
/**
* A ReadWriteOnce claim per workspace (`chamvi-ws-<id>`, like its pod)
* holding `/workspace` and `/home/sandbox`, so the files outlive the pod.
*/
export type KubernetesPersistence = {
/** A DNS-1123 subdomain; default the cluster's default storage class. */
storageClassName?: string;
/** The claim's storage request (a quantity); default the resolved `limits.storage`. */
size?: string;
};
export type KubernetesSandboxOptions = {
/** Namespace of the workspace pods (required). */
namespace: string;
/** Default `new KubeConfig()` with `loadFromDefault()` (in-cluster or `KUBECONFIG`). */
kubeConfig?: KubeConfig;
/** Default `DEFAULT_SANDBOX_IMAGE`; pin a digest in production. */
image?: string;
/** Added to every workspace's environment, after `SANDBOX_ENV`. */
env?: Record<string, string>;
limits?: SandboxLimits;
/** Extra pod labels (e.g. for a NetworkPolicy); may not name a managed label. */
podLabels?: Record<string, string>;
/**
* Pull policy of every workspace image (the provider's, the manager's
* and one a run asked for through `create_workspace({ image })`):
* default `'IfNotPresent'`, `'Always'` for a mutable tag.
*/
imagePullPolicy?: ImagePullPolicy;
/**
* uid and gid of the pod; default `{ uid: 0, gid: 0 }` (root with the
* `ROOT_CAPABILITIES`, which needs a namespace whose Pod Security admits
* root pods, i.e. `baseline`). `{ uid: 1000, gid: 1000 }` with
* `readOnlyRoot: true` is the hardened mode, which `restricted` admits.
*/
user?: PodUser;
/** A read-only root filesystem (only `/workspace`, `/cache` and `/tmp` writable). Default false. */
readOnlyRoot?: boolean;
/**
* A ReadWriteMany claim every workspace mounts at `/cache`, shared by every
* run and agent of the namespace (a package one run fetched can be used by
* another). Without it each pod gets an emptyDir `/cache` of its own.
*/
cache?: { claimName: string };
/**
* Keep each workspace's files on a claim of its own (see
* `KubernetesPersistence`); a custom `client` then needs the claim
* methods. Default none: the files live in emptyDirs and go with the pod.
*/
persistence?: KubernetesPersistence;
/** Size of the in-memory `/tmp`; default `TMP_SIZE` (`'1Gi'`). */
tmpSize?: string;
/** Default `START_TIMEOUT_MS`. */
startTimeoutMs?: number;
/** Default `POLL_MS`. */
pollMs?: number;
clock?: IClock;
/** Test seam; default `createPodClient({ kubeConfig, namespace })`. */
client?: IPodClient;
};
export type PodInput = {
id: string;
deployment: string;
namespace: string;
/** Run, image, repo, ref and times: labels and annotations a provider's `find` rebuilds the info from. */
info: WorkspaceInfo & { image: string };
env: Record<string, string>;
limits: Required<SandboxLimits>;
/** The `podLabels`; the managed labels win. */
labels: Record<string, string>;
imagePullPolicy: ImagePullPolicy;
user: PodUser;
readOnlyRoot: boolean;
/** The shared cache claim; undefined mounts an emptyDir. */
cacheClaim?: string;
/** The workspace's own claim for `/workspace` and the home; undefined mounts emptyDirs. */
claim?: string;
tmpSize: string;
/** Default `lifetimeSeconds(info)`; a pod rebuilt from its claim gets what is left. */
activeDeadlineSeconds?: number;
};
export type ClaimInput = {
id: string;
deployment: string;
namespace: string;
/** The same labels and annotations as the pod's, so `readWorkspaceInfo()` works on the claim. */
info: WorkspaceInfo & { image: string };
/** The storage request, a quantity. */
size: string;
storageClassName?: string;
};/*
* Copyright (c) 2026.
* Author Peter Placzek (tada5hi)
* For the full copyright and license information,
* view the LICENSE file that was distributed with this source code.
*/
import type { Writable } from 'node:stream';
import type {
CoreV1Api,
Exec,
KubeConfig,
V1PersistentVolumeClaim,
V1Pod,
} from '@kubernetes/client-node';
export type PodExecInput = {
argv: readonly string[];
/** Written to the command; closed only on the `v5.channel.k8s.io` protocol. */
stdin?: Uint8Array;
stdout: Writable;
stderr: Writable;
/** Closes the socket: the command runs on until its `timeout` or the pod's deletion. */
signal: AbortSignal;
};
/**
* The pod operations the Kubernetes sandbox needs, in one namespace. Every
* failure is a `SandboxError`; deleting a missing pod is fine. The claim
* methods are needed only with the provider's `persistence`.
*/
export interface IPodClient {
create(pod: V1Pod): Promise<V1Pod>;
read(name: string): Promise<V1Pod>;
/** Without a grace period; a missing pod is fine. */
delete(name: string): Promise<void>;
list(labelSelector: string): Promise<V1Pod[]>;
/** Runs argv in the pod's sandbox container; the exit code from the exec status. */
exec(name: string, input: PodExecInput): Promise<{ exitCode: number }>;
createClaim?(claim: V1PersistentVolumeClaim): Promise<V1PersistentVolumeClaim>;
/** A missing claim is fine. */
deleteClaim?(name: string): Promise<void>;
listClaims?(labelSelector: string): Promise<V1PersistentVolumeClaim[]>;
}
export type CreatePodClientInput = {
kubeConfig: KubeConfig;
namespace: string;
};
export type PodClientParts = {
core: Pick<
CoreV1Api,
'createNamespacedPod' |
'readNamespacedPod' |
'deleteNamespacedPod' |
'listNamespacedPod' |
'createNamespacedPersistentVolumeClaim' |
'deleteNamespacedPersistentVolumeClaim' |
'listNamespacedPersistentVolumeClaim'
>;
exec: Pick<Exec, 'exec'>;
namespace: string;
};
/** The part of the exec WebSocket the client uses. */
export type ExecSocket = {
readonly protocol: string;
close(): void;
on(event: 'close', listener: () => void): unknown;
on(event: 'error', listener: (error: Error) => void): unknown;
};Bash-first migration
Remove credentialMode, its CredentialMode type and CHAMVI_GIT_CREDENTIAL_MODE. Workspace-installed credentials are the only mode; a set CHAMVI_GIT_CREDENTIAL_MODE or a credentialMode option is refused with InvalidAgentDefinitionError instead of being ignored (a former tools mode would otherwise hand bash the write token). The structured Git tools, their result types and PushPolicy remain available. Push checks govern git_push only; sandbox code with another execution path can bypass them.
Structured Git tools and policy scope
manager.tools() includes git_fetch, git_pull and git_push without granting a bash tool. They retain structured results, per-target credential lookup, force-with-lease, branch checks and the optional durable approval flow through push: { mode: 'approve', channel?, allowBranch?, allowForce? }. The push policy applies only to git_push: bash with write credentials can bypass it. In a tainted run git_push asks once: the untrusted-content gate's approval (private, in the inbox and API, with only a generic notice on the run's source channel) carries the same Push <n> commits to <branch> title and commit log, and the push asks nothing more, so push.channel is not asked in a tainted run. A push the policy refuses (a force push without allowForce, a branch allowBranch refuses) is denied before the gate asks. Separately, fetch/pull and push taint the run before exposing their results, including remote hook output from push. Push is always guarded in tainted runs; fetch/pull are classified outbound when their normalized target differs from the workspace's configured origin. Tainted runs therefore need approval (or are denied) before contacting a non-origin target. Origin requests remain exempt. This is not general SSRF prevention; constrain allowed repositories and network access separately. Disabling bash narrows the offered capabilities, but writable Git configuration, hooks and other indirect execution still require a threat model; the tools are not a credential-secrecy boundary. Enforce hard restrictions through token scope and forge rules.