How the frontier agent harnesses actually work

Claude Code, Codex CLI, Gemini CLI, Kimi CLI, Grok Build, OpenCode, Hermes, GLM/Z.ai, and DeepSeek Harness — compared at the level that matters: the harness. System prompts read directly from source, tool inventories, context management, and the techniques that repeat — distilled into a playbook for building your own.

Compiled 2026‑07‑19 · Updated 2026‑08‑31 with DeepSeek Harness (open-sourced Aug 13 with the V4 rollout) · Prompts cloned & read from the actual repos · Open the prompt reader to read every system prompt in full, or browse harness_lab/prompts/

01 · Foundations

Anatomy of a harness

Every product here is the same ~200-line loop wearing different clothes: send the conversation + tool schemas to the model, execute whatever tool calls come back, append results, repeat until the model answers in plain text. Everything else — the six boxes below — is where harnesses actually differ and compete.

1 · System promptIdentity, tone, coding rules, output format. 370–4,000 words. The most legible part — and increasingly the smallest.
2 · Tools3 tools (Codex: shell, apply_patch, update_plan) to ~18 (Amp). Edit format wars: exact-string replace vs. custom diff.
3 · The loopTurn-taking, parallel tool calls, background tasks, preserved thinking blocks between turns.
4 · Context managementThe 2026 battleground: compaction prompts, KV-cache discipline, subagent isolation, Kimi's D‑Mail rollback, DSH's event-sourced session log.
5 · Safety & permissionsOS sandboxes (Seatbelt/Landlock) × approval policies. Hooks for deterministic guardrails.
6 · Memory & extensibilityAGENTS.md / CLAUDE.md, skills with progressive disclosure, MCP as the universal tool bus.
02 · The players

Nine harnesses, nine philosophies

Claude Code

Anthropic · closed binary · Claude models

The feature-maximal harness that popularized CLAUDE.md, subagents, hooks, skills, and plan mode. Design center: context is the scarcest resource — progressive disclosure everywhere (skills load on demand, tool schemas load via ToolSearch), rules attached to the tools they govern.

hooksskillssubagentsdeferred tools

Codex CLI

OpenAI · open source (Rust, Apache-2.0) · GPT-5.x

The minimalist: three core tools, OS-level sandboxing instead of per-tool prompts, and per-model system prompts — codex-tuned models get a prompt ⅓ the size because the behavior is trained in, not written down. The cleanest permission model in the field.

3 toolsapply_patchsandbox × approval

Gemini CLI

Google · open source (TypeScript) · Gemini

The most engineered prompt: a "Context Efficiency" section with an in-repo warning that it must be re-benchmarked on SWE-bench before edits. Teaches the model to estimate token cost of its own strategy, self-heal sandbox failures, and distinguish Directives from Inquiries.

context efficiencyself-healing sandboxuntrusted_context

Kimi CLI

Moonshot AI · open source (Python, Apache-2.0) · K2/K3

The most inventive on context: D‑Mail lets the model roll its own context back to a checkpoint, replacing dead-end exploration with a note to its past self. Declarative YAML agent specs, persistent resumable subagents, schema-constrained XML compaction.

D-Mail rollbackYAML agentsK3: 1M ctx

Grok Build

xAI · open source (Rust, some templates XOR-encrypted) · Grok

The smallest general prompt in the field (668 words, templated per config) and the most novel edit tool: hashline anchors — content-hashed line references instead of exact strings, with atomic batch edits that return fresh anchors on staleness. Two-level compaction, including mid-turn tool-result summarization.

hashline edits668-word promptintra-turn compaction

OpenCode

SST community · open source · any model

The model-agnostic harness: ships seven different system prompts (anthropic.txt, codex.txt, kimi.txt, gemini.txt…) and picks one per model family — hard evidence that prompts must be written per model, not per product.

per-model promptsagents as markdown

Hermes

Nous Research · open weights + MIT agent

The harness-as-text school: tool schemas live inside the system prompt in <tools> tags, calls come back as JSON in <tool_call> tags — portable to any inference stack. Since Feb 2026 also a product: Hermes Agent, a server-resident agent that writes its own skills after each task.

schema-in-prompt<think> togglesself-writing skills

