diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 995ab17..94a6589 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -46,7 +46,9 @@ jobs: rustup toolchain install "$version" --profile minimal --component clippy rustup override set "$version" - name: Check translations - run: python3 scripts/check-i18n.py + run: | + python3 scripts/check-i18n.py + python3 scripts/test_i18n_checks.py - name: Run tests run: | set -o pipefail diff --git a/README.md b/README.md index 9c9fa27..94f91a5 100644 --- a/README.md +++ b/README.md @@ -1,224 +1,72 @@ -# lmm +# LMM CLI -**LMM API · 连接模型与工具,让智能自由流动** +[简体中文](README.zh-CN.md) · [Usage guide](docs/usage.md) · [Translation guide](docs/i18n.md) -LMM = **Language Model Mesh**,中文「语言模型网络」。Mesh 表达互联与协作,呼应多模型路由、渠道共享和微服务协作的方向。 +LMM (Language Model Mesh) is an independent Rust CLI for provider presets, local software inspection, account catalog and balance reads, and explicitly scoped application adapters. The Cargo package is `lmm-cli`; the executable is `lmm`. Its build and dependency lockfile are independent of the parent service. -这是 [TokenNotIncluded/lmm](https://github.com/TokenNotIncluded/lmm) 独立维护的 Rust CLI。crates.io 包名为 `lmm-cli`,可执行文件名为 `lmm`;父仓库通过子模块锁定版本,CLI 的构建和依赖独立管理。 +This source tree is a development preview. It includes a Linux adapter for an explicitly installed Pi 1.2.0 SDK and a managed CC Switch distribution adapter. A successful plan, database update or process launch does not establish that an application is active on an LMM route or that a model call works. The [usage guide](docs/usage.md), [managed distribution contract](docs/managed-distributions.md) and [native integration evidence](docs/native-credential-evidence.md) describe these boundaries. -**当前是开发预览,已实现服务商预设、桌面 OAuth、模型目录与余额读取、限定版本的 Pi Provider 适配器,以及 CC Switch 的 Linux 受管发行包生命周期。** -Pi 使用显式指定的官方 Pi 1.2.0 SDK 安装和恢复固定 Provider,授权与激活仍在 Pi 内完成。 -CC Switch 支持固定官方 AppImage 的安装、更新、按回执恢复、卸载、显式启动和 schema 24 的只读检查;独立应用授权、仅添加配置、目录同步和撤销分别使用其管理合同。 -原生应用激活与真实调用需要单独验收,其他软件的写入流程继续明确阻塞。详细边界见 [受管发行包说明](docs/managed-distributions.md) 和 [原生凭据接入说明](docs/native-credential-evidence.md)。 +## Build this source revision -完整产品要求见 [原始需求](docs/requirements.zh-CN.md)。完整需求保留为目标,不因当前实现范围而缩减。 -与 Magpie 的功能对照及下一步任务见 [Magpie 对照](docs/magpie-parity.md)。实现使用 Rust,不包装或启动 Magpie,也不依赖 Go 运行时。 - -## 从 crates.io 安装 - -```bash -cargo install lmm-cli --version 0.1.0 --locked -lmm --help -``` - -服务商预设查询是本仓库的新实现,本轮尚未发布;体验这项功能请使用下文的源码构建命令。 - -这是开发预览版,功能边界见上文。Cargo 安装需要 Rust 1.99.1 或更新版本及本机编译工具; -面向无需开发环境用户的二进制安装器尚未提供。 -Linux OAuth 功能另需运行中的 Secret Service;Windows/macOS 使用系统凭据库。 - -## 当前可用 - -- `lmm presets [关键词] [--json]`:查询 56 项内置服务商预设,离线运行,不读取密钥、不访问服务商。 -- `lmm catalog [关键词]`:搜索明确项目身份的软件目录,分别说明安装、接入、维护能力。 -- `lmm status [软件]`:当前环境与 PATH 线索;指定 CC Switch 时校验受管发行包,显式 `--instance` 时读取 schema 24 的非凭据元数据;Pi 支持下文限定的显式设置检查。 -- `lmm install|update|uninstall cc-switch --dry-run --json`:可执行的固定发行包计划;确认时带原 `--yes --plan-id`。 -- `lmm restore cc-switch --change --dry-run --json`:按回执恢复受管版本,保留后续修改和应用数据。 -- `lmm run cc-switch`:启动已校验的受管程序;启动成功不代表应用健康或模型调用通过。 -- `lmm doctor [软件] --report`:只读诊断摘要,移除实例和文件路径,仅输出各适配器允许的状态字段。 -- `lmm setup [软件] --dry-run`:生成带阻塞原因的预览;无目标且有终端时可选择软件。 -- `--json`:结构化结果;自动禁用交互。`--non-interactive` 同样禁止等待输入。 -- `lmm login`:桌面浏览器 PKCE 登录;凭据保存于系统凭据库。 -- `lmm models [--json]`:获取当前授权模型、服务器上下文/能力元数据、缓存价格及分组/信任倍率;未知保留 null,价格已含倍率,不调用模型、不切换配置。 -- `lmm balance [--json]`:读取余额 V2,保留服务端整数积分及美元单位;未知单位或失败不会显示为零。 -- `lmm logout`:撤销当前 issuer 下的 CLI 令牌族,成功后删除本地凭据;不影响 Pi/DSH 等其他应用。 - -## Pi Provider 适配器(Linux / Pi 1.2.0) - -此适配器连接**已经安装的官方 Pi 1.2.0 npm 包**,仅管理明确项目内的 LMM Provider。 -它不安装或卸载 Pi 本体,不复制 CLI 登录凭据。Pi 使用自己的 `/login` 授权、`/model` 选择和原生模型调用。 -固定 Provider 来源为 `git:github.com/TokenNotIncluded/pi-lmm-provider@f0c54764eb3d73e50790346f0dbab834587fe27b`。 - -```bash -lmm setup pi --add-only --instance /absolute/project --node /absolute/node \ - --pi-package /absolute/node_modules/@earendil-works/pi-coding-agent \ - --agent-dir /absolute/pi-agent --dry-run --json -# 核对预览后,用相同参数移除 --dry-run,并添加 --yes -``` - -`setup` / `install` 只添加固定 Provider;结果为 `provider_added_authorization_pending`,不代表模型已可用。 -`setup`、`sync`、`disconnect` 的后续授权/目录刷新/撤销仍需目标 Pi 完成,因此实际执行返回 3 并报告具体阶段。 -已有其他 LMM 安装来源时拒绝创建副本;默认服务商和模型保留当前选择。`--activate` 必须交由目标 Pi 的交互授权和模型选择完成。 -`update` 只接受仍存在的自有固定来源,本版本不自动追逐最新版。 -`sync` 验证 Provider 存在,明确返回 `catalog_refresh_pending`;在 Pi 中运行 `/lmm-prices` 才会刷新目录。 -`run pi` 使用相同的四个显式路径启动 Pi,只允许交互终端。 - -`restore` / `disconnect` 加相同目标路径和 `--yes`,仅从原生设置事务中移除本次添加的精确来源。 -这不会撤销 Pi OAuth 授权;需要撤销时在 Pi 中运行 `/lmm-revoke`。 -用户后来新增的插件、默认模型及其他字段都会保留;若用户改写了此来源对象则拒绝恢复。 -下载代码可能被其他实例引用,因此保留。`uninstall` 仍受阻,不删除 Pi 本体或未知资源。 - -无秘密日志在所选项目 `.pi/lmm-owned.json`,锁在 `.pi/lmm-adapter.lock`。 -修改前持久化 pending,读回成功后才完成日志;中断或不确定结果保持待检查状态,不自动声称完成。 -配置增删在 Pi 自己的 `FileSettingsStorage.withLock` 中读取最新内容执行,避免用旧插件数组覆盖并发编辑。 -普通 CLI 的 OAuth 凭据继续只保存在系统凭据库;适配器从不读取 Pi 的凭据文件。 - -## 服务商预设 - -```bash -lmm presets -lmm presets deepseek --json +```sh +mise install +mise exec -- cargo install --path . --locked +lmm --lang en --help ``` -预设来自 [Magpie 的固定版本](https://github.com/yetone/magpie/blob/d5cae267a727e23f4b6e2b28aa107ecdeac5aa9c/internal/provider/presets.go),是服务商地址及相关元数据的静态目录。它不是已经配置的服务商列表,不代表当前账号有权限或额度,也不代表已完成服务商接入、模型发现或调用验证。端点和模型信息可能随服务商变化,不能作为实时承诺。 +Use this repository's `mise.toml` for the pinned development toolchain (Rust 1.100.0); the package declares Rust 1.99.1 as its minimum. Building needs native compilation tools. Linux OAuth also needs a running Secret Service; Windows and macOS use their system credential stores. Published packages may differ from this source revision. A standalone installer for users without a development environment is not provided here. -`presets` 查询服务商预设,`catalog` 查询软件目录,`models` 读取 LMM 账号的授权模型;三者分别表示不同内容。 +## Choose a language -## 登录与模型目录 - -```bash -lmm login -lmm models --json -lmm balance --json -lmm logout -# 自托管必须明确指定可信的 HTTPS origin,认证和只读命令使用同一 issuer -lmm login --issuer https://lmm.example.com --no-browser +```sh +lmm --lang en catalog astrbot +lmm catalog astrbot --lang zh-CN +LMM_LANG=zh-CN lmm --help ``` -服务端需要注册 `lmm` 客户端并启用已有 OAuth 服务。使用前应确认目标服务支持这些接口,并验证实际账号的浏览器登录流程。 -CLI 只申请 `catalog:read balance:read` 和同意页显示的分组快照;没有 `models:invoke`、 -MCP 或账号管理权限。CLI 登录成功不代表 AstrBot 或 CC Switch 已授权。 - -浏览器回调只监听 `127.0.0.1` 随机端口,等待默认 180 秒,可用 `--timeout 10..600` 调整。 -`--no-browser` 仅关闭自动打开浏览器,**不是设备码登录**:浏览器仍须能访问本机回环端口。 -无图形服务器跨设备授权尚未实现;非交互 `login` 直接返回,不暗中等待授权。 -切换账号先 `logout` 再 `login`;已有 CLI 登录不会被新登录静默覆盖。 - -Windows 使用 Credential Manager,macOS 使用 Keychain,Linux 使用 Secret Service。 -凭据库可能显示系统解锁提示;不可用时明确报错,不使用明文文件后备。 -因此认证命令暂不支持 `--non-interactive`,会在访问凭据库之前退出;`models --json`、`balance --json` 只禁用 CLI 文本交互,系统仍可能要求解锁。 -Linux 通过 zbus 访问 Secret Service,不再静态链接 libdbus; -运行时仍需要可用的 Secret Service;不能将开发机单测当作三个系统的实际凭据库验收。 +The global `--lang` flag takes precedence over the first nonempty value in `LMM_LANG`, `LC_ALL`, `LC_MESSAGES` and `LANG`. Unknown environment locales fall back to English; an unsupported explicit flag is rejected. Help and terminal prose are translated. JSON, including catalog purposes, notes and recognized error messages, remains canonical English in both languages. Command names, identifiers, protocol values and numeric data do not change. See [Translations](docs/i18n.md). -认证操作使用当前用户状态目录中的无密钥 `oauth.lock`,防止并发登录/刷新/退出。 -Linux 为 `$XDG_STATE_HOME/lmm` 或 `~/.local/state/lmm`,macOS 为 -`~/Library/Application Support/lmm`,Windows 为 `%LOCALAPPDATA%/lmm`。 -Unix 目录/锁文件新建权限分别为 0700/0600;已有不安全目录会被拒绝。 -刷新前将“不可重试”状态存入凭据库,响应丢失或保存失败后不会自动重放旧 refresh token。 -此时需要退出再登录;退出撤销失败保留本地记录供重试,不能报告已完成。 +## Available commands -模型目录只表示账号可见范围,不表示某个软件已经兼容。未知价格保留 null, -价格包含服务端返回的倍率,不重复计算;本命令不执行付费测试。 +| Task | Entry point | Result and boundary | +| --- | --- | --- | +| Provider presets | `lmm presets [query] --json` | Offline snapshot of 56 presets; no provider configuration or connectivity test | +| Software catalog | `lmm catalog [query]` | Project identities and separate installation/integration/maintenance capability fields | +| Local inspection | `lmm status [software] --json` | Path evidence, managed CC Switch state, or explicitly selected native settings | +| Shareable diagnosis | `lmm doctor [software] --report --json` | Redacts local paths; incomplete verification remains explicit | +| CLI account | `lmm login`, `models`, `balance`, `logout` | Browser PKCE and read-only account scopes; no application model-call grant | +| Managed CC Switch | `lmm install cc-switch --dry-run --json` | Fixed official release plan; applying it requires the exact `plan_id` | +| Native CC Switch configuration | `lmm setup cc-switch --help` | Separate application grant and add-only native database transactions; activation is separate | +| Pi Provider | `lmm setup pi --help` | Explicit Node, Pi 1.2.0 SDK, project and agent paths; authorization stays in Pi | -## 本地软件检查 +`--json` disables CLI prompts. `--non-interactive` does not wait for missing input. Credential-store operations that may require unlocking reject unattended use before accessing credentials. `--yes` cannot replace a missing adapter, a required plan ID, application consent or a server-enforced spending limit. -显式实例接受 AstrBot 部署根目录、CC Switch 配置根目录,以及下述 Pi 项目根目录: +## Start with read-only commands -```bash -lmm status astrbot --instance /absolute/path/to/AstrBot -lmm status cc-switch --instance /absolute/path/to/.cc-switch +```sh +lmm presets deepseek --json +lmm catalog +lmm status astrbot --instance /absolute/path/to/AstrBot --json lmm doctor astrbot --instance /absolute/path/to/AstrBot --report --json -lmm setup astrbot --dry-run --json +lmm install cc-switch --dry-run --json ``` -Windows 使用当前 Windows 环境的绝对路径。AstrBot 只检查所选根目录的 -`data/cmd_config.json` 路径;CC Switch 在显式 `--instance` 时打开只读 SQLite 事务,仅查询 schema 和非凭据的供应商元数据。 -不自动搜索项目、其他用户、Docker 实例、局域网或远程机器。 -PATH 文件可能是包装脚本或来自其他环境,因此只标为线索;不执行 `--version`。 -符号链接和不可访问项显示 `unknown`,文件缺失只描述被检查的那个位置。 - -CC Switch 的受管安装与 schema 24 配置管理者依据本地日志和原生数据库确认;授权、实际模型及真实调用路径不凭这些事实推断。 - -Pi 的只读设置检查仅支持 Linux、声明为官方 Pi 1.2.0 的 npm 包格式,必须显式指定三个目录: +Explicit paths refer to the operating system running the CLI. The CLI does not scan other users, remote systems or container instances. The [usage guide](docs/usage.md) explains Pi settings inspection, CC Switch receipts, OAuth, recovery and exit codes before any write is requested. -```bash -lmm status pi --instance /absolute/project \ - --pi-package /absolute/node_modules/@earendil-works/pi-coding-agent \ - --agent-dir /absolute/pi-agent --json -lmm doctor pi --instance /absolute/project \ - --pi-package /absolute/node_modules/@earendil-works/pi-coding-agent \ - --agent-dir /absolute/pi-agent --report --json -``` +## Develop and verify -这条路径只读包清单和所选 agent 的 `settings.json`、项目的 `.pi/settings.json`, -不需要 Node,不启动目标或 SDK,不读取 `auth.json`,也不创建状态目录或配置锁。 -Linux 检查使用内核的禁止跟随符号链接标志逐级打开目录及设置文件。 -`pi_settings.provider_reference` 区分固定来源、其他已知 LMM 来源和多个引用; -识别 Pi 1.2.0 常见的 npm 和 Git 来源写法,不解析本地插件路径、npm 别名或未知写法。 -仅有无法识别的来源时结果为 `unknown`;已知 LMM 来源与无法识别的来源并存时为 -`known_with_unresolved_sources`,并仍报告已知引用。即使为 `no_known_source`, -也不能据此排除其他扩展加载了 LMM。包引用不代表代码已安装或已加载。 -`lmm_added=referenced_in_settings` 与 `lmm_enabled=selected_in_settings` 分别表示 -引用存在和默认服务商字段为 LMM;二者不等同于运行时添加或启用。 -项目的默认服务商、模型字段分别覆盖全局字段,`provider_scope` / `model_scope` -指出各自来源。模型只显示已设置/未设置,其他服务商只显示 `other`,不输出原始配置值。 -多个已知来源会单独标出,不自动去重或修复。 - -未知版本、无法访问、符号链接(含目录祖先)、超过 1 MiB 的文件及已知字段结构不符, -保留 `unknown` 并使 `status` 返回 3;不存在的设置文件按未设置处理,不创建它们。 -设置是分别读取的快照,不是跨文件原子快照;硬链接、绑定挂载以及文件打开后的并发修改 -不在符号链接防护范围内。项目信任、启动参数、会话选择及模型缓存 -可能改变实际行为,本检查不确认它们,也不验证 SDK 内容真实性、安装管理者或配置管理归属。 -仅提供项目路径、未提供 Pi 格式检查参数时,仍保留原有路径检查行为。 - -软件目录中的完整兼容版本/平台/场景列表仍为空;上述局部配置检查不是完整接入兼容声明。 -授权、连通性、实际服务商/模型及真实调用路径仍未验证。 -`status` 的退出码 0 只表示完成对应只读查询,不能用于判断“软件可使用”。 -`doctor` 即使配置检查通过也返回 3,`--fix` 仍阻止写入。 -`status`、`doctor`、`setup --dry-run` 没有网络调用或付费验证。 - -`--all` 不把目录视为安装列表。`update --all` 仅包含已由 LMM 管理的 CC Switch;没有受管安装时返回阻塞。应用接入的 `setup --all` 仍无可执行目标。 -`--yes` 不能消除能力缺失,不能代表支付、重新授权或切换服务商的同意。 -单独 `install` 不要求登录。CC Switch 的写操作需确认精确计划,不能用 `--yes` 跳过计划 ID。 - -## 开发 - -从这个独立仓库的根目录执行,工具版本由 `mise.toml` 固定: - -```bash -mise install -mise exec -- cargo run --locked -- presets deepseek --json -mise exec -- cargo run --locked -- catalog +```sh +python3 scripts/check-i18n.py +python3 scripts/test_i18n_checks.py +mise exec -- cargo fmt --all -- --check mise exec -- cargo test --locked mise exec -- cargo clippy --locked --all-targets --all-features -- -D warnings -mise exec -- cargo fmt --all --check -mise exec -- cargo build --locked --release ``` -不需要先构建或启动父仓库中的核心、扩展或 Web 服务。独立 Cargo 工程与后端分开锁定依赖,避免将 CLI 发布绑定到后端构建。 -源码开发需要 Rust;面向普通用户的签名二进制、安装器和更新渠道尚待发布, -当前没有声称普通用户已经能“一键安装”。CI 构建产物仅作开发预览,不自动发布。 - -## 退出码与安全边界 - -| 退出码 | 含义 | -| --- | --- | -| 0 | 查询或可执行预览已输出,或受管操作已提交;请继续检查各层状态 | -| 2 | 参数不完整、目标未知、无法选择目标或输出失败 | -| 3 | 能力未实现、检查未完成或操作被阻止 | - -`restore_fields` 是内存中的三方字段恢复算法:仅在字段仍等于 LMM 写入值时撤销, -保留用户后续修改;任一冲突使整个目标的计算失败。它拒绝整对象、数组及数组索引恢复。 -该字段算法仍未连接应用配置写入;CC Switch 的 `restore` 默认恢复受管发行包版本,`--configuration` 按原生数据库回执恢复 LMM 配置。这些路径使用各自的持久日志、原生版本门禁和三方状态检查。 -同样,付费检查函数只是客户端规划规则,**不能代替服务端消费限制**。 - -指纹函数只用于有界配置快照的内容比较,不是原子写锁。未来接入必须使用目标软件原生 -事务/管理接口解决并发写入;“比较哈希后覆盖文件”不满足完整并发修改验收。 +Tests use isolated fixtures. The two Linux credential migration checks are opt-in and require an explicitly isolated Secret Service; ordinary tests do not certify live credential stores on every operating system. Local validation does not publish a crate, release or production deployment. -只读检查和 `--dry-run` 不建立状态目录;确认的受管安装建立自己的私有目录与无凭据日志。OAuth 操作使用独立锁与系统凭据库。 -LMM 不复制第三方凭据、不上传遥测、不进行付费调用。 -分享前建议使用 `doctor --report --json`;普通 `status` 会显示本地路径。 +## Scope and attribution -## 来源与许可证 +The [original requirements](docs/requirements.zh-CN.md) remain the product target. The [Magpie comparison](docs/magpie-parity.md) records implemented features and remaining work against a pinned upstream revision. LMM ports behavior to Rust and does not wrap or start Magpie or depend on a Go runtime. -项目按 [AGPL-3.0-only](LICENSE) 发布。服务商预设参考 Magpie 的 MIT 许可源码;来源及保留的许可说明见 [NOTICE](NOTICE)。参考预设数据不意味着具备 Magpie 的全部能力。 +LMM is licensed under [AGPL-3.0-only](LICENSE). The bundled provider snapshot derives from MIT-licensed Magpie material; see [NOTICE](NOTICE) and [third-party provenance](third_party/magpie/NOTICE.md). Static presets are not a claim of current provider access or runtime compatibility. diff --git a/README.zh-CN.md b/README.zh-CN.md new file mode 100644 index 0000000..3d46fe5 --- /dev/null +++ b/README.zh-CN.md @@ -0,0 +1,72 @@ +# LMM CLI + +[English](README.md) · [使用指南](docs/usage.zh-CN.md) · [翻译指南](docs/i18n.md) + +LMM(Language Model Mesh,语言模型网络)是独立的 Rust CLI,用于服务商预设查询、本地软件检查、账号模型目录与余额读取,以及范围明确的应用适配器。Cargo 包名为 `lmm-cli`,可执行文件为 `lmm`;构建和依赖锁文件独立于父项目服务。 + +当前源码是开发预览,包含显式安装的 Pi 1.2.0 SDK 的 Linux 适配器,以及 CC Switch 受管发行包适配器。计划、数据库写入或进程启动成功,均不能证明应用已通过 LMM 路由激活或模型调用可用。详细边界见[使用指南](docs/usage.zh-CN.md)、[受管发行包合同](docs/managed-distributions.md)和[原生接入证据](docs/native-credential-evidence.md)。 + +## 构建当前源码 + +```sh +mise install +mise exec -- cargo install --path . --locked +lmm --lang zh-CN --help +``` + +使用本仓库 `mise.toml` 固定的开发工具链(Rust 1.100.0);Cargo 清单声明的最低版本为 Rust 1.99.1。构建需要本机编译工具。Linux OAuth 另需运行中的 Secret Service,Windows 和 macOS 使用系统凭据库。已发布包可能不同于当前源码;这里尚未提供面向无开发环境用户的独立安装器。 + +## 选择语言 + +```sh +lmm --lang en catalog astrbot +lmm catalog astrbot --lang zh-CN +LMM_LANG=zh-CN lmm --help +``` + +全局 `--lang` 优先于 `LMM_LANG`、`LC_ALL`、`LC_MESSAGES`、`LANG` 中首个非空值。未知环境语言回退英文;不支持的显式参数会被拒绝。帮助和终端文字支持中英文;JSON 的目录用途、提示和已识别错误正文在两种语言下均保持固定英文。命令名、标识符、协议值和数字不变,详见[翻译指南](docs/i18n.md)。 + +## 当前命令 + +| 任务 | 入口 | 结果与边界 | +| --- | --- | --- | +| 服务商预设 | `lmm presets [query] --json` | 离线的 56 项预设快照;不配置服务商、不验证连通性 | +| 软件目录 | `lmm catalog [query]` | 项目身份,以及分别列出的安装、接入、维护能力 | +| 本地检查 | `lmm status [software] --json` | 路径线索、CC Switch 受管状态或显式选择的原生设置 | +| 分享诊断 | `lmm doctor [software] --report --json` | 移除本地路径,明确保留未完成的验证项 | +| CLI 账号 | `lmm login`、`models`、`balance`、`logout` | 浏览器 PKCE 和账号只读权限;不授予应用模型调用权限 | +| CC Switch 受管程序 | `lmm install cc-switch --dry-run --json` | 固定官方版本计划;执行时需要精确 `plan_id` | +| CC Switch 原生配置 | `lmm setup cc-switch --help` | 独立应用授权和仅添加的原生数据库事务;激活另行处理 | +| Pi Provider | `lmm setup pi --help` | 显式指定 Node、Pi 1.2.0 SDK、项目和 agent 路径;授权保留在 Pi 内 | + +`--json` 禁用 CLI 提示;`--non-interactive` 不等待缺失输入。可能需要系统解锁的凭据操作会在访问凭据前拒绝无人值守模式。`--yes` 不能替代缺失的适配器、必要的计划 ID、应用同意或服务端消费上限。 + +## 从只读命令开始 + +```sh +lmm presets deepseek --json +lmm catalog +lmm status astrbot --instance /absolute/path/to/AstrBot --json +lmm doctor astrbot --instance /absolute/path/to/AstrBot --report --json +lmm install cc-switch --dry-run --json +``` + +显式路径属于运行 CLI 的当前操作系统。CLI 不扫描其他用户、远程系统或容器实例。请求写入之前,先阅读[使用指南](docs/usage.zh-CN.md)中的 Pi 设置检查、CC Switch 回执、OAuth、恢复和退出码说明。 + +## 开发与验证 + +```sh +python3 scripts/check-i18n.py +python3 scripts/test_i18n_checks.py +mise exec -- cargo fmt --all -- --check +mise exec -- cargo test --locked +mise exec -- cargo clippy --locked --all-targets --all-features -- -D warnings +``` + +测试使用隔离 fixture。两项 Linux 凭据迁移检查需要显式启用并提供隔离的 Secret Service;普通测试不能代替各操作系统真实凭据库验收。本地验证不会发布 crate、正式版本或生产部署。 + +## 范围与来源 + +[原始需求](docs/requirements.zh-CN.md)继续作为产品目标;[Magpie 对照](docs/magpie-parity.md)基于固定上游版本记录已实现能力与剩余工作。LMM 将行为移植到 Rust,不包装或启动 Magpie,也不依赖 Go 运行时。 + +项目使用 [AGPL-3.0-only](LICENSE) 许可。内置服务商快照参考 MIT 许可的 Magpie 材料,见 [NOTICE](NOTICE) 和[第三方来源记录](third_party/magpie/NOTICE.md)。静态预设不代表当前账号有权限,也不代表运行时兼容。 diff --git a/docs/i18n.md b/docs/i18n.md new file mode 100644 index 0000000..33e9f83 --- /dev/null +++ b/docs/i18n.md @@ -0,0 +1,70 @@ +# Translations + +[English README](../README.md) · [中文 README](../README.zh-CN.md) + +## Runtime contract + +LMM translates terminal presentation while keeping machine-readable output independent of the selected language. Both catalogs are compiled into the binary using `include_str!`; language selection does not require a network request, a working-directory lookup or another runtime dependency. The implementation is in [src/i18n.rs](../src/i18n.rs), with subprocess coverage in [tests/i18n.rs](../tests/i18n.rs). + +| File | Purpose | +| --- | --- | +| `locales/en.json` | Complete English catalog and canonical machine prose | +| `locales/zh-CN.json` | Complete Simplified Chinese catalog | +| `src/i18n.rs` | Locale selection, typed messages and named placeholders | +| `scripts/check-i18n.py` | Catalog values, references and placeholder validation | +| `scripts/test_i18n_checks.py` | Validator regressions using temporary fixtures | + +## Select a language + +The global `--lang en` or `--lang zh-CN` flag works before or after a subcommand. Selection happens before Clap builds help. An unsupported explicit language is an argument error and does not run the requested command. + +Without the flag, the first nonempty value in `LMM_LANG`, `LC_ALL`, `LC_MESSAGES` and `LANG` selects the language. Unknown values, `C` and `POSIX` fall back to English. Supported Simplified Chinese aliases include `zh`, `zh_CN.UTF-8`, `zh-SG` and `zh-Hans`; Traditional Chinese does not yet have a catalog and falls back to English. A value after `--` is positional data and cannot select a language. + +The selected locale is immutable for the CLI process, including the OAuth callback thread. An uninitialized library defaults to English. Library callers can use `Locale::ZhCn.text(key)` or `msg(key).render_in(locale, values)` without mutating global state; tests use explicit locales and child-process environments. + +## Add or change a message + +Use the same semantic key in both catalogs and keep a complete sentence together. For example: + +```json +{ + "output.target": "{software}: installation {installation}" +} +``` + +```rust +msg("error.unknown_software") +msg("output.scope").render(&[("time", &checked_at.to_string())]) +text("arg.instance") +``` + +Named placeholders may move within a sentence, but their names and occurrence counts must match. Formatting specifiers, conversions, nested templates and literal braces are not supported. Substitution happens once: inserted values are never parsed as templates. Escape untrusted paths and server text with debug formatting, such as `format!("{value:?}")`, before inserting them into terminal output. + +`help.template` belongs to Clap rather than the message renderer. Preserve Clap's named fields. Command descriptions and help headings are translated; Clap's own argument validation details and built-in annotations remain in upstream English. + +## Keep JSON and adapter errors stable + +`Message` serializes its English text regardless of display locale. JSON keys, descriptions, purposes, notes, blockers, recognized error text, command names, IDs, protocol values, currencies, numbers and timestamps do not change when only `--lang` changes. Catalog and provider search can match both bundled languages without changing returned identifiers. Original vendor metadata is preserved rather than translated. + +Existing native adapter APIs return strings or typed errors that are also used in JSON previews. They use `english(key)` to retain a canonical value. At the terminal boundary, `message_from_english` recognizes only exact catalog values and recovers a typed message; `localize` translates that recognized value. Unknown external text stays literal. Do not perform broad string replacement or interpret an adapter's text as a template. + +Recognized CLI and OAuth errors include a stable `error_code`; unclassified adapter strings have no recognized code. Consumers should inspect structured outcomes and known codes instead of matching human prose. The hidden `credential` command is a raw-token pipe and rejects JSON or terminal token output in either language; it is not a general-purpose account display command. + +A missing localized entry falls back to English and then to its visible key. This avoids a runtime failure but does not make an incomplete catalog acceptable: repository validation requires matching nonempty catalogs and rejects missing or unused message references. + +## Verify a change + +Run these commands from the repository root: + +```sh +python3 scripts/check-i18n.py +python3 scripts/test_i18n_checks.py +mise exec -- cargo fmt --all -- --check +mise exec -- cargo test --locked +mise exec -- cargo clippy --locked --all-targets --all-features -- -D warnings +mise exec -- cargo package --list --locked +``` + +The Python checker rejects duplicate and malformed keys, empty or non-string values, disallowed control characters, CJK text in the English catalog or Rust sources, mismatched placeholders, and missing or unused references. It recognizes `msg`, `text`, `english` and the typed enum message mappings. Its fixture tests do not compile Rust; the Cargo tests verify locale precedence, help, errors, JSON equality, native adapter refusal paths and escaped untrusted paths. + +The source package must include both catalogs, both READMEs and the translation guide. To add another language, extend `Locale`, its aliases, its embedded catalog mapping and `Locale::ALL`, then add subprocess tests and update documentation in the same change. No command, adapter permission or credential-store behavior should change as a side effect of translation work. diff --git a/docs/managed-distributions.md b/docs/managed-distributions.md index 2297c12..86b88d3 100644 --- a/docs/managed-distributions.md +++ b/docs/managed-distributions.md @@ -68,6 +68,8 @@ lmm status cc-switch --instance /absolute/path/to/.cc-switch --json 显式实例检查使用只读 SQLite 事务,要求 schema 24 和已核验的 `providers` 主键与列。仅查询 ID、应用类型、名称及数据库选择标志;不读取 `settings_config`、`meta` 或凭据内容。`selected_in_database` 不能证明本机 Codex/Claude 配置已经激活,也不能证明经过本地代理。 -`setup`、`sync` 和 `disconnect` 的完整应用接入仍需要独立应用授权与原生配置激活合同。现有 CLI 登录只拥有 `catalog:read balance:read`,不得把该 token 写进 CC Switch 的供应商配置。不得只修改 `is_current` 就声称完成激活,因为上游激活还写本机应用配置。这些尚未具备的流程继续返回明确阻塞,不返回空成功。 +应用配置使用独立于发行包管理的授权与事务路径。当前 `setup --add-only` 和 `sync` 通过显式实例的原生 SQLite 事务添加或更新 LMM,保留原模型选择;`restore --configuration --change` 按回执恢复受管理字段并拒绝后续编辑冲突。代码入口见 [applications_cli.rs](../src/applications_cli.rs) 与 [bindings.rs](../src/cc_switch/bindings.rs)。现有 CLI 登录只拥有 `catalog:read balance:read`,不会把该 token 写进供应商配置;独立应用授权仍需服务端对应合同与用户同意。 + +完整激活和删除继续受原生应用状态限制。不能只修改 `is_current` 就声称完成激活,也不能只凭 SQLite 中未选中的标记删除可能被 live、代理或 Stack 引用的项目。这些操作需要 CC Switch 原生管理入口或独立审阅的上游集成,详见[原生接入证据](native-credential-evidence.md)。受管发行包成功、供应商记录存在和真实模型调用成功仍是不同结果。 隔离测试使用合成发行包字节、临时目录和真实 SQLite;不下载或执行官方 AppImage,不访问真实账号或支付渠道。真实 Linux 图形环境运行、官方文件端到端下载与模型调用仍需独立验收。 diff --git a/docs/usage.md b/docs/usage.md new file mode 100644 index 0000000..84cfa08 --- /dev/null +++ b/docs/usage.md @@ -0,0 +1,175 @@ +# Usage guide + +[English README](../README.md) · [简体中文](usage.zh-CN.md) + +This guide describes the current Rust source tree, its implemented commands and their limits. `lmm-cli` is the Cargo package and `lmm` is the executable. The CLI builds independently of the parent service. The full [product requirements](requirements.zh-CN.md) remain the target; the [Magpie comparison](magpie-parity.md) distinguishes implemented behavior from remaining work. + +## Build and language selection + +From the repository root: + +```sh +mise install +mise exec -- cargo install --path . --locked +lmm --lang en --help +``` + +The development toolchain is pinned to Rust 1.100.0 in `mise.toml`; `Cargo.toml` declares Rust 1.99.1 as the minimum. Native compilation tools are required. Published packages can lag this source tree. Source validation does not certify the capabilities of a separately published binary. + +`--lang en` and `--lang zh-CN` work before or after a subcommand, including help. The flag overrides the first nonempty value in `LMM_LANG`, `LC_ALL`, `LC_MESSAGES` and `LANG`. Unknown environment locales fall back to English; unsupported explicit flags are rejected. Terminal presentation is translated, while CLI-generated JSON prose stays English and protocol values remain unchanged. Original vendor metadata is preserved. See [Translations](i18n.md). + +## Presets, software and account data + +`lmm presets [query] --json` searches the offline snapshot of 56 provider presets. It does not configure a provider, read a key, discover live models or test connectivity. Source attribution and the fixed Magpie revision are preserved under [third_party/magpie](../third_party/magpie/NOTICE.md). Static endpoints and models may become outdated. + +`lmm catalog [query]` searches software identities and translated descriptions. The catalog separately records installation, integration and maintenance capabilities. It is not an installed-software list or a complete compatibility declaration. `lmm models` instead reads the model catalog authorized for the current LMM account; `lmm balance` reads the account's balance. + +```sh +lmm presets deepseek --json +lmm catalog +lmm models --json +lmm balance --json +``` + +Model results preserve server context/capability metadata, cache prices and group/trust multipliers. Unknown fields remain `null`, and returned prices are not multiplied again. Balance V2 preserves exact integer credits, USD balance and the server conversion unit; unknown units or a failed request are not rendered as zero. These commands do not select a model or make a paid model call. + +## Local inspection + +Local inspection uses explicit paths in the operating system running the CLI. It does not scan other users, remote systems, networks or container instances. PATH matches are only evidence; discovered executables are not run, even for `--version`. Symlinks and inaccessible paths remain unknown, and a missing file describes only the location inspected. + +```sh +lmm status astrbot --instance /absolute/path/to/AstrBot --json +lmm status cc-switch --instance /absolute/path/to/.cc-switch --json +lmm doctor astrbot --instance /absolute/path/to/AstrBot --report --json +lmm setup astrbot --dry-run --json +``` + +AstrBot inspection checks the selected root's `data/cmd_config.json` path. CC Switch opens an explicitly selected database in a read-only SQLite transaction, checks schema 24 and reads non-credential provider metadata. Managed installation state and database selection are reported separately. Neither establishes application authorization, the actual model route or a successful call. + +`--report` removes instance and evidence paths from diagnostic output; ordinary `status` can expose local paths. Configuration values and credential contents are not included. `doctor` remains incomplete, returning `3` even if a supported configuration check passes; `--fix` still refuses writes. Status exit code `0` means the applicable query completed, not that the application is ready for use. + +### Pi settings inspection + +The read-only Pi inspector supports Linux and the manifest format of the official Pi 1.2.0 npm package. Supply three explicit directories: + +```sh +lmm status pi --instance /absolute/project \ + --pi-package /absolute/node_modules/@earendil-works/pi-coding-agent \ + --agent-dir /absolute/pi-agent --json +lmm doctor pi --instance /absolute/project \ + --pi-package /absolute/node_modules/@earendil-works/pi-coding-agent \ + --agent-dir /absolute/pi-agent --report --json +``` + +This path reads the package manifest, the selected agent's `settings.json` and the project's `.pi/settings.json`. It does not need Node, run the SDK, read `auth.json`, or create a state directory or configuration lock. Linux directory and file opens reject symlink traversal at each component. + +`pi_settings.provider_reference` distinguishes the pinned source, other recognized LMM sources and multiple references. Common Pi 1.2.0 npm/Git forms are recognized; local extension paths, npm aliases and unknown forms are unresolved. A known source mixed with unresolved entries reports `known_with_unresolved_sources`. Even `no_known_source` cannot exclude an extension loading LMM by another mechanism. A package reference does not prove code is installed or loaded. + +`lmm_added=referenced_in_settings` and `lmm_enabled=selected_in_settings` describe a reference and a default provider field, not runtime activation. Project provider/model defaults override the corresponding global fields independently; `provider_scope` and `model_scope` report those sources. Model values are reduced to set/unset and other providers to `other`. Multiple known sources are reported without automatic deduplication. + +Unknown versions, inaccessible files, symlinks including directory ancestors, files over 1 MiB and incompatible known field shapes remain unknown and make `status` return `3`. Missing settings are treated as unset and are not created. The files are separate snapshots, not an atomic cross-file view. Hard links, bind mounts and changes after opening are outside the symlink checks. Project trust, launch arguments, session selections and model caches can change actual behavior; this check verifies none of them or the SDK's authenticity. A project path without Pi format arguments retains ordinary path inspection. + +## Plans and explicit consent + +`--json` disables CLI prompts, and `--non-interactive` does not wait for missing input. `--yes` cannot bypass missing capability, required application consent or server-enforced cost limits. `--all` does not turn the software catalog into a list of installed targets: `update --all` considers only LMM-managed CC Switch, while `setup --all` still has no executable application targets. + +Supported adapters use their own native transactions, journals and exact scope checks. Unsupported software continues to return a blocked plan instead of an empty success. Installation alone does not need CLI login. Status, diagnostics and dry-run planning do not make paid model calls or create their own state directories. + +### Managed CC Switch distributions + +The Linux x86_64/aarch64 adapter manages a pinned official CC Switch AppImage inside an LMM-owned private directory. Its version, source commit, byte length and SHA-256 are recorded in the [managed distribution contract](managed-distributions.md) and [release manifest](../src/managed/releases.rs). It does not execute an arbitrary network `latest` release or claim upstream signature verification. + +```sh +lmm install cc-switch --dry-run --json +lmm update cc-switch --dry-run --json +lmm restore cc-switch --change --dry-run --json +lmm uninstall cc-switch --dry-run --json +``` + +After reviewing a plan, repeat the same arguments without `--dry-run` and with `--yes --plan-id `. The plan becomes invalid if managed state changes. `--yes` alone does not skip the plan. `--managed-root` selects the private program directory; `--instance` selects application data for database compatibility checks. `run --instance` is refused because it cannot rewrite CC Switch's native launch settings. + +`lmm run cc-switch` starts only the verified managed program. A `process_started` result establishes only that a child process was created. Graphical-session/FUSE requirements, application health, live routing and model calls need separate acceptance. Installation does not edit PATH, system packages, desktop entries or application configuration. + +The journal records pending work before download or removal, then commits state and a receipt. Resume an interrupted operation with its original plan ID. A previously committed plan returns its receipt rather than overwriting later changes. `--cancel-pending` requires the original plan and refuses cancellation after original files have been removed. Restoration needs an explicit `change_id` and preserves later user changes; a native database newer than the old program's supported schema blocks a downgrade. App data is not rolled back or removed. + +### Native CC Switch application configuration + +Independent application grants do not reuse the CLI read-only login. `authorize` obtains browser consent for the selected instance, group and spending scope. The server must provide the matching independent authorization and recoverable renewal contract. Credentials remain in the system vault; native Codex command authentication obtains a model bearer without copying a CLI token or another application's credentials. + +`setup cc-switch --add-only` adds an LMM provider to an explicit schema 24 instance. `sync` refreshes metadata from that application's authorized catalog while retaining the original model choice. Preview and apply require exact target/plan identifiers. If a database commit outcome is unknown, query the original `change_id` with `receipt` before retrying. `restore --configuration --change` uses native receipts and refuses conflicting later edits. + +A provider row is not evidence that Codex is active on the route. `--activate` and complete removal need a CC Switch native operation that checks live configuration, proxy and Stack references; an `is_current` field or inactive SQLite pointer is insufficient. The hidden `credential` command serves the native raw-token pipe and rejects JSON and terminal token display. See [native credential evidence](native-credential-evidence.md) for the pinned upstream contract and unexecuted compatibility boundaries. + +### Pi Provider adapter + +The Linux adapter uses an already installed official Pi 1.2.0 SDK and manages only the pinned LMM Provider in an explicitly selected project. It does not install/uninstall Pi itself or copy CLI credentials. The current source is `git:github.com/TokenNotIncluded/pi-lmm-provider@f0c54764eb3d73e50790346f0dbab834587fe27b`. + +```sh +lmm setup pi --add-only --instance /absolute/project --node /absolute/node \ + --pi-package /absolute/node_modules/@earendil-works/pi-coding-agent \ + --agent-dir /absolute/pi-agent --dry-run --json +``` + +After reviewing the preview, repeat the same paths without `--dry-run` and add `--yes`. `setup`/`install` adds only the pinned Provider. `provider_added_authorization_pending` is not a usable-model claim. Choose LMM using `/login` inside Pi and explicitly choose a model with `/model`; `--activate` cannot substitute for those steps. Existing alternate LMM sources block duplicate installation, while current default provider/model selections are preserved. + +`update` accepts only the still-present owned source and does not chase latest versions. `sync` verifies presence and reports `catalog_refresh_pending`; `/lmm-prices` in Pi performs the actual refresh. `run pi` uses the same four explicit paths and requires an interactive terminal. Setup, sync and disconnect can return `3` after their limited phase because authorization, refresh or revocation remains pending in Pi. + +Restore/disconnect removes only the exact source that LMM added through Pi's native settings transaction. It preserves later plugins and defaults and refuses restoration if the user changed the owned source object. Downloaded code may be shared by another instance and is retained. Use `/lmm-revoke` inside Pi to revoke Pi authorization; removing a settings reference does not revoke it. Uninstall does not delete Pi or unknown resources. + +The secret-free journal is `.pi/lmm-owned.json` and the adapter lock is `.pi/lmm-adapter.lock` in the selected project. Pending state is persisted before a write and completed only after readback. Pi's `FileSettingsStorage.withLock` reads the latest settings before editing, avoiding replacement of a concurrent user's plugin array. The adapter never reads Pi's credential file. + +## Browser login and credential stores + +```sh +lmm login +lmm models --json +lmm balance --json +lmm logout + +# Use the same explicitly trusted issuer for related account commands. +lmm login --issuer https://lmm.example.com --no-browser +``` + +The server must register the `lmm` client and implement its OAuth contract. CLI login requests `catalog:read balance:read` and the group snapshot displayed on the consent page; it does not request `models:invoke`, MCP access or account administration. A CLI session does not authorize AstrBot, CC Switch or Pi. + +The callback listens only on a random `127.0.0.1` port. The default wait is 180 seconds; `--timeout` accepts 10–600 seconds. `--no-browser` disables automatic browser opening but still requires that browser to reach this machine's loopback port. It is not device-code login or cross-device headless authorization. Login requires an interactive terminal. An existing session is not silently replaced; log out before switching accounts. A callback receipt alone does not prove token exchange and storage completed. + +Windows uses Credential Manager, macOS uses Keychain, and Linux uses Secret Service through zbus rather than a statically linked libdbus. A system unlock prompt may appear. There is no ordinary-file credential fallback. Authentication and applicable application commands reject `--non-interactive` before opening the store; `models --json` and `balance --json` disable CLI prompts but cannot suppress an operating-system unlock prompt. + +OAuth operations share a secret-free `oauth.lock` in the current user's state directory: + +| System | State directory | +| --- | --- | +| Linux | `$XDG_STATE_HOME/lmm` or `~/.local/state/lmm` | +| macOS | `~/Library/Application Support/lmm` | +| Windows | `%LOCALAPPDATA%/lmm` | + +New Unix directories and lock files use `0700` and `0600`; unsafe existing directories or locks are rejected. Before refreshing, the CLI saves a non-retryable state in the vault. A lost response or failed save does not cause replay of an old refresh token; log out and obtain consent again. If logout revocation fails, the local record remains for a retry and success is not reported. Logout affects only this issuer's CLI token family, not independent application grants. + +## Development, outcomes and remaining limits + +Run checks from the repository root using `mise`: + +```sh +python3 scripts/check-i18n.py +python3 scripts/test_i18n_checks.py +mise exec -- cargo fmt --all -- --check +mise exec -- cargo test --locked +mise exec -- cargo clippy --locked --all-targets --all-features -- -D warnings +``` + +Fixture tests use temporary directories, synthetic inputs and SQLite. They do not start an official AppImage, authorize a real account or make a paid model call. Two opt-in Linux credential migration tests require a deliberately isolated Secret Service and remain ignored in an ordinary test run. Local success does not certify live credential stores on all platforms or publish a release. + +| Exit code | Meaning | +| --- | --- | +| `0` | A query or executable preview was produced, or a managed operation committed; inspect individual verification fields | +| `2` | Invalid/incomplete arguments, unknown target, selection failure or output error | +| `3` | Blocked operation, unsupported capability or incomplete verification | + +The in-memory `restore_fields` helper restores only scalar fields still equal to LMM's previous write and rejects conflicts across the target. It is not a file transaction or authorization mechanism. Managed distribution restoration and `restore --configuration` instead use their own persistent journals, native version gates and state comparisons. A bounded fingerprint is not an atomic write lock, and client-side cost checks do not replace server-enforced spending limits. + +The CLI does not copy third-party credentials or upload telemetry. Confirmed managed operations create their private state and secret-free journals; OAuth uses its separate lock and system vault. Normal status can include local paths, so review output or use `doctor --report --json` before sharing it. + +## Attribution + +The project uses [AGPL-3.0-only](../LICENSE). Provider preset data retains attribution and licensing for the pinned MIT-licensed Magpie source in [NOTICE](../NOTICE). Referencing this data does not imply feature parity with Magpie or a Go runtime dependency. diff --git a/docs/usage.zh-CN.md b/docs/usage.zh-CN.md new file mode 100644 index 0000000..096bb34 --- /dev/null +++ b/docs/usage.zh-CN.md @@ -0,0 +1,239 @@ +# 使用指南 + +[中文 README](../README.zh-CN.md) · [English](usage.md) + +LMM = **Language Model Mesh**,中文「语言模型网络」。本指南说明当前源码中的命令及其实际边界。 + +这是 [TokenNotIncluded/lmm](https://github.com/TokenNotIncluded/lmm) 独立维护的 Rust CLI。crates.io 包名为 `lmm-cli`,可执行文件名为 `lmm`;父仓库通过子模块锁定版本,CLI 的构建和依赖独立管理。 + +**当前是开发预览,已实现服务商预设、桌面 OAuth、模型目录与余额读取、限定版本的 Pi Provider 适配器,以及 CC Switch 的 Linux 受管发行包生命周期。** +Pi 使用显式指定的官方 Pi 1.2.0 SDK 安装和恢复固定 Provider,授权与激活仍在 Pi 内完成。 +CC Switch 支持固定官方 AppImage 的安装、更新、按回执恢复、卸载、显式启动和 schema 24 的只读检查;独立应用授权、仅添加配置、目录同步和撤销分别使用其管理合同。 +原生应用激活与真实调用需要单独验收,其他软件的写入流程继续明确阻塞。详细边界见 [受管发行包说明](managed-distributions.md) 和 [原生凭据接入说明](native-credential-evidence.md)。 + +完整产品要求见 [原始需求](requirements.zh-CN.md)。完整需求保留为目标,不因当前实现范围而缩减。 +与 Magpie 的功能对照及下一步任务见 [Magpie 对照](magpie-parity.md)。实现使用 Rust,不包装或启动 Magpie,也不依赖 Go 运行时。 + +## 构建当前源码 + +从独立仓库根目录使用固定工具链构建: + +```sh +mise install +mise exec -- cargo install --path . --locked +lmm --lang zh-CN --help +``` + +`mise.toml` 固定 Rust 1.100.0,Cargo 清单最低版本为 Rust 1.99.1。构建需要本机编译工具;Linux OAuth 另需运行中的 Secret Service,Windows/macOS 使用系统凭据库。已发布包可能不包含当前源码能力;这里不把源码验证作为某个已发布版本的验收。 + +## 语言选择 + +`--lang en` 或 `--lang zh-CN` 可放在子命令前后,且作用于帮助输出。优先级为显式参数,然后是 `LMM_LANG`、`LC_ALL`、`LC_MESSAGES`、`LANG` 中首个非空值,最后回退英文。未知环境语言回退英文,不支持的显式参数会被拒绝。 + +终端帮助、提示和已识别错误随语言切换;JSON 中由 CLI 生成的说明、用途、提示、错误正文保持英文,字段名、状态值、标识符和数字不变。上游原始元数据保持原样。详见[翻译指南](i18n.md)。 + +## 当前可用 + +- `lmm presets [关键词] [--json]`:查询 56 项内置服务商预设,离线运行,不读取密钥、不访问服务商。 +- `lmm catalog [关键词]`:搜索明确项目身份的软件目录,分别说明安装、接入、维护能力。 +- `lmm status [软件]`:当前环境与 PATH 线索;指定 CC Switch 时校验受管发行包,显式 `--instance` 时读取 schema 24 的非凭据元数据;Pi 支持下文限定的显式设置检查。 +- `lmm install|update|uninstall cc-switch --dry-run --json`:可执行的固定发行包计划;确认时带原 `--yes --plan-id`。 +- `lmm restore cc-switch --change --dry-run --json`:按回执恢复受管版本,保留后续修改和应用数据。 +- `lmm run cc-switch`:启动已校验的受管程序;启动成功不代表应用健康或模型调用通过。 +- `lmm doctor [软件] --report`:只读诊断摘要,移除实例和文件路径,仅输出各适配器允许的状态字段。 +- `lmm setup [软件] --dry-run`:生成带阻塞原因的预览;无目标且有终端时可选择软件。 +- `--json`:结构化结果;自动禁用交互。`--non-interactive` 同样禁止等待输入。 +- `lmm login`:桌面浏览器 PKCE 登录;凭据保存于系统凭据库。 +- `lmm models [--json]`:获取当前授权模型、服务器上下文/能力元数据、缓存价格及分组/信任倍率;未知保留 null,价格已含倍率,不调用模型、不切换配置。 +- `lmm balance [--json]`:读取余额 V2,保留服务端整数积分及美元单位;未知单位或失败不会显示为零。 +- `lmm logout`:撤销当前 issuer 下的 CLI 令牌族,成功后删除本地凭据;不影响 Pi/DSH 等其他应用。 + +## Pi Provider 适配器(Linux / Pi 1.2.0) + +此适配器连接**已经安装的官方 Pi 1.2.0 npm 包**,仅管理明确项目内的 LMM Provider。 +它不安装或卸载 Pi 本体,不复制 CLI 登录凭据。Pi 使用自己的 `/login` 授权、`/model` 选择和原生模型调用。 +固定 Provider 来源为 `git:github.com/TokenNotIncluded/pi-lmm-provider@f0c54764eb3d73e50790346f0dbab834587fe27b`。 + +```bash +lmm setup pi --add-only --instance /absolute/project --node /absolute/node \ + --pi-package /absolute/node_modules/@earendil-works/pi-coding-agent \ + --agent-dir /absolute/pi-agent --dry-run --json +# 核对预览后,用相同参数移除 --dry-run,并添加 --yes +``` + +`setup` / `install` 只添加固定 Provider;结果为 `provider_added_authorization_pending`,不代表模型已可用。 +`setup`、`sync`、`disconnect` 的后续授权/目录刷新/撤销仍需目标 Pi 完成,因此实际执行返回 3 并报告具体阶段。 +已有其他 LMM 安装来源时拒绝创建副本;默认服务商和模型保留当前选择。`--activate` 必须交由目标 Pi 的交互授权和模型选择完成。 +`update` 只接受仍存在的自有固定来源,本版本不自动追逐最新版。 +`sync` 验证 Provider 存在,明确返回 `catalog_refresh_pending`;在 Pi 中运行 `/lmm-prices` 才会刷新目录。 +`run pi` 使用相同的四个显式路径启动 Pi,只允许交互终端。 + +`restore` / `disconnect` 加相同目标路径和 `--yes`,仅从原生设置事务中移除本次添加的精确来源。 +这不会撤销 Pi OAuth 授权;需要撤销时在 Pi 中运行 `/lmm-revoke`。 +用户后来新增的插件、默认模型及其他字段都会保留;若用户改写了此来源对象则拒绝恢复。 +下载代码可能被其他实例引用,因此保留。`uninstall` 仍受阻,不删除 Pi 本体或未知资源。 + +无秘密日志在所选项目 `.pi/lmm-owned.json`,锁在 `.pi/lmm-adapter.lock`。 +修改前持久化 pending,读回成功后才完成日志;中断或不确定结果保持待检查状态,不自动声称完成。 +配置增删在 Pi 自己的 `FileSettingsStorage.withLock` 中读取最新内容执行,避免用旧插件数组覆盖并发编辑。 +普通 CLI 的 OAuth 凭据继续只保存在系统凭据库;适配器从不读取 Pi 的凭据文件。 + +## 服务商预设 + +```bash +lmm presets +lmm presets deepseek --json +``` + +预设来自 [Magpie 的固定版本](https://github.com/yetone/magpie/blob/d5cae267a727e23f4b6e2b28aa107ecdeac5aa9c/internal/provider/presets.go),是服务商地址及相关元数据的静态目录。它不是已经配置的服务商列表,不代表当前账号有权限或额度,也不代表已完成服务商接入、模型发现或调用验证。端点和模型信息可能随服务商变化,不能作为实时承诺。 + +`presets` 查询服务商预设,`catalog` 查询软件目录,`models` 读取 LMM 账号的授权模型;三者分别表示不同内容。 + +## 登录与模型目录 + +```bash +lmm login +lmm models --json +lmm balance --json +lmm logout +# 自托管必须明确指定可信的 HTTPS origin,认证和只读命令使用同一 issuer +lmm login --issuer https://lmm.example.com --no-browser +``` + +服务端需要注册 `lmm` 客户端并启用已有 OAuth 服务。使用前应确认目标服务支持这些接口,并验证实际账号的浏览器登录流程。 +CLI 只申请 `catalog:read balance:read` 和同意页显示的分组快照;没有 `models:invoke`、 +MCP 或账号管理权限。CLI 登录成功不代表 AstrBot 或 CC Switch 已授权。 + +浏览器回调只监听 `127.0.0.1` 随机端口,等待默认 180 秒,可用 `--timeout 10..600` 调整。 +`--no-browser` 仅关闭自动打开浏览器,**不是设备码登录**:浏览器仍须能访问本机回环端口。 +无图形服务器跨设备授权尚未实现;非交互 `login` 直接返回,不暗中等待授权。 +切换账号先 `logout` 再 `login`;已有 CLI 登录不会被新登录静默覆盖。 + +Windows 使用 Credential Manager,macOS 使用 Keychain,Linux 使用 Secret Service。 +凭据库可能显示系统解锁提示;不可用时明确报错,不使用明文文件后备。 +因此认证命令暂不支持 `--non-interactive`,会在访问凭据库之前退出;`models --json`、`balance --json` 只禁用 CLI 文本交互,系统仍可能要求解锁。 +Linux 通过 zbus 访问 Secret Service,不再静态链接 libdbus; +运行时仍需要可用的 Secret Service;不能将开发机单测当作三个系统的实际凭据库验收。两项 Linux 原生凭据迁移测试需要显式提供隔离服务,普通 cargo test 会保留为 ignored。 + +认证操作使用当前用户状态目录中的无密钥 `oauth.lock`,防止并发登录/刷新/退出。 +Linux 为 `$XDG_STATE_HOME/lmm` 或 `~/.local/state/lmm`,macOS 为 +`~/Library/Application Support/lmm`,Windows 为 `%LOCALAPPDATA%/lmm`。 +Unix 目录/锁文件新建权限分别为 0700/0600;已有不安全目录或锁文件会被拒绝。 +刷新前将“不可重试”状态存入凭据库,响应丢失或保存失败后不会自动重放旧 refresh token。 +此时需要退出再登录;退出撤销失败保留本地记录供重试,不能报告已完成。 + +模型目录只表示账号可见范围,不表示某个软件已经兼容。未知价格保留 null, +价格包含服务端返回的倍率,不重复计算;本命令不执行付费测试。 + +## 本地软件检查 + +显式实例接受 AstrBot 部署根目录、CC Switch 配置根目录,以及下述 Pi 项目根目录: + +```bash +lmm status astrbot --instance /absolute/path/to/AstrBot +lmm status cc-switch --instance /absolute/path/to/.cc-switch +lmm doctor astrbot --instance /absolute/path/to/AstrBot --report --json +lmm setup astrbot --dry-run --json +``` + +Windows 使用当前 Windows 环境的绝对路径。AstrBot 只检查所选根目录的 +`data/cmd_config.json` 路径;CC Switch 在显式 `--instance` 时打开只读 SQLite 事务,仅查询 schema 和非凭据的供应商元数据。 +不自动搜索项目、其他用户、Docker 实例、局域网或远程机器。 +PATH 文件可能是包装脚本或来自其他环境,因此只标为线索;不执行 `--version`。 +符号链接和不可访问项显示 `unknown`,文件缺失只描述被检查的那个位置。 + +CC Switch 的受管安装与 schema 24 配置管理者依据本地日志和原生数据库确认;授权、实际模型及真实调用路径不凭这些事实推断。 + +Pi 的只读设置检查仅支持 Linux、声明为官方 Pi 1.2.0 的 npm 包格式,必须显式指定三个目录: + +```bash +lmm status pi --instance /absolute/project \ + --pi-package /absolute/node_modules/@earendil-works/pi-coding-agent \ + --agent-dir /absolute/pi-agent --json +lmm doctor pi --instance /absolute/project \ + --pi-package /absolute/node_modules/@earendil-works/pi-coding-agent \ + --agent-dir /absolute/pi-agent --report --json +``` + +这条路径只读包清单和所选 agent 的 `settings.json`、项目的 `.pi/settings.json`, +不需要 Node,不启动目标或 SDK,不读取 `auth.json`,也不创建状态目录或配置锁。 +Linux 检查使用内核的禁止跟随符号链接标志逐级打开目录及设置文件。 +`pi_settings.provider_reference` 区分固定来源、其他已知 LMM 来源和多个引用; +识别 Pi 1.2.0 常见的 npm 和 Git 来源写法,不解析本地插件路径、npm 别名或未知写法。 +仅有无法识别的来源时结果为 `unknown`;已知 LMM 来源与无法识别的来源并存时为 +`known_with_unresolved_sources`,并仍报告已知引用。即使为 `no_known_source`, +也不能据此排除其他扩展加载了 LMM。包引用不代表代码已安装或已加载。 +`lmm_added=referenced_in_settings` 与 `lmm_enabled=selected_in_settings` 分别表示 +引用存在和默认服务商字段为 LMM;二者不等同于运行时添加或启用。 +项目的默认服务商、模型字段分别覆盖全局字段,`provider_scope` / `model_scope` +指出各自来源。模型只显示已设置/未设置,其他服务商只显示 `other`,不输出原始配置值。 +多个已知来源会单独标出,不自动去重或修复。 + +未知版本、无法访问、符号链接(含目录祖先)、超过 1 MiB 的文件及已知字段结构不符, +保留 `unknown` 并使 `status` 返回 3;不存在的设置文件按未设置处理,不创建它们。 +设置是分别读取的快照,不是跨文件原子快照;硬链接、绑定挂载以及文件打开后的并发修改 +不在符号链接防护范围内。项目信任、启动参数、会话选择及模型缓存 +可能改变实际行为,本检查不确认它们,也不验证 SDK 内容真实性、安装管理者或配置管理归属。 +仅提供项目路径、未提供 Pi 格式检查参数时,仍保留原有路径检查行为。 + +软件目录中的完整兼容版本/平台/场景列表仍为空;上述局部配置检查不是完整接入兼容声明。 +授权、连通性、实际服务商/模型及真实调用路径仍未验证。 +`status` 的退出码 0 只表示完成对应只读查询,不能用于判断“软件可使用”。 +`doctor` 即使配置检查通过也返回 3,`--fix` 仍阻止写入。 +`status`、`doctor`、`setup --dry-run` 没有网络调用或付费验证。 + +`--all` 不把目录视为安装列表。`update --all` 仅包含已由 LMM 管理的 CC Switch;没有受管安装时返回阻塞。应用接入的 `setup --all` 仍无可执行目标。 +`--yes` 不能消除能力缺失,不能代表支付、重新授权或切换服务商的同意。 +单独 `install` 不要求登录。CC Switch 的写操作需确认精确计划,不能用 `--yes` 跳过计划 ID。 + +## CC Switch 原生应用配置 + +CC Switch 的应用授权与 CLI 只读登录分开。`authorize` 在浏览器中确认独立实例、授权分组与消费范围;凭据留在系统凭据库,配置使用 Codex 原生凭据命令获取模型 bearer,不复制 CLI token 或其他应用凭据。服务端必须支持相应独立授权和可恢复续期合同。 + +`setup cc-switch --add-only` 在显式实例的 schema 24 数据库中添加 LMM,`sync` 根据该应用的授权目录更新元数据并保留原模型选择。计划与执行需要精确目标和计划 ID;未知提交结果必须先用 `receipt` 查询原 change_id,不能新建操作重复执行。`restore --configuration --change` 按原生回执恢复受管理字段,后续编辑触发冲突。 + +数据库记录存在不等于本机 Codex 已使用该路由。`--activate` 和完整删除需要 CC Switch 的原生管理入口核对 live、代理与 Stack 状态;不能只凭 is_current 或数据库不活动标记完成激活或删除。`credential` 只供原生凭据管道使用,拒绝 JSON 和终端 token 输出。具体协议依据见[原生接入证据](native-credential-evidence.md)。 + +## 开发 + +从这个独立仓库的根目录执行,工具版本由 `mise.toml` 固定: + +```bash +mise install +mise exec -- cargo run --locked -- presets deepseek --json +mise exec -- cargo run --locked -- catalog +python3 scripts/check-i18n.py +python3 scripts/test_i18n_checks.py +mise exec -- cargo test --locked +mise exec -- cargo clippy --locked --all-targets --all-features -- -D warnings +mise exec -- cargo fmt --all -- --check +mise exec -- cargo build --locked --release +``` + +不需要先构建或启动父仓库中的核心、扩展或 Web 服务。独立 Cargo 工程与后端分开锁定依赖,避免将 CLI 发布绑定到后端构建。 +源码开发需要 Rust;面向普通用户的签名二进制、安装器和更新渠道尚待发布, +当前没有声称普通用户已经能“一键安装”。CI 构建产物仅作开发预览,不自动发布。 + +## 退出码与安全边界 + +| 退出码 | 含义 | +| --- | --- | +| 0 | 查询或可执行预览已输出,或受管操作已提交;请继续检查各层状态 | +| 2 | 参数不完整、目标未知、无法选择目标或输出失败 | +| 3 | 能力未实现、检查未完成或操作被阻止 | + +`restore_fields` 是内存中的三方字段恢复算法:仅在字段仍等于 LMM 写入值时撤销, +保留用户后续修改;任一冲突使整个目标的计算失败。它拒绝整对象、数组及数组索引恢复。 +该字段算法仍未连接应用配置写入;CC Switch 的 `restore` 默认恢复受管发行包版本,`--configuration` 按原生数据库回执恢复 LMM 配置。这些路径使用各自的持久日志、原生版本门禁和三方状态检查。 +同样,付费检查函数只是客户端规划规则,**不能代替服务端消费限制**。 + +指纹函数只用于有界配置快照的内容比较,不是原子写锁。未来接入必须使用目标软件原生 +事务/管理接口解决并发写入;“比较哈希后覆盖文件”不满足完整并发修改验收。 + +只读检查和 `--dry-run` 不建立状态目录;确认的受管安装建立自己的私有目录与无凭据日志。OAuth 操作使用独立锁与系统凭据库。 +LMM 不复制第三方凭据、不上传遥测、不进行付费调用。 +分享前建议使用 `doctor --report --json`;普通 `status` 会显示本地路径。 + +## 来源与许可证 + +项目按 [AGPL-3.0-only](../LICENSE) 发布。服务商预设参考 Magpie 的 MIT 许可源码;来源及保留的许可说明见 [NOTICE](../NOTICE)。参考预设数据不意味着具备 Magpie 的全部能力。 diff --git a/scripts/check-i18n.py b/scripts/check-i18n.py index a66e4d3..26c2427 100644 --- a/scripts/check-i18n.py +++ b/scripts/check-i18n.py @@ -1,15 +1,17 @@ #!/usr/bin/env python3 -"""Check embedded translations with only the Python standard library.""" +"""Validate embedded translations and Rust references with the standard library.""" from __future__ import annotations import json import re +import sys from pathlib import Path ROOT = Path(__file__).resolve().parents[1] HAN = re.compile("[\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff\U00020000-\U0003134f]") +KEY = re.compile(r"[a-z][a-z0-9_]*(?:\.[a-z][a-z0-9_]*)+\Z") PLACEHOLDER = re.compile(r"\{([a-zA-Z][a-zA-Z0-9_-]*)\}") -CALL_KEY = re.compile(r'(?\s*"([a-z]+\.[a-z_]+)"') @@ -17,11 +19,25 @@ def unique_object(pairs: list[tuple[str, object]]) -> dict[str, object]: result: dict[str, object] = {} for key, value in pairs: if key in result: - raise ValueError(f"duplicate translation key: {key}") + raise ValueError(f"duplicate key: {key}") result[key] = value return result +def load_catalog(path: Path) -> dict[str, str]: + value = json.loads(path.read_text(encoding="utf-8"), object_pairs_hook=unique_object) + if not isinstance(value, dict) or not value: + raise ValueError("catalog must be a nonempty JSON object") + for key, message in value.items(): + if not KEY.fullmatch(key): + raise ValueError(f"invalid message key: {key!r}") + if not isinstance(message, str) or not message.strip(): + raise ValueError(f"{key}: expected a nonempty string") + if any(ord(char) < 32 and char not in "\n\t" for char in message): + raise ValueError(f"{key}: disallowed control character") + return value + + def placeholders(value: str) -> list[str]: remainder = PLACEHOLDER.sub("", value) if "{" in remainder or "}" in remainder: @@ -29,33 +45,58 @@ def placeholders(value: str) -> list[str]: return sorted(PLACEHOLDER.findall(value)) -def main() -> None: - catalogs = { - path.stem: json.loads(path.read_text(encoding="utf-8"), object_pairs_hook=unique_object) - for path in sorted((ROOT / "locales").glob("*.json")) - } - reference = catalogs["en"] +def validate(root: Path) -> list[str]: + errors: list[str] = [] + catalogs: dict[str, dict[str, str]] = {} + for path in sorted((root / "locales").glob("*.json")): + try: + catalogs[path.stem] = load_catalog(path) + except (ValueError, OSError) as error: + errors.append(f"{path.name}: {error}") + if not {"en", "zh-CN"}.issubset(catalogs): + errors.append("both en.json and zh-CN.json are required") + reference = catalogs.get("en", {}) for locale, catalog in catalogs.items(): - if set(catalog) != set(reference): - raise ValueError(f"{locale}: missing={set(reference) - set(catalog)}, extra={set(catalog) - set(reference)}") + missing = sorted(reference.keys() - catalog.keys()) + extra = sorted(catalog.keys() - reference.keys()) + if missing or extra: + errors.append(f"{locale}: missing keys {missing}; extra keys {extra}") for key, value in catalog.items(): - if not isinstance(value, str) or not value.strip(): - raise ValueError(f"{locale}.{key}: expected a nonempty string") - if placeholders(value) != placeholders(reference[key]): - raise ValueError(f"{locale}.{key}: placeholders differ from English") + try: + fields = placeholders(value) + if key in reference and fields != placeholders(reference[key]): + errors.append(f"{locale}.{key}: placeholders differ from English") + except ValueError as error: + errors.append(f"{locale}.{key}: {error}") + if any(HAN.search(value) for value in reference.values()): + errors.append("en: unexpected CJK text in the English catalog") used: set[str] = set() - for path in (ROOT / "src").rglob("*.rs"): + paths = sorted((root / "src").rglob("*.rs")) + if not paths: + errors.append("no Rust source files found") + for path in paths: source = path.read_text(encoding="utf-8") if HAN.search(source): - raise ValueError(f"{path.relative_to(ROOT)}: move Chinese UI text into locales/") + errors.append(f"{path.relative_to(root)}: move CJK UI text to locales/") used.update(CALL_KEY.findall(source)) used.update(MATCH_KEY.findall(source)) - unknown = used - set(reference) - unused = set(reference) - used - if unknown or unused: - raise ValueError(f"unknown message keys={unknown}; unused message keys={unused}") - print(f"i18n: {len(catalogs)} catalogs, {len(reference)} keys; placeholders and runtime references verified") + for key in sorted(used - reference.keys()): + errors.append(f"missing message {key}") + unused = sorted(reference.keys() - used) + if unused: + errors.append(f"unused message keys: {unused}") + return errors + + +def main() -> int: + errors = validate(ROOT) + if errors: + print("\n".join(errors), file=sys.stderr) + return 1 + count = len(load_catalog(ROOT / "locales/en.json")) + print(f"i18n: 2 catalogs, {count} keys; values, placeholders and runtime references verified") + return 0 if __name__ == "__main__": - main() + raise SystemExit(main()) diff --git a/scripts/test_i18n_checks.py b/scripts/test_i18n_checks.py new file mode 100644 index 0000000..7e66fe4 --- /dev/null +++ b/scripts/test_i18n_checks.py @@ -0,0 +1,95 @@ +#!/usr/bin/env python3 +"""Regression tests for the catalog validator; no Rust toolchain is required.""" +from __future__ import annotations + +import importlib.util +import json +import tempfile +import unittest +from pathlib import Path + +SPEC = importlib.util.spec_from_file_location("check_i18n", Path(__file__).with_name("check-i18n.py")) +assert SPEC is not None and SPEC.loader is not None +CHECK = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(CHECK) + + +class CatalogChecks(unittest.TestCase): + def setUp(self) -> None: + self.temporary = tempfile.TemporaryDirectory() + self.addCleanup(self.temporary.cleanup) + self.root = Path(self.temporary.name) + (self.root / "src").mkdir() + (self.root / "locales").mkdir() + (self.root / "src/main.rs").write_text('fn main() { msg("test.message"); }\n', encoding="utf-8") + self.write("en", {"test.message": "Hello {name}"}) + self.write("zh-CN", {"test.message": "你好,{name}"}) + + def write(self, language: str, value: object) -> None: + (self.root / f"locales/{language}.json").write_text(json.dumps(value, ensure_ascii=False), encoding="utf-8") + + def test_valid_catalogs(self) -> None: + self.assertEqual(CHECK.validate(self.root), []) + + def test_duplicate_keys_are_rejected(self) -> None: + (self.root / "locales/zh-CN.json").write_text('{"test.message":"a","test.message":"b"}', encoding="utf-8") + self.assertTrue(any("duplicate key" in error for error in CHECK.validate(self.root))) + + def test_missing_and_extra_keys_are_rejected(self) -> None: + self.write("zh-CN", {"test.other": "Other"}) + self.assertTrue(any("missing keys" in error and "extra keys" in error for error in CHECK.validate(self.root))) + + def test_placeholder_mismatch_and_malformed_template_are_rejected(self) -> None: + for message in ["Hello {other}", "Hello {name", "Hello {name!r}"]: + with self.subTest(message=message): + self.write("zh-CN", {"test.message": message}) + self.assertTrue(CHECK.validate(self.root)) + + def test_empty_and_non_string_messages_are_rejected(self) -> None: + for message in ["", " ", None, 1, {"nested": "value"}]: + with self.subTest(message=message): + self.write("zh-CN", {"test.message": message}) + self.assertTrue(CHECK.validate(self.root)) + + def test_source_literals_and_missing_references_are_rejected(self) -> None: + (self.root / "src/main.rs").write_text('fn main() { msg("test.missing"); println!("中文"); }', encoding="utf-8") + errors = CHECK.validate(self.root) + self.assertTrue(any("CJK UI text" in error for error in errors)) + self.assertTrue(any("missing message" in error for error in errors)) + + def test_english_catalog_and_control_characters_are_checked(self) -> None: + for message in ["中文 {name}", "Hello\u001b {name}"]: + with self.subTest(message=message): + self.write("en", {"test.message": message}) + self.assertTrue(CHECK.validate(self.root)) + + def test_required_catalogs_and_source_files_are_checked(self) -> None: + (self.root / "locales/zh-CN.json").unlink() + (self.root / "src/main.rs").unlink() + errors = CHECK.validate(self.root) + self.assertTrue(any("both en.json and zh-CN.json" in error for error in errors)) + self.assertTrue(any("no Rust source" in error for error in errors)) + + def test_unused_keys_and_placeholder_counts_are_checked(self) -> None: + self.write("en", {"test.message": "Hello {name}", "test.unused": "unused"}) + self.write("zh-CN", {"test.message": "Hello {name} {name}", "test.unused": "unused"}) + errors = CHECK.validate(self.root) + self.assertTrue(any("unused message keys" in error for error in errors)) + self.assertTrue(any("placeholders differ" in error for error in errors)) + + def test_catalog_shape_key_format_and_literal_braces_are_checked(self) -> None: + for value in [[], {}, {"bad key": "value"}, {"test.message": "{{name}}"}]: + with self.subTest(value=value): + self.write("en", value) + self.assertTrue(CHECK.validate(self.root)) + + def test_all_runtime_reference_helpers_are_recognized(self) -> None: + for call in ['msg("test.message")', 'text("test.message")', 'english("test.message")', + 'crate::i18n::english("test.message")', 'msg(\n"test.message")']: + with self.subTest(call=call): + (self.root / "src/main.rs").write_text(f"fn main() {{ {call}; }}\n", encoding="utf-8") + self.assertEqual(CHECK.validate(self.root), []) + + +if __name__ == "__main__": + unittest.main() diff --git a/src/i18n.rs b/src/i18n.rs index 32c0b7a..2d4ec64 100644 --- a/src/i18n.rs +++ b/src/i18n.rs @@ -19,6 +19,13 @@ pub enum Locale { impl Locale { pub const ALL: [Self; 2] = [Self::En, Self::ZhCn]; + pub const fn tag(self) -> &'static str { + match self { + Self::En => "en", + Self::ZhCn => "zh-CN", + } + } + /// Recognize supported language tags and common POSIX locale names. pub fn from_name(value: &str) -> Option { let name = value diff --git a/src/oauth/callback.rs b/src/oauth/callback.rs index 9f3422e..8175444 100644 --- a/src/oauth/callback.rs +++ b/src/oauth/callback.rs @@ -1,5 +1,5 @@ use super::AuthError; -use crate::i18n::text; +use crate::i18n::{self, Locale, msg}; use std::{ collections::BTreeMap, io::{Read, Write}, @@ -48,22 +48,9 @@ impl Callback { break; } let result = read_request(&mut stream, &host, issuer, state, remaining); - let body = if result.is_ok() { - text("callback.received") - } else { - text("callback.invalid") - }; - let status = if result.is_ok() { - "200 OK" - } else { - "400 Bad Request" - }; + let response = callback_response(result.is_ok(), i18n::locale()); let _ = stream.set_write_timeout(Some(Duration::from_millis(200))); - let _ = write!( - stream, - "HTTP/1.1 {status}\r\nContent-Type: text/plain; charset=utf-8\r\nContent-Length: {}\r\nCache-Control: no-store\r\nReferrer-Policy: no-referrer\r\nContent-Security-Policy: default-src 'none'; frame-ancestors 'none'\r\nConnection: close\r\n\r\n{body}", - body.len() - ); + let _ = stream.write_all(response.as_bytes()); match result { Ok(code) => return Ok(code), Err(AuthError::Denied) => return Err(AuthError::Denied), @@ -81,6 +68,26 @@ impl Callback { } } +/// Fixed plain text; neither authorization codes nor request text are echoed. +fn callback_response(accepted: bool, locale: Locale) -> String { + let message = if accepted { + msg("callback.received") + } else { + msg("callback.invalid") + }; + let body = locale.text(message.key()); + let status = if accepted { + "200 OK" + } else { + "400 Bad Request" + }; + format!( + "HTTP/1.1 {status}\r\nContent-Type: text/plain; charset=utf-8\r\nContent-Length: {}\r\nContent-Language: {}\r\nCache-Control: no-store\r\nReferrer-Policy: no-referrer\r\nContent-Security-Policy: default-src 'none'; frame-ancestors 'none'\r\nConnection: close\r\n\r\n{body}", + body.len(), + locale.tag() + ) +} + fn read_request( stream: &mut TcpStream, host: &str, @@ -206,6 +213,29 @@ mod tests { format!("/oauth/lmm/callback?{}", query.finish()) } + #[test] + fn callback_translation_uses_utf8_byte_lengths_and_fixed_language_headers() { + for locale in Locale::ALL { + for accepted in [true, false] { + let response = callback_response(accepted, locale); + let (headers, body) = response.split_once("\r\n\r\n").unwrap(); + let length: usize = headers + .lines() + .find_map(|line| line.strip_prefix("Content-Length: ")) + .unwrap() + .parse() + .unwrap(); + assert_eq!(length, body.len()); + assert!(headers.contains(&format!("Content-Language: {}", locale.tag()))); + assert!(headers.contains("Content-Type: text/plain; charset=utf-8")); + assert!(headers.contains("Cache-Control: no-store")); + assert!(headers.contains("Content-Security-Policy: default-src 'none'")); + assert!(body.contains("LMM CLI")); + assert!(!body.contains("callback.")); + } + } + } + #[test] fn callbacks_reject_mismatched_state_issuer_duplicates_and_malformed_encoding() { let good = query(&[("code", "lmm_oa_abc")]); diff --git a/tests/i18n.rs b/tests/i18n.rs index 73ed8a2..4af91b8 100644 --- a/tests/i18n.rs +++ b/tests/i18n.rs @@ -344,3 +344,29 @@ fn credential_command_keeps_its_no_json_contract_in_both_languages() { assert!(String::from_utf8_lossy(&output.stderr).contains("credential")); } } + +#[cfg(unix)] +#[test] +fn translated_output_keeps_untrusted_paths_escaped() { + let root = tempfile::tempdir().unwrap(); + let path = root.path().join("line\n\u{1b}[31m{software}"); + std::fs::create_dir(&path).unwrap(); + for language in ["en", "zh-CN"] { + let output = run( + &[ + "status", + "astrbot", + "--instance", + path.to_str().unwrap(), + "--lang", + language, + ], + &[], + ); + assert!(output.status.success()); + let text = stdout(&output); + assert!(!text.contains('\u{1b}')); + assert!(text.contains("\\n")); + assert!(text.contains("{software}")); + } +}