Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
18 commits
Select commit Hold shift + click to select a range
fe45eaf
Compact run results, exact read() text, relative result paths
mths-mcfs Nov 16, 2026
3f0c1db
Fix compact run results; add readOverflow, grep rows, plain-text resu…
mths-mcfs Nov 16, 2026
ab93007
Benchmark: paired runs, equal warm-up, baseline build arm, pass^k and…
mths-mcfs Nov 16, 2026
2ccb7bd
Expand relative globs for pure readers; close brace, tilde and multi-…
mths-mcfs Nov 16, 2026
3454a9d
Fix CI: take glob order from the bash that runs the command; portable…
mths-mcfs Nov 16, 2026
b108b5b
Close tilde bypasses; never hide denied or failed calls under the out…
mths-mcfs Nov 16, 2026
78bfd02
Expand globs in an allowlisted environment; case-insensitive-safe exp…
mths-mcfs Nov 16, 2026
b9f9c0f
Glob expansion: follow the bash version, stay inside the jail, skip w…
mths-mcfs Nov 16, 2026
0e8089d
Bench: T13-T15 and a hybrid Claude arm; serve --hybrid, the default i…
mths-mcfs Nov 17, 2026
b8ee1a6
Keep bench fixtures and shell scripts LF on every OS; give the hidden…
mths-mcfs Nov 17, 2026
40e37e2
Bench verifier tests: one 120 s timeout for the whole file
mths-mcfs Nov 17, 2026
4443ac8
Merge ci-speed/integration into ci-speed/economia
mths-mcfs Nov 19, 2026
4b878d0
Merge ci-speed/integration into ci-speed/economia
mths-mcfs Nov 19, 2026
4d89b1b
Merge ci-speed/integration into ci-speed/economia
mths-mcfs Nov 19, 2026
344657e
Merge ci-speed/integration into ci-speed/economia
mths-mcfs Nov 19, 2026
79f8441
Bench tests: split the T15 hidden-test cases in three files
mths-mcfs Nov 19, 2026
e512769
Merge ci-speed/integration into ci-speed/economia
mths-mcfs Nov 19, 2026
f10163a
Bench tests: give the end-to-end baseline and isolation runs 300 s
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
6 changes: 6 additions & 0 deletions .gitattributes
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
# Bench task fixtures and recorded parser inputs are read byte for byte (hidden tests compare trap files
# exactly, the verifier tests edit exact snippets): keep them LF on every OS, whatever core.autocrlf says.
bench/tasks/** text eol=lf
bench/parser-fixtures/** text eol=lf
# Shell scripts (test hook fixtures, e2e scripts) run under bash, which rejects CRLF.
*.sh text eol=lf
16 changes: 10 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,11 @@ 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
claude mcp add --scope user agent-code-mode -- npx -y agent-code-mode serve --host claude --hybrid
```

Install uses `--hybrid` by default because Claude Code keeps its native file and shell tools enabled next to `run`: the tool description then says when to batch calls with `run` and when a native tool is enough. Drop `--hybrid` only if you turn the native tools off and the model works through `run` alone.

```json
{
"hooks": {
Expand Down Expand Up @@ -58,11 +60,11 @@ The script is the body of an async function. All bindings are async globals; `re

```js
const hits = await grep({ pattern: 'TODO', glob: '*.ts' });
for (const file of [...new Set(hits.matches.map((m) => m.file))]) {
for (const file of [...new Set(hits.rows.map(([file]) => 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 };
return { matches: hits.count, exitCode: test.exitCode };
```

| Binding | Returns |
Expand All @@ -71,10 +73,11 @@ return { files: hits.matches.length, exitCode: test.exitCode };
| `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}` |
| `grep({pattern, path?, glob?, ignoreCase?, maxResults?})` | `{columns: ['file', 'line', 'text'], rows: [[file, line, text]], count, truncated, filtered}` |
| `glob({pattern, path?, maxResults?})` | `{files, truncated, filtered}` |
| `readOverflow(id, offset?, limit?)` | `{text, offset, totalChars, truncated}`: a slice of a result a response cut |

`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; if the server process dies mid-run, the next start restores them from its journal (inside the roots of that run only). The result holds the return value, logs, a call log, the changed files and a combined diff.
`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`). `read` returns the exact text of the lines, final newline included, and paths in results are relative to the working directory when inside it. `run` takes `{code, transaction?, timeoutMs?, verbose?}`. With `transaction: true`, file changes are rolled back if the script throws, times out, is cancelled or any call is denied; if the server process dies mid-run, the next start restores them from its journal (inside the roots of that run only). The response is a JSON block: `{ok, result | error, logs, calls: {total, byTool, denied, errors}, changedFiles, diff | diffStat, warnings}`, with empty fields left out. Every denied and failed call is listed with its reason, and every changed file is listed. A multi-line string result longer than 200 characters comes as plain text in a second block instead of an escaped JSON string. A diff above 1,500 characters becomes `diffStat` (lines added and removed for up to 10 files, plus the totals). A response stays under about 10,000 tokens (40,000 characters; 9,500 for an error): above that, the result and the logs keep their start and end, long lists keep their first entries, each cut is marked and `truncated: true` is set. Denied and failed calls are never cut by entry: when they do not fit whole, they are grouped by tool and reason as `{tool, reason, count, first}` (`first` is the summary of the first call), so every distinct reason shows with its exact count. Only with thousands of distinct reasons is each reason cut to 200 characters and, if that is still too much, the last groups replaced by a `…[N more reasons (M calls)]` marker. With `verbose: true`, a call log above the cap keeps its first entries and the compact calls come beside it as `callSummary`. Whenever something is left out, the whole result is kept in the server's memory for 30 minutes and the response carries `overflow: {id, chars}`; a later script reads it with `readOverflow(id)`. The id is random, works only in the same server process and nothing is written to disk. `verbose: true` returns the log of every call and the whole 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.

Expand All @@ -92,6 +95,7 @@ Semantics:
- **`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`.
- **Globs in `bash` (Claude).** A relative glob read by `cat`, `head`, `tail`, `wc` or `ls` (with options from a fixed list, no `ls -R`, no redirection, no `..`, `~`, `$VAR`, `$(...)` or backticks) is expanded before authorization, and the command names each match literally, single-quoted after `--`: `wc -l src/*` becomes `wc -l -- 'src/a.js' 'src/b.js'`. Rules, hooks and the result (`command`) see that command. The matches and their order come from the same bash, in the same environment and locale, with startup files (`BASH_ENV`) left out so expanding runs no code; on Windows (Git Bash) globs are not expanded. Each match must resolve inside the workspace and be a regular file (or a directory for `ls`, whose listed children must pass your Read rules); otherwise the call fails. A glob that matches nothing, or any other command, stays as written. Right before the command starts, every match is checked again (device, inode and type, of the link and of what it points to); if one changed, nothing runs. What remains is the moment between that check and the reader opening the file, a few milliseconds in which a process that can write the workspace could swap a file. Native Claude Code checks a command's paths and then runs it with no second check at all, so that window is larger there.
- **`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.
- **Overlapping transactions.** Within one server, a transactional run may not write a file that another unfinished transactional run already changed: that write fails, so both runs can still roll back to the true original.
- **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.
Expand All @@ -110,7 +114,7 @@ Output is capped below the hosts' MCP limits (about 30,000 characters, less for

## 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.
- **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 denied or failed call shows up in the result you get back (every call with `verbose: true`).
- **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
Expand Down
2 changes: 2 additions & 0 deletions bench/.gitignore
Original file line number Diff line number Diff line change
@@ -1 +1,3 @@
# Old default work dir (now <os tmpdir>/acm-bench, outside the checkout). The runner refuses a
# --work-dir inside the repo; this line only keeps leftovers of older runs out of git.
.work/
47 changes: 28 additions & 19 deletions bench/lib/claude.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import { z } from 'zod';
import type { ArmId, ParsedRun, ToolCalls } from './record.ts';
import { runInnerCalls } from './run-result.ts';

/** Native file and shell tools of Claude Code. Using one of them in the agent-code-mode arm is a fallback. */
/** Native file and shell tools of Claude Code. Using one of them in the strict agent-code-mode arm is a fallback. */
export const CLAUDE_NATIVE_TOOLS = ['Bash', 'Read', 'Write', 'Edit', 'MultiEdit', 'Glob', 'Grep', 'NotebookEdit'];
export const CLAUDE_RUN_TOOL = 'mcp__agent-code-mode__run';
/** Native tool names allowed by rule in both arms (in arm B they only reach the model through `run`). */
/** Native tool names allowed by rule in every arm (in arm B they only reach the model through `run`). */
export const CLAUDE_INNER_ALLOWED = ['Bash', 'Read', 'Write', 'Edit', 'Glob', 'Grep'];
/** Agents Claude Code 2.1.325 ships; anything else in the init event came from the user's config. */
export const CLAUDE_BUILTIN_AGENTS = ['claude', 'Explore', 'general-purpose', 'Plan', 'statusline-setup'];
Expand Down Expand Up @@ -39,17 +40,23 @@ export function claudeArgs(o: ClaudeCommandOptions): string[] {
// Arm A: the native tools, allowed by rule. Arm B: no built-in tools at all (`--tools ""` removes them
// without denying them: a CLI deny rule would also deny the same tool inside agent-code-mode, by
// parity), and the same native names allowed by rule so the inner calls are allowed exactly as in A.
// Both arms see no other built-in tool (no Task, ToolSearch, web...), so they differ only in native
// Arm C (hybrid): the native tools of A and `run`, all allowed by rule; the model picks per call.
// No arm sees any other built-in tool (no Task, ToolSearch, web...), so they differ only in native
// file/shell tools vs `run`.
if (o.arm === 'A') args.push('--tools', CLAUDE_INNER_ALLOWED.join(','), '--allowedTools', CLAUDE_INNER_ALLOWED.join(','));
else args.push('--tools', '', '--allowedTools', [CLAUDE_RUN_TOOL, ...CLAUDE_INNER_ALLOWED].join(','));
else if (o.arm === 'B') args.push('--tools', '', '--allowedTools', [CLAUDE_RUN_TOOL, ...CLAUDE_INNER_ALLOWED].join(','));
else args.push('--tools', CLAUDE_INNER_ALLOWED.join(','), '--allowedTools', [CLAUDE_RUN_TOOL, ...CLAUDE_INNER_ALLOWED].join(','));
return args;
}

