add cloudflare-workers-ai: Cloudflare Workers AI provider plugin (#326)

New community provider plugin @magpie-community/opencode-cloudflare-workers-ai-auth 0.0.1 (Guislabert): signs in to Cloudflare Workers AI with an API token and Account ID, lists the models models.dev has under cloudflare-workers-ai, marks the 8 paid-only models "(Paid)", and adds a Neurons/day quota row. registry.json gains its one entry.

Run at the reviewed head 84b3aaf (based on origin/main):
- bun scripts/check.mjs cloudflare-workers-ai: ok
- node --test in the package under a temp HOME: 12 of 12 pass
- models.dev outage repro (stubbed fetch, discoveryTTLMs 1, catalog reachable then down): the second request still goes out ("down: sent 2"). At 6e9fd73 it failed; review asked for this.
- registry.json diff against main: the one new entry only

Not tried: a real Cloudflare account; no request reached Cloudflare.
This commit is contained in:
Guislabert
2026-10-23 07:08:14 +08:00
committed by GitHub
parent 5ab7df285b
commit dbcd4e9464
9 changed files with 1210 additions and 1 deletions
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 Guislabert
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.
+154
View File
@@ -0,0 +1,154 @@
# @magpie-community/opencode-cloudflare-workers-ai-auth
[English](README.md) | [简体中文](README.zh-CN.md) | 日本語
[![npm version](https://img.shields.io/badge/npm%20version-0.0.1-EA4335.svg)](https://www.npmjs.com/package/@magpie-community/opencode-cloudflare-workers-ai-auth)
[![License: MIT](https://img.shields.io/badge/License-MIT-FBBC05.svg)](https://opensource.org/licenses/MIT)
[OpenCode](https://opencode.ai) 1.x と [magpie](https://usemagpie.ai) 向けのプロバイダー
プラグイン。API トークンで **Cloudflare Workers AI** にサインインし、どのエージェントでも
使えるプロバイダーとして提供します。[models.dev](https://models.dev) から 28+ モデルを
リアルタイム取得、有料専用モデルには目印、
`magpie quota` には 1 日あたりの Neurons 余裕枠が表示されます。
> Cloudflare とは提携・承認関係にありません。
## 必要なもの
| 項目 | 在処 |
|---|---|
| Cloudflare Account ID | ダッシュボードの **Account home** → 右sidebar の 32 桁 hex |
| Cloudflare API トークン | ダッシュボード → アバター → **My Profile** → API Tokens → カスタムトークンを `Account → Workers AI → Edit` で作成(`magpie quota` でプラン名まで表示したい場合は `Account Settings → Read` も追加) |
| magpie | 0.1.1110 以降、または OpenCode 1.x |
トークンに Zone の選択は不要。Free/Paid 両プランに **1 日 10,000 Neurons** の無料枠が
つき、8 つのフロンティアモデルだけ Workers Paid または AI Gateway クレジットが必要です(下記の目印)。
## magpie へのインストール
```sh
magpie plugin add @magpie-community/opencode-cloudflare-workers-ai-auth # npm から
magpie plugin add /path/to/folder # ローカルコピー
```
サインイン:
```sh
magpie plugin login cloudflare-workers-ai
```
| 入力 | 内容 |
|---|---|
| API Token | 上の Workers AI:Edit トークン |
| Account ID(任意) | 32 桁 hex。空欄ならプラグイン options の `accountId` を使用 |
- サインイン 1 回 = アカウント 1 つ。もう一度サインインするとアカウントを追加
(例:Free と Paid を並べる)— magpie が自動フェイルオーバーし、`magpie quota`
には各行が分けて表示されます。
- 同じ Account IDで再サインインすると同じアカウントを差し替え(トークンをローテーション)。
- Cloudflare がトークンを拒んだら、magpie がそのアカウントに申し込み直しを要求します。
## よく使うコマンド
```sh
magpie providers # サインイン済みか
magpie provider test cloudflare-workers-ai # 小さな 1 リクエスト(サンドボックスで約 300 ms)
magpie provider test cloudflare-workers-ai @cf/meta/llama-3.3-70b-instruct-fp8-fast
magpie quota # プラン + Neurons/日
magpie claude cloudflare-workers-ai/@cf/meta/llama-3.3-70b-instruct-fp8-fast # Claude Code で使用
magpie codex cloudflare-workers-ai/@cf/openai/gpt-oss-120b # Codex でも同様
magpie plugin logout cloudflare-workers-ai # サインインを削除
```
モデル名は `cloudflare-workers-ai/@cf/<org>/<model>` — [models.dev](https://models.dev) の
カタログ ID そのままで、1 時間ごとに更新されます。
### OpenCode 1.x での使い方
`opencode.json`:
```json
{ "plugin": ["@magpie-community/opencode-cloudflare-workers-ai-auth"] }
```
その後 `opencode auth login` → Cloudflare Workers AI(同じ 2 項目)。
## 有料専用モデル
Workers Paid または AI Gateway クレジットが必要な 8 モデルは名前に半角括号の **(Paid)** を付けます:
`@cf/moonshotai/kimi-k2.6`、
`@cf/moonshotai/kimi-k2.7-code`、`@cf/zai-org/glm-5.2`、`@cf/zai-org/glm-5.3`、
`@cf/zai-org/glm-5.3-flash`、`@cf/deepseek-ai/deepseek-v4-flash-0731`、
`@cf/deepseek-ai/deepseek-v4.1-flash-1017`、
`@cf/deepseek-ai/deepseek-v4-pro-0813` です。
それ以外のモデルは 1 日 10,000 Neurons の共有枠に含まれ(Paid では超過分に課金)、free バッジは付けません。
## オプション
```sh
magpie plugin options opencode-cloudflare-workers-ai-auth '{"accountId": "…", "discoveryTTLMs": 1800000}'
```
| オプション | 既定 | 説明 |
|---|---|---|
| `accountId` | — | サインインで空欄のときの既定 Account ID |
| `apiKey` | — | 既定トークン(サインインのキーが優先) |
| `baseTemplate` | 下記参照 | 差し込み先の URL テンプレート |
| `discoveryTTLMs` | `3600000` | カタログ再取得間隔 |
**`baseTemplate` のデフォルト**(差し込み先、Account ID はアカウント毎に注入):
```
https://api.cloudflare.com/client/v4/accounts/${CLOUDFLARE_ACCOUNT_ID}/ai/v1
```
## トラブルシューティング
| 表示 | 意味 |
|---|---|
| モデル一覧が空・プロバイダーが見えない | `magpie plugin add .` をやり直し、`magpie plugin --json` の `error` を確認(カタログ取得失敗、トークン拒否) |
| `magpie: the sign-in failed: 需要 API Token` | トークン入力が空 — `magpie plugin login cloudflare-workers-ai` をやり直す |
| `provider test` で 401 `Authentication error` | トークン拒否:権限(`Workers AI:Edit`)を確認し再サインイン |
| `provider test` で 403 | トークンと Account ID の不一致 |
| 400 `No route for that URI` | `plugin add` 再実行後も出るなら、古いプラグインが残っている可能性 — 最新版 URL 正規化で解決済み、要 issue |
| `Model … absent from the current catalog` | models.dev の cloudflare-workers-ai セクションにない ID — 一覧から選ぶ |
| (Paid) モデルで 400 | プランが Free:Workers Paid か AI Gateway クレジットが必要 |
| quota 行がプラン名の代償テキスト | トークンに `Account Settings → Read` がない — 表示だけの問題で Neurons 枠は出る |
## 開発
```sh
node --check src/index.mjs # パース検査(元リポジトリのバグ)
node --test # 11 テスト、ネットワーク不要
sh scripts/sandbox.sh login # magpie 0.1.1326 を使い捨て HOME で
sh scripts/sandbox.sh test # サンドボックス内で provider test
sh scripts/sandbox.sh json # サンドボックス内で plugin --json
```
`scripts/sandbox.sh` の HOME は `.sandbox/`(git 無視)なので、本物の magpie・エージェント・
サインインには触れません。
## プラグイン契約のメモ
- 単一 async プラグイン関数。`config`、`auth.methods`(`password` prompts 付きの 1 つの
`api` メソッド)、`auth.loader`、`auth.usage`、`provider.models` を書き出す
- `loader(getAuth, provider)` は契約アカウント形(`auth.key`、`auth.metadata.accountId`)を
読む。OpenCode の旧マルチメソッド形も受ける
- `authorize` は `{ type: "success", key, metadata }` / `{ type: "failed", error }` を返す
- カタログ取得失敗時、`config()` は空のモデル一覧に落として例外化しない。その後アカウント毎の
`provider.models` がキャッシュ済みカタログを提供
- 単一ファイル、実行時依存ゼロ、ESM、`node >= 20`
## バージョン / ライセンス
| | |
|---|---|
| **バージョン** | [`0.0.1`](CHANGELOG.md) |
| **ライセンス** | [MIT](LICENSE) — Copyright (c) 2026 Guislabert |
| **ランタイム** | Node.js >= 20、ESM のみ |
| **作者** | [@Guislabert](https://github.com/Guislabert) |
| **言語** | [English](README.md) · [简体中文](README.zh-CN.md) |
MIT © [Guislabert](https://github.com/Guislabert)
+161
View File
@@ -0,0 +1,161 @@
# @magpie-community/opencode-cloudflare-workers-ai-auth
English | [简体中文](README.zh-CN.md) | [日本語](README.ja.md)
[![npm version](https://img.shields.io/badge/npm%20version-0.0.1-EA4335.svg)](https://www.npmjs.com/package/@magpie-community/opencode-cloudflare-workers-ai-auth)
[![License: MIT](https://img.shields.io/badge/License-MIT-FBBC05.svg)](https://opensource.org/licenses/MIT)
A provider plugin for [OpenCode](https://opencode.ai) 1.x and
[magpie](https://usemagpie.ai) that signs in to **Cloudflare Workers AI** with your
API token and serves it as a provider every agent can use: 28+ models discovered
live from [models.dev](https://models.dev), paid-only models flagged,
and a daily Neurons allowance row in `magpie quota`.
> Not affiliated with or endorsed by Cloudflare.
## What you need
| Item | Where to find it |
|---|---|
| Cloudflare Account ID | 32 hex characters, on the dashboard's **Account home** → right sidebar |
| Cloudflare API token | Dashboard → avatar → **My Profile** → API Tokens → create a **Custom Token** with `Account → Workers AI → Edit` (add `Account Settings → Read` if you also want the plan name in `magpie quota`) |
| magpie | 0.1.1110 or later, or OpenCode 1.x |
No zones need to be selected on the token. Free and Paid plans both get
**10,000 Neurons/day** free; eight frontier models need Workers Paid or prepaid
AI Gateway credits (flagged below).
## Install in magpie
```sh
magpie plugin add @magpie-community/opencode-cloudflare-workers-ai-auth # from npm
magpie plugin add /path/to/folder # local copy
```
Then sign in:
```sh
magpie plugin login cloudflare-workers-ai
```
| Prompt | What to enter |
|---|---|
| API Token | the Workers AI:Edit token from the table above |
| Account ID (optional) | 32 hex characters; leave empty to use the plugin's `accountId` option |
- Each sign-in is one account. Sign in again to add another one (e.g. a Free
account and a Paid account) — magpie fails over between them automatically;
`magpie quota` shows each account's row separately.
- Sign in again with the same Account ID to replace that account, e.g. to rotate
the token. Sign-ins are kept in magpie's account storage; nothing is written
outside magpie's config.
- If Cloudflare refuses the token, magpie marks the account and asks you to sign
in again.
## Commands you'll actually use
```sh
magpie providers # is the provider signed in?
magpie provider test cloudflare-workers-ai # one small request (~300 ms in our sandbox)
magpie provider test cloudflare-workers-ai @cf/meta/llama-3.3-70b-instruct-fp8-fast
magpie quota # plan + Neurons/day window
magpie claude cloudflare-workers-ai/@cf/meta/llama-3.3-70b-instruct-fp8-fast # run Claude Code on it
magpie codex cloudflare-workers-ai/@cf/openai/gpt-oss-120b # or Codex, same idea
magpie plugin logout cloudflare-workers-ai # remove the sign-in
```
Models are named `cloudflare-workers-ai/@cf/<org>/<model>` — the same IDs
[models.dev](https://models.dev) lists for the provider, refreshed hourly.
### In OpenCode 1.x
`opencode.json`:
```json
{ "plugin": ["@magpie-community/opencode-cloudflare-workers-ai-auth"] }
```
then `opencode auth login` → Cloudflare Workers AI (same two fields).
## Paid-only models
Eight models are gated by Cloudflare behind Workers Paid or prepaid AI Gateway
credits and are flagged ** (Paid)** in the name — that is exactly how the
model picker renders it:
`@cf/moonshotai/kimi-k2.6`,
`@cf/moonshotai/kimi-k2.7-code`, `@cf/zai-org/glm-5.2`, `@cf/zai-org/glm-5.3`,
`@cf/zai-org/glm-5.3-flash`, `@cf/deepseek-ai/deepseek-v4-flash-0731`,
`@cf/deepseek-ai/deepseek-v4.1-flash-1017`,
`@cf/deepseek-ai/deepseek-v4-pro-0813`
Everything else counts only against the shared 10,000 Neurons/day allowance
(billed on a Paid account past it), so no model carries a free badge by design.
## Options
```sh
magpie plugin options opencode-cloudflare-workers-ai-auth '{"accountId": "…", "discoveryTTLMs": 1800000}'
```
| Option | Default | Notes |
|---|---|---|
| `accountId` | — | default Account ID used when a sign-in leaves it empty |
| `apiKey` | — | default token (the sign-in's key wins) |
| `baseTemplate` | see below | template target that the Account ID is interpolated into |
| `discoveryTTLMs` | `3600000` | catalog refresh interval |
**`baseTemplate` default** (insertion target, Account ID interpolated per account):
```
https://api.cloudflare.com/client/v4/accounts/${CLOUDFLARE_ACCOUNT_ID}/ai/v1
```
## Troubleshooting
| You see | Meaning |
|---|---|
| Model list empty, provider missing | `magpie plugin add .` again, then `magpie plugin --json`: the `error` field says why (catalog fetch failed, or the token was refused) |
| `magpie: the sign-in failed: 需要 API Token` | the token prompt was left empty — re-run `magpie plugin login cloudflare-workers-ai` |
| 401 `Authentication error` from `provider test` | the token was refused: check scope (`Workers AI:Edit`) or sign in again |
| 403 from `provider test` | token and Account ID don't match |
| 400 `No route for that URI` | if this survives a re-`plugin add`, it's a stale plugin version — the current proxy normalizes template URLs; file an issue |
| `Model … absent from the current catalog` | the model id isn't in models.dev's cloudflare-workers-ai section; pick a listed model |
| 400 on a (Paid) model | your plan is Free and the model needs Workers Paid or AI Gateway credits |
| Quota row shows the fallback plan text | the token lacks `Account Settings → Read`; the escalation is purely cosmetic — the Neurons window is still shown |
## Development
```sh
node --check src/index.mjs # parse guard (the upstream bug that started this fork)
node --test # 11 tests, no network needed
sh scripts/sandbox.sh login # magpie 0.1.1326 in a throwaway HOME
sh scripts/sandbox.sh test # provider test inside that sandbox
sh scripts/sandbox.sh json # plugin --json inside that sandbox
```
`scripts/sandbox.sh` keeps its HOME in `.sandbox/` (git-ignored), so your real
magpie, agents and sign-ins are never touched.
## Plugin contract notes
- Single async plugin function; `config`, `auth.methods` (one `api` method with
`password` prompts), `auth.loader`, `auth.usage` and `provider.models` hooks
- `loader(getAuth, provider)` reads the contract account shape (`auth.key`,
`auth.metadata.accountId`); the legacy OpenCode multi-method shape works too
- `authorize` returns `{ type: "success", key, metadata }` / `{ type: "failed", error }`
- On catalog failure at load, `config()` degrades to an empty model list instead
of throwing; the per-account `provider.models` serves the cached catalog after
- One file, zero runtime dependencies, ESM, `node >= 20`
## Version / license
| | |
|---|---|
| **Version** | [`0.0.1`](CHANGELOG.md) |
| **License** | [MIT](LICENSE) — Copyright (c) 2026 Guislabert |
| **Runtime** | Node.js >= 20, ESM only |
| **Author** | [@Guislabert](https://github.com/Guislabert) |
| **中文** | [README.zh-CN.md](README.zh-CN.md) |
MIT © [Guislabert](https://github.com/Guislabert)
@@ -0,0 +1,154 @@
# @magpie-community/opencode-cloudflare-workers-ai-auth
[English](README.md) | 简体中文 | [日本語](README.ja.md)
[![npm version](https://img.shields.io/badge/npm%20version-0.0.1-EA4335.svg)](https://www.npmjs.com/package/@magpie-community/opencode-cloudflare-workers-ai-auth)
[![License: MIT](https://img.shields.io/badge/License-MIT-FBBC05.svg)](https://opensource.org/licenses/MIT)
面向 [OpenCode](https://opencode.ai) 1.x 和 [magpie](https://usemagpie.ai) 的供应商插件:
用你的 API Token 登录 **Cloudflare Workers AI**,让它成为所有 Agent 都能选的供应商。
从 [models.dev](https://models.dev) 实时发现 28+ 个模型,付费专属模型自动标注,
付费专属模型自动打标,`magpie quota` 显示每日 Neurons 额度窗口。
> 与 Cloudflare 无隶属或背书关系。
## 前置要求
| 项目 | 在哪里找 |
|---|---|
| Cloudflare Account ID | 控制台首页(Account home)右侧栏,32 位十六进制 |
| Cloudflare API Token | 控制台 → 头像 → **My Profile** → API Tokens → 创建 **Custom Token**,授权 `Account → Workers AI → Edit`(想让 `magpie quota` 显示套餐名,再加 `Account Settings → Read`) |
| magpie | 0.1.1110 及以上,或 OpenCode 1.x |
Token 不需要选择任何 Zone。Free 与 Paid 两个计划均含 **每日 10,000 Neurons** 免费额度;
有 8 个前沿模型需要 Workers Paid 或 AI Gateway 预充值(下文有标注)。
## 在 magpie 中安装
```sh
magpie plugin add @magpie-community/opencode-cloudflare-workers-ai-auth # 从 npm
magpie plugin add /path/to/folder # 本地副本
```
然后登录:
```sh
magpie plugin login cloudflare-workers-ai
```
| 提示 | 填什么 |
|---|---|
| API Token | 上表中的 Workers AI:Edit token |
| Account ID(可选) | 32 位十六进制;留空则使用插件 options 里的 `accountId` |
- 每次登录 = 一个账号。再登录一次即可添加新账号(比如 Free 账号 + Paid 账号)——
magpie 会在它们之间自动故障切换(failover),`magpie quota` 会分账号显示。
- 用相同 Account ID 再次登录会替换该账号(例如轮换 token)。登录信息只保存在
magpie 自己的账号存储里,不会写到其他地方。
- 如果 Cloudflare 拒绝 token,magpie 会标记该账号并提示重新登录。
## 你实际会用到的命令
```sh
magpie providers # 已登录?
magpie provider test cloudflare-workers-ai # 一条小请求(沙盒约 300 ms)
magpie provider test cloudflare-workers-ai @cf/meta/llama-3.3-70b-instruct-fp8-fast
magpie quota # 套餐 + Neurons/日 窗口
magpie claude cloudflare-workers-ai/@cf/meta/llama-3.3-70b-instruct-fp8-fast # 让 Claude Code 用上
magpie codex cloudflare-workers-ai/@cf/openai/gpt-oss-120b # Codex 同理
magpie plugin logout cloudflare-workers-ai # 删除登录
```
模型命名为 `cloudflare-workers-ai/@cf/<org>/<model>`——ID 与
[models.dev](https://models.dev) 中该供应商的目录一致,每小时刷新。
### 在 OpenCode 1.x 中使用
`opencode.json`:
```json
{ "plugin": ["@magpie-community/opencode-cloudflare-workers-ai-auth"] }
```
然后 `opencode auth login` → Cloudflare Workers AI(同样的两个字段)。
## 付费专属模型
8 个模型被 Cloudflare 限制在 Workers Paid 或 AI Gateway 预充值之后,名字中标注 **(Paid)**:
`@cf/moonshotai/kimi-k2.6`、
`@cf/moonshotai/kimi-k2.7-code`、`@cf/zai-org/glm-5.2`、`@cf/zai-org/glm-5.3`、
`@cf/zai-org/glm-5.3-flash`、`@cf/deepseek-ai/deepseek-v4-flash-0731`、
`@cf/deepseek-ai/deepseek-v4.1-flash-1017`、
`@cf/deepseek-ai/deepseek-v4-pro-0813`
其余模型只消耗共享的每日 10,000 Neurons 额度(Paid 计划超出部分会计费),
因此设计上不给任何模型打 free 徽章。
## 插件选项
```sh
magpie plugin options opencode-cloudflare-workers-ai-auth '{"accountId": "…", "discoveryTTLMs": 1800000}'
```
| 选项 | 默认值 | 说明 |
|---|---|---|
| `accountId` | — | 登录时留空所用的默认 Account ID |
| `apiKey` | — | 默认 token(登录时的 key 优先) |
| `baseTemplate` | 见下方 | 插值目标,Account ID 会注入其中 |
| `discoveryTTLMs` | `3600000` | 目录刷新间隔 |
**`baseTemplate` 默认值**(插值目标,Account ID 按账号注入):
```
https://api.cloudflare.com/client/v4/accounts/${CLOUDFLARE_ACCOUNT_ID}/ai/v1
```
## 排障
| 你看到 | 意味着 |
|---|---|
| 模型列表为空 / 供应商没出现 | 重新 `magpie plugin add .`,再看 `magpie plugin --json` 的 `error` 字段(目录拉取失败或 token 被拒) |
| `magpie: the sign-in failed: 需要 API Token` | token 输入框留空了——重新执行 `magpie plugin login cloudflare-workers-ai` |
| `provider test` 返回 401 `Authentication error` | token 被拒:核对权限(`Workers AI:Edit`)或重新登录 |
| `provider test` 返回 403 | token 与 Account ID 不匹配 |
| 400 `No route for that URI` | 重新 `plugin add` 后仍出现,说明插件是旧版本——现版本代理已做 URL 归一化,可提 issue |
| `Model … absent from the current catalog` | 模型 ID 不在 models.dev 的 cloudflare-workers-ai 分节里,请从列表中选择 |
| (Paid) 模型返回 400 | 你的计划是 Free,该模型需要 Workers Paid 或 AI Gateway 预充值 |
| quota 行显示套餐兜底文案 | token 缺 `Account Settings → Read`;仅影响显示,Neurons 窗口照常展示 |
## 开发
```sh
node --check src/index.mjs # 语法防线(本 fork 起初修的核心 bug)
node --test # 11 项测试,无需联网
sh scripts/sandbox.sh login # 在一个用完即弃的 HOME 里跑 magpie
sh scripts/sandbox.sh test # 沙盒内 provider test
sh scripts/sandbox.sh json # 沙盒内 plugin --json
```
`scripts/sandbox.sh` 的 HOME 固定在 `.sandbox/`(已 git-ignore),不会碰你真实
的 magpie、Agent 和登录信息。
## 插件契约要点
- 单一 async 插件函数;导出 `config`、`auth.methods`(带 `password` prompts 的单一
`api` 方式)、`auth.loader`、`auth.usage`、`provider.models`
- `loader(getAuth, provider)` 按契约账号形态读取(`auth.key`、
`auth.metadata.accountId`);兼容 OpenCode 旧的多方法形态
- `authorize` 返回 `{ type: "success", key, metadata }` / `{ type: "failed", error }`
- 目录拉取失败时,`config()` 降级为空模型列表而不是抛错;随后账号级
`provider.models` 提供缓存目录
- 单文件、零运行时依赖、ESM,`node >= 20`
## 版本 / 许可证
| | |
|---|---|
| **版本** | [`0.0.1`](CHANGELOG.md) |
| **许可证** | [MIT](LICENSE) — Copyright (c) 2026 Guislabert |
| **运行时** | Node.js >= 20,仅 ESM |
| **作者** | [@Guislabert](https://github.com/Guislabert) |
| **语言** | [English](README.md) · [日本語](README.ja.md) |
MIT © [Guislabert](https://github.com/Guislabert)
+4
View File
@@ -0,0 +1,4 @@
import { CloudflareWorkersAIPlugin } from "./src/index.mjs";
export { CloudflareWorkersAIPlugin };
export default CloudflareWorkersAIPlugin;
@@ -0,0 +1,41 @@
{
"name": "@magpie-community/opencode-cloudflare-workers-ai-auth",
"version": "0.0.1",
"private": false,
"type": "module",
"main": "./index.mjs",
"description": "Cloudflare Workers AI provider plugin for Magpie with template URL and auto model discovery from models.dev",
"keywords": [
"opencode",
"opencode-plugin",
"magpie",
"cloudflare",
"workers-ai",
"provider",
"template"
],
"license": "MIT",
"repository": {
"type": "git",
"url": "git+https://github.com/magpie-community/plugins.git",
"directory": "packages/cloudflare-workers-ai"
},
"files": [
"index.mjs",
"src/",
"README.md",
"README.zh-CN.md",
"README.ja.md",
"LICENSE"
],
"scripts": {
"test": "node --test",
"check": "node --check index.mjs && node --test"
},
"engines": {
"node": ">=20"
},
"magpie": {
"maxConcurrency": 3
}
}
@@ -0,0 +1,390 @@
// Cloudflare Workers AI Plugin for Magpie
// Supports template URL with ${CLOUDFLARE_ACCOUNT_ID} placeholder
// Auto-discovers models from models.dev API
const CF_WORKERS_AI_ID = "cloudflare-workers-ai";
const MODELS_DEV_URL = "https://models.dev/api.json";
const CF_API_BASE_TEMPLATE = "https://api.cloudflare.com/client/v4/accounts/${CLOUDFLARE_ACCOUNT_ID}/ai/v1";
const DEFAULT_DISCOVERY_TTL_MS = 60 * 60 * 1000; // 1 hour
const CHAT_SDK = "@ai-sdk/openai-compatible";
// Models Cloudflare gates behind a Workers Paid plan / prepaid AI Gateway credits
// (developers.cloudflare.com/workers-ai/platform/pricing/)
const PAID_ONLY_MODELS = new Set([
"@cf/moonshotai/kimi-k2.6",
"@cf/moonshotai/kimi-k2.7-code",
"@cf/zai-org/glm-5.2",
"@cf/zai-org/glm-5.3",
"@cf/zai-org/glm-5.3-flash",
"@cf/deepseek-ai/deepseek-v4-flash-0731",
"@cf/deepseek-ai/deepseek-v4.1-flash-1017",
"@cf/deepseek-ai/deepseek-v4-pro-0813",
]);
const FREE_ALLOCATION_NEURONS = 10000; // per day, both plans
const DAY_MS = 24 * 60 * 60 * 1000;
function checkedURL(value) {
const url = new URL(value);
if (!["https:", "http:"].includes(url.protocol) || url.username || url.password) {
throw new Error("Expected a plain HTTP(S) base URL");
}
return url.href.replace(/\/+$/, "");
}
function interpolateTemplate(template, vars) {
return template.replace(/\$\{(\w+)\}/g, (_, key) => vars[key] ?? `\${${key}}`);
}
async function fetchModelsDev({ fetchImpl = fetch } = {}) {
const resp = await fetchImpl(MODELS_DEV_URL, {
signal: AbortSignal.timeout(15_000),
redirect: "error",
});
if (!resp.ok) {
throw new Error(`models.dev returned HTTP ${resp.status}`);
}
return resp.json();
}
function buildModels(catalog, baseURL) {
const cfSection = catalog["cloudflare-workers-ai"]?.models;
if (!cfSection || typeof cfSection !== "object") {
throw new Error("cloudflare-workers-ai section not found in models.dev catalog");
}
const result = {};
for (const [modelId, meta] of Object.entries(cfSection)) {
const limit = meta.limit ?? {};
const cost = meta.cost ?? {};
result[modelId] = {
id: modelId,
providerID: CF_WORKERS_AI_ID,
name: meta.name ?? modelId,
api: { id: modelId, url: baseURL, npm: CHAT_SDK },
limit: {
context: limit.context ?? 32768,
output: limit.output ?? 4096,
},
capabilities: {
temperature: true,
reasoning: !!meta.reasoning,
attachment: (meta.modalities?.input ?? ["text"]).some((m) => m !== "text"),
toolcall: !!meta.tool_call,
input: Object.fromEntries((meta.modalities?.input ?? ["text"]).map((m) => [m, true])),
output: Object.fromEntries((meta.modalities?.output ?? ["text"]).map((m) => [m, true])),
interleaved: meta.interleaved?.field === "reasoning_content" || false,
},
cost: {
input: cost.input ?? 0,
output: cost.output ?? 0,
cache: { read: cost.cache_read ?? 0, write: cost.cache_write ?? 0 },
},
variants: meta.reasoning_options
? Object.fromEntries(
meta.reasoning_options
.filter((o) => o.type === "effort")
.flatMap((o) => o.values ?? [])
.map((effort) => [effort, { reasoningEffort: effort }])
)
: {},
status: "active",
release_date: meta.release_date ?? "",
};
}
return result;
}
function createDiscovery({ load, initial = {}, ttlMs = DEFAULT_DISCOVERY_TTL_MS, now = Date.now }) {
let current = initial;
let verifiedAt;
let pending;
async function refresh(force = false) {
if (!force && verifiedAt !== undefined && now() - verifiedAt < ttlMs) return current;
if (pending) return pending;
pending = (async () => {
const next = await load();
if (!next || typeof next !== "object" || Array.isArray(next))
throw new Error("Invalid live model catalog");
current = next;
verifiedAt = now();
return current;
})();
try {
return await pending;
} finally {
pending = undefined;
}
}
return {
get verifiedAt() { return verifiedAt; },
get current() { return current; },
refresh,
async forDisplay() {
try { return await refresh(); }
catch {
if (verifiedAt === undefined && !Object.keys(current).length)
throw new Error("Model discovery failed with no cached list");
const fallback = { ...current };
fallback[Symbol.for("magpie.fellBack")] = true;
return fallback;
}
},
async requireModel(id) {
const models = await refresh();
if (!Object.hasOwn(models, id))
throw new Error(`Model ${JSON.stringify(id)} is absent from the current catalog`);
return models[id];
},
};
}
export async function CloudflareWorkersAIPlugin(_input, options = {}) {
const accountId = options.accountId ?? "";
const apiKey = options.apiKey ?? "";
const baseTemplate = options.baseTemplate ?? CF_API_BASE_TEMPLATE;
const fetchImpl = options.fetchImpl ?? fetch;
const discoveryTTL = options.discoveryTTLMs ?? DEFAULT_DISCOVERY_TTL_MS;
// accountId is optional at init: it is provided per account at sign-in time
// (metadata.accountId) or via plugin options. Do not fail the plugin load.
const baseURL = accountId
? interpolateTemplate(baseTemplate, { CLOUDFLARE_ACCOUNT_ID: accountId })
: baseTemplate; // placeholder left intact until sign-in provides the id
checkedURL(baseURL);
// No models.dev fetch at plugin load: config()/provider.models() discover
// lazily via discovery.forDisplay(), so host startup never waits on a
// third-party site.
const discovery = createDiscovery({
initial: {},
ttlMs: discoveryTTL,
load: async () => {
const catalog = await fetchModelsDev({ fetchImpl });
return buildModels(catalog, baseURL);
},
});
return {
async config(cfg) {
cfg.provider ??= {};
let models;
try {
models = await discovery.forDisplay();
} catch (e) {
// Graceful degrade: load errors in the config hook fail the whole plugin.
console.warn("[magpie-cloudflare-workers-ai] catalog unavailable, registering provider with empty model list; models come from provider.models per account:", e.message);
models = {};
}
cfg.provider[CF_WORKERS_AI_ID] ??= {
name: "Cloudflare Workers AI",
npm: CHAT_SDK,
api: baseURL,
models: Object.fromEntries(
Object.entries(models).map(([id, m]) => [id, {
name: PAID_ONLY_MODELS.has(id) ? `${m.name} (Paid)` : m.name,
limit: m.limit,
reasoning: m.capabilities.reasoning,
tool_call: m.capabilities.toolcall,
attachment: m.capabilities.attachment,
modalities: {
input: Object.keys(m.capabilities.input).filter((k) => m.capabilities.input[k]),
output: Object.keys(m.capabilities.output).filter((k) => m.capabilities.output[k]),
},
cost: { input: m.cost.input, output: m.cost.output },
// No `free` badge by design: every Workers AI model spends Neurons
// against the shared 10,000/day allowance (billed on Paid past it).
variants: m.variants,
interleaved: m.capabilities.interleaved,
}])
)
};
},
auth: {
provider: CF_WORKERS_AI_ID,
maxConcurrency: 3,
methods: [
{
type: "api",
label: "Cloudflare API Token (requires Workers AI:Edit permission)",
prompts: [
{
type: "password",
key: "token",
message: "API Token",
placeholder: "Cloudflare API token with Workers AI:Edit permission",
validate: (v) => (v && v.trim() ? undefined : "API Token required"),
},
{
type: "text",
key: "accountId",
message: "Account ID (optional; falls back to the plugin's accountId option)",
placeholder: "32 hex characters",
validate: (v) => (!v || /^[0-9a-f]{32}$/i.test(v.trim()) ? undefined : "Account ID must be 32 hex characters"),
},
],
async authorize(input, inputs) {
// magpie passes the prompts answers object as the first argument
// ({ token?, accountId? }); accept legacy shapes as well.
const obj =
input && typeof input === "object" && !Array.isArray(input)
? input
: inputs && typeof inputs === "object"
? inputs
: {};
const token = (
(typeof input === "string" && input.trim()) ||
obj.token || obj.key || obj.apiKey || ""
).trim();
if (!token) return { type: "failed", error: "API Token required" };
const accountIdInput = (obj.accountId ?? "").trim();
return {
type: "success",
key: token,
metadata: accountIdInput ? { accountId: accountIdInput } : {},
};
},
}
],
async loader(getAuth, provider) {
const auth = await getAuth();
if (!auth) return {};
// Account object shapes: contract api account is { type: "api", key, ... };
// keep the legacy OpenCode multi-method shape accepted for compatibility.
const apiKey = auth.key ?? auth.methods?.[0]?.key ?? "";
const customAccountId = auth.metadata?.accountId || auth.methods?.[1]?.key || "";
const effectiveAccountId = customAccountId || accountId;
if (!/^[0-9a-f]{32}$/i.test(effectiveAccountId)) {
throw new Error("Cloudflare Workers AI needs a 32-char hex Account ID — provide it in the sign-in prompt or the plugin's accountId option");
}
const effectiveBaseURL = interpolateTemplate(baseTemplate, { CLOUDFLARE_ACCOUNT_ID: effectiveAccountId });
return {
baseURL: effectiveBaseURL,
apiKey,
async fetch(input, init) {
const req = new Request(input, init);
const parsed = new URL(req.url);
// The gateway may address us via a model-metadata URL that still
// carries the ${CLOUDFLARE_ACCOUNT_ID} template. Rebuild the target
// from the effective account's base URL, reusing only the resource
// part after /accounts/<whatever>/ai/v1.
let targetURL;
const m = parsed.pathname.match(/\/accounts\/[^/]*\/ai\/v1(\/.*)?$/);
if (m) {
const suffix = m[1] && m[1] !== "/" ? m[1] : "";
targetURL = effectiveBaseURL.replace(/\/+$/, "") + suffix;
} else {
targetURL = effectiveBaseURL.replace(/\/+$/, "") + "/" + parsed.pathname.replace(/^\/+/, "");
}
if (parsed.search) targetURL += parsed.search;
const headers = new Headers({ authorization: `Bearer ${apiKey}` });
// Pass through CF-specific headers and content-type as given
const contentType = req.headers.get("content-type");
if (contentType) headers.set("content-type", contentType);
for (const h of ["cf-aig-authorization", "cf-aig-metadata"]) {
const v = req.headers.get(h);
if (v) headers.set(h, v);
}
let body = init?.body;
if (req.method === "POST" && !body && req.body) {
body = await req.json().catch(() => null);
if (body) {
body = JSON.stringify(body);
if (!headers.get("content-type")) headers.set("content-type", "application/json");
}
}
// Cloudflare is the authority on whether a model exists: check only
// against the LAST GOOD list, never refresh on the request path (a
// models.dev outage must not take chat requests down).
if (body && typeof body === "string") {
let parsedBody = null;
try {
parsedBody = JSON.parse(body);
} catch {
/* non-JSON body: forward as-is */
}
const known = discovery.current;
const catalogPrimed = known && Object.keys(known).length;
if (
parsedBody &&
typeof parsedBody === "object" &&
parsedBody.model &&
catalogPrimed &&
!Object.hasOwn(known, parsedBody.model)
) {
throw new Error(`Model ${JSON.stringify(parsedBody.model)} is absent from the last known Workers AI catalog`);
}
}
return fetchImpl(targetURL, {
method: req.method,
headers,
body,
signal: init?.signal ?? req.signal,
redirect: "error",
});
},
};
},
async usage(getAuth, _provider) {
// Cloudflare publishes no REST for per-account Neurons (dashboard only);
// show the repeatable free-allocation window (10,000 Neurons/day,
// resets daily 00:00 UTC) and best-effort plan detection.
const auth = await getAuth?.();
const acct = auth?.metadata?.accountId || accountId;
if (!acct) return { plan: "Workers Free / Paid (confirm in the dashboard)", windows: [] };
let plan = "Workers Free / Paid (confirm in the dashboard)";
try {
const res = await fetchImpl(`https://api.cloudflare.com/client/v4/accounts/${acct}`, {
headers: { authorization: `Bearer ${auth?.key ?? apiKey}` },
redirect: "error",
signal: AbortSignal.timeout(15_000),
});
if (res.ok) {
const info = await res.json();
const planName = info?.result?.plan?.name ?? info?.result?.plan ?? "";
if (/free/i.test(String(planName))) plan = "Workers Free";
else if (String(planName)) plan = String(planName);
}
} catch {
/* token scope not enough or network issue — keep unknown */
}
const nextUtcMidnight = new Date(Math.floor(Date.now() / DAY_MS) * DAY_MS + DAY_MS);
return {
plan,
windows: [
{
name: "Neurons/day (free allowance)",
span: DAY_MS,
resetsAt: nextUtcMidnight.toISOString(),
amount: null,
limit: FREE_ALLOCATION_NEURONS,
unit: "neurons",
display: "≤10,000 Neurons/day; exact usage is on the Cloudflare dashboard (no public API)",
},
],
};
},
},
provider: {
id: CF_WORKERS_AI_ID,
async models(provider, { auth } = {}) {
if (!auth) return provider.models;
const models = await discovery.forDisplay();
// Name-flag the models Cloudflare serves only behind Workers Paid / AI
// Gateway credits. No `free` flag: shared daily Neurons allowance is not
// the same thing as a free model.
return Object.fromEntries(
Object.entries(models).map(([id, m]) => [
id,
PAID_ONLY_MODELS.has(id) ? { ...m, name: `${m.name} (Paid)` } : m,
]),
);
},
},
};
}
@@ -0,0 +1,282 @@
import test from "node:test";
import assert from "node:assert/strict";
import { CloudflareWorkersAIPlugin } from "../index.mjs";
const ACCOUNT_ID = "a".repeat(32);
function fakeCatalog() {
return {
"cloudflare-workers-ai": {
models: {
"@cf/meta/llama-3-8b-instruct": {
name: "Llama 3 8B",
limit: { context: 8192, output: 4096 },
tool_call: true,
cost: { input: 0.05, output: 0.12 },
modalities: { input: ["text"], output: ["text"] },
},
"@cf/deepseek/deepseek-r1": {
name: "DeepSeek R1",
reasoning: true,
tool_call: true,
reasoning_options: [{ type: "effort", values: ["low", "high"] }],
modalities: { input: ["text", "image"], output: ["text"] },
interleaved: { field: "reasoning_content" },
cost: { input: 0.1, output: 0.2 },
},
},
},
};
}
function opts(catalogJson = fakeCatalog()) {
return {
accountId: ACCOUNT_ID,
discoveryTTLMs: 3600_000,
fetchImpl: async () => new Response(JSON.stringify(catalogJson)),
};
}
test("module parses and exports plugin function", async () => {
const mod = await import("../index.mjs");
assert.equal(typeof mod.CloudflareWorkersAIPlugin, "function");
assert.equal(typeof (await import("../index.mjs")).default, "function");
});
test("registers provider with interpolated account id in models.dev-driven config", async () => {
const plugin = await CloudflareWorkersAIPlugin({}, opts());
const cfg = {};
await plugin.config(cfg);
const p = cfg.provider["cloudflare-workers-ai"];
assert.ok(p, "provider registered");
assert.equal(p.api, `https://api.cloudflare.com/client/v4/accounts/${ACCOUNT_ID}/ai/v1`);
assert.equal(p.models["@cf/meta/llama-3-8b-instruct"].name, "Llama 3 8B");
assert.equal(p.models["@cf/meta/llama-3-8b-instruct"].limit.context, 8192);
assert.equal(p.models["@cf/deepseek/deepseek-r1"].reasoning, true);
assert.deepEqual(p.models["@cf/deepseek/deepseek-r1"].variants, {
low: { reasoningEffort: "low" },
high: { reasoningEffort: "high" },
});
});
test("init succeeds without accountId option (no load-time throw)", async () => {
const noOpts = await CloudflareWorkersAIPlugin({}, { fetchImpl: async () => new Response("{}") });
const cfg = {};
await noOpts.config(cfg);
assert.ok(cfg.provider["cloudflare-workers-ai"], "plugin loads without accountId option");
});
test("loader rejects accounts without a 32-hex accountId", async () => {
const plugin = await CloudflareWorkersAIPlugin({}, { fetchImpl: async () => new Response("{}") });
await assert.rejects(
async () => plugin.auth.loader(async () => ({ key: "tok", metadata: [] })),
/Account ID/
);
});
test("discovery falls back to cached catalog on refresh failure", async () => {
let fail = false;
const o = {
accountId: ACCOUNT_ID,
discoveryTTLMs: 0, // always stale
fetchImpl: async () => {
if (fail) return new Response("boom", { status: 500 });
return new Response(JSON.stringify(fakeCatalog()));
},
};
const plugin = await CloudflareWorkersAIPlugin({}, o);
const cfg = {};
await plugin.config(cfg); // primes cache
fail = true;
const cfg2 = {};
await plugin.config(cfg2);
const p = cfg2.provider["cloudflare-workers-ai"];
assert.ok(p.models["@cf/meta/llama-3-8b-instruct"], "served cached models after failure");
});
test("auth loader forwards chat/completions with bearer token", async () => {
let seen = {};
const o = opts();
o.fetchImpl = async (url, init) => {
if (typeof url === "string" && url.includes("models.dev")) {
return new Response(JSON.stringify(fakeCatalog()));
}
seen = { url, init };
return new Response(JSON.stringify({ ok: true }), { status: 200 });
};
const plugin = await CloudflareWorkersAIPlugin({}, o);
const result = await plugin.auth.loader(async () => ({ methods: [{ key: "tok" }, { key: "" }] }));
assert.equal(result.baseURL, `https://api.cloudflare.com/client/v4/accounts/${ACCOUNT_ID}/ai/v1`);
assert.equal(result.apiKey, "tok");
const req = new Request(`${result.baseURL}/chat/completions`, {
method: "POST",
headers: { "content-type": "application/json", "cf-aig-authorization": "z" },
body: JSON.stringify({ model: "@cf/meta/llama-3-8b-instruct", messages: [] }),
});
const resp = await result.fetch(req, {});
assert.equal(resp.status, 200);
assert.equal(seen.init.headers.get("authorization"), "Bearer tok");
assert.equal(seen.init.headers.get("cf-aig-authorization"), "z");
assert.match(seen.url, /\/chat\/completions$/);
});
test("auth loader rejects unknown models but passes other endpoints through", async () => {
const plugin = await CloudflareWorkersAIPlugin({}, opts());
const cfg = {}; await plugin.config(cfg); // prime the model catalog
const result = await plugin.auth.loader(async () => ({ key: "tok", metadata: { accountId: "" } }));
await assert.rejects(
async () =>
result.fetch(
new Request(`${result.baseURL}/chat/completions`, {
method: "POST",
body: JSON.stringify({ model: "@cf/nope" }),
}),
{}
),
/last known Workers AI catalog/
);
// Non-chat paths are forwarded untouched to the same base URL
let forwarded = "";
const o2 = opts();
o2.fetchImpl = async (url) => {
if (typeof url === "string" && url.includes("models.dev")) {
return new Response(JSON.stringify(fakeCatalog()));
}
forwarded = url;
return new Response("{}", { status: 200 });
};
const p2 = await CloudflareWorkersAIPlugin({}, o2);
const r2 = await p2.auth.loader(async () => ({ key: "tok" }));
const resp2 = await r2.fetch(`${r2.baseURL}/embeddings`, {
method: "POST",
body: JSON.stringify({ text: "x" }),
});
assert.equal(resp2.status, 200);
assert.match(forwarded, /\/embeddings$/);
});
test("a models.dev outage must not take chat requests down (request path never refreshes)", async () => {
let down = false;
const o = {
accountId: ACCOUNT_ID,
discoveryTTLMs: 1, // every refresh is stale immediately
fetchImpl: async (url) => {
if (typeof url === "string" && url.includes("models.dev")) {
if (down) return new Response("down", { status: 503 });
return new Response(JSON.stringify(fakeCatalog()));
}
return new Response("{}", { status: 200 });
},
};
const plugin = await CloudflareWorkersAIPlugin({}, o);
const cfg = {};
await plugin.config(cfg); // prime once while models.dev is up
const loader = await plugin.auth.loader(async () => ({ key: "tok", metadata: { accountId: "" } }));
down = true; // TTL passed AND models.dev unreachable
const resp = await loader.fetch(
`https://api.cloudflare.com/client/v4/accounts/${ACCOUNT_ID}/ai/v1/chat/completions`,
{ method: "POST", body: JSON.stringify({ model: "@cf/meta/llama-3-8b-instruct", messages: [] }) }
);
assert.equal(resp.status, 200, "known model must still be sent using the last good catalog");
// an unknown model is rejected locally at once, without touching models.dev
await assert.rejects(
async () =>
loader.fetch(
`https://api.cloudflare.com/client/v4/accounts/${ACCOUNT_ID}/ai/v1/chat/completions`,
{ method: "POST", body: JSON.stringify({ model: "@cf/nope", messages: [] }) }
),
/last known Workers AI catalog/
);
});
test("authorize accepts bare-string and fields-object token shapes", async () => {
const plugin = await CloudflareWorkersAIPlugin({}, opts());
const method = plugin.auth.methods[0];
for (const call of [
[" tok ", { accountId: "b".repeat(32) }],
[{ key: "tok", accountId: "b".repeat(32) }],
[{ token: "tok", accountId: "b".repeat(32) }],
[{ apiKey: "tok", accountId: "b".repeat(32) }],
]) {
const ok = await method.authorize(...call);
assert.equal(ok.type, "success", JSON.stringify(call[0]).slice(0, 30));
assert.equal(ok.key, "tok");
assert.equal(ok.metadata.accountId, "b".repeat(32));
}
const noTok = await method.authorize({}, { accountId: "b".repeat(32) });
assert.equal(noTok.type, "failed");
});
test("usage reports free-allocation window with next UTC midnight reset", async () => {
const o = opts();
o.fetchImpl = async (url, init) => {
if (typeof url === "string" && url.includes("models.dev")) {
return new Response(JSON.stringify(fakeCatalog()));
}
return new Response("{}", { status: 200 });
};
const plugin = await CloudflareWorkersAIPlugin({}, o);
const u = await plugin.auth.usage(async () => ({
key: "tok",
metadata: { accountId: ACCOUNT_ID },
}));
assert.ok(u.plan, "plan name present");
assert.equal(u.windows.length, 1);
const w = u.windows[0];
assert.equal(w.limit, 10000);
assert.equal(w.unit, "neurons");
assert.equal(new Date(w.resetsAt).getUTCHours(), 0);
assert.equal(new Date(w.resetsAt).getUTCMinutes(), 0);
assert.equal(w.span, 86400_000);
});
test("paid-only models are flagged (Paid) in config and provider.models", async () => {
const catalog = fakeCatalog();
catalog["cloudflare-workers-ai"].models["@cf/zai-org/glm-5.3"] = {
name: "GLM 5.3",
limit: { context: 128000, output: 32000 },
modalities: { input: ["text"], output: ["text"] },
};
const o = opts(catalog);
const plugin = await CloudflareWorkersAIPlugin({}, o);
const cfg = {};
await plugin.config(cfg);
assert.match(cfg.provider["cloudflare-workers-ai"].models["@cf/zai-org/glm-5.3"].name, /Paid/, "config decoration");
assert.equal(cfg.provider["cloudflare-workers-ai"].meta, undefined);
const pm = cfg.provider["cloudflare-workers-ai"].models["@cf/meta/llama-3-8b-instruct"];
assert.doesNotMatch(pm.name, /Paid/, "free model not flagged");
});
test("fetch normalizes template-account URLs onto the effective account base", async () => {
let forwarded = "";
const o = opts();
o.fetchImpl = async (url) => {
if (typeof url === "string" && url.includes("models.dev")) {
return new Response(JSON.stringify(fakeCatalog()));
}
forwarded = url;
return new Response("{}", { status: 200 });
};
const plugin = await CloudflareWorkersAIPlugin({}, o);
const r = await plugin.auth.loader(async () => ({
key: "tok",
metadata: { accountId: ACCOUNT_ID },
}));
// gateway addressed us via model metadata URL that still holds the template
const req = new Request(
"https://api.cloudflare.com/client/v4/accounts/${CLOUDFLARE_ACCOUNT_ID}/ai/v1/chat/completions",
{ method: "POST", body: JSON.stringify({ model: "@cf/meta/llama-3-8b-instruct", messages: [] }) }
);
await r.fetch(req, {});
assert.equal(
forwarded,
`https://api.cloudflare.com/client/v4/accounts/${ACCOUNT_ID}/ai/v1/chat/completions`
);
// concrete (non-template) incoming URL must keep its resource suffix too
await r.fetch(`${r.baseURL}/embeddings`, { method: "POST", body: "{}" });
assert.match(forwarded, /\/embeddings$/);
});
+3 -1
View File
@@ -66,6 +66,8 @@
"summary": { "en": "Exact arithmetic, unit conversion and calendar date math as tools for every agent: no network, no key.", "zh": "给每个 agent 的精确计算、单位换算和日历日期计算工具:不联网,不需要 key。" } },
{ "package": "@magpie-community/page-usage", "name": "Usage Glance", "kind": "page", "community": true,
"summary": { "en": "A page in magpie's window with calls, errors, tokens and cost for today, 7 or 30 days, and the models behind them. Reads only your usage summary.", "zh": "在 magpie 窗口里一眼看到今天、7 天或 30 天的调用、错误、token、费用和对应模型。只读取用量汇总。" } },
{"package": "@magpie-community/agent-kimi-desktop", "name": "Kimi", "kind": "agent", "community": true, "summary": {"en": "Kimi desktop Work on Magpie's Agents page: select a model from Magpie, then disconnect to restore the original service. Not Kimi Code CLI.", "zh": "把普通 Kimi 桌面版 Work 接入 Magpie Agent 页,使用已配置的模型;断开恢复原连接。不是 Kimi Code CLI。"}}
{"package": "@magpie-community/agent-kimi-desktop", "name": "Kimi", "kind": "agent", "community": true, "summary": {"en": "Kimi desktop Work on Magpie's Agents page: select a model from Magpie, then disconnect to restore the original service. Not Kimi Code CLI.", "zh": "把普通 Kimi 桌面版 Work 接入 Magpie Agent 页,使用已配置的模型;断开恢复原连接。不是 Kimi Code CLI。"}},
{ "package": "@magpie-community/opencode-cloudflare-workers-ai-auth", "name": "Cloudflare Workers AI", "providers": ["cloudflare-workers-ai"], "community": true,
"summary": { "en": "Cloudflare Workers AI with your API token (Workers AI:Edit): 28+ models discovered live from models.dev, the 8 paid-only models flagged, and a Neurons/day allowance row in magpie quota.", "zh": "用你的 Cloudflare API Token(Workers AI:Edit 权限)登录 Workers AI:28+ 模型经 models.dev 实时发现,付费专属模型自动标注,magpie quota 显示每日 Neurons 免费额度。" } }
]
}