Skip to content

Use a workspace

ai.workspace(policy) returns a workspace: a bounded place an agent reads, writes, and runs commands. One policy, one shared rule set, two ways to touch it — the agent uses ws.tools.*, you use the direct methods. Ships in @warlock.js/ai-workspace; import the package once for its side effect so the verb registers on the shared ai.

import "@warlock.js/ai-workspace";
import { ai } from "@warlock.js/ai";
const ws = ai.workspace({
cwd: "/srv/acme-api",
denyPaths: [".git/**", ".env*"],
shell: { allow: ["npm", "node"], inheritEnv: ["PATH"], timeoutMs: 60_000 },
read: { defaultLines: 2_000 },
backend: "local", // default; use "mock" for hermetic tests
});

Needs @warlock.js/fs. The "local" backend runs over the real disk via @warlock.js/fs + node:child_process (a direct dependency of the package — no extra install). The "mock" backend needs nothing.

This is least-privilege guardrails for a trusted agent — not a sandbox around hostile code. It enforces a realpath-resolved cwd jail, path allow/deny, a fail-closed shell allow/deny list, timeouts, output caps, and a non-inherited environment. It does not contain what an allowed process does once it runs. For an untrusted agent, run the workspace inside a container, a microVM or as a separate unprivileged user, and treat this policy as a second layer (see Shell mode is a policy layer, not a sandbox).

How paths are jailed. Every path is resolved against cwd with symlinks collapsed (realpath of the deepest existing ancestor), then accepted only inside cwd or an allowPaths root and off denyPaths. Absolute paths inside the jail, a symlinked cwd, links whose target stays inside, and paths that do not exist yet (for writeFile / mkdir) are all accepted. This is deliberately not @warlock.js/fs’s confined reader (fs.confined), which refuses absolute paths and every link and only reads existing files: an app reading a folder it does not trust should use that reader; the workspace keeps its own resolver because its tools also write, run commands and honour several roots.

FieldWhat it does
cwdAbsolute jail root. Every path resolves against it and must stay inside.
allowPathsExtra readable roots outside cwd.
denyPathsGlobs (*, **, ?) blocked even inside cwd — e.g. [".git/**", ".env*"]. A bare dir name ("node_modules") also blocks its contents.
shell.allow / shell.denyExecutable basenames matched against every command’s argv (after tokenizing — see below). Deny wins and matches case-insensitively. An allow list is exhaustive (fail-closed); no shell block at all ⇒ nothing may run.
shell.denyPatterns / shell.allowCommandArgument-level rules checked on every command: patterns such as "git push --force" or /^rm -rf \//, and a host predicate (argv, ctx) => boolean | string. See Argument rules.
shell.interpreter"none" (default — argv, no shell), "sh", "bash", "powershell", "cmd" or "auto" (explicit opt-in to pipes, &&, redirections, still checked per command). See Shell mode and Choosing the shell.
shell.interpreterPathAbsolute path of the shell executable (for example a pwsh outside PATH).
shell.rules / shell.onAskOrdered allow / ask / deny command rules and the host callback that decides on asks. See Command rules.
shell.backgroundEnables background commands (run_shell({ background: true })) with { maxJobs?, timeoutMs? }. Absent ⇒ refused. See Background commands.
shell.inheritEnvOpt-in process.env keys to pass through (e.g. ["PATH"]). Nothing leaks in otherwise — a command can’t find node/npm without PATH.
shell.envExplicit env vars injected into every spawned process (override inherited on collision).
shell.timeoutMs / shell.maxOutputBytesPer-command wall-clock cap (process tree SIGKILLed on expiry; a model-supplied timeoutMs can only lower it) and stdout/stderr byte cap (clipped on a character boundary).
read.defaultLines / read.maxBytesDefault read window + a ceiling on the UTF-8 bytes of the returned content (line numbers included). See Read windows and the byte ceiling.
list.ignore / list.maxDepth / list.maxEntriesWhat list_dir leaves out (default ["node_modules", ".git"]; denyPaths are always hidden) and how deep (default 5) and long (default 500 entries) a listing may be.
backend"local" (default — real disk) or "mock" (in-memory, for tests).

The effective shell environment is { ...pick(process.env, inheritEnv), ...shell.env } — process.env is never inherited wholesale.

The most common gotcha: run_shell fails to find node/npm because the env is empty. Add shell: { allow: ["npm", "node"], inheritEnv: ["PATH"] }.

