agnes: add the international Agnes AI provider with browser sign-in, usage and balance (#619)

Adds @magpie-community/opencode-agnes-auth 0.1.0 (provider `agnes`): Agnes AI's
international API platform (apihub.agnes-ai.com for models, platform-backend.agnes-ai.com
for keys and usage). Agnes trains and serves its own agnes-* models, so it is a vendor,
not a relay, and a different channel from `agnes-code` (the Agnes Code desktop's
gateway). Sign-in: a private Chromium profile read over loopback CDP (plan, personal or
enterprise key), or an API key plus an optional console token. Usage: a plan key shows
Token Plan and Agent Plan windows; a personal or enterprise key shows the balance only.
By CasonMo (#619).

Since the first review (9242396): the callback's /user/self result no longer shadows the
Chrome session (6ca6f68 broke every browser sign-in); a page exception from CDP is
reported instead of timing out, but only once the same exception has lasted 4s, since
Chrome raises SecurityError on localStorage while the page is still loading; the
platform gets x-user-language en-US; browser sign-ins aren't told to paste a token.

Reviewed head 8a30c65ee88ab432ed7f63f86b81c18d0db3680c, merged onto origin/main 581ca13.
Run on mote, HOME=$(mktemp -d), Bun 1.4.2:
- bun scripts/check.mjs: exit 0 (agnes included)
- bun test packages/agnes: 51 pass, 1 skip, 0 fail
- bun test (whole repo): 4775 pass, 13 skip, 0 fail (main 581ca13 alone: 4741 pass, 0 fail)
- AGNES_BROWSER_TEST=1 with Chrome for Testing 1234 (--use-mock-keychain): the real-browser
  test passed 5 of 5 headed and 5 of 5 with --headless=new; no browser left running.
Broken by hand: making the first page exception final again turned the two new
token-poll tests red, and the real-browser test red 5 of 5 with the same
"SecurityError ... Access is denied for this document" seen at 1eea3f7. Earlier rounds
broke the TDZ fix and the exceptionDetails branch by hand; their tests went red.

Harm check: no dependencies, install scripts, .github or publish changes, or encoded
blobs. The only addresses are agnes-ai.com hosts and 127.0.0.1 CDP; the console token
goes only to platform-backend and the API key only to apihub. The plugin uses its own
browser profile, never the user's.

Not tried: a real Agnes account or the real login page (no account here; tests stay
offline); the Windows and Linux browser paths.
This commit is contained in:
Cason Mo
2026-11-02 15:54:08 +08:00
committed by GitHub
parent 581ca13db6
commit b48f2e754f
7 changed files with 1871 additions and 0 deletions
+1
View File
@@ -11,6 +11,7 @@ subscription and makes its requests. The packages work in OpenCode and in
| Package | Signs in to | Provider id |
|---|---|---|
| [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` |
| [catpaw](packages/catpaw) | Meituan's 妙手 CatPaw (ai.catpaw.meituan.com), with a browser web sign-in or the desktop client's saved credentials | `catpaw` |
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 magpie-community 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.
+137
View File
@@ -0,0 +1,137 @@
# agnes
Agnes AI ([agnes-ai.com](https://www.agnes-ai.com)) in
[OpenCode](https://opencode.ai) and [magpie](https://usemagpie.ai). The plugin
uses Agnes's OpenAI-compatible endpoint at `https://apihub.agnes-ai.com/v1`,
discovers the account's text models, and reads both Token Plan and Agent Plan
usage. Its primary sign-in opens the official Agnes login in a private Chrome
window and finishes without asking for your password or a copied token.
**Provider id:** `agnes`
This package targets the **international site**: `platform.agnes-ai.com` and
`apihub.agnes-ai.com`. The CN site would need its own package and provider id,
for example `agnes-cn`.
## Sign-in
### Browser sign-in
Choose one of the browser sign-in methods:
- **Agnes browser sign-in (plan key)** for a Token Plan or Agent Plan key.
- **Agnes browser sign-in (personal key)** for a `default` profile key.
- **Agnes browser sign-in (enterprise key)** for an `enterprise` profile key.
The plugin starts a separate Chrome, Edge, Chromium or Brave profile, opens
the official Agnes login page, and waits for you to sign in. It then reads the
session through Chrome DevTools Protocol, reveals the selected profile's API
key, and closes the browser window.
The dedicated profile is kept at
`~/.config/magpie/agnes-browser` (`AGNES_PROFILE` overrides it), so the next
sign-in can reuse the login instead of asking again. It is separate from your
everyday browser profile; the plugin does not read your normal cookies, saved
passwords or history. The profile is created with mode `0700`, but it does
contain the Agnes session because Chrome keeps it there.
The API key and console session are also stored in the plugin account. Set
`AGNES_BROWSER` to a Chromium-based browser path if it is outside the usual
locations.
Browser accounts are labeled `Agnes Plan`, `Agnes Personal` or
`Agnes Enterprise`; the account's email or username is not written into
Magpie's plugin auth file.
Personal and enterprise keys are billed from the account balance and can use
the free models enabled for that key. If a profile has more than one active
key, the browser sign-in picks the first active key in the platform's list; use
the API-key fallback if you need a specific key.
This browser path is experimental because it relies on Agnes keeping its
current `localStorage.token` login shape.
### API key fallback
There are two credentials:
- **API key** (for example `cpk-…` for a Token Plan key): used for model
requests. Create or copy it in the Agnes platform's API key page.
- **Console token** (optional): used only to read plan usage. Sign in at
[platform.agnes-ai.com](https://platform.agnes-ai.com), then copy
`localStorage.getItem("token")` from the browser console and paste it into
the plugin's sign-in prompt.
In the fallback, the API key is stored as the account key and the console token
is stored in `metadata.consoleToken`. The plugin sends the console token only
to `platform-backend.agnes-ai.com`; it never sends it to the model API. A
refused console token does not sign the API key out.
The fallback also asks for the key type, so a manually entered personal or
enterprise key does not request plan quota endpoints.
Treat the console token like a password: it grants access to the Agnes account,
not just to usage.
Agnes currently offers no standard OAuth callback for third-party clients, so
the console token has to be pasted manually. It can expire independently of
the API key; sign in again with a fresh token when that happens.
## Models
After sign-in, `GET /v1/models` supplies the account's live list. Image and
video generation models are left out because this is a chat provider; their
quotas still appear on the usage card.
The bootstrap and documented text models are:
| Model | Context | Max output | Input |
| --- | ---: | ---: | --- |
| `agnes-3.0-flash` | 512K | 65,536 | text, image URL |
| `agnes-2.5-flash` | 512K | 65,536 | text, image URL |
| `agnes-2.5-pro` | 1M | 65,536 | text, image URL |
| `agnes-2.5-pro-beta` | 1M | 65,536 | text, image URL |
All documented models support streaming, tools and reasoning. Prices shown by
magpie use Agnes's published list prices in USD per million tokens. During a
promotion or trial, Agnes may bill less; the platform's usage page remains the
source of truth.
## Usage
The usage card supports both Agnes plans:
- **Token Plan** (`/api/user/subscription`): text requests in the 5-hour and
weekly windows, daily image count and daily video seconds.
- **Agent Plan** (`/api/user/agentplan/subscription` and `/credits`): monthly
Credits, the shared 5-hour Credits window and purchased Credits balance.
- **Personal / enterprise keys** (`/api/user/balance`): the available USD
balance only. Their model calls are billed from that balance.
An account holding both plans sees both sets of windows. The usage endpoints
are Agnes platform interfaces rather than the public inference API, so a
future upstream change may require a plugin update.
Only accounts signed in with a **plan key** query Token Plan/Agent Plan
usage. **Personal** and **enterprise** accounts show only the wallet balance.
Plan-key accounts do not show the wallet balance.
## Install
```sh
magpie plugin add @magpie-community/opencode-agnes-auth
magpie plugin login agnes
magpie provider test agnes
```
In OpenCode, add the package under `plugin` and sign in with
`opencode auth login`.
## Development
```sh
bun test
bun scripts/check.mjs agnes
```
MIT. Not affiliated with Agnes AI.
+905
View File
@@ -0,0 +1,905 @@
import { spawn } from "node:child_process"
import { chmodSync, existsSync, mkdirSync } from "node:fs"
import { createServer } from "node:net"
import { tmpdir } from "node:os"
import { join } from "node:path"
// Local browser sign-in: a private Chrome/Edge profile, read through CDP.
// The API key and console session are both obtained without asking for a password.
const ID = "agnes"
const BASE = "https://apihub.agnes-ai.com/v1"
const PLATFORM = "https://platform-backend.agnes-ai.com/api"
const LOGIN = "https://platform.agnes-ai.com/login?redirect=%2Fsettings%2FapiKeys"
const activeChrome = new Set()
process.once("exit", () => {
for (const child of activeChrome) {
try {
child.kill("SIGKILL")
} catch {}
}
})
const MODELS = {
"agnes-3.0-flash": {
name: "Agnes 3.0 Flash",
context: 524288,
output: 65536,
image: true,
reasoning: true,
cost: { input: 0.05, output: 0.15, cache_read: 0.005 },
},
"agnes-2.5-flash": {
name: "Agnes 2.5 Flash",
context: 524288,
output: 65536,
image: true,
reasoning: true,
cost: { input: 0.05, output: 0.15, cache_read: 0.005 },
},
"agnes-2.5-pro": {
name: "Agnes 2.5 Pro",
context: 1048576,
output: 65536,
image: true,
reasoning: true,
cost: { input: 0.45, output: 0.9, cache_read: 0.045 },
},
"agnes-2.5-pro-beta": {
name: "Agnes 2.5 Pro Beta",
context: 1048576,
output: 65536,
image: true,
reasoning: true,
cost: { input: 0.1, output: 0.3, cache_read: 0.01 },
},
}
function modelRow(id, runtime = false) {
const known = MODELS[id]
const image = known?.image === true
const reasoning = known?.reasoning ?? false
const row = {
...(runtime ? { id, providerID: ID } : {}),
name: known?.name ?? id,
limit: { context: known?.context ?? 0, output: known?.output ?? 0 },
reasoning,
tool_call: true,
modalities: { input: image ? ["text", "image"] : ["text"], output: ["text"] },
...(known?.cost ? { cost: known.cost } : {}),
}
if (!runtime) return row
return {
...row,
api: { id, url: BASE, npm: "@ai-sdk/openai-compatible" },
status: "active",
headers: {},
options: {},
capabilities: {
temperature: true,
reasoning,
attachment: image,
toolcall: true,
input: { text: true, image },
output: { text: true, image: false, audio: false, video: false, pdf: false },
interleaved: false,
},
variants: {},
free: false,
}
}
const DEPRECATED = new Set(["agnes-2.0-flash", "agnes-2.5-pro-alpha"])
const isTextModel = (id) =>
!/^agnes-(?:image|video)-/i.test(id) && !DEPRECATED.has(id.toLowerCase())
async function accountModels(fetchImpl, key) {
return await fetchImpl(`${BASE}/models`, {
headers: { authorization: `Bearer ${key}`, accept: "application/json" },
signal: AbortSignal.timeout(15000),
redirect: "error",
})
}
function createPlugin({
fetchImpl = globalThis.fetch,
openChrome = openChromeSession,
} = {}) {
async function platform(path, token, { method = "GET" } = {}) {
let res
try {
res = await fetchImpl(`${PLATFORM}${path}`, {
method,
headers: {
authorization: `Bearer ${token}`,
accept: "application/json",
"x-user-language": "en-US",
...(method === "POST" ? { "content-type": "application/json" } : {}),
},
signal: AbortSignal.timeout(15000),
redirect: "error",
})
} catch (error) {
return { error: error?.cause?.code || error?.message || "network error" }
}
if (res.status === 401 || res.status === 403) return { lapsed: true }
if (!res.ok) return { error: `HTTP ${res.status}` }
let body
try {
body = await res.json()
} catch {
return { error: "Agnes sent no JSON" }
}
if (body?.code === 401 || body?.code === 403) return { lapsed: true }
if (body?.code === 404) return { missing: true }
if (body?.code !== 200) return { error: body?.message || `code ${body?.code ?? "unknown"}` }
return { data: body.data }
}
async function usage(getAuth) {
const auth = await getAuth()
if (!apiKeyOf(auth)) return {}
const token = consoleTokenOf(auth)
if (!token) {
return {
plan: "Agnes API",
windows: [],
error:
"Agnes plan usage needs the console token from platform.agnes-ai.com; add one to this account",
signIn: "kept",
}
}
const profile = keyProfileOf(auth)
if (profile !== "plan") {
return await balanceOnlyUsage(
token,
profile,
platform,
auth.type === "oauth",
)
}
const refused =
auth.type === "oauth"
? "Agnes session was refused; sign in again"
: "Agnes console token was refused; sign in again and paste a new token"
const [legacyResult, agentResult] = await Promise.all([
platform("/user/subscription", token),
platform("/user/agentplan/subscription", token),
])
if (legacyResult.lapsed || agentResult.lapsed) {
return {
plan: "Agnes API",
windows: [],
error: refused,
signIn: "kept",
}
}
let creditsResult = null
if (agentResult.data) creditsResult = await platform("/user/agentplan/credits", token)
if (creditsResult?.lapsed) {
return {
plan: "Agnes API",
windows: [],
error: refused,
signIn: "kept",
}
}
const legacy = legacyResult.data
const agent = agentResult.data
const credits = creditsResult?.data
const windows = [...legacyWindows(legacy), ...agentWindows(agent, credits)]
const planNames = [agentPlanName(agent), legacyPlanName(legacy)].filter(Boolean)
const errors = []
if (legacyResult.error) errors.push(`Token Plan usage couldn't be read: ${legacyResult.error}`)
if (agentResult.error) errors.push(`Agent Plan usage couldn't be read: ${agentResult.error}`)
if (creditsResult?.error) {
errors.push(`Agent Plan credits couldn't be read: ${creditsResult.error}`)
}
return {
plan: planNames.join(" + ") || "Agnes API",
...(vendorTime(agent?.current_period_end ?? legacy?.current_period_end)
? { until: vendorTime(agent?.current_period_end ?? legacy?.current_period_end) }
: {}),
...(renewalOf(agent, legacy) ? { renew: renewalOf(agent, legacy) } : {}),
windows,
...(errors.length ? { error: errors.join("; ") } : {}),
signIn: "kept",
}
}
async function browserAuthorize(profile) {
const session = await openChrome(LOGIN)
return {
url: "",
instructions:
"Sign in to Agnes in the Chrome window that just opened. Magpie will finish automatically.",
method: "auto",
opened: true,
callback: async () => {
try {
const token = await session.token(5 * 60 * 1000)
if (!token) {
return {
type: "failed",
error: "Agnes sign-in timed out; start it again",
}
}
const self = await platform("/user/self", token)
if (self.lapsed) {
try {
await session.evaluate('localStorage.removeItem("token")')
} catch {}
return {
type: "failed",
error: "Agnes session expired; sign in again",
}
}
const key =
profile === "plan"
? await revealApiKey(token, platform)
: await revealProfileKey(token, profile, platform)
return {
type: "success",
refresh: "",
access: key,
expires: 0,
consoleToken: token,
accountId: profileLabel(profile),
source: "browser",
keyProfile: profile,
}
} catch (error) {
return {
type: "failed",
error: String(error?.message ?? error).slice(0, 500),
}
} finally {
await session.close()
}
},
}
}
return {
async config(cfg) {
cfg.provider ??= {}
const was = cfg.provider[ID] ?? {}
cfg.provider[ID] = {
name: "Agnes",
npm: "@ai-sdk/openai-compatible",
api: BASE,
...was,
models: {
...Object.fromEntries(Object.keys(MODELS).map((id) => [id, modelRow(id)])),
...(was.models ?? {}),
},
}
},
auth: {
provider: ID,
methods: [
{
type: "oauth",
label: "Agnes browser sign-in (plan key)",
authorize: () => browserAuthorize("plan"),
},
{
type: "oauth",
label: "Agnes browser sign-in (personal key)",
authorize: () => browserAuthorize("default"),
},
{
type: "oauth",
label: "Agnes browser sign-in (enterprise key)",
authorize: () => browserAuthorize("enterprise"),
},
{
type: "api",
label: "Agnes API key",
placeholder: "cpk-…",
prompts: [
{
type: "select",
key: "keyProfile",
message: "Key type (which usage card it should show)",
options: [
{ label: "Plan key (Token/Agent Plan)", value: "plan" },
{ label: "Personal API key", value: "default" },
{ label: "Enterprise API key", value: "enterprise" },
],
},
{
type: "text",
key: "consoleToken",
message: "Agnes console token (paste to show plan usage; leave empty to skip)",
placeholder: "localStorage.token after signing in at platform.agnes-ai.com",
},
],
},
],
async loader(getAuth) {
const auth = await getAuth()
const key = apiKeyOf(auth)
if (!key) return {}
return { baseURL: BASE, apiKey: key }
},
usage,
},
provider: {
id: ID,
async models(provider, { auth } = {}) {
const key = apiKeyOf(auth)
if (!key) return provider?.models ?? {}
let res
try {
res = await accountModels(fetchImpl, key)
} catch {
return provider?.models ?? {}
}
if (res.status === 401 || res.status === 403) {
throw Object.assign(new Error(`Agnes refused this API key (HTTP ${res.status})`), {
signIn: "expired",
})
}
if (!res.ok) return provider?.models ?? {}
let body
try {
body = await res.json()
} catch {
throw new Error("Agnes sent no model list")
}
if (
!Array.isArray(body?.data) ||
body.data.some((model) => typeof model?.id !== "string" || !model.id)
) {
throw new Error("Agnes sent no model list")
}
const ids = [...new Set(body.data.map((model) => model.id).filter(isTextModel))]
return Object.fromEntries(ids.map((id) => [id, modelRow(id, true)]))
},
},
}
}
export const AgnesPlugin = async () => createPlugin()
export const _internal = {
createPlugin,
MODELS,
BASE,
PLATFORM,
modelRow,
isTextModel,
legacyWindows,
agentWindows,
apiKeyOf,
keyProfileOf,
profileLabel,
consoleTokenOf,
revealApiKey,
revealProfileKey,
balanceText,
browserArgs,
browserProfileDir,
findBrowser,
cdpEvaluate,
cdpTarget,
openChromeSession,
waitForBrowserToken,
vendorTime,
}
function apiKeyOf(auth) {
if (auth?.type === "api" && typeof auth.key === "string") return auth.key.trim()
if (auth?.type === "oauth" && typeof auth.access === "string") return auth.access.trim()
return ""
}
function keyProfileOf(auth) {
const profile = auth?.keyProfile ?? auth?.metadata?.keyProfile
if (profile === "plan" || profile === "default" || profile === "enterprise") {
return profile
}
const key = apiKeyOf(auth)
if (/^(?:cpk|apk)-/i.test(key)) return "plan"
return ""
}
function profileLabel(profile) {
if (profile === "default") return "Agnes Personal"
if (profile === "enterprise") return "Agnes Enterprise"
return "Agnes Plan"
}
function consoleTokenOf(auth) {
const value = auth?.consoleToken ?? auth?.metadata?.consoleToken
if (typeof value !== "string") return ""
return value.trim().replace(/^Bearer\s+/i, "")
}
async function revealApiKey(token, platform) {
const agent = await platform("/user/agentplan/subscription", token)
if (agent?.data) {
const reveal = await platform("/user/agentplan/key/reveal", token, { method: "POST" })
if (reveal?.data?.key) return reveal.data.key
}
const legacy = await platform("/user/subscription/key/reveal", token, { method: "POST" })
if (legacy?.data?.key) return legacy.data.key
const agentAgain = await platform("/user/agentplan/key/reveal", token, { method: "POST" })
if (agentAgain?.data?.key) return agentAgain.data.key
throw new Error(
"Agnes reported no plan API key; use the API key sign-in for a free account",
)
}
async function revealProfileKey(token, profile, platform) {
const list = await platform(`/token?key_profile=${encodeURIComponent(profile)}`, token)
const items = Array.isArray(list?.data?.items) ? list.data.items : []
const active = items.find(
(item) => item && item.status === 1 && Number.isInteger(item.id),
)
if (!active) {
throw new Error(`Agnes has no active ${profile} API key; create one in the platform first`)
}
const revealed = await platform(`/token/${active.id}/key`, token, { method: "POST" })
if (!revealed?.data?.key) {
throw new Error(`Agnes could not reveal the ${profile} API key`)
}
return revealed.data.key
}
async function balanceOnlyUsage(token, profile, platform, browser) {
const result = await platform("/user/balance", token)
if (result.lapsed) {
return {
plan: profile === "enterprise" ? "Enterprise API key" : "Personal API key",
windows: [],
error: browser
? "Agnes session was refused; sign in again"
: "Agnes console token was refused; sign in again and paste a new token",
signIn: "kept",
}
}
const balance = balanceText(result.data)
return {
plan: profile === "enterprise" ? "Enterprise API key" : "Personal API key",
...(balance ? { balance } : {}),
windows: [],
...(result.error ? { error: `Agnes balance couldn't be read: ${result.error}` } : {}),
signIn: "kept",
}
}
function browserArgs(profile, port, url) {
return [
`--user-data-dir=${profile}`,
`--remote-debugging-port=${port}`,
"--remote-debugging-address=127.0.0.1",
"--no-first-run",
"--no-default-browser-check",
"--disable-sync",
"--disable-default-apps",
"--disable-background-mode",
"--new-window",
url,
]
}
function browserProfileDir(env = process.env, platform = process.platform) {
if (env.AGNES_PROFILE) return env.AGNES_PROFILE
if (platform === "win32") {
return join(env.LOCALAPPDATA || env.APPDATA || tmpdir(), "magpie", "agnes-browser")
}
return join(
env.XDG_CONFIG_HOME || join(env.HOME || tmpdir(), ".config"),
"magpie",
"agnes-browser",
)
}
function findBrowser(platform = process.platform, env = process.env) {
if (env.AGNES_BROWSER && existsSync(env.AGNES_BROWSER)) return env.AGNES_BROWSER
const home = env.HOME || ""
const candidates =
platform === "darwin"
? [
"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
"/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge",
"/Applications/Chromium.app/Contents/MacOS/Chromium",
"/Applications/Brave Browser.app/Contents/MacOS/Brave Browser",
join(home, "Applications/Google Chrome.app/Contents/MacOS/Google Chrome"),
]
: platform === "win32"
? [
join(env.PROGRAMFILES || "", "Google/Chrome/Application/chrome.exe"),
join(env["PROGRAMFILES(X86)"] || "", "Google/Chrome/Application/chrome.exe"),
join(env.LOCALAPPDATA || "", "Google/Chrome/Application/chrome.exe"),
join(env.PROGRAMFILES || "", "Microsoft/Edge/Application/msedge.exe"),
join(env["PROGRAMFILES(X86)"] || "", "Microsoft/Edge/Application/msedge.exe"),
]
: [
"/usr/bin/google-chrome",
"/usr/bin/google-chrome-stable",
"/usr/bin/chromium",
"/usr/bin/chromium-browser",
"/snap/bin/chromium",
"/usr/bin/microsoft-edge",
]
return candidates.find((path) => path && existsSync(path)) ?? ""
}
function freePort() {
return new Promise((resolve, reject) => {
const server = createServer()
server.on("error", reject)
server.listen(0, "127.0.0.1", () => {
const port = server.address().port
server.close(() => resolve(port))
})
})
}
async function cdpTarget(port, targetPrefix = "https://platform.agnes-ai.com/") {
try {
const res = await fetch(`http://127.0.0.1:${port}/json/list`, {
signal: AbortSignal.timeout(1200),
})
if (!res.ok) return null
const list = await res.json()
return (
list.find(
(target) =>
target?.type === "page" &&
typeof target.url === "string" &&
target.url.startsWith(targetPrefix) &&
target.webSocketDebuggerUrl,
) ?? null
)
} catch {
return null
}
}
function cdpEvaluate(
webSocketUrl,
expression,
timeout = 3000,
WebSocketImpl = globalThis.WebSocket,
) {
return new Promise((resolve, reject) => {
let ws
try {
ws = new WebSocketImpl(webSocketUrl)
} catch (error) {
reject(error)
return
}
const timer = setTimeout(() => {
try {
ws.close()
} catch {}
reject(new Error("CDP timed out"))
}, timeout)
ws.onopen = () => {
ws.send(
JSON.stringify({
id: 1,
method: "Runtime.evaluate",
params: { expression, returnByValue: true },
}),
)
}
ws.onerror = () => {
clearTimeout(timer)
reject(new Error("CDP connection failed"))
}
ws.onmessage = (event) => {
let message
try {
message = JSON.parse(String(event.data))
} catch {
return
}
if (message.id !== 1) return
clearTimeout(timer)
try {
ws.close()
} catch {}
if (message.error) {
reject(new Error(message.error.message || "CDP evaluation failed"))
return
}
if (message.result?.exceptionDetails) {
const details = message.result.exceptionDetails
const text =
details.exception?.description ||
details.exception?.value ||
details.text ||
"CDP evaluation failed"
reject(Object.assign(new Error(String(text)), { fatal: true }))
return
}
resolve(message.result?.result?.value)
}
})
}
function waitForExit(child, timeoutMs) {
if (child.exitCode !== null || child.signalCode !== null) return Promise.resolve()
return new Promise((resolve) => {
const timer = setTimeout(resolve, timeoutMs)
child.once("exit", () => {
clearTimeout(timer)
resolve()
})
})
}
// Chrome can report a transient SecurityError while the login page is loading.
async function waitForBrowserToken(
evaluate,
timeoutMs,
{ isActive = () => true, pollMs = 750, fatalGraceMs = 4000 } = {},
) {
const deadline = Date.now() + timeoutMs
let lastFatalText = ""
let fatalSince = 0
while (Date.now() < deadline && isActive()) {
try {
const value = await evaluate('localStorage.getItem("token")')
if (typeof value === "string" && value.trim()) return value.trim()
lastFatalText = ""
fatalSince = 0
} catch (error) {
if (error?.fatal) {
const text = String(error.message ?? error)
const now = Date.now()
if (text !== lastFatalText) {
lastFatalText = text
fatalSince = now
} else if (now - fatalSince >= fatalGraceMs) {
throw error
}
}
}
await new Promise((resolve) => setTimeout(resolve, pollMs))
}
if (lastFatalText) throw new Error(lastFatalText)
return ""
}
async function openChromeSession(
url,
{
targetPrefix = "https://platform.agnes-ai.com/",
profileDir = browserProfileDir(),
} = {},
) {
const browser = findBrowser()
if (!browser) {
throw new Error(
"Chrome or Edge was not found; set AGNES_BROWSER or use the API key sign-in",
)
}
const port = await freePort()
const profile = profileDir
mkdirSync(profile, { recursive: true, mode: 0o700 })
try {
chmodSync(profile, 0o700)
} catch {}
const child = spawn(browser, browserArgs(profile, port, url), {
stdio: "ignore",
detached: false,
})
activeChrome.add(child)
let closed = false
let exited = false
let spawnError = ""
child.once("error", (error) => {
spawnError = String(error?.message ?? error)
exited = true
})
child.once("exit", () => {
exited = true
})
let closing = null
const session = {
profilePath: profile,
close,
evaluate,
async token(timeoutMs) {
const token = await waitForBrowserToken(evaluate, timeoutMs, {
isActive: () => !closed && !exited,
})
if (spawnError) throw new Error(`Chrome failed to start: ${spawnError}`)
return token
},
}
async function evaluate(expression) {
const target = await cdpTarget(port, targetPrefix)
if (!target?.webSocketDebuggerUrl) return null
return await cdpEvaluate(target.webSocketDebuggerUrl, expression)
}
function close() {
if (closing) return closing
closed = true
closing = (async () => {
activeChrome.delete(child)
if (child.exitCode === null && child.signalCode === null) {
try {
child.kill("SIGTERM")
} catch {}
await waitForExit(child, 2000)
}
if (child.exitCode === null && child.signalCode === null) {
try {
child.kill("SIGKILL")
} catch {}
await waitForExit(child, 1000)
}
})()
return closing
}
return session
}
function number(value) {
return typeof value === "number" && Number.isFinite(value) ? value : null
}
function usedPercent(used, limit, given) {
if (typeof given === "number" && Number.isFinite(given)) return given
if (used === null || !limit || limit <= 0) return null
return Math.max(0, (used / limit) * 100)
}
function amountText(value) {
return value.toLocaleString("en-US", { maximumFractionDigits: 2 })
}
function balanceText(data) {
if (!data || typeof data !== "object") return ""
const minor = number(data.available_total_minor) ?? number(data.total_minor)
if (minor === null) return ""
const currency = typeof data.currency === "string" && data.currency.trim()
? data.currency.trim().toUpperCase()
: "USD"
try {
return new Intl.NumberFormat("en-US", {
style: "currency",
currency,
minimumFractionDigits: 2,
maximumFractionDigits: 4,
}).format(minor / 100)
} catch {
return `${(minor / 100).toFixed(2)} ${currency}`
}
}
function windowOf({ name, used, limit, unit, reset, display, aside }) {
const amount = used === null ? 0 : Math.max(0, used)
const total = limit === null ? 0 : Math.max(0, limit)
return {
name,
...(used === null ? { used: null } : { used: usedPercent(amount, total) }),
...(reset ? { resetsAt: reset } : {}),
...(display ? { display } : {}),
amount,
limit: total,
unit,
...(aside ? { aside: true } : {}),
}
}
function legacyWindows(data) {
const usage = data?.usage
if (!usage || typeof usage !== "object") return []
const definitions = [
["text_generation", "windowed", "Text · 5 hours", "requests", false],
["text_generation", "weekly", "Text · weekly", "requests", false],
["image_generation", "daily", "Images · daily", "images", true],
["video_generation", "daily", "Video seconds · daily", "seconds", true],
]
const out = []
for (const [kind, period, name, unit, aside] of definitions) {
const raw = usage[kind]?.[period]
if (!raw || typeof raw !== "object") continue
const used = number(raw.used)
const limit = number(raw.limit)
const amount = used ?? 0
const total = limit ?? 0
out.push({
...windowOf({
name,
used,
limit,
unit,
reset: vendorTime(raw.reset_at),
aside,
display:
used !== null && limit !== null
? `${amountText(amount)} / ${amountText(total)} ${unit}`
: "",
}),
used: usedPercent(amount, total, raw.usage_pct),
})
}
return out
}
function agentWindows(subscription, credits) {
if (!subscription || !credits || typeof credits !== "object") return []
const out = []
const quota =
number(credits.plan_quota_credits) ?? number(subscription.monthly_credits)
const planBalance = number(credits.plan_balance_credits)
if (quota !== null && quota > 0) {
const used = planBalance === null ? 0 : Math.max(0, quota - planBalance)
out.push({
name: "Monthly credits",
used: usedPercent(used, quota),
resetsAt: vendorTime(subscription.current_period_end),
display: `${amountText(used)} / ${amountText(quota)} credits`,
amount: used,
limit: quota,
unit: "credits",
})
}
const windowUsed = number(credits.window_used_credits)
const windowLimit = number(credits.window_limit_credits)
if (windowUsed !== null && windowLimit !== null && windowLimit > 0) {
out.push({
name: "5-hour window",
used: usedPercent(windowUsed, windowLimit),
display: `${amountText(windowUsed)} / ${amountText(windowLimit)} credits`,
amount: windowUsed,
limit: windowLimit,
unit: "credits",
})
}
const pack = number(credits.pack_balance_credits)
if (pack !== null) {
out.push({
name: "Purchased credits",
balance: Math.max(0, pack),
display: `${amountText(pack)} credits`,
unit: "credits",
aside: true,
})
}
return out
}
function legacyPlanName(data) {
const name = typeof data?.plan_name === "string" ? data.plan_name.trim() : ""
return name ? `${name} (Token Plan)` : ""
}
function agentPlanName(data) {
const name =
(typeof data?.tier_name === "string" && data.tier_name.trim()) ||
(typeof data?.tier_code === "string" && data.tier_code.trim()) ||
""
return name ? `${name} (Agent Plan)` : ""
}
function renewalOf(agent, legacy) {
if (agent) {
if (agent.auto_renew === true) return "auto"
if (agent.auto_renew === false) return "off"
}
if (legacy) return legacy.cancel_renewal_at ? "off" : "auto"
return ""
}
function vendorTime(value) {
if (typeof value !== "string" || !value.trim()) return ""
let text = value.trim()
if (/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?$/.test(text)) text += "Z"
const date = new Date(text)
return Number.isNaN(date.getTime()) ? "" : date.toISOString()
}
+774
View File
@@ -0,0 +1,774 @@
import { describe, expect, test } from "bun:test"
import { existsSync, mkdtempSync, rmSync } from "node:fs"
import { tmpdir } from "node:os"
import { join } from "node:path"
import { AgnesPlugin, _internal } from "./index.mjs"
const {
createPlugin,
BASE,
PLATFORM,
agentWindows,
profileLabel,
revealApiKey,
revealProfileKey,
browserArgs,
findBrowser,
openChromeSession,
cdpEvaluate,
waitForBrowserToken,
} = _internal
const apiKey = "test-api-key"
const consoleToken = "console-token"
const browserToken = "browser" + "-token-value"
const auth = {
type: "api",
key: apiKey,
metadata: { consoleToken, keyProfile: "plan" },
}
function jsonRes(status, body) {
return new Response(body === undefined ? null : JSON.stringify(body), {
status,
headers: { "content-type": "application/json" },
})
}
function fakeFetch(calls) {
return async (input, init) => {
calls.push({ input: String(input), init })
return calls.handler(calls.length - 1, input, init)
}
}
function fakeBrowserSession(token = browserToken) {
const events = []
let closed = false
return {
events,
token: async () => token,
evaluate: async (expression) => {
events.push(["evaluate", expression])
},
close: async () => {
closed = true
},
get closed() {
return closed
},
}
}
describe("config", () => {
test("declares Agnes with bootstrap text models and keeps configured values", async () => {
const plugin = createPlugin()
const cfg = { provider: { agnes: { name: "Mine" } } }
await plugin.config(cfg)
expect(cfg.provider.agnes.name).toBe("Mine")
expect(cfg.provider.agnes.npm).toBe("@ai-sdk/openai-compatible")
expect(cfg.provider.agnes.api).toBe(BASE)
expect(Object.keys(cfg.provider.agnes.models)).toContain("agnes-3.0-flash")
expect(cfg.provider.agnes.models["agnes-3.0-flash"].limit).toEqual({ context: 524288, output: 65536 })
})
})
describe("sign-in", () => {
test("keeps the API key for requests and the console token for usage", async () => {
const plugin = createPlugin()
expect(await plugin.auth.loader(async () => auth)).toEqual({
baseURL: BASE,
apiKey,
})
expect(plugin.auth.methods).toHaveLength(4)
expect(plugin.auth.methods[0]).toMatchObject({
type: "oauth",
label: "Agnes browser sign-in (plan key)",
})
expect(typeof plugin.auth.methods[0].authorize).toBe("function")
expect(plugin.auth.methods[1]).toMatchObject({
type: "oauth",
label: "Agnes browser sign-in (personal key)",
})
expect(plugin.auth.methods[2]).toMatchObject({
type: "oauth",
label: "Agnes browser sign-in (enterprise key)",
})
expect(plugin.auth.methods[3]).toMatchObject({ type: "api", placeholder: "cpk-…" })
expect(plugin.auth.methods[3].prompts[0]).toMatchObject({ key: "keyProfile" })
expect(plugin.auth.methods[3].prompts[1]).toMatchObject({ key: "consoleToken" })
})
test("loads an OAuth account's API key and console token", async () => {
const plugin = createPlugin()
const oauthAuth = { type: "oauth", access: apiKey, consoleToken, keyProfile: "plan" }
expect(await plugin.auth.loader(async () => oauthAuth)).toEqual({
baseURL: BASE,
apiKey,
})
})
})
describe("browser sign-in callback", () => {
test("finishes a plan-key browser sign-in", async () => {
const calls = []
const session = fakeBrowserSession()
calls.handler = (_i, input) => {
const path = new URL(String(input)).pathname.replace("/api", "")
if (path === "/user/self") {
expect(calls.at(-1).init.headers["x-user-language"]).toBe("en-US")
return jsonRes(200, { code: 200, data: {} })
}
if (path === "/user/agentplan/subscription") {
return jsonRes(200, { code: 404, message: "No AgentPlan subscription", data: null })
}
if (path === "/user/subscription/key/reveal") {
return jsonRes(200, { code: 200, data: { key: "plan-fixture" } })
}
throw new Error(`unexpected ${path}`)
}
const plugin = createPlugin({
fetchImpl: fakeFetch(calls),
openChrome: async () => session,
})
const flow = await plugin.auth.methods[0].authorize()
const saved = await flow.callback()
expect(saved).toMatchObject({
type: "success",
access: "plan-fixture",
consoleToken: browserToken,
accountId: "Agnes Plan",
})
expect(session.closed).toBe(true)
})
test("finishes a personal-key browser sign-in", async () => {
const calls = []
const session = fakeBrowserSession()
calls.handler = (_i, input) => {
const path = new URL(String(input)).pathname.replace("/api", "")
if (path === "/user/self") return jsonRes(200, { code: 200, data: {} })
if (path === "/token") {
return jsonRes(200, {
code: 200,
data: { items: [{ id: 7, key_profile: "default", status: 1 }] },
})
}
if (path === "/token/7/key") {
return jsonRes(200, { code: 200, data: { id: 7, key: "personal-fixture" } })
}
throw new Error(`unexpected ${path}`)
}
const plugin = createPlugin({
fetchImpl: fakeFetch(calls),
openChrome: async () => session,
})
const flow = await plugin.auth.methods[1].authorize()
const saved = await flow.callback()
expect(saved).toMatchObject({
type: "success",
access: "personal-fixture",
accountId: "Agnes Personal",
})
expect(session.closed).toBe(true)
})
test("clears a refused browser session token", async () => {
const calls = []
const session = fakeBrowserSession()
calls.handler = () => jsonRes(200, { code: 401, message: "not logged in", data: null })
const plugin = createPlugin({
fetchImpl: fakeFetch(calls),
openChrome: async () => session,
})
const flow = await plugin.auth.methods[0].authorize()
const saved = await flow.callback()
expect(saved.type).toBe("failed")
expect(saved.error).toContain("session expired")
expect(session.events).toContainEqual([
"evaluate",
'localStorage.removeItem("token")',
])
expect(session.closed).toBe(true)
expect(calls).toHaveLength(1)
})
})
test("exports one plugin function", async () => {
const hooks = await AgnesPlugin()
expect(hooks.auth.provider).toBe("agnes")
expect(hooks.provider.id).toBe("agnes")
})
describe("provider.models", () => {
test("lists the account's text models with documented limits and filters media models", async () => {
const calls = []
calls.handler = () =>
jsonRes(200, {
object: "list",
data: [
{ id: "agnes-3.0-flash" },
{ id: "agnes-new-text" },
{ id: "agnes-2.5-pro-alpha" },
{ id: "agnes-image-2.5-flash" },
{ id: "agnes-video-2.5-flash" },
],
})
const plugin = createPlugin({ fetchImpl: fakeFetch(calls) })
const models = await plugin.provider.models({ models: {} }, { auth })
expect(Object.keys(models)).toEqual(["agnes-3.0-flash", "agnes-new-text"])
expect(models["agnes-3.0-flash"].limit).toEqual({ context: 524288, output: 65536 })
expect(models["agnes-3.0-flash"].modalities.input).toEqual(["text", "image"])
expect(models["agnes-new-text"].limit).toEqual({ context: 0, output: 0 })
expect(models["agnes-new-text"].modalities.input).toEqual(["text"])
expect(calls[0].input).toBe(`${BASE}/models`)
expect(calls[0].init.headers.authorization).toBe(`Bearer ${apiKey}`)
})
test("keeps the previous list on a server error or network failure", async () => {
for (const handler of [() => jsonRes(503, {}), () => Promise.reject(new Error("offline"))]) {
const calls = []
calls.handler = handler
const plugin = createPlugin({ fetchImpl: fakeFetch(calls) })
const kept = { models: { kept: { name: "kept" } } }
expect(await plugin.provider.models(kept, { auth })).toBe(kept.models)
}
})
test("marks a refused API key as expired", async () => {
for (const status of [401, 403]) {
const calls = []
calls.handler = () => jsonRes(status, {})
const plugin = createPlugin({ fetchImpl: fakeFetch(calls) })
await expect(plugin.provider.models({ models: {} }, { auth })).rejects.toMatchObject({
signIn: "expired",
})
}
})
test("throws on a malformed model list so the host keeps its fallback", async () => {
for (const body of [{ data: "x" }, { data: [{ id: 42 }] }, null]) {
const calls = []
calls.handler = () => jsonRes(200, body)
const plugin = createPlugin({ fetchImpl: fakeFetch(calls) })
await expect(plugin.provider.models({ models: {} }, { auth })).rejects.toThrow(
"Agnes sent no model list",
)
}
})
test("lists nothing per-account without an API key", async () => {
const plugin = createPlugin()
const kept = { models: { kept: { name: "kept" } } }
expect(await plugin.provider.models(kept, {})).toBe(kept.models)
})
test("lists models for an OAuth account's API key", async () => {
const calls = []
calls.handler = () => jsonRes(200, { data: [{ id: "agnes-3.0-flash" }] })
const plugin = createPlugin({ fetchImpl: fakeFetch(calls) })
const oauthAuth = { type: "oauth", access: apiKey, consoleToken, keyProfile: "plan" }
const models = await plugin.provider.models({ models: {} }, { auth: oauthAuth })
expect(Object.keys(models)).toEqual(["agnes-3.0-flash"])
})
})
const legacyPlan = {
code: 200,
message: "ok",
data: {
plan_name: "Starter",
status: "active",
current_period_end: "2026-11-28T09:02:07",
cancel_renewal_at: null,
usage: {
text_generation: {
windowed: {
used: 12,
limit: 1500,
reset_at: "2026-10-31T12:00:00Z",
usage_pct: 0.8,
},
weekly: {
used: 120,
limit: 15000,
reset_at: "2026-11-02T00:00:00Z",
usage_pct: 0.8,
},
},
image_generation: {
daily: {
used: 60,
limit: 4000,
reset_at: "2026-11-01T00:00:00Z",
usage_pct: 1.5,
},
},
video_generation: {
daily: {
used: 115,
limit: 500,
reset_at: "2026-11-01T00:00:00Z",
usage_pct: 23,
},
},
},
},
}
const agentPlan = {
code: 200,
message: "ok",
data: {
tier_name: "Pro",
tier_code: "pro",
status: "active",
current_period_end: "2026-11-28T09:02:07",
auto_renew: true,
},
}
const agentCredits = {
code: 200,
message: "ok",
data: {
plan_quota_credits: 240000,
plan_balance_credits: 200000,
window_used_credits: 12000,
window_limit_credits: 24000,
pack_balance_credits: 50000,
},
}
const balance = {
code: 200,
message: "ok",
data: {
topup_balance_minor: 1000,
bonus_balance_minor: 234.56,
total_minor: 1234.56,
available_total_minor: 1200,
currency: "usd",
},
}
function platformHandler(routes) {
return (_i, input) => {
const path = new URL(String(input)).pathname.replace("/api", "")
return jsonRes(200, routes[path] ?? { code: 404, message: "not found", data: null })
}
}
describe("auth.usage", () => {
test("asks for the console token without sending the API key to its endpoint", async () => {
const calls = []
calls.handler = () => {
throw new Error("must not fetch")
}
const plugin = createPlugin({ fetchImpl: fakeFetch(calls) })
const card = await plugin.auth.usage(async () => ({ type: "api", key: apiKey }))
expect(calls).toHaveLength(0)
expect(card.error).toContain("console token")
expect(card.signIn).toBe("kept")
expect(card.windows).toEqual([])
})
test("maps the legacy Token Plan's request, image and video windows", async () => {
const calls = []
calls.handler = platformHandler({
"/user/subscription": legacyPlan,
"/user/agentplan/subscription": { code: 404, message: "No AgentPlan subscription", data: null },
})
const plugin = createPlugin({ fetchImpl: fakeFetch(calls) })
const card = await plugin.auth.usage(async () => auth)
expect(card.plan).toBe("Starter (Token Plan)")
expect(card.until).toBe("2026-11-28T09:02:07.000Z")
expect(card.renew).toBe("auto")
expect(card.windows.map((w) => w.name)).toEqual([
"Text · 5 hours",
"Text · weekly",
"Images · daily",
"Video seconds · daily",
])
expect(card.windows[0]).toMatchObject({
used: 0.8,
amount: 12,
limit: 1500,
unit: "requests",
display: "12 / 1,500 requests",
resetsAt: "2026-10-31T12:00:00.000Z",
})
expect(card.windows[2]).toMatchObject({ used: 1.5, display: "60 / 4,000 images" })
expect(card.windows[3]).toMatchObject({ used: 23, display: "115 / 500 seconds" })
expect(card.windows[0].aside).toBeUndefined()
expect(card.windows[1].aside).toBeUndefined()
expect(card.windows[2].aside).toBe(true)
expect(card.windows[3].aside).toBe(true)
expect(calls.map((c) => c.input)).toEqual([
`${PLATFORM}/user/subscription`,
`${PLATFORM}/user/agentplan/subscription`,
])
for (const call of calls) {
expect(call.init.headers.authorization).toBe(`Bearer ${consoleToken}`)
expect(call.init.headers.authorization).not.toContain(apiKey)
}
})
test("reads usage for an OAuth account's console token", async () => {
const calls = []
calls.handler = platformHandler({
"/user/subscription": legacyPlan,
"/user/agentplan/subscription": { code: 404, message: "No AgentPlan subscription", data: null },
})
const plugin = createPlugin({ fetchImpl: fakeFetch(calls) })
const oauthAuth = { type: "oauth", access: apiKey, consoleToken, keyProfile: "plan" }
const card = await plugin.auth.usage(async () => oauthAuth)
expect(card.windows).toHaveLength(4)
})
test("plan accounts do not query or show balance", async () => {
const calls = []
calls.handler = (_i, input) => {
const path = new URL(String(input)).pathname.replace("/api", "")
if (path === "/user/balance") throw new Error("must not read balance")
if (path === "/user/agentplan/subscription") {
return jsonRes(200, { code: 404, message: "No AgentPlan subscription", data: null })
}
return jsonRes(200, legacyPlan)
}
const plugin = createPlugin({ fetchImpl: fakeFetch(calls) })
const card = await plugin.auth.usage(async () => auth)
expect(card.windows).toHaveLength(4)
expect(card.balance).toBeUndefined()
expect(calls).toHaveLength(2)
})
test.each(["default", "enterprise"])(
"%s accounts show balance without querying plan usage",
async (keyProfile) => {
const calls = []
calls.handler = (_i, input) => {
const path = new URL(String(input)).pathname.replace("/api", "")
if (path !== "/user/balance") throw new Error(`unexpected ${path}`)
return jsonRes(200, balance)
}
const plugin = createPlugin({ fetchImpl: fakeFetch(calls) })
const profileAuth = {
type: "oauth",
access:
keyProfile === "enterprise" ? "profile-enterprise" : "profile-personal",
consoleToken,
keyProfile,
}
const card = await plugin.auth.usage(async () => profileAuth)
expect(card.plan).toBe(
keyProfile === "enterprise" ? "Enterprise API key" : "Personal API key",
)
expect(card.balance).toBe("$12.00")
expect(card.windows).toEqual([])
expect(calls).toHaveLength(1)
expect(calls[0].input).toBe(`${PLATFORM}/user/balance`)
},
)
test("maps Agent Plan monthly, five-hour and purchased credits", async () => {
const calls = []
calls.handler = platformHandler({
"/user/subscription": { code: 404, message: "No subscription", data: null },
"/user/agentplan/subscription": agentPlan,
"/user/agentplan/credits": agentCredits,
})
const plugin = createPlugin({ fetchImpl: fakeFetch(calls) })
const card = await plugin.auth.usage(async () => auth)
expect(card.plan).toBe("Pro (Agent Plan)")
expect(card.until).toBe("2026-11-28T09:02:07.000Z")
expect(card.renew).toBe("auto")
expect(card.windows).toHaveLength(3)
expect(card.windows[0]).toMatchObject({
name: "Monthly credits",
amount: 40000,
limit: 240000,
unit: "credits",
display: "40,000 / 240,000 credits",
resetsAt: "2026-11-28T09:02:07.000Z",
})
expect(card.windows[0].used).toBeCloseTo(16.67, 1)
expect(card.windows[1]).toMatchObject({
name: "5-hour window",
used: 50,
amount: 12000,
limit: 24000,
display: "12,000 / 24,000 credits",
})
expect(card.windows[2]).toMatchObject({
name: "Purchased credits",
balance: 50000,
unit: "credits",
display: "50,000 credits",
aside: true,
})
expect(calls.map((c) => c.input)).toContain(`${PLATFORM}/user/agentplan/credits`)
})
test("shows both plans when the account holds both", async () => {
const calls = []
calls.handler = platformHandler({
"/user/subscription": legacyPlan,
"/user/agentplan/subscription": agentPlan,
"/user/agentplan/credits": agentCredits,
})
const plugin = createPlugin({ fetchImpl: fakeFetch(calls) })
const card = await plugin.auth.usage(async () => auth)
expect(card.plan).toBe("Pro (Agent Plan) + Starter (Token Plan)")
expect(card.windows).toHaveLength(7)
})
test("falls back to the subscription's monthly credits when the balance is absent", () => {
const windows = agentWindows(
{ current_period_end: "2026-11-28T09:02:07", monthly_credits: 100000 },
{ plan_quota_credits: null, plan_balance_credits: null },
)
expect(windows[0]).toMatchObject({
name: "Monthly credits",
used: 0,
amount: 0,
limit: 100000,
display: "0 / 100,000 credits",
})
})
test("a refused console token keeps the API-key sign-in", async () => {
const calls = []
calls.handler = (_i, input) =>
String(input).includes("agentplan")
? jsonRes(200, { code: 404, message: "No AgentPlan subscription", data: null })
: jsonRes(401, { code: 401, message: "Not logged in or invalid token", data: null })
const plugin = createPlugin({ fetchImpl: fakeFetch(calls) })
const card = await plugin.auth.usage(async () => auth)
expect(card.signIn).toBe("kept")
expect(card.windows).toEqual([])
expect(card.error).toContain("console token")
})
test("keeps a readable plan when another usage request fails", async () => {
const calls = []
calls.handler = (_i, input) =>
String(input).endsWith("/user/agentplan/subscription")
? jsonRes(503, {})
: jsonRes(200, legacyPlan)
const plugin = createPlugin({ fetchImpl: fakeFetch(calls) })
const card = await plugin.auth.usage(async () => auth)
expect(card.windows).toHaveLength(4)
expect(card.error).toContain("Agent Plan")
})
})
describe("plan key reveal", () => {
test("prefers Agent Plan's key when that plan is active", async () => {
const calls = []
const platform = async (path) => {
calls.push(path)
if (path === "/user/agentplan/subscription") return { data: { tier_code: "pro" } }
if (path === "/user/agentplan/key/reveal") return { data: { key: "apk-key" } }
throw new Error(`unexpected ${path}`)
}
expect(await revealApiKey("jwt", platform)).toBe("apk-key")
expect(calls).toEqual(["/user/agentplan/subscription", "/user/agentplan/key/reveal"])
})
test("falls back to the Token Plan key", async () => {
const calls = []
const platform = async (path) => {
calls.push(path)
if (path === "/user/agentplan/subscription") return { missing: true }
if (path === "/user/subscription/key/reveal") return { data: { key: "cpk-key" } }
throw new Error(`unexpected ${path}`)
}
expect(await revealApiKey("jwt", platform)).toBe("cpk-key")
expect(calls).toEqual(["/user/agentplan/subscription", "/user/subscription/key/reveal"])
})
})
describe("profile key reveal", () => {
test("selects the first active personal key and reveals it by id", async () => {
const calls = []
const platform = async (path, _token, options) => {
calls.push([path, options?.method ?? "GET"])
if (path === "/token?key_profile=default") {
return {
data: {
items: [
{ id: 1, key_profile: "default", status: 0 },
{ id: 2, key_profile: "default", status: 1 },
{ id: 3, key_profile: "default", status: 1 },
],
},
}
}
if (path === "/token/2/key") return { data: { id: 2, key: "personal-key" } }
throw new Error(`unexpected ${path}`)
}
expect(await revealProfileKey("jwt", "default", platform)).toBe("personal-key")
expect(calls).toEqual([
["/token?key_profile=default", "GET"],
["/token/2/key", "POST"],
])
})
test("fails clearly when the profile has no active key", async () => {
const platform = async () => ({ data: { items: [{ id: 1, status: 0 }] } })
await expect(revealProfileKey("jwt", "enterprise", platform)).rejects.toThrow(
"no active enterprise API key",
)
})
})
test("profile labels contain no account identity", () => {
expect(profileLabel("plan")).toBe("Agnes Plan")
expect(profileLabel("default")).toBe("Agnes Personal")
expect(profileLabel("enterprise")).toBe("Agnes Enterprise")
})
test("browser args use a private profile and loopback debugging", () => {
const args = browserArgs("/tmp/agnes-profile", 9222, "https://platform.agnes-ai.com/login")
expect(args).toContain("--user-data-dir=/tmp/agnes-profile")
expect(args).toContain("--remote-debugging-port=9222")
expect(args).toContain("--remote-debugging-address=127.0.0.1")
expect(args).not.toContain("--remote-allow-origins=*")
expect(args.at(-1)).toBe("https://platform.agnes-ai.com/login")
})
test("CDP evaluation surfaces page exceptions", async () => {
class FakeWebSocket {
constructor() {
setTimeout(() => {
this.onopen?.()
}, 0)
}
send() {
setTimeout(() => {
this.onmessage?.({
data: JSON.stringify({
id: 1,
result: {
exceptionDetails: {
exception: { description: "SecurityError: localStorage access is denied" },
},
},
}),
})
}, 0)
}
close() {}
}
await expect(
cdpEvaluate("ws://127.0.0.1/fake", "localStorage.getItem('token')", 1000, FakeWebSocket),
).rejects.toThrow("SecurityError")
})
test("browser token polling retries page exceptions while the page loads", async () => {
let calls = 0
const token = await waitForBrowserToken(
async () => {
calls++
if (calls <= 2) {
throw Object.assign(new Error("SecurityError: localStorage access is denied"), {
fatal: true,
})
}
return "browser-token"
},
1000,
{ pollMs: 1, fatalGraceMs: 1000 },
)
expect(token).toBe("browser-token")
expect(calls).toBe(3)
})
test("browser token polling reports the last page exception on timeout", async () => {
await expect(
waitForBrowserToken(
async () => {
throw Object.assign(new Error("SecurityError: localStorage access is denied"), {
fatal: true,
})
},
20,
{ pollMs: 1, fatalGraceMs: 1000 },
),
).rejects.toThrow("SecurityError: localStorage access is denied")
})
test("browser token polling gives up on a persistent page exception", async () => {
let calls = 0
await expect(
waitForBrowserToken(
async () => {
calls++
throw Object.assign(new Error("SecurityError: localStorage access is denied"), {
fatal: true,
})
},
1000,
{ pollMs: 1, fatalGraceMs: 5 },
),
).rejects.toThrow("SecurityError: localStorage access is denied")
expect(calls).toBeGreaterThan(1)
})
test.skipIf(!findBrowser() || process.env.AGNES_BROWSER_TEST !== "1")(
"browser session reads only its target page and keeps its private profile",
async () => {
const server = Bun.serve({
hostname: "127.0.0.1",
port: 0,
fetch() {
return new Response(
'<!doctype html><script>localStorage.setItem("token","browser-test-token")</script>',
{ headers: { "content-type": "text/html" } },
)
},
})
const profile = mkdtempSync(join(tmpdir(), "agnes-profile-test-"))
const session = await openChromeSession(`http://127.0.0.1:${server.port}/`, {
targetPrefix: `http://127.0.0.1:${server.port}/`,
profileDir: profile,
})
try {
expect(await session.token(20000)).toBe("browser-test-token")
} finally {
await session.close()
server.stop(true)
}
expect(existsSync(session.profilePath)).toBe(true)
rmSync(profile, { recursive: true, force: true, maxRetries: 5, retryDelay: 200 })
},
30000,
)
+31
View File
@@ -0,0 +1,31 @@
{
"name": "@magpie-community/opencode-agnes-auth",
"version": "0.1.0",
"description": "Agnes AI international in OpenCode and magpie: Chrome browser sign-in, live text models, OpenAI-compatible chat, plan usage and USD balance",
"type": "module",
"main": "./index.mjs",
"files": [
"index.mjs",
"README.md",
"LICENSE"
],
"keywords": [
"opencode",
"opencode-plugin",
"magpie",
"agnes",
"agnes-ai"
],
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/magpie-community/plugins",
"directory": "packages/agnes"
},
"scripts": {
"test": "bun test"
},
"magpie": {
"icon": "https://www.agnes-ai.com/images/biglogo.png"
}
}
+2
View File
@@ -1,6 +1,8 @@
{
"version": 1,
"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/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 服务召回记忆,并按需存回完整对话。先配置服务地址;对话存回默认关闭。" } },