diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..995ab17 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,74 @@ +name: CI + +on: + push: + branches: [main] + pull_request: + +permissions: + contents: read + +concurrency: + group: ci-${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +jobs: + format: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - name: Install the pinned formatter + shell: bash + run: | + version=$(python3 -c 'import tomllib; print(tomllib.load(open("mise.toml", "rb"))["tools"]["rust"]["version"])') + rustup toolchain install "$version" --profile minimal --component rustfmt + rustup override set "$version" + - name: Check formatting + run: | + cargo fmt --all + git diff --exit-code > "$RUNNER_TEMP/rustfmt.patch" + - name: Keep formatting corrections on failure + if: failure() + uses: actions/upload-artifact@v4 + with: + name: rustfmt-patch + path: ${{ runner.temp }}/rustfmt.patch + retention-days: 7 + if-no-files-found: ignore + check: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - name: Install the pinned Rust toolchain + shell: bash + run: | + version=$(python3 -c 'import tomllib; print(tomllib.load(open("mise.toml", "rb"))["tools"]["rust"]["version"])') + rustup toolchain install "$version" --profile minimal --component clippy + rustup override set "$version" + - name: Check translations + run: python3 scripts/check-i18n.py + - name: Run tests + run: | + set -o pipefail + cargo test --locked 2>&1 | tee "$RUNNER_TEMP/tests.log" + - name: Check lints + run: | + set -o pipefail + cargo clippy --locked --all-targets --all-features -- -D warnings 2>&1 | tee "$RUNNER_TEMP/clippy.log" + - name: Verify source package + run: cargo package --locked + - name: Keep check logs + if: always() + uses: actions/upload-artifact@v4 + with: + name: check-logs + path: ${{ runner.temp }}/*.log + retention-days: 7 + if-no-files-found: ignore + - name: Keep the checked source package + uses: actions/upload-artifact@v4 + with: + name: lmm-cli-source-${{ github.sha }} + path: target/package/*.crate + retention-days: 7 + if-no-files-found: error diff --git a/AGENTS.md b/AGENTS.md index 67a1e02..b4cf7d3 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -16,3 +16,8 @@ fixtures instead of real account, system configuration or production writes. Run fmt, clippy and the complete CLI tests locally. Report the tested commit and skipped checks. A source change does not authorize publishing a crate, release or production deployment. + +Keep user-facing text in locales/en.json and locales/zh-CN.json, not Rust source. +Use stable message keys and named placeholders. Do not translate command names, +JSON field names, identifiers or protocol values. Run scripts/check-i18n.py and +read docs/i18n.md when adding messages. Keep both README versions in sync. diff --git a/Cargo.toml b/Cargo.toml index a62c8d4..8e8de53 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -11,7 +11,7 @@ homepage = "https://api.lmm.best" readme = "README.md" keywords = ["lmm", "cli", "oauth", "ai"] categories = ["command-line-utilities"] -include = ["Cargo.toml", "Cargo.lock", "README.md", "LICENSE", "src/**", "tests/**", "docs/**", "NOTICE", "third_party/**", "scripts/*.py"] +include = ["Cargo.toml", "Cargo.lock", "README.md", "README.zh-CN.md", "locales/**", "mise.toml", "LICENSE", "src/**", "tests/**", "docs/**", "NOTICE", "third_party/**", "scripts/*.py"] [lib] name = "lmm" diff --git a/locales/en.json b/locales/en.json new file mode 100644 index 0000000..f8679d4 --- /dev/null +++ b/locales/en.json @@ -0,0 +1,263 @@ +{ + "application.browser": "Browser authorization did not complete; the target software was not configured", + "application.busy": "Another local authorization operation is running", + "application.existing": "This instance already has an independent grant; explicitly disconnect the old grant before replacing it", + "application.expired": "The original renewal operation exceeded its recovery window; revoke the old grant and obtain consent again", + "application.invalid": "The application instance, issuer or grant format is invalid", + "application.network": "The application authorization request did not receive a reliable response; completion is unconfirmed", + "application.output": "Could not write to the Codex credential pipe", + "application.unauthorized": "Application authorization is incomplete, expired or missing required scopes", + "application.unavailable": "The server has not enabled independent CC Switch grants with recoverable renewal", + "application.unknown": "The application authorization code exchange outcome is unknown; no software was configured. Check this CC Switch instance on the LMM authorization page", + "application.unstored": "The new application grant could not be saved and revocation is unconfirmed; revoke this CC Switch instance on the LMM authorization page", + "application.vault": "The system vault is unavailable; OAuth credentials will not be stored in ordinary files", + "arg.activate": "Request adding and selecting LMM; this does not mean it has been applied", + "arg.add_only": "Add LMM without changing the current selection", + "arg.agent_dir": "Explicit Pi agent directory; other instances are not guessed or read", + "arg.all": "Include only installed, supported targets; updates also require management approval", + "arg.application_issuer": "Confirmed HTTPS issuer; defaults to the management record or official origin", + "arg.cancel_pending": "Cancel a pending operation only before commit or deletion of original files; confirm the original plan_id", + "arg.change": "Exact change_id to restore, available from status history", + "arg.configuration": "Restore native provider configuration; otherwise restore the managed program version", + "arg.dry_run": "Create a plan without applying changes", + "arg.fix": "Request approved LMM repairs without bypassing capability checks", + "arg.installation_id": "Independent application instance ID; never shared with read-only CLI login or other applications", + "arg.instance": "Explicit local instance root; remote and Docker instances are not scanned", + "arg.issuer": "Trusted LMM HTTPS origin; set explicitly for a self-hosted server", + "arg.json": "Write JSON without CLI prompts or configuration contents", + "arg.lang": "Display language: en or zh-CN; overrides LMM_LANG and locale variables", + "arg.managed_root": "LMM-owned program directory, separate from application data selected by --instance", + "arg.model_id": "Exact catalog model for unattended use; interactive setup can select from the catalog", + "arg.no_browser": "Print the login URL; the browser must still reach this machine through loopback", + "arg.node": "Explicit absolute path to Node (Pi adapter only)", + "arg.non_interactive": "Do not wait for input when a target or authorization is missing", + "arg.pi_package": "Root of the installed official Pi 1.2.0 npm package (Pi adapter only)", + "arg.plan_id": "Confirm the exact previously previewed plan; reject execution if state changed", + "arg.query": "Search text; omit to list all entries", + "arg.report": "Create a shareable report without paths or configuration contents", + "arg.software": "Exact catalog ID, such as astrbot or cc-switch", + "arg.timeout": "Maximum wait for the browser callback, in seconds", + "arg.yes": "Approve the displayed scope, not account changes, provider switches, or paid tests", + "auth.already_logged_in": "The CLI is already signed in; run lmm logout before switching accounts. Application grants will not be transferred", + "auth.busy": "Another LMM authorization operation is running, or a secure per-user lock could not be created", + "auth.callback": "Could not bind the local OAuth callback port", + "auth.credential_store": "Could not access the system vault. Unlock Keychain, Credential Manager, or Secret Service; plain-text files will not be used", + "auth.denied": "Authorization was cancelled or denied", + "auth.invalid_issuer": "issuer must be a canonical HTTPS domain origin without a port, path, query, or credentials", + "auth.invalid_response": "The LMM OAuth response was invalid; authorization has stopped", + "auth.network": "The LMM network request failed; check connectivity and whether the server has enabled the lmm client", + "auth.not_logged_in": "Not signed in; run lmm login first", + "auth.output": "Could not display the login URL; login has stopped", + "auth.refresh_blocked": "The previous refresh did not complete reliably. The old refresh token will not be reused; run logout, then login", + "auth.timeout": "Login timed out; no further requests were sent", + "auth.unauthorized": "The server rejected authorization; sign in again or check that the lmm client is deployed", + "auth.unstored_grant": "The new grant could not be saved and revocation could not be confirmed; check LMM CLI on the LMM authorization page", + "binding.authorization": "A valid independent CC Switch model grant belonging to this instance is required", + "binding.confirm": "Confirm the exact plan_id of the current preview", + "binding.conflict": "The target changed, a same-name item exists or a native database write is in progress; preview again", + "binding.database": "The CC Switch database is unavailable", + "binding.delete": "Removing a provider needs CC Switch's native management interface to check live, proxy and Stack references; database selection alone is insufficient", + "binding.invalid": "The CC Switch target, model selection or credential command path is invalid", + "binding.model_removed": "The original model is no longer in the authorized catalog; its selection was preserved. Explicitly select another model first", + "binding.receipt": "The change receipt or this instance's management record does not exist", + "binding.schema": "This is not a verified CC Switch schema 24 database, or the adapter's history structure is incomplete", + "binding.unknown": "The database commit outcome is unknown; query the receipt using the original change_id before retrying. Do not create a new operation", + "callback.invalid": "Invalid or denied authorization. Return to LMM CLI.", + "callback.received": "Authorization received. Return to LMM CLI to check completion.", + "cc_switch.bounds": "CC Switch data exceeds the bounded semantic inspection scope", + "cc_switch.database": "The CC Switch database is busy, unreadable or corrupt", + "cc_switch.path": "An explicit, existing CC Switch database without symlink traversal is required", + "cc_switch.schema": "The CC Switch database version or structure is not the verified schema 24", + "cli.about": "LMM: managed CC Switch installations and independent grants, native Pi integration", + "cmd.authorize": "Approve an independent application grant in a browser; the read-only CLI login is not reused", + "cmd.balance": "Read the current account balance, preserving server integer credits and USD units", + "cmd.catalog": "Search the software catalog; entries are not verified integrations", + "cmd.credential": "For Codex's native auth.command credential pipe only", + "cmd.disconnect": "Disconnect an explicitly selected integration and its independent application grant", + "cmd.doctor": "Run read-only checks; --fix still requires adapter support and approval", + "cmd.help": "Print help for a command", + "cmd.install": "Preview or apply an explicitly confirmed managed software installation; LMM login is not required", + "cmd.login": "Sign in with a browser and store credentials in the system vault", + "cmd.logout": "Sign out of the CLI without revoking other application grants", + "cmd.models": "Read authorized models and prices without calling or selecting a model", + "cmd.presets": "Search the built-in provider snapshot without reading credentials or using the network", + "cmd.receipt": "Query an immutable native configuration receipt without repeating a write", + "cmd.restore": "Restore an explicit managed change or native configuration receipt while preserving later edits", + "cmd.run": "Request a launch with the selected software configuration", + "cmd.setup": "Preview integration and apply only a supported, explicitly authorized adapter", + "cmd.status": "Inspect local environment and path evidence without making changes", + "cmd.sync": "Refresh supported LMM configuration while preserving the current provider and model", + "cmd.uninstall": "Plan removal of managed software; keep user data by default", + "cmd.update": "Plan updates for software explicitly placed under management", + "error.absolute_instance": "--instance must be an absolute local path", + "error.adapter_output": "Could not write adapter results", + "error.application_adapter": "This target has no independent application configuration adapter; authorization arguments cannot be ignored", + "error.application_arguments": "Application model selection and browser authorization arguments apply only to an explicitly selected CC Switch instance", + "error.application_authorize_first": "Independent application authorization is missing; preview and unattended mode cannot create it. First run interactive setup or authorize", + "error.application_flags_unsupported": "This operation does not support application authorization arguments", + "error.application_id": "Could not create an application instance", + "error.application_instance_required": "--installation-id or a configured --instance is required", + "error.application_interactive": "Application authorization requires the user's consent in a local browser; unattended mode will not authorize automatically", + "error.application_model": "The selected model is not in this application's Responses catalog", + "error.application_multiple": "This instance has multiple LMM management records; specify --issuer and --installation-id", + "error.application_no_models": "This application currently has no available Responses models", + "error.application_output": "Could not display application instances", + "error.application_record_required": "No management record was found; an independent grant requires --installation-id and --issuer", + "error.application_revoke_root": "Independent grant revocation does not use a managed program directory", + "error.application_unattended": "The system vault may need unlocking; these application commands do not yet accept --non-interactive. No credentials or network were accessed", + "error.auth_unattended": "The system vault may need to be unlocked; OAuth commands do not support --non-interactive yet. No credentials or network were accessed", + "error.balance_output": "Could not write the balance", + "error.binding_activation": "This adapter supports --add-only; full activation must confirm live/Stack state through CC Switch's native management interface", + "error.binding_instance": "Use --instance to select the CC Switch configuration root explicitly", + "error.binding_missing_record": "No management record was found", + "error.binding_not_added": "LMM has not been added; first run setup --add-only", + "error.binding_plan_changed": "State or catalog changed, or --plan-id does not match; preview again. For an unknown commit result, query the original receipt", + "error.binding_repeat_model": "Repeated setup preserves the current model; --model-id cannot implicitly change the original selection", + "error.binding_restore_change": "restore requires --change with the original configuration receipt", + "error.binding_scope": "Application configuration operations require an exact instance; SQLite has no cancelable half-commit. --change and --configuration apply only to restore", + "error.binding_setup_first": "This instance has no LMM management record; first run interactive setup --add-only", + "error.binding_target": "Configuration integration requires cc-switch and a separate --instance; a managed distribution directory cannot be substituted", + "error.catalog_output": "Could not write the software catalog", + "error.cc_switch_launch_instance": "CC Switch starts with its native instance settings; --instance cannot rewrite its launch configuration in this version", + "error.change_restore_only": "--change is supported only for restore", + "error.config_shape": "not a bounded regular configuration file", + "error.config_size": "configuration exceeds size limit", + "error.confirm_input": "Could not read confirmation", + "error.confirm_output": "Could not request confirmation", + "error.credential_executable": "Could not locate the current LMM credential command", + "error.credential_pipe": "credential is only for Codex's native credential pipe; it cannot be printed as JSON or displayed in a terminal", + "error.credential_unattended": "The system vault may need unlocking; credential does not accept --non-interactive", + "error.database_output": "Could not write database inspection results", + "error.instance_absolute": "--instance must be an absolute path", + "error.instance_unsupported": "Instance selection is not supported for this software; --instance will not be ignored", + "error.invalid_instance": "--instance must be an absolute local path for this environment; remote and container adapters are not available", + "error.json_output": "Could not write JSON", + "error.lifecycle_authorization": "Program lifecycle operations do not accept application authorization arguments; use restore --configuration to restore configuration", + "error.login_interactive": "Login needs browser approval; run lmm login in an interactive terminal. Unattended mode will not wait or consent for you", + "error.login_output": "Could not write the login result", + "error.logout_output": "Could not write the logout result", + "error.managed_arguments": "Independent application authorization, configuration restore and managed receipt arguments apply only to CC Switch and cannot be ignored for another target", + "error.managed_output": "Could not write managed installation status", + "error.managed_target": "--managed-root supports only managed CC Switch distributions", + "error.menu_output": "Could not display the selection menu", + "error.model_required": "Use --model-id to select a model explicitly; interactive setup can choose directly from the current catalog", + "error.model_selection_output": "Could not display models", + "error.models_output": "Could not write models", + "error.no_selection": "No target selected; no changes were made", + "error.output": "Could not write results", + "error.pi_activation": "Pi activation requires explicit authorization in /login and selection in /model inside Pi; first install the Provider with --add-only", + "error.pi_adapter_paths": "The Pi adapter needs absolute --instance, --node, --pi-package and --agent-dir paths together", + "error.pi_application_grant": "Pi manages authorization inside the target application; CC Switch authorization instance arguments are not accepted", + "error.pi_output": "Could not write Pi execution results", + "error.pi_paths_absolute": "Pi paths must be absolute local paths in this environment", + "error.pi_read_paths": "Read-only Pi inspection requires absolute --instance, --pi-package and --agent-dir paths; --node is not required", + "error.pi_read_target": "Pi paths apply only to an explicitly selected pi instance", + "error.pi_run_flags": "--dry-run and --yes for run/disconnect currently apply only to Pi; no other target was started or disconnected", + "error.pi_run_interactive": "Pi run requires an interactive terminal; JSON or unattended mode will not silently start the application", + "error.pi_target": "Pi paths apply only to an explicitly selected pi instance and cannot be ignored by another adapter", + "error.plan_output": "Could not write the plan", + "error.presets_output": "Could not write provider presets", + "error.presets_read": "Could not read the built-in provider presets", + "error.receipt_output": "Could not write the change receipt", + "error.restore_change": "restore needs --change with a receipt from status history; entire backups cannot be overwritten", + "error.selection_empty": "Nothing selected; operation stopped", + "error.selection_input": "Could not read the selection", + "error.selection_output": "Could not display the selection", + "error.target_required": "Unattended mode requires a software ID or --all; no changes were made", + "error.unknown_software": "Unknown software ID; run lmm catalog to find the exact name", + "error.unsupported_language": "Unsupported language. Use en or zh-CN.", + "help.arguments": "Arguments", + "help.commands": "Commands", + "help.help": "Print help", + "help.options": "Options", + "help.template": "{about-with-newline}\nUsage: {usage}\n\n{all-args}{after-help}", + "help.version": "Print version", + "kind.local": "local", + "kind.relay": "relay", + "kind.remote": "remote", + "kind.vendor": "vendor", + "managed.busy": "Another LMM operation is handling this installation; retry the original plan later", + "managed.cancel": "Some managed files were already removed; finish with the original plan. The operation cannot be reported as canceled", + "managed.change": "The change receipt was not found, or later changes conflict with the restoration target", + "managed.conflict": "Installation state changed after the preview; inspect the plan again", + "managed.database": "The local database version is incompatible with the target program; user data was not overwritten or rolled back", + "managed.downgrade": "This update would downgrade the version; use the restoration workflow with an explicit change receipt", + "managed.download": "Download failed before the change was committed; continue or cancel using the original plan ID", + "managed.integrity": "Downloaded length or SHA-256 does not match the pinned official release record", + "managed.launch": "The verified program could not start; check the graphical session, FUSE and runtime dependencies", + "managed.missing": "No managed installation exists; a program on PATH cannot be treated as an LMM installation", + "managed.modified": "The managed program was modified later; files were preserved and cannot be overwritten, executed or deleted", + "managed.ownership": "LMM did not create this managed installation; it cannot be adopted or removed", + "managed.path": "The managed directory must be absolute, private and free of symlink traversal", + "managed.pending": "An operation is incomplete; resume that same operation with the original plan ID", + "managed.platform": "This managed installation adapter supports only Linux x86_64 and aarch64", + "managed.state": "The managed installation journal is corrupt or has an unknown version; no changes were made", + "managed.storage": "The installation journal could not be durably written or read; check status and query the receipt with the original plan ID", + "note.all_blocked": "No automatic integration adapter has been verified; --all has no executable targets. No software was installed or changed", + "note.binding_next_step": "After confirmation, repeat the same arguments with --yes --plan-id; use receipt with the original plan_id to query an unknown result", + "note.binding_recovery": "Use receipt to query this change_id; do not create a new operation to repeat a commit with an unknown outcome", + "note.doctor_incomplete": "Diagnosis is incomplete: only local path evidence was checked. Check the selected instance, version, and configuration manager. No network or paid tests were run", + "note.dry_run": "Plan only; blockers remain unresolved. This is not evidence of a completed integration", + "note.execution_blocked": "No safe execution adapter is available for this target; no software was started or removed, no configuration changed, and no grants revoked", + "note.fix_blocked": "No repair adapter has been verified; configuration was not changed", + "note.install": "Installation does not require LMM login; a verified installation adapter is not available yet", + "note.managed_next_step": "After reviewing the plan, repeat the same arguments with --yes --plan-id ; --dry-run does not download or modify anything", + "note.pi_doctor_incomplete": "Diagnosis is incomplete: read-only settings inspection does not verify application loading, authorization, connectivity or real calls. No network or paid tests were run", + "note.pi_read_limits": "The two settings files are read separately. Installed code, project trust, session overrides, configuration ownership and actual routing are unverified. Project defaults describe overrides only if that project's settings are trusted.", + "note.pi_read_scope": "Only known package references and defaults in the selected Pi 1.2.0 settings are parsed. Configuration values are not printed; Node/Pi is not executed and credentials are not read.", + "note.yes": "--yes does not bypass missing capabilities, authorization, or cost limits", + "observation.not_found": "Not found", + "observation.present": "Present", + "observation.unknown": "Unknown", + "output.adapter": "\nAdapter: {error}", + "output.application_authorization": "Approve the independent CC Switch grant, group and spending limit for {label} in your browser.\nInstance: {instance}\n{url}", + "output.application_browser_failed": "The browser did not open automatically. Open the URL above in a browser on this machine.", + "output.application_heading": "CC Switch - independent application authorization and native database; activation and real calls are verified separately", + "output.application_model": "{index}. {name} / {group} / input {input} / output {output} / per request {request} ({currency}, {unit}; unknown values preserved)", + "output.authorization_url": "Approve LMM CLI in your browser (catalog and balance reads only; no application migration):\n{url}", + "output.balance": "Balance: {dollars} USD ({credits} credits; {rate} credits per USD)", + "output.blocked_plan": "\n{software} plan blocked: no configuration changes, paid calls, or restarts", + "output.browser_failed": "The browser could not be opened. Open the URL above in a browser on this machine.", + "output.catalog_entry": "{id} - {name}\n {purpose}\n Source: {source}\n Installation: {installation}; integration: {integration}; maintenance: {maintenance}; real application compatibility: unverified\n", + "output.database_status": "\nCC Switch schema {schema}: {providers} provider records; current application selection and actual routing are unverified", + "output.evidence": " {path}: {observation} (path evidence only)", + "output.login": "LMM CLI is signed in. Credentials are stored in the system vault. Applications have not been granted model-call permission; run lmm models to read the catalog.", + "output.logout": "CLI signed out. Other application grants were not revoked and cannot be listed by this version.", + "output.managed_heading": "CC Switch - LMM managed distribution; application configuration and request verification are reported separately", + "output.managed_status": "\nManaged distribution: {installation}, file integrity {integrity}, program health {health}", + "output.model_entry": "{id} / {upstream} / {group}\n Price unit: {currency} / {unit}; input: {input}, output: {output}, per request: {request}; basis: {basis}\n null/None means unknown; no model was called or selected.", + "output.model_metadata": " Metadata: {metadata}\n Cache read/write: {cache_read} / {cache_write}; group/trust multipliers: {group} / {trust} (already included in prices)", + "output.models": "Authorized models (application compatibility is not verified; final costs depend on usage):", + "output.pi_settings": " LMM reference/selection in settings: {added} / {enabled}; default model: {model} ({scope})\n Configuration inspection: {configuration}; diagnosis: {diagnostic}\n Authorization, connectivity, application, streaming and tool calls: not checked", + "output.presets": "Built-in provider presets (Magpie snapshot {revision}); configuration and connectivity were not checked. No providers were added.", + "output.scope": "Scope: current user and runtime environment; checked at {time} (Unix seconds)", + "output.target": "\n{software}: installation {installation}; installation manager {installation_manager}; configuration manager {configuration_manager}", + "output.verification": " LMM added/active: unknown; authorization, connectivity, application, streaming, and tool calls: not checked", + "pi.confirm": "First inspect the pinned source and instance with --dry-run, then confirm that scope with --yes", + "pi.incomplete": "Pi integration is incomplete; check explicit paths, Pi 1.2.0, configuration conflicts and pending recovery journals. No application credentials were read or copied", + "pi.platform": "The native Pi write adapter has been verified only on Linux; this platform is not enabled", + "pi.scope": "Only the pinned LMM Provider in the selected project is managed. Pi itself, other plugins, credentials and default models remain user-managed. After installation, choose LMM in Pi /login and explicitly select a model with /model.", + "plan.application_grant": "CLI login allows only catalog and balance reads; this target still needs a supported independent application grant", + "plan.install_adapter": "A verified software version, download-source check, and installation adapter are required", + "plan.paid_verification": "Paid verification requires explicit consent, a known quote, and a server-enforced spending limit", + "plan.restore_adapter": "No target change journal or native transaction adapter is connected; backups cannot be overwritten directly", + "plan.revoked_grant": "The application grant was revoked; explicit approval is required to authorize it again", + "plan.unknown_selection": "The current provider is unknown; first read the selected instance configuration", + "plan.unverified_target": "The software version, configuration manager, and actual request path have not been verified", + "plan.write_adapter": "This version has no verified configuration-write adapter for the target software", + "purpose.astrbot": "Agent and bot runtime for messaging platforms", + "purpose.cc_switch": "Provider configuration management and local routing", + "purpose.coding": "Coding assistant for the terminal", + "purpose.pi": "Terminal agent; its LMM provider is a separate project", + "restore.conflict": "The field changed after LMM wrote it; restoration has stopped", + "restore.duplicate_field": "The change journal contains duplicate fields", + "restore.invalid_pointer": "Could not locate the parent object for the field to restore", + "restore.unsupported_shape": "Only individual scalar fields in objects are supported; collections need a dedicated adapter", + "select.application": "Select the independent application instance to maintain", + "select.application_model": "Select a model for the new LMM provider", + "select.application_prompt": "{label} (Enter to cancel): ", + "select.binding_confirm": "Apply the exact database plan above? [y/N] ", + "select.managed_confirm": "Apply the exact plan above? [y/N] ", + "select.prompt": "Enter a number, or press Enter to cancel: ", + "select.title": "Select software to plan setup; adapter support is checked for the selected target:" +} diff --git a/locales/zh-CN.json b/locales/zh-CN.json new file mode 100644 index 0000000..09c5b09 --- /dev/null +++ b/locales/zh-CN.json @@ -0,0 +1,263 @@ +{ + "application.browser": "浏览器授权未完成;未配置目标软件", + "application.busy": "另一项本机授权操作正在运行", + "application.existing": "该实例已有独立授权;必须先明确解除旧授权才能更换", + "application.expired": "原续期操作超过恢复窗口;请撤销旧授权后重新征得同意", + "application.invalid": "应用实例、issuer 或授权格式无效", + "application.network": "应用授权请求未获得可靠响应;尚未确认操作完成", + "application.output": "无法向 Codex 凭据管道写入结果", + "application.unauthorized": "应用授权未完成、已失效或不包含所需权限", + "application.unavailable": "服务端尚未启用具有可恢复续期能力的 CC Switch 独立授权", + "application.unknown": "应用授权码交换结果未知;未配置软件,请在 LMM 授权页检查此 CC Switch 实例", + "application.unstored": "新应用授权未能保存,且撤销结果未知;请在 LMM 授权页撤销此 CC Switch 实例", + "application.vault": "系统凭据库不可用;不会把 OAuth 凭据存入普通文件", + "arg.activate": "明确请求添加并切换到 LMM(不表示已执行)", + "arg.add_only": "仅添加 LMM,保留当前选择", + "arg.agent_dir": "显式 Pi agent 目录;不会猜测或读取其他实例", + "arg.all": "仅包含当前环境中已安装且受支持的目标;更新还要求管理授权", + "arg.application_issuer": "已确认的 HTTPS issuer;未指定时沿用该管理记录或官方 origin", + "arg.cancel_pending": "取消仍未提交且未删除原文件的 pending 操作;必须确认原 plan_id", + "arg.change": "restore 要撤销的精确 change_id,可从 status 的 history 获取", + "arg.configuration": "restore 还原原生供应商目录;省略时还原受管程序版本", + "arg.dry_run": "只生成计划,不执行修改", + "arg.fix": "请求修复已获允许的 LMM 配置;不会绕过能力检查", + "arg.installation_id": "独立应用实例 ID;不与只读 CLI 登录或其他应用共用", + "arg.instance": "明确的本地实例根目录;不自动扫描远程或 Docker 实例", + "arg.issuer": "信任的 LMM HTTPS origin(自托管时显式指定)", + "arg.json": "输出结构化 JSON;不交互、不输出配置内容", + "arg.lang": "显示语言:en 或 zh-CN;优先于 LMM_LANG 和系统语言变量", + "arg.managed_root": "LMM 拥有的程序目录;与 --instance 指定的应用数据目录分开", + "arg.model_id": "无人值守时的精确目录模型;交互模式可从目录直接选择", + "arg.no_browser": "只显示登录链接;仍需要浏览器能访问当前机器的回环端口", + "arg.node": "显式 Node 可执行文件绝对路径(仅 Pi 适配器)", + "arg.non_interactive": "无人值守:缺少目标或授权时直接返回", + "arg.pi_package": "已安装官方 Pi 1.2.0 npm 包根目录(仅 Pi 适配器)", + "arg.plan_id": "确认先前预览的精确计划;状态改变时拒绝执行", + "arg.query": "搜索关键词;留空则列出全部条目", + "arg.report": "生成可主动分享的摘要,去除路径和配置内容", + "arg.software": "精确的软件目录 ID,例如 astrbot 或 cc-switch", + "arg.timeout": "浏览器回调等待上限(秒)", + "arg.yes": "确认已展示范围;不代表允许切换账号、服务商或付费测试", + "auth.already_logged_in": "已有 CLI 登录;切换账号请先 lmm logout,不会迁移应用授权", + "auth.busy": "另一项 LMM 授权操作正在运行,或无法建立当前用户的安全锁", + "auth.callback": "无法绑定本机 OAuth 回调端口", + "auth.credential_store": "无法访问系统凭据库;请解锁 Keychain、Credential Manager 或 Secret Service,不会回退到明文文件", + "auth.denied": "授权已取消或被拒绝", + "auth.invalid_issuer": "issuer 必须是规范的 HTTPS 域名 origin,不含端口、路径、查询或凭据", + "auth.invalid_response": "LMM OAuth 响应不符合约定,已停止授权", + "auth.network": "LMM 网络请求失败;请检查网络和服务端是否已启用 lmm 客户端", + "auth.not_logged_in": "尚未登录;请先运行 lmm login", + "auth.output": "无法输出登录入口;登录已停止", + "auth.refresh_blocked": "上次刷新未可靠完成;不会重放旧刷新令牌,请先 logout 再 login", + "auth.timeout": "登录等待超时;没有继续发起请求", + "auth.unauthorized": "服务端返回未授权;请重新登录,或检查 lmm 客户端是否已部署", + "auth.unstored_grant": "新授权未能保存,且无法确认已撤销;请在 LMM 授权页检查 LMM CLI 授权", + "binding.authorization": "需要仍有效且属于该实例的独立 CC Switch 模型授权", + "binding.confirm": "必须确认当前预览的精确 plan_id", + "binding.conflict": "目标已被修改、已有同名项目或原生数据库写入正在进行;请重新预览", + "binding.database": "CC Switch 数据库不可用", + "binding.delete": "删除供应商需要 CC Switch 原生管理入口确认 live、代理和 Stack 引用;仅凭数据库选择状态不能删除", + "binding.invalid": "CC Switch 目标、模型选择或凭据命令路径无效", + "binding.model_removed": "原模型已不在当前授权目录中;已保留选择,请先明确选择另一个模型", + "binding.receipt": "变更回执或本实例的管理记录不存在", + "binding.schema": "此数据库不是已核验的 CC Switch schema 24,或本适配器的历史结构不完整", + "binding.unknown": "数据库提交结果未知;请先使用原 change_id 查询回执,不能新建操作重试", + "callback.invalid": "授权无效或已被拒绝。请返回 LMM CLI。", + "callback.received": "已收到授权。请返回 LMM CLI 查看是否完成登录。", + "cc_switch.bounds": "CC Switch 数据超出语义检查的有界范围", + "cc_switch.database": "CC Switch 数据库忙、不可读或内容损坏", + "cc_switch.path": "需要明确、存在且不经过符号链接的 CC Switch 数据库", + "cc_switch.schema": "CC Switch 数据库版本或表结构不属于已核验的 schema 24", + "cli.about": "LMM 安装与接入工具(CC Switch 受管安装与独立授权、Pi 原生适配器)", + "cmd.authorize": "在浏览器中授予独立应用权限;不会复用只读 CLI 登录", + "cmd.balance": "读取当前账号余额;保留服务端整数积分和美元单位", + "cmd.catalog": "搜索软件目录;目录条目不代表已验证兼容", + "cmd.credential": "仅供 Codex 原生 auth.command 凭据管道", + "cmd.disconnect": "解除指定软件接入并撤销对应授权", + "cmd.doctor": "只读诊断;--fix 仍受适配器能力与确认范围限制", + "cmd.help": "显示指定命令的帮助", + "cmd.install": "安装软件;不要求 LMM 登录", + "cmd.login": "通过浏览器登录,凭据保存在系统凭据库", + "cmd.logout": "退出 CLI;不撤销独立应用授权", + "cmd.models": "读取当前授权模型与计费信息,不发起模型调用或更改选择", + "cmd.presets": "搜索内置服务商预设快照;不读取配置、凭据或网络", + "cmd.receipt": "查询原生配置操作的不可变回执;不重发写入", + "cmd.restore": "按字段恢复 LMM 变更,保留后续修改", + "cmd.run": "按当前配置启动指定软件", + "cmd.setup": "规划完整接入;当前版本在未具备适配器时明确阻止写入", + "cmd.status": "只读检查环境、安装线索与各层验证状态", + "cmd.sync": "同步 LMM 信息,保留当前服务商与模型", + "cmd.uninstall": "卸载已确认纳入管理的软件,默认保留数据", + "cmd.update": "更新明确纳入管理的软件", + "error.absolute_instance": "--instance 必须是绝对本地路径", + "error.adapter_output": "无法输出适配器结果", + "error.application_adapter": "此目标尚未提供独立应用配置适配器,不能忽略授权参数继续执行", + "error.application_arguments": "应用模型选择和浏览器授权参数只适用于明确选择的 CC Switch 实例", + "error.application_authorize_first": "缺少独立应用授权;预览或无人值守不会创建授权,请先交互 setup 或 authorize", + "error.application_flags_unsupported": "此操作不支持应用授权参数", + "error.application_id": "无法创建应用实例", + "error.application_instance_required": "需要 --installation-id 或已配置的 --instance", + "error.application_interactive": "应用授权必须由本机浏览器中的用户同意;无人值守不会自动授权", + "error.application_model": "所选模型不在这个应用的 Responses 目录中", + "error.application_multiple": "这个实例有多个 LMM 管理记录;需要明确 --issuer 与 --installation-id", + "error.application_no_models": "这个应用当前没有可选 Responses 模型", + "error.application_output": "无法显示应用实例", + "error.application_record_required": "未找到管理记录;独立授权需要 --installation-id 与 --issuer", + "error.application_revoke_root": "独立授权撤销不使用受管程序目录", + "error.application_unattended": "系统凭据库可能需要解锁;这些应用命令暂不接受 --non-interactive,未访问凭据或网络", + "error.auth_unattended": "当前系统凭据库可能需要解锁交互;OAuth 命令尚不支持 --non-interactive,未访问凭据或网络", + "error.balance_output": "无法输出余额", + "error.binding_activation": "此适配器支持 --add-only;完整激活必须通过 CC Switch 原生管理入口确认 live/Stack 状态", + "error.binding_instance": "请用 --instance 明确选择 CC Switch 配置根目录", + "error.binding_missing_record": "未找到管理记录", + "error.binding_not_added": "尚未添加 LMM;请先 setup --add-only", + "error.binding_plan_changed": "状态或目录已改变,或未提供匹配的 --plan-id;请重新预览,未知提交请查询原回执", + "error.binding_repeat_model": "重复 setup 保留当前模型;不能用 --model-id 隐式改动原选择", + "error.binding_restore_change": "restore 需要 --change 原配置回执", + "error.binding_scope": "应用配置操作需要精确实例;SQLite 无可取消的半提交,--change 和 --configuration 只用于 restore", + "error.binding_setup_first": "此实例没有 LMM 管理记录;请先交互 setup --add-only", + "error.binding_target": "配置接入需要 cc-switch 和独立 --instance,不能混用受管发行包目录", + "error.catalog_output": "无法输出目录", + "error.cc_switch_launch_instance": "CC Switch 使用其原生实例设置启动;此版本不能用 --instance 改写其启动配置", + "error.change_restore_only": "--change 只用于 restore", + "error.config_shape": "配置不是大小受限的普通文件", + "error.config_size": "配置超出大小限制", + "error.confirm_input": "无法读取确认", + "error.confirm_output": "无法请求确认", + "error.credential_executable": "无法确定当前 LMM 凭据命令的位置", + "error.credential_pipe": "credential 仅供 Codex 原生凭据管道调用;不能输出为 JSON 或显示在终端", + "error.credential_unattended": "系统凭据库可能要求解锁;credential 不接受 --non-interactive", + "error.database_output": "无法输出数据库检查", + "error.instance_absolute": "--instance 必须是绝对路径", + "error.instance_unsupported": "此软件尚未实现实例选择,不能忽略 --instance 后继续操作", + "error.invalid_instance": "--instance 必须是当前环境的绝对本地路径;远程与容器适配器尚未提供", + "error.json_output": "无法输出 JSON", + "error.lifecycle_authorization": "程序生命周期不接收应用授权参数;恢复配置请用 restore --configuration", + "error.login_interactive": "登录需要浏览器授权;请在交互终端运行 lmm login。无人值守模式不会等待或代替用户同意", + "error.login_output": "无法输出登录结果", + "error.logout_output": "无法输出退出结果", + "error.managed_arguments": "独立应用授权、配置恢复与受管回执参数只适用于 CC Switch,不能在其他目标上忽略", + "error.managed_output": "无法输出受管状态", + "error.managed_target": "--managed-root 当前只支持 CC Switch 的受管发行包", + "error.menu_output": "无法显示选择菜单", + "error.model_required": "需要 --model-id 明确选择模型;交互 setup 可直接从当前目录选择", + "error.model_selection_output": "无法显示模型", + "error.models_output": "无法输出模型", + "error.no_selection": "未选择目标;没有执行任何修改", + "error.output": "无法输出结果", + "error.pi_activation": "Pi 激活需要在目标 Pi 的 /login 和 /model 完成明确授权和选择;可先 --add-only 安装 Provider", + "error.pi_adapter_paths": "Pi 适配器需要同时指定 --instance、--node、--pi-package、--agent-dir 的绝对路径", + "error.pi_application_grant": "Pi 在目标应用内管理授权,不接受 CC Switch 的授权实例参数", + "error.pi_output": "无法输出 Pi 执行结果", + "error.pi_paths_absolute": "Pi 路径必须是当前环境的绝对本地路径", + "error.pi_read_paths": "Pi 只读检查需要 --instance、--pi-package、--agent-dir 的绝对路径;不需要 --node", + "error.pi_read_target": "Pi 路径参数只适用于明确选择的 pi 实例", + "error.pi_run_flags": "run/disconnect 的 --dry-run 和 --yes 当前只适用于 Pi,未执行其他目标的启动或撤销", + "error.pi_run_interactive": "Pi run 需要交互终端;不会在 JSON 或无人值守模式暗中启动应用", + "error.pi_target": "Pi 路径参数只适用于明确选择的 pi 实例,不能被其他适配器忽略", + "error.plan_output": "无法输出计划", + "error.presets_output": "无法输出服务商预设", + "error.presets_read": "内置服务商预设无法读取", + "error.receipt_output": "无法输出变更回执", + "error.restore_change": "restore 需要 --change 指定 status history 中的变更回执,不能覆盖整个备份", + "error.selection_empty": "没有选择;已停止操作", + "error.selection_input": "无法读取选择", + "error.selection_output": "无法显示选择", + "error.target_required": "无人值守模式需要明确软件或 --all;没有执行任何修改", + "error.unknown_software": "未知软件 ID;运行 lmm catalog 查看精确名称", + "error.unsupported_language": "不支持此语言。请使用 en 或 zh-CN。", + "help.arguments": "参数", + "help.commands": "命令", + "help.help": "显示帮助", + "help.options": "选项", + "help.template": "{about-with-newline}\n用法:{usage}\n\n{all-args}{after-help}", + "help.version": "显示版本", + "kind.local": "本地", + "kind.relay": "中转", + "kind.remote": "远程", + "kind.vendor": "服务商", + "managed.busy": "另一个 LMM 操作正在处理此安装,请稍后重试原计划", + "managed.cancel": "操作已移除部分受管文件,必须用原计划完成,不能宣称已取消", + "managed.change": "找不到该变更回执,或后续变更与恢复目标冲突", + "managed.conflict": "安装状态已在预览之后改变,请重新查看计划", + "managed.database": "本机数据库版本不适合目标程序;没有覆盖或回退用户数据", + "managed.downgrade": "此更新会降低版本,请使用明确变更回执的恢复流程", + "managed.download": "下载失败;变更尚未提交,使用原计划 ID 可继续或取消", + "managed.integrity": "下载长度或 SHA-256 不符合固定官方发布记录", + "managed.launch": "无法启动已校验程序;请确认图形会话、FUSE 和运行依赖", + "managed.missing": "尚无受管安装;不能把 PATH 中的程序当作 LMM 安装", + "managed.modified": "受管程序被后续修改,已保留文件;不能覆盖、执行或删除", + "managed.ownership": "该目录不是 LMM 创建的受管安装,不能接管或删除", + "managed.path": "受管目录必须是绝对、私有且不经过符号链接的路径", + "managed.pending": "存在未完成操作;请使用原计划 ID 恢复同一操作", + "managed.platform": "此受管安装适配器仅支持 Linux x86_64 和 aarch64", + "managed.state": "受管安装日志损坏或版本未知,未执行变更", + "managed.storage": "无法持久保存或读取安装日志;请查看状态并用原计划 ID 查回执", + "note.all_blocked": "当前版本没有经过验证的自动接入适配器,--all 没有可执行目标;未安装或修改任何软件", + "note.binding_next_step": "确认后使用相同参数与 --yes --plan-id;已有未知结果用 receipt 查询原 plan_id", + "note.binding_recovery": "使用 receipt 查询此 change_id;不要新建操作重复未知提交", + "note.doctor_incomplete": "诊断未完成:仅检查本地路径线索;请核对目标实例、版本及配置管理关系。没有执行网络或付费测试", + "note.dry_run": "仅规划;阻塞项仍需解决,不能作为接入完成的证据", + "note.execution_blocked": "未实现该目标的安全执行适配器;未启动或卸载软件,未修改配置或撤销授权", + "note.fix_blocked": "当前没有经过验证的修复适配器;未修改配置", + "note.install": "安装本身不需要 LMM 登录;当前缺少经过验证的安装适配器", + "note.managed_next_step": "确认计划后用相同参数加 --yes --plan-id ;--dry-run 不执行下载或修改", + "note.pi_doctor_incomplete": "诊断未完成:只读设置检查不验证目标应用加载、授权、连通性或真实调用;没有执行网络或付费测试", + "note.pi_read_limits": "两个设置文件分别读取;代码安装、项目信任、会话覆盖、配置管理归属及实际路由未验证。项目默认选择仅描述信任该项目设置时的覆盖规则。", + "note.pi_read_scope": "仅解析所选 Pi 1.2.0 设置中的已知包引用与默认选择,不输出配置值;不执行 Node 或 Pi,不读取凭据。", + "note.yes": "--yes 不会跳过缺失能力、授权或费用限制", + "observation.not_found": "未找到", + "observation.present": "存在", + "observation.unknown": "未知", + "output.adapter": "\n适配器:{error}", + "output.application_authorization": "请在浏览器确认 {label} 的独立 CC Switch 授权、分组和消费上限。\n实例:{instance}\n{url}", + "output.application_browser_failed": "浏览器未自动打开,请在本机浏览器打开上述地址。", + "output.application_heading": "CC Switch · 独立应用授权与原生数据库;激活和实际调用单独验证", + "output.application_model": "{index}. {name} · {group} · 输入 {input} / 输出 {output} / 每次 {request}({currency},{unit};未知值保留)", + "output.authorization_url": "请在浏览器确认 LMM CLI 授权(仅目录和余额读取,不迁移任何应用):\n{url}", + "output.balance": "余额:{dollars} USD({credits} 积分;每美元 {rate} 积分)", + "output.blocked_plan": "\n{software} 计划已阻止:无配置修改、无付费调用、无重启", + "output.browser_failed": "浏览器未能自动打开,请在本机浏览器打开上述链接。", + "output.catalog_entry": "{id} — {name}\n {purpose}\n 来源:{source}\n 安装:{installation};接入:{integration};维护:{maintenance};真实应用兼容场景:未验证\n", + "output.database_status": "\nCC Switch schema {schema}:{providers} 个服务商记录;当前应用选择与实际路由尚未验证", + "output.evidence": " {path}:{observation}(仅路径线索)", + "output.login": "LMM CLI 已登录,凭据已保存到系统凭据库。尚未授予应用调用权限;可运行 lmm models。", + "output.logout": "CLI 已退出;其他应用授权未撤销,当前版本尚不能列出这些授权。", + "output.managed_heading": "CC Switch · LMM 受管发行包;应用配置与调用验证独立报告", + "output.managed_status": "\n受管发行包:{installation},文件校验 {integrity},程序健康 {health}", + "output.model_entry": "{id} / {upstream} / {group}\n 价格单位:{currency} / {unit};输入:{input},输出:{output},每次请求:{request};依据:{basis}\n null/None 表示未知;未调用或切换模型。", + "output.model_metadata": " 元数据:{metadata}\n 缓存读取/写入:{cache_read} / {cache_write};分组/信任倍率:{group} / {trust}(价格已含倍率)", + "output.models": "当前授权模型(不代表目标软件兼容;价格可能随使用变化):", + "output.pi_settings": " 设置中的 LMM 引用/选择:{added} / {enabled};默认模型:{model}({scope})\n 配置检查:{configuration};诊断:{diagnostic}\n 授权、连通性、目标调用、流式及工具调用:未检查", + "output.presets": "内置服务商预设(Magpie 快照 {revision});配置与连通性未检查,未添加服务商。", + "output.scope": "范围:当前用户、当前运行环境;检查时间:{time}(Unix 秒)", + "output.target": "\n{software}:安装 {installation};安装管理者 {installation_manager};配置管理者 {configuration_manager}", + "output.verification": " LMM 添加/启用:未知;授权、连通性、目标调用、流式及工具调用:未检查", + "pi.confirm": "请先用 --dry-run 查看固定来源和实例,再用 --yes 确认该范围", + "pi.incomplete": "Pi 接入未完成;请检查显式路径、Pi 1.2.0、配置冲突或待恢复日志。未读取或复制应用凭据", + "pi.platform": "Pi 原生写入适配器目前仅验证 Linux;当前平台尚未开放", + "pi.scope": "仅管理所选项目中的固定 LMM Provider;Pi 本体、其他插件、凭据和默认模型保持用户管理。安装后在 Pi /login 选择 LMM,再用 /model 明确选择模型。", + "plan.application_grant": "CLI 登录只允许读取目录和余额;此目标仍需要受支持的独立应用授权", + "plan.install_adapter": "缺少经过验证的软件版本、下载来源校验及安装适配器", + "plan.paid_verification": "付费验证需要明确同意、已知报价和服务端可执行的消费上限", + "plan.restore_adapter": "尚未接入目标的变更日志与原生事务适配器,不能直接覆盖备份", + "plan.revoked_grant": "应用授权已撤销;需要明确确认重新授权", + "plan.unknown_selection": "无法确认当前服务商;需要先读取选定实例的实际配置", + "plan.unverified_target": "未验证软件版本、配置管理关系及实际调用路径", + "plan.write_adapter": "此版本尚无经过验证的目标软件写入适配器", + "purpose.astrbot": "消息平台 Agent 与机器人运行环境", + "purpose.cc_switch": "服务商配置管理与本地路由", + "purpose.coding": "终端编程助手", + "purpose.pi": "终端 Agent,LMM Provider 已有独立项目", + "restore.conflict": "字段在 LMM 修改后再次变化,恢复已暂停", + "restore.duplicate_field": "变更记录包含重复字段", + "restore.invalid_pointer": "无法定位恢复字段的父对象", + "restore.unsupported_shape": "仅支持对象中的单个标量字段;集合需要专用适配器", + "select.application": "选择要维护的独立应用实例", + "select.application_model": "选择新 LMM 供应商的模型", + "select.application_prompt": "{label}(回车取消):", + "select.binding_confirm": "应用上面的精确数据库计划?[y/N] ", + "select.managed_confirm": "应用上面的精确计划?[y/N] ", + "select.prompt": "输入序号,或直接回车取消:", + "select.title": "选择要规划接入的软件;随后检查所选目标的适配器支持:" +} diff --git a/scripts/check-i18n.py b/scripts/check-i18n.py new file mode 100644 index 0000000..a66e4d3 --- /dev/null +++ b/scripts/check-i18n.py @@ -0,0 +1,61 @@ +#!/usr/bin/env python3 +"""Check embedded translations with only the Python standard library.""" +from __future__ import annotations + +import json +import re +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +HAN = re.compile("[\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff\U00020000-\U0003134f]") +PLACEHOLDER = re.compile(r"\{([a-zA-Z][a-zA-Z0-9_-]*)\}") +CALL_KEY = re.compile(r'(?\s*"([a-z]+\.[a-z_]+)"') + + +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}") + result[key] = value + return result + + +def placeholders(value: str) -> list[str]: + remainder = PLACEHOLDER.sub("", value) + if "{" in remainder or "}" in remainder: + raise ValueError(f"invalid placeholder syntax: {value!r}") + 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"] + 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)}") + 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") + used: set[str] = set() + for path in (ROOT / "src").rglob("*.rs"): + source = path.read_text(encoding="utf-8") + if HAN.search(source): + raise ValueError(f"{path.relative_to(ROOT)}: move Chinese UI text into 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") + + +if __name__ == "__main__": + main() diff --git a/src/applications_cli.rs b/src/applications_cli.rs index 70cefde..998d2c8 100644 --- a/src/applications_cli.rs +++ b/src/applications_cli.rs @@ -3,6 +3,7 @@ use clap::Args; use lmm::{ cc_switch, + i18n::{english, msg, text}, oauth::{ self, applications::{self, ApplicationInstance}, @@ -18,10 +19,10 @@ use std::{ #[derive(Args, Default)] pub(super) struct Scope { - /// 独立应用实例 ID;不与只读 CLI 登录或其他应用共用 + #[arg(help = text("arg.installation_id"))] #[arg(long)] pub installation_id: Option, - /// 已确认的 HTTPS issuer;未指定时沿用该管理记录或官方 origin + #[arg(help = text("arg.application_issuer"))] #[arg(long)] pub issuer: Option, } @@ -68,13 +69,13 @@ pub(super) struct ReceiptArgs { fn output(value: &impl Serialize, json: bool) -> Result<(), String> { if !json { - writeln!( - io::stdout().lock(), - "CC Switch · 独立应用授权与原生数据库;激活和实际调用单独验证" - ) - .map_err(|_| "无法输出结果")?; + writeln!(io::stdout().lock(), "{}", msg("output.application_heading")) + .map_err(|_| english("error.output"))?; } - super::write_json(value) + super::write_json(value).map_err(|error| match error { + super::CliError::Message(message) => lmm::i18n::english(message.key()).to_owned(), + super::CliError::Adapter(value) => value, + }) } fn instance(issuer: &str, id: &str, label: &str) -> Result { ApplicationInstance::new(issuer, id, label).map_err(|error| error.to_string()) @@ -83,7 +84,7 @@ fn random_id() -> Result { let mut bytes = [0_u8; 32]; SysRng .try_fill_bytes(&mut bytes) - .map_err(|_| "无法创建应用实例")?; + .map_err(|_| english("error.application_id"))?; Ok(bytes.iter().map(|byte| format!("{byte:02x}")).collect()) } fn authorize_instance( @@ -96,14 +97,16 @@ fn authorize_instance( let mut stderr = io::stderr().lock(); writeln!( stderr, - "请在浏览器确认 {:?} 的独立 CC Switch 授权、分组和消费上限。\n实例:{}\n{}", - label, - instance.installation_id(), - url + "{}", + msg("output.application_authorization").render(&[ + ("label", &format!("{label:?}")), + ("instance", instance.installation_id()), + ("url", url), + ]) ) .map_err(|_| oauth::AuthError::Output)?; if !no_browser && open::that_detached(url).is_err() { - writeln!(stderr, "浏览器未自动打开,请在本机浏览器打开上述地址。") + writeln!(stderr, "{}", msg("output.application_browser_failed")) .map_err(|_| oauth::AuthError::Output)?; } Ok(()) @@ -113,7 +116,7 @@ fn authorize_instance( } pub(super) fn authorize(args: &AuthorizeArgs, interactive: bool, json: bool) -> Result { if !interactive { - return Err("应用授权必须由本机浏览器中的用户同意;无人值守不会自动授权".into()); + return Err(english("error.application_interactive").into()); } let generated; let id = match args.scope.installation_id.as_deref() { @@ -143,7 +146,7 @@ pub(super) fn authorize(args: &AuthorizeArgs, interactive: bool, json: bool) -> } pub(super) fn credential(args: &CredentialArgs, json: bool) -> Result { if json || io::stdout().is_terminal() { - return Err("credential 仅供 Codex 原生凭据管道调用;不能输出为 JSON 或显示在终端".into()); + return Err(english("error.credential_pipe").into()); } let application = instance( &args.issuer, @@ -156,14 +159,14 @@ pub(super) fn credential(args: &CredentialArgs, json: bool) -> Result Result { if target.software.as_deref() != Some("cc-switch") || target.managed_root.is_some() { - return Err("配置接入需要 cc-switch 和独立 --instance,不能混用受管发行包目录".into()); + return Err(english("error.binding_target").into()); } let root = target .instance .as_ref() - .ok_or("请用 --instance 明确选择 CC Switch 配置根目录")?; + .ok_or(english("error.binding_instance"))?; if !root.is_absolute() { - return Err("--instance 必须是绝对路径".into()); + return Err(english("error.instance_absolute").into()); } Ok(root.join("cc-switch.db")) } @@ -203,9 +206,7 @@ fn selection( 0 } else { if !interactive { - return Err( - "这个实例有多个 LMM 管理记录;需要明确 --issuer 与 --installation-id".into(), - ); + return Err(english("error.application_multiple").into()); } let mut stderr = io::stderr().lock(); for (index, entry) in matches.iter().enumerate() { @@ -217,27 +218,35 @@ fn selection( entry.group, entry.installation_id ) - .map_err(|_| "无法显示应用实例")?; + .map_err(|_| english("error.application_output"))?; } drop(stderr); - choose(matches.len(), "选择要维护的独立应用实例")? + choose(matches.len(), text("select.application"))? }; let chosen = matches[selected]; instance(&chosen.issuer, &chosen.installation_id, "CC Switch").map(Some) } fn choose(count: usize, label: &str) -> Result { - write!(io::stderr().lock(), "{label}(回车取消):").map_err(|_| "无法显示选择")?; - io::stderr().lock().flush().map_err(|_| "无法显示选择")?; + write!( + io::stderr().lock(), + "{}", + msg("select.application_prompt").render(&[("label", label)]) + ) + .map_err(|_| english("error.selection_output"))?; + io::stderr() + .lock() + .flush() + .map_err(|_| english("error.selection_output"))?; let mut line = String::new(); io::stdin() .read_line(&mut line) - .map_err(|_| "无法读取选择")?; + .map_err(|_| english("error.selection_input"))?; line.trim() .parse::() .ok() .and_then(|value| value.checked_sub(1)) .filter(|value| *value < count) - .ok_or("没有选择;已停止操作".into()) + .ok_or(english("error.selection_empty").into()) } fn choose_model( proof: &applications::VerifiedCatalog, @@ -254,38 +263,42 @@ fn choose_model( return if models.iter().any(|model| model.id == id) { Ok(id.into()) } else { - Err("所选模型不在这个应用的 Responses 目录中".into()) + Err(english("error.application_model").into()) }; } if models.is_empty() { - return Err("这个应用当前没有可选 Responses 模型".into()); + return Err(english("error.application_no_models").into()); } if models.len() == 1 { return Ok(models[0].id.clone()); } if !interactive { - return Err("需要 --model-id 明确选择模型;交互 setup 可直接从当前目录选择".into()); + return Err(english("error.model_required").into()); } let mut stderr = io::stderr().lock(); for (index, model) in models.iter().enumerate() { writeln!( stderr, - "{}. {:?} · {:?} · 输入 {:?} / 输出 {:?} / 每次 {:?}({:?},{:?};未知值保留)", - index + 1, - model.name, - model.group, - model.pricing.input, - model.pricing.output, - model.pricing.request, - model.pricing.currency, - model.pricing.unit + "{}", + msg("output.application_model").render(&[ + ("index", &(index + 1).to_string()), + ("name", &format!("{:?}", model.name)), + ("group", &format!("{:?}", model.group)), + ("input", &format!("{:?}", model.pricing.input)), + ("output", &format!("{:?}", model.pricing.output)), + ("request", &format!("{:?}", model.pricing.request)), + ("currency", &format!("{:?}", model.pricing.currency)), + ("unit", &format!("{:?}", model.pricing.unit)), + ]) ) - .map_err(|_| "无法显示模型")?; + .map_err(|_| english("error.model_selection_output"))?; } drop(stderr); - Ok(models[choose(models.len(), "选择新 LMM 供应商的模型")?] - .id - .clone()) + Ok( + models[choose(models.len(), text("select.application_model"))?] + .id + .clone(), + ) } fn confirmed( args: &super::OperationArgs, @@ -297,26 +310,27 @@ fn confirmed( return if args.plan_id.as_deref() == Some(&planned.plan_id) { Ok(true) } else { - Err( - "状态或目录已改变,或未提供匹配的 --plan-id;请重新预览,未知提交请查询原回执" - .into(), - ) + Err(english("error.binding_plan_changed").into()) }; } output( &serde_json::json!({"outcome":if args.dry_run {"planned"} else {"confirmation_required"},"binding_plan":planned, - "next_step":"确认后使用相同参数与 --yes --plan-id;已有未知结果用 receipt 查询原 plan_id"}), + "next_step":english("note.binding_next_step")}), json, )?; if args.dry_run || !interactive { return Ok(false); } - write!(io::stderr().lock(), "应用上面的精确数据库计划?[y/N] ").map_err(|_| "无法请求确认")?; - io::stderr().lock().flush().map_err(|_| "无法请求确认")?; + write!(io::stderr().lock(), "{}", msg("select.binding_confirm")) + .map_err(|_| english("error.confirm_output"))?; + io::stderr() + .lock() + .flush() + .map_err(|_| english("error.confirm_output"))?; let mut answer = String::new(); io::stdin() .read_line(&mut answer) - .map_err(|_| "无法读取确认")?; + .map_err(|_| english("error.confirm_input"))?; Ok(matches!(answer.trim(), "y" | "Y" | "yes")) } pub(super) fn operation( @@ -330,25 +344,19 @@ pub(super) fn operation( || args.cancel_pending || (name != "restore" && (args.change.is_some() || args.configuration)) { - return Err("应用配置操作需要精确实例;SQLite 无可取消的半提交,--change 和 --configuration 只用于 restore".into()); + return Err(english("error.binding_scope").into()); } if setup.is_some_and(|setup| !setup.add_only || setup.activate) { - return Err( - "此适配器支持 --add-only;完整激活必须通过 CC Switch 原生管理入口确认 live/Stack 状态" - .into(), - ); + return Err(english("error.binding_activation").into()); } let path = database(&args.target)?; let existing = selection(&path, &args.application, interactive)?; let application = match existing { Some(application) => application, None => { - let setup = setup.ok_or("此实例没有 LMM 管理记录;请先交互 setup --add-only")?; + let setup = setup.ok_or(english("error.binding_setup_first"))?; if !interactive || args.dry_run || args.yes { - return Err( - "缺少独立应用授权;预览或无人值守不会创建授权,请先交互 setup 或 authorize" - .into(), - ); + return Err(english("error.application_authorize_first").into()); } let application = instance( args.application @@ -379,7 +387,7 @@ pub(super) fn operation( application.installation_id(), args.change .as_deref() - .ok_or("restore 需要 --change 原配置回执")?, + .ok_or(english("error.binding_restore_change"))?, ) } else { let current = applications::catalog(&application).map_err(|error| error.to_string())?; @@ -392,13 +400,14 @@ pub(super) fn operation( }); let result = if already { if setup.is_some_and(|setup| setup.model_id.is_some()) { - return Err("重复 setup 保留当前模型;不能用 --model-id 隐式改动原选择".into()); + return Err(english("error.binding_repeat_model").into()); } cc_switch::bindings::preview_sync(&path, ¤t) } else { - let setup = setup.ok_or("尚未添加 LMM;请先 setup --add-only")?; + let setup = setup.ok_or(english("error.binding_not_added"))?; let model = choose_model(¤t, setup.model_id.as_deref(), interactive)?; - let helper = std::env::current_exe().map_err(|_| "无法确定当前 LMM 凭据命令的位置")?; + let helper = + std::env::current_exe().map_err(|_| english("error.credential_executable"))?; cc_switch::bindings::preview_add(&path, ¤t, &model, &setup.display_name, &helper) }; proof = Some(current); @@ -423,7 +432,7 @@ pub(super) fn operation( Err(error) => { output( &serde_json::json!({"outcome":"incomplete","error":error.to_string(),"issuer":application.issuer(),"installation_id":application.installation_id(),"change_id":planned.plan_id, - "recovery":"使用 receipt 查询此 change_id;不要新建操作重复未知提交"}), + "recovery":english("note.binding_recovery")}), json, )?; Ok(3) @@ -432,7 +441,8 @@ pub(super) fn operation( } pub(super) fn receipt(args: &ReceiptArgs, interactive: bool, json: bool) -> Result { let path = args.instance.join("cc-switch.db"); - let application = selection(&path, &args.scope, interactive)?.ok_or("未找到管理记录")?; + let application = selection(&path, &args.scope, interactive)? + .ok_or(english("error.binding_missing_record"))?; let receipt = cc_switch::bindings::receipt( &path, application.issuer(), @@ -453,7 +463,7 @@ pub(super) fn disconnect( ) -> Result { let application = if args.instance.is_none() { if args.managed_root.is_some() { - return Err("独立授权撤销不使用受管程序目录".into()); + return Err(english("error.application_revoke_root").into()); } instance( args.application @@ -463,7 +473,7 @@ pub(super) fn disconnect( args.application .installation_id .as_deref() - .ok_or("需要 --installation-id 或已配置的 --instance")?, + .ok_or(english("error.application_instance_required"))?, "CC Switch", )? } else { @@ -479,7 +489,7 @@ pub(super) fn disconnect( }; let path = database(&target)?; selection(&path, &args.application, interactive)? - .ok_or("未找到管理记录;独立授权需要 --installation-id 与 --issuer")? + .ok_or(english("error.application_record_required"))? }; let outcome = applications::revoke(&application).map_err(|error| error.to_string())?; let confirmed = matches!(outcome, applications::RevocationOutcome::Revoked); diff --git a/src/catalog.rs b/src/catalog.rs index 60e9a0b..f8fa498 100644 --- a/src/catalog.rs +++ b/src/catalog.rs @@ -1,5 +1,6 @@ //! Explicit project identities and independently stated integration capabilities. +use crate::i18n::{Locale, Message, msg}; use serde::Serialize; /// A capability with no verified adapter must never be promoted by discovery. @@ -31,7 +32,7 @@ pub struct Software { /// Canonical project identity, not a download mirror. pub source: &'static str, /// Intended use. - pub purpose: &'static str, + pub purpose: Message, /// Installation capability of this LMM release. pub installation: Capability, /// Integration capability of this LMM release. @@ -48,7 +49,7 @@ const fn software( id: &'static str, name: &'static str, source: &'static str, - purpose: &'static str, + purpose: Message, executables: &'static [&'static str], ) -> Software { Software { @@ -70,42 +71,42 @@ pub static SOFTWARE: &[Software] = &[ "astrbot", "AstrBot", "https://github.com/AstrBotDevs/AstrBot", - "消息平台 Agent 与机器人运行环境", + msg("purpose.astrbot"), &["astrbot"], ), managed_distribution(software( "cc-switch", "CC Switch", "https://github.com/farion1231/cc-switch", - "服务商配置管理与本地路由", + msg("purpose.cc_switch"), &["cc-switch"], )), software( "claude-code", "Claude Code CLI", "https://github.com/anthropics/claude-code", - "终端编程助手", + msg("purpose.coding"), &["claude"], ), software( "codex", "OpenAI Codex CLI", "https://github.com/openai/codex", - "终端编程助手", + msg("purpose.coding"), &["codex"], ), software( "gemini-cli", "Gemini CLI", "https://github.com/google-gemini/gemini-cli", - "终端编程助手", + msg("purpose.coding"), &["gemini"], ), software( "pi", "Pi coding agent", "https://github.com/badlogic/pi-mono", - "终端 Agent,LMM Provider 已有独立项目", + msg("purpose.pi"), &["pi"], ), ]; @@ -117,13 +118,19 @@ pub fn find(id: &str) -> Option<&'static Software> { /// Search project identity and purpose without network access. pub fn search(query: &str) -> Vec<&'static Software> { - let query = query.to_lowercase(); + let query = query.trim().to_lowercase(); SOFTWARE .iter() .filter(|item| { - [item.id, item.name, item.purpose] + [item.id, item.name] .iter() .any(|text| text.to_lowercase().contains(&query)) + || Locale::ALL.iter().any(|locale| { + locale + .text(item.purpose.key()) + .to_lowercase() + .contains(&query) + }) }) .collect() } diff --git a/src/cc_switch.rs b/src/cc_switch.rs index eb6f67a..22fbeaf 100644 --- a/src/cc_switch.rs +++ b/src/cc_switch.rs @@ -19,13 +19,13 @@ pub const SCHEMA_VERSION: u32 = 24; #[derive(Debug, thiserror::Error)] pub enum DatabaseError { - #[error("需要明确、存在且不经过符号链接的 CC Switch 数据库")] + #[error("{}", crate::i18n::english("cc_switch.path"))] Path, - #[error("CC Switch 数据库忙、不可读或内容损坏")] + #[error("{}", crate::i18n::english("cc_switch.database"))] Storage, - #[error("CC Switch 数据库版本或表结构不属于已核验的 schema 24")] + #[error("{}", crate::i18n::english("cc_switch.schema"))] UnsupportedSchema, - #[error("CC Switch 数据超出语义检查的有界范围")] + #[error("{}", crate::i18n::english("cc_switch.bounds"))] Limit, } diff --git a/src/cc_switch/bindings.rs b/src/cc_switch/bindings.rs index 250a8e8..650d7e5 100644 --- a/src/cc_switch/bindings.rs +++ b/src/cc_switch/bindings.rs @@ -47,27 +47,25 @@ type Result = std::result::Result; #[derive(Debug, thiserror::Error, PartialEq, Eq)] pub enum BindingError { - #[error("CC Switch 目标、模型选择或凭据命令路径无效")] + #[error("{}", crate::i18n::english("binding.invalid"))] Invalid, - #[error("需要仍有效且属于该实例的独立 CC Switch 模型授权")] + #[error("{}", crate::i18n::english("binding.authorization"))] Grant, - #[error("此数据库不是已核验的 CC Switch schema 24,或本适配器的历史结构不完整")] + #[error("{}", crate::i18n::english("binding.schema"))] Schema, - #[error("目标已被修改、已有同名项目或原生数据库写入正在进行;请重新预览")] + #[error("{}", crate::i18n::english("binding.conflict"))] Conflict, - #[error("原模型已不在当前授权目录中;已保留选择,请先明确选择另一个模型")] + #[error("{}", crate::i18n::english("binding.model_removed"))] SelectedModelUnavailable, - #[error("变更回执或本实例的管理记录不存在")] + #[error("{}", crate::i18n::english("binding.receipt"))] NotFound, - #[error( - "删除供应商需要 CC Switch 原生管理入口确认 live、代理和 Stack 引用;仅凭数据库选择状态不能删除" - )] + #[error("{}", crate::i18n::english("binding.delete"))] NativeRemoval, - #[error("必须确认当前预览的精确 plan_id")] + #[error("{}", crate::i18n::english("binding.confirm"))] Confirmation, - #[error("CC Switch 数据库不可用")] + #[error("{}", crate::i18n::english("binding.database"))] Storage, - #[error("数据库提交结果未知;请先使用原 change_id 查询回执,不能新建操作重试")] + #[error("{}", crate::i18n::english("binding.unknown"))] CommitUnknown, } impl From for BindingError { diff --git a/src/discovery.rs b/src/discovery.rs index 95c5080..2304796 100644 --- a/src/discovery.rs +++ b/src/discovery.rs @@ -1,6 +1,9 @@ //! Bounded local probes. Finding a path is evidence, not proof of installation. -use crate::catalog::Software; +use crate::{ + catalog::Software, + i18n::{Message, msg}, +}; use serde::Serialize; use sha2::{Digest, Sha256}; use std::{ @@ -24,6 +27,17 @@ pub enum Observation { Unknown, } +impl Observation { + /// Localized display label; serialized observation values remain unchanged. + pub const fn label(self) -> Message { + msg(match self { + Self::Present => "observation.present", + Self::NotFound => "observation.not_found", + Self::Unknown => "observation.unknown", + }) + } +} + /// Public evidence contains no configuration values or credentials. #[derive(Debug, Serialize)] pub struct Evidence { @@ -189,7 +203,7 @@ pub fn fingerprint(path: &Path) -> io::Result { if !meta.is_file() || meta.len() > MAX_CONFIG_BYTES { return Err(io::Error::new( io::ErrorKind::InvalidData, - "not a bounded regular configuration file", + msg("error.config_shape"), )); } let mut data = Vec::new(); @@ -199,7 +213,7 @@ pub fn fingerprint(path: &Path) -> io::Result { if data.len() as u64 > MAX_CONFIG_BYTES { return Err(io::Error::new( io::ErrorKind::InvalidData, - "configuration exceeds size limit", + msg("error.config_size"), )); } crate::hex::digest(Sha256::digest(data)) diff --git a/src/i18n.rs b/src/i18n.rs new file mode 100644 index 0000000..32c0b7a --- /dev/null +++ b/src/i18n.rs @@ -0,0 +1,251 @@ +//! Embedded CLI translations. Machine-readable messages always use English. + +use serde::{Serialize, Serializer}; +use std::{collections::BTreeMap, ffi::OsString, fmt, str::FromStr, sync::OnceLock}; + +type Catalog = BTreeMap; +static ENGLISH: OnceLock = OnceLock::new(); +static CHINESE: OnceLock = OnceLock::new(); +static LANGUAGE: OnceLock = OnceLock::new(); + +/// Languages shipped with the binary; no files or network are needed at runtime. +#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] +pub enum Locale { + #[default] + En, + ZhCn, +} + +impl Locale { + pub const ALL: [Self; 2] = [Self::En, Self::ZhCn]; + + /// Recognize supported language tags and common POSIX locale names. + pub fn from_name(value: &str) -> Option { + let name = value + .trim() + .split(['.', '@']) + .next() + .unwrap_or_default() + .replace('_', "-") + .to_ascii_lowercase(); + match name.as_str() { + "c" | "posix" | "en" => Some(Self::En), + "zh" | "zh-cn" | "zh-sg" | "zh-hans" => Some(Self::ZhCn), + name if name.starts_with("en-") => Some(Self::En), + name if name.starts_with("zh-hans-") => Some(Self::ZhCn), + _ => None, + } + } + + /// Resolve language before clap renders help. Clap still validates all arguments. + /// Stop at `--` so positional data cannot change the language. + pub fn detect(args: &[OsString], get_env: impl Fn(&str) -> Option) -> Self { + let mut selected = None; + let mut args = args.iter().skip(1); + while let Some(arg) = args.next() { + if arg == "--" { + break; + } + let value = if arg == "--lang" { + args.next().and_then(|value| value.to_str()) + } else { + arg.to_str().and_then(|arg| arg.strip_prefix("--lang=")) + }; + if let Some(value) = value { + selected = Self::from_name(value); + } + } + if let Some(locale) = selected { + return locale; + } + for key in ["LMM_LANG", "LC_ALL", "LC_MESSAGES", "LANG"] { + if let Some(value) = get_env(key).filter(|value| !value.is_empty()) { + return value.to_str().and_then(Self::from_name).unwrap_or_default(); + } + } + Self::default() + } + + fn catalog(self) -> &'static Catalog { + let (cache, source) = match self { + Self::En => (&ENGLISH, include_str!("../locales/en.json")), + Self::ZhCn => (&CHINESE, include_str!("../locales/zh-CN.json")), + }; + cache.get_or_init(|| { + serde_json::from_str(source) + .unwrap_or_else(|error| panic!("invalid embedded translation catalog: {error}")) + }) + } + + /// Missing translations fall back to English, then to the visible message key. + pub fn text(self, key: &'static str) -> &'static str { + self.catalog() + .get(key) + .or_else(|| Self::En.catalog().get(key)) + .map_or(key, String::as_str) + } +} + +impl FromStr for Locale { + type Err = Message; + + fn from_str(value: &str) -> Result { + Self::from_name(value).ok_or(msg("error.unsupported_language")) + } +} + +/// Select once at process startup. Tests should use explicit locales instead. +pub fn initialize(locale: Locale) -> Result<(), Locale> { + LANGUAGE.set(locale) +} + +pub fn locale() -> Locale { + LANGUAGE.get().copied().unwrap_or_default() +} + +/// A stable message key, separated from both presentation and serialization. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct Message(&'static str); + +pub const fn msg(key: &'static str) -> Message { + Message(key) +} + +pub fn text(key: &'static str) -> &'static str { + msg(key).text() +} + +/// Canonical prose for machine-readable adapter results and legacy error APIs. +pub fn english(key: &'static str) -> &'static str { + Locale::En.text(key) +} + +/// Recover a message at the presentation boundary of an existing String API. +/// Only exact catalog values are recognized; external text is never a template. +pub fn message_from_english(value: &str) -> Option { + Locale::En + .catalog() + .iter() + .find_map(|(key, candidate)| (candidate == value).then_some(Message(key.as_str()))) +} + +pub fn localize(value: &str) -> &str { + match message_from_english(value) { + Some(message) => message.text(), + None => value, + } +} + +impl Message { + pub const fn key(self) -> &'static str { + self.0 + } + + pub fn text(self) -> &'static str { + locale().text(self.0) + } + + /// Substitute named values once; inserted text is never parsed as a template. + pub fn render(self, values: &[(&str, &str)]) -> String { + self.render_in(locale(), values) + } + + pub fn render_in(self, locale: Locale, values: &[(&str, &str)]) -> String { + let mut rest = locale.text(self.0); + let mut output = String::with_capacity(rest.len()); + while let Some(start) = rest.find('{') { + output.push_str(&rest[..start]); + let Some(end) = rest[start..].find('}').map(|end| start + end) else { + output.push_str(&rest[start..]); + return output; + }; + let name = &rest[start + 1..end]; + match values.iter().find(|(key, _)| *key == name) { + Some((_, value)) => output.push_str(value), + None => output.push_str(&rest[start..=end]), + } + rest = &rest[end + 1..]; + } + output.push_str(rest); + output + } +} + +impl fmt::Display for Message { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter.write_str(self.text()) + } +} + +impl std::error::Error for Message {} + +impl Serialize for Message { + fn serialize(&self, serializer: S) -> Result { + serializer.serialize_str(Locale::En.text(self.0)) + } +} + +#[cfg(test)] +mod tests { + #![allow(clippy::unwrap_used)] + use super::*; + + #[test] + fn shipped_catalogs_have_the_same_nonempty_keys() { + let reference = Locale::En.catalog(); + assert!(!reference.is_empty()); + for locale in Locale::ALL { + let catalog = locale.catalog(); + assert_eq!( + reference.keys().collect::>(), + catalog.keys().collect::>() + ); + assert!(catalog.values().all(|value| !value.trim().is_empty())); + } + } + + #[test] + fn unknown_keys_remain_visible() { + assert_eq!(Locale::ZhCn.text("missing.test.key"), "missing.test.key"); + } + + #[test] + fn replacement_values_cannot_inject_other_placeholders() { + let output = msg("output.catalog_entry").render_in( + Locale::En, + &[ + ("id", "{source}"), + ("name", "name"), + ("purpose", "purpose"), + ("source", "URL"), + ], + ); + assert!(output.starts_with("{source} - name")); + assert!(output.contains("Source: URL")); + } + + #[test] + fn serialization_does_not_depend_on_display_language() { + let message = msg("error.unknown_software"); + assert_ne!( + Locale::En.text(message.key()), + Locale::ZhCn.text(message.key()) + ); + assert_eq!( + serde_json::to_value(message).unwrap(), + Locale::En.text(message.key()) + ); + } + + #[test] + fn canonical_adapter_errors_recover_only_exact_catalog_messages() { + let message = message_from_english(english("managed.conflict")).unwrap(); + assert_eq!(message.key(), "managed.conflict"); + assert_eq!( + serde_json::to_value(message).unwrap(), + english("managed.conflict") + ); + assert!(message_from_english("untrusted {software} {source}").is_none()); + assert_eq!(localize("untrusted {software}"), "untrusted {software}"); + } +} diff --git a/src/lib.rs b/src/lib.rs index 8f0490a..41ba255 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -8,6 +8,7 @@ pub mod discovery; pub mod environment; mod hex; mod http_client; +pub mod i18n; pub mod managed; pub mod oauth; pub mod plan; diff --git a/src/main.rs b/src/main.rs index 60450b5..d5ab91d 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,10 +1,11 @@ mod applications_cli; -use clap::{Args, Parser, Subcommand}; +use clap::{Args, CommandFactory, FromArgMatches, Parser, Subcommand}; use lmm::{ catalog, cc_switch, discovery::{self, ProbeContext, TargetStatus}, environment::{self, Environment}, + i18n::{self, Locale, Message, english, localize, msg, text}, managed::{self, Action as ManagedAction}, oauth, pi, plan::{Intent, Preview}, @@ -12,24 +13,77 @@ use lmm::{ }; use serde::Serialize; use std::{ - env, + env, fmt, io::{self, IsTerminal, Write}, path::{Path, PathBuf}, process::ExitCode, time::{SystemTime, UNIX_EPOCH}, }; +#[derive(Debug)] +enum CliError { + Message(Message), + Adapter(String), +} + +impl CliError { + fn key(&self) -> Option<&'static str> { + match self { + Self::Message(message) => Some(message.key()), + Self::Adapter(_) => None, + } + } +} + +impl From for CliError { + fn from(message: Message) -> Self { + Self::Message(message) + } +} + +impl From for CliError { + fn from(value: String) -> Self { + i18n::message_from_english(&value).map_or_else(|| Self::Adapter(value), Self::Message) + } +} + +impl From<&str> for CliError { + fn from(value: &str) -> Self { + value.to_owned().into() + } +} + +impl fmt::Display for CliError { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Message(message) => message.fmt(formatter), + Self::Adapter(value) => formatter.write_str(value), + } + } +} + +impl Serialize for CliError { + fn serialize(&self, serializer: S) -> Result { + match self { + Self::Message(message) => message.serialize(serializer), + Self::Adapter(value) => value.serialize(serializer), + } + } +} + #[derive(Parser)] #[command( name = "lmm", version, - about = "LMM 安装与接入工具(CC Switch 受管安装与独立授权、Pi 原生适配器)" + about = text("cli.about") )] struct Cli { - /// 输出结构化 JSON;不交互、不输出配置内容 + #[arg(long, global = true, value_name = "LANG", help = text("arg.lang"))] + lang: Option, + #[arg(help = text("arg.json"))] #[arg(long, global = true)] json: bool, - /// 无人值守:缺少目标或授权时直接返回 + #[arg(help = text("arg.non_interactive"))] #[arg(long, global = true)] non_interactive: bool, #[command(subcommand)] @@ -38,50 +92,56 @@ struct Cli { #[derive(Subcommand)] enum Command { - /// 搜索内置服务商预设快照;不读取配置、凭据或网络 - Presets { query: Option }, - /// 搜索软件目录;目录条目不代表已验证兼容 - Catalog { query: Option }, - /// 规划完整接入;当前版本在未具备适配器时明确阻止写入 + #[command(about = text("cmd.presets"))] + Presets { + #[arg(help = text("arg.query"))] + query: Option, + }, + #[command(about = text("cmd.catalog"))] + Catalog { + #[arg(help = text("arg.query"))] + query: Option, + }, + #[command(about = text("cmd.setup"))] Setup(SetupArgs), - /// 在浏览器中授予独立应用权限;不会复用只读 CLI 登录 + #[command(about = text("cmd.authorize"))] Authorize(applications_cli::AuthorizeArgs), - /// 查询原生配置操作的不可变回执;不重发写入 + #[command(about = text("cmd.receipt"))] Receipt(applications_cli::ReceiptArgs), - /// 仅供 Codex 原生 auth.command 凭据管道 + #[command(about = text("cmd.credential"))] #[command(hide = true)] Credential(applications_cli::CredentialArgs), - /// 安装软件;不要求 LMM 登录 + #[command(about = text("cmd.install"))] Install(OperationArgs), - /// 通过浏览器登录,凭据保存在系统凭据库 + #[command(about = text("cmd.login"))] Login(LoginArgs), - /// 退出 CLI;不撤销独立应用授权 + #[command(about = text("cmd.logout"))] Logout(AuthArgs), - /// 读取当前授权模型与计费信息,不发起模型调用或更改选择 + #[command(about = text("cmd.models"))] Models(AuthArgs), - /// 读取当前账号余额;保留服务端整数积分和美元单位 + #[command(about = text("cmd.balance"))] Balance(AuthArgs), - /// 只读检查环境、安装线索与各层验证状态 + #[command(about = text("cmd.status"))] Status(TargetArgs), - /// 同步 LMM 信息,保留当前服务商与模型 + #[command(about = text("cmd.sync"))] Sync(OperationArgs), - /// 更新明确纳入管理的软件 + #[command(about = text("cmd.update"))] Update(OperationArgs), - /// 只读诊断;--fix 仍受适配器能力与确认范围限制 + #[command(about = text("cmd.doctor"))] Doctor(DoctorArgs), - /// 按字段恢复 LMM 变更,保留后续修改 + #[command(about = text("cmd.restore"))] Restore(OperationArgs), - /// 解除指定软件接入并撤销对应授权 + #[command(about = text("cmd.disconnect"))] Disconnect(RequiredTarget), - /// 卸载已确认纳入管理的软件,默认保留数据 + #[command(about = text("cmd.uninstall"))] Uninstall(OperationArgs), - /// 按当前配置启动指定软件 + #[command(about = text("cmd.run"))] Run(RequiredTarget), } #[derive(Args)] struct AuthArgs { - /// 信任的 LMM HTTPS origin(自托管时显式指定) + #[arg(help = text("arg.issuer"))] #[arg(long, default_value = oauth::DEFAULT_ISSUER)] issuer: String, } @@ -90,23 +150,23 @@ struct AuthArgs { struct LoginArgs { #[command(flatten)] auth: AuthArgs, - /// 只显示登录链接;仍需要浏览器能访问当前机器的回环端口 + #[arg(help = text("arg.no_browser"))] #[arg(long)] no_browser: bool, - /// 浏览器回调等待上限(秒) + #[arg(help = text("arg.timeout"))] #[arg(long, default_value_t = 180, value_parser = clap::value_parser!(u64).range(10..=600))] timeout: u64, } #[derive(Args)] struct PiArgs { - /// 显式 Node 可执行文件绝对路径(仅 Pi 适配器) + #[arg(help = text("arg.node"))] #[arg(long)] node: Option, - /// 已安装官方 Pi 1.2.0 npm 包根目录(仅 Pi 适配器) + #[arg(help = text("arg.pi_package"))] #[arg(long)] pi_package: Option, - /// 显式 Pi agent 目录;不会猜测或读取其他实例 + #[arg(help = text("arg.agent_dir"))] #[arg(long)] agent_dir: Option, } @@ -119,12 +179,12 @@ impl PiArgs { #[derive(Args)] struct TargetArgs { - /// 精确的软件目录 ID,例如 astrbot 或 cc-switch + #[arg(help = text("arg.software"))] software: Option, - /// 明确的本地实例根目录;不自动扫描远程或 Docker 实例 + #[arg(help = text("arg.instance"))] #[arg(long, requires = "software")] instance: Option, - /// LMM 拥有的程序目录;与 --instance 指定的应用数据目录分开 + #[arg(help = text("arg.managed_root"))] #[arg(long, requires = "software")] managed_root: Option, #[command(flatten)] @@ -137,25 +197,25 @@ struct OperationArgs { target: TargetArgs, #[command(flatten)] application: applications_cli::Scope, - /// restore 还原原生供应商目录;省略时还原受管程序版本 + #[arg(help = text("arg.configuration"))] #[arg(long)] configuration: bool, - /// 仅包含当前环境中已安装且受支持的目标;更新还要求管理授权 + #[arg(help = text("arg.all"))] #[arg(long, conflicts_with_all = ["software", "instance", "managed_root"])] all: bool, - /// 只生成计划,不执行修改 + #[arg(help = text("arg.dry_run"))] #[arg(long)] dry_run: bool, - /// 确认已展示范围;不代表允许切换账号、服务商或付费测试 + #[arg(help = text("arg.yes"))] #[arg(long)] yes: bool, - /// 确认先前预览的精确计划;状态改变时拒绝执行 + #[arg(help = text("arg.plan_id"))] #[arg(long, requires = "yes")] plan_id: Option, - /// restore 要撤销的精确 change_id,可从 status 的 history 获取 + #[arg(help = text("arg.change"))] #[arg(long)] change: Option, - /// 取消仍未提交且未删除原文件的 pending 操作;必须确认原 plan_id + #[arg(help = text("arg.cancel_pending"))] #[arg(long, requires_all = ["yes", "plan_id"], conflicts_with = "dry_run")] cancel_pending: bool, } @@ -164,7 +224,7 @@ struct OperationArgs { struct SetupArgs { #[command(flatten)] operation: OperationArgs, - /// 无人值守时的精确目录模型;交互模式可从目录直接选择 + #[arg(help = text("arg.model_id"))] #[arg(long)] model_id: Option, #[arg(long, default_value = "LMM")] @@ -173,10 +233,10 @@ struct SetupArgs { no_browser: bool, #[arg(long, default_value_t = 180, value_parser = clap::value_parser!(u64).range(10..=600))] timeout: u64, - /// 仅添加 LMM,保留当前选择 + #[arg(help = text("arg.add_only"))] #[arg(long, conflicts_with = "activate")] add_only: bool, - /// 明确请求添加并切换到 LMM(不表示已执行) + #[arg(help = text("arg.activate"))] #[arg(long)] activate: bool, } @@ -185,20 +245,20 @@ struct SetupArgs { struct DoctorArgs { #[command(flatten)] target: TargetArgs, - /// 请求修复已获允许的 LMM 配置;不会绕过能力检查 + #[arg(help = text("arg.fix"))] #[arg(long)] fix: bool, - /// 生成可主动分享的摘要,去除路径和配置内容 - #[arg(long)] + #[arg(long, help = text("arg.report"))] report: bool, } #[derive(Args)] struct RequiredTarget { + #[arg(help = text("arg.software"))] software: String, #[command(flatten)] application: applications_cli::Scope, - #[arg(long)] + #[arg(long, help = text("arg.instance"))] instance: Option, #[arg(long)] managed_root: Option, @@ -221,7 +281,7 @@ struct Report { environment: Environment, targets: Vec, plans: Vec, - notes: Vec<&'static str>, + notes: Vec, #[serde(skip_serializing_if = "Option::is_none")] managed_installation: Option, #[serde(skip_serializing_if = "Option::is_none")] @@ -286,23 +346,22 @@ fn context() -> ProbeContext { } } -fn inspect(target: &TargetArgs, context: &ProbeContext) -> Result, String> { +fn inspect(target: &TargetArgs, context: &ProbeContext) -> Result, CliError> { if target.managed_root.is_some() && target.software.as_deref() != Some("cc-switch") { - return Err("--managed-root 当前只支持 CC Switch 的受管发行包".into()); + return Err(english("error.managed_target").into()); } if target .instance .as_ref() .is_some_and(|path| !path.is_absolute()) { - return Err("--instance 必须是当前环境的绝对本地路径;远程与容器适配器尚未提供".into()); + return Err(msg("error.invalid_instance").into()); } match target.software.as_deref() { Some(id) => { - let software = catalog::find(id) - .ok_or_else(|| "未知软件 ID;运行 lmm catalog 查看精确名称".to_owned())?; + let software = catalog::find(id).ok_or(msg("error.unknown_software"))?; if target.instance.is_some() && !matches!(id, "astrbot" | "cc-switch" | "pi") { - return Err("此软件尚未实现实例选择,不能忽略 --instance 后继续操作".into()); + return Err(msg("error.instance_unsupported").into()); } Ok(vec![discovery::discover( software, @@ -322,7 +381,7 @@ fn readonly_report( name: &'static str, target: &TargetArgs, context: &ProbeContext, -) -> Result { +) -> Result { let mut report = Report::new(name, inspect(target, context)?); let requested = target.pi.node.is_some() || target.pi.pi_package.is_some() || target.pi.agent_dir.is_some(); @@ -330,17 +389,14 @@ fn readonly_report( return Ok(report); } if target.software.as_deref() != Some("pi") { - return Err("Pi 路径参数只适用于明确选择的 pi 实例".into()); + return Err(english("error.pi_read_target").into()); } let (Some(project), Some(sdk), Some(agent)) = ( &target.instance, &target.pi.pi_package, &target.pi.agent_dir, ) else { - return Err( - "Pi 只读检查需要 --instance、--pi-package、--agent-dir 的绝对路径;不需要 --node" - .into(), - ); + return Err(english("error.pi_read_paths").into()); }; if ![project, sdk, agent].iter().all(|path| path.is_absolute()) || target @@ -349,7 +405,7 @@ fn readonly_report( .as_ref() .is_some_and(|path| !path.is_absolute()) { - return Err("Pi 路径必须是当前环境的绝对本地路径".into()); + return Err(english("error.pi_paths_absolute").into()); } let inspection = pi::status::inspect(project, sdk, agent); report.check_scope = "explicit_pi_settings_snapshot"; @@ -389,26 +445,25 @@ fn readonly_report( }); } } - report.notes.push("仅解析所选 Pi 1.2.0 设置中的已知包引用与默认选择,不输出配置值;不执行 Node 或 Pi,不读取凭据。"); - report.notes.push("两个设置文件分别读取;代码安装、项目信任、会话覆盖、配置管理归属及实际路由未验证。项目默认选择仅描述信任该项目设置时的覆盖规则。"); + report.notes.push(msg("note.pi_read_scope")); + report.notes.push(msg("note.pi_read_limits")); report.pi_settings = Some(inspection); Ok(report) } -fn select_software() -> Result { +fn select_software() -> Result { let mut output = io::stderr().lock(); - writeln!(output, "选择要规划接入的软件(当前均未完成集成验证):") - .map_err(|_| "无法显示选择菜单")?; + writeln!(output, "{}", msg("select.title")).map_err(|_| msg("error.menu_output"))?; for (i, software) in catalog::SOFTWARE.iter().enumerate() { writeln!(output, " {}. {} ({})", i + 1, software.name, software.id) - .map_err(|_| "无法显示选择菜单")?; + .map_err(|_| msg("error.menu_output"))?; } - write!(output, "输入序号,或直接回车取消:").map_err(|_| "无法显示选择菜单")?; - output.flush().map_err(|_| "无法显示选择菜单")?; + write!(output, "{}", msg("select.prompt")).map_err(|_| msg("error.menu_output"))?; + output.flush().map_err(|_| msg("error.menu_output"))?; let mut input = String::new(); io::stdin() .read_line(&mut input) - .map_err(|_| "无法读取选择")?; + .map_err(|_| msg("error.selection_input"))?; let index = input .trim() .parse::() @@ -417,7 +472,7 @@ fn select_software() -> Result { index .and_then(|index| catalog::SOFTWARE.get(index)) .map(|software| software.id.to_owned()) - .ok_or_else(|| "未选择目标;没有执行任何修改".to_owned()) + .ok_or_else(|| msg("error.no_selection").into()) } fn operation_report( @@ -426,14 +481,14 @@ fn operation_report( intent: Intent, interactive: bool, context: &ProbeContext, -) -> Result { +) -> Result { if args.application.supplied() || args.configuration { - return Err("此目标尚未提供独立应用配置适配器,不能忽略授权参数继续执行".into()); + return Err(english("error.application_adapter").into()); } let selected; let target = if args.target.software.is_none() && !args.all { if !interactive { - return Err("无人值守模式需要明确软件或 --all;没有执行任何修改".into()); + return Err(msg("error.target_required").into()); } selected = TargetArgs { software: Some(select_software()?), @@ -461,47 +516,41 @@ fn operation_report( let mut preview = Preview::blocked(target.software, intent); if name == "install" { preview.account = "not_required"; - preview.blockers = vec!["缺少经过验证的软件版本、下载来源校验及安装适配器"]; + preview.blockers = vec![msg("plan.install_adapter")]; } else if name == "restore" { preview.account = "not_required"; - preview.blockers = vec!["尚未接入目标的变更日志与原生事务适配器,不能直接覆盖备份"]; + preview.blockers = vec![msg("plan.restore_adapter")]; } report.plans.push(preview); } if args.all { - report.notes.push( - "当前版本没有经过验证的自动接入适配器,--all 没有可执行目标;未安装或修改任何软件", - ); + report.notes.push(msg("note.all_blocked")); } if args.dry_run { - report - .notes - .push("仅规划;阻塞项仍需解决,不能作为接入完成的证据"); + report.notes.push(msg("note.dry_run")); } if args.yes { - report.notes.push("--yes 不会跳过缺失能力、授权或费用限制"); + report.notes.push(msg("note.yes")); } if name == "install" { - report - .notes - .push("安装本身不需要 LMM 登录;当前缺少经过验证的安装适配器"); + report.notes.push(msg("note.install")); } Ok(report) } -fn write_json(value: &impl Serialize) -> Result<(), String> { +fn write_json(value: &impl Serialize) -> Result<(), CliError> { let mut output = io::stdout().lock(); - serde_json::to_writer_pretty(&mut output, value).map_err(|_| "无法输出 JSON".to_owned())?; - writeln!(output).map_err(|_| "无法输出 JSON".to_owned()) + serde_json::to_writer_pretty(&mut output, value).map_err(|_| msg("error.json_output"))?; + writeln!(output).map_err(|_| msg("error.json_output").into()) } -fn managed_manager(target: &TargetArgs) -> Result { +fn managed_manager(target: &TargetArgs) -> Result { if target .instance .as_ref() .is_some_and(|path| !path.is_absolute()) { - return Err("--instance 必须是绝对本地路径".into()); + return Err(english("error.absolute_instance").into()); } let database = target .instance @@ -510,18 +559,15 @@ fn managed_manager(target: &TargetArgs) -> Result { .map_or_else(managed::default_database, Ok) .map_err(|error| error.to_string())?; managed::Manager::for_current_environment(target.managed_root.clone(), Some(database)) - .map_err(|error| error.to_string()) + .map_err(|error| CliError::from(error.to_string())) } -fn managed_output(value: &impl Serialize, json: bool) -> Result<(), String> { +fn managed_output(value: &impl Serialize, json: bool) -> Result<(), CliError> { // Plans contain source, digest, exact scope and receipt IDs. The same // structured preview is available in terminals and unattended workflows. if !json { - writeln!( - io::stdout().lock(), - "CC Switch · LMM 受管发行包;应用配置与调用验证独立报告" - ) - .map_err(|_| "无法输出计划")?; + writeln!(io::stdout().lock(), "{}", msg("output.managed_heading")) + .map_err(|_| english("error.plan_output"))?; } write_json(value) } @@ -532,17 +578,15 @@ fn managed_operation( args: &OperationArgs, interactive: bool, json: bool, -) -> Result { +) -> Result { if args.application.supplied() || args.configuration { - return Err("程序生命周期不接收应用授权参数;恢复配置请用 restore --configuration".into()); + return Err(english("error.lifecycle_authorization").into()); } if action != ManagedAction::Restore && args.change.is_some() { - return Err("--change 只用于 restore".into()); + return Err(english("error.change_restore_only").into()); } if action == ManagedAction::Restore && args.change.is_none() { - return Err( - "restore 需要 --change 指定 status history 中的变更回执,不能覆盖整个备份".into(), - ); + return Err(english("error.restore_change").into()); } let manager = managed_manager(&args.target)?; if !args.dry_run @@ -611,7 +655,7 @@ fn managed_operation( managed_output( &serde_json::json!({ "schema_version":1,"command":name,"outcome":outcome,"managed_plan":plan, - "next_step":"确认计划后用相同参数加 --yes --plan-id ;--dry-run 不执行下载或修改" + "next_step":english("note.managed_next_step") }), json, )?; @@ -621,12 +665,16 @@ fn managed_operation( if !interactive || args.yes { return Ok(3); } - write!(io::stderr().lock(), "应用上面的精确计划?[y/N] ").map_err(|_| "无法请求确认")?; - io::stderr().lock().flush().map_err(|_| "无法请求确认")?; + write!(io::stderr().lock(), "{}", msg("select.managed_confirm")) + .map_err(|_| english("error.confirm_output"))?; + io::stderr() + .lock() + .flush() + .map_err(|_| english("error.confirm_output"))?; let mut answer = String::new(); io::stdin() .read_line(&mut answer) - .map_err(|_| "无法读取确认")?; + .map_err(|_| english("error.confirm_input"))?; if !matches!(answer.trim(), "y" | "Y" | "yes") { return Ok(3); } @@ -653,9 +701,11 @@ fn enrich_cc_switch(report: &mut Report, target: &TargetArgs) { return; } report.check_scope = "managed_distribution_and_explicit_native_database"; - match managed_manager(target) - .and_then(|manager| manager.status().map_err(|error| error.to_string())) - { + match managed_manager(target).and_then(|manager| { + manager + .status() + .map_err(|error| CliError::from(error.to_string())) + }) { Ok(status) => { if let Some(row) = report .targets @@ -672,7 +722,10 @@ fn enrich_cc_switch(report: &mut Report, target: &TargetArgs) { report.managed_installation = Some(status); } Err(error) => { - report.adapter_error = Some(error); + report.adapter_error = Some(match error { + CliError::Message(message) => english(message.key()).to_owned(), + CliError::Adapter(value) => value, + }); report.outcome = "incomplete"; } } @@ -696,108 +749,127 @@ fn enrich_cc_switch(report: &mut Report, target: &TargetArgs) { } } -fn emit(report: &Report, json: bool) -> Result<(), String> { +fn emit(report: &Report, json: bool) -> Result<(), CliError> { if json { return write_json(report); } let mut output = io::stdout().lock(); writeln!( output, - "LMM · {} · {} / {}", + "LMM - {} - {} / {}", report.command, report.environment.os, report.environment.arch ) - .map_err(|_| "无法输出结果")?; + .map_err(|_| msg("error.output"))?; writeln!( output, - "范围:当前用户、当前运行环境;检查时间:{}(Unix 秒)", - report.checked_at + "{}", + msg("output.scope").render(&[("time", &report.checked_at.to_string())]) ) - .map_err(|_| "无法输出结果")?; + .map_err(|_| msg("error.output"))?; for target in &report.targets { writeln!( output, - "\n{}:安装 {};安装管理者 {};配置管理者 {}", - target.software, - target.installation, - target.installation_manager, - target.configuration_manager + "{}", + msg("output.target").render(&[ + ("software", target.software), + ("installation", target.installation), + ("installation_manager", target.installation_manager), + ("configuration_manager", target.configuration_manager), + ]) ) - .map_err(|_| "无法输出结果")?; + .map_err(|_| msg("error.output"))?; for evidence in &target.evidence { - // Debug formatting escapes control characters in user-controlled paths. + // Debug formatting still escapes control characters in user-controlled paths. + let path = format!("{:?}", evidence.path); + let observation = evidence.observation.label(); writeln!( output, - " {:?}: {:?}(仅路径线索)", - evidence.path, evidence.observation + "{}", + msg("output.evidence") + .render(&[("path", &path), ("observation", observation.text())]) ) - .map_err(|_| "无法输出结果")?; + .map_err(|_| msg("error.output"))?; } if let Some(settings) = &report.pi_settings { writeln!( output, - " 设置中的 LMM 引用/选择:{} / {};默认模型:{}({})\n 配置检查:{};诊断:{}\n 授权、连通性、目标调用、流式及工具调用:未检查", - target.lmm_added, target.lmm_enabled, settings.default_model, - settings.model_scope, settings.configuration, settings.diagnostic, + "{}", + msg("output.pi_settings").render(&[ + ("added", target.lmm_added), + ("enabled", target.lmm_enabled), + ("model", settings.default_model), + ("scope", settings.model_scope), + ("configuration", settings.configuration), + ("diagnostic", settings.diagnostic), + ]) ) - .map_err(|_| "无法输出结果")?; + .map_err(|_| english("error.output"))?; } else { - writeln!( - output, - " LMM 添加/启用:未知;授权、连通性、目标调用、流式及工具调用:未检查" - ) - .map_err(|_| "无法输出结果")?; + writeln!(output, "{}", msg("output.verification")).map_err(|_| msg("error.output"))?; } } for plan in &report.plans { writeln!( output, - "\n{} 计划已阻止:无配置修改、无付费调用、无重启", - plan.software + "{}", + msg("output.blocked_plan").render(&[("software", plan.software)]) ) - .map_err(|_| "无法输出结果")?; + .map_err(|_| msg("error.output"))?; for blocker in &plan.blockers { - writeln!(output, " - {blocker}").map_err(|_| "无法输出结果")?; + writeln!(output, " - {blocker}").map_err(|_| msg("error.output"))?; } } for note in &report.notes { - writeln!(output, "\n{note}").map_err(|_| "无法输出结果")?; + writeln!(output, "\n{note}").map_err(|_| msg("error.output"))?; } if let Some(status) = &report.managed_installation { writeln!( output, - "\n受管发行包:{},文件校验 {},程序健康 {}", - status.installation, status.binary_integrity, status.application_health + "{}", + msg("output.managed_status").render(&[ + ("installation", status.installation), + ("integrity", status.binary_integrity), + ("health", status.application_health), + ]) ) - .map_err(|_| "无法输出受管状态")?; + .map_err(|_| english("error.managed_output"))?; for receipt in &status.history { writeln!( output, " {:?} · change_id={} · plan_id={}", receipt.action, receipt.change_id, receipt.plan_id ) - .map_err(|_| "无法输出变更回执")?; + .map_err(|_| english("error.receipt_output"))?; } } if let Some(status) = &report.cc_switch_database { writeln!( output, - "\nCC Switch schema {}:{} 个服务商记录;当前应用选择与实际路由尚未验证", - status.schema_version, - status.providers.len() + "{}", + msg("output.database_status").render(&[ + ("schema", &status.schema_version.to_string()), + ("providers", &status.providers.len().to_string()), + ]) ) - .map_err(|_| "无法输出数据库检查")?; + .map_err(|_| english("error.database_output"))?; } if let Some(error) = &report.adapter_error { - writeln!(output, "\n适配器:{error}").map_err(|_| "无法输出适配器结果")?; + writeln!( + output, + "{}", + msg("output.adapter").render(&[("error", localize(error))]) + ) + .map_err(|_| english("error.adapter_output"))?; } Ok(()) } -fn pi_failure(action: &str, error: &str, json: bool) -> Result, String> { +fn pi_failure(action: &str, error: &str, json: bool) -> Result, CliError> { if json { write_json(&serde_json::json!({"action":action,"outcome":"incomplete","error":error}))?; } else { - writeln!(io::stderr().lock(), "{error}").map_err(|_| "无法输出 Pi 执行结果")?; + writeln!(io::stderr().lock(), "{}", localize(error)) + .map_err(|_| english("error.pi_output"))?; } Ok(Some(3)) } @@ -806,17 +878,17 @@ fn validate_target_arguments( software: Option<&str>, managed_root: Option<&Path>, pi: &PiArgs, -) -> Result<(), String> { +) -> Result<(), CliError> { if pi.supplied() && software != Some("pi") { - return Err("Pi 路径参数只适用于明确选择的 pi 实例,不能被其他适配器忽略".into()); + return Err(english("error.pi_target").into()); } if managed_root.is_some() && software != Some("cc-switch") { - return Err("--managed-root 当前只支持 CC Switch 的受管发行包".into()); + return Err(english("error.managed_target").into()); } Ok(()) } -fn validate_operation_arguments(name: &str, args: &OperationArgs) -> Result<(), String> { +fn validate_operation_arguments(name: &str, args: &OperationArgs) -> Result<(), CliError> { validate_target_arguments( args.target.software.as_deref(), args.target.managed_root.as_deref(), @@ -831,16 +903,14 @@ fn validate_operation_arguments(name: &str, args: &OperationArgs) -> Result<(), || args.change.is_some() || args.cancel_pending) { - return Err( - "独立应用授权、配置恢复与受管回执参数只适用于 CC Switch,不能在其他目标上忽略".into(), - ); + return Err(english("error.managed_arguments").into()); } Ok(()) } // Adapter flags share command structs, but never an execution meaning. Validate // them before either adapter can touch a credential store, process or file. -fn validate_adapter_arguments(cli: &Cli) -> Result<(), String> { +fn validate_adapter_arguments(cli: &Cli) -> Result<(), CliError> { match &cli.command { Command::Status(target) => validate_target_arguments( target.software.as_deref(), @@ -860,7 +930,7 @@ fn validate_adapter_arguments(cli: &Cli) -> Result<(), String> { || args.no_browser || args.timeout != 180) { - return Err("应用模型选择和浏览器授权参数只适用于明确选择的 CC Switch 实例".into()); + return Err(english("error.application_arguments").into()); } Ok(()) } @@ -876,10 +946,10 @@ fn validate_adapter_arguments(cli: &Cli) -> Result<(), String> { &args.pi, )?; if args.software == "pi" && args.application.supplied() { - return Err("Pi 在目标应用内管理授权,不接受 CC Switch 的授权实例参数".into()); + return Err(english("error.pi_application_grant").into()); } if args.software != "pi" && (args.dry_run || args.yes) { - return Err("run/disconnect 的 --dry-run 和 --yes 当前只适用于 Pi,未执行其他目标的启动或撤销".into()); + return Err(english("error.pi_run_flags").into()); } Ok(()) } @@ -887,7 +957,7 @@ fn validate_adapter_arguments(cli: &Cli) -> Result<(), String> { } } -fn execute_pi(cli: &Cli) -> Result, String> { +fn execute_pi(cli: &Cli) -> Result, CliError> { let target_owned; let (action, target, dry_run, yes, activate) = match &cli.command { Command::Setup(args) => ( @@ -930,7 +1000,7 @@ fn execute_pi(cli: &Cli) -> Result, String> { return Ok(None); } if activate { - return Err("Pi 激活需要在目标 Pi 的 /login 和 /model 完成明确授权和选择;可先 --add-only 安装 Provider".into()); + return Err(english("error.pi_activation").into()); } let (Some(node), Some(sdk), Some(project), Some(agent_dir)) = ( &target.pi.node, @@ -942,10 +1012,7 @@ fn execute_pi(cli: &Cli) -> Result, String> { || target.pi.pi_package.is_some() || target.pi.agent_dir.is_some() { - return Err( - "Pi 适配器需要同时指定 --instance、--node、--pi-package、--agent-dir 的绝对路径" - .into(), - ); + return Err(english("error.pi_adapter_paths").into()); } return Ok(None); }; @@ -961,7 +1028,7 @@ fn execute_pi(cli: &Cli) -> Result, String> { || !io::stdin().is_terminal() || !io::stderr().is_terminal() { - return Err("Pi run 需要交互终端;不会在 JSON 或无人值守模式暗中启动应用".into()); + return Err(english("error.pi_run_interactive").into()); } return match target.run() { Ok(code) => Ok(Some(code)), @@ -982,13 +1049,13 @@ fn execute_pi(cli: &Cli) -> Result, String> { )) } -fn execute(cli: &Cli) -> Result { +fn execute(cli: &Cli) -> Result { validate_adapter_arguments(cli)?; if let Command::Credential(args) = &cli.command { if cli.non_interactive { - return Err("系统凭据库可能要求解锁;credential 不接受 --non-interactive".into()); + return Err(english("error.credential_unattended").into()); } - return applications_cli::credential(args, cli.json); + return applications_cli::credential(args, cli.json).map_err(Into::into); } let application_vault = match &cli.command { Command::Authorize(_) => true, @@ -998,10 +1065,7 @@ fn execute(cli: &Cli) -> Result { _ => false, }; if cli.non_interactive && application_vault { - return Err( - "系统凭据库可能需要解锁;这些应用命令暂不接受 --non-interactive,未访问凭据或网络" - .into(), - ); + return Err(english("error.application_unattended").into()); } if cli.non_interactive && matches!( @@ -1009,7 +1073,7 @@ fn execute(cli: &Cli) -> Result { Command::Login(_) | Command::Logout(_) | Command::Models(_) | Command::Balance(_) ) { - return Err("当前系统凭据库可能需要解锁交互;OAuth 命令尚不支持 --non-interactive,未访问凭据或网络".into()); + return Err(msg("error.auth_unattended").into()); } if let Some(code) = execute_pi(cli)? { return Ok(code); @@ -1022,26 +1086,26 @@ fn execute(cli: &Cli) -> Result { let report = match &cli.command { Command::Presets { query } => { let snapshot = provider::search(query.as_deref().unwrap_or_default()) - .map_err(|_| "内置服务商预设无法读取".to_owned())?; + .map_err(|_| msg("error.presets_read"))?; if cli.json { write_json(&snapshot)?; } else { let mut output = io::stdout().lock(); writeln!( output, - "内置服务商预设(Magpie 快照 {});配置与连通性未检查,未添加服务商。", - provider::UPSTREAM_REVISION + "{}", + msg("output.presets").render(&[("revision", provider::UPSTREAM_REVISION)]) ) - .map_err(|_| "无法输出服务商预设")?; + .map_err(|_| msg("error.presets_output"))?; for preset in &snapshot.presets { writeln!( output, "{} — {} ({})", preset.id, preset.name, - preset.kind.as_str() + preset.kind.label() ) - .map_err(|_| "无法输出服务商预设")?; + .map_err(|_| msg("error.presets_output"))?; } } return Ok(0); @@ -1053,7 +1117,20 @@ fn execute(cli: &Cli) -> Result { } else { let mut output = io::stdout().lock(); for software in entries { - writeln!(output, "{} — {}\n {}\n 来源:{}\n 安装:{:?};接入:{:?};维护:{:?};真实应用兼容场景:未验证\n", software.id, software.name, software.purpose, software.source, software.installation, software.integration, software.maintenance).map_err(|_| "无法输出目录")?; + writeln!( + output, + "{}", + msg("output.catalog_entry").render(&[ + ("id", software.id), + ("name", software.name), + ("purpose", software.purpose.text()), + ("source", software.source), + ("installation", &format!("{:?}", software.installation)), + ("integration", &format!("{:?}", software.integration)), + ("maintenance", &format!("{:?}", software.maintenance)), + ]) + ) + .map_err(|_| msg("error.catalog_output"))?; } } return Ok(0); @@ -1067,16 +1144,14 @@ fn execute(cli: &Cli) -> Result { let mut report = readonly_report("doctor", &args.target, &context)?; report.outcome = "incomplete"; report.notes.push(if report.pi_settings.is_some() { - "诊断未完成:只读设置检查不验证目标应用加载、授权、连通性或真实调用;没有执行网络或付费测试" + msg("note.pi_doctor_incomplete") } else { - "诊断未完成:仅检查本地路径线索;请核对目标实例、版本及配置管理关系。没有执行网络或付费测试" + msg("note.doctor_incomplete") }); enrich_cc_switch(&mut report, &args.target); if args.fix { report.outcome = "blocked"; - report - .notes - .push("当前没有经过验证的修复适配器;未修改配置"); + report.notes.push(msg("note.fix_blocked")); } if args.report { report.redact(); @@ -1084,10 +1159,14 @@ fn execute(cli: &Cli) -> Result { report } Command::Authorize(args) => { - return applications_cli::authorize(args, interactive, cli.json); + return applications_cli::authorize(args, interactive, cli.json).map_err(Into::into); + } + Command::Receipt(args) => { + return applications_cli::receipt(args, interactive, cli.json).map_err(Into::into); + } + Command::Credential(args) => { + return applications_cli::credential(args, cli.json).map_err(Into::into); } - Command::Receipt(args) => return applications_cli::receipt(args, interactive, cli.json), - Command::Credential(args) => return applications_cli::credential(args, cli.json), Command::Setup(args) => { if args.operation.target.software.as_deref() == Some("cc-switch") { return applications_cli::operation( @@ -1096,7 +1175,8 @@ fn execute(cli: &Cli) -> Result { Some(args), interactive, cli.json, - ); + ) + .map_err(Into::into); } operation_report( "setup", @@ -1126,7 +1206,8 @@ fn execute(cli: &Cli) -> Result { } Command::Sync(args) => { if args.target.software.as_deref() == Some("cc-switch") { - return applications_cli::operation("sync", args, None, interactive, cli.json); + return applications_cli::operation("sync", args, None, interactive, cli.json) + .map_err(Into::into); } operation_report("sync", args, Intent::Maintain, interactive, &context)? } @@ -1144,7 +1225,8 @@ fn execute(cli: &Cli) -> Result { } Command::Restore(args) => { if args.target.software.as_deref() == Some("cc-switch") && args.configuration { - return applications_cli::operation("restore", args, None, interactive, cli.json); + return applications_cli::operation("restore", args, None, interactive, cli.json) + .map_err(Into::into); } if args.target.software.as_deref() == Some("cc-switch") { return managed_operation( @@ -1171,7 +1253,7 @@ fn execute(cli: &Cli) -> Result { } Command::Login(args) => { if !interactive { - return Err("登录需要浏览器授权;请在交互终端运行 lmm login。无人值守模式不会等待或代替用户同意".into()); + return Err(msg("error.login_interactive").into()); } let result = oauth::login( &args.auth.issuer, @@ -1180,11 +1262,12 @@ fn execute(cli: &Cli) -> Result { let mut output = io::stderr().lock(); writeln!( output, - "请在浏览器确认 LMM CLI 授权(仅目录和余额读取,不迁移任何应用):\n{url}" + "{}", + msg("output.authorization_url").render(&[("url", url)]) ) .map_err(|_| oauth::AuthError::Output)?; if !args.no_browser && open::that_detached(url).is_err() { - writeln!(output, "浏览器未能自动打开,请在本机浏览器打开上述链接。") + writeln!(output, "{}", msg("output.browser_failed")) .map_err(|_| oauth::AuthError::Output)?; } Ok(()) @@ -1195,8 +1278,8 @@ fn execute(cli: &Cli) -> Result { if cli.json { write_json(&status)?; } else { - writeln!(io::stdout().lock(), "LMM CLI 已登录,凭据已保存到系统凭据库。尚未授予应用调用权限;可运行 lmm models。") - .map_err(|_| "无法输出登录结果")?; + writeln!(io::stdout().lock(), "{}", msg("output.login")) + .map_err(|_| msg("error.login_output"))?; } Ok(0) } @@ -1211,11 +1294,8 @@ fn execute(cli: &Cli) -> Result { &serde_json::json!({"outcome": outcome, "applications_changed": false, "other_application_grants": "not_checked"}), )?; } else { - writeln!( - io::stdout().lock(), - "CLI 已退出;其他应用授权未撤销,当前版本尚不能列出这些授权。" - ) - .map_err(|_| "无法输出退出结果")?; + writeln!(io::stdout().lock(), "{}", msg("output.logout")) + .map_err(|_| msg("error.logout_output"))?; } Ok(0) } @@ -1230,12 +1310,14 @@ fn execute(cli: &Cli) -> Result { } else { writeln!( io::stdout().lock(), - "余额:{} USD({} 积分;每美元 {} 积分)", - balance.balance, - balance.public_credit_balance, - balance.credits_per_usd + "{}", + msg("output.balance").render(&[ + ("dollars", &balance.balance.to_string()), + ("credits", &balance.public_credit_balance.to_string()), + ("rate", &balance.credits_per_usd.to_string()), + ]) ) - .map_err(|_| "无法输出余额")?; + .map_err(|_| english("error.balance_output"))?; } Ok(0) } @@ -1249,14 +1331,37 @@ fn execute(cli: &Cli) -> Result { write_json(&catalog)?; } else { let mut output = io::stdout().lock(); - writeln!( - output, - "当前授权模型(不代表目标软件兼容;价格可能随使用变化):" - ) - .map_err(|_| "无法输出模型")?; + writeln!(output, "{}", msg("output.models")) + .map_err(|_| msg("error.models_output"))?; for model in &catalog.models { - writeln!(output, "{:?} · {:?} · {:?}\n 价格单位:{:?} / {:?};输入:{:?},输出:{:?},每次请求:{:?};依据:{:?}\n null/None 表示未知;未调用或切换模型。", model.id, model.upstream_model, model.group, model.pricing.currency, model.pricing.unit, model.pricing.input, model.pricing.output, model.pricing.request, model.pricing.price_basis).map_err(|_| "无法输出模型")?; - writeln!(output, " 元数据:{:?}\n 缓存读取/写入:{:?} / {:?};分组/信任倍率:{:?} / {:?}(价格已含倍率)", model.metadata, model.pricing.cache_read, model.pricing.cache_write, model.pricing.group_multiplier, model.pricing.trust_multiplier).map_err(|_| "无法输出模型")?; + writeln!( + output, + "{}", + msg("output.model_entry").render(&[ + ("id", &format!("{:?}", model.id)), + ("upstream", &format!("{:?}", model.upstream_model)), + ("group", &format!("{:?}", model.group)), + ("currency", &format!("{:?}", model.pricing.currency)), + ("unit", &format!("{:?}", model.pricing.unit)), + ("input", &format!("{:?}", model.pricing.input)), + ("output", &format!("{:?}", model.pricing.output)), + ("request", &format!("{:?}", model.pricing.request)), + ("basis", &format!("{:?}", model.pricing.price_basis)), + ]) + ) + .map_err(|_| msg("error.models_output"))?; + writeln!( + output, + "{}", + msg("output.model_metadata").render(&[ + ("metadata", &format!("{:?}", model.metadata)), + ("cache_read", &format!("{:?}", model.pricing.cache_read)), + ("cache_write", &format!("{:?}", model.pricing.cache_write)), + ("group", &format!("{:?}", model.pricing.group_multiplier)), + ("trust", &format!("{:?}", model.pricing.trust_multiplier)), + ]) + ) + .map_err(|_| english("error.models_output"))?; } } Ok(0) @@ -1266,10 +1371,11 @@ fn execute(cli: &Cli) -> Result { } Command::Disconnect(args) | Command::Run(args) => { if matches!(&cli.command, Command::Disconnect(_)) && args.software == "cc-switch" { - return applications_cli::disconnect(args, interactive, cli.json); + return applications_cli::disconnect(args, interactive, cli.json) + .map_err(Into::into); } if args.application.supplied() { - return Err("此操作不支持应用授权参数".into()); + return Err(english("error.application_flags_unsupported").into()); } let name = match &cli.command { Command::Disconnect(_) => "disconnect", @@ -1287,10 +1393,7 @@ fn execute(cli: &Cli) -> Result { }; if name == "run" && args.software == "cc-switch" { if args.instance.is_some() { - return Err( - "CC Switch 使用其原生实例设置启动;此版本不能用 --instance 改写其启动配置" - .into(), - ); + return Err(english("error.cc_switch_launch_instance").into()); } let manager = managed_manager(&target)?; return match manager.launch() { @@ -1312,9 +1415,7 @@ fn execute(cli: &Cli) -> Result { } let mut report = Report::new(name, inspect(&target, &context)?); report.outcome = "blocked"; - report - .notes - .push("未实现该目标的安全执行适配器;未启动或卸载软件,未修改配置或撤销授权"); + report.notes.push(msg("note.execution_blocked")); report } }; @@ -1326,10 +1427,10 @@ fn execute(cli: &Cli) -> Result { }) } -fn auth_failure(error: oauth::AuthError, json: bool) -> Result { +fn auth_failure(error: oauth::AuthError, json: bool) -> Result { if json { write_json( - &serde_json::json!({"schema_version":1,"outcome":"blocked","error":error.to_string()}), + &serde_json::json!({"schema_version":1,"outcome":"blocked","error":error.message(),"error_code":error.message().key()}), )?; } else { eprintln!("lmm: {error}"); @@ -1337,14 +1438,43 @@ fn auth_failure(error: oauth::AuthError, json: bool) -> Result { Ok(3) } +fn localized_help(mut command: clap::Command) -> clap::Command { + command.build(); + if command.get_name() == "help" { + command = command.about(text("cmd.help")); + } + command + .help_template(text("help.template")) + .subcommand_help_heading(text("help.commands")) + .mut_args(|arg| { + let heading = if arg.is_positional() { + text("help.arguments") + } else { + text("help.options") + }; + let arg = match arg.get_id().as_str() { + "help" => arg.help(text("help.help")), + "version" => arg.help(text("help.version")), + _ => arg, + }; + arg.help_heading(heading) + }) + .mut_subcommands(localized_help) +} + fn main() -> ExitCode { - let cli = Cli::parse(); + let args: Vec<_> = env::args_os().collect(); + let selected = Locale::detect(&args, |key| env::var_os(key)); + let _ = i18n::initialize(selected); + let matches = localized_help(Cli::command()).get_matches_from(args); + let cli = Cli::from_arg_matches(&matches).unwrap_or_else(|error| error.exit()); + debug_assert!(cli.lang.is_none_or(|locale| locale == selected)); match execute(&cli) { Ok(code) => ExitCode::from(code), Err(error) => { if cli.json && !matches!(&cli.command, Command::Credential(_)) { let _ = write_json( - &serde_json::json!({"schema_version": 1, "outcome": "invalid_request", "error": error}), + &serde_json::json!({"schema_version": 1, "outcome": "invalid_request", "error": error, "error_code": error.key()}), ); } else { eprintln!("lmm: {error}"); diff --git a/src/managed.rs b/src/managed.rs index 89a9f55..ca961fe 100644 --- a/src/managed.rs +++ b/src/managed.rs @@ -24,39 +24,39 @@ const MAX_EVENTS: usize = 128; /// Typed refusal or incomplete operation. No response includes secret content. #[derive(Debug, thiserror::Error)] pub enum ManagedError { - #[error("此受管安装适配器仅支持 Linux x86_64 和 aarch64")] + #[error("{}", crate::i18n::english("managed.platform"))] UnsupportedPlatform, - #[error("受管目录必须是绝对、私有且不经过符号链接的路径")] + #[error("{}", crate::i18n::english("managed.path"))] UnsafePath, - #[error("该目录不是 LMM 创建的受管安装,不能接管或删除")] + #[error("{}", crate::i18n::english("managed.ownership"))] NotOwned, - #[error("受管安装日志损坏或版本未知,未执行变更")] + #[error("{}", crate::i18n::english("managed.state"))] InvalidState, - #[error("另一个 LMM 操作正在处理此安装,请稍后重试原计划")] + #[error("{}", crate::i18n::english("managed.busy"))] Busy, - #[error("安装状态已在预览之后改变,请重新查看计划")] + #[error("{}", crate::i18n::english("managed.conflict"))] Conflict, - #[error("受管程序被后续修改,已保留文件;不能覆盖、执行或删除")] + #[error("{}", crate::i18n::english("managed.modified"))] ModifiedArtifact, - #[error("尚无受管安装;不能把 PATH 中的程序当作 LMM 安装")] + #[error("{}", crate::i18n::english("managed.missing"))] NotInstalled, - #[error("找不到该变更回执,或后续变更与恢复目标冲突")] + #[error("{}", crate::i18n::english("managed.change"))] UnknownChange, - #[error("存在未完成操作;请使用原计划 ID 恢复同一操作")] + #[error("{}", crate::i18n::english("managed.pending"))] Pending, - #[error("此更新会降低版本,请使用明确变更回执的恢复流程")] + #[error("{}", crate::i18n::english("managed.downgrade"))] Downgrade, - #[error("本机数据库版本不适合目标程序;没有覆盖或回退用户数据")] + #[error("{}", crate::i18n::english("managed.database"))] DatabaseCompatibility, - #[error("下载失败;变更尚未提交,使用原计划 ID 可继续或取消")] + #[error("{}", crate::i18n::english("managed.download"))] Download, - #[error("下载长度或 SHA-256 不符合固定官方发布记录")] + #[error("{}", crate::i18n::english("managed.integrity"))] Integrity, - #[error("无法持久保存或读取安装日志;请查看状态并用原计划 ID 查回执")] + #[error("{}", crate::i18n::english("managed.storage"))] Storage, - #[error("无法启动已校验程序;请确认图形会话、FUSE 和运行依赖")] + #[error("{}", crate::i18n::english("managed.launch"))] Launch, - #[error("操作已移除部分受管文件,必须用原计划完成,不能宣称已取消")] + #[error("{}", crate::i18n::english("managed.cancel"))] CannotCancel, } diff --git a/src/oauth.rs b/src/oauth.rs index c7d0fa6..4491d60 100644 --- a/src/oauth.rs +++ b/src/oauth.rs @@ -10,6 +10,7 @@ mod storage; #[cfg(test)] mod tests; +use crate::i18n::{Message, msg}; use protocol::{Credential, TokenResponse}; use reqwest::blocking::Client; use serde::{Deserialize, Serialize}; @@ -18,7 +19,6 @@ use std::{ time::{Duration, SystemTime, UNIX_EPOCH}, }; use storage::{SecretStore, StoredSession, SystemStore}; -use thiserror::Error; use zeroize::Zeroizing; /// Default trusted deployment issuer; never taken from HTTP redirects. @@ -27,40 +27,54 @@ const CLIENT_ID: &str = "lmm"; const SCOPE: &str = "catalog:read balance:read"; /// Errors contain fixed messages only: never HTTP bodies, URLs or credentials. -#[derive(Debug, Error, PartialEq, Eq)] +#[derive(Debug, PartialEq, Eq)] pub enum AuthError { - #[error("issuer 必须是规范的 HTTPS 域名 origin,不含端口、路径、查询或凭据")] InvalidIssuer, - #[error("LMM 网络请求失败;请检查网络和服务端是否已启用 lmm 客户端")] Network, - #[error("LMM OAuth 响应不符合约定,已停止授权")] InvalidResponse, - #[error("授权已取消或被拒绝")] Denied, - #[error("登录等待超时;没有继续发起请求")] Timeout, - #[error("无法绑定本机 OAuth 回调端口")] Callback, - #[error( - "无法访问系统凭据库;请解锁 Keychain、Credential Manager 或 Secret Service,不会回退到明文文件" - )] CredentialStore, - #[error("尚未登录;请先运行 lmm login")] NotLoggedIn, - #[error("已有 CLI 登录;切换账号请先 lmm logout,不会迁移应用授权")] AlreadyLoggedIn, - #[error("上次刷新未可靠完成;不会重放旧刷新令牌,请先 logout 再 login")] RefreshBlocked, - #[error("另一项 LMM 授权操作正在运行,或无法建立当前用户的安全锁")] Busy, - #[error("服务端返回未授权;请重新登录,或检查 lmm 客户端是否已部署")] Unauthorized, - #[error("新授权未能保存,且无法确认已撤销;请在 LMM 授权页检查 LMM CLI 授权")] UnstoredGrant, - #[error("无法输出登录入口;登录已停止")] Output, } +impl AuthError { + /// A fixed, non-sensitive description with a stable machine-readable key. + pub const fn message(&self) -> Message { + msg(match self { + Self::InvalidIssuer => "auth.invalid_issuer", + Self::Network => "auth.network", + Self::InvalidResponse => "auth.invalid_response", + Self::Denied => "auth.denied", + Self::Timeout => "auth.timeout", + Self::Callback => "auth.callback", + Self::CredentialStore => "auth.credential_store", + Self::NotLoggedIn => "auth.not_logged_in", + Self::AlreadyLoggedIn => "auth.already_logged_in", + Self::RefreshBlocked => "auth.refresh_blocked", + Self::Busy => "auth.busy", + Self::Unauthorized => "auth.unauthorized", + Self::UnstoredGrant => "auth.unstored_grant", + Self::Output => "auth.output", + }) + } +} + +impl std::fmt::Display for AuthError { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + std::fmt::Display::fmt(&self.message(), formatter) + } +} + +impl std::error::Error for AuthError {} + /// Login information deliberately excludes tokens, account secrets and scopes with group IDs. #[derive(Debug, Serialize)] pub struct LoginStatus { diff --git a/src/oauth/applications.rs b/src/oauth/applications.rs index a49f3c6..9e4496e 100644 --- a/src/oauth/applications.rs +++ b/src/oauth/applications.rs @@ -20,29 +20,29 @@ const RECOVERY_SECONDS: u64 = 600; #[derive(Debug, thiserror::Error, Eq, PartialEq)] pub enum ApplicationError { - #[error("应用实例、issuer 或授权格式无效")] + #[error("{}", crate::i18n::english("application.invalid"))] Invalid, - #[error("服务端尚未启用具有可恢复续期能力的 CC Switch 独立授权")] + #[error("{}", crate::i18n::english("application.unavailable"))] Unavailable, - #[error("应用授权未完成、已失效或不包含所需权限")] + #[error("{}", crate::i18n::english("application.unauthorized"))] Unauthorized, - #[error("该实例已有独立授权;必须先明确解除旧授权才能更换")] + #[error("{}", crate::i18n::english("application.existing"))] AlreadyAuthorized, - #[error("系统凭据库不可用;不会把 OAuth 凭据存入普通文件")] + #[error("{}", crate::i18n::english("application.vault"))] CredentialStore, - #[error("应用授权请求未获得可靠响应;尚未确认操作完成")] + #[error("{}", crate::i18n::english("application.network"))] Network, - #[error("原续期操作超过恢复窗口;请撤销旧授权后重新征得同意")] + #[error("{}", crate::i18n::english("application.expired"))] RecoveryExpired, - #[error("另一项本机授权操作正在运行")] + #[error("{}", crate::i18n::english("application.busy"))] Busy, - #[error("浏览器授权未完成;未配置目标软件")] + #[error("{}", crate::i18n::english("application.browser"))] Browser, - #[error("新应用授权未能保存,且撤销结果未知;请在 LMM 授权页撤销此 CC Switch 实例")] + #[error("{}", crate::i18n::english("application.unstored"))] UnstoredGrant, - #[error("应用授权码交换结果未知;未配置软件,请在 LMM 授权页检查此 CC Switch 实例")] + #[error("{}", crate::i18n::english("application.unknown"))] AuthorizationUnknown, - #[error("无法向 Codex 凭据管道写入结果")] + #[error("{}", crate::i18n::english("application.output"))] CredentialOutput, } impl From for ApplicationError { diff --git a/src/oauth/callback.rs b/src/oauth/callback.rs index 0e671f8..9f3422e 100644 --- a/src/oauth/callback.rs +++ b/src/oauth/callback.rs @@ -1,4 +1,5 @@ use super::AuthError; +use crate::i18n::text; use std::{ collections::BTreeMap, io::{Read, Write}, @@ -48,9 +49,9 @@ impl Callback { } let result = read_request(&mut stream, &host, issuer, state, remaining); let body = if result.is_ok() { - "Authorization received. Return to LMM CLI to check completion." + text("callback.received") } else { - "Invalid or denied authorization. Return to LMM CLI." + text("callback.invalid") }; let status = if result.is_ok() { "200 OK" diff --git a/src/pi.rs b/src/pi.rs index 2fb1fa8..4d2e81d 100644 --- a/src/pi.rs +++ b/src/pi.rs @@ -2,6 +2,7 @@ //! OAuth stays in Pi; this adapter never reads, copies or grants credentials. pub mod status; +use crate::i18n::english; use fs2::FileExt; use serde::{Deserialize, Serialize}; use std::{ @@ -14,8 +15,9 @@ use std::{ pub const SOURCE: &str = "git:github.com/TokenNotIncluded/pi-lmm-provider@f0c54764eb3d73e50790346f0dbab834587fe27b"; const BRIDGE: &str = include_str!("pi-bridge.mjs"); -const ERROR: &str = - "Pi 接入未完成;请检查显式路径、Pi 1.2.0、配置冲突或待恢复日志。未读取或复制应用凭据"; +fn failure() -> &'static str { + english("pi.incomplete") +} #[derive(Debug)] pub struct Target<'a> { @@ -48,16 +50,16 @@ pub struct Outcome { impl Target<'_> { fn validate(&self) -> Result<(), String> { if !cfg!(target_os = "linux") { - return Err("Pi 原生写入适配器目前仅验证 Linux;当前平台尚未开放".into()); + return Err(english("pi.platform").into()); } for path in [self.node, self.sdk, self.project, self.agent_dir] { if !path.is_absolute() || fs::symlink_metadata(path) - .map_err(|_| ERROR)? + .map_err(|_| failure())? .file_type() .is_symlink() { - return Err(ERROR.into()); + return Err(failure().into()); } } if !self.node.is_file() @@ -65,35 +67,36 @@ impl Target<'_> { .iter() .all(|p| p.is_dir()) { - return Err(ERROR.into()); + return Err(failure().into()); } - let manifest: serde_json::Value = - serde_json::from_slice(&fs::read(self.sdk.join("package.json")).map_err(|_| ERROR)?) - .map_err(|_| ERROR)?; + let manifest: serde_json::Value = serde_json::from_slice( + &fs::read(self.sdk.join("package.json")).map_err(|_| failure())?, + ) + .map_err(|_| failure())?; if manifest["name"] != "@earendil-works/pi-coding-agent" || manifest["version"] != "1.2.0" { - return Err(ERROR.into()); + return Err(failure().into()); } let version = Command::new(self.node) .arg("--version") .output() - .map_err(|_| ERROR)?; - let text = std::str::from_utf8(&version.stdout).map_err(|_| ERROR)?; + .map_err(|_| failure())?; + let text = std::str::from_utf8(&version.stdout).map_err(|_| failure())?; let parts: Vec<_> = text .trim() .strip_prefix('v') - .ok_or(ERROR)? + .ok_or(failure())? .split('.') .collect(); let major = parts .first() .and_then(|value| value.parse::().ok()) - .ok_or(ERROR)?; + .ok_or(failure())?; let minor = parts .get(1) .and_then(|value| value.parse::().ok()) - .ok_or(ERROR)?; + .ok_or(failure())?; if !version.status.success() || major < 22 || (major == 22 && minor < 19) { - return Err(ERROR.into()); + return Err(failure().into()); } Ok(()) } @@ -105,20 +108,20 @@ impl Target<'_> { .stdout(Stdio::piped()) .stderr(Stdio::null()) .spawn() - .map_err(|_| ERROR)?; + .map_err(|_| failure())?; let request = serde_json::json!({"sdk":self.sdk,"cwd":self.project,"agentDir":self.agent_dir,"source":SOURCE,"action":action}); - let input = serde_json::to_vec(&request).map_err(|_| ERROR)?; + let input = serde_json::to_vec(&request).map_err(|_| failure())?; child .stdin .take() - .ok_or(ERROR)? + .ok_or(failure())? .write_all(&input) - .map_err(|_| ERROR)?; - let output = child.wait_with_output().map_err(|_| ERROR)?; + .map_err(|_| failure())?; + let output = child.wait_with_output().map_err(|_| failure())?; if !output.status.success() || output.stdout.len() > 64 * 1024 { - return Err(ERROR.into()); + return Err(failure().into()); } - serde_json::from_slice(&output.stdout).map_err(|_| ERROR.into()) + serde_json::from_slice(&output.stdout).map_err(|_| failure().into()) } fn journal(&self) -> PathBuf { self.project.join(".pi/lmm-owned.json") @@ -128,12 +131,12 @@ impl Target<'_> { match fs::symlink_metadata(&path) { Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None), Ok(meta) if meta.is_file() && !meta.file_type().is_symlink() && meta.len() <= 4096 => {} - _ => return Err(ERROR.into()), + _ => return Err(failure().into()), } - let receipt: Receipt = - serde_json::from_slice(&fs::read(path).map_err(|_| ERROR)?).map_err(|_| ERROR)?; + let receipt: Receipt = serde_json::from_slice(&fs::read(path).map_err(|_| failure())?) + .map_err(|_| failure())?; if receipt.version != 1 || receipt.source != SOURCE { - return Err(ERROR.into()); + return Err(failure().into()); } Ok(Some(receipt)) } @@ -147,7 +150,7 @@ impl Target<'_> { use std::os::unix::fs::OpenOptionsExt; opts.mode(0o600); } - let mut file = opts.open(&temp).map_err(|_| ERROR)?; + let mut file = opts.open(&temp).map_err(|_| failure())?; let result = (|| { serde_json::to_writer( &mut file, @@ -157,12 +160,12 @@ impl Target<'_> { phase: phase.into(), }, ) - .map_err(|_| ERROR)?; - file.sync_all().map_err(|_| ERROR)?; - fs::rename(&temp, &path).map_err(|_| ERROR)?; - File::open(path.parent().ok_or(ERROR)?) + .map_err(|_| failure())?; + file.sync_all().map_err(|_| failure())?; + fs::rename(&temp, &path).map_err(|_| failure())?; + File::open(path.parent().ok_or(failure())?) .and_then(|dir| dir.sync_all()) - .map_err(|_| ERROR)?; + .map_err(|_| failure())?; Ok(()) })(); if result.is_err() { @@ -173,14 +176,14 @@ impl Target<'_> { pub fn run(&self) -> Result { self.validate()?; if self.native("inspect")?["installed"] != true { - return Err(ERROR.into()); + return Err(failure().into()); } let status = Command::new(self.node) .arg(self.sdk.join("dist/bundle/cli.js")) .current_dir(self.project) .env("PI_CODING_AGENT_DIR", self.agent_dir) .status() - .map_err(|_| ERROR)?; + .map_err(|_| failure())?; Ok(status .code() .and_then(|code| u8::try_from(code).ok()) @@ -197,34 +200,34 @@ impl Target<'_> { authorization: "not_checked_use_pi_login", activation: "preserved", paid_call: false, - notes: "仅管理所选项目中的固定 LMM Provider;Pi 本体、其他插件、凭据和默认模型保持用户管理。安装后在 Pi /login 选择 LMM,再用 /model 明确选择模型。", + notes: english("pi.scope"), }; if dry_run { return Ok(result); } if action == "sync" { if self.native("inspect")?["installed"] != true { - return Err(ERROR.into()); + return Err(failure().into()); } result.state = "provider_present_catalog_refresh_pending"; return Ok(result); } if !yes { - return Err("请先用 --dry-run 查看固定来源和实例,再用 --yes 确认该范围".into()); + return Err(english("pi.confirm").into()); } let directory = self.project.join(".pi"); if directory.exists() && fs::symlink_metadata(&directory) - .map_err(|_| ERROR)? + .map_err(|_| failure())? .file_type() .is_symlink() { - return Err(ERROR.into()); + return Err(failure().into()); } if matches!(action, "restore" | "disconnect") && self.receipt()?.is_none() { - return Err(ERROR.into()); + return Err(failure().into()); } - fs::create_dir_all(&directory).map_err(|_| ERROR)?; + fs::create_dir_all(&directory).map_err(|_| failure())?; // Pi 1.2.0 reads an absent settings file before acquiring its first lock. // Create exclusively first, so all native mutations read under an existing-file lock. let settings_path = directory.join("settings.json"); @@ -237,22 +240,22 @@ impl Target<'_> { } match settings_options.open(&settings_path) { Ok(mut file) => { - file.write_all(b"{}\n").map_err(|_| ERROR)?; - file.sync_all().map_err(|_| ERROR)?; + file.write_all(b"{}\n").map_err(|_| failure())?; + file.sync_all().map_err(|_| failure())?; } Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => { - let metadata = fs::symlink_metadata(&settings_path).map_err(|_| ERROR)?; + let metadata = fs::symlink_metadata(&settings_path).map_err(|_| failure())?; if !metadata.is_file() || metadata.file_type().is_symlink() { - return Err(ERROR.into()); + return Err(failure().into()); } } - Err(_) => return Err(ERROR.into()), + Err(_) => return Err(failure().into()), } let lock_path = directory.join("lmm-adapter.lock"); if fs::symlink_metadata(&lock_path) .is_ok_and(|m| !m.is_file() || m.file_type().is_symlink()) { - return Err(ERROR.into()); + return Err(failure().into()); } let mut options = OpenOptions::new(); options.read(true).write(true).create(true).truncate(false); @@ -261,8 +264,8 @@ impl Target<'_> { use std::os::unix::fs::OpenOptionsExt; options.mode(0o600); } - let lock = options.open(lock_path).map_err(|_| ERROR)?; - lock.try_lock_exclusive().map_err(|_| ERROR)?; + let lock = options.open(lock_path).map_err(|_| failure())?; + lock.try_lock_exclusive().map_err(|_| failure())?; let receipt = self.receipt()?; match action { "setup" | "install" | "update" => { @@ -270,19 +273,19 @@ impl Target<'_> { .as_ref() .is_some_and(|r| r.phase != "installed" && r.phase != "restored") { - return Err(ERROR.into()); + return Err(failure().into()); } let current = self.native("inspect")?; if current["conflicting"] != false || (current["configured"] == true && current["installed"] != true) { - return Err(ERROR.into()); + return Err(failure().into()); } if action == "update" && (receipt.as_ref().is_none_or(|r| r.phase != "installed") || current["installed"] != true) { - return Err(ERROR.into()); + return Err(failure().into()); } if current["installed"] == true { result.state = "already_present"; @@ -291,10 +294,10 @@ impl Target<'_> { self.save("pending_add")?; let added = self.native("add")?; if added["added"] != true { - return Err(ERROR.into()); + return Err(failure().into()); } if self.native("inspect")?["installed"] != true { - return Err(ERROR.into()); + return Err(failure().into()); } self.save("installed")?; result.state = "provider_added_authorization_pending"; @@ -306,23 +309,23 @@ impl Target<'_> { result.state = "already_restored"; return Ok(result); } - _ => return Err(ERROR.into()), + _ => return Err(failure().into()), } self.save("pending_remove")?; self.native("remove")?; if self.native("inspect")?["configured"] != false { - return Err(ERROR.into()); + return Err(failure().into()); } self.save("restored")?; result.state = "provider_detached_credentials_unchanged"; } "sync" => { if self.native("inspect")?["installed"] != true { - return Err(ERROR.into()); + return Err(failure().into()); } result.state = "provider_present_catalog_refresh_pending"; } - _ => return Err(ERROR.into()), + _ => return Err(failure().into()), } Ok(result) } diff --git a/src/plan.rs b/src/plan.rs index 76e4cce..4668353 100644 --- a/src/plan.rs +++ b/src/plan.rs @@ -1,5 +1,6 @@ //! Policy decisions shared by future adapters; discovery never authorizes a write. +use crate::i18n::{Message, msg}; use serde::Serialize; use thiserror::Error; @@ -43,13 +44,13 @@ pub enum Activation { #[derive(Debug, Error, PartialEq, Eq)] pub enum PlanError { /// Unknown state must not be silently replaced with defaults. - #[error("无法确认当前服务商;需要先读取选定实例的实际配置")] + #[error("{}", msg("plan.unknown_selection"))] UnknownSelection, /// A revoked application must not be silently granted permission again. - #[error("应用授权已撤销;需要明确确认重新授权")] + #[error("{}", msg("plan.revoked_grant"))] RevokedGrant, /// Cost checks must use a server-enforced reservation. - #[error("付费验证需要明确同意、已知报价和服务端可执行的消费上限")] + #[error("{}", msg("plan.paid_verification"))] PaidVerificationNotAuthorized, } @@ -110,7 +111,7 @@ pub struct Preview { /// No discovered service is restarted. pub restart: bool, /// Specific missing prerequisites. - pub blockers: Vec<&'static str>, + pub blockers: Vec, } impl Preview { @@ -130,9 +131,9 @@ impl Preview { paid_test: false, restart: false, blockers: vec![ - "此版本尚无经过验证的目标软件写入适配器", - "CLI 登录只允许读取目录和余额;目标应用独立授权尚未接入", - "未验证软件版本、配置管理关系及实际调用路径", + msg("plan.write_adapter"), + msg("plan.application_grant"), + msg("plan.unverified_target"), ], } } diff --git a/src/provider.rs b/src/provider.rs index 742429a..4033323 100644 --- a/src/provider.rs +++ b/src/provider.rs @@ -1,6 +1,7 @@ //! Read-only built-in provider presets ported from Magpie's MIT data. //! No provider configuration, credentials, or network requests are accessed. +use crate::i18n::{Locale, Message, msg}; use serde::{Deserialize, Serialize}; use serde_json::{Map, Value}; @@ -17,6 +18,16 @@ pub enum Kind { } impl Kind { + /// Localized category label; as_str and serialized values stay stable. + pub const fn label(self) -> Message { + msg(match self { + Self::Vendor => "kind.vendor", + Self::Relay => "kind.relay", + Self::Local => "kind.local", + Self::Remote => "kind.remote", + }) + } + pub fn as_str(self) -> &'static str { match self { Self::Vendor => "vendor", @@ -67,6 +78,12 @@ pub fn search(query: &str) -> Result { || preset.id.to_lowercase().contains(&query) || preset.name.to_lowercase().contains(&query) || preset.kind.as_str().contains(&query) + || Locale::ALL.iter().any(|locale| { + locale + .text(preset.kind.label().key()) + .to_lowercase() + .contains(&query) + }) }) .collect(); Ok(Snapshot { diff --git a/src/restore.rs b/src/restore.rs index 09065e6..54b3ac7 100644 --- a/src/restore.rs +++ b/src/restore.rs @@ -3,6 +3,7 @@ //! Arrays and secrets require adapter-specific ownership; broad object replacement //! is deliberately rejected. A restore never renews any authorization. +use crate::i18n::msg; use serde_json::Value; use thiserror::Error; @@ -21,16 +22,16 @@ pub struct FieldChange { #[derive(Debug, Error, PartialEq, Eq)] pub enum RestoreError { /// A newer user or manager edit takes precedence over the backup. - #[error("字段在 LMM 修改后再次变化,恢复已暂停")] + #[error("{}", msg("restore.conflict"))] Conflict, /// Object/array replacement would have an overly broad scope. - #[error("仅支持对象中的单个标量字段;集合需要专用适配器")] + #[error("{}", msg("restore.unsupported_shape"))] UnsupportedShape, /// Invalid JSON pointer or missing parent. - #[error("无法定位恢复字段的父对象")] + #[error("{}", msg("restore.invalid_pointer"))] InvalidPointer, /// A malformed or overlapping journal must not reorder writes. - #[error("变更记录包含重复字段")] + #[error("{}", msg("restore.duplicate_field"))] DuplicateField, } diff --git a/tests/i18n.rs b/tests/i18n.rs new file mode 100644 index 0000000..73ed8a2 --- /dev/null +++ b/tests/i18n.rs @@ -0,0 +1,346 @@ +#![allow(clippy::unwrap_used, clippy::expect_used)] + +use lmm::i18n::Locale; +use serde_json::Value; +use std::{ + ffi::OsString, + process::{Command, Output, Stdio}, +}; + +fn run(args: &[&str], variables: &[(&str, &str)]) -> Output { + let home = tempfile::tempdir().unwrap(); + let mut command = Command::new(env!("CARGO_BIN_EXE_lmm")); + command + .args(args) + .env("HOME", home.path()) + .env("USERPROFILE", home.path()) + .env("LOCALAPPDATA", home.path()) + .env("XDG_STATE_HOME", home.path()) + .env("PATH", "") + .env("NO_COLOR", "1") + .env("TERM", "dumb") + .stdin(Stdio::null()); + for key in ["LMM_LANG", "LC_ALL", "LC_MESSAGES", "LANG"] { + command.env_remove(key); + } + command.envs(variables.iter().copied()); + command.output().unwrap() +} + +fn stdout(output: &Output) -> &str { + std::str::from_utf8(&output.stdout).unwrap() +} + +fn detect(args: &[&str], variables: &[(&str, &str)]) -> Locale { + let args = args + .iter() + .map(|value| OsString::from(*value)) + .collect::>(); + Locale::detect(&args, |key| { + variables + .iter() + .find(|(name, _)| *name == key) + .map(|(_, value)| OsString::from(*value)) + }) +} + +#[test] +fn recognizes_language_tags_without_confusing_traditional_chinese_with_simplified() { + for name in ["en", "EN-us", "en_GB.UTF-8", "C", "C.UTF-8", "POSIX"] { + assert_eq!(Locale::from_name(name), Some(Locale::En), "{name}"); + } + for name in [ + "zh", + "zh-CN", + "zh_CN.UTF-8", + "zh_SG", + "zh-Hans", + "zh-Hans-CN", + "zh_CN@variant", + ] { + assert_eq!(Locale::from_name(name), Some(Locale::ZhCn), "{name}"); + } + for name in ["", "fr_FR.UTF-8", "zh-TW", "zh-Hant", "pirate"] { + assert_eq!(Locale::from_name(name), None, "{name}"); + } +} + +#[test] +fn language_precedence_and_fallback_are_deterministic() { + assert_eq!( + detect( + &["lmm", "--lang", "en", "catalog"], + &[("LMM_LANG", "zh-CN")] + ), + Locale::En + ); + assert_eq!( + detect(&["lmm", "catalog", "--lang=zh-CN"], &[("LC_ALL", "C")]), + Locale::ZhCn + ); + assert_eq!( + detect(&["lmm"], &[("LMM_LANG", "zh-CN"), ("LC_ALL", "C")]), + Locale::ZhCn + ); + assert_eq!( + detect(&["lmm"], &[("LC_ALL", "C"), ("LANG", "zh-CN")]), + Locale::En + ); + assert_eq!( + detect( + &["lmm"], + &[("LC_MESSAGES", "zh_CN.UTF-8"), ("LANG", "en_US")] + ), + Locale::ZhCn + ); + assert_eq!( + detect(&["lmm"], &[("LMM_LANG", ""), ("LANG", "zh_CN.UTF-8")]), + Locale::ZhCn + ); + assert_eq!( + detect(&["lmm"], &[("LC_ALL", "fr_FR.UTF-8"), ("LANG", "zh-CN")]), + Locale::En + ); + assert_eq!(detect(&["lmm"], &[]), Locale::En); +} + +#[test] +fn positional_data_after_double_dash_does_not_select_a_language() { + assert_eq!( + detect(&["lmm", "presets", "--", "--lang=zh-CN"], &[]), + Locale::En + ); + let output = run(&["presets", "--", "--lang=zh-CN"], &[]); + assert!(output.status.success()); + assert!(stdout(&output).contains("Built-in provider presets")); +} + +#[cfg(unix)] +#[test] +fn non_unicode_environment_does_not_panic_or_override_a_cli_choice() { + use std::os::unix::ffi::OsStringExt; + let args = vec![OsString::from("lmm")]; + assert_eq!( + Locale::detect(&args, |_| Some(OsString::from_vec(vec![0xff]))), + Locale::En + ); + let args = vec![OsString::from("lmm"), OsString::from("--lang=zh-CN")]; + assert_eq!( + Locale::detect(&args, |_| Some(OsString::from_vec(vec![0xff]))), + Locale::ZhCn + ); +} + +#[test] +fn root_and_subcommand_help_use_the_selected_language() { + for (language, heading) in [("en", "Usage:"), ("zh-CN", "用法:")] { + let root = run(&["--lang", language, "--help"], &[]); + assert!(root.status.success(), "{:?}", root.stderr); + assert!(stdout(&root).contains(heading)); + assert!(stdout(&root).contains("--lang")); + for name in [ + "presets", + "catalog", + "setup", + "install", + "login", + "logout", + "models", + "balance", + "authorize", + "receipt", + "credential", + "status", + "sync", + "update", + "doctor", + "restore", + "disconnect", + "uninstall", + "run", + ] { + let output = run(&[name, "--lang", language, "--help"], &[]); + assert!(output.status.success(), "{name}: {:?}", output.stderr); + assert!( + stdout(&output).contains(heading), + "{name}: {}", + stdout(&output) + ); + assert!(stdout(&output).contains("--lang")); + assert!(!stdout(&output).contains("arg.")); + assert!(!stdout(&output).contains("cmd.")); + } + let help = run(&["--lang", language, "help", "login"], &[]); + assert!(help.status.success(), "{:?}", help.stderr); + assert!(stdout(&help).contains(heading)); + assert!(stdout(&help).contains("--issuer")); + } +} + +#[test] +fn environment_selection_and_global_flag_work_for_real_commands() { + let chinese = run(&["catalog", "astrbot"], &[("LANG", "zh_CN.UTF-8")]); + assert!(stdout(&chinese).contains("消息平台")); + let english = run( + &["catalog", "astrbot", "--lang=en-US"], + &[("LMM_LANG", "zh-CN")], + ); + assert!(stdout(&english).contains("messaging platforms")); + assert!(!stdout(&english).contains("消息平台")); + let chinese = run( + &["--lang=zh_CN.UTF-8", "catalog", "astrbot"], + &[("LC_ALL", "C")], + ); + assert!(stdout(&chinese).contains("消息平台")); +} + +#[test] +fn invalid_explicit_language_fails_without_running_a_command() { + for args in [ + vec!["--lang", "pirate", "catalog"], + vec!["catalog", "--lang"], + vec!["--lang=", "catalog"], + ] { + let output = run(&args, &[]); + assert_eq!(output.status.code(), Some(2)); + assert!(output.stdout.is_empty()); + } +} + +#[test] +fn runtime_errors_and_blocked_plans_are_translated() { + let english = run(&["--lang=en", "status", "unknown-software"], &[]); + let chinese = run(&["--lang=zh-CN", "status", "unknown-software"], &[]); + assert_eq!(english.status.code(), Some(2)); + assert_eq!(chinese.status.code(), Some(2)); + assert!(String::from_utf8_lossy(&english.stderr).contains("Unknown software ID")); + assert!(String::from_utf8_lossy(&chinese.stderr).contains("未知软件 ID")); + let chinese = run(&["setup", "astrbot", "--dry-run", "--lang=zh-CN"], &[]); + assert_eq!(chinese.status.code(), Some(3)); + assert!(stdout(&chinese).contains("计划已阻止")); + assert!(stdout(&chinese).contains("写入适配器")); + let chinese = run( + &["models", "--issuer", "http://127.0.0.1", "--lang=zh-CN"], + &[], + ); + assert_eq!(chinese.status.code(), Some(3)); + assert!(String::from_utf8_lossy(&chinese.stderr).contains("HTTPS 域名")); +} + +#[test] +fn json_messages_and_codes_do_not_change_with_the_display_language() { + for arguments in [ + vec!["catalog", "astrbot"], + vec!["presets", "local"], + vec!["status", "astrbot"], + vec!["doctor", "astrbot", "--report"], + vec!["setup", "astrbot", "--dry-run"], + vec!["status", "unknown-software"], + vec!["models", "--issuer", "http://127.0.0.1"], + vec!["login", "--non-interactive"], + vec!["balance", "--non-interactive"], + vec!["authorize", "cc-switch", "--non-interactive"], + vec!["setup", "pi", "--activate"], + vec!["status", "astrbot", "--node", "/unavailable-node"], + vec!["status", "pi", "--node", "/unavailable-node"], + vec!["setup", "astrbot", "--installation-id", "unused-instance"], + ] { + let mut results = Vec::new(); + for language in ["en", "zh-CN"] { + let mut args = vec!["--json", "--lang", language]; + args.extend_from_slice(&arguments); + let output = run(&args, &[]); + assert!(output.stderr.is_empty(), "{args:?}: {:?}", output.stderr); + let mut value: Value = serde_json::from_slice(&output.stdout).unwrap(); + if let Some(object) = value.as_object_mut() { + object.remove("checked_at"); + } + results.push((output.status.code(), value)); + } + assert_eq!(results[0], results[1], "{arguments:?}"); + } + let output = run( + &["status", "unknown-software", "--lang=zh-CN", "--json"], + &[], + ); + let value: Value = serde_json::from_slice(&output.stdout).unwrap(); + assert_eq!(value["error_code"], "error.unknown_software"); + assert!( + value["error"] + .as_str() + .unwrap() + .starts_with("Unknown software ID") + ); +} + +#[test] +fn search_matches_translated_descriptions_without_changing_identifiers() { + for query in ["messaging platforms", " 消息平台 "] { + let output = run(&["catalog", query, "--json", "--lang=en"], &[]); + let value: Value = serde_json::from_slice(&output.stdout).unwrap(); + assert_eq!(value.as_array().unwrap().len(), 1); + assert_eq!(value[0]["id"], "astrbot"); + } + let local = run(&["presets", "local", "--json"], &[]); + let translated = run(&["presets", "本地", "--json"], &[]); + assert_eq!(local.stdout, translated.stdout); +} + +#[test] +fn native_adapter_errors_translate_without_accessing_credentials() { + for (arguments, english, chinese) in [ + ( + vec!["setup", "pi", "--activate"], + "Pi activation requires", + "Pi 激活需要", + ), + ( + vec!["authorize", "cc-switch", "--non-interactive"], + "system vault", + "系统凭据库", + ), + ( + vec!["setup", "astrbot", "--installation-id", "unused-instance"], + "only to CC Switch", + "只适用于 CC Switch", + ), + ] { + for (locale, expected) in [("en", english), ("zh-CN", chinese)] { + let mut args = vec!["--lang", locale]; + args.extend_from_slice(&arguments); + let output = run(&args, &[]); + assert_eq!(output.status.code(), Some(2), "{args:?}"); + assert!(output.stdout.is_empty()); + assert!( + String::from_utf8_lossy(&output.stderr).contains(expected), + "{args:?}: {:?}", + output.stderr + ); + } + } +} + +#[test] +fn credential_command_keeps_its_no_json_contract_in_both_languages() { + for locale in ["en", "zh-CN"] { + let output = run( + &[ + "--lang", + locale, + "--json", + "credential", + "cc-switch", + "--issuer", + "https://example.invalid", + "--installation-id", + "unused-instance", + "--grant-id", + "unused-grant", + ], + &[], + ); + assert_eq!(output.status.code(), Some(2)); + assert!(output.stdout.is_empty()); + assert!(String::from_utf8_lossy(&output.stderr).contains("credential")); + } +}