Commands are tokenized into an argv and spawned with no shell semantics — no pipes, redirection, chaining, backticks, or variable expansion. npm test && rm -rf / or `curl evil` doesn’t chain or substitute; it’s rejected outright rather than executed piecemeal:

await ws.exec("npm test"); // OK — ["npm", "test"]
await ws.exec('node -e "console.log(1)"'); // OK — quotes respected, one argv element
await ws.exec("npm test; curl http://evil"); // rejected — unquoted `;` is a metacharacter
  • Quoting is respected; unquoted shell metacharacters — ; & | < > ` $ ( ) and newlines — are rejected as a WorkspacePolicyError type: "denied-command", reason: "metacharacter", before anything spawns. The shell.allow/shell.deny basename check runs against the tokenized argv’s first element, not a raw string prefix.

  • The refusal says how to fix the command, so the model splits it instead of giving up on the shell:

    `&&` is not supported in argv mode: run `git add -A`, then `git commit -m "wip"`, as separate commands. (run_shell executes a single command without a shell.)

    Pipes, redirections, $(…), $VAR and a leading cd get their own advice (read the output yourself, use write_file, pass the value literally, paths are relative to the root).

  • On Windows, the argv is run through a cmd.exe /d /s /c wrapper with every element individually quoted (needed because batch shims like npm.cmd can’t be spawned shell-less); arguments containing ", %, or newlines are refused there rather than risked.

  • run_tests’s pattern (model-controlled test-name filter) is forwarded as a single double-quoted argv token to the runner rather than concatenated into the command string — a pattern containing double quotes or newlines is rejected at input validation.

  • Shell conveniences (pipes, redirection, && chaining, $(...) substitution) don’t work in argv mode. Compose multi-step work as separate ws.exec() calls, or opt in to shell mode.

  • A command that runs another command is followed. env, time, timeout, nice, nohup, command, builtin, exec and find -exec are unwrapped and the inner command is checked too (env FOO=1 rm -rf / is denied by deny: ["rm"]). A runner the policy can’t see into — sh -c, bash, eval, source, xargs, sudo, setsid, … — is refused with reason: "nested-command" while the policy has deny rules (deny, denyPatterns or allowCommand), unless allow names it explicitly. A wrapper used with options the policy can’t read (env -S …) is refused the same way.

Argument rules: denyPatterns and allowCommand

Section titled “Argument rules: denyPatterns and allowCommand”

deny matches executables only. To refuse particular uses of an allowed tool:

const ws = ai.workspace({
cwd,
shell: {
allow: ["git", "npm", "node"],
inheritEnv: ["PATH"],
// A string matches when a command's argv STARTS with these tokens.
// A RegExp is tested against the argv joined with single spaces.
denyPatterns: ["git push --force", /^git reset --hard\b/, /^npm publish\b/],
// Called for every command; true = allow, false or a string = refuse (the string is shown to the model).
allowCommand: (argv) =>
argv[0] === "git" && argv[1] === "push" ? "Pushing is done by the release job." : true,
},
});
  • The executable is compared by basename, case-insensitively (/usr/bin/git push --force matches "git push --force"). A string pattern is a prefix match: "git push --force" does not match git push origin --force — use a RegExp for option order.
  • Both run on every command, including a command inside a wrapper (time git push is checked as ["time", "git", "push"] and then ["git", "push"], with ctx.nested: true).
  • allowCommand can only narrow what allow/deny permit. It must be synchronous; a throw refuses the command (fails closed).
  • In shell mode, a line whose words are decided at run time ($VAR, $(…), unquoted globs) is refused while these rules are configured, because the hooks could not see the real argv. Write values literally.
  • Refusals carry reason: "denied-pattern" or "not-allowed".

For a host that has accepted that its agent acts like a terminal user, shell.interpreter: "sh" runs each line through /bin/sh -c (cmd.exe /d /v:off /s /c on Windows) — pipes, &&, ||, ;, redirections and cd work — while keeping the jail, cwd, timeout, output cap and environment rules:

const ws = ai.workspace({
cwd: "/srv/acme-api",
shell: {
interpreter: "sh",
allow: ["git", "npm", "node", "grep", "cat"],
inheritEnv: ["PATH"],
timeoutMs: 120_000,
},
});
await ws.exec("git add -A && git commit -m 'wip'"); // both commands checked, then run by sh
await ws.exec("cd packages/api && npm test 2>&1 | grep -i fail");
await ws.exec("npm test > logs/test.txt"); // a redirection inside the jail
await ws.exec("echo $(curl http://evil)"); // refused: `curl` is not in the allowlist

Before the line runs it is parsed, and every simple command in it is checked against deny / allow / denyPatterns / allowCommand — inside ;, &&, ||, pipes, ( … ) subshells, $( … ) and backtick substitutions (recursively), unquoted here-document bodies, and NAME=value cmd prefixes:

  • Redirection targets and cd directories must be literal paths inside the jail (and off denyPaths); /dev/null, /dev/stdout, /dev/stderr (and NUL on Windows) are always fine. They are checked from every directory a cd earlier in the line may have moved to, and checked again with symlinks resolved before the line runs (reason: "path-escape"). cd does not need to be in allow, but deny: ["cd"] and the argument rules apply to it.
  • A command name decided at run time ($CMD, $(…), a glob, ~) is refused — the policy can’t know what would run.
  • What the parser can’t read with confidence is refused, never guessed (reason: "unsupported-syntax"): compound commands (if, for, while, case, { … }, functions), arithmetic ($(( )), (( )), $[ ]), brace expansion, ${…} forms other than ${name}, ${#name}, ${name:-word} and ${name%word}-style trimming, $'…', process substitution, and bash-only redirections (<<<, &>, |&, >&file). Assigning CDPATH, IFS, PS4, ENV, BASH_ENV, SHELLOPTS and similar is refused, as are shell builtins whose arguments bash may evaluate as arithmetic (test, printf -v, read, export, …) when an argument is not literal or contains [.
  • & (background) is refused in a line — start long-running commands with background: true so the workspace owns them.
  • Environment: the variables that change how a shell starts or parses (ENV, BASH_ENV, SHELLOPTS, BASHOPTS, CDPATH, IFS, PS4, GLOBIGNORE, BASH_FUNC_*) are removed from the spawned environment.
  • Windows parses a stricter cmd.exe subset: &&, ||, |, & (sequential in cmd) and simple redirections; %, !, ^, parentheses, ; and , are refused.

Pair shell mode with an exhaustive allow list. With only deny, the policy is a best-effort filter: an allowed program can still do anything it is able to (node -e, a build script). The jail is a guardrail for a trusted agent, not OS isolation.

Shell mode is a policy layer, not a sandbox

Section titled “Shell mode is a policy layer, not a sandbox”

Shell mode checks a command line before /bin/sh runs it. It is defence in depth: a parser that reads the line the way the shell will, and refuses what it cannot read. It is not an operating-system sandbox, and it cannot be one:

  • /bin/sh differs between systems (bash, dash, busybox ash), and between versions of each. The parser refuses the constructs where they disagree, but a check that runs before the shell can never be stronger than the shell’s own reading of the line.
  • Once an allowed program runs, the policy no longer sees what it does. An allowed node, npm, make or git hook can start any process and touch any file the operating-system user can.
  • Symlinked redirection targets are re-checked just before the line runs, but the filesystem can change between that check and the write.

For an agent you do not fully trust (one that reads untrusted repositories, issues, web pages or tool output), run the whole workspace under real OS isolation: a container or microVM with only the project mounted, or at least a separate unprivileged user that owns nothing else, without network access it does not need. Use the shell policy on top of that, never instead of it. Argv mode (interpreter: "none", the default) gives the agent far less surface than shell mode; prefer it when the agent does not need pipes or redirections.

Every shell refusal is a WorkspacePolicyError with type: "denied-command" and a structured reason, so a host can phrase it itself:

reasonCause
"metacharacter"argv mode met an unquoted operator; the message suggests the split
"unbalanced-quotes"a quote (or $(, backtick, ${) is never closed
"denied-executable"an executable is in shell.deny (error.executable names it)
"not-allowed"not in shell.allow, refused by allowCommand, no shell policy, empty line, background not enabled
"denied-pattern"a command matched shell.denyPatterns
"nested-command"a command runner the policy can’t see into, while deny rules are in force
"unsupported-syntax"shell mode: syntax the parser does not read with confidence
"path-escape"shell mode: a redirection target or cd directory outside the jail (error.path names it)
"approval-required"a command matches an ask rule and the policy has no shell.onAsk
"approval-denied"shell.onAsk said no (or threw)

checkShellCommand(policy, command) returns the same verdict without running anything: { allowed, reason?, message?, executable?, path?, asks, commands, paths }.

shell.interpreter takes more than "sh". Each shell is read by its own conservative parser, and every command it finds goes through the same deny / allow / denyPatterns / allowCommand / rule checks as "sh", with redirection targets and directory changes held to the jail.

interpreterRuns the line withGrammar
"sh"/bin/sh -c (cmd.exe on Windows) — unchangedPOSIX / cmd
"bash"bash -c (found on PATH, or interpreterPath)POSIX
"powershell"pwsh (else powershell, Windows PowerShell 5.1) with -NoLogo -NoProfile -NonInteractive -CommandPowerShell
"cmd"cmd.exe /d /v:off /s /ccmd.exe
"auto"POSIX: bash if on PATH, else sh. Windows: pwsh (PowerShell 7+), Git Bash (next to git on PATH), powershell (5.1), then cmd.exethe resolved one

run_shell’s description names the resolved shell (“Commands run on Windows using PowerShell 7 (pwsh).”) and its syntax rules, so the model writes the right dialect. run_tests quotes its pattern for the shell too (single quotes for POSIX shells and PowerShell, double quotes for cmd.exe and argv mode).

PowerShell lines support ;, line breaks, && and ||, pipelines, $( ) subexpressions (their commands are checked), the call operator & before a command, single and double quotes, $name / $env:NAME (dynamic words), and the redirections >, >>, 2>, 2>>, *> and 2>&1 ($null is always fine). It refuses, as "unsupported-syntax": script blocks and braces, bare parentheses, @( ) / @{ } / splatting / here-strings, --%, <, comments, the comma operator, statements (if, foreach, function, try, …), dot-sourcing, & as a background job, and Push-Location / pushd / popd. Invoke-Expression / iex, Invoke-Command, Start-Process, Add-Type, Set-Alias, Invoke-Item, and powershell / pwsh themselves (-Command, -EncodedCommand) run code the policy cannot see, so they are refused as "nested-command" while deny rules exist. Set-Location / sl / cd / chdir take one directory (-Path, -LiteralPath or positional) and must stay in the jail.

Windows PowerShell 5.1 (powershell.exe) has no && or ||, so it reads the same grammar without them: a line that uses either is refused as "unsupported-syntax" with “Windows PowerShell 5.1 cannot run &&; use ; or run each command in its own call instead.”, and run_shell’s description tells the model not to chain. resolveShell() reports edition ("desktop" for 5.1, "core" for PowerShell 7+) and version ("5.1" for Windows PowerShell; for pwsh only when the host supplies it through ShellHost.powershellVersion). The edition comes from the executable that was found, and the dialect is "powershell5" for 5.1 and "powershell" for 7+. Install pwsh or pick interpreter: "bash" (Git Bash) when the agent needs &&.

PowerShell names the same command many ways, so each command is checked as written and in a canonical form: Remove-Item / ri / rm / del / erase / rd / rmdir become rm with -Recurse / -Force (and their unambiguous prefixes) turned into -rf; Copy-Item, Move-Item, Get-ChildItem, Get-Content, Invoke-WebRequest and Stop-Process map to cp, mv, ls, cat, curl and kill the same way. A denyPatterns entry of "rm -rf" therefore stops Remove-Item -Recurse -Force x. The canonical form skips the allow list (which names the spelling you wrote) but runs deny, denyPatterns, allowCommand and the rules.

shell.rules is an ordered list of { match, effect, reason? }. match is a string prefix on the argv or a RegExp on the joined argv (same as denyPatterns); effect is "allow", "ask" or "deny". For one command the last matching rule wins; a deny anywhere in a line refuses the whole line, and allow / deny / denyPatterns / allowCommand keep working as before.

const ws = ai.workspace({
cwd,
shell: {
interpreter: "sh",
rules: [
{ match: "git status", effect: "allow" },
{ match: "git push", effect: "ask", reason: "Pushing publishes work." },
{ match: /^rm -[a-z]*r/, effect: "deny", reason: "Recursive deletes are not allowed." },
],
onAsk: async ({ command, asks, signal }) => {
const approved = await confirm(`Run ${command}?`, { signal });
return { allow: approved, remember: approved ? "git push" : undefined };
},
},
});

onAsk is called once per line with every command that needs a decision (asks[i].reason is "rule" for an ask rule or an unmatched command, "unparsed" for syntax the parser cannot read, "nested" for a runner such as bash -c or iex). With onAsk set, a command no rule matches also asks; without it, behaviour is as before and an ask rule is refused with "approval-required". { allow: false }, a throw or a rejection refuses the line with "approval-denied". remember adds a session allow for a pattern (or an array of patterns, for a line such as git status -s && npm test that asks about two commands), shared with readonly() and scope() views: it skips later asks for matching commands but never overrides a deny. ws.shell.remembered() lists the remembered patterns and ws.shell.forget(pattern) removes one (returns whether it was there). { allow: false, reason: "use staging" } appends the reason to the refusal the model reads from run_shell (cut at 500 characters with a [truncated] marker).

ws.shell.classify(line) (and the standalone classifyShellCommand(line, policy?)) returns { commands: string[][], opaque? }: the simple commands a line would run, read with the workspace’s dialect, without running or checking anything. opaque carries the reason when the line cannot be read.

The model supplies pattern freely, so grep treats it as untrusted input before compiling it into a RegExp: patterns over 200 characters and patterns matching a nested-quantifier shape ((x+)+, (x*)*, (x+)*, (x*)+-style groups — the classic catastrophic-backtracking shape) are rejected up front as a WorkspacePolicyError type: "unsafe-pattern", before any regex is compiled. Any scanned line longer than 2000 characters is skipped (not tested), bounding the worst-case backtracking cost of any single call.

Each tool is a ToolContract ready for ai.agent({ tools }), and publishes a JSON Schema of its input so the provider sends the model the real parameter shape. The LLM-visible tool names are read_file, edit_file, multi_edit, apply_patch, write_file, list_dir, run_shell, shell_output, shell_kill, run_tests, grep, glob, todo_write and todo_read. shell_output / shell_kill are included in all() only when shell.background is set.

ws.tools.all(); // every tool, canonical order
ws.tools.pick("readFile", "grep", "glob"); // a least-privilege subset
ws.tools.readFile({ name: "open" }); // one tool, optionally renamed
ws.tools.runTests({ command: "pnpm test" }); // override the test base command

pick(...) silently drops any name the projection does not allow, so a readonly() workspace can never be coaxed into vending a mutating tool.

const dev = ai.agent({
model,
tools: ws.tools.all(),
maxTrips: 25,
});
await dev.execute("`npm test` fails on the cart-total suite. Make it green.");

The same policy seam, callable from code (no LLM):

const { content, hash, totalLines, endLine, truncated, bytesCapped } = await ws.readFile(
"src/index.ts",
{ offset: 1, limit: 200 },
);
await ws.writeFile("src/new.ts", "export const x = 1;\n");
await ws.editFile({ path: "src/index.ts", oldString: "old", newString: "new", expectHash: hash });
const { exitCode, stdout, stderr, timedOut, cancelled, truncated } = await ws.exec("npm test");
const { matches } = await ws.grep("TODO", { glob: "src/**/*.ts", ignoreCase: true });
const paths = await ws.glob("src/models/**/*.ts");
await ws.exists("package.json");
await ws.mkdir("src/generated");
await ws.remove("dist");
await ws.multiEdit({ path: "src/cart.ts", edits: [{ oldString: "a", newString: "b" }] });
const { entries, truncated } = await ws.listDir("src", { depth: 2 });
const job = await ws.startShell("npm run dev"); // needs shell.background
const { stdout, cursor, status } = await ws.shellOutput(job.id, { waitMs: 2_000 });
await ws.shellKill(job.id);
ws.writeTodos([{ content: "Fix the rounding bug", status: "in_progress" }]);
const { todos, counts } = ws.readTodos();
await ws.dispose(); // kills background commands; refuses new commands

list_dir({ path?, depth?, ignore? }) returns { path, entries, truncated }: entries breadth-first, each level sorted by name, with type ("file", "directory", "symlink", "other"), size for files and depth (1 = direct child). It is bounded — depth is capped by list.maxDepth (default 5) and the listing by list.maxEntries (default 500, then truncated: true) — and jailed: denyPaths are always left out, as are the list.ignore globs (default node_modules, .git) and any ignore globs the model passes. Ignored paths are hidden, not blocked: listing node_modules directly still works. Symlinks are reported, never followed.

apply_patch({ patch, dryRun? }) applies a unified diff (plain, or git diff style) that can modify, create (--- /dev/null), delete (+++ /dev/null) and rename (rename from / rename to) several files in one call. It is atomic: every hunk of every file is checked in memory first, and the files are written only if all of them apply; if a write fails part-way, the files already written are restored. Nothing changes otherwise.

  • Every path (old and new) goes through the same jail as the other file tools, so .., absolute paths and symlinks out of the workspace are refused, as are denyPaths.
  • Hunks are found by their context, not only by line number, so a few lines of drift are fine. A hunk whose context is not in the file fails with type: "hunk-failed" and its hunkIndex.
  • Line endings are preserved: untouched lines stay byte-for-byte, and added lines use the file’s CRLF or LF style. A patch wrapped in CRLF is accepted. \ No newline at end of file is honoured.
  • Binary patches (Binary files … differ, GIT binary patch) and target files that contain NUL bytes are refused with type: "binary-file". Copies are not supported.
  • A create over an existing path fails with "file-exists"; changing, renaming or deleting a missing path fails with "file-missing". A malformed or oversized diff (over 2 MB or 200 files) fails with "patch-invalid".
  • File patches apply in order against a virtual tree, so a patch can delete a path and create it again, or swap two files by renames.
  • dryRun: true validates and reports without writing.

It returns { files: [{ path, action, oldPath?, hunks, hash? }], dryRun } where action is "modified", "created", "deleted" or "renamed". Directly: await ws.applyPatch({ patch }). It is not part of readonly(). A custom WorkspaceOps does not have to implement applyPatch: without it, the same engine runs on its exists, readFile, writeFile and remove (applyPatchWithOps), with the same checks and rollback. The patch engine itself is exported as parsePatch(text) and applyHunks(content, hunks, path) for code that needs to apply a diff to a string.

multi_edit({ path, edits: [{ oldString, newString, replaceAll? }, …], expectHash? }) applies up to 100 replacements to one file atomically: in order, each against the result of the previous ones, under the same rules as edit_file (oldString found, and unique unless replaceAll), then one write. If any edit fails, nothing is written and the WorkspaceEditError says which one (editIndex, and “Edit 2: …” in the message). expectHash rejects the whole call when the file changed since it was read. It returns { path, edits, replacements, hash }.

Dev servers and watchers need to keep running while the agent works. Enable them with shell.background:

const ws = ai.workspace({
cwd,
shell: {
allow: ["npm", "node"],
inheritEnv: ["PATH"],
background: { maxJobs: 2, timeoutMs: 30 * 60_000 },
},
});
const dev = ai.agent({ model, tools: ws.tools.all() }); // includes shell_output + shell_kill
  • run_shell({ command, background: true }) checks the command like any other, starts it and returns at once with { background: true, id: "job-1", status: "running", pid, … }.
  • shell_output({ id, since?, waitMs? }) returns { stdout, stderr, cursor, droppedBytes, truncated, status, exitCode, … } — output produced since the previous read (or since cursor you pass as since). waitMs (max 30 s) waits for new output or for the command to stop. Only the newest shell.maxOutputBytes (default 1 MB) of each command’s output is kept; droppedBytes says how much the reader missed.
  • shell_kill({ id }) kills the command’s whole process tree and reports its final state ("killed"). States: "running", "exited", "killed", "timed-out".
  • Background commands belong to the workspace, not to the agent run: cancelling the run does not stop them. ws.dispose() kills every one of them (whole trees) and makes the workspace refuse new commands; trees still running when the Node process exits are killed too. Call dispose() when the work is done.
  • maxJobs (default 4) bounds how many run at once; timeoutMs (default none) kills one after that long, and a model-supplied timeoutMs can only lower it. Without shell.background, a background request is refused with reason: "not-allowed".
  • Only the processes the workspace started are ever signalled: on POSIX each command runs in its own process group and that group is killed; on Windows taskkill /T is run on the command’s own PID.

Coding agents plan better with a visible checklist. todo_write({ todos: [{ content, status, id? }, …] }) replaces the list with the complete updated one (status: "pending", "in_progress", "completed"; at most 100 items; missing ids become "1", "2", …); todo_read({}) returns { todos, counts }. The list lives in memory, one per workspace, shared by its readonly() and scope() projections — ws.readTodos() / ws.writeTodos() reach the same list from code.

readFile() and the read_file tool return the same result for the same arguments: a cat -n numbered window plus { startLine, endLine, totalLines, totalBytes, truncated, bytesCapped, hash }.

  • The window starts at offset (startLine on the tool) and holds at most limit lines (default read.defaultLines, else 2000).
  • read.maxBytes caps the UTF-8 bytes of the returned content itself — line-number prefixes and newlines count. Whole lines are kept while they fit; the first line that doesn’t is cut on a character boundary (never mid-character), so a single very long line still comes back bounded. bytesCapped is true whenever the cap cut anything, and endLine is the last line included, possibly partially.
  • truncated is true when anything after content was withheld — later lines (by limit, the default window or the cap) or the tail of endLine.
  • hash is always the SHA-256 of the whole file, not the window, so it is a valid expectHash whatever was returned. totalBytes is the whole file’s size.
  • No maxBytes ⇒ no byte cap (only the line window applies).
  • maxBytes bounds what a read returns, not what it loads: the whole file is still read into memory and hashed, because hash covers the whole file. Keep very large files out of the jail with denyPaths if memory matters.
const ws = ai.workspace({ cwd, read: { maxBytes: 64_000, defaultLines: 400 } });
const page = await ws.readFile("dist/bundle.js");
if (page.bytesCapped) console.warn(`Only part of line ${page.endLine} fit in the read budget.`);

exec() accepts a per-call signal; run_shell and run_tests pass the agent run’s signal (the dispatch ctx.signal) automatically, so cancelling the agent run stops the command it is waiting on.

  • Already aborted ⇒ the command is not started (exitCode: 130).
  • Aborted mid-run ⇒ the whole process tree is SIGKILLed, as on a timeout.
  • Either way the result says cancelled: true — it resolves, it doesn’t throw — and cancelled and timedOut are never both true. Branch on those flags, not on the exit code.
  • The signal belongs to that one call; the workspace never stores it, so one workspace can serve many runs. The abort listener is removed once the command settles.
const controller = new AbortController();
const pending = ws.exec("npm test", { signal: controller.signal, timeoutMs: 120_000 });
controller.abort();
const { cancelled } = await pending; // true

A custom WorkspaceBackend receives the signal as exec(command, { signal }) and should follow the same rules, reporting cancelled: true in its result.

readFile returns a SHA-256 hash of the full file. Pass it to editFile’s expectHash; if the file changed since you read it, the edit is rejected as stale so you re-read before clobbering. editFile also requires the oldString to be found uniquely (see “Finding the text to edit”) — pass replaceAll: true to replace every occurrence, or include more surrounding context to disambiguate.

Writes, edits and removes of the same path run one after another, even when the agent dispatches several tool calls at once. Two edit_file calls pinned to the same expectHash therefore cannot both succeed: the second re-reads after the first has written and is rejected as stale, instead of silently overwriting it. Without expectHash, the second edit applies on top of the first. Different paths are not held up.

Finding the text to edit — edit.matching

Section titled “Finding the text to edit — edit.matching”

By default an edit looks for oldString in tiers and uses the first tier that finds it: the exact text, then the text with line endings normalised (an LF oldString finds CRLF lines), then with look-alike punctuation folded (curly quotes, en/em dashes and non-breaking spaces match their plain forms), then line by line ignoring trailing whitespace. A result found by one of the last two tiers reports matchTier: "unicode" or "whitespace"; an exact find leaves it out. A loose find must be unique: with two candidates the edit fails with not-unique and writes nothing, even with replaceAll. Replacement text takes the file’s dominant line ending, so a CRLF file stays CRLF.

ai.workspace({
cwd,
edit: { matching: "tiered", missHintLines: 12, lineEndings: "preserve" },
});
  • matching: "exact" accepts only the text byte for byte.
  • lineEndings: "lf" | "crlf" forces the ending of replacement text.
  • When the text is not found, the WorkspaceEditError (type: "not-found") carries a hint: the closest file text (at most missHintLines lines, 12 by default, each at most 200 characters; 0 turns it off, and it never exceeds read.maxBytes) or a note that newString is already present. A file the jail refuses never gets a hint.

Diagnostics after an edit — hooks.afterEdit

Section titled “Diagnostics after an edit — hooks.afterEdit”
ai.workspace({
cwd,
hooks: {
afterEdit: async ({ paths, tool }) => await typecheck(paths), // returns text or nothing
afterEditMaxChars: 4_000,
afterEditTimeoutMs: 10_000,
},
});

After write_file, edit_file, multi_edit or apply_patch writes files, the hook runs once per call with the written paths (not on a patch dryRun, not for deleted files). Text it returns comes back on the result as diagnostics, between [diagnostics] and [/diagnostics] lines; output over afterEditMaxChars is cut with a marker. A hook that throws or does not answer within afterEditTimeoutMs yields diagnostics unavailable and never fails the edit.

ai.workspace({
cwd,
output: {
spillDir: ".warlock/spill",
maxLines: 2_000,
maxBytes: 51_200,
retentionMs: 604_800_000,
},
});

With output.spillDir set, output too large to return whole (run_shell, shell_output, grep, glob, and read_file when read.maxBytes cut the window) is saved in full to spill-<time>-<random>-<label>.txt there. The result keeps the start and end (keep: "head+tail", the default for shell output; "head" for the rest, or set keep yourself) and carries a marker such as [showing lines 1-25 and 99976-100000 of 100000; full output saved to FILE]. Every result that spilled also carries a flat spilledTo: string[] (absolute paths; run_shell and shell_output list one per spilled stream), and the text the model sees ends with a line naming the file. The boolean truncated stays; truncation adds { shown: { lines }, total: { lines, bytes }, path? } (per stream, truncation.stdout / truncation.stderr, for commands). read_file may open the spill directory even when it is outside the jail, so the model can page through the file with startLine / limit; nothing else outside the jail opens, and writes never reach it. Files older than retentionMs (7 days by default) are removed when a workspace is created, when a new file is written and on dispose(); retentionMs: 0 removes the files this workspace wrote on dispose(). Only files named like spill files are ever removed. Without spillDir, output is cut at shell.maxOutputBytes / read.maxBytes as before, and run_shell results still report the sizes in truncation.

Policy and edit failures are typed errors extending the @warlock.js/ai AIError base. Inside a tool the tool() wrapper catches them and surfaces them in { error }, so the agent reads the failure and self-corrects. A failing test isn’t an error at all — it’s a normal result with exitCode !== 0, so the model reads the failure on the next trip. Branch on .type:

import { WorkspacePolicyError, WorkspaceEditError } from "@warlock.js/ai-workspace";
try {
await ws.exec("rm -rf /");
} catch (error) {
if (error instanceof WorkspacePolicyError && error.type === "denied-command") {
console.warn(`Blocked: ${error.command}`);
}
}
  • WorkspacePolicyError.type: "path-escape" (jail escape / deny glob) | "denied-command" (the shell policy refused the line — see reason in Refusal reasons) | "unsafe-pattern" (grep pattern too long or nested-quantifier ReDoS shape).
  • WorkspaceEditError.type: "not-found" | "not-unique" | "stale-hash" | "patch-invalid" | "hunk-failed" | "binary-file" | "file-exists" | "file-missing"; a multiEdit failure also sets editIndex, and an applyPatch hunk failure sets hunkIndex.
  • WorkspaceJobError.type: "not-found" (no background command with that id).
const ro = ws.readonly(); // vends only read/grep/glob; mutating direct methods reject
const api = ws.scope("packages/api"); // a sub-jailed workspace rooted at the subdir

readonly() is the least-privilege reviewer projection — tools.all() on it returns read_file, list_dir, grep, glob and the todo tools only, and writeFile / editFile / multiEdit / applyPatch / exec / startShell / shellKill / mkdir / remove throw a WorkspacePolicyError. Projections share the workspace’s background commands and todo list; dispose() on any of them disposes the whole workspace. scope(subdir) narrows cwd to join(cwd, subdir) (same sub-policies, same backend), so a per-package agent gets a tighter blast radius:

const apiDev = ai.agent({ model, tools: ws.scope("packages/api").tools.all() });
const webDev = ai.agent({ model, tools: ws.scope("packages/web").tools.all() });

One workspace is one jail and one tree. Pass it to several members of a supervisor, varying only the tool slice each gets — they all read/write the same files:

const ws = ai.workspace({ cwd, shell: { allow: ["npm", "node"], inheritEnv: ["PATH"] } });
ai.supervisor({
members: [
ai.agent({ /* executor */ model, tools: ws.tools.all() }),
ai.agent({ /* reviewer */ model, tools: ws.readonly().tools.all() }),
ai.agent({ /* tester */ model, tools: ws.tools.pick("readFile", "runTests") }),
],
});

backend: "mock" swaps the local disk for an in-memory Map + scripted exec — same policy, same tool/method surface, no filesystem:

const ws = ai.workspace({ cwd: "/srv/app", backend: "mock", shell: { allow: ["npm"] } });
// Seed files / scripted commands via createMockBackend when constructing a backend directly.

A scripted command with running: true (createMockBackend({ commands: { "npm run dev": { stdout: "ready\n", running: true } } })) stays “running” as a background command until it is killed.

  • Use AI tools — the network/utility tool belt (web search, fetch, HTTP, calculator, date-time).
  • Connect MCP — ai.mcp.serve({ tools: () => ws.tools.all() }, ...) publishes a workspace AS an MCP server.
  • Run supervisor — coordinating the members that share one workspace.
  • Run agent — the agent loop, maxTrips, and the run report.