Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
56 commits
Select commit Hold shift + click to select a range
aa978d6
Scaffold, core contracts and run pipeline
mths-mcfs Nov 15, 2026
b230183
Fix four seam defects found in adversarial review
mths-mcfs Nov 15, 2026
c7a6e20
Tools runtime: jail, tolerant edit, transactional rollback, contained…
mths-mcfs Nov 15, 2026
8e8a3f0
Match protected patterns written through an alias of the workspace
mths-mcfs Nov 15, 2026
7c10018
Add the QuickJS-ng WASM sandbox
mths-mcfs Nov 15, 2026
204b823
Expect forward slashes in changedFiles on every platform
mths-mcfs Nov 15, 2026
131c8a2
Fix the sandbox on macOS and Windows
mths-mcfs Nov 15, 2026
9cd2af7
Add reproducible benchmark harness: native vs agent-code-mode
mths-mcfs Nov 15, 2026
35be942
Codex host adapter: exec policy rules, hooks, session context
mths-mcfs Nov 15, 2026
6ba5f52
Claude Code host adapter: permissions, hooks, session context
mths-mcfs Nov 15, 2026
c84b94e
Read node --test counts from both spec and TAP output
mths-mcfs Nov 15, 2026
d0c97b1
Resolve sandbox roots against the project drive in the Windows test
mths-mcfs Nov 15, 2026
20318a5
Close races and path gaps found by the correctness review
mths-mcfs Nov 15, 2026
0b0d85a
Bound reply buffering, fail closed without a permission model, honor …
mths-mcfs Nov 15, 2026
9a1789d
Let the kernel decide whether an oracle path resolves
mths-mcfs Nov 15, 2026
81756db
Ignore the probe's connection reset in the permission-model test
mths-mcfs Nov 15, 2026
1cd0a25
Merge remote-tracking branch 'origin/feat/scaffold' into feat/tools
mths-mcfs Nov 15, 2026
28f276b
Key prepare metadata by content, not by object identity
mths-mcfs Nov 15, 2026
ff6d7e0
Codex adapter: fix matcher, plain-script, wrapper, patch and output d…
mths-mcfs Nov 15, 2026
d869b10
Fix rule bypasses, auto mode, file checks, hook dedup and context claim
mths-mcfs Nov 15, 2026
7a45b85
Fix bench review findings: credential isolation, sanitizer, strict ar…
mths-mcfs Nov 15, 2026
3232f19
Claim context records with an exclusive claim file
mths-mcfs Nov 15, 2026
c10d5f6
Refuse malformed permission rules instead of ignoring them
mths-mcfs Nov 16, 2026
0d930c0
Merge remote-tracking branch 'origin/feat/sandbox' into feat/integration
mths-mcfs Nov 16, 2026
8ff406d
Merge remote-tracking branch 'origin/feat/host-claude' into feat/inte…
mths-mcfs Nov 16, 2026
ed2b0c0
Merge remote-tracking branch 'origin/feat/host-codex' into feat/integ…
mths-mcfs Nov 16, 2026
00bc33e
Merge remote-tracking branch 'origin/feat/bench' into feat/integration
mths-mcfs Nov 16, 2026
da66562
Support the documented tool-name globs in permission rules
mths-mcfs Nov 16, 2026
8350cee
Make Codex token refresh safe and close two verifier holes
mths-mcfs Nov 16, 2026
0de5930
Integrate contracts: readFilter, additionalRoots, edit rung names, re…
mths-mcfs Nov 16, 2026
b0b219a
Add the attack suite through run, install and runtime tests; fix shel…
mths-mcfs Nov 16, 2026
d624646
Add real-host e2e scripts, run log, README and module map
mths-mcfs Nov 16, 2026
36555ca
Merge remote-tracking branch 'origin/feat/host-claude' into feat/inte…
mths-mcfs Nov 16, 2026
da4e85e
Merge remote-tracking branch 'origin/feat/bench' into feat/integration
mths-mcfs Nov 16, 2026
8e2b9ed
Use native real paths in tests and show sandboxed bash stderr on failure
mths-mcfs Nov 16, 2026
01de9d4
Relax the cancellation test for slow runners; lift the AppArmor user-…
mths-mcfs Nov 16, 2026
503d9eb
CI: unload Ubuntu's bwrap user-namespace AppArmor profile so containm…
mths-mcfs Nov 16, 2026
8863168
Fix bench smoke-run findings: Claude B tools, isolation, T8, Codex C …
mths-mcfs Nov 16, 2026
42e2fbd
Fix tool-surface check marking every observed Codex run invalid
mths-mcfs Nov 16, 2026
7bc5608
Give every arm of a host the same non-file tool surface
mths-mcfs Nov 16, 2026
56e17b6
Merge ci-speed/scaffold into ci-speed/bench
mths-mcfs Nov 19, 2026
2dec002
CI: run once per push and cancel superseded PR runs
mths-mcfs Nov 19, 2026
c9bc319
Bench tests: run verifier cases concurrently and split the dry runs
mths-mcfs Nov 19, 2026
dd3be47
Bench tests: limit the verifier cases to two at a time everywhere
mths-mcfs Nov 19, 2026
404e4e1
Bench tests: give every verifier case 120 s from the start of the stack
mths-mcfs Nov 19, 2026
dc220f9
Bench tests: split the verifier and dry-run files instead of running …
mths-mcfs Nov 19, 2026
f0dff35
Bench tests: give the end-to-end dry runs 300 s
mths-mcfs Nov 19, 2026
d1b9d96
Make the cancellation test wait on a completed file instead of an ent…
mths-mcfs Nov 16, 2026
535304b
fix(review): round 1
mths-mcfs Nov 19, 2026
3cba6ae
fix(review): round 2
mths-mcfs Nov 19, 2026
9824d9d
Refuse UNC workspace roots and bound edit preparation in the memory r…
mths-mcfs Nov 19, 2026
c61bedd
Refuse UNC session roots under a fixed root and count diff rows exactly
mths-mcfs Nov 19, 2026
7396009
fix(review): round 1
mths-mcfs Nov 19, 2026
fc6026b
fix(review): round 2
mths-mcfs Nov 19, 2026
725cab7
Merge origin/feat/scaffold into feat/bench
mths-mcfs Nov 19, 2026
86e2503
Merge main (squashed #1) into feat/bench
mths-mcfs Nov 19, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,17 @@ jobs:
with:
node-version: ${{ matrix.node }}
cache: npm
- name: Install bash containment tools (Linux)
if: runner.os == 'Linux'
run: |
sudo apt-get update && sudo apt-get install -y bubblewrap socat ripgrep
# Ubuntu 24.04 restricts unprivileged user namespaces, which bubblewrap needs.
sudo sysctl -w kernel.apparmor_restrict_unprivileged_userns=0 || true
sudo sysctl -w kernel.apparmor_restrict_unprivileged_unconfined=0 || true
# Its bwrap profile also forbids the nested user namespace the sandbox's seccomp helper needs.
if [ -f /etc/apparmor.d/bwrap-userns-restrict ]; then sudo apparmor_parser -R /etc/apparmor.d/bwrap-userns-restrict || true; fi
bwrap --ro-bind / / --dev /dev --proc /proc --unshare-user --unshare-net bwrap --ro-bind / / --dev /dev --unshare-user true && echo "nested bubblewrap works" || echo "nested bubblewrap fails"
echo "ACM_REQUIRE_CONTAINMENT=1" >> "$GITHUB_ENV"
- run: npm ci
- run: npm run verify

Expand Down
7 changes: 5 additions & 2 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,14 @@ Every binding call is prepared, authorized against the host's permission rules a

## Module map

- `src/core`: frozen contracts (`types.ts`), boundary schemas, dispatcher (prepare, authorize, commit), run orchestration, output shaping, command hooks.
- `src/server`: MCP stdio server, host detection, runtime factory.
- `src/core`: contracts (`types.ts`), boundary schemas, dispatcher (prepare, authorize, commit), run orchestration, output shaping, command hooks.
- `src/server`: MCP stdio server, host detection, runtime factory (real sandbox, tools and host adapters), the generic read-only policy.
- `src/cli.ts`, `src/install.ts`: `serve`, `hook` (Claude companion hook) and `install`.
- `src/sandbox`: QuickJS-ng WASM sandbox in a child process.
- `src/hosts/claude`: Claude Code host adapter (settings, permission rules, hooks).
- `src/hosts/codex`: Codex CLI host adapter (config, exec policy, hooks).
- `src/tools`: tool runtime (`bash`, `read`, `write`, `edit`, `grep`, `glob`), journal and rollback.
- `src/testing`: fakes for tests (sandbox, host adapter, in-memory tool runtime).
- `test/attack`: attack suite through `run` with the real sandbox, tools and adapters (part of `npm test`).
- `test/e2e`: real-host end-to-end scripts (need a logged-in `claude`/`codex`; not in CI).
- `bench`: benchmark.
7 changes: 5 additions & 2 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,14 @@ Every binding call is prepared, authorized against the host's permission rules a

## Module map

- `src/core`: frozen contracts (`types.ts`), boundary schemas, dispatcher (prepare, authorize, commit), run orchestration, output shaping, command hooks.
- `src/server`: MCP stdio server, host detection, runtime factory.
- `src/core`: contracts (`types.ts`), boundary schemas, dispatcher (prepare, authorize, commit), run orchestration, output shaping, command hooks.
- `src/server`: MCP stdio server, host detection, runtime factory (real sandbox, tools and host adapters), the generic read-only policy.
- `src/cli.ts`, `src/install.ts`: `serve`, `hook` (Claude companion hook) and `install`.
- `src/sandbox`: QuickJS-ng WASM sandbox in a child process.
- `src/hosts/claude`: Claude Code host adapter (settings, permission rules, hooks).
- `src/hosts/codex`: Codex CLI host adapter (config, exec policy, hooks).
- `src/tools`: tool runtime (`bash`, `read`, `write`, `edit`, `grep`, `glob`), journal and rollback.
- `src/testing`: fakes for tests (sandbox, host adapter, in-memory tool runtime).
- `test/attack`: attack suite through `run` with the real sandbox, tools and adapters (part of `npm test`).
- `test/e2e`: real-host end-to-end scripts (need a logged-in `claude`/`codex`; not in CI).
- `bench`: benchmark.
17 changes: 17 additions & 0 deletions NOTICE
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,20 @@ Third-party code
----------------
Portions of this product that are derived from third-party projects are
listed below together with their copyright notices and licenses.

Turnpack
Files: src/tools/edit-match.ts, src/tools/edit-match.test.ts (ported),
src/tools/journal.ts and src/tools/jail.ts (design and parts adapted)
Source: https://github.com/OnlyTerp/turnpack (commit b14330d)
License: Apache License, Version 2.0
Modified by the agent-code-mode authors (see the header of each file).
Turnpack's NOTICE:

Turnpack
Copyright 2026 OnlyTerp (https://github.com/OnlyTerp)

This product is licensed under the Apache License, Version 2.0.
You may obtain a copy of the License in the LICENSE file, or at
http://www.apache.org/licenses/LICENSE-2.0

Project home: https://github.com/OnlyTerp/turnpack
137 changes: 135 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,137 @@
# agent-code-mode
A generic Code Mode for coding agents: the model writes one sandboxed script that makes many tool calls, with your existing hooks still enforced. Works with Claude Code and Codex.

Status: under construction.
A generic Code Mode for coding agents. The model writes one JavaScript script that makes many tool calls (`bash`, `read`, `write`, `edit`, `grep`, `glob`) in a single step. Every call inside the script still goes through your host's permission rules and PreToolUse hooks.
It is an MCP stdio server with one tool, `run`, and works in Claude Code (interactive CLI, `claude -p`, Claude Agent SDK) and in OpenAI Codex CLI.

## Install

Requires Node.js 22 or later. `install` prints the configuration; `--write` applies it after showing the diff.

### Claude Code

```sh
npx -y agent-code-mode install --host claude # user scope (default)
npx -y agent-code-mode install --host claude --scope project
```

User scope prints the registration command and the companion hook for `~/.claude/settings.json`:

```sh
claude mcp add --scope user agent-code-mode -- npx -y agent-code-mode serve --host claude
```

```json
{
"hooks": {
"PreToolUse": [
{ "matcher": "mcp__agent-code-mode__run", "hooks": [{ "type": "command", "command": "npx -y agent-code-mode hook" }] }
]
}
}
```

Project scope writes the same server entry to `.mcp.json` and the hook to `.claude/settings.json`. The companion hook prints nothing and never decides anything: it hands the server the live permission mode, cwd and subagent of each `run` call, which Claude Code does not send to MCP servers.

In `claude -p` and the Agent SDK, allow the tool as usual (`--allowedTools mcp__agent-code-mode__run`).

### Codex CLI

```sh
npx -y agent-code-mode install --host codex # ~/.codex/config.toml (or $CODEX_HOME); --scope project for .codex/config.toml
```

```toml
[mcp_servers.agent-code-mode]
command = "npx"
args = ["-y", "agent-code-mode", "serve", "--host", "codex"]
tool_timeout_sec = 300

[mcp_servers.agent-code-mode.tools.run]
approval_mode = "approve"
```

`run` changes files, so it does not claim `readOnlyHint`. Under `approval_policy = "never"` (including `codex exec`) Codex only calls it with the per-tool approval above. That approval only lets `run` start: every call inside it is checked against your exec-policy rules, sandbox mode and hooks.

## Usage

The script is the body of an async function. All bindings are async globals; `return` a value to get it back.

```js
const hits = await grep({ pattern: 'TODO', glob: '*.ts' });
for (const file of [...new Set(hits.matches.map((m) => m.file))]) {
await edit({ path: file, oldString: 'TODO', newString: 'DONE', replaceAll: true });
}
const test = await bash({ command: 'npm test --silent' });
return { files: hits.matches.length, exitCode: test.exitCode };
```

| Binding | Returns |
| --- | --- |
| `bash({command, cwd?, timeoutMs?})` | `{exitCode, signal, stdout, stderr, truncated, timedOut}` |
| `read({path, offset?, limit?})` | `{path, content, startLine, totalLines, truncated}` |
| `write({path, content})` | `{path, created, diff}` |
| `edit({path, oldString, newString, replaceAll?})` | `{path, replacements, matchStrategy, diff}` |
| `grep({pattern, path?, glob?, ignoreCase?, maxResults?})` | `{matches: [{file, line, text}], truncated, filtered}` |
| `glob({pattern, path?, maxResults?})` | `{files, truncated, filtered}` |

`console.log/info/warn/error` go to `logs`. A denied call rejects with an `Error` named `PermissionDenied` (with `source` and `reason`); other failures reject with `ToolError` (with `code`). `run` takes `{code, transaction?, timeoutMs?}`. With `transaction: true`, file changes are rolled back if the script throws, times out, is cancelled or any call is denied. The result holds the return value, logs, a call log, the changed files and a combined diff.

Edits that do not match exactly fall back through tolerant rungs (line endings, copied line numbers, trailing whitespace, indentation, typographic punctuation). `matchStrategy` says which rung matched.

## Security model and limits

The script runs in a QuickJS-ng WebAssembly VM inside a child Node process. The VM has no `require`, `process`, `fetch`, timers, filesystem, network or environment. Its only way out is the six bindings. Each binding call goes back to the server, which:

1. **prepares** the exact effect (real paths inside the workspace, the diff of a write, the command and cwd of `bash`) with no side effect;
2. **authorizes** it as the native tool: `Bash`, `Read`, `Write`, `Edit`, `Grep`, `Glob` in Claude Code; shell commands and `apply_patch` in Codex. Your permission rules (deny → ask → allow) apply, then your PreToolUse hooks run with the input the native tool would send. A hook rewrite (`updatedInput`) is re-validated, re-prepared and re-checked against the rules;
3. **commits** exactly what was authorized, re-checking that the file did not change in between.

Semantics:

- **Fail-closed.** A hook that crashes, times out, exits with an unexpected code or prints invalid output denies the call. So does a configuration the server cannot understand: a malformed rule, an unknown hook type or an unreadable settings file denies every call.
- **`ask` is denied.** The server has no way to prompt you. When the host would ask, the call is refused with source `ask-unavailable`. Allow what the script needs with your usual rules or permission mode.
- **Auto mode (Claude).** Claude's classifier reviews the whole `run` call once. Deny and ask rules still apply to every inner call. If an allow rule approves `run` itself, the classifier never saw the script, so inner calls no rule decides follow auto mode's fallback: reads and edits inside the working directories pass, everything else asks.
- **Paths.** Calls are confined to the session cwd, the client's roots and the host's additional directories. Symlinks leading out are refused. Host policy files (`.claude/settings*.json`, `.claude/hooks/`, `.mcp.json`, `.codex/`, `~/.claude/`, `$CODEX_HOME`, the server state dir) cannot be written. `grep` and `glob` drop files your Read rules deny and count them in `filtered`.
- **`bash` containment** mirrors the host. When Claude's sandbox is enabled, or Codex runs `read-only`/`workspace-write`, commands run in an OS sandbox (bubblewrap on Linux, Seatbelt on macOS) with the host's writable roots. If that cannot be enforced, the call is refused, never run unconfined.
- **Rollback covers files only.** Effects of `bash` (processes, network, files a command wrote) are never undone; the result warns when a rolled-back run had committed `bash` calls.
- **Network on Node 22/24.** Node's permission model blocks sockets in the sandbox child only from Node 25. On Node 22 and 24, network isolation of scripts rests on the QuickJS VM exposing no network API.
- **Windows.** `bash` needs Git Bash and is otherwise refused; OS containment is not available there.
- **Unknown clients.** When neither Claude Code nor Codex is detected and no `--host` is given, only `read`, `grep` and `glob` inside the workspace are allowed; every other call is denied with the reason.

What the server cannot see, so it cannot apply:

- CLI flags other than those it parses from the parent process (`--settings`, `--permission-mode`, `--allowedTools`, `--disallowedTools`, `--setting-sources`, `--add-dir` for Claude; `-c`, `--profile`, `-s`, `-a` for Codex), and anything passed over the Agent SDK control channel;
- managed policies delivered by MDM or the Windows registry;
- Agent SDK `canUseTool` callbacks;
- Claude skill and agent frontmatter hooks, and `prompt`/`agent`/`mcp_tool` hook types (refused, not ignored).

Output is capped below the hosts' MCP limits (about 30,000 characters, less for errors). A larger result is written to a file in the state directory and its path is returned.

## Compared with the built-in code modes

- **Claude Code's official Code Mode** applies the same per-call rules and hooks, but only in interactive sessions. agent-code-mode also works in `claude -p`, the Agent SDK and Codex, and every call shows up in a call log you get back.
- **Codex's own code mode.** Codex 0.169 models already run in Codex's code mode by default (its `exec` tool calls nested tools). agent-code-mode gives Codex the same binding surface as Claude, with transactions, the call log and your hooks applied to file reads and edits made inside the script.

## Benchmark

`bench/` compares native tools, the host's own code mode and agent-code-mode on the same tasks, on both hosts. It uses your logged-in `claude` and `codex` and costs real tokens.

```sh
npm run bench -- --dry-run # no model calls
npm run bench -- --host claude --arms A,C --tasks T1,T5 --runs 3
```

Results pending.

## Development

```sh
npm ci
npm run verify # typecheck, tests (including test/attack), build
test/e2e/claude.sh <dir> # real claude -p run with the example deny-rm hook (needs login)
test/e2e/codex.sh <dir> # real codex exec run with the same hook (needs login)
```

## License

Apache-2.0. See [LICENSE](LICENSE) and [NOTICE](NOTICE), which lists the third-party code this project adapts.
1 change: 1 addition & 0 deletions bench/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
.work/
Loading
Loading