euxaristiaandGitHub 02d43b6942 fix: surface swallowed error in plan file write (#1725)
* fix: surface swallowed error in plan file write

* test: add regression test for plan file write failure path

* test(ExitPlanModeV2Tool): scope fs mock to single test and pass full call signature

Two CodeRabbit concerns:

1. The global fs/promises mock in beforeAll was leaking into unrelated
   test suites (e.g. loadAgentsDir.test.ts) because mock.module() cannot
   be cleanly undone mid-suite. Move the mock into the single test that
   needs it and call mock.restore() in a finally block so it is torn
   down as soon as the assertion completes.

2. ExitPlanModeV2Tool.call() was invoked with 2 args but the Tool base
   class signature requires 4 (input, context, canUseTool,
   parentMessage). Pass the two extra args so the test typechecks
   against the real signature.

* fix(test): prevent fs/promises mock leak from ExitPlanModeV2Tool test

Addresses jatmn's P2 on #1725.

The previous test used mock.module('fs/promises', ...) in a try/finally
with mock.restore(). On Linux CI the mock was still active when
loadAgentsDir.test.ts ran, causing all five agent-fixture tests to fail
with "write failed" traces pointing back to this file.

Fix: add afterEach(mock.restore()) to guarantee the mock is torn down
after each test, regardless of pass/fail path. Verified locally by
running both test files in the same process — 6/6 pass.

* fix(test): avoid fs/promises mock entirely to prevent CI leak

The afterEach(mock.restore()) approach still leaked the fs/promises mock
into loadAgentsDir.test.ts on Linux CI (CodeRabbit comment at 12:12 EST).
Bun's mock.module on Linux replaces the module cache in a way that
persists across test files in the same process.

Fix: don't mock fs/promises at all. Instead, re-mock plans.js to point
getPlanFilePath at a nonexistent directory, so the REAL fs/promises.writeFile
rejects with ENOENT. Nothing to leak.

Verified: both test files pass in both orderings with --max-concurrency=1.

* Fix race on exiting plan mode by saving plan file before permission updates and add regression tests asserting no side effects on error

* fix(test): completely isolate mock module by using teammate context APIs instead of module mock override

* test(plan-mode): cover the React write-before-permission guard; drop global fs/promises mock

Addresses jatmn's two P2 findings on #1725.

- Extract the plan-file write guard from ExitPlanModePermissionRequest's
  handleResponse into an exported persistPlanFileBeforeExit() helper (jatmn
  suggested extraction for testability). The component path is unchanged: on
  write failure it stays in plan mode (returns early) and queues a
  'plan-save-error' notification. Adds focused tests for both success and
  write-failure (mutation-checked: a helper that swallows the failure fails the
  test). Tests use real filesystem paths — a temp file for success and a path
  with a missing parent dir for failure — so they need no fs/promises mock.

- ExitPlanModeV2Tool.test.ts: replace the process-global mock.module('fs/promises')
  in both write-failure tests with the same real-failing-path mechanism (a plan
  path whose parent dir does not exist → genuine ENOENT). This removes the
  fragile core-module mock jatmn flagged, which mock.restore() cannot undo and
  which could leak into other test files.

* test(plan-mode): assert the specific ENOENT write failure in ExitPlanModeV2Tool tests

Addresses CodeRabbit's review on #1725: the two write-failure tests asserted a
generic rejects.toThrow(), which would pass on any error. Tighten both to
rejects.toThrow(/ENOENT/) so they lock in the intended missing-parent-dir write
failure rather than masking an unrelated error. The post-write side-effect
assertions (persistFileSnapshotIfRemote / writeToMailbox / setAppState not
called) are unchanged.

* test(plan-mode): add rendered guard test for handleResponse write failure

Addresses jatmn's P3 on #1725: the only coverage for the write-before-permission
guard was at the persistPlanFileBeforeExit helper level; there was no test that
handleResponse itself returns early on write failure.

Renders ExitPlanModePermissionRequest (following the MonitorPermissionRequest
harness), points the V2 plan file at a path whose parent dir is missing (real
ENOENT), confirms the first accept option, and asserts the plan-save-error
notification is queued while toolUseConfirm.onAllow / onReject and onDone are NOT
called. Mutation-checked: removing the `if (!saved) return` guard makes it fail,
so a future refactor cannot silently drop the guard.

* fix(test): type addNotification mock so render test typechecks

CodeRabbit (correctly) flagged that `mock(() => {})` infers a zero-arg tuple, so
`call[0]` was TS2493 and `bun run typecheck` (CI) failed. Type the mock param
with the real `Notification` type, which also lets the assertion drop its cast.
2026-06-25 06:25:58 +08:00
2026-04-30 18:22:01 +08:00
2026-04-30 18:22:01 +08:00
2026-04-03 09:40:17 +08:00

OpenClaude

OpenClaude is an open-source coding-agent CLI for cloud and local model providers.

Use OpenAI-compatible APIs, Gemini, GitHub Models, Codex OAuth, Codex, Ollama, Atomic Chat, and other supported backends while keeping one terminal-first workflow: prompts, tools, agents, MCP, slash commands, and streaming output.

PR Checks Release Discussions Discord X Security Policy License

OpenClaude is also mirrored to GitLawb: gitlawb.com/node/repos/z6MkqDnb/openclaude

Quick Start | Setup Guides | Providers | Source Build | VS Code Extension | Sponsors | Community

Sponsors

GitLawb logo Bankr.bot logo Atomic Chat logo Xiaomi MiMo logo Atlas Cloud logo
GitLawb Bankr.bot Atomic Chat Xiaomi MiMo Atlas Cloud

Star History

Star History Chart

Why OpenClaude

  • Use one CLI across cloud APIs and local model backends
  • Save provider profiles inside the app with /provider
  • Run with OpenAI-compatible services, Gemini, GitHub Models, Codex OAuth, Codex, Ollama, Atomic Chat, and other supported providers
  • Keep coding-agent workflows in one place: bash, file tools, grep, glob, agents, tasks, MCP, and web tools
  • Use the bundled VS Code extension for launch integration and theme support

Quick Start

Install

OpenClaude requires Node.js >=22.0.0 for npm installs and runtime. Bun is only needed for source builds and local development.

npm install -g @gitlawb/openclaude@latest

If you're on Arch Linux, you can install OpenClaude from the community-maintained AUR package:

paru -S openclaude

If the install later reports ripgrep not found, install ripgrep system-wide and confirm rg --version works in the same terminal before starting OpenClaude.

Verify / troubleshoot installed version:

openclaude --version
npm view @gitlawb/openclaude dist-tags
npm install -g @gitlawb/openclaude@latest

Start

openclaude

Inside OpenClaude:

  • run /provider for guided provider setup and saved profiles
  • run /onboard-github for GitHub Models onboarding

Note: OpenClaude does not automatically load project .env files. We recommend using the /provider command for setup, which saves provider profiles and credentials in .openclaude-profile.json. If you prefer environment variables, export them explicitly or run openclaude --provider-env-file .env for provider/setup variables. Export runtime/debug knobs from your shell or launcher.

Background sessions

Run long non-interactive prompts detached from the current terminal:

openclaude --bg "fix failing tests"
openclaude --bg --name auth-refactor "refactor auth middleware"
openclaude ps
openclaude logs auth-refactor
openclaude logs auth-refactor -f
openclaude kill auth-refactor

Background sessions are local child processes. OpenClaude does not start a daemon or network service, and permission/provider/model/settings flags are passed to the child process the same way they are for a foreground --print run. Session metadata and logs are stored under the resolved OpenClaude config directory, usually ~/.openclaude/bg-sessions/; OPENCLAUDE_CONFIG_DIR can point OpenClaude somewhere else, with CLAUDE_CONFIG_DIR still supported as the legacy fallback. Session names can be reused after older sessions reach a terminal state; use the session ID to inspect older logs with the same name.

openclaude attach <id-or-name> currently reports the matching session and points to openclaude logs <id> -f; full terminal reattach is not implemented for local background sessions yet.

Fastest OpenAI setup

macOS / Linux:

export CLAUDE_CODE_USE_OPENAI=1
export OPENAI_API_KEY=sk-your-key-here
export OPENAI_MODEL=gpt-4o

openclaude

Windows PowerShell:

$env:CLAUDE_CODE_USE_OPENAI="1"
$env:OPENAI_API_KEY="sk-your-key-here"
$env:OPENAI_MODEL="gpt-4o"

openclaude

Fastest local Ollama setup

macOS / Linux:

export CLAUDE_CODE_USE_OPENAI=1
export OPENAI_BASE_URL=http://localhost:11434/v1
export OPENAI_MODEL=qwen2.5-coder:7b

openclaude

Windows PowerShell:

$env:CLAUDE_CODE_USE_OPENAI="1"
$env:OPENAI_BASE_URL="http://localhost:11434/v1"
$env:OPENAI_MODEL="qwen2.5-coder:7b"

openclaude

Setup Guides

Beginner-friendly guides:

Advanced and source-build guides:

Supported Providers

Provider Setup Path Notes
OpenAI-compatible /provider or env vars Works with OpenAI, OpenRouter, DeepSeek, Groq, Mistral, LM Studio, and other compatible /v1 servers
Z.AI GLM Coding Plan /provider or OpenAI-compatible env vars Uses OPENAI_API_KEY at https://api.z.ai/api/coding/paas/v4 and defaults to glm-5.2
Hicap /provider or OpenAI-compatible env vars Uses api-key auth, discovers models from unauthenticated /models, and supports Responses mode for gpt- models
Fireworks AI /provider or env vars First-class provider with 276 curated models (DeepSeek, Qwen, Llama, Gemma, and more); uses FIREWORKS_API_KEY
Gemini /provider or env vars Supports API key only
GitHub Models /onboard-github Interactive onboarding with saved credentials
Codex OAuth /provider Opens ChatGPT sign-in in your browser and stores Codex credentials securely
Codex /provider Uses existing Codex CLI auth, OpenClaude secure storage, or env credentials
Gitlawb Opengateway Startup default, /provider, or env vars Smart gateway at https://opengateway.gitlawb.com/v1; requires an API key from https://gitlawb.com/opengateway/keys and routes Xiaomi MiMo and GMI Cloud partner models by OPENAI_MODEL
OpenCode Zen /provider or env vars Pay-as-you-go AI gateway (48 models); uses OPENCODE_API_KEY via https://opencode.ai/zen/v1; shared key with OpenCode Go
OpenCode Go /provider or env vars $10/mo subscription for open models (13 models); uses OPENCODE_API_KEY via https://opencode.ai/zen/go/v1; shared key with OpenCode Zen
Xiaomi MiMo /provider or env vars OpenAI-compatible API at https://mimo.mi.com; uses MIMO_API_KEY and defaults to mimo-v2.5-pro
NEAR AI /provider or env vars Unified gateway (Claude, GPT, Gemini + TEE open models); uses NEARAI_API_KEY at https://cloud-api.near.ai/v1
Ollama /provider or env vars Local inference with no API key
Atomic Chat /provider, env vars, or bun run dev:atomic-chat Local Model Provider; auto-detects loaded models
Bedrock / Vertex / Foundry env vars Anthropic-family cloud routes; Vertex is for Claude on Vertex AI, not arbitrary Model Garden models

What Works

  • Tool-driven coding workflows: Bash, file read/write/edit, grep, glob, agents, tasks, MCP, and slash commands
  • Streaming responses: Real-time token output and tool progress
  • Tool calling: Multi-step tool loops with model calls, tool execution, and follow-up responses
  • Images: URL and base64 image inputs for providers that support vision
  • Provider profiles: Guided setup plus saved user-level provider profile support
  • Local and remote model backends: Cloud APIs, local servers, and Apple Silicon local inference

Provider Notes

OpenClaude supports multiple providers, but behavior is not identical across all of them.

  • Anthropic-specific features may not exist on other providers
  • Tool quality depends heavily on the selected model
  • Smaller local models can struggle with long multi-step tool flows
  • Some providers impose lower output caps than the CLI defaults, and OpenClaude adapts where possible
  • Gitlawb Opengateway is the fresh-install startup default and requires an API key from https://gitlawb.com/opengateway/keys. It uses one OpenAI-compatible base URL; switch between mimo-* and google/gemini-3.1-flash-lite-preview with /model, and do not pin the base URL to /v1/xiaomi-mimo.
  • Z.AI GLM Coding Plan uses https://api.z.ai/api/coding/paas/v4 with glm-5.2 by default. Use glm-5.2?reasoning=high for enhanced reasoning, glm-5.2?reasoning=xhigh to request Z.AI reasoning_effort=max, or glm-5.2?thinking=disabled for faster direct answers.
  • Xiaomi MiMo uses api-key header auth on the direct OpenAI-compatible route and currently does not support /usage reporting in OpenClaude

GitHub Copilot sub-agent optimization

When CLAUDE_CODE_USE_GITHUB=1, OpenClaude serializes sub-agent execution to reduce GitHub Copilot Premium Request consumption. Default behavior is GITHUB_COPILOT_MAX_SUBAGENTS=1 (synchronous, one sub-agent at a time). Tuning vars (all optional):

Var Effect
GITHUB_COPILOT_MAX_SUBAGENTS=0 Suppress sub-agents entirely (sub-agents throw an error).
GITHUB_COPILOT_MAX_SUBAGENTS=1 Force synchronous execution. Default.
GITHUB_COPILOT_MAX_SUBAGENTS=2..10 Parsed/clamped but not enforced differently from =1 (any positive cap = synchronous).
GITHUB_COPILOT_ALLOW_SUBAGENTS=1 Re-enable parallel/background sub-agents, overriding the cap.
GITHUB_COPILOT_FORCE_SYNC_SUBAGENTS=1 Force synchronous execution regardless of cap.
GITHUB_COPILOT_OPTIMIZATION_DISABLED=1 Disable all of the above; sub-agents run as before this feature.

The is_async field reported in the tengu_agent_tool_selected event and the agent metadata now reflects the final execution mode (i.e., false when synchronous is forced). See .env.example for the full descriptions.

For best results, use models with strong tool/function calling support.

Agent Routing

OpenClaude can route different agents to different models through settings-based routing. This is useful for cost optimization or splitting work by model strength.

Add to ~/.openclaude.json:

{
  "agentModels": {
    "deepseek-v4-flash": {
      "base_url": "https://api.deepseek.com/v1",
      "api_key": "sk-your-key"
    },
    "zai-default": {
      "model": "glm-5.2",
      "base_url": "https://api.z.ai/api/coding/paas/v4",
      "api_key": "sk-your-key"
    },
    "gpt-4o": {
      "base_url": "https://api.openai.com/v1",
      "api_key": "sk-your-key"
    }
  },
  "agentRouting": {
    "Explore": "deepseek-v4-flash",
    "Plan": "gpt-4o",
    "general-purpose": "gpt-4o",
    "frontend-dev": "zai-default",
    "default": "gpt-4o"
  }
}

When no routing match is found, the global provider remains the fallback.

agentRouting values and explicit Agent tool model overrides match keys in agentModels. By default, that key is also the model string sent to the provider. Set agentModels.<key>.model when you want a local route key such as zai-default to call a different provider model name such as glm-5.2.

Note: /provider changes the global/parent provider for your current session. agentModels and agentRouting are specifically for configuring per-agent provider overrides while keeping the parent session unchanged.

Note: api_key values in settings.json are stored in plaintext. Keep this file private and do not commit it to version control.

Model-only routes (same provider): Omit base_url and api_key to run an agent on a different model using your current provider's endpoint and key — no credential duplication:

{
  "agentModels": {
    "mini": { "model": "gpt-5-mini" }
  },
  "agentRouting": {
    "verification": "mini"
  }
}

Built-in agents are routable by their type name. Useful keys: verification (the read-only auditor that runs before completion), Explore, and Plan. For example, "agentRouting": { "verification": "mini" } runs the verifier on gpt-5-mini while your main session stays on its model. Absent any entry, the verifier inherits the main-loop model.

Web Search and Fetch

By default, WebSearch works on non-Anthropic models using DuckDuckGo. This gives GPT-4o, DeepSeek, Gemini, Ollama, and other OpenAI-compatible providers a free web search path out of the box.

Note: DuckDuckGo fallback works by scraping search results and may be rate-limited, blocked, or subject to DuckDuckGo's Terms of Service. If you want a more reliable supported option, configure Firecrawl.

For Anthropic-native backends and Codex responses, OpenClaude keeps the native provider web search behavior.

WebFetch works, but its basic HTTP plus HTML-to-markdown path can still fail on JavaScript-rendered sites or sites that block plain HTTP requests.

Set a Firecrawl API key if you want Firecrawl-powered search/fetch behavior:

export FIRECRAWL_API_KEY=your-key-here

With Firecrawl enabled:

  • WebSearch can use Firecrawl's search API while DuckDuckGo remains the default free path for non-Claude models
  • WebFetch uses Firecrawl's scrape endpoint instead of raw HTTP, handling JS-rendered pages correctly

Free tier at firecrawl.dev includes 500 credits. The key is optional.


Headless gRPC Server

OpenClaude can be run as a headless gRPC service, allowing you to integrate its agentic capabilities (tools, bash, file editing) into other applications, CI/CD pipelines, or custom user interfaces. The server uses bidirectional streaming to send real-time text chunks, tool calls, and request permissions for sensitive commands.

1. Start the gRPC Server

Start the core engine as a gRPC service on localhost:50051:

npm run dev:grpc

Configuration

Variable Default Description
GRPC_PORT 50051 Port the gRPC server listens on
GRPC_HOST localhost Bind address. Use 0.0.0.0 to expose on all interfaces (not recommended without authentication)

2. Run the Test CLI Client

We provide a lightweight CLI client that communicates exclusively over gRPC. It acts just like the main interactive CLI, rendering colors, streaming tokens, and prompting you for tool permissions (y/n) via the gRPC action_required event.

In a separate terminal, run:

npm run dev:grpc:cli

Note: The gRPC definitions are located in src/proto/openclaude.proto. You can use this file to generate clients in Python, Go, Rust, or any other language.


Source Build And Local Development

Use Node.js >=22.0.0 and Bun 1.3.13 or newer for source builds.

bun install
bun run build
node dist/cli.mjs

Helpful commands:

  • bun run dev
  • bun test
  • bun run test:coverage
  • bun run security:pr-scan -- --base origin/main
  • bun run smoke
  • bun run doctor:runtime
  • bun run verify:privacy
  • focused bun test ... runs for the areas you touch

Testing And Coverage

OpenClaude uses Bun's built-in test runner for unit tests.

Run the full unit suite:

bun test

Generate unit test coverage:

bun run test:coverage

Open the visual coverage report:

open coverage/index.html

If you already have coverage/lcov.info and only want to rebuild the UI:

bun run test:coverage:ui

Use focused test runs when you only touch one area:

  • bun run test:provider
  • bun run test:provider-recommendation
  • bun test path/to/file.test.ts

Recommended contributor validation before opening a PR:

  • bun run build
  • bun run smoke
  • bun run test:coverage for broader unit coverage when your change affects shared runtime or provider logic
  • focused bun test ... runs for the files and flows you changed

Coverage output is written to coverage/lcov.info, and OpenClaude also generates a git-activity-style heatmap at coverage/index.html.

Repository Structure

  • src/ - core CLI/runtime
  • scripts/ - build, verification, and maintenance scripts
  • docs/ - setup, contributor, and project documentation
  • python/ - standalone Python helpers and their tests
  • vscode-extension/openclaude-vscode/ - VS Code extension
  • .github/ - repo automation, templates, and CI configuration
  • bin/ - CLI launcher entrypoints

VS Code Extension

The repo includes a VS Code extension in vscode-extension/openclaude-vscode for OpenClaude launch integration, provider-aware Control Center, in-editor chat, theme support, and optional Microsoft Foundry / Azure OpenAI configuration (endpoint, API version, deployment, API key via Secret Storage) injected into launched terminals. See that folders README.

Security

If you believe you found a security issue, see SECURITY.md.

Community

Contributing

Contributions are welcome.

For larger changes, open an issue first so the scope is clear before implementation. Helpful validation commands include:

  • bun run build
  • bun run test:coverage
  • bun run smoke
  • focused bun test ... runs for files and flows you changed

Disclaimer

OpenClaude is an independent community project and is not affiliated with, endorsed by, or sponsored by Anthropic.

OpenClaude originated from the Claude Code codebase and has since been substantially modified to support multiple providers and open use. "Claude" and "Claude Code" are trademarks of Anthropic PBC. See LICENSE for details.

License

MIT for OpenClaude contributors' modifications; the derived Claude Code remains Anthropic's. See more.

S
Description
runs anywhere. uses anything
Readme
83 MiB
Languages
TypeScript 99%
JavaScript 0.7%
Astro 0.2%