From 31624a2a501bcf800505502377667d638396f408 Mon Sep 17 00:00:00 2001 From: loveuer Date: Tue, 17 Nov 2026 16:00:15 +0800 Subject: [PATCH] docs: align guides with the slimmed fork Refresh setup, Docker, release, and contribution guidance. Fix channel settings examples and credential documentation. Remove Antigravity tutorials and redirect outdated translations. Align platform, model routing, and troubleshooting instructions. --- CONTRIBUTING.md | 314 +------- README.md | 10 +- docs/README.md | 2 + docs/architecture/routing-system.md | 2 +- docs/architecture/session-system.md | 2 +- docs/architecture/subturn.md | 2 +- docs/channels/dingtalk/README.fr.md | 8 +- docs/channels/dingtalk/README.ja.md | 8 +- docs/channels/dingtalk/README.md | 10 +- docs/channels/dingtalk/README.pt-br.md | 8 +- docs/channels/dingtalk/README.vi.md | 8 +- docs/channels/dingtalk/README.zh.md | 10 +- docs/channels/feishu/README.fr.md | 12 +- docs/channels/feishu/README.ja.md | 12 +- docs/channels/feishu/README.md | 14 +- docs/channels/feishu/README.pt-br.md | 12 +- docs/channels/feishu/README.vi.md | 12 +- docs/channels/feishu/README.zh.md | 20 +- docs/channels/mqtt/README.md | 2 + docs/channels/mqtt/README.zh.md | 2 + docs/channels/onebot/README.fr.md | 8 +- docs/channels/onebot/README.ja.md | 8 +- docs/channels/onebot/README.md | 10 +- docs/channels/onebot/README.pt-br.md | 8 +- docs/channels/onebot/README.vi.md | 8 +- docs/channels/onebot/README.zh.md | 10 +- docs/channels/qq/README.fr.md | 8 +- docs/channels/qq/README.ja.md | 8 +- docs/channels/qq/README.md | 10 +- docs/channels/qq/README.pt-br.md | 8 +- docs/channels/qq/README.vi.md | 8 +- docs/channels/qq/README.zh.md | 10 +- docs/channels/telegram/README.fr.md | 22 +- docs/channels/telegram/README.ja.md | 22 +- docs/channels/telegram/README.md | 28 +- docs/channels/telegram/README.pt-br.md | 22 +- docs/channels/telegram/README.vi.md | 22 +- docs/channels/telegram/README.zh.md | 26 +- docs/channels/wecom/README.fr.md | 12 +- docs/channels/wecom/README.ja.md | 12 +- docs/channels/wecom/README.md | 16 +- docs/channels/wecom/README.pt-br.md | 12 +- docs/channels/wecom/README.vi.md | 12 +- docs/channels/wecom/README.zh.md | 18 +- docs/channels/weixin/README.md | 10 +- docs/channels/weixin/README.zh.md | 10 +- docs/guides/ANTIGRAVITY_USAGE.fr.md | 72 -- docs/guides/ANTIGRAVITY_USAGE.ja.md | 72 -- docs/guides/ANTIGRAVITY_USAGE.md | 70 -- docs/guides/ANTIGRAVITY_USAGE.pt-br.md | 72 -- docs/guides/ANTIGRAVITY_USAGE.vi.md | 72 -- docs/guides/ANTIGRAVITY_USAGE.zh.md | 72 -- docs/guides/README.md | 4 +- docs/guides/android-termux.md | 87 +-- docs/guides/chat-apps.fr.md | 447 +---------- docs/guides/chat-apps.ja.md | 444 +---------- docs/guides/chat-apps.md | 66 +- docs/guides/chat-apps.ms.md | 317 +------- docs/guides/chat-apps.pt-br.md | 447 +---------- docs/guides/chat-apps.vi.md | 448 +---------- docs/guides/chat-apps.zh.md | 64 +- docs/guides/configuration.fr.md | 118 +-- docs/guides/configuration.it.md | 4 +- docs/guides/configuration.ja.md | 118 +-- docs/guides/configuration.md | 6 +- docs/guides/configuration.ms.md | 4 +- docs/guides/configuration.pt-br.md | 118 +-- docs/guides/configuration.vi.md | 118 +-- docs/guides/configuration.zh.md | 4 +- docs/guides/docker.fr.md | 155 +--- docs/guides/docker.ja.md | 157 +--- docs/guides/docker.md | 162 +--- docs/guides/docker.ms.md | 154 +--- docs/guides/docker.pt-br.md | 155 +--- docs/guides/docker.vi.md | 155 +--- docs/guides/docker.zh.md | 171 +---- docs/guides/hardware-compatibility.fr.md | 152 +--- docs/guides/hardware-compatibility.ja.md | 152 +--- docs/guides/hardware-compatibility.md | 150 +--- docs/guides/hardware-compatibility.pt-br.md | 152 +--- docs/guides/hardware-compatibility.vi.md | 152 +--- docs/guides/hardware-compatibility.zh.md | 151 +--- docs/guides/routing-guide.md | 7 +- docs/guides/routing-guide.zh.md | 5 +- docs/guides/session-guide.md | 2 +- docs/guides/spawn-tasks.md | 2 +- docs/operations/troubleshooting.fr.md | 46 +- docs/operations/troubleshooting.ja.md | 46 +- docs/operations/troubleshooting.md | 70 +- docs/operations/troubleshooting.ms.md | 44 +- docs/operations/troubleshooting.pt-br.md | 46 +- docs/operations/troubleshooting.vi.md | 46 +- docs/operations/troubleshooting.zh.md | 53 +- docs/project/CONTRIBUTING.zh.md | 304 +------- docs/reference/cron.md | 2 +- docs/reference/mcp-cli.md | 2 +- docs/security/ANTIGRAVITY_AUTH.fr.md | 809 -------------------- docs/security/ANTIGRAVITY_AUTH.ja.md | 809 -------------------- docs/security/ANTIGRAVITY_AUTH.md | 807 ------------------- docs/security/ANTIGRAVITY_AUTH.pt-br.md | 809 -------------------- docs/security/ANTIGRAVITY_AUTH.vi.md | 807 ------------------- docs/security/ANTIGRAVITY_AUTH.zh.md | 809 -------------------- docs/security/README.md | 1 - docs/security/security_configuration.md | 663 +--------------- pkg/audio/tts/README.md | 2 +- workspace/skills/picoclaw-agent/SKILL.md | 21 +- 106 files changed, 697 insertions(+), 11595 deletions(-) delete mode 100644 docs/guides/ANTIGRAVITY_USAGE.fr.md delete mode 100644 docs/guides/ANTIGRAVITY_USAGE.ja.md delete mode 100644 docs/guides/ANTIGRAVITY_USAGE.md delete mode 100644 docs/guides/ANTIGRAVITY_USAGE.pt-br.md delete mode 100644 docs/guides/ANTIGRAVITY_USAGE.vi.md delete mode 100644 docs/guides/ANTIGRAVITY_USAGE.zh.md delete mode 100644 docs/security/ANTIGRAVITY_AUTH.fr.md delete mode 100644 docs/security/ANTIGRAVITY_AUTH.ja.md delete mode 100644 docs/security/ANTIGRAVITY_AUTH.md delete mode 100644 docs/security/ANTIGRAVITY_AUTH.pt-br.md delete mode 100644 docs/security/ANTIGRAVITY_AUTH.vi.md delete mode 100644 docs/security/ANTIGRAVITY_AUTH.zh.md diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 5780bfd9..f79ac56e 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,308 +1,48 @@ -# Contributing to PicoClaw +# Contributing to this fork -Thank you for your interest in contributing to PicoClaw! This project is a community-driven effort to build the lightweight and versatile personal AI assistant. We welcome contributions of all kinds: bug fixes, features, documentation, translations, and testing. +This repository is [loveuer/picoclaw](https://github.com/loveuer/picoclaw), a smaller fork of [sipeed/picoclaw](https://github.com/sipeed/picoclaw). Its supported features and release process differ from upstream. Start with the [README](README.md) and [configuration example](config/config.example.json). -PicoClaw itself was substantially developed with AI assistance — we embrace this approach and have built our contribution process around it. +## Scope -## Table of Contents +Keep the CLI, Gateway, supported message channels, OpenAI and Anthropic protocols, tools, MCP, and Skills maintainable. Prefer optional Skills or external tools for specialized integrations such as office files and hardware. Discuss substantial changes before adding dependencies or reintroducing removed features. -- [Code of Conduct](#code-of-conduct) -- [Ways to Contribute](#ways-to-contribute) -- [Getting Started](#getting-started) -- [Development Setup](#development-setup) -- [Making Changes](#making-changes) -- [AI-Assisted Contributions](#ai-assisted-contributions) -- [Pull Request Process](#pull-request-process) -- [Branch Strategy](#branch-strategy) -- [Code Review](#code-review) -- [Communication](#communication) +The current channels are Weixin, WeCom, Feishu, DingTalk, QQ, OneBot, Telegram, and MQTT. Native Gemini, Azure, Bedrock, vendor presets, CLI model proxies, WebUI, and built-in hardware tools have been removed. Compatible model endpoints use an explicit `openai` or `anthropic` provider and `api_base`. ---- +## Development -## Code of Conduct - -We are committed to maintaining a welcoming and respectful community. Be kind, constructive, and assume good faith. Harassment or discrimination of any kind will not be tolerated. - ---- - -## Ways to Contribute - -- **Bug reports** — Open an issue using the bug report template. -- **Feature requests** — Open an issue using the feature request template; discuss before implementing. -- **Code** — Fix bugs or implement features. See the workflow below. -- **Documentation** — Improve READMEs, docs, inline comments, or translations. -- **Testing** — Run PicoClaw on new hardware, channels, or LLM providers and report your results. - -For substantial new features, please open an issue first to discuss the design before writing code. This prevents wasted effort and ensures alignment with the project's direction. - -For documentation contributions, prefer the layout and naming conventions in [`docs/README.md`](docs/README.md). Run `make lint-docs` after adding or moving Markdown files to catch common consistency issues early. - ---- - -## Getting Started - -1. **Fork** the repository on GitHub. -2. **Clone** your fork locally: - ```bash - git clone https://github.com//picoclaw.git - cd picoclaw - ``` -3. Add the upstream remote: - ```bash - git remote add upstream https://github.com/sipeed/picoclaw.git - ``` - ---- - -## Development Setup - -### Prerequisites - -- Go 1.25 or later -- `make` - -### Build +Install Git, Make, and a Go toolchain satisfying [go.mod](go.mod), currently Go 1.25.13 or later. Clone this fork, or your fork of it: ```bash -make build # Build binary (runs go generate first) -make generate # Run go generate only -make check # Full pre-commit check: deps + fmt + vet + test + docs consistency checks +git clone https://github.com/loveuer/picoclaw.git +cd picoclaw +make build +./build/picoclaw version ``` -### Running Tests +`make build` generates embedded resources, uses `stdjson`, and disables CGO by default. Keep the Go module path `github.com/sipeed/picoclaw`; it remains the internal import path. + +Before submitting changes, run the checks relevant to the change: ```bash -make test # Run all tests -make integration-test # Run Docker-backed integration suites -go test -run TestName -v ./pkg/session/ # Run a single test -go test -bench=. -benchmem -run='^$' ./... # Run benchmarks +go generate ./... +go test -tags stdjson ./... +go vet -tags stdjson ./... +make lint-docs +make lint ``` -Docker-backed integration suites are auto-discovered from [`integration/suites/`](integration/suites/). See [`integration/README.md`](integration/README.md) for the suite layout and the conventions used by CI. +CI also runs vulnerability checks and Docker integration suites. For integration setup and suite selection, see [integration/README.md](integration/README.md). -### Code Style +Keep changes focused. Describe the problem, resulting behavior, and validation in the PR. Never include credentials, personal configuration, or user workspace data. Preserve third-party license and attribution files, including those bundled with the Office Skills. -```bash -make fmt # Format code -make vet # Static analysis -make lint # Full linter run -make lint-docs # Check common documentation layout and naming conventions -``` +## Configuration and documentation -All CI checks must pass before a PR can be merged. Run `make check` locally before pushing to catch issues early, including the common docs consistency checks from `make lint-docs`. +When removing a feature, clean up its registration, configuration, tests, dependencies, examples, and documentation. Consider existing user configurations so upgrades do not unexpectedly fail. Channels use `channel_list` with channel-specific values under `settings`; `.security.yml` may override values from the main JSON file. ---- +Maintain the root README as the project overview. Do not restore duplicate upstream README translations. Keep specialized guides beside their translations and update links when moving or deleting documents. See [docs/README.md](docs/README.md). -## Making Changes +## Releases -### Branching +CI builds Linux amd64. Releases are published manually through the `Release` workflow, using an existing stable tag or replacing the `nightly` prerelease. Assets are a Linux amd64 archive and `checksums.txt`; there are no scheduled nightly builds, Docker registry uploads, or deb/rpm packages. See the [README release instructions](README.md#检查与发布). -Always branch off `main` and target `main` in your PR. Never push directly to `main` or any `release/*` branch: - -```bash -git checkout main -git pull upstream main -git checkout -b your-feature-branch -``` - -Use descriptive branch names, e.g. `fix/telegram-timeout`, `feat/ollama-provider`, `docs/contributing-guide`. - -### Commits - -- Write clear, concise commit messages in English. -- Use the imperative mood: "Add retry logic" not "Added retry logic". -- Reference the related issue when relevant: `Fix session leak (#123)`. -- Keep commits focused. One logical change per commit is preferred. -- For minor cleanups or typo fixes, squash them into a single commit before opening a PR. -- Refer to [Conventional Commits](https://www.conventionalcommits.org/en/v1.0.0/) - -### Keeping Up to Date - -Rebase your branch onto upstream `main` before opening a PR: - -```bash -git fetch upstream -git rebase upstream/main -``` - ---- - -## AI-Assisted Contributions - -PicoClaw was built with substantial AI assistance, and we fully embrace AI-assisted development. However, contributors must understand their responsibilities when using AI tools. - -### Disclosure Is Required - -Every PR must disclose AI involvement using the PR template's **🤖 AI Code Generation** section. There are three levels: - -| Level | Description | -|---|---| -| 🤖 Fully AI-generated | AI wrote the code; contributor reviewed and validated it | -| 🛠️ Mostly AI-generated | AI produced the draft; contributor made significant modifications | -| 👨‍💻 Mostly Human-written | Contributor led; AI provided suggestions or none at all | - -Honest disclosure is expected. There is no stigma attached to any level — what matters is the quality of the contribution. - -### You Are Responsible for What You Submit - -Using AI to generate code does not reduce your responsibility as the contributor. Before opening a PR with AI-generated code, you must: - -- **Read and understand** every line of the generated code. -- **Test it** in a real environment (see the Test Environment section of the PR template). -- **Check for security issues** — AI models can generate subtly insecure code (e.g., path traversal, injection, credential exposure). Review carefully. -- **Verify correctness** — AI-generated logic can be plausible-sounding but wrong. Validate the behavior, not just the syntax. - -PRs where it is clear the contributor has not read or tested the AI-generated code will be closed without review. - -### AI-Generated Code Quality Standards - -AI-generated contributions are held to the **same quality bar** as human-written code: - -- It must pass all CI checks (`make check`). -- It must be idiomatic Go and consistent with the existing codebase style. -- It must not introduce unnecessary abstractions, dead code, or over-engineering. -- It must include or update tests where appropriate. - -### Security Review - -AI-generated code requires extra security scrutiny. Pay special attention to: - -- File path handling and sandbox escapes (see commit `244eb0b` for a real example) -- External input validation in channel handlers and tool implementations -- Credential or secret handling -- Command execution (`exec.Command`, shell invocations) - -If you are unsure whether a piece of AI-generated code is safe, say so in the PR — reviewers will help. - ---- - -## Pull Request Process - -### Before Opening a PR - -- [ ] Run `make check` and ensure it passes locally. -- [ ] Fill in the PR template completely, including the AI disclosure section. -- [ ] Link any related issue(s) in the PR description. -- [ ] Keep the PR focused. Avoid bundling unrelated changes together. - -### PR Template Sections - -The PR template asks for: - -- **Description** — What does this change do and why? -- **Type of Change** — Bug fix, feature, docs, or refactor. -- **AI Code Generation** — Disclosure of AI involvement (required). -- **Related Issue** — Link to the issue this addresses. -- **Technical Context** — Reference URLs and reasoning (skip for pure docs PRs). -- **Test Environment** — Hardware, OS, model/provider, and channels used for testing. -- **Evidence** — Optional logs or screenshots demonstrating the change works. -- **Checklist** — Self-review confirmation. - -### PR Size - -Prefer small, reviewable PRs. A PR that changes 200 lines across 5 files is much easier to review than one that changes 2000 lines across 30 files. If your feature is large, consider splitting it into a series of smaller, logically complete PRs. - ---- - -## Branch Strategy - -### Long-Lived Branches - -- **`main`** — the active development branch. All feature PRs target `main`. The branch is protected: direct pushes are not permitted, and at least one maintainer approval is required before merging. -- **`release/x.y`** — stable release branches, cut from `main` when a version is ready to ship. These branches are more strictly protected than `main`. - -### Requirements to Merge into `main` - -A PR can only be merged when all of the following are satisfied: - -1. **CI passes** — All GitHub Actions workflows (lint, test, build) must be green. -2. **Reviewer approval** — At least one maintainer has approved the PR. -3. **No unresolved review comments** — All review threads must be resolved. -4. **PR template is complete** — Including AI disclosure and test environment. - -### Who Can Merge - -Only maintainers can merge PRs. Contributors cannot merge their own PRs, even if they have write access. - -### Merge Strategy - -We use **squash merge** for most PRs to keep the `main` history clean and readable. Each merged PR becomes a single commit referencing the PR number, e.g.: - -``` -feat: Add Ollama provider support (#491) -``` - -If a PR consists of multiple independent, well-separated commits that tell a clear story, a regular merge may be used at the maintainer's discretion. - -### Release Branches - -When a version is ready, maintainers cut a `release/x.y` branch from `main`. After that point: - -- **New features are not backported.** The release branch receives no new functionality after it is cut. -- **Security fixes and critical bug fixes are cherry-picked.** If a fix in `main` qualifies (security vulnerability, data loss, crash), maintainers will cherry-pick the relevant commit(s) onto the affected `release/x.y` branch and issue a patch release. - -If you believe a fix in `main` should be backported to a release branch, note it in the PR description or open a separate issue. The decision rests with the maintainers. - -Release branches have stricter protections than `main` and are never directly pushed to under any circumstances. - ---- - -## Code Review - -### For Contributors - -- Respond to review comments within a reasonable time. If you need more time, say so. -- When you update a PR in response to feedback, briefly note what changed (e.g., "Updated to use `sync.RWMutex` as suggested"). -- If you disagree with feedback, engage respectfully. Explain your reasoning; reviewers can be wrong too. -- Do not force-push after a review has started — it makes it harder for reviewers to see what changed. Use additional commits instead; the maintainer will squash on merge. - -### For Reviewers - -Review for: - -1. **Correctness** — Does the code do what it claims? Are there edge cases? -2. **Security** — Especially for AI-generated code, tool implementations, and channel handlers. -3. **Architecture** — Is the approach consistent with the existing design? -4. **Simplicity** — Is there a simpler solution? Does this add unnecessary complexity? -5. **Tests** — Are the changes covered by tests? Are existing tests still meaningful? - -Be constructive and specific. "This could have a race condition if two goroutines call this concurrently — consider using a mutex here" is better than "this looks wrong". - - -### Reviewer List -Once your PR is submitted, you can reach out to the assigned reviewers listed in the following table. - -|Function| Reviewer| -|--- |--- | -|Provider|@yinwm | -|Channel |@yinwm/@alexhoshina | -|Agent |@lxowalle/@Zhaoyikaiii| -|Tools |@lxowalle| -|SKill || -|MCP || -|Optimization|@lxowalle| -|Security|| -|AI CI |@imguoguo| -|UX || -|Document|| - ---- - -## Communication - -- **GitHub Issues** — Bug reports, feature requests, design discussions. -- **GitHub Discussions** — General questions, ideas, community conversation. -- **Pull Request comments** — Code-specific feedback. -- **Wechat&Discord** — We will invite you when you have at least one merged PR - -When in doubt, open an issue before writing code. It costs little and prevents wasted effort. - ---- - -## A Note on the Project's AI-Driven Origin - -PicoClaw's architecture was substantially designed and implemented with AI assistance, guided by human oversight. If you find something that looks odd or over-engineered, it may be an artifact of that process — opening an issue to discuss it is always welcome. - -We believe AI-assisted development done responsibly produces great results. We also believe humans must remain accountable for what they ship. These two beliefs are not in conflict. - -Thank you for contributing! +The updater defaults to this fork's GitHub Releases. Changing the default source or publication format requires reviewing updater compatibility. diff --git a/README.md b/README.md index 00831589..d8499735 100644 --- a/README.md +++ b/README.md @@ -10,6 +10,7 @@ - **模型接入**:仅保留 OpenAI(Responses / Chat Completions)和 Anthropic Messages,支持兼容端点、多模型配置与切换。 - **会话管理**:保存对话上下文,支持摘要压缩,以及通过 `/new` 清空上下文后重新提问。 - **工具与扩展**:文件操作、命令执行、网页搜索与抓取、MCP、Skills 和定时任务。 +- **办公文件**:内置 `docx`、`xlsx`、`pptx` Skills,通过独立 Docker 环境处理 Word、Excel 和 PowerPoint。 - **语音能力**:保留语音识别与合成,实际可用能力取决于模型、服务及渠道配置。 已移除 WebUI、launcher、桌面托盘及相关前端构建;网页搜索和网页抓取工具仍然保留。 @@ -180,7 +181,9 @@ picoclaw update --url https://github.com/loveuer/picoclaw/releases/tag/v1.0.0 -- ./build/picoclaw gateway ``` -Gateway 会连接已启用的渠道。可用 `./build/picoclaw status` 查看状态,或用 `./build/picoclaw --help` 查看其他命令。 +Gateway 会连接已启用的渠道。可用 `./build/picoclaw status` 查看版本、配置路径、默认模型和 OpenAI / Anthropic 的密钥及登录状态;该命令不检查模型连通性或服务运行状态。其他命令见 `./build/picoclaw --help`。 + +当前配置使用 `channel_list`:`enabled`、`type`、`allow_from` 等公共字段放在渠道条目中,Token、App ID、代理地址等渠道专有字段放在 `settings` 中。请以 [配置示例](config/config.example.json) 的结构为准。 ## 在 IM 中开始新对话 @@ -209,7 +212,7 @@ Gateway 会连接已启用的渠道。可用 `./build/picoclaw status` 查看状 - `slack`、`slack_webhook`、`teams_webhook`、`matrix`、`deltachat`、`irc`、`vk` - `line`、`whatsapp`、`whatsapp_native`、`discord` -升级时,需要从 `config.json` **和** `.security.yml` 的 `channels` 中删除这些渠道条目。仅设置 `enabled: false` 仍可能因未知渠道类型而导致启动失败,例如: +升级时,需要从 `config.json` **和** `.security.yml` 的 `channel_list`(旧版名为 `channels`)中删除这些渠道条目。仅设置 `enabled: false` 仍可能因未知渠道类型而导致启动失败,例如: ```text channel "maixcam" has unknown type "maixcam" @@ -221,13 +224,14 @@ channel "maixcam" has unknown type "maixcam" ## 更多说明 +- [Docker 本地构建与运行](docs/guides/docker.zh.md) - [配置指南](docs/guides/configuration.zh.md) - [会话管理](docs/guides/session-guide.zh.md) - [工具配置](docs/reference/tools_configuration.zh.md) - [MCP 命令](docs/reference/mcp-cli.md) - [定时任务](docs/reference/cron.md) -部分专题文档沿用上游内容;如与本页的功能范围不一致,以当前源码和配置示例为准。 +Evolution 自学习和 Seahorse 上下文引擎仍保留,默认分别为关闭和使用 legacy 引擎;不属于本轮已移除的功能。专题文档的入口见 [文档目录](docs/README.md)。 开发检查: diff --git a/docs/README.md b/docs/README.md index b252abfe..c14184c3 100644 --- a/docs/README.md +++ b/docs/README.md @@ -19,6 +19,8 @@ If you are browsing docs rather than reorganizing them, start with these directo - [Architecture](architecture/README.md): implementation notes and internal design docs. - [Migration](migration/README.md): upgrade and migration notes. +The maintained deployment and model guides are [Docker](guides/docker.md), [providers](guides/providers.md), and [troubleshooting](operations/troubleshooting.md). [Office Skills](guides/office-skills.zh.md) describe the separate document runtime. Design and migration documents may describe historical implementations; they are not installation instructions. + For channel-specific setup, start with [Chat Apps Configuration](guides/chat-apps.md) and then drill into `docs/channels//README.md` as needed. ## Principles diff --git a/docs/architecture/routing-system.md b/docs/architecture/routing-system.md index ccdec740..ab9e9a89 100644 --- a/docs/architecture/routing-system.md +++ b/docs/architecture/routing-system.md @@ -1,6 +1,6 @@ # Routing System -> Back to [README](../README.md) +> Back to [README](../../README.md) In PicoClaw, the runtime "routing system" is not just one decision. It is the combined pipeline that decides: diff --git a/docs/architecture/session-system.md b/docs/architecture/session-system.md index f930c55a..bf7dae6e 100644 --- a/docs/architecture/session-system.md +++ b/docs/architecture/session-system.md @@ -1,6 +1,6 @@ # Session System -> Back to [README](../README.md) +> Back to [README](../../README.md) This document describes the runtime session system used by PicoClaw to: diff --git a/docs/architecture/subturn.md b/docs/architecture/subturn.md index 31a56902..cbf95dc8 100644 --- a/docs/architecture/subturn.md +++ b/docs/architecture/subturn.md @@ -1,6 +1,6 @@ # 🔄 SubTurn Mechanism -> Back to [README](../README.md) +> Back to [README](../../README.md) ## Overview diff --git a/docs/channels/dingtalk/README.fr.md b/docs/channels/dingtalk/README.fr.md index c756cbad..dd24cc80 100644 --- a/docs/channels/dingtalk/README.fr.md +++ b/docs/channels/dingtalk/README.fr.md @@ -12,9 +12,11 @@ DingTalk est la plateforme de communication d'entreprise d'Alibaba, très popula "dingtalk": { "enabled": true, "type": "dingtalk", - "client_id": "YOUR_CLIENT_ID", - "client_secret": "YOUR_CLIENT_SECRET", - "allow_from": [] + "allow_from": [], + "settings": { + "client_id": "YOUR_CLIENT_ID", + "client_secret": "YOUR_CLIENT_SECRET" + } } } } diff --git a/docs/channels/dingtalk/README.ja.md b/docs/channels/dingtalk/README.ja.md index f92940b0..b75611f0 100644 --- a/docs/channels/dingtalk/README.ja.md +++ b/docs/channels/dingtalk/README.ja.md @@ -12,9 +12,11 @@ DingTalkはアリババの企業向けコミュニケーションプラットフ "dingtalk": { "enabled": true, "type": "dingtalk", - "client_id": "YOUR_CLIENT_ID", - "client_secret": "YOUR_CLIENT_SECRET", - "allow_from": [] + "allow_from": [], + "settings": { + "client_id": "YOUR_CLIENT_ID", + "client_secret": "YOUR_CLIENT_SECRET" + } } } } diff --git a/docs/channels/dingtalk/README.md b/docs/channels/dingtalk/README.md index ed220ac6..6fc879cc 100644 --- a/docs/channels/dingtalk/README.md +++ b/docs/channels/dingtalk/README.md @@ -6,15 +6,19 @@ DingTalk is Alibaba's enterprise communication platform, widely used in Chinese ## Configuration +> Configuration: common fields such as `enabled`, `type`, and `allow_from` belong on the channel entry; channel-specific fields belong under `settings`. Credentials saved under `channel_list..settings` in `.security.yml` override the main JSON configuration. + ```json { "channel_list": { "dingtalk": { "enabled": true, "type": "dingtalk", - "client_id": "YOUR_CLIENT_ID", - "client_secret": "YOUR_CLIENT_SECRET", - "allow_from": [] + "allow_from": [], + "settings": { + "client_id": "YOUR_CLIENT_ID", + "client_secret": "YOUR_CLIENT_SECRET" + } } } } diff --git a/docs/channels/dingtalk/README.pt-br.md b/docs/channels/dingtalk/README.pt-br.md index 4cfd2bbc..723dd0e9 100644 --- a/docs/channels/dingtalk/README.pt-br.md +++ b/docs/channels/dingtalk/README.pt-br.md @@ -12,9 +12,11 @@ DingTalk é a plataforma de comunicação empresarial da Alibaba, amplamente uti "dingtalk": { "enabled": true, "type": "dingtalk", - "client_id": "YOUR_CLIENT_ID", - "client_secret": "YOUR_CLIENT_SECRET", - "allow_from": [] + "allow_from": [], + "settings": { + "client_id": "YOUR_CLIENT_ID", + "client_secret": "YOUR_CLIENT_SECRET" + } } } } diff --git a/docs/channels/dingtalk/README.vi.md b/docs/channels/dingtalk/README.vi.md index 62bfa031..608b70a4 100644 --- a/docs/channels/dingtalk/README.vi.md +++ b/docs/channels/dingtalk/README.vi.md @@ -12,9 +12,11 @@ DingTalk là nền tảng giao tiếp doanh nghiệp của Alibaba, được s "dingtalk": { "enabled": true, "type": "dingtalk", - "client_id": "YOUR_CLIENT_ID", - "client_secret": "YOUR_CLIENT_SECRET", - "allow_from": [] + "allow_from": [], + "settings": { + "client_id": "YOUR_CLIENT_ID", + "client_secret": "YOUR_CLIENT_SECRET" + } } } } diff --git a/docs/channels/dingtalk/README.zh.md b/docs/channels/dingtalk/README.zh.md index 18fe7317..a63e28be 100644 --- a/docs/channels/dingtalk/README.zh.md +++ b/docs/channels/dingtalk/README.zh.md @@ -6,15 +6,19 @@ ## 配置 +> 配置结构:`enabled`、`type`、`allow_from` 等公共字段位于渠道条目,Token、App ID 等专有字段位于 `settings`。`.security.yml` 使用 `channel_list.<名称>.settings` 保存渠道密钥;其中的同名值会覆盖主配置。 + ```json { "channel_list": { "dingtalk": { "enabled": true, "type": "dingtalk", - "client_id": "YOUR_CLIENT_ID", - "client_secret": "YOUR_CLIENT_SECRET", - "allow_from": [] + "allow_from": [], + "settings": { + "client_id": "YOUR_CLIENT_ID", + "client_secret": "YOUR_CLIENT_SECRET" + } } } } diff --git a/docs/channels/feishu/README.fr.md b/docs/channels/feishu/README.fr.md index d726d8b8..0c3805f9 100644 --- a/docs/channels/feishu/README.fr.md +++ b/docs/channels/feishu/README.fr.md @@ -12,11 +12,13 @@ Feishu (nom international : Lark) est une plateforme de collaboration d'entrepri "feishu": { "enabled": true, "type": "feishu", - "app_id": "cli_xxx", - "app_secret": "xxx", - "encrypt_key": "", - "verification_token": "", - "allow_from": [] + "allow_from": [], + "settings": { + "app_id": "cli_xxx", + "app_secret": "xxx", + "encrypt_key": "", + "verification_token": "" + } } } } diff --git a/docs/channels/feishu/README.ja.md b/docs/channels/feishu/README.ja.md index 32eb0288..cf3fe436 100644 --- a/docs/channels/feishu/README.ja.md +++ b/docs/channels/feishu/README.ja.md @@ -12,11 +12,13 @@ "feishu": { "enabled": true, "type": "feishu", - "app_id": "cli_xxx", - "app_secret": "xxx", - "encrypt_key": "", - "verification_token": "", - "allow_from": [] + "allow_from": [], + "settings": { + "app_id": "cli_xxx", + "app_secret": "xxx", + "encrypt_key": "", + "verification_token": "" + } } } } diff --git a/docs/channels/feishu/README.md b/docs/channels/feishu/README.md index b920a95f..7245d181 100644 --- a/docs/channels/feishu/README.md +++ b/docs/channels/feishu/README.md @@ -6,17 +6,21 @@ Feishu (international name: Lark) is an enterprise collaboration platform by Byt ## Configuration +> Configuration: common fields such as `enabled`, `type`, and `allow_from` belong on the channel entry; channel-specific fields belong under `settings`. Credentials saved under `channel_list..settings` in `.security.yml` override the main JSON configuration. + ```json { "channel_list": { "feishu": { "enabled": true, "type": "feishu", - "app_id": "cli_xxx", - "app_secret": "xxx", - "encrypt_key": "", - "verification_token": "", - "allow_from": [] + "allow_from": [], + "settings": { + "app_id": "cli_xxx", + "app_secret": "xxx", + "encrypt_key": "", + "verification_token": "" + } } } } diff --git a/docs/channels/feishu/README.pt-br.md b/docs/channels/feishu/README.pt-br.md index 29d49d0f..d0746221 100644 --- a/docs/channels/feishu/README.pt-br.md +++ b/docs/channels/feishu/README.pt-br.md @@ -12,11 +12,13 @@ Feishu (nome internacional: Lark) é uma plataforma de colaboração empresarial "feishu": { "enabled": true, "type": "feishu", - "app_id": "cli_xxx", - "app_secret": "xxx", - "encrypt_key": "", - "verification_token": "", - "allow_from": [] + "allow_from": [], + "settings": { + "app_id": "cli_xxx", + "app_secret": "xxx", + "encrypt_key": "", + "verification_token": "" + } } } } diff --git a/docs/channels/feishu/README.vi.md b/docs/channels/feishu/README.vi.md index a66d5a17..24fe839d 100644 --- a/docs/channels/feishu/README.vi.md +++ b/docs/channels/feishu/README.vi.md @@ -12,11 +12,13 @@ Feishu (tên quốc tế: Lark) là nền tảng cộng tác doanh nghiệp củ "feishu": { "enabled": true, "type": "feishu", - "app_id": "cli_xxx", - "app_secret": "xxx", - "encrypt_key": "", - "verification_token": "", - "allow_from": [] + "allow_from": [], + "settings": { + "app_id": "cli_xxx", + "app_secret": "xxx", + "encrypt_key": "", + "verification_token": "" + } } } } diff --git a/docs/channels/feishu/README.zh.md b/docs/channels/feishu/README.zh.md index 2ef420e5..b333caf3 100644 --- a/docs/channels/feishu/README.zh.md +++ b/docs/channels/feishu/README.zh.md @@ -2,22 +2,26 @@ # 飞书 -飞书(国际版名称:Lark)是字节跳动旗下的企业协作平台。它通过事件驱动的 Webhook 同时支持中国和全球市场。 +飞书(国际版名称:Lark)是字节跳动旗下的企业协作平台。本 fork 使用 WebSocket 长连接接收事件,无需公网 Webhook 回调地址。 ## 配置 +> 配置结构:`enabled`、`type`、`allow_from` 等公共字段位于渠道条目,Token、App ID 等专有字段位于 `settings`。`.security.yml` 使用 `channel_list.<名称>.settings` 保存渠道密钥;其中的同名值会覆盖主配置。 + ```json { "channel_list": { "feishu": { "enabled": true, "type": "feishu", - "app_id": "cli_xxx", - "app_secret": "xxx", - "encrypt_key": "", - "verification_token": "", "allow_from": [], - "is_lark": false + "settings": { + "app_id": "cli_xxx", + "app_secret": "xxx", + "encrypt_key": "", + "verification_token": "", + "is_lark": false + } } } } @@ -29,7 +33,7 @@ | app_id | string | 是 | 飞书应用的 App ID(以cli\_开头) | | app_secret | string | 是 | 飞书应用的 App Secret | | encrypt_key | string | 否 | 事件回调加密密钥 | -| verification_token | string | 否 | 用于Webhook事件验证的Token | +| verification_token | string | 否 | 可选事件校验 Token,长连接模式无需配置公网回调 URL | | allow_from | array | 否 | 用户ID白名单,空表示所有用户 | | random_reaction_emoji | array | 否 | 随机添加的表情列表,空则使用默认 "Typing"(敲键盘) | | is_lark | bool | 否 | 是否使用 Lark 国际版域名(`open.larksuite.com`),默认为 `false`(使用飞书域名 `open.feishu.cn`) | @@ -38,7 +42,7 @@ 1. 前往 [飞书开放平台](https://open.feishu.cn/)(国际版用户请前往 [Lark 开放平台](https://open.larksuite.com/))创建应用程序 2. 获取 App ID 和 App Secret -3. 配置事件订阅和Webhook URL +3. 在开放平台的事件订阅中选择长连接接收事件,并订阅所需的消息事件 4. 设置加密(可选,生产环境建议启用) 5. 将 App ID、App Secret、Encrypt Key 和 Verification Token(如果启用加密) 填入配置文件中 6. 自定义你希望 PicoClaw react 你消息时的表情(可选, Reference URL: [Feishu Emoji List](https://open.larkoffice.com/document/server-docs/im-v1/message-reaction/emojis-introduce)) diff --git a/docs/channels/mqtt/README.md b/docs/channels/mqtt/README.md index c894d77f..e097978f 100644 --- a/docs/channels/mqtt/README.md +++ b/docs/channels/mqtt/README.md @@ -6,6 +6,8 @@ PicoClaw supports any MQTT client as a chat channel. Devices or services publish **1. Add the channel to `~/.picoclaw/config.json`:** +> Configuration: common fields such as `enabled`, `type`, and `allow_from` belong on the channel entry; channel-specific fields belong under `settings`. Credentials saved under `channel_list..settings` in `.security.yml` override the main JSON configuration. + ```json { "channel_list": { diff --git a/docs/channels/mqtt/README.zh.md b/docs/channels/mqtt/README.zh.md index e7e529cd..b1f01e11 100644 --- a/docs/channels/mqtt/README.zh.md +++ b/docs/channels/mqtt/README.zh.md @@ -6,6 +6,8 @@ PicoClaw 支持将任意 MQTT 客户端作为消息渠道。设备或服务向 B **1. 在 `~/.picoclaw/config.json` 中添加渠道:** +> 配置结构:`enabled`、`type`、`allow_from` 等公共字段位于渠道条目,Token、App ID 等专有字段位于 `settings`。`.security.yml` 使用 `channel_list.<名称>.settings` 保存渠道密钥;其中的同名值会覆盖主配置。 + ```json { "channel_list": { diff --git a/docs/channels/onebot/README.fr.md b/docs/channels/onebot/README.fr.md index 09ff0f99..620eefca 100644 --- a/docs/channels/onebot/README.fr.md +++ b/docs/channels/onebot/README.fr.md @@ -12,9 +12,11 @@ OneBot est un standard de protocole ouvert pour les bots QQ, fournissant une int "onebot": { "enabled": true, "type": "onebot", - "ws_url": "ws://localhost:8080", - "access_token": "", - "allow_from": [] + "allow_from": [], + "settings": { + "ws_url": "ws://localhost:8080", + "access_token": "" + } } } } diff --git a/docs/channels/onebot/README.ja.md b/docs/channels/onebot/README.ja.md index abd8433c..a5f60f8e 100644 --- a/docs/channels/onebot/README.ja.md +++ b/docs/channels/onebot/README.ja.md @@ -12,9 +12,11 @@ OneBot は QQ ボット向けのオープンプロトコル標準で、複数の "onebot": { "enabled": true, "type": "onebot", - "ws_url": "ws://localhost:8080", - "access_token": "", - "allow_from": [] + "allow_from": [], + "settings": { + "ws_url": "ws://localhost:8080", + "access_token": "" + } } } } diff --git a/docs/channels/onebot/README.md b/docs/channels/onebot/README.md index 7dd1e3c8..a2681736 100644 --- a/docs/channels/onebot/README.md +++ b/docs/channels/onebot/README.md @@ -6,15 +6,19 @@ OneBot is an open protocol standard for QQ bots, providing a unified interface f ## Configuration +> Configuration: common fields such as `enabled`, `type`, and `allow_from` belong on the channel entry; channel-specific fields belong under `settings`. Credentials saved under `channel_list..settings` in `.security.yml` override the main JSON configuration. + ```json { "channel_list": { "onebot": { "enabled": true, "type": "onebot", - "ws_url": "ws://localhost:8080", - "access_token": "", - "allow_from": [] + "allow_from": [], + "settings": { + "ws_url": "ws://localhost:8080", + "access_token": "" + } } } } diff --git a/docs/channels/onebot/README.pt-br.md b/docs/channels/onebot/README.pt-br.md index dd97fca1..b824a5f0 100644 --- a/docs/channels/onebot/README.pt-br.md +++ b/docs/channels/onebot/README.pt-br.md @@ -12,9 +12,11 @@ OneBot é um padrão de protocolo aberto para bots QQ, fornecendo uma interface "onebot": { "enabled": true, "type": "onebot", - "ws_url": "ws://localhost:8080", - "access_token": "", - "allow_from": [] + "allow_from": [], + "settings": { + "ws_url": "ws://localhost:8080", + "access_token": "" + } } } } diff --git a/docs/channels/onebot/README.vi.md b/docs/channels/onebot/README.vi.md index 7f1e8543..d9314c34 100644 --- a/docs/channels/onebot/README.vi.md +++ b/docs/channels/onebot/README.vi.md @@ -12,9 +12,11 @@ OneBot là tiêu chuẩn giao thức mở dành cho bot QQ, cung cấp giao di "onebot": { "enabled": true, "type": "onebot", - "ws_url": "ws://localhost:8080", - "access_token": "", - "allow_from": [] + "allow_from": [], + "settings": { + "ws_url": "ws://localhost:8080", + "access_token": "" + } } } } diff --git a/docs/channels/onebot/README.zh.md b/docs/channels/onebot/README.zh.md index 8e3cbecc..61d78fc6 100644 --- a/docs/channels/onebot/README.zh.md +++ b/docs/channels/onebot/README.zh.md @@ -6,15 +6,19 @@ OneBot 是一个面向 QQ 机器人的开放协议标准,为多种 QQ 机器 ## 配置 +> 配置结构:`enabled`、`type`、`allow_from` 等公共字段位于渠道条目,Token、App ID 等专有字段位于 `settings`。`.security.yml` 使用 `channel_list.<名称>.settings` 保存渠道密钥;其中的同名值会覆盖主配置。 + ```json { "channel_list": { "onebot": { "enabled": true, "type": "onebot", - "ws_url": "ws://localhost:8080", - "access_token": "", - "allow_from": [] + "allow_from": [], + "settings": { + "ws_url": "ws://localhost:8080", + "access_token": "" + } } } } diff --git a/docs/channels/qq/README.fr.md b/docs/channels/qq/README.fr.md index 4def62c0..03166967 100644 --- a/docs/channels/qq/README.fr.md +++ b/docs/channels/qq/README.fr.md @@ -12,9 +12,11 @@ PicoClaw prend en charge QQ via l'API Bot officielle de la plateforme ouverte QQ "qq": { "enabled": true, "type": "qq", - "app_id": "YOUR_APP_ID", - "app_secret": "YOUR_APP_SECRET", - "allow_from": [] + "allow_from": [], + "settings": { + "app_id": "YOUR_APP_ID", + "app_secret": "YOUR_APP_SECRET" + } } } } diff --git a/docs/channels/qq/README.ja.md b/docs/channels/qq/README.ja.md index 02f9c0ec..fe2d831c 100644 --- a/docs/channels/qq/README.ja.md +++ b/docs/channels/qq/README.ja.md @@ -12,9 +12,11 @@ PicoClaw は QQ オープンプラットフォームの公式 Bot API を通じ "qq": { "enabled": true, "type": "qq", - "app_id": "YOUR_APP_ID", - "app_secret": "YOUR_APP_SECRET", - "allow_from": [] + "allow_from": [], + "settings": { + "app_id": "YOUR_APP_ID", + "app_secret": "YOUR_APP_SECRET" + } } } } diff --git a/docs/channels/qq/README.md b/docs/channels/qq/README.md index bc8ccf83..814c2508 100644 --- a/docs/channels/qq/README.md +++ b/docs/channels/qq/README.md @@ -6,15 +6,19 @@ PicoClaw provides QQ support via the official Bot API from the QQ Open Platform. ## Configuration +> Configuration: common fields such as `enabled`, `type`, and `allow_from` belong on the channel entry; channel-specific fields belong under `settings`. Credentials saved under `channel_list..settings` in `.security.yml` override the main JSON configuration. + ```json { "channel_list": { "qq": { "enabled": true, "type": "qq", - "app_id": "YOUR_APP_ID", - "app_secret": "YOUR_APP_SECRET", - "allow_from": [] + "allow_from": [], + "settings": { + "app_id": "YOUR_APP_ID", + "app_secret": "YOUR_APP_SECRET" + } } } } diff --git a/docs/channels/qq/README.pt-br.md b/docs/channels/qq/README.pt-br.md index 3ad1dc0d..fcf6e28c 100644 --- a/docs/channels/qq/README.pt-br.md +++ b/docs/channels/qq/README.pt-br.md @@ -12,9 +12,11 @@ O PicoClaw oferece suporte ao QQ via API Bot oficial da Plataforma Aberta QQ. "qq": { "enabled": true, "type": "qq", - "app_id": "YOUR_APP_ID", - "app_secret": "YOUR_APP_SECRET", - "allow_from": [] + "allow_from": [], + "settings": { + "app_id": "YOUR_APP_ID", + "app_secret": "YOUR_APP_SECRET" + } } } } diff --git a/docs/channels/qq/README.vi.md b/docs/channels/qq/README.vi.md index 4e678be4..7cca1a7e 100644 --- a/docs/channels/qq/README.vi.md +++ b/docs/channels/qq/README.vi.md @@ -12,9 +12,11 @@ PicoClaw hỗ trợ QQ thông qua API Bot chính thức của Nền tảng Mở "qq": { "enabled": true, "type": "qq", - "app_id": "YOUR_APP_ID", - "app_secret": "YOUR_APP_SECRET", - "allow_from": [] + "allow_from": [], + "settings": { + "app_id": "YOUR_APP_ID", + "app_secret": "YOUR_APP_SECRET" + } } } } diff --git a/docs/channels/qq/README.zh.md b/docs/channels/qq/README.zh.md index afffb3d2..48e43e90 100644 --- a/docs/channels/qq/README.zh.md +++ b/docs/channels/qq/README.zh.md @@ -6,16 +6,20 @@ PicoClaw 通过 QQ 开放平台的官方机器人 API 提供对 QQ 的支持。 ## 配置 +> 配置结构:`enabled`、`type`、`allow_from` 等公共字段位于渠道条目,Token、App ID 等专有字段位于 `settings`。`.security.yml` 使用 `channel_list.<名称>.settings` 保存渠道密钥;其中的同名值会覆盖主配置。 + ```json { "channel_list": { "qq": { "enabled": true, "type": "qq", - "app_id": "YOUR_APP_ID", - "app_secret": "YOUR_APP_SECRET", "allow_from": [], - "max_base64_file_size_mib": 0 + "settings": { + "app_id": "YOUR_APP_ID", + "app_secret": "YOUR_APP_SECRET", + "max_base64_file_size_mib": 0 + } } } } diff --git a/docs/channels/telegram/README.fr.md b/docs/channels/telegram/README.fr.md index cbe20a62..779eb44f 100644 --- a/docs/channels/telegram/README.fr.md +++ b/docs/channels/telegram/README.fr.md @@ -12,10 +12,14 @@ Le canal Telegram utilise le long polling via l'API Bot Telegram pour une commun "telegram": { "enabled": true, "type": "telegram", - "token": "123456789:ABCdefGHIjklMNOpqrsTUVwxyz", - "allow_from": ["123456789"], - "proxy": "", - "use_markdown_v2": false + "allow_from": [ + "123456789" + ], + "settings": { + "token": "123456789:ABCdefGHIjklMNOpqrsTUVwxyz", + "proxy": "", + "use_markdown_v2": false + } } } } @@ -47,9 +51,13 @@ Vous pouvez définir `use_markdown_v2: true` pour activer les options de formata "telegram": { "enabled": true, "type": "telegram", - "token": "YOUR_BOT_TOKEN", - "allow_from": ["YOUR_USER_ID"], - "use_markdown_v2": true + "allow_from": [ + "YOUR_USER_ID" + ], + "settings": { + "token": "YOUR_BOT_TOKEN", + "use_markdown_v2": true + } } } } diff --git a/docs/channels/telegram/README.ja.md b/docs/channels/telegram/README.ja.md index 1c94a4ed..42bcd5ae 100644 --- a/docs/channels/telegram/README.ja.md +++ b/docs/channels/telegram/README.ja.md @@ -12,10 +12,14 @@ Telegram チャンネルは、Telegram Bot API を使用したロングポーリ "telegram": { "enabled": true, "type": "telegram", - "token": "123456789:ABCdefGHIjklMNOpqrsTUVwxyz", - "allow_from": ["123456789"], - "proxy": "", - "use_markdown_v2": false + "allow_from": [ + "123456789" + ], + "settings": { + "token": "123456789:ABCdefGHIjklMNOpqrsTUVwxyz", + "proxy": "", + "use_markdown_v2": false + } } } } @@ -47,9 +51,13 @@ Telegram チャンネルは、Telegram Bot API を使用したロングポーリ "telegram": { "enabled": true, "type": "telegram", - "token": "YOUR_BOT_TOKEN", - "allow_from": ["YOUR_USER_ID"], - "use_markdown_v2": true + "allow_from": [ + "YOUR_USER_ID" + ], + "settings": { + "token": "YOUR_BOT_TOKEN", + "use_markdown_v2": true + } } } } diff --git a/docs/channels/telegram/README.md b/docs/channels/telegram/README.md index 215d80af..f5675b06 100644 --- a/docs/channels/telegram/README.md +++ b/docs/channels/telegram/README.md @@ -2,21 +2,27 @@ # Telegram -The Telegram channel uses long polling via the Telegram Bot API for bot-based communication. It supports text messages, media attachments (photos, voice, audio, documents), voice transcription ([setup](../../guides/providers.md#voice-transcription)), and built-in command handling. +The Telegram channel uses long polling via the Telegram Bot API for bot-based communication. It supports text messages, media attachments (photos, voice, audio, documents), voice transcription ([setup](../../../pkg/audio/asr/README.md)), and built-in command handling. ## Configuration +> Configuration: common fields such as `enabled`, `type`, and `allow_from` belong on the channel entry; channel-specific fields belong under `settings`. Credentials saved under `channel_list..settings` in `.security.yml` override the main JSON configuration. + ```json { "channel_list": { "telegram": { "enabled": true, "type": "telegram", - "token": "123456789:ABCdefGHIjklMNOpqrsTUVwxyz", - "allow_from": ["123456789"], - "proxy": "", - "use_markdown_v2": false, - "media_group_delay_ms": 500 + "allow_from": [ + "123456789" + ], + "settings": { + "token": "123456789:ABCdefGHIjklMNOpqrsTUVwxyz", + "proxy": "", + "use_markdown_v2": false, + "media_group_delay_ms": 500 + } } } } @@ -73,9 +79,13 @@ You can set `use_markdown_v2: true` to enable enhanced formatting options. This "telegram": { "enabled": true, "type": "telegram", - "token": "YOUR_BOT_TOKEN", - "allow_from": ["YOUR_USER_ID"], - "use_markdown_v2": true + "allow_from": [ + "YOUR_USER_ID" + ], + "settings": { + "token": "YOUR_BOT_TOKEN", + "use_markdown_v2": true + } } } } diff --git a/docs/channels/telegram/README.pt-br.md b/docs/channels/telegram/README.pt-br.md index b72fd304..8178b3b2 100644 --- a/docs/channels/telegram/README.pt-br.md +++ b/docs/channels/telegram/README.pt-br.md @@ -12,10 +12,14 @@ O canal Telegram utiliza long polling via a API de Bot do Telegram para comunica "telegram": { "enabled": true, "type": "telegram", - "token": "123456789:ABCdefGHIjklMNOpqrsTUVwxyz", - "allow_from": ["123456789"], - "proxy": "", - "use_markdown_v2": false + "allow_from": [ + "123456789" + ], + "settings": { + "token": "123456789:ABCdefGHIjklMNOpqrsTUVwxyz", + "proxy": "", + "use_markdown_v2": false + } } } } @@ -47,9 +51,13 @@ Você pode definir `use_markdown_v2: true` para habilitar opções de formataç "telegram": { "enabled": true, "type": "telegram", - "token": "YOUR_BOT_TOKEN", - "allow_from": ["YOUR_USER_ID"], - "use_markdown_v2": true + "allow_from": [ + "YOUR_USER_ID" + ], + "settings": { + "token": "YOUR_BOT_TOKEN", + "use_markdown_v2": true + } } } } diff --git a/docs/channels/telegram/README.vi.md b/docs/channels/telegram/README.vi.md index c5250897..9c3e9bf9 100644 --- a/docs/channels/telegram/README.vi.md +++ b/docs/channels/telegram/README.vi.md @@ -12,10 +12,14 @@ Kênh Telegram sử dụng long polling qua Telegram Bot API để giao tiếp d "telegram": { "enabled": true, "type": "telegram", - "token": "123456789:ABCdefGHIjklMNOpqrsTUVwxyz", - "allow_from": ["123456789"], - "proxy": "", - "use_markdown_v2": false + "allow_from": [ + "123456789" + ], + "settings": { + "token": "123456789:ABCdefGHIjklMNOpqrsTUVwxyz", + "proxy": "", + "use_markdown_v2": false + } } } } @@ -47,9 +51,13 @@ Bạn có thể đặt `use_markdown_v2: true` để bật các tùy chọn đ "telegram": { "enabled": true, "type": "telegram", - "token": "YOUR_BOT_TOKEN", - "allow_from": ["YOUR_USER_ID"], - "use_markdown_v2": true + "allow_from": [ + "YOUR_USER_ID" + ], + "settings": { + "token": "YOUR_BOT_TOKEN", + "use_markdown_v2": true + } } } } diff --git a/docs/channels/telegram/README.zh.md b/docs/channels/telegram/README.zh.md index 667ad55c..545847da 100644 --- a/docs/channels/telegram/README.zh.md +++ b/docs/channels/telegram/README.zh.md @@ -2,20 +2,26 @@ # Telegram -Telegram Channel 通过 Telegram 机器人 API 使用长轮询实现基于机器人的通信。它支持文本消息、媒体附件(照片、语音、音频、文档)、语音转录(配置见[提供商与模型配置](../../guides/providers.zh.md#语音转录)),以及内置命令处理器。 +Telegram Channel 通过 Telegram 机器人 API 使用长轮询实现基于机器人的通信。它支持文本消息、媒体附件(照片、语音、音频、文档)、语音转录(配置见[提供商与模型配置](../../../pkg/audio/asr/README.zh.md)),以及内置命令处理器。 ## 配置 +> 配置结构:`enabled`、`type`、`allow_from` 等公共字段位于渠道条目,Token、App ID 等专有字段位于 `settings`。`.security.yml` 使用 `channel_list.<名称>.settings` 保存渠道密钥;其中的同名值会覆盖主配置。 + ```json { "channel_list": { "telegram": { "enabled": true, "type": "telegram", - "token": "123456789:ABCdefGHIjklMNOpqrsTUVwxyz", - "allow_from": ["123456789"], - "proxy": "", - "use_markdown_v2": false + "allow_from": [ + "123456789" + ], + "settings": { + "token": "123456789:ABCdefGHIjklMNOpqrsTUVwxyz", + "proxy": "", + "use_markdown_v2": false + } } } } @@ -67,9 +73,13 @@ explain how to squash the last 3 commits "telegram": { "enabled": true, "type": "telegram", - "token": "YOUR_BOT_TOKEN", - "allow_from": ["YOUR_USER_ID"], - "use_markdown_v2": true + "allow_from": [ + "YOUR_USER_ID" + ], + "settings": { + "token": "YOUR_BOT_TOKEN", + "use_markdown_v2": true + } } } } diff --git a/docs/channels/wecom/README.fr.md b/docs/channels/wecom/README.fr.md index ffd01467..2e27fd5b 100644 --- a/docs/channels/wecom/README.fr.md +++ b/docs/channels/wecom/README.fr.md @@ -52,12 +52,14 @@ Si vous disposez déjà d'un `bot_id` et d'un `secret` depuis la plateforme WeCo "wecom": { "enabled": true, "type": "wecom", - "bot_id": "YOUR_BOT_ID", - "secret": "YOUR_SECRET", - "websocket_url": "wss://openws.work.weixin.qq.com", - "send_thinking_message": true, "allow_from": [], - "reasoning_channel_id": "" + "reasoning_channel_id": "", + "settings": { + "bot_id": "YOUR_BOT_ID", + "secret": "YOUR_SECRET", + "websocket_url": "wss://openws.work.weixin.qq.com", + "send_thinking_message": true + } } } } diff --git a/docs/channels/wecom/README.ja.md b/docs/channels/wecom/README.ja.md index b09c1a6f..c463588b 100644 --- a/docs/channels/wecom/README.ja.md +++ b/docs/channels/wecom/README.ja.md @@ -52,12 +52,14 @@ WeCom AI Bot プラットフォームから `bot_id` と `secret` を既にお "wecom": { "enabled": true, "type": "wecom", - "bot_id": "YOUR_BOT_ID", - "secret": "YOUR_SECRET", - "websocket_url": "wss://openws.work.weixin.qq.com", - "send_thinking_message": true, "allow_from": [], - "reasoning_channel_id": "" + "reasoning_channel_id": "", + "settings": { + "bot_id": "YOUR_BOT_ID", + "secret": "YOUR_SECRET", + "websocket_url": "wss://openws.work.weixin.qq.com", + "send_thinking_message": true + } } } } diff --git a/docs/channels/wecom/README.md b/docs/channels/wecom/README.md index d78b1a14..f9c4c09e 100644 --- a/docs/channels/wecom/README.md +++ b/docs/channels/wecom/README.md @@ -46,18 +46,22 @@ picoclaw auth wecom --timeout 10m If you already have a `bot_id` and `secret` from the WeCom AI Bot platform, configure directly: +> Configuration: common fields such as `enabled`, `type`, and `allow_from` belong on the channel entry; channel-specific fields belong under `settings`. Credentials saved under `channel_list..settings` in `.security.yml` override the main JSON configuration. + ```json { "channel_list": { "wecom": { "enabled": true, "type": "wecom", - "bot_id": "YOUR_BOT_ID", - "secret": "YOUR_SECRET", - "websocket_url": "wss://openws.work.weixin.qq.com", - "send_thinking_message": true, "allow_from": [], - "reasoning_channel_id": "" + "reasoning_channel_id": "", + "settings": { + "bot_id": "YOUR_BOT_ID", + "secret": "YOUR_SECRET", + "websocket_url": "wss://openws.work.weixin.qq.com", + "send_thinking_message": true + } } } } @@ -138,4 +142,4 @@ All fields can be overridden via environment variables with the prefix `PICOCLAW ### Replies do not arrive - Check whether `allow_from` is blocking the sender. -- Check that `channels.wecom.bot_id` and `channels.wecom.secret` are set and non-empty. +- Check that `channel_list.wecom.settings.bot_id` and `channel_list.wecom.settings.secret` are set and non-empty. diff --git a/docs/channels/wecom/README.pt-br.md b/docs/channels/wecom/README.pt-br.md index 268f8beb..c042ee01 100644 --- a/docs/channels/wecom/README.pt-br.md +++ b/docs/channels/wecom/README.pt-br.md @@ -52,12 +52,14 @@ Se você já possui um `bot_id` e `secret` da plataforma WeCom AI Bot, configure "wecom": { "enabled": true, "type": "wecom", - "bot_id": "YOUR_BOT_ID", - "secret": "YOUR_SECRET", - "websocket_url": "wss://openws.work.weixin.qq.com", - "send_thinking_message": true, "allow_from": [], - "reasoning_channel_id": "" + "reasoning_channel_id": "", + "settings": { + "bot_id": "YOUR_BOT_ID", + "secret": "YOUR_SECRET", + "websocket_url": "wss://openws.work.weixin.qq.com", + "send_thinking_message": true + } } } } diff --git a/docs/channels/wecom/README.vi.md b/docs/channels/wecom/README.vi.md index f992b5b6..43048325 100644 --- a/docs/channels/wecom/README.vi.md +++ b/docs/channels/wecom/README.vi.md @@ -52,12 +52,14 @@ Nếu bạn đã có `bot_id` và `secret` từ nền tảng WeCom AI Bot, hãy "wecom": { "enabled": true, "type": "wecom", - "bot_id": "YOUR_BOT_ID", - "secret": "YOUR_SECRET", - "websocket_url": "wss://openws.work.weixin.qq.com", - "send_thinking_message": true, "allow_from": [], - "reasoning_channel_id": "" + "reasoning_channel_id": "", + "settings": { + "bot_id": "YOUR_BOT_ID", + "secret": "YOUR_SECRET", + "websocket_url": "wss://openws.work.weixin.qq.com", + "send_thinking_message": true + } } } } diff --git a/docs/channels/wecom/README.zh.md b/docs/channels/wecom/README.zh.md index d44f8893..f26b947c 100644 --- a/docs/channels/wecom/README.zh.md +++ b/docs/channels/wecom/README.zh.md @@ -32,7 +32,7 @@ picoclaw auth wecom 1. 向企业微信请求二维码并在终端打印 2. 同时打印一个**二维码链接**,终端二维码不清晰时可在浏览器中打开 3. 轮询确认状态——扫码后还需要在**企业微信 App 内点击确认** -4. 成功后将 `bot_id` 和 `secret` 写入 `channels.wecom` 并保存配置 +4. 成功后将 `bot_id` 和 `secret` 写入 `channel_list.wecom.settings` 并保存配置 默认超时为 **5 分钟**,可通过 `--timeout` 延长: @@ -46,18 +46,22 @@ picoclaw auth wecom --timeout 10m 如果已有企业微信 AI Bot 的 `bot_id` 和 `secret`,可直接配置: +> 配置结构:`enabled`、`type`、`allow_from` 等公共字段位于渠道条目,Token、App ID 等专有字段位于 `settings`。`.security.yml` 使用 `channel_list.<名称>.settings` 保存渠道密钥;其中的同名值会覆盖主配置。 + ```json { "channel_list": { "wecom": { "enabled": true, "type": "wecom", - "bot_id": "YOUR_BOT_ID", - "secret": "YOUR_SECRET", - "websocket_url": "wss://openws.work.weixin.qq.com", - "send_thinking_message": true, "allow_from": [], - "reasoning_channel_id": "" + "reasoning_channel_id": "", + "settings": { + "bot_id": "YOUR_BOT_ID", + "secret": "YOUR_SECRET", + "websocket_url": "wss://openws.work.weixin.qq.com", + "send_thinking_message": true + } } } } @@ -138,4 +142,4 @@ picoclaw auth wecom --timeout 10m ### 收不到回复 - 检查 `allow_from` 是否屏蔽了发送者。 -- 确认 `channels.wecom.bot_id` 和 `channels.wecom.secret` 已填写且非空。 +- 确认 `channel_list.wecom.settings.bot_id` 和 `channel_list.wecom.settings.secret` 已填写且非空。 diff --git a/docs/channels/weixin/README.md b/docs/channels/weixin/README.md index 4e240d69..20ad3cd2 100644 --- a/docs/channels/weixin/README.md +++ b/docs/channels/weixin/README.md @@ -25,7 +25,9 @@ picoclaw gateway ## ⚙️ Configuration -You can also manually configure the filter rules in `config.json` under the `channels.weixin` section. +You can also manually configure the filter rules in `config.json` under the `channel_list.weixin` section. + +> Configuration: common fields such as `enabled`, `type`, and `allow_from` belong on the channel entry; channel-specific fields belong under `settings`. Credentials saved under `channel_list..settings` in `.security.yml` override the main JSON configuration. ```json { @@ -33,12 +35,14 @@ You can also manually configure the filter rules in `config.json` under the `cha "weixin": { "enabled": true, "type": "weixin", - "token": "YOUR_WEIXIN_TOKEN", "allow_from": [ "user_id_1", "user_id_2" ], - "proxy": "" + "settings": { + "token": "YOUR_WEIXIN_TOKEN", + "proxy": "" + } } } } diff --git a/docs/channels/weixin/README.zh.md b/docs/channels/weixin/README.zh.md index 19a9f9fa..61848a0c 100644 --- a/docs/channels/weixin/README.zh.md +++ b/docs/channels/weixin/README.zh.md @@ -25,7 +25,9 @@ picoclaw gateway ## ⚙️ 配置说明 -您也可以在 `config.json` 的 `channels.weixin` 段目下进行手动维护。 +您也可以在 `config.json` 的 `channel_list.weixin` 段目下进行手动维护。 + +> 配置结构:`enabled`、`type`、`allow_from` 等公共字段位于渠道条目,Token、App ID 等专有字段位于 `settings`。`.security.yml` 使用 `channel_list.<名称>.settings` 保存渠道密钥;其中的同名值会覆盖主配置。 ```json { @@ -33,12 +35,14 @@ picoclaw gateway "weixin": { "enabled": true, "type": "weixin", - "token": "YOUR_WEIXIN_TOKEN", "allow_from": [ "user_id_1", "user_id_2" ], - "proxy": "" + "settings": { + "token": "YOUR_WEIXIN_TOKEN", + "proxy": "" + } } } } diff --git a/docs/guides/ANTIGRAVITY_USAGE.fr.md b/docs/guides/ANTIGRAVITY_USAGE.fr.md deleted file mode 100644 index 02e8fbaf..00000000 --- a/docs/guides/ANTIGRAVITY_USAGE.fr.md +++ /dev/null @@ -1,72 +0,0 @@ -> Retour au [README](../../README.md) - -# Utiliser le fournisseur Antigravity dans PicoClaw - -Ce guide explique comment configurer et utiliser le fournisseur **Antigravity** (Google Cloud Code Assist) dans PicoClaw. - -## Prérequis - -1. Un compte Google. -2. Google Cloud Code Assist activé (généralement disponible via l'intégration « Gemini for Google Cloud »). - -## 1. Authentification - -Pour vous authentifier avec Antigravity, exécutez la commande suivante : - -```bash -picoclaw auth login --provider antigravity -``` - -### Authentification manuelle (Headless/VPS) -Si vous exécutez PicoClaw sur un serveur (Coolify/Docker) et ne pouvez pas accéder à `localhost`, suivez ces étapes : -1. Exécutez la commande ci-dessus. -2. Copiez l'URL fournie et ouvrez-la dans votre navigateur local. -3. Complétez la connexion. -4. Votre navigateur sera redirigé vers une URL `localhost:51121` (qui ne se chargera pas). -5. **Copiez cette URL finale** depuis la barre d'adresse de votre navigateur. -6. **Collez-la dans le terminal** où PicoClaw attend. - -PicoClaw extraira automatiquement le code d'autorisation et terminera le processus. - -## 2. Gestion des modèles - -### Lister les modèles disponibles -Pour voir quels modèles sont accessibles à votre projet et vérifier leurs quotas : - -```bash -picoclaw auth models -``` - -### Changer de modèle -Vous pouvez modifier le modèle par défaut dans `~/.picoclaw/config.json` ou le remplacer via le CLI : - -```bash -# Remplacer pour une seule commande -picoclaw agent -m "Hello" --model claude-opus-4-6-thinking -``` - -## 3. Utilisation en production (Coolify/Docker) - -Si vous déployez via Coolify ou Docker, suivez ces étapes pour tester : - -1. **Variables d'environnement** : - * `PICOCLAW_AGENTS_DEFAULTS_MODEL=gemini-flash` -2. **Persistance de l'authentification** : - Si vous vous êtes connecté localement, vous pouvez copier vos identifiants vers le serveur : - ```bash - scp ~/.picoclaw/auth.json user@your-server:~/.picoclaw/ - ``` - *Alternativement*, exécutez la commande `auth login` une fois sur le serveur si vous avez un accès terminal. - -## 4. Dépannage - -* **Réponse vide** : Si un modèle renvoie une réponse vide, il peut être restreint pour votre projet. Essayez `gemini-3-flash` ou `claude-opus-4-6-thinking`. -* **429 Limite de débit** : Antigravity a des quotas stricts. PicoClaw affichera le « temps de réinitialisation » dans le message d'erreur si vous atteignez une limite. -* **404 Non trouvé** : Assurez-vous d'utiliser un ID de modèle provenant de la liste `picoclaw auth models`. Utilisez l'ID court (par ex. `gemini-3-flash`) et non le chemin complet. - -## 5. Résumé des modèles fonctionnels - -D'après les tests, les modèles suivants sont les plus fiables : -* `gemini-3-flash` (Rapide, haute disponibilité) -* `gemini-2.5-flash-lite` (Léger) -* `claude-opus-4-6-thinking` (Puissant, inclut le raisonnement) diff --git a/docs/guides/ANTIGRAVITY_USAGE.ja.md b/docs/guides/ANTIGRAVITY_USAGE.ja.md deleted file mode 100644 index 1621766f..00000000 --- a/docs/guides/ANTIGRAVITY_USAGE.ja.md +++ /dev/null @@ -1,72 +0,0 @@ -> [README](../../README.md) に戻る - -# PicoClaw で Antigravity プロバイダーを使用する - -このガイドでは、PicoClaw で **Antigravity**(Google Cloud Code Assist)プロバイダーをセットアップして使用する方法を説明します。 - -## 前提条件 - -1. Google アカウント。 -2. Google Cloud Code Assist が有効であること(通常「Gemini for Google Cloud」のオンボーディングから利用可能)。 - -## 1. 認証 - -Antigravity で認証するには、以下のコマンドを実行します: - -```bash -picoclaw auth login --provider antigravity -``` - -### 手動認証(ヘッドレス/VPS) -サーバー(Coolify/Docker)上で実行しており、`localhost` にアクセスできない場合は、以下の手順に従ってください: -1. 上記のコマンドを実行します。 -2. 表示された URL をコピーし、ローカルブラウザで開きます。 -3. ログインを完了します。 -4. ブラウザが `localhost:51121` URL にリダイレクトされます(ページは読み込めません)。 -5. **ブラウザのアドレスバーからその最終 URL をコピーします**。 -6. **PicoClaw が待機しているターミナルにそれを貼り付けます**。 - -PicoClaw が自動的に認証コードを抽出し、プロセスを完了します。 - -## 2. モデルの管理 - -### 利用可能なモデルの一覧 -プロジェクトがアクセスできるモデルとそのクォータを確認するには: - -```bash -picoclaw auth models -``` - -### モデルの切り替え -`~/.picoclaw/config.json` でデフォルトモデルを変更するか、CLI でオーバーライドできます: - -```bash -# 単一コマンドでオーバーライド -picoclaw agent -m "Hello" --model claude-opus-4-6-thinking -``` - -## 3. 実際の使用方法(Coolify/Docker) - -Coolify または Docker でデプロイしている場合、以下の手順でテストしてください: - -1. **環境変数**: - * `PICOCLAW_AGENTS_DEFAULTS_MODEL=gemini-flash` -2. **認証の永続化**: - ローカルでログイン済みの場合、認証情報をサーバーにコピーできます: - ```bash - scp ~/.picoclaw/auth.json user@your-server:~/.picoclaw/ - ``` - *または*、ターミナルアクセスがある場合、サーバー上で `auth login` コマンドを一度実行してください。 - -## 4. トラブルシューティング - -* **空のレスポンス**:モデルが空の応答を返す場合、プロジェクトで制限されている可能性があります。`gemini-3-flash` または `claude-opus-4-6-thinking` を試してください。 -* **429 レート制限**:Antigravity には厳格なクォータがあります。制限に達した場合、PicoClaw はエラーメッセージに「リセット時間」を表示します。 -* **404 Not Found**:`picoclaw auth models` リストのモデル ID を使用していることを確認してください。フルパスではなく、短い ID(例:`gemini-3-flash`)を使用してください。 - -## 5. 動作確認済みモデルのまとめ - -テストに基づき、以下のモデルが最も信頼性が高いです: -* `gemini-3-flash`(高速、高可用性) -* `gemini-2.5-flash-lite`(軽量) -* `claude-opus-4-6-thinking`(高性能、推論機能を含む) diff --git a/docs/guides/ANTIGRAVITY_USAGE.md b/docs/guides/ANTIGRAVITY_USAGE.md deleted file mode 100644 index e8194b6b..00000000 --- a/docs/guides/ANTIGRAVITY_USAGE.md +++ /dev/null @@ -1,70 +0,0 @@ -# Using Antigravity Provider in PicoClaw - -This guide explains how to set up and use the **Antigravity** (Google Cloud Code Assist) provider in PicoClaw. - -## Prerequisites - -1. A Google account. -2. Google Cloud Code Assist enabled (usually available via the "Gemini for Google Cloud" onboarding). - -## 1. Authentication - -To authenticate with Antigravity, run the following command: - -```bash -picoclaw auth login --provider antigravity -``` - -### Manual Authentication (Headless/VPS) -If you are running on a server (Coolify/Docker) and cannot reach `localhost`, follow these steps: -1. Run the command above. -2. Copy the URL provided and open it in your local browser. -3. Complete the login. -4. Your browser will redirect to a `localhost:51121` URL (which will fail to load). -5. **Copy that final URL** from your browser's address bar. -6. **Paste it back into the terminal** where PicoClaw is waiting. - -PicoClaw will extract the authorization code and complete the process automatically. - -## 2. Managing Models - -### List Available Models -To see which models your project has access to and check their quotas: - -```bash -picoclaw auth models -``` - -### Switch Models -You can change the default model in `~/.picoclaw/config.json` or override it via the CLI: - -```bash -# Override for a single command -picoclaw agent -m "Hello" --model claude-opus-4-6-thinking -``` - -## 3. Real-world Usage (Coolify/Docker) - -If you are deploying via Coolify or Docker, follow these steps to test: - -1. **Environment Variables**: - * `PICOCLAW_AGENTS_DEFAULTS_MODEL=gemini-flash` -2. **Authentication persistence**: - If you've logged in locally, you can copy your credentials to the server: - ```bash - scp ~/.picoclaw/auth.json user@your-server:~/.picoclaw/ - ``` - *Alternatively*, run the `auth login` command once on the server if you have terminal access. - -## 4. Troubleshooting - -* **Empty Response**: If a model returns an empty reply, it may be restricted for your project. Try `gemini-3-flash` or `claude-opus-4-6-thinking`. -* **429 Rate Limit**: Antigravity has strict quotas. PicoClaw will display the "reset time" in the error message if you hit a limit. -* **404 Not Found**: Ensure you are using a model ID from the `picoclaw auth models` list. Use the short ID (e.g., `gemini-3-flash`) not the full path. - -## 5. Summary of Working Models - -Based on testing, the following models are most reliable: -* `gemini-3-flash` (Fast, highly available) -* `gemini-2.5-flash-lite` (Lightweight) -* `claude-opus-4-6-thinking` (Powerful, includes reasoning) diff --git a/docs/guides/ANTIGRAVITY_USAGE.pt-br.md b/docs/guides/ANTIGRAVITY_USAGE.pt-br.md deleted file mode 100644 index fec71663..00000000 --- a/docs/guides/ANTIGRAVITY_USAGE.pt-br.md +++ /dev/null @@ -1,72 +0,0 @@ -> Voltar ao [README](../../README.md) - -# Usando o provedor Antigravity no PicoClaw - -Este guia explica como configurar e usar o provedor **Antigravity** (Google Cloud Code Assist) no PicoClaw. - -## Pré-requisitos - -1. Uma conta Google. -2. Google Cloud Code Assist habilitado (geralmente disponível através da integração "Gemini for Google Cloud"). - -## 1. Autenticação - -Para se autenticar com o Antigravity, execute o seguinte comando: - -```bash -picoclaw auth login --provider antigravity -``` - -### Autenticação manual (Headless/VPS) -Se você está executando em um servidor (Coolify/Docker) e não consegue acessar `localhost`, siga estas etapas: -1. Execute o comando acima. -2. Copie a URL fornecida e abra-a no seu navegador local. -3. Complete o login. -4. Seu navegador será redirecionado para uma URL `localhost:51121` (que não carregará). -5. **Copie essa URL final** da barra de endereços do seu navegador. -6. **Cole-a de volta no terminal** onde o PicoClaw está aguardando. - -O PicoClaw extrairá automaticamente o código de autorização e completará o processo. - -## 2. Gerenciando modelos - -### Listar modelos disponíveis -Para ver quais modelos seu projeto tem acesso e verificar suas cotas: - -```bash -picoclaw auth models -``` - -### Trocar de modelo -Você pode alterar o modelo padrão em `~/.picoclaw/config.json` ou substituí-lo via CLI: - -```bash -# Substituir para um único comando -picoclaw agent -m "Hello" --model claude-opus-4-6-thinking -``` - -## 3. Uso em produção (Coolify/Docker) - -Se você está implantando via Coolify ou Docker, siga estas etapas para testar: - -1. **Variáveis de ambiente**: - * `PICOCLAW_AGENTS_DEFAULTS_MODEL=gemini-flash` -2. **Persistência da autenticação**: - Se você já fez login localmente, pode copiar suas credenciais para o servidor: - ```bash - scp ~/.picoclaw/auth.json user@your-server:~/.picoclaw/ - ``` - *Alternativamente*, execute o comando `auth login` uma vez no servidor se você tiver acesso ao terminal. - -## 4. Solução de problemas - -* **Resposta vazia**: Se um modelo retorna uma resposta vazia, ele pode estar restrito para o seu projeto. Tente `gemini-3-flash` ou `claude-opus-4-6-thinking`. -* **429 Limite de taxa**: O Antigravity possui cotas rigorosas. O PicoClaw exibirá o "tempo de redefinição" na mensagem de erro se você atingir um limite. -* **404 Não encontrado**: Certifique-se de que está usando um ID de modelo da lista `picoclaw auth models`. Use o ID curto (ex.: `gemini-3-flash`) e não o caminho completo. - -## 5. Resumo dos modelos funcionais - -Com base nos testes, os seguintes modelos são os mais confiáveis: -* `gemini-3-flash` (Rápido, alta disponibilidade) -* `gemini-2.5-flash-lite` (Leve) -* `claude-opus-4-6-thinking` (Poderoso, inclui raciocínio) diff --git a/docs/guides/ANTIGRAVITY_USAGE.vi.md b/docs/guides/ANTIGRAVITY_USAGE.vi.md deleted file mode 100644 index c8ea4d98..00000000 --- a/docs/guides/ANTIGRAVITY_USAGE.vi.md +++ /dev/null @@ -1,72 +0,0 @@ -> Quay lại [README](../../README.md) - -# Sử dụng nhà cung cấp Antigravity trong PicoClaw - -Hướng dẫn này giải thích cách thiết lập và sử dụng nhà cung cấp **Antigravity** (Google Cloud Code Assist) trong PicoClaw. - -## Điều kiện tiên quyết - -1. Một tài khoản Google. -2. Đã kích hoạt Google Cloud Code Assist (thường có sẵn thông qua quy trình giới thiệu "Gemini for Google Cloud"). - -## 1. Xác thực - -Để xác thực với Antigravity, chạy lệnh sau: - -```bash -picoclaw auth login --provider antigravity -``` - -### Xác thực thủ công (Headless/VPS) -Nếu bạn đang chạy trên máy chủ (Coolify/Docker) và không thể truy cập `localhost`, hãy làm theo các bước sau: -1. Chạy lệnh ở trên. -2. Sao chép URL được cung cấp và mở nó trong trình duyệt cục bộ của bạn. -3. Hoàn tất đăng nhập. -4. Trình duyệt của bạn sẽ chuyển hướng đến URL `localhost:51121` (trang sẽ không tải được). -5. **Sao chép URL cuối cùng đó** từ thanh địa chỉ trình duyệt. -6. **Dán nó vào terminal** nơi PicoClaw đang chờ. - -PicoClaw sẽ tự động trích xuất mã ủy quyền và hoàn tất quy trình. - -## 2. Quản lý mô hình - -### Liệt kê các mô hình khả dụng -Để xem dự án của bạn có quyền truy cập vào những mô hình nào và kiểm tra hạn mức của chúng: - -```bash -picoclaw auth models -``` - -### Chuyển đổi mô hình -Bạn có thể thay đổi mô hình mặc định trong `~/.picoclaw/config.json` hoặc ghi đè qua CLI: - -```bash -# Ghi đè cho một lệnh duy nhất -picoclaw agent -m "Hello" --model claude-opus-4-6-thinking -``` - -## 3. Sử dụng thực tế (Coolify/Docker) - -Nếu bạn đang triển khai qua Coolify hoặc Docker, hãy làm theo các bước sau để kiểm tra: - -1. **Biến môi trường**: - * `PICOCLAW_AGENTS_DEFAULTS_MODEL=gemini-flash` -2. **Lưu trữ xác thực**: - Nếu bạn đã đăng nhập cục bộ, bạn có thể sao chép thông tin xác thực lên máy chủ: - ```bash - scp ~/.picoclaw/auth.json user@your-server:~/.picoclaw/ - ``` - *Hoặc*, chạy lệnh `auth login` một lần trên máy chủ nếu bạn có quyền truy cập terminal. - -## 4. Khắc phục sự cố - -* **Phản hồi trống**: Nếu một mô hình trả về phản hồi trống, nó có thể bị hạn chế cho dự án của bạn. Hãy thử `gemini-3-flash` hoặc `claude-opus-4-6-thinking`. -* **429 Giới hạn tốc độ**: Antigravity có hạn mức nghiêm ngặt. PicoClaw sẽ hiển thị "thời gian đặt lại" trong thông báo lỗi nếu bạn đạt đến giới hạn. -* **404 Không tìm thấy**: Đảm bảo bạn đang sử dụng ID mô hình từ danh sách `picoclaw auth models`. Sử dụng ID ngắn (ví dụ: `gemini-3-flash`) thay vì đường dẫn đầy đủ. - -## 5. Tóm tắt các mô hình hoạt động tốt - -Dựa trên kiểm tra, các mô hình sau đáng tin cậy nhất: -* `gemini-3-flash` (Nhanh, khả dụng cao) -* `gemini-2.5-flash-lite` (Nhẹ) -* `claude-opus-4-6-thinking` (Mạnh mẽ, bao gồm khả năng suy luận) diff --git a/docs/guides/ANTIGRAVITY_USAGE.zh.md b/docs/guides/ANTIGRAVITY_USAGE.zh.md deleted file mode 100644 index c68c3ad8..00000000 --- a/docs/guides/ANTIGRAVITY_USAGE.zh.md +++ /dev/null @@ -1,72 +0,0 @@ -> 返回 [README](../../README.md) - -# 在 PicoClaw 中使用 Antigravity 提供商 - -本指南介绍如何在 PicoClaw 中设置和使用 **Antigravity**(Google Cloud Code Assist)提供商。 - -## 前提条件 - -1. 一个 Google 账户。 -2. 已启用 Google Cloud Code Assist(通常通过"Gemini for Google Cloud"引导流程获取)。 - -## 1. 身份验证 - -要使用 Antigravity 进行身份验证,请运行以下命令: - -```bash -picoclaw auth login --provider antigravity -``` - -### 手动验证(无界面/VPS 环境) -如果你在服务器(Coolify/Docker)上运行且无法访问 `localhost`,请按照以下步骤操作: -1. 运行上述命令。 -2. 复制提供的 URL 并在本地浏览器中打开。 -3. 完成登录。 -4. 浏览器将重定向到 `localhost:51121` URL(页面将无法加载)。 -5. **从浏览器地址栏复制该最终 URL**。 -6. **将其粘贴回 PicoClaw 正在等待的终端中**。 - -PicoClaw 将自动提取授权码并完成流程。 - -## 2. 管理模型 - -### 列出可用模型 -查看你的项目可以访问哪些模型并检查其配额: - -```bash -picoclaw auth models -``` - -### 切换模型 -你可以在 `~/.picoclaw/config.json` 中更改默认模型,或通过 CLI 覆盖: - -```bash -# 为单个命令覆盖 -picoclaw agent -m "Hello" --model claude-opus-4-6-thinking -``` - -## 3. 实际使用(Coolify/Docker) - -如果你通过 Coolify 或 Docker 部署,请按照以下步骤进行测试: - -1. **环境变量**: - * `PICOCLAW_AGENTS_DEFAULTS_MODEL=gemini-flash` -2. **身份验证持久化**: - 如果你已在本地登录,可以将凭据复制到服务器: - ```bash - scp ~/.picoclaw/auth.json user@your-server:~/.picoclaw/ - ``` - *或者*,如果你有终端访问权限,可以在服务器上运行一次 `auth login` 命令。 - -## 4. 故障排除 - -* **空响应**:如果模型返回空回复,可能是该模型在你的项目中受到限制。请尝试 `gemini-3-flash` 或 `claude-opus-4-6-thinking`。 -* **429 速率限制**:Antigravity 有严格的配额限制。如果触发限制,PicoClaw 将在错误消息中显示"重置时间"。 -* **404 未找到**:确保你使用的是 `picoclaw auth models` 列表中的模型 ID。请使用短 ID(例如 `gemini-3-flash`),而非完整路径。 - -## 5. 可用模型总结 - -根据测试,以下模型最为可靠: -* `gemini-3-flash`(快速,高可用性) -* `gemini-2.5-flash-lite`(轻量级) -* `claude-opus-4-6-thinking`(强大,包含推理能力) diff --git a/docs/guides/README.md b/docs/guides/README.md index 9d9a0bb4..65cf3471 100644 --- a/docs/guides/README.md +++ b/docs/guides/README.md @@ -10,7 +10,7 @@ Task-oriented guides for setup, configuration, and common PicoClaw workflows. - [Chat Apps Configuration](chat-apps.md): supported chat platforms and channel-specific setup paths. - [Providers & Model Configuration](providers.md): `model_list`, providers, and model routing. - [Spawn & Async Tasks](spawn-tasks.md): background work, long-running tasks, and sub-agent orchestration. -- [PicoClaw Hardware Compatibility List](hardware-compatibility.md): tested boards and platform notes. -- [Using Antigravity Provider in PicoClaw](ANTIGRAVITY_USAGE.md): Google Cloud Code Assist setup and usage. +- [Platforms and hardware boundaries](hardware-compatibility.md): build targets and optional hardware integrations. +- [Office Skills](office-skills.zh.md): Docker runtime for Word, Excel and PowerPoint files. Translations usually live beside the English source when available. diff --git a/docs/guides/android-termux.md b/docs/guides/android-termux.md index c57eb6ed..cf79a72c 100644 --- a/docs/guides/android-termux.md +++ b/docs/guides/android-termux.md @@ -1,88 +1,9 @@ -# Android Termux Guide +# Android Termux > Back to [Guides](README.md) -This guide covers running the PicoClaw terminal binary on an ARM64 Android phone with Termux for a lightweight command-line install. +This fork currently publishes only Linux amd64 archives. There is no Android or Linux ARM64 release asset; the previous upstream download commands do not install this fork. -## Requirements +The Makefile retains `make build-android-arm64`, which produces `build/picoclaw-android-arm64` from this repository. Android builds and runtime behavior are outside the current CI and have not been verified for this fork. Check the target environment and dependencies before using them. -- ARM64 Android device. Run `uname -m` in Termux and use this guide when it prints `aarch64`. -- Termux installed from [Termux GitHub Releases](https://github.com/termux/termux-app/releases) or F-Droid. -- Network access for downloading the release and calling your LLM provider. -- An API key for at least one configured model provider. - -## Install PicoClaw - -Open Termux and install the packages used by the release archive and chroot wrapper: - -```bash -pkg update -pkg install -y wget tar proot -``` - -Download and unpack the ARM64 Linux release: - -```bash -mkdir -p ~/picoclaw -cd ~/picoclaw -wget https://github.com/sipeed/picoclaw/releases/latest/download/picoclaw_Linux_arm64.tar.gz -tar xzf picoclaw_Linux_arm64.tar.gz -chmod +x ./picoclaw -``` - -Start first-run setup through `termux-chroot`, which gives the Linux binary a more standard filesystem layout than a raw Android userspace: - -```bash -termux-chroot ./picoclaw onboard -``` - -## Configure - -Edit the generated config and add at least one model provider API key: - -```bash -vim ~/.picoclaw/config.json -``` - -The default workspace is `~/.picoclaw/workspace`. If you want PicoClaw to read or write Android shared storage, run `termux-setup-storage` first and then point the workspace or any file paths at the mounted storage directory. - -See [Configuration Guide](configuration.md) and [Providers & Model Configuration](providers.md) for the available config fields and provider examples. - -## Run - -Use one-shot agent mode to confirm the installation: - -```bash -termux-chroot ./picoclaw agent -m "Hello from Termux" -``` - -For long-running use, start the gateway: - -```bash -termux-chroot ./picoclaw gateway -``` - -Keep the Termux session open while PicoClaw is running. Android battery optimization can stop background work, so disable battery optimization for Termux if you expect PicoClaw to keep running after the screen locks. - -## Update - -Your config and workspace live under `~/.picoclaw`, so updating the binary does not remove them: - -```bash -cd ~/picoclaw -rm -f picoclaw_Linux_arm64.tar.gz -wget https://github.com/sipeed/picoclaw/releases/latest/download/picoclaw_Linux_arm64.tar.gz -tar xzf picoclaw_Linux_arm64.tar.gz -chmod +x ./picoclaw -termux-chroot ./picoclaw version -``` - -## Troubleshooting - -| Symptom | Check | -|---------|-------| -| `permission denied` | Run `chmod +x ./picoclaw` after unpacking the archive. | -| `not found` after running `./picoclaw` | Confirm `uname -m` prints `aarch64` and that you downloaded `picoclaw_Linux_arm64.tar.gz`. | -| Files or paths behave differently than Linux | Run PicoClaw through `termux-chroot` instead of calling the binary directly. | -| Provider requests fail | Check the API key and network access in `~/.picoclaw/config.json`. | -| PicoClaw stops when the phone sleeps | Disable Android battery optimization for Termux and keep a foreground Termux session active. | +For the maintained installation path, use [Linux amd64 or a local source build](../../README.md#从源码构建). Model protocols and configuration are described in the [provider guide](providers.md). diff --git a/docs/guides/chat-apps.fr.md b/docs/guides/chat-apps.fr.md index bfda1686..8a8b2830 100644 --- a/docs/guides/chat-apps.fr.md +++ b/docs/guides/chat-apps.fr.md @@ -1,446 +1,5 @@ -# 💬 Configuration des Applications de Chat +# Chat channels in this fork -> Retour au [README](../../README.md) +Supported channels are Weixin, WeCom, Feishu, DingTalk, QQ, OneBot, Telegram, and MQTT. The previous WeCom app/webhook variants have been replaced by the unified AI Bot WebSocket channel. -## 💬 Applications de Chat - -Communiquez avec votre PicoClaw via Telegram, QQ, DingTalk, WeCom, Feishu, OneBot, MQTT. - - -| Canal | Difficulté | Description | Documentation | -| -------------------- | ------------------ | ----------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------- | -| **Telegram** | ⭐ Facile | Recommandé, transcription vocale, long polling (pas d'IP publique requise) | [Documentation](../channels/telegram/README.fr.md) | -| **Weixin** | ⭐ Facile | Scan QR natif (API Tencent iLink) | [Documentation](#weixin) | -| **QQ** | ⭐⭐ Moyen | API bot officielle, communauté chinoise | [Documentation](../channels/qq/README.fr.md) | -| **DingTalk** | ⭐⭐ Moyen | Mode Stream (pas d'IP publique requise), entreprise | [Documentation](../channels/dingtalk/README.fr.md) | -| **WeCom (企业微信)** | ⭐⭐⭐ Avancé | Bot groupe (Webhook), app personnalisée (API), AI Bot | [Guide](../channels/wecom/README.fr.md) | -| **Feishu (飞书)** | ⭐⭐⭐ Avancé | Collaboration entreprise, fonctionnalités riches | [Documentation](../channels/feishu/README.fr.md) | -| **OneBot** | ⭐⭐ Moyen | Compatible NapCat/Go-CQHTTP, écosystème communautaire | [Documentation](../channels/onebot/README.fr.md) | -| **MQTT** | ⭐ Facile | N'importe quel client MQTT via broker pub/sub | [Documentation](../channels/mqtt/README.fr.md) | - - -
-Telegram (Recommandé) - -**1. Créer un bot** - -* Ouvrez Telegram, recherchez `@BotFather` -* Envoyez `/newbot`, suivez les instructions -* Copiez le token - -**2. Configurer** - -```json -{ - "channel_list": { - "telegram": { - "enabled": true, - "type": "telegram", - "token": "YOUR_BOT_TOKEN", - "allow_from": ["YOUR_USER_ID"] - } - } -} -``` - -> Obtenez votre identifiant utilisateur via `@userinfobot` sur Telegram. - -**3. Lancer** - -```bash -picoclaw gateway -``` - -**4. Menu de commandes Telegram (enregistré automatiquement au démarrage)** - -PicoClaw conserve les définitions de commandes dans un registre partagé unique. Au démarrage, Telegram enregistre automatiquement les commandes bot prises en charge (par exemple `/start`, `/help`, `/show`, `/list`, `/use`, `/btw`) afin que le menu de commandes et le comportement à l'exécution restent synchronisés. -L'enregistrement du menu de commandes Telegram reste une découverte UX locale au canal ; l'exécution générique des commandes est gérée de manière centralisée dans la boucle agent via l'exécuteur de commandes. - -Si l'enregistrement des commandes échoue (erreurs transitoires réseau/API), le canal démarre quand même et PicoClaw réessaie l'enregistrement en arrière-plan. - -Vous pouvez aussi gerer les competences installees directement depuis Telegram : - -- `/list skills` -- `/use ` -- `/use ` puis envoyer la vraie requete dans le message suivant -- `/use clear` -- `/btw ` pour poser une question annexe immediate sans modifier l'historique actif de la session ; `/btw` est traite comme une requete directe sans outils et n'entre pas dans le flux normal d'execution des outils - -
- - -
-Weixin (WeChat Personnel) - -PicoClaw prend en charge la connexion à votre compte WeChat personnel via l'API officielle Tencent iLink. - -**1. Connexion** - -Lancez le flux de connexion interactif par QR code : -```bash -picoclaw auth weixin -``` -Scannez le QR code affiché avec votre application WeChat mobile. Une fois connecté, le token est sauvegardé dans votre configuration. - -**2. Configurer** - -(Optionnel) Ajoutez votre identifiant utilisateur WeChat dans `allow_from` pour restreindre qui peut envoyer des messages au bot : -```json -{ - "channel_list": { - "weixin": { - "enabled": true, - "type": "weixin", - "token": "YOUR_TOKEN", - "allow_from": ["YOUR_USER_ID"] - } - } -} -``` - -**3. Lancer** -```bash -picoclaw gateway -``` - -
- - -
-QQ - -**Configuration rapide (recommandée)** - -QQ Open Platform propose une page de configuration en un clic pour les bots compatibles OpenClaw : - -1. Ouvrez [QQ Bot Quick Start](https://q.qq.com/qqbot/openclaw/index.html) et scannez le QR code pour vous connecter -2. Un bot est créé automatiquement — copiez l'**App ID** et l'**App Secret** -3. Configurez PicoClaw : - -```json -{ - "channel_list": { - "qq": { - "enabled": true, - "type": "qq", - "app_id": "YOUR_APP_ID", - "app_secret": "YOUR_APP_SECRET", - "allow_from": [] - } - } -} -``` - -4. Lancez `picoclaw gateway` et ouvrez QQ pour discuter avec votre bot - -> L'App Secret n'est affiché qu'une seule fois. Enregistrez-le immédiatement — le consulter à nouveau forcera une réinitialisation. -> -> Les bots créés via la page de configuration rapide sont initialement réservés au créateur et ne prennent pas en charge les discussions de groupe. Pour activer l'accès en groupe, configurez le mode sandbox sur la [QQ Open Platform](https://q.qq.com/). - -**Configuration manuelle** - -Si vous préférez créer le bot manuellement : - -* Connectez-vous sur [QQ Open Platform](https://q.qq.com/) pour vous inscrire en tant que développeur -* Créez un bot QQ — personnalisez son avatar et son nom -* Copiez l'**App ID** et l'**App Secret** depuis les paramètres du bot -* Configurez comme indiqué ci-dessus et lancez `picoclaw gateway` - -
- - -
-DingTalk - -**1. Créer un bot** - -* Allez sur [Open Platform](https://open.dingtalk.com/) -* Créez une application interne -* Copiez le Client ID et le Client Secret - -**2. Configurer** - -```json -{ - "channel_list": { - "dingtalk": { - "enabled": true, - "type": "dingtalk", - "client_id": "YOUR_CLIENT_ID", - "client_secret": "YOUR_CLIENT_SECRET", - "allow_from": [] - } - } -} -``` - -> Définissez `allow_from` vide pour autoriser tous les utilisateurs, ou spécifiez des identifiants DingTalk pour restreindre l'accès. - -**3. Lancer** - -```bash -picoclaw gateway -``` -
- - -
-WeCom (企业微信) - -PicoClaw prend en charge trois types d'intégration WeCom : - -**Option 1 : WeCom Bot (Bot)** - Configuration plus facile, prend en charge les discussions de groupe -**Option 2 : WeCom App (Application personnalisée)** - Plus de fonctionnalités, messagerie proactive, chat privé uniquement -**Option 3 : WeCom AI Bot (Bot IA)** - Bot IA officiel, réponses en streaming, prend en charge les discussions de groupe et privées - -Voir le [Guide de Configuration WeCom](../channels/wecom/README.fr.md) pour les instructions détaillées. - -**Configuration rapide - WeCom Bot :** - -**1. Créer un bot** - -* Allez dans la console d'administration WeCom → Discussion de groupe → Ajouter un bot de groupe -* Copiez l'URL du webhook (format : `https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=xxx`) - -**2. Configurer** - -```json -{ - "channel_list": { - "wecom": { - "enabled": true, - "type": "wecom", - "token": "YOUR_TOKEN", - "encoding_aes_key": "YOUR_ENCODING_AES_KEY", - "webhook_url": "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=YOUR_KEY", - "webhook_path": "/webhook/wecom", - "allow_from": [] - } - } -} -``` - - -**Configuration rapide - WeCom App :** - -**1. Créer une application** - -* Allez dans la console d'administration WeCom → Gestion des applications → Créer une application -* Copiez **AgentId** et **Secret** -* Allez sur la page "Mon entreprise", copiez **CorpID** - -**2. Configurer la réception des messages** - -* Dans les détails de l'application, cliquez sur "Recevoir les messages" → "Configurer l'API" -* Définissez l'URL à `http://your-server:18790/webhook/wecom-app` -* Générez **Token** et **EncodingAESKey** - -**3. Configurer** - -```json -{ - "channel_list": { - "wecom_app": { - "enabled": true, - "corp_id": "wwxxxxxxxxxxxxxxxx", - "corp_secret": "YOUR_CORP_SECRET", - "agent_id": 1000002, - "token": "YOUR_TOKEN", - "encoding_aes_key": "YOUR_ENCODING_AES_KEY", - "webhook_path": "/webhook/wecom-app", - "allow_from": [] - } - } -} -``` - -**4. Lancer** - -```bash -picoclaw gateway -``` - -> **Note** : Les callbacks webhook WeCom sont servis sur le port Gateway (par défaut 18790). Utilisez un reverse proxy pour HTTPS. - -**Configuration rapide - WeCom AI Bot :** - -**1. Créer un AI Bot** - -* Allez dans la console d'administration WeCom → Gestion des applications → AI Bot -* Dans les paramètres du AI Bot, configurez l'URL de callback : `http://your-server:18790/webhook/wecom-aibot` -* Copiez **Token** et cliquez sur "Générer aléatoirement" pour **EncodingAESKey** - -**2. Configurer** - -```json -{ - "channel_list": { - "wecom_aibot": { - "enabled": true, - "token": "YOUR_TOKEN", - "encoding_aes_key": "YOUR_43_CHAR_ENCODING_AES_KEY", - "webhook_path": "/webhook/wecom-aibot", - "allow_from": [], - "welcome_message": "Hello! How can I help you?", - "processing_message": "⏳ Processing, please wait. The results will be sent shortly." - } - } -} -``` - -**3. Lancer** - -```bash -picoclaw gateway -``` - -> **Note** : WeCom AI Bot utilise le protocole streaming pull — pas de problème de timeout de réponse. Les tâches longues (>30 secondes) basculent automatiquement vers la livraison push via `response_url`. - -
- - -
-Feishu (飞书) - -PicoClaw se connecte à Feishu via le mode WebSocket/SDK — aucune URL webhook publique ni serveur de callback nécessaire. - -**1. Créer une application** - -* Allez sur [Feishu Open Platform](https://open.feishu.cn/) et créez une application -* Dans les paramètres de l'application, activez la capacité **Bot** -* Créez une version et publiez l'application (l'application doit être publiée pour prendre effet) -* Copiez l'**App ID** (commence par `cli_`) et l'**App Secret** - -**2. Configurer** - -```json -{ - "channel_list": { - "feishu": { - "enabled": true, - "type": "feishu", - "app_id": "cli_xxx", - "app_secret": "YOUR_APP_SECRET", - "allow_from": [] - } - } -} -``` - -Optionnel : `encrypt_key` et `verification_token` pour le chiffrement des événements (recommandé en production). - -**3. Lancer et discuter** - -```bash -picoclaw gateway -``` - -Ouvrez Feishu, recherchez le nom de votre bot et commencez à discuter. Vous pouvez aussi ajouter le bot à un groupe — utilisez `group_trigger.mention_only: true` pour ne répondre que lorsqu'il est @mentionné. - -Pour toutes les options, voir le [Guide de Configuration du Canal Feishu](../channels/feishu/README.fr.md). - -
- - -
-OneBot (QQ via protocole OneBot) - -OneBot est un protocole ouvert pour les bots QQ. PicoClaw se connecte à toute implémentation compatible OneBot v11 (par ex. [Lagrange](https://github.com/LagrangeDev/Lagrange.Core), [NapCat](https://github.com/NapNeko/NapCatQQ)) via WebSocket. - -**1. Configurer une implémentation OneBot** - -Installez et exécutez un framework de bot QQ compatible OneBot v11. Activez son serveur WebSocket. - -**2. Configurer** - -```json -{ - "channel_list": { - "onebot": { - "enabled": true, - "type": "onebot", - "ws_url": "ws://127.0.0.1:8080", - "access_token": "", - "allow_from": [] - } - } -} -``` - -| Champ | Description | -|-------|-------------| -| `ws_url` | URL WebSocket de l'implémentation OneBot | -| `access_token` | Token d'accès pour l'authentification (si configuré dans OneBot) | -| `reconnect_interval` | Intervalle de reconnexion en secondes (par défaut : 5) | - -**3. Lancer** - -```bash -picoclaw gateway -``` - -
- - -
-MQTT - -N'importe quel client MQTT peut communiquer avec PicoClaw via un broker. Les appareils ou services publient des requêtes vers le broker ; PicoClaw s'abonne, les traite et publie les réponses en retour. - -**1. Configurer** - -```json -{ - "channel_list": { - "mqtt": { - "enabled": true, - "type": "mqtt", - "settings": { - "broker": "ssl://votre-broker:8883", - "agent_id": "assistant", - "topic_prefix": "/picoclaw", - "keep_alive": 60, - "qos": 0 - } - } - } -} -``` - -Nom d'utilisateur et mot de passe dans `~/.picoclaw/.security.yml` : - -```yaml -channel_list: - mqtt: - settings: - username: votre_utilisateur - password: votre_mot_de_passe -``` - -**Format des topics** - -``` -{prefix}/{agent_id}/{client_id}/request # Client → PicoClaw -{prefix}/{agent_id}/{client_id}/response # PicoClaw → Client -``` - -Le `client_id` est défini par votre application cliente pour identifier les appareils ou sessions. - -**2. Lancer** - -```bash -picoclaw gateway -``` - -**3. Tester** - -```bash -mosquitto_pub -t "/picoclaw/assistant/device1/request" \ - -m '{"text": "Bonjour"}' - -mosquitto_sub -t "/picoclaw/assistant/device1/response" -``` - -Pour les options complètes, voir [Documentation du canal MQTT](../channels/mqtt/README.fr.md). - -
+Use the maintained [channel guide](chat-apps.md) or [中文说明](chat-apps.zh.md), and the current [configuration example](../../config/config.example.json). Channel-specific values belong under `channel_list..settings`. diff --git a/docs/guides/chat-apps.ja.md b/docs/guides/chat-apps.ja.md index 6d1bd033..8a8b2830 100644 --- a/docs/guides/chat-apps.ja.md +++ b/docs/guides/chat-apps.ja.md @@ -1,443 +1,5 @@ -# 💬 チャットアプリ設定 +# Chat channels in this fork -> [README](../../README.md) に戻る +Supported channels are Weixin, WeCom, Feishu, DingTalk, QQ, OneBot, Telegram, and MQTT. The previous WeCom app/webhook variants have been replaced by the unified AI Bot WebSocket channel. -## 💬 チャットアプリ連携 - -PicoClaw は複数のチャットプラットフォームをサポートしており、Agent をどこにでも接続できます。 - - -### チャネル一覧 - -| チャネル | セットアップ難易度 | 特徴 | ドキュメント | -| -------------------- | ------------------ | ----------------------------------------- | --------------------------------------------------------------------------------------------------------------- | -| **Telegram** | ⭐ 簡単 | 推奨、音声テキスト変換対応、ロングポーリング(公開 IP 不要) | [ドキュメント](../channels/telegram/README.ja.md) | -| **微信 (Weixin)** | ⭐ 簡単 | ネイティブ QR スキャン(Tencent iLink API)| [ドキュメント](#weixin) | -| **QQ** | ⭐⭐ 中程度 | 公式ボット API、中国コミュニティ向け | [ドキュメント](../channels/qq/README.ja.md) | -| **DingTalk** | ⭐⭐ 中程度 | Stream モード(公開 IP 不要)、企業向け | [ドキュメント](../channels/dingtalk/README.ja.md) | -| **WeCom (企業微信)** | ⭐⭐⭐ やや難 | グループ Bot (Webhook)、カスタムアプリ (API)、AI Bot 対応 | [ガイド](../channels/wecom/README.ja.md) | -| **Feishu (飛書)** | ⭐⭐⭐ やや難 | エンタープライズコラボレーション、機能豊富 | [ドキュメント](../channels/feishu/README.ja.md) | -| **OneBot** | ⭐⭐ 中程度 | NapCat/Go-CQHTTP 互換、コミュニティエコシステム充実 | [ドキュメント](../channels/onebot/README.ja.md) | -| **MQTT** | ⭐ 簡単 | ブローカー経由で任意の MQTT クライアントと通信 | [ドキュメント](../channels/mqtt/README.ja.md) | - ---- - - -
-Telegram(推奨) - -**1. Bot を作成** - -* Telegram を開き、`@BotFather` を検索 -* `/newbot` を送信し、プロンプトに従う -* Token をコピー - -**2. 設定** - -```json -{ - "channel_list": { - "telegram": { - "enabled": true, - "type": "telegram", - "token": "YOUR_BOT_TOKEN", - "allow_from": ["YOUR_USER_ID"] - } - } -} -``` - -> Telegram の `@userinfobot` から User ID を取得できます。 - -**3. 実行** - -```bash -picoclaw gateway -``` - -**4. Telegram コマンドメニュー(起動時に自動登録)** - -PicoClaw は統一されたコマンド定義を使用します。起動時に Telegram がサポートするコマンド(例: `/start`、`/help`、`/show`、`/list`、`/use`、`/btw`)を Bot コマンドメニューに自動登録し、メニュー表示と実際の動作を一致させます。 -Telegram 側はコマンドメニュー登録機能を保持し、汎用コマンドの実行は Agent Loop 内の commands executor で統一的に処理されます。 - -ネットワークや API の一時的なエラーで登録に失敗しても、チャネルの起動はブロックされません。システムがバックグラウンドで自動リトライします。 - -
- - -
-微信 (Weixin) - -PicoClaw は Tencent iLink 公式 API を使用して WeChat 個人アカウントへの接続をサポートしています。 - -**1. ログイン** - -インタラクティブな QR ログインフローを実行します: -```bash -picoclaw auth weixin -``` -WeChat モバイルアプリで表示された QR コードをスキャンしてください。ログイン成功後、トークンが設定ファイルに保存されます。 - -**2. 設定** - -(オプション)ボットと会話できるユーザーを制限するために `allow_from` に WeChat ユーザー ID を追加します: -```json -{ - "channel_list": { - "weixin": { - "enabled": true, - "type": "weixin", - "token": "YOUR_TOKEN", - "allow_from": ["YOUR_USER_ID"] - } - } -} -``` - -**3. 実行** -```bash -picoclaw gateway -``` - -
- - -
-QQ - -**クイックセットアップ(推奨)** - -QQ 開放プラットフォームでは、OpenClaw 互換ボットのワンクリックセットアップページが提供されています: - -1. [QQ Bot クイックスタート](https://q.qq.com/qqbot/openclaw/index.html) を開き、QR コードをスキャンしてログイン -2. ボットが自動的に作成されます — **App ID** と **App Secret** をコピー -3. PicoClaw を設定: - -```json -{ - "channel_list": { - "qq": { - "enabled": true, - "type": "qq", - "app_id": "YOUR_APP_ID", - "app_secret": "YOUR_APP_SECRET", - "allow_from": [] - } - } -} -``` - -4. `picoclaw gateway` を実行し、QQ を開いてボットとチャット - -> App Secret は一度しか表示されません。すぐに保存してください — 再度表示するとリセットされます。 -> -> クイックセットアップで作成されたボットは、最初は作成者のみが使用でき、グループチャットには対応していません。グループアクセスを有効にするには、[QQ 開放プラットフォーム](https://q.qq.com/) でサンドボックスモードを設定してください。 - -**手動セットアップ** - -ボットを手動で作成する場合: - -* [QQ 開放プラットフォーム](https://q.qq.com/) にログインして開発者登録 -* QQ ボットを作成 — アバターと名前をカスタマイズ -* ボット設定から **App ID** と **App Secret** をコピー -* 上記の設定を行い、`picoclaw gateway` を実行 - -
- - -
-DingTalk - -**1. Bot を作成** - -* [開放プラットフォーム](https://open.dingtalk.com/) にアクセス -* 内部アプリを作成 -* Client ID と Client Secret をコピー - -**2. 設定** - -```json -{ - "channel_list": { - "dingtalk": { - "enabled": true, - "type": "dingtalk", - "client_id": "YOUR_CLIENT_ID", - "client_secret": "YOUR_CLIENT_SECRET", - "allow_from": [] - } - } -} -``` - -> `allow_from` を空にするとすべてのユーザーを許可します。DingTalk ユーザー ID を指定してアクセスを制限することもできます。 - -**3. 実行** - -```bash -picoclaw gateway -``` - -
- - -
-Feishu (飛書) - -PicoClaw は WebSocket/SDK モードで飛書に接続します — 公開 Webhook URL やコールバックサーバーは不要です。 - -**1. アプリを作成** - -* [飛書開放プラットフォーム](https://open.feishu.cn/) にアクセスしてアプリケーションを作成 -* アプリ設定で **ボット** 機能を有効化 -* バージョンを作成してアプリを公開(アプリは公開しないと有効になりません) -* **App ID**(`cli_` で始まる)と **App Secret** をコピー - -**2. 設定** - -```json -{ - "channel_list": { - "feishu": { - "enabled": true, - "type": "feishu", - "app_id": "cli_xxx", - "app_secret": "YOUR_APP_SECRET", - "allow_from": [] - } - } -} -``` - -オプション:`encrypt_key` と `verification_token` でイベント暗号化(本番環境推奨)。 - -**3. 実行してチャット** - -```bash -picoclaw gateway -``` - -飛書を開き、ボット名を検索してチャットを開始できます。ボットをグループに追加することもできます — `group_trigger.mention_only: true` を設定すると @メンション時のみ応答します。 - -詳細なオプションについては [飛書チャネル設定ガイド](../channels/feishu/README.ja.md) を参照してください。 - -
- - -
-WeCom (企業微信) - -PicoClaw は 3 種類の WeCom 統合をサポートしています: - -**方式 1: グループ Bot (Bot)** — セットアップ簡単、グループチャット対応 -**方式 2: カスタムアプリ (App)** — より多機能、プロアクティブメッセージング、プライベートチャットのみ -**方式 3: AI Bot** — 公式 AI Bot、ストリーミング返信、グループ・プライベートチャット対応 - -詳細なセットアップ手順は [WeCom 設定ガイド](../channels/wecom/README.ja.md) を参照してください。 - -**クイックセットアップ — グループ Bot:** - -**1. Bot を作成** - -* WeCom 管理コンソール → グループチャット → グループ Bot を追加 -* Webhook URL をコピー(形式:`https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=xxx`) - -**2. 設定** - -```json -{ - "channel_list": { - "wecom": { - "enabled": true, - "type": "wecom", - "token": "YOUR_TOKEN", - "encoding_aes_key": "YOUR_ENCODING_AES_KEY", - "webhook_url": "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=YOUR_KEY", - "webhook_path": "/webhook/wecom", - "allow_from": [] - } - } -} -``` - - -**クイックセットアップ — カスタムアプリ:** - -**1. アプリを作成** - -* WeCom 管理コンソール → アプリ管理 → アプリを作成 -* **AgentId** と **Secret** をコピー -* 「マイ企業」ページで **CorpID** をコピー - -**2. メッセージ受信を設定** - -* アプリ詳細で「メッセージ受信」→「API を設定」をクリック -* URL を `http://your-server:18790/webhook/wecom-app` に設定 -* **Token** と **EncodingAESKey** を生成 - -**3. 設定** - -```json -{ - "channel_list": { - "wecom_app": { - "enabled": true, - "corp_id": "wwxxxxxxxxxxxxxxxx", - "corp_secret": "YOUR_CORP_SECRET", - "agent_id": 1000002, - "token": "YOUR_TOKEN", - "encoding_aes_key": "YOUR_ENCODING_AES_KEY", - "webhook_path": "/webhook/wecom-app", - "allow_from": [] - } - } -} -``` - -**4. 実行** - -```bash -picoclaw gateway -``` - -> **注意**: WeCom Webhook コールバックは Gateway ポート(デフォルト 18790)で提供されます。HTTPS にはリバースプロキシを使用してください。 - -**クイックセットアップ — AI Bot:** - -**1. AI Bot を作成** - -* WeCom 管理コンソール → アプリ管理 → AI Bot -* AI Bot 設定でコールバック URL を設定:`http://your-server:18790/webhook/wecom-aibot` -* **Token** をコピーし、「ランダム生成」をクリックして **EncodingAESKey** を取得 - -**2. 設定** - -```json -{ - "channel_list": { - "wecom_aibot": { - "enabled": true, - "token": "YOUR_TOKEN", - "encoding_aes_key": "YOUR_43_CHAR_ENCODING_AES_KEY", - "webhook_path": "/webhook/wecom-aibot", - "allow_from": [], - "welcome_message": "こんにちは!何かお手伝いできますか?", - "processing_message": "⏳ Processing, please wait. The results will be sent shortly." - } - } -} -``` - -**3. 実行** - -```bash -picoclaw gateway -``` - -> **注意**: WeCom AI Bot はストリーミングプルプロトコルを使用しており、返信タイムアウトの心配はありません。長時間タスク(30 秒超)は自動的に `response_url` プッシュ配信に切り替わります。 - -
- - -
-OneBot(OneBot プロトコル経由の QQ) - -OneBot は QQ ボット向けのオープンプロトコルです。PicoClaw は OneBot v11 互換の実装(例:[Lagrange](https://github.com/LagrangeDev/Lagrange.Core)、[NapCat](https://github.com/NapNeko/NapCatQQ))に WebSocket で接続します。 - -**1. OneBot 実装をセットアップ** - -OneBot v11 互換の QQ ボットフレームワークをインストールして実行します。WebSocket サーバーを有効にしてください。 - -**2. 設定** - -```json -{ - "channel_list": { - "onebot": { - "enabled": true, - "type": "onebot", - "ws_url": "ws://127.0.0.1:8080", - "access_token": "", - "allow_from": [] - } - } -} -``` - -| フィールド | 説明 | -|-------|-------------| -| `ws_url` | OneBot 実装の WebSocket URL | -| `access_token` | 認証用アクセストークン(OneBot 側で設定している場合) | -| `reconnect_interval` | 再接続間隔(秒)(デフォルト:5) | - -**3. 実行** - -```bash -picoclaw gateway -``` - -
- - -
-MQTT - -任意の MQTT クライアントがブローカーを介して PicoClaw と通信できます。デバイスやサービスがブローカーにリクエストをパブリッシュし、PicoClaw がサブスクライブして処理し、レスポンスをパブリッシュして返します。 - -**1. 設定** - -```json -{ - "channel_list": { - "mqtt": { - "enabled": true, - "type": "mqtt", - "settings": { - "broker": "ssl://your-broker:8883", - "agent_id": "assistant", - "topic_prefix": "/picoclaw", - "keep_alive": 60, - "qos": 0 - } - } - } -} -``` - -ユーザー名とパスワードは `~/.picoclaw/.security.yml` に記載します: - -```yaml -channel_list: - mqtt: - settings: - username: your_username - password: your_password -``` - -**トピック形式** - -``` -{prefix}/{agent_id}/{client_id}/request # クライアント → PicoClaw -{prefix}/{agent_id}/{client_id}/response # PicoClaw → クライアント -``` - -`client_id` はクライアントアプリケーションがデバイスやセッションを識別するために設定します。 - -**2. 起動** - -```bash -picoclaw gateway -``` - -**3. テスト** - -```bash -mosquitto_pub -t "/picoclaw/assistant/device1/request" \ - -m '{"text": "こんにちは"}' - -mosquitto_sub -t "/picoclaw/assistant/device1/response" -``` - -完全な設定オプションは [MQTT チャンネルドキュメント](../channels/mqtt/README.ja.md) を参照してください。 - -
+Use the maintained [channel guide](chat-apps.md) or [中文说明](chat-apps.zh.md), and the current [configuration example](../../config/config.example.json). Channel-specific values belong under `channel_list..settings`. diff --git a/docs/guides/chat-apps.md b/docs/guides/chat-apps.md index b1556b59..0ac28d56 100644 --- a/docs/guides/chat-apps.md +++ b/docs/guides/chat-apps.md @@ -1,6 +1,6 @@ # 💬 Chat Apps Configuration -> Back to [README](../README.md) +> Back to [README](../../README.md) ## 💬 Chat Apps @@ -31,15 +31,21 @@ Talk to your picoclaw through Telegram, QQ, DingTalk, WeCom, Feishu, OneBot, MQT **2. Configure** +> Configuration: common fields such as `enabled`, `type`, and `allow_from` belong on the channel entry; channel-specific fields belong under `settings`. Credentials saved under `channel_list..settings` in `.security.yml` override the main JSON configuration. + ```json { "channel_list": { "telegram": { "enabled": true, "type": "telegram", - "token": "YOUR_BOT_TOKEN", - "allow_from": ["YOUR_USER_ID"], - "use_markdown_v2": false + "allow_from": [ + "YOUR_USER_ID" + ], + "settings": { + "token": "YOUR_BOT_TOKEN", + "use_markdown_v2": false + } } } } @@ -98,8 +104,12 @@ Scan the printed QR code with your WeChat mobile app. On success, the token is s "weixin": { "enabled": true, "type": "weixin", - "token": "YOUR_TOKEN", - "allow_from": ["YOUR_USER_ID"] + "allow_from": [ + "YOUR_USER_ID" + ], + "settings": { + "token": "YOUR_TOKEN" + } } } } @@ -130,9 +140,11 @@ QQ Open Platform provides a one-click setup page for OpenClaw-compatible bots: "qq": { "enabled": true, "type": "qq", - "app_id": "YOUR_APP_ID", - "app_secret": "YOUR_APP_SECRET", - "allow_from": [] + "allow_from": [], + "settings": { + "app_id": "YOUR_APP_ID", + "app_secret": "YOUR_APP_SECRET" + } } } } @@ -173,9 +185,11 @@ If you prefer to create the bot manually: "dingtalk": { "enabled": true, "type": "dingtalk", - "client_id": "YOUR_CLIENT_ID", - "client_secret": "YOUR_CLIENT_SECRET", - "allow_from": [] + "allow_from": [], + "settings": { + "client_id": "YOUR_CLIENT_ID", + "client_secret": "YOUR_CLIENT_SECRET" + } } } } @@ -217,12 +231,14 @@ This command shows a QR code, waits for approval in WeCom, and writes `bot_id` + "wecom": { "enabled": true, "type": "wecom", - "bot_id": "YOUR_BOT_ID", - "secret": "YOUR_SECRET", - "websocket_url": "wss://openws.work.weixin.qq.com", - "send_thinking_message": true, "allow_from": [], - "reasoning_channel_id": "" + "reasoning_channel_id": "", + "settings": { + "bot_id": "YOUR_BOT_ID", + "secret": "YOUR_SECRET", + "websocket_url": "wss://openws.work.weixin.qq.com", + "send_thinking_message": true + } } } } @@ -259,9 +275,11 @@ PicoClaw connects to Feishu via WebSocket/SDK mode — no public webhook URL or "feishu": { "enabled": true, "type": "feishu", - "app_id": "cli_xxx", - "app_secret": "YOUR_APP_SECRET", - "allow_from": [] + "allow_from": [], + "settings": { + "app_id": "cli_xxx", + "app_secret": "YOUR_APP_SECRET" + } } } } @@ -299,9 +317,11 @@ Install and run a OneBot v11 compatible QQ bot framework. Enable its WebSocket s "onebot": { "enabled": true, "type": "onebot", - "ws_url": "ws://127.0.0.1:8080", - "access_token": "", - "allow_from": [] + "allow_from": [], + "settings": { + "ws_url": "ws://127.0.0.1:8080", + "access_token": "" + } } } } diff --git a/docs/guides/chat-apps.ms.md b/docs/guides/chat-apps.ms.md index b58fd980..8a8b2830 100644 --- a/docs/guides/chat-apps.ms.md +++ b/docs/guides/chat-apps.ms.md @@ -1,316 +1,5 @@ -# 💬 Konfigurasi Aplikasi Sembang +# Chat channels in this fork -> Kembali ke [README](../../README.md) +Supported channels are Weixin, WeCom, Feishu, DingTalk, QQ, OneBot, Telegram, and MQTT. The previous WeCom app/webhook variants have been replaced by the unified AI Bot WebSocket channel. -## 💬 Aplikasi Sembang - -Berbual dengan picoclaw anda melalui Telegram, QQ, DingTalk, WeCom, Feishu, OneBot, MQTT - - -| Saluran | Penyediaan | -| ---------------- | ------------------------------------------ | -| **Telegram** | Mudah (hanya token) | -| **QQ** | Mudah (AppID + AppSecret) | -| **DingTalk** | Sederhana (kelayakan aplikasi) | -| **WeCom AI Bot** | Sederhana (Token + kunci AES) | -| **Feishu** | Sederhana (App ID + Secret, mod WebSocket) | -| **OneBot** | Sederhana (QQ melalui protokol OneBot) | -| **MQTT** | Mudah (broker + agent_id) | - -
-Telegram (Disyorkan) - -**1. Cipta bot** - -* Buka Telegram, cari `@BotFather` -* Hantar `/newbot`, ikut arahan -* Salin token - -**2. Konfigurasi** - -```json -{ - "channel_list": { - "telegram": { - "enabled": true, - "type": "telegram", - "token": "YOUR_BOT_TOKEN", - "allow_from": ["YOUR_USER_ID"], - "use_markdown_v2": false, - } - } -} -``` - -> Dapatkan user ID anda daripada `@userinfobot` di Telegram. - -**3. Jalankan** - -```bash -picoclaw gateway -``` - -**4. Menu arahan Telegram (auto-register semasa startup)** - -PicoClaw kini menyimpan definisi arahan dalam satu registry bersama. Semasa startup, Telegram akan mendaftarkan arahan bot yang disokong secara automatik (contohnya `/start`, `/help`, `/show`, `/list`, `/use`, `/btw`) supaya menu arahan dan tingkah laku runtime sentiasa selari. -Pendaftaran menu arahan Telegram kekal sebagai UX penemuan setempat saluran; pelaksanaan arahan generik dikendalikan secara berpusat dalam gelung agen melalui commands executor. - -Jika pendaftaran arahan gagal (ralat sementara rangkaian/API), saluran tetap akan bermula dan PicoClaw akan mencuba semula pendaftaran di latar belakang. - -Anda juga boleh mengurus skill yang dipasang terus dari Telegram: - -- `/list skills` -- `/use ` -- `/use ` kemudian hantar permintaan sebenar dalam mesej seterusnya -- `/use clear` -- `/btw ` untuk bertanya soalan sampingan segera tanpa mengubah sejarah sesi aktif; `/btw` dikendalikan sebagai pertanyaan langsung tanpa tool dan tidak memasuki aliran pelaksanaan tool biasa - -**4. Pemformatan Lanjutan** -Anda boleh menetapkan `use_markdown_v2: true` untuk mengaktifkan pilihan pemformatan yang lebih maju. Ini membolehkan bot menggunakan keseluruhan set ciri Telegram MarkdownV2, termasuk gaya bersarang, spoiler, dan blok lebar tetap tersuai. - -
- -
-QQ - -**1. Cipta bot** - -- Pergi ke [QQ Open Platform](https://q.qq.com/#) -- Cipta aplikasi → Dapatkan **AppID** dan **AppSecret** - -**2. Konfigurasi** - -```json -{ - "channel_list": { - "qq": { - "enabled": true, - "type": "qq", - "app_id": "YOUR_APP_ID", - "app_secret": "YOUR_APP_SECRET", - "allow_from": [] - } - } -} -``` - -> Tetapkan `allow_from` kepada kosong untuk membenarkan semua pengguna, atau nyatakan nombor QQ untuk mengehadkan akses. - -**3. Jalankan** - -```bash -picoclaw gateway -``` - -
- -
-DingTalk - -**1. Cipta bot** - -* Pergi ke [Open Platform](https://open.dingtalk.com/) -* Cipta aplikasi dalaman -* Salin Client ID dan Client Secret - -**2. Konfigurasi** - -```json -{ - "channel_list": { - "dingtalk": { - "enabled": true, - "type": "dingtalk", - "client_id": "YOUR_CLIENT_ID", - "client_secret": "YOUR_CLIENT_SECRET", - "allow_from": [] - } - } -} -``` - -> Tetapkan `allow_from` kepada kosong untuk membenarkan semua pengguna, atau nyatakan user ID DingTalk untuk mengehadkan akses. - -**3. Jalankan** - -```bash -picoclaw gateway -``` -
- -
-WeCom (企业微信) - -PicoClaw menyokong tiga jenis integrasi WeCom: - -**Pilihan 1: WeCom Bot (Bot)** - Penyediaan lebih mudah, menyokong sembang kumpulan -**Pilihan 2: WeCom App (Custom App)** - Lebih banyak ciri, pemesejan proaktif, sembang peribadi sahaja -**Pilihan 3: WeCom AI Bot (AI Bot)** - AI Bot rasmi, balasan streaming, menyokong sembang kumpulan & peribadi - -Lihat [Panduan Konfigurasi WeCom](../channels/wecom/README.zh.md) untuk arahan penyediaan terperinci. - -**Quick Setup - WeCom Bot:** - -**1. Cipta bot** - -* Pergi ke WeCom Admin Console → Group Chat → Add Group Bot -* Salin webhook URL (format: `https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=xxx`) - -**2. Konfigurasi** - -```json -{ - "channel_list": { - "wecom": { - "enabled": true, - "type": "wecom", - "token": "YOUR_TOKEN", - "encoding_aes_key": "YOUR_ENCODING_AES_KEY", - "webhook_url": "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=YOUR_KEY", - "webhook_path": "/webhook/wecom", - "allow_from": [] - } - } -} -``` - - -**Quick Setup - WeCom App:** - -**1. Cipta aplikasi** - -* Pergi ke WeCom Admin Console → App Management → Create App -* Salin **AgentId** dan **Secret** -* Pergi ke halaman "My Company", salin **CorpID** - -**2. Konfigurasi penerimaan mesej** - -* Dalam butiran aplikasi, klik "Receive Message" → "Set API" -* Tetapkan URL kepada `http://your-server:18790/webhook/wecom-app` -* Jana **Token** dan **EncodingAESKey** - -**3. Konfigurasi** - -```json -{ - "channel_list": { - "wecom_app": { - "enabled": true, - "corp_id": "wwxxxxxxxxxxxxxxxx", - "corp_secret": "YOUR_CORP_SECRET", - "agent_id": 1000002, - "token": "YOUR_TOKEN", - "encoding_aes_key": "YOUR_ENCODING_AES_KEY", - "webhook_path": "/webhook/wecom-app", - "allow_from": [] - } - } -} -``` - -**4. Jalankan** - -```bash -picoclaw gateway -``` - -> **Nota**: Callback webhook WeCom diservis pada port Gateway (lalai 18790). Gunakan reverse proxy untuk HTTPS. - -**Quick Setup - WeCom AI Bot:** - -**1. Cipta AI Bot** - -* Pergi ke WeCom Admin Console → App Management → AI Bot -* Dalam tetapan AI Bot, konfigurasikan callback URL: `http://your-server:18791/webhook/wecom-aibot` -* Salin **Token** dan klik "Random Generate" untuk **EncodingAESKey** - -**2. Konfigurasi** - -```json -{ - "channel_list": { - "wecom_aibot": { - "enabled": true, - "token": "YOUR_TOKEN", - "encoding_aes_key": "YOUR_43_CHAR_ENCODING_AES_KEY", - "webhook_path": "/webhook/wecom-aibot", - "allow_from": [], - "welcome_message": "Hello! How can I help you?" - } - } -} -``` - -**3. Jalankan** - -```bash -picoclaw gateway -``` - -> **Nota**: WeCom AI Bot menggunakan protokol streaming pull — tiada isu timeout balasan. Tugasan panjang (>30 saat) akan bertukar secara automatik kepada penghantaran push `response_url`. - -
- - -
-MQTT - -Mana-mana client MQTT boleh berkomunikasi dengan PicoClaw melalui broker. Peranti atau perkhidmatan menerbitkan permintaan ke broker; PicoClaw melanggan, memproses dan menerbitkan respons kembali. - -**1. Konfigurasi** - -```json -{ - "channel_list": { - "mqtt": { - "enabled": true, - "type": "mqtt", - "settings": { - "broker": "ssl://your-broker:8883", - "agent_id": "assistant", - "topic_prefix": "/picoclaw", - "keep_alive": 60, - "qos": 0 - } - } - } -} -``` - -Nama pengguna dan kata laluan dalam `~/.picoclaw/.security.yml`: - -```yaml -channel_list: - mqtt: - settings: - username: nama_pengguna - password: kata_laluan -``` - -**Format topik** - -``` -{prefix}/{agent_id}/{client_id}/request # Client → PicoClaw -{prefix}/{agent_id}/{client_id}/response # PicoClaw → Client -``` - -`client_id` ditetapkan oleh aplikasi client anda untuk mengenal pasti peranti atau sesi. - -**2. Jalankan** - -```bash -picoclaw gateway -``` - -**3. Uji** - -```bash -mosquitto_pub -t "/picoclaw/assistant/device1/request" \ - -m '{"text": "Helo"}' - -mosquitto_sub -t "/picoclaw/assistant/device1/response" -``` - -Untuk semua pilihan konfigurasi, lihat [Dokumentasi Saluran MQTT](../channels/mqtt/README.md). - -
+Use the maintained [channel guide](chat-apps.md) or [中文说明](chat-apps.zh.md), and the current [configuration example](../../config/config.example.json). Channel-specific values belong under `channel_list..settings`. diff --git a/docs/guides/chat-apps.pt-br.md b/docs/guides/chat-apps.pt-br.md index 390fa65a..8a8b2830 100644 --- a/docs/guides/chat-apps.pt-br.md +++ b/docs/guides/chat-apps.pt-br.md @@ -1,446 +1,5 @@ -# 💬 Configuração de Aplicativos de Chat +# Chat channels in this fork -> Voltar ao [README](../../README.md) +Supported channels are Weixin, WeCom, Feishu, DingTalk, QQ, OneBot, Telegram, and MQTT. The previous WeCom app/webhook variants have been replaced by the unified AI Bot WebSocket channel. -## 💬 Aplicativos de Chat - -Converse com seu picoclaw através do Telegram, QQ, DingTalk, WeCom, Feishu, OneBot, MQTT - - -| Canal | Dificuldade | Descrição | Documentação | -| -------------------- | ------------------ | ----------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------- | -| **Telegram** | ⭐ Fácil | Recomendado, voz para texto, long polling (sem IP público) | [Documentação](../channels/telegram/README.pt-br.md) | -| **Weixin** | ⭐ Fácil | Scan QR nativo (API Tencent iLink) | [Documentação](#weixin) | -| **QQ** | ⭐⭐ Médio | API bot oficial, comunidade chinesa | [Documentação](../channels/qq/README.pt-br.md) | -| **DingTalk** | ⭐⭐ Médio | Modo Stream (sem IP público), empresarial | [Documentação](../channels/dingtalk/README.pt-br.md) | -| **WeCom (企业微信)** | ⭐⭐⭐ Avançado | Bot de grupo (Webhook), app personalizado (API), AI Bot | [Guia](../channels/wecom/README.pt-br.md) | -| **Feishu (飞书)** | ⭐⭐⭐ Avançado | Colaboração empresarial, rico em recursos | [Documentação](../channels/feishu/README.pt-br.md) | -| **OneBot** | ⭐⭐ Médio | Compatível com NapCat/Go-CQHTTP, ecossistema comunitário | [Documentação](../channels/onebot/README.pt-br.md) | -| **MQTT** | ⭐ Fácil | Qualquer cliente MQTT via broker pub/sub | [Documentação](../channels/mqtt/README.pt-br.md) | - - -
-Telegram (Recomendado) - -**1. Criar um bot** - -* Abra o Telegram, pesquise `@BotFather` -* Envie `/newbot`, siga as instruções -* Copie o token - -**2. Configurar** - -```json -{ - "channel_list": { - "telegram": { - "enabled": true, - "type": "telegram", - "token": "YOUR_BOT_TOKEN", - "allow_from": ["YOUR_USER_ID"] - } - } -} -``` - -> Obtenha seu ID de usuário com `@userinfobot` no Telegram. - -**3. Executar** - -```bash -picoclaw gateway -``` - -**4. Menu de comandos do Telegram (registrado automaticamente na inicialização)** - -O PicoClaw agora mantém definições de comandos em um registro compartilhado. Na inicialização, o Telegram registrará automaticamente os comandos de bot suportados (por exemplo `/start`, `/help`, `/show`, `/list`, `/use`, `/btw`) para que o menu de comandos e o comportamento em tempo de execução permaneçam sincronizados. -O registro do menu de comandos do Telegram permanece como descoberta UX local do canal; a execução genérica de comandos é tratada centralmente no loop do agente via commands executor. - -Se o registro de comandos falhar (erros transitórios de rede/API), o canal ainda inicia e o PicoClaw tenta novamente o registro em segundo plano. - -Voce tambem pode gerenciar skills instaladas diretamente pelo Telegram: - -- `/list skills` -- `/use ` -- `/use ` e depois enviar a solicitacao real na proxima mensagem -- `/use clear` -- `/btw ` para fazer uma pergunta lateral imediata sem alterar o historico ativo da sessao; `/btw` e tratado como uma consulta direta sem ferramentas e nao entra no fluxo normal de execucao de ferramentas - -
- - -
-Weixin (WeChat Pessoal) - -O PicoClaw suporta conexão com sua conta pessoal do WeChat usando a API oficial Tencent iLink. - -**1. Login** - -Execute o fluxo de login interativo por QR code: -```bash -picoclaw auth weixin -``` -Escaneie o QR code exibido com seu aplicativo WeChat mobile. Após o login bem-sucedido, o token é salvo na sua configuração. - -**2. Configurar** - -(Opcional) Adicione seu ID de usuário WeChat em `allow_from` para restringir quem pode enviar mensagens ao bot: -```json -{ - "channel_list": { - "weixin": { - "enabled": true, - "type": "weixin", - "token": "YOUR_TOKEN", - "allow_from": ["YOUR_USER_ID"] - } - } -} -``` - -**3. Executar** -```bash -picoclaw gateway -``` - -
- - -
-QQ - -**Configuração rápida (recomendada)** - -A QQ Open Platform oferece uma página de configuração com um clique para bots compatíveis com OpenClaw: - -1. Abra o [QQ Bot Quick Start](https://q.qq.com/qqbot/openclaw/index.html) e escaneie o QR code para fazer login -2. Um bot é criado automaticamente — copie o **App ID** e o **App Secret** -3. Configure o PicoClaw: - -```json -{ - "channel_list": { - "qq": { - "enabled": true, - "type": "qq", - "app_id": "YOUR_APP_ID", - "app_secret": "YOUR_APP_SECRET", - "allow_from": [] - } - } -} -``` - -4. Execute `picoclaw gateway` e abra o QQ para conversar com seu bot - -> O App Secret é exibido apenas uma vez. Salve-o imediatamente — visualizá-lo novamente forçará uma redefinição. -> -> Bots criados pela página de configuração rápida são inicialmente apenas para o criador e não suportam chats de grupo. Para habilitar o acesso em grupo, configure o modo sandbox na [QQ Open Platform](https://q.qq.com/). - -**Configuração manual** - -Se preferir criar o bot manualmente: - -* Faça login na [QQ Open Platform](https://q.qq.com/) para se registrar como desenvolvedor -* Crie um bot QQ — personalize seu avatar e nome -* Copie o **App ID** e o **App Secret** nas configurações do bot -* Configure conforme mostrado acima e execute `picoclaw gateway` - -
- - -
-DingTalk - -**1. Criar um bot** - -* Acesse a [Open Platform](https://open.dingtalk.com/) -* Crie um aplicativo interno -* Copie o Client ID e o Client Secret - -**2. Configurar** - -```json -{ - "channel_list": { - "dingtalk": { - "enabled": true, - "type": "dingtalk", - "client_id": "YOUR_CLIENT_ID", - "client_secret": "YOUR_CLIENT_SECRET", - "allow_from": [] - } - } -} -``` - -> Defina `allow_from` como vazio para permitir todos os usuários, ou especifique IDs de usuário DingTalk para restringir o acesso. - -**3. Executar** - -```bash -picoclaw gateway -``` - -
- - -
-WeCom (企业微信) - -O PicoClaw suporta três tipos de integração WeCom: - -**Opção 1: WeCom Bot (Bot)** - Configuração mais fácil, suporta chats de grupo -**Opção 2: WeCom App (App Personalizado)** - Mais recursos, mensagens proativas, apenas chat privado -**Opção 3: WeCom AI Bot (AI Bot)** - AI Bot oficial, respostas em streaming, suporta chat de grupo e privado - -Veja o [Guia de Configuração do WeCom](../channels/wecom/README.pt-br.md) para instruções detalhadas de configuração. - -**Configuração Rápida - WeCom Bot:** - -**1. Criar um bot** - -* Acesse o Console de Administração WeCom → Chat de Grupo → Adicionar Bot de Grupo -* Copie a URL do webhook (formato: `https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=xxx`) - -**2. Configurar** - -```json -{ - "channel_list": { - "wecom": { - "enabled": true, - "type": "wecom", - "token": "YOUR_TOKEN", - "encoding_aes_key": "YOUR_ENCODING_AES_KEY", - "webhook_url": "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=YOUR_KEY", - "webhook_path": "/webhook/wecom", - "allow_from": [] - } - } -} -``` - - -**Configuração Rápida - WeCom App:** - -**1. Criar um aplicativo** - -* Acesse o Console de Administração WeCom → Gerenciamento de Apps → Criar App -* Copie o **AgentId** e o **Secret** -* Acesse a página "Minha Empresa", copie o **CorpID** - -**2. Configurar recebimento de mensagens** - -* Nos detalhes do App, clique em "Receber Mensagem" → "Configurar API" -* Defina a URL como `http://your-server:18790/webhook/wecom-app` -* Gere o **Token** e o **EncodingAESKey** - -**3. Configurar** - -```json -{ - "channel_list": { - "wecom_app": { - "enabled": true, - "corp_id": "wwxxxxxxxxxxxxxxxx", - "corp_secret": "YOUR_CORP_SECRET", - "agent_id": 1000002, - "token": "YOUR_TOKEN", - "encoding_aes_key": "YOUR_ENCODING_AES_KEY", - "webhook_path": "/webhook/wecom-app", - "allow_from": [] - } - } -} -``` - -**4. Executar** - -```bash -picoclaw gateway -``` - -> **Nota**: Os callbacks de webhook do WeCom são servidos na porta do Gateway (padrão 18790). Use um proxy reverso para HTTPS. - -**Configuração Rápida - WeCom AI Bot:** - -**1. Criar um AI Bot** - -* Acesse o Console de Administração WeCom → Gerenciamento de Apps → AI Bot -* Nas configurações do AI Bot, configure a URL de callback: `http://your-server:18790/webhook/wecom-aibot` -* Copie o **Token** e clique em "Gerar Aleatoriamente" para o **EncodingAESKey** - -**2. Configurar** - -```json -{ - "channel_list": { - "wecom_aibot": { - "enabled": true, - "token": "YOUR_TOKEN", - "encoding_aes_key": "YOUR_43_CHAR_ENCODING_AES_KEY", - "webhook_path": "/webhook/wecom-aibot", - "allow_from": [], - "welcome_message": "Hello! How can I help you?" - } - } -} -``` - -**3. Executar** - -```bash -picoclaw gateway -``` - -> **Nota**: O WeCom AI Bot usa protocolo de streaming pull — sem preocupações com timeout de resposta. Tarefas longas (>30 segundos) mudam automaticamente para entrega via `response_url` push. - -
- - -
-Feishu (Lark) - -O PicoClaw se conecta ao Feishu via modo WebSocket/SDK — não é necessário URL de webhook público nem servidor de callback. - -**1. Criar um aplicativo** - -* Acesse a [Feishu Open Platform](https://open.feishu.cn/) e crie um aplicativo -* Nas configurações do aplicativo, habilite a capacidade **Bot** -* Crie uma versão e publique o aplicativo (o aplicativo deve ser publicado para funcionar) -* Copie o **App ID** (começa com `cli_`) e o **App Secret** - -**2. Configurar** - -```json -{ - "channel_list": { - "feishu": { - "enabled": true, - "type": "feishu", - "app_id": "cli_xxx", - "app_secret": "YOUR_APP_SECRET", - "allow_from": [] - } - } -} -``` - -Opcional: `encrypt_key` e `verification_token` para criptografia de eventos (recomendado para produção). - -**3. Executar e conversar** - -```bash -picoclaw gateway -``` - -Abra o Feishu, pesquise o nome do seu bot e comece a conversar. Você também pode adicionar o bot a um grupo — use `group_trigger.mention_only: true` para responder apenas quando @mencionado. - -Para opções completas, veja o [Guia de Configuração do Canal Feishu](../channels/feishu/README.pt-br.md). - -
- - -
-OneBot (QQ via protocolo OneBot) - -OneBot é um protocolo aberto para bots QQ. O PicoClaw se conecta a qualquer implementação compatível com OneBot v11 (ex.: [Lagrange](https://github.com/LagrangeDev/Lagrange.Core), [NapCat](https://github.com/NapNeko/NapCatQQ)) via WebSocket. - -**1. Configurar uma implementação OneBot** - -Instale e execute um framework de bot QQ compatível com OneBot v11. Habilite seu servidor WebSocket. - -**2. Configurar** - -```json -{ - "channel_list": { - "onebot": { - "enabled": true, - "type": "onebot", - "ws_url": "ws://127.0.0.1:8080", - "access_token": "", - "allow_from": [] - } - } -} -``` - -| Campo | Descrição | -|-------|-----------| -| `ws_url` | URL WebSocket da implementação OneBot | -| `access_token` | Token de acesso para autenticação (se configurado no OneBot) | -| `reconnect_interval` | Intervalo de reconexão em segundos (padrão: 5) | - -**3. Executar** - -```bash -picoclaw gateway -``` - -
- - -
-MQTT - -Qualquer cliente MQTT pode se comunicar com o PicoClaw via broker. Dispositivos ou serviços publicam requisições para o broker; o PicoClaw assina, processa e publica as respostas de volta. - -**1. Configurar** - -```json -{ - "channel_list": { - "mqtt": { - "enabled": true, - "type": "mqtt", - "settings": { - "broker": "ssl://seu-broker:8883", - "agent_id": "assistant", - "topic_prefix": "/picoclaw", - "keep_alive": 60, - "qos": 0 - } - } - } -} -``` - -Nome de usuário e senha em `~/.picoclaw/.security.yml`: - -```yaml -channel_list: - mqtt: - settings: - username: seu_usuario - password: sua_senha -``` - -**Formato dos tópicos** - -``` -{prefix}/{agent_id}/{client_id}/request # Cliente → PicoClaw -{prefix}/{agent_id}/{client_id}/response # PicoClaw → Cliente -``` - -O `client_id` é definido pela sua aplicação cliente para identificar dispositivos ou sessões. - -**2. Iniciar** - -```bash -picoclaw gateway -``` - -**3. Testar** - -```bash -mosquitto_pub -t "/picoclaw/assistant/device1/request" \ - -m '{"text": "Olá"}' - -mosquitto_sub -t "/picoclaw/assistant/device1/response" -``` - -Para todas as opções de configuração, veja a [Documentação do Canal MQTT](../channels/mqtt/README.pt-br.md). - -
+Use the maintained [channel guide](chat-apps.md) or [中文说明](chat-apps.zh.md), and the current [configuration example](../../config/config.example.json). Channel-specific values belong under `channel_list..settings`. diff --git a/docs/guides/chat-apps.vi.md b/docs/guides/chat-apps.vi.md index adfb226d..8a8b2830 100644 --- a/docs/guides/chat-apps.vi.md +++ b/docs/guides/chat-apps.vi.md @@ -1,447 +1,5 @@ -# 💬 Cấu Hình Ứng Dụng Chat +# Chat channels in this fork -> Quay lại [README](../../README.md) +Supported channels are Weixin, WeCom, Feishu, DingTalk, QQ, OneBot, Telegram, and MQTT. The previous WeCom app/webhook variants have been replaced by the unified AI Bot WebSocket channel. -## 💬 Ứng Dụng Chat - -Trò chuyện với picoclaw của bạn qua Telegram, QQ, DingTalk, WeCom, Feishu, OneBot, MQTT - - -| Kênh | Độ khó | Mô tả | Tài liệu | -| -------------------- | ------------------ | ----------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------- | -| **Telegram** | ⭐ Dễ | Khuyến nghị, chuyển giọng nói thành văn bản, long polling (không cần IP công khai) | [Tài liệu](../channels/telegram/README.vi.md) | -| **Weixin** | ⭐ Dễ | Quét QR gốc (API Tencent iLink) | [Tài liệu](#weixin) | -| **QQ** | ⭐⭐ Trung bình | API bot chính thức, cộng đồng Trung Quốc | [Tài liệu](../channels/qq/README.vi.md) | -| **DingTalk** | ⭐⭐ Trung bình | Chế độ Stream (không cần IP công khai), doanh nghiệp | [Tài liệu](../channels/dingtalk/README.vi.md) | -| **WeCom (企业微信)** | ⭐⭐⭐ Nâng cao | Bot nhóm (Webhook), ứng dụng tùy chỉnh (API), AI Bot | [Hướng dẫn](../channels/wecom/README.vi.md) | -| **Feishu (飞书)** | ⭐⭐⭐ Nâng cao | Cộng tác doanh nghiệp, nhiều tính năng | [Tài liệu](../channels/feishu/README.vi.md) | -| **OneBot** | ⭐⭐ Trung bình | Tương thích NapCat/Go-CQHTTP, hệ sinh thái cộng đồng | [Tài liệu](../channels/onebot/README.vi.md) | -| **MQTT** | ⭐ Dễ | Bất kỳ client MQTT nào qua broker pub/sub | [Tài liệu](../channels/mqtt/README.vi.md) | - - -
-Telegram (Khuyến nghị) - -**1. Tạo bot** - -* Mở Telegram, tìm `@BotFather` -* Gửi `/newbot`, làm theo hướng dẫn -* Sao chép token - -**2. Cấu hình** - -```json -{ - "channel_list": { - "telegram": { - "enabled": true, - "type": "telegram", - "token": "YOUR_BOT_TOKEN", - "allow_from": ["YOUR_USER_ID"] - } - } -} -``` - -> Lấy user ID của bạn từ `@userinfobot` trên Telegram. - -**3. Chạy** - -```bash -picoclaw gateway -``` - -**4. Menu lệnh Telegram (tự động đăng ký khi khởi động)** - -PicoClaw hiện lưu trữ định nghĩa lệnh trong một registry chung. Khi khởi động, Telegram sẽ tự động đăng ký các lệnh bot được hỗ trợ (ví dụ `/start`, `/help`, `/show`, `/list`, `/use`, `/btw`) để menu lệnh và hành vi runtime luôn đồng bộ. -Đăng ký menu lệnh Telegram vẫn là UX khám phá cục bộ của kênh; thực thi lệnh chung được xử lý tập trung trong vòng lặp agent qua commands executor. - -Nếu đăng ký lệnh thất bại (lỗi tạm thời mạng/API), kênh vẫn khởi động và PicoClaw thử lại đăng ký trong nền. - -Ban cung co the quan ly skill da cai dat truc tiep tu Telegram: - -- `/list skills` -- `/use ` -- `/use ` roi gui yeu cau that o tin nhan tiep theo -- `/use clear` -- `/btw ` de hoi them mot cau ngoai le ngay lap tuc ma khong thay doi lich su phien dang hoat dong; `/btw` duoc xu ly nhu mot truy van truc tiep khong dung cong cu va khong di vao luong thuc thi cong cu thong thuong - -
- - -
-Weixin (WeChat Cá nhân) - -PicoClaw hỗ trợ kết nối với tài khoản WeChat cá nhân của bạn thông qua API chính thức Tencent iLink. - -**1. Đăng nhập** - -Chạy luồng đăng nhập QR tương tác: -```bash -picoclaw auth weixin -``` -Quét mã QR được in ra bằng ứng dụng WeChat trên điện thoại. Sau khi đăng nhập thành công, token sẽ được lưu vào cấu hình. - -**2. Cấu hình** - -(Tùy chọn) Thêm ID người dùng WeChat vào `allow_from` để giới hạn ai có thể nhắn tin với bot: -```json -{ - "channel_list": { - "weixin": { - "enabled": true, - "type": "weixin", - "token": "YOUR_TOKEN", - "allow_from": ["YOUR_USER_ID"] - } - } -} -``` - -**3. Chạy** -```bash -picoclaw gateway -``` - -
- - -
-QQ - -**Thiết lập nhanh (khuyến nghị)** - -QQ Open Platform cung cấp trang thiết lập một chạm cho bot tương thích OpenClaw: - -1. Mở [QQ Bot Quick Start](https://q.qq.com/qqbot/openclaw/index.html) và quét mã QR để đăng nhập -2. Bot được tạo tự động — sao chép **App ID** và **App Secret** -3. Cấu hình PicoClaw: - -```json -{ - "channel_list": { - "qq": { - "enabled": true, - "type": "qq", - "app_id": "YOUR_APP_ID", - "app_secret": "YOUR_APP_SECRET", - "allow_from": [] - } - } -} -``` - -4. Chạy `picoclaw gateway` và mở QQ để trò chuyện với bot của bạn - -> App Secret chỉ hiển thị một lần. Lưu ngay lập tức — xem lại sẽ buộc phải đặt lại. -> -> Bot được tạo qua trang thiết lập nhanh ban đầu chỉ dành cho người tạo và không hỗ trợ chat nhóm. Để bật quyền truy cập nhóm, cấu hình chế độ sandbox trên [QQ Open Platform](https://q.qq.com/). - -**Thiết lập thủ công** - -Nếu bạn muốn tạo bot thủ công: - -* Đăng nhập tại [QQ Open Platform](https://q.qq.com/) để đăng ký làm nhà phát triển -* Tạo bot QQ — tùy chỉnh avatar và tên -* Sao chép **App ID** và **App Secret** từ cài đặt bot -* Cấu hình như trên và chạy `picoclaw gateway` - -
- - -
-DingTalk - -**1. Tạo bot** - -* Truy cập [Open Platform](https://open.dingtalk.com/) -* Tạo ứng dụng nội bộ -* Sao chép Client ID và Client Secret - -**2. Cấu hình** - -```json -{ - "channel_list": { - "dingtalk": { - "enabled": true, - "type": "dingtalk", - "client_id": "YOUR_CLIENT_ID", - "client_secret": "YOUR_CLIENT_SECRET", - "allow_from": [] - } - } -} -``` - -> Đặt `allow_from` trống để cho phép tất cả người dùng, hoặc chỉ định DingTalk user ID để giới hạn truy cập. - -**3. Chạy** - -```bash -picoclaw gateway -``` - -
- - -
-WeCom (企业微信) - -PicoClaw hỗ trợ ba loại tích hợp WeCom: - -**Tùy chọn 1: WeCom Bot (Bot)** - Thiết lập dễ hơn, hỗ trợ chat nhóm -**Tùy chọn 2: WeCom App (App Tùy chỉnh)** - Nhiều tính năng hơn, nhắn tin chủ động, chỉ chat riêng -**Tùy chọn 3: WeCom AI Bot (AI Bot)** - AI Bot chính thức, phản hồi streaming, hỗ trợ chat nhóm & riêng - -Xem [Hướng Dẫn Cấu Hình WeCom](../channels/wecom/README.vi.md) để biết hướng dẫn thiết lập chi tiết. - -**Thiết Lập Nhanh - WeCom Bot:** - -**1. Tạo bot** - -* Truy cập Console Quản Trị WeCom → Chat Nhóm → Thêm Bot Nhóm -* Sao chép URL webhook (định dạng: `https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=xxx`) - -**2. Cấu hình** - -```json -{ - "channel_list": { - "wecom": { - "enabled": true, - "type": "wecom", - "token": "YOUR_TOKEN", - "encoding_aes_key": "YOUR_ENCODING_AES_KEY", - "webhook_url": "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=YOUR_KEY", - "webhook_path": "/webhook/wecom", - "allow_from": [] - } - } -} -``` - - -**Thiết Lập Nhanh - WeCom App:** - -**1. Tạo ứng dụng** - -* Truy cập Console Quản Trị WeCom → Quản Lý App → Tạo App -* Sao chép **AgentId** và **Secret** -* Truy cập trang "Công Ty Của Tôi", sao chép **CorpID** - -**2. Cấu hình nhận tin nhắn** - -* Trong chi tiết App, nhấp "Nhận Tin Nhắn" → "Cấu Hình API" -* Đặt URL thành `http://your-server:18790/webhook/wecom-app` -* Tạo **Token** và **EncodingAESKey** - -**3. Cấu hình** - -```json -{ - "channel_list": { - "wecom_app": { - "enabled": true, - "corp_id": "wwxxxxxxxxxxxxxxxx", - "corp_secret": "YOUR_CORP_SECRET", - "agent_id": 1000002, - "token": "YOUR_TOKEN", - "encoding_aes_key": "YOUR_ENCODING_AES_KEY", - "webhook_path": "/webhook/wecom-app", - "allow_from": [] - } - } -} -``` - -**4. Chạy** - -```bash -picoclaw gateway -``` - -> **Lưu ý**: Callback webhook WeCom được phục vụ trên port Gateway (mặc định 18790). Sử dụng reverse proxy cho HTTPS. - -**Thiết Lập Nhanh - WeCom AI Bot:** - -**1. Tạo AI Bot** - -* Truy cập Console Quản Trị WeCom → Quản Lý App → AI Bot -* Trong cài đặt AI Bot, cấu hình callback URL: `http://your-server:18790/webhook/wecom-aibot` -* Sao chép **Token** và nhấp "Tạo Ngẫu Nhiên" cho **EncodingAESKey** - -**2. Cấu hình** - -```json -{ - "channel_list": { - "wecom_aibot": { - "enabled": true, - "token": "YOUR_TOKEN", - "encoding_aes_key": "YOUR_43_CHAR_ENCODING_AES_KEY", - "webhook_path": "/webhook/wecom-aibot", - "allow_from": [], - "welcome_message": "Hello! How can I help you?", - "processing_message": "⏳ Processing, please wait. The results will be sent shortly." - } - } -} -``` - -**3. Chạy** - -```bash -picoclaw gateway -``` - -> **Lưu ý**: WeCom AI Bot sử dụng giao thức streaming pull — không lo timeout phản hồi. Tác vụ dài (>30 giây) tự động chuyển sang gửi qua `response_url` push. - -
- - -
-Feishu (Lark) - -PicoClaw kết nối với Feishu qua chế độ WebSocket/SDK — không cần URL webhook công khai hay máy chủ callback. - -**1. Tạo ứng dụng** - -* Truy cập [Feishu Open Platform](https://open.feishu.cn/) và tạo ứng dụng -* Trong cài đặt ứng dụng, bật khả năng **Bot** -* Tạo phiên bản và xuất bản ứng dụng (ứng dụng phải được xuất bản mới có hiệu lực) -* Sao chép **App ID** (bắt đầu bằng `cli_`) và **App Secret** - -**2. Cấu hình** - -```json -{ - "channel_list": { - "feishu": { - "enabled": true, - "type": "feishu", - "app_id": "cli_xxx", - "app_secret": "YOUR_APP_SECRET", - "allow_from": [] - } - } -} -``` - -Tùy chọn: `encrypt_key` và `verification_token` để mã hóa sự kiện (khuyến nghị cho môi trường production). - -**3. Chạy và trò chuyện** - -```bash -picoclaw gateway -``` - -Mở Feishu, tìm tên bot của bạn và bắt đầu trò chuyện. Bạn cũng có thể thêm bot vào nhóm — sử dụng `group_trigger.mention_only: true` để chỉ phản hồi khi được @mention. - -Để xem đầy đủ các tùy chọn, xem [Hướng Dẫn Cấu Hình Kênh Feishu](../channels/feishu/README.vi.md). - -
- - -
-OneBot (QQ qua giao thức OneBot) - -OneBot là giao thức mở cho bot QQ. PicoClaw kết nối với bất kỳ triển khai tương thích OneBot v11 nào (ví dụ: [Lagrange](https://github.com/LagrangeDev/Lagrange.Core), [NapCat](https://github.com/NapNeko/NapCatQQ)) qua WebSocket. - -**1. Thiết lập triển khai OneBot** - -Cài đặt và chạy framework bot QQ tương thích OneBot v11. Bật máy chủ WebSocket của nó. - -**2. Cấu hình** - -```json -{ - "channel_list": { - "onebot": { - "enabled": true, - "type": "onebot", - "ws_url": "ws://127.0.0.1:8080", - "access_token": "", - "allow_from": [] - } - } -} -``` - -| Trường | Mô tả | -|--------|-------| -| `ws_url` | URL WebSocket của triển khai OneBot | -| `access_token` | Token truy cập để xác thực (nếu đã cấu hình trong OneBot) | -| `reconnect_interval` | Khoảng thời gian kết nối lại tính bằng giây (mặc định: 5) | - -**3. Chạy** - -```bash -picoclaw gateway -``` - -
- - -
-MQTT - -Bất kỳ client MQTT nào đều có thể giao tiếp với PicoClaw qua broker. Thiết bị hoặc dịch vụ publish yêu cầu lên broker; PicoClaw subscribe, xử lý và publish phản hồi trở lại. - -**1. Cấu hình** - -```json -{ - "channel_list": { - "mqtt": { - "enabled": true, - "type": "mqtt", - "settings": { - "broker": "ssl://your-broker:8883", - "agent_id": "assistant", - "topic_prefix": "/picoclaw", - "keep_alive": 60, - "qos": 0 - } - } - } -} -``` - -Tên người dùng và mật khẩu trong `~/.picoclaw/.security.yml`: - -```yaml -channel_list: - mqtt: - settings: - username: ten_nguoi_dung - password: mat_khau -``` - -**Định dạng topic** - -``` -{prefix}/{agent_id}/{client_id}/request # Client → PicoClaw -{prefix}/{agent_id}/{client_id}/response # PicoClaw → Client -``` - -`client_id` do ứng dụng client đặt để phân biệt thiết bị hoặc phiên. - -**2. Khởi động** - -```bash -picoclaw gateway -``` - -**3. Kiểm tra** - -```bash -mosquitto_pub -t "/picoclaw/assistant/device1/request" \ - -m '{"text": "Xin chào"}' - -mosquitto_sub -t "/picoclaw/assistant/device1/response" -``` - -Xem đầy đủ tùy chọn cấu hình tại [Tài liệu Kênh MQTT](../channels/mqtt/README.vi.md). - -
+Use the maintained [channel guide](chat-apps.md) or [中文说明](chat-apps.zh.md), and the current [configuration example](../../config/config.example.json). Channel-specific values belong under `channel_list..settings`. diff --git a/docs/guides/chat-apps.zh.md b/docs/guides/chat-apps.zh.md index 709e7bbd..48195be5 100644 --- a/docs/guides/chat-apps.zh.md +++ b/docs/guides/chat-apps.zh.md @@ -35,14 +35,20 @@ PicoClaw 支持多种聊天平台,使您的 Agent 能够连接到任何地方 **2. 配置** +> 配置结构:`enabled`、`type`、`allow_from` 等公共字段位于渠道条目,Token、App ID 等专有字段位于 `settings`。`.security.yml` 使用 `channel_list.<名称>.settings` 保存渠道密钥;其中的同名值会覆盖主配置。 + ```json { "channel_list": { "telegram": { "enabled": true, "type": "telegram", - "token": "YOUR_BOT_TOKEN", - "allow_from": ["YOUR_USER_ID"] + "allow_from": [ + "YOUR_USER_ID" + ], + "settings": { + "token": "YOUR_BOT_TOKEN" + } } } } @@ -96,8 +102,12 @@ picoclaw auth weixin "weixin": { "enabled": true, "type": "weixin", - "token": "YOUR_TOKEN", - "allow_from": ["YOUR_USER_ID"] + "allow_from": [ + "YOUR_USER_ID" + ], + "settings": { + "token": "YOUR_TOKEN" + } } } } @@ -128,9 +138,11 @@ QQ 开放平台提供了一键创建 OpenClaw 兼容机器人的页面: "qq": { "enabled": true, "type": "qq", - "app_id": "YOUR_APP_ID", - "app_secret": "YOUR_APP_SECRET", - "allow_from": [] + "allow_from": [], + "settings": { + "app_id": "YOUR_APP_ID", + "app_secret": "YOUR_APP_SECRET" + } } } } @@ -171,9 +183,11 @@ QQ 开放平台提供了一键创建 OpenClaw 兼容机器人的页面: "dingtalk": { "enabled": true, "type": "dingtalk", - "client_id": "YOUR_CLIENT_ID", - "client_secret": "YOUR_CLIENT_SECRET", - "allow_from": [] + "allow_from": [], + "settings": { + "client_id": "YOUR_CLIENT_ID", + "client_secret": "YOUR_CLIENT_SECRET" + } } } } @@ -210,9 +224,11 @@ PicoClaw 通过 WebSocket/SDK 模式连接飞书 — 无需公网 Webhook URL "feishu": { "enabled": true, "type": "feishu", - "app_id": "cli_xxx", - "app_secret": "YOUR_APP_SECRET", - "allow_from": [] + "allow_from": [], + "settings": { + "app_id": "cli_xxx", + "app_secret": "YOUR_APP_SECRET" + } } } } @@ -249,7 +265,7 @@ PicoClaw 现在将企业微信统一为一个基于 WebSocket 的 AI Bot 渠道 picoclaw auth wecom ``` -该命令会显示二维码,等待你在企业微信里确认,然后把 `bot_id` 和 `secret` 写入 `channels.wecom`。 +该命令会显示二维码,等待你在企业微信里确认,然后把 `bot_id` 和 `secret` 写入 `channel_list.wecom.settings`。 **2. 如需手动配置** @@ -259,12 +275,14 @@ picoclaw auth wecom "wecom": { "enabled": true, "type": "wecom", - "bot_id": "YOUR_BOT_ID", - "secret": "YOUR_SECRET", - "websocket_url": "wss://openws.work.weixin.qq.com", - "send_thinking_message": true, "allow_from": [], - "reasoning_channel_id": "" + "reasoning_channel_id": "", + "settings": { + "bot_id": "YOUR_BOT_ID", + "secret": "YOUR_SECRET", + "websocket_url": "wss://openws.work.weixin.qq.com", + "send_thinking_message": true + } } } } @@ -298,9 +316,11 @@ OneBot 是 QQ 机器人的开放协议。PicoClaw 通过 WebSocket 连接任何 "onebot": { "enabled": true, "type": "onebot", - "ws_url": "ws://127.0.0.1:8080", - "access_token": "", - "allow_from": [] + "allow_from": [], + "settings": { + "ws_url": "ws://127.0.0.1:8080", + "access_token": "" + } } } } diff --git a/docs/guides/configuration.fr.md b/docs/guides/configuration.fr.md index bda61e6b..aea9adad 100644 --- a/docs/guides/configuration.fr.md +++ b/docs/guides/configuration.fr.md @@ -1,5 +1,7 @@ # ⚙️ Guide de Configuration +> Fork configuration: `PICOCLAW_HOME` also changes the default config path; `PICOCLAW_CONFIG` overrides that path. For current model protocols and channel settings, use the [README](../../README.md) and [configuration example](../../config/config.example.json). + > Retour au [README](../../README.md) ## ⚙️ Configuration @@ -23,7 +25,7 @@ Vous pouvez remplacer les chemins par défaut à l'aide de variables d'environne PICOCLAW_CONFIG=/etc/picoclaw/production.json picoclaw gateway # Run picoclaw with all its data stored in /opt/picoclaw -# Config will be loaded from the default ~/.picoclaw/config.json +# Config: /opt/picoclaw/config.json (PICOCLAW_HOME=/opt/picoclaw) # Workspace will be created at /opt/picoclaw/workspace PICOCLAW_HOME=/opt/picoclaw picoclaw agent @@ -352,119 +354,9 @@ Répond HEARTBEAT_OK Utilisateur reçoit le résultat * `PICOCLAW_HEARTBEAT_ENABLED=false` pour désactiver * `PICOCLAW_HEARTBEAT_INTERVAL=60` pour changer l'intervalle -### Providers +### Model providers -> [!NOTE] -> Groq fournit une transcription vocale gratuite via Whisper. Si configuré, les messages audio de n'importe quel canal seront automatiquement transcrits au niveau de l'agent. - -| Provider | Usage | Obtenir une clé API | -| ------------ | --------------------------------------- | ------------------------------------------------------------ | -| `gemini` | LLM (Gemini direct) | [aistudio.google.com](https://aistudio.google.com) | -| `zhipu` | LLM (Zhipu direct) | [bigmodel.cn](https://bigmodel.cn) | -| `volcengine` | LLM (Volcengine direct) | [volcengine.com](https://www.volcengine.com/activity/codingplan?utm_campaign=PicoClaw&utm_content=PicoClaw&utm_medium=devrel&utm_source=OWO&utm_term=PicoClaw) | -| `openrouter` | LLM (recommandé, accès à tous modèles) | [openrouter.ai](https://openrouter.ai) | -| `anthropic` | LLM (Claude direct) | [console.anthropic.com](https://console.anthropic.com) | -| `openai` | LLM (GPT direct) | [platform.openai.com](https://platform.openai.com) | -| `deepseek` | LLM (DeepSeek direct) | [platform.deepseek.com](https://platform.deepseek.com) | -| `qwen` | LLM (Qwen direct) | [dashscope.console.aliyun.com](https://dashscope.console.aliyun.com) | -| `groq` | LLM + **Transcription vocale** (Whisper)| [console.groq.com](https://console.groq.com) | -| `cerebras` | LLM (Cerebras direct) | [cerebras.ai](https://cerebras.ai) | -| `vivgrid` | LLM (Vivgrid direct) | [vivgrid.com](https://vivgrid.com) | - -### Configuration des Modèles (model_list) - -> **Nouveauté :** PicoClaw utilise désormais une approche **centrée sur le modèle**. Spécifiez simplement le format `vendor/model` (ex. `zhipu/glm-4.7`) pour ajouter de nouveaux providers — **aucune modification de code requise !** - -#### Tous les Vendors Supportés - -| Vendor | Préfixe `model` | API Base par défaut | Protocole | API Key | -| ----------------------- | --------------- | --------------------------------------------------- | --------- | ---------------------------------------------------------------- | -| **OpenAI** | `openai/` | `https://api.openai.com/v1` | OpenAI | [Obtenir](https://platform.openai.com) | -| **Anthropic** | `anthropic/` | `https://api.anthropic.com/v1` | Anthropic | [Obtenir](https://console.anthropic.com) | -| **智谱 AI (GLM)** | `zhipu/` | `https://open.bigmodel.cn/api/paas/v4` | OpenAI | [Obtenir](https://open.bigmodel.cn/usercenter/proj-mgmt/apikeys) | -| **DeepSeek** | `deepseek/` | `https://api.deepseek.com/v1` | OpenAI | [Obtenir](https://platform.deepseek.com) | -| **Google Gemini** | `gemini/` | `https://generativelanguage.googleapis.com/v1beta` | Gemini | [Obtenir](https://aistudio.google.com/api-keys) | -| **Groq** | `groq/` | `https://api.groq.com/openai/v1` | OpenAI | [Obtenir](https://console.groq.com) | -| **通义千问 (Qwen)** | `qwen/` | `https://dashscope.aliyuncs.com/compatible-mode/v1` | OpenAI | [Obtenir](https://dashscope.console.aliyun.com) | -| **Ollama** | `ollama/` | `http://localhost:11434/v1` | OpenAI | Local (pas de clé) | -| **OpenRouter** | `openrouter/` | `https://openrouter.ai/api/v1` | OpenAI | [Obtenir](https://openrouter.ai/keys) | -| **VolcEngine (Doubao)** | `volcengine/` | `https://ark.cn-beijing.volces.com/api/v3` | OpenAI | [Obtenir](https://www.volcengine.com/activity/codingplan?utm_campaign=PicoClaw&utm_content=PicoClaw&utm_medium=devrel&utm_source=OWO&utm_term=PicoClaw) | -| **Antigravity** | `antigravity/` | Google Cloud | Custom | OAuth uniquement | - -#### Équilibrage de Charge - -Configurez plusieurs endpoints pour le même nom de modèle — PicoClaw effectuera automatiquement un round-robin : - -```json -{ - "model_list": [ - { "model_name": "gpt-5.4", "model": "openai/gpt-5.4", "api_base": "https://api1.example.com/v1", "api_keys": ["sk-key1"] }, - { "model_name": "gpt-5.4", "model": "openai/gpt-5.4", "api_base": "https://api2.example.com/v1", "api_keys": ["sk-key2"] } - ] -} -``` - -#### Migration depuis l'ancienne config `providers` - -L'ancienne configuration `providers` est **dépréciée** et a été supprimée dans V2. Les configs V0/V1 existantes sont auto-migrées. Voir [docs/migration/model-list-migration.md](../migration/model-list-migration.md). - -#### Configuration du Streaming - -Le streaming provider utilise un double opt-in et est désactivé par défaut. L'agent ne tente le streaming que lorsque le channel courant a `settings.streaming.enabled: true`, que l'entrée de modèle active a `streaming.enabled: true`, et que le provider comme le channel prennent en charge le streaming. Si une condition manque, PicoClaw utilise le chemin de requête non-streaming normal. - -Laissez `streaming` absent si vous ne voulez pas de streaming. Un bloc `streaming` omis signifie désactivé; il n'est pas nécessaire d'écrire `"streaming": {"enabled": false}`. - -Exemple d'activation : - -```json -{ - "model_list": [ - { - "model_name": "gpt-5.4", - "provider": "openai", - "model": "gpt-5.4", - "api_keys": ["sk-your-openai-key"], - "streaming": { - "enabled": true - } - } - ], - "channel_list": { - "telegram": { - "enabled": true, - "type": "telegram", - "settings": { - "token": "YOUR_TELEGRAM_TOKEN", - "streaming": { - "enabled": true - } - } - } - } -} -``` - -| Champ | Type | Défaut | Description | -| ----- | ---- | ------ | ----------- | -| `channel_list..settings.streaming.enabled` | bool | `false` | Autorise ce channel à afficher la sortie streaming du provider | -| `channel_list..settings.streaming.throttle_seconds` | int | Telegram: `3` | Intervalle minimal entre les mises à jour intermédiaires; le contenu final est toujours envoyé | -| `channel_list..settings.streaming.min_growth_chars` | int | Telegram: `200` | Croissance minimale du texte avant une mise à jour intermédiaire; le contenu final est toujours envoyé | -| `model_list[].streaming.enabled` | bool | `false` | Autorise cette entrée de modèle à tenter des requêtes provider en streaming | - -Les anciennes variables d'environnement Telegram restent compatibles : `PICOCLAW_CHANNELS_TELEGRAM_STREAMING_ENABLED`, `PICOCLAW_CHANNELS_TELEGRAM_STREAMING_THROTTLE_SECONDS` et `PICOCLAW_CHANNELS_TELEGRAM_STREAMING_MIN_GROWTH_CHARS`. - -Le comportement d'échec est volontairement conservateur : si le streaming échoue avant l'envoi d'un chunk visible, PicoClaw réessaie une fois via le chemin `Chat()` normal. Si un chunk a déjà été affiché à l'utilisateur, PicoClaw n'envoie pas une deuxième réponse non-streaming, afin d'éviter une sortie dupliquée. - -### Architecture des Providers - -PicoClaw route les providers par famille de protocole : - -- **Compatible OpenAI** : OpenRouter, Groq, Zhipu, endpoints vLLM et la plupart des autres. -- **Gemini natif** : Google Gemini via les endpoints natifs `models/*:generateContent` et `models/*:streamGenerateContent`. -- **Anthropic** : Comportement natif de l'API Claude. -- **Codex/OAuth** : Route d'authentification OAuth/token OpenAI. - -Cela maintient le runtime léger tout en faisant des nouveaux backends compatibles OpenAI principalement une opération de configuration (`api_base` + `api_keys`). +This fork supports only OpenAI (Responses / Chat Completions) and Anthropic Messages. For compatible endpoints, API keys, streaming and login, see the maintained [provider guide](providers.md) or [中文说明](providers.zh.md). ### Tâches Planifiées / Rappels diff --git a/docs/guides/configuration.it.md b/docs/guides/configuration.it.md index 2068f246..975ebfbb 100644 --- a/docs/guides/configuration.it.md +++ b/docs/guides/configuration.it.md @@ -1,5 +1,7 @@ # ⚙️ Guida alla Configurazione +> Fork configuration: `PICOCLAW_HOME` also changes the default config path; `PICOCLAW_CONFIG` overrides that path. For current model protocols and channel settings, use the [README](../../README.md) and [configuration example](../../config/config.example.json). + > Torna al [README](../../README.md) ## ⚙️ Configurazione @@ -23,7 +25,7 @@ Puoi sovrascrivere i percorsi predefiniti usando variabili d'ambiente. Questo è PICOCLAW_CONFIG=/etc/picoclaw/production.json picoclaw gateway # Esegui picoclaw con tutti i dati salvati in /opt/picoclaw -# La configurazione verrà caricata dal percorso predefinito ~/.picoclaw/config.json +# Config: /opt/picoclaw/config.json (PICOCLAW_HOME=/opt/picoclaw) # Il workspace verrà creato in /opt/picoclaw/workspace PICOCLAW_HOME=/opt/picoclaw picoclaw agent diff --git a/docs/guides/configuration.ja.md b/docs/guides/configuration.ja.md index c37fddb6..82febe7b 100644 --- a/docs/guides/configuration.ja.md +++ b/docs/guides/configuration.ja.md @@ -1,5 +1,7 @@ # ⚙️ 設定ガイド +> Fork configuration: `PICOCLAW_HOME` also changes the default config path; `PICOCLAW_CONFIG` overrides that path. For current model protocols and channel settings, use the [README](../../README.md) and [configuration example](../../config/config.example.json). + > [README](../../README.md) に戻る ## ⚙️ 設定詳細 @@ -23,7 +25,7 @@ PICOCLAW_CONFIG=/etc/picoclaw/production.json picoclaw gateway # /opt/picoclaw にすべてのデータを保存して picoclaw を実行 -# 設定はデフォルトの ~/.picoclaw/config.json から読み込まれます +# Config: /opt/picoclaw/config.json (PICOCLAW_HOME=/opt/picoclaw) # ワークスペースは /opt/picoclaw/workspace に作成されます PICOCLAW_HOME=/opt/picoclaw picoclaw agent @@ -353,119 +355,9 @@ Agent が HEARTBEAT.md を読む HEARTBEAT_OK を返信 ユーザーが直接結果を受信 ``` -### Providers +### Model providers -> [!NOTE] -> Groq は Whisper による無料音声文字起こしを提供します。設定すると、任意のチャンネルの音声メッセージが Agent レベルで自動的に文字起こしされます。 - -| Provider | 用途 | API キー取得 | -| ------------ | --------------------------------------- | ------------------------------------------------------------ | -| `gemini` | LLM(Gemini 直接) | [aistudio.google.com](https://aistudio.google.com) | -| `zhipu` | LLM(Zhipu 直接) | [bigmodel.cn](https://bigmodel.cn) | -| `volcengine` | LLM(Volcengine 直接) | [volcengine.com](https://www.volcengine.com/activity/codingplan?utm_campaign=PicoClaw&utm_content=PicoClaw&utm_medium=devrel&utm_source=OWO&utm_term=PicoClaw) | -| `openrouter` | LLM(推奨、全モデルにアクセス可能) | [openrouter.ai](https://openrouter.ai) | -| `anthropic` | LLM(Claude 直接) | [console.anthropic.com](https://console.anthropic.com) | -| `openai` | LLM(GPT 直接) | [platform.openai.com](https://platform.openai.com) | -| `deepseek` | LLM(DeepSeek 直接) | [platform.deepseek.com](https://platform.deepseek.com) | -| `qwen` | LLM(Qwen 直接) | [dashscope.console.aliyun.com](https://dashscope.console.aliyun.com) | -| `groq` | LLM + **音声文字起こし**(Whisper) | [console.groq.com](https://console.groq.com) | -| `cerebras` | LLM(Cerebras 直接) | [cerebras.ai](https://cerebras.ai) | -| `vivgrid` | LLM(Vivgrid 直接) | [vivgrid.com](https://vivgrid.com) | - -### モデル設定 (model_list) - -> **新機能:** PicoClaw は**モデル中心**の設定アプローチを採用しました。`vendor/model` 形式(例:`zhipu/glm-4.7`)を指定するだけで新しい Provider を追加できます — **コード変更不要!** - -#### サポートされている全 Vendor - -| Vendor | `model` プレフィックス | デフォルト API Base | プロトコル | API Key | -| ----------------------- | ---------------------- | --------------------------------------------------- | ---------- | ---------------------------------------------------------------- | -| **OpenAI** | `openai/` | `https://api.openai.com/v1` | OpenAI | [取得](https://platform.openai.com) | -| **Anthropic** | `anthropic/` | `https://api.anthropic.com/v1` | Anthropic | [取得](https://console.anthropic.com) | -| **智谱 AI (GLM)** | `zhipu/` | `https://open.bigmodel.cn/api/paas/v4` | OpenAI | [取得](https://open.bigmodel.cn/usercenter/proj-mgmt/apikeys) | -| **DeepSeek** | `deepseek/` | `https://api.deepseek.com/v1` | OpenAI | [取得](https://platform.deepseek.com) | -| **Google Gemini** | `gemini/` | `https://generativelanguage.googleapis.com/v1beta` | Gemini | [取得](https://aistudio.google.com/api-keys) | -| **Groq** | `groq/` | `https://api.groq.com/openai/v1` | OpenAI | [取得](https://console.groq.com) | -| **通義千問 (Qwen)** | `qwen/` | `https://dashscope.aliyuncs.com/compatible-mode/v1` | OpenAI | [取得](https://dashscope.console.aliyun.com) | -| **Ollama** | `ollama/` | `http://localhost:11434/v1` | OpenAI | ローカル(キー不要) | -| **OpenRouter** | `openrouter/` | `https://openrouter.ai/api/v1` | OpenAI | [取得](https://openrouter.ai/keys) | -| **VolcEngine (Doubao)** | `volcengine/` | `https://ark.cn-beijing.volces.com/api/v3` | OpenAI | [取得](https://www.volcengine.com/activity/codingplan?utm_campaign=PicoClaw&utm_content=PicoClaw&utm_medium=devrel&utm_source=OWO&utm_term=PicoClaw) | -| **Antigravity** | `antigravity/` | Google Cloud | Custom | OAuth のみ | - -#### ロードバランシング - -同じモデル名に複数のエンドポイントを設定すると、PicoClaw が自動的にラウンドロビンします: - -```json -{ - "model_list": [ - { "model_name": "gpt-5.4", "model": "openai/gpt-5.4", "api_base": "https://api1.example.com/v1", "api_keys": ["sk-key1"] }, - { "model_name": "gpt-5.4", "model": "openai/gpt-5.4", "api_base": "https://api2.example.com/v1", "api_keys": ["sk-key2"] } - ] -} -``` - -#### 旧 `providers` 設定からの移行 - -旧 `providers` 設定は**非推奨**となり、V2 で削除されました。既存の V0/V1 設定は自動的に移行されます。[docs/migration/model-list-migration.md](../migration/model-list-migration.md) を参照してください。 - -#### ストリーミング設定 - -Provider ストリーミングは二重の opt-in 方式で、デフォルトでは無効です。現在の channel に `settings.streaming.enabled: true` があり、アクティブなモデルエントリに `streaming.enabled: true` があり、さらに provider と channel の両方がストリーミングをサポートしている場合にのみ、agent はストリーミングリクエストを試行します。いずれかの条件が欠ける場合、PicoClaw は通常の非ストリーミングリクエスト経路を使います。 - -ストリーミングを使わない場合は `streaming` を省略してください。`streaming` ブロックの省略は無効を意味するため、`"streaming": {"enabled": false}` を書く必要はありません。 - -有効化例: - -```json -{ - "model_list": [ - { - "model_name": "gpt-5.4", - "provider": "openai", - "model": "gpt-5.4", - "api_keys": ["sk-your-openai-key"], - "streaming": { - "enabled": true - } - } - ], - "channel_list": { - "telegram": { - "enabled": true, - "type": "telegram", - "settings": { - "token": "YOUR_TELEGRAM_TOKEN", - "streaming": { - "enabled": true - } - } - } - } -} -``` - -| フィールド | 型 | デフォルト | 説明 | -| ---------- | -- | ---------- | ---- | -| `channel_list..settings.streaming.enabled` | bool | `false` | この channel で provider のストリーミング出力を表示できるようにします | -| `channel_list..settings.streaming.throttle_seconds` | int | Telegram: `3` | 中間更新の最小間隔。最終内容は常に flush されます | -| `channel_list..settings.streaming.min_growth_chars` | int | Telegram: `200` | 次の中間更新を送るために必要な最小文字増加数。最終内容は常に flush されます | -| `model_list[].streaming.enabled` | bool | `false` | このモデルエントリで provider ストリーミングリクエストを試行できるようにします | - -既存の Telegram 環境変数 `PICOCLAW_CHANNELS_TELEGRAM_STREAMING_ENABLED`、`PICOCLAW_CHANNELS_TELEGRAM_STREAMING_THROTTLE_SECONDS`、`PICOCLAW_CHANNELS_TELEGRAM_STREAMING_MIN_GROWTH_CHARS`. - -失敗時の動作は保守的です。可視 chunk が送信される前にストリーミングが失敗した場合、PicoClaw は通常の `Chat()` 経路で一度だけ再試行します。すでに chunk がユーザーに表示されている場合は、表示済み出力の重複を避けるため、二つ目の非ストリーミング回答は送信しません。 - -### Provider アーキテクチャ - -PicoClaw はプロトコルファミリーで Provider をルーティングします: - -- **OpenAI 互換**:OpenRouter、Groq、Zhipu、vLLM スタイルのエンドポイントなど。 -- **Gemini ネイティブ**:Google Gemini のネイティブ `models/*:generateContent` / `models/*:streamGenerateContent` エンドポイント。 -- **Anthropic**:Claude ネイティブ API の動作。 -- **Codex/OAuth**:OpenAI OAuth/トークン認証ルート。 - -これによりランタイムを軽量に保ちつつ、新しい OpenAI 互換バックエンドの追加をほぼ設定操作(`api_base` + `api_keys`)のみで実現します。 +This fork supports only OpenAI (Responses / Chat Completions) and Anthropic Messages. For compatible endpoints, API keys, streaming and login, see the maintained [provider guide](providers.md) or [中文说明](providers.zh.md). ### スケジュールタスク / リマインダー diff --git a/docs/guides/configuration.md b/docs/guides/configuration.md index 714e6ab0..3c95afc2 100644 --- a/docs/guides/configuration.md +++ b/docs/guides/configuration.md @@ -1,6 +1,6 @@ # ⚙️ Configuration Guide -> Back to [README](../README.md) +> Back to [README](../../README.md) ## ⚙️ Configuration @@ -10,7 +10,7 @@ Config file: `~/.picoclaw/config.json` ### Environment Variables -You can override default paths using environment variables. This is useful for portable installations, containerized deployments, or running picoclaw as a system service. These variables are independent and control different paths. +You can override default paths using environment variables. This is useful for portable installations, containerized deployments, or running picoclaw as a system service. `PICOCLAW_HOME` also moves the default config path; `PICOCLAW_CONFIG` takes precedence for the config file. | Variable | Description | Default Path | |-------------------|-----------------------------------------------------------------------------------------------------------------------------------------|---------------------------| @@ -25,7 +25,7 @@ You can override default paths using environment variables. This is useful for p PICOCLAW_CONFIG=/etc/picoclaw/production.json picoclaw gateway # Run picoclaw with all its data stored in /opt/picoclaw -# Config will be loaded from the default ~/.picoclaw/config.json +# Config: /opt/picoclaw/config.json (PICOCLAW_HOME=/opt/picoclaw) # Workspace will be created at /opt/picoclaw/workspace PICOCLAW_HOME=/opt/picoclaw picoclaw agent diff --git a/docs/guides/configuration.ms.md b/docs/guides/configuration.ms.md index 91ce5423..341934e6 100644 --- a/docs/guides/configuration.ms.md +++ b/docs/guides/configuration.ms.md @@ -1,5 +1,7 @@ # ⚙️ Panduan Konfigurasi +> Fork configuration: `PICOCLAW_HOME` also changes the default config path; `PICOCLAW_CONFIG` overrides that path. For current model protocols and channel settings, use the [README](../../README.md) and [configuration example](../../config/config.example.json). + > Kembali ke [README](../../README.md) ## ⚙️ Konfigurasi @@ -23,7 +25,7 @@ Anda boleh menggantikan laluan lalai menggunakan pemboleh ubah persekitaran. Ini PICOCLAW_CONFIG=/etc/picoclaw/production.json picoclaw gateway # Jalankan picoclaw dengan semua data disimpan di /opt/picoclaw -# Config akan dimuatkan dari lalai ~/.picoclaw/config.json +# Config: /opt/picoclaw/config.json (PICOCLAW_HOME=/opt/picoclaw) # Workspace akan dicipta di /opt/picoclaw/workspace PICOCLAW_HOME=/opt/picoclaw picoclaw agent diff --git a/docs/guides/configuration.pt-br.md b/docs/guides/configuration.pt-br.md index 82df2531..39425d1c 100644 --- a/docs/guides/configuration.pt-br.md +++ b/docs/guides/configuration.pt-br.md @@ -1,5 +1,7 @@ # ⚙️ Guia de Configuração +> Fork configuration: `PICOCLAW_HOME` also changes the default config path; `PICOCLAW_CONFIG` overrides that path. For current model protocols and channel settings, use the [README](../../README.md) and [configuration example](../../config/config.example.json). + > Voltar ao [README](../../README.md) ## ⚙️ Configuração @@ -23,7 +25,7 @@ Você pode substituir os caminhos padrão usando variáveis de ambiente. Isso é PICOCLAW_CONFIG=/etc/picoclaw/production.json picoclaw gateway # Executar picoclaw com todos os dados armazenados em /opt/picoclaw -# A configuração será carregada do padrão ~/.picoclaw/config.json +# Config: /opt/picoclaw/config.json (PICOCLAW_HOME=/opt/picoclaw) # O workspace será criado em /opt/picoclaw/workspace PICOCLAW_HOME=/opt/picoclaw picoclaw agent @@ -353,119 +355,9 @@ Responde HEARTBEAT_OK Usuário recebe resultado diretamente * `PICOCLAW_HEARTBEAT_ENABLED=false` para desativar * `PICOCLAW_HEARTBEAT_INTERVAL=60` para alterar o intervalo -### Providers +### Model providers -> [!NOTE] -> O Groq fornece transcrição de voz gratuita via Whisper. Se configurado, mensagens de áudio de qualquer canal serão automaticamente transcritas no nível do agente. - -| Provider | Finalidade | Obter API Key | -| ------------ | --------------------------------------- | ------------------------------------------------------------ | -| `gemini` | LLM (Gemini direto) | [aistudio.google.com](https://aistudio.google.com) | -| `zhipu` | LLM (Zhipu direto) | [bigmodel.cn](https://bigmodel.cn) | -| `volcengine` | LLM (Volcengine direto) | [volcengine.com](https://www.volcengine.com/activity/codingplan?utm_campaign=PicoClaw&utm_content=PicoClaw&utm_medium=devrel&utm_source=OWO&utm_term=PicoClaw) | -| `openrouter` | LLM (recomendado, acesso a todos modelos) | [openrouter.ai](https://openrouter.ai) | -| `anthropic` | LLM (Claude direto) | [console.anthropic.com](https://console.anthropic.com) | -| `openai` | LLM (GPT direto) | [platform.openai.com](https://platform.openai.com) | -| `deepseek` | LLM (DeepSeek direto) | [platform.deepseek.com](https://platform.deepseek.com) | -| `qwen` | LLM (Qwen direto) | [dashscope.console.aliyun.com](https://dashscope.console.aliyun.com) | -| `groq` | LLM + **Transcrição de voz** (Whisper) | [console.groq.com](https://console.groq.com) | -| `cerebras` | LLM (Cerebras direto) | [cerebras.ai](https://cerebras.ai) | -| `vivgrid` | LLM (Vivgrid direto) | [vivgrid.com](https://vivgrid.com) | - -### Configuração de Modelos (model_list) - -> **Novidade:** PicoClaw agora usa uma abordagem **centrada no modelo**. Basta especificar o formato `vendor/model` (ex.: `zhipu/glm-4.7`) para adicionar novos providers — **sem alterações de código!** - -#### Todos os Vendors Suportados - -| Vendor | Prefixo `model` | API Base padrão | Protocolo | API Key | -| ----------------------- | --------------- | --------------------------------------------------- | --------- | ---------------------------------------------------------------- | -| **OpenAI** | `openai/` | `https://api.openai.com/v1` | OpenAI | [Obter](https://platform.openai.com) | -| **Anthropic** | `anthropic/` | `https://api.anthropic.com/v1` | Anthropic | [Obter](https://console.anthropic.com) | -| **智谱 AI (GLM)** | `zhipu/` | `https://open.bigmodel.cn/api/paas/v4` | OpenAI | [Obter](https://open.bigmodel.cn/usercenter/proj-mgmt/apikeys) | -| **DeepSeek** | `deepseek/` | `https://api.deepseek.com/v1` | OpenAI | [Obter](https://platform.deepseek.com) | -| **Google Gemini** | `gemini/` | `https://generativelanguage.googleapis.com/v1beta` | Gemini | [Obter](https://aistudio.google.com/api-keys) | -| **Groq** | `groq/` | `https://api.groq.com/openai/v1` | OpenAI | [Obter](https://console.groq.com) | -| **通义千问 (Qwen)** | `qwen/` | `https://dashscope.aliyuncs.com/compatible-mode/v1` | OpenAI | [Obter](https://dashscope.console.aliyun.com) | -| **Ollama** | `ollama/` | `http://localhost:11434/v1` | OpenAI | Local (sem chave) | -| **OpenRouter** | `openrouter/` | `https://openrouter.ai/api/v1` | OpenAI | [Obter](https://openrouter.ai/keys) | -| **VolcEngine (Doubao)** | `volcengine/` | `https://ark.cn-beijing.volces.com/api/v3` | OpenAI | [Obter](https://www.volcengine.com/activity/codingplan?utm_campaign=PicoClaw&utm_content=PicoClaw&utm_medium=devrel&utm_source=OWO&utm_term=PicoClaw) | -| **Antigravity** | `antigravity/` | Google Cloud | Custom | Somente OAuth | - -#### Balanceamento de Carga - -Configure múltiplos endpoints para o mesmo nome de modelo — PicoClaw fará round-robin automaticamente: - -```json -{ - "model_list": [ - { "model_name": "gpt-5.4", "model": "openai/gpt-5.4", "api_base": "https://api1.example.com/v1", "api_keys": ["sk-key1"] }, - { "model_name": "gpt-5.4", "model": "openai/gpt-5.4", "api_base": "https://api2.example.com/v1", "api_keys": ["sk-key2"] } - ] -} -``` - -#### Migração da Configuração Legada `providers` - -A configuração antiga `providers` está **depreciada** e foi removida no V2. Configs V0/V1 existentes são auto-migradas. Veja [docs/migration/model-list-migration.md](../migration/model-list-migration.md). - -#### Configuração de Streaming - -O streaming do provider usa double opt-in e fica desativado por padrão. O agent só tenta streaming quando o canal atual tem `settings.streaming.enabled: true`, a entrada de modelo ativa tem `streaming.enabled: true`, e tanto o provider quanto o canal suportam streaming. Se qualquer condição estiver ausente, o PicoClaw usa o caminho normal de requisição sem streaming. - -Deixe `streaming` ausente quando não quiser streaming. Um bloco `streaming` omitido significa desativado; você não precisa escrever `"streaming": {"enabled": false}`. - -Exemplo de ativação: - -```json -{ - "model_list": [ - { - "model_name": "gpt-5.4", - "provider": "openai", - "model": "gpt-5.4", - "api_keys": ["sk-your-openai-key"], - "streaming": { - "enabled": true - } - } - ], - "channel_list": { - "telegram": { - "enabled": true, - "type": "telegram", - "settings": { - "token": "YOUR_TELEGRAM_TOKEN", - "streaming": { - "enabled": true - } - } - } - } -} -``` - -| Campo | Tipo | Padrão | Descrição | -| ----- | ---- | ------ | --------- | -| `channel_list..settings.streaming.enabled` | bool | `false` | Permite que este canal exiba output streaming do provider | -| `channel_list..settings.streaming.throttle_seconds` | int | Telegram: `3` | Intervalo mínimo entre atualizações intermediárias; o conteúdo final sempre é enviado | -| `channel_list..settings.streaming.min_growth_chars` | int | Telegram: `200` | Crescimento mínimo de texto antes de enviar outra atualização intermediária; o conteúdo final sempre é enviado | -| `model_list[].streaming.enabled` | bool | `false` | Permite que esta entrada de modelo tente requisições de provider streaming | - -As variáveis de ambiente legadas do Telegram continuam compatíveis: `PICOCLAW_CHANNELS_TELEGRAM_STREAMING_ENABLED`, `PICOCLAW_CHANNELS_TELEGRAM_STREAMING_THROTTLE_SECONDS` e `PICOCLAW_CHANNELS_TELEGRAM_STREAMING_MIN_GROWTH_CHARS`. - -O comportamento de falha é intencionalmente conservador: se o streaming falhar antes de qualquer chunk visível ser enviado, o PicoClaw tenta novamente uma vez pelo caminho normal `Chat()`. Se um chunk já foi mostrado ao usuário, o PicoClaw não envia uma segunda resposta sem streaming, evitando output duplicado. - -### Arquitetura de Providers - -PicoClaw roteia providers por família de protocolo: - -- **Compatível com OpenAI**: OpenRouter, Groq, Zhipu, endpoints vLLM e a maioria dos outros. -- **Gemini nativo**: Google Gemini via endpoints nativos `models/*:generateContent` e `models/*:streamGenerateContent`. -- **Anthropic**: Comportamento nativo da API Claude. -- **Codex/OAuth**: Rota de autenticação OAuth/token OpenAI. - -Isso mantém o runtime leve enquanto torna novos backends compatíveis com OpenAI basicamente uma operação de configuração (`api_base` + `api_keys`). +This fork supports only OpenAI (Responses / Chat Completions) and Anthropic Messages. For compatible endpoints, API keys, streaming and login, see the maintained [provider guide](providers.md) or [中文说明](providers.zh.md). ### Tarefas Agendadas / Lembretes diff --git a/docs/guides/configuration.vi.md b/docs/guides/configuration.vi.md index e31f1575..6677723d 100644 --- a/docs/guides/configuration.vi.md +++ b/docs/guides/configuration.vi.md @@ -1,5 +1,7 @@ # ⚙️ Hướng Dẫn Cấu Hình +> Fork configuration: `PICOCLAW_HOME` also changes the default config path; `PICOCLAW_CONFIG` overrides that path. For current model protocols and channel settings, use the [README](../../README.md) and [configuration example](../../config/config.example.json). + > Quay lại [README](../../README.md) ## ⚙️ Cấu Hình @@ -23,7 +25,7 @@ Bạn có thể ghi đè các đường dẫn mặc định bằng biến môi t PICOCLAW_CONFIG=/etc/picoclaw/production.json picoclaw gateway # Chạy picoclaw với tất cả dữ liệu lưu tại /opt/picoclaw -# Cấu hình sẽ được tải từ mặc định ~/.picoclaw/config.json +# Config: /opt/picoclaw/config.json (PICOCLAW_HOME=/opt/picoclaw) # Workspace sẽ được tạo tại /opt/picoclaw/workspace PICOCLAW_HOME=/opt/picoclaw picoclaw agent @@ -353,119 +355,9 @@ Trả lời HEARTBEAT_OK Người dùng nhận kết quả trực tiếp * `PICOCLAW_HEARTBEAT_ENABLED=false` để tắt * `PICOCLAW_HEARTBEAT_INTERVAL=60` để thay đổi khoảng thời gian -### Providers +### Model providers -> [!NOTE] -> Groq cung cấp chuyển đổi giọng nói thành văn bản miễn phí qua Whisper. Nếu được cấu hình, tin nhắn âm thanh từ bất kỳ kênh nào sẽ được tự động chuyển đổi ở cấp độ agent. - -| Provider | Mục đích | Lấy API Key | -| ------------ | --------------------------------------- | ------------------------------------------------------------ | -| `gemini` | LLM (Gemini trực tiếp) | [aistudio.google.com](https://aistudio.google.com) | -| `zhipu` | LLM (Zhipu trực tiếp) | [bigmodel.cn](https://bigmodel.cn) | -| `volcengine` | LLM (Volcengine trực tiếp) | [volcengine.com](https://www.volcengine.com/activity/codingplan?utm_campaign=PicoClaw&utm_content=PicoClaw&utm_medium=devrel&utm_source=OWO&utm_term=PicoClaw) | -| `openrouter` | LLM (khuyến nghị, truy cập tất cả mô hình) | [openrouter.ai](https://openrouter.ai) | -| `anthropic` | LLM (Claude trực tiếp) | [console.anthropic.com](https://console.anthropic.com) | -| `openai` | LLM (GPT trực tiếp) | [platform.openai.com](https://platform.openai.com) | -| `deepseek` | LLM (DeepSeek trực tiếp) | [platform.deepseek.com](https://platform.deepseek.com) | -| `qwen` | LLM (Qwen trực tiếp) | [dashscope.console.aliyun.com](https://dashscope.console.aliyun.com) | -| `groq` | LLM + **Chuyển đổi giọng nói** (Whisper)| [console.groq.com](https://console.groq.com) | -| `cerebras` | LLM (Cerebras trực tiếp) | [cerebras.ai](https://cerebras.ai) | -| `vivgrid` | LLM (Vivgrid trực tiếp) | [vivgrid.com](https://vivgrid.com) | - -### Cấu Hình Mô Hình (model_list) - -> **Tính năng mới:** PicoClaw hiện sử dụng cách tiếp cận **lấy mô hình làm trung tâm**. Chỉ cần chỉ định định dạng `vendor/model` (ví dụ: `zhipu/glm-4.7`) để thêm provider mới — **không cần thay đổi code!** - -#### Tất Cả Vendor Được Hỗ Trợ - -| Vendor | Tiền tố `model` | API Base mặc định | Giao thức | API Key | -| ----------------------- | --------------- | --------------------------------------------------- | --------- | ---------------------------------------------------------------- | -| **OpenAI** | `openai/` | `https://api.openai.com/v1` | OpenAI | [Lấy](https://platform.openai.com) | -| **Anthropic** | `anthropic/` | `https://api.anthropic.com/v1` | Anthropic | [Lấy](https://console.anthropic.com) | -| **智谱 AI (GLM)** | `zhipu/` | `https://open.bigmodel.cn/api/paas/v4` | OpenAI | [Lấy](https://open.bigmodel.cn/usercenter/proj-mgmt/apikeys) | -| **DeepSeek** | `deepseek/` | `https://api.deepseek.com/v1` | OpenAI | [Lấy](https://platform.deepseek.com) | -| **Google Gemini** | `gemini/` | `https://generativelanguage.googleapis.com/v1beta` | Gemini | [Lấy](https://aistudio.google.com/api-keys) | -| **Groq** | `groq/` | `https://api.groq.com/openai/v1` | OpenAI | [Lấy](https://console.groq.com) | -| **通义千问 (Qwen)** | `qwen/` | `https://dashscope.aliyuncs.com/compatible-mode/v1` | OpenAI | [Lấy](https://dashscope.console.aliyun.com) | -| **Ollama** | `ollama/` | `http://localhost:11434/v1` | OpenAI | Cục bộ (không cần key) | -| **OpenRouter** | `openrouter/` | `https://openrouter.ai/api/v1` | OpenAI | [Lấy](https://openrouter.ai/keys) | -| **VolcEngine (Doubao)** | `volcengine/` | `https://ark.cn-beijing.volces.com/api/v3` | OpenAI | [Lấy](https://www.volcengine.com/activity/codingplan?utm_campaign=PicoClaw&utm_content=PicoClaw&utm_medium=devrel&utm_source=OWO&utm_term=PicoClaw) | -| **Antigravity** | `antigravity/` | Google Cloud | Custom | Chỉ OAuth | - -#### Cân Bằng Tải - -Cấu hình nhiều endpoint cho cùng tên mô hình — PicoClaw sẽ tự động round-robin: - -```json -{ - "model_list": [ - { "model_name": "gpt-5.4", "model": "openai/gpt-5.4", "api_base": "https://api1.example.com/v1", "api_keys": ["sk-key1"] }, - { "model_name": "gpt-5.4", "model": "openai/gpt-5.4", "api_base": "https://api2.example.com/v1", "api_keys": ["sk-key2"] } - ] -} -``` - -#### Di Chuyển Từ Cấu Hình `providers` Cũ - -Cấu hình `providers` cũ đã **bị deprecated** và đã được loại bỏ trong V2. Các cấu hình V0/V1 hiện có sẽ được tự động migrate. Xem [docs/migration/model-list-migration.md](../migration/model-list-migration.md). - -#### Cấu Hình Streaming - -Provider streaming dùng cơ chế double opt-in và bị tắt theo mặc định. Agent chỉ thử streaming khi channel hiện tại có `settings.streaming.enabled: true`, entry model đang dùng có `streaming.enabled: true`, và cả provider lẫn channel đều hỗ trợ streaming. Nếu thiếu bất kỳ điều kiện nào, PicoClaw dùng đường dẫn yêu cầu không streaming thông thường. - -Hãy để trống `streaming` khi bạn không muốn dùng streaming. Bỏ qua block `streaming` nghĩa là đã tắt; bạn không cần viết `"streaming": {"enabled": false}`. - -Ví dụ bật streaming: - -```json -{ - "model_list": [ - { - "model_name": "gpt-5.4", - "provider": "openai", - "model": "gpt-5.4", - "api_keys": ["sk-your-openai-key"], - "streaming": { - "enabled": true - } - } - ], - "channel_list": { - "telegram": { - "enabled": true, - "type": "telegram", - "settings": { - "token": "YOUR_TELEGRAM_TOKEN", - "streaming": { - "enabled": true - } - } - } - } -} -``` - -| Trường | Kiểu | Mặc định | Mô tả | -| ------ | ---- | -------- | ----- | -| `channel_list..settings.streaming.enabled` | bool | `false` | Cho phép channel này hiển thị output streaming từ provider | -| `channel_list..settings.streaming.throttle_seconds` | int | Telegram: `3` | Khoảng cách tối thiểu giữa các cập nhật trung gian; nội dung cuối luôn được flush | -| `channel_list..settings.streaming.min_growth_chars` | int | Telegram: `200` | Số ký tự tăng tối thiểu trước khi gửi cập nhật trung gian; nội dung cuối luôn được flush | -| `model_list[].streaming.enabled` | bool | `false` | Cho phép entry model này thử yêu cầu provider streaming | - -Các biến môi trường Telegram cũ vẫn tương thích: `PICOCLAW_CHANNELS_TELEGRAM_STREAMING_ENABLED`, `PICOCLAW_CHANNELS_TELEGRAM_STREAMING_THROTTLE_SECONDS`, và `PICOCLAW_CHANNELS_TELEGRAM_STREAMING_MIN_GROWTH_CHARS`. - -Hành vi lỗi được giữ thận trọng: nếu streaming lỗi trước khi gửi bất kỳ chunk hiển thị nào, PicoClaw thử lại một lần qua đường dẫn `Chat()` thông thường. Nếu đã có chunk hiển thị cho người dùng, PicoClaw không gửi thêm một câu trả lời non-streaming thứ hai để tránh lặp output. - -### Kiến Trúc Provider - -PicoClaw định tuyến provider theo họ giao thức: - -- **Tương thích OpenAI**: OpenRouter, Groq, Zhipu, endpoint kiểu vLLM và hầu hết các provider khác. -- **Gemini native**: Google Gemini qua các endpoint native `models/*:generateContent` và `models/*:streamGenerateContent`. -- **Anthropic**: Hành vi API Claude gốc. -- **Codex/OAuth**: Tuyến xác thực OAuth/token OpenAI. - -Điều này giữ runtime nhẹ trong khi khiến backend OpenAI-compatible mới chủ yếu chỉ là thao tác cấu hình (`api_base` + `api_keys`). +This fork supports only OpenAI (Responses / Chat Completions) and Anthropic Messages. For compatible endpoints, API keys, streaming and login, see the maintained [provider guide](providers.md) or [中文说明](providers.zh.md). ### Tác Vụ Đã Lên Lịch / Nhắc Nhở diff --git a/docs/guides/configuration.zh.md b/docs/guides/configuration.zh.md index 33587c85..8c76c02a 100644 --- a/docs/guides/configuration.zh.md +++ b/docs/guides/configuration.zh.md @@ -8,7 +8,7 @@ ### 环境变量 -你可以使用环境变量覆盖默认路径。这对于便携安装、容器化部署或将 picoclaw 作为系统服务运行非常有用。这些变量是独立的,控制不同的路径。 +你可以使用环境变量覆盖默认路径。这对于便携安装、容器化部署或将 picoclaw 作为系统服务运行非常有用。`PICOCLAW_HOME` 也会改变默认配置文件路径;显式指定的 `PICOCLAW_CONFIG` 优先。 | 变量 | 描述 | 默认路径 | |-------------------|-----------------------------------------------------------------------------------------------------------------------------------------|---------------------------| @@ -23,7 +23,7 @@ PICOCLAW_CONFIG=/etc/picoclaw/production.json picoclaw gateway # 在 /opt/picoclaw 中存储所有数据运行 picoclaw -# 配置将从默认的 ~/.picoclaw/config.json 加载 +# 配置将从 /opt/picoclaw/config.json 加载 # 工作区将在 /opt/picoclaw/workspace 创建 PICOCLAW_HOME=/opt/picoclaw picoclaw agent diff --git a/docs/guides/docker.fr.md b/docs/guides/docker.fr.md index 45b42d1b..c1c3a3e6 100644 --- a/docs/guides/docker.fr.md +++ b/docs/guides/docker.fr.md @@ -1,154 +1,5 @@ -# 🐳 Docker et Démarrage Rapide +# Docker builds for this fork -> Retour au [README](../../README.md) +The upstream image and provider setup instructions no longer apply. Build from this fork; do not pull the upstream Docker image. -## 🐳 Docker Compose - -Vous pouvez également exécuter PicoClaw avec Docker Compose sans rien installer localement. - -```bash -# 1. Cloner ce dépôt -git clone https://github.com/sipeed/picoclaw.git -cd picoclaw - -# 2. Premier lancement — génère automatiquement docker/data/config.json puis s'arrête -# (se déclenche uniquement quand config.json et workspace/ sont tous deux absents) -docker compose -f docker/docker-compose.yml --profile gateway up -# Le conteneur affiche "First-run setup complete." et s'arrête. - -# 3. Configurer vos clés API -vim docker/data/config.json # Set provider API keys, bot tokens, etc. - -# 4. Démarrer -docker compose -f docker/docker-compose.yml --profile gateway up -d -``` - -> [!TIP] -> **Utilisateurs Docker** : Par défaut, le Gateway écoute sur `127.0.0.1`, ce qui n'est pas accessible depuis l'hôte. Si vous devez accéder aux endpoints de santé ou exposer des ports, définissez `PICOCLAW_GATEWAY_HOST=0.0.0.0` dans votre environnement ou mettez à jour `config.json`. - -```bash -# 5. Vérifier les logs -docker compose -f docker/docker-compose.yml logs -f picoclaw-gateway - -# 6. Arrêter -docker compose -f docker/docker-compose.yml --profile gateway down -``` - -### Mode Agent (One-shot) - -```bash -# Poser une question -docker compose -f docker/docker-compose.yml run --rm picoclaw-agent -m "What is 2+2?" - -# Mode interactif -docker compose -f docker/docker-compose.yml run --rm picoclaw-agent -``` - -### Mise à jour - -```bash -docker compose -f docker/docker-compose.yml pull -docker compose -f docker/docker-compose.yml --profile gateway up -d -``` - -### 🚀 Démarrage Rapide - -> [!TIP] -> Configurez votre clé API dans `~/.picoclaw/config.json`. Obtenir des clés API : [Volcengine (CodingPlan)](https://www.volcengine.com/activity/codingplan?utm_campaign=PicoClaw&utm_content=PicoClaw&utm_medium=devrel&utm_source=OWO&utm_term=PicoClaw) (LLM) · [OpenRouter](https://openrouter.ai/keys) (LLM) · [Zhipu](https://open.bigmodel.cn/usercenter/proj-mgmt/apikeys) (LLM). La recherche web est optionnelle — obtenez gratuitement une [API Tavily](https://tavily.com) (1000 requêtes gratuites/mois) ou une [API Brave Search](https://brave.com/search/api) (2000 requêtes gratuites/mois). - -**1. Initialiser** - -```bash -picoclaw onboard -``` - -**2. Configurer** (`~/.picoclaw/config.json`) - -```json -{ - "agents": { - "defaults": { - "workspace": "~/.picoclaw/workspace", - "model_name": "gpt-5.4", - "max_tokens": 8192, - "temperature": 0.7, - "max_tool_iterations": 20 - } - }, - "model_list": [ - { - "model_name": "ark-code-latest", - "model": "volcengine/ark-code-latest", - "api_keys": ["sk-your-api-key"], - "api_base":"https://ark.cn-beijing.volces.com/api/coding/v3" - }, - { - "model_name": "gpt-5.4", - "model": "openai/gpt-5.4", - "api_keys": ["your-api-key"], - "request_timeout": 300 - }, - { - "model_name": "claude-sonnet-4.6", - "model": "anthropic/claude-sonnet-4.6", - "api_keys": ["your-anthropic-key"] - } - ], - "tools": { - "web": { - "enabled": true, - "fetch_limit_bytes": 10485760, - "format": "plaintext", - "brave": { - "enabled": false, - "api_key": "YOUR_BRAVE_API_KEY", - "max_results": 5 - }, - "tavily": { - "enabled": false, - "api_key": "YOUR_TAVILY_API_KEY", - "max_results": 5 - }, - "duckduckgo": { - "enabled": true, - "max_results": 5 - }, - "perplexity": { - "enabled": false, - "api_key": "YOUR_PERPLEXITY_API_KEY", - "max_results": 5 - }, - "searxng": { - "enabled": false, - "base_url": "http://your-searxng-instance:8888", - "max_results": 5 - } - } - } -} -``` - -> **Nouveau** : Le format de configuration `model_list` permet l'ajout de fournisseurs sans modification de code. Voir [Configuration des Modèles](#configuration-des-modèles-model_list) pour plus de détails. -> `request_timeout` est optionnel et utilise les secondes. S'il est omis ou défini à `<= 0`, PicoClaw utilise le timeout par défaut (120s). - -**3. Obtenir des clés API** - -* **Fournisseur LLM** : [OpenRouter](https://openrouter.ai/keys) · [Zhipu](https://open.bigmodel.cn/usercenter/proj-mgmt/apikeys) · [Anthropic](https://console.anthropic.com) · [OpenAI](https://platform.openai.com) · [Gemini](https://aistudio.google.com/api-keys) -* **Recherche Web** (optionnel) : - * [Brave Search](https://brave.com/search/api) - Payant ($5/1000 requêtes, ~$5-6/mois) - * [Perplexity](https://www.perplexity.ai) - Recherche alimentée par l'IA avec interface de chat - * [SearXNG](https://github.com/searxng/searxng) - Métamoteur auto-hébergé (gratuit, pas de clé API nécessaire) - * [Tavily](https://tavily.com) - Optimisé pour les agents IA (1000 requêtes/mois) - * DuckDuckGo - Solution de repli intégrée (pas de clé API requise) - -> **Note** : Voir `config.example.json` pour un modèle de configuration complet. - -**4. Discuter** - -```bash -picoclaw agent -m "What is 2+2?" -``` - -C'est tout ! Vous avez un assistant IA fonctionnel en 2 minutes. - ---- +See the maintained [Docker guide](docker.md) or [中文说明](docker.zh.md), and the [README](../../README.md). diff --git a/docs/guides/docker.ja.md b/docs/guides/docker.ja.md index a52c5dbe..c1c3a3e6 100644 --- a/docs/guides/docker.ja.md +++ b/docs/guides/docker.ja.md @@ -1,156 +1,5 @@ -# 🐳 Docker とクイックスタート +# Docker builds for this fork -> [README](../../README.md) に戻る +The upstream image and provider setup instructions no longer apply. Build from this fork; do not pull the upstream Docker image. -## 🐳 Docker Compose - -Docker Compose を使用して PicoClaw を実行できます。ローカルに何もインストールする必要はありません。 - -```bash -# 1. リポジトリをクローン -git clone https://github.com/sipeed/picoclaw.git -cd picoclaw - -# 2. 初回実行 — docker/data/config.json を自動生成して終了 -# (config.json と workspace/ の両方が存在しない場合のみ実行) -docker compose -f docker/docker-compose.yml --profile gateway up -# コンテナが "First-run setup complete." と表示して停止します - -# 3. API Key を設定 -vim docker/data/config.json # provider API key、Bot Token などを設定 - -# 4. 起動 -docker compose -f docker/docker-compose.yml --profile gateway up -d -``` - -> [!TIP] -> **Docker ユーザー**: デフォルトでは Gateway は `127.0.0.1` でリッスンしており、コンテナ外からはアクセスできません。ヘルスチェックエンドポイントへのアクセスやポート公開が必要な場合は、環境変数で `PICOCLAW_GATEWAY_HOST=0.0.0.0` を設定するか、`config.json` を更新してください。 - -```bash -# 5. ログを確認 -docker compose -f docker/docker-compose.yml logs -f picoclaw-gateway - -# 6. 停止 -docker compose -f docker/docker-compose.yml --profile gateway down -``` - -### Agent モード (ワンショット) - -```bash -# 質問する -docker compose -f docker/docker-compose.yml run --rm picoclaw-agent -m "2+2は?" - -# インタラクティブモード -docker compose -f docker/docker-compose.yml run --rm picoclaw-agent -``` - -### イメージの更新 - -```bash -docker compose -f docker/docker-compose.yml pull -docker compose -f docker/docker-compose.yml --profile gateway up -d -``` - ---- - -## 🚀 クイックスタート - -> [!TIP] -> `~/.picoclaw/config.json` に API Key を設定してください。API Key の取得先: [Volcengine (CodingPlan)](https://www.volcengine.com/activity/codingplan?utm_campaign=PicoClaw&utm_content=PicoClaw&utm_medium=devrel&utm_source=OWO&utm_term=PicoClaw) (LLM) · [OpenRouter](https://openrouter.ai/keys) (LLM) · [Zhipu](https://open.bigmodel.cn/usercenter/proj-mgmt/apikeys) (LLM)。Web 検索は**オプション**です — 無料の [Tavily API](https://tavily.com) (月 1000 回無料) または [Brave Search API](https://brave.com/search/api) (月 2000 回無料) を取得できます。 - -**1. 初期化** - -```bash -picoclaw onboard -``` - -**2. 設定** (`~/.picoclaw/config.json`) - -```json -{ - "agents": { - "defaults": { - "workspace": "~/.picoclaw/workspace", - "model_name": "gpt-5.4", - "max_tokens": 8192, - "temperature": 0.7, - "max_tool_iterations": 20 - } - }, - "model_list": [ - { - "model_name": "ark-code-latest", - "model": "volcengine/ark-code-latest", - "api_keys": ["sk-your-api-key"], - "api_base":"https://ark.cn-beijing.volces.com/api/coding/v3" - }, - { - "model_name": "gpt-5.4", - "model": "openai/gpt-5.4", - "api_keys": ["your-api-key"], - "request_timeout": 300 - }, - { - "model_name": "claude-sonnet-4.6", - "model": "anthropic/claude-sonnet-4.6", - "api_keys": ["your-anthropic-key"] - } - ], - "tools": { - "web": { - "enabled": true, - "fetch_limit_bytes": 10485760, - "format": "plaintext", - "brave": { - "enabled": false, - "api_key": "YOUR_BRAVE_API_KEY", - "max_results": 5 - }, - "tavily": { - "enabled": false, - "api_key": "YOUR_TAVILY_API_KEY", - "max_results": 5 - }, - "duckduckgo": { - "enabled": true, - "max_results": 5 - }, - "perplexity": { - "enabled": false, - "api_key": "YOUR_PERPLEXITY_API_KEY", - "max_results": 5 - }, - "searxng": { - "enabled": false, - "base_url": "http://your-searxng-instance:8888", - "max_results": 5 - } - } - } -} -``` - -> **新機能**: `model_list` 設定形式により、コード変更なしで provider を追加できます。詳細は[モデル設定](providers.ja.md#モデル設定-model_list)を参照してください。 -> `request_timeout` はオプションで、単位は秒です。省略または `<= 0` に設定した場合、PicoClaw はデフォルトのタイムアウト(120 秒)を使用します。 - -**3. API Key の取得** - -* **LLM プロバイダー**: [OpenRouter](https://openrouter.ai/keys) · [Zhipu](https://open.bigmodel.cn/usercenter/proj-mgmt/apikeys) · [Anthropic](https://console.anthropic.com) · [OpenAI](https://platform.openai.com) · [Gemini](https://aistudio.google.com/api-keys) -* **Web 検索** (オプション): - * [Brave Search](https://brave.com/search/api) - 有料 ($5/1000 queries, ~$5-6/month) - * [Perplexity](https://www.perplexity.ai) - AI 搭載の検索・チャットインターフェース - * [SearXNG](https://github.com/searxng/searxng) - セルフホスト型メタ検索エンジン(無料、API Key 不要) - * [Tavily](https://tavily.com) - AI Agent 向けに最適化 (1000 requests/month) - * DuckDuckGo - 組み込みフォールバック(API Key 不要) - -> **注意**: 完全な設定テンプレートは `config.example.json` を参照してください。 - -**4. チャット** - -```bash -picoclaw agent -m "2+2は?" -``` - -以上です!2 分で動作する AI アシスタントが手に入ります。 - ---- +See the maintained [Docker guide](docker.md) or [中文说明](docker.zh.md), and the [README](../../README.md). diff --git a/docs/guides/docker.md b/docs/guides/docker.md index d6200e46..40656cde 100644 --- a/docs/guides/docker.md +++ b/docs/guides/docker.md @@ -1,160 +1,38 @@ -# 🐳 Docker & Quick Start Guide +# Docker builds for this fork -> Back to [README](../README.md) +> Back to [README](../../README.md) -## 🐳 Docker Compose - -You can also run PicoClaw using Docker Compose without installing anything locally. +This fork does not publish Docker images. Build from this repository. The Compose image name `docker.io/sipeed/picoclaw:latest` is a historical local tag; pulling it downloads the upstream image. ```bash -# 1. Clone this repo -git clone https://github.com/sipeed/picoclaw.git +git clone https://github.com/loveuer/picoclaw.git cd picoclaw - -# 2. First run — auto-generates docker/data/config.json then exits -# (only triggers when both config.json and workspace/ are missing) -docker compose -f docker/docker-compose.yml --profile gateway up -# The container prints "First-run setup complete." and stops. - -# 3. Set your API keys -vim docker/data/config.json # Set provider API keys, bot tokens, etc. - -# 4. Start -docker compose -f docker/docker-compose.yml --profile gateway up -d +docker compose -f docker/docker-compose.yml --profile gateway build +docker compose -f docker/docker-compose.yml run --rm \ + --entrypoint picoclaw picoclaw-agent onboard ``` -> [!TIP] -> **Docker Users**: By default, the Gateway listens on `127.0.0.1` which is not accessible from the host. If you need to access the health endpoints or expose ports, set `PICOCLAW_GATEWAY_HOST=0.0.0.0` in your environment or update `config.json`. - -> [!NOTE] -> The `gateway` profile only serves the webhook handlers and health endpoints on the gateway port, so it does not expose generic REST chat endpoints such as `/chat` or `/a2a`. +Edit `docker/data/config.json` and, where applicable, `docker/data/.security.yml`. Configure an OpenAI or Anthropic model and enable the required channels. Use `channel_list..settings` for channel-specific fields. See the [configuration example](../../config/config.example.json) and [provider guide](providers.md). ```bash -# 5. Check logs +docker compose -f docker/docker-compose.yml --profile gateway up -d --no-build --pull never docker compose -f docker/docker-compose.yml logs -f picoclaw-gateway - -# 6. Stop docker compose -f docker/docker-compose.yml --profile gateway down + +# CLI instead of Gateway +docker compose -f docker/docker-compose.yml run --rm --pull never picoclaw-agent -m "Hello" ``` -### Agent Mode (One-shot) +`docker/data/` is mounted at `/root/.picoclaw`; stopping the container preserves it. Gateway binds locally within the container by default, and Compose does not publish its port. Accessing `/health` or `/ready` from the host requires both `gateway.host: "0.0.0.0"` and a port mapping. There is no WebUI or generic REST chat endpoint. + +After updating the local source, rebuild and start the container again: ```bash -# Ask a question -docker compose -f docker/docker-compose.yml run --rm picoclaw-agent -m "What is 2+2?" - -# Interactive mode -docker compose -f docker/docker-compose.yml run --rm picoclaw-agent +git pull --ff-only +docker compose -f docker/docker-compose.yml --profile gateway build +docker compose -f docker/docker-compose.yml --profile gateway up -d --no-build --pull never ``` -### Update +Do not use `docker compose pull` to update this fork. Existing workspace Skills are not overwritten by image updates. The ordinary Gateway image does not provide Docker daemon access for the Office Skills; use a host deployment with the [dedicated Office runtime](office-skills.zh.md) when needed. -```bash -docker compose -f docker/docker-compose.yml pull -docker compose -f docker/docker-compose.yml --profile gateway up -d -``` - -### 🚀 Quick Start - -> [!TIP] -> Set your API Key in `~/.picoclaw/config.json`. Get API Keys: [Volcengine (CodingPlan)](https://www.volcengine.com/activity/codingplan?utm_campaign=PicoClaw&utm_content=PicoClaw&utm_medium=devrel&utm_source=OWO&utm_term=PicoClaw) (LLM) · [OpenRouter](https://openrouter.ai/keys) (LLM) · [Zhipu](https://open.bigmodel.cn/usercenter/proj-mgmt/apikeys) (LLM). Web search is optional — get a free [Tavily API](https://tavily.com) (1000 free queries/month) or [Brave Search API](https://brave.com/search/api) (2000 free queries/month). - -**1. Initialize** - -```bash -picoclaw onboard -``` - -**2. Configure** (`~/.picoclaw/config.json`) - -```json -{ - "agents": { - "defaults": { - "workspace": "~/.picoclaw/workspace", - "model_name": "gpt-5.4", - "max_tokens": 8192, - "temperature": 0.7, - "max_tool_iterations": 20 - } - }, - "model_list": [ - { - "model_name": "ark-code-latest", - "provider": "volcengine", - "model": "ark-code-latest", - "api_keys": ["sk-your-api-key"], - "api_base":"https://ark.cn-beijing.volces.com/api/coding/v3" - }, - { - "model_name": "gpt-5.4", - "provider": "openai", - "model": "gpt-5.4", - "api_keys": ["your-api-key"], - "request_timeout": 300 - }, - { - "model_name": "claude-sonnet-4.6", - "provider": "anthropic", - "model": "claude-sonnet-4.6", - "api_keys": ["your-anthropic-key"] - } - ], - "tools": { - "web": { - "enabled": true, - "fetch_limit_bytes": 10485760, - "format": "plaintext", - "brave": { - "enabled": false, - "api_key": "YOUR_BRAVE_API_KEY", - "max_results": 5 - }, - "tavily": { - "enabled": false, - "api_key": "YOUR_TAVILY_API_KEY", - "max_results": 5 - }, - "duckduckgo": { - "enabled": true, - "max_results": 5 - }, - "perplexity": { - "enabled": false, - "api_key": "YOUR_PERPLEXITY_API_KEY", - "max_results": 5 - }, - "searxng": { - "enabled": false, - "base_url": "http://your-searxng-instance:8888", - "max_results": 5 - } - } - } -} -``` - -> **New**: The `model_list` configuration format allows zero-code provider addition. See [Model Configuration](#model-configuration-model_list) for details. -> `request_timeout` is optional and uses seconds. If omitted or set to `<= 0`, PicoClaw uses the default timeout (120s). - -**3. Get API Keys** - -* **LLM Provider**: [OpenRouter](https://openrouter.ai/keys) · [Zhipu](https://open.bigmodel.cn/usercenter/proj-mgmt/apikeys) · [Anthropic](https://console.anthropic.com) · [OpenAI](https://platform.openai.com) · [Gemini](https://aistudio.google.com/api-keys) -* **Web Search** (optional): - * [Brave Search](https://brave.com/search/api) - Paid ($5/1000 queries, ~$5-6/month) - * [Perplexity](https://www.perplexity.ai) - AI-powered search with chat interface - * [SearXNG](https://github.com/searxng/searxng) - Self-hosted metasearch engine (free, no API key needed) - * [Tavily](https://tavily.com) - Optimized for AI Agents (1000 requests/month) - * DuckDuckGo - Built-in fallback (no API key required) - -> **Note**: See `config.example.json` for a complete configuration template. - -**4. Chat** - -```bash -picoclaw agent -m "What is 2+2?" -``` - -That's it! You have a working AI assistant in 2 minutes. - ---- +The full/heavy Docker variants remain local build options, outside the automated release workflow. See the [Chinese guide](docker.zh.md) for details. diff --git a/docs/guides/docker.ms.md b/docs/guides/docker.ms.md index 942a1aa4..c1c3a3e6 100644 --- a/docs/guides/docker.ms.md +++ b/docs/guides/docker.ms.md @@ -1,153 +1,5 @@ -# 🐳 Panduan Docker & Quick Start +# Docker builds for this fork -> Kembali ke [README](../../README.md) +The upstream image and provider setup instructions no longer apply. Build from this fork; do not pull the upstream Docker image. -## 🐳 Docker Compose - -Anda juga boleh menjalankan PicoClaw menggunakan Docker Compose tanpa memasang apa-apa secara setempat. - -```bash -# 1. Clone repo ini -git clone https://github.com/sipeed/picoclaw.git -cd picoclaw - -# 2. Larian pertama — jana docker/data/config.json secara automatik kemudian keluar -docker compose -f docker/docker-compose.yml --profile gateway up -# Container akan memaparkan "First-run setup complete." dan berhenti. - -# 3. Tetapkan kunci API anda -vim docker/data/config.json # Tetapkan API key penyedia, token bot, dan sebagainya. - -# 4. Mula -docker compose -f docker/docker-compose.yml --profile gateway up -d -``` - -> [!TIP] -> **Pengguna Docker**: Secara lalai, Gateway mendengar pada `127.0.0.1` yang tidak boleh diakses dari host. Jika anda perlu mengakses health endpoint atau mendedahkan port, tetapkan `PICOCLAW_GATEWAY_HOST=0.0.0.0` dalam persekitaran anda atau kemas kini `config.json`. - -```bash -# 5. Semak log -docker compose -f docker/docker-compose.yml logs -f picoclaw-gateway - -# 6. Hentikan -docker compose -f docker/docker-compose.yml --profile gateway down -``` - -### Mod Agent (One-shot) - -```bash -# Tanyakan soalan -docker compose -f docker/docker-compose.yml run --rm picoclaw-agent -m "What is 2+2?" - -# Mod interaktif -docker compose -f docker/docker-compose.yml run --rm picoclaw-agent -``` - -### Kemas kini - -```bash -docker compose -f docker/docker-compose.yml pull -docker compose -f docker/docker-compose.yml --profile gateway up -d -``` - -### 🚀 Quick Start - -> [!TIP] -> Tetapkan API Key anda dalam `~/.picoclaw/config.json`. Dapatkan API Key: [Volcengine (CodingPlan)](https://www.volcengine.com/activity/codingplan?utm_campaign=PicoClaw&utm_content=PicoClaw&utm_medium=devrel&utm_source=OWO&utm_term=PicoClaw) (LLM) · [OpenRouter](https://openrouter.ai/keys) (LLM) · [Zhipu](https://open.bigmodel.cn/usercenter/proj-mgmt/apikeys) (LLM). Carian web adalah pilihan — dapatkan [Tavily API](https://tavily.com) percuma (1000 pertanyaan percuma/bulan) atau [Brave Search API](https://brave.com/search/api) (2000 pertanyaan percuma/bulan). - -**1. Inisialisasi** - -```bash -picoclaw onboard -``` - -**2. Konfigurasi** (`~/.picoclaw/config.json`) - -```json -{ - "agents": { - "defaults": { - "workspace": "~/.picoclaw/workspace", - "model_name": "gpt-5.4", - "max_tokens": 8192, - "temperature": 0.7, - "max_tool_iterations": 20 - } - }, - "model_list": [ - { - "model_name": "ark-code-latest", - "model": "volcengine/ark-code-latest", - "api_keys": ["sk-your-api-key"], - "api_base":"https://ark.cn-beijing.volces.com/api/coding/v3" - }, - { - "model_name": "gpt-5.4", - "model": "openai/gpt-5.4", - "api_keys": ["your-api-key"], - "request_timeout": 300 - }, - { - "model_name": "claude-sonnet-4.6", - "model": "anthropic/claude-sonnet-4.6", - "api_keys": ["your-anthropic-key"] - } - ], - "tools": { - "web": { - "enabled": true, - "fetch_limit_bytes": 10485760, - "format": "plaintext", - "brave": { - "enabled": false, - "api_key": "YOUR_BRAVE_API_KEY", - "max_results": 5 - }, - "tavily": { - "enabled": false, - "api_key": "YOUR_TAVILY_API_KEY", - "max_results": 5 - }, - "duckduckgo": { - "enabled": true, - "max_results": 5 - }, - "perplexity": { - "enabled": false, - "api_key": "YOUR_PERPLEXITY_API_KEY", - "max_results": 5 - }, - "searxng": { - "enabled": false, - "base_url": "http://your-searxng-instance:8888", - "max_results": 5 - } - } - } -} -``` - -> **Baharu**: Format konfigurasi `model_list` membolehkan penambahan penyedia tanpa perubahan kod. Lihat [Konfigurasi Model](#konfigurasi-model-model_list) untuk butiran. -> `request_timeout` adalah pilihan dan menggunakan saat. Jika diabaikan atau ditetapkan kepada `<= 0`, PicoClaw menggunakan timeout lalai (120s). - -**3. Dapatkan API Key** - -* **Penyedia LLM**: [OpenRouter](https://openrouter.ai/keys) · [Zhipu](https://open.bigmodel.cn/usercenter/proj-mgmt/apikeys) · [Anthropic](https://console.anthropic.com) · [OpenAI](https://platform.openai.com) · [Gemini](https://aistudio.google.com/api-keys) -* **Carian Web** (pilihan): - * [Brave Search](https://brave.com/search/api) - Berbayar ($5/1000 pertanyaan, ~$5-6/bulan) - * [Perplexity](https://www.perplexity.ai) - Carian berkuasa AI dengan antara muka sembang - * [SearXNG](https://github.com/searxng/searxng) - Enjin meta-carian hos kendiri (percuma, tidak perlu API key) - * [Tavily](https://tavily.com) - Dioptimumkan untuk AI Agents (1000 permintaan/bulan) - * DuckDuckGo - Fallback terbina dalam (tidak memerlukan API key) - -> **Nota**: Lihat `config.example.json` untuk templat konfigurasi penuh. - -**4. Sembang** - -```bash -picoclaw agent -m "What is 2+2?" -``` - -Itu sahaja! Anda kini mempunyai pembantu AI yang berfungsi dalam masa 2 minit. - ---- +See the maintained [Docker guide](docker.md) or [中文说明](docker.zh.md), and the [README](../../README.md). diff --git a/docs/guides/docker.pt-br.md b/docs/guides/docker.pt-br.md index 0fb8a9dd..c1c3a3e6 100644 --- a/docs/guides/docker.pt-br.md +++ b/docs/guides/docker.pt-br.md @@ -1,154 +1,5 @@ -# 🐳 Docker e Início Rápido +# Docker builds for this fork -> Voltar ao [README](../../README.md) +The upstream image and provider setup instructions no longer apply. Build from this fork; do not pull the upstream Docker image. -## 🐳 Docker Compose - -Você também pode executar o PicoClaw usando Docker Compose sem instalar nada localmente. - -```bash -# 1. Clone este repositório -git clone https://github.com/sipeed/picoclaw.git -cd picoclaw - -# 2. Primeira execução — gera automaticamente docker/data/config.json e encerra -# (só é acionado quando config.json e workspace/ estão ambos ausentes) -docker compose -f docker/docker-compose.yml --profile gateway up -# O contêiner exibe "First-run setup complete." e para. - -# 3. Configure suas chaves de API -vim docker/data/config.json # Set provider API keys, bot tokens, etc. - -# 4. Iniciar -docker compose -f docker/docker-compose.yml --profile gateway up -d -``` - -> [!TIP] -> **Usuários Docker**: Por padrão, o Gateway escuta em `127.0.0.1`, que não é acessível a partir do host. Se você precisar acessar os endpoints de saúde ou expor portas, defina `PICOCLAW_GATEWAY_HOST=0.0.0.0` no seu ambiente ou atualize o `config.json`. - -```bash -# 5. Verificar logs -docker compose -f docker/docker-compose.yml logs -f picoclaw-gateway - -# 6. Parar -docker compose -f docker/docker-compose.yml --profile gateway down -``` - -### Modo Agent (One-shot) - -```bash -# Fazer uma pergunta -docker compose -f docker/docker-compose.yml run --rm picoclaw-agent -m "What is 2+2?" - -# Modo interativo -docker compose -f docker/docker-compose.yml run --rm picoclaw-agent -``` - -### Atualização - -```bash -docker compose -f docker/docker-compose.yml pull -docker compose -f docker/docker-compose.yml --profile gateway up -d -``` - -### 🚀 Início Rápido - -> [!TIP] -> Configure sua chave de API em `~/.picoclaw/config.json`. Obtenha chaves de API: [Volcengine (CodingPlan)](https://www.volcengine.com/activity/codingplan?utm_campaign=PicoClaw&utm_content=PicoClaw&utm_medium=devrel&utm_source=OWO&utm_term=PicoClaw) (LLM) · [OpenRouter](https://openrouter.ai/keys) (LLM) · [Zhipu](https://open.bigmodel.cn/usercenter/proj-mgmt/apikeys) (LLM). A busca na web é opcional — obtenha gratuitamente uma [API Tavily](https://tavily.com) (1000 consultas gratuitas/mês) ou [API Brave Search](https://brave.com/search/api) (2000 consultas gratuitas/mês). - -**1. Inicializar** - -```bash -picoclaw onboard -``` - -**2. Configurar** (`~/.picoclaw/config.json`) - -```json -{ - "agents": { - "defaults": { - "workspace": "~/.picoclaw/workspace", - "model_name": "gpt-5.4", - "max_tokens": 8192, - "temperature": 0.7, - "max_tool_iterations": 20 - } - }, - "model_list": [ - { - "model_name": "ark-code-latest", - "model": "volcengine/ark-code-latest", - "api_keys": ["sk-your-api-key"], - "api_base":"https://ark.cn-beijing.volces.com/api/coding/v3" - }, - { - "model_name": "gpt-5.4", - "model": "openai/gpt-5.4", - "api_keys": ["your-api-key"], - "request_timeout": 300 - }, - { - "model_name": "claude-sonnet-4.6", - "model": "anthropic/claude-sonnet-4.6", - "api_keys": ["your-anthropic-key"] - } - ], - "tools": { - "web": { - "enabled": true, - "fetch_limit_bytes": 10485760, - "format": "plaintext", - "brave": { - "enabled": false, - "api_key": "YOUR_BRAVE_API_KEY", - "max_results": 5 - }, - "tavily": { - "enabled": false, - "api_key": "YOUR_TAVILY_API_KEY", - "max_results": 5 - }, - "duckduckgo": { - "enabled": true, - "max_results": 5 - }, - "perplexity": { - "enabled": false, - "api_key": "YOUR_PERPLEXITY_API_KEY", - "max_results": 5 - }, - "searxng": { - "enabled": false, - "base_url": "http://your-searxng-instance:8888", - "max_results": 5 - } - } - } -} -``` - -> **Novo**: O formato de configuração `model_list` permite adicionar provedores sem alteração de código. Veja [Configuração de Modelos](#configuração-de-modelos-model_list) para detalhes. -> `request_timeout` é opcional e usa segundos. Se omitido ou definido como `<= 0`, o PicoClaw usa o timeout padrão (120s). - -**3. Obter chaves de API** - -* **Provedor LLM**: [OpenRouter](https://openrouter.ai/keys) · [Zhipu](https://open.bigmodel.cn/usercenter/proj-mgmt/apikeys) · [Anthropic](https://console.anthropic.com) · [OpenAI](https://platform.openai.com) · [Gemini](https://aistudio.google.com/api-keys) -* **Busca na Web** (opcional): - * [Brave Search](https://brave.com/search/api) - Pago ($5/1000 consultas, ~$5-6/mês) - * [Perplexity](https://www.perplexity.ai) - Busca com IA e interface de chat - * [SearXNG](https://github.com/searxng/searxng) - Metabuscador auto-hospedado (gratuito, sem necessidade de chave de API) - * [Tavily](https://tavily.com) - Otimizado para agentes de IA (1000 requisições/mês) - * DuckDuckGo - Fallback integrado (sem necessidade de chave de API) - -> **Nota**: Veja `config.example.json` para um modelo de configuração completo. - -**4. Conversar** - -```bash -picoclaw agent -m "What is 2+2?" -``` - -Pronto! Você tem um assistente de IA funcionando em 2 minutos. - ---- +See the maintained [Docker guide](docker.md) or [中文说明](docker.zh.md), and the [README](../../README.md). diff --git a/docs/guides/docker.vi.md b/docs/guides/docker.vi.md index d31f8436..c1c3a3e6 100644 --- a/docs/guides/docker.vi.md +++ b/docs/guides/docker.vi.md @@ -1,154 +1,5 @@ -# 🐳 Docker và Bắt Đầu Nhanh +# Docker builds for this fork -> Quay lại [README](../../README.md) +The upstream image and provider setup instructions no longer apply. Build from this fork; do not pull the upstream Docker image. -## 🐳 Docker Compose - -Bạn cũng có thể chạy PicoClaw bằng Docker Compose mà không cần cài đặt gì trên máy. - -```bash -# 1. Clone repo này -git clone https://github.com/sipeed/picoclaw.git -cd picoclaw - -# 2. Lần chạy đầu tiên — tự động tạo docker/data/config.json rồi thoát -# (chỉ kích hoạt khi cả config.json và workspace/ đều không tồn tại) -docker compose -f docker/docker-compose.yml --profile gateway up -# Container hiển thị "First-run setup complete." và dừng lại. - -# 3. Cấu hình API key của bạn -vim docker/data/config.json # Set provider API keys, bot tokens, etc. - -# 4. Khởi động -docker compose -f docker/docker-compose.yml --profile gateway up -d -``` - -> [!TIP] -> **Người dùng Docker**: Mặc định, Gateway lắng nghe trên `127.0.0.1`, không thể truy cập từ host. Nếu bạn cần truy cập các health endpoint hoặc mở port, hãy đặt `PICOCLAW_GATEWAY_HOST=0.0.0.0` trong môi trường hoặc cập nhật `config.json`. - -```bash -# 5. Kiểm tra log -docker compose -f docker/docker-compose.yml logs -f picoclaw-gateway - -# 6. Dừng -docker compose -f docker/docker-compose.yml --profile gateway down -``` - -### Chế Độ Agent (One-shot) - -```bash -# Đặt câu hỏi -docker compose -f docker/docker-compose.yml run --rm picoclaw-agent -m "What is 2+2?" - -# Chế độ tương tác -docker compose -f docker/docker-compose.yml run --rm picoclaw-agent -``` - -### Cập Nhật - -```bash -docker compose -f docker/docker-compose.yml pull -docker compose -f docker/docker-compose.yml --profile gateway up -d -``` - -### 🚀 Bắt Đầu Nhanh - -> [!TIP] -> Cấu hình API Key trong `~/.picoclaw/config.json`. Lấy API Key: [Volcengine (CodingPlan)](https://www.volcengine.com/activity/codingplan?utm_campaign=PicoClaw&utm_content=PicoClaw&utm_medium=devrel&utm_source=OWO&utm_term=PicoClaw) (LLM) · [OpenRouter](https://openrouter.ai/keys) (LLM) · [Zhipu](https://open.bigmodel.cn/usercenter/proj-mgmt/apikeys) (LLM). Tìm kiếm web là tùy chọn — lấy miễn phí [Tavily API](https://tavily.com) (1000 truy vấn miễn phí/tháng) hoặc [Brave Search API](https://brave.com/search/api) (2000 truy vấn miễn phí/tháng). - -**1. Khởi tạo** - -```bash -picoclaw onboard -``` - -**2. Cấu hình** (`~/.picoclaw/config.json`) - -```json -{ - "agents": { - "defaults": { - "workspace": "~/.picoclaw/workspace", - "model_name": "gpt-5.4", - "max_tokens": 8192, - "temperature": 0.7, - "max_tool_iterations": 20 - } - }, - "model_list": [ - { - "model_name": "ark-code-latest", - "model": "volcengine/ark-code-latest", - "api_keys": ["sk-your-api-key"], - "api_base":"https://ark.cn-beijing.volces.com/api/coding/v3" - }, - { - "model_name": "gpt-5.4", - "model": "openai/gpt-5.4", - "api_keys": ["your-api-key"], - "request_timeout": 300 - }, - { - "model_name": "claude-sonnet-4.6", - "model": "anthropic/claude-sonnet-4.6", - "api_keys": ["your-anthropic-key"] - } - ], - "tools": { - "web": { - "enabled": true, - "fetch_limit_bytes": 10485760, - "format": "plaintext", - "brave": { - "enabled": false, - "api_key": "YOUR_BRAVE_API_KEY", - "max_results": 5 - }, - "tavily": { - "enabled": false, - "api_key": "YOUR_TAVILY_API_KEY", - "max_results": 5 - }, - "duckduckgo": { - "enabled": true, - "max_results": 5 - }, - "perplexity": { - "enabled": false, - "api_key": "YOUR_PERPLEXITY_API_KEY", - "max_results": 5 - }, - "searxng": { - "enabled": false, - "base_url": "http://your-searxng-instance:8888", - "max_results": 5 - } - } - } -} -``` - -> **Mới**: Định dạng cấu hình `model_list` cho phép thêm provider mà không cần thay đổi code. Xem [Cấu Hình Mô Hình](#cấu-hình-mô-hình-model_list) để biết chi tiết. -> `request_timeout` là tùy chọn và tính bằng giây. Nếu bỏ qua hoặc đặt `<= 0`, PicoClaw sử dụng timeout mặc định (120s). - -**3. Lấy API Key** - -* **Nhà cung cấp LLM**: [OpenRouter](https://openrouter.ai/keys) · [Zhipu](https://open.bigmodel.cn/usercenter/proj-mgmt/apikeys) · [Anthropic](https://console.anthropic.com) · [OpenAI](https://platform.openai.com) · [Gemini](https://aistudio.google.com/api-keys) -* **Tìm kiếm Web** (tùy chọn): - * [Brave Search](https://brave.com/search/api) - Trả phí ($5/1000 truy vấn, ~$5-6/tháng) - * [Perplexity](https://www.perplexity.ai) - Tìm kiếm bằng AI với giao diện chat - * [SearXNG](https://github.com/searxng/searxng) - Công cụ tìm kiếm tổng hợp tự host (miễn phí, không cần API key) - * [Tavily](https://tavily.com) - Tối ưu cho AI Agent (1000 yêu cầu/tháng) - * DuckDuckGo - Fallback tích hợp (không cần API key) - -> **Lưu ý**: Xem `config.example.json` để có mẫu cấu hình đầy đủ. - -**4. Chat** - -```bash -picoclaw agent -m "What is 2+2?" -``` - -Vậy là xong! Bạn có một trợ lý AI hoạt động trong 2 phút. - ---- +See the maintained [Docker guide](docker.md) or [中文说明](docker.zh.md), and the [README](../../README.md). diff --git a/docs/guides/docker.zh.md b/docs/guides/docker.zh.md index aa6999da..2370c49d 100644 --- a/docs/guides/docker.zh.md +++ b/docs/guides/docker.zh.md @@ -1,159 +1,54 @@ -# 🐳 Docker 与快速开始 +# Docker 本地构建与运行 > 返回 [README](../../README.md) -## 🐳 Docker Compose +本 fork 没有发布 Docker 镜像。必须从本仓库构建,避免拉取上游镜像后运行已移除的功能或不同的配置格式。Compose 中的 `docker.io/sipeed/picoclaw:latest` 是历史遗留的本地镜像标签,不代表本 fork 的发布源。 -您也可以使用 Docker Compose 运行 PicoClaw,无需在本地安装任何环境。 +## 初始化 + +需要 Git、Docker 和 Compose 插件。从仓库根目录运行: ```bash -# 1. 克隆仓库 -git clone https://github.com/sipeed/picoclaw.git +git clone https://github.com/loveuer/picoclaw.git cd picoclaw +docker compose -f docker/docker-compose.yml --profile gateway build -# 2. 首次运行 — 自动生成 docker/data/config.json 后退出 -# (仅在 config.json 和 workspace/ 都不存在时触发) -docker compose -f docker/docker-compose.yml --profile gateway up -# 容器打印 "First-run setup complete." 后自动停止 - -# 3. 填写 API Key 等配置 -vim docker/data/config.json # 设置 provider API key、Bot Token 等 - -# 4. 正式启动 -docker compose -f docker/docker-compose.yml --profile gateway up -d +# 初始化 docker/data/ 中的配置和工作区,不启动 Gateway +# 已有配置时请按 onboard 的提示处理 +docker compose -f docker/docker-compose.yml run --rm \ + --entrypoint picoclaw picoclaw-agent onboard ``` -> [!TIP] -> **Docker 用户**: 默认情况下, Gateway 监听 `127.0.0.1`,该端口不会暴露到容器外。如果需要通过端口映射访问健康检查接口,请在环境变量中设置 `PICOCLAW_GATEWAY_HOST=0.0.0.0` 或修改 `config.json`。 +编辑 `docker/data/config.json`,按照[模型配置](providers.zh.md)设置 OpenAI 或 Anthropic 模型,并启用需要的渠道。密钥也可能保存在 `docker/data/.security.yml`,该文件中的同名值会覆盖主配置。 + +当前格式是 `channel_list.<名称>.settings`,参见 [完整配置示例](../../config/config.example.json)。 + +## 运行 ```bash -# 5. 查看日志 +# 只使用刚才在本地构建的镜像 +docker compose -f docker/docker-compose.yml --profile gateway up -d --no-build --pull never + docker compose -f docker/docker-compose.yml logs -f picoclaw-gateway - -# 6. 停止 docker compose -f docker/docker-compose.yml --profile gateway down + +# 单次提问或交互式 CLI +docker compose -f docker/docker-compose.yml run --rm --pull never picoclaw-agent -m "2+2 等于几?" +docker compose -f docker/docker-compose.yml run --rm --pull never picoclaw-agent ``` -### Agent 模式 (一次性运行) +数据目录 `docker/data/` 挂载到容器内的 `/root/.picoclaw`,停止容器不会删除配置和工作区。Gateway 默认监听容器内的本地地址,Compose 未发布端口;如需从宿主机访问 `/health`、`/ready`,需同时设置 `gateway.host: "0.0.0.0"` 和所需的端口映射。没有 WebUI 或通用 REST 聊天接口。 + +## 更新 + +更新本地源码后重新构建并启动,保留 `docker/data/`: ```bash -# 提问 -docker compose -f docker/docker-compose.yml run --rm picoclaw-agent -m "2+2 等于几?" - -# 交互模式 -docker compose -f docker/docker-compose.yml run --rm picoclaw-agent +git pull --ff-only +docker compose -f docker/docker-compose.yml --profile gateway build +docker compose -f docker/docker-compose.yml --profile gateway up -d --no-build --pull never ``` -### 更新镜像 +不要用 `docker compose pull` 更新本 fork,它会拉取历史标签对应的上游镜像。已有工作区的内置 Skill 不会随镜像更新自动覆盖,参见[办公 Skills](office-skills.zh.md)。当前普通 Gateway 镜像没有为办公 Skill 配置 Docker daemon 访问;需要办公能力时,优先按主 README 在宿主机部署并单独准备办公环境。 -```bash -docker compose -f docker/docker-compose.yml pull -docker compose -f docker/docker-compose.yml --profile gateway up -d -``` - ---- - -## 🚀 快速开始 - -> [!TIP] -> 在 `~/.picoclaw/config.json` 中设置您的 API Key。获取 API Key: [火山引擎 (CodingPlan)](https://www.volcengine.com/activity/codingplan?utm_campaign=PicoClaw&utm_content=PicoClaw&utm_medium=devrel&utm_source=OWO&utm_term=PicoClaw) (LLM) · [OpenRouter](https://openrouter.ai/keys) (LLM) · [Zhipu (智谱)](https://open.bigmodel.cn/usercenter/proj-mgmt/apikeys) (LLM)。网络搜索是 **可选的** — 获取免费的 [Tavily API](https://tavily.com) (每月 1000 次免费查询) 或 [Brave Search API](https://brave.com/search/api) (每月 2000 次免费查询)。 - -**1. 初始化 (Initialize)** - -```bash -picoclaw onboard -``` - -**2. 配置 (Configure)** (`~/.picoclaw/config.json`) - -```json -{ - "agents": { - "defaults": { - "workspace": "~/.picoclaw/workspace", - "model_name": "gpt-5.4", - "max_tokens": 8192, - "temperature": 0.7, - "max_tool_iterations": 20 - } - }, - "model_list": [ - { - "model_name": "ark-code-latest", - "provider": "volcengine", - "model": "ark-code-latest", - "api_keys": ["sk-your-api-key"], - "api_base":"https://ark.cn-beijing.volces.com/api/coding/v3" - }, - { - "model_name": "gpt-5.4", - "provider": "openai", - "model": "gpt-5.4", - "api_keys": ["your-api-key"], - "request_timeout": 300 - }, - { - "model_name": "claude-sonnet-4.6", - "provider": "anthropic", - "model": "claude-sonnet-4.6", - "api_keys": ["your-anthropic-key"] - } - ], - "tools": { - "web": { - "enabled": true, - "fetch_limit_bytes": 10485760, - "format": "plaintext", - "brave": { - "enabled": false, - "api_key": "YOUR_BRAVE_API_KEY", - "max_results": 5 - }, - "tavily": { - "enabled": false, - "api_key": "YOUR_TAVILY_API_KEY", - "max_results": 5 - }, - "duckduckgo": { - "enabled": true, - "max_results": 5 - }, - "perplexity": { - "enabled": false, - "api_key": "YOUR_PERPLEXITY_API_KEY", - "max_results": 5 - }, - "searxng": { - "enabled": false, - "base_url": "http://your-searxng-instance:8888", - "max_results": 5 - } - } - } -} -``` - -> **新功能**: `model_list` 配置格式支持零代码添加 provider。详见[模型配置](providers.zh.md#模型配置-model_list)章节。 -> `request_timeout` 为可选项,单位为秒。若省略或设置为 `<= 0`,PicoClaw 使用默认超时(120 秒)。 - -**3. 获取 API Key** - -* **LLM 提供商**: [OpenRouter](https://openrouter.ai/keys) · [Zhipu](https://open.bigmodel.cn/usercenter/proj-mgmt/apikeys) · [Anthropic](https://console.anthropic.com) · [OpenAI](https://platform.openai.com) · [Gemini](https://aistudio.google.com/api-keys) -* **网络搜索** (可选): - * [Brave Search](https://brave.com/search/api) - 付费 ($5/1000 次查询,约 $5-6/月) - * [Perplexity](https://www.perplexity.ai) - AI 驱动的搜索与聊天界面 - * [SearXNG](https://github.com/searxng/searxng) - 自建元搜索引擎(免费,无需 API Key) - * [Tavily](https://tavily.com) - 专为 AI Agent 优化 (1000 请求/月) - * DuckDuckGo - 内置回退(无需 API Key) - -> **注意**: 完整的配置模板请参考 `config.example.json`。 - -**4. 对话 (Chat)** - -```bash -picoclaw agent -m "2+2 等于几?" -``` - -就是这样!您在 2 分钟内就拥有了一个可工作的 AI 助手。 - ---- +本地仍保留 full/heavy 镜像构建变体,是否收敛这些变体是后续维护事项;它们不属于自动发布产物。 diff --git a/docs/guides/hardware-compatibility.fr.md b/docs/guides/hardware-compatibility.fr.md index defbf849..c85125a6 100644 --- a/docs/guides/hardware-compatibility.fr.md +++ b/docs/guides/hardware-compatibility.fr.md @@ -1,151 +1,5 @@ -> Retour au [README](../../README.md) +# Platforms and hardware boundaries -# 🖥️ PicoClaw Liste de compatibilité matérielle +The upstream device list and download instructions no longer describe this fork. -PicoClaw fonctionne sur pratiquement n'importe quel appareil Linux. Cette page répertorie les puces, produits et cartes de développement vérifiés. - -**Votre matériel n'est pas listé ?** Soumettez une PR pour l'ajouter ! Les fabricants de matériel sont invités à contribuer et à co-promouvoir. - ---- - -## 1. Support de puces vérifié - -### x86 - -| Fabricant | Puce | Notes | -|-----------|------|-------| -| Intel | Any x86 CPU (i386+) | Tous les processeurs de bureau/serveur/portable | -| AMD | Any x86 CPU | Tous les processeurs de bureau/serveur/portable | - -### ARM - -| Sous-arch | Puces typiques | Notes | -|-----------|----------------|-------| -| ARMv6 | [BCM2835](https://www.raspberrypi.com/documentation/computers/processors.html#bcm2835) (Raspberry Pi 1/Zero) | Monocœur ARM1176JZF-S | -| ARMv7 | [Allwinner V3s](https://linux-sunxi.org/V3s) | Monocœur Cortex-A7, utilisé dans LicheePi Zero | -| ARM64 | [Allwinner H618](https://linux-sunxi.org/H618) | Quadricœur Cortex-A53, utilisé dans Orange Pi Zero 3 | -| ARM64 | [BCM2711](https://www.raspberrypi.com/documentation/computers/processors.html#bcm2711) (Raspberry Pi 4) | Quadricœur Cortex-A72 | -| ARM64 | [BCM2712](https://www.raspberrypi.com/documentation/computers/processors.html#bcm2712) (Raspberry Pi 5) | Quadricœur Cortex-A76 | -| ARM64 | [AX630C](https://www.axera-tech.com/) (爱芯元智) | Bicœur Cortex-A53 + NPU, utilisé dans NanoKVM-Pro / MaixCAM2 | - -### RISC-V (riscv64) - -| Fabricant | Puce | Cœur | Notes | -|-----------|------|------|-------| -| [SOPHGO (算能)](https://www.sophgo.com/) | SG2002 | C906 @ 1GHz | 256MB DDR3 intégré, utilisé dans LicheeRV-Nano / NanoKVM / MaixCAM | -| [Allwinner (全志)](https://www.allwinnertech.com/) | V861 | Dual C907 | 128MB DDR3L intégré, 1 TOPS NPU, caméra AI 4K SiP | -| [Allwinner (全志)](https://www.allwinnertech.com/) | V881 | C907 | Série de caméras AI RISC-V | -| [Arterytek (匠芯创)](https://www.arterytek.com/) | D213 | RISC-V | Utilisé dans HaaS506-LD1 RTU industriel | -| [SpacemiT (进迭)](https://www.spacemit.com/) | K1 | 8x X60 @ 1.8GHz | Utilisé dans Milk-V Jupiter, BananaPi BPI-F3 | -| [SpacemiT (进迭)](https://www.spacemit.com/) | K3 | 8x X100 @ 2.5GHz | Conforme RVA23, RVV 1024 bits, inférence AI FP8 | -| [Zhihe (知合)](https://www.zhihe-tech.com/) | A210 | High-perf RISC-V | 8 cœurs, 16MB cache L3, classe bureau | -| [Canaan (嘉楠)](https://www.canaan-creative.com/) | K230 | Dual C908 @ 1.6GHz | 6 TOPS KPU, utilisé dans CanMV-K230 | - -### MIPS - -| Fabricant | Puce | Notes | -|-----------|------|-------| -| MediaTek | [MT7620](https://www.mediatek.com/products/home-networking/mt7620) | MIPS24KEc @ 580MHz, utilisé dans de nombreux routeurs OpenWrt (ex. Xiaomi Router 3G) | - -### LoongArch (loong64) - -| Fabricant | Puce | Notes | -|-----------|------|-------| -| [Loongson (龙芯)](https://www.loongson.cn/) | 3A5000 | Quadricœur LA464 @ 2.5GHz, bureau/station de travail | -| [Loongson (龙芯)](https://www.loongson.cn/) | 3A6000 | Quadricœur 4C/8T @ 2.5GHz, IPC comparable à Intel 10e génération | -| [Loongson (龙芯)](https://www.loongson.cn/) | 2K1000LA | Bicœur @ 1GHz, applications industrielles/IoT | - ---- - -## 2. Produits vérifiés (par date de sortie) - -Produits grand public, routeurs et appareils industriels testés avec PicoClaw. - -| Année | Produit | Arch | SoC | RAM | Catégorie | -|-------|---------|------|-----|-----|-----------| -| 2009 | Nokia N900 | ARM (A8) | OMAP3430 | 256MB | Smartphone | -| 2012 | Samsung Galaxy Note 10.1 (N8000) | ARM (A9) | Exynos 4412 | 2GB | Tablette | -| 2016 | Xiaomi Router 3G (小米路由器3G) | MIPS | MT7620 | 256MB | Routeur (OpenWrt) | -| 2018 | Phicomm N1 (斐讯N1) | ARM64 (A53) | S905D | 2GB | Boîtier TV / Serveur domestique | -| 2019 | Xiaomi AI Speaker (小爱音箱) | ARM64 (A53) | — | 256MB | Enceinte connectée | -| 2024 | [NanoKVM](https://wiki.sipeed.com/hardware/en/kvm/NanoKVM/introduction.html) | RISC-V | SG2002 | 256MB | IP-KVM | -| 2025 | HaaS506-LD1 | RISC-V | D213 | 128MB | RTU industriel | -| 2025 | [NanoKVM-Pro](https://wiki.sipeed.com/hardware/en/kvm/NanoKVM_Pro/introduction.html) | ARM64 (A53) | AX630C | 1GB | IP-KVM Pro | -| 2026 | [MaixCAM2](https://wiki.sipeed.com/hardware/en/maixcam/index.html) | ARM64 (A53) | AX630C | 1/4GB | Caméra AI 4K | - ---- - -## 3. Cartes de développement vérifiées (par date de sortie) - -| Année | Carte | Arch | SoC | RAM | Lien d'achat | -|-------|-------|------|-----|-----|--------------| -| 2012 | [Raspberry Pi 1 Model B](https://www.raspberrypi.com/products/) | ARMv6 | BCM2835 | 512MB | — | -| 2015 | [Raspberry Pi 2 Model B](https://www.raspberrypi.com/products/raspberry-pi-2-model-b/) | ARMv7 (A7) | BCM2836 | 1GB | — | -| 2015 | [Raspberry Pi Zero](https://www.raspberrypi.com/products/raspberry-pi-zero/) | ARMv6 | BCM2835 | 512MB | — | -| 2016 | [Raspberry Pi 3 Model B](https://www.raspberrypi.com/products/raspberry-pi-3-model-b/) | ARM64 (A53) | BCM2837 | 1GB | — | -| 2017 | [LicheePi Zero](https://wiki.sipeed.com/hardware/en/lichee/Zero/Zero.html) | ARMv7 (A7) | Allwinner V3s | 64MB | [Sipeed](https://sipeed.com/) | -| 2019 | [Raspberry Pi 4 Model B](https://www.raspberrypi.com/products/raspberry-pi-4-model-b/) | ARM64 (A72) | BCM2711 | 1~8GB | [RPi](https://www.raspberrypi.com/) | -| 2023 | [Raspberry Pi 5](https://www.raspberrypi.com/products/raspberry-pi-5/) | ARM64 (A76) | BCM2712 | 2~8GB | [RPi](https://www.raspberrypi.com/) | -| 2024 | [LicheeRV-Nano](https://wiki.sipeed.com/hardware/en/lichee/RV_Nano/1_intro.html) | RISC-V | SG2002 | 256MB | [AliExpress](https://www.aliexpress.com/item/1005006519668532.html) | -| 2024 | [MaixCAM-Pro](https://wiki.sipeed.com/hardware/en/maixcam/index.html) | RISC-V | SG2002 | 256MB | [Sipeed](https://sipeed.com/) | -| 2024 | [Milk-V Duo 64M](https://milkv.io/docs/duo/getting-started/duo) | RISC-V | CV1800B | 64MB | [Milk-V](https://milkv.io/) | -| 2024 | [CanMV-K230](https://developer.canaan-creative.com/k230_canmv/en/main/) | RISC-V | K230 | 512MB | [Canaan](https://www.canaan-creative.com/) | - ---- - -## 4. Fonctionne également sur - -### Téléphones Android (via Termux) - -Tout téléphone Android ARM64 (2015+) avec 1 Go+ de RAM. Installez [Termux](https://github.com/termux/termux-app), utilisez `proot` pour exécuter PicoClaw. - - -### Bureau / Serveur / Cloud - -| Plateforme | Notes | -|------------|-------| -| x86_64 Linux | Binaire natif, aucune dépendance | -| x86_64 Windows | Binaire natif | -| macOS (Intel / Apple Silicon) | Binaire natif | -| Docker (any platform) | `docker compose` en une ligne, voir [Guide Docker](docker.md) | -| OpenWrt routers | Builds MIPS/ARM, nécessite >32 Mo de RAM libre | -| FreeBSD / NetBSD | Builds x86_64 et arm64 disponibles | - ---- - -## 5. Configuration minimale requise - -| Ressource | Minimum | Recommandé | -|-----------|---------|------------| -| RAM | 10 Mo libres | 32 Mo+ libres | -| Stockage | 20 Mo (binaire) | 50 Mo+ (avec espace de travail) | -| CPU | N'importe lequel (monocœur 0,6 GHz+) | — | -| OS | Linux (kernel 3.x+) | Linux 5.x+ | -| Réseau | Requis (pour les appels API LLM) | Ethernet ou WiFi | - ---- - -## 6. Comment tester et contribuer - -```bash -# 1. Télécharger pour votre architecture -wget https://github.com/sipeed/picoclaw/releases/latest/download/picoclaw_Linux_arm64.tar.gz -tar xzf picoclaw_Linux_arm64.tar.gz - -# 2. Initialiser -./picoclaw onboard - -# 3. Tester -./picoclaw agent -m "Hello, what board am I running on?" -``` - -Builds disponibles : `linux-amd64`, `linux-arm64`, `linux-arm`, `linux-riscv64`, `linux-loong64`, `linux-mipsle` - -### Ajouter votre matériel - -1. Forkez ce dépôt -2. Ajoutez votre puce / produit / carte dans le tableau approprié -3. Incluez : nom, architecture, SoC, RAM, année et un lien si disponible -4. Soumettez une PR - -Fabricants de matériel : vous souhaitez ajouter un support officiel ou co-promouvoir ? Ouvrez une issue ou contactez-nous via [Discord](https://discord.gg/V4sAZ9XWpN). +See the maintained [platform guide](hardware-compatibility.md) or [中文说明](hardware-compatibility.zh.md). Built-in hardware tools have been removed; the current automated release target is Linux amd64. diff --git a/docs/guides/hardware-compatibility.ja.md b/docs/guides/hardware-compatibility.ja.md index e74d5614..c85125a6 100644 --- a/docs/guides/hardware-compatibility.ja.md +++ b/docs/guides/hardware-compatibility.ja.md @@ -1,151 +1,5 @@ -> [README](../../README.md) に戻る +# Platforms and hardware boundaries -# 🖥️ PicoClaw ハードウェア互換性リスト +The upstream device list and download instructions no longer describe this fork. -PicoClaw はほぼすべての Linux デバイスで動作します。このページでは、検証済みのチップ、製品、開発ボードを記録しています。 - -**お使いのハードウェアがリストにない場合は?** PR を送信して追加してください!ハードウェアベンダーの貢献と共同プロモーションを歓迎します。 - ---- - -## 1. 検証済みチップサポート - -### x86 - -| ベンダー | チップ | 備考 | -|----------|--------|------| -| Intel | Any x86 CPU (i386+) | すべてのデスクトップ/サーバー/ノートPC プロセッサ | -| AMD | Any x86 CPU | すべてのデスクトップ/サーバー/ノートPC プロセッサ | - -### ARM - -| サブアーキテクチャ | 代表的なチップ | 備考 | -|--------------------|----------------|------| -| ARMv6 | [BCM2835](https://www.raspberrypi.com/documentation/computers/processors.html#bcm2835) (Raspberry Pi 1/Zero) | シングルコア ARM1176JZF-S | -| ARMv7 | [Allwinner V3s](https://linux-sunxi.org/V3s) | シングルコア Cortex-A7、LicheePi Zero で使用 | -| ARM64 | [Allwinner H618](https://linux-sunxi.org/H618) | クアッドコア Cortex-A53、Orange Pi Zero 3 で使用 | -| ARM64 | [BCM2711](https://www.raspberrypi.com/documentation/computers/processors.html#bcm2711) (Raspberry Pi 4) | クアッドコア Cortex-A72 | -| ARM64 | [BCM2712](https://www.raspberrypi.com/documentation/computers/processors.html#bcm2712) (Raspberry Pi 5) | クアッドコア Cortex-A76 | -| ARM64 | [AX630C](https://www.axera-tech.com/) (爱芯元智) | デュアルコア Cortex-A53 + NPU、NanoKVM-Pro / MaixCAM2 で使用 | - -### RISC-V (riscv64) - -| ベンダー | チップ | コア | 備考 | -|----------|--------|------|------| -| [SOPHGO (算能)](https://www.sophgo.com/) | SG2002 | C906 @ 1GHz | 256MB DDR3 オンチップ、LicheeRV-Nano / NanoKVM / MaixCAM で使用 | -| [Allwinner (全志)](https://www.allwinnertech.com/) | V861 | Dual C907 | 128MB DDR3L オンチップ、1 TOPS NPU、4K AI カメラ SiP | -| [Allwinner (全志)](https://www.allwinnertech.com/) | V881 | C907 | RISC-V AI カメラシリーズ | -| [Arterytek (匠芯创)](https://www.arterytek.com/) | D213 | RISC-V | HaaS506-LD1 産業用 RTU で使用 | -| [SpacemiT (进迭)](https://www.spacemit.com/) | K1 | 8x X60 @ 1.8GHz | Milk-V Jupiter, BananaPi BPI-F3 で使用 | -| [SpacemiT (进迭)](https://www.spacemit.com/) | K3 | 8x X100 @ 2.5GHz | RVA23 準拠、1024 ビット RVV、FP8 AI 推論 | -| [Zhihe (知合)](https://www.zhihe-tech.com/) | A210 | High-perf RISC-V | 8 コア、16MB L3 キャッシュ、デスクトップクラス | -| [Canaan (嘉楠)](https://www.canaan-creative.com/) | K230 | Dual C908 @ 1.6GHz | 6 TOPS KPU、CanMV-K230 で使用 | - -### MIPS - -| ベンダー | チップ | 備考 | -|----------|--------|------| -| MediaTek | [MT7620](https://www.mediatek.com/products/home-networking/mt7620) | MIPS24KEc @ 580MHz、多くの OpenWrt ルーターで使用(例:Xiaomi Router 3G) | - -### LoongArch (loong64) - -| ベンダー | チップ | 備考 | -|----------|--------|------| -| [Loongson (龙芯)](https://www.loongson.cn/) | 3A5000 | クアッドコア LA464 @ 2.5GHz、デスクトップ/ワークステーション | -| [Loongson (龙芯)](https://www.loongson.cn/) | 3A6000 | クアッドコア 4C/8T @ 2.5GHz、IPC は Intel 第10世代に匹敵 | -| [Loongson (龙芯)](https://www.loongson.cn/) | 2K1000LA | デュアルコア @ 1GHz、産業/IoT アプリケーション | - ---- - -## 2. 検証済み製品(発売日順) - -PicoClaw でテスト済みのコンシューマー製品、ルーター、産業用デバイス。 - -| 年 | 製品 | アーキテクチャ | SoC | RAM | カテゴリ | -|----|------|----------------|-----|-----|----------| -| 2009 | Nokia N900 | ARM (A8) | OMAP3430 | 256MB | スマートフォン | -| 2012 | Samsung Galaxy Note 10.1 (N8000) | ARM (A9) | Exynos 4412 | 2GB | タブレット | -| 2016 | Xiaomi Router 3G (小米路由器3G) | MIPS | MT7620 | 256MB | ルーター (OpenWrt) | -| 2018 | Phicomm N1 (斐讯N1) | ARM64 (A53) | S905D | 2GB | TV ボックス / ホームサーバー | -| 2019 | Xiaomi AI Speaker (小爱音箱) | ARM64 (A53) | — | 256MB | スマートスピーカー | -| 2024 | [NanoKVM](https://wiki.sipeed.com/hardware/en/kvm/NanoKVM/introduction.html) | RISC-V | SG2002 | 256MB | IP-KVM | -| 2025 | HaaS506-LD1 | RISC-V | D213 | 128MB | 産業用 RTU | -| 2025 | [NanoKVM-Pro](https://wiki.sipeed.com/hardware/en/kvm/NanoKVM_Pro/introduction.html) | ARM64 (A53) | AX630C | 1GB | プロ IP-KVM | -| 2026 | [MaixCAM2](https://wiki.sipeed.com/hardware/en/maixcam/index.html) | ARM64 (A53) | AX630C | 1/4GB | 4K AI カメラ | - ---- - -## 3. 検証済み開発ボード(発売日順) - -| 年 | ボード | アーキテクチャ | SoC | RAM | 購入リンク | -|----|--------|----------------|-----|-----|------------| -| 2012 | [Raspberry Pi 1 Model B](https://www.raspberrypi.com/products/) | ARMv6 | BCM2835 | 512MB | — | -| 2015 | [Raspberry Pi 2 Model B](https://www.raspberrypi.com/products/raspberry-pi-2-model-b/) | ARMv7 (A7) | BCM2836 | 1GB | — | -| 2015 | [Raspberry Pi Zero](https://www.raspberrypi.com/products/raspberry-pi-zero/) | ARMv6 | BCM2835 | 512MB | — | -| 2016 | [Raspberry Pi 3 Model B](https://www.raspberrypi.com/products/raspberry-pi-3-model-b/) | ARM64 (A53) | BCM2837 | 1GB | — | -| 2017 | [LicheePi Zero](https://wiki.sipeed.com/hardware/en/lichee/Zero/Zero.html) | ARMv7 (A7) | Allwinner V3s | 64MB | [Sipeed](https://sipeed.com/) | -| 2019 | [Raspberry Pi 4 Model B](https://www.raspberrypi.com/products/raspberry-pi-4-model-b/) | ARM64 (A72) | BCM2711 | 1~8GB | [RPi](https://www.raspberrypi.com/) | -| 2023 | [Raspberry Pi 5](https://www.raspberrypi.com/products/raspberry-pi-5/) | ARM64 (A76) | BCM2712 | 2~8GB | [RPi](https://www.raspberrypi.com/) | -| 2024 | [LicheeRV-Nano](https://wiki.sipeed.com/hardware/en/lichee/RV_Nano/1_intro.html) | RISC-V | SG2002 | 256MB | [AliExpress](https://www.aliexpress.com/item/1005006519668532.html) | -| 2024 | [MaixCAM-Pro](https://wiki.sipeed.com/hardware/en/maixcam/index.html) | RISC-V | SG2002 | 256MB | [Sipeed](https://sipeed.com/) | -| 2024 | [Milk-V Duo 64M](https://milkv.io/docs/duo/getting-started/duo) | RISC-V | CV1800B | 64MB | [Milk-V](https://milkv.io/) | -| 2024 | [CanMV-K230](https://developer.canaan-creative.com/k230_canmv/en/main/) | RISC-V | K230 | 512MB | [Canaan](https://www.canaan-creative.com/) | - ---- - -## 4. その他の対応環境 - -### Android スマートフォン(Termux 経由) - -1GB 以上の RAM を搭載した ARM64 Android スマートフォン(2015年以降)。[Termux](https://github.com/termux/termux-app) をインストールし、`proot` を使用して PicoClaw を実行します。 - - -### デスクトップ / サーバー / クラウド - -| プラットフォーム | 備考 | -|------------------|------| -| x86_64 Linux | ネイティブバイナリ、依存関係なし | -| x86_64 Windows | ネイティブバイナリ | -| macOS (Intel / Apple Silicon) | ネイティブバイナリ | -| Docker (any platform) | `docker compose` ワンライナー、[Docker ガイド](docker.md) を参照 | -| OpenWrt routers | MIPS/ARM ビルド、32MB 以上の空きメモリが必要 | -| FreeBSD / NetBSD | x86_64 および arm64 ビルドが利用可能 | - ---- - -## 5. 最小要件 - -| リソース | 最小 | 推奨 | -|----------|------|------| -| RAM | 10MB 空き | 32MB 以上空き | -| ストレージ | 20MB(バイナリ) | 50MB 以上(ワークスペース含む) | -| CPU | 任意(シングルコア 0.6GHz 以上) | — | -| OS | Linux (kernel 3.x+) | Linux 5.x+ | -| ネットワーク | 必須(LLM API 呼び出し用) | イーサネットまたは WiFi | - ---- - -## 6. テストと貢献の方法 - -```bash -# 1. お使いのアーキテクチャ向けをダウンロード -wget https://github.com/sipeed/picoclaw/releases/latest/download/picoclaw_Linux_arm64.tar.gz -tar xzf picoclaw_Linux_arm64.tar.gz - -# 2. 初期化 -./picoclaw onboard - -# 3. テスト -./picoclaw agent -m "Hello, what board am I running on?" -``` - -利用可能なビルド:`linux-amd64`, `linux-arm64`, `linux-arm`, `linux-riscv64`, `linux-loong64`, `linux-mipsle` - -### ハードウェアを追加する - -1. このリポジトリをフォーク -2. 該当するテーブルにチップ/製品/ボードを追加 -3. 名前、アーキテクチャ、SoC、RAM、年、リンク(あれば)を含める -4. PR を送信 - -ハードウェアベンダーの方へ:公式サポートの追加や共同プロモーションをご希望ですか?Issue を作成するか、[Discord](https://discord.gg/V4sAZ9XWpN) でお問い合わせください。 +See the maintained [platform guide](hardware-compatibility.md) or [中文说明](hardware-compatibility.zh.md). Built-in hardware tools have been removed; the current automated release target is Linux amd64. diff --git a/docs/guides/hardware-compatibility.md b/docs/guides/hardware-compatibility.md index ab0c4c8a..e9c81eae 100644 --- a/docs/guides/hardware-compatibility.md +++ b/docs/guides/hardware-compatibility.md @@ -1,150 +1,14 @@ -# 🖥️ PicoClaw Hardware Compatibility List +# Platforms and hardware boundaries -PicoClaw runs on virtually any Linux device. This page tracks verified chips, products, and development boards. - -**Your hardware not listed?** Submit a PR to add it! Hardware vendors are welcome to contribute and co-promote. - ---- - -## 1. Verified Chip Support - -### x86 - -| Vendor | Chip | Notes | -|--------|------|-------| -| Intel | Any x86 CPU (i386+) | All desktop/server/laptop processors | -| AMD | Any x86 CPU | All desktop/server/laptop processors | - -### ARM - -| Sub-arch | Typical Chips | Notes | -|----------|--------------|-------| -| ARMv6 | [BCM2835](https://www.raspberrypi.com/documentation/computers/processors.html#bcm2835) (Raspberry Pi 1/Zero) | Single-core ARM1176JZF-S | -| ARMv7 | [Allwinner V3s](https://linux-sunxi.org/V3s) | Single-core Cortex-A7, used in LicheePi Zero | -| ARM64 | [Allwinner H618](https://linux-sunxi.org/H618) | Quad-core Cortex-A53, used in Orange Pi Zero 3 | -| ARM64 | [BCM2711](https://www.raspberrypi.com/documentation/computers/processors.html#bcm2711) (Raspberry Pi 4) | Quad-core Cortex-A72 | -| ARM64 | [BCM2712](https://www.raspberrypi.com/documentation/computers/processors.html#bcm2712) (Raspberry Pi 5) | Quad-core Cortex-A76 | -| ARM64 | [AX630C](https://www.axera-tech.com/) (爱芯元智) | Dual-core Cortex-A53 + NPU, used in NanoKVM-Pro / MaixCAM2 | - -### RISC-V (riscv64) - -| Vendor | Chip | Core | Notes | -|--------|------|------|-------| -| [SOPHGO (算能)](https://www.sophgo.com/) | SG2002 | C906 @ 1GHz | 256MB DDR3 on-chip, used in LicheeRV-Nano / NanoKVM / MaixCAM | -| [Allwinner (全志)](https://www.allwinnertech.com/) | V861 | Dual C907 | 128MB DDR3L on-chip, 1 TOPS NPU, 4K AI camera SiP | -| [Allwinner (全志)](https://www.allwinnertech.com/) | V881 | C907 | RISC-V AI camera series | -| [Arterytek (匠芯创)](https://www.arterytek.com/) | D213 | RISC-V | Used in HaaS506-LD1 industrial RTU | -| [SpacemiT (进迭)](https://www.spacemit.com/) | K1 | 8x X60 @ 1.8GHz | Used in Milk-V Jupiter, BananaPi BPI-F3 | -| [SpacemiT (进迭)](https://www.spacemit.com/) | K3 | 8x X100 @ 2.5GHz | RVA23 compliant, 1024-bit RVV, FP8 AI inference | -| [Zhihe (知合)](https://www.zhihe-tech.com/) | A210 | High-perf RISC-V | 8-core, 16MB L3 cache, desktop-class | -| [Canaan (嘉楠)](https://www.canaan-creative.com/) | K230 | Dual C908 @ 1.6GHz | 6 TOPS KPU, used in CanMV-K230 | - -### MIPS - -| Vendor | Chip | Notes | -|--------|------|-------| -| MediaTek | [MT7620](https://www.mediatek.com/products/home-networking/mt7620) | MIPS24KEc @ 580MHz, used in many OpenWrt routers (e.g. Xiaomi Router 3G) | - -### LoongArch (loong64) - -| Vendor | Chip | Notes | -|--------|------|-------| -| [Loongson (龙芯)](https://www.loongson.cn/) | 3A5000 | Quad-core LA464 @ 2.5GHz, desktop/workstation | -| [Loongson (龙芯)](https://www.loongson.cn/) | 3A6000 | Quad-core 4C/8T @ 2.5GHz, IPC comparable to Intel 10th gen | -| [Loongson (龙芯)](https://www.loongson.cn/) | 2K1000LA | Dual-core @ 1GHz, industrial/IoT applications | - ---- - -## 2. Verified Products (by release date) - -Consumer products, routers, and industrial devices that have been tested with PicoClaw. - -| Year | Product | Arch | SoC | RAM | Category | -|------|---------|------|-----|-----|----------| -| 2009 | Nokia N900 | ARM (A8) | OMAP3430 | 256MB | Smartphone | -| 2012 | Samsung Galaxy Note 10.1 (N8000) | ARM (A9) | Exynos 4412 | 2GB | Tablet | -| 2016 | Xiaomi Router 3G (小米路由器3G) | MIPS | MT7620 | 256MB | Router (OpenWrt) | -| 2018 | Phicomm N1 (斐讯N1) | ARM64 (A53) | S905D | 2GB | TV Box / Home Server | -| 2019 | Xiaomi AI Speaker (小爱音箱) | ARM64 (A53) | — | 256MB | Smart Speaker | -| 2024 | [NanoKVM](https://wiki.sipeed.com/hardware/en/kvm/NanoKVM/introduction.html) | RISC-V | SG2002 | 256MB | IP-KVM | -| 2025 | HaaS506-LD1 | RISC-V | D213 | 128MB | Industrial RTU | -| 2025 | [NanoKVM-Pro](https://wiki.sipeed.com/hardware/en/kvm/NanoKVM_Pro/introduction.html) | ARM64 (A53) | AX630C | 1GB | Pro IP-KVM | -| 2026 | [MaixCAM2](https://wiki.sipeed.com/hardware/en/maixcam/index.html) | ARM64 (A53) | AX630C | 1/4GB | 4K AI Camera | - ---- - -## 3. Verified Development Boards (by release date) - -| Year | Board | Arch | SoC | RAM | Buy Link | -|------|-------|------|-----|-----|----------| -| 2012 | [Raspberry Pi 1 Model B](https://www.raspberrypi.com/products/) | ARMv6 | BCM2835 | 512MB | — | -| 2015 | [Raspberry Pi 2 Model B](https://www.raspberrypi.com/products/raspberry-pi-2-model-b/) | ARMv7 (A7) | BCM2836 | 1GB | — | -| 2015 | [Raspberry Pi Zero](https://www.raspberrypi.com/products/raspberry-pi-zero/) | ARMv6 | BCM2835 | 512MB | — | -| 2016 | [Raspberry Pi 3 Model B](https://www.raspberrypi.com/products/raspberry-pi-3-model-b/) | ARM64 (A53) | BCM2837 | 1GB | — | -| 2017 | [LicheePi Zero](https://wiki.sipeed.com/hardware/en/lichee/Zero/Zero.html) | ARMv7 (A7) | Allwinner V3s | 64MB | [Sipeed](https://sipeed.com/) | -| 2019 | [Raspberry Pi 4 Model B](https://www.raspberrypi.com/products/raspberry-pi-4-model-b/) | ARM64 (A72) | BCM2711 | 1~8GB | [RPi](https://www.raspberrypi.com/) | -| 2023 | [Raspberry Pi 5](https://www.raspberrypi.com/products/raspberry-pi-5/) | ARM64 (A76) | BCM2712 | 2~8GB | [RPi](https://www.raspberrypi.com/) | -| 2024 | [LicheeRV-Nano](https://wiki.sipeed.com/hardware/en/lichee/RV_Nano/1_intro.html) | RISC-V | SG2002 | 256MB | [AliExpress](https://www.aliexpress.com/item/1005006519668532.html) | -| 2024 | [MaixCAM-Pro](https://wiki.sipeed.com/hardware/en/maixcam/index.html) | RISC-V | SG2002 | 256MB | [Sipeed](https://sipeed.com/) | -| 2024 | [Milk-V Duo 64M](https://milkv.io/docs/duo/getting-started/duo) | RISC-V | CV1800B | 64MB | [Milk-V](https://milkv.io/) | -| 2024 | [CanMV-K230](https://developer.canaan-creative.com/k230_canmv/en/main/) | RISC-V | K230 | 512MB | [Canaan](https://www.canaan-creative.com/) | - ---- - -## 4. Also Works On - -### Android Phones (via Termux) - -Any ARM64 Android phone (2015+) with 1GB+ RAM. Install [Termux](https://github.com/termux/termux-app), use `proot` to run PicoClaw. - -> See the [Android Termux Guide](android-termux.md) for setup instructions. - -### Desktop / Server / Cloud - -| Platform | Notes | -|----------|-------| -| x86_64 Linux | Native binary, no dependencies | -| x86_64 Windows | Native binary | -| macOS (Intel / Apple Silicon) | Native binary | -| Docker (any platform) | `docker compose` one-liner, see [Docker Guide](docker.md) | -| OpenWrt routers | MIPS/ARM builds, requires >32MB free RAM | -| FreeBSD / NetBSD | x86_64 and arm64 builds available | - ---- - -## 5. Minimum Requirements - -| Resource | Minimum | Recommended | -|----------|---------|-------------| -| RAM | 10MB free | 32MB+ free | -| Storage | 20MB (binary) | 50MB+ (with workspace) | -| CPU | Any (single core 0.6GHz+) | — | -| OS | Linux (kernel 3.x+) | Linux 5.x+ | -| Network | Required (for LLM API calls) | Ethernet or WiFi | - ---- - -## 6. How to Test & Contribute +The automated build and release target for this fork is **Linux amd64**. See the [README](../../README.md) for source builds and release packaging. ```bash -# 1. Download for your architecture -wget https://github.com/sipeed/picoclaw/releases/latest/download/picoclaw_Linux_arm64.tar.gz -tar xzf picoclaw_Linux_arm64.tar.gz - -# 2. Initialize -./picoclaw onboard - -# 3. Test -./picoclaw agent -m "Hello, what board am I running on?" +make build GOOS=linux GOARCH=amd64 +# build/picoclaw-linux-amd64 ``` -Available builds: `linux-amd64`, `linux-arm64`, `linux-arm`, `linux-riscv64`, `linux-loong64`, `linux-mipsle` +The Makefile retains other cross-compilation helpers, but they are not part of the current release workflow or a verified device compatibility list. Validate builds, channel SDK support, and runtime behavior on the target platform before deploying. In particular, the Feishu SDK is unavailable on 32-bit targets. -### Add Your Hardware +Built-in I²C, SPI, serial tools, USB device monitoring, and the hardware Skill have been removed. Add hardware integrations through optional Skills and external tools. This does not prevent the Gateway or CLI from running on a supported host with hardware attached. -1. Fork this repo -2. Add your chip / product / board to the appropriate table -3. Include: name, arch, SoC, RAM, year, and a link if available -4. Submit a PR - -Hardware vendors: want to add official support or co-promote? Open an issue or reach out via [Discord](https://discord.gg/V4sAZ9XWpN). +Do not install upstream release archives as updates for this fork. The Office Skills use a separate Docker runtime; see the [Office guide](office-skills.zh.md). diff --git a/docs/guides/hardware-compatibility.pt-br.md b/docs/guides/hardware-compatibility.pt-br.md index d8456940..c85125a6 100644 --- a/docs/guides/hardware-compatibility.pt-br.md +++ b/docs/guides/hardware-compatibility.pt-br.md @@ -1,151 +1,5 @@ -> Voltar ao [README](../../README.md) +# Platforms and hardware boundaries -# 🖥️ PicoClaw Lista de compatibilidade de hardware +The upstream device list and download instructions no longer describe this fork. -O PicoClaw roda em praticamente qualquer dispositivo Linux. Esta página registra chips, produtos e placas de desenvolvimento verificados. - -**Seu hardware não está na lista?** Envie um PR para adicioná-lo! Fabricantes de hardware são bem-vindos para contribuir e co-promover. - ---- - -## 1. Suporte a chips verificado - -### x86 - -| Fabricante | Chip | Notas | -|------------|------|-------| -| Intel | Any x86 CPU (i386+) | Todos os processadores desktop/servidor/notebook | -| AMD | Any x86 CPU | Todos os processadores desktop/servidor/notebook | - -### ARM - -| Sub-arq | Chips típicos | Notas | -|---------|---------------|-------| -| ARMv6 | [BCM2835](https://www.raspberrypi.com/documentation/computers/processors.html#bcm2835) (Raspberry Pi 1/Zero) | Single-core ARM1176JZF-S | -| ARMv7 | [Allwinner V3s](https://linux-sunxi.org/V3s) | Single-core Cortex-A7, usado no LicheePi Zero | -| ARM64 | [Allwinner H618](https://linux-sunxi.org/H618) | Quad-core Cortex-A53, usado no Orange Pi Zero 3 | -| ARM64 | [BCM2711](https://www.raspberrypi.com/documentation/computers/processors.html#bcm2711) (Raspberry Pi 4) | Quad-core Cortex-A72 | -| ARM64 | [BCM2712](https://www.raspberrypi.com/documentation/computers/processors.html#bcm2712) (Raspberry Pi 5) | Quad-core Cortex-A76 | -| ARM64 | [AX630C](https://www.axera-tech.com/) (爱芯元智) | Dual-core Cortex-A53 + NPU, usado no NanoKVM-Pro / MaixCAM2 | - -### RISC-V (riscv64) - -| Fabricante | Chip | Núcleo | Notas | -|------------|------|--------|-------| -| [SOPHGO (算能)](https://www.sophgo.com/) | SG2002 | C906 @ 1GHz | 256MB DDR3 integrado, usado no LicheeRV-Nano / NanoKVM / MaixCAM | -| [Allwinner (全志)](https://www.allwinnertech.com/) | V861 | Dual C907 | 128MB DDR3L integrado, 1 TOPS NPU, câmera AI 4K SiP | -| [Allwinner (全志)](https://www.allwinnertech.com/) | V881 | C907 | Série de câmeras AI RISC-V | -| [Arterytek (匠芯创)](https://www.arterytek.com/) | D213 | RISC-V | Usado no HaaS506-LD1 RTU industrial | -| [SpacemiT (进迭)](https://www.spacemit.com/) | K1 | 8x X60 @ 1.8GHz | Usado no Milk-V Jupiter, BananaPi BPI-F3 | -| [SpacemiT (进迭)](https://www.spacemit.com/) | K3 | 8x X100 @ 2.5GHz | Compatível com RVA23, RVV de 1024 bits, inferência AI FP8 | -| [Zhihe (知合)](https://www.zhihe-tech.com/) | A210 | High-perf RISC-V | 8 núcleos, 16MB cache L3, classe desktop | -| [Canaan (嘉楠)](https://www.canaan-creative.com/) | K230 | Dual C908 @ 1.6GHz | 6 TOPS KPU, usado no CanMV-K230 | - -### MIPS - -| Fabricante | Chip | Notas | -|------------|------|-------| -| MediaTek | [MT7620](https://www.mediatek.com/products/home-networking/mt7620) | MIPS24KEc @ 580MHz, usado em muitos roteadores OpenWrt (ex. Xiaomi Router 3G) | - -### LoongArch (loong64) - -| Fabricante | Chip | Notas | -|------------|------|-------| -| [Loongson (龙芯)](https://www.loongson.cn/) | 3A5000 | Quad-core LA464 @ 2.5GHz, desktop/estação de trabalho | -| [Loongson (龙芯)](https://www.loongson.cn/) | 3A6000 | Quad-core 4C/8T @ 2.5GHz, IPC comparável ao Intel 10ª geração | -| [Loongson (龙芯)](https://www.loongson.cn/) | 2K1000LA | Dual-core @ 1GHz, aplicações industriais/IoT | - ---- - -## 2. Produtos verificados (por data de lançamento) - -Produtos de consumo, roteadores e dispositivos industriais testados com o PicoClaw. - -| Ano | Produto | Arq | SoC | RAM | Categoria | -|-----|---------|-----|-----|-----|-----------| -| 2009 | Nokia N900 | ARM (A8) | OMAP3430 | 256MB | Smartphone | -| 2012 | Samsung Galaxy Note 10.1 (N8000) | ARM (A9) | Exynos 4412 | 2GB | Tablet | -| 2016 | Xiaomi Router 3G (小米路由器3G) | MIPS | MT7620 | 256MB | Roteador (OpenWrt) | -| 2018 | Phicomm N1 (斐讯N1) | ARM64 (A53) | S905D | 2GB | TV Box / Servidor doméstico | -| 2019 | Xiaomi AI Speaker (小爱音箱) | ARM64 (A53) | — | 256MB | Alto-falante inteligente | -| 2024 | [NanoKVM](https://wiki.sipeed.com/hardware/en/kvm/NanoKVM/introduction.html) | RISC-V | SG2002 | 256MB | IP-KVM | -| 2025 | HaaS506-LD1 | RISC-V | D213 | 128MB | RTU industrial | -| 2025 | [NanoKVM-Pro](https://wiki.sipeed.com/hardware/en/kvm/NanoKVM_Pro/introduction.html) | ARM64 (A53) | AX630C | 1GB | IP-KVM Pro | -| 2026 | [MaixCAM2](https://wiki.sipeed.com/hardware/en/maixcam/index.html) | ARM64 (A53) | AX630C | 1/4GB | Câmera AI 4K | - ---- - -## 3. Placas de desenvolvimento verificadas (por data de lançamento) - -| Ano | Placa | Arq | SoC | RAM | Link de compra | -|-----|-------|-----|-----|-----|----------------| -| 2012 | [Raspberry Pi 1 Model B](https://www.raspberrypi.com/products/) | ARMv6 | BCM2835 | 512MB | — | -| 2015 | [Raspberry Pi 2 Model B](https://www.raspberrypi.com/products/raspberry-pi-2-model-b/) | ARMv7 (A7) | BCM2836 | 1GB | — | -| 2015 | [Raspberry Pi Zero](https://www.raspberrypi.com/products/raspberry-pi-zero/) | ARMv6 | BCM2835 | 512MB | — | -| 2016 | [Raspberry Pi 3 Model B](https://www.raspberrypi.com/products/raspberry-pi-3-model-b/) | ARM64 (A53) | BCM2837 | 1GB | — | -| 2017 | [LicheePi Zero](https://wiki.sipeed.com/hardware/en/lichee/Zero/Zero.html) | ARMv7 (A7) | Allwinner V3s | 64MB | [Sipeed](https://sipeed.com/) | -| 2019 | [Raspberry Pi 4 Model B](https://www.raspberrypi.com/products/raspberry-pi-4-model-b/) | ARM64 (A72) | BCM2711 | 1~8GB | [RPi](https://www.raspberrypi.com/) | -| 2023 | [Raspberry Pi 5](https://www.raspberrypi.com/products/raspberry-pi-5/) | ARM64 (A76) | BCM2712 | 2~8GB | [RPi](https://www.raspberrypi.com/) | -| 2024 | [LicheeRV-Nano](https://wiki.sipeed.com/hardware/en/lichee/RV_Nano/1_intro.html) | RISC-V | SG2002 | 256MB | [AliExpress](https://www.aliexpress.com/item/1005006519668532.html) | -| 2024 | [MaixCAM-Pro](https://wiki.sipeed.com/hardware/en/maixcam/index.html) | RISC-V | SG2002 | 256MB | [Sipeed](https://sipeed.com/) | -| 2024 | [Milk-V Duo 64M](https://milkv.io/docs/duo/getting-started/duo) | RISC-V | CV1800B | 64MB | [Milk-V](https://milkv.io/) | -| 2024 | [CanMV-K230](https://developer.canaan-creative.com/k230_canmv/en/main/) | RISC-V | K230 | 512MB | [Canaan](https://www.canaan-creative.com/) | - ---- - -## 4. Também funciona em - -### Celulares Android (via Termux) - -Qualquer celular Android ARM64 (2015+) com 1GB+ de RAM. Instale o [Termux](https://github.com/termux/termux-app), use `proot` para rodar o PicoClaw. - - -### Desktop / Servidor / Nuvem - -| Plataforma | Notas | -|------------|-------| -| x86_64 Linux | Binário nativo, sem dependências | -| x86_64 Windows | Binário nativo | -| macOS (Intel / Apple Silicon) | Binário nativo | -| Docker (any platform) | `docker compose` em uma linha, veja [Guia Docker](docker.md) | -| OpenWrt routers | Builds MIPS/ARM, requer >32MB de RAM livre | -| FreeBSD / NetBSD | Builds x86_64 e arm64 disponíveis | - ---- - -## 5. Requisitos mínimos - -| Recurso | Mínimo | Recomendado | -|---------|--------|-------------| -| RAM | 10MB livres | 32MB+ livres | -| Armazenamento | 20MB (binário) | 50MB+ (com workspace) | -| CPU | Qualquer (single-core 0,6GHz+) | — | -| OS | Linux (kernel 3.x+) | Linux 5.x+ | -| Rede | Necessária (para chamadas de API LLM) | Ethernet ou WiFi | - ---- - -## 6. Como testar e contribuir - -```bash -# 1. Baixar para sua arquitetura -wget https://github.com/sipeed/picoclaw/releases/latest/download/picoclaw_Linux_arm64.tar.gz -tar xzf picoclaw_Linux_arm64.tar.gz - -# 2. Inicializar -./picoclaw onboard - -# 3. Testar -./picoclaw agent -m "Hello, what board am I running on?" -``` - -Builds disponíveis: `linux-amd64`, `linux-arm64`, `linux-arm`, `linux-riscv64`, `linux-loong64`, `linux-mipsle` - -### Adicionar seu hardware - -1. Faça fork deste repositório -2. Adicione seu chip / produto / placa na tabela apropriada -3. Inclua: nome, arquitetura, SoC, RAM, ano e um link se disponível -4. Envie um PR - -Fabricantes de hardware: deseja adicionar suporte oficial ou co-promover? Abra uma issue ou entre em contato via [Discord](https://discord.gg/V4sAZ9XWpN). +See the maintained [platform guide](hardware-compatibility.md) or [中文说明](hardware-compatibility.zh.md). Built-in hardware tools have been removed; the current automated release target is Linux amd64. diff --git a/docs/guides/hardware-compatibility.vi.md b/docs/guides/hardware-compatibility.vi.md index 2e89bcc0..c85125a6 100644 --- a/docs/guides/hardware-compatibility.vi.md +++ b/docs/guides/hardware-compatibility.vi.md @@ -1,151 +1,5 @@ -> Quay lại [README](../../README.md) +# Platforms and hardware boundaries -# 🖥️ PicoClaw Danh sách tương thích phần cứng +The upstream device list and download instructions no longer describe this fork. -PicoClaw chạy được trên hầu hết mọi thiết bị Linux. Trang này ghi nhận các chip, sản phẩm và bo mạch phát triển đã được xác minh. - -**Phần cứng của bạn chưa có trong danh sách?** Gửi PR để thêm vào! Các nhà sản xuất phần cứng được hoan nghênh đóng góp và đồng quảng bá. - ---- - -## 1. Hỗ trợ chip đã xác minh - -### x86 - -| Nhà sản xuất | Chip | Ghi chú | -|--------------|------|---------| -| Intel | Any x86 CPU (i386+) | Tất cả bộ xử lý desktop/server/laptop | -| AMD | Any x86 CPU | Tất cả bộ xử lý desktop/server/laptop | - -### ARM - -| Kiến trúc phụ | Chip tiêu biểu | Ghi chú | -|----------------|----------------|---------| -| ARMv6 | [BCM2835](https://www.raspberrypi.com/documentation/computers/processors.html#bcm2835) (Raspberry Pi 1/Zero) | Đơn nhân ARM1176JZF-S | -| ARMv7 | [Allwinner V3s](https://linux-sunxi.org/V3s) | Đơn nhân Cortex-A7, dùng trong LicheePi Zero | -| ARM64 | [Allwinner H618](https://linux-sunxi.org/H618) | Bốn nhân Cortex-A53, dùng trong Orange Pi Zero 3 | -| ARM64 | [BCM2711](https://www.raspberrypi.com/documentation/computers/processors.html#bcm2711) (Raspberry Pi 4) | Bốn nhân Cortex-A72 | -| ARM64 | [BCM2712](https://www.raspberrypi.com/documentation/computers/processors.html#bcm2712) (Raspberry Pi 5) | Bốn nhân Cortex-A76 | -| ARM64 | [AX630C](https://www.axera-tech.com/) (爱芯元智) | Hai nhân Cortex-A53 + NPU, dùng trong NanoKVM-Pro / MaixCAM2 | - -### RISC-V (riscv64) - -| Nhà sản xuất | Chip | Lõi | Ghi chú | -|--------------|------|-----|---------| -| [SOPHGO (算能)](https://www.sophgo.com/) | SG2002 | C906 @ 1GHz | 256MB DDR3 tích hợp, dùng trong LicheeRV-Nano / NanoKVM / MaixCAM | -| [Allwinner (全志)](https://www.allwinnertech.com/) | V861 | Dual C907 | 128MB DDR3L tích hợp, 1 TOPS NPU, camera AI 4K SiP | -| [Allwinner (全志)](https://www.allwinnertech.com/) | V881 | C907 | Dòng camera AI RISC-V | -| [Arterytek (匠芯创)](https://www.arterytek.com/) | D213 | RISC-V | Dùng trong HaaS506-LD1 RTU công nghiệp | -| [SpacemiT (进迭)](https://www.spacemit.com/) | K1 | 8x X60 @ 1.8GHz | Dùng trong Milk-V Jupiter, BananaPi BPI-F3 | -| [SpacemiT (进迭)](https://www.spacemit.com/) | K3 | 8x X100 @ 2.5GHz | Tuân thủ RVA23, RVV 1024-bit, suy luận AI FP8 | -| [Zhihe (知合)](https://www.zhihe-tech.com/) | A210 | High-perf RISC-V | 8 lõi, 16MB cache L3, cấp desktop | -| [Canaan (嘉楠)](https://www.canaan-creative.com/) | K230 | Dual C908 @ 1.6GHz | 6 TOPS KPU, dùng trong CanMV-K230 | - -### MIPS - -| Nhà sản xuất | Chip | Ghi chú | -|--------------|------|---------| -| MediaTek | [MT7620](https://www.mediatek.com/products/home-networking/mt7620) | MIPS24KEc @ 580MHz, dùng trong nhiều router OpenWrt (vd. Xiaomi Router 3G) | - -### LoongArch (loong64) - -| Nhà sản xuất | Chip | Ghi chú | -|--------------|------|---------| -| [Loongson (龙芯)](https://www.loongson.cn/) | 3A5000 | Bốn nhân LA464 @ 2.5GHz, desktop/máy trạm | -| [Loongson (龙芯)](https://www.loongson.cn/) | 3A6000 | Bốn nhân 4C/8T @ 2.5GHz, IPC tương đương Intel thế hệ 10 | -| [Loongson (龙芯)](https://www.loongson.cn/) | 2K1000LA | Hai nhân @ 1GHz, ứng dụng công nghiệp/IoT | - ---- - -## 2. Sản phẩm đã xác minh (theo ngày phát hành) - -Sản phẩm tiêu dùng, router và thiết bị công nghiệp đã được kiểm thử với PicoClaw. - -| Năm | Sản phẩm | Kiến trúc | SoC | RAM | Danh mục | -|-----|----------|-----------|-----|-----|----------| -| 2009 | Nokia N900 | ARM (A8) | OMAP3430 | 256MB | Điện thoại thông minh | -| 2012 | Samsung Galaxy Note 10.1 (N8000) | ARM (A9) | Exynos 4412 | 2GB | Máy tính bảng | -| 2016 | Xiaomi Router 3G (小米路由器3G) | MIPS | MT7620 | 256MB | Router (OpenWrt) | -| 2018 | Phicomm N1 (斐讯N1) | ARM64 (A53) | S905D | 2GB | TV Box / Máy chủ gia đình | -| 2019 | Xiaomi AI Speaker (小爱音箱) | ARM64 (A53) | — | 256MB | Loa thông minh | -| 2024 | [NanoKVM](https://wiki.sipeed.com/hardware/en/kvm/NanoKVM/introduction.html) | RISC-V | SG2002 | 256MB | IP-KVM | -| 2025 | HaaS506-LD1 | RISC-V | D213 | 128MB | RTU công nghiệp | -| 2025 | [NanoKVM-Pro](https://wiki.sipeed.com/hardware/en/kvm/NanoKVM_Pro/introduction.html) | ARM64 (A53) | AX630C | 1GB | IP-KVM Pro | -| 2026 | [MaixCAM2](https://wiki.sipeed.com/hardware/en/maixcam/index.html) | ARM64 (A53) | AX630C | 1/4GB | Camera AI 4K | - ---- - -## 3. Bo mạch phát triển đã xác minh (theo ngày phát hành) - -| Năm | Bo mạch | Kiến trúc | SoC | RAM | Liên kết mua | -|-----|---------|-----------|-----|-----|--------------| -| 2012 | [Raspberry Pi 1 Model B](https://www.raspberrypi.com/products/) | ARMv6 | BCM2835 | 512MB | — | -| 2015 | [Raspberry Pi 2 Model B](https://www.raspberrypi.com/products/raspberry-pi-2-model-b/) | ARMv7 (A7) | BCM2836 | 1GB | — | -| 2015 | [Raspberry Pi Zero](https://www.raspberrypi.com/products/raspberry-pi-zero/) | ARMv6 | BCM2835 | 512MB | — | -| 2016 | [Raspberry Pi 3 Model B](https://www.raspberrypi.com/products/raspberry-pi-3-model-b/) | ARM64 (A53) | BCM2837 | 1GB | — | -| 2017 | [LicheePi Zero](https://wiki.sipeed.com/hardware/en/lichee/Zero/Zero.html) | ARMv7 (A7) | Allwinner V3s | 64MB | [Sipeed](https://sipeed.com/) | -| 2019 | [Raspberry Pi 4 Model B](https://www.raspberrypi.com/products/raspberry-pi-4-model-b/) | ARM64 (A72) | BCM2711 | 1~8GB | [RPi](https://www.raspberrypi.com/) | -| 2023 | [Raspberry Pi 5](https://www.raspberrypi.com/products/raspberry-pi-5/) | ARM64 (A76) | BCM2712 | 2~8GB | [RPi](https://www.raspberrypi.com/) | -| 2024 | [LicheeRV-Nano](https://wiki.sipeed.com/hardware/en/lichee/RV_Nano/1_intro.html) | RISC-V | SG2002 | 256MB | [AliExpress](https://www.aliexpress.com/item/1005006519668532.html) | -| 2024 | [MaixCAM-Pro](https://wiki.sipeed.com/hardware/en/maixcam/index.html) | RISC-V | SG2002 | 256MB | [Sipeed](https://sipeed.com/) | -| 2024 | [Milk-V Duo 64M](https://milkv.io/docs/duo/getting-started/duo) | RISC-V | CV1800B | 64MB | [Milk-V](https://milkv.io/) | -| 2024 | [CanMV-K230](https://developer.canaan-creative.com/k230_canmv/en/main/) | RISC-V | K230 | 512MB | [Canaan](https://www.canaan-creative.com/) | - ---- - -## 4. Cũng hoạt động trên - -### Điện thoại Android (qua Termux) - -Bất kỳ điện thoại Android ARM64 nào (2015+) với 1GB+ RAM. Cài đặt [Termux](https://github.com/termux/termux-app), sử dụng `proot` để chạy PicoClaw. - - -### Desktop / Máy chủ / Đám mây - -| Nền tảng | Ghi chú | -|----------|---------| -| x86_64 Linux | Binary gốc, không phụ thuộc | -| x86_64 Windows | Binary gốc | -| macOS (Intel / Apple Silicon) | Binary gốc | -| Docker (any platform) | `docker compose` một dòng lệnh, xem [Hướng dẫn Docker](docker.md) | -| OpenWrt routers | Bản dựng MIPS/ARM, yêu cầu >32MB RAM trống | -| FreeBSD / NetBSD | Có bản dựng x86_64 và arm64 | - ---- - -## 5. Yêu cầu tối thiểu - -| Tài nguyên | Tối thiểu | Khuyến nghị | -|------------|-----------|-------------| -| RAM | 10MB trống | 32MB+ trống | -| Lưu trữ | 20MB (binary) | 50MB+ (với workspace) | -| CPU | Bất kỳ (đơn nhân 0.6GHz+) | — | -| OS | Linux (kernel 3.x+) | Linux 5.x+ | -| Mạng | Bắt buộc (cho các lệnh gọi API LLM) | Ethernet hoặc WiFi | - ---- - -## 6. Cách kiểm thử và đóng góp - -```bash -# 1. Tải xuống cho kiến trúc của bạn -wget https://github.com/sipeed/picoclaw/releases/latest/download/picoclaw_Linux_arm64.tar.gz -tar xzf picoclaw_Linux_arm64.tar.gz - -# 2. Khởi tạo -./picoclaw onboard - -# 3. Kiểm thử -./picoclaw agent -m "Hello, what board am I running on?" -``` - -Các bản dựng có sẵn: `linux-amd64`, `linux-arm64`, `linux-arm`, `linux-riscv64`, `linux-loong64`, `linux-mipsle` - -### Thêm phần cứng của bạn - -1. Fork kho lưu trữ này -2. Thêm chip / sản phẩm / bo mạch của bạn vào bảng tương ứng -3. Bao gồm: tên, kiến trúc, SoC, RAM, năm và liên kết nếu có -4. Gửi PR - -Nhà sản xuất phần cứng: muốn thêm hỗ trợ chính thức hoặc đồng quảng bá? Mở issue hoặc liên hệ qua [Discord](https://discord.gg/V4sAZ9XWpN). +See the maintained [platform guide](hardware-compatibility.md) or [中文说明](hardware-compatibility.zh.md). Built-in hardware tools have been removed; the current automated release target is Linux amd64. diff --git a/docs/guides/hardware-compatibility.zh.md b/docs/guides/hardware-compatibility.zh.md index 2182d3ed..652b4a02 100644 --- a/docs/guides/hardware-compatibility.zh.md +++ b/docs/guides/hardware-compatibility.zh.md @@ -1,151 +1,14 @@ -> 返回 [README](../../README.md) +# 平台与硬件功能边界 -# 🖥️ PicoClaw 硬件兼容性列表 - -PicoClaw 几乎可以在任何 Linux 设备上运行。本页面记录了已验证的芯片、产品和开发板。 - -**你的硬件不在列表中?** 提交 PR 来添加它!欢迎硬件厂商贡献和联合推广。 - ---- - -## 1. 已验证的芯片支持 - -### x86 - -| 厂商 | 芯片 | 备注 | -|------|------|------| -| Intel | Any x86 CPU (i386+) | 所有桌面/服务器/笔记本处理器 | -| AMD | Any x86 CPU | 所有桌面/服务器/笔记本处理器 | - -### ARM - -| 子架构 | 典型芯片 | 备注 | -|--------|----------|------| -| ARMv6 | [BCM2835](https://www.raspberrypi.com/documentation/computers/processors.html#bcm2835) (Raspberry Pi 1/Zero) | 单核 ARM1176JZF-S | -| ARMv7 | [Allwinner V3s](https://linux-sunxi.org/V3s) | 单核 Cortex-A7,用于 LicheePi Zero | -| ARM64 | [Allwinner H618](https://linux-sunxi.org/H618) | 四核 Cortex-A53,用于 Orange Pi Zero 3 | -| ARM64 | [BCM2711](https://www.raspberrypi.com/documentation/computers/processors.html#bcm2711) (Raspberry Pi 4) | 四核 Cortex-A72 | -| ARM64 | [BCM2712](https://www.raspberrypi.com/documentation/computers/processors.html#bcm2712) (Raspberry Pi 5) | 四核 Cortex-A76 | -| ARM64 | [AX630C](https://www.axera-tech.com/) (爱芯元智) | 双核 Cortex-A53 + NPU,用于 NanoKVM-Pro / MaixCAM2 | - -### RISC-V (riscv64) - -| 厂商 | 芯片 | 核心 | 备注 | -|------|------|------|------| -| [SOPHGO (算能)](https://www.sophgo.com/) | SG2002 | C906 @ 1GHz | 256MB DDR3 片上内存,用于 LicheeRV-Nano / NanoKVM / MaixCAM | -| [Allwinner (全志)](https://www.allwinnertech.com/) | V861 | Dual C907 | 128MB DDR3L 片上内存,1 TOPS NPU,4K AI 摄像头 SiP | -| [Allwinner (全志)](https://www.allwinnertech.com/) | V881 | C907 | RISC-V AI 摄像头系列 | -| [Arterytek (匠芯创)](https://www.arterytek.com/) | D213 | RISC-V | 用于 HaaS506-LD1 工业 RTU | -| [SpacemiT (进迭)](https://www.spacemit.com/) | K1 | 8x X60 @ 1.8GHz | 用于 Milk-V Jupiter, BananaPi BPI-F3 | -| [SpacemiT (进迭)](https://www.spacemit.com/) | K3 | 8x X100 @ 2.5GHz | 符合 RVA23 规范,1024 位 RVV,FP8 AI 推理 | -| [Zhihe (知合)](https://www.zhihe-tech.com/) | A210 | High-perf RISC-V | 8 核,16MB L3 缓存,桌面级 | -| [Canaan (嘉楠)](https://www.canaan-creative.com/) | K230 | Dual C908 @ 1.6GHz | 6 TOPS KPU,用于 CanMV-K230 | - -### MIPS - -| 厂商 | 芯片 | 备注 | -|------|------|------| -| MediaTek | [MT7620](https://www.mediatek.com/products/home-networking/mt7620) | MIPS24KEc @ 580MHz,用于许多 OpenWrt 路由器(如小米路由器 3G) | - -### LoongArch (loong64) - -| 厂商 | 芯片 | 备注 | -|------|------|------| -| [Loongson (龙芯)](https://www.loongson.cn/) | 3A5000 | 四核 LA464 @ 2.5GHz,桌面/工作站 | -| [Loongson (龙芯)](https://www.loongson.cn/) | 3A6000 | 四核 4C/8T @ 2.5GHz,IPC 可与 Intel 第十代相媲美 | -| [Loongson (龙芯)](https://www.loongson.cn/) | 2K1000LA | 双核 @ 1GHz,工业/物联网应用 | - ---- - -## 2. 已验证的产品(按发布日期排列) - -已通过 PicoClaw 测试的消费产品、路由器和工业设备。 - -| 年份 | 产品 | 架构 | SoC | 内存 | 类别 | -|------|------|------|-----|------|------| -| 2009 | Nokia N900 | ARM (A8) | OMAP3430 | 256MB | 智能手机 | -| 2012 | Samsung Galaxy Note 10.1 (N8000) | ARM (A9) | Exynos 4412 | 2GB | 平板电脑 | -| 2016 | Xiaomi Router 3G (小米路由器3G) | MIPS | MT7620 | 256MB | 路由器 (OpenWrt) | -| 2018 | Phicomm N1 (斐讯N1) | ARM64 (A53) | S905D | 2GB | 电视盒子 / 家庭服务器 | -| 2019 | Xiaomi AI Speaker (小爱音箱) | ARM64 (A53) | — | 256MB | 智能音箱 | -| 2024 | [NanoKVM](https://wiki.sipeed.com/hardware/en/kvm/NanoKVM/introduction.html) | RISC-V | SG2002 | 256MB | IP-KVM | -| 2025 | HaaS506-LD1 | RISC-V | D213 | 128MB | 工业 RTU | -| 2025 | [NanoKVM-Pro](https://wiki.sipeed.com/hardware/en/kvm/NanoKVM_Pro/introduction.html) | ARM64 (A53) | AX630C | 1GB | 专业 IP-KVM | -| 2026 | [MaixCAM2](https://wiki.sipeed.com/hardware/en/maixcam/index.html) | ARM64 (A53) | AX630C | 1/4GB | 4K AI 摄像头 | - ---- - -## 3. 已验证的开发板(按发布日期排列) - -| 年份 | 开发板 | 架构 | SoC | 内存 | 购买链接 | -|------|--------|------|-----|------|----------| -| 2012 | [Raspberry Pi 1 Model B](https://www.raspberrypi.com/products/) | ARMv6 | BCM2835 | 512MB | — | -| 2015 | [Raspberry Pi 2 Model B](https://www.raspberrypi.com/products/raspberry-pi-2-model-b/) | ARMv7 (A7) | BCM2836 | 1GB | — | -| 2015 | [Raspberry Pi Zero](https://www.raspberrypi.com/products/raspberry-pi-zero/) | ARMv6 | BCM2835 | 512MB | — | -| 2016 | [Raspberry Pi 3 Model B](https://www.raspberrypi.com/products/raspberry-pi-3-model-b/) | ARM64 (A53) | BCM2837 | 1GB | — | -| 2017 | [LicheePi Zero](https://wiki.sipeed.com/hardware/en/lichee/Zero/Zero.html) | ARMv7 (A7) | Allwinner V3s | 64MB | [Sipeed](https://sipeed.com/) | -| 2019 | [Raspberry Pi 4 Model B](https://www.raspberrypi.com/products/raspberry-pi-4-model-b/) | ARM64 (A72) | BCM2711 | 1~8GB | [RPi](https://www.raspberrypi.com/) | -| 2023 | [Raspberry Pi 5](https://www.raspberrypi.com/products/raspberry-pi-5/) | ARM64 (A76) | BCM2712 | 2~8GB | [RPi](https://www.raspberrypi.com/) | -| 2024 | [LicheeRV-Nano](https://wiki.sipeed.com/hardware/en/lichee/RV_Nano/1_intro.html) | RISC-V | SG2002 | 256MB | [AliExpress](https://www.aliexpress.com/item/1005006519668532.html) | -| 2024 | [MaixCAM-Pro](https://wiki.sipeed.com/hardware/en/maixcam/index.html) | RISC-V | SG2002 | 256MB | [Sipeed](https://sipeed.com/) | -| 2024 | [Milk-V Duo 64M](https://milkv.io/docs/duo/getting-started/duo) | RISC-V | CV1800B | 64MB | [Milk-V](https://milkv.io/) | -| 2024 | [CanMV-K230](https://developer.canaan-creative.com/k230_canmv/en/main/) | RISC-V | K230 | 512MB | [Canaan](https://www.canaan-creative.com/) | - ---- - -## 4. 同样适用于 - -### Android 手机(通过 Termux) - -任何 ARM64 Android 手机(2015 年以后),1GB 以上内存。安装 [Termux](https://github.com/termux/termux-app),使用 `proot` 运行 PicoClaw。 - - -### 桌面 / 服务器 / 云 - -| 平台 | 备注 | -|------|------| -| x86_64 Linux | 原生二进制文件,无依赖 | -| x86_64 Windows | 原生二进制文件 | -| macOS (Intel / Apple Silicon) | 原生二进制文件 | -| Docker (any platform) | `docker compose` 一行命令,参见 [Docker 指南](docker.md) | -| OpenWrt routers | MIPS/ARM 构建,需要 >32MB 可用内存 | -| FreeBSD / NetBSD | 提供 x86_64 和 arm64 构建 | - ---- - -## 5. 最低要求 - -| 资源 | 最低要求 | 推荐配置 | -|------|----------|----------| -| 内存 | 10MB 可用 | 32MB 以上可用 | -| 存储 | 20MB(二进制文件) | 50MB 以上(含工作区) | -| CPU | 任意(单核 0.6GHz 以上) | — | -| 操作系统 | Linux (kernel 3.x+) | Linux 5.x+ | -| 网络 | 必需(用于 LLM API 调用) | 以太网或 WiFi | - ---- - -## 6. 如何测试与贡献 +本 fork 的自动构建与发布目标为 **Linux amd64**,源码构建、发布包和自更新方式见 [README](../../README.md)。 ```bash -# 1. 下载适合你架构的版本 -wget https://github.com/sipeed/picoclaw/releases/latest/download/picoclaw_Linux_arm64.tar.gz -tar xzf picoclaw_Linux_arm64.tar.gz - -# 2. 初始化 -./picoclaw onboard - -# 3. 测试 -./picoclaw agent -m "Hello, what board am I running on?" +make build GOOS=linux GOARCH=amd64 +# build/picoclaw-linux-amd64 ``` -可用构建版本:`linux-amd64`, `linux-arm64`, `linux-arm`, `linux-riscv64`, `linux-loong64`, `linux-mipsle` +Makefile 仍保留其他交叉编译命令,但不代表当前验证过这些平台或设备。部署前需要自行验证目标平台、渠道 SDK 及运行行为;飞书 SDK 不支持 32 位平台。不再维护上游的芯片/开发板验证列表,也不要混用上游发行包更新本 fork。 -### 添加你的硬件 +内置 I²C、SPI、串口工具、USB 设备监控和 hardware Skill 已移除。硬件接入通过按需安装的 Skill 和外部工具完成;这不影响 CLI/Gateway 在支持的主机上运行。 -1. Fork 本仓库 -2. 将你的芯片/产品/开发板添加到相应的表格中 -3. 包含:名称、架构、SoC、内存、年份,以及可用的链接 -4. 提交 PR - -硬件厂商:想要添加官方支持或联合推广?请提交 issue 或通过 [Discord](https://discord.gg/V4sAZ9XWpN) 联系我们。 +办公文件处理使用单独的 Docker 环境,见[办公 Skills](office-skills.zh.md)。 diff --git a/docs/guides/routing-guide.md b/docs/guides/routing-guide.md index 595ac181..15db55f4 100644 --- a/docs/guides/routing-guide.md +++ b/docs/guides/routing-guide.md @@ -1,6 +1,6 @@ # Routing Guide -> Back to [README](../README.md) +> Back to [README](../../README.md) In PicoClaw, routing has two user-facing parts: @@ -75,8 +75,9 @@ This guide explains how to configure both for real deployments. }, { "model_name": "flash-light", - "provider": "gemini", - "model": "gemini-2.0-flash-exp", + "provider": "openai", + "model": "your-light-model-id", + "api_base": "https://your-compatible-endpoint.example/v1", "api_keys": ["sk-light"] } ], diff --git a/docs/guides/routing-guide.zh.md b/docs/guides/routing-guide.zh.md index 62b10b04..c447d1cf 100644 --- a/docs/guides/routing-guide.zh.md +++ b/docs/guides/routing-guide.zh.md @@ -75,8 +75,9 @@ PicoClaw 里用户能直接感知到的“路由”主要有两部分: }, { "model_name": "flash-light", - "provider": "gemini", - "model": "gemini-2.0-flash-exp", + "provider": "openai", + "model": "your-light-model-id", + "api_base": "https://your-compatible-endpoint.example/v1", "api_keys": ["sk-light"] } ], diff --git a/docs/guides/session-guide.md b/docs/guides/session-guide.md index 12087521..722c58aa 100644 --- a/docs/guides/session-guide.md +++ b/docs/guides/session-guide.md @@ -1,6 +1,6 @@ # Session Guide -> Back to [README](../README.md) +> Back to [README](../../README.md) PicoClaw sessions decide which messages share the same conversation history. If your bot "remembers too much" or "forgets too much", the first thing to check is the session configuration. diff --git a/docs/guides/spawn-tasks.md b/docs/guides/spawn-tasks.md index 05a5215d..20454020 100644 --- a/docs/guides/spawn-tasks.md +++ b/docs/guides/spawn-tasks.md @@ -1,6 +1,6 @@ # 🔄 Spawn & Async Tasks -> Back to [README](../README.md) +> Back to [README](../../README.md) PicoClaw supports **asynchronous task execution** via the `spawn` tool. This is primarily used by the **Heartbeat** system to run long-running tasks without blocking the main agent loop. diff --git a/docs/operations/troubleshooting.fr.md b/docs/operations/troubleshooting.fr.md index adfc29ac..56bb7889 100644 --- a/docs/operations/troubleshooting.fr.md +++ b/docs/operations/troubleshooting.fr.md @@ -1,45 +1,3 @@ -# 🐛 Dépannage +# Troubleshooting this fork -> Retour au [README](../../README.md) - -## "model ... not found in model_list" ou OpenRouter "free is not a valid model ID" - -**Symptôme :** Vous voyez l'une des erreurs suivantes : - -- `Error creating provider: model "openrouter/free" not found in model_list` -- OpenRouter retourne 400 : `"free is not a valid model ID"` - -**Cause :** Le champ `model` dans votre entrée `model_list` est ce qui est envoyé à l'API. Pour OpenRouter, vous devez utiliser l'identifiant de modèle **complet**, pas un raccourci. - -- **Incorrect :** `"model": "free"` → OpenRouter reçoit `free` et le rejette. -- **Correct :** `"model": "openrouter/free"` → OpenRouter reçoit `openrouter/free` (routage automatique du niveau gratuit). - -**Correction :** Dans `~/.picoclaw/config.json` (ou votre chemin de configuration) : - -1. **agents.defaults.model_name** doit correspondre à un `model_name` dans `model_list` (par ex. `"openrouter-free"`). -2. Le **model** de cette entrée doit être un identifiant de modèle OpenRouter valide, par exemple : - - `"openrouter/free"` – niveau gratuit automatique - - `"google/gemini-2.0-flash-exp:free"` - - `"meta-llama/llama-3.1-8b-instruct:free"` - -Exemple : - -```json -{ - "agents": { - "defaults": { - "model_name": "openrouter-free" - } - }, - "model_list": [ - { - "model_name": "openrouter-free", - "model": "openrouter/free", - "api_key": "sk-or-v1-YOUR_OPENROUTER_KEY", - "api_base": "https://openrouter.ai/api/v1" - } - ] -} -``` - -Obtenez votre clé sur [OpenRouter Keys](https://openrouter.ai/keys). +The upstream provider presets no longer apply. See the maintained [troubleshooting guide](troubleshooting.md) or [中文说明](troubleshooting.zh.md) for current model, channel, configuration, and Office runtime issues. diff --git a/docs/operations/troubleshooting.ja.md b/docs/operations/troubleshooting.ja.md index c2da2a86..56bb7889 100644 --- a/docs/operations/troubleshooting.ja.md +++ b/docs/operations/troubleshooting.ja.md @@ -1,45 +1,3 @@ -# 🐛 トラブルシューティング +# Troubleshooting this fork -> [README](../../README.md) に戻る - -## "model ... not found in model_list" または OpenRouter "free is not a valid model ID" - -**症状:** 以下のいずれかのエラーが表示されます: - -- `Error creating provider: model "openrouter/free" not found in model_list` -- OpenRouter が 400 を返す:`"free is not a valid model ID"` - -**原因:** `model_list` エントリの `model` フィールドは API に送信される値です。OpenRouter では省略形ではなく、**完全な**モデル ID を使用する必要があります。 - -- **誤り:** `"model": "free"` → OpenRouter は `free` を受け取り、拒否します。 -- **正しい:** `"model": "openrouter/free"` → OpenRouter は `openrouter/free` を受け取ります(自動無料枠ルーティング)。 - -**修正方法:** `~/.picoclaw/config.json`(またはお使いの設定パス)で: - -1. **agents.defaults.model_name** は `model_list` 内の `model_name` と一致する必要があります(例:`"openrouter-free"`)。 -2. そのエントリの **model** は有効な OpenRouter モデル ID である必要があります。例: - - `"openrouter/free"` – 自動無料枠 - - `"google/gemini-2.0-flash-exp:free"` - - `"meta-llama/llama-3.1-8b-instruct:free"` - -設定例: - -```json -{ - "agents": { - "defaults": { - "model_name": "openrouter-free" - } - }, - "model_list": [ - { - "model_name": "openrouter-free", - "model": "openrouter/free", - "api_key": "sk-or-v1-YOUR_OPENROUTER_KEY", - "api_base": "https://openrouter.ai/api/v1" - } - ] -} -``` - -キーは [OpenRouter Keys](https://openrouter.ai/keys) で取得できます。 +The upstream provider presets no longer apply. See the maintained [troubleshooting guide](troubleshooting.md) or [中文说明](troubleshooting.zh.md) for current model, channel, configuration, and Office runtime issues. diff --git a/docs/operations/troubleshooting.md b/docs/operations/troubleshooting.md index 16229f36..7db55cef 100644 --- a/docs/operations/troubleshooting.md +++ b/docs/operations/troubleshooting.md @@ -1,50 +1,40 @@ -# Troubleshooting +# Troubleshooting this fork -## "model ... not found in model_list" or OpenRouter "free is not a valid model ID" +## Model alias not found -**Symptom:** You see either: +`agents.defaults.model_name` must match an enabled entry's `model_name` in `model_list`. It is a local alias, separate from the remote model ID. -- `Error creating provider: model "openrouter/free" not found in model_list` -- OpenRouter returns 400: `"free is not a valid model ID"` +## Unsupported provider or rejected model ID -**Cause:** PicoClaw now resolves provider/model in two steps: - -- If `provider` is set, the `model` field is sent to that provider unchanged. -- If `provider` is omitted, PicoClaw infers the provider from the first `/` segment and sends everything after that first `/` as the runtime model ID. - -For OpenRouter free-tier routing, the preferred config is explicit `provider`. - -- **Wrong:** `"model": "free"` → no OpenRouter provider is selected, so `free` is not a valid OpenRouter model route. -- **Right:** `"provider": "openrouter", "model": "free"` → OpenRouter receives `free`. -- **Also supported:** `"model": "openrouter/free"` → provider resolves to `openrouter`, runtime model ID resolves to `free`. - -**Fix:** In `~/.picoclaw/config.json` (or your config path): - -1. **agents.defaults.model_name** must match a `model_name` in `model_list` (e.g. `"openrouter-free"`). -2. That entry should preferably set **provider** to `openrouter`, and **model** should be a valid OpenRouter model ID, for example: - - `"free"` – auto free-tier - - `"google/gemini-2.0-flash-exp:free"` - - `"meta-llama/llama-3.1-8b-instruct:free"` - -Example snippet: +Only `openai` and `anthropic` chat protocols remain. For compatible endpoints, specify the supported protocol, complete endpoint and remote model ID explicitly: ```json { - "agents": { - "defaults": { - "model_name": "openrouter-free" - } - }, - "model_list": [ - { - "model_name": "openrouter-free", - "provider": "openrouter", - "model": "free", - "api_keys": ["sk-or-v1-YOUR_OPENROUTER_KEY"], - "api_base": "https://openrouter.ai/api/v1" - } - ] + "provider": "openai", + "api_base": "https://openrouter.ai/api/v1", + "model": "vendor/your-model-id", + "api_keys": ["YOUR_API_KEY"] } ``` -Get your key at [OpenRouter Keys](https://openrouter.ai/keys). +The example fields belong on a `model_list` entry. Replace the remote ID with one supported by your service. With an explicit provider, the complete `model` string is preserved. `provider: "openrouter"` and other vendor presets have been removed. See the [provider guide](../guides/providers.md). + +## Removed channel prevents startup + +Remove obsolete entries from both `config.json` and `.security.yml`, including old `channels` or current `channel_list` mappings. Disabling an unknown channel type is insufficient. Current channel credentials belong under `channel_list..settings`. + +Obsolete `devices`, `tools.i2c`, `tools.spi`, and `tools.serial` settings are ignored and disappear when the configuration is saved. See the [upgrade notes](../../README.md#从旧版或上游配置升级). + +## Configuration edits do not take effect + +Check `PICOCLAW_HOME` and `PICOCLAW_CONFIG`, and inspect the paths printed by `picoclaw status`. A `.security.yml` beside the selected config file may override JSON values. Restart the Gateway when changing settings unless hot reload is enabled for the relevant change. + +`status` reports configuration and stored authentication state; it does not probe model connectivity or service health. Gateway exposes `/health` and `/ready` on its configured HTTP address. + +## Office runtime missing + +Run `office.sh setup` and `office.sh check` as the Gateway user. See the [Office runtime guide](../guides/office-skills.zh.md). Updating the binary does not overwrite existing workspace Skills. + +## Cron CLI + +The current `picoclaw cron add` command supports recurring schedules through `--every` and `--cron`. One-shot reminders are available through the cron tool, rather than a CLI `at_seconds` flag. diff --git a/docs/operations/troubleshooting.ms.md b/docs/operations/troubleshooting.ms.md index c9d987ab..56bb7889 100644 --- a/docs/operations/troubleshooting.ms.md +++ b/docs/operations/troubleshooting.ms.md @@ -1,43 +1,3 @@ -# Penyelesaian Masalah +# Troubleshooting this fork -## "model ... not found in model_list" atau OpenRouter "free is not a valid model ID" - -**Gejala:** Anda akan melihat salah satu daripada mesej berikut: - -- `Error creating provider: model "openrouter/free" not found in model_list` -- OpenRouter memulangkan 400: `"free is not a valid model ID"` - -**Punca:** Medan `model` dalam entri `model_list` anda ialah nilai yang dihantar ke API. Untuk OpenRouter, anda mesti menggunakan ID model **penuh**, bukan bentuk singkatan. - -- **Salah:** `"model": "free"` → OpenRouter menerima `free` dan menolaknya. -- **Betul:** `"model": "openrouter/free"` → OpenRouter menerima `openrouter/free` (routing auto free-tier). - -**Penyelesaian:** Dalam `~/.picoclaw/config.json` (atau laluan config anda): - -1. **agents.defaults.model** mesti sepadan dengan `model_name` dalam `model_list` (contohnya `"openrouter-free"`). -2. Medan **model** bagi entri tersebut mesti merupakan ID model OpenRouter yang sah, contohnya: - - `"openrouter/free"` – auto free-tier - - `"google/gemini-2.0-flash-exp:free"` - - `"meta-llama/llama-3.1-8b-instruct:free"` - -Example snippet: - -```json -{ - "agents": { - "defaults": { - "model": "openrouter-free" - } - }, - "model_list": [ - { - "model_name": "openrouter-free", - "model": "openrouter/free", - "api_key": "sk-or-v1-YOUR_OPENROUTER_KEY", - "api_base": "https://openrouter.ai/api/v1" - } - ] -} -``` - -Dapatkan kunci anda di [OpenRouter Keys](https://openrouter.ai/keys). +The upstream provider presets no longer apply. See the maintained [troubleshooting guide](troubleshooting.md) or [中文说明](troubleshooting.zh.md) for current model, channel, configuration, and Office runtime issues. diff --git a/docs/operations/troubleshooting.pt-br.md b/docs/operations/troubleshooting.pt-br.md index e99679b2..56bb7889 100644 --- a/docs/operations/troubleshooting.pt-br.md +++ b/docs/operations/troubleshooting.pt-br.md @@ -1,45 +1,3 @@ -# 🐛 Solução de Problemas +# Troubleshooting this fork -> Voltar ao [README](../../README.md) - -## "model ... not found in model_list" ou OpenRouter "free is not a valid model ID" - -**Sintoma:** Você vê um dos seguintes erros: - -- `Error creating provider: model "openrouter/free" not found in model_list` -- OpenRouter retorna 400: `"free is not a valid model ID"` - -**Causa:** O campo `model` na sua entrada `model_list` é o que é enviado para a API. Para o OpenRouter, você deve usar o ID de modelo **completo**, não uma abreviação. - -- **Errado:** `"model": "free"` → OpenRouter recebe `free` e rejeita. -- **Correto:** `"model": "openrouter/free"` → OpenRouter recebe `openrouter/free` (roteamento automático do nível gratuito). - -**Correção:** Em `~/.picoclaw/config.json` (ou seu caminho de configuração): - -1. **agents.defaults.model_name** deve corresponder a um `model_name` em `model_list` (ex.: `"openrouter-free"`). -2. O **model** dessa entrada deve ser um ID de modelo OpenRouter válido, por exemplo: - - `"openrouter/free"` – nível gratuito automático - - `"google/gemini-2.0-flash-exp:free"` - - `"meta-llama/llama-3.1-8b-instruct:free"` - -Exemplo: - -```json -{ - "agents": { - "defaults": { - "model_name": "openrouter-free" - } - }, - "model_list": [ - { - "model_name": "openrouter-free", - "model": "openrouter/free", - "api_key": "sk-or-v1-YOUR_OPENROUTER_KEY", - "api_base": "https://openrouter.ai/api/v1" - } - ] -} -``` - -Obtenha sua chave em [OpenRouter Keys](https://openrouter.ai/keys). +The upstream provider presets no longer apply. See the maintained [troubleshooting guide](troubleshooting.md) or [中文说明](troubleshooting.zh.md) for current model, channel, configuration, and Office runtime issues. diff --git a/docs/operations/troubleshooting.vi.md b/docs/operations/troubleshooting.vi.md index 5472c6fc..56bb7889 100644 --- a/docs/operations/troubleshooting.vi.md +++ b/docs/operations/troubleshooting.vi.md @@ -1,45 +1,3 @@ -# 🐛 Khắc Phục Sự Cố +# Troubleshooting this fork -> Quay lại [README](../../README.md) - -## "model ... not found in model_list" hoặc OpenRouter "free is not a valid model ID" - -**Triệu chứng:** Bạn thấy một trong các lỗi sau: - -- `Error creating provider: model "openrouter/free" not found in model_list` -- OpenRouter trả về 400: `"free is not a valid model ID"` - -**Nguyên nhân:** Trường `model` trong mục `model_list` của bạn là giá trị được gửi đến API. Đối với OpenRouter, bạn phải sử dụng ID mô hình **đầy đủ**, không phải dạng viết tắt. - -- **Sai:** `"model": "free"` → OpenRouter nhận được `free` và từ chối. -- **Đúng:** `"model": "openrouter/free"` → OpenRouter nhận được `openrouter/free` (định tuyến tự động tầng miễn phí). - -**Cách sửa:** Trong `~/.picoclaw/config.json` (hoặc đường dẫn cấu hình của bạn): - -1. **agents.defaults.model_name** phải khớp với một `model_name` trong `model_list` (ví dụ: `"openrouter-free"`). -2. **model** của mục đó phải là ID mô hình OpenRouter hợp lệ, ví dụ: - - `"openrouter/free"` – tầng miễn phí tự động - - `"google/gemini-2.0-flash-exp:free"` - - `"meta-llama/llama-3.1-8b-instruct:free"` - -Ví dụ: - -```json -{ - "agents": { - "defaults": { - "model_name": "openrouter-free" - } - }, - "model_list": [ - { - "model_name": "openrouter-free", - "model": "openrouter/free", - "api_key": "sk-or-v1-YOUR_OPENROUTER_KEY", - "api_base": "https://openrouter.ai/api/v1" - } - ] -} -``` - -Lấy khóa của bạn tại [OpenRouter Keys](https://openrouter.ai/keys). +The upstream provider presets no longer apply. See the maintained [troubleshooting guide](troubleshooting.md) or [中文说明](troubleshooting.zh.md) for current model, channel, configuration, and Office runtime issues. diff --git a/docs/operations/troubleshooting.zh.md b/docs/operations/troubleshooting.zh.md index a33e2e13..4a1e81b8 100644 --- a/docs/operations/troubleshooting.zh.md +++ b/docs/operations/troubleshooting.zh.md @@ -1,52 +1,27 @@ -# 🐛 疑难解答 +# 疑难解答 -> 返回 [README](../../README.md) +## 找不到模型或提供商不支持 -## "model ... not found in model_list" 或 OpenRouter "free is not a valid model ID" +`agents.defaults.model_name` 必须对应 `model_list` 中已启用条目的 `model_name`。它是本地别名,不是远端模型 ID。 -**症状:** 你看到以下任一错误: +聊天模型仅支持 `openai` 和 `anthropic`。第三方兼容服务应显式填写协议、`api_base` 和完整远端 `model`,不要继续使用 `openrouter`、`gemini`、`ollama` 等旧 provider 名称。显式指定协议后,带厂商命名空间的模型 ID 会原样发送;参见[模型配置](../guides/providers.zh.md)。 -- `Error creating provider: model "openrouter/free" not found in model_list` -- OpenRouter 返回 400:`"free is not a valid model ID"` +## 升级后渠道启动失败 -**原因:** PicoClaw 现在按两步解析 provider 和 model: +从 `config.json` 和 `.security.yml` 中删除已移除的渠道条目,检查当前 `channel_list` 和旧版 `channels` 两种名称。仅设置 `enabled: false` 无法解决未知渠道类型。渠道密钥等专有字段应放在 `channel_list.<名称>.settings` 中。 -- 如果设置了 `provider`,则会把 `model` 原样发送给该 provider。 -- 如果未设置 `provider`,则会把 `model` 第一个 `/` 之前的字段当作 provider,并把第一个 `/` 之后的全部内容当作最终发送的模型 ID。 +旧的 `devices`、`tools.i2c`、`tools.spi`、`tools.serial` 会兼容忽略,保存后不再输出。详细清单见 [README 升级说明](../../README.md#从旧版或上游配置升级)。 -对于 OpenRouter 免费层路由,推荐显式设置 `provider`。 +## 配置修改没有生效 -- **错误:** `"model": "free"` → 不会选中 OpenRouter,`free` 也不是可直接路由的 OpenRouter 模型配置。 -- **正确:** `"provider": "openrouter", "model": "free"` → OpenRouter 收到 `free`。 -- **也兼容:** `"model": "openrouter/free"` → provider 解析为 `openrouter`,最终模型 ID 解析为 `free`。 +用 `picoclaw status` 检查实际配置路径,注意 `PICOCLAW_HOME`、`PICOCLAW_CONFIG` 及配置文件旁的 `.security.yml`。同名密钥可能被安全文件覆盖。没有启用对应热重载能力时,修改配置后重启 Gateway。 -**修复方法:** 在 `~/.picoclaw/config.json`(或你的配置路径)中: +`status` 展示配置和凭据状态,不验证模型连通性或服务健康。运行状态请检查服务日志,以及 Gateway HTTP 地址上的 `/health`、`/ready`。 -1. **agents.defaults.model_name** 必须匹配 `model_list` 中的某个 `model_name`(例如 `"openrouter-free"`)。 -2. 该条目推荐显式设置 **provider** 为 `openrouter`,并在 **model** 中填写有效的 OpenRouter 模型 ID,例如: - - `"free"` – 自动免费层 - - `"google/gemini-2.0-flash-exp:free"` - - `"meta-llama/llama-3.1-8b-instruct:free"` +## 办公文件环境不可用 -示例片段: +以 Gateway 用户执行 `office.sh setup` 和 `office.sh check`,见[办公环境说明](../guides/office-skills.zh.md)。更新二进制不会自动覆盖已有工作区 Skill。 -```json -{ - "agents": { - "defaults": { - "model_name": "openrouter-free" - } - }, - "model_list": [ - { - "model_name": "openrouter-free", - "provider": "openrouter", - "model": "free", - "api_keys": ["sk-or-v1-YOUR_OPENROUTER_KEY"], - "api_base": "https://openrouter.ai/api/v1" - } - ] -} -``` +## 定时任务 CLI -在 [OpenRouter Keys](https://openrouter.ai/keys) 获取你的密钥。 +`picoclaw cron add` 支持 `--every`、`--cron` 周期任务。一次性提醒通过 cron 工具设置,当前没有 CLI `at_seconds` 参数。 diff --git a/docs/project/CONTRIBUTING.zh.md b/docs/project/CONTRIBUTING.zh.md index ca6c66b3..c09b975b 100644 --- a/docs/project/CONTRIBUTING.zh.md +++ b/docs/project/CONTRIBUTING.zh.md @@ -1,303 +1,5 @@ -# 参与贡献 PicoClaw +# 参与本 fork 的开发 -感谢你对 PicoClaw 的关注!本项目是一个社区驱动的开源项目,目标是构建 轻量灵活,人人可用 的个人AI助手。我们欢迎一切形式的贡献:Bug 修复、新功能、文档、翻译和测试。 +本仓库是 `loveuer/picoclaw`,功能范围与上游不同。开发约定和检查命令统一维护在 [CONTRIBUTING.md](../../CONTRIBUTING.md)。 -PicoClaw 本身在很大程度上是借助 AI 辅助开发的——我们拥抱这种方式,并围绕它构建了贡献流程。 - -## 目录 - -- [行为准则](#行为准则) -- [贡献方式](#贡献方式) -- [快速开始](#快速开始) -- [开发环境配置](#开发环境配置) -- [提交修改](#提交修改) -- [AI 辅助贡献](#ai-辅助贡献) -- [Pull Request 流程](#pull-request-流程) -- [分支策略](#分支策略) -- [代码审查](#代码审查) -- [沟通渠道](#沟通渠道) - ---- - -## 行为准则 - -我们致力于维护一个友好、互相尊重的社区环境。请保持善意、建设性的态度,并善意地理解他人。任何形式的骚扰或歧视均不被接受。 - ---- - -## 贡献方式 - -- **Bug 反馈** — 使用 Bug 报告模板提交 Issue。 -- **功能建议** — 使用功能请求模板提交 Issue,建议在开始实现前先进行讨论。 -- **代码贡献** — 修复 Bug 或实现新功能,参见下方工作流程。 -- **文档改进** — 完善 README、文档、代码注释或翻译。 -- **测试与验证** — 在新硬件、新渠道或新 LLM 提供商上运行 PicoClaw 并反馈结果。 - -对于较大的新功能,请先提交 Issue 讨论设计方案,再动手写代码。这能避免无效投入,也确保与项目方向保持一致。 - ---- - -## 快速开始 - -1. 在 GitHub 上 **Fork** 本仓库。 -2. 将你的 Fork **克隆**到本地: - ```bash - git clone https://github.com/<你的用户名>/picoclaw.git - cd picoclaw - ``` -3. 添加上游远程仓库: - ```bash - git remote add upstream https://github.com/sipeed/picoclaw.git - ``` - ---- - -## 开发环境配置 - -### 前置依赖 - -- Go 1.25 或更高版本 -- `make` - -### 构建 - -```bash -make build # 构建二进制文件(会先执行 go generate) -make generate # 仅执行 go generate -make check # 完整的提交前检查:deps + fmt + vet + test -``` - -### 运行测试 - -```bash -make test # 运行所有测试 -go test -run TestName -v ./pkg/session/ # 运行单个测试 -go test -bench=. -benchmem -run='^$' ./... # 运行基准测试 -``` - -### 代码风格 - -```bash -make fmt # 格式化代码 -make vet # 静态分析 -make lint # 完整的 lint 检查 -``` - -所有 CI 检查通过后 PR 才能被合并。推送代码前请先在本地运行 `make check`,提前发现问题。 - ---- - -## 提交修改 - -### 分支管理 - -始终从 `main` 分支切出,并在 PR 中以 `main` 为目标分支。不要直接向 `main` 或任何 `release/*` 分支推送代码: - -```bash -git checkout main -git pull upstream main -git checkout -b 你的功能分支名 -``` - -请使用描述性的分支名,例如:`fix/telegram-timeout`、`feat/ollama-provider`、`docs/contributing-guide`。 - -### Commit 规范 - -- 使用英文撰写清晰、简洁的 commit 信息。 -- 使用祈使句:写 "Add retry logic",而不是 "Added retry logic"。 -- 有关联 Issue 时请引用:`Fix session leak (#123)`。 -- 保持 commit 专注,每个 commit 只做一件事。 -- 对于小的清理或拼写修正,提 PR 前请将其合并为一个 commit。 -- 按照 [Conventional Commits](https://www.conventionalcommits.org/zh-hans/v1.0.0/) 规范来撰写 - -### 保持与上游同步 - -提 PR 前,请将你的分支变基到上游 `main`: - -```bash -git fetch upstream -git rebase upstream/main -``` - ---- - -## AI 辅助贡献 - -PicoClaw 在很大程度上借助 AI 辅助开发,我们完全拥抱这种开发方式。但贡献者必须清楚地了解自己在使用 AI 工具时所承担的责任。 - -### 必须披露 AI 使用情况 - -每个 PR 都必须通过 PR 模板中的 **🤖 AI 代码生成** 部分披露 AI 参与情况,共分三个级别: - -| 级别 | 说明 | -|---|---| -| 🤖 完全由 AI 生成 | AI 编写代码,贡献者负责审查和验证 | -| 🛠️ 主要由 AI 生成 | AI 起草,贡献者做了较大修改 | -| 👨‍💻 主要由人工编写 | 贡献者主导,AI 仅提供辅助或未使用 AI | - -我们期望你诚实填写。三种级别均可接受,没有任何歧视——重要的是贡献的质量。 - -### 你对提交的代码负全责 - -使用 AI 生成代码并不能减轻你作为贡献者的责任。在提交含有 AI 生成代码的 PR 之前,你必须: - -- **逐行阅读并理解**生成的代码。 -- **在真实环境中测试**(参见 PR 模板中的测试环境部分)。 -- **检查安全问题** — AI 模型可能生成存在安全隐患的代码(如路径穿越、注入攻击、凭据泄露等),请仔细审查。 -- **验证正确性** — AI 生成的逻辑可能听起来合理但实际上是错误的,请验证行为,而不仅仅是语法。 - -如果明显可以看出贡献者没有阅读或测试 AI 生成的代码,该 PR 将被直接关闭,不予审查。 - -### AI 生成代码的质量标准 - -AI 生成的代码与人工编写的代码遵循**相同的质量要求**: - -- 必须通过所有 CI 检查(`make check`)。 -- 必须符合 Go 惯用写法,并与现有代码库的风格保持一致。 -- 不得引入不必要的抽象、死代码或过度设计。 -- 须在适当的地方包含或更新测试。 - -### 安全审查 - -AI 生成的代码需要格外仔细的安全审查。请特别关注以下方面: - -- 文件路径处理与沙箱逃逸(项目历史中的 commit `244eb0b` 就是真实案例) -- channel 处理器和 tool 实现中的外部输入校验 -- 凭据或密钥的处理 -- 命令执行(`exec.Command`、shell 调用等) - -如果你不确定某段 AI 生成代码是否安全,请在 PR 中说明——审查者会帮助判断。 - ---- - -## Pull Request 流程 - -### 提 PR 前的检查 - -- [ ] 在本地运行 `make check` 并确认通过。 -- [ ] 完整填写 PR 模板,包括 AI 披露部分。 -- [ ] 在 PR 描述中关联相关 Issue。 -- [ ] 保持 PR 专注,避免将不相关的修改混在一起。 - -### PR 模板各部分说明 - -PR 模板要求填写: - -- **描述** — 这个改动做了什么,为什么要做? -- **变更类型** — Bug 修复、新功能、文档或重构。 -- **AI 代码生成** — AI 参与情况披露(必填)。 -- **关联 Issue** — 此 PR 解决的 Issue 链接。 -- **技术背景** — 参考链接和设计理由(纯文档类 PR 可跳过)。 -- **测试环境** — 用于测试的硬件、操作系统、模型/提供商和渠道。 -- **验证证据** — 可选的日志或截图,用于证明改动有效。 -- **检查清单** — 自我审查确认。 - -### PR 规模 - -请尽量提交小而易于审查的 PR。一个涉及 5 个文件共 200 行改动的 PR,远比涉及 30 个文件共 2000 行改动的 PR 容易审查。如果你的功能较大,可以考虑将其拆分为一系列逻辑完整的小 PR。 - ---- - -## 分支策略 - -### 长期分支 - -- **`main`** — 活跃开发分支。所有功能 PR 均以 `main` 为目标。该分支受保护:禁止直接推送,合并前必须获得至少一名维护者的批准。 -- **`release/x.y`** — 稳定发布分支,在某个版本准备发布时从 `main` 切出。这些分支的保护级别高于 `main`。 - -### 合并到 `main` 的前提条件 - -PR 必须同时满足以下所有条件,才能被合并: - -1. **CI 全部通过** — 所有 GitHub Actions 工作流(lint、test、build)均为绿色。 -2. **获得审查者批准** — 至少一名维护者已批准该 PR。 -3. **无未解决的审查意见** — 所有审查讨论线程均已关闭。 -4. **PR 模板填写完整** — 包括 AI 披露和测试环境信息。 - -### 谁可以合并 - -只有维护者才能合并 PR。贡献者不能合并自己的 PR,即使拥有写权限也不行。 - -### 合并策略 - -为保持 `main` 历史清晰可读,我们对大多数 PR 使用 **Squash Merge**。每个合并的 PR 变为一个包含 PR 编号的单独 commit,例如: - -``` -feat: Add Ollama provider support (#491) -``` - -如果一个 PR 包含多个独立、结构清晰、能讲述完整故事的 commit,维护者可视情况使用普通 merge。 - -### Release 分支 - -当某个版本准备就绪时,维护者会从 `main` 切出 `release/x.y` 分支。此后: - -- **新功能不会被回溯(backport)。** Release 分支切出后,不再接收任何新功能。 -- **安全修复和关键 Bug 修复会被 cherry-pick 进来。** 若 `main` 上的某个修复属于安全漏洞、数据丢失或崩溃类问题,维护者会将相关 commit cherry-pick 到受影响的 `release/x.y` 分支,并发布补丁版本。 - -如果你认为 `main` 上的某个修复应该被回溯到某个 release 分支,请在 PR 描述中注明,或单独开一个 Issue 说明。最终决定由维护者做出。 - -Release 分支的保护级别高于 `main`,在任何情况下均不允许直接推送。 - ---- - -## 代码审查 - -### 对贡献者的建议 - -- 在合理时间内回复审查意见。如果需要更多时间,请告知。 -- 更新 PR 以响应反馈时,简要说明改动内容(例如:"按建议改用了 `sync.RWMutex`")。 -- 如果你不同意某条反馈,请礼貌地阐述你的理由——审查者也可能有判断失误的时候。 -- 审查开始后请不要 force push——这会让审查者难以追踪变化。请使用额外的 commit,维护者在合并时会进行 squash。 - -### 对审查者的建议 - -审查重点: - -1. **正确性** — 代码是否实现了其声称的功能?是否存在边界情况? -2. **安全性** — 对 AI 生成代码、tool 实现和 channel 处理器尤其需要关注。 -3. **架构** — 实现方式是否与现有设计一致? -4. **简洁性** — 是否有更简单的方案?是否引入了不必要的复杂度? -5. **测试** — 改动是否有测试覆盖?现有测试是否仍然有意义? - -请给出建设性且具体的反馈。"如果两个 goroutine 同时调用这个函数可能会有竞态条件,建议在这里加一个 mutex" 远比 "这里看起来有问题" 更有帮助。 - -### 审查者列表 -提交对应PR后,可以参考下表联系对应的审查人员沟通 - -|Function| Reviewer| -|--- |--- | -|Provider|@yinwm | -|Channel |@yinwm/@alexhoshina | -|Agent |@lxowalle/@Zhaoyikaiii| -|Tools |@lxowalle| -|SKill || -|MCP || -|Optimization|@lxowalle| -|Security|| -|AI CI |@imguoguo| -|UX || -|Document|| - - - ---- - -## 沟通渠道 - -- **GitHub Issues** — Bug 报告、功能建议、设计讨论。 -- **GitHub Discussions** — 一般性问题、想法交流、社区讨论。 -- **Pull Request 评论** — 与具体代码相关的反馈。 -- **Wechat&Discord** — 当你有至少一个已合并的PR后,我们会邀请你加入开发者交流群 - -有疑问时,请先开 Issue 讨论,再动手写代码。这几乎没有成本,却能避免大量无效投入。 - ---- - -## 关于本项目的 AI 驱动起源 - -PicoClaw 的架构在人工监督下,经由 AI 辅助完成了大量设计和实现工作。如果你发现某处看起来奇怪或过度设计,这可能是该过程留下的痕迹——欢迎提 Issue 讨论。 - -我们相信,负责任地使用 AI 辅助开发能产生优秀的成果。我们同样相信,人类必须对自己提交的内容负责。这两点并不矛盾。 - -感谢你的贡献! +当前功能、配置、构建与发布方式见 [README](../../README.md),完整配置结构见 [config/config.example.json](../../config/config.example.json)。新增专用功能时优先考虑 Skill 或外部工具;删除功能时同步清理代码、依赖、配置、测试和文档,并考虑旧配置的升级兼容性。 diff --git a/docs/reference/cron.md b/docs/reference/cron.md index e421b37e..89496db0 100644 --- a/docs/reference/cron.md +++ b/docs/reference/cron.md @@ -1,6 +1,6 @@ # Scheduled Tasks and Cron Jobs -> Back to [README](../README.md) +> Back to [README](../../README.md) PicoClaw stores scheduled jobs in the current workspace and can run them either as reminders, full agent turns, or shell commands. diff --git a/docs/reference/mcp-cli.md b/docs/reference/mcp-cli.md index d530815a..a1961ac0 100644 --- a/docs/reference/mcp-cli.md +++ b/docs/reference/mcp-cli.md @@ -1,6 +1,6 @@ # MCP Server CLI -> Back to [README](../README.md) +> Back to [README](../../README.md) PicoClaw includes an `mcp` CLI command group for managing MCP server entries in `config.json`. diff --git a/docs/security/ANTIGRAVITY_AUTH.fr.md b/docs/security/ANTIGRAVITY_AUTH.fr.md deleted file mode 100644 index ef815255..00000000 --- a/docs/security/ANTIGRAVITY_AUTH.fr.md +++ /dev/null @@ -1,809 +0,0 @@ -> Retour au [README](../../README.md) - -# Guide d'authentification et d'intégration Antigravity - -## Aperçu - -**Antigravity** (Google Cloud Code Assist) est un fournisseur de modèles IA soutenu par Google qui offre l'accès à des modèles tels que Claude Opus 4.6 et Gemini via l'infrastructure cloud de Google. Ce document fournit un guide complet sur le fonctionnement de l'authentification, la récupération des modèles et l'implémentation d'un nouveau fournisseur dans PicoClaw. - ---- - -## Table des matières - -1. [Flux d'authentification](#flux-dauthentification) -2. [Détails de l'implémentation OAuth](#détails-de-limplémentation-oauth) -3. [Gestion des jetons](#gestion-des-jetons) -4. [Récupération de la liste des modèles](#récupération-de-la-liste-des-modèles) -5. [Suivi de l'utilisation](#suivi-de-lutilisation) -6. [Structure du plugin fournisseur](#structure-du-plugin-fournisseur) -7. [Exigences d'intégration](#exigences-dintégration) -8. [Points de terminaison API](#points-de-terminaison-api) -9. [Configuration](#configuration) -10. [Créer un nouveau fournisseur dans PicoClaw](#créer-un-nouveau-fournisseur-dans-picoclaw) - ---- - -## Flux d'authentification - -### 1. OAuth 2.0 avec PKCE - -Antigravity utilise **OAuth 2.0 avec PKCE (Proof Key for Code Exchange)** pour une authentification sécurisée : - -``` -┌─────────────┐ ┌─────────────────┐ -│ Client │ ───(1) Generate PKCE Pair────────> │ │ -│ │ ───(2) Open Auth URL─────────────> │ Google OAuth │ -│ │ │ Server │ -│ │ <──(3) Redirect with Code───────── │ │ -│ │ └─────────────────┘ -│ │ ───(4) Exchange Code for Tokens──> │ Token URL │ -│ │ │ │ -│ │ <──(5) Access + Refresh Tokens──── │ │ -└─────────────┘ └─────────────────┘ -``` - -### 2. Étapes détaillées - -#### Étape 1 : Générer les paramètres PKCE -```typescript -function generatePkce(): { verifier: string; challenge: string } { - const verifier = randomBytes(32).toString("hex"); - const challenge = createHash("sha256").update(verifier).digest("base64url"); - return { verifier, challenge }; -} -``` - -#### Étape 2 : Construire l'URL d'autorisation -```typescript -const AUTH_URL = "https://accounts.google.com/o/oauth2/v2/auth"; -const REDIRECT_URI = "http://localhost:51121/oauth-callback"; - -function buildAuthUrl(params: { challenge: string; state: string }): string { - const url = new URL(AUTH_URL); - url.searchParams.set("client_id", CLIENT_ID); - url.searchParams.set("response_type", "code"); - url.searchParams.set("redirect_uri", REDIRECT_URI); - url.searchParams.set("scope", SCOPES.join(" ")); - url.searchParams.set("code_challenge", params.challenge); - url.searchParams.set("code_challenge_method", "S256"); - url.searchParams.set("state", params.state); - url.searchParams.set("access_type", "offline"); - url.searchParams.set("prompt", "consent"); - return url.toString(); -} -``` - -**Portées requises :** -```typescript -const SCOPES = [ - "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/userinfo.email", - "https://www.googleapis.com/auth/userinfo.profile", - "https://www.googleapis.com/auth/cclog", - "https://www.googleapis.com/auth/experimentsandconfigs", -]; -``` - -#### Étape 3 : Gérer le callback OAuth - -**Mode automatique (développement local) :** -- Démarrer un serveur HTTP local sur le port 51121 -- Attendre la redirection de Google -- Extraire le code d'autorisation des paramètres de requête - -**Mode manuel (distant/sans interface graphique) :** -- Afficher l'URL d'autorisation à l'utilisateur -- L'utilisateur complète l'authentification dans son navigateur -- L'utilisateur colle l'URL de redirection complète dans le terminal -- Analyser le code depuis l'URL collée - -#### Étape 4 : Échanger le code contre des jetons -```typescript -const TOKEN_URL = "https://oauth2.googleapis.com/token"; - -async function exchangeCode(params: { - code: string; - verifier: string; -}): Promise<{ access: string; refresh: string; expires: number }> { - const response = await fetch(TOKEN_URL, { - method: "POST", - headers: { "Content-Type": "application/x-www-form-urlencoded" }, - body: new URLSearchParams({ - client_id: CLIENT_ID, - client_secret: CLIENT_SECRET, - code: params.code, - grant_type: "authorization_code", - redirect_uri: REDIRECT_URI, - code_verifier: params.verifier, - }), - }); - - const data = await response.json(); - - return { - access: data.access_token, - refresh: data.refresh_token, - expires: Date.now() + data.expires_in * 1000 - 5 * 60 * 1000, // 5 min buffer - }; -} -``` - -#### Étape 5 : Récupérer les données utilisateur supplémentaires - -**E-mail de l'utilisateur :** -```typescript -async function fetchUserEmail(accessToken: string): Promise { - const response = await fetch( - "https://www.googleapis.com/oauth2/v1/userinfo?alt=json", - { headers: { Authorization: `Bearer ${accessToken}` } } - ); - const data = await response.json(); - return data.email; -} -``` - -**ID du projet (requis pour les appels API) :** -```typescript -async function fetchProjectId(accessToken: string): Promise { - const headers = { - Authorization: `Bearer ${accessToken}`, - "Content-Type": "application/json", - "User-Agent": "google-api-nodejs-client/9.15.1", - "X-Goog-Api-Client": "google-cloud-sdk vscode_cloudshelleditor/0.1", - "Client-Metadata": JSON.stringify({ - ideType: "IDE_UNSPECIFIED", - platform: "PLATFORM_UNSPECIFIED", - pluginType: "GEMINI", - }), - }; - - const response = await fetch( - "https://cloudcode-pa.googleapis.com/v1internal:loadCodeAssist", - { - method: "POST", - headers, - body: JSON.stringify({ - metadata: { - ideType: "IDE_UNSPECIFIED", - platform: "PLATFORM_UNSPECIFIED", - pluginType: "GEMINI", - }, - }), - } - ); - - const data = await response.json(); - return data.cloudaicompanionProject || "rising-fact-p41fc"; // Valeur par défaut -} -``` - ---- - -## Détails de l'implémentation OAuth - -### Identifiants client - -**Important :** Ceux-ci sont encodés en base64 dans le code source pour la synchronisation avec pi-ai : - -```typescript -const decode = (s: string) => Buffer.from(s, "base64").toString(); - -const CLIENT_ID = decode( - "MTA3MTAwNjA2MDU5MS10bWhzc2luMmgyMWxjcmUyMzV2dG9sb2poNGc0MDNlcC5hcHBzLmdvb2dsZXVzZXJjb250ZW50LmNvbQ==" -); -const CLIENT_SECRET = decode("R09DU1BYLUs1OEZXUjQ4NkxkTEoxbUxCOHNYQzR6NnFEQWY="); -``` - -### Modes de flux OAuth - -1. **Flux automatique** (machines locales avec navigateur) : - - Ouvre le navigateur automatiquement - - Le serveur de callback local capture la redirection - - Aucune interaction utilisateur requise après l'authentification initiale - -2. **Flux manuel** (distant/sans interface/WSL2) : - - URL affichée pour copier-coller manuellement - - L'utilisateur complète l'authentification dans un navigateur externe - - L'utilisateur colle l'URL de redirection complète - -```typescript -function shouldUseManualOAuthFlow(isRemote: boolean): boolean { - return isRemote || isWSL2Sync(); -} -``` - ---- - -## Gestion des jetons - -### Structure du profil d'authentification - -```typescript -type OAuthCredential = { - type: "oauth"; - provider: "google-antigravity"; - access: string; // Jeton d'accès - refresh: string; // Jeton de rafraîchissement - expires: number; // Horodatage d'expiration (ms depuis epoch) - email?: string; // E-mail de l'utilisateur - projectId?: string; // ID du projet Google Cloud -}; -``` - -### Rafraîchissement des jetons - -Les identifiants incluent un jeton de rafraîchissement qui peut être utilisé pour obtenir de nouveaux jetons d'accès lorsque le jeton actuel expire. L'expiration est définie avec un tampon de 5 minutes pour éviter les conditions de concurrence. - ---- - -## Récupération de la liste des modèles - -### Récupérer les modèles disponibles - -```typescript -const BASE_URL = "https://cloudcode-pa.googleapis.com"; - -async function fetchAvailableModels( - accessToken: string, - projectId: string -): Promise { - const headers = { - Authorization: `Bearer ${accessToken}`, - "Content-Type": "application/json", - "User-Agent": "antigravity", - "X-Goog-Api-Client": "google-cloud-sdk vscode_cloudshelleditor/0.1", - }; - - const response = await fetch( - `${BASE_URL}/v1internal:fetchAvailableModels`, - { - method: "POST", - headers, - body: JSON.stringify({ project: projectId }), - } - ); - - const data = await response.json(); - - // Retourne les modèles avec les informations de quota - return Object.entries(data.models).map(([modelId, modelInfo]) => ({ - id: modelId, - displayName: modelInfo.displayName, - quotaInfo: { - remainingFraction: modelInfo.quotaInfo?.remainingFraction, - resetTime: modelInfo.quotaInfo?.resetTime, - isExhausted: modelInfo.quotaInfo?.isExhausted, - }, - })); -} -``` - -### Format de réponse - -```typescript -type FetchAvailableModelsResponse = { - models?: Record; -}; -``` - ---- - -## Suivi de l'utilisation - -### Récupérer les données d'utilisation - -```typescript -export async function fetchAntigravityUsage( - token: string, - timeoutMs: number -): Promise { - // 1. Récupérer les crédits et les informations du plan - const loadCodeAssistRes = await fetch( - `${BASE_URL}/v1internal:loadCodeAssist`, - { - method: "POST", - headers: { - Authorization: `Bearer ${token}`, - "Content-Type": "application/json", - }, - body: JSON.stringify({ - metadata: { - ideType: "ANTIGRAVITY", - platform: "PLATFORM_UNSPECIFIED", - pluginType: "GEMINI", - }, - }), - } - ); - - // Extraire les informations de crédits - const { availablePromptCredits, planInfo, currentTier } = data; - - // 2. Récupérer les quotas des modèles - const modelsRes = await fetch( - `${BASE_URL}/v1internal:fetchAvailableModels`, - { - method: "POST", - headers: { Authorization: `Bearer ${token}` }, - body: JSON.stringify({ project: projectId }), - } - ); - - // Construire les fenêtres d'utilisation - return { - provider: "google-antigravity", - displayName: "Google Antigravity", - windows: [ - { label: "Credits", usedPercent: calculateUsedPercent(available, monthly) }, - // Quotas individuels des modèles... - ], - plan: currentTier?.name || planType, - }; -} -``` - -### Structure de la réponse d'utilisation - -```typescript -type ProviderUsageSnapshot = { - provider: "google-antigravity"; - displayName: string; - windows: UsageWindow[]; - plan?: string; - error?: string; -}; - -type UsageWindow = { - label: string; // "Credits" ou ID du modèle - usedPercent: number; // 0-100 - resetAt?: number; // Horodatage de réinitialisation du quota -}; -``` - ---- - -## Structure du plugin fournisseur - -### Définition du plugin - -```typescript -const antigravityPlugin = { - id: "google-antigravity-auth", - name: "Google Antigravity Auth", - description: "OAuth flow for Google Antigravity (Cloud Code Assist)", - configSchema: emptyPluginConfigSchema(), - - register(api: PicoClawPluginApi) { - api.registerProvider({ - id: "google-antigravity", - label: "Google Antigravity", - docsPath: "/providers/models", - aliases: ["antigravity"], - - auth: [ - { - id: "oauth", - label: "Google OAuth", - hint: "PKCE + localhost callback", - kind: "oauth", - run: async (ctx: ProviderAuthContext) => { - // Implémentation OAuth ici - }, - }, - ], - }); - }, -}; -``` - -### ProviderAuthContext - -```typescript -type ProviderAuthContext = { - config: PicoClawConfig; - agentDir?: string; - workspaceDir?: string; - prompter: WizardPrompter; // Invites/notifications UI - runtime: RuntimeEnv; // Journalisation, etc. - isRemote: boolean; // Exécution à distance ou non - openUrl: (url: string) => Promise; // Ouverture du navigateur - oauth: { - createVpsAwareHandlers: Function; - }; -}; -``` - -### ProviderAuthResult - -```typescript -type ProviderAuthResult = { - profiles: Array<{ - profileId: string; - credential: AuthProfileCredential; - }>; - configPatch?: Partial; - defaultModel?: string; - notes?: string[]; -}; -``` - ---- - -## Exigences d'intégration - -### 1. Environnement/dépendances requis - -- Go ≥ 1.25 -- Base de code PicoClaw (`pkg/providers/` et `pkg/auth/`) -- Packages de la bibliothèque standard `crypto` et `net/http` - -### 2. En-têtes requis pour les appels API - -```typescript -const REQUIRED_HEADERS = { - "Authorization": `Bearer ${accessToken}`, - "Content-Type": "application/json", - "User-Agent": "antigravity", // ou "google-api-nodejs-client/9.15.1" - "X-Goog-Api-Client": "google-cloud-sdk vscode_cloudshelleditor/0.1", -}; - -// Pour les appels loadCodeAssist, inclure également : -const CLIENT_METADATA = { - ideType: "ANTIGRAVITY", // ou "IDE_UNSPECIFIED" - platform: "PLATFORM_UNSPECIFIED", - pluginType: "GEMINI", -}; -``` - -### 3. Assainissement des schémas de modèles - -Antigravity utilise des modèles compatibles Gemini, les schémas d'outils doivent donc être assainis : - -```typescript -const GOOGLE_SCHEMA_UNSUPPORTED_KEYWORDS = new Set([ - "patternProperties", - "additionalProperties", - "$schema", - "$id", - "$ref", - "$defs", - "definitions", - "examples", - "minLength", - "maxLength", - "minimum", - "maximum", - "multipleOf", - "pattern", - "format", - "minItems", - "maxItems", - "uniqueItems", - "minProperties", - "maxProperties", -]); - -// Nettoyer le schéma avant l'envoi -function cleanToolSchemaForGemini(schema: Record): unknown { - // Supprimer les mots-clés non supportés - // S'assurer que le niveau supérieur a type: "object" - // Aplatir les unions anyOf/oneOf -} -``` - -### 4. Gestion des blocs de réflexion (modèles Claude) - -Pour les modèles Claude via Antigravity, les blocs de réflexion nécessitent un traitement spécial : - -```typescript -const ANTIGRAVITY_SIGNATURE_RE = /^[A-Za-z0-9+/]+={0,2}$/; - -export function sanitizeAntigravityThinkingBlocks( - messages: AgentMessage[] -): AgentMessage[] { - // Valider les signatures de réflexion - // Normaliser les champs de signature - // Rejeter les blocs de réflexion non signés -} -``` - ---- - -## Points de terminaison API - -### Points de terminaison d'authentification - -| Point de terminaison | Méthode | Objectif | -|---------------------|---------|----------| -| `https://accounts.google.com/o/oauth2/v2/auth` | GET | Autorisation OAuth | -| `https://oauth2.googleapis.com/token` | POST | Échange de jetons | -| `https://www.googleapis.com/oauth2/v1/userinfo` | GET | Informations utilisateur (e-mail) | - -### Points de terminaison Cloud Code Assist - -| Point de terminaison | Méthode | Objectif | -|---------------------|---------|----------| -| `https://cloudcode-pa.googleapis.com/v1internal:loadCodeAssist` | POST | Charger les infos du projet, crédits, plan | -| `https://cloudcode-pa.googleapis.com/v1internal:fetchAvailableModels` | POST | Lister les modèles disponibles avec quotas | -| `https://cloudcode-pa.googleapis.com/v1internal:streamGenerateContent?alt=sse` | POST | Point de terminaison de streaming de chat | - -**Format de requête API (chat) :** -Le point de terminaison `v1internal:streamGenerateContent` attend une enveloppe encapsulant la requête Gemini standard : - -```json -{ - "project": "your-project-id", - "model": "model-id", - "request": { - "contents": [...], - "systemInstruction": {...}, - "generationConfig": {...}, - "tools": [...] - }, - "requestType": "agent", - "userAgent": "antigravity", - "requestId": "agent-timestamp-random" -} -``` - -**Format de réponse API (SSE) :** -Chaque message SSE (`data: {...}`) est encapsulé dans un champ `response` : - -```json -{ - "response": { - "candidates": [...], - "usageMetadata": {...}, - "modelVersion": "...", - "responseId": "..." - }, - "traceId": "...", - "metadata": {} -} -``` - ---- - -## Configuration - -### Configuration config.json - -```json -{ - "model_list": [ - { - "model_name": "gemini-flash", - "model": "antigravity/gemini-3-flash", - "auth_method": "oauth" - } - ], - "agents": { - "defaults": { - "model_name": "gemini-flash" - } - } -} -``` - -### Stockage du profil d'authentification - -Les profils d'authentification sont stockés dans `~/.picoclaw/auth.json` : - -```json -{ - "credentials": { - "google-antigravity": { - "access_token": "ya29...", - "refresh_token": "1//...", - "expires_at": "2026-01-01T00:00:00Z", - "provider": "google-antigravity", - "auth_method": "oauth", - "email": "user@example.com", - "project_id": "my-project-id" - } - } -} -``` - ---- - -## Créer un nouveau fournisseur dans PicoClaw - -Les fournisseurs PicoClaw sont implémentés en tant que packages Go sous `pkg/providers/`. Pour ajouter un nouveau fournisseur : - -### Implémentation étape par étape - -#### 1. Créer le fichier du fournisseur - -Créez un nouveau fichier Go dans `pkg/providers/` : - -``` -pkg/providers/ -└── your_provider.go -``` - -#### 2. Implémenter l'interface Provider - -Votre fournisseur doit implémenter l'interface `Provider` définie dans `pkg/providers/types.go` : - -```go -package providers - -type YourProvider struct { - apiKey string - apiBase string -} - -func NewYourProvider(apiKey, apiBase, proxy string) *YourProvider { - if apiBase == "" { - apiBase = "https://api.your-provider.com/v1" - } - return &YourProvider{apiKey: apiKey, apiBase: apiBase} -} - -func (p *YourProvider) Chat(ctx context.Context, messages []Message, tools []Tool, cb StreamCallback) error { - // Implémenter la complétion de chat avec streaming -} -``` - -#### 3. Enregistrer dans la factory - -Ajoutez votre fournisseur au switch de protocole dans `pkg/providers/factory.go` : - -```go -case "your-provider": - return NewYourProvider(sel.apiKey, sel.apiBase, sel.proxy), nil -``` - -#### 4. Ajouter la configuration par défaut (optionnel) - -Ajoutez une entrée par défaut dans `pkg/config/defaults.go` : - -```go -{ - ModelName: "your-model", - Model: "your-provider/model-name", - APIKey: "", -}, -``` - -#### 5. Ajouter le support d'authentification (optionnel) - -Si votre fournisseur nécessite OAuth ou une authentification spéciale, ajoutez un cas dans `cmd/picoclaw/internal/auth/helpers.go` : - -```go -case "your-provider": - authLoginYourProvider() -``` - -#### 6. Configurer via `config.json` - -```json -{ - "model_list": [ - { - "model_name": "your-model", - "model": "your-provider/model-name", - "api_keys": ["your-api-key"], - "api_base": "https://api.your-provider.com/v1" - } - ] -} -``` - ---- - -## Tester votre implémentation - -### Commandes CLI - -```bash -# S'authentifier avec un fournisseur -picoclaw auth login --provider your-provider - -# Lister les modèles (pour Antigravity) -picoclaw auth models - -# Démarrer la passerelle -picoclaw gateway - -# Exécuter un agent avec un modèle spécifique -picoclaw agent -m "Hello" --model your-model -``` - -### Variables d'environnement pour les tests - -```bash -# Remplacer le modèle par défaut -export PICOCLAW_AGENTS_DEFAULTS_MODEL=your-model - -# Remplacer les paramètres du fournisseur -export PICOCLAW_MODEL_LIST='[{"model_name":"your-model","model":"your-provider/model-name","api_keys":["..."]}]' -``` - ---- - -## Références - -- **Fichiers source :** - - `pkg/providers/antigravity_provider.go` - Implémentation du fournisseur Antigravity - - `pkg/auth/oauth.go` - Implémentation du flux OAuth - - `pkg/auth/store.go` - Stockage des identifiants d'authentification (`~/.picoclaw/auth.json`) - - `pkg/providers/factory.go` - Factory des fournisseurs et routage de protocole - - `pkg/providers/types.go` - Définitions de l'interface fournisseur - - `cmd/picoclaw/internal/auth/helpers.go` - Commandes CLI d'authentification - -- **Documentation :** - - `docs/ANTIGRAVITY_USAGE.md` - Guide d'utilisation d'Antigravity - - `docs/migration/model-list-migration.md` - Guide de migration - ---- - -## Notes - -1. **Projet Google Cloud :** Antigravity nécessite que Gemini for Google Cloud soit activé sur votre projet Google Cloud -2. **Quotas :** Utilise les quotas du projet Google Cloud (pas de facturation séparée) -3. **Accès aux modèles :** Les modèles disponibles dépendent de la configuration de votre projet Google Cloud -4. **Blocs de réflexion :** Les modèles Claude via Antigravity nécessitent un traitement spécial des blocs de réflexion avec signatures -5. **Assainissement des schémas :** Les schémas d'outils doivent être assainis pour supprimer les mots-clés JSON Schema non supportés - ---- - ---- - -## Gestion des erreurs courantes - -### 1. Limitation de débit (HTTP 429) - -Antigravity retourne une erreur 429 lorsque les quotas du projet/modèle sont épuisés. La réponse d'erreur contient souvent un `quotaResetDelay` dans le champ `details`. - -**Exemple d'erreur 429 :** -```json -{ - "error": { - "code": 429, - "message": "You have exhausted your capacity on this model. Your quota will reset after 4h30m28s.", - "status": "RESOURCE_EXHAUSTED", - "details": [ - { - "@type": "type.googleapis.com/google.rpc.ErrorInfo", - "metadata": { - "quotaResetDelay": "4h30m28.060903746s" - } - } - ] - } -} -``` - -### 2. Réponses vides (modèles restreints) - -Certains modèles peuvent apparaître dans la liste des modèles disponibles mais retourner une réponse vide (200 OK mais flux SSE vide). Cela se produit généralement pour les modèles en préversion ou restreints que le projet actuel n'a pas la permission d'utiliser. - -**Traitement :** Traiter les réponses vides comme des erreurs informant l'utilisateur que le modèle pourrait être restreint ou invalide pour son projet. - ---- - -## Dépannage - -### "Token expired" (jeton expiré) -- Rafraîchir les jetons OAuth : `picoclaw auth login --provider antigravity` - -### "Gemini for Google Cloud is not enabled" (Gemini for Google Cloud n'est pas activé) -- Activer l'API dans votre Google Cloud Console - -### "Project not found" (projet non trouvé) -- Vérifier que votre projet Google Cloud a les API nécessaires activées -- Vérifier que l'ID du projet est correctement récupéré lors de l'authentification - -### Les modèles n'apparaissent pas dans la liste -- Vérifier que l'authentification OAuth s'est terminée avec succès -- Vérifier le stockage du profil d'authentification : `~/.picoclaw/auth.json` -- Relancer `picoclaw auth login --provider antigravity` diff --git a/docs/security/ANTIGRAVITY_AUTH.ja.md b/docs/security/ANTIGRAVITY_AUTH.ja.md deleted file mode 100644 index 83888a5d..00000000 --- a/docs/security/ANTIGRAVITY_AUTH.ja.md +++ /dev/null @@ -1,809 +0,0 @@ -> [README](../../README.md) に戻る - -# Antigravity 認証・統合ガイド - -## 概要 - -**Antigravity**(Google Cloud Code Assist)は、Google が提供する AI モデルプロバイダーで、Google のクラウドインフラストラクチャを通じて Claude Opus 4.6 や Gemini などのモデルへのアクセスを提供します。本ドキュメントでは、認証の仕組み、モデルの取得方法、PicoClaw での新しいプロバイダーの実装方法について完全なガイドを提供します。 - ---- - -## 目次 - -1. [認証フロー](#認証フロー) -2. [OAuth 実装の詳細](#oauth-実装の詳細) -3. [トークン管理](#トークン管理) -4. [モデルリストの取得](#モデルリストの取得) -5. [使用量トラッキング](#使用量トラッキング) -6. [プロバイダープラグイン構造](#プロバイダープラグイン構造) -7. [統合要件](#統合要件) -8. [API エンドポイント](#api-エンドポイント) -9. [設定](#設定) -10. [PicoClaw での新しいプロバイダーの作成](#picoclaw-での新しいプロバイダーの作成) - ---- - -## 認証フロー - -### 1. PKCE 付き OAuth 2.0 - -Antigravity はセキュアな認証のために **OAuth 2.0 with PKCE(Proof Key for Code Exchange)** を使用します: - -``` -┌─────────────┐ ┌─────────────────┐ -│ Client │ ───(1) Generate PKCE Pair────────> │ │ -│ │ ───(2) Open Auth URL─────────────> │ Google OAuth │ -│ │ │ Server │ -│ │ <──(3) Redirect with Code───────── │ │ -│ │ └─────────────────┘ -│ │ ───(4) Exchange Code for Tokens──> │ Token URL │ -│ │ │ │ -│ │ <──(5) Access + Refresh Tokens──── │ │ -└─────────────┘ └─────────────────┘ -``` - -### 2. 詳細手順 - -#### ステップ 1:PKCE パラメータの生成 -```typescript -function generatePkce(): { verifier: string; challenge: string } { - const verifier = randomBytes(32).toString("hex"); - const challenge = createHash("sha256").update(verifier).digest("base64url"); - return { verifier, challenge }; -} -``` - -#### ステップ 2:認可 URL の構築 -```typescript -const AUTH_URL = "https://accounts.google.com/o/oauth2/v2/auth"; -const REDIRECT_URI = "http://localhost:51121/oauth-callback"; - -function buildAuthUrl(params: { challenge: string; state: string }): string { - const url = new URL(AUTH_URL); - url.searchParams.set("client_id", CLIENT_ID); - url.searchParams.set("response_type", "code"); - url.searchParams.set("redirect_uri", REDIRECT_URI); - url.searchParams.set("scope", SCOPES.join(" ")); - url.searchParams.set("code_challenge", params.challenge); - url.searchParams.set("code_challenge_method", "S256"); - url.searchParams.set("state", params.state); - url.searchParams.set("access_type", "offline"); - url.searchParams.set("prompt", "consent"); - return url.toString(); -} -``` - -**必要なスコープ:** -```typescript -const SCOPES = [ - "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/userinfo.email", - "https://www.googleapis.com/auth/userinfo.profile", - "https://www.googleapis.com/auth/cclog", - "https://www.googleapis.com/auth/experimentsandconfigs", -]; -``` - -#### ステップ 3:OAuth コールバックの処理 - -**自動モード(ローカル開発):** -- ポート 51121 でローカル HTTP サーバーを起動 -- Google からのリダイレクトを待機 -- クエリパラメータから認可コードを抽出 - -**手動モード(リモート/ヘッドレス):** -- ユーザーに認可 URL を表示 -- ユーザーがブラウザで認証を完了 -- ユーザーが完全なリダイレクト URL をターミナルに貼り付け -- 貼り付けられた URL からコードを解析 - -#### ステップ 4:コードをトークンに交換 -```typescript -const TOKEN_URL = "https://oauth2.googleapis.com/token"; - -async function exchangeCode(params: { - code: string; - verifier: string; -}): Promise<{ access: string; refresh: string; expires: number }> { - const response = await fetch(TOKEN_URL, { - method: "POST", - headers: { "Content-Type": "application/x-www-form-urlencoded" }, - body: new URLSearchParams({ - client_id: CLIENT_ID, - client_secret: CLIENT_SECRET, - code: params.code, - grant_type: "authorization_code", - redirect_uri: REDIRECT_URI, - code_verifier: params.verifier, - }), - }); - - const data = await response.json(); - - return { - access: data.access_token, - refresh: data.refresh_token, - expires: Date.now() + data.expires_in * 1000 - 5 * 60 * 1000, // 5 min buffer - }; -} -``` - -#### ステップ 5:追加のユーザーデータの取得 - -**ユーザーメール:** -```typescript -async function fetchUserEmail(accessToken: string): Promise { - const response = await fetch( - "https://www.googleapis.com/oauth2/v1/userinfo?alt=json", - { headers: { Authorization: `Bearer ${accessToken}` } } - ); - const data = await response.json(); - return data.email; -} -``` - -**プロジェクト ID(API 呼び出しに必須):** -```typescript -async function fetchProjectId(accessToken: string): Promise { - const headers = { - Authorization: `Bearer ${accessToken}`, - "Content-Type": "application/json", - "User-Agent": "google-api-nodejs-client/9.15.1", - "X-Goog-Api-Client": "google-cloud-sdk vscode_cloudshelleditor/0.1", - "Client-Metadata": JSON.stringify({ - ideType: "IDE_UNSPECIFIED", - platform: "PLATFORM_UNSPECIFIED", - pluginType: "GEMINI", - }), - }; - - const response = await fetch( - "https://cloudcode-pa.googleapis.com/v1internal:loadCodeAssist", - { - method: "POST", - headers, - body: JSON.stringify({ - metadata: { - ideType: "IDE_UNSPECIFIED", - platform: "PLATFORM_UNSPECIFIED", - pluginType: "GEMINI", - }, - }), - } - ); - - const data = await response.json(); - return data.cloudaicompanionProject || "rising-fact-p41fc"; // デフォルトのフォールバック -} -``` - ---- - -## OAuth 実装の詳細 - -### クライアント認証情報 - -**重要:** これらは pi-ai との同期のためにソースコード内で base64 エンコードされています: - -```typescript -const decode = (s: string) => Buffer.from(s, "base64").toString(); - -const CLIENT_ID = decode( - "MTA3MTAwNjA2MDU5MS10bWhzc2luMmgyMWxjcmUyMzV2dG9sb2poNGc0MDNlcC5hcHBzLmdvb2dsZXVzZXJjb250ZW50LmNvbQ==" -); -const CLIENT_SECRET = decode("R09DU1BYLUs1OEZXUjQ4NkxkTEoxbUxCOHNYQzR6NnFEQWY="); -``` - -### OAuth フローモード - -1. **自動フロー**(ブラウザのあるローカルマシン): - - ブラウザを自動的に開く - - ローカルコールバックサーバーがリダイレクトをキャプチャ - - 初回認証後はユーザー操作不要 - -2. **手動フロー**(リモート/ヘッドレス/WSL2): - - 手動コピー&ペースト用の URL を表示 - - ユーザーが外部ブラウザで認証を完了 - - ユーザーが完全なリダイレクト URL を貼り付け - -```typescript -function shouldUseManualOAuthFlow(isRemote: boolean): boolean { - return isRemote || isWSL2Sync(); -} -``` - ---- - -## トークン管理 - -### 認証プロファイル構造 - -```typescript -type OAuthCredential = { - type: "oauth"; - provider: "google-antigravity"; - access: string; // アクセストークン - refresh: string; // リフレッシュトークン - expires: number; // 有効期限タイムスタンプ(エポックからのミリ秒) - email?: string; // ユーザーメール - projectId?: string; // Google Cloud プロジェクト ID -}; -``` - -### トークンの更新 - -認証情報にはリフレッシュトークンが含まれており、現在のアクセストークンが期限切れになった際に新しいアクセストークンを取得するために使用できます。有効期限は競合状態を防ぐために 5 分のバッファを設けています。 - ---- - -## モデルリストの取得 - -### 利用可能なモデルの取得 - -```typescript -const BASE_URL = "https://cloudcode-pa.googleapis.com"; - -async function fetchAvailableModels( - accessToken: string, - projectId: string -): Promise { - const headers = { - Authorization: `Bearer ${accessToken}`, - "Content-Type": "application/json", - "User-Agent": "antigravity", - "X-Goog-Api-Client": "google-cloud-sdk vscode_cloudshelleditor/0.1", - }; - - const response = await fetch( - `${BASE_URL}/v1internal:fetchAvailableModels`, - { - method: "POST", - headers, - body: JSON.stringify({ project: projectId }), - } - ); - - const data = await response.json(); - - // クォータ情報付きのモデルを返す - return Object.entries(data.models).map(([modelId, modelInfo]) => ({ - id: modelId, - displayName: modelInfo.displayName, - quotaInfo: { - remainingFraction: modelInfo.quotaInfo?.remainingFraction, - resetTime: modelInfo.quotaInfo?.resetTime, - isExhausted: modelInfo.quotaInfo?.isExhausted, - }, - })); -} -``` - -### レスポンス形式 - -```typescript -type FetchAvailableModelsResponse = { - models?: Record; -}; -``` - ---- - -## 使用量トラッキング - -### 使用量データの取得 - -```typescript -export async function fetchAntigravityUsage( - token: string, - timeoutMs: number -): Promise { - // 1. クレジットとプラン情報を取得 - const loadCodeAssistRes = await fetch( - `${BASE_URL}/v1internal:loadCodeAssist`, - { - method: "POST", - headers: { - Authorization: `Bearer ${token}`, - "Content-Type": "application/json", - }, - body: JSON.stringify({ - metadata: { - ideType: "ANTIGRAVITY", - platform: "PLATFORM_UNSPECIFIED", - pluginType: "GEMINI", - }, - }), - } - ); - - // クレジット情報を抽出 - const { availablePromptCredits, planInfo, currentTier } = data; - - // 2. モデルクォータを取得 - const modelsRes = await fetch( - `${BASE_URL}/v1internal:fetchAvailableModels`, - { - method: "POST", - headers: { Authorization: `Bearer ${token}` }, - body: JSON.stringify({ project: projectId }), - } - ); - - // 使用量ウィンドウを構築 - return { - provider: "google-antigravity", - displayName: "Google Antigravity", - windows: [ - { label: "Credits", usedPercent: calculateUsedPercent(available, monthly) }, - // 個別モデルクォータ... - ], - plan: currentTier?.name || planType, - }; -} -``` - -### 使用量レスポンス構造 - -```typescript -type ProviderUsageSnapshot = { - provider: "google-antigravity"; - displayName: string; - windows: UsageWindow[]; - plan?: string; - error?: string; -}; - -type UsageWindow = { - label: string; // "Credits" またはモデル ID - usedPercent: number; // 0-100 - resetAt?: number; // クォータがリセットされるタイムスタンプ -}; -``` - ---- - -## プロバイダープラグイン構造 - -### プラグイン定義 - -```typescript -const antigravityPlugin = { - id: "google-antigravity-auth", - name: "Google Antigravity Auth", - description: "OAuth flow for Google Antigravity (Cloud Code Assist)", - configSchema: emptyPluginConfigSchema(), - - register(api: PicoClawPluginApi) { - api.registerProvider({ - id: "google-antigravity", - label: "Google Antigravity", - docsPath: "/providers/models", - aliases: ["antigravity"], - - auth: [ - { - id: "oauth", - label: "Google OAuth", - hint: "PKCE + localhost callback", - kind: "oauth", - run: async (ctx: ProviderAuthContext) => { - // OAuth 実装はここに記述 - }, - }, - ], - }); - }, -}; -``` - -### ProviderAuthContext - -```typescript -type ProviderAuthContext = { - config: PicoClawConfig; - agentDir?: string; - workspaceDir?: string; - prompter: WizardPrompter; // UI プロンプト/通知 - runtime: RuntimeEnv; // ログなど - isRemote: boolean; // リモート実行かどうか - openUrl: (url: string) => Promise; // ブラウザオープナー - oauth: { - createVpsAwareHandlers: Function; - }; -}; -``` - -### ProviderAuthResult - -```typescript -type ProviderAuthResult = { - profiles: Array<{ - profileId: string; - credential: AuthProfileCredential; - }>; - configPatch?: Partial; - defaultModel?: string; - notes?: string[]; -}; -``` - ---- - -## 統合要件 - -### 1. 必要な環境/依存関係 - -- Go ≥ 1.25 -- PicoClaw コードベース(`pkg/providers/` および `pkg/auth/`) -- `crypto` および `net/http` 標準ライブラリパッケージ - -### 2. API 呼び出しに必要なヘッダー - -```typescript -const REQUIRED_HEADERS = { - "Authorization": `Bearer ${accessToken}`, - "Content-Type": "application/json", - "User-Agent": "antigravity", // または "google-api-nodejs-client/9.15.1" - "X-Goog-Api-Client": "google-cloud-sdk vscode_cloudshelleditor/0.1", -}; - -// loadCodeAssist 呼び出しには以下も含める: -const CLIENT_METADATA = { - ideType: "ANTIGRAVITY", // または "IDE_UNSPECIFIED" - platform: "PLATFORM_UNSPECIFIED", - pluginType: "GEMINI", -}; -``` - -### 3. モデルスキーマのサニタイズ - -Antigravity は Gemini 互換モデルを使用するため、ツールスキーマのサニタイズが必要です: - -```typescript -const GOOGLE_SCHEMA_UNSUPPORTED_KEYWORDS = new Set([ - "patternProperties", - "additionalProperties", - "$schema", - "$id", - "$ref", - "$defs", - "definitions", - "examples", - "minLength", - "maxLength", - "minimum", - "maximum", - "multipleOf", - "pattern", - "format", - "minItems", - "maxItems", - "uniqueItems", - "minProperties", - "maxProperties", -]); - -// 送信前にスキーマをクリーンアップ -function cleanToolSchemaForGemini(schema: Record): unknown { - // サポートされていないキーワードを削除 - // トップレベルに type: "object" があることを確認 - // anyOf/oneOf ユニオンをフラット化 -} -``` - -### 4. 思考ブロックの処理(Claude モデル) - -Antigravity の Claude モデルでは、思考ブロックに特別な処理が必要です: - -```typescript -const ANTIGRAVITY_SIGNATURE_RE = /^[A-Za-z0-9+/]+={0,2}$/; - -export function sanitizeAntigravityThinkingBlocks( - messages: AgentMessage[] -): AgentMessage[] { - // 思考シグネチャを検証 - // シグネチャフィールドを正規化 - // 署名されていない思考ブロックを破棄 -} -``` - ---- - -## API エンドポイント - -### 認証エンドポイント - -| エンドポイント | メソッド | 用途 | -|---------------|---------|------| -| `https://accounts.google.com/o/oauth2/v2/auth` | GET | OAuth 認可 | -| `https://oauth2.googleapis.com/token` | POST | トークン交換 | -| `https://www.googleapis.com/oauth2/v1/userinfo` | GET | ユーザー情報(メール) | - -### Cloud Code Assist エンドポイント - -| エンドポイント | メソッド | 用途 | -|---------------|---------|------| -| `https://cloudcode-pa.googleapis.com/v1internal:loadCodeAssist` | POST | プロジェクト情報、クレジット、プランの読み込み | -| `https://cloudcode-pa.googleapis.com/v1internal:fetchAvailableModels` | POST | クォータ付き利用可能モデルの一覧 | -| `https://cloudcode-pa.googleapis.com/v1internal:streamGenerateContent?alt=sse` | POST | チャットストリーミングエンドポイント | - -**API リクエスト形式(チャット):** -`v1internal:streamGenerateContent` エンドポイントは、標準の Gemini リクエストをラップするエンベロープ形式を期待します: - -```json -{ - "project": "your-project-id", - "model": "model-id", - "request": { - "contents": [...], - "systemInstruction": {...}, - "generationConfig": {...}, - "tools": [...] - }, - "requestType": "agent", - "userAgent": "antigravity", - "requestId": "agent-timestamp-random" -} -``` - -**API レスポンス形式(SSE):** -各 SSE メッセージ(`data: {...}`)は `response` フィールドでラップされます: - -```json -{ - "response": { - "candidates": [...], - "usageMetadata": {...}, - "modelVersion": "...", - "responseId": "..." - }, - "traceId": "...", - "metadata": {} -} -``` - ---- - -## 設定 - -### config.json の設定 - -```json -{ - "model_list": [ - { - "model_name": "gemini-flash", - "model": "antigravity/gemini-3-flash", - "auth_method": "oauth" - } - ], - "agents": { - "defaults": { - "model_name": "gemini-flash" - } - } -} -``` - -### 認証プロファイルの保存 - -認証プロファイルは `~/.picoclaw/auth.json` に保存されます: - -```json -{ - "credentials": { - "google-antigravity": { - "access_token": "ya29...", - "refresh_token": "1//...", - "expires_at": "2026-01-01T00:00:00Z", - "provider": "google-antigravity", - "auth_method": "oauth", - "email": "user@example.com", - "project_id": "my-project-id" - } - } -} -``` - ---- - -## PicoClaw での新しいプロバイダーの作成 - -PicoClaw のプロバイダーは `pkg/providers/` 配下の Go パッケージとして実装されます。新しいプロバイダーを追加するには: - -### ステップバイステップの実装 - -#### 1. プロバイダーファイルの作成 - -`pkg/providers/` に新しい Go ファイルを作成します: - -``` -pkg/providers/ -└── your_provider.go -``` - -#### 2. Provider インターフェースの実装 - -プロバイダーは `pkg/providers/types.go` で定義された `Provider` インターフェースを実装する必要があります: - -```go -package providers - -type YourProvider struct { - apiKey string - apiBase string -} - -func NewYourProvider(apiKey, apiBase, proxy string) *YourProvider { - if apiBase == "" { - apiBase = "https://api.your-provider.com/v1" - } - return &YourProvider{apiKey: apiKey, apiBase: apiBase} -} - -func (p *YourProvider) Chat(ctx context.Context, messages []Message, tools []Tool, cb StreamCallback) error { - // ストリーミング付きチャット補完を実装 -} -``` - -#### 3. ファクトリーへの登録 - -`pkg/providers/factory.go` のプロトコルスイッチにプロバイダーを追加します: - -```go -case "your-provider": - return NewYourProvider(sel.apiKey, sel.apiBase, sel.proxy), nil -``` - -#### 4. デフォルト設定の追加(オプション) - -`pkg/config/defaults.go` にデフォルトエントリを追加します: - -```go -{ - ModelName: "your-model", - Model: "your-provider/model-name", - APIKey: "", -}, -``` - -#### 5. 認証サポートの追加(オプション) - -プロバイダーが OAuth や特別な認証を必要とする場合、`cmd/picoclaw/internal/auth/helpers.go` にケースを追加します: - -```go -case "your-provider": - authLoginYourProvider() -``` - -#### 6. `config.json` での設定 - -```json -{ - "model_list": [ - { - "model_name": "your-model", - "model": "your-provider/model-name", - "api_keys": ["your-api-key"], - "api_base": "https://api.your-provider.com/v1" - } - ] -} -``` - ---- - -## 実装のテスト - -### CLI コマンド - -```bash -# プロバイダーで認証 -picoclaw auth login --provider your-provider - -# モデルの一覧表示(Antigravity 用) -picoclaw auth models - -# ゲートウェイの起動 -picoclaw gateway - -# 特定のモデルでエージェントを実行 -picoclaw agent -m "Hello" --model your-model -``` - -### テスト用環境変数 - -```bash -# デフォルトモデルの上書き -export PICOCLAW_AGENTS_DEFAULTS_MODEL=your-model - -# プロバイダー設定の上書き -export PICOCLAW_MODEL_LIST='[{"model_name":"your-model","model":"your-provider/model-name","api_keys":["..."]}]' -``` - ---- - -## 参考資料 - -- **ソースファイル:** - - `pkg/providers/antigravity_provider.go` - Antigravity プロバイダー実装 - - `pkg/auth/oauth.go` - OAuth フロー実装 - - `pkg/auth/store.go` - 認証情報ストレージ(`~/.picoclaw/auth.json`) - - `pkg/providers/factory.go` - プロバイダーファクトリーとプロトコルルーティング - - `pkg/providers/types.go` - プロバイダーインターフェース定義 - - `cmd/picoclaw/internal/auth/helpers.go` - 認証 CLI コマンド - -- **ドキュメント:** - - `docs/ANTIGRAVITY_USAGE.md` - Antigravity 使用ガイド - - `docs/migration/model-list-migration.md` - 移行ガイド - ---- - -## 注意事項 - -1. **Google Cloud プロジェクト:** Antigravity は Google Cloud プロジェクトで Gemini for Google Cloud が有効になっている必要があります -2. **クォータ:** Google Cloud プロジェクトのクォータを使用します(個別の課金ではありません) -3. **モデルアクセス:** 利用可能なモデルは Google Cloud プロジェクトの設定に依存します -4. **思考ブロック:** Antigravity 経由の Claude モデルは、署名付き思考ブロックの特別な処理が必要です -5. **スキーマサニタイズ:** ツールスキーマはサポートされていない JSON Schema キーワードを削除するためにサニタイズが必要です - ---- - ---- - -## 一般的なエラー処理 - -### 1. レート制限(HTTP 429) - -プロジェクト/モデルのクォータが枯渇すると、Antigravity は 429 エラーを返します。エラーレスポンスには通常、`details` フィールドに `quotaResetDelay` が含まれます。 - -**429 エラーの例:** -```json -{ - "error": { - "code": 429, - "message": "You have exhausted your capacity on this model. Your quota will reset after 4h30m28s.", - "status": "RESOURCE_EXHAUSTED", - "details": [ - { - "@type": "type.googleapis.com/google.rpc.ErrorInfo", - "metadata": { - "quotaResetDelay": "4h30m28.060903746s" - } - } - ] - } -} -``` - -### 2. 空のレスポンス(制限付きモデル) - -一部のモデルは利用可能モデルリストに表示されますが、空のレスポンスを返す場合があります(200 OK だが SSE ストリームが空)。これは通常、現在のプロジェクトに使用権限がないプレビュー版または制限付きモデルで発生します。 - -**対処法:** 空のレスポンスをエラーとして扱い、そのモデルがプロジェクトに対して制限されているか無効である可能性があることをユーザーに通知します。 - ---- - -## トラブルシューティング - -### "Token expired"(トークン期限切れ) -- OAuth トークンを更新:`picoclaw auth login --provider antigravity` - -### "Gemini for Google Cloud is not enabled"(Gemini for Google Cloud が有効になっていない) -- Google Cloud Console で API を有効にしてください - -### "Project not found"(プロジェクトが見つからない) -- Google Cloud プロジェクトで必要な API が有効になっていることを確認してください -- 認証中にプロジェクト ID が正しく取得されているか確認してください - -### モデルがリストに表示されない -- OAuth 認証が正常に完了したことを確認してください -- 認証プロファイルストレージを確認:`~/.picoclaw/auth.json` -- `picoclaw auth login --provider antigravity` を再実行してください diff --git a/docs/security/ANTIGRAVITY_AUTH.md b/docs/security/ANTIGRAVITY_AUTH.md deleted file mode 100644 index 7488ad9b..00000000 --- a/docs/security/ANTIGRAVITY_AUTH.md +++ /dev/null @@ -1,807 +0,0 @@ -# Antigravity Authentication & Integration Guide - -## Overview - -**Antigravity** (Google Cloud Code Assist) is a Google-backed AI model provider that offers access to models like Claude Opus 4.6 and Gemini through Google's Cloud infrastructure. This document provides a complete guide on how authentication works, how to fetch models, and how to implement a new provider in PicoClaw. - ---- - -## Table of Contents - -1. [Authentication Flow](#authentication-flow) -2. [OAuth Implementation Details](#oauth-implementation-details) -3. [Token Management](#token-management) -4. [Models List Fetching](#models-list-fetching) -5. [Usage Tracking](#usage-tracking) -6. [Provider Plugin Structure](#provider-plugin-structure) -7. [Integration Requirements](#integration-requirements) -8. [API Endpoints](#api-endpoints) -9. [Configuration](#configuration) -10. [Creating a New Provider in PicoClaw](#creating-a-new-provider-in-picoclaw) - ---- - -## Authentication Flow - -### 1. OAuth 2.0 with PKCE - -Antigravity uses **OAuth 2.0 with PKCE (Proof Key for Code Exchange)** for secure authentication: - -``` -┌─────────────┐ ┌─────────────────┐ -│ Client │ ───(1) Generate PKCE Pair────────> │ │ -│ │ ───(2) Open Auth URL─────────────> │ Google OAuth │ -│ │ │ Server │ -│ │ <──(3) Redirect with Code───────── │ │ -│ │ └─────────────────┘ -│ │ ───(4) Exchange Code for Tokens──> │ Token URL │ -│ │ │ │ -│ │ <──(5) Access + Refresh Tokens──── │ │ -└─────────────┘ └─────────────────┘ -``` - -### 2. Detailed Steps - -#### Step 1: Generate PKCE Parameters -```typescript -function generatePkce(): { verifier: string; challenge: string } { - const verifier = randomBytes(32).toString("hex"); - const challenge = createHash("sha256").update(verifier).digest("base64url"); - return { verifier, challenge }; -} -``` - -#### Step 2: Build Authorization URL -```typescript -const AUTH_URL = "https://accounts.google.com/o/oauth2/v2/auth"; -const REDIRECT_URI = "http://localhost:51121/oauth-callback"; - -function buildAuthUrl(params: { challenge: string; state: string }): string { - const url = new URL(AUTH_URL); - url.searchParams.set("client_id", CLIENT_ID); - url.searchParams.set("response_type", "code"); - url.searchParams.set("redirect_uri", REDIRECT_URI); - url.searchParams.set("scope", SCOPES.join(" ")); - url.searchParams.set("code_challenge", params.challenge); - url.searchParams.set("code_challenge_method", "S256"); - url.searchParams.set("state", params.state); - url.searchParams.set("access_type", "offline"); - url.searchParams.set("prompt", "consent"); - return url.toString(); -} -``` - -**Required Scopes:** -```typescript -const SCOPES = [ - "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/userinfo.email", - "https://www.googleapis.com/auth/userinfo.profile", - "https://www.googleapis.com/auth/cclog", - "https://www.googleapis.com/auth/experimentsandconfigs", -]; -``` - -#### Step 3: Handle OAuth Callback - -**Automatic Mode (Local Development):** -- Start a local HTTP server on port 51121 -- Wait for the redirect from Google -- Extract the authorization code from the query parameters - -**Manual Mode (Remote/Headless):** -- Display the authorization URL to the user -- User completes authentication in their browser -- User pastes the full redirect URL back into the terminal -- Parse the code from the pasted URL - -#### Step 4: Exchange Code for Tokens -```typescript -const TOKEN_URL = "https://oauth2.googleapis.com/token"; - -async function exchangeCode(params: { - code: string; - verifier: string; -}): Promise<{ access: string; refresh: string; expires: number }> { - const response = await fetch(TOKEN_URL, { - method: "POST", - headers: { "Content-Type": "application/x-www-form-urlencoded" }, - body: new URLSearchParams({ - client_id: CLIENT_ID, - client_secret: CLIENT_SECRET, - code: params.code, - grant_type: "authorization_code", - redirect_uri: REDIRECT_URI, - code_verifier: params.verifier, - }), - }); - - const data = await response.json(); - - return { - access: data.access_token, - refresh: data.refresh_token, - expires: Date.now() + data.expires_in * 1000 - 5 * 60 * 1000, // 5 min buffer - }; -} -``` - -#### Step 5: Fetch Additional User Data - -**User Email:** -```typescript -async function fetchUserEmail(accessToken: string): Promise { - const response = await fetch( - "https://www.googleapis.com/oauth2/v1/userinfo?alt=json", - { headers: { Authorization: `Bearer ${accessToken}` } } - ); - const data = await response.json(); - return data.email; -} -``` - -**Project ID (Required for API calls):** -```typescript -async function fetchProjectId(accessToken: string): Promise { - const headers = { - Authorization: `Bearer ${accessToken}`, - "Content-Type": "application/json", - "User-Agent": "google-api-nodejs-client/9.15.1", - "X-Goog-Api-Client": "google-cloud-sdk vscode_cloudshelleditor/0.1", - "Client-Metadata": JSON.stringify({ - ideType: "IDE_UNSPECIFIED", - platform: "PLATFORM_UNSPECIFIED", - pluginType: "GEMINI", - }), - }; - - const response = await fetch( - "https://cloudcode-pa.googleapis.com/v1internal:loadCodeAssist", - { - method: "POST", - headers, - body: JSON.stringify({ - metadata: { - ideType: "IDE_UNSPECIFIED", - platform: "PLATFORM_UNSPECIFIED", - pluginType: "GEMINI", - }, - }), - } - ); - - const data = await response.json(); - return data.cloudaicompanionProject || "rising-fact-p41fc"; // Default fallback -} -``` - ---- - -## OAuth Implementation Details - -### Client Credentials - -**Important:** These are base64-encoded in the source code for sync with pi-ai: - -```typescript -const decode = (s: string) => Buffer.from(s, "base64").toString(); - -const CLIENT_ID = decode( - "MTA3MTAwNjA2MDU5MS10bWhzc2luMmgyMWxjcmUyMzV2dG9sb2poNGc0MDNlcC5hcHBzLmdvb2dsZXVzZXJjb250ZW50LmNvbQ==" -); -const CLIENT_SECRET = decode("R09DU1BYLUs1OEZXUjQ4NkxkTEoxbUxCOHNYQzR6NnFEQWY="); -``` - -### OAuth Flow Modes - -1. **Automatic Flow** (Local machines with browser): - - Opens browser automatically - - Local callback server captures redirect - - No user interaction required after initial auth - -2. **Manual Flow** (Remote/headless/WSL2): - - URL displayed for manual copy-paste - - User completes auth in external browser - - User pastes full redirect URL back - -```typescript -function shouldUseManualOAuthFlow(isRemote: boolean): boolean { - return isRemote || isWSL2Sync(); -} -``` - ---- - -## Token Management - -### Auth Profile Structure - -```typescript -type OAuthCredential = { - type: "oauth"; - provider: "google-antigravity"; - access: string; // Access token - refresh: string; // Refresh token - expires: number; // Expiration timestamp (ms since epoch) - email?: string; // User email - projectId?: string; // Google Cloud project ID -}; -``` - -### Token Refresh - -The credential includes a refresh token that can be used to obtain new access tokens when the current one expires. The expiration is set with a 5-minute buffer to prevent race conditions. - ---- - -## Models List Fetching - -### Fetch Available Models - -```typescript -const BASE_URL = "https://cloudcode-pa.googleapis.com"; - -async function fetchAvailableModels( - accessToken: string, - projectId: string -): Promise { - const headers = { - Authorization: `Bearer ${accessToken}`, - "Content-Type": "application/json", - "User-Agent": "antigravity", - "X-Goog-Api-Client": "google-cloud-sdk vscode_cloudshelleditor/0.1", - }; - - const response = await fetch( - `${BASE_URL}/v1internal:fetchAvailableModels`, - { - method: "POST", - headers, - body: JSON.stringify({ project: projectId }), - } - ); - - const data = await response.json(); - - // Returns models with quota information - return Object.entries(data.models).map(([modelId, modelInfo]) => ({ - id: modelId, - displayName: modelInfo.displayName, - quotaInfo: { - remainingFraction: modelInfo.quotaInfo?.remainingFraction, - resetTime: modelInfo.quotaInfo?.resetTime, - isExhausted: modelInfo.quotaInfo?.isExhausted, - }, - })); -} -``` - -### Response Format - -```typescript -type FetchAvailableModelsResponse = { - models?: Record; -}; -``` - ---- - -## Usage Tracking - -### Fetch Usage Data - -```typescript -export async function fetchAntigravityUsage( - token: string, - timeoutMs: number -): Promise { - // 1. Fetch credits and plan info - const loadCodeAssistRes = await fetch( - `${BASE_URL}/v1internal:loadCodeAssist`, - { - method: "POST", - headers: { - Authorization: `Bearer ${token}`, - "Content-Type": "application/json", - }, - body: JSON.stringify({ - metadata: { - ideType: "ANTIGRAVITY", - platform: "PLATFORM_UNSPECIFIED", - pluginType: "GEMINI", - }, - }), - } - ); - - // Extract credits info - const { availablePromptCredits, planInfo, currentTier } = data; - - // 2. Fetch model quotas - const modelsRes = await fetch( - `${BASE_URL}/v1internal:fetchAvailableModels`, - { - method: "POST", - headers: { Authorization: `Bearer ${token}` }, - body: JSON.stringify({ project: projectId }), - } - ); - - // Build usage windows - return { - provider: "google-antigravity", - displayName: "Google Antigravity", - windows: [ - { label: "Credits", usedPercent: calculateUsedPercent(available, monthly) }, - // Individual model quotas... - ], - plan: currentTier?.name || planType, - }; -} -``` - -### Usage Response Structure - -```typescript -type ProviderUsageSnapshot = { - provider: "google-antigravity"; - displayName: string; - windows: UsageWindow[]; - plan?: string; - error?: string; -}; - -type UsageWindow = { - label: string; // "Credits" or model ID - usedPercent: number; // 0-100 - resetAt?: number; // Timestamp when quota resets -}; -``` - ---- - -## Provider Plugin Structure - -### Plugin Definition - -```typescript -const antigravityPlugin = { - id: "google-antigravity-auth", - name: "Google Antigravity Auth", - description: "OAuth flow for Google Antigravity (Cloud Code Assist)", - configSchema: emptyPluginConfigSchema(), - - register(api: PicoClawPluginApi) { - api.registerProvider({ - id: "google-antigravity", - label: "Google Antigravity", - docsPath: "/providers/models", - aliases: ["antigravity"], - - auth: [ - { - id: "oauth", - label: "Google OAuth", - hint: "PKCE + localhost callback", - kind: "oauth", - run: async (ctx: ProviderAuthContext) => { - // OAuth implementation here - }, - }, - ], - }); - }, -}; -``` - -### ProviderAuthContext - -```typescript -type ProviderAuthContext = { - config: PicoClawConfig; - agentDir?: string; - workspaceDir?: string; - prompter: WizardPrompter; // UI prompts/notifications - runtime: RuntimeEnv; // Logging, etc. - isRemote: boolean; // Whether running remotely - openUrl: (url: string) => Promise; // Browser opener - oauth: { - createVpsAwareHandlers: Function; - }; -}; -``` - -### ProviderAuthResult - -```typescript -type ProviderAuthResult = { - profiles: Array<{ - profileId: string; - credential: AuthProfileCredential; - }>; - configPatch?: Partial; - defaultModel?: string; - notes?: string[]; -}; -``` - ---- - -## Integration Requirements - -### 1. Required Environment/Dependencies - -- Go ≥ 1.25 -- PicoClaw codebase (`pkg/providers/` and `pkg/auth/`) -- `crypto` and `net/http` standard library packages - -### 2. Required Headers for API Calls - -```typescript -const REQUIRED_HEADERS = { - "Authorization": `Bearer ${accessToken}`, - "Content-Type": "application/json", - "User-Agent": "antigravity", // or "google-api-nodejs-client/9.15.1" - "X-Goog-Api-Client": "google-cloud-sdk vscode_cloudshelleditor/0.1", -}; - -// For loadCodeAssist calls, also include: -const CLIENT_METADATA = { - ideType: "ANTIGRAVITY", // or "IDE_UNSPECIFIED" - platform: "PLATFORM_UNSPECIFIED", - pluginType: "GEMINI", -}; -``` - -### 3. Model Schema Sanitization - -Antigravity uses Gemini-compatible models, so tool schemas must be sanitized: - -```typescript -const GOOGLE_SCHEMA_UNSUPPORTED_KEYWORDS = new Set([ - "patternProperties", - "additionalProperties", - "$schema", - "$id", - "$ref", - "$defs", - "definitions", - "examples", - "minLength", - "maxLength", - "minimum", - "maximum", - "multipleOf", - "pattern", - "format", - "minItems", - "maxItems", - "uniqueItems", - "minProperties", - "maxProperties", -]); - -// Clean schema before sending -function cleanToolSchemaForGemini(schema: Record): unknown { - // Remove unsupported keywords - // Ensure top-level has type: "object" - // Flatten anyOf/oneOf unions -} -``` - -### 4. Thinking Block Handling (Claude Models) - -For Antigravity Claude models, thinking blocks require special handling: - -```typescript -const ANTIGRAVITY_SIGNATURE_RE = /^[A-Za-z0-9+/]+={0,2}$/; - -export function sanitizeAntigravityThinkingBlocks( - messages: AgentMessage[] -): AgentMessage[] { - // Validate thinking signatures - // Normalize signature fields - // Discard unsigned thinking blocks -} -``` - ---- - -## API Endpoints - -### Authentication Endpoints - -| Endpoint | Method | Purpose | -|----------|--------|---------| -| `https://accounts.google.com/o/oauth2/v2/auth` | GET | OAuth authorization | -| `https://oauth2.googleapis.com/token` | POST | Token exchange | -| `https://www.googleapis.com/oauth2/v1/userinfo` | GET | User info (email) | - -### Cloud Code Assist Endpoints - -| Endpoint | Method | Purpose | -|----------|--------|---------| -| `https://cloudcode-pa.googleapis.com/v1internal:loadCodeAssist` | POST | Load project info, credits, plan | -| `https://cloudcode-pa.googleapis.com/v1internal:fetchAvailableModels` | POST | List available models with quotas | -| `https://cloudcode-pa.googleapis.com/v1internal:streamGenerateContent?alt=sse` | POST | Chat streaming endpoint | - -**API Request Format (Chat):** -The `v1internal:streamGenerateContent` endpoint expects an envelope wrapping the standard Gemini request: - -```json -{ - "project": "your-project-id", - "model": "model-id", - "request": { - "contents": [...], - "systemInstruction": {...}, - "generationConfig": {...}, - "tools": [...] - }, - "requestType": "agent", - "userAgent": "antigravity", - "requestId": "agent-timestamp-random" -} -``` - -**API Response Format (SSE):** -Each SSE message (`data: {...}`) is wrapped in a `response` field: - -```json -{ - "response": { - "candidates": [...], - "usageMetadata": {...}, - "modelVersion": "...", - "responseId": "..." - }, - "traceId": "...", - "metadata": {} -} -``` - ---- - -## Configuration - -### config.json Configuration - -```json -{ - "model_list": [ - { - "model_name": "gemini-flash", - "model": "antigravity/gemini-3-flash", - "auth_method": "oauth" - } - ], - "agents": { - "defaults": { - "model_name": "gemini-flash" - } - } -} -``` - -### Auth Profile Storage - -Auth profiles are stored in `~/.picoclaw/auth.json`: - -```json -{ - "credentials": { - "google-antigravity": { - "access_token": "ya29...", - "refresh_token": "1//...", - "expires_at": "2026-01-01T00:00:00Z", - "provider": "google-antigravity", - "auth_method": "oauth", - "email": "user@example.com", - "project_id": "my-project-id" - } - } -} -``` - ---- - -## Creating a New Provider in PicoClaw - -PicoClaw providers are implemented as Go packages under `pkg/providers/`. To add a new provider: - -### Step-by-Step Implementation - -#### 1. Create Provider File - -Create a new Go file in `pkg/providers/`: - -``` -pkg/providers/ -└── your_provider.go -``` - -#### 2. Implement the Provider Interface - -Your provider must implement the `Provider` interface defined in `pkg/providers/types.go`: - -```go -package providers - -type YourProvider struct { - apiKey string - apiBase string -} - -func NewYourProvider(apiKey, apiBase, proxy string) *YourProvider { - if apiBase == "" { - apiBase = "https://api.your-provider.com/v1" - } - return &YourProvider{apiKey: apiKey, apiBase: apiBase} -} - -func (p *YourProvider) Chat(ctx context.Context, messages []Message, tools []Tool, cb StreamCallback) error { - // Implement chat completion with streaming -} -``` - -#### 3. Register in the Factory - -Add your provider to the protocol switch in `pkg/providers/factory.go`: - -```go -case "your-provider": - return NewYourProvider(sel.apiKey, sel.apiBase, sel.proxy), nil -``` - -#### 4. Add Default Config (Optional) - -Add a default entry in `pkg/config/defaults.go`: - -```go -{ - ModelName: "your-model", - Model: "your-provider/model-name", - APIKey: "", -}, -``` - -#### 5. Add Auth Support (Optional) - -If your provider requires OAuth or special authentication, add a case to `cmd/picoclaw/internal/auth/helpers.go`: - -```go -case "your-provider": - authLoginYourProvider() -``` - -#### 6. Configure via `config.json` - -```json -{ - "model_list": [ - { - "model_name": "your-model", - "model": "your-provider/model-name", - "api_keys": ["your-api-key"], - "api_base": "https://api.your-provider.com/v1" - } - ] -} -``` - ---- - -## Testing Your Implementation - -### CLI Commands - -```bash -# Authenticate with a provider -picoclaw auth login --provider your-provider - -# List models (for Antigravity) -picoclaw auth models - -# Start the gateway -picoclaw gateway - -# Run an agent with a specific model -picoclaw agent -m "Hello" --model your-model -``` - -### Environment Variables for Testing - -```bash -# Override default model -export PICOCLAW_AGENTS_DEFAULTS_MODEL=your-model - -# Override provider settings -export PICOCLAW_MODEL_LIST='[{"model_name":"your-model","model":"your-provider/model-name","api_keys":["..."]}]' -``` - ---- - -## References - -- **Source Files:** - - `pkg/providers/antigravity_provider.go` - Antigravity provider implementation - - `pkg/auth/oauth.go` - OAuth flow implementation - - `pkg/auth/store.go` - Auth credential storage (`~/.picoclaw/auth.json`) - - `pkg/providers/factory.go` - Provider factory and protocol routing - - `pkg/providers/types.go` - Provider interface definitions - - `cmd/picoclaw/internal/auth/helpers.go` - Auth CLI commands - -- **Documentation:** - - `docs/ANTIGRAVITY_USAGE.md` - Antigravity usage guide - - `docs/migration/model-list-migration.md` - Migration guide - ---- - -## Notes - -1. **Google Cloud Project:** Antigravity requires Gemini for Google Cloud to be enabled on your Google Cloud project -2. **Quotas:** Uses Google Cloud project quotas (not separate billing) -3. **Model Access:** Available models depend on your Google Cloud project configuration -4. **Thinking Blocks:** Claude models via Antigravity require special handling of thinking blocks with signatures -5. **Schema Sanitization:** Tool schemas must be sanitized to remove unsupported JSON Schema keywords - ---- - ---- - -## Common Error Handling - -### 1. Rate Limiting (HTTP 429) - -Antigravity returns a 429 error when project/model quotas are exhausted. The error response often contains a `quotaResetDelay` in the `details` field. - -**Example 429 Error:** -```json -{ - "error": { - "code": 429, - "message": "You have exhausted your capacity on this model. Your quota will reset after 4h30m28s.", - "status": "RESOURCE_EXHAUSTED", - "details": [ - { - "@type": "type.googleapis.com/google.rpc.ErrorInfo", - "metadata": { - "quotaResetDelay": "4h30m28.060903746s" - } - } - ] - } -} -``` - -### 2. Empty Responses (Restricted Models) - -Some models might show up in the available models list but return an empty response (200 OK but empty SSE stream). This usually happens for preview or restricted models that the current project doesn't have permission to use. - -**Treatment:** Treat empty responses as errors informing the user that the model might be restricted or invalid for their project. - ---- - -## Troubleshooting - -### "Token expired" -- Refresh OAuth tokens: `picoclaw auth login --provider antigravity` - -### "Gemini for Google Cloud is not enabled" -- Enable the API in your Google Cloud Console - -### "Project not found" -- Ensure your Google Cloud project has the necessary APIs enabled -- Check that the project ID is correctly fetched during authentication - -### Models not appearing in list -- Verify OAuth authentication completed successfully -- Check auth profile storage: `~/.picoclaw/auth.json` -- Re-run `picoclaw auth login --provider antigravity` diff --git a/docs/security/ANTIGRAVITY_AUTH.pt-br.md b/docs/security/ANTIGRAVITY_AUTH.pt-br.md deleted file mode 100644 index 7e8ee079..00000000 --- a/docs/security/ANTIGRAVITY_AUTH.pt-br.md +++ /dev/null @@ -1,809 +0,0 @@ -> Voltar ao [README](../../README.md) - -# Guia de Autenticação e Integração do Antigravity - -## Visão Geral - -**Antigravity** (Google Cloud Code Assist) é um provedor de modelos de IA apoiado pelo Google que oferece acesso a modelos como Claude Opus 4.6 e Gemini através da infraestrutura de nuvem do Google. Este documento fornece um guia completo sobre como a autenticação funciona, como buscar modelos e como implementar um novo provedor no PicoClaw. - ---- - -## Índice - -1. [Fluxo de Autenticação](#fluxo-de-autenticação) -2. [Detalhes da Implementação OAuth](#detalhes-da-implementação-oauth) -3. [Gerenciamento de Tokens](#gerenciamento-de-tokens) -4. [Busca da Lista de Modelos](#busca-da-lista-de-modelos) -5. [Rastreamento de Uso](#rastreamento-de-uso) -6. [Estrutura do Plugin do Provedor](#estrutura-do-plugin-do-provedor) -7. [Requisitos de Integração](#requisitos-de-integração) -8. [Endpoints da API](#endpoints-da-api) -9. [Configuração](#configuração) -10. [Criando um Novo Provedor no PicoClaw](#criando-um-novo-provedor-no-picoclaw) - ---- - -## Fluxo de Autenticação - -### 1. OAuth 2.0 com PKCE - -O Antigravity utiliza **OAuth 2.0 com PKCE (Proof Key for Code Exchange)** para autenticação segura: - -``` -┌─────────────┐ ┌─────────────────┐ -│ Client │ ───(1) Generate PKCE Pair────────> │ │ -│ │ ───(2) Open Auth URL─────────────> │ Google OAuth │ -│ │ │ Server │ -│ │ <──(3) Redirect with Code───────── │ │ -│ │ └─────────────────┘ -│ │ ───(4) Exchange Code for Tokens──> │ Token URL │ -│ │ │ │ -│ │ <──(5) Access + Refresh Tokens──── │ │ -└─────────────┘ └─────────────────┘ -``` - -### 2. Etapas Detalhadas - -#### Etapa 1: Gerar Parâmetros PKCE -```typescript -function generatePkce(): { verifier: string; challenge: string } { - const verifier = randomBytes(32).toString("hex"); - const challenge = createHash("sha256").update(verifier).digest("base64url"); - return { verifier, challenge }; -} -``` - -#### Etapa 2: Construir a URL de Autorização -```typescript -const AUTH_URL = "https://accounts.google.com/o/oauth2/v2/auth"; -const REDIRECT_URI = "http://localhost:51121/oauth-callback"; - -function buildAuthUrl(params: { challenge: string; state: string }): string { - const url = new URL(AUTH_URL); - url.searchParams.set("client_id", CLIENT_ID); - url.searchParams.set("response_type", "code"); - url.searchParams.set("redirect_uri", REDIRECT_URI); - url.searchParams.set("scope", SCOPES.join(" ")); - url.searchParams.set("code_challenge", params.challenge); - url.searchParams.set("code_challenge_method", "S256"); - url.searchParams.set("state", params.state); - url.searchParams.set("access_type", "offline"); - url.searchParams.set("prompt", "consent"); - return url.toString(); -} -``` - -**Escopos Necessários:** -```typescript -const SCOPES = [ - "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/userinfo.email", - "https://www.googleapis.com/auth/userinfo.profile", - "https://www.googleapis.com/auth/cclog", - "https://www.googleapis.com/auth/experimentsandconfigs", -]; -``` - -#### Etapa 3: Tratar o Callback OAuth - -**Modo Automático (Desenvolvimento Local):** -- Iniciar um servidor HTTP local na porta 51121 -- Aguardar o redirecionamento do Google -- Extrair o código de autorização dos parâmetros da query - -**Modo Manual (Remoto/Sem Interface Gráfica):** -- Exibir a URL de autorização para o usuário -- O usuário completa a autenticação no navegador -- O usuário cola a URL de redirecionamento completa no terminal -- Analisar o código da URL colada - -#### Etapa 4: Trocar o Código por Tokens -```typescript -const TOKEN_URL = "https://oauth2.googleapis.com/token"; - -async function exchangeCode(params: { - code: string; - verifier: string; -}): Promise<{ access: string; refresh: string; expires: number }> { - const response = await fetch(TOKEN_URL, { - method: "POST", - headers: { "Content-Type": "application/x-www-form-urlencoded" }, - body: new URLSearchParams({ - client_id: CLIENT_ID, - client_secret: CLIENT_SECRET, - code: params.code, - grant_type: "authorization_code", - redirect_uri: REDIRECT_URI, - code_verifier: params.verifier, - }), - }); - - const data = await response.json(); - - return { - access: data.access_token, - refresh: data.refresh_token, - expires: Date.now() + data.expires_in * 1000 - 5 * 60 * 1000, // 5 min buffer - }; -} -``` - -#### Etapa 5: Buscar Dados Adicionais do Usuário - -**E-mail do Usuário:** -```typescript -async function fetchUserEmail(accessToken: string): Promise { - const response = await fetch( - "https://www.googleapis.com/oauth2/v1/userinfo?alt=json", - { headers: { Authorization: `Bearer ${accessToken}` } } - ); - const data = await response.json(); - return data.email; -} -``` - -**ID do Projeto (Necessário para chamadas de API):** -```typescript -async function fetchProjectId(accessToken: string): Promise { - const headers = { - Authorization: `Bearer ${accessToken}`, - "Content-Type": "application/json", - "User-Agent": "google-api-nodejs-client/9.15.1", - "X-Goog-Api-Client": "google-cloud-sdk vscode_cloudshelleditor/0.1", - "Client-Metadata": JSON.stringify({ - ideType: "IDE_UNSPECIFIED", - platform: "PLATFORM_UNSPECIFIED", - pluginType: "GEMINI", - }), - }; - - const response = await fetch( - "https://cloudcode-pa.googleapis.com/v1internal:loadCodeAssist", - { - method: "POST", - headers, - body: JSON.stringify({ - metadata: { - ideType: "IDE_UNSPECIFIED", - platform: "PLATFORM_UNSPECIFIED", - pluginType: "GEMINI", - }, - }), - } - ); - - const data = await response.json(); - return data.cloudaicompanionProject || "rising-fact-p41fc"; // Valor padrão de fallback -} -``` - ---- - -## Detalhes da Implementação OAuth - -### Credenciais do Cliente - -**Importante:** Estas são codificadas em base64 no código-fonte para sincronização com pi-ai: - -```typescript -const decode = (s: string) => Buffer.from(s, "base64").toString(); - -const CLIENT_ID = decode( - "MTA3MTAwNjA2MDU5MS10bWhzc2luMmgyMWxjcmUyMzV2dG9sb2poNGc0MDNlcC5hcHBzLmdvb2dsZXVzZXJjb250ZW50LmNvbQ==" -); -const CLIENT_SECRET = decode("R09DU1BYLUs1OEZXUjQ4NkxkTEoxbUxCOHNYQzR6NnFEQWY="); -``` - -### Modos do Fluxo OAuth - -1. **Fluxo Automático** (máquinas locais com navegador): - - Abre o navegador automaticamente - - O servidor de callback local captura o redirecionamento - - Nenhuma interação do usuário necessária após a autenticação inicial - -2. **Fluxo Manual** (remoto/sem interface/WSL2): - - URL exibida para copiar e colar manualmente - - O usuário completa a autenticação em um navegador externo - - O usuário cola a URL de redirecionamento completa de volta - -```typescript -function shouldUseManualOAuthFlow(isRemote: boolean): boolean { - return isRemote || isWSL2Sync(); -} -``` - ---- - -## Gerenciamento de Tokens - -### Estrutura do Perfil de Autenticação - -```typescript -type OAuthCredential = { - type: "oauth"; - provider: "google-antigravity"; - access: string; // Token de acesso - refresh: string; // Token de atualização - expires: number; // Timestamp de expiração (ms desde epoch) - email?: string; // E-mail do usuário - projectId?: string; // ID do projeto Google Cloud -}; -``` - -### Atualização de Tokens - -A credencial inclui um token de atualização que pode ser usado para obter novos tokens de acesso quando o atual expira. A expiração é definida com um buffer de 5 minutos para evitar condições de corrida. - ---- - -## Busca da Lista de Modelos - -### Buscar Modelos Disponíveis - -```typescript -const BASE_URL = "https://cloudcode-pa.googleapis.com"; - -async function fetchAvailableModels( - accessToken: string, - projectId: string -): Promise { - const headers = { - Authorization: `Bearer ${accessToken}`, - "Content-Type": "application/json", - "User-Agent": "antigravity", - "X-Goog-Api-Client": "google-cloud-sdk vscode_cloudshelleditor/0.1", - }; - - const response = await fetch( - `${BASE_URL}/v1internal:fetchAvailableModels`, - { - method: "POST", - headers, - body: JSON.stringify({ project: projectId }), - } - ); - - const data = await response.json(); - - // Retorna modelos com informações de cota - return Object.entries(data.models).map(([modelId, modelInfo]) => ({ - id: modelId, - displayName: modelInfo.displayName, - quotaInfo: { - remainingFraction: modelInfo.quotaInfo?.remainingFraction, - resetTime: modelInfo.quotaInfo?.resetTime, - isExhausted: modelInfo.quotaInfo?.isExhausted, - }, - })); -} -``` - -### Formato da Resposta - -```typescript -type FetchAvailableModelsResponse = { - models?: Record; -}; -``` - ---- - -## Rastreamento de Uso - -### Buscar Dados de Uso - -```typescript -export async function fetchAntigravityUsage( - token: string, - timeoutMs: number -): Promise { - // 1. Buscar créditos e informações do plano - const loadCodeAssistRes = await fetch( - `${BASE_URL}/v1internal:loadCodeAssist`, - { - method: "POST", - headers: { - Authorization: `Bearer ${token}`, - "Content-Type": "application/json", - }, - body: JSON.stringify({ - metadata: { - ideType: "ANTIGRAVITY", - platform: "PLATFORM_UNSPECIFIED", - pluginType: "GEMINI", - }, - }), - } - ); - - // Extrair informações de créditos - const { availablePromptCredits, planInfo, currentTier } = data; - - // 2. Buscar cotas dos modelos - const modelsRes = await fetch( - `${BASE_URL}/v1internal:fetchAvailableModels`, - { - method: "POST", - headers: { Authorization: `Bearer ${token}` }, - body: JSON.stringify({ project: projectId }), - } - ); - - // Construir janelas de uso - return { - provider: "google-antigravity", - displayName: "Google Antigravity", - windows: [ - { label: "Credits", usedPercent: calculateUsedPercent(available, monthly) }, - // Cotas individuais dos modelos... - ], - plan: currentTier?.name || planType, - }; -} -``` - -### Estrutura da Resposta de Uso - -```typescript -type ProviderUsageSnapshot = { - provider: "google-antigravity"; - displayName: string; - windows: UsageWindow[]; - plan?: string; - error?: string; -}; - -type UsageWindow = { - label: string; // "Credits" ou ID do modelo - usedPercent: number; // 0-100 - resetAt?: number; // Timestamp de quando a cota é redefinida -}; -``` - ---- - -## Estrutura do Plugin do Provedor - -### Definição do Plugin - -```typescript -const antigravityPlugin = { - id: "google-antigravity-auth", - name: "Google Antigravity Auth", - description: "OAuth flow for Google Antigravity (Cloud Code Assist)", - configSchema: emptyPluginConfigSchema(), - - register(api: PicoClawPluginApi) { - api.registerProvider({ - id: "google-antigravity", - label: "Google Antigravity", - docsPath: "/providers/models", - aliases: ["antigravity"], - - auth: [ - { - id: "oauth", - label: "Google OAuth", - hint: "PKCE + localhost callback", - kind: "oauth", - run: async (ctx: ProviderAuthContext) => { - // Implementação OAuth aqui - }, - }, - ], - }); - }, -}; -``` - -### ProviderAuthContext - -```typescript -type ProviderAuthContext = { - config: PicoClawConfig; - agentDir?: string; - workspaceDir?: string; - prompter: WizardPrompter; // Prompts/notificações da UI - runtime: RuntimeEnv; // Logging, etc. - isRemote: boolean; // Se está executando remotamente - openUrl: (url: string) => Promise; // Abridor de navegador - oauth: { - createVpsAwareHandlers: Function; - }; -}; -``` - -### ProviderAuthResult - -```typescript -type ProviderAuthResult = { - profiles: Array<{ - profileId: string; - credential: AuthProfileCredential; - }>; - configPatch?: Partial; - defaultModel?: string; - notes?: string[]; -}; -``` - ---- - -## Requisitos de Integração - -### 1. Ambiente/Dependências Necessários - -- Go ≥ 1.25 -- Base de código do PicoClaw (`pkg/providers/` e `pkg/auth/`) -- Pacotes da biblioteca padrão `crypto` e `net/http` - -### 2. Cabeçalhos Necessários para Chamadas de API - -```typescript -const REQUIRED_HEADERS = { - "Authorization": `Bearer ${accessToken}`, - "Content-Type": "application/json", - "User-Agent": "antigravity", // ou "google-api-nodejs-client/9.15.1" - "X-Goog-Api-Client": "google-cloud-sdk vscode_cloudshelleditor/0.1", -}; - -// Para chamadas loadCodeAssist, incluir também: -const CLIENT_METADATA = { - ideType: "ANTIGRAVITY", // ou "IDE_UNSPECIFIED" - platform: "PLATFORM_UNSPECIFIED", - pluginType: "GEMINI", -}; -``` - -### 3. Sanitização de Schemas de Modelos - -O Antigravity usa modelos compatíveis com Gemini, então os schemas de ferramentas devem ser sanitizados: - -```typescript -const GOOGLE_SCHEMA_UNSUPPORTED_KEYWORDS = new Set([ - "patternProperties", - "additionalProperties", - "$schema", - "$id", - "$ref", - "$defs", - "definitions", - "examples", - "minLength", - "maxLength", - "minimum", - "maximum", - "multipleOf", - "pattern", - "format", - "minItems", - "maxItems", - "uniqueItems", - "minProperties", - "maxProperties", -]); - -// Limpar schema antes de enviar -function cleanToolSchemaForGemini(schema: Record): unknown { - // Remover palavras-chave não suportadas - // Garantir que o nível superior tenha type: "object" - // Achatar uniões anyOf/oneOf -} -``` - -### 4. Tratamento de Blocos de Pensamento (Modelos Claude) - -Para modelos Claude via Antigravity, os blocos de pensamento requerem tratamento especial: - -```typescript -const ANTIGRAVITY_SIGNATURE_RE = /^[A-Za-z0-9+/]+={0,2}$/; - -export function sanitizeAntigravityThinkingBlocks( - messages: AgentMessage[] -): AgentMessage[] { - // Validar assinaturas de pensamento - // Normalizar campos de assinatura - // Descartar blocos de pensamento não assinados -} -``` - ---- - -## Endpoints da API - -### Endpoints de Autenticação - -| Endpoint | Método | Finalidade | -|----------|--------|-----------| -| `https://accounts.google.com/o/oauth2/v2/auth` | GET | Autorização OAuth | -| `https://oauth2.googleapis.com/token` | POST | Troca de tokens | -| `https://www.googleapis.com/oauth2/v1/userinfo` | GET | Informações do usuário (e-mail) | - -### Endpoints do Cloud Code Assist - -| Endpoint | Método | Finalidade | -|----------|--------|-----------| -| `https://cloudcode-pa.googleapis.com/v1internal:loadCodeAssist` | POST | Carregar informações do projeto, créditos, plano | -| `https://cloudcode-pa.googleapis.com/v1internal:fetchAvailableModels` | POST | Listar modelos disponíveis com cotas | -| `https://cloudcode-pa.googleapis.com/v1internal:streamGenerateContent?alt=sse` | POST | Endpoint de streaming de chat | - -**Formato de Requisição da API (Chat):** -O endpoint `v1internal:streamGenerateContent` espera um envelope encapsulando a requisição Gemini padrão: - -```json -{ - "project": "your-project-id", - "model": "model-id", - "request": { - "contents": [...], - "systemInstruction": {...}, - "generationConfig": {...}, - "tools": [...] - }, - "requestType": "agent", - "userAgent": "antigravity", - "requestId": "agent-timestamp-random" -} -``` - -**Formato de Resposta da API (SSE):** -Cada mensagem SSE (`data: {...}`) é encapsulada em um campo `response`: - -```json -{ - "response": { - "candidates": [...], - "usageMetadata": {...}, - "modelVersion": "...", - "responseId": "..." - }, - "traceId": "...", - "metadata": {} -} -``` - ---- - -## Configuração - -### Configuração do config.json - -```json -{ - "model_list": [ - { - "model_name": "gemini-flash", - "model": "antigravity/gemini-3-flash", - "auth_method": "oauth" - } - ], - "agents": { - "defaults": { - "model_name": "gemini-flash" - } - } -} -``` - -### Armazenamento do Perfil de Autenticação - -Os perfis de autenticação são armazenados em `~/.picoclaw/auth.json`: - -```json -{ - "credentials": { - "google-antigravity": { - "access_token": "ya29...", - "refresh_token": "1//...", - "expires_at": "2026-01-01T00:00:00Z", - "provider": "google-antigravity", - "auth_method": "oauth", - "email": "user@example.com", - "project_id": "my-project-id" - } - } -} -``` - ---- - -## Criando um Novo Provedor no PicoClaw - -Os provedores do PicoClaw são implementados como pacotes Go em `pkg/providers/`. Para adicionar um novo provedor: - -### Implementação Passo a Passo - -#### 1. Criar o Arquivo do Provedor - -Crie um novo arquivo Go em `pkg/providers/`: - -``` -pkg/providers/ -└── your_provider.go -``` - -#### 2. Implementar a Interface Provider - -Seu provedor deve implementar a interface `Provider` definida em `pkg/providers/types.go`: - -```go -package providers - -type YourProvider struct { - apiKey string - apiBase string -} - -func NewYourProvider(apiKey, apiBase, proxy string) *YourProvider { - if apiBase == "" { - apiBase = "https://api.your-provider.com/v1" - } - return &YourProvider{apiKey: apiKey, apiBase: apiBase} -} - -func (p *YourProvider) Chat(ctx context.Context, messages []Message, tools []Tool, cb StreamCallback) error { - // Implementar conclusão de chat com streaming -} -``` - -#### 3. Registrar na Factory - -Adicione seu provedor ao switch de protocolo em `pkg/providers/factory.go`: - -```go -case "your-provider": - return NewYourProvider(sel.apiKey, sel.apiBase, sel.proxy), nil -``` - -#### 4. Adicionar Configuração Padrão (Opcional) - -Adicione uma entrada padrão em `pkg/config/defaults.go`: - -```go -{ - ModelName: "your-model", - Model: "your-provider/model-name", - APIKey: "", -}, -``` - -#### 5. Adicionar Suporte de Autenticação (Opcional) - -Se seu provedor requer OAuth ou autenticação especial, adicione um caso em `cmd/picoclaw/internal/auth/helpers.go`: - -```go -case "your-provider": - authLoginYourProvider() -``` - -#### 6. Configurar via `config.json` - -```json -{ - "model_list": [ - { - "model_name": "your-model", - "model": "your-provider/model-name", - "api_keys": ["your-api-key"], - "api_base": "https://api.your-provider.com/v1" - } - ] -} -``` - ---- - -## Testando Sua Implementação - -### Comandos CLI - -```bash -# Autenticar com um provedor -picoclaw auth login --provider your-provider - -# Listar modelos (para Antigravity) -picoclaw auth models - -# Iniciar o gateway -picoclaw gateway - -# Executar um agente com um modelo específico -picoclaw agent -m "Hello" --model your-model -``` - -### Variáveis de Ambiente para Testes - -```bash -# Substituir o modelo padrão -export PICOCLAW_AGENTS_DEFAULTS_MODEL=your-model - -# Substituir configurações do provedor -export PICOCLAW_MODEL_LIST='[{"model_name":"your-model","model":"your-provider/model-name","api_keys":["..."]}]' -``` - ---- - -## Referências - -- **Arquivos Fonte:** - - `pkg/providers/antigravity_provider.go` - Implementação do provedor Antigravity - - `pkg/auth/oauth.go` - Implementação do fluxo OAuth - - `pkg/auth/store.go` - Armazenamento de credenciais de autenticação (`~/.picoclaw/auth.json`) - - `pkg/providers/factory.go` - Factory de provedores e roteamento de protocolo - - `pkg/providers/types.go` - Definições da interface do provedor - - `cmd/picoclaw/internal/auth/helpers.go` - Comandos CLI de autenticação - -- **Documentação:** - - `docs/ANTIGRAVITY_USAGE.md` - Guia de uso do Antigravity - - `docs/migration/model-list-migration.md` - Guia de migração - ---- - -## Observações - -1. **Projeto Google Cloud:** O Antigravity requer que o Gemini for Google Cloud esteja habilitado no seu projeto Google Cloud -2. **Cotas:** Usa cotas do projeto Google Cloud (sem cobrança separada) -3. **Acesso a Modelos:** Os modelos disponíveis dependem da configuração do seu projeto Google Cloud -4. **Blocos de Pensamento:** Modelos Claude via Antigravity requerem tratamento especial de blocos de pensamento com assinaturas -5. **Sanitização de Schemas:** Os schemas de ferramentas devem ser sanitizados para remover palavras-chave JSON Schema não suportadas - ---- - ---- - -## Tratamento de Erros Comuns - -### 1. Limitação de Taxa (HTTP 429) - -O Antigravity retorna um erro 429 quando as cotas do projeto/modelo estão esgotadas. A resposta de erro frequentemente contém um `quotaResetDelay` no campo `details`. - -**Exemplo de Erro 429:** -```json -{ - "error": { - "code": 429, - "message": "You have exhausted your capacity on this model. Your quota will reset after 4h30m28s.", - "status": "RESOURCE_EXHAUSTED", - "details": [ - { - "@type": "type.googleapis.com/google.rpc.ErrorInfo", - "metadata": { - "quotaResetDelay": "4h30m28.060903746s" - } - } - ] - } -} -``` - -### 2. Respostas Vazias (Modelos Restritos) - -Alguns modelos podem aparecer na lista de modelos disponíveis, mas retornar uma resposta vazia (200 OK mas stream SSE vazio). Isso geralmente acontece com modelos em preview ou restritos que o projeto atual não tem permissão para usar. - -**Tratamento:** Tratar respostas vazias como erros informando ao usuário que o modelo pode estar restrito ou inválido para seu projeto. - ---- - -## Solução de Problemas - -### "Token expired" (token expirado) -- Atualizar tokens OAuth: `picoclaw auth login --provider antigravity` - -### "Gemini for Google Cloud is not enabled" (Gemini for Google Cloud não está habilitado) -- Habilitar a API no seu Google Cloud Console - -### "Project not found" (projeto não encontrado) -- Verificar se seu projeto Google Cloud tem as APIs necessárias habilitadas -- Verificar se o ID do projeto foi obtido corretamente durante a autenticação - -### Modelos não aparecem na lista -- Verificar se a autenticação OAuth foi concluída com sucesso -- Verificar o armazenamento do perfil de autenticação: `~/.picoclaw/auth.json` -- Executar novamente `picoclaw auth login --provider antigravity` diff --git a/docs/security/ANTIGRAVITY_AUTH.vi.md b/docs/security/ANTIGRAVITY_AUTH.vi.md deleted file mode 100644 index 8caf0b99..00000000 --- a/docs/security/ANTIGRAVITY_AUTH.vi.md +++ /dev/null @@ -1,807 +0,0 @@ -> Quay lại [README](../../README.md) - -# Hướng dẫn Xác thực và Tích hợp Antigravity - -## Tổng quan - -**Antigravity** (Google Cloud Code Assist) là nhà cung cấp mô hình AI được Google hỗ trợ, cung cấp quyền truy cập vào các mô hình như Claude Opus 4.6 và Gemini thông qua hạ tầng đám mây của Google. Tài liệu này cung cấp hướng dẫn đầy đủ về cách xác thực hoạt động, cách lấy danh sách mô hình và cách triển khai nhà cung cấp mới trong PicoClaw. - ---- - -## Mục lục - -1. [Luồng xác thực](#luồng-xác-thực) -2. [Chi tiết triển khai OAuth](#chi-tiết-triển-khai-oauth) -3. [Quản lý token](#quản-lý-token) -4. [Lấy danh sách mô hình](#lấy-danh-sách-mô-hình) -5. [Theo dõi mức sử dụng](#theo-dõi-mức-sử-dụng) -6. [Cấu trúc plugin nhà cung cấp](#cấu-trúc-plugin-nhà-cung-cấp) -7. [Yêu cầu tích hợp](#yêu-cầu-tích-hợp) -8. [Các endpoint API](#các-endpoint-api) -9. [Cấu hình](#cấu-hình) -10. [Tạo nhà cung cấp mới trong PicoClaw](#tạo-nhà-cung-cấp-mới-trong-picoclaw) - ---- - -## Luồng xác thực - -### 1. OAuth 2.0 với PKCE - -Antigravity sử dụng **OAuth 2.0 với PKCE (Proof Key for Code Exchange)** để xác thực an toàn: - -``` -┌─────────────┐ ┌─────────────────┐ -│ Client │ ───(1) Generate PKCE Pair────────> │ │ -│ │ ───(2) Open Auth URL─────────────> │ Google OAuth │ -│ │ │ Server │ -│ │ <──(3) Redirect with Code───────── │ │ -│ │ └─────────────────┘ -│ │ ───(4) Exchange Code for Tokens──> │ Token URL │ -│ │ │ │ -│ │ <──(5) Access + Refresh Tokens──── │ │ -└─────────────┘ └─────────────────┘ -``` - -### 2. Các bước chi tiết - -#### Bước 1: Tạo tham số PKCE -```typescript -function generatePkce(): { verifier: string; challenge: string } { - const verifier = randomBytes(32).toString("hex"); - const challenge = createHash("sha256").update(verifier).digest("base64url"); - return { verifier, challenge }; -} -``` - -#### Bước 2: Xây dựng URL ủy quyền -```typescript -const AUTH_URL = "https://accounts.google.com/o/oauth2/v2/auth"; -const REDIRECT_URI = "http://localhost:51121/oauth-callback"; - -function buildAuthUrl(params: { challenge: string; state: string }): string { - const url = new URL(AUTH_URL); - url.searchParams.set("client_id", CLIENT_ID); - url.searchParams.set("response_type", "code"); - url.searchParams.set("redirect_uri", REDIRECT_URI); - url.searchParams.set("scope", SCOPES.join(" ")); - url.searchParams.set("code_challenge", params.challenge); - url.searchParams.set("code_challenge_method", "S256"); - url.searchParams.set("state", params.state); - url.searchParams.set("access_type", "offline"); - url.searchParams.set("prompt", "consent"); - return url.toString(); -} -``` - -**Các phạm vi quyền cần thiết:** -```typescript -const SCOPES = [ - "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/userinfo.email", - "https://www.googleapis.com/auth/userinfo.profile", - "https://www.googleapis.com/auth/cclog", - "https://www.googleapis.com/auth/experimentsandconfigs", -]; -``` - -#### Bước 3: Xử lý callback OAuth - -**Chế độ tự động (Phát triển cục bộ):** -- Khởi động máy chủ HTTP cục bộ trên cổng 51121 -- Chờ chuyển hướng từ Google -- Trích xuất mã ủy quyền từ tham số truy vấn - -**Chế độ thủ công (Từ xa/Không có giao diện):** -- Hiển thị URL ủy quyền cho người dùng -- Người dùng hoàn tất xác thực trong trình duyệt -- Người dùng dán URL chuyển hướng đầy đủ vào terminal -- Phân tích mã từ URL đã dán - -#### Bước 4: Đổi mã lấy token -```typescript -const TOKEN_URL = "https://oauth2.googleapis.com/token"; - -async function exchangeCode(params: { - code: string; - verifier: string; -}): Promise<{ access: string; refresh: string; expires: number }> { - const response = await fetch(TOKEN_URL, { - method: "POST", - headers: { "Content-Type": "application/x-www-form-urlencoded" }, - body: new URLSearchParams({ - client_id: CLIENT_ID, - client_secret: CLIENT_SECRET, - code: params.code, - grant_type: "authorization_code", - redirect_uri: REDIRECT_URI, - code_verifier: params.verifier, - }), - }); - - const data = await response.json(); - - return { - access: data.access_token, - refresh: data.refresh_token, - expires: Date.now() + data.expires_in * 1000 - 5 * 60 * 1000, // 5 min buffer - }; -} -``` - -#### Bước 5: Lấy dữ liệu người dùng bổ sung - -**Email người dùng:** -```typescript -async function fetchUserEmail(accessToken: string): Promise { - const response = await fetch( - "https://www.googleapis.com/oauth2/v1/userinfo?alt=json", - { headers: { Authorization: `Bearer ${accessToken}` } } - ); - const data = await response.json(); - return data.email; -} -``` - -**ID dự án (Bắt buộc cho các lệnh gọi API):** -```typescript -async function fetchProjectId(accessToken: string): Promise { - const headers = { - Authorization: `Bearer ${accessToken}`, - "Content-Type": "application/json", - "User-Agent": "google-api-nodejs-client/9.15.1", - "X-Goog-Api-Client": "google-cloud-sdk vscode_cloudshelleditor/0.1", - "Client-Metadata": JSON.stringify({ - ideType: "IDE_UNSPECIFIED", - platform: "PLATFORM_UNSPECIFIED", - pluginType: "GEMINI", - }), - }; - - const response = await fetch( - "https://cloudcode-pa.googleapis.com/v1internal:loadCodeAssist", - { - method: "POST", - headers, - body: JSON.stringify({ - metadata: { - ideType: "IDE_UNSPECIFIED", - platform: "PLATFORM_UNSPECIFIED", - pluginType: "GEMINI", - }, - }), - } - ); - - const data = await response.json(); - return data.cloudaicompanionProject || "rising-fact-p41fc"; // Giá trị mặc định dự phòng -} -``` - ---- - -## Chi tiết triển khai OAuth - -### Thông tin xác thực client - -**Quan trọng:** Các giá trị này được mã hóa base64 trong mã nguồn để đồng bộ với pi-ai: - -```typescript -const decode = (s: string) => Buffer.from(s, "base64").toString(); - -const CLIENT_ID = decode( - "MTA3MTAwNjA2MDU5MS10bWhzc2luMmgyMWxjcmUyMzV2dG9sb2poNGc0MDNlcC5hcHBzLmdvb2dsZXVzZXJjb250ZW50LmNvbQ==" -); -const CLIENT_SECRET = decode("R09DU1BYLUs1OEZXUjQ4NkxkTEoxbUxCOHNYQzR6NnFEQWY="); -``` - -### Các chế độ luồng OAuth - -1. **Luồng tự động** (Máy cục bộ có trình duyệt): - - Tự động mở trình duyệt - - Máy chủ callback cục bộ bắt chuyển hướng - - Không cần tương tác người dùng sau xác thực ban đầu - -2. **Luồng thủ công** (Từ xa/Không có giao diện/WSL2): - - Hiển thị URL để sao chép-dán thủ công - - Người dùng hoàn tất xác thực trong trình duyệt bên ngoài - - Người dùng dán lại URL chuyển hướng đầy đủ - -```typescript -function shouldUseManualOAuthFlow(isRemote: boolean): boolean { - return isRemote || isWSL2Sync(); -} -``` - ---- - -## Quản lý token - -### Cấu trúc hồ sơ xác thực - -```typescript -type OAuthCredential = { - type: "oauth"; - provider: "google-antigravity"; - access: string; // Token truy cập - refresh: string; // Token làm mới - expires: number; // Dấu thời gian hết hạn (ms kể từ epoch) - email?: string; // Email người dùng - projectId?: string; // ID dự án Google Cloud -}; -``` - -### Làm mới token - -Thông tin xác thực bao gồm token làm mới có thể được sử dụng để lấy token truy cập mới khi token hiện tại hết hạn. Thời gian hết hạn được đặt với bộ đệm 5 phút để tránh điều kiện tranh chấp. - ---- - -## Lấy danh sách mô hình - -### Lấy các mô hình khả dụng - -```typescript -const BASE_URL = "https://cloudcode-pa.googleapis.com"; - -async function fetchAvailableModels( - accessToken: string, - projectId: string -): Promise { - const headers = { - Authorization: `Bearer ${accessToken}`, - "Content-Type": "application/json", - "User-Agent": "antigravity", - "X-Goog-Api-Client": "google-cloud-sdk vscode_cloudshelleditor/0.1", - }; - - const response = await fetch( - `${BASE_URL}/v1internal:fetchAvailableModels`, - { - method: "POST", - headers, - body: JSON.stringify({ project: projectId }), - } - ); - - const data = await response.json(); - - // Trả về các mô hình kèm thông tin hạn mức - return Object.entries(data.models).map(([modelId, modelInfo]) => ({ - id: modelId, - displayName: modelInfo.displayName, - quotaInfo: { - remainingFraction: modelInfo.quotaInfo?.remainingFraction, - resetTime: modelInfo.quotaInfo?.resetTime, - isExhausted: modelInfo.quotaInfo?.isExhausted, - }, - })); -} -``` - -### Định dạng phản hồi - -```typescript -type FetchAvailableModelsResponse = { - models?: Record; -}; -``` - ---- - -## Theo dõi mức sử dụng - -### Lấy dữ liệu sử dụng - -```typescript -export async function fetchAntigravityUsage( - token: string, - timeoutMs: number -): Promise { - // 1. Lấy thông tin tín dụng và gói dịch vụ - const loadCodeAssistRes = await fetch( - `${BASE_URL}/v1internal:loadCodeAssist`, - { - method: "POST", - headers: { - Authorization: `Bearer ${token}`, - "Content-Type": "application/json", - }, - body: JSON.stringify({ - metadata: { - ideType: "ANTIGRAVITY", - platform: "PLATFORM_UNSPECIFIED", - pluginType: "GEMINI", - }, - }), - } - ); - - // Trích xuất thông tin tín dụng - const { availablePromptCredits, planInfo, currentTier } = data; - - // 2. Lấy hạn mức mô hình - const modelsRes = await fetch( - `${BASE_URL}/v1internal:fetchAvailableModels`, - { - method: "POST", - headers: { Authorization: `Bearer ${token}` }, - body: JSON.stringify({ project: projectId }), - } - ); - - // Xây dựng cửa sổ sử dụng - return { - provider: "google-antigravity", - displayName: "Google Antigravity", - windows: [ - { label: "Credits", usedPercent: calculateUsedPercent(available, monthly) }, - // Hạn mức từng mô hình... - ], - plan: currentTier?.name || planType, - }; -} -``` - -### Cấu trúc phản hồi sử dụng - -```typescript -type ProviderUsageSnapshot = { - provider: "google-antigravity"; - displayName: string; - windows: UsageWindow[]; - plan?: string; - error?: string; -}; - -type UsageWindow = { - label: string; // "Credits" hoặc ID mô hình - usedPercent: number; // 0-100 - resetAt?: number; // Dấu thời gian khi hạn mức được đặt lại -}; -``` - ---- - -## Cấu trúc plugin nhà cung cấp - -### Định nghĩa plugin - -```typescript -const antigravityPlugin = { - id: "google-antigravity-auth", - name: "Google Antigravity Auth", - description: "OAuth flow for Google Antigravity (Cloud Code Assist)", - configSchema: emptyPluginConfigSchema(), - - register(api: PicoClawPluginApi) { - api.registerProvider({ - id: "google-antigravity", - label: "Google Antigravity", - docsPath: "/providers/models", - aliases: ["antigravity"], - - auth: [ - { - id: "oauth", - label: "Google OAuth", - hint: "PKCE + localhost callback", - kind: "oauth", - run: async (ctx: ProviderAuthContext) => { - // Triển khai OAuth tại đây - }, - }, - ], - }); - }, -}; -``` - -### ProviderAuthContext - -```typescript -type ProviderAuthContext = { - config: PicoClawConfig; - agentDir?: string; - workspaceDir?: string; - prompter: WizardPrompter; // Lời nhắc/thông báo UI - runtime: RuntimeEnv; // Ghi log, v.v. - isRemote: boolean; // Có đang chạy từ xa không - openUrl: (url: string) => Promise; // Mở trình duyệt - oauth: { - createVpsAwareHandlers: Function; - }; -}; -``` - -### ProviderAuthResult - -```typescript -type ProviderAuthResult = { - profiles: Array<{ - profileId: string; - credential: AuthProfileCredential; - }>; - configPatch?: Partial; - defaultModel?: string; - notes?: string[]; -}; -``` - ---- - -## Yêu cầu tích hợp - -### 1. Môi trường/Phụ thuộc cần thiết - -- Go ≥ 1.25 -- Mã nguồn PicoClaw (`pkg/providers/` và `pkg/auth/`) -- Các gói thư viện chuẩn `crypto` và `net/http` - -### 2. Các header bắt buộc cho lệnh gọi API - -```typescript -const REQUIRED_HEADERS = { - "Authorization": `Bearer ${accessToken}`, - "Content-Type": "application/json", - "User-Agent": "antigravity", // hoặc "google-api-nodejs-client/9.15.1" - "X-Goog-Api-Client": "google-cloud-sdk vscode_cloudshelleditor/0.1", -}; - -// Đối với các lệnh gọi loadCodeAssist, cũng bao gồm: -const CLIENT_METADATA = { - ideType: "ANTIGRAVITY", // hoặc "IDE_UNSPECIFIED" - platform: "PLATFORM_UNSPECIFIED", - pluginType: "GEMINI", -}; -``` - -### 3. Làm sạch schema mô hình - -Antigravity sử dụng các mô hình tương thích Gemini, vì vậy schema công cụ phải được làm sạch: - -```typescript -const GOOGLE_SCHEMA_UNSUPPORTED_KEYWORDS = new Set([ - "patternProperties", - "additionalProperties", - "$schema", - "$id", - "$ref", - "$defs", - "definitions", - "examples", - "minLength", - "maxLength", - "minimum", - "maximum", - "multipleOf", - "pattern", - "format", - "minItems", - "maxItems", - "uniqueItems", - "minProperties", - "maxProperties", -]); - -// Làm sạch schema trước khi gửi -function cleanToolSchemaForGemini(schema: Record): unknown { - // Xóa các từ khóa không được hỗ trợ - // Đảm bảo cấp cao nhất có type: "object" - // Làm phẳng các union anyOf/oneOf -} -``` - -### 4. Xử lý khối suy nghĩ (Mô hình Claude) - -Đối với các mô hình Claude qua Antigravity, khối suy nghĩ cần xử lý đặc biệt: - -```typescript -const ANTIGRAVITY_SIGNATURE_RE = /^[A-Za-z0-9+/]+={0,2}$/; - -export function sanitizeAntigravityThinkingBlocks( - messages: AgentMessage[] -): AgentMessage[] { - // Xác thực chữ ký suy nghĩ - // Chuẩn hóa các trường chữ ký - // Loại bỏ các khối suy nghĩ chưa ký -} -``` - ---- - -## Các endpoint API - -### Endpoint xác thực - -| Endpoint | Phương thức | Mục đích | -|----------|------------|----------| -| `https://accounts.google.com/o/oauth2/v2/auth` | GET | Ủy quyền OAuth | -| `https://oauth2.googleapis.com/token` | POST | Trao đổi token | -| `https://www.googleapis.com/oauth2/v1/userinfo` | GET | Thông tin người dùng (email) | - -### Endpoint Cloud Code Assist - -| Endpoint | Phương thức | Mục đích | -|----------|------------|----------| -| `https://cloudcode-pa.googleapis.com/v1internal:loadCodeAssist` | POST | Tải thông tin dự án, tín dụng, gói dịch vụ | -| `https://cloudcode-pa.googleapis.com/v1internal:fetchAvailableModels` | POST | Liệt kê các mô hình khả dụng kèm hạn mức | -| `https://cloudcode-pa.googleapis.com/v1internal:streamGenerateContent?alt=sse` | POST | Endpoint streaming chat | - -**Định dạng yêu cầu API (Chat):** -Endpoint `v1internal:streamGenerateContent` yêu cầu một envelope bao bọc yêu cầu Gemini tiêu chuẩn: - -```json -{ - "project": "your-project-id", - "model": "model-id", - "request": { - "contents": [...], - "systemInstruction": {...}, - "generationConfig": {...}, - "tools": [...] - }, - "requestType": "agent", - "userAgent": "antigravity", - "requestId": "agent-timestamp-random" -} -``` - -**Định dạng phản hồi API (SSE):** -Mỗi thông điệp SSE (`data: {...}`) được bao bọc trong trường `response`: - -```json -{ - "response": { - "candidates": [...], - "usageMetadata": {...}, - "modelVersion": "...", - "responseId": "..." - }, - "traceId": "...", - "metadata": {} -} -``` - ---- - -## Cấu hình - -### Cấu hình config.json - -```json -{ - "model_list": [ - { - "model_name": "gemini-flash", - "model": "antigravity/gemini-3-flash", - "auth_method": "oauth" - } - ], - "agents": { - "defaults": { - "model_name": "gemini-flash" - } - } -} -``` - -### Lưu trữ hồ sơ xác thực - -Hồ sơ xác thực được lưu trữ trong `~/.picoclaw/auth.json`: - -```json -{ - "credentials": { - "google-antigravity": { - "access_token": "ya29...", - "refresh_token": "1//...", - "expires_at": "2026-01-01T00:00:00Z", - "provider": "google-antigravity", - "auth_method": "oauth", - "email": "user@example.com", - "project_id": "my-project-id" - } - } -} -``` - ---- - -## Tạo nhà cung cấp mới trong PicoClaw - -Các nhà cung cấp PicoClaw được triển khai dưới dạng gói Go trong `pkg/providers/`. Để thêm nhà cung cấp mới: - -### Triển khai từng bước - -#### 1. Tạo file nhà cung cấp - -Tạo file Go mới trong `pkg/providers/`: - -``` -pkg/providers/ -└── your_provider.go -``` - -#### 2. Triển khai interface Provider - -Nhà cung cấp của bạn phải triển khai interface `Provider` được định nghĩa trong `pkg/providers/types.go`: - -```go -package providers - -type YourProvider struct { - apiKey string - apiBase string -} - -func NewYourProvider(apiKey, apiBase, proxy string) *YourProvider { - if apiBase == "" { - apiBase = "https://api.your-provider.com/v1" - } - return &YourProvider{apiKey: apiKey, apiBase: apiBase} -} - -func (p *YourProvider) Chat(ctx context.Context, messages []Message, tools []Tool, cb StreamCallback) error { - // Triển khai hoàn thành chat với streaming -} -``` - -#### 3. Đăng ký trong factory - -Thêm nhà cung cấp của bạn vào switch giao thức trong `pkg/providers/factory.go`: - -```go -case "your-provider": - return NewYourProvider(sel.apiKey, sel.apiBase, sel.proxy), nil -``` - -#### 4. Thêm cấu hình mặc định (Tùy chọn) - -Thêm mục mặc định trong `pkg/config/defaults.go`: - -```go -{ - ModelName: "your-model", - Model: "your-provider/model-name", - APIKey: "", -}, -``` - -#### 5. Thêm hỗ trợ xác thực (Tùy chọn) - -Nếu nhà cung cấp của bạn yêu cầu OAuth hoặc xác thực đặc biệt, thêm case vào `cmd/picoclaw/internal/auth/helpers.go`: - -```go -case "your-provider": - authLoginYourProvider() -``` - -#### 6. Cấu hình qua `config.json` - -```json -{ - "model_list": [ - { - "model_name": "your-model", - "model": "your-provider/model-name", - "api_keys": ["your-api-key"], - "api_base": "https://api.your-provider.com/v1" - } - ] -} -``` - ---- - -## Kiểm thử triển khai của bạn - -### Lệnh CLI - -```bash -# Xác thực với nhà cung cấp -picoclaw auth login --provider your-provider - -# Liệt kê mô hình (cho Antigravity) -picoclaw auth models - -# Khởi động gateway -picoclaw gateway - -# Chạy agent với mô hình cụ thể -picoclaw agent -m "Hello" --model your-model -``` - -### Biến môi trường cho kiểm thử - -```bash -# Ghi đè mô hình mặc định -export PICOCLAW_AGENTS_DEFAULTS_MODEL=your-model - -# Ghi đè cài đặt nhà cung cấp -export PICOCLAW_MODEL_LIST='[{"model_name":"your-model","model":"your-provider/model-name","api_keys":["..."]}]' -``` - ---- - -## Tài liệu tham khảo - -- **File nguồn:** - - `pkg/providers/antigravity_provider.go` - Triển khai nhà cung cấp Antigravity - - `pkg/auth/oauth.go` - Triển khai luồng OAuth - - `pkg/auth/store.go` - Lưu trữ thông tin xác thực (`~/.picoclaw/auth.json`) - - `pkg/providers/factory.go` - Factory nhà cung cấp và định tuyến giao thức - - `pkg/providers/types.go` - Định nghĩa interface nhà cung cấp - - `cmd/picoclaw/internal/auth/helpers.go` - Lệnh CLI xác thực - -- **Tài liệu:** - - `docs/ANTIGRAVITY_USAGE.md` - Hướng dẫn sử dụng Antigravity - - `docs/migration/model-list-migration.md` - Hướng dẫn di chuyển - ---- - -## Lưu ý - -1. **Dự án Google Cloud:** Antigravity yêu cầu Gemini for Google Cloud được bật trên dự án Google Cloud của bạn -2. **Hạn mức:** Sử dụng hạn mức dự án Google Cloud (không tính phí riêng) -3. **Truy cập mô hình:** Các mô hình khả dụng phụ thuộc vào cấu hình dự án Google Cloud của bạn -4. **Khối suy nghĩ:** Mô hình Claude qua Antigravity yêu cầu xử lý đặc biệt khối suy nghĩ có chữ ký -5. **Làm sạch schema:** Schema công cụ phải được làm sạch để loại bỏ các từ khóa JSON Schema không được hỗ trợ - ---- - -## Xử lý lỗi thường gặp - -### 1. Giới hạn tốc độ (HTTP 429) - -Antigravity trả về lỗi 429 khi hạn mức dự án/mô hình đã cạn kiệt. Phản hồi lỗi thường chứa `quotaResetDelay` trong trường `details`. - -**Ví dụ lỗi 429:** -```json -{ - "error": { - "code": 429, - "message": "You have exhausted your capacity on this model. Your quota will reset after 4h30m28s.", - "status": "RESOURCE_EXHAUSTED", - "details": [ - { - "@type": "type.googleapis.com/google.rpc.ErrorInfo", - "metadata": { - "quotaResetDelay": "4h30m28.060903746s" - } - } - ] - } -} -``` - -### 2. Phản hồi trống (Mô hình bị hạn chế) - -Một số mô hình có thể xuất hiện trong danh sách mô hình khả dụng nhưng trả về phản hồi trống (200 OK nhưng luồng SSE trống). Điều này thường xảy ra với các mô hình xem trước hoặc bị hạn chế mà dự án hiện tại không có quyền sử dụng. - -**Cách xử lý:** Coi phản hồi trống là lỗi, thông báo cho người dùng rằng mô hình có thể bị hạn chế hoặc không hợp lệ cho dự án của họ. - ---- - -## Khắc phục sự cố - -### "Token expired" (Token đã hết hạn) -- Làm mới token OAuth: `picoclaw auth login --provider antigravity` - -### "Gemini for Google Cloud is not enabled" (Gemini for Google Cloud chưa được bật) -- Bật API trong Google Cloud Console của bạn - -### "Project not found" (Không tìm thấy dự án) -- Đảm bảo dự án Google Cloud của bạn đã bật các API cần thiết -- Kiểm tra xem ID dự án có được lấy chính xác trong quá trình xác thực không - -### Mô hình không xuất hiện trong danh sách -- Xác minh xác thực OAuth đã hoàn tất thành công -- Kiểm tra lưu trữ hồ sơ xác thực: `~/.picoclaw/auth.json` -- Chạy lại `picoclaw auth login --provider antigravity` diff --git a/docs/security/ANTIGRAVITY_AUTH.zh.md b/docs/security/ANTIGRAVITY_AUTH.zh.md deleted file mode 100644 index ccd6b23d..00000000 --- a/docs/security/ANTIGRAVITY_AUTH.zh.md +++ /dev/null @@ -1,809 +0,0 @@ -> 返回 [README](../../README.md) - -# Antigravity 认证与集成指南 - -## 概述 - -**Antigravity**(Google Cloud Code Assist)是由 Google 支持的 AI 模型提供商,通过 Google 的云基础设施提供对 Claude Opus 4.6 和 Gemini 等模型的访问。本文档提供了关于认证工作原理、如何获取模型以及如何在 PicoClaw 中实现新提供商的完整指南。 - ---- - -## 目录 - -1. [认证流程](#认证流程) -2. [OAuth 实现细节](#oauth-实现细节) -3. [令牌管理](#令牌管理) -4. [模型列表获取](#模型列表获取) -5. [用量追踪](#用量追踪) -6. [提供商插件结构](#提供商插件结构) -7. [集成要求](#集成要求) -8. [API 端点](#api-端点) -9. [配置](#配置) -10. [在 PicoClaw 中创建新提供商](#在-picoclaw-中创建新提供商) - ---- - -## 认证流程 - -### 1. 带 PKCE 的 OAuth 2.0 - -Antigravity 使用 **OAuth 2.0 with PKCE(Proof Key for Code Exchange)** 进行安全认证: - -``` -┌─────────────┐ ┌─────────────────┐ -│ Client │ ───(1) Generate PKCE Pair────────> │ │ -│ │ ───(2) Open Auth URL─────────────> │ Google OAuth │ -│ │ │ Server │ -│ │ <──(3) Redirect with Code───────── │ │ -│ │ └─────────────────┘ -│ │ ───(4) Exchange Code for Tokens──> │ Token URL │ -│ │ │ │ -│ │ <──(5) Access + Refresh Tokens──── │ │ -└─────────────┘ └─────────────────┘ -``` - -### 2. 详细步骤 - -#### 步骤 1:生成 PKCE 参数 -```typescript -function generatePkce(): { verifier: string; challenge: string } { - const verifier = randomBytes(32).toString("hex"); - const challenge = createHash("sha256").update(verifier).digest("base64url"); - return { verifier, challenge }; -} -``` - -#### 步骤 2:构建授权 URL -```typescript -const AUTH_URL = "https://accounts.google.com/o/oauth2/v2/auth"; -const REDIRECT_URI = "http://localhost:51121/oauth-callback"; - -function buildAuthUrl(params: { challenge: string; state: string }): string { - const url = new URL(AUTH_URL); - url.searchParams.set("client_id", CLIENT_ID); - url.searchParams.set("response_type", "code"); - url.searchParams.set("redirect_uri", REDIRECT_URI); - url.searchParams.set("scope", SCOPES.join(" ")); - url.searchParams.set("code_challenge", params.challenge); - url.searchParams.set("code_challenge_method", "S256"); - url.searchParams.set("state", params.state); - url.searchParams.set("access_type", "offline"); - url.searchParams.set("prompt", "consent"); - return url.toString(); -} -``` - -**所需权限范围:** -```typescript -const SCOPES = [ - "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/userinfo.email", - "https://www.googleapis.com/auth/userinfo.profile", - "https://www.googleapis.com/auth/cclog", - "https://www.googleapis.com/auth/experimentsandconfigs", -]; -``` - -#### 步骤 3:处理 OAuth 回调 - -**自动模式(本地开发):** -- 在端口 51121 上启动本地 HTTP 服务器 -- 等待来自 Google 的重定向 -- 从查询参数中提取授权码 - -**手动模式(远程/无头环境):** -- 向用户显示授权 URL -- 用户在浏览器中完成认证 -- 用户将完整的重定向 URL 粘贴回终端 -- 从粘贴的 URL 中解析授权码 - -#### 步骤 4:用授权码交换令牌 -```typescript -const TOKEN_URL = "https://oauth2.googleapis.com/token"; - -async function exchangeCode(params: { - code: string; - verifier: string; -}): Promise<{ access: string; refresh: string; expires: number }> { - const response = await fetch(TOKEN_URL, { - method: "POST", - headers: { "Content-Type": "application/x-www-form-urlencoded" }, - body: new URLSearchParams({ - client_id: CLIENT_ID, - client_secret: CLIENT_SECRET, - code: params.code, - grant_type: "authorization_code", - redirect_uri: REDIRECT_URI, - code_verifier: params.verifier, - }), - }); - - const data = await response.json(); - - return { - access: data.access_token, - refresh: data.refresh_token, - expires: Date.now() + data.expires_in * 1000 - 5 * 60 * 1000, // 5 min buffer - }; -} -``` - -#### 步骤 5:获取额外的用户数据 - -**用户邮箱:** -```typescript -async function fetchUserEmail(accessToken: string): Promise { - const response = await fetch( - "https://www.googleapis.com/oauth2/v1/userinfo?alt=json", - { headers: { Authorization: `Bearer ${accessToken}` } } - ); - const data = await response.json(); - return data.email; -} -``` - -**项目 ID(API 调用必需):** -```typescript -async function fetchProjectId(accessToken: string): Promise { - const headers = { - Authorization: `Bearer ${accessToken}`, - "Content-Type": "application/json", - "User-Agent": "google-api-nodejs-client/9.15.1", - "X-Goog-Api-Client": "google-cloud-sdk vscode_cloudshelleditor/0.1", - "Client-Metadata": JSON.stringify({ - ideType: "IDE_UNSPECIFIED", - platform: "PLATFORM_UNSPECIFIED", - pluginType: "GEMINI", - }), - }; - - const response = await fetch( - "https://cloudcode-pa.googleapis.com/v1internal:loadCodeAssist", - { - method: "POST", - headers, - body: JSON.stringify({ - metadata: { - ideType: "IDE_UNSPECIFIED", - platform: "PLATFORM_UNSPECIFIED", - pluginType: "GEMINI", - }, - }), - } - ); - - const data = await response.json(); - return data.cloudaicompanionProject || "rising-fact-p41fc"; // 默认回退值 -} -``` - ---- - -## OAuth 实现细节 - -### 客户端凭据 - -**重要:** 这些凭据在源代码中以 base64 编码存储,用于与 pi-ai 同步: - -```typescript -const decode = (s: string) => Buffer.from(s, "base64").toString(); - -const CLIENT_ID = decode( - "MTA3MTAwNjA2MDU5MS10bWhzc2luMmgyMWxjcmUyMzV2dG9sb2poNGc0MDNlcC5hcHBzLmdvb2dsZXVzZXJjb250ZW50LmNvbQ==" -); -const CLIENT_SECRET = decode("R09DU1BYLUs1OEZXUjQ4NkxkTEoxbUxCOHNYQzR6NnFEQWY="); -``` - -### OAuth 流程模式 - -1. **自动流程**(有浏览器的本地机器): - - 自动打开浏览器 - - 本地回调服务器捕获重定向 - - 初始认证后无需用户交互 - -2. **手动流程**(远程/无头/WSL2 环境): - - 显示 URL 供手动复制粘贴 - - 用户在外部浏览器中完成认证 - - 用户将完整的重定向 URL 粘贴回来 - -```typescript -function shouldUseManualOAuthFlow(isRemote: boolean): boolean { - return isRemote || isWSL2Sync(); -} -``` - ---- - -## 令牌管理 - -### 认证配置文件结构 - -```typescript -type OAuthCredential = { - type: "oauth"; - provider: "google-antigravity"; - access: string; // 访问令牌 - refresh: string; // 刷新令牌 - expires: number; // 过期时间戳(毫秒,自 epoch 起) - email?: string; // 用户邮箱 - projectId?: string; // Google Cloud 项目 ID -}; -``` - -### 令牌刷新 - -凭据包含一个刷新令牌,可在当前访问令牌过期时用于获取新的访问令牌。过期时间设置了 5 分钟的缓冲区以防止竞态条件。 - ---- - -## 模型列表获取 - -### 获取可用模型 - -```typescript -const BASE_URL = "https://cloudcode-pa.googleapis.com"; - -async function fetchAvailableModels( - accessToken: string, - projectId: string -): Promise { - const headers = { - Authorization: `Bearer ${accessToken}`, - "Content-Type": "application/json", - "User-Agent": "antigravity", - "X-Goog-Api-Client": "google-cloud-sdk vscode_cloudshelleditor/0.1", - }; - - const response = await fetch( - `${BASE_URL}/v1internal:fetchAvailableModels`, - { - method: "POST", - headers, - body: JSON.stringify({ project: projectId }), - } - ); - - const data = await response.json(); - - // 返回带有配额信息的模型 - return Object.entries(data.models).map(([modelId, modelInfo]) => ({ - id: modelId, - displayName: modelInfo.displayName, - quotaInfo: { - remainingFraction: modelInfo.quotaInfo?.remainingFraction, - resetTime: modelInfo.quotaInfo?.resetTime, - isExhausted: modelInfo.quotaInfo?.isExhausted, - }, - })); -} -``` - -### 响应格式 - -```typescript -type FetchAvailableModelsResponse = { - models?: Record; -}; -``` - ---- - -## 用量追踪 - -### 获取用量数据 - -```typescript -export async function fetchAntigravityUsage( - token: string, - timeoutMs: number -): Promise { - // 1. 获取额度和计划信息 - const loadCodeAssistRes = await fetch( - `${BASE_URL}/v1internal:loadCodeAssist`, - { - method: "POST", - headers: { - Authorization: `Bearer ${token}`, - "Content-Type": "application/json", - }, - body: JSON.stringify({ - metadata: { - ideType: "ANTIGRAVITY", - platform: "PLATFORM_UNSPECIFIED", - pluginType: "GEMINI", - }, - }), - } - ); - - // 提取额度信息 - const { availablePromptCredits, planInfo, currentTier } = data; - - // 2. 获取模型配额 - const modelsRes = await fetch( - `${BASE_URL}/v1internal:fetchAvailableModels`, - { - method: "POST", - headers: { Authorization: `Bearer ${token}` }, - body: JSON.stringify({ project: projectId }), - } - ); - - // 构建用量窗口 - return { - provider: "google-antigravity", - displayName: "Google Antigravity", - windows: [ - { label: "Credits", usedPercent: calculateUsedPercent(available, monthly) }, - // 各模型配额... - ], - plan: currentTier?.name || planType, - }; -} -``` - -### 用量响应结构 - -```typescript -type ProviderUsageSnapshot = { - provider: "google-antigravity"; - displayName: string; - windows: UsageWindow[]; - plan?: string; - error?: string; -}; - -type UsageWindow = { - label: string; // "Credits" 或模型 ID - usedPercent: number; // 0-100 - resetAt?: number; // 配额重置的时间戳 -}; -``` - ---- - -## 提供商插件结构 - -### 插件定义 - -```typescript -const antigravityPlugin = { - id: "google-antigravity-auth", - name: "Google Antigravity Auth", - description: "OAuth flow for Google Antigravity (Cloud Code Assist)", - configSchema: emptyPluginConfigSchema(), - - register(api: PicoClawPluginApi) { - api.registerProvider({ - id: "google-antigravity", - label: "Google Antigravity", - docsPath: "/providers/models", - aliases: ["antigravity"], - - auth: [ - { - id: "oauth", - label: "Google OAuth", - hint: "PKCE + localhost callback", - kind: "oauth", - run: async (ctx: ProviderAuthContext) => { - // OAuth 实现在此处 - }, - }, - ], - }); - }, -}; -``` - -### ProviderAuthContext - -```typescript -type ProviderAuthContext = { - config: PicoClawConfig; - agentDir?: string; - workspaceDir?: string; - prompter: WizardPrompter; // UI 提示/通知 - runtime: RuntimeEnv; // 日志等 - isRemote: boolean; // 是否在远程运行 - openUrl: (url: string) => Promise; // 浏览器打开器 - oauth: { - createVpsAwareHandlers: Function; - }; -}; -``` - -### ProviderAuthResult - -```typescript -type ProviderAuthResult = { - profiles: Array<{ - profileId: string; - credential: AuthProfileCredential; - }>; - configPatch?: Partial; - defaultModel?: string; - notes?: string[]; -}; -``` - ---- - -## 集成要求 - -### 1. 所需环境/依赖 - -- Go ≥ 1.25 -- PicoClaw 代码库(`pkg/providers/` 和 `pkg/auth/`) -- `crypto` 和 `net/http` 标准库包 - -### 2. API 调用所需的请求头 - -```typescript -const REQUIRED_HEADERS = { - "Authorization": `Bearer ${accessToken}`, - "Content-Type": "application/json", - "User-Agent": "antigravity", // 或 "google-api-nodejs-client/9.15.1" - "X-Goog-Api-Client": "google-cloud-sdk vscode_cloudshelleditor/0.1", -}; - -// 对于 loadCodeAssist 调用,还需包含: -const CLIENT_METADATA = { - ideType: "ANTIGRAVITY", // 或 "IDE_UNSPECIFIED" - platform: "PLATFORM_UNSPECIFIED", - pluginType: "GEMINI", -}; -``` - -### 3. 模型 Schema 清理 - -Antigravity 使用兼容 Gemini 的模型,因此工具 schema 必须进行清理: - -```typescript -const GOOGLE_SCHEMA_UNSUPPORTED_KEYWORDS = new Set([ - "patternProperties", - "additionalProperties", - "$schema", - "$id", - "$ref", - "$defs", - "definitions", - "examples", - "minLength", - "maxLength", - "minimum", - "maximum", - "multipleOf", - "pattern", - "format", - "minItems", - "maxItems", - "uniqueItems", - "minProperties", - "maxProperties", -]); - -// 发送前清理 schema -function cleanToolSchemaForGemini(schema: Record): unknown { - // 移除不支持的关键字 - // 确保顶层有 type: "object" - // 展平 anyOf/oneOf 联合类型 -} -``` - -### 4. 思维块处理(Claude 模型) - -对于 Antigravity 的 Claude 模型,思维块需要特殊处理: - -```typescript -const ANTIGRAVITY_SIGNATURE_RE = /^[A-Za-z0-9+/]+={0,2}$/; - -export function sanitizeAntigravityThinkingBlocks( - messages: AgentMessage[] -): AgentMessage[] { - // 验证思维签名 - // 规范化签名字段 - // 丢弃未签名的思维块 -} -``` - ---- - -## API 端点 - -### 认证端点 - -| 端点 | 方法 | 用途 | -|------|------|------| -| `https://accounts.google.com/o/oauth2/v2/auth` | GET | OAuth 授权 | -| `https://oauth2.googleapis.com/token` | POST | 令牌交换 | -| `https://www.googleapis.com/oauth2/v1/userinfo` | GET | 用户信息(邮箱) | - -### Cloud Code Assist 端点 - -| 端点 | 方法 | 用途 | -|------|------|------| -| `https://cloudcode-pa.googleapis.com/v1internal:loadCodeAssist` | POST | 加载项目信息、额度、计划 | -| `https://cloudcode-pa.googleapis.com/v1internal:fetchAvailableModels` | POST | 列出可用模型及配额 | -| `https://cloudcode-pa.googleapis.com/v1internal:streamGenerateContent?alt=sse` | POST | 聊天流式端点 | - -**API 请求格式(聊天):** -`v1internal:streamGenerateContent` 端点期望一个包装标准 Gemini 请求的信封格式: - -```json -{ - "project": "your-project-id", - "model": "model-id", - "request": { - "contents": [...], - "systemInstruction": {...}, - "generationConfig": {...}, - "tools": [...] - }, - "requestType": "agent", - "userAgent": "antigravity", - "requestId": "agent-timestamp-random" -} -``` - -**API 响应格式(SSE):** -每条 SSE 消息(`data: {...}`)被包装在 `response` 字段中: - -```json -{ - "response": { - "candidates": [...], - "usageMetadata": {...}, - "modelVersion": "...", - "responseId": "..." - }, - "traceId": "...", - "metadata": {} -} -``` - ---- - -## 配置 - -### config.json 配置 - -```json -{ - "model_list": [ - { - "model_name": "gemini-flash", - "model": "antigravity/gemini-3-flash", - "auth_method": "oauth" - } - ], - "agents": { - "defaults": { - "model_name": "gemini-flash" - } - } -} -``` - -### 认证配置文件存储 - -认证配置文件存储在 `~/.picoclaw/auth.json` 中: - -```json -{ - "credentials": { - "google-antigravity": { - "access_token": "ya29...", - "refresh_token": "1//...", - "expires_at": "2026-01-01T00:00:00Z", - "provider": "google-antigravity", - "auth_method": "oauth", - "email": "user@example.com", - "project_id": "my-project-id" - } - } -} -``` - ---- - -## 在 PicoClaw 中创建新提供商 - -PicoClaw 提供商以 Go 包的形式实现,位于 `pkg/providers/` 下。要添加新提供商: - -### 分步实现 - -#### 1. 创建提供商文件 - -在 `pkg/providers/` 中创建新的 Go 文件: - -``` -pkg/providers/ -└── your_provider.go -``` - -#### 2. 实现 Provider 接口 - -你的提供商必须实现 `pkg/providers/types.go` 中定义的 `Provider` 接口: - -```go -package providers - -type YourProvider struct { - apiKey string - apiBase string -} - -func NewYourProvider(apiKey, apiBase, proxy string) *YourProvider { - if apiBase == "" { - apiBase = "https://api.your-provider.com/v1" - } - return &YourProvider{apiKey: apiKey, apiBase: apiBase} -} - -func (p *YourProvider) Chat(ctx context.Context, messages []Message, tools []Tool, cb StreamCallback) error { - // 实现带流式传输的聊天补全 -} -``` - -#### 3. 在工厂中注册 - -将你的提供商添加到 `pkg/providers/factory.go` 中的协议分支: - -```go -case "your-provider": - return NewYourProvider(sel.apiKey, sel.apiBase, sel.proxy), nil -``` - -#### 4. 添加默认配置(可选) - -在 `pkg/config/defaults.go` 中添加默认条目: - -```go -{ - ModelName: "your-model", - Model: "your-provider/model-name", - APIKey: "", -}, -``` - -#### 5. 添加认证支持(可选) - -如果你的提供商需要 OAuth 或特殊认证,在 `cmd/picoclaw/internal/auth/helpers.go` 中添加分支: - -```go -case "your-provider": - authLoginYourProvider() -``` - -#### 6. 通过 `config.json` 配置 - -```json -{ - "model_list": [ - { - "model_name": "your-model", - "model": "your-provider/model-name", - "api_keys": ["your-api-key"], - "api_base": "https://api.your-provider.com/v1" - } - ] -} -``` - ---- - -## 测试你的实现 - -### CLI 命令 - -```bash -# 使用提供商进行认证 -picoclaw auth login --provider your-provider - -# 列出模型(用于 Antigravity) -picoclaw auth models - -# 启动网关 -picoclaw gateway - -# 使用指定模型运行代理 -picoclaw agent -m "Hello" --model your-model -``` - -### 测试用环境变量 - -```bash -# 覆盖默认模型 -export PICOCLAW_AGENTS_DEFAULTS_MODEL=your-model - -# 覆盖提供商设置 -export PICOCLAW_MODEL_LIST='[{"model_name":"your-model","model":"your-provider/model-name","api_keys":["..."]}]' -``` - ---- - -## 参考资料 - -- **源文件:** - - `pkg/providers/antigravity_provider.go` - Antigravity 提供商实现 - - `pkg/auth/oauth.go` - OAuth 流程实现 - - `pkg/auth/store.go` - 认证凭据存储(`~/.picoclaw/auth.json`) - - `pkg/providers/factory.go` - 提供商工厂和协议路由 - - `pkg/providers/types.go` - 提供商接口定义 - - `cmd/picoclaw/internal/auth/helpers.go` - 认证 CLI 命令 - -- **文档:** - - `docs/ANTIGRAVITY_USAGE.md` - Antigravity 使用指南 - - `docs/migration/model-list-migration.md` - 迁移指南 - ---- - -## 注意事项 - -1. **Google Cloud 项目:** Antigravity 要求在你的 Google Cloud 项目上启用 Gemini for Google Cloud -2. **配额:** 使用 Google Cloud 项目配额(非独立计费) -3. **模型访问:** 可用模型取决于你的 Google Cloud 项目配置 -4. **思维块:** 通过 Antigravity 使用的 Claude 模型需要对带签名的思维块进行特殊处理 -5. **Schema 清理:** 工具 schema 必须清理以移除不支持的 JSON Schema 关键字 - ---- - ---- - -## 常见错误处理 - -### 1. 速率限制(HTTP 429) - -当项目/模型配额耗尽时,Antigravity 会返回 429 错误。错误响应通常在 `details` 字段中包含 `quotaResetDelay`。 - -**429 错误示例:** -```json -{ - "error": { - "code": 429, - "message": "You have exhausted your capacity on this model. Your quota will reset after 4h30m28s.", - "status": "RESOURCE_EXHAUSTED", - "details": [ - { - "@type": "type.googleapis.com/google.rpc.ErrorInfo", - "metadata": { - "quotaResetDelay": "4h30m28.060903746s" - } - } - ] - } -} -``` - -### 2. 空响应(受限模型) - -某些模型可能出现在可用模型列表中,但返回空响应(200 OK 但 SSE 流为空)。这通常发生在当前项目没有权限使用的预览版或受限模型上。 - -**处理方式:** 将空响应视为错误,通知用户该模型可能对其项目受限或无效。 - ---- - -## 故障排除 - -### "Token expired"(令牌已过期) -- 刷新 OAuth 令牌:`picoclaw auth login --provider antigravity` - -### "Gemini for Google Cloud is not enabled"(Gemini for Google Cloud 未启用) -- 在 Google Cloud Console 中启用该 API - -### "Project not found"(项目未找到) -- 确保你的 Google Cloud 项目已启用必要的 API -- 检查认证过程中项目 ID 是否正确获取 - -### 模型未出现在列表中 -- 验证 OAuth 认证是否成功完成 -- 检查认证配置文件存储:`~/.picoclaw/auth.json` -- 重新运行 `picoclaw auth login --provider antigravity` diff --git a/docs/security/README.md b/docs/security/README.md index 7bd42da1..f184e98c 100644 --- a/docs/security/README.md +++ b/docs/security/README.md @@ -5,4 +5,3 @@ Security-focused docs covering configuration, secrets handling, and provider aut - [Security Configuration](security_configuration.md): security-related config knobs and hardening guidance. - [Sensitive Data Filtering](sensitive_data_filtering.md): filtering secrets from tool output before model use. - [Credential Encryption](credential_encryption.md): encrypting stored API keys and credentials. -- [Antigravity Authentication & Integration Guide](ANTIGRAVITY_AUTH.md): auth flow and integration notes for the Antigravity provider. diff --git a/docs/security/security_configuration.md b/docs/security/security_configuration.md index ec760aa8..02d8c109 100644 --- a/docs/security/security_configuration.md +++ b/docs/security/security_configuration.md @@ -1,665 +1,82 @@ -# Security Configuration +# Configuration and credentials -## Overview +PicoClaw loads `config.json` and a `.security.yml` beside that JSON file. The security file overrides corresponding secret values in the main configuration. `PICOCLAW_HOME` changes the default data directory, including the default config path; `PICOCLAW_CONFIG` selects a different JSON file and therefore the location of its companion security file. -PicoClaw supports separating sensitive data (API keys, tokens, secrets, passwords) from the main configuration by storing them in a `.security.yml` file. This improves security by: +Keep both files private until you have inspected them. Saving configuration separates supported secret fields into `.security.yml`, but manually written JSON, custom headers, and other arbitrary values may still contain credentials. -1. **Separation of concerns**: Configuration settings and secrets are in separate files -2. **Easier sharing**: The main config can be shared without exposing sensitive data -3. **Better version control**: `.security.yml` should be added to `.gitignore` -4. **Flexible deployment**: Different environments can use different security files +## Main configuration -## File Structure +Use the current schema shown in [config/config.example.json](../../config/config.example.json): -``` -~/.picoclaw/ -├── config.json # Main configuration (safe to share) -└── .security.yml # Security data (never share) -``` - -## How It Works - -The security configuration works through **direct field mapping**, NOT through `ref:` string references. The system automatically loads values from `.security.yml` and applies them to the corresponding fields in `config.json`. - -### Key Points: - -- Values in `.security.yml` are automatically mapped to corresponding fields in the config -- The mapping is based on field names and structure, not on reference strings -- If a value exists in `.security.yml`, it **overrides** the value in `config.json` -- You can omit sensitive fields from `config.json` entirely (recommended) - -## Security Configuration Structure - -### Complete Example: .security.yml - -```yaml -# Model API Keys -# All models MUST use `api_keys` (plural) array format -# Even a single key must be provided as an array with one element -model_list: - gpt-5.4: - api_keys: - - "sk-proj-your-actual-openai-key-1" - - "sk-proj-your-actual-openai-key-2" # Optional: Multiple keys for failover - claude-sonnet-4.6: - api_keys: - - "sk-ant-your-actual-anthropic-key" # Single key in array format - -# Channel Tokens -channels: - telegram: - token: "your-telegram-bot-token" - feishu: - app_secret: "your-feishu-app-secret" - encrypt_key: "your-feishu-encrypt-key" - verification_token: "your-feishu-verification-token" - weixin: - token: "your-weixin-token" - qq: - app_secret: "your-qq-app-secret" - dingtalk: - client_secret: "your-dingtalk-client-secret" - onebot: - access_token: "your-onebot-access-token" - wecom: - token: "your-wecom-token" - encoding_aes_key: "your-wecom-encoding-aes-key" - wecom_app: - corp_secret: "your-wecom-app-corp-secret" - token: "your-wecom-app-token" - encoding_aes_key: "your-wecom-app-encoding-aes-key" - wecom_aibot: - secret: "your-wecom-aibot-secret" - token: "your-wecom-aibot-token" - encoding_aes_key: "your-wecom-aibot-encoding-aes-key" - pico: - token: "your-pico-token" - -# Channel Settings (nested format for channels that use settings block) -channel_list: - mqtt: - settings: - username: "your-mqtt-username" - password: "your-mqtt-password" - -# Web Tool API Keys -web: - brave: - api_keys: - - "BSAyour-brave-api-key-1" - - "BSAyour-brave-api-key-2" # Optional: Multiple keys for failover - tavily: - api_keys: - - "tvly-your-tavily-api-key" # Single key in array format - perplexity: - api_keys: - - "pplx-your-perplexity-api-key" # Single key in array format - glm_search: - api_key: "your-glm-search-api-key" # GLMSearch uses single key format (not array) - baidu_search: - api_key: "your-baidu-search-api-key" - -# Skills Registry Tokens -skills: - github: - token: "your-github-token" - clawhub: - auth_token: "your-clawhub-auth-token" -``` - -## Usage - -### Step 1: Create .security.yml - -Create or copy the security file: -```bash -cp security.example.yml ~/.picoclaw/.security.yml -``` - -### Step 2: Fill in your actual values - -Edit `~/.picoclaw/.security.yml` and replace placeholder values with your actual API keys and tokens. - -### Step 3: Set proper permissions - -```bash -chmod 600 ~/.picoclaw/.security.yml -``` - -### Step 4: Simplify config.json (Recommended) - -You can now remove sensitive fields from `config.json` since they're loaded from `.security.yml`: - -**Before:** ```json { + "version": 3, + "agents": { + "defaults": {"model_name": "main"} + }, "model_list": [ { - "model_name": "gpt-5.4", - "model": "openai/gpt-5.4", + "model_name": "main", + "provider": "openai", + "model": "your-model-id", "api_base": "https://api.openai.com/v1", - "api_keys": ["sk-your-actual-api-key-here"] + "enabled": true } ], "channel_list": { "telegram": { "enabled": true, "type": "telegram", - "token": "1234567890:ABCdefGHIjklMNOpqrsTUVwxyz" + "allow_from": ["YOUR_USER_ID"], + "settings": {} } } } ``` -**After:** -```json -{ - "model_list": [ - { - "model_name": "gpt-5.4", - "model": "openai/gpt-5.4", - "api_base": "https://api.openai.com/v1" - // api_key is now loaded from .security.yml - } - ], - "channel_list": { - "telegram": { - "enabled": true, - "type": "telegram" - // token is now loaded from .security.yml - } - } -} -``` +`enabled`, `type`, `allow_from`, and other common channel fields belong on the channel entry. Token, App ID, proxy and other channel-specific fields belong under `settings`. App IDs and other non-secret settings stay in `config.json`; supported secret fields can be stored in the companion file. -### Step 5: Verify +## Companion security file -Restart PicoClaw and verify it loads correctly: -```bash -picoclaw --version -``` - -## Field Mapping Rules - -### Models - -**In .security.yml:** ```yaml model_list: - : + main: api_keys: - - "key-1" - - "key-2" -``` - -**Mapping:** -- Field `api_keys` (array) maps to the model's API keys -- The `` must match the `model_name` field in `config.json` -- Supports indexed names (e.g., "gpt-5.4:0") - the system will also try the base name ("gpt-5.4") - -### Channels - -Each channel maps its fields directly: - -**In .security.yml:** -```yaml -channels: - telegram: - token: "value" - feishu: - app_secret: "value" - encrypt_key: "value" - verification_token: "value" -``` - -**Mapping:** -- `channels.telegram.token` → `config.channels.telegram.token` -- `channels.feishu.app_secret` → `config.channels.feishu.app_secret` -- etc. - -Channels that use a `settings` block (e.g. MQTT) use the `channel_list` key instead: - -```yaml + - "YOUR_MODEL_API_KEY" channel_list: + telegram: + settings: + token: "YOUR_TELEGRAM_BOT_TOKEN" + feishu: + settings: + app_secret: "YOUR_FEISHU_APP_SECRET" + wecom: + settings: + secret: "YOUR_WECOM_SECRET" mqtt: settings: - username: "value" - password: "value" -``` - -- `channel_list.mqtt.settings.username` → `config.channel_list.mqtt.settings.username` -- `channel_list.mqtt.settings.password` → `config.channel_list.mqtt.settings.password` - -### Web Tools - -**Brave, Tavily, Perplexity, Kagi:** -```yaml + username: "YOUR_MQTT_USERNAME" + password: "YOUR_MQTT_PASSWORD" web: brave: api_keys: - - "key-1" - - "key-2" - kagi: - api_keys: - - "your-kagi-api-key" -``` -- Use `api_keys` (plural) array format - -**GLMSearch:** -```yaml -web: - glm_search: - api_key: "single-key-here" -``` -- Use `api_key` (singular) single string format - -**BaiduSearch:** -```yaml -web: - baidu_search: - api_key: "your-key" -``` -- Use `api_key` (singular) single string format - -### Skills - -**In .security.yml:** -```yaml -skills: - github: - token: "value" - clawhub: - auth_token: "value" + - "YOUR_BRAVE_API_KEY" ``` -## API Key Formats +Keep only entries for models, channels, and tools you actually configure. Model credentials use a **mapping** keyed by the local `model_name`, not the JSON model list. Saved files can use indexed names such as `main:0`; loading also supports the base name `main`. Model keys use `api_keys` arrays, even for one key. This is direct field mapping, without `ref:` references. -### Models - Single key +All current channel credentials use the nested `channel_list..settings` structure. Legacy `channels` is accepted during migration; it should not be used in new examples. The channel name must match the corresponding main-config entry. Settings for unknown or removed channels must be removed from both files; see the [upgrade notes](../../README.md#从旧版或上游配置升级). -Use array format with one element: -```yaml -model_list: - gpt-5.4: - api_keys: - - "sk-your-key" -``` +Chat protocols are `openai` and `anthropic`. Compatible services require an explicit supported protocol, endpoint, and model ID. Search credentials under `web` are separate from chat model providers. See the [provider guide](../guides/providers.md) and [tool configuration](../reference/tools_configuration.md). -### Models - Multiple keys (Load Balancing & Failover) +## Authentication and encryption -Use array format with multiple elements: -```yaml -model_list: - gpt-5.4: - api_keys: - - "sk-your-key-1" - - "sk-your-key-2" - - "sk-your-key-3" -``` +OpenAI OAuth and Anthropic setup-token credentials use `auth.json` under `PICOCLAW_HOME`. Manage them with `picoclaw auth login`, `auth status`, and `auth logout`; keep that file private too. -**Benefits:** -- **Load balancing**: Requests are distributed across multiple keys -- **Failover**: Automatic switching to another key if one fails -- **Rate limit management**: Distribute usage across multiple keys -- **High availability**: Reduce downtime during API provider issues +For optional encrypted credential storage, follow [Credential Encryption](credential_encryption.md). Do not copy encryption settings or encrypted values between installations without the required key material. -### Web Tools (Brave/Tavily/Perplexity/Kagi) - Single key +## Checking changes -```yaml -web: - brave: - api_keys: - - "BSA-your-key" - kagi: - api_keys: - - "your-kagi-api-key" -``` +`picoclaw status` shows the selected config path and model credential state, but does not test API connectivity or Gateway health. Check the service logs after restarting and use `/health` and `/ready` on the Gateway HTTP address. -### Web Tools (Brave/Tavily/Perplexity/Kagi) - Multiple keys - -```yaml -web: - brave: - api_keys: - - "BSA-key-1" - - "BSA-key-2" - kagi: - api_keys: - - "kagi-key-1" - - "kagi-key-2" -``` - -### Web Tool (GLMSearch/BaiduSearch) - Single key only - -```yaml -web: - glm_search: - api_key: "your-glm-key" # Single string (NOT array) - baidu_search: - api_key: "your-baidu-key" # Single string (NOT array) -``` - -## Model Name Matching - -The system supports intelligent model name matching in `.security.yml`: - -### Example 1: Exact Match - -**config.json:** -```json -{ - "model_name": "gpt-5.4:0" -} -``` - -**.security.yml (exact match with index):** -```yaml -model_list: - gpt-5.4:0: - api_keys: ["key-1"] -``` - -### Example 2: Base Name Match - -**config.json:** -```json -{ - "model_name": "gpt-5.4:0" -} -``` - -**.security.yml (base name without index):** -```yaml -model_list: - gpt-5.4: - api_keys: ["key-1", "key-2"] -``` - -Both methods work. The base name match allows you to use simpler keys in `.security.yml` even when your config uses indexed model names for load balancing. - -## Backward Compatibility - -The system maintains full backward compatibility: - -1. **Direct values**: You can still use direct values in `config.json` (not recommended for production) -2. **Mixed usage**: You can have some fields in `.security.yml` and others in `config.json` -3. **Optional security file**: If `.security.yml` doesn't exist, the system will only use values from `config.json` -4. **Override behavior**: If a field exists in both files, `.security.yml` value takes precedence - -## Environment Variables - -You can override any security value using environment variables: - -**For models:** -```bash -export PICOCLAW_CHANNELS_TELEGRAM_TOKEN="token-from-env" -``` - -**For channels:** -```bash -export PICOCLAW_CHANNELS_TELEGRAM_TOKEN="token-from-env" -export PICOCLAW_CHANNELS_FEISHU_APP_SECRET="secret-from-env" -``` - -**For web tools:** -```bash -export PICOCLAW_TOOLS_WEB_BRAVE_API_KEY="key-from-env" -export PICOCLAW_TOOLS_WEB_BAIDU_API_KEY="baidu-key-from-env" -``` - -Environment variables have the highest priority and will override both `config.json` and `.security.yml` values. - -The pattern is: `PICOCLAW_
__` with underscores separating path segments and converted to uppercase. - -## Security Best Practices - -1. **Never commit `.security.yml`** to version control -2. **Add to .gitignore**: Ensure `.security.yml` is in your `.gitignore` file -3. **Set file permissions**: `chmod 600 ~/.picoclaw/.security.yml` -4. **Use different keys** for different environments (dev, staging, production) -5. **Rotate keys regularly** and update `.security.yml` -6. **Backup securely**: Encrypt backups containing `.security.yml`. Note that config migrations automatically create date-stamped backups (e.g., `config.json.20260330.bak` and `.security.yml.20260330.bak`) -7. **Review access**: Ensure only authorized users have read access to the file - -## API - -### loadSecurityConfig - -```go -func loadSecurityConfig(securityPath string) (*SecurityConfig, error) -``` - -Loads the security configuration from `.security.yml`. Returns an empty `SecurityConfig` if the file doesn't exist. - -### saveSecurityConfig - -```go -func saveSecurityConfig(securityPath string, sec *SecurityConfig) error -``` - -Saves the security configuration to `.security.yml` with `0o600` permissions. - -### applySecurityConfig - -```go -func applySecurityConfig(cfg *Config, sec *SecurityConfig) error -``` - -Applies security configuration to the main config by copying values from `.security.yml` to the corresponding fields in the config. - -### securityPath - -```go -func securityPath(configPath string) string -``` - -Returns the path to `.security.yml` relative to the config file. - -## Example: Complete Configuration - -### config.json - -```json -{ - "version": 3, - "agents": { - "defaults": { - "workspace": "~/picoclaw-workspace", - "model_name": "gpt-5.4" - } - }, - "model_list": [ - { - "model_name": "gpt-5.4", - "model": "openai/gpt-5.4", - "api_base": "https://api.openai.com/v1" - }, - { - "model_name": "claude-sonnet-4.6", - "model": "anthropic/claude-sonnet-4.6", - "api_base": "https://api.anthropic.com/v1" - } - ], - "channel_list": { - "telegram": { - "enabled": true, - "type": "telegram" - } - }, - "tools": { - "web": { - "brave": { - "enabled": true - } - } - } -} -``` - -### .security.yml - -```yaml -model_list: - gpt-5.4: - api_keys: - - "sk-proj-actual-openai-key-1" - - "sk-proj-actual-openai-key-2" - claude-sonnet-4.6: - api_keys: - - "sk-ant-actual-anthropic-key" - -channels: - telegram: - token: "1234567890:ABCdefGHIjklMNOpqrsTUVwxyz" - -web: - brave: - api_keys: - - "BSAactualbravekey-1" - - "BSAactualbravekey-2" - tavily: - api_keys: - - "tvly-your-tavily-key" - glm_search: - api_key: "your-glm-key" - baidu_search: - api_key: "your-baidu-key" -``` - -## Testing - -Run the security configuration tests: - -```bash -go test ./pkg/config -run TestSecurityConfig -``` - -## Troubleshooting - -### Error: "failed to load security config" - -- Verify `.security.yml` exists in the same directory as `config.json` -- Check the YAML syntax is valid (use a YAML validator) -- Ensure file permissions allow reading - -### Error: "model security entry not found" - -- Ensure the model name in `config.json` matches exactly in `.security.yml` -- Check that the `model_list` section exists in `.security.yml` -- For models with indexed names (e.g., "gpt-5.4:0"), ensure the exact name is used or check the base name without index -- Verify the YAML structure is correct (proper indentation) - -### Multiple API Keys Not Working - -- Ensure you're using `api_keys` (plural) in `.security.yml` for models and web tools (except GLMSearch/BaiduSearch) -- Check that the array format is correct in YAML (proper indentation with dashes) -- Remember: Models, Brave, Tavily, Perplexity, Kagi MUST use `api_keys` (array format) -- GLMSearch and BaiduSearch MUST use `api_key` (single string format) - -### Load Balancing/Failover Issues - -- Verify all API keys in the `api_keys` array are valid -- Check that all keys have the same rate limits and permissions -- Monitor logs to see which keys are being used and failing -- Ensure the `api_keys` array is properly formatted in YAML - -### Keys Not Being Applied - -- Check that `.security.yml` is in the same directory as `config.json` -- Verify the file permissions allow reading (`chmod 600 ~/.picoclaw/.security.yml`) -- Ensure the YAML structure matches the expected format -- Check for typos in field names (case-sensitive) -- Verify the model/channel names match exactly (case-sensitive) - -## Migration Guide - -### Step 1: Backup your config - -The system automatically creates a date-stamped backup before saving a migrated config (e.g., `config.json.20260330.bak` and `.security.yml.20260330.bak`). If you prefer a manual backup: - -```bash -cp ~/.picoclaw/config.json ~/.picoclaw/config.json.backup -``` - -### Step 2: Create .security.yml - -```bash -cp security.example.yml ~/.picoclaw/.security.yml -``` - -### Step 3: Fill in your API keys - -Edit `~/.picoclaw/.security.yml` and replace placeholder values with your actual keys. - -### Step 4: Remove sensitive fields from config.json - -Remove or comment out sensitive fields from `config.json`: -- `api_key` fields from `model_list` entries -- `token` fields from `channels` -- `api_key` fields from `tools.web` -- `token`/`auth_token` fields from `tools.skills` - -### Step 5: Set proper permissions - -```bash -chmod 600 ~/.picoclaw/.security.yml -``` - -### Step 6: Test - -```bash -picoclaw --version -``` - -### Step 7: Verify functionality - -Test your models and channels to ensure everything works correctly. - -### Step 8: Clean up (optional) - -If everything works, you can delete the backups: -```bash -rm ~/.picoclaw/config.json.backup -# Also remove auto-generated date-stamped backups if desired: -rm ~/.picoclaw/config.json.20*.bak ~/.picoclaw/.security.yml.20*.bak -``` - -## Advanced: Encrypted API Keys - -PicoClaw supports encrypting API keys in the security file for additional protection. - -### Setup - -1. Set a passphrase via environment variable: -```bash -export PICOCLAW_CREDENTIAL_PASSPHRASE="your-secure-passphrase" -``` - -2. When saving config, API keys will be encrypted automatically: -```go -SaveConfig(path, config) -``` - -### Encrypted Format - -Encrypted keys are stored as: -```yaml -model_list: - gpt-5.4: - api_keys: - - "enc://encrypted-base64-string" -``` - -The system automatically decrypts keys at runtime when loading the configuration. - -### Benefits - -- Additional layer of security -- Keys are encrypted at rest -- Passphrase can be managed separately from the config file - -### Important Notes - -- Always backup your passphrase securely -- If you lose the passphrase, you'll lose access to encrypted keys -- Use a strong, unique passphrase -- Never commit the passphrase to version control +If a credential change in JSON appears ineffective, inspect the companion `.security.yml` for an overriding value. Avoid pasting either file into issue reports; use redacted examples. diff --git a/pkg/audio/tts/README.md b/pkg/audio/tts/README.md index c3fe2d80..5f65477c 100644 --- a/pkg/audio/tts/README.md +++ b/pkg/audio/tts/README.md @@ -105,7 +105,7 @@ voice name and works best with `response_format: "mp3"`. "model_list": [ { "model_name": "mai-voice-2", - "provider": "openrouter", + "provider": "openai", "model": "microsoft/mai-voice-2", "api_base": "https://openrouter.ai/api/v1", "extra_body": { diff --git a/workspace/skills/picoclaw-agent/SKILL.md b/workspace/skills/picoclaw-agent/SKILL.md index ab38a1c7..9a043c43 100644 --- a/workspace/skills/picoclaw-agent/SKILL.md +++ b/workspace/skills/picoclaw-agent/SKILL.md @@ -446,7 +446,7 @@ Example with OpenRouter MAI Voice 2: "model_list": [ { "model_name": "mai-voice-2", - "provider": "openrouter", + "provider": "openai", "model": "microsoft/mai-voice-2", "api_base": "https://openrouter.ai/api/v1", "extra_body": { @@ -748,24 +748,9 @@ Check that: - the target `model_list` entry is enabled - the `provider` and `model` fields use PicoClaw's model-centric rules -### OpenRouter `free is not a valid model ID` +### Compatible endpoint rejects the model ID -Prefer explicit provider config: - -```json -{ - "provider": "openrouter", - "model": "free" -} -``` - -Not: - -```json -{ - "model": "free" -} -``` +Select `provider: "openai"` or `"anthropic"` explicitly and provide the service's `api_base` and complete remote `model` ID. Vendor-specific provider presets have been removed. For OpenRouter, use `provider: "openai"`, `api_base: "https://openrouter.ai/api/v1"`, and an ID accepted by that service; vendor namespaces in the model ID are preserved. ### Skill not appearing