GLM / Z.ai

Zhipu AI · open weights (MIT) · GLM-5.x

The contrarian: builds no general harness at all. Ships an Anthropic-compatible API and trains GLM to fit Claude Code's conventions (preserved thinking, tool wire format), selling a coding plan that plugs into Claude Code, Cline, and OpenCode. The harness is a commodity; the model is the product.

borrow the harnessslime RL1M ctx

DeepSeek Harness

DeepSeek AI · open source (TypeScript, MIT) · V4 · Aug 13, 2026

The kernel: everything is a plugin — model adapter, tools, session log, sandbox, and the agent loop itself, on the Cordis composition framework (405 packages). No prompt file exists: the 702-word system prompt is assembled from plugin-owned sections. Sessions are event-sourced; it even runs Claude Code and Codex as subagent backends. 206K stars in 18 days.

all-pluginevent-sourced logrival CLIs as subagents
03 · Measured

System prompt size is a design decision

Word counts measured directly from the cloned repos (core system prompt, excluding tool schemas). The spread is 10×. The headline: OpenAI ships a 3,917-word prompt to general GPT-5 models but only 1,221 words to codex-tuned models — when behavior is trained in, the prompt shrinks to just editing constraints and formatting rules. Grok Build's general template is smaller still (668 words), and Hermes goes furthest: the whole harness fits in 374 words plus schemas. DeepSeek Harness (added Aug 2026) lands near the bottom by construction: no prompt file exists in the repo — the 702-word default is assembled at runtime from sections each tool plugin owns, and pinned by deterministic snapshot fixtures.

Core system prompt length (words)

measured 2026-07-19 with wc -w on repo files · lighter bars = estimates
measured from source   estimate (prompt is assembled at runtime or not fully public)
04 · Compared

Technique adoption matrix

What each harness ships. ● native  ◐ partial / via convention  · absent. GLM column reflects what the model is trained to exploit in borrowed harnesses.

TechniqueClaude CodeCodex CLIGemini CLIKimi CLIGrok BuildOpenCodeHermes AgentGLM/Z.aiDeepSeek dsh
Plan / todo toolupdate_plan, TodoWrite, SetTodoList●●●●●●◐◐●
Plan mode (read-only gate)●◐●●·●··◐
Subagents / task delegation●◐●●●●●·●
Persistent / resumable subagents●··●··◐·●
Auto-compactiondedicated summarization prompt●●●●●●◐◐●
Intra-turn tool-result compaction●···●···●
Model-initiated context rollbackKimi D-Mail···●·····
Memory filesAGENTS.md / CLAUDE.md / GEMINI.md●●●●●●●◐●
Auto-memory directoryagent-curated persistent facts●·●◐◐·●··
Skills / progressive disclosure●●●●●◐●·●
Hooks (deterministic guardrails)●●◐·●●··●
OS-level sandboxSeatbelt / Landlock / containers●●●··◐●·●
Per-model system prompts·●◐··●··◐
Preserved thinking across turns●●◐●◐◐●●◐
Deferred tool loadingschemas fetched on demand●●·······
MCP client●●●●●●◐·●
Background / long-running tasks●●◐●●◐●·●

Compiled from direct repo reads (Codex, Kimi, Gemini, OpenCode, Hermes FC, DeepSeek dsh) + research on docs/changelogs for closed or product-level features. Treat ◐/· cells as "as of Jul 2026" (DeepSeek column: Aug 2026). DSH plan mode is ◐ because it is deliberately soft guidance — sandbox/approval enforce independently.

05 · Primary sources

Deep dives — with receipts

Quotes marked ✓ read from source were read directly from the cloned repos today. Everything else is flagged as reported. Full verbatim files live in prompts/.

Codex CLI OpenAI — the minimalist
  • Three tools: shell, apply_patch (a custom freeform diff grammar with *** Begin Patch envelopes), update_plan. The shell is the universal tool.
  • Per-model prompts: gpt-5.2-codex_prompt.md (1,221 words) vs prompt_with_apply_patch_instructions.md (3,917 words) for general GPT-5. Trained-in behavior needs no prose.
  • Sandbox × approval as orthogonal axes: read-only / workspace-write / danger-full-access crossed with untrusted / on-failure / on-request / never. The prompt itself adapts: in never mode run tests proactively; in interactive modes hold off.
  • Preambles: short narrated updates before grouped tool calls — a deliberate UX voice.
