From 8765cf8f9c7953c1f52449f3d214856a923c8f79 Mon Sep 17 00:00:00 2001 From: LEOLI <273223592@qq.com> Date: Thu, 5 Nov 2026 16:54:02 +0800 Subject: [PATCH] atomcode 0.3.0: AtomGit CodingPlan provider plugin (LILEOO, #716) Adds packages/atomcode (@magpie-community/opencode-atomcode-auth 0.3.0), an AtomGit CodingPlan provider: browser OAuth and AtomCode CLI sign-in (~/.atomcode/auth.toml), signed requests to AtomGit's own gateway, per-account models and quota, daily claim, a loopback-only diagnostics page, and OpenCode 1.x/2.x entries. Registry and README entries added. By LILEOO. Reviewed at c57b099fff4689c0198c1c6414f04b27614b4092. The last blocking point (an inline TOML comment on a known line went into the uid and was written back) is fixed: values end at an unquoted #, quoted/escaped/literal strings keep their #, and a rewritten line keeps its comment. Run on a separate test machine (Bun 1.4.2, sandbox HOME): - PR head merged onto origin/main 24da52b8: bun scripts/check.mjs exit 0 (atomcode ok); whole-repo bun test 6103 pass, 0 fail. origin/main alone: 5942 pass, 0 fail. - packages/atomcode at the head: bun test 161 pass; node --test test/*.test.mjs 161 pass. - The new auth-file test against 55ff272's auth-file.mjs: red (1 fail), green at the head. - Probe: the review's file (id = "123456" # c) parses to uid 123456 and renders back as id = "123456" # c; also #c with no space, CRLF with a tab before #, "1#2", and a literal-string id all round-trip to the same uid. At 55ff272 each gave a uid with the comment in it. Not tried: a real AtomGit account. A [user] header with a trailing comment is refused ("no user id"), not corrupted; the CLI never writes one. First npm version needs an owner publish; until then magpie installs it from the dist branch. --- README.md | 1 + packages/atomcode/CHANGELOG.md | 130 ++ packages/atomcode/LICENSE | 21 + packages/atomcode/NOTICE.md | 26 + packages/atomcode/README.md | 233 +++ packages/atomcode/README.zh-CN.md | 209 +++ packages/atomcode/SECURITY.md | 38 + packages/atomcode/assets/atomcode.ico | Bin 0 -> 9662 bytes packages/atomcode/auth-file.mjs | 344 ++++ packages/atomcode/codingplan.mjs | 262 ++++ packages/atomcode/diagnostics.mjs | 445 ++++++ packages/atomcode/docs/diagnostics.jpg | Bin 0 -> 130223 bytes packages/atomcode/errors.mjs | 169 ++ packages/atomcode/i18n.mjs | 190 +++ packages/atomcode/index.mjs | 1324 ++++++++++++++++ packages/atomcode/internal.mjs | 294 ++++ packages/atomcode/models.mjs | 228 +++ packages/atomcode/oauth.mjs | 167 ++ packages/atomcode/opencode.mjs | 2 + packages/atomcode/opencode2.mjs | 594 +++++++ packages/atomcode/package.json | 92 ++ packages/atomcode/page/app.css | 738 +++++++++ packages/atomcode/page/app.js | 869 +++++++++++ packages/atomcode/page/boot.js | 60 + packages/atomcode/page/diagnostics.html | 262 ++++ packages/atomcode/page/icon.svg | 11 + packages/atomcode/page/index.html | 51 + packages/atomcode/quota.mjs | 226 +++ packages/atomcode/request-body.mjs | 147 ++ packages/atomcode/scripts/live-smoke.mjs | 98 ++ packages/atomcode/sign.mjs | 120 ++ packages/atomcode/state.mjs | 371 +++++ packages/atomcode/test/auth-file.test.mjs | 241 +++ packages/atomcode/test/codingplan.test.mjs | 202 +++ packages/atomcode/test/diagnostics.test.mjs | 362 +++++ packages/atomcode/test/errors.test.mjs | 98 ++ packages/atomcode/test/i18n.test.mjs | 33 + packages/atomcode/test/internal.test.mjs | 134 ++ packages/atomcode/test/models.test.mjs | 182 +++ packages/atomcode/test/oauth.test.mjs | 114 ++ packages/atomcode/test/plugin.test.mjs | 1468 ++++++++++++++++++ packages/atomcode/test/quota.test.mjs | 246 +++ packages/atomcode/test/request-body.test.mjs | 139 ++ packages/atomcode/test/sign.test.mjs | 58 + packages/atomcode/test/state.test.mjs | 177 +++ packages/atomcode/test/version.test.mjs | 146 ++ packages/atomcode/version.mjs | 215 +++ registry.json | 2 + 48 files changed, 11539 insertions(+) create mode 100644 packages/atomcode/CHANGELOG.md create mode 100644 packages/atomcode/LICENSE create mode 100644 packages/atomcode/NOTICE.md create mode 100644 packages/atomcode/README.md create mode 100644 packages/atomcode/README.zh-CN.md create mode 100644 packages/atomcode/SECURITY.md create mode 100644 packages/atomcode/assets/atomcode.ico create mode 100644 packages/atomcode/auth-file.mjs create mode 100644 packages/atomcode/codingplan.mjs create mode 100644 packages/atomcode/diagnostics.mjs create mode 100644 packages/atomcode/docs/diagnostics.jpg create mode 100644 packages/atomcode/errors.mjs create mode 100644 packages/atomcode/i18n.mjs create mode 100644 packages/atomcode/index.mjs create mode 100644 packages/atomcode/internal.mjs create mode 100644 packages/atomcode/models.mjs create mode 100644 packages/atomcode/oauth.mjs create mode 100644 packages/atomcode/opencode.mjs create mode 100644 packages/atomcode/opencode2.mjs create mode 100644 packages/atomcode/package.json create mode 100644 packages/atomcode/page/app.css create mode 100644 packages/atomcode/page/app.js create mode 100644 packages/atomcode/page/boot.js create mode 100644 packages/atomcode/page/diagnostics.html create mode 100644 packages/atomcode/page/icon.svg create mode 100644 packages/atomcode/page/index.html create mode 100644 packages/atomcode/quota.mjs create mode 100644 packages/atomcode/request-body.mjs create mode 100644 packages/atomcode/scripts/live-smoke.mjs create mode 100644 packages/atomcode/sign.mjs create mode 100644 packages/atomcode/state.mjs create mode 100644 packages/atomcode/test/auth-file.test.mjs create mode 100644 packages/atomcode/test/codingplan.test.mjs create mode 100644 packages/atomcode/test/diagnostics.test.mjs create mode 100644 packages/atomcode/test/errors.test.mjs create mode 100644 packages/atomcode/test/i18n.test.mjs create mode 100644 packages/atomcode/test/internal.test.mjs create mode 100644 packages/atomcode/test/models.test.mjs create mode 100644 packages/atomcode/test/oauth.test.mjs create mode 100644 packages/atomcode/test/plugin.test.mjs create mode 100644 packages/atomcode/test/quota.test.mjs create mode 100644 packages/atomcode/test/request-body.test.mjs create mode 100644 packages/atomcode/test/sign.test.mjs create mode 100644 packages/atomcode/test/state.test.mjs create mode 100644 packages/atomcode/test/version.test.mjs create mode 100644 packages/atomcode/version.mjs 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 0000000000000000000000000000000000000000..363e6d99fd1bdcb86ebcab6e41fc1103fdc55026 GIT binary patch literal 9662 zcmd5?eP~r>7(d#W5}_8cmR8!D^KQFeio~$x*8HAxo4dE@5B~@m{vi<}B`IQte+&@` z2@#QykT400kQx!;B1egsNgrmloGtTX&CS-lyWY*)?|Gi{ob%qhyWP9nZZtVQ?|IMr z@q2#n?|I($oXxT(;a@Ol;r}_-yK^n8z_Kh4E>u}B;G%l|DHfB9|L4}6$}6t=tkB=s zyU4rdkLP^#H(s3o?9g^xJA&cpmh!sG&3INjZ|NCN*{X|EbAe&JW6oRlb%DR3=lNhL zawHJC-4%Q`77vDp>}!m2Xs{pc+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|gD(|$-(ClQw&2}A9P;N zvUB<1wp;zx^<++rHK5o47mKyu|H%fLZoflX=XHQ4xy;z@I>sK0m#@B5^nb#wSny6? z>G18uz7fadQz+7n9GaE>b)H;V&+>2cptbX&AvY&DT0*{qK3j7&|3r*S-*DU*7?}$Y z|NF{UcP@pWFCoVEq3sd)^p>xo=S7^svi@$5F=t@B#~$)*b8=!f{>*)*9dR6yy^Qo? zU%a1@rfAP$YsZ994u+z=I7=Qy-e~r&x#BID_e#oKVd8q?>5ub~%lFy)Ta3z-*82Hp@r)4;5OURJ161ed}-$$$wx+=<|^m8=*`VrghSes&(Pc%zM z-=VR_Ctt7z&Fb%XEn=zwbNp=PAK{6x3Ad^x@dx#!E#`9cGRBC(hZgX2N!n9eTbIOx zQO5jPoww9i+N)?C6{ntg>0ZmKF>RwZ(|R4p98=542?rEQwiY^l1U_(1Vts;NwyM`u z_vW(<%B+2DrxxQPr*6y^x7ly*GpFuFUONQbeEwB_nCql9H`hOH*^Yf4XGA%Ay}b5U z`ZIzF`+;upt{Lre;+6HDqFIk3l(*ouPt@Pq+32EsRMeAA%c0~@~^ z<29$)qqrb_NttzFms8bCo$W98L*G#30?z0o&iDp|2`QGX`e~-0_6fYxP&}vx(&Zmn z8>7A8jv*hlgY%~1>d*hvZCPv@K+^tUR&>&Ls- zg#CR(oPR7U9^W}B9)}&WtSYj7mNlJhn`PZYb|?Ohh%EW=nq}Q3TV+{j&UTROY|HAi zUK_He!(z0ZQ!J} 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 0000000000000000000000000000000000000000..4fe92dbd749a7b42f40dc1c7ea7de6ea521485b0 GIT binary patch literal 130223 zcmeFZ2{@JQ_b~cwdz+KY^Gu46dA3RB5M>UTX&W-nwg{Pv5Q;>`Q0A#5Qz$ZLwh5Ux zh0Wf!@6r4AzVGk%{r>0t&$-TZedjvoyLCU$de*(xy4PCw{XF-&huz87lX>8rwz`%& z0D%C2Cin-Opa5mH02fC9(A5P5001BXATcfg41_=ufEmmHK=7R4H-<3aIrKLSRX!~| z*#u;+JA3$ecsqOC_IpIgfDq#aCUt@4DIq{(AU-^5W*|3;OF_RYiTRnXc zrUv12E}(UP!racjnnoZD(i2G7d8>lH1n5Cn)7$li)}MGQdz-5|APoA6z{|m1Rpn27 zlB0|IDGk_L2wu3m>Ye)Tl()*oN9!gCGlK9(2XD0-f8yu8JPd#9u( zPyGf(+u8imAG8IEb8uJr?W-gQZ_`uVPW`!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ACY4v}K0ojG1@TppXwbMuJ&|lj|E|6<3Z1t!;`70AgrQl)qPtAj& zK+T_R#@|@7Cc0yZ9e{zF9|6+%A2sB^ROvrOm43a8e!cepi4`IL>015runyhR|GtMM z2q3TkzwBQ*WSk;^ADO5@NiJ(!_m503JK)&@PGobR$?FE@_s<@FSxDNaxI+d;b7_ES zBNrS6VMW3$h;>S-ZSsK<@+#RFWqM$%WLj~oFbX;Z+#}b<+e-jqFG%Wknp*@*f1`+mWFYc7h>18k5+u3${}PsE zAOasLK5&5^!VU9}9)R+Xe4Si(Hi{>~>nd}K^El`ZN67eB)N&w%aw+3=d{i}W#Ap8M zV)2t5%?V;ZaeTexIfwk@=|@p*L`#QsqVCs^ z{gT-sKJ%Aq{Cb=YfxiEHtj1M_0;{Vh&Tfhcy_pI-fFjMZSHOGQsHxxZ$icK#*p2Jd z0OjtFEDd=dP`Of(pa?BgYH~5c+AuS_$xbLYJu~o%CE-Rx8t%gW3BOSwf1zc)<19Q7 zOzo?Nl#WV1UTmAMIWO$f@nq@!E%>_1IjA>CbJTVwuYO0o} z(lPh(-IZ^mSvwB{9s!hjx@MEb_?r#W*aPxq!qufLw7eOP>s=523~~XWL*hh)s+lMu uD{^dxhxPS~_$qqW^O%zKO-U; literal 0 HcmV?d00001 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 服务召回记忆,并按需存回完整对话。先配置服务地址;对话存回默认关闭。" } },