/** The `--mcp-config` content for an arm: no servers for A, the agent-code-mode server for B. */
/**
* The `--mcp-config` content for an arm: no servers for A, the agent-code-mode server for B and, started
* with `--hybrid` (the `run` description then says when to batch and when to use a native tool), for C.
*/
export function claudeMcpConfig(arm: ArmId, serverEntry: string): unknown {
if (arm === 'A') return { mcpServers: {} };
return { mcpServers: { 'agent-code-mode': { type: 'stdio', command: process.execPath, args: [serverEntry, 'serve', '--host', 'claude'] } } };
const args = [serverEntry, 'serve', '--host', 'claude', ...(arm === 'C' ? ['--hybrid'] : [])];
return { mcpServers: { 'agent-code-mode': { type: 'stdio', command: process.execPath, args } } };
}

const UsageEvent = z.object({
Expand Down Expand Up @@ -78,6 +85,8 @@ const ToolResult = z.object({ type: z.literal('tool_result'), tool_use_id: z.str
/** Error text of a blocked call (hook deny, permission rule), as opposed to an ordinary tool failure. */
export const DENIAL_TEXT = /denied|blocked|hook|protected|not allowed|permission/i;
const MessageEvent = z.object({ type: z.enum(['assistant', 'user']), message: z.object({ content: z.union([z.string(), z.array(ContentBlock)]) }).passthrough() }).passthrough();
/** An assistant event with the request's usage. Claude streams one event per content block, all with the same message id. */
const AssistantUsage = z.object({ type: z.literal('assistant'), message: z.object({ id: z.string().min(1), usage: z.object({ output_tokens: z.number() }).passthrough() }).passthrough() }).passthrough();
const InitEvent = z.object({
type: z.literal('system'),
subtype: z.literal('init'),
Expand All @@ -99,11 +108,6 @@ export function claudeIsolationIssues(ctx: { agents: readonly string[]; plugins:
return reasons;
}

/** The agent-code-mode `run` result as the server returns it (only the fields the bench reads). */
const RunResultText = z.object({
calls: z.array(z.object({ tool: z.string(), decision: z.string(), summary: z.string().optional(), reason: z.string().optional() }).passthrough()),
}).passthrough();

function textOf(content: unknown): string {
if (typeof content === 'string') return content;
if (Array.isArray(content)) {
Expand Down Expand Up @@ -146,7 +150,8 @@ export function parseClaudeTranscript(text: string): ParsedRun {
let availableTools: string[] | null = null;
let hostContext: { agents: string[]; plugins: string[]; memory: boolean } | null = null;
let result: z.infer<typeof ResultEvent> | undefined;
const evidence: Record<string, number[]> = { result: [], toolUse: [], innerCalls: [] };
const evidence: Record<string, number[]> = { result: [], toolUse: [], innerCalls: [], requests: [] };
const requestIds = new Set<string>();

lines.forEach((line, i) => {
if (line.trim() === '') return;
Expand All @@ -169,6 +174,11 @@ export function parseClaudeTranscript(text: string): ParsedRun {
evidence['result'] = [i + 1];
return;
}
const req = AssistantUsage.safeParse(event);
if (req.success && !requestIds.has(req.data.message.id)) {
requestIds.add(req.data.message.id);
evidence['requests']?.push(i + 1);
}
const msg = MessageEvent.safeParse(event);
if (!msg.success || typeof msg.data.message.content === 'string') return;
for (const block of msg.data.message.content) {
Expand All @@ -190,14 +200,12 @@ export function parseClaudeTranscript(text: string): ParsedRun {
// A result can be replayed in the stream (e.g. on resume); count each tool_use_id once.
if (tr.success && runToolUses.has(tr.data.tool_use_id) && !seenToolResult.has(tr.data.tool_use_id)) {
seenToolResult.add(tr.data.tool_use_id);
const parsed = RunResultText.safeParse(parseJson(textOf(tr.data.content)));
if (parsed.success) {
const innerCalls = runInnerCalls(textOf(tr.data.content));
if (innerCalls !== null) {
innerSeen = true;
for (const call of parsed.data.calls) {
innerTotal += 1;
inner[call.tool] = (inner[call.tool] ?? 0) + 1;
if (call.decision === 'denied') denials.push(`${call.tool} ${call.summary ?? ''}: ${call.reason ?? 'denied'}`.slice(0, 500));
}
innerTotal += innerCalls.total;
for (const [tool, n] of Object.entries(innerCalls.byTool)) inner[tool] = (inner[tool] ?? 0) + n;
denials.push(...innerCalls.denials);
evidence['innerCalls']?.push(i + 1);
}
}
Expand All @@ -208,6 +216,7 @@ export function parseClaudeTranscript(text: string): ParsedRun {
const r: z.infer<typeof ResultEvent> = result;
return {
turns: r.num_turns,
requests: requestIds.size === 0 ? null : requestIds.size,
hostDurationMs: r.duration_ms,
usage: {
input: r.usage.input_tokens,
Expand Down
17 changes: 7 additions & 10 deletions bench/lib/codex.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { z } from 'zod';
import type { ArmId, ParsedRun, ToolCalls } from './record.ts';
import { runInnerCalls } from './run-result.ts';

/**
* Codex CLI 0.169 facts the arms depend on (checked with `codex debug prompt-input`, no model calls):
Expand Down Expand Up @@ -190,9 +191,6 @@ const Failure = z.object({ type: z.enum(['turn.failed', 'error']), error: z.obje
const RequestLine = z.object({ kind: z.literal('request'), usage: TokenRecord.shape.usage });
const CallLine = z.object({ kind: z.literal('call'), type: z.string(), name: z.string(), namespace: z.string().optional() });
const DenialLine = z.object({ kind: z.literal('denial'), text: z.string() });
const RunResultText = z.object({
calls: z.array(z.object({ tool: z.string(), decision: z.string().optional(), summary: z.string().optional(), reason: z.string().optional() }).passthrough()),
}).passthrough();
const McpResult = z.object({ content: z.array(z.object({ type: z.string(), text: z.string().optional() }).passthrough()) }).passthrough();

export function classifyCodexTool(name: string, namespace?: string): 'native' | 'run' | 'codeMode' | 'other' {
Expand Down Expand Up @@ -275,14 +273,12 @@ export function parseCodexTranscript(json: string, requests: string | null): Par
const result = McpResult.safeParse(mcp.data.result);
if (kind === 'run' && result.success) {
const text = result.data.content.map((c) => c.text ?? '').join('');
const log = RunResultText.safeParse(parseJson(text));
if (log.success) {
const innerCalls = runInnerCalls(text);
if (innerCalls !== null) {
runInnerSeen = true;
for (const c of log.data.calls) {
runInnerTotal += 1;
runInner[c.tool] = (runInner[c.tool] ?? 0) + 1;
if (c.decision === 'denied') runDenials.push(`${c.tool} ${c.summary ?? ''}: ${c.reason ?? 'denied'}`.slice(0, 500));
}
runInnerTotal += innerCalls.total;
for (const [tool, n] of Object.entries(innerCalls.byTool)) runInner[tool] = (runInner[tool] ?? 0) + n;
runDenials.push(...innerCalls.denials);
}
}
} else if (type === 'command_execution' || type === 'file_change') {
Expand Down Expand Up @@ -341,6 +337,7 @@ export function parseCodexTranscript(json: string, requests: string | null): Par

return {
turns,
requests: turns,
hostDurationMs: null,
usage: { input: Math.max(0, input - cached - cacheWrite), output, cacheCreation: cacheWrite, cacheRead: cached, reasoning },
hostCostUsd: null,
Expand Down
Loading
Loading