# AlwaysAgent > AlwaysAgent (alwaysagent.app) gives you a dedicated Linux cloud server with Claude Code and OpenAI Codex preinstalled, used from any browser — desktop, phone, or iPad. Bring your own API key, OpenRouter, a custom relay (base URL), Anthropic-compatible models such as DeepSeek, Kimi, GLM, Qwen, or MiniMax, or log in with your own subscription. Tasks keep running on the server after you close your laptop. AlwaysAgent is an independent product. It is not affiliated with, endorsed by, or sponsored by Anthropic or OpenAI. Claude Code and Codex are the official CLIs from those companies, installed unmodified on the user's server. ## What it is - One dedicated Linux VM per user (US region), full root access, its own public IP. Run Docker, databases, and serve live websites on ports 80/443. - Claude Code CLI and OpenAI Codex CLI preinstalled; a browser workspace with chat, files, terminal, and preview. - Model access is the user's choice: official login, Anthropic API key, OpenRouter, any Anthropic-compatible relay, or vendor endpoints (DeepSeek, Kimi, Zhipu GLM, Alibaba Qwen, MiniMax). Credentials are stored only on the user's own server; AlwaysAgent does not proxy model calls and adds no markup on tokens. - Works on mobile browsers; no app install. Tasks continue running when the browser or laptop is closed. ## Pricing - Hourly: top up $10, about $0.05 per hour. Billed while the server exists (including when powered off) until deleted. No auto-renewal. Unused balance refundable within 14 days minus payment processing fees. - Monthly plans (auto-renew, cancel anytime): Starter $9.9 (2 vCPU / 4 GB / 40 GB NVMe), Developer $17.9 (4 vCPU / 8 GB / 75 GB), Pro $24.9 (6 vCPU / 12 GB / 100 GB), Power $44.9 (8 vCPU / 24 GB / 200 GB). Unlimited monthly traffic, dedicated IP, free daily snapshots on monthly plans. - One-click upgrade from hourly to monthly keeps files and databases. ## How it differs from official cloud options - Anthropic's Claude Code cloud sessions and Remote Control require a claude.ai subscription login; Anthropic's docs state API keys and third-party providers are not supported there, and Remote Control needs your own computer to stay on. - AlwaysAgent runs the same CLI on a server you control, so API keys, relays, OpenRouter, and Anthropic-compatible models all work, and the laptop can be off. ## Guides (English) - [Run Claude Code in the cloud with your own API key](https://alwaysagent.app/claude-code-api-key): why official cloud sessions don't accept API keys and how to configure ANTHROPIC_API_KEY / ANTHROPIC_AUTH_TOKEN / ANTHROPIC_BASE_URL. Markdown: https://alwaysagent.app/claude-code-api-key.md - [How to use Claude Code with OpenRouter](https://alwaysagent.app/claude-code-openrouter): base URL https://openrouter.ai/api, blank ANTHROPIC_API_KEY, verify with /status. Markdown: https://alwaysagent.app/claude-code-openrouter.md - [Claude Code on the web vs. Remote Control vs. your own server](https://alwaysagent.app/claude-code-cloud-vs-alwaysagent): comparison of subscription vs API key, laptop-on requirement, model choice, and cost. Markdown: https://alwaysagent.app/claude-code-cloud-vs-alwaysagent.md - [Run Claude Code on a VPS, 24/7](https://alwaysagent.app/claude-code-vps): self-hosting guide — server sizing, install, subscription vs API key, tmux, phone access, SSH/firewall hardening, troubleshooting. Markdown: https://alwaysagent.app/claude-code-vps.md ## 中文指南 - [Claude Code 国内怎么用?](https://alwaysagent.app/zh/claude-code-china):接 DeepSeek、Kimi、智谱 GLM、通义千问、MiniMax 等国产模型或中转站,附官方接口地址与配置示例。Markdown:https://alwaysagent.app/zh/claude-code-china.md - [Claude Code 中转站怎么配置?](https://alwaysagent.app/zh/claude-code-relay):Base URL 与 Key 的填法、常见报错。Markdown:https://alwaysagent.app/zh/claude-code-relay.md - [手机怎么用 Claude Code?](https://alwaysagent.app/zh/claude-code-phone):官方 Remote Control 与云服务器方案对比。Markdown:https://alwaysagent.app/zh/claude-code-phone.md - [Codex 国内怎么用?](https://alwaysagent.app/zh/codex-china):Codex CLI 安装、~/.codex/config.toml 接 DeepSeek、智谱、Kimi、MiniMax、百炼、火山方舟等国产模型(Responses 接口),附常见报错。Markdown:https://alwaysagent.app/zh/codex-china.md - [云服务器 24 小时跑 Claude Code](https://alwaysagent.app/zh/claude-code-vps):境外与国内服务器怎么选、安装、订阅/API Key/国产模型接入、tmux 常驻、手机远程、安全加固与排错。Markdown:https://alwaysagent.app/zh/claude-code-vps.md ## Site - [Home (English)](https://alwaysagent.app/) - [首页(中文)](https://alwaysagent.app/zh/) - [Pricing](https://alwaysagent.app/#pricing) - [Terms of Service](https://alwaysagent.app/legal/terms) - [Privacy Policy](https://alwaysagent.app/legal/privacy) - [Refund Policy](https://alwaysagent.app/legal/refund) - [Contact](https://alwaysagent.app/legal/contact) — support@alwaysagent.app - [Full text for LLMs](https://alwaysagent.app/llms-full.txt) - [Sitemap](https://alwaysagent.app/sitemap.xml) --- # How to run Claude Code 24/7 in the cloud without managing a VPS > When your laptop sleeps, local coding agents stop. You can move Claude Code to the cloud without maintaining a Linux VPS, but the right choice depends on whether you run isolated tasks or need an always-on workspace. Source: https://alwaysagent.app/claude-code-24-7-cloud Updated: 2026-11-06 ## Quick answer and decision checklist You can run Claude Code in the cloud without managing a VPS by using Anthropic's hosted cloud sessions, CI runners like GitHub Actions, cloud dev environments like GitHub Codespaces, programmatic AI sandboxes, or a managed always-on workspace like AlwaysAgent. None of these require you to configure SSH keys, firewalls, or operating system updates, though they differ sharply in how long they stay awake and what they retain between runs. Before picking a platform, answer four questions about your workflow: - **Is the job a run-to-completion task or an always-on workspace?** If you want an agent to fix a single issue, open a pull request, and exit, task runners and CI workflows fit well. If you want an interactive environment that stays open between coding sessions with your files and processes intact, you need a persistent machine. - **Do you have a claude.ai subscription?** Anthropic's built-in cloud sessions require a paid claude.ai subscription (Pro, Max, Ultra, Team, or Enterprise with qualifying seats). - **Do you use an API key, a gateway, or other models?** Anthropic's cloud sessions do not accept Anthropic Console API keys or third-party providers. If you pay per token via `ANTHROPIC_API_KEY`, route through OpenRouter or an LLM gateway, or also run OpenAI Codex, you need an environment where you control the CLI credentials. - **Do you need custom toolchains, databases, or long-running processes?** Ephemeral sandboxes and CI jobs start from a fresh clone or template and shut down when the task ends or a timer expires. Running local databases, background watchers, or preview servers 24/7 requires persistent compute and storage. ## 1. Anthropic cloud sessions & scheduled tasks (Best for subscription users on GitHub) Anthropic offers built-in cloud execution through Claude Code on the web and cloud scheduled tasks, allowing you to hand off repository tasks without running anything on your own computer. ### How it works Per Anthropic's documentation, a cloud session runs on infrastructure Anthropic manages rather than on your local machine. The session continues running after you close your laptop, and you can monitor or steer it from a browser at `claude.ai/code`, the Code tab in the Claude mobile app, the Desktop app, or the terminal via `claude --cloud`. For recurring or automated background work, Anthropic provides cloud scheduled tasks (formerly called routines, currently in research preview). Scheduled tasks launch autonomous cloud sessions on a recurring cadence (custom cron expressions that run more often than once per hour are rejected), on demand via a dedicated HTTP POST API trigger, or in response to GitHub repository events such as pull requests or releases. Anthropic also offers Projects (public beta on select plans), where Claude coordinates multiple parallel cloud sessions from one conversation. (Note: Do not confuse cloud sessions with Anthropic's Remote Control feature. Per the documentation, Remote Control is only a window into a local session, so "your computer has to stay on and the claude process has to keep running".) ### What you need - A Pro, Max, Ultra, or Team plan, or an Enterprise account with premium seats or Chat + Claude Code seats (plus the cloud sessions permission if your organization uses custom roles). - A connected GitHub account (or GitHub Enterprise Server on Team and Enterprise plans) so the cloud environment can clone repositories and push branches. - A configured cloud environment if you need custom environment variables, network access levels, or startup setup scripts. ### Limits - **Duration and idle behavior:** Per Anthropic's docs, an idle session's VM pauses with its files saved, and cloud sessions stop after a period of inactivity, after which the VM is reclaimed. You can reopen the session from claude.ai/code to provision a fresh VM; your conversation history is restored, but background work that was still running (shell commands, subagents, session-scoped scheduled tasks) is not. - **State persistence:** According to Anthropic's docs, "Cloud sessions start from a fresh clone of your repository. Anything you commit to the repo is available. Anything you've installed or configured only on your own machine isn't available in the session." In Projects, Anthropic notes that if a thread's sandbox cannot be resumed, the thread continues from a fresh clone, so uncommitted changes can be lost. - **Authentication and models:** Cloud sessions require a `claude.ai` account. Anthropic states they "aren't reachable with an Anthropic Console API key or from a third-party provider such as Amazon Bedrock". - **Billing:** Cloud sessions and scheduled tasks count toward your Claude plan's usage limits alongside your other usage, with "no separate charge for the cloud VM". ## 2. Claude Code GitHub Actions (Best for PR & event-driven automation) If your goal is to have Claude Code respond to repository events, triage issues, or review and write pull requests automatically, Claude Code GitHub Actions runs the agent inside your CI pipeline. ### How it works You add the `anthropics/claude-code-action` step to a GitHub Actions workflow file (`.github/workflows/claude.yml`). Whenever a matching GitHub event occurs—such as an `@claude` mention in an issue or pull request comment, an opened PR, or a cron schedule—the workflow runs on a GitHub Actions runner, where Claude Code works on the prompt and can push commits or post a reply. ### What you need - Admin access to a GitHub repository to install the Claude GitHub App (granting read and write permissions for Contents, Issues, and Pull requests) and configure repository secrets. - Either an `ANTHROPIC_API_KEY` from the Claude Console or a `CLAUDE_CODE_OAUTH_TOKEN` generated from a Pro, Max, Ultra, Team, or Enterprise subscription using `claude setup-token`. You can also configure OpenID Connect (OIDC) to route inference through Amazon Bedrock, Google Cloud's Agent Platform, or Microsoft Foundry. - Quick setup via `/install-github-app` inside Claude Code, or manual workflow file setup. ### Limits - **Duration cap:** On standard GitHub-hosted runners, GitHub documentation specifies that each workflow job can run for a maximum of 6 hours of execution time; if a job reaches this limit, it is terminated. (Self-hosted runners allow up to 5 days of job execution.) - **Idle behavior and state persistence:** CI runners are ephemeral and non-interactive. Each GitHub-hosted runner job starts in a fresh environment. Nothing persists outside of what is committed to Git or uploaded as a workflow artifact. - **Billing:** You pay for model usage (via your API key, cloud provider, or subscription token) plus GitHub Actions runner compute. See GitHub's Actions billing documentation for current pricing and included minutes. ## 3. GitHub Codespaces (Best for interactive cloud IDE sessions) Managed cloud development environments like GitHub Codespaces give you a container-backed Linux environment in your browser or VS Code where you can install and run the Claude Code CLI just as you would locally. ### How it works When you create a codespace on a repository, GitHub provisions a virtual machine running a dev container with your repository checked out. You open a terminal in the browser client or connect via VS Code, install the Claude Code CLI, sign in with your subscription or export `ANTHROPIC_API_KEY`, and run interactive coding sessions. ### What you need - A GitHub account and a repository. Personal accounts include a monthly quota of free compute time and storage; per GitHub's docs, usage is blocked once you use up the quota unless a valid payment method is on file, and spending may be limited by budgets. - The Claude Code CLI installed inside the codespace (or added to your `devcontainer.json` so it persists across container rebuilds). ### Limits - **Idle stop policy:** Codespaces is designed to stop when you step away. According to GitHub's documentation, a codespace stops running after a period of inactivity—by default, 30 minutes. Per GitHub's docs, you can change the timeout in your personal settings (between 5 and 240 minutes), and interaction such as typing or using the mouse, as well as terminal input or output, resets the idle timer. - **Hard duration cap:** GitHub's docs state unambiguously: "Regardless of your idle timeout setting, a codespace has a maximum lifetime of 12 hours." This means a codespace cannot run continuously beyond that limit. - **State persistence:** When a codespace stops, "any running processes are stopped," though saved changes and terminal history are preserved for the next time you start it. - **Billing:** Active codespaces bill for compute in core hours (active duration multiplied by the machine type's core multiplier), and storage is billed for as long as a codespace exists. ## 4. AI agent sandbox platforms (Best for developers building custom agent apps) If you are writing your own orchestration code in Python, TypeScript, or Go and want to spawn isolated Linux environments via SDK to execute Claude Code or custom agents programmatically, several infrastructure platforms specialize in agent sandboxes. ### How it works Instead of logging into a workstation yourself, your application calls an API or SDK to boot a container or microVM, injects credentials, runs commands over a programmatic shell or SSH gateway, and pauses or destroys the sandbox when done. Four documented options include: - **E2B:** Provides isolated microVM sandboxes controlled via Python and JavaScript/TypeScript SDKs. You create a sandbox with `Sandbox.create()`, run commands, and either kill it or pause it. Pausing a sandbox saves both its filesystem and memory state, and per E2B's docs "a paused sandbox is kept indefinitely" until you kill it, which permanently deletes it. - **Daytona:** Offers sandboxes that run as Linux containers by default, with VM sandboxes as a separate option; VM sandboxes support pause/resume and memory snapshots, per Daytona's docs. Sandboxes can be managed via SDK, CLI, API, or SSH. - **Modal Sandboxes:** Provides secure containers for running untrusted or LLM-generated code, with Python, JavaScript, and Go SDKs. Volumes can be mounted in Sandboxes, and Filesystem Snapshots can preserve state for runs that need to continue past the maximum lifetime. Exit Snapshots capture the filesystem when a Sandbox exits; check Modal's docs for how long they are retained. - **Fly.io Machines:** Fast-launching VMs driven by a REST API or the `flyctl` CLI. A Machine's root filesystem is ephemeral, so any data you want to keep belongs on an attached Fly Volume (a slice of an NVMe drive on the same physical server as the Machine). ### What you need - Custom integration code using the platform's SDK or API, plus custom templates or Docker images with Claude Code installed. - Programmatic secret injection (such as passing `ANTHROPIC_API_KEY` via environment variables or platform secret managers). ### Limits - **Duration caps and idle timeouts:** In E2B, sandboxes can run continuously for up to 24 hours on Pro or 1 hour on Hobby. In Modal, Sandboxes have a default maximum lifetime of 5 minutes, accept a timeout of up to 24 hours, and can be configured with an `idle_timeout`. In Daytona, sandboxes have idle-based lifecycle settings; Daytona's SSH documentation notes that a long-running command that produces output without further input does not reset the idle clock. - **State persistence nuances:** Persistence differs by platform and sandbox type, so check each provider's lifecycle documentation for what survives a stop, pause, or delete. - **Billing:** These platforms use usage-based billing. For example, E2B bills running sandboxes per second for provisioned CPU and RAM. ## 5. AlwaysAgent (Best for a plug-and-play 24/7 server in your browser) If you want a persistent Linux machine that stays online 24/7 so Claude Code and background services never stop, but you do not want to manage a raw VPS yourself, [AlwaysAgent](https://alwaysagent.app) provides a preconfigured server behind a browser workspace. ### How it works Each user gets a dedicated cloud Linux server with its own public IP address and both Claude Code and OpenAI Codex preinstalled. You access the server through a workbench in your computer or phone browser—which includes AI chat, a file manager, a terminal, remote browser preview, and version history—without installing an app or configuring SSH. When you close your browser tab or shut your laptop, the server remains online 24/7 and your tasks continue running. ### What you need - An AlwaysAgent account and your own model credentials. In the workspace settings, you enter your own Base URL and API Key—supporting official Anthropic or OpenAI keys, third-party relays, domestic model APIs, or OpenRouter. Your keys are stored only on your own server; the platform does not proxy AI calls, add markup, or resell model quota. ### Limits - **Duration and state:** The server stays online 24/7. Your files, installed packages, databases, and running processes persist on your server across sessions, and monthly plans include automatic daily snapshots. - **Billing:** Hourly trials require a minimum $10 top-up and bill at approximately $0.05/hour; billing continues even if the server is powered off and stops only when you delete the server (unspent balance within 14 days of top-up is refundable minus processing fees). Monthly plans with unlimited bandwidth auto-renew and can be canceled anytime: Starter at $9.9/mo (2 vCPU, 4 GB RAM, 40 GB disk), Developer at $17.9/mo (4 vCPU, 8 GB RAM, 75 GB disk), Pro at $24.9/mo (6 vCPU, 12 GB RAM, 100 GB disk), and Power at $44.9/mo (8 vCPU, 24 GB RAM, 200 GB disk). Hourly servers can be converted to monthly plans in one click with data migrated. If you are comfortable handling SSH hardening, firewall rules, and `tmux` yourself, see our tutorial on [setting up Claude Code on your own VPS](/claude-code-vps). ## Comparison of cloud options for Claude Code Use the table below to match your requirements against how each cloud runtime behaves. | Option | Always-on 24/7 | State persists | Needs Claude subscription | API key / other models | Runs your own tools & services | Setup effort | Billing model | | --- | --- | --- | --- | --- | --- | --- | --- | | Anthropic Cloud Sessions | No (runs per task; stops after inactivity) | Partly (starts from a fresh Git clone; idle VMs pause, then may be reclaimed) | Yes (Pro, Max, Ultra, Team, Enterprise) | No (claude.ai account only) | Via setup scripts in cloud environment | Low (connect GitHub) | Included in plan usage limits | | Claude Code GitHub Actions | No (6h max per job on hosted runners) | No (ephemeral CI runner) | Optional (OAuth token or API key) | Yes (API key, Bedrock, Google Cloud, Foundry) | Within CI job duration | Low (/install-github-app or YAML) | CI compute minutes + model usage | | GitHub Codespaces | No (30m default idle stop; 12h max lifetime) | Yes (saved changes kept across stops; processes stop) | Optional | Yes (full CLI control) | Yes (while active) | Low (browser or VS Code) | Core hours while active + storage | | AI Agent Sandboxes (E2B, Modal, Daytona) | No (e.g., 24h max continuous on E2B Pro; Modal timeouts up to 24h) | Varies (pause/resume, volumes, or snapshots, depending on platform) | Optional | Yes (inject via SDK/env) | Yes (inside sandbox limits) | High (requires SDK code & templates) | Usage-based (e.g., per-second compute) | | AlwaysAgent | Yes (dedicated 24/7 Linux server) | Yes (full disk & running processes) | No | Yes (BYO API key, Base URL, OpenRouter, Codex) | Yes (dedicated server + public IP) | Low (ready in browser tab) | ~$0.05/h or $9.9–$44.9/mo + your own API usage | ## What to check before you pick Cloud platforms use the words "background" and "persistent" differently. Verify these six details before committing your workflow: - **Maximum session duration:** Check if the platform enforces a hard wall-clock ceiling. GitHub-hosted Actions jobs terminate at 6 hours, GitHub Codespaces have a 12-hour maximum lifetime regardless of the idle timeout setting, E2B Pro caps continuous runtime at 24 hours, and Modal Sandboxes accept timeouts up to 24 hours. Only an always-on server runs indefinitely without a hard reset. - **Idle timeout rules:** Find out what triggers an automatic shutdown. In Codespaces, the default is 30 minutes of inactivity. In Daytona over SSH, a long-running command that only prints output does not reset the idle timer without client input. If your agent pauses to wait for an approval prompt, an idle timer may stop the environment mid-task. - **Filesystem vs. process persistence:** Keeping files on disk is not the same as keeping processes in memory. Stopping a Codespace or using a Modal Exit Snapshot preserves your files, but stops running processes. Anthropic's cloud sessions restore conversation history after expiry but not background work, and start from a fresh clone of your repository. E2B's memory+filesystem pause and always-on servers keep both files and running processes. - **Where credentials live and what they unlock:** If you rely on `ANTHROPIC_API_KEY`, a custom `ANTHROPIC_BASE_URL` gateway, or OpenRouter, Anthropic's hosted cloud sessions will not work. Make sure your chosen runtime lets you store environment secrets on the machine or in repository secrets without routing your keys through an untrusted proxy. - **How idle vs. active billing works:** Codespaces bills compute while a codespace is active and storage for as long as it exists, and E2B bills running sandboxes per second; check each provider's pricing for paused or stopped states. AlwaysAgent hourly servers bill until you delete the server, even when powered off. - **Mobile access when you are away:** If you want to check progress or approve edits from your phone, check the client interface. Anthropic cloud sessions work in the Claude iOS/Android app (terminal-only commands such as `/plugin` and `/resume` are unavailable in cloud sessions), GitHub Actions workflows can be triggered by `@claude` comments on issues and pull requests, and AlwaysAgent provides its full workbench directly in a mobile web browser without installing an app. For a deeper comparison between Anthropic's hosted cloud and a dedicated server workspace, read [Claude Code Cloud vs. AlwaysAgent](/claude-code-cloud-vs-alwaysagent). ## FAQ ### Can I run Claude Code in the cloud without a VPS? Yes. You can use Anthropic's hosted cloud sessions at claude.ai/code, automate repository tasks with Claude Code GitHub Actions, run the CLI inside GitHub Codespaces, build on programmatic sandboxes like E2B or Modal, or use a preconfigured browser-based server like AlwaysAgent. None of these require manual Linux server administration. ### Does Anthropic's Claude Code on the web work with an API key? No. According to Anthropic's documentation, cloud sessions at claude.ai/code require a paid claude.ai subscription (Pro, Max, Ultra, Team, or qualifying Enterprise seats) and cannot be used with an Anthropic Console API key or third-party providers like Amazon Bedrock. To use an API key or a custom base URL in the cloud, use GitHub Actions, Codespaces, an agent sandbox, or AlwaysAgent. ### Why does Claude Code stop when I use GitHub Codespaces? GitHub Codespaces stops running after a period of inactivity (30 minutes by default) and enforces a hard maximum lifetime of 12 hours regardless of your timeout setting. When a codespace stops, running processes—including Claude Code—are stopped, though saved changes are kept for your next session. ### What is the difference between Anthropic's Remote Control and cloud sessions? Cloud sessions run on infrastructure managed by Anthropic, so they keep working when you turn off your computer. Remote Control connects the Claude mobile app or browser to a Claude Code process running on your own machine; per Anthropic's docs, your computer must stay on and the local claude process must stay running for Remote Control to work. ### How can I schedule Claude Code to run recurring tasks in the cloud? You have three main options that do not require your computer to stay on: Anthropic's cloud scheduled tasks (which run on a schedule, via HTTP API, or on GitHub events; recurring runs more often than once per hour are not accepted), Claude Code GitHub Actions triggered by a cron schedule in your workflow YAML, or a cron job / background process on an always-on server such as AlwaysAgent. ### Do cloud sessions keep my uncommitted files and installed packages? In Anthropic's cloud sessions, each session starts from a fresh clone of your GitHub repository; an idle session's VM pauses with files saved but can later be reclaimed, in which case reopening provisions a fresh VM. Commit and push work you want to keep. If you need uncommitted files, local databases, and custom packages to stay in place permanently without rebuilding, use a persistent server workspace like AlwaysAgent. --- # Claude Code API key setup: from first login to a cloud server > Setting an API key in Claude Code takes one environment variable, but the details decide whether you get billed per token, which credential wins, and whether Anthropic's own cloud features still work. Here is the full picture, with copy-paste config. Source: https://alwaysagent.app/claude-code-api-key Updated: 2026-11-04 ## The short version To use an API key with Claude Code, export `ANTHROPIC_API_KEY` (or put it under `env` in `~/.claude/settings.json`), start `claude`, approve the key when asked, and confirm with `/status`. Requests are then billed per token to the account that owns the key, not drawn from a Pro or Max subscription. `bash` ``` export ANTHROPIC_API_KEY="" claude # inside Claude Code: /status ``` Everything below explains what that does, how to make it permanent on a server, and what to check when it stops working. All behavior described here comes from Anthropic's Claude Code documentation; where a detail changes between versions, check the docs for your version. ## Subscription login vs API key: what actually differs A subscription login draws on your plan's usage limits, while an API key bills every token to the Console organization that owns it. Anthropic's cost documentation says Claude Code "charges by API token consumption" for API users, and that subscribers have usage included in their plan. | | Subscription login (/login) | API key | | --- | --- | --- | | Billing | Included in Pro, Max, Team or Enterprise plan limits | Per token, billed to the key's Console organization | | Limits | Plan usage windows | API rate limits and any spend limit you set on the workspace | | Where to see spend | Plan usage in /usage | Cost page in the Claude Console | | Official cloud sessions | Supported | Not supported | | Remote Control | Supported | Not supported | A subscription suits one person working interactively. An API key suits automation, shared billing, or a hard spend cap. Check Anthropic's pricing page for current plan numbers. ## Which variable to use: ANTHROPIC_API_KEY, ANTHROPIC_AUTH_TOKEN or apiKeyHelper Use `ANTHROPIC_API_KEY` for a key from the Claude Console, and `ANTHROPIC_AUTH_TOKEN` when a gateway or relay expects a bearer token. The only practical difference is the HTTP header. - **Console API key** (`ANTHROPIC_API_KEY`): Sent as the X-Api-Key header. Used instead of your subscription once set and approved. - **Gateway or relay token** (`ANTHROPIC_AUTH_TOKEN`): Sent as `Authorization: Bearer`. Anthropic says to use it if you were not told which kind your gateway expects. - **Rotating credentials** (`apiKeyHelper`): A script that prints a key on demand, for short-lived tokens from a vault. - **Endpoint** (`ANTHROPIC_BASE_URL`): Where requests go. Leave it unset for Anthropic's own API. Putting a credential in the wrong variable is a classic cause of 401 errors, because the header is wrong. For a gateway, see the [OpenRouter guide](/claude-code-openrouter) for a worked example. Credential precedence When several credentials exist, Claude Code picks one in a fixed order, and an API key beats a saved subscription login. Per Anthropic's authentication docs, the order is: - Cloud provider credentials (`CLAUDE_CODE_USE_BEDROCK`, `CLAUDE_CODE_USE_VERTEX` or `CLAUDE_CODE_USE_FOUNDRY` set) - `ANTHROPIC_AUTH_TOKEN` - `ANTHROPIC_API_KEY` - Output of the `apiKeyHelper` script - `CLAUDE_CODE_OAUTH_TOKEN` (a long-lived subscription token from `claude setup-token`) - Anthropic profile and federation credentials - Subscription OAuth login from `/login` Two consequences matter in practice. First, if you are logged in to a subscription and also have `ANTHROPIC_API_KEY` set, Claude Code uses the key once you approve it. Second, your saved login is not deleted; it just sits unused while a higher-ranked credential is present. In interactive mode Claude Code asks once whether to use the key and remembers your answer. You can change it later with the "Use custom API key" toggle in `/config`, which only appears while the variable is set. In non-interactive mode (`claude -p`) the key is always used when present, with no prompt. ## Configure it: three ways to set the key Pick one method and stick with it, because mixing shell exports and settings files makes it hard to tell which value is live. Option 1: shell environment variable The simplest option is a shell export. It applies to every `claude` started from that shell. `~/.bashrc or ~/.zshrc` ``` export ANTHROPIC_API_KEY="" ``` Reload with `source ~/.bashrc`. The weakness is that non-interactive launches (cron, systemd, some SSH commands) may not read your interactive profile, so the variable can be missing exactly where you need it. Option 2: settings.json env block Put the key under `env` in your user settings so it applies however `claude` is launched. Anthropic's docs say Claude Code reads these directly from the file. `~/.claude/settings.json` ``` { "env": { "ANTHROPIC_API_KEY": "" } } ``` For a gateway or relay, set `ANTHROPIC_BASE_URL` and `ANTHROPIC_AUTH_TOKEN` in the same block instead. Do not set the same variable in both a shell export and the `env` block; the docs and some vendor pages disagree on which one wins in edge cases, so one source of truth is safer. Option 3: apiKeyHelper Use `apiKeyHelper` when the key rotates or lives in a secret manager. Point it at a script that prints the key. `~/.claude/settings.json` ``` { "apiKeyHelper": "/usr/local/bin/print-anthropic-key" } ``` The script must print only the key to stdout, as a single printable token, and exit with code 0. A banner or log line in the output breaks it. If it takes more than 10 seconds, Claude Code shows a slow-helper notice. Note that `/login` will not help while a helper is set, because the helper's output outranks a saved login. ## Verify which credential is active Run `/status` inside Claude Code; it shows the credential source in use and, if a login and a key both exist, marks the one that is not being used. When you set a custom base URL, it also shows the `Anthropic base URL` line. - Expect an `API key` row (or `Auth token` for a gateway) when the key is in effect. - Run `env | grep ANTHROPIC` in the same shell to see what the process inherited. Tools like direnv can load a stale key from a project `.env` file. - To switch back to a subscription, run `unset ANTHROPIC_API_KEY`, remove it from your profile, and relaunch. - To clear a saved login before using a gateway token, type `/logout`; Anthropic recommends it to avoid conflicts between a login and an external credential. ## Persist the key on a Linux server On a server, store the key in a file only your user can read, and start sessions inside `tmux` so they survive disconnects. A reliable pattern: - Create the settings file with the key, as in Option 2 above. - Lock it down: `chmod 600 ~/.claude/settings.json`. - Run `claude` inside `tmux new -s work` so a dropped SSH connection does not kill the task. - Check `/status` once after every change to the config. Claude Code itself stores a saved login on Linux in `~/.claude/.credentials.json` with mode `0600`, and the same permissions are a good default for anything you write yourself. If you run several accounts, give each its own directory with `CLAUDE_CONFIG_DIR`. For unattended jobs, remember that in `-p` mode the key is used without a prompt, and a `--bare` run does not read the subscription token, so authenticate those with the API key or an `apiKeyHelper`. ## Keep the key safe Treat an API key like a password: keep it out of git, scope it, cap its spend, and rotate it when in doubt. Anthropic's own warning is specific: do not put the credential in a project's `.claude/settings.json`, because that file is committed and shared with everyone who clones the repository. - **Where to store it:** user-level `~/.claude/settings.json` or `.claude/settings.local.json` (check that your `.gitignore` covers the latter), never a committed file. - **Limit blast radius:** in the Console, use workspaces and set a workspace spend limit so a leaked or runaway key cannot spend without bound. - **Rotate:** create a new key at the Console's API keys page, update the server, then revoke the old key. A revoked key shows up as an "Invalid API key" error, which is also how you notice a stale copy somewhere. ## Claude Code API key not working: common errors Most failures come down to a stale or higher-priority credential, a key in the wrong variable, or a wrong base URL. Work through these in order. Authentication conflict or "my old login keeps winning" If you see a warning about conflicting credentials, you have both a login and an environment credential. Run `/status` to see which is active, then either unset the variable or run `/logout` and log in again. If an old `ANTHROPIC_API_KEY` is set in `~/.bashrc`, `~/.zshrc` or `~/.profile`, remove it from there too, or it comes back in every new shell. "Invalid API key" The API rejected the key, or Claude Code blocked it before sending. Check for typos, trailing whitespace or line breaks in the value, confirm the key has not been revoked in the Console, and look for a stale key loaded from a `.env` file. If the key comes from `apiKeyHelper`, run the script by hand and confirm it prints a valid key. 401 "Invalid authentication credentials" The credential's format was recognized but the account or organization behind it was rejected. If `/status` shows an `API key` row, that key overrides your login: rotate it or unset it. Behind a gateway, the text after "401" is the gateway's own message, so fix the credential the gateway expects, and check you used `ANTHROPIC_AUTH_TOKEN` versus `ANTHROPIC_API_KEY` as the provider specifies. 403 "Request not allowed" A 403 usually means a permissions or network problem rather than a bad key. Anthropic lists three common causes: an inactive subscription, a Console account without the "Claude Code" or "Developer" role, and a corporate proxy interfering with requests. A proxy or filter blocking the host, or Claude Code being unavailable in your region, can also produce it. "This organization has been disabled" An old `ANTHROPIC_API_KEY` from a previous employer or project is overriding a working subscription. Unset it, remove it from your shell profile, relaunch, and confirm with `/status`. Base URL and proxy mistakes `ANTHROPIC_BASE_URL` changes where requests go, not which model answers them. Set it only when you actually use a gateway, with the exact URL the provider documents. A wrong path, an extra `/v1`, or a leftover value from an old experiment shows up as connection errors, 404s or auth failures. Set only the base URL without a credential variable and Claude Code keeps using your saved login. Slow gateways may also need a larger `API_TIMEOUT_MS`. "Your apiKeyHelper script is failing" The helper exited with an error, timed out, or printed something other than the key. Run it directly, make it print one token and nothing else, and check the `apiKeyHelper` row in `/status` for the last error. ## Why official cloud sessions and Remote Control don't accept API keys Anthropic's cloud sessions and Remote Control both require a claude.ai subscription login. Per the docs, Remote Control states "API keys are not supported", and it is also unavailable while `ANTHROPIC_API_KEY`, `ANTHROPIC_AUTH_TOKEN`, an `apiKeyHelper` or a non-Anthropic `ANTHROPIC_BASE_URL` is active. Cloud sessions "always use your subscription credentials": setting an API key in the cloud environment does not override them, and gateway variables set there are not applied. So the choice is real. If you want per-token billing, a company gateway, or OpenRouter, the CLI works with all of them, but you run it somewhere you control. Remote Control also needs your own machine to stay on with the `claude` process running. The comparison is covered in detail in [Claude Code on the web vs. Remote Control vs. your own server](/claude-code-cloud-vs-alwaysagent). ## Running it in the cloud with AlwaysAgent AlwaysAgent hands you a dedicated US Linux server with Claude Code and Codex preinstalled and a browser workspace on top. You paste your key, base URL or relay in settings and start a session; the config lives on your own server. - Your keys stay on your server. AlwaysAgent does not proxy model calls or add a markup on tokens. - Close your laptop and the task keeps running; check in from your phone. - Use an Anthropic key, OpenRouter, a relay, or your own subscription login, per session. AlwaysAgent is independent and not affiliated with Anthropic. The same security rules above apply on any box, ours included: one key per purpose, a spend limit in the Console, and rotation when you are unsure. ## FAQ ### How do I set up an API key for Claude Code? Export ANTHROPIC_API_KEY in your shell or add it under env in ~/.claude/settings.json, run claude, approve the key when prompted, and confirm with /status. Requests are then billed per token to the key's Console organization. ### Will ANTHROPIC_API_KEY override my Claude subscription? Yes. Per Anthropic's docs, once the key is set and you approve it, it is used instead of your Pro, Max, Team or Enterprise login, even if you are logged in. Unset it and relaunch to go back to your subscription. ### Should I use ANTHROPIC_API_KEY or ANTHROPIC_AUTH_TOKEN? Use ANTHROPIC_API_KEY for a key from the Claude Console. Use ANTHROPIC_AUTH_TOKEN for gateways and relays that expect a bearer token, and use it when you are not sure which one the provider wants. ### Why is my Claude Code API key not working? Usual causes are a stale key in your shell profile or a .env file, a revoked key, a credential in the wrong variable, a wrong ANTHROPIC_BASE_URL, or an old login conflicting. Run /status and env | grep ANTHROPIC, then unset or fix the offending value. ### How do I switch from an API key back to my subscription? Run unset ANTHROPIC_API_KEY, delete it from ~/.bashrc, ~/.zshrc or ~/.profile and from settings.json, relaunch claude, and check /status. Run /login if no saved login remains. ### Does Claude Code on the web or Remote Control support API keys? No. Anthropic's docs say cloud sessions use subscription credentials only, and Remote Control states API keys are not supported. To pay per token, run the CLI on a server you control. ### Is it safe to put the API key in settings.json? Yes in your user-level ~/.claude/settings.json with chmod 600, but never in a project's committed .claude/settings.json. Add a Console spend limit and rotate the key if it may have leaked. ### Can I keep my key out of config files entirely? Yes. Set apiKeyHelper to a script that fetches the key from a secret manager and prints only the key to stdout. It outranks a saved login, so /login will not override it while it is set. --- # Claude Code Remote Control vs cloud sessions vs your own server > There are three ways to keep using Claude Code away from your desk. The real difference is where the session runs, and that decides whether your laptop has to stay on, which logins work, and what the session can touch. Source: https://alwaysagent.app/claude-code-cloud-vs-alwaysagent Updated: 2026-11-04 ## The short answer Use cloud sessions when the work lives in GitHub and you want it to keep running without your computer. Use Remote Control when the work needs your own machine and you only want to steer it from your phone. Use your own server when you need an always-on machine you control, or credentials the official features do not accept. All three are real options, and the first two are free with a paid Claude plan. The rest of this page covers how each one starts, what it requires, where it breaks, and a checklist for choosing. Details come from Anthropic's Claude Code documentation as of November 2026; plan names and limits change, so check the docs linked below before you commit. ## The three options - **Cloud sessions** (`claude.ai/code`): Claude Code on the web. Runs on Anthropic-managed VMs by default and keeps going with your laptop closed. Needs a claude.ai plan. - **Remote Control** (`Your computer + Claude app`): Your phone or browser becomes a window into a session on your own machine, which must stay on. - **Your own server** (`Linux + claude`): Claude Code runs on a server you control. Any supported credentials, plus whatever tools you install. ## Claude Code on the web (cloud sessions) A cloud session is Claude Code running on Anthropic's infrastructure instead of your machine, so it keeps running after you close your laptop. It is the easiest of the three to start and the only official option that does not depend on a computer of yours being awake. ### How to start - Open [claude.ai/code](https://claude.ai/code), connect GitHub, pick a repository and branch, and describe the task. - Or use the **Code** tab in the Claude mobile app. - Or run `claude --cloud "your task"` from a terminal. The cloud VM clones your GitHub remote at your current branch, so push your commits first. - Pull a finished session back into your terminal with `claude --teleport`. ### Requirements You need a Pro, Max, Ultra, or Team plan, or an Enterprise seat that includes Claude Code, plus a claude.ai login. Sessions count toward your plan's usage limits, and Anthropic states there is no separate charge for the cloud VM. Per the docs, cloud sessions are not available with an Anthropic Console API key or a third-party provider such as Amazon Bedrock. ### What it does well - No setup: no machine to maintain and nothing to leave running. - The VM comes with common toolchains, Docker, PostgreSQL, and Redis preinstalled, and you can add a setup script. - Pull request workflow: Claude can push a branch, and auto-fix can watch a PR for CI failures and review comments when the Claude GitHub App is installed. ### Limits to know - GitHub is the main path. Cloning in Anthropic-hosted environments and PR creation require GitHub. Other hosts can be sent as a local bundle, but the session cannot push back to that remote. - Network access is restricted by default (the Trusted level covers package registries and common domains), so a task that calls your own APIs needs a custom allowlist. - Idle sessions pause after a few minutes and a VM can later be reclaimed. Reopening restores the conversation, but not shell commands or subagents that were still running. - Parallel sessions share your account's rate limits, so more tasks use up your plan faster. Best for: developers on GitHub with a Claude plan who want to fire off a task and come back to a branch or a pull request. ## Remote Control Remote Control connects claude.ai/code or the Claude mobile app to a Claude Code session that runs on your own computer. Code execution and file access stay local; the phone is a client. Your computer must stay on and the `claude` process must keep running. ### How to start - `claude remote-control` starts server mode, which waits for connections and shows a URL; press the spacebar for a QR code. - `claude --remote-control` starts a normal interactive session that you can also drive remotely. - `/remote-control` (or `/rc`) inside an existing session carries over the current conversation. Then open the session from the list at claude.ai/code or the Code tab of the Claude app. On the first run, Claude Code asks you to accept a one-time confirmation. ### Requirements Remote Control is available on Pro, Max, Ultra, Team, and Enterprise plans, and the docs state that API keys are not supported. On Team and Enterprise, an owner has to enable the toggle first. It does not work with Bedrock, Vertex, or Foundry, or when `ANTHROPIC_BASE_URL` points at a host other than `api.anthropic.com`, such as an LLM gateway or proxy. It needs outbound HTTPS to the Anthropic API on port 443 and opens no inbound ports. ### What it does well - Your full local environment stays available: filesystem, MCP servers, tools, and project configuration. - You can work from terminal, browser, and phone at once; the conversation stays in sync. - If your laptop sleeps or the network drops, an interactive session reconnects when the machine is back online. ### Limits to know - If you close the terminal or the process stops, the session goes offline until you bring it back. - In server mode, an extended network outage makes the process give up after roughly ten minutes and exit. - Terminal-only commands such as `/plugin` and `/resume` do not work from the app, and you cannot choose Bypass permissions from it. - While connected, the session transcript is stored on Anthropic's servers to keep devices in sync. Best for: people who already work in Claude Code on a machine that stays on, and want to check in or approve a step from their phone. ## Your own server An always-on Linux machine that you run Claude Code on gives you the "laptop closed" benefit of cloud sessions with the environment control of Remote Control. You connect over SSH or a browser terminal, and the task keeps running when you disconnect. ### How to start Rent a VPS, install Claude Code, sign in or set credentials, and run `claude` inside `tmux` or `screen`. Anthropic's own Remote Control docs suggest exactly that when you run `claude` from a terminal on a remote machine, so the session survives an SSH disconnect. ### Requirements You need a Linux server, a Claude Code install, and credentials: a claude.ai login, an Anthropic API key, or a compatible gateway. You are responsible for updates, backups, firewall rules, and keeping credentials off shared files. ### What it does well - Any credentials that Claude Code itself accepts, including API keys and gateways, where the official cloud features require a claude.ai login. - Full root access, long-running databases, Docker, and public ports, without the network allowlist of a hosted cloud VM. ### Limits to know - You maintain it. Patching, disk space, and security are yours. - If you sign in with a subscription on the server, Remote Control works there like on any machine. If you use an API key or point `ANTHROPIC_BASE_URL` at a gateway, Remote Control is unavailable, so you reach the server over SSH or a browser terminal instead. - You pay for the server, and for tokens if you use an API key. Best for: pay-per-token users, people routing through a gateway, and anyone who needs more control than a managed VM allows. ## Side by side | | Cloud sessions | Remote Control | Your own server | | --- | --- | --- | --- | | Where code runs | Anthropic-managed VM | Your computer | Your server | | Works with laptop closed | Yes | No | Yes | | Starts from | claude.ai/code, app, --cloud | claude remote-control, /rc | SSH or browser terminal | | claude.ai login | Required | Required | Optional | | Anthropic API key | No | No | Yes | | Gateways, OpenRouter | No | No | Yes | | Phone and browser access | Claude app, claude.ai/code | Claude app, claude.ai/code | SSH app or browser workspace | | Repository host | GitHub (others as a bundle, no push back) | Anything on your machine | Anything you can reach | | Outbound network | Allowlist by default | Your own network | Unrestricted by default | | Parallel sessions | Many, share plan limits | Several in server mode | As many as the server can run | | Maintenance | None | Keep your machine awake | You patch and secure it | | Cost | Counts toward plan usage | Counts toward plan usage | Server fee, plus tokens if API | Facts about cloud sessions and Remote Control come from Anthropic's documentation as of November 2026. The docs say cloud sessions "aren't available through third-party providers," and that Remote Control does not support API keys. ## Real scenarios ### Continuing a task from your phone while out If the task is already running on your desktop, Remote Control is the fastest path: scan the QR code or open the Code tab in the Claude app, and answer questions or approve steps. If it was never started locally, launch a cloud session from the phone instead, so you do not depend on a machine at home. ### Long tasks that run overnight Cloud sessions survive a closed laptop, but they pause when idle and can be reclaimed, so they suit work that makes steady progress rather than waiting for hours on you. Remote Control only works while the machine stays awake. A server running inside `tmux` has no such limits, which makes it the safest place for a long migration or batch job. Whichever you pick, tell Claude to commit often so progress is saved. ### Teams and many repositories On Team and Enterprise plans, cloud sessions can be shared with teammates, and owners can create shared cloud environments. For repositories on GitLab or Bitbucket, or tasks that need your internal network, a self-managed machine is simpler. Anthropic also offers self-hosted environments on Team and Enterprise plans, which run cloud sessions on your own infrastructure. ## Common problems and fixes - **"Remote Control requires a claude.ai subscription."** You are signed out, or an API key or token is taking precedence. Run `claude auth login` and remove `ANTHROPIC_API_KEY`, `ANTHROPIC_AUTH_TOKEN`, or `apiKeyHelper` from your shell or settings. - **Remote Control unavailable with a gateway.** Unset `ANTHROPIC_BASE_URL` if it points anywhere except `api.anthropic.com`. - **"Remote Control disconnected" or "Can't reach."** Your computer slept, lost the network, or the `claude` process stopped. Interactive sessions reconnect on their own; in server mode, run `claude remote-control` again. - **`--cloud` or `--teleport` asks you to sign in.** You are on an API key or Console login. Run `claude auth login` and choose claude.ai. - **"Branch is not on GitHub."** The cloud session started from an older commit or the default branch. Push your branch and start again. - **Cloud session stopped after being left alone.** The VM expired. Reopen it from claude.ai/code and ask Claude to rerun the commands that stopped. ## How to decide 1. **You have a Claude plan and your repositories are on GitHub** — Start with cloud sessions. No extra cost, nothing to maintain, and the task runs without your computer. 1. **You have a Claude plan and your work needs local files, MCP servers, or tools** — Use Remote Control, and keep the machine awake and the process running. 1. **You pay per token, use a relay or OpenRouter, or want root and long-running services** — Use your own server. The official cloud features will not accept those credentials. 1. **You want a server but not the sysadmin work** — Use a prepared server. That is what AlwaysAgent packages: a dedicated Linux server with Claude Code and Codex installed, and a browser workspace that works on a phone. ## Where AlwaysAgent fits AlwaysAgent is the server option with the setup done. Each user gets a dedicated Linux VM with root access, Claude Code and Codex preinstalled, and a browser workspace with chat, files, a terminal, and preview. Tasks keep running after you close the browser. You can sign in with your own subscription or supply an API key, OpenRouter, or a compatible relay, and credentials stay on your server. AlwaysAgent does not proxy model calls or add token markup. Hourly pricing is about $0.05 per hour; monthly plans start at $9.9. > AlwaysAgent is independent and not affiliated with Anthropic or OpenAI. Anthropic's Remote Control and cloud sessions are a good fit for many people; this page is about the cases they do not cover. ## Official documentation - [Use Claude Code in the cloud](https://code.claude.com/docs/en/claude-code-on-the-web) - [Remote Control](https://code.claude.com/docs/en/remote-control) - [Claude Code on mobile](https://code.claude.com/docs/en/mobile) - [Configure cloud environments](https://code.claude.com/docs/en/cloud-environments) ## FAQ ### What is the difference between Claude Remote Control and cloud sessions? Where the session runs. Remote Control drives a Claude Code session on your own computer, which must stay on. A cloud session runs on Anthropic-managed infrastructure and keeps going with your laptop closed. Both use claude.ai/code and the Claude app, and both need a claude.ai login. ### Does Claude Code Remote Control need my computer on? Yes. The web and mobile apps are a window into a local session, so your computer must stay on and the claude process must keep running. A sleeping machine reconnects when it is back online, but a stopped process takes the session offline until you restart it. ### Is Claude Code on the web free? There is no separate charge for the cloud VM, but sessions count toward your plan's usage limits. You need a Pro, Max, Ultra, or Team plan, or an eligible Enterprise seat. Check Anthropic's site for current plan prices. ### Can I use Remote Control or cloud sessions with an API key? No. Anthropic's docs say API keys are not supported for Remote Control, and cloud sessions require a claude.ai sign-in. Setting ANTHROPIC_API_KEY, ANTHROPIC_AUTH_TOKEN, or pointing ANTHROPIC_BASE_URL at a gateway also makes Remote Control unavailable. ### Can I run Claude Code on my own server and still use Remote Control? Yes, if you sign in with a claude.ai subscription and do not set a gateway URL or API key. Anthropic recommends tmux or screen when you run claude on a remote machine, so the session survives an SSH disconnect. ### Which option is best for long tasks that run overnight? A server you control is the most predictable, because nothing pauses or sleeps. Cloud sessions work if the task keeps making progress, but idle VMs pause and can be reclaimed. Remote Control only works while your machine stays awake. ### Does Claude Code on the web work with GitLab or Bitbucket? Not fully. Cloning and pull requests in Anthropic-hosted environments require GitHub. You can send a non-GitHub repository as a local bundle, but the session cannot push results back to that remote. ### Can I use my Claude subscription on AlwaysAgent? Yes. You can sign in with your own account on your server, or use an API key, a relay, or OpenRouter instead. Using a key or gateway disables Remote Control, which needs a subscription login. --- # How to use an OpenRouter API key in Claude Code > OpenRouter has an official Claude Code integration. Four environment variables and a logout are all it takes. This guide covers the full config, verification, model switching, costs, troubleshooting, server setups, and the open-source Claude Code Router. Source: https://alwaysagent.app/claude-code-openrouter Updated: 2026-11-04 ## The short answer: four variables To use an OpenRouter API key in Claude Code, point `ANTHROPIC_BASE_URL` at `https://openrouter.ai/api`, put your key in `ANTHROPIC_AUTH_TOKEN`, set `ANTHROPIC_API_KEY` to an empty string, and log out of any Anthropic account. This is the setup described in OpenRouter's official Claude Code integration guide. `Terminal` ``` export OPENROUTER_API_KEY="" export ANTHROPIC_BASE_URL="https://openrouter.ai/api" export ANTHROPIC_AUTH_TOKEN="$OPENROUTER_API_KEY" export ANTHROPIC_API_KEY="" ``` - The base URL is `https://openrouter.ai/api`, with no `/v1`. - The key goes in `ANTHROPIC_AUTH_TOKEN`, which Claude Code sends as `Authorization: Bearer`. `ANTHROPIC_API_KEY` is sent as `x-api-key` and treated as a direct Anthropic credential, so it must stay blank. - Define `OPENROUTER_API_KEY` before the line that references it, or the token expands to nothing and you get an auth error. ## Shell variables or settings.json? Both work. Shell variables are the fastest way to try it; `settings.json` is better when you want the config to apply however `claude` is launched. ### Option 1: shell profile Add the exports above to `~/.zshrc`, `~/.bashrc`, or your fish config, then reload it with `source ~/.zshrc` or open a new terminal. OpenRouter also suggests an optional `CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY=1`, which turns on a gateway model picker (more on that below). ### Option 2: settings.json Claude Code reads an `env` block from its settings files. Use `~/.claude/settings.json` for all projects, or `.claude/settings.local.json` for one project. `~/.claude/settings.json` ``` { "env": { "ANTHROPIC_BASE_URL": "https://openrouter.ai/api", "ANTHROPIC_AUTH_TOKEN": "", "ANTHROPIC_API_KEY": "", "CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY": "1" } } ``` - Never put the key in a project's `.claude/settings.json`. Anthropic's docs warn that this file is committed and shared with everyone who clones the repo. - Don't rely on a project `.env` file. OpenRouter notes the native installer does not read it. - If the same variable is set both in your shell and in a settings `env` block, Anthropic's docs say the settings value applies. To avoid confusion, configure it in one place only. ## Step-by-step setup and verification The whole process takes a few minutes, and `/status` tells you whether it worked. 1. **Install Claude Code** — Use the native installer from Anthropic (`curl -fsSL https://claude.ai/install.sh | bash` on macOS, Linux, and WSL) or `npm install -g @anthropic-ai/claude-code`. 1. **Create an OpenRouter key** — Add credits and create an API key in your OpenRouter dashboard. 1. **Set the variables** — Use either option above, not both. 1. **Log out of Anthropic** — If you ever signed in with a claude.ai account, run `/logout`, quit, and start `claude` again. The gateway credential takes precedence over a saved login, but logging out avoids auth-conflict warnings. 1. **Check `/status`** — Run `claude`, then `/status`. You should see `Auth token: ANTHROPIC_AUTH_TOKEN` and `Anthropic base URL: https://openrouter.ai/api`. If the auth line names `ANTHROPIC_API_KEY` or a Claude account, reload your shell and restart `claude`. 1. **Send a prompt and check the dashboard** — Send any message. A normal reply confirms it works, and the request should appear in your OpenRouter Activity dashboard with the model name. ## How to choose and switch models Claude Code picks models by alias (`opus`, `sonnet`, `haiku`), and you can map each alias to an OpenRouter model ID with environment variables. Anthropic notes that `ANTHROPIC_BASE_URL` changes where requests go, not which model answers them, so the mapping is what decides the model. - **Inside a session:** `/model` opens the picker; `/model sonnet` switches immediately. - **At startup:** `claude --model opus` applies to that session only. - **Persistently:** set `"model"` in your settings file, or `ANTHROPIC_MODEL` in the environment. To pin which OpenRouter model each alias resolves to, set these in your shell or `env` block: `Terminal` ``` export ANTHROPIC_DEFAULT_OPUS_MODEL="" export ANTHROPIC_DEFAULT_SONNET_MODEL="" export ANTHROPIC_DEFAULT_HAIKU_MODEL="" export CLAUDE_CODE_SUBAGENT_MODEL="" ``` Use the exact IDs from the OpenRouter model list, because names and versions change often. OpenRouter's guide also documents "latest" style aliases for the Claude families; check its page for the current spelling. After setting them, open `/model` and confirm the expected entries appear, then check the model column in the OpenRouter dashboard. `ANTHROPIC_DEFAULT_HAIKU_MODEL` also covers background tasks, so pin it too if you want predictable costs. `ANTHROPIC_SMALL_FAST_MODEL` is deprecated. ### Gateway model picker With `CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY=1`, Claude Code asks the gateway for its model list at startup and adds those names to `/model`. OpenRouter says this shows a curated set of top-ranked models rather than the full catalog, and that pinning a model through the variables above bypasses it. Restart Claude Code to refresh the list. ### Context window OpenRouter's guide says Claude Code assumes a 200k context unless the model name ends in `[1m]`, and that OpenRouter strips the marker before routing. If your context seems stuck at 200k, add the suffix to model IDs that support 1M. ## Costs and credits With OpenRouter, you pay OpenRouter per token from your credit balance; there is no Claude subscription quota involved. Anthropic's docs confirm that once a gateway credential is set, requests no longer count against a claude.ai plan. - **Per-request view:** OpenRouter's Activity dashboard shows usage, cost, and the model for each request. - **Budgets:** OpenRouter says teams can set spending limits and allocate credits. Keep your balance topped up, since an empty balance shows up as request errors. - **In-terminal cost:** OpenRouter publishes an optional status line script (in its `openrouter-examples` repo, under `claude-code`) that shows session cost in Claude Code. It is configured through the `statusLine` entry in `~/.claude/settings.json`, and replaces any status line you already have. - **Prompt logging:** OpenRouter says prompts are not logged unless you opt in. ## Troubleshooting common errors Most failures come from a leftover credential, a blank-token expansion, or a model that does not behave like Claude. Work through these in order. | Symptom | Likely cause | Fix | | --- | --- | --- | | Auth error or invalid key | ANTHROPIC_API_KEY is not empty, or the token expanded to blank | Set ANTHROPIC_API_KEY="", define the key variable first, reload the shell, check /status | | Auth-conflict warning at startup | A saved claude.ai login plus a gateway credential | Run /logout, or unset the variable to go back to the login | | Still logged into Anthropic after /logout | A real ANTHROPIC_API_KEY is exported in your shell profile | /logout only clears the cached login, not shell variables; blank the variable and reload | | "Model not found" for a model ID | Auth conflict, or a wrong model ID | OpenRouter lists this as usually an auth conflict; fix auth first, then verify the ID in OpenRouter's model list | | 401 errors | Credential in the wrong variable | Use ANTHROPIC_AUTH_TOKEN for bearer-style gateways such as OpenRouter | | Asked to log in even though the key works | The env block is in a project settings file, which applies only after first-run setup and the trust prompt | Put it in ~/.claude/settings.json or a shell export | | Context stuck at 200k | Model ID lacks [1m] | Append [1m] on models that support it | | 400 errors about unrecognized fields | An upstream provider rejects fields Claude Code sends | Anthropic documents CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS=1 for this on gateways | > OpenRouter states Claude Code "is only guaranteed to work with the Anthropic first-party provider." Claude Code is built for Anthropic models, so routing to other providers or non-Anthropic models may not work correctly, including tool calling. Anthropic's own docs say it does not support routing Claude Code to non-Claude models through any gateway. Test any non-Claude model on a small task before relying on it. - Fast mode is only available when requests are routed to Anthropic first-party, and `/fast` through OpenRouter needs `CLAUDE_CODE_SKIP_FAST_MODE_ORG_CHECK=1` according to OpenRouter's guide. - OpenRouter can fail over between providers. If you need consistency, pin the provider with `provider.order` or `provider.only`; OpenRouter recommends making Anthropic first-party the top priority. - Using a gateway disables Anthropic's Remote Control and cloud sessions, which require a claude.ai login. ## Using it on a server or in the cloud On a remote machine the setup is the same, but the main risk is where your key ends up. Treat the OpenRouter key like a password, because anyone who holds it can spend your credits. - **Keep it out of git.** Use `~/.claude/settings.json` in your home directory or a shell profile, never a committed project file. If you use `.claude/settings.local.json`, add it to your gitignore first. - **Restrict file permissions.** Run `chmod 600 ~/.claude/settings.json` so other users on the machine cannot read it. - **Load from a secret store where you can.** OpenRouter suggests pulling the key from the OS keychain rather than hardcoding it. For CI, use your platform's secrets. - **Use settings.json for background processes.** Anthropic notes that shell-only exports do not reliably reach background agents, while a settings file does. - **CI example.** For the Claude Code GitHub Action, OpenRouter's guide stores the key as a secret, passes it as `anthropic_api_key` (only to satisfy the action's launch check), and sets `ANTHROPIC_BASE_URL` and `ANTHROPIC_AUTH_TOKEN` in the step's `env`. - **Anthropic's hosted cloud sessions will not use it.** They require a claude.ai login, and gateway variables set in their environment are not applied, so use your own server instead. - **Rotate on exposure.** If a key ever lands in a log, a screenshot, or a repo, delete it in OpenRouter and create a new one. ## Claude Code Router: what it is and when to use it Claude Code Router (CCR) is a separate open-source project that runs a local gateway between Claude Code and many model providers. It is not made by Anthropic or OpenRouter. The project's GitHub README ([musistudio/claude-code-router](https://github.com/musistudio/claude-code-router), MIT license) describes it as a local control plane for coding agents that gives supported agents one stable local endpoint. - **What it does:** you manage providers, models, accounts, and routing rules in one place. The README lists routing conditions, retries with ordered fallback models, and credential pools with key rotation. - **Providers:** it supports OpenAI-style, Anthropic Messages, and Gemini protocols, plus services such as OpenRouter, DeepSeek, Moonshot, and Z.AI, and custom compatible providers. - **Install:** the README gives `npm install -g @musistudio/claude-code-router` and then `ccr ui`, which opens a management UI locally. It requires Node.js 22 or newer, and a desktop app is also offered. Check the README for current steps. ### CCR vs. connecting directly to OpenRouter Direct OpenRouter is simpler: no extra process, four variables, and one provider's billing. CCR adds a layer you run and maintain, in exchange for flexibility. | | Direct to OpenRouter | Claude Code Router | | --- | --- | --- | | Setup | Environment variables only | Install and run a local service | | Providers | Whatever OpenRouter offers | OpenRouter and many other providers, mixed | | Routing rules, fallbacks | OpenRouter-side provider routing | Your own rules, configured locally | | Moving parts | None | A local gateway that must be running | Use direct OpenRouter if you want Claude models with minimal setup. Consider CCR if you want to send different tasks to different providers or keep several accounts behind one local endpoint. Remember that Anthropic does not support non-Claude models behind any gateway, so quality and tool-calling behavior are on you to test. ## Run it on AlwaysAgent AlwaysAgent gives you a dedicated Linux server with Claude Code and Codex preinstalled, so the "on a server" steps above are already done. Paste your OpenRouter key in settings and the workspace configures the variables for you. Your key stays on your server; we never proxy your requests or add a markup, and your tasks keep running after you close the browser. ## FAQ ### How do I use an OpenRouter API key in Claude Code? Set ANTHROPIC_BASE_URL to https://openrouter.ai/api, put your OpenRouter key in ANTHROPIC_AUTH_TOKEN, set ANTHROPIC_API_KEY to an empty string, run /logout if you were signed in to Anthropic, then restart claude and check /status. ### Why does Claude Code say my OpenRouter key is invalid? Usually ANTHROPIC_API_KEY isn't blank, the key variable was referenced before being defined so the token is empty, or an old Anthropic login is still active. Blank the API key, run /logout, restart, and check /status. ### Should I use ANTHROPIC_AUTH_TOKEN or ANTHROPIC_API_KEY for OpenRouter? Use ANTHROPIC_AUTH_TOKEN, which is sent as a Bearer token. OpenRouter's guide says ANTHROPIC_API_KEY must be explicitly empty, because it is sent as x-api-key and treated as a direct Anthropic credential. ### How do I switch models when using OpenRouter in Claude Code? Use /model in a session or claude --model at startup. To control which OpenRouter model each alias (opus, sonnet, haiku) uses, set the ANTHROPIC_DEFAULT_*_MODEL variables to IDs from the OpenRouter model list. ### Can I use non-Claude models through OpenRouter in Claude Code? You can point the model aliases at other models, but OpenRouter only guarantees Claude Code with the Anthropic first-party provider, and Anthropic doesn't support non-Claude models behind a gateway. Tool calling may break, so test before relying on it. ### How do I see how much Claude Code is costing on OpenRouter? Open the Activity dashboard on OpenRouter to see usage, cost, and model per request. OpenRouter also publishes an optional status line script that shows session cost inside Claude Code. ### What is Claude Code Router, and do I need it? Claude Code Router is a separate open-source local gateway that routes Claude Code to many providers with its own rules. You don't need it to use OpenRouter; connecting directly with environment variables is simpler. ### Can I use Codex with OpenRouter too? Codex uses its own config: define a custom provider in ~/.codex/config.toml with a base_url and env_key. AlwaysAgent sets up Claude Code and Codex separately. --- # How to use Claude Code from your phone > Claude Code does not run directly on iOS or Android. Every mobile setup uses your phone as a remote screen for a session running on your laptop, an Anthropic cloud VM, or a Linux server. Source: https://alwaysagent.app/claude-code-phone Updated: 2026-11-05 ## The short answer You can use Claude Code from your phone in four ways: Anthropic's official Remote Control, Anthropic's official cloud sessions, your own machine or VPS over SSH and `tmux`, or a managed server with a browser workspace. As Anthropic's documentation notes, "The Claude app for iOS and Android is a client for Claude Code sessions rather than a place where code runs." Pick your setup by answering four questions about how you work: - **Can your laptop stay on and awake?** If yes, use **Remote Control** to steer your local terminal session from the Claude mobile app. - **Do you have a paid Claude subscription and keep code on GitHub?** If your laptop will be closed, use **Cloud sessions** in the Claude app or at `claude.ai/code`. - **Do you use an API key, OpenRouter, or a third-party model gateway?** Official mobile features require a `claude.ai` subscription login. You will need a **self-hosted SSH server** or a **managed server**. - **Do you need unattended, long-running tasks?** Cloud sessions stop after a period of inactivity, and laptops sleep. For jobs that run for hours or need background databases and Docker, run Claude Code on an **always-on Linux server**. For a deep architecture comparison between Anthropic's two official modes and a dedicated server, see [Claude Code Remote Control vs cloud sessions vs your own server](/claude-code-cloud-vs-alwaysagent). This guide focuses on setting up and using each option on a phone. ## Remote Control (best if your laptop stays on) Remote Control links the Claude mobile app or mobile web browser to a Claude Code process running on your own computer. ### How it works According to Anthropic's docs, "When you start a Remote Control session on your machine, Claude keeps running locally the entire time, so your code execution and filesystem access stay on your machine." Your phone acts as a synchronized window into that terminal session. 1. **Install the Claude mobile app** — Download the Claude app for iOS or Android. Inside an active terminal session, you can run `/mobile` (or `/ios` or `/android`) to print a QR code that opens the app store for your phone. 1. **Start Remote Control on your computer** — Open a terminal in your project folder and run server mode to wait for remote connections, or turn on Remote Control inside an existing session:# Start server mode (press spacebar to toggle the QR code) claude remote-control # Or start an interactive session with Remote Control enabled claude --remote-control # Or enable it inside an already open session /remote-control - ### Connect from your phone Scan the QR code shown in your terminal, or open the Claude app, tap the **Code** tab, and select your session. Online Remote Control sessions display a computer icon with a green status dot. ### What you need You need a Pro, Max, Ultra, Team, or Enterprise plan signed in with a `claude.ai` account, plus your computer running the `claude` CLI over outbound HTTPS. Per Anthropic's documentation, API keys, Amazon Bedrock, Google Vertex, and custom `ANTHROPIC_BASE_URL` gateways are not supported. ### Limits "The web and mobile interfaces are a window into that local session, so your computer has to stay on and the claude process has to keep running." - If your computer loses network access for roughly ten minutes in server mode, the process times out and exits. - Terminal-only slash commands such as `/plugin` and `/resume` cannot be triggered from the mobile app, and you cannot switch to Bypass permissions from the phone. ### Phone experience Because you use the native Claude iOS or Android app, typing prompts, reading diffs, and answering permission requests works smoothly on a touchscreen. Typing `@` autocompletes file paths from your local project. You can also attach photos from your phone camera roll directly into the chat. ## Cloud sessions on the web and app (best for GitHub tasks with laptop closed) Cloud sessions run Claude Code on Anthropic-managed virtual machines instead of your computer, allowing you to start or monitor work from your phone with no home machine left on. ### How it works When you submit a task from the **Code** tab in the Claude mobile app or at [claude.ai/code](https://claude.ai/code), Anthropic clones your GitHub repository into an isolated VM, runs your setup script if configured, edits files, runs tests, and pushes a branch for review. You can also start a task from your laptop terminal with `claude --cloud "your task"` and check on it later from your phone, or pull a cloud session back to your terminal using `claude --teleport`. ### What you need You need a Pro, Max, Ultra, or Team plan, or an Enterprise seat with Claude Code access, signed in to `claude.ai`, plus a connected GitHub account. As Anthropic states, "Cloud sessions and Remote Control require a claude.ai account, so they aren't reachable with an Anthropic Console API key or from a third-party provider such as Amazon Bedrock." There is no separate fee for the cloud VM; usage counts against your plan's standard limits. ### Limits - GitHub is required for direct cloud cloning and pull request creation. Non-GitHub repositories can only be uploaded from a local machine as a bundle and cannot push back to the remote. - Outbound network access from the VM is restricted to a default allowlist unless you configure custom domains. - Cloud sessions stop after a period of inactivity and the VM is reclaimed. Reopening an expired session provisions a fresh VM and restores the chat history, but any background shell commands or subagents that were running are lost. ### Phone experience Like Remote Control, cloud sessions live inside the **Code** tab of the Claude app and the mobile web interface at `claude.ai/code`. Because the session keeps running after you put your phone away, it is practical to hand off a self-contained GitHub issue and check back on it later from your phone. ## Self-hosted PC or VPS + SSH + tmux (best for full DIY control) Before official mobile clients existed, running Claude Code inside a persistent terminal multiplexer over SSH was the standard way to code from a phone. It remains a common choice if you want full operating system control or use API credentials that Anthropic's mobile app does not accept. ### How it works You install Claude Code on a home desktop or a rented Linux VPS (see [running Claude Code on a VPS](/claude-code-vps)). To reach a home machine without opening router ports, many developers install a mesh VPN such as Tailscale on both the computer and the phone. Before launching `claude`, you start a `tmux` or `screen` session so the process stays alive when your phone locks or switches networks: # On your server or desktop over SSH tmux new -s work claude # Later, after reconnecting from your phone's SSH app tmux attach -t work ### What you need You need a Linux or macOS host that stays powered on, an SSH server, `tmux`, an iOS or Android SSH client (or Mosh for roaming connections), and any credentials Claude Code supports—including a `claude.ai` subscription, an Anthropic Console API key, or a custom gateway via `ANTHROPIC_BASE_URL`. ### Limits - **Touchscreen keyboard friction:** Standard terminal shortcuts like `Escape`, `Ctrl+C`, `Ctrl+B` (for `tmux`), and arrow keys require extra virtual keyboard bars on a phone. - **Background disconnects:** Mobile operating systems aggressively suspend background sockets. Every time you switch to a browser or lock your phone for a few minutes, the SSH connection drops and you have to reconnect. - **No native file or preview UI:** Scrolling back through long diffs inside `tmux` on a 6-inch screen is cramped, and viewing a running web server requires manual port forwarding or VPN configuration. - **Sysadmin overhead:** You are responsible for OS updates, SSH keys, firewall rules, and disk space. ### Phone experience A raw SSH client works in an emergency—such as approving a blocked prompt or running `git status`—but reading multi-file diffs or pasting screenshots into a terminal from a phone is slow. Some open-source community projects, such as Happy (`slopus/happy`) and CC Pocket (`K9i-0/ccpocket`), wrap local Claude Code and Codex CLI processes on your machine so you can interact with them through a dedicated mobile chat UI instead of raw SSH. ## Managed server: AlwaysAgent (best for 24/7 runs and any API key without SSH) If you want an always-on Linux server and support for API keys or third-party models, but do not want to manage a VPS or fight an SSH terminal on a touchscreen, AlwaysAgent packages the server and a browser workspace together. ### How it works AlwaysAgent ([alwaysagent.app](https://alwaysagent.app)) provisions a dedicated cloud Linux server with a standalone public IP for each user, with both Claude Code and OpenAI Codex preinstalled. Instead of connecting via an SSH app, you open the workspace in your phone or desktop browser. The workspace includes AI chat, a file manager, a terminal, remote browser preview, and version history. Because the server runs 24/7 in the cloud, tasks continue running after you close your laptop or mobile browser. ### What you need You only need a web browser on your phone or computer and your own model credentials. In the workspace settings, you can configure a Base URL and API Key—supporting official Anthropic or OpenAI keys, Chinese domestic model APIs, relay services, or OpenRouter. Keys are stored only on your dedicated server; AlwaysAgent does not proxy AI calls, add markup, or resell model quota. ### Limits - Because you are renting a dedicated virtual machine, the server costs money separately from your AI usage. Hourly trials start with a $10 minimum top-up at roughly $0.05/hour (stopped servers still accrue charges until deleted; unused balance is refundable within 14 days minus payment processing fees). Monthly plans with unlimited bandwidth and daily auto-snapshots range from Starter at $9.9/mo (2 vCPU, 4 GB RAM, 40 GB disk) and Developer at $17.9/mo (4 vCPU, 8 GB RAM, 75 GB disk) to Pro at $24.9/mo and Power at $44.9/mo. - It is a browser-based web workspace rather than a native App Store application, so there is no app to install on your phone. ### Phone experience You open the workspace URL in Safari or Chrome on your phone with no app or VPN to install. You can read replies in the chat view, inspect files, preview a running web app through the remote browser preview, and drop into the web terminal only when you need to run a shell command. ## Comparing the 4 mobile setups | Dimension | Remote Control | Cloud sessions | Self-hosted + SSH | AlwaysAgent | | --- | --- | --- | --- | --- | | Runs where | Your computer | Anthropic-managed VM | Your PC or VPS | Dedicated cloud Linux server | | Laptop must stay on | Yes | No | Only if hosted on laptop (No on VPS) | No | | Needs Claude subscription | Yes (claude.ai) | Yes (claude.ai) | Optional | Optional | | API key / other models | No | No | Yes | Yes (Base URL + API Key) | | Unattended long runs | While machine stays awake | Stops after inactivity; VM can expire | Yes (inside tmux) | Yes (24/7 server) | | Setup effort | Run 1 CLI command + app | Connect GitHub in app/web | Install OS, SSH, tmux, VPN | None (preinstalled) | | Phone UX | Native Claude app / web | Native Claude app / web | Mobile SSH terminal | Mobile browser workspace | ## Making Claude Code usable on a phone A phone screen is great for reviewing plans, answering questions, and kicking off well-scoped tasks, but miserable for micromanaging syntax. A few habits make mobile sessions much smoother: - **Put rules and test commands in `CLAUDE.md` at your desk.** Before you leave your laptop, make sure your repository's `CLAUDE.md` documents how to run tests, lint, and build. That way, you do not have to type shell commands or path names on a phone keyboard. - **Ask for a plan before code edits.** When starting a task from your phone, tell Claude to inspect the relevant files and propose a short implementation plan first. Reading and approving a 5-bullet plan on a phone is much easier than untangling a wrong 400-line diff. - **Write self-contained prompts that include verification.** Instead of back-and-forth steering, give a single clear goal and tell Claude how to verify its own work—for example: "Fix the null check in the checkout handler, add a unit test, and run the test suite until it passes." - **Tell Claude to work on a separate branch and commit checkpoints.** Especially during long or unattended runs, instruct Claude to create a feature branch and commit after each passing step so you can inspect clean diffs or roll back easily. - **Use voice dictation for natural-language prompts.** Built-in iOS and Android voice dictation is much faster than thumb-typing when explaining bug symptoms or architectural constraints, since you are writing English instructions rather than raw code. - **Send screenshots instead of describing UI bugs.** In Remote Control, cloud sessions, and browser workspaces, attaching a phone screenshot of a visual bug or error log is faster and more accurate than retyping the error message. ## FAQ ### Does Claude Code have a dedicated iPhone or Android app? No. As Anthropic's documentation explains, Claude Code does not have a separate mobile app. Both cloud sessions and Remote Control live inside the Code tab of the standard Claude app for iOS and Android, or at claude.ai/code in a mobile browser. ### How do I keep Claude Code running when I close my laptop? You have to run the session somewhere other than your laptop. You can use Anthropic's cloud sessions (which run on Anthropic-managed VMs for GitHub repositories), rent your own Linux VPS and run Claude Code inside tmux, or use a 24/7 managed server such as AlwaysAgent. ### Why does Remote Control disconnect when I step away with my phone? Remote Control only provides a window into the claude process on your computer. If your laptop goes to sleep, closes its lid, loses Wi-Fi for an extended period, or has its terminal window closed, the session goes offline until the computer wakes up or you restart the command. ### Can I use Claude Code on my phone with an Anthropic API key or OpenRouter? Not through the official Claude mobile app. Both Remote Control and official cloud sessions require a claude.ai subscription login and are not available with Anthropic Console API keys or third-party providers such as Amazon Bedrock. Remote Control is also unavailable when ANTHROPIC_BASE_URL points at a gateway or proxy. To use an API key or OpenRouter from your phone, run Claude Code on your own server over SSH or in a browser workspace like AlwaysAgent. ### What is the easiest way to get the Claude app link from my terminal? Inside any open Claude Code terminal session, run /mobile (or /ios or /android). The CLI prints a QR code for claude.ai/mobile that opens the matching app store on your phone. ### Can I start a task on my laptop and switch to my phone mid-conversation? Yes. If the session is running locally on your computer and you can leave the computer on, type /remote-control (or /rc) in the conversation and open the session from the Code tab in the Claude mobile app. If you need to close your laptop, push your branch to GitHub and start a cloud session with claude --cloud, or run your workflow on an always-on server. --- # How to run Claude Code on a VPS (24/7, from your phone) > A small Linux server, the official installer, and tmux are enough to keep Claude Code working after you close your laptop. Here is the whole setup, including phone access and security. Source: https://alwaysagent.app/claude-code-vps Updated: 2026-11-04 ## Why run Claude Code on a server A server removes the laptop from the loop: the session keeps running when your computer sleeps, closes, or loses Wi-Fi, and you can check on it from anywhere. Claude Code is a terminal program. It runs on the machine where you start it, so when that machine goes to sleep or shuts down, the task stops with it. Putting it on an always-on Linux box fixes three things at once: - **Tasks don't get interrupted.** Long refactors, test loops, and migrations finish while you are away. - **You can reach it from a phone or any other computer.** The session lives on the server, not on one device. - **Your computer can be off.** Nothing depends on a laptop lid staying open. Anthropic's hosted options have limits. Per its documentation, Remote Control sessions run on your machine, so "your computer has to stay on." Cloud sessions (Claude Code on the web) require a claude.ai account and don't accept API keys or third-party providers. A server you control has neither restriction. ## Pick the right server Choose a regular Linux VPS with at least 4 GB of RAM, 2 vCPUs, and enough disk for your repositories; anything smaller will make you fight the installer. Anthropic's system requirements list Ubuntu 20.04+, Debian 10+, or Alpine 3.19+, a 4 GB+ RAM machine with an x64 or ARM64 processor, and an internet connection. Beyond that, size the machine for your builds, test suites, and containers rather than for Claude Code itself. | Workload | Starting point | | --- | --- | | Scripts, small web apps, light refactors | 2 vCPU, 4 GB RAM, 40 GB disk | | Full-stack projects with a database or Docker | 4 vCPU, 8 GB RAM, 75 GB+ disk | | Heavy builds, several parallel sessions | 6+ vCPU, 12 GB+ RAM, 100 GB+ disk | Practical advice for choosing a provider: - **Use a mainstream distribution.** Ubuntu LTS or Debian match the commands in this guide. - **Check the region.** Claude Code is only available in [Anthropic's supported countries](https://www.anthropic.com/supported-countries), and a server in an unsupported location can fail at sign-in or return 403 errors. - **Mind hourly versus monthly billing.** Some providers keep charging for a powered-off server. Check before you "stop" an instance to save money. ## Create a non-root user first Do all your work as a normal user with sudo rights, not as root, so a mistake or a bad command has a smaller blast radius. Log in once as root (or the default user your provider created), then run the following. Replace `dev` with any username. `On the server, as root` ``` # Create the user (Debian/Ubuntu) adduser dev usermod -aG sudo dev ``` Then, from your own computer, copy your SSH public key to the new user so you can log in without a password: `On your computer` ``` ssh-copy-id dev@YOUR_SERVER_IP ssh dev@YOUR_SERVER_IP ``` If you have no key pair yet, run `ssh-keygen -t ed25519` first and keep the private key on your machine only. ## Install Claude Code Use Anthropic's native installer; it needs no Node.js, installs to your home directory, and updates itself in the background. `On the server, as your normal user` ``` curl -fsSL https://claude.ai/install.sh | bash claude --version ``` The installer shows no progress while it downloads. Afterwards, `claude --version` should print a version number, and `claude doctor` runs a read-only health check. Two alternatives from the official setup guide: - **apt, dnf, or apk.** Anthropic publishes signed repositories; updates come through normal system upgrades. - **npm.** `npm install -g @anthropic-ai/claude-code` works and needs Node.js 22 or later. Anthropic says not to use `sudo` for it. It installs the same native binary, so you only need Node for your own projects. ## Sign in: subscription or API key You can authenticate with a claude.ai subscription or with an Anthropic Console API key; pick based on how you want to pay. ### Option A: subscription login Run `claude` and follow the prompts. On a server there is no browser, so copy the login URL (press `c` in the prompt to copy it, or select it), open it in the browser on your own computer, sign in, and paste the code it shows back into the terminal at the `Paste code here` prompt. If pasting into the interactive prompt does nothing, Anthropic suggests running `claude auth login` instead, which reads the code from standard input. Claude Code requires a Pro, Max, Ultra, Team, Enterprise, or Console account; the free claude.ai plan does not include it. For unattended scripts, `claude setup-token` generates a one-year OAuth token for `CLAUDE_CODE_OAUTH_TOKEN`; Anthropic notes it can't establish Remote Control sessions. ### Option B: API key Set `ANTHROPIC_API_KEY` to a key from the Claude Console and Claude Code bills you per token instead of using your subscription. In interactive mode you approve the key once. Anthropic's docs state the key is used instead of your subscription "even if you are logged in," so run `unset ANTHROPIC_API_KEY` to go back. The cleanest place to store it is the `env` block of `~/.claude/settings.json`: `~/.claude/settings.json` ``` { "env": { "ANTHROPIC_API_KEY": "YOUR_API_KEY" } } ``` Never put credentials in a project's committed `.claude/settings.json`; Anthropic warns that file is shared with everyone who clones the repository. Run `/status` inside Claude Code to confirm which credential is active. For gateways, relays, and OpenRouter, see our guide on [using Claude Code with your own API key](/claude-code-api-key). ## Keep sessions alive with tmux Run Claude Code inside tmux, because a plain SSH session kills your process the moment the connection drops. tmux keeps terminals running on the server and lets you detach and reattach from any device. Anthropic's own Remote Control docs give the same advice: if you run `claude` from a terminal on a remote machine, start it inside `tmux` or `screen` so it survives an SSH disconnect. `tmux basics` ``` sudo apt install tmux # Debian/Ubuntu tmux new -s work # create a named session and attach claude # start Claude Code inside it # press Ctrl+b, then d, to detach tmux ls # list sessions tmux attach -t work # reattach later ``` The default prefix key is `Ctrl+b`: press it, release, then press the next key. `tmux new -A -s work` attaches if the session exists and creates it if not, handy as one command from a phone. tmux survives disconnects but not a server reboot; after a restart, just run `tmux new -A -s work` again. ## Use it from your phone There are three realistic ways to reach a server-hosted session from a phone: SSH through a terminal app, Anthropic's Remote Control, or a browser workspace. Each trades convenience against setup effort. ### SSH app plus tmux Install an SSH client on your phone, add your private key, connect to the server, and run `tmux new -A -s work`. Termux (Android) and Blink Shell or Prompt (iOS) are commonly used. You get the full CLI, but typing is slow, so keep prompts short and lean on the approve-or-reject flow. ### Tailscale for private access Tailscale creates a private network between your devices, so you don't have to expose SSH to the public internet at all. Install it on the server and on your phone, sign in to the same account, and connect using the server's Tailscale name. `On the server` ``` curl -fsSL https://tailscale.com/install.sh | sh sudo tailscale up ``` Tailscale also offers [Tailscale SSH](https://tailscale.com/kb/1193/tailscale-ssh), enabled with `tailscale set --ssh`. Connections over your tailnet are authenticated by Tailscale instead of SSH keys, and it leaves your regular `sshd` configuration untouched. It requires an access-control policy that allows SSH to the machine; the default policy covers your own devices. Once it works, you can close port 22 to the public internet. ### Remote Control Anthropic's Remote Control lets the Claude mobile app or claude.ai/code drive a session running on your server. Start it with `claude remote-control` (server mode) inside tmux, then connect from the app using the URL or QR code it prints. It only makes outbound HTTPS requests and never opens inbound ports. The limits matter: it requires a claude.ai subscription login (API keys are not supported), it is disabled if `ANTHROPIC_BASE_URL` points anywhere other than `api.anthropic.com`, and the `claude` process must stay running. If you pay per token or use a gateway, use SSH or a browser workspace instead. ## Lock the server down A fresh VPS is scanned by bots within minutes, so the minimum is key-only SSH, a firewall, fail2ban, and a non-root user. - **Keys only.** After confirming key login works in a second terminal, disable passwords and root login in `/etc/ssh/sshd_config`: `/etc/ssh/sshd_config` ``` PasswordAuthentication no KbdInteractiveAuthentication no PermitRootLogin no ``` Check the config with `sudo sshd -t`, then restart the SSH service (the unit is `ssh` on Debian/Ubuntu, `sshd` on many other distributions). Some distributions ship drop-in files that override the main file, so verify the effective values with `sudo sshd -T | grep -i -E "passwordauth|permitroot"`. Keep your current session open until a new login works. - **Firewall.** On Ubuntu, ufw is disabled by default but defaults to denying incoming traffic once enabled. Allow SSH first, or you will lock yourself out: `ufw` ``` sudo ufw allow 22/tcp sudo ufw enable sudo ufw status ``` Open 80 and 443 only if you serve a website. - **fail2ban.** It scans logs such as `/var/log/auth.log` for IPs with repeated failed logins and blocks them for a period. Install with `sudo apt install fail2ban` and check its jails with `sudo fail2ban-client status`. - **Don't run as root.** Use your normal user for Claude Code. Review permission prompts instead of blanket-approving commands. - **Protect secrets.** Keep API keys in `~/.claude/settings.json` or environment files readable only by you (`chmod 600`), never in git. Claude Code stores subscription credentials in `~/.claude/.credentials.json` with mode 0600 on Linux. Use a deploy key or scoped token for git. - **Keep it updated.** Native installs update Claude Code automatically; for the OS, enable unattended security updates (`unattended-upgrades` on Debian/Ubuntu). ## Estimate the cost Your total is the server rental plus model usage, and they scale differently: the server is a flat rate, while model usage depends on how much you run. - **Server.** Multiply the hourly or monthly price by how long it exists, not by how long you use it. Some providers bill powered-off servers, so check. - **Model usage.** With a subscription, usage counts against your plan's limits. With an API key, you pay per token, so heavy autonomous runs can cost more than the server itself. Snapshots, extra disk, and bandwidth can add to the bill. To estimate, run your real workflow for a week, record the server and model bills separately, and extrapolate. ## Troubleshooting Most problems on a new server are PATH, memory, or login issues, and each has a documented fix. - **`claude: command not found` after install.** The installer places the binary at `~/.local/bin/claude`. Add it to your PATH and reload your shell: `echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.bashrc && source ~/.bashrc`. - **`Killed` during install (exit code 137).** The server ran out of memory. Add swap (Anthropic's guide shows a 2 GB swap file with `fallocate`, `mkswap`, and `swapon`) or move to a larger plan, then rerun the installer. - **Install script returns HTML or a 403.** Usually a proxy, a network filter, or an unsupported region. Set `HTTPS_PROXY` if you are behind a proxy. - **OAuth error: Invalid code.** The code expired or was truncated. Retry quickly and copy the whole URL with `c`. - **Login expired or auth errors.** Run `/login` again, check the server clock, and use `/status` to see whether `ANTHROPIC_API_KEY` is overriding your subscription. - **Session gone after reconnecting.** You ran `claude` outside tmux; start it inside a tmux session next time. - **Remote Control won't start.** Check the login and base URL limits above, then run `claude remote-control --verbose`. ## Skip the setup: use AlwaysAgent If you want the outcome without the server administration, AlwaysAgent gives you the same thing, a dedicated Linux server with Claude Code already installed, behind a browser tab. You get one dedicated US Linux server with full root access, Claude Code and OpenAI Codex preinstalled, and a browser workspace with chat, files, terminal, and preview. No SSH client or app is needed, so a phone browser works, and tasks keep running when you close the tab. - **Bring your own access.** Use your subscription login, an Anthropic API key, OpenRouter, or a relay. Credentials stay on your server, and AlwaysAgent doesn't proxy model calls or add token markup. - **Simple pricing.** Hourly use is about $0.05 per hour after a $10 top-up, with no auto-renewal. Monthly plans start at $9.9 for 2 vCPU, 4 GB RAM, and 40 GB NVMe, and you can upgrade from hourly to monthly while keeping your files. - **You still own the machine.** It has root, Docker, its own public IP, and can serve websites on ports 80 and 443. Hourly billing continues while the server exists, even when powered off, until you delete it. AlwaysAgent is an independent product and is not affiliated with Anthropic or OpenAI. If you would rather self-host, everything above works on any VPS. If you would rather start in a minute, [compare the options](/claude-code-cloud-vs-alwaysagent) and try it. ## FAQ ### Can I run Claude Code on a VPS 24/7? Yes. Install it on an always-on Linux server, start it inside tmux, and the session keeps running after you disconnect. Claude Code itself stays idle while waiting for you, so the cost is the server plus whatever model usage you trigger. ### How much RAM does Claude Code need on a server? Anthropic's system requirements list 4 GB or more of RAM. The installer needs about 512 MB of free memory, and small instances can kill it, so add swap or pick a bigger plan. Size beyond that for your own builds and containers. ### Can I use Claude Code from my phone if it runs on a server? Yes. Connect with an SSH app and attach to tmux, use Tailscale for private access, or use Anthropic's Remote Control, which requires a claude.ai subscription login. A browser workspace like AlwaysAgent also works from a phone without any app. ### Does Claude Code on a VPS work with an API key? Yes. Set ANTHROPIC_API_KEY, preferably in the env block of ~/.claude/settings.json. Anthropic's cloud sessions and Remote Control don't support API keys, which is a main reason to use your own server. ### Do I need Node.js to run Claude Code? Not with the native installer. The npm package needs Node.js 22 or later, but it installs the same native binary, so you only need Node for your own projects. ### How do I sign in to Claude Code on a server with no browser? Run claude, copy the login URL (press c), open it in a browser on your own computer, sign in, and paste the code back into the terminal. If paste fails, use claude auth login. For unattended jobs, claude setup-token creates a long-lived token. ### Is it safe to run Claude Code on a public server? It can be, if you harden it: key-only SSH, no root login, a firewall, fail2ban, secrets stored with strict permissions, and a non-root user. Putting SSH behind Tailscale removes public exposure entirely. ### Is a VPS cheaper than a managed option? It depends on usage. A VPS is a flat rate that bills while it exists. Hourly managed servers can be cheaper if you only need one occasionally, and monthly plans suit constant use. Compare the real monthly total, not the headline rate. --- # Claude Code 国内怎么用? > Claude Code 是一个在终端里干活的 AI 编程助手,它本身不绑定模型。国内用户最省事的做法,是给它接上国产大模型或中转站——改两个环境变量就行。 Source: https://alwaysagent.app/zh/claude-code-china 更新于: 2026-10-25 ## 国内用 Claude Code 难在哪 Claude Code 分成两部分:一个是装在电脑或服务器上的命令行程序 `claude`,另一个是它背后调用的大模型。国内用户卡住,通常卡在后者:Anthropic 官方的 Claude 账号和 API 不对中国大陆提供服务。 但 Claude Code 允许把请求发到别的接口。只要接口兼容 Anthropic 的格式,`claude` 就能照常读代码、改文件、跑命令。所以国内的用法就是:**程序还是 Claude Code,模型换成你能用的。** ## 两种常见接法 - **国产大模型** (`厂商官方接口`): DeepSeek、Kimi、智谱、通义千问、MiniMax 都有官方的 Claude Code 接入文档,人民币充值。 - **中转站** (`第三方 Base URL`): 转发到各家模型,一个 Key 用多个模型。选择时注意稳定性和数据安全。 两种接法的配置方式一样:告诉 Claude Code 往哪个地址发请求(`ANTHROPIC_BASE_URL`),以及用哪个密钥(`ANTHROPIC_AUTH_TOKEN`)。 ## 国产模型的接口地址 下面的地址都来自各厂商官方的「在 Claude Code 中使用」文档(2026 年 10 月核对)。模型名更新很快,填之前请以官方文档为准。 | 厂商 | ANTHROPIC_BASE_URL | 官方文档 | | --- | --- | --- | | DeepSeek | https://api.deepseek.com/anthropic | [DeepSeek 文档](https://api-docs.deepseek.com/zh-cn/quick_start/agent_integrations/claude_code) | | 智谱 GLM(国内站) | https://open.bigmodel.cn/api/anthropic | [智谱文档](https://docs.bigmodel.cn/cn/coding-plan/tool/claude) | | Kimi(月之暗面) | https://api.moonshot.ai/anthropic | [Kimi 文档](https://platform.kimi.ai/docs/guide/claude-code-kimi) | | 通义千问(阿里云百炼) | 按地域和套餐不同,地址里带你的 Workspace ID | [百炼文档](https://help.aliyun.com/zh/model-studio/claude-code) | | MiniMax | https://api.minimax.io/anthropic | [MiniMax 文档](https://platform.minimax.io/docs/token-plan/claude-code) | > 这些兼容接口由各模型厂商自己提供。Anthropic 官方不维护、也不保证 Claude Code 在非 Claude 模型上的效果,个别功能可能表现不同。 ## 配置步骤(以 DeepSeek 为例) 1. **在厂商平台创建 API Key** — 到 DeepSeek 开放平台充值并创建一个 Key。其他厂商同理。 1. **写进 Claude Code 的设置文件** — 打开 `~/.claude/settings.json`(没有就新建),在 `env` 里填地址、密钥和模型。这样不管从哪里启动 `claude` 都会生效。 1. **重新打开 Claude Code 并检查** — 输入 `/status`,能看到 Anthropic base URL 和 Auth token 两行,就说明接上了。 `~/.claude/settings.json` ``` { "env": { "ANTHROPIC_BASE_URL": "https://api.deepseek.com/anthropic", "ANTHROPIC_AUTH_TOKEN": "你的 DeepSeek API Key", "ANTHROPIC_MODEL": "deepseek-flash[1m]", "ANTHROPIC_DEFAULT_HAIKU_MODEL": "deepseek-flash" } } ``` 换成别的厂商,只需把地址、Key 和模型名换成该厂商文档里的值。密钥放在 `ANTHROPIC_AUTH_TOKEN`,这是 Claude Code 官方推荐的写法;不要把它写进项目里会提交到 Git 的 `.claude/settings.json`。 ## 在 AlwaysAgent 上怎么用 AlwaysAgent 给你一台独立的美国 Linux 服务器,Claude Code 和 Codex 已经装好。你在浏览器里打开工作台,在设置里粘贴 Base URL 和 Key,就能开始对话。密钥只保存在你自己的服务器上,平台不经手你的模型调用,也不加价。 - 不用在自己电脑上装 Node.js、配环境。 - 合上电脑任务照跑,手机浏览器打开就能接着看。 - 国产模型、中转站、OpenRouter 都能填,换模型不用重装。 ## 常见问题 ### Claude Code 接国产模型,效果和原版一样吗? 不完全一样。Claude Code 的流程(读文件、改代码、跑命令)不变,但写代码的能力取决于你接的模型。建议先用小任务试,再决定主力用哪个。 ### ANTHROPIC_AUTH_TOKEN 和 ANTHROPIC_API_KEY 有什么区别? 前者以 Bearer 方式发送,后者以 x-api-key 方式发送。国产厂商和大多数中转站的 Claude Code 文档都用 ANTHROPIC_AUTH_TOKEN;不确定时,Claude Code 官方也建议用它。 ### 配好了还是报 401 错误怎么办? 先确认 Key 没有多余空格、对应的是同一个平台;再检查是不是同时设置了 ANTHROPIC_API_KEY,或者之前登录过 Claude 账号——可以在 Claude Code 里执行 /logout 后重开。 ### 服务器在美国,能连国产模型的接口吗? 可以。上面列出的都是公网接口。部分厂商分国内站和国际站(比如智谱的 open.bigmodel.cn 和 api.z.ai),Key 不通用,填你开通账号的那个站点。 --- # 手机怎么用 Claude Code? > Claude Code 没有单独的手机 App。想在手机上用,要么让手机遥控你电脑上的 Claude Code,要么把它放到一台一直开着的云服务器上。 Source: https://alwaysagent.app/zh/claude-code-phone 更新于: 2026-10-25 ## 官方方案:Remote Control Anthropic 官方的做法是 Remote Control:在你的电脑上运行 Claude Code,再用 Claude App 的 Code 页面或 claude.ai/code 远程查看和发消息。官方文档写得很清楚: - **需要 Claude 订阅**(Pro、Max、Team 或 Enterprise),**不支持 API Key**。 - **电脑必须一直开着**,`claude` 进程也要一直运行。手机只是一个查看窗口。 - 如果你把 `ANTHROPIC_BASE_URL` 指向中转站或国产模型,Remote Control 就不能用了。 官方另有在 Anthropic 云上运行的「云端会话」,电脑关了也能跑,但同样只能用 Claude 订阅登录,不能接 API Key 或第三方接口。 ## 另一种方案:放在云服务器上 把 Claude Code 装在一台一直开着的云服务器上,手机通过浏览器连上去。这样: 1. **电脑可以关** — 任务在服务器上跑,和你的电脑、手机都没关系。 1. **模型随便接** — 官方账号、自己的 API Key、中转站、国产模型都可以。 1. **哪台设备都能接着看** — 在电脑上发出的任务,出门后用手机打开同一个工作台继续。 自己搭的话,需要租服务器、装 Node.js 和 Claude Code、配好远程访问和登录保护,再处理断线重连。AlwaysAgent 把这些都做好了。 ## 两种方案对比 | | 官方 Remote Control | AlwaysAgent 云服务器 | | --- | --- | --- | | 电脑需要一直开着 | 需要 | 不需要 | | 可用自己的 API Key | No | Yes | | 可接中转站 / 国产模型 | No | Yes | | 需要 Claude 订阅 | 需要 | 不需要(有订阅也能登录) | | 同时用 Codex | No | Yes | | 费用 | 含在 Claude 订阅里 | 服务器费用,按小时 $0.05 起 | > 如果你已经有 Claude 订阅、电脑也能一直开着,官方 Remote Control 是免费又省事的选择。需要接自己的 Key、或者不想让电脑一直开机,再考虑云服务器。 ## 常见问题 ### Claude Code 有官方手机 App 吗? 没有单独的 App。官方的手机用法是 Claude App 里的 Code 页面,用来连接云端会话或你电脑上的 Remote Control 会话。 ### 手机上用 AlwaysAgent 需要装 App 吗? 不需要。手机或 iPad 的浏览器打开 alwaysagent.app 登录即可,和电脑上是同一个工作台。 ### 手机网络断了,任务会中断吗? 不会。任务在服务器上运行,手机断网只是暂时看不到进度,重新打开页面就能接着看。 --- # Claude Code 中转站怎么配置? > 买了中转站的 Key,只需要告诉 Claude Code 两件事:请求发到哪个地址,用哪个密钥。下面是完整步骤和最常见的几个坑。 Source: https://alwaysagent.app/zh/claude-code-relay 更新于: 2026-10-25 ## 中转站是什么 中转站是第三方提供的 API 转发服务:你向它充值,它给你一个 Base URL(接口地址)和一个 Key。Claude Code 把请求发给中转站,由中转站转给背后的模型。 > 中转站会经手你的全部对话和代码。请选择口碑好、长期运营的服务,不要在上面处理敏感代码或密钥。 ## 两个关键变量 - **接口地址** (`ANTHROPIC_BASE_URL`): 中转站给你的地址,通常不带 /v1 结尾,以中转站说明为准。 - **密钥** (`ANTHROPIC_AUTH_TOKEN`): 中转站给你的 Key。Claude Code 官方建议网关类服务优先用这个变量。 ## 配置步骤 1. **打开设置文件** — 编辑 `~/.claude/settings.json`,没有就新建。写在这里,无论从哪个终端启动 `claude` 都会生效。 1. **填入地址和 Key** — 把中转站给的两项填进 `env`。如果中转站要求指定模型名,再加上 `ANTHROPIC_MODEL`。 1. **退出旧登录** — 如果之前在这台机器上登录过 Claude 账号,在 Claude Code 里执行 `/logout`,避免凭据冲突。 1. **确认生效** — 重新打开 `claude`,输入 `/status`,应该能看到 Anthropic base URL 显示为中转站地址。 `~/.claude/settings.json` ``` { "env": { "ANTHROPIC_BASE_URL": "https://你的中转站地址", "ANTHROPIC_AUTH_TOKEN": "你的中转站 Key" } } ``` 不要把 Key 写进项目目录下的 `.claude/settings.json`:这个文件通常会提交到 Git,等于把密钥公开。只对单个项目生效的配置,请写在 `.claude/settings.local.json`。 ## 常见报错 | 现象 | 常见原因 | 怎么办 | | --- | --- | --- | | 401 未授权 | Key 填错、放错变量,或同时设置了 ANTHROPIC_API_KEY | 检查 Key;只保留 ANTHROPIC_AUTH_TOKEN;执行 /logout 后重开 | | 模型不存在 | 中转站没有 Claude Code 默认请求的模型 | 按中转站说明设置 ANTHROPIC_MODEL 和 ANTHROPIC_DEFAULT_HAIKU_MODEL | | 改了配置不生效 | 终端里另外 export 了同名变量 | 只保留一处配置,用 /status 确认实际生效的值 | | 404 或连不上 | Base URL 多写或少写了路径 | 对照中转站文档核对地址末尾 | ## Codex 也想用中转站? OpenAI Codex 的配置方式不同:在 `~/.codex/config.toml` 里新建一个 `model_providers`,写上中转站的 `base_url`,用 `env_key` 指定存放 Key 的环境变量。AlwaysAgent 的设置页会帮你分别配置 Claude Code 和 Codex。 ## 常见问题 ### 中转站和官方 API 有什么区别? 官方 API 由模型厂商直接提供;中转站是第三方转发,通常价格更灵活、一个 Key 可以用多家模型,但稳定性和数据安全取决于服务商本身。 ### 中转站的 Key 放在 AlwaysAgent 安全吗? Key 只保存在你自己的那台服务器上,平台不经手你的模型调用。服务器是你独享的,不和其他用户共用。 ### 可以同时配置多个中转站吗? Claude Code 同一时间只用一组地址和 Key。AlwaysAgent 里可以为不同会话选择不同的接入方式,切换不用改文件。 --- # 怎么在云服务器上跑 Claude Code(24 小时运行 + 手机随时连) > 一台基础配置的 Linux 云服务器、一行官方安装命令,再加上 tmux,就能让 Claude Code 在你合上笔记本后继续干活。下面是完整的搭建步骤,包括国内与海外服务器怎么选、怎么接模型、手机怎么连以及安全加固清单。 Source: https://alwaysagent.app/zh/claude-code-vps 更新于: 2026-11-05 ## 为什么要把 Claude Code 放到服务器上 把 Claude Code 装在云服务器上,最大的好处是让任务和你的电脑解耦:笔记本合盖、休眠、断网或者关机,服务器上的代码重构和测试依然在跑,你随时能换台设备或掏出手机看进度。 Claude Code 本质上是一个运行在终端里的本地程序。你在哪台机器上启动它,它就在哪台机器上读写文件、执行命令。一旦这台机器休眠,正在跑的任务就会中断。把它搬到一台 24 小时在线的 Linux 云服务器上,能同时解决三个问题: - **长任务不会断。**大型重构、循环跑测试、数据库迁移可以在后台一直跑完,不用守着电脑。 - **多设备随时接力。**会话保存在服务器里,在公司电脑、家里电脑或手机上看到的都是同一个现场。 - **本地电脑零负担。**编译、Docker 容器和依赖安装都吃服务器的资源,不占本地内存和电量。 Anthropic 官方虽然提供了两个远程方案,但都有明确限制。根据官方文档,Remote Control(远程控制)的会话依然跑在你自己的电脑上,所以你的电脑必须保持开机和联网;而网页版云端会话(Claude Code on the web)强制要求绑定 claude.ai 账号,不支持自带 API Key,也没法接入国产大模型或第三方中转站。自己管一台服务器,就没有这些限制。 ## 服务器怎么选:配置要求与境内/境外取舍 选一台至少 2 核 4 GB 内存、装主流 Linux 发行版(Ubuntu 或 Debian)的云服务器;至于选国内云还是境外 VPS,完全取决于你打算接哪家的模型接口以及拉取代码的网络环境。 ### 硬件与系统要求 根据 Claude Code 官方系统要求,服务器需要满足:Ubuntu 20.04+、Debian 10+ 或 Alpine 3.19+ 系统,x64 或 ARM64 架构处理器,以及**至少 4 GB 内存**。低于这个内存,安装或运行过程中很容易因为内存不足被系统直接杀死(OOM)。 除了 Claude Code 本身,你还要给项目编译、跑测试和 Docker 留出余量: | 日常用途 | 建议起步配置 | | --- | --- | | 写脚本、小型前后端项目、轻量重构 | 2 vCPU、4 GB 内存、40 GB 硬盘 | | 带数据库或 Docker 的全栈项目 | 4 vCPU、8 GB 内存、75 GB+ 硬盘 | | 大型编译、同时开多个 Claude Code 会话 | 6+ vCPU、12 GB+ 内存、100 GB+ 硬盘 | ### 境外 VPS 还是国内云服务器? 中国大陆读者在买服务器时,最容易踩坑的是网络连通性。你可以按下面的实际情况来取舍: - **境外 VPS(美西、日本、新加坡等)** (`省心首选`): 适合需要直连 Anthropic 官方接口、用 Claude 订阅账号,或经常从 GitHub、npm、Docker Hub 拉依赖的场景。 - **国内云服务器(阿里云、腾讯云等)** (`低延迟 + 国产模型`): SSH 敲命令延迟极低,直连 DeepSeek、智谱、百炼等国内模型接口快,但访问海外资源受限。 - **官方接口与地区限制:**Anthropic 官方服务与 API 不支持中国大陆(及香港等不在支持列表内的地区)。如果你用 Claude Pro/Max 订阅登录,或者直连 Anthropic 官方 API,服务器必须选在 [Anthropic 支持的国家和地区](https://www.anthropic.com/supported-countries)(例如美国、日本、新加坡),否则登录或调用会返回 403 错误。 - **安装包与开发依赖:**Claude Code 的官方一键安装脚本托管在 `claude.ai`,日常写代码也经常要连 GitHub。中国大陆不在 Anthropic 的支持地区内,官方安装脚本在不支持的地区会返回 403;选国内机器时,模型也只能接国产模型的官方接口。 - **SSH 延迟与备案:**国内服务器连 SSH 基本没有延迟,敲命令跟本地终端一样跟手;境外 VPS 从国内直连会有一定延迟(选美西、日本或新加坡通常在可接受范围内)。另外,网站备案取决于服务器是否在中国内地并对外提供网站服务,具体以所用云厂商的规则为准。 - **注意计费方式:**很多云厂商的按量付费实例,在控制台点“关机”后磁盘等资源依然会继续计费(只有删除实例才完全停止计费)。买之前先看清计费规则。 ## 第一步:创建普通用户(不要直接用 root) 拿到新服务器后,先创建一个带 `sudo` 权限的普通用户来跑 Claude Code,不要全程用 `root`,这样就算 AI 执行了误删或改错配置的命令,破坏范围也是可控的。 先用云厂商给你的 `root` 账号登录一次服务器,执行下面的命令创建新用户(把 `dev` 换成你喜欢的用户名): `在服务器上(root 权限)` ``` # 创建用户并加入 sudo 组(Debian/Ubuntu) adduser dev usermod -aG sudo dev ``` 接着回到你自己的电脑上,把本地的 SSH 公钥传给这个新用户,以后就能免密登录了: `在你自己的电脑上` ``` ssh-copy-id dev@你的服务器IP ssh dev@你的服务器IP ``` 如果你电脑上还没有 SSH 密钥对,先在本地运行 `ssh-keygen -t ed25519` 生成一对,私钥留在自己电脑上,绝不要外传。 ## 安装 Claude Code 推荐使用官方原生安装脚本:它不需要预装 Node.js,直接把可执行文件装在当前用户的家目录下,并且会在后台自动更新。 `在服务器上(用刚创建的普通用户)` ``` curl -fsSL https://claude.ai/install.sh | bash claude --version ``` 下载过程中终端不会显示进度条,耐心等它跑完即可。装好后运行 `claude --version`,能打印出版本号就说明成功了;你还可以运行 `claude doctor` 做一次环境自检。 如果官方脚本在你的服务器上拉不下来,官方文档还提供了另外两种安装途径: - **系统包管理器(apt / dnf / apk):**Anthropic 提供了带签名的软件源,装好后可以跟着系统升级一起更新。 - **npm 安装:**如果你的机器上本来就有 Node.js(要求 Node.js 22 及以上版本),可以运行 `npm install -g @anthropic-ai/claude-code`。注意官方明确提醒**不要加 `sudo`**。npm 包安装下来的其实也是同一个原生二进制程序。 ## 登录与模型接入:国产模型、中转站、API Key 或官方订阅 装好之后,你需要给 Claude Code 接上大模型。对于国内开发者,最常见的是写入 `ANTHROPIC_BASE_URL` 和 `ANTHROPIC_AUTH_TOKEN` 来接国产模型或中转站;如果你在境外 VPS 上,也可以直接用 Anthropic 官方 API Key 或 Claude 订阅账号。 ### 方式一:接入国产大模型官方接口或中转站(国内最常用) DeepSeek、智谱 GLM、Kimi(月之暗面)、阿里云百炼(通义千问)、MiniMax 等国内厂商,都已经官方提供了兼容 Anthropic 格式的接口。中转站(聚合 API)的原理也完全一样:给 Claude Code 指定一个请求地址(Base URL)和一个密钥(Token)。 最干净的做法是把它们写进用户目录下的 `~/.claude/settings.json` 文件里(没有就新建一个)。这样不管你从哪个目录启动 `claude`,配置都会自动生效: `~/.claude/settings.json(以 DeepSeek 为例)` ``` { "env": { "ANTHROPIC_BASE_URL": "https://api.deepseek.com/anthropic", "ANTHROPIC_AUTH_TOKEN": "在这里填入你的密钥", "ANTHROPIC_MODEL": "deepseek-flash[1m]", "ANTHROPIC_DEFAULT_HAIKU_MODEL": "deepseek-flash" } } ``` 如果你用的是其他国产厂商或第三方中转站,只需把上面的 `ANTHROPIC_BASE_URL`、`ANTHROPIC_AUTH_TOKEN` 以及模型名称,替换成对应平台文档里提供的值即可。各家厂商的具体地址和写法,可以参考我们的另一篇指南:[Claude Code 国内怎么用?接国产模型或中转站的完整方法](/zh/claude-code-china)。 > **安全提醒:**千万不要把包含密钥的配置写进项目目录里的 `.claude/settings.json` 并提交到 Git 仓库——Anthropic 文档特别警告过,项目级的配置文件会共享给所有克隆该仓库的人。设置好后,在 Claude Code 里输入 `/status`,就能确认当前生效的接口地址和认证方式。 ### 方式二:使用 Anthropic 官方 API Key 如果你有可用的 Anthropic Console 账号,可以直接按 Token 用量付费。把官方生成的 Key 写进 `~/.claude/settings.json` 的 `ANTHROPIC_API_KEY` 字段即可(不需要改 Base URL): `~/.claude/settings.json(官方 API Key)` ``` { "env": { "ANTHROPIC_API_KEY": "sk-ant-你的官方API密钥" } } ``` 根据官方文档,只要环境变量里设置了 `ANTHROPIC_API_KEY`,即使你之前登录过订阅账号,Claude Code 也会优先使用这个 API Key 计费;想切回订阅账号,需要把这个变量删掉或执行 `unset ANTHROPIC_API_KEY`。 ### 方式三:使用 Claude 订阅账号登录(Pro / Max / Team 等) 如果你在境外 VPS 上,并且有付费的 claude.ai 订阅账号(Pro、Max、Ultra、Team 或 Enterprise,免费版不支持 Claude Code),可以直接用账号登录: 1. **启动并复制登录链接** — 在服务器终端运行 `claude`。因为服务器上没有图形浏览器,按键盘上的 `c` 键(或直接鼠标选中)复制终端里打印出的登录 URL。 1. **在本地电脑浏览器完成授权** — 在你自己电脑的浏览器里打开刚才复制的链接,登录你的 Claude 账号,页面会给出一个授权码(Code)。 1. **把授权码粘贴回服务器终端** — 回到服务器的 `Paste code here` 提示处,把授权码粘贴进去回车即可。如果交互界面粘贴没反应,官方建议改跑 `claude auth login` 命令,它会从标准输入读取授权码。 如果你需要写自动化脚本跑无值守任务,可以运行 `claude setup-token` 生成一个有效期一年的 OAuth 令牌,填到 `CLAUDE_CODE_OAUTH_TOKEN` 环境变量里使用(注意这种令牌不支持开启 Remote Control)。 ## 用 tmux 保持 24 小时后台运行 在服务器上跑 Claude Code,一定要把它放在 `tmux` 会话里启动;否则你的 SSH 连接一旦因为网络波动断开,正在跑的 `claude` 进程就会被系统直接终止。 `tmux` 是一个终端复用工具,它能让终端会话一直留在服务器后台,你可以随时断开(detach),过几个小时再从另一台电脑或手机重新接上(attach)。Anthropic 在 Remote Control 文档中也建议:在远程机器上运行 `claude` 时放进 `tmux` 或 `screen`,这样断开 SSH 后会话不会掉线。 `tmux 常用命令` ``` sudo apt install tmux # Debian/Ubuntu 安装 tmux tmux new -s work # 创建并进入一个叫 work 的会话 claude # 在 tmux 里面启动 Claude Code # 想离开时:先按 Ctrl+b,松开后再按 d(会话会留在后台继续跑) tmux ls # 查看后台有哪些会话 tmux attach -t work # 下次连上服务器,重新回到 work 会话 ``` 记住一个最省事的命令:`tmux new -A -s work`。它的意思是“如果已经有叫 `work` 的会话就直接连进去,没有就新建一个”。平时用电脑或手机连上服务器后,直接敲这一行就够了。 注意:`tmux` 能扛住 SSH 断线,但扛不住服务器重启。如果服务器重启了,重新跑一次 `tmux new -A -s work` 并启动 `claude` 即可。 ## 在手机上怎么远程连上去用 把 Claude Code 部署在服务器上之后,你有三种办法从手机访问它:装一个手机 SSH 客户端连 tmux、用 Anthropic 官方的 Remote Control,或者直接用浏览器工作台。更详细的对比可以看 [手机上怎么用 Claude Code](/zh/claude-code-phone)。 ### 办法一:手机 SSH App + tmux(不挑模型,最通用) 在手机上装一个支持 SSH 的终端 App(Android 常用 Termux 或 JuiceSSH,iOS 常用 Blink Shell、Termius 或 Prompt),导入你的私钥连上服务器,然后执行 `tmux new -A -s work`,就能直接看到刚才电脑上留下的 Claude Code 界面。 这种方式对所有模型接法都有效(国产模型、中转站、API Key 都能用)。缺点是手机屏幕小、敲长命令费劲,适合在外面看一眼进度、审批一下权限(按回车确认),或者发一两句简短的指令。 ### 办法二:加装 Tailscale 组建私有内网(更安全) 如果你不想把服务器的 22 端口暴露在公网上天天被机器人扫,可以在服务器和手机上都装上 Tailscale,登录同一个账号,把它们放进同一个虚拟局域网里: `在服务器上安装 Tailscale` ``` curl -fsSL https://tailscale.com/install.sh | sh sudo tailscale up ``` 你还可以运行 `tailscale set --ssh` 开启 [Tailscale SSH](https://tailscale.com/kb/1193/tailscale-ssh)。开启后,凡是通过 Tailscale 内网连过来的请求,直接由 Tailscale 验证身份,连 SSH 密钥都不用在手机上配,同时也不会改动你原有的 `sshd` 配置。配通之后,你就可以在云厂商防火墙里把公网的 22 端口彻底关掉了。 ### 办法三:官方 Remote Control(仅限官方订阅账号) Anthropic 提供了 Remote Control 功能,让你用手机上的 Claude App 或网页版 `claude.ai/code` 直接遥控服务器上的会话。用法是在服务器的 tmux 里运行 `claude remote-control`,然后在手机上打开终端显示的链接,或按空格键显示二维码后扫码。它只向外发起 HTTPS 请求,不需要服务器开放入站端口。 **但它的限制非常严,绝大多数国内用法都用不了:** - 必须使用 claude.ai 订阅账号登录(**不支持 API Key**)。 - 只要你的 `ANTHROPIC_BASE_URL` 指向了非官方地址(即非 `api.anthropic.com`),Remote Control 会被直接禁用——也就是说**国产模型和中转站全部无法使用此功能**。 - 服务器上的 `claude` 进程必须一直保持运行。 因此,只要你用的是国产模型、中转站或者按量计费的 API Key,手机端就请老老实实用 SSH,或者用下面介绍的浏览器工作台。 ## 服务器安全加固清单(必做) 一台刚开通的公网云服务器,几分钟内就会被全网的扫描器盯上。把代码和 API 密钥放上去之前,请至少做完下面 6 件事: - ### 禁用密码登录与 root 远程登录 先开第二个终端窗口,确认你的普通用户用 SSH 密钥能正常登录。确认无误后,编辑服务器上的 `/etc/ssh/sshd_config`,改成下面这样: `/etc/ssh/sshd_config` ``` PasswordAuthentication no KbdInteractiveAuthentication no PermitRootLogin no ``` 改完先运行 `sudo sshd -t` 检查语法有没有错,没报错再重启 SSH 服务(Debian/Ubuntu 上是 `sudo systemctl restart ssh`,部分其他发行版是 `sshd`)。有些云镜像自带的子配置文件会覆盖主配置,建议跑一下 `sudo sshd -T | grep -i -E "passwordauth|permitroot"`,确认实际生效的值确实是 `no`。在测试新窗口能连上之前,别关掉手头现有的终端。 - ### 开启防火墙(ufw) Ubuntu 默认没启用 ufw。启用前**必须先放行 SSH 端口**,否则会把自己锁在门外: `配置 ufw 防火墙` ``` sudo ufw allow 22/tcp sudo ufw enable sudo ufw status ``` 只有当你需要在服务器上对外展示网页时,才去额外放行 80 和 443 端口。 - ### 安装 fail2ban 防暴力破解 `fail2ban` 会自动监控 `/var/log/auth.log` 等日志,把连续试错密码或密钥的 IP 直接封禁一段时间。在 Debian/Ubuntu 上运行 `sudo apt install fail2ban` 即可装好,用 `sudo fail2ban-client status` 可以查看运行状态。 - ### 日常绝不用 root 跑 Claude Code 始终用你的普通用户启动 `claude`。遇到 Claude Code 询问是否允许执行某条危险命令时,看一眼再点确认,不要无脑全部放行。 - ### 管好 API Key 和 Git 凭证 把接口密钥放在 `~/.claude/settings.json` 里,并确保文件权限只有你自己能读写(`chmod 600 ~/.claude/settings.json`)。在 Linux 上,Claude Code 默认也会把登录凭证以 `0600` 权限保存在 `~/.claude/.credentials.json`。服务器上拉代码时,尽量用只针对单个仓库的 Deploy Key(部署密钥)或限制了权限范围的个人访问令牌(PAT)。 - ### 保持系统与工具更新 原生安装的 Claude Code 会自动更新;操作系统层面,建议在 Debian/Ubuntu 上开启 `unattended-upgrades` 自动安装安全补丁。 ## 成本怎么算:服务器租金 + 模型消耗 自己在云服务器上跑 Claude Code,总花费由两部分相加:**固定付给云厂商的服务器租金**,加上**按实际使用量付给模型厂商的费用**。 - **服务器费用:**按月或按小时固定计费。只要服务器实例还存在,不管你今天有没有打开 Claude Code,这笔钱都在走。记得留意流量包超额、额外挂载硬盘和自动快照是不是单独收费。 - **模型费用:**如果你接的是国产模型、中转站或官方 API Key,都是按 Token 消耗量扣费的——让 Claude Code 在后台自动循环改 Bug、跑测试,一晚上消耗的 Token 费用完全可能超过服务器本身的月租。如果你用的是固定月费的套餐(如 Claude Pro/Max 或部分国产厂商的包月编程套餐),则是消耗套餐内的额度上限。 最稳妥的办法是:先按平时的真实工作强度跑上一周,把云厂商账单和模型后台的消耗加起来乘以 4,就能算出你每个月的真实开销。 ## 常见问题排查(Troubleshooting) 新服务器上部署遇到报错,十有八九是环境变量 PATH、内存不足、网络拦截或认证冲突,按下面的症状对号入座即可: - **装完提示 `claude: command not found`:**官方安装脚本会把程序装在 `~/.local/bin/claude`,但这个目录可能还没加进你的 PATH。运行 `echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.bashrc && source ~/.bashrc` 即可解决。 - **安装过程中突然显示 `Killed`(退出码 137):**服务器可用内存不够,进程被 Linux 内核杀掉了。按照官方排查文档的做法,先用 `fallocate`、`mkswap` 和 `swapon` 挂载一个 2 GB 的 Swap 交换文件,或者直接升级到 4 GB 以上内存的机型,再重新运行安装脚本。 - **运行安装脚本返回一堆 HTML 或 403 错误:**说明服务器当前的网络被拦截了,或者服务器所在地区不在 Anthropic 支持列表内(官方安装脚本在不支持的地区会返回 403)。这种情况请换用支持地区的服务器。 - **配了国产模型或中转站,但一直报 401 / 403 认证错误:**在 Claude Code 里输入 `/status` 检查当前生效的配置。看看是不是环境变量名拼错了(应为 `ANTHROPIC_BASE_URL` 和 `ANTHROPIC_AUTH_TOKEN`),或者机器上同时残留了旧的 `ANTHROPIC_API_KEY` 和登录状态——可以执行 `/logout` 退出账号后重启 `claude`。 - **OAuth 登录提示 `Invalid code`:**授权码过期了,或者复制的时候漏了字符。重新运行登录,按 `c` 键完整复制链接并在浏览器里快速完成授权。 - **SSH 重连后发现之前跑的任务没了:**说明你上次是直接在普通 SSH 窗口里敲的 `claude`,没进 `tmux`。下次记得先跑 `tmux new -A -s work`,在里面再启动 Claude Code。 - **`claude remote-control` 启动失败:**先往上翻看“办法三”里的限制条件——只要你用的是 API Key、国产模型或中转站,这个功能就是不可用的。如果是官方订阅账号还连不上,可以跑 `claude remote-control --verbose` 查看详细报错日志。 ## 不想自己配服务器?用 AlwaysAgent 开箱即用 如果你想要“任务 24 小时在云端跑、手机随时能看”的效果,但不想自己去买 VPS、配 SSH 密钥、调防火墙和记 tmux 命令,可以直接用 [AlwaysAgent](https://alwaysagent.app)。 AlwaysAgent 给每位用户分配一台独享的云端 Linux 服务器(带独立公网 IP),里面已经预装好了 Claude Code 和 OpenAI Codex。你不需要装任何客户端,也不用配 SSH,直接在电脑或手机浏览器里打开工作台,就能用上 AI 对话、文件管理、终端、远程浏览器预览和版本记录。关掉电脑或浏览器标签页后,任务依然在你的服务器上 7×24 小时继续运行。 - **自带模型接口,平台不赚差价:**在工作台设置里直接填入 Base URL 和 API Key 即可——无论是 DeepSeek、智谱、Kimi 等国产模型官方接口,还是第三方中转站、OpenRouter,或是 Anthropic / OpenAI 官方 Key 都能用。密钥只保存在你自己的服务器上,平台不经手 AI 调用、不加价,也不转售模型额度。 - **计费透明,先试再买:**支持按小时试用,充值 $10 起,约 $0.05/小时(注意:按小时服务器在关机状态下也会继续计费,删除服务器即停止计费;充值 14 天内未消费余额可退,扣除手续费)。如果觉得好用,可以一键转成月付套餐并自动迁移数据:Starter $9.9/月(2 核 4GB 40GB)、Developer $17.9/月(4 核 8GB 75GB)、Pro $24.9/月(6 核 12GB 100GB)、Power $44.9/月(8 核 24GB 200GB),全部不限流量、包含每日自动快照,到期自动续费且可随时取消。 ## 常见问题 ### 云服务器跑 Claude Code,选国内服务器还是国外 VPS? 取决于你用什么模型和代码源。如果你用国产大模型(如 DeepSeek、智谱、Kimi)且代码托管在国内平台,国内云服务器延迟最低;如果你要用 Claude 官方订阅账号、Anthropic 官方 API Key,或者经常从 GitHub、npm 拉包,选美西、日本或新加坡的境外 VPS 会省去很多网络折腾。 ### 跑 Claude Code 的服务器最低需要什么配置? 按照 Anthropic 官方要求,内存至少需要 4 GB(安装程序本身也需要约 512 MB 以上的空闲内存,1 GB 或 2 GB 的小机器很容易在安装时因为内存不足被系统杀死)。日常写代码建议从 2 核 4 GB 起步;如果要跑 Docker 或大型项目编译,建议选 4 核 8 GB 及以上配置。 ### 服务器上的 Claude Code 可以接 DeepSeek、智谱或中转站吗? 可以。在服务器上的 ~/.claude/settings.json 文件里,把厂商或中转站提供的接口地址填进 ANTHROPIC_BASE_URL,把密钥填进 ANTHROPIC_AUTH_TOKEN 即可生效,用法和在本地电脑上完全一样。 ### 为什么我关掉 SSH 窗口后,服务器上的 Claude Code 任务就断了? 因为直接通过 SSH 启动的程序会绑定在当前连接上,网络一断进程就会收到挂断信号退出。解决办法是先在服务器上运行 tmux new -A -s work 进入 tmux 会话,再在里面启动 claude;这样就算关掉电脑或断开 SSH,任务也会在后台继续跑。 ### 接了国产模型或中转站,还能用 Claude 官方的手机 Remote Control 吗? 不能。Anthropic 官方的 Remote Control 强制要求使用 claude.ai 订阅账号登录,且一旦检测到 ANTHROPIC_BASE_URL 不是官方地址就会自动禁用。如果你用国产模型、中转站或 API Key,想在手机上用,可以通过手机 SSH 客户端连 tmux,或者使用 AlwaysAgent 这类直接支持手机浏览器的云端工作台。 ### 在服务器上安装 Claude Code 必须要先装 Node.js 吗? 不需要。使用官方推荐的 curl -fsSL https://claude.ai/install.sh | bash 命令安装的是独立原生二进制程序,不依赖 Node.js。只有当你选择用 npm install 方式安装,或者你自己的项目本身需要 Node 环境时,才需要安装 Node.js。 --- # Codex 国内怎么用? > Codex CLI 是 OpenAI 开源的终端编程智能体,能直接读仓库、改代码、跑测试。国内开发者不必依赖 OpenAI 账号,只需修改 ~/.codex/config.toml,就能给它换上提供 Responses 兼容接口的国产大模型或中转站。 Source: https://alwaysagent.app/zh/codex-china 更新于: 2026-11-05 ## Codex CLI 是什么?国内使用难在哪 Codex CLI(命令为 `codex`)是 OpenAI 推出的终端编程智能体(Coding Agent)。它在你的本地目录或服务器里运行,能理解整个代码库、跨文件修改代码、执行终端命令并自动根据报错修复问题。此外,Codex CLI 与桌面端应用(`codex app`)、VS Code / Cursor 等 IDE 扩展共用同一套底层配置(`~/.codex/config.toml`)。 国内开发者直接使用官方服务,通常会遇到两道门槛: - **地区限制**:中国大陆不在 OpenAI 官方支持的国家和地区列表内,直接使用官方接口和账号存在不确定性。 - **账号与付款门槛**:Codex 支持 ChatGPT 账号登录(不同套餐额度不同)或 OpenAI API Key,两者都需要在 OpenAI 开户和付款,对国内用户不够方便。 好在 OpenAI 将 Codex CLI 的模型接入层设计成了可插拔架构。通过用户级配置文件 `~/.codex/config.toml` 中的 `model_providers` 字段,你可以把请求发往任何兼容 **OpenAI Responses API** 的接口。国内目前有三种可行的接入方案: - **国产大模型直连** (`官方 Responses 接口`): DeepSeek、智谱 GLM、Kimi、MiniMax、阿里云百炼、火山方舟都有 Codex 接入官方文档,提供 Responses 兼容接口(个别套餐例外,见下表)。 - **第三方中转站 / OpenRouter** (`自定义 Base URL`): 通过中转服务或 OpenRouter 转发请求,一个 Key 调用多厂商模型;需确认服务商支持 `/responses` 端点。 - **OpenAI 官方账号 / Key** (`codex login`): 适合已有代理网络或海外云服务器,且持有 ChatGPT Plus/Pro 订阅或官方 `OPENAI_API_KEY` 的开发者。 ## 第一步:安装 Codex CLI(官方方式) OpenAI 官方提供了独立安装脚本、npm 和 Homebrew 三种安装渠道。国内或云服务器环境下,可以根据你机器上的工具链任选一种: - ### 使用官方独立安装脚本或包管理器安装 macOS 和 Linux 可以直接运行官方独立安装脚本(无需预装 Node.js)。如果你已经装好了 Node.js,使用 `npm` 全局安装是最通用的做法(各家国产模型的配置向导也普遍采用此方式)。 - ### 检查版本并生成配置目录 安装完成后运行 `codex --version` 确认命令可用。首次配置前,建议先运行一次 `codex` 或手动执行 `mkdir -p ~/.codex`,确保用户主目录下存在 `~/.codex` 文件夹。 `Terminal(macOS / Linux / Windows)` ``` # 方式 A:使用 npm 全局安装(通用,需 Node.js 环境) npm install -g @openai/codex # 方式 B:macOS / Linux 官方独立安装脚本 curl -fsSL https://chatgpt.com/codex/install.sh | sh # 方式 C:macOS Homebrew 安装 brew install --cask codex # 方式 D:Windows PowerShell 官方独立安装脚本 powershell -ExecutionPolicy ByPass -c "irm https://chatgpt.com/codex/install.ps1 | iex" # 验证安装并创建配置目录 codex --version mkdir -p ~/.codex ``` 如果你有海外网络和官方账号,安装后直接运行 `codex` 会拉起登录界面;在无桌面环境的远程服务器上,可运行 `codex login --device-auth` 使用设备码登录,或通过管道传入官方 API Key:`printenv OPENAI_API_KEY | codex login --with-api-key`。而如果在国内接国产模型或中转站,则不需要登录 OpenAI 账号,直接看下面的配置文件写法。 ## 第二步:理解 config.toml 与 Responses API 协议要求 在动手改配置前,有两个来自 OpenAI 官方文档的关键规则必须弄清楚,否则很容易踩坑: - **必须兼容 Responses API(`wire_api = "responses"`)**:新版 Codex CLI 已废弃旧的 `wire_api = "chat"`(Chat Completions 协议)。根据官方配置参考文档,`model_providers..wire_api` 目前唯一合法的值就是 `"responses"`(省略时默认也是它)。这意味着你接入的模型厂商或中转站,后端必须提供 `/responses` 路径的接口,只支持传统 `/chat/completions` 的旧接口无法直连。 - **只能在用户级配置文件中定义提供方**:Codex 的用户级配置文件位于 `~/.codex/config.toml`(Windows 原生环境为 `%USERPROFILE%\.codex\config.toml`,若设置了环境变量 `CODEX_HOME` 则为 `$CODEX_HOME/config.toml`)。为了安全,Codex 会忽略项目目录 `.codex/config.toml` 里的 `model_provider` 和 `model_providers` 键——自定义模型提供方必须写在用户级的 `~/.codex/config.toml` 中。 下面是一个标准的自定义提供方 `~/.codex/config.toml` 结构示例: `~/.codex/config.toml(通用模板)` ``` # 注意:TOML 语法要求顶层键值必须写在所有 [table] 表头之前 model_provider = "my_provider" model = "模型名称" model_reasoning_effort = "high" [model_providers.my_provider] name = "Custom Provider" base_url = "https://example.com/v1" env_key = "MY_PROVIDER_API_KEY" wire_api = "responses" ``` 核心配置键说明: - `model_provider`:指定当前启用的提供方 ID,必须与下方 `[model_providers.]` 中的 `` 完全一致(不要使用 `openai`、`ollama`、`lmstudio` 等内置保留名)。 - `model`:要调用的模型 ID(如 `deepseek-flash`、`glm-5.3`、`kimi-k3.1-pro` 等)。 - `base_url`:接口基础地址。Codex 请求时会自动在末尾拼接 `/responses`。 - `env_key`:存放 API Key 的**环境变量名称**(注意:这里填的是变量名如 `ARK_API_KEY`,而不是以 `sk-` 开头的密钥本身,密钥值需在终端里通过 `export` 设置)。部分厂商文档也会使用 `experimental_bearer_token` 字段直接填入密钥字符串(OpenAI 官方标注为不推荐,优先用 `env_key`)。 - `wire_api`:通信协议,固定填 `"responses"`。 - `model_catalog_json`(可选):指向本地模型元数据 JSON 文件(如 `~/.codex/models.json`),用于向 Codex 声明第三方模型的上下文窗口大小和思考强度档位(`low` / `medium` / `high` / `max`)。 ## 第三步:接入国产大模型(官方原生支持列表) 截至 2026 年 11 月,下面 6 家都发布了 Codex CLI 的官方接入文档,多数还提供一键配置工具。官方手动配置通常还需要一个模型目录文件 `~/.codex/models.json`(通过 `model_catalog_json` 引用),下面的示例只展示核心结构,完整写法以各家文档为准。由于 Codex CLI、桌面端和 IDE 插件共用 `~/.codex/config.toml`,按下面任意一家配置一次,三端同时生效。 | 厂商 / 平台 | Codex 专用 Base URL(Responses 协议) | 常用模型示例与配置方式 | 官方文档 | | --- | --- | --- | --- | | DeepSeek | https://api.deepseek.com | deepseek-flash、deepseek-v4-pro;提供官方一键配置脚本 | [DeepSeek 文档](https://api-docs.deepseek.com/zh-cn/quick_start/agent_integrations/codex/) | | 智谱 GLM(国内站) | https://open.bigmodel.cn/api/v1 | glm-5.3、glm-5-turbo;可手写配置或运行 npx @z_ai/coding-helper | [智谱文档](https://docs.bigmodel.cn/cn/coding-plan/tool/codex) | | Kimi(月之暗面) | 国内站:https://api.moonshot.cn/v1国际站:https://api.moonshot.ai/v1(两边 Key 不通用) | kimi-k3.1-pro;设置环境变量 KIMI_API_KEY 直连 | [Kimi 文档](https://platform.moonshot.cn/docs/guide/codex-kimi) | | MiniMax | 国内站:https://api.minimax.cn/v1国际站:https://api.minimax.io/v1 | MiniMax-M3.1-Flash;可运行 npx -y mmx-cli@latest agent setup | [MiniMax 文档](https://platform.minimaxi.com/docs/m-plan/codex) | | 阿里云百炼(通义千问等) | Token Plan:https://token-plan.cn-beijing.maas.aliyuncs.com/compatible-mode/v1按量计费:https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1 | 千问等百炼模型;套餐 Key 与按量 Key 地址不同;Coding Plan 套餐走 Chat 协议、要求旧版 Codex,不适用本文方法 | [百炼文档](https://help.aliyun.com/zh/model-studio/codex) | | 火山方舟(豆包 / DeepSeek 等) | 按量计费:https://ark.cn-beijing.volces.com/api/v3Coding Plan:https://ark.cn-beijing.volces.com/api/coding/v3Agent Plan:https://ark.cn-beijing.volces.com/api/plan/v3 | ark-code-latest 或具体模型名;支持通过 arkcli helper 一键配置 | [火山方舟文档](https://www.volcengine.com/docs/ark/ai-tools-codex) | ### 配置示例 1:接入 DeepSeek(一键脚本或手动配置) DeepSeek 官方 API 已原生支持 Responses API。最省事的方法是先确保已安装并启动过一次 `codex`,然后在终端运行 DeepSeek 官方的一键配置脚本,脚本会自动备份原配置、写入模型目录 `~/.codex/models.json` 并修改 `~/.codex/config.toml`: `Terminal(DeepSeek 官方一键配置脚本)` ``` # macOS / Linux bash <(curl -fsSL https://cdn.deepseek.com/api-docs/codex-deepseek-setup-en.sh) # Windows PowerShell irm https://cdn.deepseek.com/api-docs/codex-deepseek-setup-en.ps1 | iex ``` 如果你倾向于手动修改,下面是核心结构示意。官方手动配置还要先创建 `~/.codex/models.json`,并加上登录方式等若干项,完整内容以 DeepSeek 文档为准: `~/.codex/config.toml(DeepSeek 手动配置)` ``` model = "deepseek-flash" model_provider = "deepseek" model_catalog_json = "~/.codex/models.json" [model_providers.deepseek] name = "deepseek" base_url = "https://api.deepseek.com/" wire_api = "responses" experimental_bearer_token = "你的 DeepSeek API Key" ``` ### 配置示例 2:接入智谱 GLM(GLM-5.3) 注意智谱 GLM 接入 Codex 时,必须使用其 OpenAI Response 协议专用端点 `https://open.bigmodel.cn/api/v1`(如果是海外站 Z.ai 则是 `https://api.z.ai/api/v1`),而**不是**传统的 `/api/paas/v4`。你可以运行智谱官方工具 `npx @z_ai/coding-helper` 自动配置,或者按官方文档手动编辑(同样需要先建 `~/.codex/models.json`): `~/.codex/config.toml(智谱 GLM 配置)` ``` model_provider = "ZAI" model = "glm-5.3" model_reasoning_effort = "max" model_catalog_json = "~/.codex/models.json" [model_providers.ZAI] name = "ZAI" base_url = "https://open.bigmodel.cn/api/v1" experimental_bearer_token = "你的智谱 API Key" wire_api = "responses" ``` ### 配置示例 3:接入 Kimi 或火山方舟(使用 env_key 环境变量) 不想把明文 Key 直接写进配置文件的开发者,可以用 `env_key` 指定环境变量名。以 Kimi 国内站(`kimi-k3.1-pro`)为例,Kimi 官方也明确建议不要把 Key 写进配置文件: `~/.codex/config.toml(Kimi 配置)` ``` model = "kimi-k3.1-pro" model_provider = "kimi" model_context_window = 1048576 [model_providers.kimi] name = "Kimi" base_url = "https://api.moonshot.cn/v1" env_key = "KIMI_API_KEY" wire_api = "responses" ``` 保存后,在终端(或写入 `~/.bashrc` / `~/.zshrc`)导出对应的环境变量即可启动 `codex`: `Terminal` ``` export KIMI_API_KEY="sk-你的Kimi密钥" codex ``` ## 使用第三方中转站的注意事项 除了直连国产大模型,不少国内开发者为了在 Codex 里调用 GPT 系列模型或跨厂商切模型,会选择 OpenRouter 或各类第三方 API 中转站(前提是对方支持 Responses 接口)。中转站在 `~/.codex/config.toml` 里的配置方法与上面完全一致,只需把 `base_url`、`env_key` 和 `model` 换成服务商提供的信息。 **使用第三方中转站前,请务必评估以下三点风险:** 1. **代码与数据安全**:Codex CLI 在执行任务时,会将你项目里的代码片段、文件内容、目录结构以及终端命令的输出发送给模型接口。通过第三方中转站调用时,这些明文数据都会流经中转站服务器。请勿在涉及公司商业机密、生产环境密钥或敏感数据的代码仓库中使用来路不明的中转站,并且切勿向任何人分享含官方登录凭证的 `~/.codex/auth.json` 文件。 2. **协议兼容性与稳定性**:部分老旧中转站仅转发了 `/v1/chat/completions`,没有实现或正确透传 Codex 必需的 `/v1/responses` 接口、流式事件与工具调用(Tool Calls)字段,会导致请求报 404/400 或流式响应中断。 3. **计费透明度**:Agent 编程任务往往伴随高频的多轮上下文读取与推理(Reasoning tokens),Token 消耗量远大于普通聊天。使用中转站前请确认其倍率规则、缓存命中(Cached Input)计费是否透明,建议小额充值按量测试。 ## 常见报错与排查方法 根据 OpenAI Codex 官方仓库与各模型厂商文档,配置自定义模型时最常见的报错及解决方法如下: - **报错 ``wire_api = "chat"` is no longer supported`** 原因:你参考了早期版本的旧教程,在配置里写了 `wire_api = "chat"`。 解决:打开 `~/.codex/config.toml`,将该字段改为 `wire_api = "responses"`,并确认所填的 `base_url` 对应的是厂商支持 Responses API 的端点。 - **警告 `Ignored unsupported project-local config keys in .../.codex/config.toml: model_provider, model_providers`** 原因:你把 `model_provider` 和 `model_providers` 写进了项目目录下的 `.codex/config.toml`。 解决:Codex 规定提供方配置只能放在用户级配置文件中。请将这两项移至 `~/.codex/config.toml`(Windows 为 `%USERPROFILE%\.codex\config.toml`)。 - **报错 `legacy `profile = "x"` config is no longer supported; use `--profile x` with `x.config.toml` instead`** 原因:在 `config.toml` 顶层设置了旧写法 `profile = "x"`,或用 `--profile x` 时与旧的 `[profiles.x]` 同名。 解决:删除顶层的 `profile = ...`(以及同名的旧 `[profiles.x]`)。如果需要保存多套模型配置随时切换,按官方新规范在 `~/.codex/` 下新建独立的 `<名称>.config.toml` 文件(如 `~/.codex/kimi.config.toml`,里面直接写顶层键值),启动时运行 `codex --profile <名称>`。 - **请求返回 `401 Unauthorized`** 原因:自定义提供方默认不会去读 `~/.codex/auth.json` 里的官方 Key;或者你混用了不同计费类型的 Key。 解决:第一,确认 `env_key` 写的是环境变量名(如 `KIMI_API_KEY`),且当前终端已执行 `export KIMI_API_KEY=sk-xxx`(等号两侧无空格);第二,检查国内厂商的**套餐 Key(Coding Plan / Token Plan)与普通按量计费 Key 是否混用**——智谱、阿里云百炼、火山方舟的编程套餐 Key 与按量标准 API Key 均分开管理,对应的 `base_url` 也不同,不能混填。 - **请求返回 `404 Not Found` 或修改配置后不生效** 原因:TOML 语法把顶层键写在了 `[table]` 后面,导致 `model_provider` 被解析成了某个表的子属性;或者 Base URL 写成了 Chat Completions 路径。 解决:确保 `model_provider` 和 `model` 等顶层键位于文件最上方(任何 `[...]` 表头之前),彻底关闭所有正在运行的 Codex 终端或桌面端窗口后重新启动。 ## 在 AlwaysAgent 上直接用 Codex(免装环境) 如果你不想在本地电脑上处理 Node.js 权限、跨平台配置文件路径或网络问题,也可以直接在 [AlwaysAgent](https://alwaysagent.app) 上使用。 AlwaysAgent 为每位用户提供一台独享的云端 Linux 服务器,拥有独立公网 IP,出厂已预装好 OpenAI Codex 与 Claude Code。你不用装任何 App,也不用配 SSH,直接在电脑或手机浏览器里打开工作台(内置 AI 对话、文件管理、终端、远程浏览器预览、版本记录)就能开始写代码。 - **自带接口,平台不加价**:在工作台设置里直接填入你的 Base URL 与 API Key(无论是 OpenAI / Anthropic 官方 Key、上面列出的国产大模型官方接口,还是第三方中转站、OpenRouter 均可)。密钥只保存在你自己的服务器上,平台不经手 AI 调用、不加价、也不转售模型额度。 - **7×24 小时云端在线**:服务器全天候运行,合上电脑或关掉手机浏览器后,Codex 的长任务和测试依然在云端继续跑,随时打开浏览器就能接着看结果。 - **计费透明灵活**:支持按小时试用,充值 $10 起,约 $0.05/小时(删除服务器即停止计费,关机也计费;充值 14 天内未消费余额可退,扣手续费)。长期使用可选月付套餐:Starter $9.9(2 核 4GB 40GB)、Developer $17.9(4 核 8GB 75GB)、Pro $24.9(6 核 12GB 100GB)、Power $44.9(8 核 24GB 200GB),均不限流量、带每日自动快照,按小时服务器可一键转月付并迁移数据。 ## 常见问题 ### Codex CLI 接国产模型,为什么很多旧教程里的配置用不了了? 因为早期版本的 Codex CLI 允许使用 Chat Completions 协议(`wire_api = "chat"`),而新版 Codex CLI 已经只支持 OpenAI Responses API(`wire_api = "responses"`)。如果照搬旧教程填 `wire_api = "chat"` 或填了仅支持 `/chat/completions` 的接口地址,启动或请求时就会报错。请使用本文表格中各厂商原生支持 Responses 协议的 Base URL。 ### 为什么我在项目的 .codex/config.toml 里配了 model_providers 却被忽略了? 这是 OpenAI Codex 的安全限制。根据官方文档,项目级的 `.codex/config.toml` 不允许覆盖机器本地的提供方与认证设置,写在里面的 `model_provider`、`model_providers` 和 `openai_base_url` 都会被直接忽略并弹出警告。请把自定义模型提供方写在用户主目录的 `~/.codex/config.toml` 中。 ### 如何在不改动默认配置的情况下,在多个国产模型或官方模型之间快速切换? 可以使用 Codex 的 Profile 功能。先在 `~/.codex/config.toml` 里把各个厂商的 `[model_providers.]` 定义好,然后在 `~/.codex/` 目录下为不同模型创建单独的 `.config.toml`(例如 `~/.codex/deepseek.config.toml`),里面写上对应的顶层 `model_provider` 和 `model`。平时启动时通过 `codex --profile deepseek` 即可按需切换。 ### 国产模型厂商的 Coding Plan(编程套餐)Key 和普通按量 API Key 有什么区别? 智谱 GLM、阿里云百炼、火山方舟等厂商都推出了包月制的编程套餐(如 Coding Plan、Token Plan)。需要特别注意:这些套餐生成的专属 API Key 与平台标准的按量付费 API Key 是隔离管理的,两者不仅不能混用,在 Codex 里填写的 `base_url` 往往也不一样。配置前请核对你手头 Key 的类型,填错地址会导致 401 报错或产生套餐外的按量扣费。 ### Codex CLI、Codex 桌面端和 VS Code 插件需要分别配置吗? 不需要。OpenAI 官方文档明确说明,Codex CLI、桌面端应用和 IDE 扩展共享同一份用户级配置文件 `~/.codex/config.toml`。你在 `~/.codex/config.toml` 中配置好自定义 `model_providers` 后,重启命令行或桌面应用即可生效。 ### AlwaysAgent 服务器在海外,既能连 OpenAI 官方又能连国产模型吗? 可以。AlwaysAgent 为每位用户分配独立公网 IP 的云端 Linux 服务器,既可以直接使用 OpenAI / Anthropic 官方接口与 OpenRouter,也可以直连 DeepSeek、智谱、Kimi、MiniMax、阿里云百炼、火山方舟等公网 API 接口。连接多站点厂商(如智谱国内站 `open.bigmodel.cn` 与国际站 `api.z.ai`、MiniMax 国内站 `api.minimax.cn` 与国际站 `api.minimax.io`)时,只需确保所填的 Base URL 与你开通 API Key 的站点一致即可。