"Skip using the planning tool for straightforward tasks (roughly the easiest 25%). Do not make single-step plans."✓ read from source — codex-rs/core/gpt-5.2-codex_prompt.md
"Do not waste tokens by re-reading files after calling `apply_patch` on them. The tool call will fail if it didn't work."✓ read from source — prompt_with_apply_patch_instructions.md
"When doing frontend design tasks, avoid collapsing into 'AI slop' or safe, average-looking layouts… No purple bias or dark mode bias."✓ read from source — gpt-5.2-codex_prompt.md
"You must keep going until the query is completely resolved, before ending your turn… Do NOT guess or make up an answer."✓ read from source — prompt_with_apply_patch_instructions.md

Read the source: codex-tuned prompt base prompt + apply_patch GPT-5.2 variant all variants + notes

Claude Code Anthropic — the feature-maximal one
  • Rules live on tools, not in the global prompt: the Bash tool description carries hundreds of words of git policy; the global prompt stays about identity and communication.
  • Progressive disclosure everywhere: skills load only name+description until invoked; deferred tools ship as names only, schemas fetched via ToolSearch — thousands of tokens saved per request.
  • Subagents for context isolation first: a child burns its own window reading 50 files, returns a 1–2k-token report. 2026: background-by-default, git-worktree isolation, deterministic Workflow orchestration scripts.
  • Hooks: PreToolUse/PostToolUse/Stop shell hooks that can block or rewrite calls — users bolt deterministic policy onto a stochastic agent.
  • system-reminder channel: harness-injected state changes arrive in tagged blocks the model treats as context, not user instructions — clean channel separation.
  • Memory as auditable markdown: CLAUDE.md hierarchy + a per-project memory directory with an index file; no opaque vector store.
"Lead with the outcome… Being readable and being concise are different things, and readable matters more."✓ first-hand — from a live session's system prompt (communication section)
"Report outcomes faithfully: if tests fail, say so with the output… state it plainly without hedging."✓ first-hand — anti-sycophancy rule

Read the source: first-hand harness notes

Gemini CLI Google — the benchmarked prompt
  • The prompt is treated as tested code. An engineering comment in snippets.ts warns: "You must run the major benchmarks, such as SWEBench, prior to committing any changes to the Context Efficiency section." ✓ read from source
  • Context Efficiency section teaches the model token economics: combine turns, parallel reads, conservative grep scopes, "unnecessary turns are generally more expensive than other types of wasted context."
  • Directives vs Inquiries: requests default to analysis-only; file modification requires an explicit directive — a prompt-level fix for over-eager agents.
  • Prompt-injection defense in the prompt: MCP/tool outputs arrive wrapped in <untrusted_context> tags to be treated as passive data.
  • Self-healing sandbox: on "Operation not permitted", retry automatically with additional_permissions, surfacing an approval modal — turning failures into permission requests.
"Operate as a strategic orchestrator. Your own context window is your most precious resource… When you delegate, the sub-agent's entire execution is consolidated into a single summary in your history."✓ read from source — packages/core/src/prompts/snippets.ts
"Validation is the only path to finality. Never assume success or settle for unverified changes."✓ read from source — snippets.ts, Primary Workflows
"If you have attempted to fix a failing implementation more than 3 times without success… List your current assumptions and identify which ones might be wrong. Propose a different architectural approach."✓ read from source — Strategic Re-evaluation rule

Read the source: snippets.ts (current) snippets.legacy.ts

Kimi CLI Moonshot — the context innovator
  • D‑Mail (unique): a tool that reverts the context to an earlier checkpoint, appending a self-authored note — the model folds dead-end exploration into one message. Named after Steins;Gate.
  • Declarative YAML agent specs: agent.yaml with extend, allowed_tools, exclude_tools, role text injected into one shared system.md — users define custom agents the same way.
  • Persistent subagents: "Subagent instances are persistent session objects with their own context history" — resumable by agent_id.
  • Two-tier injected context: <system> = supplementary info; <system-reminder> = authoritative directives that may override behavior.
  • Structured compaction: the compaction prompt demands XML output (<current_focus>, <code_state>…) with priorities: current task → errors+solutions → final code versions only.
  • K3 harness contract (Jul 16, 2026): pass back all thinking history or "generation quality may become highly unstable"; 1M context via Kimi Delta Attention makes keeping full history cheaper than compacting. (reported — K3 blog/quickstart)
