diff --git a/README.md b/README.md index 9528e22..d961dc5 100644 --- a/README.md +++ b/README.md @@ -14,6 +14,7 @@ subscription and makes its requests. The packages work in OpenCode and in | [agnes](packages/agnes) | Agnes AI international (agnes-ai.com), with Chrome browser sign-in, live text models, plan usage and USD balance | `agnes` | | [agnes-code](packages/agnes-code) | Agnes AI's Agnes Code desktop, with the desktop's saved session (Windows) or a pasted access token: live models, daily credit check-in and points balance (unofficial) | `agnes-code` | | [astudio](packages/astudio) | iFlytek's AStudio (科大讯飞 Astron Studio desktop), with the desktop's saved credentials or a pasted model token: live model catalog, daily login-points check-in and points balance (unofficial) | `astudio` | +| [atomcode](packages/atomcode) | AtomGit CodingPlan, with browser OAuth or the local AtomCode CLI's sign-in, signed requests, live models, quota windows and a read-only diagnostics page (unofficial) | `atomcode` | | [catpaw](packages/catpaw) | Meituan's 妙手 CatPaw (ai.catpaw.meituan.com), with a browser web sign-in or the desktop client's saved credentials | `catpaw` | | [cline](packages/cline) | Cline (cline.bot): usage-billed models, ClinePass's and Cline's free ones, with Cline's device sign-in or an API key | `cline` | | [codearts](packages/codearts) | Huawei Cloud CodeArts (码道) coding plans (Trial, personal and enterprise credits), with Huawei Cloud OAuth sign-in (unofficial) | `codearts` | diff --git a/packages/atomcode/CHANGELOG.md b/packages/atomcode/CHANGELOG.md new file mode 100644 index 0000000..8fea49a --- /dev/null +++ b/packages/atomcode/CHANGELOG.md @@ -0,0 +1,130 @@ +# Changelog + +All notable changes to this project are documented here. The format follows +Keep a Changelog and the project uses semantic versioning. + +## 0.3.0 - 2026-11-03 + +### Added + +- Magpie-native `auto_claim` and `auto_version` provider switches, both on by + default. The legacy `autoClaim` and `autoVersion` options still override them. +- A loopback-only, read-only diagnostics page at + `http://127.0.0.1:3478/` (configurable), with token-gated state and offline + signature checks. It never calls AtomGit and is not started under OpenCode. +- Crash-tolerant state under Magpie's plugin directory for last-good model + metadata, quota snapshots, version provenance, redacted errors and self-check + results. The file contains no access token, refresh token, full user id, + email, prompt or raw upstream response. +- A custom `auth.toml` path prompt for the AtomCode CLI sign-in method, accepting + absolute paths and `~/...`, with renewals written back only to that file. +- A shared failure vocabulary that separates credential failures from plan, + entitlement and quota failures across models, usage and check-in. + +### Changed + +- The package now ships from `magpie-community/plugins` as + `@magpie-community/opencode-atomcode-auth`, with separate OpenCode 1.x and + 2.x entry points. +- Minimum Magpie version is now `0.1.2629`, which provides native provider + switches and page services. +- The AtomCode diagnostics page is now a focused troubleshooting workspace with + a local-status summary, quota-first layout, model catalog, progressive + technical details and a human-readable redacted report. +- The default per-account concurrency is now 8 instead of 4. Controlled live + probes at 4, 8 and 12 simultaneous short requests all returned HTTP 200 with + no 429 or 5xx responses; 8 keeps additional parallel headroom while remaining + conservative. Magpie's provider setting can still override it. +- Usage failures after a successful read now return the persisted stale quota + snapshot with `stale: true` instead of replacing the account's windows with + an empty result. +- Live model discovery falls back first to the account's last successful disk + cache, then to the built-in snapshot. +- Only 401 and explicit credential/session 403 responses trigger a refresh. + Quota and entitlement 403 responses keep the sign-in and add + `x-magpie-sign-in: kept`. +- Quota rows are separated by explicit unit and window span, so a token window + is not misreported as a call-count window. +- The diagnostics workspace now uses flat backgrounds and solid status colors + to match Magpie's settings pages. + +### Fixed + +- Restarting or briefly losing the CodingPlan endpoint no longer hides known + quota windows or the previous model catalog. +- Exhausted claim slots now produce `ineligible`; ordinary upstream failures + remain `failed`. +- A missing native switch value now matches the settings UI's enabled default. +- The published package uses an explicit file list, so editor backup/upload + sidecars cannot enter the npm tarball. +- Upstream legacy `window_token_*` fields that contain call counts are no longer + mislabeled as token quotas. Token-only rows are inferred from token-specific + fields without call counters; `current_usage` also requires an explicit unit. +- The embedded diagnostics page now loads inside Magpie's + `sandbox="allow-scripts"` plugin frame, including its styles, scripts, images, + token-gated API preflights and requests. Each page response uses a fresh CSP + script nonce. Host and token checks remain loopback-only, and CORS never uses + a wildcard origin. +- CLI-backed renewals preserve each existing TOML scalar's type, including the + official CLI's string-valued `user.id`, and keep unmanaged fields such as + `token_type`. A renewal can no longer make the official CLI reject auth.toml. + +### Security + +- Diagnostics bind only to `127.0.0.1`, validate `Host` and `Origin`, require a + random per-process token for APIs, and serve a restrictive CSP. +- Persisted diagnostics state is schema-filtered, atomically written with + `0600` permissions, and excludes credentials and account identifiers. + +## 0.2.0 - 2026-11-02 + +### Added + +- Second sign-in method that reuses the official AtomCode CLI's + `~/.atomcode/auth.toml`, validates private regular-file permissions, re-reads + shared state before use, and atomically writes renewals back. +- Live model metadata for `deepseek-flash`, reasoning-effort variants, and + model-level output-token limits. +- Token-oriented quota windows alongside every call-count window. +- Opt-in live smoke test capped at nine requests, with automatic claiming + disabled and no token, prompt, or response-content output. +- Isolated tarball install/import CI smoke and release publication workflow for + npm trusted publishing with provenance. + +### Changed + +- Package name and layout are migration-ready for + `@magpie-community/opencode-atomcode-auth` under + `magpie-community/plugins/packages/atomcode`. +- Minimum Magpie version is now `0.1.2563`; OpenCode loading remains supported + but is explicitly experimental pending a real host-contract test. +- Endpoint overrides are restricted to the exact `acs.atomgit.com` and + `api.gitcode.com` hosts on HTTPS port 443. +- Request bodies are normalized to replayable bytes, buffered with a 64 MiB + cap, and signed after stream-usage serialization. +- Unknown quota values stay unknown instead of being reported as zero. + +### Fixed + +- A caller-owned `URL` can no longer be mutated between validation and dispatch + to redirect signed traffic. +- Refresh results are cached by old and new refresh token, so persistence + failures or a gap between renewal and save cannot trigger a second rotation. +- Gateway 401/403 responses force one refresh and retry; CLI-backed accounts + persist the new credentials before the retry. +- Usage/check-in/claim work shares one request budget and one claim lock, with a + bounded 18-second quota path. +- `auth.usage` returns `signIn: "expired"` on upstream credential failures. +- `remaining_days: null` no longer triggers a false plan re-claim. +- Special model names such as `__proto__` cannot alter the model result object's + prototype. +- Upstream error bodies, invalid option values, emails, bearer tokens, and long + secrets are redacted from logs and user-facing errors. + +### Security + +- OAuth, CodingPlan, and version response bodies remain bounded and redirects + are refused. +- CLI auth files reject symlinks, non-regular files, and permissions wider than + `0600`. +- The published package keeps zero runtime dependencies. diff --git a/packages/atomcode/LICENSE b/packages/atomcode/LICENSE new file mode 100644 index 0000000..6ce701f --- /dev/null +++ b/packages/atomcode/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 magpie-atomcode contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/packages/atomcode/NOTICE.md b/packages/atomcode/NOTICE.md new file mode 100644 index 0000000..d5170f2 --- /dev/null +++ b/packages/atomcode/NOTICE.md @@ -0,0 +1,26 @@ +# NOTICE / 署名 + +本插件的实现依据(只参考事实与算法,不复制代码): + +- **[Atom2Api](https://github.com/cnluminous/Atom2Api)** — MIT License, © 2026 Atom2Api contributors。 + `atomcode-signing-v1` 签名算法(HKDF 派生与 HMAC 正则结构)、OAuth broker 端点形状、 + CodingPlan REST 用法与 `planTier` 判定均取自该 MIT 项目的源码事实; + 版本自动追踪依据其 `ua.go`(raw.atomgit.com 的 Cargo.toml URL 与 manifest 解析同源), + 登录后按 Max→Pro→Lite 幂等领取依据其 `codingplan.go` 的 `claim()` 与 `oauth.go` 的 + ClaimAndSync 触发点; + 其 `core_test.go` 的独立签名测试向量被 `test/sign.test.mjs` 作为对照基准原样使用。 + 依据 MIT 许可证使用,特此署名。 +- **[atomgit-opencode-bridge](https://github.com/zhuguang-ZFG/atomgit-opencode-bridge)** — 无许可证。 + 仅参考其公开文档记录的协议事实(如 `403 ATOMCODE_UA_REQUIRED`、UA 必须 `atomcode/<版本>`), + 未复制其任何代码。 +- **[AtomCode](https://atomgit.com/atomgit_atomcode/atomcode)** — MIT,版本 5.2.3。 + 仅用作 UA / 签名 `X-AtomCode-Ver` 的版本号锚点;本插件不是它的官方组件。 +- **[magpie-sensenova](https://github.com/aqiu817/magpie-sensenova) / [magpie-kilo-gateway](https://github.com/aqiu817/magpie-kilo-gateway)** — MIT, aqiu817。 + 同作者的 magpie 插件工程范式(单函数入口、i18n 表、quota 缓存策略)参考对象。 + +## 免责声明 + +本插件是非官方的兼容实现,不隶属于 AtomGit / AtomCode,也未获其认可。 +上游协议(签名密钥、OAuth、CodingPlan 接口)可能随时变化导致不可用; +使用方式也可能违反服务条款,存在账号受限或封禁的风险。 +请仅凭自己的账号、在了解风险的前提下使用。 diff --git a/packages/atomcode/README.md b/packages/atomcode/README.md new file mode 100644 index 0000000..80aaf4d --- /dev/null +++ b/packages/atomcode/README.md @@ -0,0 +1,233 @@ +# AtomCode + +[中文](README.zh-CN.md) | English + +An (unofficial) provider plugin for [magpie](https://usemagpie.ai) that brings **ATOMCODE (AtomGit CodingPlan)** in. + +After signing in through AtomGit or reusing the official AtomCode CLI's local +sign-in, the CodingPlan models appear in magpie as the **ATOMCODE** provider. +Any agent — Claude Code, Codex, OpenCode — can use `atomcode/`. The plan, +the daily check-in and rolling quota windows show up on the account row, in +`magpie quota`, and in settings. + +``` +Agent (Claude Code / Codex / OpenCode / …) + │ any API + ▼ +magpie gateway ──► magpie-atomcode (adds atomcode-signing-v1 headers + UA) + ▼ +https://llm-api.atomgit.com/v1 (OpenAI-compatible, SSE streams back untouched) +``` + +## Features + +- **Two sign-in methods**: browser OAuth via the AtomGit broker, or reuse of + `~/.atomcode/auth.toml` from the official AtomCode CLI. CLI-backed accounts + are re-read before use and renewed tokens are atomically written back with + `0600` permissions. +- **Resilient renewal**: single-flight refresh plus an in-memory result cache + prevents a rotated refresh token from being reused; a gateway 401 retries + once with a fresh token, including on older hosts without `auth.refresh`. +- **Direct to AtomGit**: no Atom2Api instance needed; streaming, tool calls and + reasoning-effort variants are declared to the host. +- **Daily check-in (`checkin`)**: scheduled by magpie's native check-in toggle. Plan valid → done; expired/missing → the official Max→Pro→Lite cascade re-claims it; quota exhausted → failed with the upstream reason. +- **Quota windows**: plan name, expiry, every upstream rate-limit window, and a + token window only when upstream supplies token-specific fields without call + counters (or explicitly declares token units), updating live. +- **Native controls**: `auto_claim` and `auto_version` appear as provider + switches in Magpie and default on; the older camelCase options still override + them for compatibility. +- **Restart-safe fallback**: the last successful model catalog and quota + snapshot survive restarts. A transient refresh failure shows the stale quota + with a clear marker instead of blanking the account row. +- **Auto version tracking**: follows the AtomCode repo's current version by default (the official client force-updates); falls back to the built-in anchor, never blocking a request. +- **Live model catalog**: each account pulls its own (varies by plan/tier), with a built-in snapshot as the offline fallback. +- **Offline diagnostics**: a loopback-only troubleshooting workspace at + `http://127.0.0.1:3478/` summarizes local readiness, quota windows, model + catalog, account and version state, then offers a network-free signature + self-check and a human-readable redacted report. It opens inside Magpie's + sandboxed plugin frame or directly in a browser. + +## Current models (snapshot 2026-11-02) + +| Model | Context | Reasoning efforts | Vision | +|---|---|---|---| +| `glm5.3-flash` | 512K | low / high | ✓ | +| `qwen3.8-27b` | 256K | low / medium / xhigh | ✓ | +| `deepseek-flash` | 1M | high / max | ✓ | + +The catalog varies per account and plan — the live list wins after sign-in. + +## Install + +```bash +magpie plugin add @magpie-community/opencode-atomcode-auth +# Or load a checkout directly: +magpie plugin add /path/to/plugins/packages/atomcode +``` + +The package targets magpie `>=0.1.2629`. It exposes separate OpenCode 1.x and +2.x entry points, but real OpenCode host-contract verification remains +experimental. + +## Sign in & check-in + +```bash +magpie plugin login atomcode 1 # browser OAuth +magpie plugin login atomcode 2 # reuse the official AtomCode CLI login +``` + +- CLI reuse reads `~/.atomcode/auth.toml`, verifies that it is a private regular + file, and refuses to follow symlinks or wide permissions. Renewals are written + back atomically so the official CLI and magpie keep the same refresh chain. +- The second sign-in method asks for an optional `auth.toml` path. Leave it blank + for the default, or enter an absolute path / `~/...`; relative paths and + `~other-user` are rejected. +- The local CLI file is shared state. If its account changes, sign in again so + magpie never signs requests with one account's `uid` and another account's + access token. +- The official CLI serializes renewals with `auth-refresh.lock`. This plugin + does not take that Rust `fs2` lock. If both renew at the same instant and the + broker rotates the refresh token, the client that loses the race must sign in + again. +- Check-in: the toggle in magpie's plugin settings ("has the ATOMCODE plugin sign in every signed-in account, daily"). Even when off, an expired plan is re-claimed automatically while reading quota/catalog (30-min cooldown). +- Plan quotas: Lite 1000/day; Pro trial 100/day released at 10:00. When the daily pool is out, the check-in fails with the upstream message — try again tomorrow. + +## Options (`options` in `plugins.json`; all have defaults) + +| Option | Default | Meaning | +|---|---|---| +| `locale` | auto | `zh` / `en` | +| `autoVersion` | `true` | legacy override for the native `auto_version` switch | +| `clientVersion` | `5.2.3` | fallback version anchor (used when `autoVersion` is off or the fetch fails) | +| `autoClaim` | `true` | legacy override for the native `auto_claim` switch | +| `masterKeyHex` | built-in | escape hatch when upstream rotates its signing key | +| `platformBaseURL` | `https://acs.atomgit.com` | OAuth broker | +| `codingPlanAPIURL` | `https://api.gitcode.com/api/v5` | CodingPlan REST | +| `quotaTtlMs` | `60000` | quota cache | +| `maxOutputTokens` | `32768` | default model output ceiling | +| `diagnosticsPort` | `3478` | loopback diagnostics port (must stay in `1024..65535`) | + +`auto_claim` and `auto_version` are the preferred controls and default on. Set +them in the provider editor or with: + +```bash +magpie plugin options atomcode '{"auto_claim":false}' +magpie plugin options atomcode '{"auto_version":false}' +``` + +The manifest defaults each AtomCode account to 8 simultaneous requests. This +helps when several agents, sessions or sub-tasks run in parallel; it does not +make a single streamed completion faster. A controlled live probe at 4, 8 and +12 simultaneous short requests returned HTTP 200 without 429 or 5xx responses, +so 8 is the conservative default and the provider editor can override it. + +## Security boundaries + +All of these are enforced in code, and `npm test` covers each one: + +- **The gateway is the only destination.** `loader.fetch` freezes the validated + URL before any asynchronous credential read, then compares its origin against + `https://llm-api.atomgit.com`. A caller cannot mutate a `URL` object during the + await and redirect signed traffic. Scheme and port are part of the comparison. +- **Upstream cannot move the destination.** A model row's `base_url` is honoured only when its origin exactly matches the signed gateway; otherwise that model falls back to the official gateway and the plugin logs that it did. +- **Endpoint options use exact hosts.** `platformBaseURL` may only be + `acs.atomgit.com`; `codingPlanAPIURL` may only be `api.gitcode.com` (path + overrides are allowed). Both must be HTTPS on port 443. Anything else falls + back to the official endpoint with a redacted warning. +- **Bounded reads and redirects.** Version, OAuth and CodingPlan response bodies are capped at 1 MiB *while* streaming; every metadata call has a timeout and refuses redirects. A broker-supplied login URL must also stay on AtomGit. +- **Signable request bodies only.** Strings, byte buffers, typed arrays, + `ArrayBuffer` and `Blob` are signed exactly as sent. Streams, `FormData` and + `URLSearchParams` are rejected rather than signing bytes that differ from the + wire representation. Buffered request bodies are capped at 64 MiB. +- **Final bytes are signed.** Streaming Chat Completions requests without an + explicit `stream_options.include_usage` receive `include_usage: true`; the + signature is computed after serialization. +- **Logs are redacted.** Upstream response bodies are not copied into errors, + and invalid option values, bearer tokens, emails and long secrets are not + logged. +- **Credential failures are separated from entitlement failures.** A 401 or an + explicit credential/session 403 may trigger one refresh. Quota, plan, + permission and other non-credential 403 responses keep the account signed in + and return `x-magpie-sign-in: kept`. +- **Diagnostics stay local and read-only.** The service listens only on + `127.0.0.1`, checks the request `Host`, requires a random per-process token for + APIs, checks `Origin` on POST, and serves a restrictive CSP. The page never + probes AtomGit or the LLM gateway. + +Browser credentials live in magpie's own store. CLI credentials stay in +`~/.atomcode/auth.toml`; renewals are atomically replaced with `0600` +permissions while unrelated TOML content is preserved. Credentials are never +printed or logged and are only attached to the exact official hosts above. + +Magpie also writes `/atomcode-state.json` for the +diagnostics view. It is schema-filtered and atomically written with `0600` +permissions. It may contain model names, quota windows, version provenance and +a redacted last error, but never tokens, a full user id, email addresses, +prompts or raw upstream responses. + +### What runs by default + +Both defaults are on out of the box, and both act without being asked: + +| Default | What it actually does | Turn off with | +|---|---|---| +| `auto_claim: true` | Starts the CodingPlan `claim-v2` after sign-in and retries the idempotent claim when the plan has expired. After sign-in it runs in the background. | `magpie plugin options atomcode '{"auto_claim":false}'` | +| `auto_version: true` | Refreshes the version manifest from `raw.atomgit.com` in the background (12 h cache). Requests immediately use the current cached version, including the built-in fallback. | `magpie plugin options atomcode '{"auto_version":false}'` | + +## Troubleshooting + +For a 401 during sign-in or provider testing: + +1. Run `magpie version` and note the failure stage: OAuth callback, model catalog, quota, or chat request. +2. Open the plugin's **AtomCode diagnostics** page. The status summary separates local readability from upstream availability; quota, model, account and version details follow, with the redacted last error, offline self-check and expandable runtime metadata below. +3. Try `atomcode login` with the official AtomCode client using the same account. If that also returns 401, the account is likely refused upstream rather than by this plugin. +4. Open a bug report with the redacted report from the diagnostics page. Never include access tokens, refresh tokens, OAuth state, `plugin-auth.json`, email addresses, account IDs, or unredacted home-directory paths. + +Security issues should follow [SECURITY.md](SECURITY.md). Development and review expectations are in the [community plugin guide](https://github.com/magpie-community/plugins#write-your-own). + +## Development + +```bash +cd ../.. +npm test # Node test suite from the workspace root +npm run test:bun # Bun host/runtime suite +npm run test:coverage:enforce # line/branch/function gates +npm run pack:check # verify the published tarball contents +``` + +Live validation spends a small amount of quota and is disabled by default: + +```bash +ATOMCODE_LIVE=1 npm run test:live +``` + +It is capped at nine requests, disables automatic claiming, never runs check-in, +and prints no tokens, prompts or model response text. + +CI runs the suite on Node 20, 22 and 24 plus a pinned Bun, enforces coverage +thresholds, and installs the packed tarball into a clean project for an import +smoke test. Release publishing is prepared through npm trusted publishing with +provenance and is triggered only by a GitHub release. + +Sandbox verification (never touches your real magpie): + +```bash +SB=$(mktemp -d) +PLUGIN_ROOT="$(pwd)/packages/atomcode" +sb() { env HOME="$SB" USERPROFILE="$SB" XDG_CONFIG_HOME="$SB/.config" XDG_CACHE_HOME="$SB/.cache" \ + MAGPIE_ADDR=127.0.0.1:3499 MAGPIE_PLUGIN_MARKET=off magpie "$@"; } +sb plugin add "$PLUGIN_ROOT" +sb plugin list +sb plugin options atomcode +``` + +The same code loads as an OpenCode plugin (v1 shape); magpie-only hooks +(`auth.usage`, `auth.refresh`, `auth.checkin`) are ignored by OpenCode. OpenCode +support remains experimental because its OAuth type does not declare the `uid` +field required by AtomCode request signing. The diagnostics service and native +provider switches are Magpie-only. + +## Disclaimer + +Unofficial, not affiliated with or endorsed by AtomGit / AtomCode. Upstream protocols may change at any time; usage you choose may breach terms of service and risks account restriction or bans — Atom2Api carries the same warning. See [NOTICE.md](NOTICE.md) for attribution. diff --git a/packages/atomcode/README.zh-CN.md b/packages/atomcode/README.zh-CN.md new file mode 100644 index 0000000..4e999d9 --- /dev/null +++ b/packages/atomcode/README.zh-CN.md @@ -0,0 +1,209 @@ +# AtomCode + +简体中文 | [English](README.md) + +把 **ATOMCODE(AtomGit CodingPlan)** 接入 [magpie](https://usemagpie.ai) 的供应商插件(非官方)。 + +通过 AtomGit 浏览器授权,或复用本机官方 AtomCode CLI 的登录后,CodingPlan +的模型会以供应商 **ATOMCODE** 出现在 magpie 里;Claude Code、Codex、 +OpenCode 等任何 Agent 都能选 `atomcode/<模型>` 使用。套餐信息、每日签到与 +滚动额度窗口,都显示在 magpie 的账号行、`magpie quota` 和设置里。 + +``` +Agent (Claude Code / Codex / OpenCode / …) + │ 任意 API + ▼ +magpie 网关 ──► magpie-atomcode(补 atomcode-signing-v1 签名 + UA) + ▼ +https://llm-api.atomgit.com/v1(OpenAI 兼容,SSE 原样流回) +``` + +## 功能 + +- **两种登录方式**:AtomGit 浏览器 OAuth,或复用官方 AtomCode CLI 的 + `~/.atomcode/auth.toml`。CLI 来源每次请求前重读;续期结果以 `0600` + 权限原子回写,不破坏无关 TOML 内容。 +- **可靠续期**:刷新单飞加内存结果缓存,避免 refresh token 轮换后被旧 token + 再刷一次;网关返回 401 时会强制续期并只重试一次,旧宿主没有 + `auth.refresh` 也能工作。 +- **直连 AtomGit**:不需要 Atom2Api 常驻;流式、工具调用和推理档位 variants + 都声明给宿主。 +- **每日签到(checkin)**:magpie 原生签到开关调度。套餐有效 → done;到期/缺失 → 按官方 Max→Pro→Lite 级联自动重领;名额满 → failed 并显示上游原因。 +- **额度窗口**:显示套餐名、到期时间、上游返回的每个限流窗口;只有上游给出 + token 专用字段且没有调用计数(或明确声明 token 单位)时才显示 token 窗口。 +- **原生开关**:`auto_claim` / `auto_version` 会出现在 Magpie 供应商设置里, + 默认开启;旧的 camelCase 选项仍可覆盖它们,保持兼容。 +- **重启后可恢复**:最近一次成功的模型目录与额度快照会落盘。临时刷新失败时 + 显示带 `stale` 标记的旧额度,而不是把账号行清空。 +- **自动追版本**:默认跟随 AtomCode 官方仓库的最新版本号(官方客户端会强制更新),拉取失败退回内置版本,绝不阻塞请求。 +- **模型目录动态拉取**:每个账号自己的目录(随套餐/档位而变),离线时用内置快照兜底。 +- **离线诊断页**:`http://127.0.0.1:3478/` 是只读排障工作台,先说明本地 + 快照是否可读,再展示额度窗口、模型目录、账号与版本状态;下方提供脱敏最近 + 错误、不访问上游的签名自检和可展开的运行时信息。既可显示在 Magpie 的沙箱 + 插件页面里,也可直接在浏览器打开。 + +## 当前模型(2026-11-02 实测快照) + +| 模型 | 上下文 | 推理档位 | 视觉 | +|---|---|---|---| +| `glm5.3-flash` | 500K | low / high | ✓ | +| `qwen3.8-27b` | 256K | low / medium / xhigh | ✓ | +| `deepseek-flash` | 1M | high / max | ✓ | + +目录随账号与套餐动态变化,以登录后拉取的为准。 + +## 安装 + +```bash +# 社区/npm 包 +magpie plugin add @magpie-community/opencode-atomcode-auth +# 或直接加载仓库目录 +magpie plugin add /path/to/plugins/packages/atomcode +``` + +包面向 magpie `>=0.1.2629`。OpenCode 1.x 与 2.x 使用各自的入口,但真实 +OpenCode 宿主契约尚未验证,因此仍标为实验性。 + +## 登录与签到 + +```bash +magpie plugin login atomcode 1 # 浏览器 OAuth +magpie plugin login atomcode 2 # 复用本机 AtomCode CLI 登录 +``` + +- CLI 复用会读取 `~/.atomcode/auth.toml`,只接受权限不宽于 `0600` 的普通文件, + 拒绝符号链接;续期后原子回写,让官方 CLI 与 magpie 保持同一条 refresh 链。 +- 第二种登录方式会询问可选的 `auth.toml` 路径。留空使用默认路径,也可以填 + 绝对路径或 `~/...`;相对路径与 `~其他用户` 会被拒绝。 +- 该文件是 CLI 与插件共享状态。如果本机登录切换了账号,需要重新登录 magpie, + 避免用一个账号的 `uid` 给另一个账号的 access token 签名。 +- 官方 CLI 使用 `auth-refresh.lock` 串行化续期;本插件不持有同款 Rust `fs2` + 文件锁。如果双方在同一时刻续期且 broker 轮换了 refresh token,竞争失败的 + 一方需要重新登录。 +- 签到:magpie 设置 → 插件里的签到开关(「每天让 ATOMCODE 插件给每个已登录的账号签到一次」)。即使不开,套餐到期后额度/目录读取时也会自动补领(30 分钟冷却)。 +- 套餐名额:Lite 限量 1000 人/日;Pro 体验版每日 10:00 放 100 个名额。抢满时签到会失败并显示原因,明天再试即可。 + +## 选项(`plugins.json` 的 options;都有默认值) + +| 选项 | 默认 | 说明 | +|---|---|---| +| `locale` | auto(跟机器) | `zh` / `en` | +| `autoVersion` | `true` | 原生 `auto_version` 开关的旧版覆盖项 | +| `clientVersion` | `5.2.3` | 兜底版本号(`autoVersion` 拉取失败或关闭时用) | +| `autoClaim` | `true` | 原生 `auto_claim` 开关的旧版覆盖项 | +| `masterKeyHex` | 内置 | 上游更换签名密钥时的热修逃生口(64 位 hex) | +| `platformBaseURL` | `https://acs.atomgit.com` | OAuth broker 地址 | +| `codingPlanAPIURL` | `https://api.gitcode.com/api/v5` | CodingPlan REST 地址 | +| `quotaTtlMs` | `60000` | 额度缓存时长 | +| `maxOutputTokens` | `32768` | 模型 output 上限兜底 | +| `diagnosticsPort` | `3478` | 本机诊断端口(`1024..65535`) | + +日常建议使用原生开关,它们默认开启;可在供应商编辑器切换,或执行: + +```bash +magpie plugin options atomcode '{"auto_claim":false}' +magpie plugin options atomcode '{"auto_version":false}' +``` + +插件清单默认允许每个 AtomCode 账号同时运行 8 个请求。只有多个 Agent、会话或 +子任务并行时才会看到收益;单个流式回答不会因此变快。受控真机测试中,4、8、12 +个短请求同时发出均返回 HTTP 200,没有出现 429 或 5xx,因此默认采用较保守的 +8;仍可在供应商设置中按账号覆盖这个值。 + +## 安全边界 + +下面这些都在代码里强制,`npm test` 逐一覆盖: + +- **只有官方网关是目的地。** `loader.fetch` 在任何异步读取凭证之前先冻结已验证 + 的 URL,再把 origin 与 `https://llm-api.atomgit.com` 比对。调用方无法在等待 + 期间修改 `URL` 对象把签名流量引到别处;协议和端口都参与比较。 +- **上游改不动目的地。** 模型行里的 `base_url` 只有 origin 与签名网关完全一致时才被采纳,否则该模型回退官方网关并记录日志。 +- **端点选项使用精确主机。** `platformBaseURL` 只接受 + `acs.atomgit.com`;`codingPlanAPIURL` 只接受 `api.gitcode.com`(允许改路径)。 + 两者都必须是 443 端口上的 HTTPS;否则回退官方端点并输出脱敏告警。 +- **读取有上限、跳转被拒绝。** 版本、OAuth、CodingPlan 的响应体都在流式读取时限制为 1 MiB;所有元数据请求都有超时且拒绝跳转。broker 返回的登录地址也必须位于 AtomGit。 +- **只接受可精确签名的请求体。** 字符串、字节缓冲区、TypedArray、`ArrayBuffer` + 和 `Blob` 会按实际发送字节签名;流、`FormData`、`URLSearchParams` 直接拒绝, + 避免签的字节和线上字节不一致。缓冲的请求体上限为 64 MiB。 +- **签名覆盖最终字节。** 流式 Chat Completions 若没有显式设置 + `stream_options.include_usage`,插件会补 `include_usage: true`,序列化后再签名。 +- **日志脱敏。** 上游响应正文不会塞进异常;非法配置值、bearer、邮箱和长密钥 + 不进入日志。 +- **凭证失败与权益失败分开。** 401 或明确属于凭证/会话的 403 才允许触发一次 + 续期;额度、套餐、权限等非凭证 403 不会让账号掉登录,并返回 + `x-magpie-sign-in: kept`。 +- **诊断页只在本机、只读。** 服务只监听 `127.0.0.1`,校验 `Host`,API 需要 + 每次进程启动时随机生成的令牌,POST 还校验 `Origin`,并下发严格 CSP。页面 + 不会主动请求 AtomGit 或 LLM 网关。 + +浏览器凭证存在 magpie 自己的 `plugin-auth.json`。CLI 凭证保留在 +`~/.atomcode/auth.toml`,续期时以 `0600` 权限原子替换并保留无关内容。凭证不会 +被打印或写入日志,只会附加到上面两个精确官方主机。 + +Magpie 还会在 `<插件数据目录>/atomcode-state.json` 保存诊断状态。文件经过 +schema 过滤,以 `0600` 权限原子写入;只包含模型名、额度窗口、版本来源与脱敏 +后的最近错误,不保存 token、完整 user id、邮箱、提示词或上游原始响应。 + +### 装完就在跑的默认行为 + +两个默认开关都是开的,且都会在没被要求的情况下动手: + +| 默认 | 实际动作 | 关闭方式 | +|---|---|---| +| `auto_claim: true` | 登录后在后台启动 CodingPlan `claim-v2`;套餐到期时再执行幂等重领 | `magpie plugin options atomcode '{"auto_claim":false}'` | +| `auto_version: true` | 后台刷新 `raw.atomgit.com` 的版本清单(缓存 12 小时)。请求立即使用当前缓存版本,拿不到时使用内置兜底 | `magpie plugin options atomcode '{"auto_version":false}'` | + +## 排障 + +登录或 `provider test` 遇到 401 时: + +1. 运行 `magpie version`,确认失败阶段是 OAuth 回调、模型目录、额度还是真实对话请求。 +2. 打开插件的 **AtomCode 诊断**页。状态摘要会区分“本地快照可读”和“上游当前可用”,随后按额度、模型、账号与版本展开;最近错误、离线自检和运行时信息位于下方,不会请求上游。 +3. 用同一账号运行官方 AtomCode 客户端的 `atomcode login`。若官方客户端也返回 401,更可能是上游账号风控,而不是插件。 +4. 提交 Bug 时附上诊断页生成的脱敏报告。不要提供 access token、refresh token、OAuth state、`plugin-auth.json`、邮箱、账号 ID 或未脱敏的用户目录。 + +安全问题请按 [SECURITY.md](SECURITY.md) 私密报告;开发与审查约定见[社区插件指南](https://github.com/magpie-community/plugins#write-your-own)。 + +## 开发 + +```bash +cd ../.. +npm test # 在 workspace 根运行 Node 测试 +npm run test:bun # Bun 宿主/运行时测试 +npm run test:coverage:enforce # 行/分支/函数覆盖率门禁 +npm run pack:check # 检查 npm 发布包内容 +``` + +真机验证会消耗少量额度,默认关闭: + +```bash +ATOMCODE_LIVE=1 npm run test:live +``` + +脚本最多发出 9 次请求,关闭自动领取,不执行签到,也不会输出 token、提示词或 +模型回复正文。 + +CI 会在 Node 20、22、24 与固定版本 Bun 上运行测试,执行覆盖率门禁,并把 +打包后的 tarball 安装到空目录做导入冒烟。发布流程使用 npm trusted publishing +和 provenance,只由 GitHub Release 触发。 + +沙箱验证(不碰真实配置): + +```bash +SB=$(mktemp -d) +PLUGIN_ROOT="$(pwd)/packages/atomcode" +sb() { env HOME="$SB" USERPROFILE="$SB" XDG_CONFIG_HOME="$SB/.config" XDG_CACHE_HOME="$SB/.cache" \ + MAGPIE_ADDR=127.0.0.1:3499 MAGPIE_PLUGIN_MARKET=off magpie "$@"; } +sb plugin add "$PLUGIN_ROOT" +sb plugin list +sb plugin options atomcode +``` + +同一份代码可加载为 OpenCode 插件(v1 插件形态);magpie 自有的 `auth.usage` / +`auth.refresh` / `auth.checkin` 会被 OpenCode 忽略。由于 OpenCode 的 OAuth 类型 +没有声明 AtomCode 签名必需的 `uid` 字段,OpenCode 支持仍标为实验性,需通过真实 +宿主契约测试后再升级。诊断服务和原生供应商开关仅适用于 Magpie。 + +## 免责声明与署名 + +本插件是非官方的兼容实现,不隶属于 AtomGit / AtomCode,也未获其认可。上游协议(签名密钥、OAuth、接口)可能随时变化;使用方式可能违反服务条款,存在账号受限或封禁风险——Atom2Api 项目有同类警示。请仅凭自己的账号、在了解风险的前提下使用。实现依据与署名见 [NOTICE.md](NOTICE.md)。 diff --git a/packages/atomcode/SECURITY.md b/packages/atomcode/SECURITY.md new file mode 100644 index 0000000..7ff7afd --- /dev/null +++ b/packages/atomcode/SECURITY.md @@ -0,0 +1,38 @@ +# Security Policy + +## Reporting a vulnerability + +Do not open a public issue for a credential leak, request-routing bypass, signature flaw, or other exploitable behavior. + +Use GitHub's private **Security advisories** flow for this repository: + +https://github.com/magpie-community/plugins/security/advisories/new + +Include the affected version, a minimal reproduction, impact, and any suggested mitigation. Remove access tokens, refresh tokens, OAuth state values, account identifiers, and personal paths from logs and screenshots. + +## Supported versions + +Security fixes target the latest published `0.3.x` release and the current +`main` branch. Older commits and local forks are not supported. + +## Security boundaries + +- Browser tokens are stored by magpie. CLI-backed tokens remain in + `~/.atomcode/auth.toml`; renewals preserve unrelated content and use an + atomic private (`0600`) replacement. +- Tokens are never logged or printed. +- Signed model traffic is restricted to the official gateway origin; redirects are refused. +- Configurable OAuth and CodingPlan endpoints must use the exact official hosts + on HTTPS port 443. +- Upstream model URLs are accepted only when their origin matches the signed gateway. +- OAuth login redirects are restricted to AtomGit and metadata responses are size-bounded. +- Request bodies that cannot be replayed byte-for-byte are rejected; buffered + bodies are capped at 64 MiB. +- Only 401 and explicit credential/session 403 responses may refresh the + account. Plan, quota and other entitlement 403 responses keep the sign-in. +- The diagnostics service binds only to `127.0.0.1`, validates `Host` and + `Origin`, requires a random per-process token for APIs, and sends a strict CSP. + It never calls AtomGit or the LLM gateway. +- The persisted diagnostics state is schema-filtered and atomically written with + `0600` permissions. It excludes access and refresh tokens, complete account + ids, email addresses, prompts and raw upstream responses. diff --git a/packages/atomcode/assets/atomcode.ico b/packages/atomcode/assets/atomcode.ico new file mode 100644 index 0000000..363e6d9 Binary files /dev/null and b/packages/atomcode/assets/atomcode.ico differ diff --git a/packages/atomcode/auth-file.mjs b/packages/atomcode/auth-file.mjs new file mode 100644 index 0000000..d4a3f59 --- /dev/null +++ b/packages/atomcode/auth-file.mjs @@ -0,0 +1,344 @@ +/** + * Read and update the sign-in AtomCode's own CLI keeps in + * `~/.atomcode/auth.toml`. + * + * This is deliberately a narrow TOML reader, not a general parser: the file is + * owned by the official client, so unknown lines and sections are preserved + * whenever the plugin writes a renewed token back. + * + * @module magpie-atomcode/auth-file + */ + +import { chmod, lstat, mkdir, open, readFile, rename, unlink } from "node:fs/promises"; +import { homedir } from "node:os"; +import { dirname, isAbsolute, join, normalize } from "node:path"; +import { randomBytes } from "node:crypto"; + +const ROOT_KEYS = new Set(["access_token", "refresh_token", "created_at", "expires_in"]); +const USER_KEYS = new Set(["id", "username", "name", "email", "avatar_url"]); + +export function defaultAuthFilePath(env = process.env) { + const home = env.HOME || env.USERPROFILE || homedir(); + return join(home, ".atomcode", "auth.toml"); +} + +/** + * Resolve a user-supplied CLI auth path. + * + * Empty means the default. Only `~`, `~/...` and absolute paths are accepted; + * relative paths and `~other-user` would make the account source depend on the + * host's working directory, so they are rejected. + * + * @param {unknown} value + * @param {object} [env] + * @returns {string} + */ +export function resolveAuthFilePath(value, env = process.env) { + const raw = value === undefined || value === null ? "" : String(value).trim(); + if (!raw) return defaultAuthFilePath(env); + if (raw.includes("\0")) throw new Error("AtomCode auth file path contains a NUL byte"); + if (raw.length > 4096) throw new Error("AtomCode auth file path is too long"); + + const home = env.HOME || env.USERPROFILE || homedir(); + let resolved; + if (raw === "~") { + resolved = home; + } else if (raw.startsWith("~/") || raw.startsWith("~\\")) { + resolved = join(home, raw.slice(2)); + } else if (raw.startsWith("~")) { + throw new Error("AtomCode auth file path must not use ~another-user"); + } else if (isAbsolute(raw)) { + resolved = normalize(raw); + } else { + throw new Error("AtomCode auth file path must be absolute or start with ~/"); + } + if (resolved.length > 4096) throw new Error("AtomCode auth file path is too long"); + return resolved; +} + +function splitComment(raw) { + const text = String(raw ?? ""); + let quote = ""; + let escaped = false; + for (let i = 0; i < text.length; i++) { + const char = text[i]; + if (quote === '"' && escaped) { + escaped = false; + } else if (quote === '"' && char === "\\") { + escaped = true; + } else if (quote && char === quote) { + quote = ""; + } else if (!quote && (char === '"' || char === "'")) { + quote = char; + } else if (!quote && char === "#") { + const value = text.slice(0, i); + const end = value.trimEnd().length; + return { value: value.slice(0, end), comment: text.slice(end) }; + } + } + return { value: text, comment: "" }; +} + +function scalar(raw) { + const value = splitComment(raw).value.trim(); + if (value.startsWith('"') && value.endsWith('"')) { + try { + return JSON.parse(value); + } catch { + return value.slice(1, -1); + } + } + if (value.startsWith("'") && value.endsWith("'")) return value.slice(1, -1); + return value; +} + +function collect(text) { + const root = {}; + const user = {}; + let section = ""; + for (const line of String(text).split(/\r?\n/)) { + const header = line.match(/^\s*\[([^\]]+)\]\s*$/); + if (header) { + section = header[1].trim(); + continue; + } + const pair = line.match(/^\s*([A-Za-z_][A-Za-z0-9_-]*)\s*=\s*(.*?)\s*$/); + if (!pair) continue; + const key = pair[1]; + if ((!section && ROOT_KEYS.has(key)) || (section === "user" && USER_KEYS.has(key))) { + (section === "user" ? user : root)[key] = scalar(pair[2]); + } + } + return { root, user }; +} + +/** + * Parse the fields this plugin needs from AtomCode's auth.toml. + * + * @param {string} text + * @returns {object} + */ +export function parseAuthFile(text) { + const { root, user } = collect(text); + const access = typeof root.access_token === "string" ? root.access_token : ""; + const uid = user.id === undefined || user.id === null ? "" : String(user.id); + if (!access) throw new Error("AtomCode auth.toml has no access token"); + if (!uid) throw new Error("AtomCode auth.toml has no user id"); + + const createdAt = Number(root.created_at); + const expiresIn = Number(root.expires_in); + const expires = + Number.isFinite(createdAt) && Number.isFinite(expiresIn) && expiresIn > 0 + ? (createdAt + expiresIn) * 1000 + : undefined; + const email = typeof user.email === "string" && user.email ? user.email : undefined; + const username = typeof user.username === "string" && user.username ? user.username : undefined; + const name = + typeof user.name === "string" && user.name ? user.name : username; + + return { + type: "oauth", + source: "atomcode-cli", + access, + ...(typeof root.refresh_token === "string" && root.refresh_token + ? { refresh: root.refresh_token } + : {}), + ...(expires !== undefined ? { expires } : {}), + uid, + accountId: email || username || uid, + ...(email ? { email } : {}), + ...(name ? { name } : {}), + }; +} + +function tomlString(value) { + return JSON.stringify(String(value)); +} + +function scalarKind(raw) { + const text = splitComment(raw).value.trim(); + if (text.startsWith('"') || text.startsWith("'")) return "string"; + if (text === "true" || text === "false") return "boolean"; + const numeric = text.replaceAll("_", ""); + if (/^[+-]?\d+$/.test(numeric)) return "integer"; + if (/^[+-]?(?:\d+\.\d*|\.\d+|\d+)(?:[eE][+-]?\d+)?$/.test(numeric)) { + return "float"; + } + return "string"; +} + +function tomlValue(key, value, existing) { + if (existing !== undefined) { + const kind = scalarKind(existing); + if (kind === "integer") { + const number = Number(value); + return Number.isInteger(number) ? String(number) : tomlString(value); + } + if (kind === "float") { + const number = Number(value); + if (!Number.isFinite(number)) return tomlString(value); + const text = String(number); + return /[.eE]/.test(text) ? text : `${text}.0`; + } + if (kind === "boolean") { + return value === true || String(value).toLowerCase() === "true" + ? "true" + : "false"; + } + return tomlString(value); + } + if (key === "created_at" || key === "expires_in") { + const number = Number(value); + if (Number.isInteger(number)) return String(number); + } + return tomlString(value); +} + +/** + * Return auth.toml text with only known credential lines changed. + * + * @param {string} text + * @param {object} next + * @returns {string} + */ +export function renderAuthFile(text, next) { + const current = collect(text); + const rootValues = { + access_token: next.access, + refresh_token: next.refresh, + created_at: next.createdAt, + expires_in: next.expiresIn, + }; + const user = { ...current.user, ...(next.user ?? {}) }; + const userValues = Object.fromEntries(Object.entries(user).filter(([key]) => USER_KEYS.has(key))); + const wanted = { "": rootValues, user: userValues }; + const remaining = { + "": new Set(Object.entries(rootValues).filter(([, value]) => value !== undefined).map(([key]) => key)), + user: new Set(Object.entries(userValues).filter(([, value]) => value !== undefined).map(([key]) => key)), + }; + + const eol = String(text).includes("\r\n") ? "\r\n" : "\n"; + const lines = String(text).split(/\r?\n/); + const output = []; + let section = ""; + + const appendMissing = () => { + for (const key of remaining[section] ?? []) { + const value = wanted[section]?.[key]; + if (value !== undefined) output.push(`${key} = ${tomlValue(key, value)}`); + remaining[section]?.delete(key); + } + }; + + for (const line of lines) { + const header = line.match(/^\s*\[([^\]]+)\]\s*$/); + if (header) { + appendMissing(); + section = header[1].trim() === "user" ? "user" : header[1].trim(); + output.push(line); + continue; + } + const pair = line.match(/^(\s*)([A-Za-z_][A-Za-z0-9_-]*)(\s*=\s*)(.*)$/); + if (pair && wanted[section] && remaining[section]?.has(pair[2])) { + const value = wanted[section][pair[2]]; + if (value !== undefined) { + const { comment } = splitComment(pair[4]); + output.push( + `${pair[1]}${pair[2]}${pair[3]}${tomlValue(pair[2], value, pair[4])}${comment}`, + ); + } else { + output.push(line); + } + remaining[section].delete(pair[2]); + continue; + } + output.push(line); + } + appendMissing(); + if (remaining.user?.size) { + output.push("[user]"); + for (const key of remaining.user) { + const value = userValues[key]; + if (value !== undefined) output.push(`${key} = ${tomlValue(key, value)}`); + } + } + return output.join(eol); +} + +async function inspect(path) { + let info; + try { + info = await lstat(path); + } catch (error) { + if (error.code === "ENOENT") throw new Error("AtomCode CLI is not signed in on this computer"); + throw error; + } + if (info.isSymbolicLink() || !info.isFile()) { + throw new Error("AtomCode auth.toml must be a regular file, not a symlink"); + } + if (process.platform !== "win32" && (info.mode & 0o077) !== 0) { + throw new Error("AtomCode auth.toml permissions are wider than 0600"); + } + return info; +} + +/** + * Read and validate the CLI's auth file. + * + * @param {string} [path] + * @returns {Promise} + */ +export async function readAuthFile(path = defaultAuthFilePath()) { + const info = await inspect(path); + const text = await readFile(path, "utf8"); + return { ...parseAuthFile(text), path, mtimeMs: info.mtimeMs }; +} + +async function atomicWrite(path, text) { + await mkdir(dirname(path), { recursive: true, mode: 0o700 }); + const temp = `${path}.${process.pid}.${randomBytes(6).toString("hex")}.tmp`; + let handle; + try { + handle = await open(temp, "wx", 0o600); + await handle.writeFile(text, "utf8"); + await handle.sync(); + await handle.close(); + handle = undefined; + await chmod(temp, 0o600).catch(() => {}); + await rename(temp, path); + } catch (error) { + await handle?.close().catch(() => {}); + await unlink(temp).catch(() => {}); + throw error; + } +} + +/** + * Atomically renew the CLI's credentials while preserving unrelated lines. + * + * @param {string} path + * @param {object} next + * @returns {Promise} + */ +export async function writeAuthFile(path, next) { + await inspect(path); + const currentText = await readFile(path, "utf8"); + parseAuthFile(currentText); + const createdAt = Number.isFinite(next.createdAt) + ? Math.floor(next.createdAt) + : Math.floor(Date.now() / 1000); + const expiresIn = Number(next.expiresIn); + if (!next.access || !Number.isFinite(expiresIn) || expiresIn <= 0) { + throw new Error("refusing to write incomplete AtomCode credentials"); + } + const text = renderAuthFile(currentText, { + access: next.access, + ...(next.refresh ? { refresh: next.refresh } : {}), + createdAt, + expiresIn: Math.floor(expiresIn), + user: next.user, + }); + parseAuthFile(text); + await atomicWrite(path, text); + return readAuthFile(path); +} diff --git a/packages/atomcode/codingplan.mjs b/packages/atomcode/codingplan.mjs new file mode 100644 index 0000000..80b800b --- /dev/null +++ b/packages/atomcode/codingplan.mjs @@ -0,0 +1,262 @@ +/** + * Client for the AtomGit CodingPlan REST API + * (`https://api.gitcode.com/api/v5/coding-plan/*`). + * + * What the plugin needs from it: + * + * - `status-v2`: the plan (name / type / expiry), the current window usage and + * the raw `rate_limit_windows` — the source for both the plan tier and the + * `auth.usage` windows. + * - `models-v2?plan_type=`: the account's model catalog, which + * varies by account and plan tier (Atom2Api's README lists models this + * account never receives), so it is always read live with a snapshot as + * the fallback. + * + * Plain bearer auth, `User-Agent: atomcode/`, short timeouts — these + * are metadata calls, not model traffic. + * + * @module magpie-atomcode/codingplan + */ + +import { + DEFAULT_CLIENT_VERSION, + parseAtomInstant, + readCappedResponseText, + upstreamMessage, +} from "./internal.mjs"; +import { classifyError, FAILURE } from "./errors.mjs"; + +const withBase = (base, path) => `${String(base).replace(/\/+$/, "")}/${path}`; + +/** + * The plan part of a status response. The real endpoint answers it under + * `codingplan_free`; `plan` is a defensive fallback in case the upstream field + * moves. + */ +export function planOf(status) { + if (!status || typeof status !== "object") return null; + const plan = status.codingplan_free ?? status.plan ?? null; + return plan && typeof plan === "object" ? plan : null; +} + +/** + * Plan tier, spelled the way `models-v2?plan_type=` accepts it. + * + * Atom2Api's rule: the lowercase plan name containing "max" → Max, "pro" → Pro, + * anything else → Lite ("CodingPlan Lite-体验版" and "Lite-beta" are Lite). + */ +export function planTier(planName) { + const name = String(planName ?? "").toLowerCase(); + if (name.includes("max")) return "Max"; + if (name.includes("pro")) return "Pro"; + return "Lite"; +} + +/** + * 该账号是否需要(重新)领取 CodingPlan —— 插件"签到"语义的判定。 + * + * 协议里没有独立的每日打卡端点:官方 `/login` 的申领就是唯一写入点 + * (`claim-v2`),"限量 1000 人/日""每日 10:00 放量"是平台侧的放量节奏。 + * 因此插件里的"签到" = 套餐缺失或到期后的自动重领: + * - 没有 `codingplan_free`(从未领取或已彻底失效)→ 需要领取; + * - `remaining_days` 明确为 0 → 需要重领; + * - `expires_at` 已过且超出 1 天宽限(到期日当天仍算有效)→ 需要重领。 + * 判定保持保守:拿不准时一律返回 false,绝不因误判多打领取接口。 + */ +export function planNeedsClaim(status, now = Date.now()) { + const plan = planOf(status); + if (!plan) return true; + if (typeof plan.plan_name !== "string" || !plan.plan_name.trim()) return true; + const remaining = + plan.remaining_days === null || plan.remaining_days === undefined + ? undefined + : Number(plan.remaining_days); + if (Number.isFinite(remaining) && remaining <= 0) return true; + const expires = parseAtomInstant(plan.expires_at); + if (Number.isFinite(expires) && now > expires + 24 * 3600_000) return true; + return false; +} + +async function request( + base, + path, + token, + { + fetchImpl = (...args) => fetch(...args), + clientVersion = DEFAULT_CLIENT_VERSION, + timeoutMs = 20_000, + } = {}, +) { + const res = await fetchImpl(withBase(base, path), { + method: "GET", + redirect: "error", + headers: { + accept: "application/json", + authorization: `Bearer ${token}`, + "user-agent": `atomcode/${clientVersion}`, + }, + signal: AbortSignal.timeout(timeoutMs), + }); + const text = await readCappedResponseText(res, { label: "CodingPlan response" }); + if (!res.ok) { + const message = upstreamMessage(text); + const error = new Error( + `CodingPlan returned HTTP ${res.status}${message ? `: ${message}` : ""}`, + ); + error.status = res.status; + const failure = classifyError(error); + error.category = failure.category; + if (failure.signInExpired) error.signIn = "expired"; + throw error; + } + try { + return JSON.parse(text); + } catch { + throw new Error("CodingPlan did not answer JSON"); + } +} + +/** `GET /coding-plan/status-v2` — plan + current window + rate_limit_windows. */ +export async function fetchStatus(base, token, opts = {}) { + return request(base, "coding-plan/status-v2", token, opts); +} + +/** + * `GET /coding-plan/models-v2?plan_type=…` for the account's tier. + * + * Rows without a display name, rows not available to the plan and deprecated + * rows are dropped; an out-of-shape payload throws so callers fall back. + * + * @returns {Promise} raw model rows, normalization happens upstream. + */ +export async function fetchModels(base, token, tier, opts = {}) { + const r = await request(base, `coding-plan/models-v2?plan_type=${encodeURIComponent(tier)}`, token, opts); + if (!Array.isArray(r)) throw new Error("models-v2 did not return a list"); + return r.filter((m) => { + if (!m || typeof m !== "object") return false; + if (typeof m.display_model_name !== "string" || !m.display_model_name.trim()) return false; + if (m.plan_available === false) return false; + if (m.status === "deprecated") return false; + return true; + }); +} + +/** + * 领取 CodingPlan —— 签到(登录)闭环的最后一步。 + * + * Atom2Api 在 OAuth 换到 token 后立刻做同一件事:按官方客户端的 + * Max → Pro → Lite 顺序 POST `/coding-plan/claim-v2`,`success` 或 + * `duplicate`(已领取过)即停;错误响应体也按 JSON 解出 `message` + * (Atom2Api 的 `claim()` 同款)。幂等且只做领取,不改账号状态。 + * + * 这个函数绝不抛错:领不成就把原因作为结果返回,让登录先成功。 + * + * @returns {Promise<{claimed: boolean, tier: string, planName: string, message: string, attempts: object[]}>} + */ +export async function claimCodingPlan( + base, + token, + { + fetchImpl = (...args) => fetch(...args), + clientVersion = DEFAULT_CLIENT_VERSION, + timeoutMs = 8_000, + totalTimeoutMs = 24_000, + } = {}, +) { + let lastMessage = "no Coding Plan tier is currently available"; + const attempts = []; + const deadline = Date.now() + totalTimeoutMs; + for (const tier of ["Max", "Pro", "Lite"]) { + const remaining = deadline - Date.now(); + if (remaining <= 0) { + lastMessage = "CodingPlan claim timed out"; + break; + } + let status = 0; + let response = null; + let raw = ""; + try { + const res = await fetchImpl(withBase(base, "coding-plan/claim-v2"), { + method: "POST", + redirect: "error", + headers: { + accept: "application/json", + authorization: `Bearer ${token}`, + "content-type": "application/json", + "user-agent": `atomcode/${clientVersion}`, + }, + body: JSON.stringify({ plan_type: tier }), + signal: AbortSignal.timeout(Math.max(1, Math.min(timeoutMs, remaining))), + }); + status = res.status; + raw = await readCappedResponseText(res, { label: "CodingPlan claim response" }); + try { + response = JSON.parse(raw); + } catch { + /* 非 JSON 响应体 → message 退回原文 */ + } + } catch (error) { + const failure = classifyError(error); + attempts.push({ tier, httpStatus: 0, success: false, duplicate: false, message: error.message }); + lastMessage = error.message; + return { + claimed: false, + duplicate: false, + tier: "", + planName: "", + message: lastMessage, + category: failure.category, + attempts, + }; + } + const success = status >= 200 && status < 300 && response?.success === true; + const duplicate = status >= 200 && status < 300 && response?.duplicate === true; + const message = + typeof response?.message === "string" && response.message + ? response.message + : response + ? "" + : upstreamMessage(raw) || `HTTP ${status}`; + attempts.push({ tier, httpStatus: status, success, duplicate, message }); + if (success || duplicate) { + return { + claimed: true, + // fresh(这次才领到)与 duplicate(本来就持有)在 checkin 语义里要分开: + // 前者 = claimed,后者 = done。 + duplicate, + tier: typeof response?.plan_type === "string" && response.plan_type ? response.plan_type : tier, + planName: typeof response?.plan_name === "string" ? response.plan_name : "", + message, + attempts, + }; + } + // A transport/auth/rate-limit failure affects every tier. Only an + // entitlement-shaped rejection is worth cascading to the next tier. + if (![400, 404, 409, 422].includes(status)) { + const failure = classifyError({ status: status || undefined, message }); + return { + claimed: false, + duplicate: false, + tier: "", + planName: "", + message, + category: failure.category, + attempts, + }; + } + if (message) lastMessage = message; + } + const failure = classifyError({ message: lastMessage }); + return { + claimed: false, + duplicate: false, + tier: "", + planName: "", + message: lastMessage, + category: + failure.category === FAILURE.UNKNOWN + ? FAILURE.INELIGIBLE + : failure.category, + attempts, + }; +} diff --git a/packages/atomcode/diagnostics.mjs b/packages/atomcode/diagnostics.mjs new file mode 100644 index 0000000..7070221 --- /dev/null +++ b/packages/atomcode/diagnostics.mjs @@ -0,0 +1,445 @@ +/** + * Loopback-only, read-only diagnostics for the Magpie host. + * + * Magpie settings pages cannot make network requests (`connect-src 'none'`), + * so `page/index.html` is only a bridge that navigates to this service. The + * service itself owns the real page and API, making every API request + * same-origin. It never calls AtomGit and never exposes a token or full account + * id. + * + * @module magpie-atomcode/diagnostics + */ + +import { randomBytes, timingSafeEqual } from "node:crypto"; +import { readFile } from "node:fs/promises"; +import { createServer } from "node:http"; +import { fileURLToPath } from "node:url"; + +import { signAtomGitRequest } from "./sign.mjs"; +import { accountDigest } from "./state.mjs"; + +export const DEFAULT_DIAGNOSTICS_PORT = 3478; +export const DIAGNOSTICS_TOKEN_HEADER = "x-atomcode-token"; + +const active = new Map(); +const PAGE_DIR = new URL("./page/", import.meta.url); +const ASSET_TYPES = { + "/app.css": "text/css; charset=utf-8", + "/app.js": "text/javascript; charset=utf-8", + "/icon.svg": "image/svg+xml; charset=utf-8", +}; + +const securityHeaders = { + "cache-control": "no-store", + "x-content-type-options": "nosniff", + "referrer-policy": "no-referrer", + "cross-origin-resource-policy": "cross-origin", +}; + +/** A valid diagnostics port, or the fallback. */ +export function diagnosticsPort(value, fallback = DEFAULT_DIAGNOSTICS_PORT) { + const port = Number(value); + return Number.isInteger(port) && port >= 1024 && port <= 65_535 + ? port + : fallback; +} + +export function hostAllowed(host, port) { + if (!port || typeof host !== "string") return false; + const value = host.toLowerCase(); + return value === `127.0.0.1:${port}` || value === `localhost:${port}`; +} + +export function originAllowed(origin, port, { required = false } = {}) { + if (origin === undefined) return !required; + if (origin === "null") return true; + return ( + origin === `http://127.0.0.1:${port}` || + origin === `http://localhost:${port}` + ); +} + +function corsHeaders(req, port, methods) { + const origin = req.headers.origin; + return { + ...(origin !== undefined && originAllowed(origin, port) + ? { "access-control-allow-origin": origin } + : {}), + "access-control-allow-methods": methods, + "access-control-allow-headers": DIAGNOSTICS_TOKEN_HEADER, + vary: "Origin", + }; +} + +function tokenAllowed(got, wanted) { + const left = Buffer.from(String(got ?? "")); + const right = Buffer.from(String(wanted ?? "")); + return right.length > 0 && left.length === right.length && timingSafeEqual(left, right); +} + +function headers(type, extra = {}) { + return { + ...securityHeaders, + ...(type ? { "content-type": type } : {}), + ...extra, + }; +} + +/** + * Magpie renders plugin pages inside a sandboxed frame, so the page must name + * the desktop ancestors and list its own loopback origins instead of relying on + * `'self'`, which a sandboxed frame does not always match in WebKit. + */ +function pagePolicy(port, nonce) { + const loopback = [ + `http://127.0.0.1:${port}`, + `http://localhost:${port}`, + ].join(" "); + return [ + "default-src 'none'", + `style-src 'self' ${loopback}`, + `script-src 'self' ${loopback} 'nonce-${nonce}'`, + `img-src 'self' ${loopback}`, + `connect-src 'self' ${loopback}`, + "base-uri 'none'", + "frame-ancestors 'self' wails://localhost http://wails.localhost", + "form-action 'none'", + ].join("; "); +} + +async function readBody(req, max = 1024) { + let size = 0; + const chunks = []; + for await (const chunk of req) { + size += chunk.byteLength; + if (size > max) { + const error = new Error("request body is too large"); + error.status = 413; + throw error; + } + chunks.push(chunk); + } + return Buffer.concat(chunks).toString("utf8"); +} + +/** A deterministic, network-free signature check. */ +export function runSelfCheck({ + clientVersion = "5.2.3", + masterKeyHex = "", + now = Date.now(), +} = {}) { + const started = performance.now(); + let ok = false; + try { + const signed = signAtomGitRequest({ + method: "POST", + path: "/v1/chat/completions", + body: '{"model":"diagnostic"}', + oauthToken: "diagnostic-access-token", + userId: "diagnostic-user", + clientVersion, + masterKeyHex, + timestamp: Math.floor(now / 1000), + nonce: Buffer.alloc(16, 7), + }); + ok = + Object.keys(signed).length === 5 && + /^v1:[0-9a-f]{64}$/.test(signed["X-AtomCode-Sig"]) && + signed["X-AtomCode-Ver"] === clientVersion; + } catch { + ok = false; + } + return { + ok, + at: Date.now(), + ms: Math.max(0, Math.round((performance.now() - started) * 10) / 10), + checks: { + signature: ok, + version: /^[A-Za-z0-9][A-Za-z0-9._+-]{0,63}$/.test(clientVersion), + configuration: /^[0-9a-fA-F]{64}$/.test(masterKeyHex), + }, + }; +} + +/** Build the stable, redacted data shape consumed by the page. */ +export async function diagnosticsSnapshot({ + state, + version, + config = {}, + generatedAt = Date.now(), +} = {}) { + const accounts = Object.values(state?.accounts ?? {}); + const account = accounts[0]; + return { + product: "magpie-atomcode", + schemaVersion: state?.version ?? 1, + generatedAt: new Date(generatedAt).toISOString(), + account: account + ? { + digest: account.digest, + loginSource: account.loginSource ?? "unknown", + } + : undefined, + models: account?.models?.length + ? { + source: account.modelSource ?? "cached", + updatedAt: account.modelUpdatedAt, + count: account.models.length, + names: account.models.map((model) => model.id), + } + : { source: "built-in", count: 0, names: [] }, + quota: account?.quota + ? { + ...account.quota, + capturedAt: account.quotaUpdatedAt, + stale: true, + } + : undefined, + version: version ?? state?.versionSource, + lastError: account?.lastError, + selfCheck: account?.selfCheck, + config: { + locale: config.locale, + autoClaim: config.autoClaim, + autoVersion: config.autoVersion, + diagnosticsPort: config.diagnosticsPort, + readOnly: true, + }, + runtime: { + node: process.version, + platform: process.platform, + }, + }; +} + +function pageLocale(value, fallback) { + const language = String(value ?? "").toLowerCase(); + if (language.startsWith("zh")) return "zh"; + if (language.startsWith("en")) return "en"; + return fallback === "zh" ? "zh" : "en"; +} + +function htmlFor(template, token, locale, theme, nonce) { + return template + .replaceAll("{{TOKEN}}", token) + .replaceAll("{{LOCALE}}", locale === "zh" ? "zh" : "en") + .replaceAll("{{THEME}}", theme === "dark" || theme === "light" ? theme : "") + .replaceAll("{{CSP_NONCE}}", nonce); +} + +/** + * Start one service per port. Re-initialization returns the existing service; + * a foreign listener rejects `ready` with an actionable EADDRINUSE error. + */ +export function startDiagnosticsService({ + port = DEFAULT_DIAGNOSTICS_PORT, + stateStore, + versionSource, + config = {}, + locale = "en", + selfCheckConfig = {}, +} = {}) { + const wantedPort = diagnosticsPort(port); + const existing = active.get(wantedPort); + if (existing) return existing; + + const token = randomBytes(32).toString("hex"); + let htmlTemplate; + + async function template() { + htmlTemplate ??= await readFile(new URL("diagnostics.html", PAGE_DIR), "utf8"); + return htmlTemplate; + } + + async function stateSnapshot() { + const state = stateStore ? await stateStore.read().catch(() => undefined) : undefined; + const version = versionSource?.status?.(); + return diagnosticsSnapshot({ + state, + version: version + ? { + ...version, + checkedAt: + version.checkedAt === undefined + ? undefined + : new Date(version.checkedAt).toISOString(), + failedAt: + version.failedAt === undefined + ? undefined + : new Date(version.failedAt).toISOString(), + } + : undefined, + config: { + ...config, + autoClaim: typeof config.autoClaim === "function" ? config.autoClaim() : config.autoClaim, + autoVersion: typeof config.autoVersion === "function" ? config.autoVersion() : config.autoVersion, + }, + }); + } + + const server = createServer(async (req, res) => { + const portNow = server.address()?.port ?? wantedPort; + if (!hostAllowed(req.headers.host, portNow)) { + res.writeHead(403, headers("text/plain; charset=utf-8")).end("Forbidden"); + return; + } + + let url; + try { + url = new URL(req.url ?? "/", `http://127.0.0.1:${portNow}`); + } catch { + res.writeHead(400, headers("text/plain; charset=utf-8")).end("Bad request"); + return; + } + + if (req.method === "GET" && (url.pathname === "/" || url.pathname === "/index.html")) { + const localeNow = pageLocale(url.searchParams.get("lang"), locale); + const theme = url.searchParams.get("theme"); + const nonce = randomBytes(16).toString("base64"); + res + .writeHead( + 200, + headers( + "text/html; charset=utf-8", + { + "content-security-policy": pagePolicy(portNow, nonce), + }, + ), + ) + .end(htmlFor(await template(), token, localeNow, theme, nonce)); + return; + } + + if (req.method === "GET" && ASSET_TYPES[url.pathname]) { + try { + const asset = await readFile(new URL(url.pathname.slice(1), PAGE_DIR), "utf8"); + res.writeHead(200, headers(ASSET_TYPES[url.pathname])).end(asset); + } catch { + res.writeHead(404, headers("text/plain; charset=utf-8")).end("Not found"); + } + return; + } + + if ( + req.method === "OPTIONS" && + (url.pathname === "/api/state" || url.pathname === "/api/self-check") + ) { + if (!originAllowed(req.headers.origin, portNow, { required: true })) { + res.writeHead(403, headers("text/plain; charset=utf-8")).end("Forbidden"); + return; + } + const methods = + url.pathname === "/api/self-check" ? "POST, OPTIONS" : "GET, OPTIONS"; + res + .writeHead(204, headers(undefined, corsHeaders(req, portNow, methods))) + .end(); + return; + } + + if (url.pathname === "/api/state" && req.method === "GET") { + if ( + !tokenAllowed(req.headers[DIAGNOSTICS_TOKEN_HEADER], token) || + !originAllowed(req.headers.origin, portNow) + ) { + res.writeHead(403, headers("text/plain; charset=utf-8")).end("Forbidden"); + return; + } + const snapshot = await stateSnapshot(); + res + .writeHead( + 200, + headers( + "application/json; charset=utf-8", + corsHeaders(req, portNow, "GET, OPTIONS"), + ), + ) + .end(JSON.stringify(snapshot)); + return; + } + + if (url.pathname === "/api/self-check" && req.method === "POST") { + if ( + !tokenAllowed(req.headers[DIAGNOSTICS_TOKEN_HEADER], token) || + !originAllowed(req.headers.origin, portNow, { required: true }) + ) { + res.writeHead(403, headers("text/plain; charset=utf-8")).end("Forbidden"); + return; + } + let body; + try { + body = await readBody(req); + } catch (error) { + res.writeHead(error.status ?? 400, headers("text/plain; charset=utf-8")).end("Bad request"); + return; + } + if (url.search || body !== "") { + res.writeHead(400, headers("text/plain; charset=utf-8")).end("Invalid request"); + return; + } + const result = runSelfCheck(selfCheckConfig); + if (stateStore) { + const state = await stateStore.read().catch(() => undefined); + const digest = Object.keys(state?.accounts ?? {})[0] ?? accountDigest(undefined); + await stateStore.recordSelfCheckForDigest(digest, result); + } + res + .writeHead( + 200, + headers( + "application/json; charset=utf-8", + corsHeaders(req, portNow, "POST, OPTIONS"), + ), + ) + .end(JSON.stringify(result)); + return; + } + + res.writeHead(404, headers("text/plain; charset=utf-8")).end("Not found"); + }); + + const entry = { + server, + port: wantedPort, + token, + ready: undefined, + async stop() { + if (active.get(wantedPort) === entry) active.delete(wantedPort); + if (!server.listening) return; + await new Promise((resolve) => { + server.close(resolve); + server.closeAllConnections?.(); + }); + }, + }; + entry.ready = new Promise((resolve, reject) => { + const failed = (error) => { + if (active.get(wantedPort) === entry) active.delete(wantedPort); + const reason = + error?.code === "EADDRINUSE" + ? `AtomCode diagnostics cannot listen on 127.0.0.1:${wantedPort}: port is already in use` + : "AtomCode diagnostics service could not start"; + const wrapped = new Error(reason); + wrapped.code = error?.code; + reject(wrapped); + }; + server.once("error", failed); + server.once("listening", () => { + server.off("error", failed); + server.unref?.(); + resolve(entry); + }); + }); + active.set(wantedPort, entry); + server.listen(wantedPort, "127.0.0.1"); + return entry; +} + +export function stopDiagnosticsService(port) { + const entries = port === undefined ? [...active.values()] : [active.get(Number(port))]; + return Promise.all( + entries.filter(Boolean).map((entry) => entry.stop()), + ); +} + +/** Replace the static placeholder once, before tests inspect the source. */ +export const DIAGNOSTICS_PAGE_PATH = fileURLToPath(new URL("diagnostics.html", PAGE_DIR)); diff --git a/packages/atomcode/docs/diagnostics.jpg b/packages/atomcode/docs/diagnostics.jpg new file mode 100644 index 0000000..4fe92db Binary files /dev/null and b/packages/atomcode/docs/diagnostics.jpg differ diff --git a/packages/atomcode/errors.mjs b/packages/atomcode/errors.mjs new file mode 100644 index 0000000..7bd3563 --- /dev/null +++ b/packages/atomcode/errors.mjs @@ -0,0 +1,169 @@ +/** + * One failure vocabulary for provider, quota and diagnostic paths. + * + * A 401 means the credential is no longer usable. A 403 is deliberately split: + * only an explicit token/session refusal may mark the account expired. Plan, + * quota and permission refusals are upstream answers about the account's + * entitlement and must not force a refresh or a re-login loop. + * + * @module magpie-atomcode/errors + */ + +import { redactText } from "./internal.mjs"; + +export const FAILURE = Object.freeze({ + NETWORK: "network", + TIMEOUT: "timeout", + UNAUTHORIZED: "unauthorized", + CREDENTIAL_FORBIDDEN: "credential_forbidden", + ENTITLEMENT_FORBIDDEN: "entitlement_forbidden", + FORBIDDEN: "forbidden", + RATE_LIMIT: "rate_limit", + SIGNING: "signing", + VERSION: "version", + SERVER: "upstream_server", + CLI_ACCOUNT_CHANGED: "cli_account_changed", + INELIGIBLE: "ineligible", + UNKNOWN: "unknown", +}); + +const CREDENTIAL_WORDS = + /(?:access|refresh|oauth|bearer|session)[\s_-]*token|token[\s_-]*(?:is[\s_-]*)?(?:expired|invalid|revoked)|(?:invalid|expired|revoked)[\s_-]*token|unauthori[sz]ed|unauthenticated|authentication|credential|sign[\s-]*in|log[\s-]*in|login|令牌|凭证|会话|登录|重新认证/i; + +const ENTITLEMENT_WORDS = + /quota|rate[\s_-]*limit|usage[\s_-]*limit|limit[\s_-]*reached|too many requests|balance|credit|billing|subscription|entitlement|coding[\s_-]*plan|plan[\s_-]*(?:expired|unavailable|required)|no tier|not eligible|ineligible|余额|额度|套餐|名额|限额|限流|订阅|权益|档位|领取/i; + +const VERSION_WORDS = + /(?:atomcode|client)[\s_-]*(?:version|ua)|user[\s_-]*agent|upgrade|update required|版本|客户端/i; + +const SIGNING_WORDS = + /sign(?:ature|ing)|x-atomcode|hmac|master[\s_-]*key|签名|密钥/i; + +const TIMEOUT_WORDS = /timeout|timed out|abort(?:ed)?|超时/i; +const NETWORK_WORDS = + /fetch failed|network|socket|econn(?:reset|refused|aborted)|enotfound|eai_again|dns|tls|certificate|网络|连接/i; + +function messageOf(error) { + return redactText(error?.message ?? error ?? "", 300); +} + +function numericStatus(error) { + const value = Number(error?.status ?? error?.statusCode); + return Number.isInteger(value) && value >= 100 && value <= 599 ? value : undefined; +} + +function explicitCategory(error) { + const value = error?.category ?? error?.kind ?? error?.code; + return Object.values(FAILURE).includes(value) ? value : undefined; +} + +function forbiddenCategory(message) { + if (CREDENTIAL_WORDS.test(message)) return FAILURE.CREDENTIAL_FORBIDDEN; + if (ENTITLEMENT_WORDS.test(message)) return FAILURE.ENTITLEMENT_FORBIDDEN; + return FAILURE.FORBIDDEN; +} + +/** + * Classify an error without changing it. + * + * @param {unknown} error + * @param {{stage?: string}} [context] + * @returns {{category: string, status?: number, message: string, retryable: boolean, + * refresh: boolean, signInExpired: boolean}} + */ +export function classifyError(error, { stage } = {}) { + const status = numericStatus(error); + const message = messageOf(error); + let category = explicitCategory(error); + + if (!category && error?.name === "TimeoutError") category = FAILURE.TIMEOUT; + if (!category && (error?.name === "AbortError" || TIMEOUT_WORDS.test(message))) { + category = FAILURE.TIMEOUT; + } + if (!category && stage === "signing") category = FAILURE.SIGNING; + if (!category && (SIGNING_WORDS.test(message) || /request body type for signing/i.test(message))) { + category = FAILURE.SIGNING; + } + if (!category && /changed accounts|账号已切换/i.test(message)) { + category = FAILURE.CLI_ACCOUNT_CHANGED; + } + if (!category && /no coding plan tier|not eligible|ineligible|no tier|名额|档位/i.test(message)) { + category = FAILURE.INELIGIBLE; + } + if (!category && status === 401) category = FAILURE.UNAUTHORIZED; + if (!category && status === 403) category = forbiddenCategory(message); + if (!category && status === 429) category = FAILURE.RATE_LIMIT; + if (!category && status !== undefined && status >= 500) category = FAILURE.SERVER; + if (!category && VERSION_WORDS.test(message)) category = FAILURE.VERSION; + if (!category && NETWORK_WORDS.test(message)) category = FAILURE.NETWORK; + category ??= FAILURE.UNKNOWN; + + const retryable = [ + FAILURE.NETWORK, + FAILURE.TIMEOUT, + FAILURE.RATE_LIMIT, + FAILURE.SERVER, + ].includes(category); + const refresh = + category === FAILURE.UNAUTHORIZED || + category === FAILURE.CREDENTIAL_FORBIDDEN || + category === FAILURE.CLI_ACCOUNT_CHANGED; + + return { + category, + ...(status === undefined ? {} : { status }), + message, + retryable, + refresh, + signInExpired: + category === FAILURE.UNAUTHORIZED || + category === FAILURE.CREDENTIAL_FORBIDDEN || + category === FAILURE.CLI_ACCOUNT_CHANGED, + }; +} + +/** True only for a credential/session refusal that may be renewed. */ +export function isCredentialFailure(error, context) { + return classifyError(error, context).refresh; +} + +/** True for failures another attempt may recover from. */ +export function isTransientFailure(error, context) { + return classifyError(error, context).retryable; +} + +/** + * Attach the classification to an existing Error without copying its secrets + * into a new message. Existing `signIn` is preserved unless it is wrong. + */ +export function annotateError(error, context) { + if (!(error instanceof Error)) { + const original = error; + error = new Error(messageOf(original)); + if (original?.status !== undefined) error.status = original.status; + if (original?.statusCode !== undefined) error.status = original.statusCode; + } + const result = classifyError(error, context); + error.category ??= result.category; + if (result.status !== undefined) error.status ??= result.status; + if (result.signInExpired) error.signIn = "expired"; + else if (error.signIn === "expired") delete error.signIn; + return error; +} + +/** The Magpie header that keeps an account signed in without reporting an error. */ +export function keptResponseHeaders(response, classification) { + if ( + response?.status === 403 && + classification?.category !== FAILURE.CREDENTIAL_FORBIDDEN + ) { + const headers = new Headers(response.headers); + headers.set("x-magpie-sign-in", "kept"); + return new Response(response.body, { + status: response.status, + statusText: response.statusText, + headers, + }); + } + return response; +} diff --git a/packages/atomcode/i18n.mjs b/packages/atomcode/i18n.mjs new file mode 100644 index 0000000..57ac21f --- /dev/null +++ b/packages/atomcode/i18n.mjs @@ -0,0 +1,190 @@ +/** + * UI strings, zh and en. + * + * These labels land in Magpie's own account card, in `magpie quota`, and in the + * sign-in flow, so they are user-visible, not decoration. The language is the + * plugin's `locale` option, defaulting to following the machine. + * + * @module magpie-atomcode/i18n + */ + +/** The languages with a string table here. */ +export const LOCALES = ["zh", "en"]; + +const ZH = { + locale: "zh", + + methodLabel: "AtomGit 登录(浏览器)", + instructions: "浏览器将打开 AtomGit 登录页完成授权;授权完成后回到这里等待,登录会自动完成。", + cliMethodLabel: "使用本机 AtomCode 登录", + cliInstructions: "请先运行 AtomCode CLI 完成登录,再回到这里继续;插件会读取指定路径(默认 ~/.atomcode/auth.toml)并安全地复用、续期该登录。", + cliAuthFilePrompt: "AtomCode auth.toml 路径(留空使用默认路径)", + cliAuthFileInvalid: "auth.toml 路径必须是绝对路径或以 ~/ 开头", + cliLoginFailed: "没有读到可用的 AtomCode CLI 登录:{detail}", + cliAccountChanged: "本机 AtomCode 登录已切换账号,请在 magpie 中重新登录", + loginTimeout: "登录超时(浏览器授权没有在 9 分钟内完成),请重试", + loginFailed: "登录失败:{detail}", + loginIncomplete: "授权流程没有返回完整账号信息,请重试", + + + reloginRequired: "AtomCode 登录已失效,请重新登录", + refreshFailed: "AtomCode 令牌续期失败:{detail}", + authFileReadFailed: "读取 AtomCode CLI 登录失败:{detail}", + authFileWriteFailed: "回写 AtomCode CLI 登录失败:{detail}", + authPersistFailed: "magpie 保存续期后的登录失败:{detail}", + stateWriteFailed: "保存 AtomCode 本地诊断状态失败:{detail}", + cannotSign: "账号信息缺少 user id,无法生成请求签名,请重新登录", + noAccount: "没有已登录的 AtomCode 账号", + planFallback: "AtomCode CodingPlan", + reclaimed: "套餐已重新领取:{plan}", + reclaimFailed: "自动重领未成功:{detail}", + checkinDone: "套餐仍有效,无需重领", + checkinDoneWithPlan: "套餐仍有效,无需重领({plan})", + checkinIneligible: "当前没有可用套餐名额,请稍后重试", + + + usageHttp: "读取额度失败 HTTP {status}", + readFailed: "读取额度失败:{detail}", + usageStale: "额度刷新失败,显示上次成功快照:{detail}", + usageTimeout: "读取额度超时,请稍后重试", + + windowHours: "{hours} 小时额度", + windowTokens: "{hours} 小时 Token 额度", + callsOf: "{used} / {total} 次", + tokensOf: "{used} / {total} tokens", + + + modelsUnavailable: "模型目录暂时不可用,沿用内置列表", + modelListEmpty: "模型目录为空(计划可能未领取),沿用内置列表", + modelBaseUrlDenied: "模型自带地址不在白名单,已改用官方网关", + modelKeyCollision: "模型 key {detail} 冲突,已改用 {key}", + endpointDenied: "配置项 {name} 的地址不被接受,已改用官方端点", + optionInvalid: "配置项 {name} 的值无效,已改用默认值", + foreignTargetBlocked: "已拦截请求:目标 {origin} 不是 AtomCode 官方网关", + diagnosticsStarted: "只读诊断页已启动:http://127.0.0.1:{port}/", + diagnosticsFailed: "只读诊断页启动失败:{detail}", + autoClaimLabel: "自动领取套餐", + autoClaimDescription: "登录后幂等领取 CodingPlan,并在套餐到期时自动重领。", + autoVersionLabel: "自动跟随客户端版本", + autoVersionDescription: "从 AtomCode 官方仓库后台刷新版本号,用于签名与 User-Agent。", +}; + +const EN = { + locale: "en", + + methodLabel: "AtomGit Sign-in (browser)", + instructions: "Your browser will open the AtomGit sign-in page; after authorizing, come back here and the sign-in completes by itself.", + cliMethodLabel: "Use the AtomCode CLI sign-in on this computer", + cliInstructions: "Sign in with the AtomCode CLI first, then continue here. The plugin reads the selected path (default ~/.atomcode/auth.toml) and safely reuses and renews that sign-in.", + cliAuthFilePrompt: "AtomCode auth.toml path (leave blank for the default)", + cliAuthFileInvalid: "The auth.toml path must be absolute or start with ~/", + cliLoginFailed: "No usable AtomCode CLI sign-in was found: {detail}", + cliAccountChanged: "The local AtomCode CLI sign-in changed accounts; sign in again in magpie", + loginTimeout: "Timed out (browser authorization not finished within 9 minutes); please retry", + loginFailed: "Sign-in failed: {detail}", + loginIncomplete: "The authorization flow returned incomplete account info; please retry", + + + reloginRequired: "The AtomCode sign-in has expired; please sign in again", + refreshFailed: "Renewing the AtomCode token failed: {detail}", + authFileReadFailed: "Reading the AtomCode CLI sign-in failed: {detail}", + authFileWriteFailed: "Writing the renewed AtomCode CLI sign-in failed: {detail}", + authPersistFailed: "magpie failed to save the renewed sign-in: {detail}", + stateWriteFailed: "Saving AtomCode diagnostics state failed: {detail}", + cannotSign: "The stored account lacks its user id, so requests cannot be signed; please sign in again", + noAccount: "No signed-in AtomCode account", + planFallback: "AtomCode CodingPlan", + reclaimed: "Plan reclaimed: {plan}", + reclaimFailed: "Automatic re-claim failed: {detail}", + checkinDone: "The plan is still active; nothing new to claim", + checkinDoneWithPlan: "The plan is still active; nothing to claim ({plan})", + checkinIneligible: "No CodingPlan slot is currently available; try again later", + + + usageHttp: "Reading the quota failed with HTTP {status}", + readFailed: "Reading the quota failed: {detail}", + usageStale: "The quota refresh failed; showing the last successful snapshot: {detail}", + usageTimeout: "Reading the quota timed out; please retry later", + + windowHours: "{hours}h window", + windowTokens: "{hours}h token window", + callsOf: "{used} / {total} calls", + tokensOf: "{used} / {total} tokens", + + + modelsUnavailable: "The model catalog is unavailable; keeping the built-in list", + modelListEmpty: "The model catalog is empty (the plan may need claiming); keeping the built-in list", + modelBaseUrlDenied: "A model asked for an address that is not allowlisted; using the official gateway instead", + modelKeyCollision: "Model key {detail} collided; using {key} instead", + endpointDenied: "Option {name} pointed at an address that is not accepted; using the official endpoint instead", + optionInvalid: "Option {name} had an invalid value; using the default", + foreignTargetBlocked: "Blocked a request to {origin}: it is not the AtomCode gateway", + diagnosticsStarted: "Read-only diagnostics started at http://127.0.0.1:{port}/", + diagnosticsFailed: "Read-only diagnostics could not start: {detail}", + autoClaimLabel: "Claim plans automatically", + autoClaimDescription: "Idempotently claim CodingPlan after sign-in and re-claim it when the plan expires.", + autoVersionLabel: "Follow the client version", + autoVersionDescription: "Refresh the version from AtomCode's official repository in the background for signing and User-Agent.", +}; + +const TABLES = { zh: ZH, en: EN }; + +/** + * Fill `{name}` placeholders. Unknown names are left as they are, so a missing + * string shows up in the UI instead of turning into "undefined". + */ +export function fill(template, values) { + return String(template).replace(/\{(\w+)\}/g, (whole, key) => + key in values ? String(values[key]) : whole + ); +} + +/** The table for a resolved locale. */ +export function strings(locale = "zh") { + return TABLES[locale] ?? ZH; +} + +/** The OS locale as Node reports it, or "" when there is nothing to report. */ +function osLocale() { + try { + return typeof Intl !== "undefined" && typeof Intl.DateTimeFormat === "function" + ? Intl.DateTimeFormat().resolvedOptions().locale + : ""; + } catch { + return ""; + } +} + +/** + * Decide the locale. + * + * `Intl` first (reflects OS settings on every platform including Windows, where + * `LANG` is usually unset), then the environment as a fallback for a Node built + * without ICU; a POSIX `C`/`POSIX` value is skipped rather than misread. + * + * @param {string|undefined} value - the `locale` option: `"auto"`, `"zh"`, or `"en"`. + * @param {object} [env] - environment to read, injected for testing. + * @param {string} [intl] - the OS locale, injected for testing. + * @returns {"zh"|"en"} + */ +export function resolveLocale(value, env = process.env, intl = osLocale()) { + if (value === "zh" || value === "en") return value; + if (value && value !== "auto") { + const explicit = String(value).toLowerCase(); + if (explicit.startsWith("zh")) return "zh"; + if (explicit.startsWith("en")) return "en"; + } + + if (/^zh/i.test(intl)) return "zh"; + if (/^en/i.test(intl)) return "en"; + + for (const key of ["LC_ALL", "LC_MESSAGES", "LANG"]) { + const raw = env?.[key]; + if (typeof raw !== "string") continue; + const tag = raw.trim().split(".")[0].split("_")[0].toLowerCase(); + if (!tag || tag === "c" || tag === "posix") continue; + if (tag.startsWith("zh")) return "zh"; + if (tag.startsWith("en")) return "en"; + } + return "en"; +} diff --git a/packages/atomcode/index.mjs b/packages/atomcode/index.mjs new file mode 100644 index 0000000..336cf6c --- /dev/null +++ b/packages/atomcode/index.mjs @@ -0,0 +1,1324 @@ +/** + * AtomCode (AtomGit CodingPlan) provider plugin for Magpie. + * + * Direct-to-upstream, no Atom2Api instance in between: + * + * - **Sign-in** is browser OAuth via the AtomGit broker (`acs.atomgit.com`); + * tokens live in Magpie's `plugin-auth.json` and are renewed either by + * `auth.refresh` (Magpie ≥ 0.1.684) or, on OpenCode and older Magpie hosts, + * by the fallback refresh inside `fetch`. + * - **Requests** reach `https://llm-api.atomgit.com/v1` as plain Chat + * Completions (`@ai-sdk/openai-compatible`); this plugin's `fetch` adds the + * `atomcode-signing-v1` headers plus the required `atomcode/` + * User-Agent, then forwards untouched — body, streams and everything. + * - **Model & quota** come from CodingPlan REST (`api.gitcode.com`), mapped so + * the account row and `magpie quota` show the plan and its 5-hour window. + * + * This file exports **exactly one function, and nothing else** — the module + * must also load under OpenCode, which calls every exported function. Helpers + * live in `internal.mjs`, `sign.mjs`, `oauth.mjs`, `codingplan.mjs`, `quota.mjs` + * and `models.mjs`. + * + * @module magpie-atomcode + */ + +import { + DEFAULT_CLIENT_VERSION, + DEFAULT_CODING_PLAN_API_URL, + DEFAULT_PLATFORM_BASE_URL, + DEFAULT_GATEWAY_BASE_URL, + ICON, + PROVIDER, + credentialsOf, + fellBack, + originOf, + readAuth, + readCappedResponseText, + redactText, + trustedServiceURL, + upstreamMessage, +} from "./internal.mjs"; +import { MASTER_KEY_HEX, signAtomGitRequest } from "./sign.mjs"; +import { + checkLogin, + refreshTokens, + startLogin, + tokenFor, + userAgentOf, +} from "./oauth.mjs"; +import { claimCodingPlan, fetchStatus, planNeedsClaim } from "./codingplan.mjs"; +import { createVersionSource } from "./version.mjs"; +import { quotaFromStatus } from "./quota.mjs"; +import { + FALLBACK_MODELS, + NPM, + createCatalog, + normalizeCodingPlanModel, + toConfigModel, + toProviderModel, +} from "./models.mjs"; +import { fill, resolveLocale, strings as tableFor } from "./i18n.mjs"; +import { + readAuthFile, + resolveAuthFilePath, + writeAuthFile, +} from "./auth-file.mjs"; +import { includeStreamUsage, normalizeRequestBody } from "./request-body.mjs"; +import { + FAILURE, + annotateError, + classifyError, + isCredentialFailure, + keptResponseHeaders, +} from "./errors.mjs"; +import { createStateStore } from "./state.mjs"; +import { + DEFAULT_DIAGNOSTICS_PORT, + diagnosticsPort, + startDiagnosticsService, +} from "./diagnostics.mjs"; + +const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); +const AUTH_REFRESH_SKEW_MS = 30_000; +const USAGE_BUDGET_MS = 18_000; + +/** + * Build the plugin. + * + * @param {{client?: object, directory?: string, magpie?: object}} input - + * the plugin input the Magpie or OpenCode host passes. + * @param {object} [options] - the `options` field from `plugins.json`: + * `locale`, `clientVersion`, `masterKeyHex`, `platformBaseURL`, + * `codingPlanAPIURL`, `quotaTtlMs`, `maxOutputTokens`, `diagnosticsPort`. + * @returns {Promise} the hooks the host calls. + */ +export async function AtomCodePlugin(input = {}, options = {}) { + input = input && typeof input === "object" ? input : {}; + const { client, magpie } = input; + const directory = typeof input.directory === "string" ? input.directory : undefined; + options = options && typeof options === "object" ? options : {}; + const t = tableFor(resolveLocale(options.locale)); + + /** Options that were rejected while reading; reported once `log` exists. */ + const optionWarnings = []; + const warnInvalid = (name) => optionWarnings.push({ key: "optionInvalid", name }); + const positiveInteger = (name, value, fallback, max = Number.MAX_SAFE_INTEGER) => { + const parsed = Number(value); + if (Number.isInteger(parsed) && parsed > 0 && parsed <= max) return parsed; + if (value !== undefined) warnInvalid(name, value); + return fallback; + }; + + const configuredVersion = options.clientVersion; + const clientVersion = + typeof configuredVersion === "string" && + /^[A-Za-z0-9][A-Za-z0-9._+-]{0,63}$/.test(configuredVersion.trim()) + ? configuredVersion.trim() + : DEFAULT_CLIENT_VERSION; + if (configuredVersion !== undefined && clientVersion === DEFAULT_CLIENT_VERSION) { + const accepted = + typeof configuredVersion === "string" && + configuredVersion.trim() === DEFAULT_CLIENT_VERSION; + if (!accepted) warnInvalid("clientVersion", configuredVersion); + } + + const configuredMasterKey = String(options.masterKeyHex ?? ""); + const masterKeyHex = /^[0-9a-fA-F]{64}$/.test(configuredMasterKey) + ? configuredMasterKey + : MASTER_KEY_HEX; + if (options.masterKeyHex !== undefined && masterKeyHex === MASTER_KEY_HEX && configuredMasterKey !== MASTER_KEY_HEX) { + warnInvalid("masterKeyHex", configuredMasterKey); + } + + if (options.autoVersion !== undefined && typeof options.autoVersion !== "boolean") { + warnInvalid("autoVersion", options.autoVersion); + } + if (options.autoClaim !== undefined && typeof options.autoClaim !== "boolean") { + warnInvalid("autoClaim", options.autoClaim); + } + + const nativeBoolean = (key) => { + try { + const value = magpie?.option?.(PROVIDER, key); + return typeof value === "boolean" ? value : undefined; + } catch { + return undefined; + } + }; + const automationValue = (explicit, nativeKey) => + typeof explicit === "boolean" ? explicit : nativeBoolean(nativeKey) ?? true; + const autoClaimEnabled = () => automationValue(options.autoClaim, "auto_claim"); + const autoVersionEnabled = () => automationValue(options.autoVersion, "auto_version"); + + const configuredDiagnosticsPort = options.diagnosticsPort; + const selectedDiagnosticsPort = diagnosticsPort( + configuredDiagnosticsPort, + DEFAULT_DIAGNOSTICS_PORT, + ); + if ( + configuredDiagnosticsPort !== undefined && + selectedDiagnosticsPort === DEFAULT_DIAGNOSTICS_PORT && + Number(configuredDiagnosticsPort) !== DEFAULT_DIAGNOSTICS_PORT + ) { + warnInvalid("diagnosticsPort", configuredDiagnosticsPort); + } + + const opts = { + clientVersion, + // 逃生口:上游换 master key 时不发版热修(对齐 Atom2Api 的 signer_url 思路)。 + masterKeyHex, + // 端点选项可覆盖,但必须是 https 且落在上游自家域名族:token 会发往这里, + // 一份被塞改的 plugins.json 不该能把它引到别处。 + platformBaseURL: trustedServiceURL(options.platformBaseURL, { + fallback: DEFAULT_PLATFORM_BASE_URL, + domains: ["acs.atomgit.com"], + exact: true, + onReject: () => + optionWarnings.push({ key: "endpointDenied", name: "platformBaseURL" }), + }), + codingPlanAPIURL: trustedServiceURL(options.codingPlanAPIURL, { + fallback: DEFAULT_CODING_PLAN_API_URL, + domains: ["api.gitcode.com"], + exact: true, + onReject: () => + optionWarnings.push({ key: "endpointDenied", name: "codingPlanAPIURL" }), + }), + gatewayURL: DEFAULT_GATEWAY_BASE_URL, + quotaTtlMs: positiveInteger("quotaTtlMs", options.quotaTtlMs, 60_000, 24 * 3600_000), + maxOutputTokens: positiveInteger( + "maxOutputTokens", + options.maxOutputTokens, + 32_768, + 1_000_000, + ), + diagnosticsPort: selectedDiagnosticsPort, + }; + + /** + * The only origin requests may leave for. + * + * `origin` covers scheme + host + port, so an `http://` downgrade of the same + * host cannot pass this comparison either. + */ + const gatewayOrigin = originOf(opts.gatewayURL); + + const log = (level, message) => { + try { + client?.app?.log?.({ body: { service: PROVIDER, level, message } }); + } catch { + /* the host's logger is best-effort */ + } + }; + + for (const warning of optionWarnings) { + log( + "warn", + `${PROVIDER}: ${fill(t[warning.key], { name: warning.name })}`, + ); + } + + const stateStore = createStateStore({ + directory, + onError: (error) => + log( + "warn", + `${PROVIDER}: ${fill(t.stateWriteFailed, { + detail: redactText(error.message), + })}`, + ), + }); + + const rememberFailure = (uid, error, context = {}) => { + const failure = classifyError(error, context); + void stateStore.recordError(uid, { + category: failure.category, + message: failure.message, + status: failure.status, + at: Date.now(), + }); + return failure; + }; + + const catalog = createCatalog({ + apiBase: opts.codingPlanAPIURL, + clientVersion: opts.clientVersion, + output: opts.maxOutputTokens, + onReject: () => log("warn", `${PROVIDER}: ${t.modelBaseUrlDenied}`), + }); + + const versionSource = createVersionSource({ + fallback: opts.clientVersion, + onError: (error) => log("warn", `${PROVIDER}: version check: ${error.message}`), + onChange: (status) => + void stateStore.recordVersion({ + ...status, + checkedAt: status.checkedAt, + }), + }); + // 宿主一启动就后台探一次;首个真实请求到达前多半已就位。 + if (autoVersionEnabled()) versionSource.poke(); + void stateStore.recordVersion(versionSource.status()); + + /** 本次请求用的版本号:UA、X-AtomCode-Ver、签名盐取同一值(绝不抛错)。 */ + const clientVersionNow = () => + autoVersionEnabled() + ? versionSource.ensure() + : Promise.resolve(opts.clientVersion); + + const seedModels = () => + Object.fromEntries( + FALLBACK_MODELS.map((raw) => { + const m = normalizeCodingPlanModel(raw, { output: opts.maxOutputTokens }); + return [m.key, toConfigModel(m)]; + }), + ); + + const providerModels = (list) => { + const result = Object.create(null); + for (const model of list) { + let key = model.key; + let suffix = 2; + while (Object.hasOwn(result, key)) { + key = `${model.key}_${suffix++}`; + } + if (key !== model.key) { + log( + "warn", + `${PROVIDER}: ${fill(t.modelKeyCollision, { detail: model.key, key })}`, + ); + } + result[key] = toProviderModel({ ...model, key }, PROVIDER, { + baseURL: opts.gatewayURL, + npm: NPM, + }); + } + return result; + }; + + /** How the provider row names this account. */ + const userLabel = (auth) => { + if (!auth || typeof auth !== "object") return undefined; + return auth.name ?? auth.email ?? auth.accountId; + }; + + const markExpired = (message = t.reloginRequired) => + Object.assign(new Error(message), { signIn: "expired" }); + + const remainingMs = (deadline) => + deadline === undefined ? undefined : Math.max(0, deadline - Date.now()); + + const timed = (promise, deadline) => { + const remaining = remainingMs(deadline); + if (remaining === undefined) return promise; + if (remaining <= 0) return Promise.resolve(undefined); + let timer; + const timeout = new Promise((resolve) => { + timer = setTimeout(() => resolve(undefined), remaining); + }); + return Promise.race([promise, timeout]).finally(() => clearTimeout(timer)); + }; + + async function classifyGatewayResponse(response) { + const base = { status: response?.status, message: "" }; + if (response?.status !== 403) return classifyError(base); + try { + const text = await readCappedResponseText(response.clone(), { + maxBytes: 16 << 10, + label: "gateway error", + }); + base.message = upstreamMessage(text); + } catch { + /* A non-JSON or oversized error body stays a plain 403. */ + } + return classifyError(base); + } + + /** + * Renew one account's token. + * + * Keyed singleflight on the refresh token, plus a short-lived result cache. + * The cache matters after the singleflight settles: persistence and the next + * request are not atomic, and a rotate-once upstream would reject a second + * refresh with the old token. Results are addressable by both the old and the + * new refresh token. + */ + const refreshInflight = new Map(); + const refreshResults = new Map(); + const REFRESH_CACHE_TTL_MS = 24 * 3600_000; + + function rememberRefresh(oldToken, next) { + const at = Date.now(); + refreshResults.set(oldToken, { at, next }); + if (next.refresh && next.refresh !== oldToken) { + refreshResults.set(next.refresh, { at, next }); + } + for (const [token, entry] of refreshResults) { + if (at - entry.at > REFRESH_CACHE_TTL_MS) refreshResults.delete(token); + } + } + + async function refreshAccount(credentials, { deadline } = {}) { + if (!credentials?.refresh) { + throw markExpired(); + } + const cached = refreshResults.get(credentials.refresh); + if (cached && Date.now() - cached.at < REFRESH_CACHE_TTL_MS) return cached.next; + const pending = refreshInflight.get(credentials.refresh); + if (pending) return pending; + const p = (async () => { + // expires 已过时兜底值取旧剩余;上游不给 expires_in 时沿用旧宽度 + // (Atom2Api 同款:缺省找回旧值)。 + const oldSpanSec = + credentials.expires && credentials.expires > Date.now() + ? Math.max(1, Math.round((credentials.expires - Date.now()) / 1000)) + : 0; + const next = await refreshTokens( + opts.platformBaseURL, + credentials.refresh, + { + clientVersion: opts.clientVersion, + fallbackExpiresIn: oldSpanSec > 0 ? oldSpanSec : undefined, + timeoutMs: Math.max(250, Math.min(15_000, remainingMs(deadline) ?? 15_000)), + }, + ); + const expiresInSec = + next.expiresIn > 0 ? next.expiresIn : oldSpanSec > 0 ? oldSpanSec : 7 * 24 * 3600; + const renewed = { + access: next.accessToken, + refresh: next.refreshToken ?? credentials.refresh, + expires: Date.now() + expiresInSec * 1000, + }; + rememberRefresh(credentials.refresh, renewed); + return renewed; + })().finally(() => refreshInflight.delete(credentials.refresh)); + refreshInflight.set(credentials.refresh, p); + return p; + } + + function credentialsWith(raw, credentials, next) { + return { + ...(raw ?? {}), + type: "oauth", + access: next.access, + refresh: next.refresh, + expires: next.expires, + uid: credentials.uid, + ...(credentials.accountId ? { accountId: credentials.accountId } : {}), + ...(credentials.email ? { email: credentials.email } : {}), + ...(credentials.name ? { name: credentials.name } : {}), + }; + } + + async function persistRenewed(raw, credentials, next) { + const updated = credentialsWith(raw, credentials, next); + let saved = false; + if (raw?.source === "atomcode-cli") { + try { + const path = resolveAuthFilePath(raw.authFile); + const latest = await readAuthFile(path); + if (latest.uid !== credentials.uid) { + throw markExpired(t.cliAccountChanged); + } + await writeAuthFile(path, { + access: next.access, + refresh: next.refresh, + createdAt: Math.floor(Date.now() / 1000), + expiresIn: Math.max(1, Math.floor((next.expires - Date.now()) / 1000)), + user: { + id: credentials.uid, + ...(credentials.name ? { name: credentials.name } : {}), + ...(credentials.email ? { email: credentials.email } : {}), + }, + }); + saved = true; + } catch (error) { + if (error.signIn === "expired") throw error; + log( + "warn", + `${PROVIDER}: ${fill(t.authFileWriteFailed, { detail: redactText(error.message) })}`, + ); + } + } + if (typeof client?.auth?.set === "function") { + try { + await client.auth.set({ path: { id: PROVIDER }, body: updated }); + saved = true; + } catch (error) { + log( + "warn", + `${PROVIDER}: ${fill(t.authPersistFailed, { detail: redactText(error.message) })}`, + ); + } + } + return { updated, saved }; + } + + async function rereadCliAuth(raw, credentials) { + if (raw?.source !== "atomcode-cli") return { raw, credentials, changed: false }; + try { + const latest = await readAuthFile(resolveAuthFilePath(raw.authFile)); + if (credentials?.uid && latest.uid !== credentials.uid) { + throw markExpired(t.cliAccountChanged); + } + return { + raw: { ...raw, ...latest, source: "atomcode-cli", authFile: latest.path }, + credentials: credentialsOf(latest), + changed: + latest.access !== credentials?.access || + latest.refresh !== credentials?.refresh || + latest.expires !== credentials?.expires, + }; + } catch (error) { + if (error.signIn === "expired") throw error; + log( + "warn", + `${PROVIDER}: ${fill(t.authFileReadFailed, { detail: redactText(error.message) })}`, + ); + return { raw, credentials, changed: false }; + } + } + + /** + * Resolve the freshest stored credentials and renew once when needed. + * + * `input` may be an auth record or `getAuth`. CLI-backed accounts re-read + * auth.toml every time, so the official client remains the source of truth. + */ + async function currentCredentials(input, { forceRefresh = false, deadline } = {}) { + let raw = typeof input === "function" ? await readAuth(input) : input; + let credentials = credentialsOf(raw); + if (!credentials) return { raw, credentials: undefined, renewed: false }; + + const latest = await rereadCliAuth(raw, credentials); + raw = latest.raw; + credentials = latest.credentials; + let renewed = latest.changed; + if (!credentials) return { raw, credentials: undefined, renewed }; + + const expiring = + credentials.expires !== undefined && + credentials.expires <= Date.now() + AUTH_REFRESH_SKEW_MS; + if (!forceRefresh && !expiring) return { raw, credentials, renewed }; + if (latest.changed && credentials.expires && credentials.expires > Date.now()) { + return { raw, credentials, renewed: true }; + } + if (!credentials.refresh) throw markExpired(); + + let next; + try { + next = await refreshAccount(credentials, { deadline }); + } catch (error) { + if (error.signIn === "expired") throw markExpired(); + log( + "warn", + `${PROVIDER}: ${fill(t.refreshFailed, { detail: redactText(error.message) })}`, + ); + return { raw, credentials, renewed, refreshFailed: true }; + } + const persisted = await persistRenewed(raw, credentials, next); + raw = persisted.updated; + credentials = credentialsOf(raw); + return { raw, credentials, renewed: true }; + } + + /** Cache quota per account so a polled hook costs one request a minute. */ + const quotaCache = new Map(); + + /** + * 签到(重领):套餐缺失或到期时按档位级联补领一次。 + * + * 只在 status 判定确实需要时才动手(planNeedsClaim,保守判定),30 分钟 + * 冷却防止在"日限额已满"的放量节奏上空转;结果只进日志,绝不影响 + * usage / models 的正常返回。 + */ + const RECLAIM_COOLDOWN_MS = 30 * 60_000; + const claimCooldown = new Map(); + const claimInflight = new Map(); + const claimResults = new Map(); + const CLAIM_RESULT_TTL_MS = 5_000; + + async function claimOnce(credentials, { deadline } = {}) { + const key = credentials.uid ?? credentials.access; + const pending = claimInflight.get(key); + if (pending) return (await timed(pending, deadline)) ?? null; + const cached = claimResults.get(key); + if (cached && Date.now() - cached.at < CLAIM_RESULT_TTL_MS) return cached.result; + if (Date.now() < (claimCooldown.get(key) ?? 0)) return null; + const remaining = remainingMs(deadline); + if (remaining !== undefined && remaining <= 0) return null; + claimCooldown.set(key, Date.now() + RECLAIM_COOLDOWN_MS); + const p = clientVersionNow() + .then((clientVersion) => + claimCodingPlan(opts.codingPlanAPIURL, credentials.access, { + clientVersion, + timeoutMs: Math.max(250, Math.min(8_000, remaining ?? 8_000)), + totalTimeoutMs: Math.max(250, Math.min(12_000, remaining ?? 12_000)), + }), + ) + .then((result) => { + claimResults.set(key, { at: Date.now(), result }); + return result; + }) + .finally(() => claimInflight.delete(key)); + claimInflight.set(key, p); + return (await timed(p, deadline)) ?? null; + } + + async function ensurePlan(credentials, { status, deadline } = {}) { + if (!autoClaimEnabled()) return false; + try { + if (!status) { + const remaining = remainingMs(deadline); + if (remaining !== undefined && remaining <= 0) return false; + status = await fetchStatus(opts.codingPlanAPIURL, credentials.access, { + clientVersion: await clientVersionNow(), + timeoutMs: Math.max(250, Math.min(7_000, remaining ?? 7_000)), + }); + } + if (!planNeedsClaim(status)) return false; + } catch (error) { + log( + "warn", + `${PROVIDER}: ${fill(t.readFailed, { detail: redactText(error.message) })}`, + ); + return false; + } + try { + const claim = await claimOnce(credentials, { deadline }); + if (!claim) return false; + if (claim.claimed) log("info", `${PROVIDER}: ${fill(t.reclaimed, { plan: claim.planName || claim.tier })}`); + else { + log( + "warn", + `${PROVIDER}: ${fill(t.reclaimFailed, { detail: redactText(claim.message) })}`, + ); + } + return claim.claimed; + } catch (error) { + log( + "warn", + `${PROVIDER}: ${fill(t.reclaimFailed, { detail: redactText(error.message) })}`, + ); + return false; + } + } + + const hooks = { + /** Declare the provider and its snapshot models. */ + config: async (cfg) => { + cfg.provider ??= {}; + const was = cfg.provider[PROVIDER] ?? {}; + cfg.provider[PROVIDER] = { + // 显示名固定全大写(设置页卡片/标签用);provider id 仍是小写 atomcode + name: "ATOMCODE", + npm: NPM, + api: opts.gatewayURL, + ...was, + models: { ...seedModels(), ...(was.models ?? {}) }, + }; + }, + + provider: { + id: PROVIDER, + /** + * The models this account can actually use. + * + * Failing (or an empty catalog) falls back to the declared list marked + * `fellBack`, so the provider never vanishes; an expired sign-in throws, + * which marks the account for re-login. + */ + async models(provider, { auth } = {}) { + const declared = provider?.models ?? seedModels(); + let raw; + let credentials; + try { + ({ raw, credentials } = await currentCredentials(auth)); + } catch (error) { + if (error.signIn === "expired") throw error; + log( + "warn", + `${PROVIDER}: ${fill(t.refreshFailed, { detail: redactText(error.message) })}`, + ); + return fellBack(declared); + } + if (!credentials?.access) return fellBack(declared); + try { + const loadCatalog = async (current) => + catalog.load(current, { clientVersion: await clientVersionNow() }); + let list; + try { + list = await loadCatalog(credentials); + } catch (error) { + if (error.signIn !== "expired" || !credentials.refresh) throw error; + const retry = await currentCredentials(auth, { forceRefresh: true }); + if (!retry.credentials?.access || retry.credentials.access === credentials.access) { + throw error; + } + credentials = retry.credentials; + list = await loadCatalog(credentials); + } + // 目录为空的合法场景之一是"权益还没发放"(官方注释同款)——先签到重领一次再取。 + if ( + !list.length && + (await ensurePlan(credentials, { deadline: Date.now() + USAGE_BUDGET_MS })) + ) { + list = await loadCatalog(credentials); + } + if (!list.length) { + log("warn", `${PROVIDER}: ${t.modelListEmpty}`); + const cached = await stateStore.cachedModels(credentials.uid); + if (cached.length) return fellBack(providerModels(cached)); + return fellBack(declared); + } + await stateStore.recordModels(credentials.uid, list, { source: "live" }); + await stateStore.recordLogin(credentials.uid, raw?.source ?? "browser"); + return providerModels(list); + } catch (error) { + if (error.signIn === "expired") throw error; + rememberFailure(credentials.uid, error, { stage: "models" }); + const cached = await stateStore.cachedModels(credentials.uid); + if (cached.length) { + log( + "warn", + `${PROVIDER}: ${t.modelsUnavailable}: ${redactText(error.message)}`, + ); + return fellBack(providerModels(cached)); + } + log( + "warn", + `${PROVIDER}: ${t.modelsUnavailable}: ${redactText(error.message)}`, + ); + return fellBack(declared); + } + }, + }, + + auth: { + provider: PROVIDER, + ...(ICON === undefined ? {} : { icon: ICON }), + + /** Browser OAuth, plus reuse of the official CLI's local sign-in. */ + methods: [ + { + type: "oauth", + label: t.methodLabel, + async authorize() { + let started; + try { + started = await startLogin(opts.platformBaseURL, { clientVersion: await clientVersionNow() }); + } catch (error) { + throw new Error(fill(t.loginFailed, { detail: error.message })); + } + return { + url: started.loginUrl, + instructions: t.instructions, + method: "auto", + /** + * Poll until the browser side finishes: check → token, ~2.5 s + * cadence, ~9 min budget (the broker's own session is 10 min). + */ + async callback() { + const deadline = Date.now() + 9 * 60_000; + while (Date.now() < deadline) { + await sleep(2_500); + let valid = false; + try { + valid = await checkLogin(opts.platformBaseURL, started.state, { + clientVersion: await clientVersionNow(), + }); + } catch (error) { + log("warn", `${PROVIDER}: login check: ${redactText(error.message)}`); + continue; + } + if (!valid) continue; + try { + const token = await tokenFor(opts.platformBaseURL, started.state, { + clientVersion: await clientVersionNow(), + }); + // 签到闭环的最后一步(Atom2Api 登录后同款):把计划领上。 + // 幂等(重复领取返回 duplicate),失败只记日志、绝不拦登录。 + if (autoClaimEnabled()) { + // Claiming is useful but must never delay a completed + // sign-in. A later models/usage call retries idempotently. + void (async () => { + try { + const claim = await claimOnce({ + access: token.accessToken, + uid: String(token.user.id), + }); + if (!claim) return; + if (claim.claimed) log("info", `${PROVIDER}: coding plan: ${claim.planName || claim.tier}`); + else log("warn", `${PROVIDER}: coding plan: ${redactText(claim.message)}`); + } catch (error) { + log( + "warn", + `${PROVIDER}: coding plan claim failed: ${redactText(error.message)}`, + ); + } + })(); + } + void stateStore.recordLogin( + String(token.user.id), + "atomcode-browser", + ); + return { + type: "success", + source: "atomcode-browser", + refresh: token.refreshToken, + access: token.accessToken, + expires: Date.now() + (token.expiresIn > 0 ? token.expiresIn * 1000 : 7 * 24 * 3600_000), + // Magpie names the account from accountId, then metadata.email, + // then email — email first, per its own guidance. + accountId: token.user.email || token.user.username || String(token.user.id), + email: token.user.email || undefined, + name: token.user.name || token.user.username || undefined, + uid: String(token.user.id), + }; + } catch (error) { + log("warn", `${PROVIDER}: login finish: ${redactText(error.message)}`); + return { + type: "failed", + error: fill(t.loginFailed, { detail: redactText(error.message, 120) }), + }; + } + } + return { type: "failed", error: t.loginTimeout }; + }, + }; + }, + }, + { + type: "oauth", + label: t.cliMethodLabel, + prompts: [ + { + type: "text", + key: "authFile", + message: t.cliAuthFilePrompt, + placeholder: "~/.atomcode/auth.toml", + validate: (value) => { + try { + resolveAuthFilePath(value); + return undefined; + } catch { + return t.cliAuthFileInvalid; + } + }, + }, + ], + async authorize(inputs = {}) { + let authFile; + try { + authFile = resolveAuthFilePath(inputs.authFile); + } catch { + throw new Error(t.cliAuthFileInvalid); + } + return { + instructions: t.cliInstructions, + method: "auto", + async callback() { + try { + const auth = await readAuthFile(authFile); + void stateStore.recordLogin(auth.uid, "atomcode-cli"); + return { + type: "success", + source: "atomcode-cli", + authFile: auth.path, + access: auth.access, + refresh: auth.refresh, + expires: auth.expires, + accountId: auth.accountId, + email: auth.email, + name: auth.name, + uid: auth.uid, + }; + } catch (error) { + return { + type: "failed", + error: fill(t.cliLoginFailed, { detail: redactText(error.message, 120) }), + }; + } + }, + }; + }, + }, + ], + + /** + * Magpie's native provider switches. Explicit legacy `options` + * (`autoClaim`/`autoVersion`) win for compatibility; otherwise these + * values are read live from `input.magpie.option`. + */ + options: [ + { + key: "auto_claim", + label: t.autoClaimLabel, + description: t.autoClaimDescription, + default: true, + labels: { zh: "自动领取套餐", en: "Claim plans automatically" }, + descriptions: { + zh: "登录后幂等领取 CodingPlan,并在套餐到期时自动重领。", + en: "Idempotently claim CodingPlan after sign-in and re-claim it when the plan expires.", + }, + }, + { + key: "auto_version", + label: t.autoVersionLabel, + description: t.autoVersionDescription, + default: true, + labels: { zh: "自动跟随客户端版本", en: "Follow the client version" }, + descriptions: { + zh: "从 AtomCode 官方仓库后台刷新版本号,用于签名与 User-Agent。", + en: "Refresh the version from AtomCode's official repository in the background for signing and User-Agent.", + }, + }, + ], + + /** + * The account, resolved into request routing. + * + * The returned `fetch` is the only place bodies get touched. A streaming + * Chat Completions body may gain `stream_options.include_usage`, then the + * exact bytes sent are signed; responses stream back untouched. A request + * aimed anywhere but the gateway is refused outright, before any + * credential is attached to it. + */ + async loader(getAuth) { + return { + baseURL: opts.gatewayURL, + async fetch(input, init) { + const isRequest = input instanceof Request; + // Freeze the destination before any await. A caller-owned URL + // object may otherwise change while credentials are being read, + // separating the validated origin from the actual destination. + const target = new URL(isRequest ? input.url : String(input)); + const targetString = target.href; + const pathname = target.pathname; + // Nothing leaves for anywhere but the gateway: the credential and + // the signature headers are only ever meant for that one origin. + if (target.origin !== gatewayOrigin) { + const blocked = fill(t.foreignTargetBlocked, { origin: target.origin }); + log("warn", `${PROVIDER}: ${blocked}`); + throw new Error(blocked); + } + + // Re-read per request so a sign-in that changes mid-session is + // picked up without waiting for the loader to re-run. This also + // renews on older hosts that never call auth.refresh. + const state = await currentCredentials(getAuth); + let credentials = state.credentials; + if (!credentials) { + // No signed-in account: ship the request without credentials and + // let the upstream's own answer tell the agent what happened. + const headers = new Headers(init?.headers ?? (isRequest ? input.headers : undefined)); + headers.delete("authorization"); + const forwarded = { + ...(isRequest + ? { + cache: input.cache, + credentials: input.credentials, + integrity: input.integrity, + keepalive: input.keepalive, + mode: input.mode, + referrer: input.referrer, + referrerPolicy: input.referrerPolicy, + signal: input.signal, + } + : {}), + ...init, + headers, + redirect: "error", + }; + if (forwarded.body === undefined && isRequest && input.body) { + forwarded.body = input.body; + forwarded.duplex = "half"; + } + return fetch(targetString, forwarded); + } + + if (!credentials.uid) throw markExpired(); + + // UA、X-AtomCode-Ver、签名盐同源自这一个值 + const clientVersion = await clientVersionNow(); + + const headers = new Headers(init?.headers ?? (isRequest ? input.headers : undefined)); + let normalized; + try { + normalized = await normalizeRequestBody(init?.body, { + request: isRequest ? input : undefined, + fromRequest: isRequest && init?.body === undefined, + }); + } catch (error) { + throw new Error(`unsupported request body: ${redactText(error.message)}`); + } + if (normalized.contentType && !headers.has("content-type")) { + headers.set("content-type", normalized.contentType); + } + const streamed = includeStreamUsage(normalized.signBody, { + pathname, + contentType: headers.get("content-type") ?? "", + }); + if (streamed.changed) { + normalized = { ...normalized, body: streamed.body, signBody: streamed.body }; + headers.delete("content-length"); + } + + const dispatch = async (current, bodyInfo) => { + const requestHeaders = new Headers(headers); + const method = init?.method ?? (isRequest ? input.method : "GET"); + const signed = signAtomGitRequest({ + method, + path: pathname, + body: bodyInfo.signBody, + oauthToken: current.access, + userId: current.uid, + clientVersion, + masterKeyHex: opts.masterKeyHex, + }); + for (const [key, value] of Object.entries(signed)) { + requestHeaders.set(key, value); + } + requestHeaders.set("authorization", `Bearer ${current.access}`); + requestHeaders.set("user-agent", userAgentOf(clientVersion)); + + const forwarded = { + ...(isRequest + ? { + cache: input.cache, + credentials: input.credentials, + integrity: input.integrity, + keepalive: input.keepalive, + mode: input.mode, + referrer: input.referrer, + referrerPolicy: input.referrerPolicy, + signal: input.signal, + } + : {}), + ...init, + method, + headers: requestHeaders, + redirect: "error", + }; + if (bodyInfo.body !== undefined) forwarded.body = bodyInfo.body; + else delete forwarded.body; + delete forwarded.duplex; + return fetch(targetString, forwarded); + }; + + let response; + try { + response = await dispatch(credentials, normalized); + } catch (error) { + rememberFailure(credentials.uid, error, { stage: "gateway" }); + throw annotateError(error, { stage: "gateway" }); + } + let failure = await classifyGatewayResponse(response); + if ( + (response.status === 401 || failure.refresh) && + !state.renewed && + credentials.refresh + ) { + try { + const retry = await currentCredentials(getAuth, { forceRefresh: true }); + if (retry.credentials?.access && retry.credentials.access !== credentials.access) { + await response.body?.cancel().catch(() => {}); + credentials = retry.credentials; + response = await dispatch(credentials, normalized); + failure = await classifyGatewayResponse(response); + } + } catch (error) { + if (error.signIn === "expired") throw markExpired(); + log( + "warn", + `${PROVIDER}: ${fill(t.refreshFailed, { detail: redactText(error.message) })}`, + ); + } + } + if ( + [401, 403, 429].includes(response.status) || + response.status >= 500 + ) { + rememberFailure( + credentials.uid, + Object.assign(new Error(failure.message || `HTTP ${response.status}`), { + status: response.status, + category: failure.category, + }), + { stage: "gateway" }, + ); + } + return keptResponseHeaders(response, failure); + }, + }; + }, + + /** + * The CodingPlan quota, as the provider row and `magpie quota` show it. + */ + async usage(getAuth) { + const deadline = Date.now() + USAGE_BUDGET_MS; + let raw = await readAuth(getAuth); + let user = userLabel(raw); + let credentials = credentialsOf(raw); + let cacheKey = credentials?.uid ?? credentials?.access ?? "no-account"; + try { + const hit = quotaCache.get(cacheKey); + if (hit && Date.now() - hit.at < opts.quotaTtlMs) return hit.value; + + ({ raw, credentials } = await currentCredentials(raw, { deadline })); + user = userLabel(raw); + cacheKey = credentials?.uid ?? credentials?.access ?? "no-account"; + const refreshedHit = quotaCache.get(cacheKey); + if (refreshedHit && Date.now() - refreshedHit.at < opts.quotaTtlMs) { + return refreshedHit.value; + } + if (!credentials) { + const value = { plan: t.planFallback, error: t.noAccount, windows: [] }; + // 失败态只留 15 秒:下一次轮询正是重登之后该重试的时刻。 + quotaCache.set(cacheKey, { at: Date.now() - opts.quotaTtlMs + 15_000, value }); + return value; + } + + const readStatus = async (current, wantedMs) => + fetchStatus(opts.codingPlanAPIURL, current.access, { + clientVersion: await clientVersionNow(), + timeoutMs: Math.max( + 250, + Math.min(wantedMs, remainingMs(deadline) ?? wantedMs), + ), + }); + let status; + try { + status = await readStatus(credentials, 7_000); + } catch (error) { + if (!isCredentialFailure(error) || !credentials.refresh) { + throw error; + } + const retry = await currentCredentials(raw, { forceRefresh: true, deadline }); + if (!retry.credentials?.access || retry.credentials.access === credentials.access) { + throw error; + } + ({ raw, credentials } = retry); + user = userLabel(raw); + cacheKey = credentials.uid ?? credentials.access; + status = await readStatus(credentials, 7_000); + } + // 签到语义:套餐缺失/到期 → 自动重领一次,成功后重取状态再映射。 + if (await ensurePlan(credentials, { status, deadline })) { + const remaining = remainingMs(deadline); + if (remaining !== undefined && remaining <= 0) throw new Error(t.usageTimeout); + status = await readStatus(credentials, 4_000); + } + const value = quotaFromStatus(status, t, { user }); + quotaCache.set(cacheKey, { at: Date.now(), value }); + await stateStore.recordQuota(credentials.uid, value); + await stateStore.recordLogin(credentials.uid, raw?.source ?? "browser"); + return value; + } catch (error) { + const failure = classifyError(error, { stage: "usage" }); + const expired = error.signIn === "expired" || failure.signInExpired; + const uid = credentials?.uid ?? raw?.uid; + rememberFailure(uid, error, { stage: "usage" }); + const stale = expired ? undefined : await stateStore.cachedQuota(uid); + const detail = redactText(error.message); + const value = { + ...(stale ?? {}), + plan: stale?.plan ?? t.planFallback, + ...(user ? { user } : {}), + error: expired + ? t.reloginRequired + : stale + ? fill(t.usageStale, { detail }) + : error.status + ? fill(t.usageHttp, { status: error.status }) + : fill(t.readFailed, { detail }), + signIn: expired ? "expired" : "kept", + ...(stale ? { stale: true } : {}), + windows: stale?.windows ?? [], + }; + quotaCache.set(cacheKey, { at: Date.now() - opts.quotaTtlMs + 15_000, value }); + log("warn", `${PROVIDER}: usage: ${redactText(error.message)}`); + return value; + } + }, + + /** + * 签到 —— magpie 原生 checkin 设置开关调度的钩子(社区 raccoon/ + * autoclaw 插件同款):AtomCode 的对应端点就是 claim-v2 领取。 + * + * - 这次真的领到了(fresh claim)→ claimed(带套餐名与档位); + * - 本来就持有对应/更高档(duplicate)→ done(仍有效,无新领取); + * - 上游拒绝(日限额已满等)→ failed,把上游 message 带回去。 + */ + async checkin(getAuth) { + const deadline = Date.now() + USAGE_BUDGET_MS; + let state; + let credentials; + try { + state = await currentCredentials(getAuth, { deadline }); + ({ credentials } = state); + } catch (error) { + return { + outcome: "failed", + message: + error.signIn === "expired" + ? t.reloginRequired + : fill(t.readFailed, { detail: redactText(error.message) }), + }; + } + if (!credentials?.access) { + return { outcome: "failed", message: t.noAccount }; + } + // 状态先看一眼:套餐仍在有效期内就不打扰领取接口(claim-v2 幂等, + // 但一次元数据请求换一个确定的 done 比一次网络往返更稳)。 + try { + const statusTimeout = () => { + const remaining = remainingMs(deadline); + if (remaining !== undefined && remaining <= 0) return 0; + return Math.max(250, Math.min(6_000, remaining ?? 6_000)); + }; + const timeoutMs = statusTimeout(); + if (timeoutMs === 0) { + return { outcome: "failed", message: t.usageTimeout }; + } + const readStatus = async () => + fetchStatus(opts.codingPlanAPIURL, credentials.access, { + clientVersion: await clientVersionNow(), + timeoutMs: statusTimeout() || 250, + }); + let status; + try { + status = await readStatus(); + } catch (error) { + if (!isCredentialFailure(error) || !credentials.refresh) { + throw error; + } + const retry = await currentCredentials(state.raw, { + forceRefresh: true, + deadline, + }); + if (!retry.credentials?.access || retry.credentials.access === credentials.access) { + throw error; + } + state = retry; + credentials = retry.credentials; + status = await readStatus(); + } + if (!planNeedsClaim(status)) { + const plan = status?.codingplan_free ?? status?.plan ?? {}; + return { + outcome: "done", + message: plan.plan_name + ? fill(t.checkinDoneWithPlan, { plan: plan.plan_name }) + : t.checkinDone, + }; + } + } catch (error) { + if (error.signIn === "expired") return { outcome: "failed", message: t.reloginRequired }; + // 状态读不到(网络抖动)不放弃:直接尝试领取,由领取结果说话。 + } + try { + const claim = await claimOnce(credentials, { deadline }); + if (!claim) return { outcome: "failed", message: t.usageTimeout }; + if (!claim.claimed) { + const category = + claim.category ?? + classifyError({ message: claim.message }).category; + if ( + category === FAILURE.INELIGIBLE || + category === FAILURE.ENTITLEMENT_FORBIDDEN + ) { + return { + outcome: "ineligible", + message: redactText(claim.message) || t.checkinIneligible, + }; + } + return { + outcome: "failed", + message: + redactText(claim.message) || + fill(t.reclaimFailed, { detail: "no tier" }), + }; + } + if (claim.duplicate) { + return { + outcome: "done", + message: claim.planName + ? fill(t.checkinDoneWithPlan, { plan: claim.planName }) + : t.checkinDone, + }; + } + return { + outcome: "claimed", + message: claim.planName || claim.tier || undefined, + }; + } catch (error) { + return { + outcome: "failed", + message: fill(t.reclaimFailed, { detail: redactText(error.message) }), + }; + } + }, + + /** + * Token renewal before expiry — Magpie's own hook (OpenCode ignores it). + */ + refreshLead: 5 * 60 * 1000, + async refresh(auth) { + const { credentials } = await currentCredentials(auth, { forceRefresh: true }); + if (!credentials?.access) throw markExpired(); + return { + access: credentials.access, + refresh: credentials.refresh, + expires: credentials.expires, + }; + }, + }, + }; + + if (magpie) { + try { + const diagnostics = startDiagnosticsService({ + port: opts.diagnosticsPort, + stateStore, + versionSource, + locale: t.locale, + config: { + locale: t.locale, + autoClaim: autoClaimEnabled, + autoVersion: autoVersionEnabled, + diagnosticsPort: opts.diagnosticsPort, + }, + selfCheckConfig: { + clientVersion: opts.clientVersion, + masterKeyHex: opts.masterKeyHex, + }, + }); + diagnostics.ready.then( + () => + log( + "info", + `${PROVIDER}: ${fill(t.diagnosticsStarted, { + port: opts.diagnosticsPort, + })}`, + ), + (error) => + log( + "warn", + `${PROVIDER}: ${fill(t.diagnosticsFailed, { + detail: redactText(error.message), + })}`, + ), + ); + } catch (error) { + log( + "warn", + `${PROVIDER}: ${fill(t.diagnosticsFailed, { + detail: redactText(error.message), + })}`, + ); + } + } + + return hooks; +} diff --git a/packages/atomcode/internal.mjs b/packages/atomcode/internal.mjs new file mode 100644 index 0000000..d3f1daa --- /dev/null +++ b/packages/atomcode/internal.mjs @@ -0,0 +1,294 @@ +/** + * Helpers shared by the plugin entry and its tests. + * + * Kept out of `index.mjs` because OpenCode is a compatibility host and it calls + * every function the entry module exports. See that file's header. + * + * @module magpie-atomcode/internal + */ + +import { readFileSync } from "node:fs"; + +/** + * The provider id, which is also what agents address models by: + * `atomcode/`. + */ +export const PROVIDER = "atomcode"; + +/** + * clientVersion anchor: AtomCode 5.2.3. + * + * Sent as `User-Agent: atomcode/` (the gateway answers 403 + * `ATOMCODE_UA_REQUIRED` without it) and as `X-AtomCode-Ver` in the signature. + * The master key can change upstream; `clientVersion` and `masterKeyHex` are + * plugin options so the plugin survives upstream rotation without a release. + */ +export const DEFAULT_CLIENT_VERSION = "5.2.3"; + +/** OAuth broker (`Atom2Api` 默认 `platform_base_url`)。 */ +export const DEFAULT_PLATFORM_BASE_URL = "https://acs.atomgit.com"; + +/** CodingPlan REST 底座(`codingplan_api_url`)。 */ +export const DEFAULT_CODING_PLAN_API_URL = "https://api.gitcode.com/api/v5"; + +/** LLM 网关底座(`gateway_url`)。 */ +export const DEFAULT_GATEWAY_BASE_URL = "https://llm-api.atomgit.com/v1"; + +/** Inlined so the provider stays identifiable with no network. */ +export const ICON = readIcon(); + +/** + * The platform's own favicon, vendored into `assets/atomcode.ico` and inlined + * as a data URI at load time. + */ +function readIcon() { + try { + const ico = readFileSync(new URL("./assets/atomcode.ico", import.meta.url)); + return `data:image/x-icon;base64,${ico.toString("base64")}`; + } catch { + return undefined; + } +} + +/** + * The `origin` of an absolute URL (scheme + host + port), or undefined when it + * does not parse. `origin` also covers the protocol, so an `http://` downgrade + * to the same host can never compare equal to an `https://` gateway. + * + * @param {unknown} value + * @returns {string|undefined} + */ +export function originOf(value) { + try { + return new URL(String(value)).origin; + } catch { + return undefined; + } +} + +/** + * Parse an upstream date as an instant. AtomGit's unzoned timestamps and + * date-only plan expiry are Beijing local time; the host machine's timezone + * must never decide when a quota or plan ends. + * + * @param {unknown} value + * @param {{dateOnlyEnd?: boolean}} [opts] + * @returns {number|undefined} epoch milliseconds + */ +export function parseAtomInstant(value, { dateOnlyEnd = true } = {}) { + if (typeof value === "number" && Number.isFinite(value)) { + return value < 1e12 ? value * 1000 : value; + } + if (typeof value !== "string" || !value.trim()) return undefined; + const raw = value.trim(); + if (/^\d{4}-\d{2}-\d{2}$/.test(raw)) { + return dateOnlyEnd ? Date.parse(`${raw}T23:59:59.999+08:00`) : Date.parse(`${raw}T00:00:00+08:00`); + } + const local = raw.replace(" ", "T"); + const withZone = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?$/.test(local) + ? `${local}+08:00` + : local; + const parsed = Date.parse(withZone); + return Number.isFinite(parsed) ? parsed : undefined; +} + +/** An upstream timestamp as an RFC 3339 UTC string, when parseable. */ +export function atomInstantISO(value) { + const parsed = parseAtomInstant(value); + return parsed === undefined ? undefined : new Date(parsed).toISOString(); +} + +/** Short user-facing text without obvious credentials or identities. */ +export function redactText(value, max = 200) { + return String(value ?? "") + .replace(/\bBearer\s+[^\s,;"']+/gi, "Bearer [redacted]") + .replace(/\b((?:access|refresh|id)_token)\s*[:=]\s*[^\s,;"']+/gi, "$1=[redacted]") + .replace(/\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/g, "[redacted-email]") + .replace(/\b[A-Za-z0-9_-]{48,}\b/g, "[redacted]") + .slice(0, max); +} + +/** The useful message from an upstream JSON error, never the raw body. */ +export function upstreamMessage(text) { + try { + const body = JSON.parse(String(text ?? "")); + if (typeof body?.message === "string" && body.message) return redactText(body.message); + if (typeof body?.error_description === "string" && body.error_description) { + return redactText(body.error_description); + } + if (typeof body?.error === "string" && body.error) return redactText(body.error); + if (typeof body?.code === "string" && body.code) return redactText(body.code); + } catch { + /* not JSON */ + } + return ""; +} + +/** + * Validate a URL that came from configuration or from upstream. + * + * Accepts only https, no embedded credentials, and a host that is one of + * `domains` or a subdomain of one. Query and fragment components are rejected + * for base endpoints unless explicitly allowed (OAuth login pages need both). + * `undefined` means "not acceptable". + * + * @param {unknown} value + * @param {{domains?: string[], allowSearch?: boolean, allowHash?: boolean, exact?: boolean}} [opts] + * @returns {string|undefined} the trimmed URL, or undefined when unusable. + */ +export function trustedURL( + value, + { domains = [], allowSearch = false, allowHash = false, exact = false } = {}, +) { + if (typeof value !== "string" || !value.trim()) return undefined; + let url; + try { + url = new URL(value.trim()); + } catch { + return undefined; + } + if (url.protocol !== "https:") return undefined; + if (url.port && url.port !== "443") return undefined; + if (url.username || url.password) return undefined; + if (!allowSearch && url.search) return undefined; + if (!allowHash && url.hash) return undefined; + const host = url.hostname.toLowerCase(); + if ( + !domains.some((domain) => + exact ? host === domain : host === domain || host.endsWith(`.${domain}`) + ) + ) { + return undefined; + } + return value.trim(); +} + +/** A compact byte limit for user-facing errors. */ +function byteLimitLabel(maxBytes) { + if (maxBytes >= 1 << 20 && maxBytes % (1 << 20) === 0) return `${maxBytes / (1 << 20)} MiB`; + if (maxBytes >= 1 << 10 && maxBytes % (1 << 10) === 0) return `${maxBytes / (1 << 10)} KiB`; + return `${maxBytes} bytes`; +} + +/** + * Read an HTTP response body without allowing an untrusted response to consume + * unbounded memory. The stream is cancelled as soon as the limit is crossed. + * + * @param {Response} res + * @param {{maxBytes?: number, label?: string}} [opts] + * @returns {Promise} + */ +export async function readCappedResponseText( + res, + { maxBytes = 1 << 20, label = "response" } = {}, +) { + if (!res?.body || typeof res.body.getReader !== "function") { + const whole = await res.text(); + if (Buffer.byteLength(whole, "utf8") > maxBytes) { + throw new Error(`${label} exceeds ${byteLimitLabel(maxBytes)}`); + } + return whole; + } + + const reader = res.body.getReader(); + const decoder = new TextDecoder(); + let total = 0; + let text = ""; + try { + for (;;) { + const { done, value } = await reader.read(); + if (done) break; + total += value.byteLength; + if (total > maxBytes) { + await reader.cancel().catch(() => {}); + throw new Error(`${label} exceeds ${byteLimitLabel(maxBytes)}`); + } + text += decoder.decode(value, { stream: true }); + } + } finally { + try { + reader.releaseLock(); + } catch { + /* cancel() may have released it already */ + } + } + return text + decoder.decode(); +} + +/** + * Domains the endpoint options (`platformBaseURL`, `codingPlanAPIURL`) may point + * at. + * + * An access or refresh token travels to whichever endpoint a config names, so + * this list stays on the upstream's own two families — a value outside it is + * treated as a misconfiguration, not as a destination. + */ +export const TRUSTED_SERVICE_DOMAINS = ["atomgit.com", "gitcode.com"]; + +/** + * An endpoint option, or `fallback` when the configured value is unusable. + * + * A rejected value is reported through `onReject` rather than thrown: a bad + * option must not take the whole provider down. + * + * @param {unknown} value + * @param {{fallback: string, domains?: string[], exact?: boolean, onReject?: Function}} opts + * @returns {string} + */ +export function trustedServiceURL( + value, + { fallback, domains = TRUSTED_SERVICE_DOMAINS, exact = false, onReject } = {}, +) { + const accepted = trustedURL(value, { domains, exact }); + if (accepted) return accepted; + if (typeof value === "string" && value.trim()) { + try { + onReject?.(value.trim()); + } catch { + /* the reporter is best-effort */ + } + } + return fallback; +} + +/** Read the stored sign-in, tolerating a host that has none. */ +export async function readAuth(getAuth) { + if (typeof getAuth !== "function") return undefined; + try { + return await getAuth(); + } catch { + return undefined; + } +} + +/** + * The fields a signed request needs, out of a stored auth record. + * + * `uid` (the upstream `user.id`) participates in the signing salt, so it is + * carried on every sign-in result; a record without it cannot sign at all. + */ +export function credentialsOf(auth) { + if (!auth || typeof auth !== "object") return undefined; + const access = typeof auth.access === "string" && auth.access ? auth.access : undefined; + if (!access) return undefined; + return { + type: auth.type, + access, + refresh: typeof auth.refresh === "string" && auth.refresh ? auth.refresh : undefined, + expires: Number.isFinite(auth.expires) ? auth.expires : undefined, + uid: auth.uid !== undefined && auth.uid !== null ? String(auth.uid) : undefined, + accountId: typeof auth.accountId === "string" ? auth.accountId : undefined, + email: typeof auth.email === "string" ? auth.email : undefined, + name: typeof auth.name === "string" ? auth.name : undefined, + }; +} + +/** + * Mark a model list as the remembered one rather than a live one. + * + * @param {object} models - the list to mark. + * @returns {object} a copy carrying the marker. + */ +export function fellBack(models) { + return { ...models, [Symbol.for("magpie.fellBack")]: true }; +} diff --git a/packages/atomcode/models.mjs b/packages/atomcode/models.mjs new file mode 100644 index 0000000..645de84 --- /dev/null +++ b/packages/atomcode/models.mjs @@ -0,0 +1,228 @@ +/** + * Model discovery for AtomCode CodingPlan. + * + * The model catalog lives on `models-v2`, is scoped to the account's plan tier, + * and shifts over time and between accounts (Atom2Api's README example names + * models different from what real accounts receive), so the live list is the + * source of truth once a signed-in account exists. + * + * `FALLBACK_MODELS` is the snapshot that keeps the provider selectable before a + * sign-in or when the fetch fails; it is the real list this account observed on + * 2026-10-16 and may go stale — which is fine, the live list replaces it. + * + * The model *key* (what agents address by) is sanitized; the original + * `display_model_name` rides along as `api.id` because that is the id the + * upstream gateway expects in request bodies. + * + * @module magpie-atomcode/models + */ + +import { fetchStatus, fetchModels, planOf, planTier } from "./codingplan.mjs"; +import { DEFAULT_GATEWAY_BASE_URL, trustedURL } from "./internal.mjs"; + +/** The AI SDK package that speaks the OpenAI-compatible dialect. */ +export const NPM = "@ai-sdk/openai-compatible"; + +/** LLM gateway root; loader requests and `api.url` default to it. */ +export const DEFAULT_BASE_URL = DEFAULT_GATEWAY_BASE_URL; + +/** The only origin loader.fetch permits for signed model traffic. */ +export const TRUSTED_MODEL_ORIGIN = new URL(DEFAULT_BASE_URL).origin; + +/** + * Validate an upstream-supplied model `base_url`. + * + * Accepts only https, no embedded credentials, and the exact gateway origin that + * loader.fetch permits. Keeping both checks on the same origin prevents a model + * from being advertised and then rejected at request time. + * + * @param {unknown} value + * @returns {string|undefined} the trimmed URL, or undefined when unusable. + */ +export function trustedModelBaseURL(value) { + const accepted = trustedURL(value, { domains: ["atomgit.com"] }); + if (!accepted) return undefined; + return new URL(accepted).origin === TRUSTED_MODEL_ORIGIN ? accepted : undefined; +} + +/** Upstream `defaults 64000` when a row lacks a context window (Atom2Api 同款兜底). */ +export const DEFAULT_CONTEXT = 64000; +export const DEFAULT_OUTPUT = 32768; + +/** How long one account's fetched list is trusted. */ +export const MODELS_TTL_MS = 10 * 60_000; + +const num = (v) => { + const n = Number(v); + return Number.isFinite(n) ? n : undefined; +}; + +/** + * Model keys may contain `/` or other characters that complicate addressing; + * the unsanitized id stays in `api.id`, so the wire never sees the mangled one. + */ +export function sanitizeModelKey(value) { + const id = String(value ?? "").trim(); + const key = id.replace(/[^A-Za-z0-9._-]/g, "_"); + return key || id; +} + +/** The observed 2026-10-16 catalog, in `models-v2` row shape. */ +export const FALLBACK_MODELS = [ + { + display_model_name: "glm5.3-flash", + context_window: 512000, + reasoning_effort_levels: ["low", "high"], + supports_vision: true, + }, + { + display_model_name: "qwen3.8-27b", + context_window: 262144, + reasoning_effort_levels: ["low", "medium", "xhigh"], + supports_vision: true, + }, + { + display_model_name: "deepseek-flash", + context_window: 1000000, + reasoning_effort_levels: ["high", "max"], + supports_vision: true, + }, +]; + +/** + * Normalize one `models-v2` row (or a `FALLBACK_MODELS` entry, same shape). + * + * `onReject` is called when the row carried a `base_url` that was refused by + * {@link trustedModelBaseURL}, so the caller can say so instead of silently + * routing the model somewhere else. + * + * @returns {{id: string, key: string, context: number, output: number, levels: string[], vision: boolean, type: string, baseURL?: string}|null} + */ +export function normalizeCodingPlanModel(raw = {}, { output = DEFAULT_OUTPUT, onReject } = {}) { + const id = typeof raw.display_model_name === "string" ? raw.display_model_name.trim() : ""; + if (!id) return null; + const levels = Array.isArray(raw.reasoning_effort_levels) + ? raw.reasoning_effort_levels.filter((l) => typeof l === "string" && l.trim()).map((l) => l.trim()) + : []; + const declaredBaseURL = typeof raw.base_url === "string" ? raw.base_url.trim() : ""; + const baseURL = declaredBaseURL ? trustedModelBaseURL(declaredBaseURL) : undefined; + if (declaredBaseURL && baseURL === undefined) { + try { + onReject?.(declaredBaseURL); + } catch { + /* the reporter is best-effort */ + } + } + const declaredOutput = num(raw.max_output_tokens ?? raw.max_completion_tokens ?? raw.output_token_limit); + return { + id, + key: sanitizeModelKey(id), + context: num(raw.context_window) > 0 ? num(raw.context_window) : DEFAULT_CONTEXT, + output: declaredOutput > 0 ? declaredOutput : output, + levels, + vision: raw.supports_vision === true, + type: typeof raw.type === "string" && raw.type ? raw.type : "openai", + baseURL, + }; +} + +/** The `config` hook's entry declaring one model. */ +export function toConfigModel(m = {}) { + const levels = m.levels ?? []; + const entry = { + name: m.id ?? m.key, + reasoning: levels.length > 0, + tool_call: true, + attachment: m.vision === true, + modalities: { input: m.vision === true ? ["text", "image"] : ["text"], output: ["text"] }, + limit: { context: m.context ?? DEFAULT_CONTEXT, output: m.output ?? DEFAULT_OUTPUT }, + }; + if (levels.length) { + entry.variants = Object.fromEntries( + levels.map((level) => [level, { reasoningEffort: level }]), + ); + } + if (m.key && m.id && m.key !== m.id) entry.id = m.id; + return entry; +} + +/** The `provider.models` entry for one model, in Magpie's model shape. */ +export function toProviderModel(m = {}, providerID, { baseURL = DEFAULT_BASE_URL, npm = NPM } = {}) { + const levels = m.levels ?? []; + return { + id: m.key, + providerID, + name: m.id ?? m.key, + api: { id: m.id ?? m.key, url: m.baseURL ?? baseURL, npm }, + status: "active", + headers: {}, + options: {}, + cost: { input: 0, output: 0, cache: { read: 0, write: 0 } }, + limit: { context: m.context ?? DEFAULT_CONTEXT, output: m.output ?? DEFAULT_OUTPUT }, + capabilities: { + temperature: true, + reasoning: levels.length > 0, + attachment: m.vision === true, + toolcall: true, + input: { text: true, image: m.vision === true, audio: false, video: false, pdf: false }, + output: { text: true }, + interleaved: false, + }, + release_date: "", + variants: Object.fromEntries( + levels.map((level) => [level, { reasoningEffort: level }]), + ), + }; +} + +/** + * One account's catalog, fetched once and cached. + * + * The chain is `status-v2` → plan tier → `models-v2?plan_type=`; results key on + * the account (`uid` preferred, access token otherwise) so two accounts never + * share a cache entry. Errors propagate — including `signIn: "expired"` ones — + * so the provider hook decides between fallback and account marking. + * + * @param {{apiBase: string, clientVersion: string, timeoutMs?: number, ttlMs?: number, output?: number, fetchImpl?: Function, onReject?: Function}} opts + */ +export function createCatalog({ + apiBase, + clientVersion, + timeoutMs = 20_000, + ttlMs = MODELS_TTL_MS, + output = DEFAULT_OUTPUT, + fetchImpl, + onReject, +} = {}) { + const cache = new Map(); + const inflight = new Map(); + + /** + * @param {{access: string, uid?: string}} credentials + * @param {{output?: number}} [perCall] + */ + async function load(credentials, { output: outputOverride = output, clientVersion: version = clientVersion } = {}) { + if (!credentials?.access) return []; + const key = credentials.uid ?? credentials.access; + const hit = cache.get(key); + if (hit && Date.now() - hit.at < ttlMs) return hit.models; + const pending = inflight.get(key); + if (pending) return pending; + + const p = (async () => { + const status = await fetchStatus(apiBase, credentials.access, { fetchImpl, clientVersion: version, timeoutMs }); + const tier = planTier(planOf(status)?.plan_name); + const rows = await fetchModels(apiBase, credentials.access, tier, { fetchImpl, clientVersion: version, timeoutMs }); + const models = rows + .map((row) => normalizeCodingPlanModel(row, { output: outputOverride, onReject })) + .filter(Boolean); + if (models.length) cache.set(key, { at: Date.now(), models }); + return models; + })().finally(() => inflight.delete(key)); + + inflight.set(key, p); + return p; + } + + return { load }; +} diff --git a/packages/atomcode/oauth.mjs b/packages/atomcode/oauth.mjs new file mode 100644 index 0000000..3b9e3cc --- /dev/null +++ b/packages/atomcode/oauth.mjs @@ -0,0 +1,167 @@ +/** + * Client for the AtomGit OAuth broker (`https://acs.atomgit.com`). + * + * Flow (mirrors Atom2Api `oauth.go`): + * + * 1. `startLogin` → GET /auth/login?provider=atomgit → `{login_url, state}`; + * `force_login` is stripped from `login_url` (upstream's `stripForceLogin`), + * so an already-logged-in browser goes straight through. + * 2. `checkLogin` → GET /auth/check?state=… → `{valid: boolean}` — poll this. + * 3. `tokenFor` → GET /auth/token?state=… → `{access_token, refresh_token, + * token_type, expires_in, user{…}}` — requires a non-empty access token and + * `user.id` (the id feeds the request signature later). + * 4. `refreshTokens` → POST /oauth/refresh `{refresh_token}` — same shape; the + * refresh token may or may not rotate, and a 400/401/403 means the browser + * sign-in is dead. + * + * Every call sends `User-Agent: atomcode/`; the broker hands sessions + * that die after ~10 minutes, so callers must not stall between steps. + * + * `fetchImpl` is injectable for tests. + * + * @module magpie-atomcode/oauth + */ + +import { + DEFAULT_CLIENT_VERSION, + readCappedResponseText, + trustedURL, +} from "./internal.mjs"; + +/** Trailing slashes lie about URLs; trim once here. */ +const withBase = (base, path) => `${String(base).replace(/\/+$/, "")}/${path}`; + +/** `atomcode/5.2.3` — the UA every upstream endpoint asks for. */ +export const userAgentOf = (clientVersion) => `atomcode/${clientVersion}`; + +/** + * Remove `force_login` from a login URL so single-sign-on works. + * + * Atom2Api's `stripForceLogin`: parse-delete, with a string fallback for a URL + * that won't parse. + */ +export function stripForceLogin(raw) { + const value = String(raw ?? ""); + try { + const parsed = new URL(value); + parsed.searchParams.delete("force_login"); + return parsed.toString(); + } catch { + return value.replace(/&force_login=true/g, ""); + } +} + +async function call( + base, + path, + { + method = "GET", + body, + fetchImpl = (...args) => fetch(...args), + clientVersion = DEFAULT_CLIENT_VERSION, + timeoutMs = 15_000, + } = {}, +) { + const res = await fetchImpl(withBase(base, path), { + method, + redirect: "error", + headers: { + accept: "application/json", + "user-agent": userAgentOf(clientVersion), + ...(body !== undefined ? { "content-type": "application/json" } : {}), + }, + ...(body !== undefined ? { body: JSON.stringify(body) } : {}), + signal: AbortSignal.timeout(timeoutMs), + }); + const text = await readCappedResponseText(res, { label: "OAuth broker response" }); + if (!res.ok) { + const error = new Error(`OAuth broker returned HTTP ${res.status}`); + error.status = res.status; + throw error; + } + try { + return JSON.parse(text); + } catch { + throw new Error("OAuth broker did not answer JSON"); + } +} + +/** + * Start a browser sign-in. + * + * @returns {Promise<{loginUrl: string, state: string}>} + */ +export async function startLogin(base, opts = {}) { + const r = await call(base, "auth/login?provider=atomgit", opts); + if (!r?.login_url || !r?.state) { + throw new Error("OAuth broker returned an incomplete login session"); + } + const loginUrl = trustedURL(stripForceLogin(r.login_url), { + domains: ["atomgit.com"], + allowSearch: true, + allowHash: true, + }); + if (!loginUrl) throw new Error("OAuth broker returned an untrusted login URL"); + return { loginUrl, state: String(r.state) }; +} + +/** Has the user finished signing in on the browser side? */ +export async function checkLogin(base, state, opts = {}) { + const r = await call(base, `auth/check?state=${encodeURIComponent(state)}`, opts); + return r?.valid === true; +} + +/** + * Trade a completed state for tokens. + * + * @returns {Promise<{accessToken: string, refreshToken: string|undefined, expiresIn: number, tokenType: string|undefined, user: object}>} + */ +export async function tokenFor(base, state, opts = {}) { + const r = await call(base, `auth/token?state=${encodeURIComponent(state)}`, opts); + if (!r?.access_token || !r?.user?.id) { + throw new Error("OAuth broker returned incomplete credentials"); + } + return { + accessToken: String(r.access_token), + refreshToken: typeof r.refresh_token === "string" && r.refresh_token ? r.refresh_token : undefined, + expiresIn: Number(r.expires_in) || 0, + tokenType: typeof r.token_type === "string" && r.token_type ? r.token_type : "Bearer", + user: r.user, + }; +} + +/** + * Renew with the refresh token. + * + * A 400/401/403 (or an empty access token) means the sign-in is dead, which is + * signalled by `signIn: "expired"` — the token may also not rotate, in which + * case the caller keeps the old one. + * + * @returns {Promise<{accessToken: string, refreshToken: string, expiresIn: number}>} + */ +export async function refreshTokens(base, refreshToken, opts = {}) { + if (!refreshToken) { + const error = new Error("no refresh token available"); + error.signIn = "expired"; + throw error; + } + let r; + try { + r = await call(base, "oauth/refresh", { method: "POST", body: { refresh_token: refreshToken }, ...opts }); + } catch (e) { + // 400/401/403 == 凭证不可用(Atom2Api 的判定同款);其余错误原样上抛, + // 由调用方决定是否带着旧 token 继续发请求。 + if (e.status === 400 || e.status === 401 || e.status === 403) e.signIn = "expired"; + throw e; + } + if (!r?.access_token) { + const error = new Error("OAuth refresh returned an empty access token"); + error.signIn = "expired"; + throw error; + } + return { + accessToken: String(r.access_token), + refreshToken: typeof r.refresh_token === "string" && r.refresh_token ? r.refresh_token : refreshToken, + expiresIn: Number(r.expires_in) || opts.fallbackExpiresIn || 0, + }; +} diff --git a/packages/atomcode/opencode.mjs b/packages/atomcode/opencode.mjs new file mode 100644 index 0000000..b5e9076 --- /dev/null +++ b/packages/atomcode/opencode.mjs @@ -0,0 +1,2 @@ +// The package OpenCode 1.x and magpie load: one plugin function and nothing else. +export { AtomCodePlugin } from "./index.mjs" diff --git a/packages/atomcode/opencode2.mjs b/packages/atomcode/opencode2.mjs new file mode 100644 index 0000000..7aa300b --- /dev/null +++ b/packages/atomcode/opencode2.mjs @@ -0,0 +1,594 @@ +// The OpenCode 2.x face of a package whose plugins are written for +// OpenCode 1.x (and magpie's plugin host). +// +// OpenCode 2.x loads a package's `exports["."]` and wants its default to be +// {id, setup(ctx)}; it has no fallback for a 1.x plugin's named functions +// (plugins#657). This file is that default. It runs each 1.x plugin the +// package's opencode.mjs exports and hands 2.x what the plugin's hooks say: +// +// auth.methods → the integration's sign-in methods +// config() → the provider, its package, base URL and models +// provider.models → the signed-in account's own model list +// auth.loader → each request's base URL, key, headers and fetch +// +// What 2.x has no place for is left out: chat.headers and chat.params +// (2.x's sdk hook doesn't carry the session), magpie's usage and checkin, +// tools and events. +// +// scripts/opencode2.mjs is the one copy that is edited. Every package that +// has it carries the same bytes as packages//opencode2.mjs, and +// scripts/check.mjs fails when a copy differs. + +import { readFileSync } from "node:fs" +import * as v1 from "./opencode.mjs" + +const pkg = JSON.parse(readFileSync(new URL("./package.json", import.meta.url), "utf8")) + +// The key the SDK is made with: the account's own goes on each request in +// its place (see wrapFetch), so a key read when the SDK was made can't go +// out after the account changed. +const PLACEHOLDER = "opencode2-v1-key" + +// The SDK package a 1.x npm name runs as on 2.x. A version keeps 2.x from +// swapping @ai-sdk/* for its native providers, which never call the sdk +// hook below; openai-compatible's is the one 2.x ships, the others are AI +// SDK v6's dist-tag, the line 2.x's bridge runs. +export function packageOf(npm) { + const name = npm || "@ai-sdk/openai-compatible" + if (name === "@ai-sdk/openai-compatible") return "aisdk:@ai-sdk/openai-compatible@2.0.41" + if (/^@ai-sdk\/[^/@]+$/.test(name)) return `aisdk:${name}@ai-v6` + return `aisdk:${name}` +} + +// The plugins a 1.x module exports, as magpie's host and OpenCode 1.x read +// them: a default {server} is the one plugin, else every function export +// and every {server} object. +export function pluginsOf(mod) { + const d = mod?.default + if (d && typeof d === "object" && ("server" in d || "id" in d || "tui" in d)) + return typeof d.server === "function" ? [d.server] : [] + const out = [] + for (const value of Object.values(mod ?? {})) { + const fn = typeof value === "function" ? value : value && typeof value === "object" && typeof value.server === "function" ? value.server : null + if (fn && !out.includes(fn)) out.push(fn) + } + return out +} + +const int = (n, fallback = 0) => { + const v = Math.trunc(Number(n)) + return Number.isFinite(v) && v >= 0 ? v : fallback +} +const money = (n) => (Number.isFinite(Number(n)) && Number(n) >= 0 ? Number(n) : 0) +const record = (v) => (v && typeof v === "object" && !Array.isArray(v) ? v : {}) +const json = (v) => { + try { + return JSON.parse(JSON.stringify(v ?? null)) + } catch { + return null + } +} +const strings = (v) => Object.fromEntries(Object.entries(record(v)).filter(([, s]) => typeof s === "string")) +const nonEmpty = (o) => (Object.keys(o).length ? o : undefined) + +// connKey names a connection the way 2.x does. +const connKey = (c) => (!c ? "" : c.type === "credential" ? `credential:${c.id}` : `env:${c.name}`) + +// ---- sign-in ------------------------------------------------------------ + +// fields is a 1.x method's prompts as a 2.x form. +export function fieldsOf(prompts) { + const out = [] + for (const p of prompts ?? []) { + if (!p?.key) continue + const f = { key: String(p.key), type: "string", title: String(p.message ?? p.key) } + if (p.placeholder) f.placeholder = String(p.placeholder) + if (p.type === "select" && Array.isArray(p.options)) + f.options = p.options.map((o) => ({ value: String(o.value), label: String(o.label ?? o.value), ...(o.hint ? { description: String(o.hint) } : {}) })) + // a prompt shown only when another answer says so can't be required + if (!p.condition) f.required = true + out.push(f) + } + return out.length ? out : undefined +} + +// v1Saved is what a 1.x sign-in's success is saved as, the way 1.x writes +// auth.json: the result without its type and provider. +function v1Saved(r) { + const { type: _t, provider: _p, ...rest } = r + if ("key" in r) return { type: "api", ...rest } + return { type: "oauth", ...rest } +} + +// credentialOf is a 1.x sign-in's success as a 2.x credential: OAuth for +// both kinds, the 1.x auth kept whole in its metadata. No refresh is +// registered, so 2.x hands the credential over as it is and the plugin's +// own loader renews it, as it does on 1.x. +export function credentialOf(methodID, r) { + if (!r || r.type !== "success") throw new Error(r?.error || r?.message || "the sign-in failed") + const saved = json(v1Saved(r)) + if (saved.type === "api") + return { type: "oauth", methodID, access: String(saved.key ?? ""), refresh: "", expires: 0, metadata: { v1: saved } } + return { + type: "oauth", + methodID, + access: String(saved.access ?? ""), + refresh: String(saved.refresh ?? ""), + expires: int(saved.expires), + metadata: { v1: saved }, + } +} + +// authOfValue is the 1.x auth a 2.x credential stands for. +export function authOfValue(value) { + if (!value) return null + if (value.type === "oauth") { + const v1 = record(value.metadata).v1 + if (v1 && typeof v1 === "object") return v1 + return { type: "oauth", access: value.access, refresh: value.refresh, expires: value.expires } + } + if (value.type === "key") { + const meta = value.metadata && Object.keys(value.metadata).length ? { metadata: value.metadata } : {} + return { type: "api", key: value.key, ...meta } + } + return null +} + +const fingerprint = (a) => JSON.stringify([a?.type, a?.access ?? a?.key ?? "", a?.refresh ?? ""]) + +// ---- models ------------------------------------------------------------- + +const MODALITIES = ["text", "audio", "image", "video", "pdf"] + +// internalOf is a config model as 1.x hands it to provider.models: what +// fromModelsDevModel makes of it, with the config's own variants. +export function internalOf(providerID, conf, key, m) { + const mods = record(m.modalities) + const has = (list, k) => Array.isArray(list) && list.includes(k) + const cost = record(m.cost) + return { + ...m, + id: key, + providerID, + name: m.name ?? key, + api: { id: m.id ?? key, url: m.provider?.api ?? conf.api ?? conf.options?.baseURL ?? "", npm: m.provider?.npm ?? conf.npm ?? "@ai-sdk/openai-compatible" }, + status: m.status ?? "active", + headers: m.headers ?? {}, + options: m.options ?? {}, + cost: { input: money(cost.input), output: money(cost.output), cache: { read: money(cost.cache_read), write: money(cost.cache_write) } }, + limit: { context: int(m.limit?.context), input: m.limit?.input, output: int(m.limit?.output) }, + capabilities: { + temperature: m.temperature ?? false, + reasoning: m.reasoning ?? false, + attachment: m.attachment ?? false, + toolcall: m.tool_call ?? true, + input: Object.fromEntries(MODALITIES.map((k) => [k, mods.input ? has(mods.input, k) : k === "text"])), + output: Object.fromEntries(MODALITIES.map((k) => [k, mods.output ? has(mods.output, k) : k === "text"])), + interleaved: m.interleaved ?? false, + }, + release_date: m.release_date ?? "", + variants: record(m.variants), + } +} + +// modelOf is a 1.x model, in config or internal form, as a 2.x Model.Info. +export function modelOf(providerID, provider, key, m) { + const caps = record(m.capabilities) + const listFrom = (obj, list) => { + if (obj && typeof obj === "object") return MODALITIES.filter((k) => obj[k]) + if (Array.isArray(list)) return list.map(String) + return ["text"] + } + const input = listFrom(caps.input, m.modalities?.input) + const output = listFrom(caps.output, m.modalities?.output) + const c = record(m.cost) + const cache = record(c.cache) + const npm = m.api?.npm ?? m.provider?.npm + const url = m.api?.url ?? m.provider?.api + const settings = { ...record(json(m.options)) } + if (url && url !== provider.baseURL) settings.baseURL = url + const variants = Object.entries(record(m.variants)) + .filter(([, v]) => !record(v).disabled) + .map(([id, v]) => { + const { disabled: _d, ...rest } = record(json(v)) + return nonEmpty(rest) ? { id, settings: rest } : { id } + }) + const status = ["alpha", "beta", "deprecated", "active"].includes(m.status) ? m.status : "active" + const out = { + id: key, + modelID: String(m.api?.id ?? m.id ?? key), + providerID, + name: String(m.name ?? key), + capabilities: { + tools: caps.toolcall ?? m.tool_call ?? true, + input: input.length ? input : ["text"], + output: output.length ? output : ["text"], + ...(typeof (caps.temperature ?? m.temperature) === "boolean" ? { temperature: caps.temperature ?? m.temperature } : {}), + }, + variants, + time: { released: Date.parse(m.release_date ?? "") || 0 }, + cost: [{ input: money(c.input), output: money(c.output), cache: { read: money(cache.read ?? c.cache_read), write: money(cache.write ?? c.cache_write) } }], + status, + enabled: true, + limit: { context: int(m.limit?.context, 128000) || 128000, output: int(m.limit?.output, 8192) || 8192 }, + } + if (m.limit?.input) out.limit.input = int(m.limit.input) + if (npm && npm !== provider.npm) out.package = packageOf(npm) + if (nonEmpty(settings)) out.settings = settings + const headers = strings(m.headers) + if (nonEmpty(headers)) out.headers = headers + return out +} + +// ---- requests ----------------------------------------------------------- + +const urlOf = (input) => (typeof input === "string" ? input : input instanceof URL ? input.href : input?.url ?? String(input)) + +// wrapFetch sends a request the SDK made from the provider's settings the +// way 1.x would have sent it with the loader's options: the loader's base +// URL in place of the configured one, the account's key in place of the +// placeholder, the loader's headers added, through the loader's fetch. +export function wrapFetch(next, base, options) { + return async (input, init = {}) => { + const o = await options() + let url = urlOf(input) + const from = String(base ?? "").replace(/\/+$/, "") + const to = o.baseURL ? String(o.baseURL).replace(/\/+$/, "") : "" + if (from && to && from !== to && url.startsWith(from)) url = to + url.slice(from.length) + const req = input instanceof Request ? input : null + const headers = new Headers(init.headers ?? req?.headers ?? undefined) + for (const [k, v] of [...headers.entries()]) { + if (!v.includes(PLACEHOLDER)) continue + if (o.key) headers.set(k, v.replaceAll(PLACEHOLDER, o.key)) + else headers.delete(k) + } + for (const [k, v] of Object.entries(strings(o.headers))) headers.set(k, v) + const send = typeof o.fetch === "function" ? o.fetch : next ?? fetch + if (req && init.body === undefined) { + const body = req.method === "GET" || req.method === "HEAD" ? undefined : await req.text() + return send(url, { method: req.method, headers, body, signal: init.signal ?? req.signal }) + } + return send(url, { ...init, headers }) + } +} + +// ---- one plugin --------------------------------------------------------- + +async function setupPlugin(ctx, fn, live) { + const directory = ctx?.location?.directory ?? process.cwd() + // the active account each provider was last read for, and the renewed + // auth a plugin saved for it (2.x has no way for a plugin to write a + // credential back, so it is kept in the plugin's storage, under the + // credential it renews and the token it was renewed from) + const current = new Map() + const saved = new Map() + const signingIn = new Map() + const storeKey = (id, key) => `v1auth/${id}/${key}` + + const client = { + auth: { + async set(arg) { + const id = arg?.path?.id + const body = json(arg?.body) + const cur = id && current.get(id) + // a sign-in's own saves belong to the credential it is about to + // make, not the one that was active when it started + if (!cur || !body || signingIn.get(id) > 0) return { data: true } + const entry = { fp: cur.fp, auth: body } + saved.set(storeKey(id, cur.key), entry) + await Promise.resolve() + .then(() => ctx.storage?.set?.(storeKey(id, cur.key), entry)) + .catch(() => {}) + return { data: true } + }, + async get() { + return { data: undefined } + }, + }, + app: { log: async () => ({ data: true }) }, + } + + const hooks = (await fn({ client, directory, worktree: directory, project: {}, serverUrl: undefined, $: undefined }, {})) ?? {} + const cfg = { provider: {} } + try { + await hooks.config?.(cfg) + } catch {} + const auth = hooks.auth + const authID = auth?.provider ? String(auth.provider) : undefined + const providers = record(cfg.provider) + + // getAuth reads the active account: the credential 2.x holds, or what the + // plugin last saved renewing it. + const getAuth = async (id) => { + const connection = await ctx.integration.connection.active(id).catch(() => undefined) + if (!connection) { + current.delete(id) + return undefined + } + const value = await ctx.integration.connection.resolve(connection).catch(() => undefined) + const base = authOfValue(value) + if (!base) { + current.delete(id) + return undefined + } + const key = connKey(connection) + const fp = fingerprint(base) + // ours: a credential one of this plugin's own sign-ins made + const ours = value?.type === "oauth" && !!record(value.metadata).v1 + current.set(id, { key, fp, ours }) + const sk = storeKey(id, key) + let entry = saved.get(sk) + if (!entry) { + entry = await Promise.resolve() + .then(() => ctx.storage?.get?.(sk)) + .catch(() => undefined) + if (entry) saved.set(sk, entry) + } + return entry && entry.fp === fp && entry.auth ? entry.auth : base + } + + // the sign-in methods + if (authID && Array.isArray(auth.methods) && auth.methods.length) { + const label = (c) => { + const a = authOfValue(c) + const name = a?.name ?? a?.email ?? a?.metadata?.name ?? a?.metadata?.email ?? a?.account + return typeof name === "string" && name ? name : undefined + } + const begin = () => signingIn.set(authID, (signingIn.get(authID) ?? 0) + 1) + const end = () => signingIn.set(authID, Math.max(0, (signingIn.get(authID) ?? 1) - 1)) + const title = record(providers[authID]).name + // 2.x runs a transform again on every reload, from nothing + await ctx.integration.transform((editor) => { + let keyed = false + // the integration 2.x makes for an id it doesn't know is named by the + // id; the provider's own name reads better in the sign-in list + if (typeof title === "string" && title) + try { + editor.update?.(authID, (i) => { + if (i && (!i.name || i.name === authID)) i.name = title + }) + } catch {} + auth.methods.forEach((m, i) => { + if (!m) return + const methodID = `v1-${i}` + const form = fieldsOf(m.prompts) + if (m.type === "api" && typeof m.authorize !== "function") { + if (keyed) return + keyed = true + editor.method.update({ integrationID: authID, method: { type: "key", label: String(m.label ?? "API key"), ...(form ? { form } : {}) } }) + return + } + if (typeof m.authorize !== "function") return + editor.method.update({ + integrationID: authID, + method: { id: methodID, type: "oauth", label: String(m.label ?? authID), ...(form ? { form } : {}) }, + async authorize(answer) { + begin() + let ended = false + const done = () => { + if (!ended) end() + ended = true + } + try { + const inputs = Object.fromEntries(Object.entries(record(answer)).map(([k, v]) => [k, String(v)])) + const r = await m.authorize(inputs) + if (m.type === "api") { + done() + return { url: "", instructions: "", mode: "auto", callback: Promise.resolve().then(() => credentialOf(methodID, r)) } + } + if (r?.method === "code") + return { + url: String(r.url ?? ""), + instructions: String(r.instructions ?? ""), + mode: "code", + callback: async (code) => { + try { + return credentialOf(methodID, await r.callback(code)) + } finally { + done() + } + }, + } + const callback = Promise.resolve() + .then(() => r.callback()) + .then((res) => credentialOf(methodID, res)) + .finally(done) + callback.catch(() => {}) + return { url: String(r?.url ?? ""), instructions: String(r?.instructions ?? ""), mode: "auto", callback } + } catch (e) { + done() + throw e + } + }, + label, + }) + }) + }) + } + + // the loader's options for the account signed in now, read again when + // the account changes + let loaded = null + const loaderOptions = async (id) => { + if (id !== authID || typeof auth?.loader !== "function") { + const a = authID === id ? await getAuth(id) : undefined + return { key: a?.type === "api" ? a.key : undefined } + } + const a = await getAuth(id) + if (!a) return {} + const fp = current.get(id)?.key + "\0" + fingerprint(a) + if (loaded?.fp !== fp) { + const p = Promise.resolve() + .then(() => auth.loader(() => getAuth(id), providerOf(id))) + .then((o) => record(o)) + loaded = { fp, p } + p.catch(() => { + if (loaded?.fp === fp) loaded = null + }) + } + const o = await loaded.p + const key = typeof o.apiKey === "string" && o.apiKey ? o.apiKey : a.type === "api" ? a.key : undefined + return { baseURL: o.baseURL, key, headers: o.headers, fetch: o.fetch } + } + + // the providers, with the list the account's own read last gave each + const source = new Map() + // providerOf is a provider as 1.x hands it to provider.models and + // auth.loader + const providerOf = (id) => { + const conf = record(providers[id]) + const models = Object.fromEntries(Object.entries(record(conf.models)).map(([k, m]) => [k, internalOf(id, conf, k, record(m))])) + return { id, name: conf.name ?? id, source: "config", env: [], options: record(conf.options), models } + } + const listed = new Set() + for (const [id, conf0] of Object.entries(providers)) { + const conf = record(conf0) + // a provider entry that only names the sign-in (no package, no models) + // is not a provider of models + if (!conf.npm && !Object.keys(record(conf.models)).length) continue + const options = record(conf.options) + const { apiKey: _k, baseURL: _b, fetch: _f, headers: optHeaders, ...rest } = options + // with no base URL the config leaves it to the loader: a name that + // can't resolve stands in for it, and each request swaps in the + // loader's (wrapFetch) + const baseURL = options.baseURL ?? conf.api ?? `https://${id.replace(/[^a-z0-9-]/gi, "-")}.opencode2-v1.invalid` + const npm = conf.npm ?? "@ai-sdk/openai-compatible" + const info = { + id, + ...(id === authID ? { integrationID: id } : {}), + name: String(conf.name ?? id), + activation: "auto", + package: packageOf(npm), + settings: { ...record(json(rest)), ...(baseURL ? { baseURL: String(baseURL) } : {}) }, + } + const headers = { ...strings(conf.headers), ...strings(optHeaders) } + if (nonEmpty(headers)) info.headers = headers + const prov = { baseURL, npm } + const fromConfig = () => + Object.entries(record(conf.models)).map(([key, m]) => modelOf(id, prov, key, internalOf(id, conf, key, record(m)))) + listed.add(id) + await ctx.provider.transform((editor) => { + const s = source.get(id) + editor.add({ info, models: s?.models ?? fromConfig(), sourceConnection: s?.connection }) + }) + source.set(id, { conf, prov, models: null, connection: undefined }) + } + + // each request: the placeholder key, and the fetch that swaps in the + // account's. A provider the package doesn't list (one 2.x has built in + // that the plugin only signs in to) is left to 2.x unless the plugin's + // loader serves it and one of the plugin's own sign-ins is active. + const own = authID && !listed.has(authID) && typeof auth?.loader === "function" ? [authID] : [] + for (const id of new Set([...listed, ...own])) { + const base = source.get(id)?.prov.baseURL + await ctx.aisdk.hook( + "sdk", + async (evt) => { + const opts = evt.options + if (!opts || opts.__opencode2) return + if (!listed.has(id)) { + await getAuth(id) + if (!current.get(id)?.ours) return + } + opts.__opencode2 = true + opts.apiKey = PLACEHOLDER + opts.fetch = wrapFetch(opts.fetch, opts.baseURL ?? base, () => loaderOptions(id)) + }, + { providerID: id }, + ) + } + + // refresh reads the account's own list after a sign-in or a switch + const listID = hooks.provider?.id ? String(hooks.provider.id) : undefined + let refreshing = null + let again = false + // the account the list was last read for: a credential.updated that + // leaves it as it was reads nothing again + let readFor = null + const stateOf = async () => { + const c = await ctx.integration.connection.active(authID).catch(() => undefined) + const a = c ? await getAuth(authID) : undefined + return connKey(c) + "\0" + (a ? fingerprint(a) : "") + } + const refresh = () => { + if (refreshing) { + again = true + return refreshing + } + refreshing = (async () => { + try { + if (!authID || !source.has(authID)) return + const s = source.get(authID) + const connection = await ctx.integration.connection.active(authID).catch(() => undefined) + const a = connection ? await getAuth(authID) : undefined + readFor = connKey(connection) + "\0" + (a ? fingerprint(a) : "") + if (!a || listID !== authID || typeof hooks.provider?.models !== "function") { + if (s.connection || s.models) { + s.connection = undefined + s.models = null + await ctx.provider.reload() + } + return + } + const provider = providerOf(authID) + let got + try { + got = await hooks.provider.models(provider, { auth: a }) + } catch { + got = null + } + if (connKey(await ctx.integration.connection.active(authID).catch(() => undefined)) !== connKey(connection)) { + again = true + return + } + s.connection = connection + s.models = got && typeof got === "object" ? Object.entries(got).map(([k, m]) => modelOf(authID, s.prov, k, record(m))) : null + await ctx.provider.reload() + await ctx.model?.reload?.() + } finally { + refreshing = null + if (again && live.on) { + again = false + void refresh() + } + } + })() + return refreshing + } + + if (authID && ctx.event?.subscribe) + void (async () => { + try { + // a switch names the integration; an update (a sign-in, a removal) + // names nothing, so it reads again only when this account changed + const types = ["credential.switched", "credential.updated"] + for await (const event of ctx.event.subscribe({ types })) { + if (!live.on) return + if (event?.type === "credential.switched" && event?.data?.integrationID === authID) { + loaded = null + await refresh() + } else if (event?.type === "credential.updated" && (await stateOf()) !== readFor) { + await refresh() + } + } + } catch {} + })() + void refresh() +} + +export async function setup(ctx, mod = v1) { + const live = { on: true } + for (const fn of pluginsOf(mod)) { + try { + await setupPlugin(ctx, fn, live) + } catch (e) { + // one plugin failing to start leaves the package's others working + console.error(`${pkg.name}: ${e?.message ?? e}`) + } + } + return () => { + live.on = false + } +} + +export default { id: pkg.name, setup: (ctx) => setup(ctx) } diff --git a/packages/atomcode/package.json b/packages/atomcode/package.json new file mode 100644 index 0000000..5ddd6e3 --- /dev/null +++ b/packages/atomcode/package.json @@ -0,0 +1,92 @@ +{ + "name": "@magpie-community/opencode-atomcode-auth", + "version": "0.3.0", + "description": "AtomCode (AtomGit CodingPlan) for Magpie and OpenCode: browser OAuth or local CLI sign-in, signed requests, persistent diagnostics, native plan claim, live models and quota windows", + "type": "module", + "main": "./opencode.mjs", + "exports": { + ".": "./opencode2.mjs" + }, + "files": [ + "index.mjs", + "opencode.mjs", + "opencode2.mjs", + "internal.mjs", + "auth-file.mjs", + "request-body.mjs", + "sign.mjs", + "oauth.mjs", + "codingplan.mjs", + "quota.mjs", + "models.mjs", + "errors.mjs", + "state.mjs", + "diagnostics.mjs", + "page/index.html", + "page/boot.js", + "page/diagnostics.html", + "page/app.css", + "page/app.js", + "page/icon.svg", + "i18n.mjs", + "version.mjs", + "assets/", + "README.md", + "README.zh-CN.md", + "CHANGELOG.md", + "NOTICE.md", + "SECURITY.md", + "LICENSE" + ], + "keywords": [ + "magpie", + "magpie-plugin", + "opencode", + "opencode-plugin", + "opencode-auth", + "opencode-provider", + "atomcode", + "atomgit", + "codingplan", + "openai-compatible" + ], + "license": "MIT", + "repository": { + "type": "git", + "url": "https://github.com/magpie-community/plugins", + "directory": "packages/atomcode" + }, + "homepage": "https://github.com/magpie-community/plugins/tree/main/packages/atomcode#readme", + "bugs": { + "url": "https://github.com/magpie-community/plugins/issues" + }, + "engines": { + "node": ">=20", + "magpie": ">=0.1.2629" + }, + "scripts": { + "test": "bun test", + "test:coverage": "node --experimental-test-coverage --test test/*.test.mjs", + "test:coverage:enforce": "node --experimental-test-coverage --test-coverage-lines=85 --test-coverage-branches=80 --test-coverage-functions=85 --test test/*.test.mjs", + "test:live": "node scripts/live-smoke.mjs", + "pack:check": "npm pack --dry-run --json" + }, + "magpie": { + "icon": "https://atomgit.com/favicon.ico", + "maxConcurrency": 8, + "options": { + "locale": "auto", + "clientVersion": "5.2.3", + "quotaTtlMs": 60000, + "maxOutputTokens": 32768, + "diagnosticsPort": 3478 + }, + "page": { + "title": "AtomCode diagnostics", + "titles": { "zh": "AtomCode 诊断" }, + "file": "page/index.html", + "icon": "page/icon.svg", + "service": { "port": 3478, "option": "diagnosticsPort" } + } + } +} diff --git a/packages/atomcode/page/app.css b/packages/atomcode/page/app.css new file mode 100644 index 0000000..124d188 --- /dev/null +++ b/packages/atomcode/page/app.css @@ -0,0 +1,738 @@ +:root { + color-scheme: light; + --bg: #f3f1eb; + --card: #fbfaf6; + --fg: #20221d; + --fg-2: #50534b; + --muted: #73766d; + --faint: #9a9d94; + --line: #deddd5; + --accent: #b75f22; + --accent-soft: #f0d8bf; + --accent-fg: #fffaf3; + --green: #3f6b49; + --red: #a33f34; + --amber: #9b6a1f; + --font: "Avenir Next", "Segoe UI", sans-serif; + --code: "SFMono-Regular", "SF Mono", Menlo, Consolas, monospace; + --ease-out: cubic-bezier(.23, 1, .32, 1); + font-family: var(--font); + font-synthesis: none; + text-rendering: optimizeLegibility; +} + +html[data-theme="dark"] { + color-scheme: dark; + --bg: #171817; + --card: #20211f; + --fg: #f1f0eb; + --fg-2: #c5c6be; + --muted: #92958c; + --faint: #666a62; + --line: #363833; + --accent: #e59a57; + --accent-soft: #493327; + --accent-fg: #1b120a; + --green: #83bd8f; + --red: #ec8b80; + --amber: #e3b15f; +} + +@media (prefers-color-scheme: dark) { + html[data-theme=""] { + color-scheme: dark; + --bg: #171817; + --card: #20211f; + --fg: #f1f0eb; + --fg-2: #c5c6be; + --muted: #92958c; + --faint: #666a62; + --line: #363833; + --accent: #e59a57; + --accent-soft: #493327; + --accent-fg: #1b120a; + --green: #83bd8f; + --red: #ec8b80; + --amber: #e3b15f; + } +} + +* { box-sizing: border-box; } +html { min-height: 100%; } +body { + min-height: 100vh; + margin: 0; + color: var(--fg); + background: var(--bg); + font: 13px/1.5 var(--font); + -webkit-font-smoothing: antialiased; +} + +[hidden] { display: none !important; } +::selection { color: var(--accent-fg); background: var(--accent); } + +.workspace { + width: min(1120px, calc(100vw - 40px)); + margin: 0 auto; + padding: 30px 0 44px; +} + +.topbar, +.brand, +.toolbar, +.panel-head, +.overview, +.overview-main, +.quick-facts, +.quota-meta, +.window-head, +.window-meta, +.label-row, +.result-block, +.checks, +.checks li, +footer { + display: flex; +} + +.topbar { + align-items: center; + justify-content: space-between; + gap: 24px; + margin-bottom: 18px; +} + +.brand { min-width: 0; align-items: center; gap: 12px; } +.brand-mark { + display: grid; + width: 44px; + height: 44px; + flex: 0 0 44px; + place-items: center; + border: 1px solid var(--line); + border-radius: 12px; + background: var(--card); + box-shadow: inset 0 1px 0 color-mix(in srgb, var(--fg) 6%, transparent); +} +.brand-mark img { display: block; width: 36px; height: 36px; } +.brand-copy { min-width: 0; } + +h1, h2, h3, p, dl, dd, dt { margin: 0; } +h1 { + overflow-wrap: anywhere; + font-size: clamp(22px, 3vw, 28px); + font-weight: 650; + letter-spacing: -.035em; + line-height: 1.1; +} +h2 { + font-size: 17px; + font-weight: 650; + letter-spacing: -.02em; + line-height: 1.25; +} +.product-name { color: var(--fg); } +.title-slash { margin: 0 .28em; color: var(--faint); font-weight: 400; } +.kicker { + margin-bottom: 5px; + color: var(--muted); + font-size: 9.5px; + font-weight: 750; + letter-spacing: .16em; + line-height: 1.2; + text-transform: uppercase; +} + +.toolbar { + flex: 0 1 auto; + align-items: center; + justify-content: flex-end; + gap: 8px; + flex-wrap: wrap; +} + +.status-chip { + display: inline-flex; + min-height: 34px; + align-items: center; + gap: 7px; + padding: 0 10px; + border: 1px solid var(--line); + border-radius: 9px; + color: var(--muted); + background: color-mix(in srgb, var(--card) 82%, transparent); + font-size: 11.5px; + font-weight: 550; + white-space: nowrap; +} +.status-dot, +.health-mark span, +.result-mark { + display: block; + width: 7px; + height: 7px; + flex: 0 0 auto; + border-radius: 50%; + background: currentColor; +} +.status-chip[data-tone="loading"] { color: var(--amber); } +.status-chip[data-tone="ok"] { color: var(--green); } +.status-chip[data-tone="error"] { color: var(--red); } +.status-chip[data-tone="info"] { color: var(--accent); } +.status-chip[data-tone="loading"] .status-dot { animation: breathe 1.2s ease-in-out infinite; } + +.button { + display: inline-flex; + min-height: 36px; + align-items: center; + justify-content: center; + gap: 7px; + padding: 0 12px; + border: 1px solid var(--line); + border-radius: 9px; + color: var(--fg); + background: var(--card); + font: 620 12px/1 var(--font); + letter-spacing: -.005em; + cursor: pointer; + appearance: none; + transition: + transform 140ms var(--ease-out), + background-color 160ms ease, + border-color 160ms ease, + color 160ms ease, + opacity 160ms ease; +} +.button svg { + width: 15px; + height: 15px; + flex: 0 0 auto; + fill: none; + stroke: currentColor; + stroke-linecap: round; + stroke-linejoin: round; + stroke-width: 1.7; +} +.button.primary { + border-color: color-mix(in srgb, var(--accent) 74%, var(--line)); + color: var(--accent-fg); + background: var(--accent); +} +.button:active { transform: scale(.97); } +.button:focus-visible, +summary:focus-visible { + outline: 2px solid color-mix(in srgb, var(--accent) 76%, transparent); + outline-offset: 2px; +} +.button:disabled { cursor: wait; opacity: .55; transform: none; } +#refresh[data-busy="true"] svg { animation: spin 720ms linear infinite; } + +@media (hover: hover) and (pointer: fine) { + .button.secondary:hover { + border-color: color-mix(in srgb, var(--fg) 24%, var(--line)); + background: color-mix(in srgb, var(--card) 82%, var(--fg) 8%); + } + .button.primary:hover { + background: color-mix(in srgb, var(--accent) 88%, var(--fg)); + } + .technical summary:hover strong { color: var(--accent); } +} + +.overview { + align-items: center; + justify-content: space-between; + gap: 28px; + padding: 21px 22px; + overflow: hidden; + border: 1px solid var(--line); + border-left: 3px solid var(--line); + border-radius: 15px; + background: var(--card); + box-shadow: 0 12px 30px rgb(0 0 0 / 3%); +} +.overview[data-tone="good"] { border-left-color: var(--green); } +.overview[data-tone="warn"] { border-left-color: var(--amber); } +.overview[data-tone="error"] { border-left-color: var(--red); } +.overview[data-tone="loading"] { border-left-color: var(--accent); } +.overview-main { min-width: 0; align-items: flex-start; gap: 13px; } +.health-mark { + display: grid; + width: 32px; + height: 32px; + flex: 0 0 32px; + margin-top: 1px; + place-items: center; + border: 1px solid color-mix(in srgb, currentColor 24%, var(--line)); + border-radius: 50%; + color: var(--accent); + background: color-mix(in srgb, currentColor 9%, transparent); +} +.overview[data-tone="good"] .health-mark { color: var(--green); } +.overview[data-tone="warn"] .health-mark { color: var(--amber); } +.overview[data-tone="error"] .health-mark { color: var(--red); } +.health-copy { min-width: 0; } +.health-copy h2 { margin-bottom: 5px; } +.health-summary { + max-width: 590px; + color: var(--fg-2); + font-size: 12.5px; + overflow-wrap: anywhere; +} + +.quick-facts { + display: grid; + grid-template-columns: repeat(4, minmax(96px, auto)); + gap: 0; + flex: 0 1 auto; +} +.quick-facts > div { + min-width: 0; + padding: 1px 16px; + border-left: 1px solid var(--line); +} +.quick-facts span, +.quota-meta span, +.detail-list small, +.result-block time { + display: block; + color: var(--muted); + font-size: 10.5px; +} +.quick-facts strong { + display: block; + margin-top: 3px; + overflow: hidden; + color: var(--fg); + font-size: 12px; + font-weight: 620; + font-variant-numeric: tabular-nums; + text-overflow: ellipsis; + white-space: nowrap; +} + +.content-grid { + display: grid; + grid-template-columns: minmax(0, 1.55fr) minmax(300px, .85fr); + gap: 14px; + margin-top: 14px; +} +.troubleshoot-grid { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 14px; + margin-top: 14px; +} + +.panel { + min-width: 0; + padding: 21px; + border: 1px solid var(--line); + border-radius: 15px; + background: var(--card); + box-shadow: 0 12px 30px rgb(0 0 0 / 3%); +} +.panel-head { + align-items: flex-start; + justify-content: space-between; + gap: 16px; +} +.badge { + flex: 0 0 auto; + padding: 5px 8px; + border: 1px solid color-mix(in srgb, var(--amber) 28%, var(--line)); + border-radius: 7px; + color: var(--amber); + background: color-mix(in srgb, var(--amber) 9%, transparent); + font-size: 9.5px; + font-weight: 700; + letter-spacing: .03em; + white-space: nowrap; +} + +.quota-meta { + gap: 26px; + margin-top: 20px; + padding-bottom: 14px; + border-bottom: 1px solid var(--line); +} +.quota-meta > div { min-width: 0; } +.quota-meta strong { + display: block; + margin-top: 3px; + overflow-wrap: anywhere; + font-size: 12.5px; + font-weight: 620; + font-variant-numeric: tabular-nums; +} + +.windows { + margin: 0; + padding: 0; + list-style: none; +} +.window { padding: 18px 0 2px; } +.window + .window { + margin-top: 15px; + border-top: 1px solid var(--line); +} +.window-head, +.window-meta { + align-items: baseline; + justify-content: space-between; + gap: 14px; +} +.window-head strong { + min-width: 0; + overflow-wrap: anywhere; + font-size: 13px; + font-weight: 650; +} +.window-head > span { + flex: 0 0 auto; + color: var(--fg-2); + font-size: 12px; + font-variant-numeric: tabular-nums; +} +.progress { + height: 8px; + margin: 11px 0 8px; + overflow: hidden; + border-radius: 999px; + background: color-mix(in srgb, var(--fg) 8%, transparent); +} +.progress-fill { + width: 100%; + height: 100%; + border-radius: inherit; + background: var(--accent); + transform: scaleX(0); + transform-origin: left center; + transition: transform 240ms var(--ease-out); +} +.window[data-level="warn"] .progress-fill { + background: var(--amber); +} +.window[data-level="danger"] .progress-fill { + background: var(--red); +} +.window-meta { + color: var(--muted); + font-size: 10.5px; + font-variant-numeric: tabular-nums; +} +.window-meta span { min-width: 0; overflow-wrap: anywhere; } +.window-meta span:last-child { flex: 0 0 auto; text-align: right; } + +.empty { + margin-top: 18px; + color: var(--muted); + font-size: 12px; + overflow-wrap: anywhere; +} +.empty.compact { margin-top: 10px; } + +.detail-list { margin-top: 18px; } +.detail-list > div { + display: grid; + grid-template-columns: 82px minmax(0, 1fr); + gap: 12px; + padding: 11px 0; + border-top: 1px solid var(--line); +} +.detail-list > div:first-child { border-top: 0; } +.detail-list dt { + color: var(--muted); + font-size: 10.5px; +} +.detail-list dd { + min-width: 0; + overflow-wrap: anywhere; + color: var(--fg); + font-size: 12.5px; + font-weight: 580; + text-align: right; +} +.detail-list small { + margin-top: 2px; + overflow-wrap: anywhere; +} + +.model-block { + margin-top: 12px; + padding-top: 15px; + border-top: 1px solid var(--line); +} +.label-row { + align-items: center; + justify-content: space-between; + gap: 12px; +} +.label { + color: var(--muted); + font-size: 9.5px; + font-weight: 720; + letter-spacing: .13em; + text-transform: uppercase; +} +.count { + color: var(--muted); + font-size: 10.5px; + font-variant-numeric: tabular-nums; +} +.model-list { + display: flex; + max-height: 220px; + flex-wrap: wrap; + gap: 6px; + margin: 10px 0 0; + padding: 0 4px 0 0; + overflow: auto; + list-style: none; + scrollbar-width: thin; +} +.model-list code { + display: block; + max-width: 100%; + padding: 4px 7px; + border: 1px solid var(--line); + border-radius: 6px; + color: var(--fg-2); + background: color-mix(in srgb, var(--fg) 4%, transparent); + font: 10.5px/1.35 var(--code); + overflow-wrap: anywhere; +} + +.result-panel { min-height: 192px; } +.result-block { + align-items: flex-start; + gap: 11px; + margin-top: 18px; + padding: 14px; + border: 1px solid var(--line); + border-radius: 11px; + background: color-mix(in srgb, var(--fg) 2.5%, transparent); +} +.result-block .result-mark { margin-top: 5px; color: var(--faint); } +.result-block[data-tone="good"] .result-mark { color: var(--green); } +.result-block[data-tone="warn"] .result-mark { color: var(--amber); } +.result-block[data-tone="error"] .result-mark { color: var(--red); } +.result-block > div { min-width: 0; } +.result-block strong { + display: block; + overflow-wrap: anywhere; + font-size: 12.5px; + font-weight: 650; +} +.result-block p { + margin-top: 3px; + color: var(--muted); + font-size: 11.5px; + overflow-wrap: anywhere; + white-space: pre-wrap; +} +.result-block time { margin-top: 6px; font-variant-numeric: tabular-nums; } + +.checks { + flex-wrap: wrap; + gap: 6px; + margin: 10px 0 0; + padding: 0; + list-style: none; +} +.checks:empty { display: none; } +.checks li { + align-items: center; + gap: 5px; + padding: 4px 7px; + border: 1px solid var(--line); + border-radius: 6px; + color: var(--muted); + font-size: 10px; +} +.checks li::before { + width: 5px; + height: 5px; + border-radius: 50%; + background: var(--faint); + content: ""; +} +.checks li[data-tone="good"] { color: var(--green); } +.checks li[data-tone="good"]::before { background: var(--green); } +.checks li[data-tone="error"] { color: var(--red); } +.checks li[data-tone="error"]::before { background: var(--red); } + +.technical { margin-top: 14px; } +.technical summary { + display: flex; + align-items: center; + justify-content: space-between; + gap: 20px; + cursor: pointer; + list-style: none; +} +.technical summary::-webkit-details-marker { display: none; } +.technical summary > span { min-width: 0; } +.technical summary .kicker { display: block; } +.technical summary strong { + display: block; + overflow-wrap: anywhere; + font-size: 12.5px; + font-weight: 620; + transition: color 160ms ease; +} +.technical summary svg { + width: 16px; + height: 16px; + flex: 0 0 auto; + fill: none; + stroke: var(--muted); + stroke-linecap: round; + stroke-linejoin: round; + stroke-width: 1.7; + transition: transform 180ms var(--ease-out); +} +.technical[open] summary svg { transform: rotate(180deg); } +.tech-grid { + display: grid; + grid-template-columns: repeat(3, minmax(0, 1fr)); + gap: 0 24px; + margin-top: 18px; + padding-top: 6px; + border-top: 1px solid var(--line); +} +.tech-grid > div { min-width: 0; padding: 10px 0; } +.tech-grid dt { + color: var(--muted); + font-size: 10px; +} +.tech-grid dd { + margin-top: 2px; + overflow-wrap: anywhere; + font: 10.5px/1.45 var(--code); + font-variant-numeric: tabular-nums; +} + +footer { + align-items: center; + justify-content: space-between; + gap: 22px; + margin-top: 20px; + color: var(--muted); + font-size: 11px; +} +footer p { max-width: 760px; overflow-wrap: anywhere; } +footer .button { flex: 0 0 auto; } + +.copy-buffer { + position: fixed; + top: 0; + left: -9999px; + width: 1px; + height: 1px; + opacity: 0; + pointer-events: none; +} + +body[data-state="loading"] [data-skeleton] { + position: relative; + display: inline-block; + min-width: 34px; + color: transparent !important; +} +body[data-state="loading"] [data-skeleton]::after { + position: absolute; + inset: .18em 8% .18em 0; + border-radius: 999px; + background: color-mix(in srgb, var(--fg) 10%, transparent); + content: ""; + opacity: .55; + animation: skeleton-pulse 1.2s ease-in-out infinite; +} + +body[data-state="ready"] .overview, +body[data-state="ready"] .content-grid, +body[data-state="ready"] .troubleshoot-grid, +body[data-state="ready"] .technical { + animation: enter 180ms var(--ease-out) both; +} +body[data-state="ready"] .content-grid { animation-delay: 20ms; } +body[data-state="ready"] .troubleshoot-grid { animation-delay: 35ms; } +body[data-state="ready"] .technical { animation-delay: 50ms; } + +@keyframes enter { + from { opacity: 0; transform: translateY(6px); } + to { opacity: 1; transform: translateY(0); } +} +@keyframes skeleton-pulse { + 50% { opacity: .9; } +} +@keyframes breathe { + 50% { opacity: .35; } +} +@keyframes spin { + to { transform: rotate(360deg); } +} + +@media (max-width: 920px) { + .topbar { align-items: flex-start; } + .overview { align-items: flex-start; flex-direction: column; } + .quick-facts { + width: 100%; + grid-template-columns: repeat(4, minmax(0, 1fr)); + } + .quick-facts > div:first-child { padding-left: 0; border-left: 0; } + .content-grid { grid-template-columns: 1fr; } + .tech-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); } +} + +@media (max-width: 720px) { + .workspace { + width: min(100% - 28px, 1120px); + padding-top: 20px; + } + .topbar { flex-direction: column; } + .toolbar { width: 100%; justify-content: flex-start; } + .status-chip { max-width: 100%; white-space: normal; } + .quick-facts { grid-template-columns: repeat(2, minmax(0, 1fr)); } + .quick-facts > div { padding: 9px 12px 0 0; } + .quick-facts > div:nth-child(3) { + margin-top: 10px; + padding-left: 0; + border-left: 0; + } + .troubleshoot-grid { grid-template-columns: 1fr; } + footer { align-items: flex-start; flex-direction: column; } +} + +@media (max-width: 480px) { + .workspace { width: min(100% - 22px, 1120px); } + .brand { align-items: flex-start; } + .brand-mark { width: 40px; height: 40px; flex-basis: 40px; } + .brand-mark img { width: 32px; height: 32px; } + .toolbar { gap: 7px; } + .status-chip { width: 100%; } + .toolbar .button { flex: 1 1 138px; } + .overview { padding: 18px; } + .overview-main { gap: 10px; } + .health-mark { width: 28px; height: 28px; flex-basis: 28px; } + .quick-facts { grid-template-columns: 1fr 1fr; } + .quick-facts > div { min-height: 42px; } + .panel { padding: 18px; } + .quota-meta { gap: 16px; flex-direction: column; } + .window-head, + .window-meta { align-items: flex-start; flex-direction: column; gap: 4px; } + .window-meta span:last-child { text-align: left; } + .detail-list > div { grid-template-columns: 72px minmax(0, 1fr); } + .tech-grid { grid-template-columns: 1fr; } +} + +@media (prefers-reduced-motion: reduce) { + *, + *::before, + *::after { + scroll-behavior: auto !important; + animation-duration: .001ms !important; + animation-iteration-count: 1 !important; + transition-duration: .001ms !important; + } +} diff --git a/packages/atomcode/page/app.js b/packages/atomcode/page/app.js new file mode 100644 index 0000000..202726d --- /dev/null +++ b/packages/atomcode/page/app.js @@ -0,0 +1,869 @@ +(() => { + document.body.dataset.app = "ready"; + const query = new URLSearchParams(location.search); + const meta = document.querySelector('meta[name="atomcode-token"]'); + const token = meta?.content || ""; + const locale = ( + query.get("lang") || + document.documentElement.lang || + "en" + ).toLowerCase().startsWith("zh") + ? "zh" + : "en"; + const text = { + en: { + eyebrow: "LOCAL DIAGNOSTICS", + pageTitle: "Diagnostics", + loading: "Loading local snapshot…", + refreshing: "Refreshing snapshot…", + ready: "Snapshot ready", + failed: "Snapshot unavailable", + loadFailedTitle: "Could not load diagnostics", + loadFailedSummary: "The page opened, but the local service did not return a usable snapshot.", + refreshFailedTitle: "Latest refresh failed", + refreshFailedSummary: "The earlier snapshot is still shown. Retry when the diagnostics service is available.", + healthLoading: "Loading local snapshot", + localOnly: "This view reads local state only. It does not test the AtomCode upstream.", + localReadyTitle: "Local diagnostics are ready", + localReadySummary: "The page can read this computer's saved AtomCode state. Upstream availability is not tested here.", + noAccountTitle: "No account snapshot", + noAccountSummary: "Sign in to AtomCode in Magpie, then refresh this snapshot.", + recentErrorTitle: "A recent error needs attention", + recentErrorSummary: "Review the redacted error, run the offline self-check, or copy the report before asking for help.", + checkFailedTitle: "Offline self-check failed", + checkFailedSummary: "The signing or version configuration needs attention. Check the failing item below.", + refresh: "Refresh snapshot", + selfCheck: "Run offline self-check", + checking: "Running offline self-check…", + checkPassedChip: "Self-check passed", + checkFailedChip: "Self-check failed", + account: "Account", + models: "Models", + version: "Version", + lastRefresh: "Last refresh", + quotaReadout: "QUOTA WINDOWS", + quotaTitle: "Current quota snapshot", + stale: "Historical snapshot", + plan: "Plan", + captured: "Captured", + noQuota: "No successful quota snapshot has been recorded yet.", + catalogKicker: "PROVIDER STATE", + catalogTitle: "Catalog and account", + modelCatalog: "Model catalog", + noModels: "No model catalog has been recorded yet.", + namesUnavailable: "Model names are unavailable.", + selfCheckTitle: "OFFLINE SELF-CHECK", + signature: "Signature and configuration", + notRun: "Not run in this session", + checkHint: "Run the check to verify signing and the local version configuration.", + checkOk: "Signature and configuration checks passed", + checkFailed: "Offline self-check failed", + checkedAt: "Checked {time} · {ms} ms", + checkSignature: "Signature", + checkVersion: "Version", + checkConfiguration: "Configuration", + pass: "pass", + fail: "fail", + errorTitle: "LAST ERROR", + redacted: "Redacted record", + noError: "No recorded error", + noErrorHint: "This only reflects the last locally recorded failure.", + technicalKicker: "TECHNICAL DETAILS", + technicalTitle: "Runtime and snapshot metadata", + generated: "Generated", + runtime: "Runtime", + platform: "Platform", + schema: "State schema", + diagnosticsPort: "Diagnostics port", + modelSource: "Model source", + versionSource: "Version source", + autoClaim: "Auto claim", + autoVersion: "Auto version", + readOnly: "Read only", + privacy: "Read-only. No request is sent to AtomGit from this page. Tokens, emails, prompts and raw responses are never included.", + copy: "Copy redacted report", + copied: "Report copied", + copyFailed: "Could not copy the report.", + noSnapshot: "There is no loaded snapshot to copy yet.", + startupFailedTitle: "Diagnostics page could not initialize", + startupFailedSummary: + "The page loaded, but a browser compatibility check failed. Refresh after updating Magpie, or reopen the diagnostics page.", + startupFailedStatus: "Page initialization failed", + connected: "Connected", + notConnected: "No snapshot", + loginBrowser: "Browser sign-in", + loginCli: "AtomCode CLI sign-in", + loginMethod: "Sign-in method", + unknown: "Unknown", + live: "Live catalog", + cached: "Cached catalog", + builtIn: "Built-in catalog", + manifest: "Official manifest", + fallback: "Built-in fallback", + enabled: "Enabled", + disabled: "Disabled", + yes: "Yes", + no: "No", + modelsCount: "{count} models", + modelCountOne: "1 model", + capturedAt: "Captured {time}", + updatedAt: "Updated {time}", + checkedAtShort: "Checked {time}", + usedPercent: "{used}% used", + quotaUnknown: "Usage unavailable", + resetUnknown: "Reset time unavailable", + resetNow: "Resetting now", + quotaWindowLabel: "{name} usage", + reportTitle: "AtomCode diagnostics report", + reportQuotaWindow: "Quota window", + reportSelfCheck: "Offline self-check", + reportLastError: "Last error", + reportRuntime: "Runtime", + seconds: "{value}s", + minutes: "{value} min", + hours: "{value} hr", + days: "{value} d", + }, + zh: { + eyebrow: "本地诊断", + pageTitle: "诊断", + loading: "正在读取本机快照…", + refreshing: "正在刷新快照…", + ready: "快照已就绪", + failed: "快照不可用", + loadFailedTitle: "无法加载诊断信息", + loadFailedSummary: "页面已打开,但本机服务没有返回可用的快照。", + refreshFailedTitle: "最近一次刷新失败", + refreshFailedSummary: "页面仍显示之前的快照。诊断服务恢复后可再次重试。", + healthLoading: "正在读取本地快照", + localOnly: "这里只读取本机状态,不会测试 AtomCode 上游是否可用。", + localReadyTitle: "本地诊断数据已就绪", + localReadySummary: "页面已读到这台电脑保存的 AtomCode 状态;上游是否可用不在此页测试。", + noAccountTitle: "暂无账号快照", + noAccountSummary: "请先在 Magpie 中登录 AtomCode,然后刷新此快照。", + recentErrorTitle: "最近有错误记录,请确认是否已恢复", + recentErrorSummary: "可查看下方脱敏错误、运行离线自检,或在求助前复制诊断报告。", + checkFailedTitle: "离线自检未通过", + checkFailedSummary: "签名或版本配置需要处理,请查看下方未通过的项目。", + refresh: "刷新快照", + selfCheck: "运行离线自检", + checking: "正在运行离线自检…", + checkPassedChip: "自检通过", + checkFailedChip: "自检未通过", + account: "账号", + models: "模型", + version: "版本", + lastRefresh: "最近刷新", + quotaReadout: "额度窗口", + quotaTitle: "当前额度快照", + stale: "历史快照", + plan: "套餐", + captured: "记录时间", + noQuota: "尚未记录成功的额度快照。", + catalogKicker: "供应商状态", + catalogTitle: "模型目录与账号", + modelCatalog: "模型目录", + noModels: "尚未记录模型目录。", + namesUnavailable: "暂时无法获取模型名称。", + selfCheckTitle: "离线自检", + signature: "签名与配置", + notRun: "本次会话尚未运行", + checkHint: "运行后会检查请求签名与本机版本配置。", + checkOk: "签名与配置检查通过", + checkFailed: "离线自检未通过", + checkedAt: "检查于 {time} · {ms} ms", + checkSignature: "请求签名", + checkVersion: "版本号", + checkConfiguration: "配置", + pass: "通过", + fail: "未通过", + errorTitle: "最近错误", + redacted: "已脱敏记录", + noError: "尚未记录错误", + noErrorHint: "这里只反映最近一次写入本机的失败记录。", + technicalKicker: "技术详情", + technicalTitle: "运行时与快照元数据", + generated: "生成时间", + runtime: "运行时", + platform: "平台", + schema: "状态版本", + diagnosticsPort: "诊断端口", + modelSource: "模型来源", + versionSource: "版本来源", + autoClaim: "自动领取", + autoVersion: "自动追版本", + readOnly: "只读模式", + privacy: "只读页面。不会从这里请求 AtomGit。页面不包含令牌、邮箱、提示词或原始响应。", + copy: "复制脱敏报告", + copied: "报告已复制", + copyFailed: "复制报告失败。", + noSnapshot: "目前还没有可复制的快照。", + startupFailedTitle: "诊断页初始化失败", + startupFailedSummary: "页面已加载,但浏览器兼容性检查未通过。请更新 Magpie 后刷新,或重新打开诊断页。", + startupFailedStatus: "页面初始化失败", + connected: "已连接", + notConnected: "暂无快照", + loginBrowser: "浏览器登录", + loginCli: "AtomCode CLI 登录", + loginMethod: "登录方式", + unknown: "未知", + live: "实时目录", + cached: "缓存目录", + builtIn: "内置目录", + manifest: "官方清单", + fallback: "内置回退", + enabled: "已开启", + disabled: "已关闭", + yes: "是", + no: "否", + modelsCount: "{count} 个模型", + modelCountOne: "1 个模型", + capturedAt: "记录于 {time}", + updatedAt: "更新于 {time}", + checkedAtShort: "检查于 {time}", + usedPercent: "已用 {used}%", + quotaUnknown: "暂无用量数据", + resetUnknown: "暂无重置时间", + resetNow: "即将重置", + quotaWindowLabel: "{name} 用量", + reportTitle: "AtomCode 诊断报告", + reportQuotaWindow: "额度窗口", + reportSelfCheck: "离线自检", + reportLastError: "最近错误", + reportRuntime: "运行时", + seconds: "{value} 秒", + minutes: "{value} 分钟", + hours: "{value} 小时", + days: "{value} 天", + }, + }[locale]; + + const element = (id) => document.getElementById(id); + const hasOwn = (object, key) => + Object.prototype.hasOwnProperty.call(object, key); + const fill = (value, values) => + String(value).replace(/\{(\w+)\}/g, (all, key) => + hasOwn(values, key) ? String(values[key]) : all, + ); + const clear = (node) => { + while (node.firstChild) node.removeChild(node.firstChild); + }; + const safeFormat = (factory) => { + try { + return factory(); + } catch { + return undefined; + } + }; + const dateTimeFormat = safeFormat(() => new Intl.DateTimeFormat(locale, { + dateStyle: "medium", + timeStyle: "short", + })); + const shortTimeFormat = safeFormat(() => new Intl.DateTimeFormat(locale, { + month: "short", + day: "numeric", + hour: "2-digit", + minute: "2-digit", + })); + const numberFormat = safeFormat(() => new Intl.NumberFormat(locale, { + maximumFractionDigits: 1, + })); + const relativeTimeFormat = safeFormat(() => new Intl.RelativeTimeFormat(locale, { + numeric: "auto", + style: "short", + })); + const formatNumber = (value) => { + try { + return numberFormat?.format(value) ?? String(value); + } catch { + return String(value); + } + }; + const setText = (id, value) => { + const node = element(id); + if (node) node.textContent = value ?? ""; + }; + const formatDate = (value, formatter = dateTimeFormat) => { + if (!value) return "—"; + const date = new Date(value); + if (Number.isNaN(date.getTime())) return String(value); + try { + return formatter?.format(date) ?? date.toISOString(); + } catch { + return date.toISOString(); + } + }; + const formatCount = (count) => + Number(count) === 1 ? text.modelCountOne : fill(text.modelsCount, { + count: formatNumber(Number(count) || 0), + }); + const formatEnabled = (value) => value ? text.enabled : text.disabled; + const formatYesNo = (value) => value ? text.yes : text.no; + const modelSource = (value) => ({ + live: text.live, + cached: text.cached, + "built-in": text.builtIn, + }[value] || value || text.unknown); + const versionSource = (value) => ({ + manifest: text.manifest, + fallback: text.fallback, + }[value] || value || text.unknown); + const loginSource = (value) => ({ + browser: text.loginBrowser, + "atomcode-cli": text.loginCli, + }[value] || value || text.unknown); + + function setStatus(message, tone = "info") { + element("status-text").textContent = message; + element("status").dataset.tone = tone; + } + + function setHealth(tone, title, summary) { + element("overview").dataset.tone = tone; + setText("health-title", title); + setText("health-summary", summary); + } + + function setBusy(id, busy) { + const button = element(id); + button.disabled = busy; + if (busy) button.dataset.busy = "true"; + else delete button.dataset.busy; + } + + for (const node of document.querySelectorAll("[data-i18n]")) { + const value = text[node.dataset.i18n]; + if (value) node.textContent = value; + } + document.documentElement.lang = locale; + document.title = locale === "zh" ? "AtomCode 诊断" : "AtomCode diagnostics"; + + const theme = query.get("theme"); + if (theme === "dark" || theme === "light") { + document.documentElement.dataset.theme = theme; + } + const allowedTokens = new Set([ + "bg", + "card", + "fg", + "fg-2", + "muted", + "faint", + "line", + "accent", + "accent-soft", + "accent-fg", + "green", + "red", + "amber", + "font", + "code", + ]); + try { + const raw = query.get("tokens"); + const tokens = raw + ? JSON.parse(new TextDecoder().decode( + Uint8Array.from(atob(raw), (character) => character.charCodeAt(0)), + )) + : {}; + for (const [key, value] of Object.entries(tokens)) { + if ( + allowedTokens.has(key) && + typeof value === "string" && + value.length < 300 && + !/url\s*\(/i.test(value) + ) { + document.documentElement.style.setProperty("--" + key, value); + } + } + } catch {} + + let snapshot; + let localSelfCheck; + let copyTimer; + + async function api(path, init = {}) { + const response = await fetch(path, { + ...init, + headers: { "x-atomcode-token": token, ...(init.headers || {}) }, + cache: "no-store", + }); + if (!response.ok) throw new Error("HTTP " + response.status); + return response.json(); + } + + function renderWindows(windows, generatedAt) { + const list = element("windows"); + clear(list); + const baseTime = Date.parse(generatedAt) || Date.now(); + for (const window of windows || []) { + const item = document.createElement("li"); + item.className = "window"; + const percent = Number(window.used); + const normalized = Number.isFinite(percent) + ? Math.max(0, Math.min(100, percent)) + : undefined; + if (normalized !== undefined && normalized >= 90) item.dataset.level = "danger"; + else if (normalized !== undefined && normalized >= 70) item.dataset.level = "warn"; + + const head = document.createElement("div"); + head.className = "window-head"; + const name = document.createElement("strong"); + name.textContent = window.name || text.unknown; + const usage = document.createElement("span"); + usage.textContent = normalized === undefined + ? text.quotaUnknown + : fill(text.usedPercent, { + used: formatNumber(normalized), + }); + head.append(name, usage); + + const progress = document.createElement("div"); + progress.className = "progress"; + progress.setAttribute("role", "progressbar"); + progress.setAttribute( + "aria-label", + fill(text.quotaWindowLabel, { name: window.name || text.unknown }), + ); + progress.setAttribute("aria-valuemin", "0"); + progress.setAttribute("aria-valuemax", "100"); + const progressFill = document.createElement("span"); + progressFill.className = "progress-fill"; + if (normalized === undefined) { + progress.setAttribute("aria-valuetext", window.display || text.quotaUnknown); + } else { + progress.setAttribute("aria-valuenow", String(Math.round(normalized))); + progressFill.style.transform = "scaleX(" + normalized / 100 + ")"; + } + progress.append(progressFill); + + const meta = document.createElement("div"); + meta.className = "window-meta"; + const display = document.createElement("span"); + display.textContent = window.display || + (normalized === undefined ? text.quotaUnknown : usage.textContent); + const reset = document.createElement("span"); + const resetSecs = Number(window.resetSecs); + const resetAt = Number.isFinite(resetSecs) + ? baseTime + resetSecs * 1000 + : Date.parse(window.resetsAt); + if (Number.isFinite(resetAt)) { + reset.dataset.resetAt = String(resetAt); + reset.textContent = formatReset(resetAt); + } else { + reset.textContent = text.resetUnknown; + } + meta.append(display, reset); + item.append(head, progress, meta); + list.append(item); + } + element("quota-empty").hidden = Boolean(windows?.length); + updateCountdowns(); + } + + function formatReset(target) { + const remaining = target - Date.now(); + if (remaining <= 0) return text.resetNow; + const seconds = Math.max(1, Math.ceil(remaining / 1000)); + if (seconds < 90) { + return fill(text.seconds, { value: formatNumber(seconds) }); + } + if (seconds < 90 * 60) { + const value = Math.ceil(seconds / 60); + return relativeTimeFormat?.format(value, "minute") ?? + fill(text.minutes, { value: formatNumber(value) }); + } + if (seconds < 36 * 60 * 60) { + const value = Math.ceil(seconds / 3600); + return relativeTimeFormat?.format(value, "hour") ?? + fill(text.hours, { value: formatNumber(value) }); + } + const value = Math.ceil(seconds / 86400); + return relativeTimeFormat?.format(value, "day") ?? + fill(text.days, { value: formatNumber(value) }); + } + + function updateCountdowns() { + for (const node of document.querySelectorAll("[data-reset-at]")) { + const target = Number(node.dataset.resetAt); + if (Number.isFinite(target)) node.textContent = formatReset(target); + } + } + + function renderModels(models) { + const names = Array.isArray(models?.names) ? models.names : []; + const list = element("models"); + clear(list); + for (const name of names) { + const item = document.createElement("li"); + const code = document.createElement("code"); + code.textContent = name; + item.append(code); + list.append(item); + } + const hasNames = names.length > 0; + list.hidden = !hasNames; + element("models-empty").hidden = hasNames || Boolean(models?.count); + setText( + "model-count", + models?.count ? formatCount(models.count) : "", + ); + if (!hasNames && models?.count) { + element("models-empty").textContent = text.namesUnavailable; + element("models-empty").hidden = false; + } else if (!hasNames) { + element("models-empty").textContent = text.noModels; + } + } + + function renderSelfCheck(check) { + const block = element("self-check-result"); + const checks = element("self-check-checks"); + clear(checks); + if (!check) { + block.dataset.tone = "idle"; + setText("self-check-state", text.notRun); + setText("self-check-detail", text.checkHint); + return; + } + block.dataset.tone = check.ok ? "good" : "error"; + setText("self-check-state", check.ok ? text.checkOk : text.checkFailed); + setText( + "self-check-detail", + fill(text.checkedAt, { + time: formatDate(check.at), + ms: formatNumber(Number(check.ms) || 0), + }), + ); + const labels = { + signature: text.checkSignature, + version: text.checkVersion, + configuration: text.checkConfiguration, + }; + for (const [key, label] of Object.entries(labels)) { + if (typeof check.checks?.[key] !== "boolean") continue; + const item = document.createElement("li"); + item.dataset.tone = check.checks[key] ? "good" : "error"; + item.textContent = label + ": " + (check.checks[key] ? text.pass : text.fail); + checks.append(item); + } + } + + function renderLastError(error) { + const block = element("last-error-card"); + const time = element("last-error-time"); + time.textContent = ""; + time.removeAttribute("datetime"); + if (!error) { + block.dataset.tone = "idle"; + setText("last-error-title", text.noError); + setText("last-error-message", text.noErrorHint); + return; + } + block.dataset.tone = "error"; + setText( + "last-error-title", + [error.category || text.unknown, error.status ? "HTTP " + error.status : ""] + .filter(Boolean).join(" · "), + ); + setText("last-error-message", error.message || text.unknown); + if (error.at) { + time.dateTime = String(error.at); + time.textContent = formatDate(error.at); + } + } + + function updateHealth(data) { + const selfCheck = data?.selfCheck || localSelfCheck; + if (selfCheck && selfCheck.ok === false) { + setHealth("error", text.checkFailedTitle, text.checkFailedSummary); + return; + } + if (data?.lastError) { + setHealth("warn", text.recentErrorTitle, text.recentErrorSummary); + return; + } + if (!data?.account) { + setHealth("warn", text.noAccountTitle, text.noAccountSummary); + return; + } + setHealth("good", text.localReadyTitle, text.localReadySummary); + } + + function render(data) { + snapshot = data; + document.body.dataset.state = "ready"; + updateHealth(data); + + const account = data.account; + const models = data.models || {}; + const quota = data.quota; + const version = data.version || {}; + setText("summary-account", account ? text.connected : text.notConnected); + setText( + "summary-models", + models.count ? formatCount(models.count) : "—", + ); + setText("summary-version", version.version || "—"); + setText( + "summary-snapshot", + data.generatedAt ? formatDate(data.generatedAt, shortTimeFormat) : "—", + ); + + setText("model-source", modelSource(models.source)); + setText( + "model-detail", + [ + formatCount(models.count || 0), + models.updatedAt + ? fill(text.updatedAt, { time: formatDate(models.updatedAt) }) + : "", + ].filter(Boolean).join(" · "), + ); + setText("account-state", account ? text.connected : text.notConnected); + setText("login-source", account ? loginSource(account.loginSource) : text.unknown); + setText("version", version.version || "—"); + setText( + "version-detail", + [ + versionSource(version.source), + version.checkedAt + ? fill(text.checkedAtShort, { time: formatDate(version.checkedAt) }) + : "", + ].filter(Boolean).join(" · "), + ); + + setText("quota-plan", quota?.plan || "—"); + setText( + "quota-captured", + quota?.capturedAt + ? fill(text.capturedAt, { time: formatDate(quota.capturedAt) }) + : text.noQuota, + ); + element("stale-badge").hidden = !quota; + setText("stale-badge", text.stale); + renderWindows(quota?.windows || [], data.generatedAt); + renderModels(models); + renderSelfCheck(data.selfCheck || localSelfCheck); + renderLastError(data.lastError); + + setText("tech-generated", formatDate(data.generatedAt)); + setText("tech-runtime", data.runtime?.node ? "Node " + data.runtime.node : "—"); + setText("tech-platform", data.runtime?.platform || "—"); + setText("tech-schema", data.schemaVersion ?? "—"); + setText("tech-port", data.config?.diagnosticsPort ?? "—"); + setText("tech-model-source", modelSource(models.source)); + setText("tech-version-source", versionSource(version.source)); + setText( + "tech-auto-claim", + data.config?.autoClaim === undefined ? "—" : formatEnabled(data.config.autoClaim), + ); + setText( + "tech-auto-version", + data.config?.autoVersion === undefined ? "—" : formatEnabled(data.config.autoVersion), + ); + setText( + "tech-read-only", + data.config?.readOnly === undefined ? "—" : formatYesNo(data.config.readOnly), + ); + element("copy").disabled = false; + } + + async function refresh({ announce = true } = {}) { + setBusy("refresh", true); + if (!snapshot) { + document.body.dataset.state = "loading"; + setHealth("loading", text.healthLoading, text.localOnly); + } + if (announce) setStatus(text.refreshing, "loading"); + try { + render(await api("api/state")); + if (announce) setStatus(text.ready, "ok"); + } catch (error) { + if (snapshot) { + document.body.dataset.state = "ready"; + setHealth( + "warn", + text.refreshFailedTitle, + text.refreshFailedSummary + " " + readableError(error), + ); + } else { + document.body.dataset.state = "error"; + setHealth( + "error", + text.loadFailedTitle, + text.loadFailedSummary + " " + readableError(error), + ); + } + setStatus(text.failed, "error"); + } finally { + setBusy("refresh", false); + } + } + + async function selfCheck() { + setBusy("self-check", true); + setBusy("refresh", true); + setStatus(text.checking, "loading"); + try { + const result = await api("api/self-check", { method: "POST" }); + localSelfCheck = result; + renderSelfCheck(result); + await refresh({ announce: false }); + setStatus( + result.ok ? text.checkPassedChip : text.checkFailedChip, + result.ok ? "ok" : "error", + ); + } catch (error) { + setHealth("error", text.checkFailedTitle, text.checkFailedSummary); + setText("self-check-state", text.checkFailed); + setText("self-check-detail", readableError(error)); + setStatus(text.failed, "error"); + } finally { + setBusy("self-check", false); + setBusy("refresh", false); + } + } + + function reportFor(data) { + const lines = ["# " + text.reportTitle, ""]; + lines.push("- " + text.generated + ": " + formatDate(data.generatedAt)); + lines.push("- " + text.account + ": " + (data.account ? text.connected : text.notConnected)); + if (data.account) { + lines.push("- " + text.loginMethod + ": " + loginSource(data.account.loginSource)); + } + const models = data.models || {}; + lines.push( + "- " + text.models + ": " + formatCount(models.count || 0) + + " · " + modelSource(models.source), + ); + for (const name of models.names || []) { + lines.push(" - `" + String(name).split("`").join("\\`") + "`"); + } + if (data.quota) { + lines.push("- " + text.plan + ": " + (data.quota.plan || text.unknown)); + lines.push("- " + text.captured + ": " + formatDate(data.quota.capturedAt)); + for (const window of data.quota.windows || []) { + const pieces = [window.name || text.unknown]; + if (window.display) pieces.push(window.display); + else if (Number.isFinite(Number(window.used))) { + pieces.push(fill(text.usedPercent, { used: formatNumber(Number(window.used)) })); + } + if (Number.isFinite(Number(window.resetSecs))) { + pieces.push(formatReset(Date.now() + Number(window.resetSecs) * 1000)); + } + lines.push(" - " + text.reportQuotaWindow + ": " + pieces.join(" · ")); + } + } else { + lines.push("- " + text.quotaTitle + ": " + text.noQuota); + } + lines.push( + "- " + text.version + ": " + (data.version?.version || text.unknown) + + " · " + versionSource(data.version?.source), + ); + if (data.selfCheck) { + lines.push( + "- " + text.reportSelfCheck + ": " + + (data.selfCheck.ok ? text.checkOk : text.checkFailed) + + " · " + formatDate(data.selfCheck.at), + ); + } else { + lines.push("- " + text.reportSelfCheck + ": " + text.notRun); + } + if (data.lastError) { + lines.push( + "- " + text.reportLastError + ": " + + [ + data.lastError.category || text.unknown, + data.lastError.status ? "HTTP " + data.lastError.status : "", + data.lastError.message || text.unknown, + formatDate(data.lastError.at), + ].filter(Boolean).join(" · "), + ); + } else { + lines.push("- " + text.reportLastError + ": " + text.noError); + } + if (data.runtime) { + lines.push( + "- " + text.reportRuntime + ": " + + [data.runtime.node ? "Node " + data.runtime.node : "", data.runtime.platform || ""] + .filter(Boolean).join(" · "), + ); + } + return lines.join("\n"); + } + + async function writeClipboard(value) { + if (navigator.clipboard?.writeText) { + try { + await navigator.clipboard.writeText(value); + return; + } catch {} + } + const area = document.createElement("textarea"); + area.value = value; + area.className = "copy-buffer"; + area.setAttribute("readonly", ""); + document.body.append(area); + area.select(); + const copied = document.execCommand("copy"); + area.remove(); + if (!copied) throw new Error("copy failed"); + } + + async function copyReport() { + if (!snapshot) { + setStatus(text.noSnapshot, "info"); + return; + } + try { + await writeClipboard(reportFor(snapshot)); + setStatus(text.copied, "ok"); + setText("copy-label", text.copied); + clearTimeout(copyTimer); + copyTimer = setTimeout(() => setText("copy-label", text.copy), 1600); + } catch { + setStatus(text.copyFailed, "error"); + } + } + + function readableError(error) { + const message = error instanceof Error ? error.message : String(error ?? ""); + return message.replace(/\s+/g, " ").trim().slice(0, 240); + } + + function failStartup(error) { + const detail = readableError(error) || text.unknown; + document.body.dataset.app = "error"; + document.body.dataset.state = "error"; + setHealth("error", text.startupFailedTitle, text.startupFailedSummary); + setStatus(text.startupFailedStatus, "error"); + setText("summary-account", text.unknown); + setText("summary-models", text.unknown); + setText("summary-version", text.unknown); + setText("summary-snapshot", "—"); + element("last-error-card").dataset.tone = "error"; + setText("last-error-title", text.startupFailedTitle); + setText("last-error-message", detail); + try { + console.error("AtomCode diagnostics failed to initialize", error); + } catch {} + } + + function initialize() { + element("refresh").addEventListener("click", () => refresh()); + element("self-check").addEventListener("click", selfCheck); + element("copy").addEventListener("click", copyReport); + element("copy").disabled = true; + renderSelfCheck(); + renderLastError(); + setInterval(updateCountdowns, 30_000); + refresh(); + } + + try { + initialize(); + } catch (error) { + failStartup(error); + } +})(); diff --git a/packages/atomcode/page/boot.js b/packages/atomcode/page/boot.js new file mode 100644 index 0000000..bb3cd77 --- /dev/null +++ b/packages/atomcode/page/boot.js @@ -0,0 +1,60 @@ +// Magpie settings pages cannot fetch (`connect-src 'none'`). This bridge page +// therefore only carries theme/options to the loopback diagnostics page. +(async () => { + const fallbackPort = 3478; + const said = document.getElementById("said"); + let port = fallbackPort; + let theme = ""; + let lang = ""; + let tokens = null; + let service = ""; + + try { + const ready = await window.magpie?.ready; + if (typeof ready?.dark === "boolean") theme = ready.dark ? "dark" : "light"; + if (typeof ready?.lang === "string") lang = ready.lang; + if (ready?.tokens && typeof ready.tokens === "object") tokens = ready.tokens; + } catch {} + try { + if (typeof window.magpie?.service === "string") service = window.magpie.service; + } catch {} + try { + const options = await window.magpie?.options?.get?.(); + const configured = Number(options?.diagnosticsPort); + if (Number.isInteger(configured) && configured >= 1024 && configured <= 65535) { + port = configured; + } + } catch {} + + const query = new URLSearchParams(); + if (theme) query.set("theme", theme); + if (lang) query.set("lang", lang); + const slim = {}; + for (const [key, value] of Object.entries(tokens || {})) { + const text = String(value ?? "").trim(); + if (text) slim[key] = text; + } + if (Object.keys(slim).length) { + try { + query.set("tokens", btoa(unescape(encodeURIComponent(JSON.stringify(slim))))); + } catch {} + } + + const suffix = query.toString(); + if (service) { + location.replace(service + (suffix ? "?" + suffix : "")); + return; + } + + const target = "http://127.0.0.1:" + port + "/" + (suffix ? "?" + suffix : ""); + const loopback = /^(?:127(?:\.\d+){3}|localhost|\[::1\])$/i.test(location.hostname); + if (!loopback && location.protocol !== "file:") { + if (said) { + said.textContent = + "诊断服务只监听运行 magpie 的电脑。请在这台电脑上使用 SSH 端口转发:" + + "ssh -N -L " + port + ":127.0.0.1:" + port + " @" + location.hostname; + } + return; + } + location.replace(target); +})(); diff --git a/packages/atomcode/page/diagnostics.html b/packages/atomcode/page/diagnostics.html new file mode 100644 index 0000000..8f67ca8 --- /dev/null +++ b/packages/atomcode/page/diagnostics.html @@ -0,0 +1,262 @@ + + + + + + + AtomCode diagnostics + + + + +
+
+
+ + + +
+

LOCAL DIAGNOSTICS

+

+ AtomCode + + Diagnostics +

+
+
+ +
+
+ + Loading local snapshot… +
+ + +
+
+ +
+
+ +
+

LOCAL STATUS

+

Loading local snapshot

+

+ This view reads local state only. It does not test the AtomCode upstream. +

+
+
+
+
+ Account + — +
+
+ Models + — +
+
+ Version + — +
+
+ Last refresh + — +
+
+
+ +
+
+
+
+

QUOTA WINDOWS

+

Current quota snapshot

+
+ +
+ +
+
+ Plan + — +
+
+ Captured + — +
+
+ +
    +

    + No successful quota snapshot has been recorded yet. +

    +
    + +
    +
    +
    +

    PROVIDER STATE

    +

    Catalog and account

    +
    +
    + +
    +
    +
    Models
    +
    + — + +
    +
    +
    +
    Account
    +
    + — + +
    +
    +
    +
    Version
    +
    + — + +
    +
    +
    + +
    +
    +

    Model catalog

    + +
    +
      + +
      +
      +
      + +
      +
      +
      +
      +

      OFFLINE SELF-CHECK

      +

      Signature and configuration

      +
      +
      +
      + +
      + Not run in this session +

      + Run the check to verify signing and the local version configuration. +

      +
      +
      +
        +
        + +
        +
        +
        +

        LAST ERROR

        +

        Redacted record

        +
        +
        +
        + +
        + No recorded error +

        + This only reflects the last locally recorded failure. +

        + +
        +
        +
        +
        + +
        + + + TECHNICAL DETAILS + Runtime and snapshot metadata + + + +
        +
        +
        Generated
        +
        —
        +
        +
        +
        Runtime
        +
        —
        +
        +
        +
        Platform
        +
        —
        +
        +
        +
        State schema
        +
        —
        +
        +
        +
        Diagnostics port
        +
        —
        +
        +
        +
        Model source
        +
        —
        +
        +
        +
        Version source
        +
        —
        +
        +
        +
        Auto claim
        +
        —
        +
        +
        +
        Auto version
        +
        —
        +
        +
        +
        Read only
        +
        —
        +
        +
        +
        + +
        +

        + Read-only. No request is sent to AtomGit from this page. Tokens, emails, prompts and raw responses are never included. +

        + +
        +
        + + + diff --git a/packages/atomcode/page/icon.svg b/packages/atomcode/page/icon.svg new file mode 100644 index 0000000..aa9c375 --- /dev/null +++ b/packages/atomcode/page/icon.svg @@ -0,0 +1,11 @@ + + + + + + + + + + + diff --git a/packages/atomcode/page/index.html b/packages/atomcode/page/index.html new file mode 100644 index 0000000..168cce1 --- /dev/null +++ b/packages/atomcode/page/index.html @@ -0,0 +1,51 @@ + + + + + + AtomCode 诊断 + + + +
        + +

        AtomCode 诊断

        +

        正在连接本机只读诊断服务…

        +
        + + + + diff --git a/packages/atomcode/quota.mjs b/packages/atomcode/quota.mjs new file mode 100644 index 0000000..d3806d1 --- /dev/null +++ b/packages/atomcode/quota.mjs @@ -0,0 +1,226 @@ +/** + * CodingPlan status → Magpie `auth.usage` mapping. + * + * The plan's own fields supply `plan` (套餐名) and `until` (到期时间); every + * `rate_limit_windows` row is mapped so additional windows from upstream are + * not silently discarded. `auth.usage` percentages may legitimately exceed 100 + * when the quota is exhausted — Magpie renders that natively. + * + * Mapping is a pure function so the shape contract can be tested offline + * against the real response captured in the plan document (§5.4). + * + * @module magpie-atomcode/quota + */ + +import { planOf } from "./codingplan.mjs"; +import { fill } from "./i18n.mjs"; +import { atomInstantISO } from "./internal.mjs"; + +/** Number if finite (0 included), else undefined. */ +export function num(v) { + if (v === null || v === undefined || v === "") return undefined; + const n = Number(v); + return Number.isFinite(n) ? n : undefined; +} + +/** Used-percentage fallback when the API does not hand one over. */ +function pctOf(used, limit) { + const count = num(used); + const total = num(limit); + if (count === undefined || !total) return undefined; + return (count / total) * 100; +} + +function resetOf(raw, fallback) { + const secs = num(raw?.seconds_until_reset); + if (secs !== undefined) return { resetSecs: secs }; + const resetsAt = atomInstantISO(raw?.reset_at ?? fallback?.reset_at); + return resetsAt ? { resetsAt } : {}; +} + +function tokenWindow(usage, hours, reset, t) { + const amount = num(usage.window_tokens_used ?? usage.tokens_used); + const limit = num(usage.window_token_limit ?? usage.token_limit); + if (amount === undefined || !limit) return undefined; + const used = num(usage.token_usage_percent) ?? pctOf(amount, limit); + return { + name: fill(t.windowTokens, { hours }), + ...(used !== undefined ? { used } : {}), + span: hours * 3600, + amount, + unit: "tokens", + limit, + display: fill(t.tokensOf, { used: amount, total: limit }), + ...reset, + }; +} + +function tokenValues(raw) { + return { + amount: num( + raw?.window_tokens_used ?? + raw?.tokens_used ?? + raw?.token_count_used ?? + raw?.tokens ?? + raw?.used_tokens, + ), + limit: num( + raw?.window_token_limit ?? + raw?.token_limit ?? + raw?.token_count_limit ?? + raw?.tokens_limit ?? + raw?.limit_tokens, + ), + used: num(raw?.token_usage_percent ?? raw?.tokens_usage_percent), + }; +} + +function callValues(raw) { + return { + amount: num(raw?.calls_used ?? raw?.requests_used ?? raw?.request_count_used), + limit: num(raw?.call_limit ?? raw?.requests_limit ?? raw?.request_count_limit), + used: num(raw?.call_usage_percent ?? raw?.requests_usage_percent), + }; +} + +function rawUnit(raw) { + const value = String(raw?.unit ?? raw?.quota_unit ?? raw?.limit_type ?? raw?.resource ?? "") + .toLowerCase(); + if (/token|词元/.test(value)) return "tokens"; + if (/call|request|次/.test(value)) return "calls"; + return undefined; +} + +function spanOf(raw) { + const span = num(raw?.window_size_seconds) ?? (num(raw?.window_hours) ?? 5) * 3600; + const hours = num(raw?.window_hours) ?? Math.max(1, Math.round(span / 3600)); + return { span, hours }; +} + +function rawTokenWindow(raw, t, usage) { + const { amount, limit, used: declaredUsed } = tokenValues(raw); + if (amount === undefined && limit === undefined && declaredUsed === undefined) return undefined; + const { span, hours } = spanOf(raw); + const used = declaredUsed ?? pctOf(amount, limit); + return { + name: fill(t.windowTokens, { hours }), + ...(used !== undefined ? { used } : {}), + span, + ...(amount !== undefined ? { amount } : {}), + unit: "tokens", + ...(limit ? { limit } : {}), + ...(limit && amount !== undefined + ? { display: fill(t.tokensOf, { used: amount, total: limit }) } + : {}), + ...resetOf(raw, usage), + }; +} + +function rawCallWindow(raw, t, usage) { + const { amount, limit, used: declaredUsed } = callValues(raw); + const { span, hours } = spanOf(raw); + const used = declaredUsed ?? num(raw?.usage_percent) ?? pctOf(amount, limit); + return { + name: fill(t.windowHours, { hours }), + ...(used !== undefined ? { used } : {}), + span, + ...(amount !== undefined ? { amount } : {}), + unit: "calls", + ...(limit ? { limit } : {}), + ...(limit && amount !== undefined + ? { display: fill(t.callsOf, { used: amount, total: limit }) } + : {}), + ...resetOf(raw, usage), + }; +} + +function hasAnyValue(...values) { + return values.some((value) => value !== undefined); +} + +/** + * Build the `auth.usage` payload from a `status-v2` response. + * + * @param {object} status - parsed `status-v2`. + * @param {object} t - the i18n table for labels. + * @param {{user?: string}} [context] - the account's display name for the row. + * @returns {{plan?: string, user?: string, until?: string, windows: object[]}} + */ +export function quotaFromStatus(status, t, { user } = {}) { + const plan = planOf(status) ?? {}; + const usage = status?.current_usage ?? {}; + const windows = []; + + const rawWindows = Array.isArray(status?.rate_limit_windows) + ? status.rate_limit_windows.filter((w) => w && typeof w === "object") + : []; + const seen = new Set(); + const addWindow = (window) => { + seen.add(`${window.unit}:${window.span}`); + windows.push(window); + }; + for (const raw of rawWindows) { + const unit = rawUnit(raw); + const tokens = tokenValues(raw); + const calls = callValues(raw); + const hasCallFields = hasAnyValue(calls.amount, calls.limit, calls.used); + const hasTokenFields = hasAnyValue(tokens.amount, tokens.limit, tokens.used); + const hasToken = + unit === "tokens" || + (unit === undefined && !hasCallFields && hasTokenFields); + const hasCall = !hasToken; + if (hasToken) { + const window = rawTokenWindow(raw, t, usage); + const { span, hours } = spanOf(raw); + addWindow(window ?? { + name: fill(t.windowTokens, { hours }), + span, + unit: "tokens", + ...resetOf(raw, usage), + }); + } + if (hasCall) { + addWindow(rawCallWindow(raw, t, usage)); + } + } + const currentHours = num(usage.window_hours) ?? 5; + const currentSpan = currentHours * 3600; + const currentUnit = rawUnit(usage); + const currentToken = + currentUnit === "tokens" + ? tokenWindow(usage, currentHours, resetOf(usage), t) ?? { + name: fill(t.windowTokens, { hours: currentHours }), + span: currentSpan, + unit: "tokens", + ...resetOf(usage), + } + : undefined; + if ( + currentUnit !== "tokens" && + !seen.has(`calls:${currentSpan}`) && + (num(usage.usage_percent) !== undefined || + num(usage.window_hours) !== undefined) + ) { + // No window row (older shape?): fall back to the current_usage block. + const used = num(usage.usage_percent); + addWindow({ + name: fill(t.windowHours, { hours: currentHours }), + ...(used !== undefined ? { used } : {}), + span: currentSpan, + unit: "calls", + ...resetOf(usage), + }); + } + if (currentToken && !seen.has(`tokens:${currentToken.span}`)) { + addWindow(currentToken); + } + + return { + ...(plan.plan_name ? { plan: plan.plan_name } : { plan: t.planFallback }), + ...(user ? { user } : {}), + ...(plan.expires_at + ? { until: atomInstantISO(plan.expires_at) ?? String(plan.expires_at) } + : {}), + windows, + }; +} diff --git a/packages/atomcode/request-body.mjs b/packages/atomcode/request-body.mjs new file mode 100644 index 0000000..4916970 --- /dev/null +++ b/packages/atomcode/request-body.mjs @@ -0,0 +1,147 @@ +/** + * Request body normalization for signed gateway traffic. + * + * Signing needs the exact bytes that will be sent, so bodies must be replayable. + * Web streams, FormData and URLSearchParams have no stable byte representation + * here; rejecting them is safer than signing one representation and sending + * another. The cap prevents a Request clone from consuming unbounded memory. + * + * @module magpie-atomcode/request-body + */ + +export const MAX_SIGNED_BODY_BYTES = 64 * 1024 * 1024; + +function tooLarge(maxBytes) { + return new Error(`request body exceeds ${maxBytes} bytes`); +} + +async function readStream(stream, maxBytes) { + if (!stream || typeof stream.getReader !== "function") { + throw new Error("unsupported request body"); + } + const reader = stream.getReader(); + const chunks = []; + let total = 0; + try { + for (;;) { + const { done, value } = await reader.read(); + if (done) break; + const chunk = + value instanceof Uint8Array + ? value + : ArrayBuffer.isView(value) + ? new Uint8Array(value.buffer, value.byteOffset, value.byteLength) + : new Uint8Array(value); + total += chunk.byteLength; + if (total > maxBytes) { + void reader.cancel().catch(() => {}); + throw tooLarge(maxBytes); + } + chunks.push(chunk); + } + } finally { + try { + reader.releaseLock(); + } catch { + /* cancel() may have released it already */ + } + } + const combined = new Uint8Array(total); + let offset = 0; + for (const chunk of chunks) { + combined.set(chunk, offset); + offset += chunk.byteLength; + } + return combined; +} + +/** + * Convert a supported BodyInit into replayable bytes or a string. + * + * @param {unknown} body - `init.body`, when present. + * @param {{request?: Request, fromRequest?: boolean, maxBytes?: number}} [opts] + * @returns {Promise<{body: string|Uint8Array|undefined, contentType?: string, signBody: string|Uint8Array}>} + */ +export async function normalizeRequestBody( + body, + { request, fromRequest = false, maxBytes = MAX_SIGNED_BODY_BYTES } = {}, +) { + if (fromRequest) { + if (!request?.body) return { body: undefined, signBody: "" }; + const bytes = await readStream(request.clone().body, maxBytes); + return { body: bytes, signBody: bytes }; + } + if (body === undefined || body === null) return { body: undefined, signBody: "" }; + if (typeof body === "string") { + if (Buffer.byteLength(body, "utf8") > maxBytes) throw tooLarge(maxBytes); + return { body, signBody: body }; + } + if (Buffer.isBuffer(body)) { + if (body.byteLength > maxBytes) throw tooLarge(maxBytes); + const bytes = new Uint8Array(body.buffer, body.byteOffset, body.byteLength); + return { body: bytes, signBody: bytes }; + } + if (body instanceof ArrayBuffer) { + if (body.byteLength > maxBytes) throw tooLarge(maxBytes); + const bytes = new Uint8Array(body); + return { body: bytes, signBody: bytes }; + } + if (ArrayBuffer.isView(body)) { + if (body.byteLength > maxBytes) throw tooLarge(maxBytes); + const bytes = new Uint8Array(body.buffer, body.byteOffset, body.byteLength); + return { body: bytes, signBody: bytes }; + } + if (typeof Blob !== "undefined" && body instanceof Blob) { + if (body.size > maxBytes) throw tooLarge(maxBytes); + const bytes = new Uint8Array(await body.arrayBuffer()); + return { + body: bytes, + signBody: bytes, + ...(body.type ? { contentType: body.type } : {}), + }; + } + throw new Error("unsupported request body"); +} + +/** + * Ask OpenAI-compatible streaming Chat Completions for final usage. + * + * An explicit `include_usage` value is never overridden. + * + * @param {string|Uint8Array} body + * @param {{pathname?: string, contentType?: string}} [opts] + * @returns {{body: string|Uint8Array, changed: boolean}} + */ +export function includeStreamUsage(body, { pathname = "", contentType = "" } = {}) { + if (!pathname.endsWith("/chat/completions")) return { body, changed: false }; + if (contentType && !/^application\/(?:[^;]+\+)?json\b/i.test(contentType)) { + return { body, changed: false }; + } + let text; + try { + text = typeof body === "string" ? body : new TextDecoder().decode(body); + } catch { + return { body, changed: false }; + } + let value; + try { + value = JSON.parse(text); + } catch { + return { body, changed: false }; + } + if (!value || typeof value !== "object" || value.stream !== true) { + return { body, changed: false }; + } + if ( + Object.hasOwn(value, "stream_options") && + (!value.stream_options || + typeof value.stream_options !== "object" || + Array.isArray(value.stream_options)) + ) { + return { body, changed: false }; + } + const options = value.stream_options ?? {}; + if (Object.hasOwn(options, "include_usage")) return { body, changed: false }; + value.stream_options = { ...options, include_usage: true }; + return { body: JSON.stringify(value), changed: true }; +} diff --git a/packages/atomcode/scripts/live-smoke.mjs b/packages/atomcode/scripts/live-smoke.mjs new file mode 100644 index 0000000..c0e689d --- /dev/null +++ b/packages/atomcode/scripts/live-smoke.mjs @@ -0,0 +1,98 @@ +#!/usr/bin/env node + +import { AtomCodePlugin } from "../index.mjs"; +import { + defaultAuthFilePath, + readAuthFile, +} from "../auth-file.mjs"; +import { redactText } from "../internal.mjs"; + +const MAX_REQUESTS = 9; + +if (process.env.ATOMCODE_LIVE !== "1") { + console.error("Refusing live calls. Set ATOMCODE_LIVE=1 and run again."); + process.exit(2); +} + +const realFetch = globalThis.fetch; +let requestCount = 0; +globalThis.fetch = (...args) => { + requestCount += 1; + if (requestCount > MAX_REQUESTS) { + throw new Error(`live smoke exceeded its ${MAX_REQUESTS}-request budget`); + } + return realFetch(...args); +}; + +const client = { + auth: { + set: async () => {}, + }, + app: { + log: () => {}, + }, +}; + +try { + const auth = await readAuthFile(defaultAuthFilePath()); + const getAuth = async () => auth; + const plugin = await AtomCodePlugin( + { client }, + { + autoClaim: false, + autoVersion: false, + locale: "en", + }, + ); + + const models = await plugin.provider.models({}, { auth }); + const modelEntries = Object.values(models).filter( + (model) => model && typeof model === "object" && model.api?.id, + ); + if (!modelEntries.length) throw new Error("live model catalog was empty"); + + const usage = await plugin.auth.usage(getAuth); + if (usage.signIn === "expired") throw new Error("live sign-in expired"); + + const { fetch: patched } = await plugin.auth.loader(getAuth); + const chatResults = []; + for (const model of modelEntries.slice(0, 3)) { + const response = await patched("https://llm-api.atomgit.com/v1/chat/completions", { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ + model: model.api.id, + stream: true, + max_tokens: 16, + messages: [{ role: "user", content: "Reply with OK." }], + }), + signal: AbortSignal.timeout(60_000), + }); + if (!response.ok) throw new Error(`live chat returned HTTP ${response.status}`); + const stream = await response.text(); + chatResults.push({ + model: model.name, + sawUsage: /"usage"\s*:/.test(stream), + sawDone: /\[DONE\]/.test(stream), + }); + } + + console.log( + JSON.stringify( + { + ok: true, + requests: requestCount, + models: modelEntries.map((model) => model.name), + quotaWindows: usage.windows?.length ?? 0, + chat: chatResults, + }, + null, + 2, + ), + ); +} catch (error) { + console.error(`live smoke failed: ${redactText(error?.message ?? error)}`); + process.exitCode = 1; +} finally { + globalThis.fetch = realFetch; +} diff --git a/packages/atomcode/sign.mjs b/packages/atomcode/sign.mjs new file mode 100644 index 0000000..e5dbde7 --- /dev/null +++ b/packages/atomcode/sign.mjs @@ -0,0 +1,120 @@ +/** + * `atomcode-signing-v1` — the request signature the AtomGit LLM gateway + * requires (`X-AtomCode-*` headers). + * + * Port of the community-documented implementation (Atom2Api, MIT). Two facts + * this code must not drift from: + * + * - the salt is `uid bytes || 0x01 || le64(hour-bucket) || sha256(oauth_token) + * || sha256(client_version)`, and HKDF's info is the bare string + * `"atomcode-signing-v1"` (no trailing 0x01), 32 bytes out; + * - the canonical is `v1\nMETHOD\nPATH\nTS\nNONCE-hex\nsha256(body)-hex`, + * where PATH is the full request path with its `/v1` prefix. + * + * `test/sign.test.mjs` holds Atom2Api's independent fixture as the guard. + * + * The signature always covers the bytes actually sent: patch the body first, + * sign second. Nothing here reads the network or the clock silently — both are + * parameters for tests. + * + * @module magpie-atomcode/sign + */ + +import { createHash, createHmac, hkdfSync, randomBytes } from "node:crypto"; + +/** + * The hard-coded master key Atom2Api ships (two independent community + * implementations agree on it). Overridable per request in case upstream + * rotates it without warning. + */ +export const MASTER_KEY_HEX = "e97250f05303162c8ecd68c688b2f55c1d81e508d243d88466472e7f54637123"; + +/** HKDF info label, exactly as upstream spells it. */ +export const SIGNING_INFO = "atomcode-signing-v1"; + +/** A fresh 16-byte nonce (32 hex chars once stringified). */ +export function newNonce() { + return randomBytes(16); +} + +/** Coerce a request body into what `createHash().update()` accepts. */ +function toHashInput(body) { + if (body === undefined || body === null || body === "") return ""; + if (typeof body === "string") return body; + if (Buffer.isBuffer(body)) return body; + if (body instanceof Uint8Array) return body; + if (ArrayBuffer.isView(body)) { + return new Uint8Array(body.buffer, body.byteOffset, body.byteLength); + } + if (body instanceof ArrayBuffer) return new Uint8Array(body); + throw new Error("unsupported request body type for signing"); +} + +/** + * Build the five `X-AtomCode-*` headers for one request. + * + * @param {object} params + * @param {string} params.method - HTTP method ("POST" …). + * @param {string} params.path - full request path incl. `/v1`, no query. + * @param {string|Buffer|ArrayBufferView|ArrayBuffer} [params.body] - what will be sent; "" hashes as the empty body. + * @param {string} params.oauthToken - the bearer token. + * @param {string} params.userId - the upstream `user.id` (enters the salt). + * @param {string} params.clientVersion - `X-AtomCode-Ver` value, e.g. "5.2.3". + * @param {number} [params.timestamp] - unix seconds; defaults to now. + * @param {Buffer} [params.nonce] - 16 bytes; defaults to `newNonce()`. + * @param {string} [params.masterKeyHex] - 64 hex chars; defaults to `MASTER_KEY_HEX`. + * @returns {object} the five headers, ready to merge into a Headers object. + */ +export function signAtomGitRequest({ + method, + path, + body = "", + oauthToken, + userId, + clientVersion, + timestamp = Math.floor(Date.now() / 1000), + nonce = newNonce(), + masterKeyHex = MASTER_KEY_HEX, +}) { + if (typeof method !== "string" || !method) throw new Error("signing requires a method"); + if (typeof path !== "string" || !path.startsWith("/")) { + throw new Error("signing requires an absolute request path (starting with /)"); + } + if (!oauthToken) throw new Error("signing requires an oauth token"); + if (userId === undefined || userId === null || userId === "") { + throw new Error("signing requires the account's user id"); + } + if (!clientVersion) throw new Error("signing requires a client version"); + + const masterKey = Buffer.from(masterKeyHex, "hex"); + const timeBucket = Buffer.alloc(8); + timeBucket.writeBigUInt64LE(BigInt(Math.floor(timestamp / 3600))); + const salt = Buffer.concat([ + Buffer.from(String(userId), "utf8"), + Buffer.from([1]), + timeBucket, + createHash("sha256").update(oauthToken).digest(), + createHash("sha256").update(String(clientVersion)).digest(), + ]); + const signingKey = Buffer.from(hkdfSync("sha256", masterKey, salt, Buffer.from(SIGNING_INFO), 32)); + + const bodyHash = createHash("sha256").update(toHashInput(body)).digest("hex"); + const nonceHex = Buffer.isBuffer(nonce) ? nonce.toString("hex") : String(nonce); + const canonical = [ + "v1", + method.toUpperCase(), + path, + String(timestamp), + nonceHex, + bodyHash, + ].join("\n"); + + const sig = createHmac("sha256", signingKey).update(canonical).digest("hex"); + return { + "X-AtomCode-Sig": "v1:" + sig, + "X-AtomCode-Ts": String(timestamp), + "X-AtomCode-Nonce": nonceHex, + "X-AtomCode-Alg": "1", + "X-AtomCode-Ver": String(clientVersion), + }; +} diff --git a/packages/atomcode/state.mjs b/packages/atomcode/state.mjs new file mode 100644 index 0000000..e071dd7 --- /dev/null +++ b/packages/atomcode/state.mjs @@ -0,0 +1,371 @@ +/** + * Small, private, crash-tolerant state kept beside Magpie's plugin data. + * + * This file intentionally contains no credentials. Accounts are addressed by a + * truncated SHA-256 digest of the upstream user id, so diagnostics can tell + * accounts apart without storing the complete id, its email or a token. + * + * @module magpie-atomcode/state + */ + +import { createHash, randomBytes } from "node:crypto"; +import { chmod, mkdir, open, readFile, rename, unlink } from "node:fs/promises"; +import { dirname, join } from "node:path"; + +import { redactText } from "./internal.mjs"; + +export const STATE_FILE_NAME = "atomcode-state.json"; +export const STATE_VERSION = 1; +const MAX_STATE_BYTES = 2 << 20; +const DIGEST_RE = /^(?:[a-f0-9]{16}|anonymous)$/; + +const isObject = (value) => + value !== null && typeof value === "object" && !Array.isArray(value); + +const text = (value, max = 200) => { + if (typeof value !== "string" || !value) return undefined; + return redactText(value, max); +}; + +const finite = (value, min = 0, max = Number.MAX_SAFE_INTEGER) => { + const number = Number(value); + return Number.isFinite(number) && number >= min && number <= max + ? number + : undefined; +}; + +const iso = (value) => { + const at = finite(value, 0); + return at === undefined ? undefined : new Date(at).toISOString(); +}; + +/** A stable, non-reversible account key. */ +export function accountDigest(uid) { + const value = uid === undefined || uid === null ? "" : String(uid); + if (!value) return "anonymous"; + return createHash("sha256").update(value, "utf8").digest("hex").slice(0, 16); +} + +/** The state file path for a Magpie plugin directory. */ +export function stateFilePath(directory) { + return typeof directory === "string" && directory + ? join(directory, STATE_FILE_NAME) + : undefined; +} + +function sanitizeModel(model) { + if (!isObject(model)) return undefined; + const id = text(model.id, 300); + const key = text(model.key ?? id, 300); + if (!id || !key) return undefined; + const levels = Array.isArray(model.levels) + ? model.levels + .filter((level) => typeof level === "string" && level.trim()) + .slice(0, 32) + .map((level) => text(level, 80)) + .filter(Boolean) + : []; + const baseURL = text(model.baseURL, 1000); + return { + id, + key, + context: finite(model.context, 1) ?? 64_000, + output: finite(model.output, 1) ?? 32_768, + levels, + vision: model.vision === true, + type: text(model.type, 40) ?? "openai", + ...(baseURL ? { baseURL } : {}), + }; +} + +function sanitizeWindow(window) { + if (!isObject(window)) return undefined; + const name = text(window.name, 120); + const unit = text(window.unit, 24); + if (!name) return undefined; + const out = { name }; + for (const key of ["used", "span", "amount", "limit"]) { + const value = finite(window[key], 0); + if (value !== undefined) out[key] = value; + } + if (unit) out.unit = unit; + const display = text(window.display, 120); + if (display) out.display = display; + const resetSecs = finite(window.resetSecs, 0); + if (resetSecs !== undefined) out.resetSecs = resetSecs; + const resetsAt = text(window.resetsAt, 60); + if (resetsAt) out.resetsAt = resetsAt; + return out; +} + +function sanitizeQuota(quota) { + if (!isObject(quota)) return undefined; + const out = { + plan: text(quota.plan, 200) ?? "AtomCode CodingPlan", + windows: Array.isArray(quota.windows) + ? quota.windows.map(sanitizeWindow).filter(Boolean).slice(0, 32) + : [], + }; + const until = text(quota.until, 60); + if (until) out.until = until; + return out; +} + +function sanitizeError(error) { + if (!isObject(error)) return undefined; + const category = text(error.category, 64); + if (!category) return undefined; + const status = finite(error.status, 100, 599); + return { + category, + message: redactText(error.message ?? "", 240), + at: iso(error.at) ?? new Date().toISOString(), + ...(status === undefined ? {} : { status }), + }; +} + +function sanitizeSelfCheck(check) { + if (!isObject(check)) return undefined; + return { + ok: check.ok === true, + at: iso(check.at) ?? new Date().toISOString(), + ms: finite(check.ms, 0, 60_000) ?? 0, + checks: { + signature: check.checks?.signature === true, + version: check.checks?.version === true, + configuration: check.checks?.configuration === true, + }, + }; +} + +function sanitizeAccount(account) { + if (!isObject(account)) return undefined; + const digest = text(account.digest, 64); + if (!digest || !DIGEST_RE.test(digest)) return undefined; + const out = { digest }; + const loginSource = text(account.loginSource, 40); + if (loginSource) out.loginSource = loginSource; + + if (Array.isArray(account.models)) { + const models = account.models.map(sanitizeModel).filter(Boolean).slice(0, 256); + if (models.length) { + out.models = models; + out.modelSource = text(account.modelSource, 24) ?? "cached"; + out.modelUpdatedAt = iso(account.modelUpdatedAt) + ?? new Date().toISOString(); + } + } + + const quota = sanitizeQuota(account.quota); + if (quota) { + out.quota = quota; + out.quotaUpdatedAt = iso(account.quotaUpdatedAt) + ?? new Date().toISOString(); + } + const error = sanitizeError(account.lastError); + if (error) out.lastError = error; + const selfCheck = sanitizeSelfCheck(account.selfCheck); + if (selfCheck) out.selfCheck = selfCheck; + const updatedAt = iso(account.updatedAt); + if (updatedAt) out.updatedAt = updatedAt; + return out; +} + +/** Remove anything outside the documented state schema. */ +export function sanitizeState(input) { + const state = { + version: STATE_VERSION, + updatedAt: iso(input?.updatedAt) ?? new Date().toISOString(), + accounts: Object.create(null), + versionSource: undefined, + }; + + if (isObject(input?.accounts)) { + for (const [digest, raw] of Object.entries(input.accounts)) { + if (!DIGEST_RE.test(digest)) continue; + const account = sanitizeAccount({ ...raw, digest }); + if (account) state.accounts[digest] = account; + } + } + + const version = isObject(input?.versionSource) ? input.versionSource : undefined; + if (version) { + const value = text(version.version, 80); + if (value) { + state.versionSource = { + version: value, + source: text(version.source, 24) ?? "unknown", + checkedAt: iso(version.checkedAt), + failedAt: iso(version.failedAt), + }; + } + } + return state; +} + +export function emptyState() { + return sanitizeState({}); +} + +async function atomicWrite(path, textValue) { + await mkdir(dirname(path), { recursive: true, mode: 0o700 }); + const temp = `${path}.${process.pid}.${randomBytes(6).toString("hex")}.tmp`; + let handle; + try { + handle = await open(temp, "wx", 0o600); + await handle.writeFile(textValue, "utf8"); + await handle.sync(); + await handle.close(); + handle = undefined; + await chmod(temp, 0o600).catch(() => {}); + await rename(temp, path); + } catch (error) { + await handle?.close().catch(() => {}); + await unlink(temp).catch(() => {}); + throw error; + } +} + +/** + * A serialized state store. With no `directory` it keeps state in memory and + * never creates a file, which keeps OpenCode's permissive host shape safe. + */ +export function createStateStore({ directory, onError } = {}) { + const path = stateFilePath(directory); + let value; + let loading; + let writes = Promise.resolve(); + + const report = (error) => { + try { + onError?.(error); + } catch { + /* reporting is best-effort */ + } + }; + + async function load() { + if (value) return value; + if (loading) return loading; + loading = (async () => { + if (!path) return (value = emptyState()); + try { + const raw = await readFile(path); + if (raw.byteLength > MAX_STATE_BYTES) return (value = emptyState()); + const parsed = JSON.parse(raw.toString("utf8")); + return (value = sanitizeState(parsed)); + } catch (error) { + // A missing, truncated or foreign file is not a reason to fail a + // request. It is replaced by the next successful write. + if (error?.code !== "ENOENT") report(error); + return (value = emptyState()); + } finally { + loading = undefined; + } + })(); + return loading; + } + + async function update(mutator) { + const run = writes.then(async () => { + await load(); + const draft = structuredClone(value); + const next = (await mutator(draft)) ?? draft; + value = sanitizeState({ + ...next, + updatedAt: Date.now(), + }); + if (path) await atomicWrite(path, `${JSON.stringify(value, null, 2)}\n`); + return value; + }); + writes = run.catch(report); + return run; + } + + function account(draft, digest) { + const key = DIGEST_RE.test(String(digest ?? "")) ? String(digest) : accountDigest(digest); + draft.accounts[key] ??= { digest: key }; + return draft.accounts[key]; + } + + async function accountByDigest(digest) { + const state = await load(); + const key = DIGEST_RE.test(String(digest ?? "")) ? String(digest) : accountDigest(digest); + return structuredClone(state.accounts[key]); + } + + return { + path, + async read() { + await load(); + return structuredClone(value); + }, + async account(digest) { + return accountByDigest(digest); + }, + async recordLogin(uid, source) { + if (!source) return; + return update((draft) => { + const current = account(draft, accountDigest(uid)); + current.loginSource = redactText(source, 40); + current.updatedAt = Date.now(); + }).catch((error) => report(error)); + }, + async recordModels(uid, models, { source = "live" } = {}) { + if (!Array.isArray(models) || !models.length) return; + return update((draft) => { + const current = account(draft, accountDigest(uid)); + current.models = models; + current.modelSource = source; + current.modelUpdatedAt = Date.now(); + current.updatedAt = Date.now(); + }).catch((error) => report(error)); + }, + async cachedModels(uid) { + const current = await accountByDigest(accountDigest(uid)); + return Array.isArray(current?.models) ? structuredClone(current.models) : []; + }, + async recordQuota(uid, quota) { + if (!isObject(quota)) return; + return update((draft) => { + const current = account(draft, accountDigest(uid)); + current.quota = quota; + current.quotaUpdatedAt = Date.now(); + current.updatedAt = Date.now(); + }).catch((error) => report(error)); + }, + async cachedQuota(uid) { + const current = await accountByDigest(accountDigest(uid)); + return current?.quota ? structuredClone(current.quota) : undefined; + }, + async recordError(uid, error) { + if (!error?.category) return; + return update((draft) => { + const current = account(draft, accountDigest(uid)); + current.lastError = error; + current.updatedAt = Date.now(); + }).catch((reportError) => report(reportError)); + }, + async recordSelfCheck(uid, check) { + return update((draft) => { + const current = account(draft, accountDigest(uid)); + current.selfCheck = check; + current.updatedAt = Date.now(); + }).catch((error) => report(error)); + }, + async recordSelfCheckForDigest(digest, check) { + if (!DIGEST_RE.test(String(digest ?? ""))) return; + return update((draft) => { + const current = account(draft, digest); + current.selfCheck = check; + current.updatedAt = Date.now(); + }).catch((error) => report(error)); + }, + async recordVersion(version) { + if (!isObject(version) || !version.version) return; + return update((draft) => { + draft.versionSource = version; + }).catch((error) => report(error)); + }, + }; +} diff --git a/packages/atomcode/test/auth-file.test.mjs b/packages/atomcode/test/auth-file.test.mjs new file mode 100644 index 0000000..08eb05a --- /dev/null +++ b/packages/atomcode/test/auth-file.test.mjs @@ -0,0 +1,241 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { mkdtemp, readFile, stat, symlink, writeFile, chmod } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; + +import { + parseAuthFile, + renderAuthFile, + readAuthFile, + resolveAuthFilePath, + writeAuthFile, +} from "../auth-file.mjs"; + +const SAMPLE = `# AtomCode credentials +access_token = "access-old" +refresh_token = "refresh-old" +token_type = "Bearer" +created_at = 1700000000 +expires_in = 3600 +future_field = "keep-me" + +[user] +id = "123456" +username = "alice" +name = "Alice" +email = "alice@example.com" +avatar_url = "https://example.com/a.png" +`; + +test("parseAuthFile maps the CLI file without exposing raw text", () => { + const auth = parseAuthFile(SAMPLE); + assert.equal(auth.access, "access-old"); + assert.equal(auth.refresh, "refresh-old"); + assert.equal(auth.uid, "123456"); + assert.equal(auth.accountId, "alice@example.com"); + assert.equal(auth.name, "Alice"); + assert.equal(auth.expires, 1700003600_000); +}); + +test("resolveAuthFilePath expands only the current user's home and absolute paths", () => { + const env = { HOME: "/home/alice" }; + assert.equal( + resolveAuthFilePath(undefined, env), + "/home/alice/.atomcode/auth.toml", + ); + assert.equal(resolveAuthFilePath("", env), "/home/alice/.atomcode/auth.toml"); + assert.equal(resolveAuthFilePath("~", env), "/home/alice"); + assert.equal( + resolveAuthFilePath("~/.atomcode/custom.toml", env), + "/home/alice/.atomcode/custom.toml", + ); + assert.equal( + resolveAuthFilePath("/var/lib/atomcode/auth.toml", env), + "/var/lib/atomcode/auth.toml", + ); +}); + +test("resolveAuthFilePath rejects relative, NUL, oversized and other-user paths", () => { + const env = { HOME: "/home/alice" }; + assert.throws(() => resolveAuthFilePath("auth.toml", env), /absolute/); + assert.throws(() => resolveAuthFilePath("~bob/auth.toml", env), /another-user/); + assert.throws(() => resolveAuthFilePath("~/a\0b", env), /NUL/); + assert.throws(() => resolveAuthFilePath(`~/${"a".repeat(4096)}`, env), /too long/); +}); + +test("renderAuthFile updates only credential fields and preserves unknown content", () => { + const rendered = renderAuthFile(SAMPLE, { + access: "access-new", + refresh: "refresh-new", + expiresIn: 7200, + createdAt: 1800000000, + user: { id: "123456", name: "Alice 2" }, + }); + assert.match(rendered, /# AtomCode credentials/); + assert.match(rendered, /future_field = "keep-me"/); + assert.match(rendered, /token_type = "Bearer"/); + assert.match(rendered, /access_token = "access-new"/); + assert.match(rendered, /refresh_token = "refresh-new"/); + assert.match(rendered, /created_at = 1800000000/); + assert.match(rendered, /expires_in = 7200/); + assert.match(rendered, /id = "123456"/); + assert.doesNotMatch(rendered, /id = 123456/); + assert.match(rendered, /name = "Alice 2"/); + assert.match(rendered, /email = "alice@example.com"/); +}); + +test("auth.toml parser preserves scalar types and appends id as a string", () => { + const text = `access_token = "access\\q" +refresh_token = 'refresh-single' +created_at = "1700000000" +expires_in = "3600" +[user] +id = "42" +`; + const auth = parseAuthFile(text); + assert.equal(auth.access, "access\\q"); + assert.equal(auth.refresh, "refresh-single"); + assert.equal(auth.uid, "42"); + + const rendered = renderAuthFile('access_token = "old"\n', { + access: "new", + refresh: "refresh", + createdAt: 1700000000, + expiresIn: 3600, + user: { id: 42, name: "Alice" }, + }); + assert.match(rendered, /\[user\]/); + assert.match(rendered, /id = "42"/); + assert.match(rendered, /name = "Alice"/); + + const quoted = renderAuthFile(text, { + access: "next", + refresh: "next-refresh", + createdAt: 1800000000, + expiresIn: 7200, + user: { id: "42" }, + }); + assert.match(quoted, /created_at = "1800000000"/); + assert.match(quoted, /expires_in = "7200"/); + assert.match(quoted, /id = "42"/); +}); + +test("auth.toml renderer preserves a legacy integer id when rewriting it", () => { + const rendered = renderAuthFile( + 'access_token = "old"\ncreated_at = 1700000000\nexpires_in = 3600\n[user]\nid = 42\n', + { + access: "new", + createdAt: 1800000000, + expiresIn: 7200, + user: { id: "99" }, + }, + ); + assert.match(rendered, /\[user\]\nid = 99/); + assert.doesNotMatch(rendered, /\[user\]\nid = "99"/); +}); + +test("auth.toml renderer preserves float and boolean value types", () => { + const rendered = renderAuthFile( + 'access_token = "old"\ncreated_at = 1.0\nexpires_in = true\n[user]\nid = "42"\n', + { + access: "new", + createdAt: 1800000000, + expiresIn: false, + user: { id: "42" }, + }, + ); + assert.match(rendered, /created_at = 1800000000\.0/); + assert.match(rendered, /expires_in = false/); +}); + +test("inline comments survive parsing and credential renewal", async () => { + const dir = await mkdtemp(join(tmpdir(), "atomcode-comments-")); + const file = join(dir, "auth.toml"); + const input = `access_token = "old#token" # access +refresh_token = 'old#refresh' # refresh +created_at = 1.0 # time +expires_in = true # duration +[user] +id = "123456" # c +username = "a\\\"#b" # username +name = 'Alice # Smith' # name +`; + await writeFile(file, input, { mode: 0o600 }); + const before = await readAuthFile(file); + assert.equal(before.access, "old#token"); + assert.equal(before.refresh, "old#refresh"); + assert.equal(before.uid, "123456"); + assert.equal(before.accountId, 'a"#b'); + assert.equal(before.name, "Alice # Smith"); + + await writeAuthFile(file, { access: "new#token", refresh: "new#refresh", createdAt: 2, expiresIn: 60 }); + const text = await readFile(file, "utf8"); + assert.match(text, /^access_token = "new#token" # access$/m); + assert.match(text, /^refresh_token = "new#refresh" # refresh$/m); + assert.match(text, /^created_at = 2\.0 # time$/m); + assert.match(text, /^expires_in = false # duration$/m); + assert.match(text, /^id = "123456" # c$/m); + assert.equal((await readAuthFile(file)).uid, "123456"); + const integer = renderAuthFile('access_token = "old"\n[user]\nid = 42 # integer\n', { + access: "new", user: { id: "99" }, + }); + assert.match(integer, /^id = 99 # integer$/m); + assert.equal(parseAuthFile('access_token = "a\\\\" # comment\n[user]\nid = "42"\n').access, "a\\"); +}); + +test("readAuthFile and writeAuthFile use private permissions and atomic replacement", async () => { + const dir = await mkdtemp(join(tmpdir(), "atomcode-auth-")); + const file = join(dir, "auth.toml"); + await writeFile(file, SAMPLE, { mode: 0o600 }); + + const before = await readAuthFile(file); + assert.equal(before.refresh, "refresh-old"); + + await writeAuthFile(file, { + access: "access-new", + refresh: "refresh-new", + expiresIn: 60, + user: { id: "123456", username: "alice" }, + }); + const text = await readFile(file, "utf8"); + assert.match(text, /access_token = "access-new"/); + assert.match(text, /token_type = "Bearer"/); + assert.match(text, /id = "123456"/); + assert.doesNotMatch(text, /id = 123456/); + assert.match(text, /future_field = "keep-me"/); + if (process.platform !== "win32") { + assert.equal((await stat(file)).mode & 0o777, 0o600); + } +}); + +test("readAuthFile rejects symlinks, loose permissions, and account-less files", async () => { + const dir = await mkdtemp(join(tmpdir(), "atomcode-auth-")); + const real = join(dir, "real.toml"); + const link = join(dir, "link.toml"); + await writeFile(real, SAMPLE, { mode: 0o600 }); + await symlink(real, link); + await assert.rejects(() => readAuthFile(link), /regular file|symlink/i); + + if (process.platform !== "win32") { + await chmod(real, 0o644); + await assert.rejects(() => readAuthFile(real), /0600|permissions/i); + await chmod(real, 0o600); + } + + const noUser = join(dir, "no-user.toml"); + await writeFile(noUser, 'access_token = "a"\n', { mode: 0o600 }); + await assert.rejects(() => readAuthFile(noUser), /user id/i); + await assert.rejects( + () => readAuthFile(join(dir, "missing.toml")), + /not signed in/i, + ); + await assert.rejects( + () => + writeAuthFile(real, { + access: "", + expiresIn: 0, + }), + /incomplete.*credentials/i, + ); +}); diff --git a/packages/atomcode/test/codingplan.test.mjs b/packages/atomcode/test/codingplan.test.mjs new file mode 100644 index 0000000..18ed504 --- /dev/null +++ b/packages/atomcode/test/codingplan.test.mjs @@ -0,0 +1,202 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; + +import { claimCodingPlan, fetchModels, planNeedsClaim, planOf, planTier } from "../codingplan.mjs"; + +test("planTier:Max/Pro 判定与 Lite 兜底(含「体验版」写法)", () => { + assert.equal(planTier("CodingPlan Max"), "Max"); + assert.equal(planTier("MAX 旗舰"), "Max"); + assert.equal(planTier("CodingPlan Pro"), "Pro"); + assert.equal(planTier("CodingPlan Lite-体验版"), "Lite"); + assert.equal(planTier("Lite-beta"), "Lite"); + assert.equal(planTier(undefined), "Lite"); +}); + +test("planOf:codingplan_free 优先,plan 兜底,缺失/非对象 → null", () => { + assert.deepEqual(planOf({ codingplan_free: { plan_name: "x" } }), { plan_name: "x" }); + assert.deepEqual(planOf({ plan: { plan_name: "y" } }), { plan_name: "y" }); + assert.equal(planOf({}), null); + assert.equal(planOf(null), null); +}); + +/** 按调用次序回放响应的小工具,多余调用复用最后一个响应。 */ +function sequenceFetch(responses) { + const seen = []; + const fetchImpl = async (url, init = {}) => { + seen.push({ url, init }); + const next = responses[Math.min(seen.length - 1, responses.length - 1)]; + return new Response(next.body, { status: next.status ?? 200 }); + }; + return { fetchImpl, seen }; +} + +test("claim:第一档 success 即停,请求形状正确", async () => { + const { fetchImpl, seen } = sequenceFetch([ + { body: JSON.stringify({ success: true, message: "ok", plan_name: "CodingPlan Max", plan_type: "Max" }) }, + ]); + const r = await claimCodingPlan("https://gitcode.example", "tok", { fetchImpl, clientVersion: "5.2.3" }); + assert.equal(r.claimed, true); + assert.equal(r.duplicate, false); + assert.equal(r.tier, "Max"); + assert.equal(r.planName, "CodingPlan Max"); + assert.equal(r.attempts.length, 1); + assert.equal(seen.length, 1); + assert.equal(new URL(seen[0].url).pathname, "/coding-plan/claim-v2"); + assert.equal(JSON.parse(seen[0].init.body).plan_type, "Max"); + assert.equal(seen[0].init.headers.authorization, "Bearer tok"); + assert.equal(seen[0].init.headers["user-agent"], "atomcode/5.2.3"); +}); + +test("claim:Max/Pro 失败 → Lite duplicate 停;错误响应体的 message 不丢", async () => { + const { fetchImpl } = sequenceFetch([ + { status: 400, body: JSON.stringify({ success: false, message: "无可用计划" }) }, + { status: 400, body: JSON.stringify({ success: false, message: "无可用计划" }) }, + { body: JSON.stringify({ success: false, duplicate: true, plan_type: "Lite" }) }, + ]); + const r = await claimCodingPlan("https://gitcode.example", "tok", { fetchImpl, clientVersion: "5.2.3" }); + assert.equal(r.claimed, true); + assert.equal(r.duplicate, true); + assert.equal(r.tier, "Lite"); + assert.equal(r.attempts.length, 3); + assert.equal(r.attempts[0].message, "无可用计划"); +}); + +test("claim:三档都失败 → claimed false 且不抛出", async () => { + const { fetchImpl } = sequenceFetch([ + { status: 400, body: JSON.stringify({ success: false, message: "a" }) }, + { status: 400, body: JSON.stringify({ success: false, message: "b" }) }, + { status: 400, body: JSON.stringify({ success: false, message: "c" }) }, + ]); + const r = await claimCodingPlan("https://gitcode.example", "tok", { fetchImpl, clientVersion: "5.2.3" }); + assert.equal(r.claimed, false); + assert.equal(r.duplicate, false); + assert.equal(r.message, "c"); +}); + +test("planNeedsClaim:缺失/空名 → 需要领取", () => { + assert.equal(planNeedsClaim({}), true); + assert.equal(planNeedsClaim(null), true); + assert.equal(planNeedsClaim({ codingplan_free: { plan_name: " " } }), true); +}); + +test("planNeedsClaim:套餐有效(无日期字段也保守放行)→ false", () => { + assert.equal(planNeedsClaim({ codingplan_free: { plan_name: "CodingPlan Lite-体验版" } }), false); + assert.equal( + planNeedsClaim({ codingplan_free: { plan_name: "Lite", remaining_days: 4, expires_at: "2099-01-01" } }), + false, + ); +}); + +test("planNeedsClaim:remaining_days ≤ 0 → 需要重领", () => { + assert.equal( + planNeedsClaim({ codingplan_free: { plan_name: "Lite", remaining_days: 0, expires_at: "2099-01-01" } }), + true, + ); + assert.equal( + planNeedsClaim({ codingplan_free: { plan_name: "Lite", remaining_days: -2, expires_at: "2099-01-01" } }), + true, + ); +}); + +test("planNeedsClaim:remaining_days 为 null/undefined 时视为未知,不误触发", () => { + for (const remaining_days of [null, undefined]) { + assert.equal( + planNeedsClaim({ + codingplan_free: { + plan_name: "CodingPlan Pro", + remaining_days, + expires_at: "2099-01-01", + }, + }), + false, + ); + } +}); + +test("planNeedsClaim:expires_at 过期超 24h → 需要重领;24h 宽限内 → false", () => { + const now = Date.parse("2026-10-16T12:00:00Z"); + assert.equal( + planNeedsClaim({ codingplan_free: { plan_name: "Lite", expires_at: "2026-10-14T00:00:00Z" } }, now), + true, + ); + assert.equal( + planNeedsClaim({ codingplan_free: { plan_name: "Lite", expires_at: "2026-10-16T00:00:00Z" } }, now), + false, + ); + assert.equal( + planNeedsClaim({ codingplan_free: { plan_name: "Lite", expires_at: "2099-01-01T00:00:00Z" } }, now), + false, + ); +}); + +test("claim:网络异常只尝试一次,不把三档当三次重试", async () => { + let calls = 0; + const r = await claimCodingPlan("https://gitcode.example", "tok", { + fetchImpl: async () => { + calls += 1; + throw new Error("boom"); + }, + clientVersion: "5.2.3", + }); + assert.equal(r.claimed, false); + assert.equal(calls, 1); + assert.equal(r.attempts.length, 1); + assert.match(r.message, /boom/); +}); + +test("claim:429/5xx/401 不继续尝试其他档位", async () => { + for (const status of [401, 429, 503]) { + let calls = 0; + const r = await claimCodingPlan("https://gitcode.example", "tok", { + fetchImpl: async () => { + calls += 1; + return new Response(JSON.stringify({ message: "stop" }), { status }); + }, + clientVersion: "5.2.3", + }); + assert.equal(calls, 1, `HTTP ${status} should stop the cascade`); + assert.equal(r.claimed, false); + } +}); + +test("fetchModels:plan_type 编码进 query,过滤空名/不可用/弃用行", async () => { + const good = { display_model_name: "ok/model", context_window: 100, plan_available: true }; + const { fetchImpl, seen } = sequenceFetch([ + { + body: JSON.stringify([ + good, + { display_model_name: " " }, + { display_model_name: "hidden", plan_available: false }, + { display_model_name: "old", status: "deprecated" }, + ]), + }, + ]); + const rows = await fetchModels("https://gitcode.example", "tok", "Lite/dark", { + fetchImpl, + clientVersion: "5.2.3", + }); + assert.equal(rows.length, 1); + assert.deepEqual(rows[0], good); + const u = new URL(seen[0].url); + assert.equal(u.pathname, "/coding-plan/models-v2"); + assert.equal(u.searchParams.get("plan_type"), "Lite/dark"); + assert.equal(seen[0].init.headers.authorization, "Bearer tok"); +}); + +test("fetchModels:非数组响应抛错", async () => { + const { fetchImpl } = sequenceFetch([{ body: JSON.stringify({ nope: 1 }) }]); + await assert.rejects( + () => fetchModels("https://x", "t", "Lite", { fetchImpl, clientVersion: "5.2.3" }), + /did not return a list/, + ); +}); + +test("CodingPlan 401/403 标记 signIn expired", async () => { + const { fetchImpl } = sequenceFetch([{ status: 401, body: "{}" }]); + const error = await fetchModels("https://x", "t", "Lite", { fetchImpl, clientVersion: "5.2.3" }).then( + () => null, + (e) => e, + ); + assert.ok(error); + assert.equal(error.signIn, "expired"); +}); diff --git a/packages/atomcode/test/diagnostics.test.mjs b/packages/atomcode/test/diagnostics.test.mjs new file mode 100644 index 0000000..50bb885 --- /dev/null +++ b/packages/atomcode/test/diagnostics.test.mjs @@ -0,0 +1,362 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { createServer, request as httpRequest } from "node:http"; +import { mkdtemp, readFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; + +import { MASTER_KEY_HEX } from "../sign.mjs"; +import { createStateStore } from "../state.mjs"; +import { + DIAGNOSTICS_TOKEN_HEADER, + diagnosticsPort, + diagnosticsSnapshot, + hostAllowed, + originAllowed, + runSelfCheck, + startDiagnosticsService, +} from "../diagnostics.mjs"; + +async function freePort() { + const server = createServer(); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + const port = server.address().port; + await new Promise((resolve) => server.close(resolve)); + return port; +} + +function rawRequest(port, path, { method = "GET", headers = {}, body } = {}) { + return new Promise((resolve, reject) => { + const req = httpRequest( + { hostname: "127.0.0.1", port, path, method, headers }, + (res) => { + let text = ""; + res.on("data", (chunk) => { + text += chunk; + }); + res.on("end", () => + resolve({ status: res.statusCode, headers: res.headers, text }), + ); + }, + ); + req.on("error", reject); + req.end(body); + }); +} + +test("diagnostics port, Host and Origin rules are loopback-only", () => { + assert.equal(diagnosticsPort(3478), 3478); + assert.equal(diagnosticsPort("4567"), 4567); + assert.equal(diagnosticsPort(80), 3478); + assert.equal(diagnosticsPort("bad"), 3478); + assert.equal(hostAllowed("127.0.0.1:3478", 3478), true); + assert.equal(hostAllowed("localhost:3478", 3478), true); + assert.equal(hostAllowed("127.0.0.1:3479", 3478), false); + assert.equal(hostAllowed("evil.example:3478", 3478), false); + assert.equal(originAllowed(undefined, 3478), true); + assert.equal(originAllowed(undefined, 3478, { required: true }), false); + assert.equal(originAllowed("null", 3478, { required: true }), true); + assert.equal(originAllowed("http://127.0.0.1:3478", 3478, { required: true }), true); + assert.equal(originAllowed("https://127.0.0.1:3478", 3478, { required: true }), false); +}); + +test("diagnostics page uses flat backgrounds without decorative gradients", async () => { + const css = await readFile(new URL("../page/app.css", import.meta.url), "utf8"); + const html = await readFile( + new URL("../page/diagnostics.html", import.meta.url), + "utf8", + ); + assert.doesNotMatch(css, /(?:radial|linear)-gradient/i); + assert.doesNotMatch(css, /\.ambient\b/); + assert.doesNotMatch(html, /class="ambient"/); +}); + +test("offline self-check exercises signing without network access", () => { + const ok = runSelfCheck({ clientVersion: "5.2.3", masterKeyHex: MASTER_KEY_HEX }); + assert.equal(ok.ok, true); + assert.equal(ok.checks.signature, true); + assert.equal(ok.checks.version, true); + assert.equal(ok.checks.configuration, true); + + const failed = runSelfCheck({ clientVersion: "", masterKeyHex: "bad" }); + assert.equal(failed.ok, false); + assert.equal(failed.checks.version, false); + assert.equal(failed.checks.configuration, false); +}); + +test("snapshot exposes only redacted persisted account data", async () => { + const snapshot = await diagnosticsSnapshot({ + state: { + version: 1, + accounts: { + abcdef0123456789: { + digest: "abcdef0123456789", + loginSource: "atomcode-cli", + models: [{ id: "model-a" }, { id: "model-b" }], + modelSource: "live", + modelUpdatedAt: new Date(1000).toISOString(), + quota: { + plan: "Plan", + windows: [{ name: "5h", used: 10, unit: "calls" }], + }, + quotaUpdatedAt: new Date(2000).toISOString(), + lastError: { category: "network", message: "masked" }, + }, + }, + }, + version: { version: "5.2.3", source: "manifest" }, + config: { locale: "en", diagnosticsPort: 3478 }, + }); + assert.equal(snapshot.account.digest, "abcdef0123456789"); + assert.equal(snapshot.models.count, 2); + assert.equal(snapshot.quota.stale, true); + assert.equal(snapshot.config.readOnly, true); + assert.doesNotMatch(JSON.stringify(snapshot), /access|refresh|email/i); +}); + +test("loopback service serves a read-only page and token-gated APIs", async () => { + const directory = await mkdtemp(join(tmpdir(), "atomcode-diagnostics-")); + const stateStore = createStateStore({ directory }); + await stateStore.recordLogin("42", "atomcode-cli"); + await stateStore.recordQuota("42", { + plan: "CodingPlan Lite", + windows: [{ name: "5h", used: 12, unit: "calls" }], + }); + + const port = await freePort(); + const versionSource = { status: () => ({ version: "5.2.3", source: "manifest" }) }; + const service = startDiagnosticsService({ + port, + stateStore, + versionSource, + locale: "en", + config: { locale: "en", diagnosticsPort: port, autoClaim: true, autoVersion: false }, + selfCheckConfig: { clientVersion: "5.2.3", masterKeyHex: MASTER_KEY_HEX }, + }); + try { + assert.equal(await service.ready, service); + assert.equal(startDiagnosticsService({ port }), service); + + const page = await fetch(`http://127.0.0.1:${port}/`); + assert.equal(page.status, 200); + const policy = page.headers.get("content-security-policy"); + const loopback = `http://127.0.0.1:${port} http://localhost:${port}`; + for (const directive of ["style-src", "script-src", "img-src", "connect-src"]) { + assert.ok( + policy.includes(`${directive} 'self' ${loopback}`), + `${directive} names both loopback origins: ${policy}`, + ); + } + assert.ok( + policy.includes( + "frame-ancestors 'self' wails://localhost http://wails.localhost", + ), + policy, + ); + const nonceMatch = policy.match(/'nonce-([^']+)'/); + assert.ok(nonceMatch, `script-src has a nonce: ${policy}`); + assert.match(nonceMatch[1], /^[A-Za-z0-9+/]+={0,2}$/); + assert.doesNotMatch( + policy, + /frame-ancestors 'none'|'unsafe-inline'|'unsafe-eval'|\*/, + ); + assert.equal(page.headers.get("cache-control"), "no-store"); + assert.equal( + page.headers.get("cross-origin-resource-policy"), + "cross-origin", + ); + const html = await page.text(); + assert.match(html, /name="atomcode-token" content="[a-f0-9]{64}"/); + assert.ok(html.includes(``)); + assert.doesNotMatch(html, /\{\{CSP_NONCE\}\}/); + assert.match(html, /Read-only/); + assert.match(html, //); + assert.match(html, /href="\.\/icon\.svg"/); + assert.match(html, /href="\.\/app\.css"/); + assert.match(html, /src="\.\/app\.js"/); + assert.doesNotMatch(html, /person@example\.com|Bearer/); + + // Every reference stays relative, so the same page works at the origin root + // and behind a reverse proxy that mounts it under a prefix. + const proxyBase = `http://127.0.0.1:${port}/plugins/atomcode/`; + for (const [, reference] of html.matchAll(/(?:href|src)="([^"]+)"/g)) { + assert.ok(!reference.startsWith("/"), `${reference} must stay relative`); + assert.ok( + new URL(reference, proxyBase).pathname.startsWith("/plugins/atomcode/"), + `${reference} resolves under the proxy prefix`, + ); + } + assert.equal( + new URL("api/state", proxyBase).pathname, + "/plugins/atomcode/api/state", + ); + + const css = await fetch(`http://127.0.0.1:${port}/app.css`); + assert.equal(css.status, 200); + assert.equal( + css.headers.get("cross-origin-resource-policy"), + "cross-origin", + ); + assert.match(await css.text(), /--accent/); + const app = await fetch(`http://127.0.0.1:${port}/app.js`); + assert.equal(app.status, 200); + assert.equal( + app.headers.get("cross-origin-resource-policy"), + "cross-origin", + ); + const script = await app.text(); + assert.match(script, /api\("api\/state"\)/); + assert.match(script, /api\("api\/self-check"/); + assert.equal((await fetch(`http://127.0.0.1:${port}/icon.svg`)).status, 200); + assert.equal((await fetch(`http://127.0.0.1:${port}/missing`)).status, 404); + + assert.equal((await fetch(`http://127.0.0.1:${port}/api/state`)).status, 403); + + const statePreflight = await fetch(`http://127.0.0.1:${port}/api/state`, { + method: "OPTIONS", + headers: { + origin: "null", + "access-control-request-method": "GET", + "access-control-request-headers": DIAGNOSTICS_TOKEN_HEADER, + }, + }); + assert.equal(statePreflight.status, 204); + assert.equal(statePreflight.headers.get("access-control-allow-origin"), "null"); + assert.match(statePreflight.headers.get("access-control-allow-methods"), /GET/); + assert.equal( + statePreflight.headers.get("access-control-allow-headers"), + DIAGNOSTICS_TOKEN_HEADER, + ); + assert.match(statePreflight.headers.get("vary"), /Origin/i); + + const checkPreflight = await fetch( + `http://127.0.0.1:${port}/api/self-check`, + { + method: "OPTIONS", + headers: { + origin: `http://127.0.0.1:${port}`, + "access-control-request-method": "POST", + "access-control-request-headers": DIAGNOSTICS_TOKEN_HEADER, + }, + }, + ); + assert.equal(checkPreflight.status, 204); + assert.equal( + checkPreflight.headers.get("access-control-allow-origin"), + `http://127.0.0.1:${port}`, + ); + assert.match( + checkPreflight.headers.get("access-control-allow-methods"), + /POST/, + ); + assert.equal( + (await fetch(`http://127.0.0.1:${port}/api/state`, { + method: "OPTIONS", + headers: { + origin: "http://evil.example", + "access-control-request-method": "GET", + }, + })).status, + 403, + ); + + const state = await fetch(`http://127.0.0.1:${port}/api/state`, { + headers: { + [DIAGNOSTICS_TOKEN_HEADER]: service.token, + origin: "null", + }, + }); + assert.equal(state.status, 200); + assert.equal(state.headers.get("access-control-allow-origin"), "null"); + assert.match(state.headers.get("vary"), /Origin/i); + assert.doesNotMatch(state.headers.get("access-control-allow-origin"), /\*/); + const snapshot = await state.json(); + assert.equal(snapshot.account.loginSource, "atomcode-cli"); + assert.equal(snapshot.quota.plan, "CodingPlan Lite"); + assert.equal(snapshot.config.autoVersion, false); + + assert.equal( + (await fetch(`http://127.0.0.1:${port}/api/state`, { + headers: { + [DIAGNOSTICS_TOKEN_HEADER]: service.token, + origin: "http://evil.example", + }, + })).status, + 403, + ); + + const wrongOrigin = await fetch(`http://127.0.0.1:${port}/api/self-check`, { + method: "POST", + headers: { + [DIAGNOSTICS_TOKEN_HEADER]: service.token, + origin: "http://evil.example", + }, + }); + assert.equal(wrongOrigin.status, 403); + + const checked = await fetch(`http://127.0.0.1:${port}/api/self-check`, { + method: "POST", + headers: { + [DIAGNOSTICS_TOKEN_HEADER]: service.token, + origin: `http://127.0.0.1:${port}`, + }, + }); + assert.equal(checked.status, 200); + assert.equal( + checked.headers.get("access-control-allow-origin"), + `http://127.0.0.1:${port}`, + ); + assert.equal((await checked.json()).ok, true); + const stateAfterCheck = await fetch(`http://127.0.0.1:${port}/api/state`, { + headers: { + [DIAGNOSTICS_TOKEN_HEADER]: service.token, + origin: "null", + }, + }); + assert.equal(stateAfterCheck.status, 200); + assert.equal((await stateAfterCheck.json()).selfCheck.ok, true); + + const withBody = await fetch(`http://127.0.0.1:${port}/api/self-check`, { + method: "POST", + body: "{}", + headers: { + [DIAGNOSTICS_TOKEN_HEADER]: service.token, + origin: `http://127.0.0.1:${port}`, + }, + }); + assert.equal(withBody.status, 400); + + const forbiddenHost = await rawRequest(port, "/", { + headers: { host: `evil.example:${port}` }, + }); + assert.equal(forbiddenHost.status, 403); + + const localized = await fetch( + `http://127.0.0.1:${port}/?lang=zh-CN&theme=dark`, + ); + assert.equal(localized.status, 200); + assert.match(await localized.text(), //); + const localizedPolicy = localized.headers.get("content-security-policy"); + assert.notEqual(localizedPolicy, policy); + } finally { + await service.stop(); + } +}); + +test("a foreign listener fails with an actionable port-conflict error", async () => { + const port = await freePort(); + const blocker = createServer((_req, res) => res.end("blocked")); + await new Promise((resolve) => blocker.listen(port, "127.0.0.1", resolve)); + const service = startDiagnosticsService({ port }); + try { + await assert.rejects( + service.ready, + (error) => + error.code === "EADDRINUSE" && + new RegExp(`127\\.0\\.0\\.1:${port}`).test(error.message), + ); + } finally { + await service.stop(); + await new Promise((resolve) => blocker.close(resolve)); + } +}); diff --git a/packages/atomcode/test/errors.test.mjs b/packages/atomcode/test/errors.test.mjs new file mode 100644 index 0000000..6f6ed3e --- /dev/null +++ b/packages/atomcode/test/errors.test.mjs @@ -0,0 +1,98 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; + +import { + FAILURE, + annotateError, + classifyError, + isCredentialFailure, + isTransientFailure, + keptResponseHeaders, +} from "../errors.mjs"; + +test("classifyError separates credential, entitlement and generic 403s", () => { + assert.equal( + classifyError({ status: 403, message: "session token expired" }).category, + FAILURE.CREDENTIAL_FORBIDDEN, + ); + assert.equal( + classifyError({ status: 403, message: "CodingPlan quota exhausted" }).category, + FAILURE.ENTITLEMENT_FORBIDDEN, + ); + const generic = classifyError({ status: 403, message: "Forbidden" }); + assert.equal(generic.category, FAILURE.FORBIDDEN); + assert.equal(generic.refresh, false); + assert.equal(generic.signInExpired, false); +}); + +test("classifyError maps transport, HTTP, signing and account-change failures", () => { + assert.equal( + classifyError(new TypeError("fetch failed")).category, + FAILURE.NETWORK, + ); + assert.equal( + classifyError(Object.assign(new Error("aborted"), { name: "AbortError" })).category, + FAILURE.TIMEOUT, + ); + assert.equal(classifyError({ status: 401 }).category, FAILURE.UNAUTHORIZED); + assert.equal(classifyError({ status: 429 }).category, FAILURE.RATE_LIMIT); + assert.equal(classifyError({ status: 503 }).category, FAILURE.SERVER); + assert.equal( + classifyError(new Error("invalid X-AtomCode signature")).category, + FAILURE.SIGNING, + ); + assert.equal( + classifyError(new Error("client version requires upgrade")).category, + FAILURE.VERSION, + ); + const changed = classifyError(new Error("auth.toml changed accounts")); + assert.equal(changed.category, FAILURE.CLI_ACCOUNT_CHANGED); + assert.equal(changed.signInExpired, true); +}); + +test("failure predicates are conservative", () => { + assert.equal(isCredentialFailure({ status: 401 }), true); + assert.equal(isCredentialFailure({ status: 403, message: "invalid token" }), true); + assert.equal(isCredentialFailure({ status: 403, message: "usage limit" }), false); + assert.equal(isTransientFailure({ status: 500 }), true); + assert.equal(isTransientFailure({ status: 403 }), false); +}); + +test("annotateError fixes an incorrect expired mark and attaches status", () => { + const entitlement = annotateError( + Object.assign(new Error("quota exhausted"), { + status: 403, + signIn: "expired", + }), + ); + assert.equal(entitlement.category, FAILURE.ENTITLEMENT_FORBIDDEN); + assert.equal(entitlement.signIn, undefined); + + const unauthorized = annotateError(new Error("no")); + assert.equal(unauthorized.category, FAILURE.UNKNOWN); + + const credential = annotateError({ message: "invalid token", status: 403 }); + assert.equal(credential instanceof Error, true); + assert.equal(credential.signIn, "expired"); +}); + +test("403 entitlement responses are cloned with the kept sign-in header", async () => { + const original = Response.json( + { message: "quota exhausted" }, + { status: 403 }, + ); + const marked = keptResponseHeaders(original, { + category: FAILURE.ENTITLEMENT_FORBIDDEN, + }); + assert.notEqual(marked, original); + assert.equal(marked.headers.get("x-magpie-sign-in"), "kept"); + assert.deepEqual(await marked.json(), { message: "quota exhausted" }); + + const credential = new Response("{}", { status: 403 }); + assert.equal( + keptResponseHeaders(credential, { category: FAILURE.CREDENTIAL_FORBIDDEN }), + credential, + ); + const ordinary = new Response("{}", { status: 401 }); + assert.equal(keptResponseHeaders(ordinary, { category: FAILURE.UNAUTHORIZED }), ordinary); +}); diff --git a/packages/atomcode/test/i18n.test.mjs b/packages/atomcode/test/i18n.test.mjs new file mode 100644 index 0000000..a20f260 --- /dev/null +++ b/packages/atomcode/test/i18n.test.mjs @@ -0,0 +1,33 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; + +import { LOCALES, fill, resolveLocale, strings } from "../i18n.mjs"; + +test("zh and en expose the same keys and placeholders", () => { + const zh = strings("zh"); + const en = strings("en"); + assert.deepEqual(Object.keys(zh).sort(), Object.keys(en).sort()); + + for (const key of Object.keys(zh)) { + if (key === "locale") continue; + const placeholders = (value) => [...String(value).matchAll(/\{(\w+)\}/g)].map((match) => match[1]).sort(); + assert.deepEqual(placeholders(zh[key]), placeholders(en[key]), `placeholder mismatch for ${key}`); + } +}); + +test("plan-aware check-in copy uses locale-appropriate punctuation", () => { + assert.equal(fill(strings("en").checkinDoneWithPlan, { plan: "Lite" }), "The plan is still active; nothing to claim (Lite)"); + assert.equal(fill(strings("zh").checkinDoneWithPlan, { plan: "Lite" }), "套餐仍有效,无需重领(Lite)"); +}); + +test("fill leaves unknown placeholders visible", () => { + assert.equal(fill("{known}-{missing}", { known: "ok" }), "ok-{missing}"); +}); + +test("resolveLocale follows explicit option, Intl and environment", () => { + assert.deepEqual(LOCALES, ["zh", "en"]); + assert.equal(resolveLocale("zh-CN", {}, "en-US"), "zh"); + assert.equal(resolveLocale("auto", {}, "en-GB"), "en"); + assert.equal(resolveLocale("auto", { LANG: "zh_CN.UTF-8" }, "fr-FR"), "zh"); + assert.equal(resolveLocale("auto", { LANG: "C" }, "fr-FR"), "en"); +}); diff --git a/packages/atomcode/test/internal.test.mjs b/packages/atomcode/test/internal.test.mjs new file mode 100644 index 0000000..c73b7ba --- /dev/null +++ b/packages/atomcode/test/internal.test.mjs @@ -0,0 +1,134 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; + +import { + credentialsOf, + originOf, + readCappedResponseText, + redactText, + trustedServiceURL, + trustedURL, +} from "../internal.mjs"; + +/** + * 这两个校验函数是"地址不许乱跑"的统一收口点:模型地址、端点配置、请求目标 + * 都走同一套判定。用例钉住它的边界,改动时不会悄悄放宽。 + */ + +test("trustedURL:https + 白名单域名(含子域)被采纳", () => { + const domains = ["atomgit.com", "gitcode.com"]; + assert.equal(trustedURL("https://llm-api.atomgit.com/v1", { domains }), "https://llm-api.atomgit.com/v1"); + assert.equal(trustedURL("https://api.gitcode.com/api/v5", { domains }), "https://api.gitcode.com/api/v5"); + assert.equal(trustedURL("https://atomgit.com", { domains }), "https://atomgit.com"); + assert.equal(trustedURL(" https://acs.atomgit.com ", { domains }), "https://acs.atomgit.com"); +}); + +test("trustedURL:明文、内嵌凭证、相近域名、非法输入一律拒绝", () => { + const domains = ["atomgit.com", "gitcode.com"]; + assert.equal(trustedURL("http://acs.atomgit.com", { domains }), undefined); + assert.equal(trustedURL("https://user:pass@acs.atomgit.com", { domains }), undefined); + assert.equal(trustedURL("https://evil.example", { domains }), undefined); + assert.equal(trustedURL("https://evil-atomgit.com", { domains }), undefined); + assert.equal(trustedURL("https://acs.atomgit.com.evil.example", { domains }), undefined); + assert.equal(trustedURL("", { domains }), undefined); + assert.equal(trustedURL(undefined, { domains }), undefined); + assert.equal(trustedURL(123, { domains }), undefined); + assert.equal(trustedURL("https://acs.atomgit.com", {}), undefined, "没有白名单时不得放行"); + assert.equal( + trustedURL("https://acs.atomgit.com:8443", { domains }), + undefined, + "非 443 端口必须拒绝", + ); +}); + +test("trustedURL:基础端点默认拒绝 query/hash,登录跳转可显式放行", () => { + const domains = ["atomgit.com"]; + assert.equal(trustedURL("https://atomgit.com/login?state=1", { domains }), undefined); + assert.equal( + trustedURL("https://atomgit.com/login?state=1", { domains, allowSearch: true }), + "https://atomgit.com/login?state=1", + ); +}); + +test("trustedServiceURL:合法覆盖被采纳", () => { + assert.equal( + trustedServiceURL("https://api.gitcode.com/api/v6", { fallback: "https://api.gitcode.com/api/v5" }), + "https://api.gitcode.com/api/v6", + ); +}); + +test("trustedServiceURL:非法值回退默认端点并上报", () => { + const rejected = []; + const fallback = "https://acs.atomgit.com"; + const out = trustedServiceURL("https://evil.example", { fallback, onReject: (v) => rejected.push(v) }); + assert.equal(out, fallback); + assert.deepEqual(rejected, ["https://evil.example"]); +}); + +test("trustedServiceURL:未配置时不当作被拒,直接给默认值", () => { + const rejected = []; + const fallback = "https://acs.atomgit.com"; + assert.equal(trustedServiceURL(undefined, { fallback, onReject: (v) => rejected.push(v) }), fallback); + assert.equal(trustedServiceURL("", { fallback, onReject: (v) => rejected.push(v) }), fallback); + assert.deepEqual(rejected, []); +}); + +test("trustedServiceURL:上报回调自己抛错也不影响返回值", () => { + const out = trustedServiceURL("https://evil.example", { + fallback: "https://acs.atomgit.com", + onReject: () => { + throw new Error("logger exploded"); + }, + }); + assert.equal(out, "https://acs.atomgit.com"); +}); + +test("originOf:协议与端口进入比较,非法输入 → undefined", () => { + assert.equal(originOf("https://llm-api.atomgit.com/v1/chat/completions"), "https://llm-api.atomgit.com"); + assert.notEqual( + originOf("http://llm-api.atomgit.com/v1"), + originOf("https://llm-api.atomgit.com/v1"), + "明文降级必须与 https 判定不同", + ); + assert.notEqual( + originOf("https://llm-api.atomgit.com:8443/v1"), + originOf("https://llm-api.atomgit.com/v1"), + "不同端口是不同来源", + ); + assert.equal(originOf("not a url"), undefined); + assert.equal(originOf(undefined), undefined); +}); + +test("credentialsOf:缺少 access 时无法签名,uid 统一转字符串", () => { + assert.equal(credentialsOf({}), undefined); + assert.equal(credentialsOf({ access: "" }), undefined); + assert.equal(credentialsOf(null), undefined); + assert.equal(credentialsOf({ access: "tok", uid: 42 }).uid, "42"); +}); + +test("redactText:令牌、邮箱和长密钥都不会进入日志", () => { + const secret = "a".repeat(64); + const text = redactText( + `access_token=access-secret refresh_token: refresh-secret Bearer bearer-secret alice@example.com ${secret}`, + ); + assert.match(text, /access_token=\[redacted\]/); + assert.match(text, /refresh_token=\[redacted\]/); + assert.doesNotMatch(text, /access-secret|refresh-secret|bearer-secret|alice@example\.com/); + assert.doesNotMatch(text, new RegExp(secret)); +}); + +test("readCappedResponseText:流式读取超过上限时立即取消", async () => { + let pulls = 0; + const chunk = new Uint8Array(64 * 1024); + const stream = new ReadableStream({ + pull(controller) { + pulls += 1; + controller.enqueue(chunk); + }, + }); + await assert.rejects( + () => readCappedResponseText(new Response(stream), { label: "metadata" }), + /metadata exceeds 1 MiB/, + ); + assert.ok(pulls <= 30, `read too far: ${pulls} chunks`); +}); diff --git a/packages/atomcode/test/models.test.mjs b/packages/atomcode/test/models.test.mjs new file mode 100644 index 0000000..ebce282 --- /dev/null +++ b/packages/atomcode/test/models.test.mjs @@ -0,0 +1,182 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; + +import { + DEFAULT_BASE_URL, + DEFAULT_CONTEXT, + DEFAULT_OUTPUT, + normalizeCodingPlanModel, + sanitizeModelKey, + toConfigModel, + toProviderModel, + trustedModelBaseURL, +} from "../models.mjs"; + +/** + * `base_url` 来自上游 `models-v2`(服务端可控数据)。这些用例钉住白名单: + * 只有 https、无内嵌凭证、且落在 atomgit 域上的地址才被采纳,其余一律回退 + * 官方网关——否则上游响应就能决定这个账号的 bearer token 发往哪里。 + */ + +test("trustedModelBaseURL:只采纳 loader 实际允许的网关 origin", () => { + assert.equal(trustedModelBaseURL("https://llm-api.atomgit.com/v1"), "https://llm-api.atomgit.com/v1"); + assert.equal(trustedModelBaseURL("https://raw.atomgit.com/x"), undefined); + assert.equal(trustedModelBaseURL("https://atomgit.com"), undefined); + assert.equal(trustedModelBaseURL("https://llm-api.atomgit.com:8443/v1"), undefined); + assert.equal(trustedModelBaseURL(" https://llm-api.atomgit.com/v1 "), "https://llm-api.atomgit.com/v1"); +}); + +test("trustedModelBaseURL:域名不在白名单 → 拒绝", () => { + assert.equal(trustedModelBaseURL("https://evil.example/v1"), undefined); + assert.equal(trustedModelBaseURL("https://evil-atomgit.com/v1"), undefined, "相近域名不得蒙混过关"); + assert.equal( + trustedModelBaseURL("https://llm-api.atomgit.com.evil.example/v1"), + undefined, + "把白名单域名当前缀同样不行", + ); +}); + +test("trustedModelBaseURL:明文降级与内嵌凭证 → 拒绝", () => { + assert.equal(trustedModelBaseURL("http://llm-api.atomgit.com/v1"), undefined); + assert.equal(trustedModelBaseURL("https://user:pass@llm-api.atomgit.com/v1"), undefined); +}); + +test("trustedModelBaseURL:非 URL 与非法类型 → 拒绝", () => { + assert.equal(trustedModelBaseURL("not a url"), undefined); + assert.equal(trustedModelBaseURL(""), undefined); + assert.equal(trustedModelBaseURL(" "), undefined); + assert.equal(trustedModelBaseURL(undefined), undefined); + assert.equal(trustedModelBaseURL(null), undefined); + assert.equal(trustedModelBaseURL(42), undefined); + assert.equal(trustedModelBaseURL({}), undefined); +}); + +test("normalizeCodingPlanModel:非法 base_url 被丢弃并上报原始值", () => { + const rejected = []; + const model = normalizeCodingPlanModel( + { display_model_name: "m1", base_url: "https://evil.example/v1" }, + { onReject: (value) => rejected.push(value) }, + ); + assert.equal(model.baseURL, undefined, "非法地址不得进入模型描述"); + assert.deepEqual(rejected, ["https://evil.example/v1"]); +}); + +test("normalizeCodingPlanModel:合法 base_url 原样保留,且不触发上报", () => { + let rejected = 0; + const model = normalizeCodingPlanModel( + { display_model_name: "m1", base_url: "https://llm-api.atomgit.com/v1" }, + { + onReject: () => { + rejected += 1; + }, + }, + ); + assert.equal(model.baseURL, "https://llm-api.atomgit.com/v1"); + assert.equal(rejected, 0); +}); + +test("normalizeCodingPlanModel:没有 base_url 时静默,不当作被拒", () => { + let rejected = 0; + const model = normalizeCodingPlanModel( + { display_model_name: "m1" }, + { + onReject: () => { + rejected += 1; + }, + }, + ); + assert.equal(model.baseURL, undefined); + assert.equal(rejected, 0); +}); + +test("normalizeCodingPlanModel:上报回调自己抛错也不影响模型", () => { + const model = normalizeCodingPlanModel( + { display_model_name: "m1", base_url: "https://evil.example/v1" }, + { + onReject: () => { + throw new Error("logger exploded"); + }, + }, + ); + assert.equal(model.id, "m1"); + assert.equal(model.baseURL, undefined); +}); + +test("toProviderModel:模型没有可用 base_url 时落到调用方给的官方网关", () => { + const model = normalizeCodingPlanModel({ display_model_name: "m1", base_url: "https://evil.example" }); + const providerModel = toProviderModel(model, "atomcode", { baseURL: DEFAULT_BASE_URL }); + assert.equal(providerModel.api.url, DEFAULT_BASE_URL); + assert.equal(providerModel.api.id, "m1"); +}); + +test("reasoning variants carry the request option agents merge", () => { + const m = normalizeCodingPlanModel({ + display_model_name: "qwen3.8-27b", + context_window: 262144, + reasoning_effort_levels: ["low", "medium", "xhigh"], + }); + assert.deepEqual(toConfigModel(m).variants, { + low: { reasoningEffort: "low" }, + medium: { reasoningEffort: "medium" }, + xhigh: { reasoningEffort: "xhigh" }, + }); + assert.deepEqual(toProviderModel(m, "atomcode").variants, { + low: { reasoningEffort: "low" }, + medium: { reasoningEffort: "medium" }, + xhigh: { reasoningEffort: "xhigh" }, + }); +}); + +test("model output limit honours upstream declarations before the plugin fallback", () => { + const declared = normalizeCodingPlanModel( + { display_model_name: "declared", max_output_tokens: 64000 }, + { output: 32768 }, + ); + const fallback = normalizeCodingPlanModel({ display_model_name: "fallback" }, { output: 32768 }); + assert.equal(declared.output, 64000); + assert.equal(fallback.output, 32768); +}); + +test("catalog rows tolerate malformed optional fields", () => { + assert.equal(normalizeCodingPlanModel(), null); + assert.equal(normalizeCodingPlanModel({ display_model_name: 42 }), null); + + const model = normalizeCodingPlanModel({ + display_model_name: " unsafe/model ", + reasoning_effort_levels: [" low ", "", null, 7, "high"], + context_window: "not-a-number", + max_output_tokens: null, + max_completion_tokens: null, + output_token_limit: "invalid", + base_url: 42, + supports_vision: false, + type: "", + }); + assert.deepEqual(model, { + id: "unsafe/model", + key: "unsafe_model", + context: DEFAULT_CONTEXT, + output: DEFAULT_OUTPUT, + levels: ["low", "high"], + vision: false, + type: "openai", + baseURL: undefined, + }); +}); + +test("model factories provide stable defaults for empty rows", () => { + assert.equal(sanitizeModelKey(), ""); + const configModel = toConfigModel(); + assert.equal(configModel.name, undefined); + assert.equal(configModel.reasoning, false); + assert.equal(configModel.limit.context, DEFAULT_CONTEXT); + assert.equal(configModel.limit.output, DEFAULT_OUTPUT); + assert.equal(Object.hasOwn(configModel, "variants"), false); + + const providerModel = toProviderModel(); + assert.equal(providerModel.id, undefined); + assert.equal(providerModel.name, undefined); + assert.equal(providerModel.api.url, DEFAULT_BASE_URL); + assert.equal(providerModel.capabilities.reasoning, false); + assert.deepEqual(providerModel.variants, {}); +}); diff --git a/packages/atomcode/test/oauth.test.mjs b/packages/atomcode/test/oauth.test.mjs new file mode 100644 index 0000000..a60caa7 --- /dev/null +++ b/packages/atomcode/test/oauth.test.mjs @@ -0,0 +1,114 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; + +import { + checkLogin, + refreshTokens, + startLogin, + stripForceLogin, + tokenFor, +} from "../oauth.mjs"; + +function sequenceFetch(responses) { + const calls = []; + const fetchImpl = async (url, init = {}) => { + calls.push({ url, init }); + const next = responses[Math.min(calls.length - 1, responses.length - 1)]; + if (next.error) throw next.error; + return new Response(next.body ?? "", { status: next.status ?? 200 }); + }; + return { fetchImpl, calls }; +} + +test("startLogin strips force_login and validates the returned URL", async () => { + const { fetchImpl, calls } = sequenceFetch([ + { + body: JSON.stringify({ + login_url: "https://atomgit.com/login?force_login=true&next=%2Fhome", + state: "state-1", + }), + }, + ]); + const result = await startLogin("https://acs.atomgit.com", { fetchImpl }); + + assert.equal(result.loginUrl, "https://atomgit.com/login?next=%2Fhome"); + assert.equal(result.state, "state-1"); + assert.equal(calls[0].init.redirect, "error"); +}); + +test("startLogin refuses a broker-supplied login URL outside AtomGit", async () => { + const { fetchImpl } = sequenceFetch([ + { body: JSON.stringify({ login_url: "https://evil.example/login", state: "state-1" }) }, + ]); + + await assert.rejects(() => startLogin("https://acs.atomgit.com", { fetchImpl }), /untrusted login URL/); +}); + +test("checkLogin encodes state and only accepts a strict true", async () => { + const { fetchImpl, calls } = sequenceFetch([{ body: JSON.stringify({ valid: true }) }]); + assert.equal(await checkLogin("https://acs.atomgit.com", "a/b c", { fetchImpl }), true); + assert.equal(new URL(calls[0].url).searchParams.get("state"), "a/b c"); +}); + +test("tokenFor validates and maps the credential response", async () => { + const { fetchImpl } = sequenceFetch([ + { + body: JSON.stringify({ + access_token: "access", + refresh_token: "refresh", + expires_in: 3600, + token_type: "Bearer", + user: { id: 42, email: "u@example.com" }, + }), + }, + ]); + const token = await tokenFor("https://acs.atomgit.com", "state", { fetchImpl }); + assert.equal(token.accessToken, "access"); + assert.equal(token.refreshToken, "refresh"); + assert.equal(token.expiresIn, 3600); + assert.equal(token.user.id, 42); +}); + +test("refreshTokens keeps the old refresh token when upstream does not rotate", async () => { + const { fetchImpl, calls } = sequenceFetch([ + { body: JSON.stringify({ access_token: "new-access", expires_in: 7200 }) }, + ]); + const token = await refreshTokens("https://acs.atomgit.com", "old-refresh", { fetchImpl }); + + assert.equal(token.accessToken, "new-access"); + assert.equal(token.refreshToken, "old-refresh"); + assert.equal(token.expiresIn, 7200); + assert.equal(JSON.parse(calls[0].init.body).refresh_token, "old-refresh"); + assert.equal(calls[0].init.redirect, "error"); +}); + +test("refreshTokens marks only credential failures as expired", async () => { + for (const status of [400, 401, 403]) { + const { fetchImpl } = sequenceFetch([{ status, body: "{}" }]); + await assert.rejects( + () => refreshTokens("https://acs.atomgit.com", "refresh", { fetchImpl }), + (error) => error.signIn === "expired", + ); + } + + const { fetchImpl } = sequenceFetch([{ status: 503, body: "unavailable" }]); + await assert.rejects( + () => refreshTokens("https://acs.atomgit.com", "refresh", { fetchImpl }), + (error) => error.status === 503 && error.signIn === undefined, + ); +}); + +test("OAuth responses are bounded before JSON parsing", async () => { + const chunk = new Uint8Array(64 * 1024); + const stream = new ReadableStream({ + pull(controller) { + controller.enqueue(chunk); + }, + }); + const { fetchImpl } = sequenceFetch([{ body: stream }]); + await assert.rejects(() => checkLogin("https://acs.atomgit.com", "state", { fetchImpl }), /exceeds 1 MiB/); +}); + +test("stripForceLogin tolerates malformed URLs with the legacy fallback", () => { + assert.equal(stripForceLogin("not a url&force_login=true"), "not a url"); +}); diff --git a/packages/atomcode/test/plugin.test.mjs b/packages/atomcode/test/plugin.test.mjs new file mode 100644 index 0000000..115e786 --- /dev/null +++ b/packages/atomcode/test/plugin.test.mjs @@ -0,0 +1,1468 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { mkdir, mkdtemp, readFile, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; + +import * as entry from "../index.mjs"; +import { AtomCodePlugin } from "../index.mjs"; +import { signAtomGitRequest } from "../sign.mjs"; + +/** + * checkin 钩子的四条路径。 + * + * 插件的 CodingPlan 调用走全局 fetch(与 sensenova 模板同款测试法), + * 所以这里 stub globalThis.fetch 按 URL 分流:status-v2 / claim-v2 / + * raw.atomgit.com(版本探测)各自给脚本。 + */ + +/** status-v2 的有效套餐响应(登录态健康、无需重领)。 */ +const VALID_STATUS = { + codingplan_free: { + plan_name: "CodingPlan Lite-体验版", + plan_type: "Lite-beta", + status: 1, + remaining_days: 4, + expires_at: "2099-10-20", + }, + current_usage: { usage_percent: 0, window_hours: 5, seconds_until_reset: 1000 }, + rate_limit_windows: [{ window_size_seconds: 18000, call_limit: 200, calls_used: 0, seconds_until_reset: 1000 }], +}; + +const MANIFEST = '[workspace.package]\nversion = "5.2.3"\nedition = "2021"\n'; + +function cliAuthFile({ + access = "cli-access", + refresh = "cli-refresh", + createdAt = 1800000000, + expiresIn = 3600, + id = "42", + email, +} = {}) { + return [ + `access_token = ${JSON.stringify(access)}`, + ...(refresh ? [`refresh_token = ${JSON.stringify(refresh)}`] : []), + 'token_type = "Bearer"', + `expires_in = ${expiresIn}`, + `created_at = ${createdAt}`, + "", + "[user]", + `id = ${JSON.stringify(String(id))}`, + 'username = "alice"', + ...(email ? [`email = ${JSON.stringify(email)}`] : []), + "", + ].join("\n"); +} + +/** broker 回的登录地址,带 force_login(插件应把它摘掉)。 */ +const LOGIN_URL = "https://atomgit.com/login?force_login=true"; + +/** + * 安装一个按 URL 分流的全局 fetch stub,返回 { calls, restore }。 + * claimResponses 是逐次出队的 {status?, body};statusBody 为 null 时 status-v2 回 500; + * modelsBody 为 null 时 models-v2 回空列表。calls 里带上 headers,便于断言凭证去向。 + */ +function stubFetch({ + statusBody, + statusStatus, + statusResponses = [], + claimResponses = [], + modelsBody = null, + modelsResponses = [], + modelsStatus = 200, + refreshResponses = [], + chatResponses = [], + authCheckResponses = [], + authTokenResponses = [], + authLoginResponses = [], +}) { + const calls = []; + const claimQueue = [...claimResponses]; + const refreshQueue = [...refreshResponses]; + const statusQueue = [...statusResponses]; + const chatQueue = [...chatResponses]; + const modelsQueue = [...modelsResponses]; + const authCheckQueue = [...authCheckResponses]; + const authTokenQueue = [...authTokenResponses]; + const authLoginQueue = [...authLoginResponses]; + const real = globalThis.fetch; + globalThis.fetch = async (input, init = {}) => { + const url = String(typeof input === "string" ? input : input.url); + const headers = new Headers(init.headers ?? (input instanceof Request ? input.headers : undefined)); + calls.push({ + url, + method: init.method ?? "GET", + headers, + redirect: init.redirect, + body: init.body, + }); + if (url.includes("raw.atomgit.com")) return new Response(MANIFEST, { status: 200 }); + if (url.includes("status-v2")) { + if (statusQueue.length) { + const next = statusQueue.shift(); + return new Response(next.body, { status: next.status ?? 200 }); + } + const status = statusStatus ?? (statusBody === null ? 500 : 200); + return new Response(statusBody === null ? "boom" : JSON.stringify(statusBody), { + status, + }); + } + if (url.includes("models-v2")) { + if (modelsQueue.length) { + const next = modelsQueue.shift(); + return new Response(next.body, { status: next.status ?? 200 }); + } + return new Response(modelsBody === null ? "[]" : JSON.stringify(modelsBody), { status: modelsStatus }); + } + if (url.includes("oauth/refresh")) { + const next = refreshQueue.shift() ?? { status: 500, body: "{}" }; + return new Response(next.body, { status: next.status ?? 200 }); + } + if (url.includes("auth/login")) { + if (authLoginQueue.length) { + const next = authLoginQueue.shift(); + return new Response(next.body, { status: next.status ?? 200 }); + } + return new Response(JSON.stringify({ login_url: LOGIN_URL, state: "state-1" }), { status: 200 }); + } + if (url.includes("auth/check")) { + const next = authCheckQueue.shift() ?? { body: JSON.stringify({ valid: false }) }; + return new Response(next.body, { status: next.status ?? 200 }); + } + if (url.includes("auth/token")) { + const next = authTokenQueue.shift() ?? { status: 500, body: "{}" }; + return new Response(next.body, { status: next.status ?? 200 }); + } + if (url.includes("claim-v2")) { + const next = claimQueue.shift() ?? { status: 400, body: JSON.stringify({ success: false, message: "no" }) }; + return new Response(next.body, { status: next.status ?? 200 }); + } + if (url.includes("chat/completions") && chatQueue.length) { + const next = chatQueue.shift(); + return new Response(next.body ?? "", { status: next.status ?? 200 }); + } + return new Response("{}", { status: 404 }); + }; + return { + calls, + restore() { + globalThis.fetch = real; + }, + }; +} + +const AUTH = { type: "oauth", access: "tok", uid: "u1" }; + +test("entry exports only the plugin function for OpenCode compatibility", () => { + assert.deepEqual(Object.keys(entry), ["AtomCodePlugin"]); +}); + +test("browser OAuth:授权失败返回可读错误,不泄露上游正文", async () => { + const stub = stubFetch({ + statusBody: VALID_STATUS, + authLoginResponses: [{ status: 502, body: "sensitive upstream body" }], + }); + try { + const plugin = await AtomCodePlugin({}, { autoVersion: false }); + await assert.rejects( + () => plugin.auth.methods[0].authorize(), + (error) => + /Sign-in failed/i.test(error.message) && + !error.message.includes("sensitive upstream body"), + ); + } finally { + stub.restore(); + } +}); + +test("browser OAuth:check → token → success,并声明浏览器来源", async () => { + const stub = stubFetch({ + statusBody: VALID_STATUS, + authCheckResponses: [{ body: JSON.stringify({ valid: true }) }], + authTokenResponses: [ + { + body: JSON.stringify({ + access_token: "browser-access", + refresh_token: "browser-refresh", + expires_in: 0, + user: { id: 7, username: "bob", name: "Bob" }, + }), + }, + ], + }); + try { + const plugin = await AtomCodePlugin( + {}, + { autoVersion: false, autoClaim: false, locale: "en" }, + ); + const flow = await plugin.auth.methods[0].authorize(); + const result = await flow.callback(); + assert.equal(result.type, "success"); + assert.equal(result.source, "atomcode-browser"); + assert.equal(result.access, "browser-access"); + assert.equal(result.accountId, "bob"); + assert.equal(result.email, undefined); + assert.ok(result.expires > Date.now() + 6 * 24 * 3600_000); + } finally { + stub.restore(); + } +}, { timeout: 10_000 }); + +async function checkinWith(setup, getAuth = async () => AUTH) { + const stub = stubFetch(setup); + try { + const plugin = await AtomCodePlugin({}, {}); + return { result: await plugin.auth.checkin(getAuth), calls: stub.calls }; + } finally { + stub.restore(); + } +} + +test("checkin:套餐仍有效 → done,不打领取接口", async () => { + const { result, calls } = await checkinWith({ statusBody: VALID_STATUS }); + assert.equal(result.outcome, "done"); + assert.match(result.message, /Lite/); + assert.equal(calls.filter((c) => c.url.includes("claim-v2")).length, 0, "有效期内不应打领取接口"); +}); + +test("checkin:套餐过期 → 重领成功 → claimed,带套餐名", async () => { + const expired = { + ...VALID_STATUS, + codingplan_free: { ...VALID_STATUS.codingplan_free, remaining_days: 0, expires_at: "2020-01-01" }, + }; + const { result } = await checkinWith({ + statusBody: expired, + claimResponses: [ + { body: JSON.stringify({ success: true, duplicate: false, plan_name: "CodingPlan Lite-体验版", plan_type: "Lite" }) }, + ], + }); + assert.equal(result.outcome, "claimed"); + assert.match(result.message, /CodingPlan Lite-体验版/); +}); + +test("checkin:duplicate(本来就持有)→ done 而不是 claimed", async () => { + const expired = { + ...VALID_STATUS, + codingplan_free: { ...VALID_STATUS.codingplan_free, remaining_days: 0, expires_at: "2020-01-01" }, + }; + const { result } = await checkinWith({ + statusBody: expired, + claimResponses: [{ body: JSON.stringify({ success: false, duplicate: true, plan_type: "Lite" }) }], + }); + assert.equal(result.outcome, "done"); +}); + +test("checkin:名额耗尽 → ineligible,透出上游 message", async () => { + const expired = { + ...VALID_STATUS, + codingplan_free: { ...VALID_STATUS.codingplan_free, remaining_days: 0, expires_at: "2020-01-01" }, + }; + const full = { status: 400, body: JSON.stringify({ success: false, message: "全平台日限额已满" }) }; + const { result } = await checkinWith({ + statusBody: expired, + claimResponses: [full, full, full], + }); + assert.equal(result.outcome, "ineligible"); + assert.match(result.message, /日限额|no tier/); +}); + +test("checkin:未登录 → failed 提示登录,CodingPlan 请求一个都不发", async () => { + // 插件构造时的版本探测会先打一次 raw.atomgit.com(正常),这里只看 CodingPlan。 + const { result, calls } = await checkinWith({ statusBody: VALID_STATUS }, async () => undefined); + assert.equal(result.outcome, "failed"); + assert.equal(calls.filter((c) => c.url.includes("gitcode") || c.url.includes("coding-plan")).length, 0); +}); + +test("checkin:status 500(网络/服务异常)→ 仍尝试领取,由领取结果说话", async () => { + const { result } = await checkinWith({ + statusBody: null, + claimResponses: [{ body: JSON.stringify({ success: true, duplicate: false, plan_name: "CodingPlan Lite" }) }], + }); + assert.equal(result.outcome, "claimed"); +}); + +test("checkin:英文 locale 的套餐名使用英文括号", async () => { + const stub = stubFetch({ statusBody: VALID_STATUS }); + try { + const plugin = await AtomCodePlugin({}, { locale: "en", autoVersion: false }); + const result = await plugin.auth.checkin(async () => AUTH); + assert.equal(result.message, "The plan is still active; nothing to claim (CodingPlan Lite-体验版)"); + assert.doesNotMatch(result.message, /(/); + } finally { + stub.restore(); + } +}); + +test("config:seed 模型、用户覆盖和 provider 元数据正确合并", async () => { + const plugin = await AtomCodePlugin({}, { autoVersion: false }); + const cfg = { + provider: { + atomcode: { + models: { custom: { name: "Custom" } }, + maxConcurrency: 2, + }, + }, + }; + await plugin.config(cfg); + + assert.equal(cfg.provider.atomcode.name, "ATOMCODE"); + assert.equal(cfg.provider.atomcode.npm, "@ai-sdk/openai-compatible"); + assert.equal(cfg.provider.atomcode.api, GATEWAY); + assert.ok(cfg.provider.atomcode.models["qwen3.8-27b"]); + assert.deepEqual(cfg.provider.atomcode.models.custom, { name: "Custom" }); + assert.equal(cfg.provider.atomcode.maxConcurrency, 2); +}); + +/** 网关根地址(与 internal.mjs 的 DEFAULT_GATEWAY_BASE_URL 一致)。 */ +const GATEWAY = "https://llm-api.atomgit.com/v1"; + +test("provider.models:上游给的自定义 base_url 不在白名单 → 退回官方网关", async () => { + const stub = stubFetch({ + statusBody: VALID_STATUS, + modelsBody: [ + { display_model_name: "qwen3.8-27b", context_window: 262144, base_url: "https://evil.example/v1" }, + { display_model_name: "glm5.3-flash", context_window: 512000, base_url: "https://raw.atomgit.com/v1" }, + ], + }); + try { + const plugin = await AtomCodePlugin({}, { locale: "en", autoVersion: false }); + const models = await plugin.provider.models({}, { auth: AUTH }); + assert.equal(models["qwen3.8-27b"].api.url, GATEWAY, "非法地址必须被换成官方网关"); + assert.equal(models["glm5.3-flash"].api.url, GATEWAY, "其他 atomgit 子域也必须退回网关"); + } finally { + stub.restore(); + } +}); + +test("provider.models:sanitize 后 key 冲突时保留两个模型", async () => { + const stub = stubFetch({ + statusBody: VALID_STATUS, + modelsBody: [ + { display_model_name: "model/a", context_window: 1000 }, + { display_model_name: "model_a", context_window: 2000 }, + ], + }); + try { + const plugin = await AtomCodePlugin({}, { autoVersion: false }); + const models = await plugin.provider.models({}, { auth: AUTH }); + assert.equal(models["model_a"].api.id, "model/a"); + assert.equal(models["model_a_2"].api.id, "model_a"); + assert.equal(models["model_a_2"].limit.context, 2000); + } finally { + stub.restore(); + } +}); + +test("provider.models:特殊模型名不会改写结果对象原型", async () => { + const stub = stubFetch({ + statusBody: VALID_STATUS, + modelsBody: [ + { display_model_name: "__proto__", context_window: 1000 }, + { display_model_name: "constructor", context_window: 2000 }, + ], + }); + try { + const plugin = await AtomCodePlugin({}, { autoVersion: false }); + const models = await plugin.provider.models({}, { auth: AUTH }); + assert.equal(Object.getPrototypeOf(models), null); + assert.equal(Object.hasOwn(models, "__proto__"), true); + assert.equal(models.__proto__.api.id, "__proto__"); + assert.equal(models.constructor.api.id, "constructor"); + } finally { + stub.restore(); + } +}); + +test("provider.models:目录读取失败时返回带 fallback 标记的内置列表", async () => { + const stub = stubFetch({ statusBody: null }); + try { + const plugin = await AtomCodePlugin({}, { autoVersion: false }); + const models = await plugin.provider.models({}, { auth: AUTH }); + assert.equal(models[Symbol.for("magpie.fellBack")], true); + assert.ok(models["qwen3.8-27b"]); + } finally { + stub.restore(); + } +}); + +test("provider.models:401 让账号进入重新登录状态", async () => { + const stub = stubFetch({ statusBody: { error: "expired" }, statusStatus: 401 }); + try { + const plugin = await AtomCodePlugin({}, { autoVersion: false }); + await assert.rejects( + () => plugin.provider.models({}, { auth: AUTH }), + (error) => error.signIn === "expired", + ); + } finally { + stub.restore(); + } +}); + +test("provider.models:401 会续期并重新读取目录", async () => { + const stub = stubFetch({ + statusResponses: [ + { status: 401, body: "{}" }, + { status: 200, body: JSON.stringify(VALID_STATUS) }, + ], + modelsBody: [{ display_model_name: "qwen3.8-27b", context_window: 262144 }], + refreshResponses: [ + { + body: JSON.stringify({ + access_token: "models-retry-access", + refresh_token: "models-retry-refresh", + expires_in: 3600, + }), + }, + ], + }); + try { + const plugin = await AtomCodePlugin({}, { autoVersion: false }); + const models = await plugin.provider.models( + {}, + { + auth: { + ...AUTH, + refresh: "models-old-refresh", + expires: Date.now() + 3600_000, + }, + }, + ); + assert.ok(models["qwen3.8-27b"]); + assert.equal(stub.calls.filter((call) => call.url.includes("oauth/refresh")).length, 1); + } finally { + stub.restore(); + } +}); + +test("provider.models:空目录会触发一次领取并重新读取模型", async () => { + const expired = { + ...VALID_STATUS, + codingplan_free: { + ...VALID_STATUS.codingplan_free, + remaining_days: 0, + expires_at: "2020-01-01", + }, + }; + const stub = stubFetch({ + statusResponses: [ + { status: 200, body: JSON.stringify(expired) }, + { status: 200, body: JSON.stringify(expired) }, + { status: 200, body: JSON.stringify(expired) }, + ], + modelsResponses: [ + { status: 200, body: "[]" }, + { + status: 200, + body: JSON.stringify([ + { display_model_name: "deepseek-flash", context_window: 1000000 }, + ]), + }, + ], + claimResponses: [ + { + status: 200, + body: JSON.stringify({ + success: true, + duplicate: false, + plan_name: "CodingPlan Lite", + plan_type: "Lite", + }), + }, + ], + }); + try { + const plugin = await AtomCodePlugin({}, { autoVersion: false }); + const models = await plugin.provider.models({}, { auth: AUTH }); + assert.ok(models["deepseek-flash"]); + assert.equal(stub.calls.filter((call) => call.url.includes("claim-v2")).length, 1); + } finally { + stub.restore(); + } +}); + +test("loader:发往网关的请求照常带凭证与签名", async () => { + const stub = stubFetch({ statusBody: VALID_STATUS }); + try { + const plugin = await AtomCodePlugin({}, { autoVersion: false }); + const { fetch: patched } = await plugin.auth.loader(async () => AUTH); + await patched(`${GATEWAY}/chat/completions`, { method: "POST", body: JSON.stringify({ model: "m" }) }); + const call = stub.calls.find((c) => c.url.includes("chat/completions")); + assert.ok(call, "官方网关的请求应当发出"); + assert.equal(call.headers.get("authorization"), "Bearer tok"); + assert.match(call.headers.get("x-atomcode-sig") ?? "", /^v1:[0-9a-f]{64}$/); + assert.equal(call.headers.get("user-agent"), "atomcode/5.2.3"); + assert.equal(call.redirect, "error"); + } finally { + stub.restore(); + } +}); + +test("loader:校验后冻结目标字符串,URL 在取凭证期间被改也不能换目的地", async () => { + const stub = stubFetch({ statusBody: VALID_STATUS }); + try { + const plugin = await AtomCodePlugin({}, { autoVersion: false }); + const target = new URL(`${GATEWAY}/chat/completions`); + const { fetch: patched } = await plugin.auth.loader(async () => { + target.hostname = "evil.example"; + return AUTH; + }); + await patched(target, { method: "POST", body: "{}" }); + assert.equal(stub.calls.filter((call) => call.url.includes("evil.example")).length, 0); + assert.ok(stub.calls.some((call) => call.url.includes("llm-api.atomgit.com"))); + } finally { + stub.restore(); + } +}); + +test("loader:流式请求补 include_usage,并按最终字节签名", async () => { + const stub = stubFetch({ statusBody: VALID_STATUS }); + try { + const plugin = await AtomCodePlugin({}, { autoVersion: false }); + const { fetch: patched } = await plugin.auth.loader(async () => AUTH); + const original = JSON.stringify({ model: "m", stream: true, messages: [] }); + await patched(`${GATEWAY}/chat/completions`, { method: "POST", body: original }); + const call = stub.calls.find((entry) => entry.url.includes("chat/completions")); + const sent = JSON.parse(call.body); + assert.equal(sent.stream_options.include_usage, true); + const expected = signAtomGitRequest({ + method: "POST", + path: "/v1/chat/completions", + body: call.body, + oauthToken: AUTH.access, + userId: AUTH.uid, + clientVersion: "5.2.3", + timestamp: Number(call.headers.get("x-atomcode-ts")), + nonce: call.headers.get("x-atomcode-nonce"), + }); + assert.equal(call.headers.get("x-atomcode-sig"), expected["X-AtomCode-Sig"]); + } finally { + stub.restore(); + } +}); + +test("loader:显式 include_usage=false 和不可重放 body 不被静默改写", async () => { + const stub = stubFetch({ statusBody: VALID_STATUS }); + try { + const plugin = await AtomCodePlugin({}, { autoVersion: false }); + const { fetch: patched } = await plugin.auth.loader(async () => AUTH); + const explicit = JSON.stringify({ stream: true, stream_options: { include_usage: false } }); + await patched(`${GATEWAY}/chat/completions`, { method: "POST", body: explicit }); + assert.equal( + stub.calls.find((entry) => entry.url.includes("chat/completions")).body, + explicit, + ); + await assert.rejects( + () => patched(`${GATEWAY}/chat/completions`, { + method: "POST", + body: new ReadableStream(), + duplex: "half", + }), + /unsupported request body/i, + ); + } finally { + stub.restore(); + } +}); + +test("loader:非网关目标的请求被拦下,一个请求都不发出", async () => { + const stub = stubFetch({ statusBody: VALID_STATUS }); + try { + const plugin = await AtomCodePlugin({}, { autoVersion: false }); + const { fetch: patched } = await plugin.auth.loader(async () => AUTH); + await assert.rejects( + () => patched("https://evil.example/v1/chat/completions", { method: "POST", body: "{}" }), + (error) => error instanceof Error && /evil\.example/.test(error.message), + ); + assert.equal(stub.calls.filter((c) => c.url.includes("evil.example")).length, 0, "凭证不得离开网关"); + } finally { + stub.restore(); + } +}); + +test("loader:同域名的 http 明文地址同样被拦下", async () => { + const stub = stubFetch({ statusBody: VALID_STATUS }); + try { + const plugin = await AtomCodePlugin({}, { autoVersion: false }); + const { fetch: patched } = await plugin.auth.loader(async () => AUTH); + await assert.rejects( + () => patched("http://llm-api.atomgit.com/v1/chat/completions", { method: "POST", body: "{}" }), + (error) => error instanceof Error && /llm-api\.atomgit\.com/.test(error.message), + ); + assert.equal(stub.calls.filter((c) => c.url.startsWith("http://")).length, 0, "明文请求不得发出"); + } finally { + stub.restore(); + } +}); + +test("loader:没有登录时移除传入的 authorization 再请求网关", async () => { + const stub = stubFetch({ statusBody: VALID_STATUS }); + try { + const plugin = await AtomCodePlugin({}, { autoVersion: false }); + const { fetch: patched } = await plugin.auth.loader(async () => undefined); + await patched(`${GATEWAY}/chat/completions`, { + method: "POST", + headers: { authorization: "Bearer caller-token" }, + body: "{}", + }); + const call = stub.calls.find((c) => c.url.includes("chat/completions")); + assert.equal(call.headers.get("authorization"), null); + } finally { + stub.restore(); + } +}); + +test("loader:过期 token 单次刷新后持久化并签名新 token", async () => { + const stub = stubFetch({ + statusBody: VALID_STATUS, + refreshResponses: [ + { + body: JSON.stringify({ + access_token: "fresh-access", + refresh_token: "fresh-refresh", + expires_in: 3600, + }), + }, + ], + }); + const saved = []; + try { + const plugin = await AtomCodePlugin( + { client: { auth: { set: async (payload) => saved.push(payload) } } }, + { autoVersion: false }, + ); + const expired = { ...AUTH, refresh: "old-refresh", expires: Date.now() - 1 }; + const { fetch: patched } = await plugin.auth.loader(async () => expired); + await patched(`${GATEWAY}/chat/completions`, { method: "POST", body: "{}" }); + + const call = stub.calls.find((c) => c.url.includes("chat/completions")); + assert.equal(call.headers.get("authorization"), "Bearer fresh-access"); + assert.equal(saved.length, 1); + assert.equal(saved[0].body.access, "fresh-access"); + assert.equal(saved[0].body.refresh, "fresh-refresh"); + } finally { + stub.restore(); + } +}); + +test("loader:持久化失败时,后续请求仍复用刷新结果而不是再次轮换", async () => { + const stub = stubFetch({ + statusBody: VALID_STATUS, + refreshResponses: [ + { + body: JSON.stringify({ + access_token: "fresh-once", + refresh_token: "rotated-once", + expires_in: 3600, + }), + }, + ], + }); + try { + const plugin = await AtomCodePlugin( + { + client: { + auth: { + set: async () => { + throw new Error("disk full"); + }, + }, + }, + }, + { autoVersion: false }, + ); + const expired = { ...AUTH, refresh: "refresh-once", expires: Date.now() - 1 }; + const { fetch: patched } = await plugin.auth.loader(async () => expired); + await patched(`${GATEWAY}/chat/completions`, { method: "POST", body: "{}" }); + await patched(`${GATEWAY}/chat/completions`, { method: "POST", body: "{}" }); + + const calls = stub.calls.filter((entry) => entry.url.includes("chat/completions")); + assert.equal(calls.length, 2); + assert.equal(calls[0].headers.get("authorization"), "Bearer fresh-once"); + assert.equal(calls[1].headers.get("authorization"), "Bearer fresh-once"); + assert.equal(stub.calls.filter((entry) => entry.url.includes("oauth/refresh")).length, 1); + } finally { + stub.restore(); + } +}); + +test("loader:网关 401 后强制续期并只重试一次", async () => { + const stub = stubFetch({ + statusBody: VALID_STATUS, + chatResponses: [ + { status: 401, body: "{}" }, + { status: 200, body: "{}" }, + ], + refreshResponses: [ + { + body: JSON.stringify({ + access_token: "retry-access", + refresh_token: "retry-refresh", + expires_in: 3600, + }), + }, + ], + }); + try { + const plugin = await AtomCodePlugin({}, { autoVersion: false }); + const auth = { + ...AUTH, + refresh: "retry-old-refresh", + expires: Date.now() + 3600_000, + }; + const { fetch: patched } = await plugin.auth.loader(async () => auth); + const response = await patched(`${GATEWAY}/chat/completions`, { + method: "POST", + body: "{}", + }); + assert.equal(response.status, 200); + const calls = stub.calls.filter((entry) => entry.url.includes("chat/completions")); + assert.equal(calls.length, 2); + assert.equal(calls[0].headers.get("authorization"), "Bearer tok"); + assert.equal(calls[1].headers.get("authorization"), "Bearer retry-access"); + assert.equal(stub.calls.filter((entry) => entry.url.includes("oauth/refresh")).length, 1); + } finally { + stub.restore(); + } +}); + +test("loader:过期且没有 refresh token 时标记重新登录", async () => { + const stub = stubFetch({ statusBody: VALID_STATUS }); + try { + const plugin = await AtomCodePlugin({}, { autoVersion: false }); + const { fetch: patched } = await plugin.auth.loader(async () => ({ + ...AUTH, + expires: Date.now() - 1, + })); + await assert.rejects( + () => patched(`${GATEWAY}/chat/completions`, { method: "POST", body: "{}" }), + (error) => error.signIn === "expired", + ); + } finally { + stub.restore(); + } +}); + +test("loader:续期只遇到网络故障时保留旧 token 并继续请求", async () => { + const stub = stubFetch({ + statusBody: VALID_STATUS, + refreshResponses: [{ status: 503, body: "{}" }], + }); + const logs = []; + try { + const plugin = await AtomCodePlugin( + { client: { app: { log: ({ body }) => logs.push(body.message) } } }, + { autoVersion: false }, + ); + const { fetch: patched } = await plugin.auth.loader(async () => ({ + ...AUTH, + refresh: "network-refresh", + expires: Date.now() - 1, + })); + await patched(`${GATEWAY}/chat/completions`, { method: "POST", body: "{}" }); + const call = stub.calls.find((entry) => entry.url.includes("chat/completions")); + assert.equal(call.headers.get("authorization"), "Bearer tok"); + assert.ok(logs.some((line) => /Renewing.*failed/.test(line))); + } finally { + stub.restore(); + } +}); + +test("auth.refresh:刷新成功返回新凭证,失败透出 expired", async () => { + const stub = stubFetch({ + statusBody: VALID_STATUS, + refreshResponses: [ + { + body: JSON.stringify({ + access_token: "new-access", + refresh_token: "new-refresh", + expires_in: 3600, + }), + }, + { status: 401, body: "{}" }, + ], + }); + try { + const plugin = await AtomCodePlugin({}, { autoVersion: false }); + const next = await plugin.auth.refresh({ ...AUTH, refresh: "old-refresh", expires: Date.now() - 1 }); + assert.equal(next.access, "new-access"); + assert.equal(next.refresh, "new-refresh"); + assert.ok(next.expires > Date.now()); + + await assert.rejects( + () => plugin.auth.refresh({ ...AUTH, refresh: "dead-refresh" }), + (error) => error.signIn === "expired", + ); + } finally { + stub.restore(); + } +}); + +test("CLI sign-in:续期后原子回写 auth.toml", async () => { + const home = await mkdtemp(join(tmpdir(), "atomcode-write-")); + const file = join(home, ".atomcode", "auth.toml"); + await mkdir(join(home, ".atomcode"), { mode: 0o700 }); + await writeFile( + file, + cliAuthFile({ + access: "cli-old", + createdAt: 1700000000, + id: "42", + email: "cli@example.com", + }), + { mode: 0o600 }, + ); + const stub = stubFetch({ + statusBody: VALID_STATUS, + refreshResponses: [ + { + body: JSON.stringify({ + access_token: "cli-new", + refresh_token: "cli-rotated", + expires_in: 7200, + }), + }, + ], + }); + const oldHome = process.env.HOME; + process.env.HOME = home; + try { + const plugin = await AtomCodePlugin({}, { autoVersion: false }); + const auth = { + type: "oauth", + source: "atomcode-cli", + authFile: file, + access: "cli-old", + refresh: "cli-refresh", + expires: Date.now() - 1, + uid: "42", + accountId: "cli@example.com", + email: "cli@example.com", + }; + const { fetch: patched } = await plugin.auth.loader(async () => auth); + await patched(`${GATEWAY}/chat/completions`, { method: "POST", body: "{}" }); + + const text = await readFile(file, "utf8"); + assert.match(text, /access_token = "cli-new"/); + assert.match(text, /refresh_token = "cli-rotated"/); + assert.match(text, /token_type = "Bearer"/); + assert.match(text, /id = "42"/); + assert.doesNotMatch(text, /id = 42/); + const call = stub.calls.find((entry) => entry.url.includes("chat/completions")); + assert.equal(call.headers.get("authorization"), "Bearer cli-new"); + } finally { + stub.restore(); + if (oldHome === undefined) delete process.env.HOME; + else process.env.HOME = oldHome; + } +}); + +test("CLI sign-in:auth.toml 账号切换时拒绝混用 uid", async () => { + const home = await mkdtemp(join(tmpdir(), "atomcode-switch-")); + const file = join(home, ".atomcode", "auth.toml"); + await mkdir(join(home, ".atomcode"), { mode: 0o700 }); + await writeFile( + file, + cliAuthFile({ + access: "other-access", + refresh: "other-refresh", + id: "99", + }), + { mode: 0o600 }, + ); + const stub = stubFetch({ statusBody: VALID_STATUS }); + try { + const plugin = await AtomCodePlugin({}, { autoVersion: false }); + const { fetch: patched } = await plugin.auth.loader(async () => ({ + type: "oauth", + source: "atomcode-cli", + authFile: file, + access: "saved-access", + refresh: "saved-refresh", + expires: Date.now() + 3600_000, + uid: "42", + })); + await assert.rejects( + () => patched(`${GATEWAY}/chat/completions`, { method: "POST", body: "{}" }), + (error) => error.signIn === "expired" && /changed accounts/i.test(error.message), + ); + } finally { + stub.restore(); + } +}); + +test("CLI sign-in:auth.toml 暂时不可读时保留已保存凭证并告警", async () => { + const stub = stubFetch({ statusBody: VALID_STATUS }); + const logs = []; + try { + const plugin = await AtomCodePlugin( + { client: { app: { log: ({ body }) => logs.push(body.message) } } }, + { autoVersion: false }, + ); + const { fetch: patched } = await plugin.auth.loader(async () => ({ + type: "oauth", + source: "atomcode-cli", + authFile: "/definitely/missing/atomcode-auth.toml", + access: "saved-access", + refresh: "saved-refresh", + expires: Date.now() + 3600_000, + uid: "42", + })); + await patched(`${GATEWAY}/chat/completions`, { method: "POST", body: "{}" }); + const call = stub.calls.find((entry) => entry.url.includes("chat/completions")); + assert.equal(call.headers.get("authorization"), "Bearer saved-access"); + assert.ok(logs.some((line) => /CLI sign-in failed/i.test(line))); + } finally { + stub.restore(); + } +}); + +test("CLI sign-in:第二个登录方式读取 auth.toml,并标记来源", async () => { + const home = await mkdtemp(join(tmpdir(), "atomcode-plugin-")); + await mkdir(join(home, ".atomcode"), { mode: 0o700 }); + await writeFile( + join(home, ".atomcode", "auth.toml"), + cliAuthFile({ + access: "cli-access", + id: "42", + email: "cli@example.com", + }), + { mode: 0o600 }, + ); + const oldHome = process.env.HOME; + process.env.HOME = home; + try { + const plugin = await AtomCodePlugin({}, { autoVersion: false }); + const flow = await plugin.auth.methods[1].authorize(); + const result = await flow.callback(); + assert.equal(result.type, "success"); + assert.equal(result.source, "atomcode-cli"); + assert.equal(result.access, "cli-access"); + assert.equal(result.uid, "42"); + } finally { + if (oldHome === undefined) delete process.env.HOME; + else process.env.HOME = oldHome; + } +}); + +test("usage:上游 401 同时返回 signIn expired", async () => { + const stub = stubFetch({ statusBody: { error: "expired" }, statusStatus: 401 }); + try { + const plugin = await AtomCodePlugin({}, { locale: "en", autoVersion: false }); + const usage = await plugin.auth.usage(async () => AUTH); + assert.equal(usage.signIn, "expired"); + assert.match(usage.error, /expired|sign in/i); + } finally { + stub.restore(); + } +}); + +test("usage:401 会先强制续期并用新 token 重试一次", async () => { + const stub = stubFetch({ + statusResponses: [ + { status: 401, body: "{}" }, + { status: 200, body: JSON.stringify(VALID_STATUS) }, + ], + refreshResponses: [ + { + body: JSON.stringify({ + access_token: "usage-retry-access", + refresh_token: "usage-retry-refresh", + expires_in: 3600, + }), + }, + ], + }); + try { + const plugin = await AtomCodePlugin({}, { locale: "en", autoVersion: false }); + const usage = await plugin.auth.usage(async () => ({ + ...AUTH, + refresh: "usage-old-refresh", + expires: Date.now() + 3600_000, + })); + assert.equal(usage.plan, "CodingPlan Lite-体验版"); + assert.equal(stub.calls.filter((call) => call.url.includes("status-v2")).length, 2); + assert.equal(stub.calls.filter((call) => call.url.includes("oauth/refresh")).length, 1); + const statusCalls = stub.calls.filter((call) => call.url.includes("status-v2")); + assert.equal(statusCalls[1].headers.get("authorization"), "Bearer usage-retry-access"); + } finally { + stub.restore(); + } +}); + +test("checkin:status 401 会续期后重试并返回 done", async () => { + const stub = stubFetch({ + statusResponses: [ + { status: 401, body: "{}" }, + { status: 200, body: JSON.stringify(VALID_STATUS) }, + ], + refreshResponses: [ + { + body: JSON.stringify({ + access_token: "checkin-retry-access", + refresh_token: "checkin-retry-refresh", + expires_in: 3600, + }), + }, + ], + }); + try { + const plugin = await AtomCodePlugin({}, { autoVersion: false }); + const result = await plugin.auth.checkin(async () => ({ + ...AUTH, + refresh: "checkin-old-refresh", + expires: Date.now() + 3600_000, + })); + assert.equal(result.outcome, "done"); + const statusCalls = stub.calls.filter((call) => call.url.includes("status-v2")); + assert.equal(statusCalls.length, 2); + assert.equal(statusCalls[1].headers.get("authorization"), "Bearer checkin-retry-access"); + } finally { + stub.restore(); + } +}); + +test("checkin:并发调用共用一次领取请求", async () => { + const expired = { + ...VALID_STATUS, + codingplan_free: { ...VALID_STATUS.codingplan_free, remaining_days: 0, expires_at: "2020-01-01" }, + }; + const stub = stubFetch({ + statusBody: expired, + claimResponses: [ + { body: JSON.stringify({ success: true, duplicate: false, plan_name: "CodingPlan Lite" }) }, + ], + }); + try { + const plugin = await AtomCodePlugin({}, { autoVersion: false }); + const [a, b] = await Promise.all([ + plugin.auth.checkin(async () => AUTH), + plugin.auth.checkin(async () => AUTH), + ]); + assert.equal(a.outcome, "claimed", JSON.stringify(a)); + assert.equal(b.outcome, "claimed", JSON.stringify(b)); + assert.equal(stub.calls.filter((call) => call.url.includes("claim-v2")).length, 1); + } finally { + stub.restore(); + } +}); + +test("usage:成功结果按账号缓存,未登录不请求上游", async () => { + const stub = stubFetch({ statusBody: VALID_STATUS }); + try { + const plugin = await AtomCodePlugin({}, { locale: "en", autoVersion: false }); + const first = await plugin.auth.usage(async () => AUTH); + const second = await plugin.auth.usage(async () => AUTH); + assert.equal(first.plan, "CodingPlan Lite-体验版"); + assert.equal(first.windows.length, 1); + assert.deepEqual(second, first); + assert.equal(stub.calls.filter((c) => c.url.includes("status-v2")).length, 1); + + const noAccount = await plugin.auth.usage(async () => undefined); + assert.equal(noAccount.error, "No signed-in AtomCode account"); + } finally { + stub.restore(); + } +}); + +test("options:非白名单的 platformBaseURL 被拒,回退官方 broker", async () => { + const stub = stubFetch({ statusBody: VALID_STATUS }); + try { + const plugin = await AtomCodePlugin({}, { autoVersion: false, platformBaseURL: "https://evil.example" }); + const started = await plugin.auth.methods[0].authorize(); + assert.equal(stub.calls.filter((c) => c.url.includes("evil.example")).length, 0, "授权请求不得打到非白名单地址"); + assert.ok( + stub.calls.some((c) => c.url.startsWith("https://acs.atomgit.com/")), + "应改用官方 broker", + ); + assert.equal(started.url, "https://atomgit.com/login"); + } finally { + stub.restore(); + } +}); + +test("options:http 或非白名单的 codingPlanAPIURL 被拒,回退官方端点", async () => { + const stub = stubFetch({ statusBody: VALID_STATUS }); + try { + const plugin = await AtomCodePlugin({}, { autoVersion: false, codingPlanAPIURL: "http://evil.example" }); + await plugin.auth.checkin(async () => AUTH); + assert.equal(stub.calls.filter((c) => c.url.includes("evil.example")).length, 0, "额度请求不得打到非白名单地址"); + assert.ok( + stub.calls.some((c) => c.url.startsWith("https://api.gitcode.com/")), + "应改用官方端点", + ); + } finally { + stub.restore(); + } +}); + +test("options:白名单内的合法覆盖被采纳(上游迁移时的逃生口)", async () => { + const stub = stubFetch({ statusBody: VALID_STATUS }); + try { + const plugin = await AtomCodePlugin({}, { autoVersion: false, codingPlanAPIURL: "https://api.gitcode.com/api/v6" }); + await plugin.auth.checkin(async () => AUTH); + assert.ok( + stub.calls.some((c) => c.url.startsWith("https://api.gitcode.com/api/v6/")), + "合法覆盖应当生效", + ); + } finally { + stub.restore(); + } +}); + +test("options:非法数值、版本号和布尔值回退默认并告警", async () => { + const logs = []; + const plugin = await AtomCodePlugin( + { + client: { + app: { + log: ({ body }) => logs.push(body.message), + }, + }, + }, + { + autoVersion: false, + autoClaim: "false", + clientVersion: "5.2.3\r\nInjected", + masterKeyHex: "not-a-key", + quotaTtlMs: Infinity, + maxOutputTokens: -1, + diagnosticsPort: 80, + }, + ); + + assert.equal(plugin.auth.refreshLead, 5 * 60 * 1000); + for (const name of [ + "autoClaim", + "clientVersion", + "masterKeyHex", + "quotaTtlMs", + "maxOutputTokens", + "diagnosticsPort", + ]) { + assert.ok(logs.some((line) => line.includes(name)), `missing warning for ${name}`); + } +}); + +test("options:告警不记录原值,避免泄漏密钥或 URL 凭证", async () => { + const logs = []; + const plugin = await AtomCodePlugin( + { client: { app: { log: ({ body }) => logs.push(body.message) } } }, + { + autoVersion: false, + masterKeyHex: "secret-that-must-not-be-logged", + platformBaseURL: "https://user:password@evil.example", + }, + ); + await plugin.config({ provider: {} }); + assert.ok(logs.some((line) => line.includes("masterKeyHex"))); + assert.ok(logs.every((line) => !line.includes("secret-that-must-not-be-logged"))); + assert.ok(logs.every((line) => !line.includes("password"))); +}); + +test("options:布尔类型错误会告警,宿主 logger 抛错也不影响加载", async () => { + const stub = stubFetch({ statusBody: VALID_STATUS }); + try { + const plugin = await AtomCodePlugin( + { + client: { + app: { + log: () => { + throw new Error("logger failed"); + }, + }, + }, + }, + { autoVersion: 1, autoClaim: "true" }, + ); + assert.equal(typeof plugin.auth.loader, "function"); + } finally { + stub.restore(); + } +}); + +test("options:合法自定义 masterKey 被采纳且不误告警", async () => { + const logs = []; + const masterKeyHex = "ab".repeat(32); + await AtomCodePlugin( + { client: { app: { log: ({ body }) => logs.push(body.message) } } }, + { autoVersion: false, masterKeyHex }, + ); + assert.ok(logs.every((line) => !line.includes("masterKeyHex"))); +}); + +test("native settings:声明布尔开关,并让显式旧选项优先于 Magpie 开关", async () => { + const expired = { + ...VALID_STATUS, + codingplan_free: { + ...VALID_STATUS.codingplan_free, + remaining_days: 0, + expires_at: "2020-01-01", + }, + }; + const stub = stubFetch({ + statusBody: expired, + modelsBody: [], + claimResponses: [ + { body: JSON.stringify({ success: true, duplicate: false, plan_name: "CodingPlan Lite" }) }, + ], + }); + const nativeReads = []; + try { + const plugin = await AtomCodePlugin( + { + magpie: { + option: (provider, key) => { + nativeReads.push([provider, key]); + if (key === "auto_claim") return false; + if (key === "auto_version") return true; + return undefined; + }, + }, + }, + { + autoClaim: true, + autoVersion: false, + diagnosticsPort: 39278, + }, + ); + assert.deepEqual( + plugin.auth.options.map((option) => option.key), + ["auto_claim", "auto_version"], + ); + assert.equal(plugin.auth.options[0].labels.zh.length > 0, true); + assert.equal(plugin.auth.options[0].descriptions.en.length > 0, true); + assert.equal(plugin.auth.options[0].default, true); + assert.equal(plugin.auth.options[1].default, true); + + await plugin.provider.models({}, { auth: AUTH }); + assert.equal( + stub.calls.filter((call) => call.url.includes("claim-v2")).length, + 1, + "显式 autoClaim=true 应压过原生 false", + ); + assert.equal( + stub.calls.filter((call) => call.url.includes("raw.atomgit.com")).length, + 0, + "显式 autoVersion=false 应压过原生 true", + ); + assert.deepEqual(nativeReads, [], "显式旧选项存在时不应再读取原生开关"); + } finally { + stub.restore(); + } +}); + +test("native settings:未设置旧选项时读取 Magpie 的自动领取开关", async () => { + const expired = { + ...VALID_STATUS, + codingplan_free: { + ...VALID_STATUS.codingplan_free, + remaining_days: 0, + expires_at: "2020-01-01", + }, + }; + const stub = stubFetch({ + statusBody: expired, + modelsBody: [], + claimResponses: [ + { body: JSON.stringify({ success: true, duplicate: false, plan_name: "CodingPlan Lite" }) }, + ], + }); + try { + const plugin = await AtomCodePlugin( + { + magpie: { + option: (_provider, key) => (key === "auto_claim" ? false : undefined), + }, + }, + { autoVersion: false, diagnosticsPort: 39279 }, + ); + await plugin.provider.models({}, { auth: AUTH }); + assert.equal(stub.calls.filter((call) => call.url.includes("claim-v2")).length, 0); + } finally { + stub.restore(); + } +}); + +test("CLI sign-in:自定义绝对路径会进入结果并用于读取", async () => { + const home = await mkdtemp(join(tmpdir(), "atomcode-custom-path-")); + const file = join(home, "custom", "atomcode-auth.toml"); + await mkdir(join(home, "custom"), { mode: 0o700 }); + await writeFile( + file, + cliAuthFile({ + access: "custom-access", + refresh: "custom-refresh", + id: "77", + }), + { mode: 0o600 }, + ); + try { + const plugin = await AtomCodePlugin({}, { autoVersion: false }); + const method = plugin.auth.methods[1]; + assert.equal(method.prompts[0].key, "authFile"); + assert.equal(method.prompts[0].validate("relative.toml"), method.prompts[0].validate("../bad")); + const flow = await method.authorize({ authFile: file }); + const result = await flow.callback(); + assert.equal(result.type, "success"); + assert.equal(result.authFile, file); + assert.equal(result.access, "custom-access"); + assert.equal(result.uid, "77"); + await assert.rejects( + () => method.authorize({ authFile: "relative.toml" }), + /absolute or start with/, + ); + } finally { + // Temporary directory is intentionally left for the OS to clean up. + } +}); + +test("loader:凭证类 403 会续期一次,额度类 403 保留登录且不续期", async () => { + const credentialStub = stubFetch({ + statusBody: VALID_STATUS, + chatResponses: [ + { status: 403, body: JSON.stringify({ message: "session token expired" }) }, + { status: 200, body: "{}" }, + ], + refreshResponses: [ + { + body: JSON.stringify({ + access_token: "forbidden-retry", + refresh_token: "forbidden-refresh", + expires_in: 3600, + }), + }, + ], + }); + try { + const plugin = await AtomCodePlugin({}, { autoVersion: false }); + const auth = { + ...AUTH, + refresh: "old-forbidden-refresh", + expires: Date.now() + 3600_000, + }; + const { fetch: patched } = await plugin.auth.loader(async () => auth); + const response = await patched(`${GATEWAY}/chat/completions`, { + method: "POST", + body: "{}", + }); + assert.equal(response.status, 200); + const calls = credentialStub.calls.filter((call) => call.url.includes("chat/completions")); + assert.equal(calls.length, 2); + assert.equal(calls[1].headers.get("authorization"), "Bearer forbidden-retry"); + assert.equal( + credentialStub.calls.filter((call) => call.url.includes("oauth/refresh")).length, + 1, + ); + } finally { + credentialStub.restore(); + } + + const entitlementStub = stubFetch({ + statusBody: VALID_STATUS, + chatResponses: [{ status: 403, body: JSON.stringify({ message: "quota exhausted" }) }], + }); + try { + const plugin = await AtomCodePlugin({}, { autoVersion: false }); + const { fetch: patched } = await plugin.auth.loader(async () => ({ + ...AUTH, + refresh: "must-not-refresh", + expires: Date.now() + 3600_000, + })); + const response = await patched(`${GATEWAY}/chat/completions`, { + method: "POST", + body: "{}", + }); + assert.equal(response.status, 403); + assert.equal(response.headers.get("x-magpie-sign-in"), "kept"); + assert.match(await response.text(), /quota/); + assert.equal( + entitlementStub.calls.filter((call) => call.url.includes("oauth/refresh")).length, + 0, + ); + } finally { + entitlementStub.restore(); + } +}); + +test("usage:重启后网络失败返回磁盘上的 stale 额度而不是清空窗口", async () => { + const directory = await mkdtemp(join(tmpdir(), "atomcode-stale-usage-")); + const first = stubFetch({ statusBody: VALID_STATUS }); + try { + const plugin = await AtomCodePlugin( + { directory }, + { locale: "en", autoVersion: false }, + ); + const value = await plugin.auth.usage(async () => AUTH); + assert.equal(value.plan, "CodingPlan Lite-体验版"); + assert.equal(value.windows.length, 1); + } finally { + first.restore(); + } + + const offline = stubFetch({ statusBody: null }); + try { + const plugin = await AtomCodePlugin( + { directory }, + { locale: "en", autoVersion: false }, + ); + const stale = await plugin.auth.usage(async () => AUTH); + assert.equal(stale.plan, "CodingPlan Lite-体验版"); + assert.equal(stale.windows.length, 1); + assert.equal(stale.stale, true); + assert.equal(stale.signIn, "kept"); + assert.match(stale.error, /last successful snapshot/i); + const persisted = await readFile(join(directory, "atomcode-state.json"), "utf8"); + assert.doesNotMatch(persisted, /"u1"|"tok"|cli@example\.com/); + } finally { + offline.restore(); + } +}); + +test("provider.models:实时目录失败时重启后使用 last-good 磁盘缓存", async () => { + const directory = await mkdtemp(join(tmpdir(), "atomcode-cached-models-")); + const catalogBody = [{ display_model_name: "cached-model", context_window: 12345 }]; + const first = stubFetch({ statusBody: VALID_STATUS, modelsBody: catalogBody }); + try { + const plugin = await AtomCodePlugin( + { directory }, + { autoVersion: false }, + ); + const models = await plugin.provider.models({}, { auth: AUTH }); + assert.equal(models["cached-model"].limit.context, 12345); + } finally { + first.restore(); + } + + const offline = stubFetch({ statusBody: null }); + try { + const plugin = await AtomCodePlugin( + { directory }, + { autoVersion: false }, + ); + const models = await plugin.provider.models({}, { auth: AUTH }); + assert.equal(models["cached-model"].api.id, "cached-model"); + assert.equal(models[Symbol.for("magpie.fellBack")], true); + } finally { + offline.restore(); + } +}); + +test("usage:额度类 403 不把账号标记为 expired", async () => { + const stub = stubFetch({ + statusBody: { message: "CodingPlan quota exhausted" }, + statusStatus: 403, + }); + try { + const plugin = await AtomCodePlugin({}, { locale: "en", autoVersion: false }); + const usage = await plugin.auth.usage(async () => ({ + ...AUTH, + refresh: "must-not-refresh", + expires: Date.now() + 3600_000, + })); + assert.notEqual(usage.signIn, "expired"); + assert.equal(usage.signIn, "kept"); + assert.equal(stub.calls.filter((call) => call.url.includes("oauth/refresh")).length, 0); + } finally { + stub.restore(); + } +}); diff --git a/packages/atomcode/test/quota.test.mjs b/packages/atomcode/test/quota.test.mjs new file mode 100644 index 0000000..76700e1 --- /dev/null +++ b/packages/atomcode/test/quota.test.mjs @@ -0,0 +1,246 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; + +import { strings } from "../i18n.mjs"; +import { quotaFromStatus } from "../quota.mjs"; + +const t = strings("en"); + +test("quotaFromStatus maps every rate-limit window", () => { + const usage = quotaFromStatus( + { + codingplan_free: { + plan_name: "CodingPlan Pro", + expires_at: "2026-12-01", + }, + current_usage: { + usage_percent: 99, + reset_at: "2026-11-01T10:00:00Z", + }, + rate_limit_windows: [ + { + window_hours: 5, + call_limit: 200, + calls_used: 50, + usage_percent: 25, + seconds_until_reset: 1200, + }, + { + window_size_seconds: 86400, + call_limit: 1000, + calls_used: 250, + usage_percent: 25, + }, + ], + }, + t, + { user: "alice" }, + ); + + assert.equal(usage.plan, "CodingPlan Pro"); + assert.equal(usage.user, "alice"); + assert.equal(usage.until, "2026-12-01T15:59:59.999Z"); + assert.equal(usage.windows.length, 2); + assert.deepEqual(usage.windows[0], { + name: "5h window", + used: 25, + span: 18000, + amount: 50, + unit: "calls", + limit: 200, + display: "50 / 200 calls", + resetSecs: 1200, + }); + assert.equal(usage.windows[1].name, "24h window"); + assert.equal(usage.windows[1].display, "250 / 1000 calls"); +}); + +test("quotaFromStatus falls back to current_usage when no window rows exist", () => { + const usage = quotaFromStatus( + { + codingplan_free: { plan_name: "CodingPlan Lite" }, + current_usage: { + usage_percent: 120, + window_hours: 3, + seconds_until_reset: 60, + }, + }, + t, + ); + assert.deepEqual(usage.windows, [ + { + name: "3h window", + used: 120, + span: 10800, + unit: "calls", + resetSecs: 60, + }, + ]); +}); + +test("quotaFromStatus returns a stable empty shape for malformed status", () => { + assert.deepEqual(quotaFromStatus(null, t), { + plan: "AtomCode CodingPlan", + windows: [], + }); +}); + +test("quotaFromStatus keeps unknown shares unknown and trusts each window's own data", () => { + const usage = quotaFromStatus( + { + codingplan_free: { plan_name: "Plan", remaining_days: null, expires_at: "2099-12-31" }, + current_usage: { usage_percent: 99, window_hours: 5, reset_at: "2099-12-31T10:00:00" }, + rate_limit_windows: [ + { window_hours: 5, call_limit: 100, usage_percent: 12, reset_at: "2099-12-31T10:00:00" }, + { window_hours: 24 }, + ], + }, + t, + ); + assert.equal(usage.windows[0].used, 12); + assert.equal(usage.windows[0].amount, undefined); + assert.equal(usage.windows[1].used, undefined); + assert.equal(usage.windows[1].amount, undefined); +}); + +test("quotaFromStatus adds a token window when the current window declares tokens", () => { + const usage = quotaFromStatus( + { + codingplan_free: { plan_name: "Plan" }, + current_usage: { + unit: "tokens", + window_hours: 5, + window_tokens_used: 250000, + window_token_limit: 1000000, + seconds_until_reset: 60, + }, + rate_limit_windows: [], + }, + t, + ); + assert.equal(usage.windows.length, 1); + assert.equal(usage.windows[0].unit, "tokens"); + assert.equal(usage.windows[0].used, 25); + assert.equal(usage.windows[0].amount, 250000); + assert.equal(usage.windows[0].limit, 1000000); +}); + +test("quotaFromStatus ignores legacy token-named call counters in current_usage", () => { + const usage = quotaFromStatus( + { + codingplan_free: { plan_name: "Plan" }, + current_usage: { + window_hours: 5, + window_tokens_used: 237, + window_token_limit: 1600, + usage_percent: 14, + seconds_until_reset: 60, + }, + rate_limit_windows: [ + { + window_size_seconds: 18000, + window_hours: 5, + call_limit: 1600, + calls_used: 237, + usage_percent: 14, + seconds_until_reset: 60, + }, + ], + }, + t, + ); + assert.equal(usage.windows.length, 1); + assert.equal(usage.windows[0].unit, "calls"); + assert.equal(usage.windows[0].amount, 237); + assert.equal(usage.windows[0].limit, 1600); +}); + +test("quotaFromStatus separates token and call rows and honours explicit units", () => { + const usage = quotaFromStatus( + { + codingplan_free: { plan_name: "Plan" }, + current_usage: { + usage_percent: 20, + window_tokens_used: 500, + window_token_limit: 1000, + window_hours: 5, + }, + rate_limit_windows: [ + { + unit: "tokens", + window_hours: 24, + tokens_used: 400, + token_limit: 2000, + token_usage_percent: 20, + }, + { + unit: "calls", + window_hours: 5, + requests_used: 10, + requests_limit: 100, + }, + { + window_hours: 7, + call_limit: 50, + calls_used: 5, + }, + ], + }, + t, + ); + assert.deepEqual( + usage.windows.map((window) => [window.unit, window.span, window.used]), + [ + ["tokens", 86400, 20], + ["calls", 18000, 10], + ["calls", 25200, 10], + ], + ); + assert.equal(usage.windows[0].display, "400 / 2000 tokens"); + assert.equal(usage.windows[1].display, "10 / 100 calls"); +}); + +test("quotaFromStatus deduplicates current_usage by unit, not span alone", () => { + const usage = quotaFromStatus( + { + codingplan_free: { plan_name: "Plan" }, + current_usage: { + usage_percent: 30, + window_hours: 5, + window_tokens_used: 300, + window_token_limit: 1000, + }, + rate_limit_windows: [ + { + unit: "tokens", + window_hours: 5, + tokens_used: 300, + token_limit: 1000, + }, + ], + }, + t, + ); + assert.deepEqual( + usage.windows.map((window) => [window.unit, window.span, window.used]), + [ + ["tokens", 18000, 30], + ["calls", 18000, 30], + ], + ); +}); + +test("quotaFromStatus keeps an explicit token window unknown instead of inventing zero", () => { + const usage = quotaFromStatus( + { + codingplan_free: { plan_name: "Plan" }, + current_usage: {}, + rate_limit_windows: [{ unit: "tokens", window_hours: 3 }], + }, + t, + ); + assert.equal(usage.windows.length, 1); + assert.equal(usage.windows[0].unit, "tokens"); + assert.equal(usage.windows[0].used, undefined); + assert.equal(usage.windows[0].amount, undefined); +}); diff --git a/packages/atomcode/test/request-body.test.mjs b/packages/atomcode/test/request-body.test.mjs new file mode 100644 index 0000000..4690a6d --- /dev/null +++ b/packages/atomcode/test/request-body.test.mjs @@ -0,0 +1,139 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; + +import { + includeStreamUsage, + normalizeRequestBody, +} from "../request-body.mjs"; + +test("normalizeRequestBody accepts replayable fetch bodies", async () => { + const cases = [ + "hello", + Buffer.from("buffer"), + new TextEncoder().encode("view"), + new TextEncoder().encode("array").buffer, + new Blob(["blob"], { type: "application/json" }), + ]; + for (const body of cases) { + const normalized = await normalizeRequestBody(body); + assert.ok(normalized.body !== undefined); + assert.ok(normalized.signBody !== undefined); + } + const empty = await normalizeRequestBody(undefined, { + request: new Request("https://example.test/"), + fromRequest: true, + }); + assert.equal(empty.signBody, ""); +}); + +test("normalizeRequestBody rejects bodies that cannot be signed exactly", async () => { + for (const body of [ + new URLSearchParams({ a: "1" }), + new FormData(), + new ReadableStream(), + ]) { + await assert.rejects(() => normalizeRequestBody(body), /unsupported request body/i); + } +}); + +test("normalizeRequestBody caps Request bodies before buffering", async () => { + const request = new Request("https://example.test/", { + method: "POST", + body: "too large", + }); + await assert.rejects( + () => + normalizeRequestBody(undefined, { + request, + fromRequest: true, + maxBytes: 4, + }), + /exceeds 4 bytes/i, + ); +}); + +test("normalizeRequestBody enforces the cap for every replayable type", async () => { + const bodies = [ + "too large", + Buffer.from("too large"), + new TextEncoder().encode("too large"), + new TextEncoder().encode("too large").buffer, + new Blob(["too large"]), + ]; + for (const body of bodies) { + await assert.rejects( + () => normalizeRequestBody(body, { maxBytes: 4 }), + /exceeds 4 bytes/i, + ); + } +}); + +test("normalizeRequestBody reads each Request stream chunk shape", async () => { + const stream = new ReadableStream({ + start(controller) { + controller.enqueue(new TextEncoder().encode("a")); + controller.enqueue( + new TextEncoder().encode("b").buffer, + ); + controller.enqueue(new DataView(new TextEncoder().encode("c").buffer)); + controller.close(); + }, + }); + const request = new Request("https://example.test/", { + method: "POST", + body: stream, + duplex: "half", + }); + const normalized = await normalizeRequestBody(undefined, { + request, + fromRequest: true, + }); + assert.equal(new TextDecoder().decode(normalized.body), "abc"); +}); + +test("includeStreamUsage only fills an absent Chat Completions option", () => { + const absent = JSON.stringify({ model: "m", stream: true }); + const added = includeStreamUsage(absent, { + pathname: "/v1/chat/completions", + contentType: "application/json", + }); + assert.equal(added.changed, true); + assert.equal(JSON.parse(added.body).stream_options.include_usage, true); + + for (const body of [ + JSON.stringify({ model: "m", stream: false }), + JSON.stringify({ + model: "m", + stream: true, + stream_options: { include_usage: false }, + }), + absent, + ]) { + const result = includeStreamUsage(body, { + pathname: body === absent ? "/v1/embeddings" : "/v1/chat/completions", + contentType: "application/json", + }); + assert.equal(result.changed, false); + assert.equal(result.body, body); + } + + const nonJson = includeStreamUsage(absent, { + pathname: "/v1/chat/completions", + contentType: "text/plain", + }); + assert.equal(nonJson.changed, false); + + for (const body of [ + "not json", + "null", + JSON.stringify({ stream: true, stream_options: null }), + JSON.stringify({ stream: true, stream_options: [] }), + ]) { + const result = includeStreamUsage(body, { + pathname: "/v1/chat/completions", + contentType: "application/json", + }); + assert.equal(result.changed, false); + assert.equal(result.body, body); + } +}); diff --git a/packages/atomcode/test/sign.test.mjs b/packages/atomcode/test/sign.test.mjs new file mode 100644 index 0000000..57c8ec6 --- /dev/null +++ b/packages/atomcode/test/sign.test.mjs @@ -0,0 +1,58 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; + +import { MASTER_KEY_HEX, signAtomGitRequest } from "../sign.mjs"; + +/** + * Atom2Api's independent signing fixture. This is the compatibility contract + * for every model request; a plugin release must never change it silently. + */ +test("signing fixture matches Atom2Api", () => { + const headers = signAtomGitRequest({ + method: "POST", + path: "/v1/chat/completions", + body: '{"model":"deepseek-v4-flash"}', + oauthToken: "token-fixture", + userId: "user-fixture", + clientVersion: "5.0.2", + timestamp: 1767225600, + nonce: Buffer.from("000102030405060708090a0b0c0d0e0f", "hex"), + }); + + assert.equal( + headers["X-AtomCode-Sig"], + "v1:c5bafa716c0fdc31a6e2738412d0b21a9d9e9d1ca09cc44eb17949a1b4fa4bdd", + ); + assert.equal(headers["X-AtomCode-Ts"], "1767225600"); + assert.equal(headers["X-AtomCode-Nonce"], "000102030405060708090a0b0c0d0e0f"); + assert.equal(headers["X-AtomCode-Alg"], "1"); + assert.equal(headers["X-AtomCode-Ver"], "5.0.2"); +}); + +test("signature covers token, user, version and raw body bytes", () => { + const base = { + method: "POST", + path: "/v1/chat/completions", + body: new TextEncoder().encode("{}"), + oauthToken: "token", + userId: "user", + clientVersion: "5.2.3", + timestamp: 1767225600, + nonce: Buffer.alloc(16, 7), + }; + const signature = (overrides = {}) => signAtomGitRequest({ ...base, ...overrides })["X-AtomCode-Sig"]; + + assert.notEqual(signature(), signature({ oauthToken: "other-token" })); + assert.notEqual(signature(), signature({ userId: "other-user" })); + assert.notEqual(signature(), signature({ clientVersion: "5.2.4" })); + assert.notEqual(signature(), signature({ body: new TextEncoder().encode('{"x":1}') })); +}); + +test("signing rejects incomplete inputs instead of producing a partial signature", () => { + assert.throws(() => signAtomGitRequest({ method: "", path: "/v1", oauthToken: "t", userId: "u", clientVersion: "v" }), /method/); + assert.throws(() => signAtomGitRequest({ method: "GET", path: "v1", oauthToken: "t", userId: "u", clientVersion: "v" }), /path/); + assert.throws(() => signAtomGitRequest({ method: "GET", path: "/v1", oauthToken: "", userId: "u", clientVersion: "v" }), /token/); + assert.throws(() => signAtomGitRequest({ method: "GET", path: "/v1", oauthToken: "t", userId: "", clientVersion: "v" }), /user id/); + assert.throws(() => signAtomGitRequest({ method: "GET", path: "/v1", oauthToken: "t", userId: "u", clientVersion: "" }), /version/); + assert.match(MASTER_KEY_HEX, /^[0-9a-f]{64}$/); +}); diff --git a/packages/atomcode/test/state.test.mjs b/packages/atomcode/test/state.test.mjs new file mode 100644 index 0000000..422f5f6 --- /dev/null +++ b/packages/atomcode/test/state.test.mjs @@ -0,0 +1,177 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { mkdtemp, readFile, stat, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; + +import { + STATE_FILE_NAME, + accountDigest, + createStateStore, + emptyState, + sanitizeState, + stateFilePath, +} from "../state.mjs"; + +test("accountDigest is stable, non-reversible and separates accounts", () => { + const first = accountDigest("user-42"); + assert.match(first, /^[a-f0-9]{16}$/); + assert.equal(first, accountDigest("user-42")); + assert.notEqual(first, accountDigest("user-43")); + assert.equal(accountDigest(undefined), "anonymous"); +}); + +test("sanitizeState keeps only the documented diagnostics schema", () => { + const forbiddenTokenKey = ["to", "ken"].join(""); + const forbiddenSecretKey = ["top", "Level", "Secret"].join(""); + const state = sanitizeState({ + version: 99, + accounts: { + [accountDigest("42")]: { + digest: accountDigest("42"), + uid: "42", + email: "person@example.com", + access: "secret-token", + prompt: "private prompt", + rawResponse: "raw upstream", + loginSource: "atomcode-cli", + models: [ + { + id: "model-a", + key: "model-a", + context: 1000, + output: 100, + levels: ["low"], + vision: true, + type: "openai", + [forbiddenTokenKey]: "must-not-survive", + }, + ], + modelSource: "live", + quota: { + plan: "Plan", + user: "person@example.com", + windows: [{ name: "5h", used: 12, unit: "calls" }], + }, + lastError: { + category: "network", + message: "Bearer abc person@example.com", + at: 1, + stack: "secret", + }, + }, + "../escape": { digest: "../escape" }, + }, + versionSource: { + version: "5.2.3", + source: "manifest", + checkedAt: 2, + [forbiddenTokenKey]: "x", + }, + [forbiddenSecretKey]: "top-level-secret", + }); + assert.equal(state.version, 1); + const account = state.accounts[accountDigest("42")]; + assert.equal(account.uid, undefined); + assert.equal(account.email, undefined); + assert.equal(account.access, undefined); + assert.equal(account.prompt, undefined); + assert.equal(account.rawResponse, undefined); + assert.equal(account.models[0][forbiddenTokenKey], undefined); + assert.equal(account.quota.user, undefined); + assert.doesNotMatch(account.lastError.message, /abc|person@example\.com/); + assert.equal(state.accounts["../escape"], undefined); + assert.equal(state[forbiddenSecretKey], undefined); + assert.equal(state.versionSource[forbiddenTokenKey], undefined); +}); + +test("state store persists models, quota, errors and a private atomic file", async () => { + const directory = await mkdtemp(join(tmpdir(), "atomcode-state-")); + const store = createStateStore({ directory }); + await store.recordLogin("42", "atomcode-cli"); + await store.recordModels( + "42", + [{ id: "m", key: "m", context: 100, output: 50, levels: [], vision: false, type: "openai" }], + { source: "live" }, + ); + await store.recordQuota("42", { + plan: "Plan", + user: "person@example.com", + windows: [{ name: "5h", used: 30, unit: "calls" }], + }); + await store.recordError("42", { + category: "network", + message: "Bearer secret person@example.com", + status: 503, + at: Date.now(), + }); + await store.recordSelfCheck("42", { + ok: true, + at: Date.now(), + ms: 1, + checks: { signature: true, version: true, configuration: true }, + }); + await store.recordSelfCheckForDigest(accountDigest("42"), { + ok: true, + at: Date.now(), + ms: 2, + checks: { signature: true, version: true, configuration: true }, + }); + await store.recordVersion({ + version: "5.4.0", + source: "manifest", + checkedAt: Date.now(), + }); + + const path = join(directory, STATE_FILE_NAME); + const text = await readFile(path, "utf8"); + const info = await stat(path); + assert.equal(info.mode & 0o777, 0o600); + assert.doesNotMatch(text, /person@example\.com|secret|"uid"|"access"/); + assert.match(text, /"digest": "[a-f0-9]{16}"/); + assert.match(text, /"version": "5\.4\.0"/); + + const reloaded = createStateStore({ directory }); + assert.equal((await reloaded.cachedModels("42"))[0].id, "m"); + assert.equal((await reloaded.cachedQuota("42")).plan, "Plan"); + const account = await reloaded.account(accountDigest("42")); + assert.equal(account.lastError.status, 503); + assert.equal(account.selfCheck.ok, true); + assert.equal(account.selfCheck.ms, 2); +}); + +test("a corrupt state file is ignored and replaced by the next write", async () => { + const directory = await mkdtemp(join(tmpdir(), "atomcode-state-corrupt-")); + const path = join(directory, STATE_FILE_NAME); + await writeFile(path, "{ definitely not json", "utf8"); + const errors = []; + const store = createStateStore({ directory, onError: (error) => errors.push(error) }); + const recovered = await store.read(); + assert.equal(recovered.version, emptyState().version); + assert.deepEqual({ ...recovered.accounts }, {}); + assert.equal(errors.length, 1); + await store.recordQuota("42", { plan: "Recovered", windows: [] }); + const reloaded = createStateStore({ directory }); + assert.equal((await reloaded.cachedQuota("42")).plan, "Recovered"); +}); + +test("stores without a directory stay in memory and report no path", async () => { + const store = createStateStore(); + assert.equal(store.path, undefined); + assert.equal(stateFilePath(undefined), undefined); + await store.recordQuota("42", { plan: "Memory", windows: [] }); + assert.equal((await store.cachedQuota("42")).plan, "Memory"); +}); + +test("concurrent updates serialize rather than losing accounts", async () => { + const directory = await mkdtemp(join(tmpdir(), "atomcode-state-concurrent-")); + const store = createStateStore({ directory }); + await Promise.all([ + store.recordLogin("a", "atomcode-browser"), + store.recordLogin("b", "atomcode-cli"), + store.recordQuota("a", { plan: "A", windows: [] }), + ]); + const state = await store.read(); + assert.ok(state.accounts[accountDigest("a")]); + assert.ok(state.accounts[accountDigest("b")]); +}); diff --git a/packages/atomcode/test/version.test.mjs b/packages/atomcode/test/version.test.mjs new file mode 100644 index 0000000..62c239b --- /dev/null +++ b/packages/atomcode/test/version.test.mjs @@ -0,0 +1,146 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; + +import { createVersionSource, extractVersionFromManifest, fetchAtomCodeVersion } from "../version.mjs"; + +const MANIFEST = '[package]\nname = "atomcode"\nversion = "9.9.9"\n\n[workspace.package]\nversion = "5.2.3"\nedition = "2021"\n'; + +test("只认 [workspace.package] 的 version,忽略 [package] 的", () => { + assert.equal(extractVersionFromManifest(MANIFEST), "5.2.3"); +}); + +test("缺段 / 缺字段 / 非语义版本 → null", () => { + assert.equal(extractVersionFromManifest('[package]\nversion = "1.2.3"\n'), null); + assert.equal(extractVersionFromManifest('[workspace.package]\nedition = "2021"\n'), null); + assert.equal(extractVersionFromManifest('[workspace.package]\nversion = "nightly"\n'), null); + assert.equal(extractVersionFromManifest(""), null); + assert.equal(extractVersionFromManifest(undefined), null); +}); + +test("CRLF / 缩进 / 前导空白容忍", () => { + assert.equal(extractVersionFromManifest('[workspace.package]\r\n version = "6.0.1" \r\n'), "6.0.1"); +}); + +test("fetchAtomCodeVersion:正常返回版本,非 2xx 抛错", async () => { + const version = await fetchAtomCodeVersion({ + fetchImpl: async () => new Response(MANIFEST, { status: 200 }), + }); + assert.equal(version, "5.2.3"); + await assert.rejects( + fetchAtomCodeVersion({ fetchImpl: async () => new Response("nope", { status: 404 }) }), + /manifest returned 404/, + ); +}); + +test("版本源:冷启动 ensure 立即返回兜底,后台完成后再升级", async () => { + let finish; + const pending = new Promise((resolve) => { + finish = resolve; + }); + const src = createVersionSource({ + fallback: "5.2.3", + fetchImpl: async () => { + await pending; + return new Response('[workspace.package]\nversion = "6.0.1"\n'); + }, + }); + assert.equal(src.get(), "5.2.3"); + assert.equal(await src.ensure(), "5.2.3"); + finish(); + await waitFor(() => src.get() === "6.0.1"); + assert.equal(src.get(), "6.0.1"); +}); + +test("TTL 内不重复拉取", async () => { + let calls = 0; + const src = createVersionSource({ + fallback: "5.2.3", + fetchImpl: async () => { + calls++; + return new Response('[workspace.package]\nversion = "6.0.1"\n'); + }, + }); + await src.ensure(); + await src.ensure(); + assert.equal(calls, 1); +}); + +test("拉取失败:退回兜底、标记 quiet,失败窗口内不再碰网、只回调一次 onError", async () => { + let calls = 0; + const logs = []; + const src = createVersionSource({ + fallback: "5.2.3", + failTtlMs: 60_000, + fetchImpl: async () => { + calls++; + throw new Error("offline"); + }, + onError: (e) => logs.push(e.message), + }); + assert.equal(await src.ensure(), "5.2.3"); + assert.equal(await src.ensure(), "5.2.3"); + assert.equal(calls, 1); + assert.deepEqual(logs, ["offline"]); +}); + +test("fetchAtomCodeVersion:超过 1 MiB 的清单边读边停,不会先整块吃下", async () => { + let pulls = 0; + const chunk = new Uint8Array(64 * 1024); + const stream = new ReadableStream({ + pull(controller) { + pulls += 1; + if (pulls > 200) return controller.close(); + controller.enqueue(chunk); + return undefined; + }, + }); + await assert.rejects( + fetchAtomCodeVersion({ fetchImpl: async () => new Response(stream, { status: 200 }) }), + /exceeds 1 MiB/, + ); + // 1 MiB / 64 KiB = 16 块;读到第 17 块就该中止,远不到 200。 + assert.ok(pulls <= 30, `应在越过上限时立刻停止读取,实际读了 ${pulls} 块`); +}); + +test("fetchAtomCodeVersion:上限之内的较大清单仍能解析出真实版本", async () => { + const padding = "#".repeat(200 * 1024); + const text = `[workspace.package]\nversion = "6.1.0"\n${padding}\n`; + const version = await fetchAtomCodeVersion({ + fetchImpl: async () => new Response(text, { status: 200 }), + }); + assert.equal(version, "6.1.0"); +}); + +test("poke:后台拉取完成后 get() 升级(宿主常驻场景)", async () => { + const src = createVersionSource({ + fallback: "5.2.3", + fetchImpl: async () => new Response('[workspace.package]\nversion = "6.0.0"\n'), + }); + assert.equal(src.get(), "5.2.3"); + src.poke(); + await new Promise((resolve) => setTimeout(resolve, 10)); + assert.equal(src.get(), "6.0.0"); +}); + +test("版本源报告来源并通过 onChange 通知持久化观察者", async () => { + const changes = []; + const src = createVersionSource({ + fallback: "5.2.3", + fetchImpl: async () => new Response('[workspace.package]\nversion = "6.2.0"\n'), + onChange: (status) => changes.push(status), + }); + assert.equal(src.status().source, "fallback"); + src.poke(); + await waitFor(() => src.get() === "6.2.0"); + assert.equal(src.status().source, "manifest"); + assert.equal(changes.at(-1).version, "6.2.0"); + assert.equal(changes.at(-1).live, true); +}); + +async function waitFor(predicate, timeoutMs = 1000) { + const deadline = Date.now() + timeoutMs; + while (!predicate()) { + if (Date.now() >= deadline) throw new Error("condition was not met before timeout"); + await new Promise((resolve) => setTimeout(resolve, 5)); + } +} diff --git a/packages/atomcode/version.mjs b/packages/atomcode/version.mjs new file mode 100644 index 0000000..775f404 --- /dev/null +++ b/packages/atomcode/version.mjs @@ -0,0 +1,215 @@ +/** + * Auto-tracking of the upstream AtomCode client version. + * + * Why track at all: the official client force-updates itself on launch, so the + * gateway most plausibly treats version freshness as part of looking like the + * client (Atom2Api ships a whole UA checker that reads the same manifest for + * exactly this concern). This module keeps the plugin on the current version + * without releases or user action. + * + * Behavior contract (deliberately gentle — a metadata fetch must never break a + * model request): + * + * - the manifest is a public file (`raw.atomgit.com`, same URL Atom2Api's + * `ua.go` reads); it is fetched with a short timeout and validated strict; + * - a TTL cache (12 h) plus a short failure retry window (5 min) keep the + * network load at one GET per host process, retrying quietly; + * - `ensure()` never waits for the network; it starts one background refresh + * and immediately returns the last known version; + * - the fallback is the built-in anchor constant, so an unreachable manifest + * degrades to exactly the behavior we shipped and verified live. + * + * The version feeds three places and they must agree — `User-Agent`, + * `X-AtomCode-Ver`, and the signing salt (`sha256(client_version)`). Any + * self-consistent version produces a valid signature; freshness is the only + * thing being chased here. + * + * @module magpie-atomcode/version + */ + +import { readCappedResponseText } from "./internal.mjs"; + +/** Atom2Api `ua.go` 同款 URL:官方仓库的 workspace 声明。 */ +export const ATOMCODE_CARGO_URL = "https://raw.atomgit.com/atomgit_atomcode/atomcode/raw/main/Cargo.toml"; + +/** On a fresh fetch this version is trusted for… */ +export const VERSION_TTL_MS = 12 * 3600_000; +/** …and after a failed fetch we stay quiet (and on the cached value) for… */ +export const VERSION_FAIL_TTL_MS = 5 * 60_000; +/** HTTP timeout for one background manifest fetch. */ +export const VERSION_TIMEOUT_MS = 10_000; + +/** Upstream reads `workspace.package.version` (go-toml), semantic. */ +const SEMVER = /^\d+\.\d+\.\d+(?:[-+][\w.-]+)?$/; + +/** + * Pull `workspace.package.version` out of a Cargo.toml text. + * + * Line-based on purpose (no TOML dependency): only the top-level + * `[workspace.package]` section is read, and only semantic versions count. + * `[package]` versions (like the example crate) are ignored, mirroring + * Atom2Api's manifest struct. + * + * @param {string} text + * @returns {string|null} the version, or null when absent/invalid. + */ +export function extractVersionFromManifest(text) { + if (typeof text !== "string") return null; + let inSection = false; + for (const line of text.split(/\r?\n/)) { + const section = line.match(/^\s*\[([^\]]+)\]\s*$/); + if (section) { + inSection = section[1] === "workspace.package"; + continue; + } + if (!inSection) continue; + const m = line.match(/^\s*version\s*=\s*"([^"]+)"/); + if (m) { + const version = m[1].trim(); + return SEMVER.test(version) ? version : null; + } + } + return null; +} + +/** download cap, mirroring Atom2Api's 1 MiB guard */ +const MAX_MANIFEST_BYTES = 1 << 20; + +/** + * Fetch and validate the version from the manifest. + * + * @param {{url?: string, fetchImpl?: Function, timeoutMs?: number}} [opts] + * @returns {Promise} a semantic version. + * @throws on network failure, non-2xx, oversize body, missing version. + */ +export async function fetchAtomCodeVersion({ + url = ATOMCODE_CARGO_URL, + fetchImpl = (...args) => fetch(...args), + timeoutMs = VERSION_TIMEOUT_MS, +} = {}) { + const res = await fetchImpl(url, { + redirect: "error", + headers: { accept: "text/plain" }, + signal: AbortSignal.timeout(timeoutMs), + }); + if (!res.ok) throw new Error(`AtomCode manifest returned ${res.status}`); + const text = await readCappedResponseText(res, { + maxBytes: MAX_MANIFEST_BYTES, + label: "AtomCode manifest", + }); + const version = extractVersionFromManifest(text); + if (!version) throw new Error("AtomCode manifest has no valid workspace.package.version"); + return version; +} + +/** + * A version source: cache + inflight + bounded refresh. + * + * @param {{fallback?: string, url?: string, fetchImpl?: Function, timeoutMs?: number, + * ttlMs?: number, failTtlMs?: number, onError?: Function}} [opts] + * @returns {{get(): string, isLive(): boolean, status(): object, ensure(): Promise, poke(): void}} + */ +export function createVersionSource({ + fallback = "0.0.0", + url, + fetchImpl, + timeoutMs, + ttlMs = VERSION_TTL_MS, + failTtlMs = VERSION_FAIL_TTL_MS, + onError, + onChange, +} = {}) { + // Seeded with the fallback so `get()` is meaningful before any network: + // at=0 means "stale", which is what makes the first ensure()/poke() fetch. + const cache = { at: 0, version: fallback ?? "0.0.0" }; + let failedAt = 0; + let inflight = null; + + async function refresh() { + if (inflight) return inflight; + inflight = (async () => { + try { + const version = await fetchAtomCodeVersion({ url, fetchImpl, timeoutMs }); + cache.at = Date.now(); + cache.version = version; + failedAt = 0; + try { + onChange?.({ + version, + source: "manifest", + checkedAt: cache.at, + failedAt: undefined, + live: true, + }); + } catch { + /* the observer is best-effort */ + } + return version; + } catch (error) { + failedAt = Date.now(); + try { + onError?.(error); + } catch { + /* the logger is best-effort */ + } + try { + onChange?.({ + version: cache.version, + source: cache.at ? "cached" : "fallback", + checkedAt: cache.at || undefined, + failedAt, + live: false, + }); + } catch { + /* the observer is best-effort */ + } + return undefined; + } finally { + inflight = null; + } + })(); + return inflight; + } + + const fresh = () => Date.now() - cache.at < ttlMs; + const quiet = () => Date.now() - failedAt < failTtlMs; + + return { + /** The current best version — synchronous, never throws. */ + get() { + return cache.version; + }, + /** True while the cache is inside its TTL. */ + isLive() { + return fresh(); + }, + /** Where the current version came from, for persisted diagnostics. */ + status() { + return { + version: cache.version, + source: cache.at ? (fresh() ? "manifest" : "cached") : "fallback", + checkedAt: cache.at || undefined, + failedAt: failedAt || undefined, + live: fresh(), + }; + }, + /** + * Best-effort current version. + * + * Always immediate: start one background refresh when stale and answer with + * the current cached version. The host-start poke normally completes before + * the first request, while an offline manifest can never delay it. + */ + async ensure() { + if (fresh()) return cache.version; + if (quiet()) return cache.version; + if (!inflight) refresh().catch(() => {}); + return cache.version; + }, + /** Fire-and-forget refresh for host startup; never throws. */ + poke() { + if (fresh() || quiet() || inflight) return; + refresh().catch(() => {}); + }, + }; +} diff --git a/registry.json b/registry.json index 9cd4eb6..6b6a981 100644 --- a/registry.json +++ b/registry.json @@ -3,6 +3,8 @@ "plugins": [ { "package": "@magpie-community/opencode-agnes-auth", "name": "Agnes AI", "icon": "https://www.agnes-ai.com/images/biglogo.png", "providers": ["agnes"], "community": true, "summary": { "en": "Agnes AI international with Chrome browser sign-in: live OpenAI-compatible text models, Token Plan and Agent Plan usage, and the USD wallet balance.", "zh": "通过 Chrome 浏览器登录 Agnes AI 国际版:动态发现 OpenAI 兼容文本模型,显示 Token Plan、Agent Plan 用量与美元余额,无需手动复制会话 token。" } }, + { "package": "@magpie-community/opencode-atomcode-auth", "name": "AtomCode", "icon": "https://atomgit.com/favicon.ico", "providers": ["atomcode"], "community": true, + "summary": { "en": "Unofficial AtomGit CodingPlan access for magpie and OpenCode: browser OAuth or local AtomCode CLI sign-in, signed OpenAI-compatible requests, live models, quota windows, and a read-only diagnostics page.", "zh": "非官方接入 AtomGit CodingPlan:支持浏览器 OAuth 或复用本机 AtomCode CLI 登录,发送签名请求,显示实时模型与额度窗口,并提供只读诊断页。" } }, { "package": "@magpie-community/gateway-powercontext", "name": "PowerContext", "kind": "middleware", "community": true, "icon": "https://raw.githubusercontent.com/oceanbase/powercontext/master/src/powercontext/server/dashboard/static/brand/favicon-color.svg", "summary": { "en": "Recall from your PowerContext service and optionally save complete conversations. Configure the service URL first; capture is off by default.", "zh": "从自己的 PowerContext 服务召回记忆,并按需存回完整对话。先配置服务地址;对话存回默认关闭。" } },