文章目录
- 配置文件采用JSON5 格式,而非纯 JSON。这意味着注释(` // like this&`)、尾随逗号和未加引号的键值都是有效的。该文件默认位于 `/etc/config/ ~/.openclaw/openclaw.jsonconfig`。您可以使用OPENCLAW_CONFIG_PATH环境变量或–profile <name>CLI 标志覆盖其默认位置,这将把所有状态隔离到一个单独的目录中,这对于测试或运行多个隔离实例非常有用。 Zod 会在启动时强制执行架构验证。未知键会导致网关拒绝启动。没有警告模式,也没有优雅降级:如果您添加了架构中不存在的键,网关将无法启动,并且错误消息会指向错误的键。这是在手动编辑文件之前必须了解的最重要的一点。安全的编辑工作流程: # 1. Back up first — always cp ~/.openclaw/openclaw.json ~/.openclaw/openclaw.json.bak # 2. Edit the file # 3. Validate JSON5 syntax cat ~/.openclaw/openclaw.json | python3 -m json.tool # 4. Validate schema and fix any issues openclaw doctor –fix 网关会监视文件更改,并在无需重启的情况下热重载大多数设置。“大多数”这个词很重要——请参阅下面的热重载部分,了解哪些更改需要重启,哪些不需要,因为在生产环境中,静默失败的热重载常常会造成混乱。
- 所有顶级部分的完整概览: { // Written by the wizard — don’t edit manually meta: { lastTouchedVersion: “…”, lastTouchedAt: “…” }, gateway: { … }, // Port, bind address, auth token update: { channel: “stable” }, // stable | beta | dev env: { shellEnv: { enabled: true }, vars: { KEY: “value” } }, agents: { defaults: { … }, list: [ … ] }, // Agent config + overrides models: { mode: “merge”, providers: { … } }, // LLM providers auth: { profiles: { … }, order: { … } }, // Provider failover channels: { telegram: { … }, discord: { … } }, // Messaging channels session: { dmScope: “per-channel-peer”, reset: { … } }, bindings: [ { agentId: “…”, match: { … } } ], // Multi-agent routing cron: { enabled: true, maxConcurrentRuns: 2 }, tools: { web: { search: { provider: “brave”, apiKey: “…” } } }, sandbox: { mode: “non-main”, docker: { … } }, logging: { level: “info”, consoleLevel: “warn” }, skills: { install: { nodeManager: “pnpm” } }, }
- 控制网关进程的绑定、身份验证和重新加载方式: gateway: { port: 18789, mode: “local”, // local | cloud bind: “loopback”, // loopback = 127.0.0.1 only (recommended) // all = 0.0.0.0 (requires auth token) auth: { mode: “token”, token: “your-generated-token”, allowTailscale: true, // Tailscale IPs bypass token check }, controlUi: { enabled: true, dangerouslyDisableDeviceAuth: false, // never true on shared hosts }, reload: “hybrid”, // hot | hybrid | restart } bind: "loopback"务必在 VPS 部署中使用此功能。bind: "all"如果没有强身份验证令牌,网关将暴露在互联网上。暴露在公共 IP 上的 OpenClaw 网关会导致 API 密钥、OAuth 令牌和会话历史记录泄露。如果没有身份验证令牌,网关将拒绝绑定到非环回地址。有关反向代理设置,请参阅VPS 安全指南。 该reload字段控制热重载行为。"hybrid"尽可能实时应用更改,仅在必要时重启。gateway.reload还有gateway.remote两个字段在更改时不会触发重新加载——如果您更改了其中任何一个字段,请手动重启网关。
- 代理部分采用“默认值+覆盖”模式,agents.defaults为每个代理设置基线。每个条目都agents.list可以覆盖特定字段。网关在运行时合并这些覆盖项:代理特定的配置优先,其余部分使用默认值。 agents: { defaults: { workspace: “~/.openclaw/workspace”, model: { primary: “anthropic/claude-sonnet-4-5”, fallbacks: [ “openai/gpt-5-mini”, “openrouter/google/gemini-3-flash-preview”, ], }, // Alias shortcuts used with the :model slash command models: { “anthropic/claude-haiku-4-5”: { alias: “haiku” }, “anthropic/claude-sonnet-4-5”: { alias: “sonnet” }, “anthropic/claude-opus-4-6”: { alias: “opus” }, }, maxConcurrent: 4, // Context pruning: trims old tool results before each LLM call contextPruning: { mode: “cache-ttl”, // off | cache-ttl ttl: “45m”, keepLastAssistants: 2, minPrunableToolChars: 12000, softTrim: { maxChars: 2500, headChars: 900, tailChars: 900 }, hardClear: { enabled: true, placeholder: “[Old tool result cleared]” }, tools: { deny: [“browser”, “canvas”] }, }, // Compaction: summarizes full history when context window fills compaction: { mode: “safeguard”, // default | safeguard reserveTokensFloor: 12000, identifierPolicy: “strict”, memoryFlush: { enabled: true, softThresholdTokens: 6000, prompt: “Write any lasting notes to memory/YYYY-MM-DD.md; reply with NO_REPLY if nothing to store.”, systemPrompt: “Session nearing compaction.”, }, }, // Heartbeat heartbeat: { every: “30m”, mode: “next-heartbeat”, }, }, list: [ { id: “main”, default: true }, { id: “work”, workspace: “~/work-agent”, model: { primary: “anthropic/claude-opus-4-6” }, lane: “work-lane”, laneConcurrency: 4, }, ], } 一个关键限制:某些字段仅在代理级别生效,如果按代理设置,agents.defaults则会被静默忽略。压缩设置、浏览器配置文件默认值和思考级别覆盖都属于此类。网关不会发出警告——热重载根本不会执行。此命令会查找并删除这些无效的代理级别键。请务必在编辑代理特定配置后运行此命令。openclaw doctor –fix
- contextPruning在每次 LLM 调用之前运行。它会检查内存中的上下文,并修剪超过 TTL 或大小阈值的旧工具结果。它不会触及磁盘上的会话文件,只会处理发送给模型的内容。如果没有 contextPruning,运行多次工具调用的会话会在上下文中积累巨大的工具结果有效负载。这正是 GitHub 问题 #2254 中记录的模式的根本原因:35 条消息生成了一个 2.9MB 的会话文件和一个包含 208,467 个令牌的上下文,当超出模型 200k 的限制时,上下文会静默停止响应。启用 contextPruningcontextPruning可以避免mode: "cache-ttl"这种情况。 当上下文窗口接近其极限时,压缩操作会运行。网关会汇总会话历史记录,并可选择先通过 `dual memory file` 将备注写入每日内存文件memoryFlush,然后用汇总结果替换完整的历史记录。"safeguard"对于非常长的历史记录,此模式会进行分块汇总,而不是尝试在一次 LLM 调用中汇总所有内容。生产环境中应同时启用这两个功能——较旧的配置可能contextPruning根本没有启用,因为它后来成为了默认设置。
- models: { mode: “merge”, // merge = combine provider lists; replace = replace defaults providers: { anthropic: { apiKey: “${ANTHROPIC_API_KEY}”, }, openai: { apiKey: “${OPENAI_API_KEY}”, }, // LM Studio (OpenAI-compatible local server) “lmstudio”: { baseUrl: “http://127.0.0.1:1234/v1”, apiKey: “lmstudio”, api: “openai-responses”, models: [ { id: “lmstudio/qwen2.5-coder-7b”, name: “Qwen 2.5 Coder 7B”, reasoning: false, input: [“text”], cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 }, contextWindow: 32768, maxTokens: 8000, }, ], }, // Ollama ollama: { baseUrl: “http://localhost:11434”, apiKey: “ollama-local”, api: “openai-completions”, models: [ … ], }, }, } 该api字段控制使用的请求格式。"openai-responses"适用于大多数兼容 OpenAI 的本地服务器;"openai-completions"适用于 Ollama;"anthropic"适用于 Anthropic API。如果模型不支持工具调用,请进行设置reasoning: false,并且不要将其用作主代理模型——OpenClaw 的工具系统需要函数调用支持。
- 每个提供商支持多个身份验证配置文件,以便在速率限制时自动进行故障转移。会话始终绑定到一个配置文件(用于缓存预热),并在缓存/new压缩时重置: auth: { profiles: { “anthropic:subscription”: { mode: “oauth”, email: “you@example.com” }, “anthropic:api”: { mode: “api_key”, apiKey: “${ANTHROPIC_API_KEY}” }, “openai:default”: { mode: “api_key”, apiKey: “${OPENAI_API_KEY}” }, }, order: { anthropic: [“anthropic:subscription”, “anthropic:api”], openai: [“openai:default”], }, } 当某个模型达到速率限制或身份验证失败时,OpenClaw 会尝试使用该提供商列表中的下一个模型。如果某个提供商的所有模型都失败,则会切换到列表中的下一个模型agents.defaults.model.fallbacks。配置跨提供商回退机制(Anthropic → OpenAI,而不是 Anthropic → Anthropic)可以避免已知问题,即一个模型达到限制会导致整个提供商进入冷却状态。
- session: { dmScope: “per-channel-peer”, // Options: // “main” — all DMs share one session (single-user default) // “per-peer” — isolate by sender ID across all channels // “per-channel-peer” — isolate by sender + channel (recommended for multi-user) // “per-account-channel-peer” — most granular threadBindings: { enabled: true, idleHours: 24, // auto-unbind thread after this many idle hours maxAgeHours: 0, // 0 = no max age }, reset: { mode: “daily”, // none | daily | idle atHour: 4, // UTC hour for daily reset idleMinutes: 120, // for idle mode }, identityLinks: { // Link one user’s identities across channels alice: [“telegram:123456”, “discord:987654”], }, } 适用dmScope: "per-channel-peer"于多人可以私信您的代理的任何场景。默认情况下"main",所有用户共享同一个会话,这意味着 Alice 的私密对话内容对 Bob 可见。这属于数据泄露,而不仅仅是偏好设置问题。请参阅隐私和合规性指南。
- sandbox: { mode: “non-main”, // off | all | non-main scope: “session”, docker: { image: “openclaw-sandbox:bookworm-slim”, network: “none”, // no outbound network from sandbox readOnlyRoot: true, cpus: “1”, memoryMb: 512, }, } "non-main"在隔离的 Docker 容器内运行子代理和定时任务,同时保持主机上的主 DM 会话运行。"all"所有操作均在沙箱中进行。需要在网关镜像中包含 Docker CLI OPENCLAW_INSTALL_DOCKER_CLI=1,并需要 Docker 套接字访问权限。
- 需要重启网关的设置: gateway.port(gateway.bind无法重新绑定活动套接字) gateway.reload(而且gateway.remote,这是有意为之——这些不会触发重新装弹) 沙箱 Docker 镜像或网络配置 插件安装或移除 无需重启即可热应用的设置:模型和回退更改、代理配置更改、通道策略(dmPolicy、allowFrom)、定时任务、心跳间隔、工具配置和大多数会话设置。
- # Interactive setup wizard openclaw onboard # Setup + install daemon in one step (most common first-run command) openclaw onboard –install-daemon # Re-run specific setup steps openclaw configure # Non-interactive (Docker, CI) openclaw onboard –non-interactive # Reset config only (preserves sessions and credentials) openclaw reset –scope config # Reset config + credentials + sessions (keeps workspace) openclaw reset –scope config+creds+sessions # Full nuclear reset (includes workspace) openclaw reset –scope full
- openclaw doctor这是整个命令行界面中最有用的单个命令。在任何配置更改后、任何升级后以及网关出现异常行为时,都应该运行它。 # Basic health check (read-only, safe any time) openclaw doctor # Health check + auto-fix openclaw doctor –fix # Deep scan (more thorough, slower) openclaw doctor –deep –yes # Non-interactive (for scripts) openclaw doctor –non-interactive # Full status dump openclaw status –all –deep # Status as JSON openclaw status –json # Direct gateway health probe (works even if daemon is down) openclaw health –json –verbose # Security audit openclaw security audit openclaw security audit –fix # Check for credential leaks openclaw secrets audit –check
- # Run in foreground (debugging) openclaw gateway run # Run on a non-default port openclaw gateway run –port 19000 –bind loopback # Force-kill any process on the port, then start fresh openclaw gateway run –force # Daemon control (requires daemon to be installed) openclaw gateway start openclaw gateway stop openclaw gateway restart openclaw gateway status # Install/manage daemon openclaw daemon install openclaw daemon install –user # user-level systemd service openclaw daemon start | stop | restart | status | logs | uninstall # Open Control UI in browser openclaw dashboard # Remote terminal UI (connect to a remote gateway) openclaw tui –url https://example.com –token YOUR_TOKEN
- 建议优先openclaw config使用命令行界面写入,而不是直接编辑文件。命令行写入操作会经过相同的 JSON5 解析器和模式验证,因此不会引入未知键。 # Get a specific value openclaw config get agents.defaults.model.primary openclaw config get gateway.port # Get everything (pretty-printed) openclaw config get # Set a value openclaw config set agents.defaults.heartbeat.every “2h” openclaw config set agents.defaults.maxConcurrent 8 openclaw config set gateway.bind “loopback” # Unset (remove) a key openclaw config unset tools.web.search.apiKey openclaw config unset agents.defaults.heartbeat
- # List channels openclaw channels list # Status check (connection health) openclaw channels status openclaw channels status –probe –all # runs extra connectivity checks # Channel-specific logs openclaw channels logs –channel telegram openclaw channels logs –channel discord –limit 100 # Add a channel (interactive wizard) openclaw channels add –channel telegram openclaw channels add –channel discord # Add non-interactively openclaw channels add –channel telegram –account main –name “My Bot” –token “$TELEGRAM_BOT_TOKEN” # WhatsApp and OAuth login (QR scan / browser flow) openclaw channels login openclaw channels login whatsapp # Approve pairing code from a new DM sender openclaw pairing approve telegram CODE123 # Remove a channel (disables by default) openclaw channels remove –channel telegram openclaw channels remove –channel discord –delete # also removes config entry
- # Tail live logs (colorized in TTY) openclaw logs –follow # Output as JSON (one event per line, for piping) openclaw logs –json # Limit output lines openclaw logs –limit 200 # Filter by log level openclaw logs –level warn # Channel-specific logs openclaw channels logs –channel whatsapp
- # List configured models openclaw models list openclaw models list –all # includes full catalog # Check model status and auth openclaw models status openclaw models status –probe # test connectivity per provider # Change primary model openclaw models set anthropic/claude-sonnet-4-5 # Set image model (for vision inputs) openclaw models set-image openai/gpt-4o # Manage aliases openclaw models aliases list openclaw models aliases add fast anthropic/claude-haiku-4-5 # Manage fallbacks openclaw models fallbacks list openclaw models fallbacks add openai/gpt-5-mini openclaw models fallbacks clear # Auth management openclaw models auth add openclaw models auth setup-token openclaw models auth order get openclaw models auth order set anthropic “anthropic:subscription,anthropic:api”
- # List agents openclaw agents list # Add an agent (interactive) openclaw agents add # Add non-interactively openclaw agents add –id “work” –workspace ~/work-agent –non-interactive # List routing bindings openclaw agents acp list # Add binding (route a channel/group to a specific agent) openclaw agents acp add –agent work –channel telegram –group-id -1001234567 # Remove binding openclaw agents acp remove –agent work –channel telegram # Run one agent turn directly (bypasses channel) openclaw agent –message “What needs my attention today?” # Delete an agent openclaw agents delete –id work
- # Memory index status openclaw memory status # Re-index all workspace memory files openclaw memory index –all # Search memory openclaw memory search –query “deployment notes” # Send a message to a specific session openclaw message agent –session “session-key” –message “Status update?”
- # List all cron jobs openclaw cron list –all # Show cron job status openclaw cron status # Add a cron job (one-time at specific time) openclaw cron add –name “morning-brief” –at “2026-04-01T09:00:00Z” –message “Summarize emails and calendar for today” # Add recurring (interval in milliseconds) openclaw cron add –name “hourly-check” –every 3600000 –message “Check for priority items” # Add with cron expression openclaw cron add –name “weekly-report” –cron “0 9 * * 1” –message “Generate weekly summary” # Run a job immediately (ignoring schedule) openclaw cron run –id morning-brief # Enable/disable openclaw cron enable –id morning-brief openclaw cron disable –id morning-brief # View run history openclaw cron runs –id morning-brief –limit 10 # Edit an existing job openclaw cron edit –id morning-brief # Remove a job openclaw cron rm –id morning-brief
- # List installed skills openclaw skills list # Show skill details openclaw skills info web-search # Check eligibility (verify requirements are met) openclaw skills check –eligible # Plugin management openclaw plugins list openclaw plugins info my-plugin openclaw plugins install my-plugin openclaw plugins enable my-plugin openclaw plugins disable my-plugin openclaw plugins doctor # report plugin load errors
- # List conversation sessions openclaw sessions –json # Clean up old session files openclaw sessions cleanup # Device management openclaw devices list openclaw devices node run –id DEVICE_ID # Approvals (for tools that require human confirmation) openclaw approvals get openclaw approvals set –policy “auto” openclaw approvals allowlist add “exec”
- # Update to latest stable openclaw update # Switch update channel openclaw update –channel stable # stable | beta | dev # Migrate config after a major version upgrade openclaw migrate
- 这些标志可以与任何命令一起使用: –dev # Use dev environment (separate state directory) –profile <name> # Use a named profile (separate state directory) –json # Output as JSON –verbose # Verbose logging –no-color # Disable ANSI color output –log-level debug # Set log level (debug | info | warn | error)
- OpenClaw 会按以下顺序解析环境变量,先解析的变量优先。一旦某个变量被设置,后解析的变量就不会覆盖它: 进程环境(启动网关时 shell 中已有的变量) .env在当前工作目录中(如果网关启动时存在) ~/.openclaw/.env(全局回退) env.vars在 openclaw.json 中(内联配置变量,非覆盖) 配置块env.vars用于设置默认值,这些默认值不会覆盖环境中已有的值。请将其用于非敏感的配置值。~/.openclaw/.env凭据信息请使用或处理环境变量。
- # Config paths OPENCLAW_HOME=~/.openclaw # Base directory OPENCLAW_CONFIG_PATH=/path/to/openclaw.json # Override config file location # Logging OPENCLAW_LOG_LEVEL=debug # debug | info | warn | error OPENCLAW_LOG_FORMAT=json # for structured log output # Model API keys (referenced via ${VAR} in config) ANTHROPIC_API_KEY=sk-ant-… OPENAI_API_KEY=sk-… OPENROUTER_API_KEY=sk-or-… # Gateway OPENCLAW_GATEWAY_TOKEN=your-token # Overrides gateway.auth.token in config
- 任何字符串值都openclaw.json可以引用环境变量${VAR_NAME}。这会在 Gateway 启动时进行评估。要使用字面美元符号,请对其进行转义:$${NOT_A_VAR}。 models: { providers: { anthropic: { apiKey: “${ANTHROPIC_API_KEY}”, }, }, } channels: { telegram: { botToken: “${TELEGRAM_BOT_TOKEN}”, }, } 为了更安全地处理凭据,请使用 SecretRef 系统,而不是直接使用环境变量。有关如何从配置中引用 Docker 密钥、HashiCorp Vault 和 1Password 的信息,请参阅密钥管理指南。
- 此env.shellEnv.enabled: true设置会运行您的登录 shell 并从中导入环境变量。当您在 shell 配置文件中设置了 API 密钥(例如 `<shell_config_file>` 和 `<shell_config_file> ~/.bashrc` ~/.zshrc)并希望 OpenClaw 能够自动获取这些密钥而无需在 ` <shell_config_file>` 中重复设置时,此功能非常有用~/.openclaw/.env。如果您的 shell 启动缓慢或占用资源过多,请设置此设置env.shellEnv.timeoutMs以限制导入等待的时间。
- .gitignoreOpenClaw 配置仓库的最小示例: # Credentials .env *.env credentials/ # Sessions (large, ephemeral, contain private conversation content) sessions/ *.jsonl # Memory files (personal content) workspace/memory/ workspace/MEMORY.md # Cron job state (runtime state, not config) cron/runs/ # Runtime state *.lock tmp/ 您可以openclaw.json安全地进行版本控制的内容包括:使用${VAR}引用代替实际键的结构、工作区技能文件AGENTS.md(SOUL.md如果它们不包含个人信息)以及 cron 作业定义cron/jobs.json。
- 添加truffleHog或gitleaks作为 pre-commit hook,以便在提交配置文件之前捕获任何意外添加到配置文件中的凭据。快速手动检查: # Scan for leaked keys before committing grep -rE “sk-ant-|sk-or-|sk-[A-Za-z0-9]{40}” ~/.openclaw/openclaw.json # Should find nothing; all key references should be ${VAR} syntax
- 每个 OpenClaw 版本都可能添加或重命名配置键,并且架构在不同版本之间也可能发生变化。升级后,务必运行openclaw doctor –fix命令删除过时的键并添加任何必需的新字段。未能执行此操作是导致设置看似已配置但未生效的最常见原因——从架构中静默删除的旧键会被忽略而不是报错,因此网关可以启动,但设置没有任何作用。有关完整的升级检查清单,请参阅升级和维护指南。 到此这篇关于OpenClaw CLI 和配置文件参考完整指南的文章就介绍到这了,更多相关OpenClaw CLI 配置文件内容请搜索风君子博客以前的文章或继续浏览下面的相关文章,希望大家以后多多支持风君子博客!
目录
- openclaw.json 配置文件
- 文件格式、位置和验证规则
- 顶层配置结构
- 网关部分
- 代理部分:默认值和每个代理的自定义设置
- 上下文剪枝与上下文压缩:详解
- 模型部分
- 身份验证部分:提供商故障转移配置文件
- 会话部分
- 沙盒部分
- 热重载:哪些操作可实时执行,哪些操作需要重启
- CLI 参考
- 设置和入职
- 医生和诊断
- 网关管理
- 配置管理
- 渠道管理
- 日志
- 模型管理
- 代理管理
- 内存管理
- 定时任务管理
- 技能和插件
- 会话和设备
- 更新管理
- 全球标志
- 环境变量
- 决议令
- 关键环境变量
- 配置中的变量替换
- Shell 环境集成
- 在版本控制下管理配置
- 哪些内容需要版本控制,哪些内容需要排除在外
- 预提交凭证扫描
- 升级后配置偏差
OpenClaw 的配置完全通过一个 JSON5 文件~/.openclaw/openclaw.json和一个包含 100 多个子命令的 CLI 来实现。然而,这两者都没有统一的完整文档。官方 CLI 参考文档列出了命令树;配置参考文档解释了各个字段;但连接它们的实用模式、模式严格性、热重载行为和配置层级结构等方面的注意事项,都分散在 GitHub issues、社区运行手册和生产环境的复盘报告中。
本指南全面涵盖了这两方面。首先介绍配置文件:格式、结构以及每个主要部分的示例。然后介绍命令行界面 (CLI):按工作流程而非字母顺序组织,方便您快速找到网关管理、通道设置、诊断和自动化所需的内容。最后介绍环境变量、其解析顺序以及如何在版本控制下安全地管理配置。
配置文件采用JSON5 格式,而非纯 JSON。这意味着注释(` // like this&`)、尾随逗号和未加引号的键值都是有效的。该文件默认位于 `/etc/config/ ~/.openclaw/openclaw.jsonconfig`。您可以使用OPENCLAW_CONFIG_PATH环境变量或–profile <name>CLI 标志覆盖其默认位置,这将把所有状态隔离到一个单独的目录中,这对于测试或运行多个隔离实例非常有用。
Zod 会在启动时强制执行架构验证。未知键会导致网关拒绝启动。没有警告模式,也没有优雅降级:如果您添加了架构中不存在的键,网关将无法启动,并且错误消息会指向错误的键。这是在手动编辑文件之前必须了解的最重要的一点。安全的编辑工作流程:
# 1. Back up first — always cp ~/.openclaw/openclaw.json ~/.openclaw/openclaw.json.bak # 2. Edit the file # 3. Validate JSON5 syntax cat ~/.openclaw/openclaw.json | python3 -m json.tool # 4. Validate schema and fix any issues openclaw doctor --fix
网关会监视文件更改,并在无需重启的情况下热重载大多数设置。“大多数”这个词很重要——请参阅下面的热重载部分,了解哪些更改需要重启,哪些不需要,因为在生产环境中,静默失败的热重载常常会造成混乱。
所有顶级部分的完整概览:
{
// Written by the wizard — don't edit manually
meta: { lastTouchedVersion: "...", lastTouchedAt: "..." },
gateway: { ... }, // Port, bind address, auth token
update: { channel: "stable" }, // stable | beta | dev
env: { shellEnv: { enabled: true }, vars: { KEY: "value" } },
agents: { defaults: { ... }, list: [ ... ] }, // Agent config + overrides
models: { mode: "merge", providers: { ... } }, // LLM providers
auth: { profiles: { ... }, order: { ... } }, // Provider failover
channels: { telegram: { ... }, discord: { ... } }, // Messaging channels
session: { dmScope: "per-channel-peer", reset: { ... } },
bindings: [ { agentId: "...", match: { ... } } ], // Multi-agent routing
cron: { enabled: true, maxConcurrentRuns: 2 },
tools: { web: { search: { provider: "brave", apiKey: "..." } } },
sandbox: { mode: "non-main", docker: { ... } },
logging: { level: "info", consoleLevel: "warn" },
skills: { install: { nodeManager: "pnpm" } },
}
控制网关进程的绑定、身份验证和重新加载方式:
gateway: {
port: 18789,
mode: "local", // local | cloud
bind: "loopback", // loopback = 127.0.0.1 only (recommended)
// all = 0.0.0.0 (requires auth token)
auth: {
mode: "token",
token: "your-generated-token",
allowTailscale: true, // Tailscale IPs bypass token check
},
controlUi: {
enabled: true,
dangerouslyDisableDeviceAuth: false, // never true on shared hosts
},
reload: "hybrid", // hot | hybrid | restart
}
bind: "loopback"务必在 VPS 部署中使用此功能。bind: "all"如果没有强身份验证令牌,网关将暴露在互联网上。暴露在公共 IP 上的 OpenClaw 网关会导致 API 密钥、OAuth 令牌和会话历史记录泄露。如果没有身份验证令牌,网关将拒绝绑定到非环回地址。有关反向代理设置,请参阅VPS 安全指南。
该reload字段控制热重载行为。"hybrid"尽可能实时应用更改,仅在必要时重启。gateway.reload还有gateway.remote两个字段在更改时不会触发重新加载——如果您更改了其中任何一个字段,请手动重启网关。
代理部分采用“默认值+覆盖”模式,agents.defaults为每个代理设置基线。每个条目都agents.list可以覆盖特定字段。网关在运行时合并这些覆盖项:代理特定的配置优先,其余部分使用默认值。
agents: {
defaults: {
workspace: "~/.openclaw/workspace",
model: {
primary: "anthropic/claude-sonnet-4-5",
fallbacks: [
"openai/gpt-5-mini",
"openrouter/google/gemini-3-flash-preview",
],
},
// Alias shortcuts used with the :model slash command
models: {
"anthropic/claude-haiku-4-5": { alias: "haiku" },
"anthropic/claude-sonnet-4-5": { alias: "sonnet" },
"anthropic/claude-opus-4-6": { alias: "opus" },
},
maxConcurrent: 4,
// Context pruning: trims old tool results before each LLM call
contextPruning: {
mode: "cache-ttl", // off | cache-ttl
ttl: "45m",
keepLastAssistants: 2,
minPrunableToolChars: 12000,
softTrim: { maxChars: 2500, headChars: 900, tailChars: 900 },
hardClear: { enabled: true, placeholder: "[Old tool result cleared]" },
tools: { deny: ["browser", "canvas"] },
},
// Compaction: summarizes full history when context window fills
compaction: {
mode: "safeguard", // default | safeguard
reserveTokensFloor: 12000,
identifierPolicy: "strict",
memoryFlush: {
enabled: true,
softThresholdTokens: 6000,
prompt: "Write any lasting notes to memory/YYYY-MM-DD.md; reply with NO_REPLY if nothing to store.",
systemPrompt: "Session nearing compaction.",
},
},
// Heartbeat
heartbeat: {
every: "30m",
mode: "next-heartbeat",
},
},
list: [
{ id: "main", default: true },
{
id: "work",
workspace: "~/work-agent",
model: { primary: "anthropic/claude-opus-4-6" },
lane: "work-lane",
laneConcurrency: 4,
},
],
}
一个关键限制:某些字段仅在代理级别生效,如果按代理设置,agents.defaults则会被静默忽略。压缩设置、浏览器配置文件默认值和思考级别覆盖都属于此类。网关不会发出警告——热重载根本不会执行。此命令会查找并删除这些无效的代理级别键。请务必在编辑代理特定配置后运行此命令。openclaw doctor –fix
contextPruning在每次 LLM 调用之前运行。它会检查内存中的上下文,并修剪超过 TTL 或大小阈值的旧工具结果。它不会触及磁盘上的会话文件,只会处理发送给模型的内容。如果没有 contextPruning,运行多次工具调用的会话会在上下文中积累巨大的工具结果有效负载。这正是 GitHub 问题 #2254 中记录的模式的根本原因:35 条消息生成了一个 2.9MB 的会话文件和一个包含 208,467 个令牌的上下文,当超出模型 200k 的限制时,上下文会静默停止响应。启用 contextPruningcontextPruning可以避免mode: "cache-ttl"这种情况。
当上下文窗口接近其极限时,压缩操作会运行。网关会汇总会话历史记录,并可选择先通过 `dual memory file` 将备注写入每日内存文件memoryFlush,然后用汇总结果替换完整的历史记录。"safeguard"对于非常长的历史记录,此模式会进行分块汇总,而不是尝试在一次 LLM 调用中汇总所有内容。生产环境中应同时启用这两个功能——较旧的配置可能contextPruning根本没有启用,因为它后来成为了默认设置。
models: {
mode: "merge", // merge = combine provider lists; replace = replace defaults
providers: {
anthropic: {
apiKey: "${ANTHROPIC_API_KEY}",
},
openai: {
apiKey: "${OPENAI_API_KEY}",
},
// LM Studio (OpenAI-compatible local server)
"lmstudio": {
baseUrl: "http://127.0.0.1:1234/v1",
apiKey: "lmstudio",
api: "openai-responses",
models: [
{
id: "lmstudio/qwen2.5-coder-7b",
name: "Qwen 2.5 Coder 7B",
reasoning: false,
input: ["text"],
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
contextWindow: 32768,
maxTokens: 8000,
},
],
},
// Ollama
ollama: {
baseUrl: "http://localhost:11434",
apiKey: "ollama-local",
api: "openai-completions",
models: [ ... ],
},
},
}
该api字段控制使用的请求格式。"openai-responses"适用于大多数兼容 OpenAI 的本地服务器;"openai-completions"适用于 Ollama;"anthropic"适用于 Anthropic API。如果模型不支持工具调用,请进行设置reasoning: false,并且不要将其用作主代理模型——OpenClaw 的工具系统需要函数调用支持。
每个提供商支持多个身份验证配置文件,以便在速率限制时自动进行故障转移。会话始终绑定到一个配置文件(用于缓存预热),并在缓存/new压缩时重置:
auth: {
profiles: {
"anthropic:subscription": { mode: "oauth", email: "you@example.com" },
"anthropic:api": { mode: "api_key", apiKey: "${ANTHROPIC_API_KEY}" },
"openai:default": { mode: "api_key", apiKey: "${OPENAI_API_KEY}" },
},
order: {
anthropic: ["anthropic:subscription", "anthropic:api"],
openai: ["openai:default"],
},
}
当某个模型达到速率限制或身份验证失败时,OpenClaw 会尝试使用该提供商列表中的下一个模型。如果某个提供商的所有模型都失败,则会切换到列表中的下一个模型agents.defaults.model.fallbacks。配置跨提供商回退机制(Anthropic → OpenAI,而不是 Anthropic → Anthropic)可以避免已知问题,即一个模型达到限制会导致整个提供商进入冷却状态。
session: {
dmScope: "per-channel-peer",
// Options:
// "main" — all DMs share one session (single-user default)
// "per-peer" — isolate by sender ID across all channels
// "per-channel-peer" — isolate by sender + channel (recommended for multi-user)
// "per-account-channel-peer" — most granular
threadBindings: {
enabled: true,
idleHours: 24, // auto-unbind thread after this many idle hours
maxAgeHours: 0, // 0 = no max age
},
reset: {
mode: "daily", // none | daily | idle
atHour: 4, // UTC hour for daily reset
idleMinutes: 120, // for idle mode
},
identityLinks: {
// Link one user's identities across channels
alice: ["telegram:123456", "discord:987654"],
},
}
适用dmScope: "per-channel-peer"于多人可以私信您的代理的任何场景。默认情况下"main",所有用户共享同一个会话,这意味着 Alice 的私密对话内容对 Bob 可见。这属于数据泄露,而不仅仅是偏好设置问题。请参阅隐私和合规性指南。
sandbox: {
mode: "non-main", // off | all | non-main
scope: "session",
docker: {
image: "openclaw-sandbox:bookworm-slim",
network: "none", // no outbound network from sandbox
readOnlyRoot: true,
cpus: "1",
memoryMb: 512,
},
}
"non-main"在隔离的 Docker 容器内运行子代理和定时任务,同时保持主机上的主 DM 会话运行。"all"所有操作均在沙箱中进行。需要在网关镜像中包含 Docker CLI OPENCLAW_INSTALL_DOCKER_CLI=1,并需要 Docker 套接字访问权限。
需要重启网关的设置:
- gateway.port(gateway.bind无法重新绑定活动套接字)
- gateway.reload(而且gateway.remote,这是有意为之——这些不会触发重新装弹)
- 沙箱 Docker 镜像或网络配置
- 插件安装或移除
无需重启即可热应用的设置:模型和回退更改、代理配置更改、通道策略(dmPolicy、allowFrom)、定时任务、心跳间隔、工具配置和大多数会话设置。
# Interactive setup wizard
openclaw onboard
# Setup + install daemon in one step (most common first-run command)
openclaw onboard --install-daemon
# Re-run specific setup steps
openclaw configure
# Non-interactive (Docker, CI)
openclaw onboard --non-interactive
# Reset config only (preserves sessions and credentials)
openclaw reset --scope config
# Reset config + credentials + sessions (keeps workspace)
openclaw reset --scope config+creds+sessions
# Full nuclear reset (includes workspace)
openclaw reset --scope full
openclaw doctor这是整个命令行界面中最有用的单个命令。在任何配置更改后、任何升级后以及网关出现异常行为时,都应该运行它。
# Basic health check (read-only, safe any time) openclaw doctor # Health check + auto-fix openclaw doctor --fix # Deep scan (more thorough, slower) openclaw doctor --deep --yes # Non-interactive (for scripts) openclaw doctor --non-interactive # Full status dump openclaw status --all --deep # Status as JSON openclaw status --json # Direct gateway health probe (works even if daemon is down) openclaw health --json --verbose # Security audit openclaw security audit openclaw security audit --fix # Check for credential leaks openclaw secrets audit --check
# Run in foreground (debugging)
openclaw gateway run
# Run on a non-default port
openclaw gateway run --port 19000 --bind loopback
# Force-kill any process on the port, then start fresh
openclaw gateway run --force
# Daemon control (requires daemon to be installed)
openclaw gateway start
openclaw gateway stop
openclaw gateway restart
openclaw gateway status
# Install/manage daemon
openclaw daemon install
openclaw daemon install --user # user-level systemd service
openclaw daemon start | stop | restart | status | logs | uninstall
# Open Control UI in browser
openclaw dashboard
# Remote terminal UI (connect to a remote gateway)
openclaw tui --url https://example.com --token YOUR_TOKEN
建议优先openclaw config使用命令行界面写入,而不是直接编辑文件。命令行写入操作会经过相同的 JSON5 解析器和模式验证,因此不会引入未知键。
# Get a specific value openclaw config get agents.defaults.model.primary openclaw config get gateway.port # Get everything (pretty-printed) openclaw config get # Set a value openclaw config set agents.defaults.heartbeat.every "2h" openclaw config set agents.defaults.maxConcurrent 8 openclaw config set gateway.bind "loopback" # Unset (remove) a key openclaw config unset tools.web.search.apiKey openclaw config unset agents.defaults.heartbeat
# List channels
openclaw channels list
# Status check (connection health)
openclaw channels status
openclaw channels status --probe --all # runs extra connectivity checks
# Channel-specific logs
openclaw channels logs --channel telegram
openclaw channels logs --channel discord --limit 100
# Add a channel (interactive wizard)
openclaw channels add --channel telegram
openclaw channels add --channel discord
# Add non-interactively
openclaw channels add --channel telegram
--account main
--name "My Bot"
--token "$TELEGRAM_BOT_TOKEN"
# WhatsApp and OAuth login (QR scan / browser flow)
openclaw channels login
openclaw channels login whatsapp
# Approve pairing code from a new DM sender
openclaw pairing approve telegram CODE123
# Remove a channel (disables by default)
openclaw channels remove --channel telegram
openclaw channels remove --channel discord --delete # also removes config entry
# Tail live logs (colorized in TTY)
openclaw logs --follow
# Output as JSON (one event per line, for piping)
openclaw logs --json
# Limit output lines
openclaw logs --limit 200
# Filter by log level
openclaw logs --level warn
# Channel-specific logs
openclaw channels logs --channel whatsapp
# List configured models
openclaw models list
openclaw models list --all # includes full catalog
# Check model status and auth
openclaw models status
openclaw models status --probe # test connectivity per provider
# Change primary model
openclaw models set anthropic/claude-sonnet-4-5
# Set image model (for vision inputs)
openclaw models set-image openai/gpt-4o
# Manage aliases
openclaw models aliases list
openclaw models aliases add fast anthropic/claude-haiku-4-5
# Manage fallbacks
openclaw models fallbacks list
openclaw models fallbacks add openai/gpt-5-mini
openclaw models fallbacks clear
# Auth management
openclaw models auth add
openclaw models auth setup-token
openclaw models auth order get
openclaw models auth order set anthropic "anthropic:subscription,anthropic:api"
# List agents
openclaw agents list
# Add an agent (interactive)
openclaw agents add
# Add non-interactively
openclaw agents add --id "work" --workspace ~/work-agent --non-interactive
# List routing bindings
openclaw agents acp list
# Add binding (route a channel/group to a specific agent)
openclaw agents acp add --agent work --channel telegram --group-id -1001234567
# Remove binding
openclaw agents acp remove --agent work --channel telegram
# Run one agent turn directly (bypasses channel)
openclaw agent --message "What needs my attention today?"
# Delete an agent
openclaw agents delete --id work
# Memory index status
openclaw memory status
# Re-index all workspace memory files
openclaw memory index --all
# Search memory
openclaw memory search --query "deployment notes"
# Send a message to a specific session
openclaw message agent --session "session-key" --message "Status update?"
# List all cron jobs
openclaw cron list --all
# Show cron job status
openclaw cron status
# Add a cron job (one-time at specific time)
openclaw cron add
--name "morning-brief"
--at "2026-04-01T09:00:00Z"
--message "Summarize emails and calendar for today"
# Add recurring (interval in milliseconds)
openclaw cron add
--name "hourly-check"
--every 3600000
--message "Check for priority items"
# Add with cron expression
openclaw cron add
--name "weekly-report"
--cron "0 9 * * 1"
--message "Generate weekly summary"
# Run a job immediately (ignoring schedule)
openclaw cron run --id morning-brief
# Enable/disable
openclaw cron enable --id morning-brief
openclaw cron disable --id morning-brief
# View run history
openclaw cron runs --id morning-brief --limit 10
# Edit an existing job
openclaw cron edit --id morning-brief
# Remove a job
openclaw cron rm --id morning-brief
# List installed skills
openclaw skills list
# Show skill details
openclaw skills info web-search
# Check eligibility (verify requirements are met)
openclaw skills check --eligible
# Plugin management
openclaw plugins list
openclaw plugins info my-plugin
openclaw plugins install my-plugin
openclaw plugins enable my-plugin
openclaw plugins disable my-plugin
openclaw plugins doctor # report plugin load errors
# List conversation sessions
openclaw sessions --json
# Clean up old session files
openclaw sessions cleanup
# Device management
openclaw devices list
openclaw devices node run --id DEVICE_ID
# Approvals (for tools that require human confirmation)
openclaw approvals get
openclaw approvals set --policy "auto"
openclaw approvals allowlist add "exec"
# Update to latest stable
openclaw update
# Switch update channel
openclaw update --channel stable # stable | beta | dev
# Migrate config after a major version upgrade
openclaw migrate
这些标志可以与任何命令一起使用:
--dev # Use dev environment (separate state directory) --profile <name> # Use a named profile (separate state directory) --json # Output as JSON --verbose # Verbose logging --no-color # Disable ANSI color output --log-level debug # Set log level (debug | info | warn | error)
OpenClaw 会按以下顺序解析环境变量,先解析的变量优先。一旦某个变量被设置,后解析的变量就不会覆盖它:
- 进程环境(启动网关时 shell 中已有的变量)
- .env在当前工作目录中(如果网关启动时存在)
- ~/.openclaw/.env(全局回退)
- env.vars在 openclaw.json 中(内联配置变量,非覆盖)
配置块env.vars用于设置默认值,这些默认值不会覆盖环境中已有的值。请将其用于非敏感的配置值。~/.openclaw/.env凭据信息请使用或处理环境变量。
# Config paths
OPENCLAW_HOME=~/.openclaw # Base directory
OPENCLAW_CONFIG_PATH=/path/to/openclaw.json # Override config file location
# Logging
OPENCLAW_LOG_LEVEL=debug # debug | info | warn | error
OPENCLAW_LOG_FORMAT=json # for structured log output
# Model API keys (referenced via ${VAR} in config)
ANTHROPIC_API_KEY=sk-ant-...
OPENAI_API_KEY=sk-...
OPENROUTER_API_KEY=sk-or-...
# Gateway
OPENCLAW_GATEWAY_TOKEN=your-token # Overrides gateway.auth.token in config
任何字符串值都openclaw.json可以引用环境变量${VAR_NAME}。这会在 Gateway 启动时进行评估。要使用字面美元符号,请对其进行转义:$${NOT_A_VAR}。
models: {
providers: {
anthropic: {
apiKey: "${ANTHROPIC_API_KEY}",
},
},
}
channels: {
telegram: {
botToken: "${TELEGRAM_BOT_TOKEN}",
},
}
为了更安全地处理凭据,请使用 SecretRef 系统,而不是直接使用环境变量。有关如何从配置中引用 Docker 密钥、HashiCorp Vault 和 1Password 的信息,请参阅密钥管理指南。
此env.shellEnv.enabled: true设置会运行您的登录 shell 并从中导入环境变量。当您在 shell 配置文件中设置了 API 密钥(例如 `<shell_config_file>` 和 `<shell_config_file> ~/.bashrc` ~/.zshrc)并希望 OpenClaw 能够自动获取这些密钥而无需在 ` <shell_config_file>` 中重复设置时,此功能非常有用~/.openclaw/.env。如果您的 shell 启动缓慢或占用资源过多,请设置此设置env.shellEnv.timeoutMs以限制导入等待的时间。
配置文件~/.openclaw/openclaw.json包含基础架构配置(可以安全地进行版本控制)和凭据(绝对不能提交)。最简单的做法是:使用经过脱敏处理的模板进行版本控制,将所有敏感值替换为环境变量引用,并将实际凭据仅保留在~/.openclaw/.env密钥管理器中。
.gitignoreOpenClaw 配置仓库的最小示例:
# Credentials .env *.env credentials/ # Sessions (large, ephemeral, contain private conversation content) sessions/ *.jsonl # Memory files (personal content) workspace/memory/ workspace/MEMORY.md # Cron job state (runtime state, not config) cron/runs/ # Runtime state *.lock tmp/
您可以openclaw.json安全地进行版本控制的内容包括:使用${VAR}引用代替实际键的结构、工作区技能文件AGENTS.md(SOUL.md如果它们不包含个人信息)以及 cron 作业定义cron/jobs.json。
添加truffleHog或gitleaks作为 pre-commit hook,以便在提交配置文件之前捕获任何意外添加到配置文件中的凭据。快速手动检查:
# Scan for leaked keys before committing
grep -rE "sk-ant-|sk-or-|sk-[A-Za-z0-9]{40}" ~/.openclaw/openclaw.json
# Should find nothing; all key references should be ${VAR} syntax
每个 OpenClaw 版本都可能添加或重命名配置键,并且架构在不同版本之间也可能发生变化。升级后,务必运行openclaw doctor –fix命令删除过时的键并添加任何必需的新字段。未能执行此操作是导致设置看似已配置但未生效的最常见原因——从架构中静默删除的旧键会被忽略而不是报错,因此网关可以启动,但设置没有任何作用。有关完整的升级检查清单,请参阅升级和维护指南。
到此这篇关于OpenClaw CLI 和配置文件参考完整指南的文章就介绍到这了,更多相关OpenClaw CLI 配置文件内容请搜索风君子博客以前的文章或继续浏览下面的相关文章,希望大家以后多多支持风君子博客!