"You are basically folding the recent messages in your context into a single message, which can significantly reduce the waste of context window… DO NOT explain to the user. The user do not care about this. Just explain to your past self."✓ read from source — src/kimi_cli/tools/dmail/dmail.md
"If you anticipate making multiple non-interfering tool calls, you are HIGHLY RECOMMENDED to make them in parallel… This is very important to your performance."✓ read from source — agents/default/system.md
"ALWAYS, keep it stupidly simple. Do not overcomplicate things."✓ read from source — Ultimate Reminders, system.md

Read the source: system prompt D-Mail tool compaction agent.yaml explore.yaml K2/K3 notes

Grok Build xAI — anchored edits and two-level compaction
  • Hashline editing (unique): hashline_read returns every line as an anchor LINE:hash:salt→content; edits reference anchors, not exact strings. Batch edits are atomic — one stale anchor rejects the whole batch, and the error returns fresh anchors so the model retries immediately. Kills the ambiguous-match/stale-file failure mode of exact-string editors.
  • Tool-role indirection: prompt templates address tools.by_kind.read/edit/search/execute/plan/monitor/lsp/memory_* — written against roles, bound to whatever implementation is active. One prompt serves many tool configurations.
  • Two-level compaction: a full-conversation summarizer (6 mandatory sections, must merge any previous summary) plus intra-turn compaction that replaces piled-up tool calls + results mid-turn "so the assistant can continue its work with the same effective knowledge but less context overhead."
  • Reversibility-weighted safety: approvals scale with blast radius, not tool identity.
  • Reads everyone's memory files: AGENTS.md, Agents.md, Claude.md, AGENT.md — nested-wins, chat overrides.
  • Open source with a twist: some templates ship XOR-encrypted (prompt_encrypted.rs, auto-generated) — the harness is public, parts of the prompt text are obfuscated. Docs live as markdown in ~/.grok/docs/ that the agent reads on demand.
"Weigh each action by how easily it can be undone and how far its effects reach… One approval is not a blank check. Approving something once (e.g. a git push) does not approve it in every later situation."✓ read from source — xai-grok-agent/templates/prompt.md, action_safety
"Edits are atomic — if any anchor is stale, ALL edits are rejected. Retry the full batch. Never fabricate or modify anchors."✓ read from source — templates/subagent_prompt.md, hashline workflow
"If you find unexpected state — unfamiliar files, branches, or configuration — investigate before deleting or overwriting; it may be the user's in-progress work."✓ read from source — action_safety

Read the source: main prompt subagent + hashline compaction intra-turn compaction notes

OpenCode SST — the model-agnostic switchboard
  • Seven system prompts, picked per model: anthropic.txt, codex.txt, kimi.txt, gemini.txt, beast.txt, trinity.txt… Its kimi.txt is essentially Kimi CLI's own prompt; gemini.txt mirrors Gemini's Core Mandates. Each model gets the dialect it was trained on.
  • Anchored compaction: the summarizer receives the <previous-summary> block and merges new history into it — an incrementally-updated anchor, not a fresh summary each time. ✓ read from source
  • Professional objectivity section: "Objective guidance and respectful correction are more valuable than false agreement" — anti-sycophancy written into an open-source prompt.
  • Delegation-for-context rules: exploration that isn't a needle query must go through the Task tool to keep the main window lean.
"VERY IMPORTANT: When exploring the codebase… that is not a needle query for a specific file/class/function, it is CRITICAL that you use the Task tool instead of running search commands directly."✓ read from source — session/prompt/anthropic.txt

Read the source: Claude variant GPT variant Kimi variant Gemini variant beast mode compaction

Hermes Nous Research — harness as text, then harness as product
  • Schema-in-prompt tool calling: JSON Schemas inside <tools> tags in the system message; calls emitted as JSON inside <tool_call> tags; results in <tool_response>. No API-level tools param needed — became the de-facto standard for open-weights serving (vLLM's hermes parser). ✓ read from source (Hermes-Function-Calling repo)
  • Reasoning as a prompt toggle: the same weights do chat or long <think> CoT depending on the system prompt — steerability-first, the user's prompt is sovereign.
  • Hermes Agent (Feb 2026, MIT): server-resident persistent agent; persona in SOUL.md, memory in MEMORY.md, user model in USER.md; post-task reflection auto-writes skills; /learn turns docs into SKILL.md files; trajectories export for training the next model — a closed data flywheel. (reported — repo/docs research)
"You are a function calling AI agent with self-recursion… Please keep a running summary with analysis of previous function results… Do not stop calling functions until the task has been accomplished or you've reached max iteration of 10."✓ read from source — prompt_assets/sys_prompt.yml

Read the source: function-calling prompt Hermes 4 + Agent notes

GLM / Z.ai Zhipu — the harness is a commodity
  • Borrow-the-harness: no first-party general CLI. An Anthropic-compatible endpoint (api.z.ai/api/anthropic) + env vars in Claude Code's settings puts GLM-5.2 in the OPUS slot, glm-4.7 in the HAIKU slot. Officially supports Claude Code, Cline, OpenCode. (reported — docs.z.ai)
  • Trained for someone else's harness: interleaved + preserved thinking modes mirror Claude Code's protocol; the model competes on price (~⅙ of GPT-5.5 claimed) inside a scaffold it didn't build.
  • Open training harness instead: slime (RL framework behind GLM-4.5→5.2) is open source; RL environments include 10k+ verifiable SWE tasks from GitHub issue–PR pairs.
  • Z.ai Code (the one first-party surface) is a locked-stack Next.js app builder, not general SWE: frontend-first ordering, "do not write any test code", shadcn-only components. ✓ read from source (captured prompt)
"When develop the fullstack, write the frontend first to let user see the result, then write the backend."✓ read from source — Z.ai Code captured system prompt

Read the source: Z.ai Code prompt GLM strategy notes

DeepSeek Harness DeepSeek — everything is a plugin (added Aug 2026)
  • All-plugin kernel: 405 packages on the Cordis composition framework — model adapter, tool registry, session log, sandbox, compaction, UI, and the agent loop itself are swappable plugins. Presets (Standard / Code / Minimal / Creator) are just cordis.yml composition files.
  • No prompt file exists: each tool plugin registers its own ordered prompt section (the read guidance lives in the read-tool plugin); assembly concatenates, scoped registrations shadow globals, a waterfall event lets experts rewrite. Default render: 702 words, pinned by deterministic snapshot fixtures.
  • Cache discipline as architecture: dynamic facts (approval policy, plan state) are "cache-safe runtime-context snapshots" — durable user-role messages appended after retained history, re-logged only on change. Plan mode toggling "changes only the prompt section, never the request tool catalog." The prefix never moves.
  • Event-sourced sessions: everything the model sees is a committed event in an append-only log; the visible conversation is a projection ("the surface"). Resume, fork, search, and replay run on the same stream; 175 snapshot fixtures replay sessions and assert the exact rendered prompt.
  • Compaction is a transaction: compaction/start → summary as a user/message surface-replace → compaction/end; a crash leaves a detectable orphaned lock. Deterministic tool-result pruning (head/tail, code-point-safe) runs first and can avoid the summary call entirely.
  • Rival CLIs as subagents: provider backends include spawn-in-process, fork-in-process, ACP, Codex, and Claude Code — plus hook bridges that speak Claude Code's hooks.json and Codex's hook formats. Capability flags are checked up front: unsupported requests are "rejected with a typed error rather than accepted-then-ignored."
  • Built by agents, with receipts: 842 dated agent notes in .agents/notes/ (proposed → implemented → archived) are cited by the docs as design authority; type blocks in docs are drift-checked against source in CI. Ships first-party workflow (JS fan-out) and ralph (fresh-agent loop) tools.
"Your bash tool runs under a file sandbox — a `[sandbox: file access denied …]` result is policy, not a command bug."✓ read from source — snapshots/session/text-turn/system-prompt.expected.md
"Use subagent in the background by default. Start independent delegations together in one assistant message and continue useful work while they run."✓ read from source — rendered default system prompt
"Mark blocked only after the same blocking condition persists for at least 3 consecutive goal rounds… difficulty, uncertainty, or useful remaining work is not blocked."✓ read from source — goal-tools prompt section
"Releasing the lock last turns a crash mid-operation into a detectable orphaned lock… rather than a `compaction/end` that falsely claims compaction finished."✓ read from source — docs/subsystems/compaction.md

Read the source: rendered system prompt Ralph variant repo AGENTS.md full notes

06 · Frontier

The techniques that are new in 2026

Deferred tool loadingClaude Code · Codex (MCP tool search, on by default since 0.142)

Tool schemas are the silent context tax — dozens of MCP tools can cost 10k+ tokens per request. The fix: ship names only, let the model fetch full schemas on demand via a search tool. Both major harnesses converged on this within months.

The preserved-thinking contractKimi K3 · GLM-5 · Claude · Codex

Models are now trained expecting their reasoning blocks back in subsequent turns. K3's docs warn that dropping thinking history makes generation "highly unstable"; GLM-5 ships an explicit "Preserved Thinking" mode. Harness and model are co-designed artifacts now — you can no longer treat the transcript as freely editable.

Anchored editing instead of exact-string matchingGrok Build hashline (unique so far)

Every read line carries a content-hash anchor; edits target anchors, batches are atomic, and stale-anchor errors return fresh anchors for immediate retry. The first structural answer to the two classic edit-tool failures: ambiguous matches and files that changed underneath you.

Model-initiated context editingKimi D-Mail (unique so far)

Compaction has always been harness-initiated. D-Mail inverts it: the model decides its recent context is waste, picks a checkpoint, and folds everything since into one note to its past self. Expect others to copy this.

Per-model prompts as standard practiceCodex (6 prompt files) · OpenCode (7) · Gemini (versioned snippets)

The era of one prompt for all models is over. Codex-tuned models get ⅓ the words of general GPT-5; OpenCode ships a different dialect per model family. Corollary: as behavior moves into training, prompts shrink toward pure constraints.

The prompt is benchmarked codeGemini CLI

Gemini's repo literally gates edits to the Context Efficiency prompt section behind SWE-bench runs. System prompts have CI now. If you build a harness, version your prompt and regression-test it.

Harness/model decoupling as business modelGLM Coding Plan · (Kimi and MiniMax run the same play)

Zhipu treats Claude Code as a commodity interface: Anthropic-compatible API, model trained to the harness's conventions, subscription priced per prompt. The moat moved from scaffold to model-fits-scaffold.

Self-writing extensibilityHermes Agent /learn · Claude Code skills ecosystem

Hermes Agent reflects after tasks and writes its own SKILL.md files; /learn converts docs into skills. The skills format (markdown + frontmatter, lazily loaded) has become the cross-vendor convention — AGENTS.md itself is now a Linux Foundation standard used by 60k+ repos.

Prompt-injection defense moves into the transcriptGemini untrusted_context · Claude Code system-reminder · Kimi two-tier tags

Harnesses now tag channel authority explicitly: harness-authored directives vs. supplementary info vs. untrusted external content. The model is taught which wrapper outranks which — a security architecture made of XML tags.

The harness as a plugin kernelDeepSeek Harness (Aug 2026)

dsh applies "everything is a plugin" to the agent itself: loop, model adapter, session log, sandbox, compaction — all swappable, composed per session from preset files. The system prompt follows: no prompt file, just plugin-owned sections assembled at request time. Claude Code's rules-live-on-tools idea taken to its structural conclusion.

Event-sourced sessions with deterministic replayDeepSeek Harness

The session is an append-only event log; the model-visible transcript is a projection over it. Compaction becomes a logged, lock-bracketed transaction (crashes leave detectable orphaned locks), token accounting is replayable via shadow-price events, and 175 snapshot fixtures pin the exact rendered prompt — the whole harness is regression-tested like a database.

Run your rival as a subagentDeepSeek Harness (Codex + Claude Code backends, hook bridges)

Instead of only borrowing a harness (GLM) or only building one, dsh absorbs the ecosystem: Claude Code and Codex are subagent backends, and their hook formats are supported natively. Your existing hooks.json works; your existing CLIs become delegation targets. Interop as a wedge for selling V4 tokens.

07 · Playbook

Build your own harness

Everything above compresses into one loop, ten decisions, and a build order. The loop is genuinely this small — ship v0 in a day, then earn each layer of sophistication.

The irreducible loop

msgs = [system_prompt(cwd, os, date, agents_md)]   # stable prefix — never edit, only append
msgs.append(user_msg)
while True:
    resp = model(msgs, tools=[shell, read, edit, write, todo])
    msgs.append(resp)
    if not resp.tool_calls:
        break                                      # plain text = final answer
    for call in resp.tool_calls:                   # execute (parallel if independent)
        gate(call)                                 # permission check / sandbox
        msgs.append(tool_result(call, run(call), cap=25_000))  # cap output tokens
    if tokens(msgs) > 0.8 * window:
        msgs = [msgs[0], compact(msgs), *msgs[-K:]]  # dedicated summarizer prompt

The ten decisions

1 · KV-cache discipline first

Stable prompt prefix, append-only transcript, no timestamps in the system prompt, mask/defer tools instead of adding/removing them. Manus: cache hit rate is the single most important metric (10× cost difference).

2 · Few tools, one great shell

Codex proves 3 tools suffice. Start: shell + read + exact-string edit + write + todo. Every tool schema is a permanent tax on every request.

3 · Edit format: exact-string replace

Uniqueness-checked old/new strings (Claude/Gemini/Cline style) is easier to implement and debug than Codex's diff grammar. Fail loudly on ambiguity.

4 · Prompt = constraints, not lectures

1–2k words: identity, editing rules, git safety ("never reset --hard", "don't commit unless asked"), verification-before-done, output format. Write per-model variants. Version it, benchmark it.

5 · Filesystem as context

Let the agent write notes/plans to disk and re-read them. Compress context by dropping bodies but keeping restorable pointers (paths, URLs). Recite the todo list near the context tail.

6 · Compaction is a feature

Dedicated summarizer prompt with a structured schema (Kimi's XML sections, OpenCode's anchored previous-summary merge). Keep: current task, errors+solutions, decisions, file paths. Preserve thinking blocks if the model expects them.

7 · Memory = markdown the agent edits

Adopt AGENTS.md (it's a standard now; closest-file-wins, chat overrides everything). Add an auto-memory dir with an index file. No vector DB until markdown fails you.

8 · Separate can-do from must-ask

Codex's two axes: sandbox (what's technically possible: read-only / workspace-write / full) × approval (when to stop and ask). Add hooks so policy is deterministic, not model-obeyed.

9 · Subagents for context, not parallelism

Fan out read-only explore agents that return 1–2k-token reports; keep a single writer. This is the cheapest 10× on effective context you can build.

10 · Tag channel authority

Wrap harness injections, tool output, and external content in distinct tags; teach the model the precedence order. This is your prompt-injection defense and your steering channel.

Build order (each phase has a pass/fail check)

  1. v0 — The loop. 5 tools, one prompt, no persistence. ✓ check: fixes a real bug in one of your repos end-to-end
  2. v1 — Memory + todo. AGENTS.md loading (nested, closest-wins) + a todo tool recited in context. ✓ check: follows a repo convention you wrote down without being told in chat
  3. v2 — Compaction. Token counter, 80% threshold, structured summarizer, keep last K turns verbatim. ✓ check: survives a 3-hour session and still knows the original task
  4. v3 — Permissions. Allow/deny rules + approval prompt + (macOS) sandbox-exec profile for the shell. ✓ check: rm -rf and git push require approval; reads don't
  5. v4 — Subagents. One explore agent type, read-only tools, returns a report. ✓ check: main context stays under 30% while answering a whole-codebase question
  6. v5 — Extensibility. Skills as markdown + frontmatter, loaded on demand; MCP client if you need external services. ✓ check: add a capability without touching harness code

Pitfalls (each one observed in the wild)