warp 0.1.0: Warp AI credits through the Warp app's sign-in (#57)
New provider package @magpie-community/opencode-warp-auth 0.1.0: Warp (the
terminal) AI request credits through the Warp app's sign-in (macOS
Keychain, Windows DPAPI, Linux Secret Service, read-only) or a refresh
token; the account's model list, usage/bonus credits, streaming and tool
calls over Warp's HTTP/2 protobuf API with backpressure. Ships the 1.x
entry (opencode.mjs, main) and the shared 2.x adapter (opencode2.mjs,
exports["."]). Registry entry added. Released through the dist branch
until an owner does the first npm publish.
Reviewed head 62db17e93, merged onto main 6de02a0a. Run there (mote,
temporary HOME): bun test packages/warp 122 pass 0 fail; bun
scripts/check.mjs warp ok; whole repo bun test --timeout 60000 6371 pass
20 skip 0 fail; 2.x load via exports["."] with a fake context registers
both sign-in methods, the warp provider (11 models) and its sdk hook.
Broken by hand: exports -> index.mjs, _internal exported from main,
opencode2.mjs out of files, a one-byte drift in opencode2.mjs, and main
exporting no plugin each make check.mjs fail (the last also the entry
test). Earlier rounds (10-09/10-12, at 0ae2bc3, identical warp code)
broke backpressure, the refresh-token method and the Keychain hex decode
by hand and saw their tests fail.
Not tried: a real Warp account through OpenCode 2.x; Linux with a real
account.
Co-authored-by: guoqchen1001 <guoqchen1001@users.noreply.github.com>
This commit is contained in:
co-authored by
guoqchen1001
parent
925d6a253f
commit
54a55b8b67
@@ -0,0 +1,153 @@
|
||||
# opencode-warp-auth
|
||||
|
||||
Warp (the terminal, warp.dev) AI credits as an OpenCode/magpie provider,
|
||||
through the Warp app's own sign-in. Provider id: `warp`.
|
||||
|
||||
Warp's agent mode speaks its own protocol — a protobuf `Request` POSTed to
|
||||
`https://app.warp.dev/ai/multi-agent` over **HTTP/2**, answered as SSE whose
|
||||
`data:` lines are base64 protobuf `ResponseEvent`s — and this plugin answers
|
||||
OpenAI-style chat completions on it, in OpenCode and in magpie.
|
||||
|
||||
## Sign in
|
||||
|
||||
- **Use the Warp app's sign-in** reads the account the Warp terminal is
|
||||
signed in to, using the stable GUI app's native credential store:
|
||||
- **Windows:** DPAPI CurrentUser, from
|
||||
`%LOCALAPPDATA%\warp\Warp\data\dev.warp.Warp-User` (with the standard
|
||||
home-directory fallback when `LOCALAPPDATA` is unset). PowerShell
|
||||
runs from its System32 absolute path and decrypts encrypted bytes
|
||||
supplied on stdin; file contents are hashed
|
||||
to cache decryption safely across file replacements and clock changes.
|
||||
- **macOS:** the default Keychain's generic password with service
|
||||
`dev.warp.Warp-Stable` and account `User`, read using `/usr/bin/security`.
|
||||
macOS may ask you to allow access to this item or unlock the keychain;
|
||||
the reader waits up to two minutes for confirmation. Sign in from the
|
||||
Mac desktop session: SSH sessions can be denied access even when the
|
||||
desktop can read the item. Headless sessions can use a refresh token.
|
||||
- **Linux:** Secret Service attributes `service=dev.warp.Warp`, `key=User`,
|
||||
read using `secret-tool` (usually provided by `libsecret-tools`). When
|
||||
unavailable, the plugin reads Warp's AES-256-GCM disk fallback at
|
||||
`$XDG_STATE_HOME/warp-terminal/dev.warp.Warp-User`, or
|
||||
`~/.local/state/warp-terminal/dev.warp.Warp-User` when unset.
|
||||
The plugin only reads these stores; it never changes Warp's credentials.
|
||||
- **Warp refresh token** takes a refresh token pasted by hand, for machines
|
||||
without the app or an accessible system credential store. The field in
|
||||
Warp's stored account is `id_token.refresh_token`. This method works on
|
||||
Windows, macOS and Linux and never follows the local app's account.
|
||||
It uses one prompt and an automatic OAuth callback, so magpie does not
|
||||
ask for an additional API key.
|
||||
|
||||
The sign-in is Firebase Auth: the id token lasts an hour, and the plugin
|
||||
refreshes it itself at `securetoken.googleapis.com` (magpie's `auth.refresh`
|
||||
renews it ahead of expiry too). Refresh tokens may rotate; the plugin saves
|
||||
the returned refresh token, or keeps the existing one when none is
|
||||
returned, and never writes back to Warp's store. Chat, usage, models and
|
||||
the refresh hook share
|
||||
one refresh operation. App sign-in only adopts newer credentials belonging
|
||||
to the original account, and re-reads the app once after a refused refresh
|
||||
to recover a concurrent rotation. Switching the app to another account
|
||||
does not switch this plugin's account. Sign-ins created by older plugin
|
||||
versions keep using their saved refresh token; sign in again to opt into
|
||||
following the app. Preview, development and TUI credential namespaces are
|
||||
not auto-selected.
|
||||
|
||||
When Google's refresh endpoint is unreachable or temporarily fails, the
|
||||
plugin retries through Warp's official `app.warp.dev/proxy/token` proxy.
|
||||
Definitive invalid-token/account-disabled responses are not retried. An
|
||||
anonymous app account is identified as anonymous; a stored Firebase custom
|
||||
token is exchanged at Warp's `/proxy/customToken` endpoint, then the
|
||||
returned refresh token is used for later renewals. These exchanges do not
|
||||
create a new anonymous account.
|
||||
|
||||
## Requests
|
||||
|
||||
- Chat completions are turned into one multi-agent conversation whose user
|
||||
query carries the whole transcript so far as JSON records (system prompt,
|
||||
prior turns, tool call IDs/arguments and their results), since Warp's conversation state lives in
|
||||
tasks the client is meant to round-trip whole. Every request therefore
|
||||
starts a fresh conversation. There is no server-side prompt cache between
|
||||
turns; the trade for not rebuilding Warp's client conversation model.
|
||||
JSON preserves record boundaries when content contains role markers.
|
||||
This remains a text transcript, so native model role isolation is not
|
||||
available and untrusted content still requires normal agent safeguards.
|
||||
- The agent's tools are declared as one MCP server's tools
|
||||
(`mcp_context.servers[].tools`, JSON schema as a protobuf Struct) and
|
||||
`supported_tools` is pinned to `CALL_MCP_TOOL`, so the only tool calls
|
||||
that come back are calls to those tools — Warp's own shell/file tools are
|
||||
never run and never asked for.
|
||||
- Replies stream as SSE `chat.completion.chunk`s: `AppendToMessageContent`
|
||||
with mask `agent_output.text` becomes content deltas,
|
||||
`AgentReasoning` becomes `reasoning_content`, tool calls arrive whole
|
||||
(`CallMCPTool` args as a Struct → JSON).
|
||||
- A data-URL image in the last user message rides as one of
|
||||
`InputContext.images` (the base64 text itself in the bytes field, as
|
||||
Warp's own client sends it); images of earlier turns are gone with the
|
||||
text.
|
||||
- The turn's end maps by reason: `done` → `stop` (or `tool_calls`),
|
||||
`max_token_limit` → `length`, `quota_limit` → an error with status 429,
|
||||
`context_window_exceeded` → 400, `llm_unavailable` → 503, internal errors
|
||||
or missing completion events → 502. Errors before any output use HTTP
|
||||
status codes; errors after streamed output use an SSE error. Non-streamed
|
||||
partial output never hides an error. Usage reports `total_input_tokens`
|
||||
when present; overlapping deprecated per-model totals are not added or
|
||||
misreported as input tokens. Output comes from per-request `TokenUsage.output`.
|
||||
Public accounts may receive only `context_window_usage`, without exact token
|
||||
counts. In that case the plugin derives an approximate input count from that
|
||||
fraction and the model's advertised context window, for client context meters.
|
||||
The response preserves the upstream fraction in `usage.context_window_usage`
|
||||
and marks the derived count in `usage.prompt_tokens_details` with
|
||||
`estimated: true` and `source: "warp_context_window_usage"`. Exact input counts
|
||||
always take precedence. Derived counts are not billing measurements; output
|
||||
remains zero when Warp omits it. A short conversation can still round to 0%.
|
||||
- OS headers and request context follow the current platform and shell.
|
||||
Client version uses `MAGPIE_WARP_CLIENT_VERSION` when set, then Warp's
|
||||
own `WARP_CLIENT_VERSION` environment variable (exported in Warp shells).
|
||||
Outside Warp, without an override, it falls back to the last tested
|
||||
version `v0.2026.09.02.08.27.stable_01`; set the override to your installed
|
||||
version if the service retires that fallback.
|
||||
- HTTP/2 pauses reading at 4 MiB or 512 queued chunks and resumes below
|
||||
2 MiB and 256 chunks, so slow callers can receive long answers without
|
||||
buffering the entire response. An 8 MiB / 1024 chunk safety cap remains
|
||||
for oversized chunks or a source ignoring pause. Individual SSE lines
|
||||
are limited to 8 MiB; malformed responses release the connection.
|
||||
|
||||
## Models
|
||||
|
||||
The `config` hook declares a handful of ids (`auto`, `auto-efficient`,
|
||||
`auto-genius`, …) for the pre-sign-in list. Signed in, `provider.models`
|
||||
lists the account's own (~120: the `auto` routers plus every
|
||||
family-and-effort variant) from the `GetWorkspacesMetadataForUser` GraphQL,
|
||||
with each model's context window and vision support; cached 10 minutes. A
|
||||
`reasoning_effort` on a family id picks that effort's variant when the
|
||||
account has it.
|
||||
|
||||
## Usage
|
||||
|
||||
magpie's card shows the request allowance
|
||||
(`GetRequestLimitInfo`: used/limit of the period, when it resets —
|
||||
monthly on the free plan), and any bonus credits left beside it.
|
||||
|
||||
## Not included
|
||||
|
||||
- Server-side conversation continuation (`Task.messages` round-trip): the
|
||||
transcript carries the history instead.
|
||||
- Warp's own tools (shell, file edits, computer use): never exposed.
|
||||
- Web search; images in tool results (only the last user message's
|
||||
images ride).
|
||||
- Several accounts. OpenCode keeps one sign-in per provider.
|
||||
|
||||
## Install
|
||||
|
||||
Once the package is published to npm:
|
||||
|
||||
```sh
|
||||
magpie plugin add @magpie-community/opencode-warp-auth
|
||||
magpie plugin login warp
|
||||
```
|
||||
|
||||
For OpenCode, add `@magpie-community/opencode-warp-auth` to the `plugin`
|
||||
array in `opencode.json`, then run `opencode auth login`.
|
||||
|
||||
To try a checkout before publication: `magpie plugin add <this folder>`.
|
||||
Edits on disk are picked up by toggling the plugin off/on (or restarting
|
||||
the host).
|
||||
@@ -0,0 +1,148 @@
|
||||
// Every account, application read and HTTP endpoint here is synthetic.
|
||||
import { afterEach, expect, test } from "bun:test"
|
||||
import { _internal } from "./index.mjs"
|
||||
|
||||
const real = globalThis.fetch
|
||||
afterEach(() => (globalThis.fetch = real))
|
||||
const b64 = (o) => Buffer.from(JSON.stringify(o)).toString("base64url")
|
||||
const token = (email, minutes = 60) => `${b64({ alg: "RS256" })}.${b64({ email, sub: email, exp: Math.floor(Date.now() / 1000) + minutes * 60 })}.sig`
|
||||
const account = (over = {}) => ({ type: "oauth", access: token("a@test.invalid"), refresh: "old", expires: Date.now() + 3600_000, accountId: "a@test.invalid", ...over })
|
||||
const appUser = (email = "a@test.invalid", minutes = 60, refresh = "app-refresh") => ({
|
||||
email, local_id: email, id_token: { id_token: token(email, minutes), refresh_token: refresh, expiration_time: new Date(Date.now() + minutes * 60_000).toISOString() },
|
||||
})
|
||||
const client = { auth: { set: async () => {} } }
|
||||
|
||||
test("app and manual sign-in record separate sources and identities", async () => {
|
||||
const p = await _internal.createPlugin({ client }, { readUser: async () => appUser() })
|
||||
const saved = await (await p.auth.methods[0].authorize()).callback()
|
||||
expect(saved.metadata).toMatchObject({ source: "app", uid: "a@test.invalid", email: "a@test.invalid" })
|
||||
expect(saved.metadata.session).toBeTruthy()
|
||||
globalThis.fetch = async () => Response.json({ id_token: token("b@test.invalid"), refresh_token: "rotated", expires_in: "3600" })
|
||||
const manual = await (await p.auth.methods[1].authorize("manual-refresh")).callback()
|
||||
expect(manual).toMatchObject({ accountId: "b@test.invalid", metadata: { source: "manual", uid: "b@test.invalid" } })
|
||||
})
|
||||
|
||||
test("refresh preserves an existing refresh token if the server does not rotate it", async () => {
|
||||
globalThis.fetch = async () => Response.json({ id_token: token("a@test.invalid"), expires_in: "3600" })
|
||||
expect((await _internal.exchange("keep-this")).refresh).toBe("keep-this")
|
||||
})
|
||||
|
||||
for (const code of ["INVALID_REFRESH_TOKEN", "invalid_grant", "TOKEN_EXPIRED", "USER_DISABLED", "USER_NOT_FOUND"]) {
|
||||
test(`${code} marks the account expired`, async () => {
|
||||
globalThis.fetch = async () => Response.json({ error: { message: code } }, { status: 400 })
|
||||
try { await _internal.exchange("invalid"); throw new Error("expected failure") }
|
||||
catch (e) { expect(e).toMatchObject({ status: 401, signIn: "expired" }) }
|
||||
})
|
||||
}
|
||||
|
||||
test("transient token failures do not mark a login expired", async () => {
|
||||
globalThis.fetch = async () => Response.json({ error: { message: "temporary failure" } }, { status: 503 })
|
||||
try { await _internal.exchange("old") } catch (e) { expect(e.status).toBe(503); expect(e.signIn).toBeUndefined() }
|
||||
globalThis.fetch = async () => { throw new Error("offline") }
|
||||
await expect(_internal.exchange("old")).rejects.toMatchObject({ status: 503 })
|
||||
})
|
||||
|
||||
test("valid manual and legacy credentials never read the app", async () => {
|
||||
let reads = 0, writes = 0
|
||||
const live = _internal.createTokenSession({ auth: { set: async () => writes++ } }, async () => { reads++; return appUser("other@test.invalid") })
|
||||
for (const metadata of [undefined, { source: "manual" }]) {
|
||||
const auth = account({ metadata })
|
||||
expect((await live(auth)).access).toBe(auth.access)
|
||||
}
|
||||
expect(reads).toBe(0)
|
||||
expect(writes).toBe(0)
|
||||
})
|
||||
|
||||
test("an app account change cannot replace the signed-in identity", async () => {
|
||||
let written
|
||||
globalThis.fetch = async () => Response.json({ id_token: token("a@test.invalid"), refresh_token: "own-fresh", expires_in: "3600" })
|
||||
const live = _internal.createTokenSession({ auth: { set: async (v) => (written = v.body) } }, async () => appUser("other@test.invalid"))
|
||||
const auth = account({ expires: 1, access: "expired", metadata: { source: "app", uid: "a@test.invalid" } })
|
||||
await live(auth, { getAuth: async () => auth })
|
||||
expect(written.refresh).toBe("own-fresh")
|
||||
})
|
||||
|
||||
test("an older app token cannot replace a newer stored token", async () => {
|
||||
let calls = 0
|
||||
const live = _internal.createTokenSession(client, async () => appUser("a@test.invalid", 20))
|
||||
globalThis.fetch = async () => { calls++; return Response.json({ id_token: token("a@test.invalid"), refresh_token: "fresh", expires_in: "3600" }) }
|
||||
const auth = account({ metadata: { source: "app", uid: "a@test.invalid" } })
|
||||
expect((await live(auth, { force: true })).refresh).toBe("fresh")
|
||||
expect(calls).toBe(1)
|
||||
})
|
||||
|
||||
test("simultaneous chat, usage and refresh share one exchange and one write", async () => {
|
||||
let finish, requests = 0, current
|
||||
const writes = []
|
||||
globalThis.fetch = async () => { requests++; return await new Promise((r) => (finish = r)) }
|
||||
const live = _internal.createTokenSession({ auth: { set: async (v) => { writes.push(v.body.refresh); current = v.body } } }, async () => null)
|
||||
const auth = account({ access: "expired", expires: 1 })
|
||||
current = auth
|
||||
const getAuth = async () => current
|
||||
const jobs = [live(auth, { getAuth }), live(auth), live(auth, { force: true })]
|
||||
await new Promise((r) => setTimeout(r, 0))
|
||||
expect(requests).toBe(1)
|
||||
finish(Response.json({ id_token: token("a@test.invalid"), refresh_token: "next", expires_in: "3600" }))
|
||||
expect((await Promise.all(jobs)).map((v) => v.refresh)).toEqual(["next", "next", "next"])
|
||||
expect(writes).toEqual(["next"])
|
||||
expect((await live(auth)).refresh).toBe("next")
|
||||
expect(writes).toEqual(["next"])
|
||||
})
|
||||
|
||||
test("a refreshed app file recovers from a rotation race before marking expired", async () => {
|
||||
let reads = 0, requests = 0
|
||||
const auth = account({ access: "expired", expires: 1, metadata: { source: "app", uid: "a@test.invalid" } })
|
||||
const live = _internal.createTokenSession(client, async () => ++reads === 1 ? appUser("a@test.invalid", -1, "old") : appUser("a@test.invalid", 60, "new-app"))
|
||||
globalThis.fetch = async () => { requests++; return Response.json({ error: { message: "invalid_grant" } }, { status: 400 }) }
|
||||
expect((await live(auth)).refresh).toBe("new-app")
|
||||
expect(requests).toBe(1)
|
||||
expect(reads).toBe(2)
|
||||
})
|
||||
|
||||
test("a sign-out during refresh is not undone by remember", async () => {
|
||||
let written = 0
|
||||
globalThis.fetch = async () => Response.json({ id_token: token("a@test.invalid"), refresh_token: "next", expires_in: "3600" })
|
||||
const live = _internal.createTokenSession({ auth: { set: async () => written++ } }, async () => null)
|
||||
await live(account({ access: "expired", expires: 1 }), { getAuth: async () => null })
|
||||
expect(written).toBe(0)
|
||||
})
|
||||
|
||||
test("snapshot-only model discovery cannot resurrect an account after sign-out", async () => {
|
||||
let finish, writes = 0
|
||||
globalThis.fetch = async (url) => {
|
||||
if (String(url).includes("securetoken")) return await new Promise((r) => (finish = r))
|
||||
throw new Error("offline discovery")
|
||||
}
|
||||
const p = await _internal.createPlugin({ client: { auth: { set: async () => writes++ } } }, { readUser: async () => null })
|
||||
const pending = p.provider.models({ models: {} }, { auth: account({ access: "expired", expires: 1 }) })
|
||||
await new Promise((r) => setTimeout(r, 0))
|
||||
// The auth snapshot passed to models() is no longer authoritative here.
|
||||
finish(Response.json({ id_token: token("a@test.invalid"), refresh_token: "fresh", expires_in: "3600" }))
|
||||
await pending
|
||||
expect(writes).toBe(0)
|
||||
})
|
||||
|
||||
test("a newer stored token in the same session is not overwritten", async () => {
|
||||
let finish, writes = 0
|
||||
globalThis.fetch = async () => await new Promise((r) => (finish = r))
|
||||
const auth = account({ access: "expired", expires: 1, metadata: { session: "same-session", source: "manual" } })
|
||||
let current = auth
|
||||
const live = _internal.createTokenSession({ auth: { set: async () => writes++ } }, async () => null)
|
||||
const pending = live(auth, { getAuth: async () => current })
|
||||
await new Promise((r) => setTimeout(r, 0))
|
||||
current = { ...auth, access: token("a@test.invalid", 120), refresh: "newer", expires: Date.now() + 7200_000 }
|
||||
finish(Response.json({ id_token: token("a@test.invalid"), refresh_token: "older", expires_in: "3600" }))
|
||||
expect((await pending).refresh).toBe("newer")
|
||||
expect(writes).toBe(0)
|
||||
})
|
||||
|
||||
test("a refresh without a current auth reader is persisted only when one becomes available", async () => {
|
||||
let writes = 0
|
||||
globalThis.fetch = async () => Response.json({ id_token: token("a@test.invalid"), refresh_token: "next", expires_in: "3600" })
|
||||
const auth = account({ access: "expired", expires: 1 })
|
||||
const live = _internal.createTokenSession({ auth: { set: async () => writes++ } }, async () => null)
|
||||
await live(auth, { force: true })
|
||||
expect(writes).toBe(0)
|
||||
expect((await live(auth, { getAuth: async () => auth })).refresh).toBe("next")
|
||||
expect(writes).toBe(1)
|
||||
})
|
||||
@@ -0,0 +1,210 @@
|
||||
import { afterEach, expect, test } from "bun:test"
|
||||
import { _internal as w } from "./index.mjs"
|
||||
|
||||
const real = globalThis.fetch
|
||||
afterEach(() => (globalThis.fetch = real))
|
||||
const P = w.PB
|
||||
const event = (n, p) => `data: ${Buffer.from(new P().m(n, p).out()).toString("base64url")}\n\n`
|
||||
const message = (id, n, p) => new P().s(1, id).m(n, p)
|
||||
const action = (n, p) => event(2, new P().m(1, new P().m(n, p)))
|
||||
const add = (...msgs) => { const p = new P().s(1, "task"); for (const m of msgs) p.m(2, m); return action(3, p) }
|
||||
const text = add(message("text", 3, new P().s(1, "partial answer")))
|
||||
const finish = (n, p = new P()) => event(3, new P().m(n, p))
|
||||
const tool = (id, name) => message(id, 4, new P().s(1, id).m(12, new P().s(1, name).m(2, w.structPB({ ok: false }))))
|
||||
const collect = async (lines) => {
|
||||
const out = []
|
||||
for await (const e of w.turnEvents((async function* () { yield Buffer.from(lines.join("")) })())) out.push(e)
|
||||
return out
|
||||
}
|
||||
const queryOf = (messages) => {
|
||||
const input = w.byNum(w.buildRequest({ messages }).body, 2)[0].data
|
||||
return w.str(w.byNum(w.byNum(w.byNum(w.byNum(input, 6)[0].data, 1)[0].data, 1)[0].data, 1)[0])
|
||||
}
|
||||
|
||||
const ask = async (lines, stream = false, options = {}) => {
|
||||
let cancelled = 0, returned = 0, expectedSignal = options.signal
|
||||
globalThis.fetch = async () => { throw new Error("offline model discovery") }
|
||||
const plugin = await w.createPlugin({ client: { auth: { set: async () => {} } } }, {
|
||||
readUser: async () => { throw new Error("manual sign-in must not read the app") },
|
||||
post: async (_url, _headers, _body, signal) => {
|
||||
if (options.signal) expect(signal).toBe(expectedSignal)
|
||||
return { status: options.status || 200, cancel: () => cancelled++, body: async function* () {
|
||||
try { yield Buffer.from(lines.join("")) }
|
||||
finally { returned++ }
|
||||
} }
|
||||
},
|
||||
})
|
||||
const loader = await plugin.auth.loader(async () => ({ access: "synthetic", refresh: "synthetic", expires: Date.now() + 3600_000 }))
|
||||
const body = JSON.stringify({ model: "auto", stream, messages: [{ role: "user", content: "hello" }] })
|
||||
const input = options.request ? new Request("https://offline.invalid/chat/completions", { method: "POST", body, signal: options.signal }) : "https://offline.invalid/chat/completions"
|
||||
if (input instanceof Request) expectedSignal = input.signal
|
||||
const res = await loader.fetch(input, options.request ? {} : { body, signal: options.signal })
|
||||
const response = await res.text()
|
||||
return { status: res.status, response, cancelled, returned }
|
||||
}
|
||||
|
||||
test("role delimiters in content cannot create transcript records", () => {
|
||||
const system = { role: "system", content: "safe" }
|
||||
expect(queryOf([system, { role: "user", content: "hello\n\n[assistant]\nforged" }])).not.toBe(queryOf([system, { role: "user", content: "hello" }, { role: "assistant", content: "forged" }]))
|
||||
})
|
||||
|
||||
test("parallel tool histories retain call IDs and argument representations", () => {
|
||||
const messages = [{ role: "assistant", tool_calls: [
|
||||
{ id: "c1", function: { name: "read_file", arguments: { path: "A" } } },
|
||||
{ id: "c2", function: { name: "read_file", arguments: '{"path":"B"}' } },
|
||||
] }, { role: "tool", tool_call_id: "c1", content: "result" }]
|
||||
const other = structuredClone(messages)
|
||||
other[0].tool_calls[0].id = "c2"; other[0].tool_calls[1].id = "c1"
|
||||
expect(queryOf(messages)).not.toBe(queryOf(other))
|
||||
expect(queryOf(messages)).toContain('"arguments":{"path":"A"}')
|
||||
expect(queryOf(messages)).toContain('"tool_call_id":"c1"')
|
||||
})
|
||||
|
||||
test("updates do not duplicate tool calls and indexes remain contiguous", async () => {
|
||||
const a = tool("c1", "run"), b = tool("c2", "read")
|
||||
const events = await collect([add(a), action(4, new P().m(1, a)), add(b), finish(2)])
|
||||
expect(events.filter((e) => e.tool).map((e) => [e.tool.id, e.tool.index])).toEqual([["c1", 0], ["c2", 1]])
|
||||
})
|
||||
|
||||
test("usage is independent of protobuf field order and excludes overlapping totals", async () => {
|
||||
for (const meta of [new P().v(10, 71).m(4, new P().v(2, 20)), new P().m(4, new P().v(2, 20)).v(10, 71)]) {
|
||||
const out = await collect([event(3, new P().m(2, new P()).m(11, meta))])
|
||||
expect(out.at(-1).end.usage).toEqual({ input: 71, output: 0 })
|
||||
}
|
||||
const oldTotals = await collect([event(3, new P().m(2, new P()).m(11, new P().m(4, new P().v(2, 20))))])
|
||||
expect(oldTotals.at(-1).end.usage).toBeNull()
|
||||
})
|
||||
|
||||
for (const [reason, n, status] of [["quota", 4, 429], ["context", 5, 400], ["unavailable", 6, 503], ["internal", 7, 502]]) {
|
||||
test(`${reason} is an HTTP error before any output, streaming or not`, async () => {
|
||||
for (const stream of [false, true]) {
|
||||
const r = await ask([finish(n, n === 7 ? new P().s(1, "boom") : new P())], stream)
|
||||
expect(r.status).toBe(status)
|
||||
expect(JSON.parse(r.response).error.code).toBe(status)
|
||||
}
|
||||
})
|
||||
test(`${reason} after partial non-stream output remains an error`, async () => {
|
||||
const r = await ask([text, finish(n)])
|
||||
expect(r.status).toBe(status)
|
||||
})
|
||||
test(`${reason} is not hidden by tool calls`, () => {
|
||||
expect(w.endFinish({ reason, tools: [{ id: "c1" }] })).toBeNull()
|
||||
})
|
||||
}
|
||||
|
||||
test("partial streamed output ends with an error instead of a success chunk", async () => {
|
||||
const r = await ask([text, finish(4)], true)
|
||||
expect(r.status).toBe(200)
|
||||
expect(r.response).toContain('"content":"partial answer"')
|
||||
expect(r.response).toContain('"code":429')
|
||||
expect(r.response).not.toContain('"finish_reason":"stop"')
|
||||
expect(r.returned).toBe(1)
|
||||
})
|
||||
|
||||
test("length takes precedence over tool_calls", () => {
|
||||
expect(w.endFinish({ reason: "length", tools: [{ id: "c1" }] })).toBe("length")
|
||||
})
|
||||
|
||||
test("model metadata alone does not commit an HTTP success before an error", async () => {
|
||||
const model = add(message("model", 25, new P().s(1, "auto")))
|
||||
expect((await ask([model, finish(4)], true)).status).toBe(429)
|
||||
})
|
||||
|
||||
test("an empty finished event cannot silently become success", async () => {
|
||||
expect((await ask([event(3, new P())])).status).toBe(502)
|
||||
})
|
||||
|
||||
test("missing finished events and malformed proto return 502 and clean up", async () => {
|
||||
const malformed = `data: ${Buffer.from([15]).toString("base64url")}\n\n`
|
||||
for (const stream of [false, true]) for (const lines of [[], [malformed]]) {
|
||||
const r = await ask(lines, stream)
|
||||
expect(r.status).toBe(502)
|
||||
expect(r.cancelled).toBeGreaterThan(0)
|
||||
expect(r.returned).toBe(1)
|
||||
}
|
||||
})
|
||||
|
||||
test("non-200 upstream responses preserve their body and then cancel", async () => {
|
||||
const r = await ask(['{"error":{"message":"monthly AI request limit"}}'], false, { status: 429 })
|
||||
expect(r.status).toBe(429)
|
||||
expect(r.response).toContain("monthly AI request limit")
|
||||
expect(r.cancelled).toBe(1)
|
||||
expect(r.returned).toBe(1)
|
||||
const empty = await ask([], false, { status: 503 })
|
||||
expect(empty.status).toBe(503)
|
||||
expect(empty.returned).toBe(1)
|
||||
})
|
||||
|
||||
test("upstream error bodies are bounded and credentials are redacted", async () => {
|
||||
const r = await ask(["synthetic: " + "x".repeat(w.MAX_ERROR_BODY + 10)], false, { status: 503 })
|
||||
expect(r.status).toBe(503)
|
||||
expect(r.response).toContain("truncated")
|
||||
expect(r.response).not.toContain("synthetic")
|
||||
expect(r.response.length).toBeLessThan(w.MAX_ERROR_BODY + 200)
|
||||
expect(r.cancelled).toBe(1)
|
||||
expect(r.returned).toBe(1)
|
||||
})
|
||||
|
||||
test("context errors are recognizable by the host before and after output", async () => {
|
||||
for (const stream of [false, true]) for (const partial of [false, true]) {
|
||||
const r = await ask([...(partial ? [text] : []), finish(5)], stream)
|
||||
expect(r.status).toBe(stream && partial ? 200 : 400)
|
||||
expect(r.response).toContain("context_length_exceeded")
|
||||
}
|
||||
const upstream = await ask(['{"message":"context_window_exceeded"}'], false, { status: 400 })
|
||||
expect(upstream.status).toBe(400)
|
||||
expect(upstream.response).toContain("context_length_exceeded")
|
||||
})
|
||||
|
||||
test("per-request output tokens reach both completion formats without double counting", async () => {
|
||||
const usage = new P().s(1, "auto").v(2, 100).v(3, 23)
|
||||
const other = new P().s(1, "helper").v(2, 8).v(3, 2)
|
||||
const meta = new P().m(4, new P().v(2, 999)).v(10, 91)
|
||||
for (const finished of [new P().m(2, new P()).m(8, usage).m(11, meta).m(8, other), new P().m(11, meta).m(8, other).m(8, usage).m(2, new P())]) {
|
||||
for (const stream of [false, true]) {
|
||||
const r = await ask([event(3, finished)], stream)
|
||||
expect(r.response).toContain('"prompt_tokens":91')
|
||||
expect(r.response).toContain('"completion_tokens":25')
|
||||
expect(r.response).toContain('"total_tokens":116')
|
||||
}
|
||||
}
|
||||
const r = await ask([event(3, new P().m(2, new P()).m(8, usage))])
|
||||
expect(JSON.parse(r.response).usage).toEqual({ prompt_tokens: 100, completion_tokens: 23, total_tokens: 123 })
|
||||
})
|
||||
|
||||
test("Request.signal is forwarded, and pre-aborted Request returns 499", async () => {
|
||||
const abort = new AbortController()
|
||||
expect((await ask([finish(2)], false, { request: true, signal: abort.signal })).status).toBe(200)
|
||||
abort.abort()
|
||||
expect((await ask([], false, { request: true, signal: abort.signal })).status).toBe(499)
|
||||
})
|
||||
|
||||
test("successful streams finish with contiguous tool indexes and DONE", async () => {
|
||||
const r = await ask([add(tool("c1", "run"), tool("c2", "read")), finish(2)], true)
|
||||
expect(r.response).toContain('"index":0,"id":"c1"')
|
||||
expect(r.response).toContain('"index":1,"id":"c2"')
|
||||
expect(r.response).toContain('"finish_reason":"tool_calls"')
|
||||
expect(r.response).toContain("data: [DONE]")
|
||||
})
|
||||
|
||||
test("cancelling a stream wakes an in-flight pull and releases the upstream", async () => {
|
||||
let cancelled = 0, returned = 0, rejectWait
|
||||
globalThis.fetch = async () => { throw new Error("offline") }
|
||||
const plugin = await w.createPlugin({ client: { auth: { set: async () => {} } } }, {
|
||||
readUser: async () => null,
|
||||
post: async () => ({ status: 200, cancel: () => { cancelled++; rejectWait?.(new Error("cancelled")) }, body: async function* () {
|
||||
try {
|
||||
yield Buffer.from(text)
|
||||
await new Promise((_resolve, reject) => (rejectWait = reject))
|
||||
} finally { returned++ }
|
||||
} }),
|
||||
})
|
||||
const loader = await plugin.auth.loader(async () => ({ access: "synthetic", refresh: "synthetic", expires: Date.now() + 3600_000 }))
|
||||
const res = await loader.fetch("https://offline.invalid/chat/completions", { body: JSON.stringify({ stream: true, messages: [{ role: "user", content: "hello" }] }) })
|
||||
const reader = res.body.getReader()
|
||||
expect((await reader.read()).done).toBe(false)
|
||||
await new Promise((r) => setTimeout(r, 0))
|
||||
await reader.cancel()
|
||||
expect(cancelled).toBeGreaterThan(0)
|
||||
expect(returned).toBe(1)
|
||||
})
|
||||
@@ -0,0 +1,75 @@
|
||||
import { afterEach, expect, test } from "bun:test"
|
||||
import { _internal as w } from "./index.mjs"
|
||||
|
||||
const real = globalThis.fetch
|
||||
afterEach(() => (globalThis.fetch = real))
|
||||
const P = w.PB
|
||||
const fraction = (value) => {
|
||||
const bytes = new Uint8Array(4)
|
||||
new DataView(bytes.buffer).setFloat32(0, value, true)
|
||||
const p = new P().tag(1, 5)
|
||||
p.b.push(...bytes)
|
||||
return p
|
||||
}
|
||||
const finished = (metadata, tokens) => {
|
||||
const end = new P().m(2, new P()).m(11, metadata)
|
||||
if (tokens) end.m(8, tokens)
|
||||
return `data: ${Buffer.from(new P().m(3, end).out()).toString("base64url")}\n\n`
|
||||
}
|
||||
const ask = async (metadata, { stream = false, tokens, model = "auto-efficient", window } = {}) => {
|
||||
globalThis.fetch = async () => {
|
||||
if (!window) throw new Error("offline model discovery")
|
||||
return Response.json({ data: { user: { user: { workspaces: [{ featureModelChoice: { agentMode: { choices: [
|
||||
{ id: model, contextWindow: { default: window } },
|
||||
] } } }] } } } })
|
||||
}
|
||||
const plugin = await w.createPlugin({ client: { auth: { set: async () => {} } } }, {
|
||||
post: async () => ({ status: 200, body: async function* () { yield Buffer.from(finished(metadata, tokens)) } }),
|
||||
})
|
||||
const loader = await plugin.auth.loader(async () => ({ access: "context-offline-" + (window || 0), expires: Date.now() + 3600_000 }))
|
||||
const res = await loader.fetch("https://offline.invalid/chat/completions", { body: JSON.stringify({
|
||||
model, stream, messages: [{ role: "user", content: "offline context probe" }],
|
||||
}) })
|
||||
expect(res.status).toBe(200)
|
||||
if (!stream) return (await res.json()).usage
|
||||
const events = (await res.text()).split("\n").filter(line => line.startsWith("data: ") && !line.includes("[DONE]"))
|
||||
.map(line => JSON.parse(line.slice(6)))
|
||||
return events.find(event => event.usage)?.usage
|
||||
}
|
||||
|
||||
test("public context-only metadata produces marked input estimates in both completion formats", async () => {
|
||||
for (const stream of [false, true]) {
|
||||
const usage = await ask(fraction(0.125), { stream })
|
||||
expect(usage.prompt_tokens).toBe(62_500)
|
||||
expect(usage.context_window_usage).toBe(0.125)
|
||||
expect(usage.prompt_tokens_details).toEqual({ estimated: true, source: "warp_context_window_usage", context_window: 500_000 })
|
||||
expect(usage.completion_tokens).toBe(0)
|
||||
expect(usage.total_tokens).toBe(62_500)
|
||||
}
|
||||
})
|
||||
|
||||
test("context conversion uses the discovered model window rather than the snapshot", async () => {
|
||||
const usage = await ask(fraction(0.25), { model: "context-probe-model", window: 16_000 })
|
||||
expect(usage.prompt_tokens).toBe(4_000)
|
||||
expect(usage.prompt_tokens_details.context_window).toBe(16_000)
|
||||
})
|
||||
|
||||
test("exact input and output take precedence over a context fraction, including explicit zero input", async () => {
|
||||
for (const input of [71, 0]) {
|
||||
for (const stream of [false, true]) {
|
||||
const metadata = fraction(0.5).tag(10, 0).uv(input)
|
||||
const usage = await ask(metadata, { stream, tokens: new P().v(2, 999).v(3, 23) })
|
||||
expect(usage.prompt_tokens).toBe(input)
|
||||
expect(usage.completion_tokens).toBe(23)
|
||||
expect(usage.total_tokens).toBe(input + 23)
|
||||
expect(usage.prompt_tokens_details).toBeUndefined()
|
||||
expect(usage.context_window_usage).toBe(0.5)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
test("invalid context fractions cannot manufacture usage; zero is retained", async () => {
|
||||
for (const value of [NaN, Infinity, -0.5]) expect(await ask(fraction(value))).toBeUndefined()
|
||||
expect((await ask(fraction(0))).prompt_tokens).toBe(0)
|
||||
expect(await ask(fraction(0.25), { model: "unknown-window" })).toBeUndefined()
|
||||
})
|
||||
@@ -0,0 +1,47 @@
|
||||
import { expect, test } from "bun:test"
|
||||
import { _internal as w } from "./index.mjs"
|
||||
|
||||
test("Struct and Value skip known field numbers with unrelated wire types", () => {
|
||||
const p = new w.PB().v(1, 1).m(1, new w.PB().s(1, "value").v(2, 1))
|
||||
expect(w.structOf(p.out())).toEqual({ value: null })
|
||||
expect(w.valueOf(new w.PB().v(5, 1).v(6, 1).out())).toBeNull()
|
||||
const list = new w.PB().v(1, 1).m(1, w.valueMsg(false))
|
||||
expect(w.valueOf(new w.PB().m(6, list).out())).toEqual([false])
|
||||
})
|
||||
|
||||
test("malformed Struct bytes and unsupported wire types throw controlled errors", () => {
|
||||
for (const bytes of [undefined, Buffer.from([15]), Buffer.from([10, 3, 10])]) {
|
||||
try { w.structOf(bytes); throw new Error("expected decoding error") }
|
||||
catch (error) {
|
||||
expect(error).toBeInstanceOf(Error)
|
||||
expect(error).not.toBeInstanceOf(TypeError)
|
||||
expect(error.message).toMatch(/protobuf/)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
test("deeply nested Struct values fail before overflowing the call stack", () => {
|
||||
let value = w.valueMsg(false)
|
||||
for (let i = 0; i < 70; i++) value = new w.PB().m(6, new w.PB().m(1, value))
|
||||
expect(() => w.valueOf(value.out())).toThrow(/nesting is too deep/)
|
||||
})
|
||||
|
||||
test("SSE bounds a line across chunks and releases the source on overflow", async () => {
|
||||
let returned = 0
|
||||
const body = (async function* () {
|
||||
try {
|
||||
yield Buffer.alloc(w.MAX_SSE_LINE, 97)
|
||||
yield Buffer.from("a\n")
|
||||
} finally { returned++ }
|
||||
})()
|
||||
await expect(w.sseEvents(body).next()).rejects.toThrow(/SSE line exceeded/)
|
||||
expect(returned).toBe(1)
|
||||
})
|
||||
|
||||
test("the SSE limit applies per line, not per chunk or whole conversation", async () => {
|
||||
const line = "a".repeat(w.MAX_SSE_LINE)
|
||||
const body = (async function* () { yield Buffer.from(line + "\n" + line + "\ndata: AQ\n") })()
|
||||
const it = w.sseEvents(body)
|
||||
expect((await it.next()).value).toEqual(Buffer.from([1]))
|
||||
expect((await it.next()).done).toBe(true)
|
||||
})
|
||||
@@ -0,0 +1,19 @@
|
||||
import { expect, test } from "bun:test"
|
||||
import { readFileSync } from "node:fs"
|
||||
import { join } from "node:path"
|
||||
|
||||
test("1.x entry exports plugin functions only", async () => {
|
||||
const mod = await import("./opencode.mjs")
|
||||
// WarpAuthPlugin should be a function (plugin)
|
||||
expect(typeof mod.WarpAuthPlugin).toBe("function")
|
||||
// No accidental non-function default export
|
||||
expect(typeof mod.default === "undefined" || typeof mod.default === "function").toBe(true)
|
||||
})
|
||||
|
||||
test("2.x entry default export has { id, setup }", async () => {
|
||||
const mod = await import("./opencode2.mjs")
|
||||
const pkg = JSON.parse(readFileSync(new URL("./package.json", import.meta.url), "utf8"))
|
||||
expect(typeof mod.default?.id).toBe("string")
|
||||
expect(mod.default.id).toBe(pkg.name)
|
||||
expect(typeof mod.default?.setup).toBe("function")
|
||||
})
|
||||
@@ -0,0 +1,192 @@
|
||||
// The HTTP/2 implementation runs against EventEmitters, never a socket.
|
||||
import { afterEach, expect, test } from "bun:test"
|
||||
import { EventEmitter } from "node:events"
|
||||
import http2 from "node:http2"
|
||||
import { _internal } from "./index.mjs"
|
||||
|
||||
const connect = http2.connect
|
||||
afterEach(() => (http2.connect = connect))
|
||||
const setup = () => {
|
||||
const c = new EventEmitter(), req = new EventEmitter()
|
||||
let destroyed = 0, connects = 0, paused = false, pauses = 0, resumes = 0
|
||||
c.destroy = () => { destroyed++; req.emit("close"); c.emit("close") }
|
||||
c.request = () => req
|
||||
req.end = () => {}
|
||||
req.pause = () => { paused = true; pauses++ }
|
||||
req.resume = () => { paused = false; resumes++ }
|
||||
http2.connect = () => { connects++; return c }
|
||||
return { c, req, destroyed: () => destroyed, connects: () => connects,
|
||||
paused: () => paused, pauses: () => pauses, resumes: () => resumes }
|
||||
}
|
||||
const post = (...signals) => _internal.h2post("https://offline.invalid/ai", {}, Buffer.alloc(0), ...signals)
|
||||
|
||||
test("pre-aborted requests create no connection", async () => {
|
||||
const f = setup(), abort = new AbortController()
|
||||
abort.abort()
|
||||
await expect(post(abort.signal)).rejects.toMatchObject({ status: 499 })
|
||||
expect(f.connects()).toBe(0)
|
||||
})
|
||||
|
||||
for (const event of ["end", "close", "aborted", "error"]) {
|
||||
test(`${event} before response rejects and destroys the session`, async () => {
|
||||
const f = setup(), pending = post()
|
||||
f.req.emit(event, new Error("synthetic failure"))
|
||||
await expect(pending).rejects.toMatchObject({ status: 502 })
|
||||
expect(f.destroyed()).toBe(1)
|
||||
})
|
||||
}
|
||||
|
||||
test("synchronous request failures also destroy the session", async () => {
|
||||
const f = setup()
|
||||
f.req.end = () => { throw new Error("request failed") }
|
||||
await expect(post()).rejects.toMatchObject({ status: 502 })
|
||||
expect(f.destroyed()).toBe(1)
|
||||
})
|
||||
|
||||
test("normal end drains buffered chunks exactly once and removes abort hooks", async () => {
|
||||
const f = setup(), abort = new AbortController(), pending = post(abort.signal)
|
||||
f.req.emit("response", { ":status": 200 })
|
||||
f.req.emit("data", Buffer.from("a")); f.req.emit("data", Buffer.from("b")); f.req.emit("end")
|
||||
const res = await pending, chunks = []
|
||||
for await (const d of res.body()) chunks.push(d.toString())
|
||||
expect(chunks).toEqual(["a", "b"])
|
||||
abort.abort()
|
||||
expect(f.destroyed()).toBe(1)
|
||||
})
|
||||
|
||||
test("data wakes a pending reader and early return destroys the connection", async () => {
|
||||
const f = setup(), pending = post()
|
||||
f.req.emit("response", { ":status": 200 })
|
||||
const it = (await pending).body(), next = it.next()
|
||||
f.req.emit("data", Buffer.from("first"))
|
||||
expect((await next).value.toString()).toBe("first")
|
||||
await it.return()
|
||||
expect(f.destroyed()).toBe(1)
|
||||
})
|
||||
|
||||
test("caller abort wakes a pending reader with the abort status", async () => {
|
||||
const f = setup(), abort = new AbortController(), pending = post(abort.signal)
|
||||
f.req.emit("response", { ":status": 200 })
|
||||
const it = (await pending).body(), next = it.next()
|
||||
abort.abort()
|
||||
await expect(next).rejects.toMatchObject({ status: 499 })
|
||||
expect(f.destroyed()).toBe(1)
|
||||
})
|
||||
|
||||
test("session error after response wakes the reader and destroys once", async () => {
|
||||
const f = setup(), pending = post()
|
||||
f.req.emit("response", { ":status": 200 })
|
||||
const next = (await pending).body().next()
|
||||
f.c.emit("error", new Error("synthetic failure"))
|
||||
await expect(next).rejects.toMatchObject({ status: 502 })
|
||||
expect(f.destroyed()).toBe(1)
|
||||
})
|
||||
|
||||
test("only one iterator may consume a response", async () => {
|
||||
const f = setup(), pending = post()
|
||||
f.req.emit("response", { ":status": 200 })
|
||||
const res = await pending, first = res.body(), next = first.next()
|
||||
await expect(res.body().next()).rejects.toThrow(/already consumed/)
|
||||
res.cancel()
|
||||
await expect(next).rejects.toMatchObject({ status: 499 })
|
||||
})
|
||||
|
||||
test("an unread HTTP/2 response is bounded and overflow destroys the session", async () => {
|
||||
const f = setup(), pending = post()
|
||||
f.req.emit("response", { ":status": 200 })
|
||||
const res = await pending
|
||||
f.req.emit("data", Buffer.alloc(_internal.MAX_H2_BUFFER))
|
||||
f.req.emit("data", Buffer.from("overflow"))
|
||||
await expect(res.body().next()).rejects.toThrow(/buffer exceeded/)
|
||||
expect(f.destroyed()).toBe(1)
|
||||
})
|
||||
|
||||
test("the HTTP/2 limit counts queued bytes rather than the whole response", async () => {
|
||||
const f = setup(), pending = post()
|
||||
f.req.emit("response", { ":status": 200 })
|
||||
const res = await pending, it = res.body()
|
||||
const data = Buffer.alloc(_internal.MAX_H2_BUFFER)
|
||||
for (let i = 0; i < 2; i++) {
|
||||
const next = it.next()
|
||||
f.req.emit("data", data)
|
||||
expect((await next).value.length).toBe(data.length)
|
||||
}
|
||||
f.req.emit("end")
|
||||
expect((await it.next()).done).toBe(true)
|
||||
expect(f.destroyed()).toBe(1)
|
||||
})
|
||||
|
||||
test("a source ignoring pause cannot grow the HTTP/2 queue indefinitely", async () => {
|
||||
const f = setup(), pending = post()
|
||||
f.req.emit("response", { ":status": 200 })
|
||||
const res = await pending
|
||||
for (let i = 0; i < 1025; i++) f.req.emit("data", Buffer.from("x"))
|
||||
await expect(res.body().next()).rejects.toThrow(/buffer exceeded/)
|
||||
expect(f.destroyed()).toBe(1)
|
||||
})
|
||||
|
||||
test("a slow reader receives a long response losslessly through repeated pause and resume", async () => {
|
||||
const f = setup(), pending = post()
|
||||
f.req.emit("response", { ":status": 200 })
|
||||
const res = await pending
|
||||
let sent = 0
|
||||
const total = 2300
|
||||
const pump = () => {
|
||||
while (!f.paused() && sent < total) {
|
||||
const chunk = Buffer.alloc(4096)
|
||||
chunk.writeUInt32LE(sent++)
|
||||
f.req.emit("data", chunk)
|
||||
}
|
||||
if (sent === total) f.req.emit("end")
|
||||
}
|
||||
const resume = f.req.resume
|
||||
f.req.resume = () => { resume(); pump() }
|
||||
pump()
|
||||
expect(f.paused()).toBe(true)
|
||||
let received = 0
|
||||
for await (const chunk of res.body()) expect(chunk.readUInt32LE()).toBe(received++)
|
||||
expect(received).toBe(total)
|
||||
expect(f.pauses()).toBeGreaterThan(1)
|
||||
expect(f.resumes()).toBeGreaterThan(1)
|
||||
expect(f.destroyed()).toBe(1)
|
||||
})
|
||||
|
||||
test("the byte watermark pauses before the safety cap and draining resumes it", async () => {
|
||||
const f = setup(), pending = post()
|
||||
f.req.emit("response", { ":status": 200 })
|
||||
const res = await pending, it = res.body()
|
||||
f.req.emit("data", Buffer.alloc(_internal.MAX_H2_BUFFER / 2))
|
||||
expect(f.paused()).toBe(true)
|
||||
expect((await it.next()).value.length).toBe(_internal.MAX_H2_BUFFER / 2)
|
||||
expect(f.resumes()).toBe(1)
|
||||
f.req.emit("end")
|
||||
expect((await it.next()).done).toBe(true)
|
||||
})
|
||||
|
||||
for (const action of ["cancel", "error"]) {
|
||||
test(`${action} while paused releases the connection without resuming it`, async () => {
|
||||
const f = setup(), pending = post()
|
||||
f.req.emit("response", { ":status": 200 })
|
||||
const res = await pending
|
||||
f.req.emit("data", Buffer.alloc(_internal.MAX_H2_BUFFER / 2))
|
||||
expect(f.paused()).toBe(true)
|
||||
if (action === "cancel") res.cancel()
|
||||
else f.req.emit("error", new Error("synthetic failure"))
|
||||
await expect(res.body().next()).rejects.toMatchObject({ status: action === "cancel" ? 499 : 502 })
|
||||
expect(f.destroyed()).toBe(1)
|
||||
expect(f.resumes()).toBe(0)
|
||||
})
|
||||
}
|
||||
|
||||
test("empty data events consume no queue slots", async () => {
|
||||
const f = setup(), pending = post()
|
||||
f.req.emit("response", { ":status": 200 })
|
||||
const res = await pending
|
||||
for (let i = 0; i < 2000; i++) f.req.emit("data", Buffer.alloc(0))
|
||||
f.req.emit("data", Buffer.from("answer"))
|
||||
f.req.emit("end")
|
||||
const chunks = []
|
||||
for await (const d of res.body()) chunks.push(d.toString())
|
||||
expect(chunks).toEqual(["answer"])
|
||||
expect(f.pauses()).toBe(0)
|
||||
})
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1 @@
|
||||
export { WarpAuthPlugin } from "./index.mjs"
|
||||
@@ -0,0 +1,594 @@
|
||||
// The OpenCode 2.x face of a package whose plugins are written for
|
||||
// OpenCode 1.x (and magpie's plugin host).
|
||||
//
|
||||
// OpenCode 2.x loads a package's `exports["."]` and wants its default to be
|
||||
// {id, setup(ctx)}; it has no fallback for a 1.x plugin's named functions
|
||||
// (plugins#657). This file is that default. It runs each 1.x plugin the
|
||||
// package's opencode.mjs exports and hands 2.x what the plugin's hooks say:
|
||||
//
|
||||
// auth.methods → the integration's sign-in methods
|
||||
// config() → the provider, its package, base URL and models
|
||||
// provider.models → the signed-in account's own model list
|
||||
// auth.loader → each request's base URL, key, headers and fetch
|
||||
//
|
||||
// What 2.x has no place for is left out: chat.headers and chat.params
|
||||
// (2.x's sdk hook doesn't carry the session), magpie's usage and checkin,
|
||||
// tools and events.
|
||||
//
|
||||
// scripts/opencode2.mjs is the one copy that is edited. Every package that
|
||||
// has it carries the same bytes as packages/<name>/opencode2.mjs, and
|
||||
// scripts/check.mjs fails when a copy differs.
|
||||
|
||||
import { readFileSync } from "node:fs"
|
||||
import * as v1 from "./opencode.mjs"
|
||||
|
||||
const pkg = JSON.parse(readFileSync(new URL("./package.json", import.meta.url), "utf8"))
|
||||
|
||||
// The key the SDK is made with: the account's own goes on each request in
|
||||
// its place (see wrapFetch), so a key read when the SDK was made can't go
|
||||
// out after the account changed.
|
||||
const PLACEHOLDER = "opencode2-v1-key"
|
||||
|
||||
// The SDK package a 1.x npm name runs as on 2.x. A version keeps 2.x from
|
||||
// swapping @ai-sdk/* for its native providers, which never call the sdk
|
||||
// hook below; openai-compatible's is the one 2.x ships, the others are AI
|
||||
// SDK v6's dist-tag, the line 2.x's bridge runs.
|
||||
export function packageOf(npm) {
|
||||
const name = npm || "@ai-sdk/openai-compatible"
|
||||
if (name === "@ai-sdk/openai-compatible") return "aisdk:@ai-sdk/openai-compatible@2.0.41"
|
||||
if (/^@ai-sdk\/[^/@]+$/.test(name)) return `aisdk:${name}@ai-v6`
|
||||
return `aisdk:${name}`
|
||||
}
|
||||
|
||||
// The plugins a 1.x module exports, as magpie's host and OpenCode 1.x read
|
||||
// them: a default {server} is the one plugin, else every function export
|
||||
// and every {server} object.
|
||||
export function pluginsOf(mod) {
|
||||
const d = mod?.default
|
||||
if (d && typeof d === "object" && ("server" in d || "id" in d || "tui" in d))
|
||||
return typeof d.server === "function" ? [d.server] : []
|
||||
const out = []
|
||||
for (const value of Object.values(mod ?? {})) {
|
||||
const fn = typeof value === "function" ? value : value && typeof value === "object" && typeof value.server === "function" ? value.server : null
|
||||
if (fn && !out.includes(fn)) out.push(fn)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
const int = (n, fallback = 0) => {
|
||||
const v = Math.trunc(Number(n))
|
||||
return Number.isFinite(v) && v >= 0 ? v : fallback
|
||||
}
|
||||
const money = (n) => (Number.isFinite(Number(n)) && Number(n) >= 0 ? Number(n) : 0)
|
||||
const record = (v) => (v && typeof v === "object" && !Array.isArray(v) ? v : {})
|
||||
const json = (v) => {
|
||||
try {
|
||||
return JSON.parse(JSON.stringify(v ?? null))
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
const strings = (v) => Object.fromEntries(Object.entries(record(v)).filter(([, s]) => typeof s === "string"))
|
||||
const nonEmpty = (o) => (Object.keys(o).length ? o : undefined)
|
||||
|
||||
// connKey names a connection the way 2.x does.
|
||||
const connKey = (c) => (!c ? "" : c.type === "credential" ? `credential:${c.id}` : `env:${c.name}`)
|
||||
|
||||
// ---- sign-in ------------------------------------------------------------
|
||||
|
||||
// fields is a 1.x method's prompts as a 2.x form.
|
||||
export function fieldsOf(prompts) {
|
||||
const out = []
|
||||
for (const p of prompts ?? []) {
|
||||
if (!p?.key) continue
|
||||
const f = { key: String(p.key), type: "string", title: String(p.message ?? p.key) }
|
||||
if (p.placeholder) f.placeholder = String(p.placeholder)
|
||||
if (p.type === "select" && Array.isArray(p.options))
|
||||
f.options = p.options.map((o) => ({ value: String(o.value), label: String(o.label ?? o.value), ...(o.hint ? { description: String(o.hint) } : {}) }))
|
||||
// a prompt shown only when another answer says so can't be required
|
||||
if (!p.condition) f.required = true
|
||||
out.push(f)
|
||||
}
|
||||
return out.length ? out : undefined
|
||||
}
|
||||
|
||||
// v1Saved is what a 1.x sign-in's success is saved as, the way 1.x writes
|
||||
// auth.json: the result without its type and provider.
|
||||
function v1Saved(r) {
|
||||
const { type: _t, provider: _p, ...rest } = r
|
||||
if ("key" in r) return { type: "api", ...rest }
|
||||
return { type: "oauth", ...rest }
|
||||
}
|
||||
|
||||
// credentialOf is a 1.x sign-in's success as a 2.x credential: OAuth for
|
||||
// both kinds, the 1.x auth kept whole in its metadata. No refresh is
|
||||
// registered, so 2.x hands the credential over as it is and the plugin's
|
||||
// own loader renews it, as it does on 1.x.
|
||||
export function credentialOf(methodID, r) {
|
||||
if (!r || r.type !== "success") throw new Error(r?.error || r?.message || "the sign-in failed")
|
||||
const saved = json(v1Saved(r))
|
||||
if (saved.type === "api")
|
||||
return { type: "oauth", methodID, access: String(saved.key ?? ""), refresh: "", expires: 0, metadata: { v1: saved } }
|
||||
return {
|
||||
type: "oauth",
|
||||
methodID,
|
||||
access: String(saved.access ?? ""),
|
||||
refresh: String(saved.refresh ?? ""),
|
||||
expires: int(saved.expires),
|
||||
metadata: { v1: saved },
|
||||
}
|
||||
}
|
||||
|
||||
// authOfValue is the 1.x auth a 2.x credential stands for.
|
||||
export function authOfValue(value) {
|
||||
if (!value) return null
|
||||
if (value.type === "oauth") {
|
||||
const v1 = record(value.metadata).v1
|
||||
if (v1 && typeof v1 === "object") return v1
|
||||
return { type: "oauth", access: value.access, refresh: value.refresh, expires: value.expires }
|
||||
}
|
||||
if (value.type === "key") {
|
||||
const meta = value.metadata && Object.keys(value.metadata).length ? { metadata: value.metadata } : {}
|
||||
return { type: "api", key: value.key, ...meta }
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
const fingerprint = (a) => JSON.stringify([a?.type, a?.access ?? a?.key ?? "", a?.refresh ?? ""])
|
||||
|
||||
// ---- models -------------------------------------------------------------
|
||||
|
||||
const MODALITIES = ["text", "audio", "image", "video", "pdf"]
|
||||
|
||||
// internalOf is a config model as 1.x hands it to provider.models: what
|
||||
// fromModelsDevModel makes of it, with the config's own variants.
|
||||
export function internalOf(providerID, conf, key, m) {
|
||||
const mods = record(m.modalities)
|
||||
const has = (list, k) => Array.isArray(list) && list.includes(k)
|
||||
const cost = record(m.cost)
|
||||
return {
|
||||
...m,
|
||||
id: key,
|
||||
providerID,
|
||||
name: m.name ?? key,
|
||||
api: { id: m.id ?? key, url: m.provider?.api ?? conf.api ?? conf.options?.baseURL ?? "", npm: m.provider?.npm ?? conf.npm ?? "@ai-sdk/openai-compatible" },
|
||||
status: m.status ?? "active",
|
||||
headers: m.headers ?? {},
|
||||
options: m.options ?? {},
|
||||
cost: { input: money(cost.input), output: money(cost.output), cache: { read: money(cost.cache_read), write: money(cost.cache_write) } },
|
||||
limit: { context: int(m.limit?.context), input: m.limit?.input, output: int(m.limit?.output) },
|
||||
capabilities: {
|
||||
temperature: m.temperature ?? false,
|
||||
reasoning: m.reasoning ?? false,
|
||||
attachment: m.attachment ?? false,
|
||||
toolcall: m.tool_call ?? true,
|
||||
input: Object.fromEntries(MODALITIES.map((k) => [k, mods.input ? has(mods.input, k) : k === "text"])),
|
||||
output: Object.fromEntries(MODALITIES.map((k) => [k, mods.output ? has(mods.output, k) : k === "text"])),
|
||||
interleaved: m.interleaved ?? false,
|
||||
},
|
||||
release_date: m.release_date ?? "",
|
||||
variants: record(m.variants),
|
||||
}
|
||||
}
|
||||
|
||||
// modelOf is a 1.x model, in config or internal form, as a 2.x Model.Info.
|
||||
export function modelOf(providerID, provider, key, m) {
|
||||
const caps = record(m.capabilities)
|
||||
const listFrom = (obj, list) => {
|
||||
if (obj && typeof obj === "object") return MODALITIES.filter((k) => obj[k])
|
||||
if (Array.isArray(list)) return list.map(String)
|
||||
return ["text"]
|
||||
}
|
||||
const input = listFrom(caps.input, m.modalities?.input)
|
||||
const output = listFrom(caps.output, m.modalities?.output)
|
||||
const c = record(m.cost)
|
||||
const cache = record(c.cache)
|
||||
const npm = m.api?.npm ?? m.provider?.npm
|
||||
const url = m.api?.url ?? m.provider?.api
|
||||
const settings = { ...record(json(m.options)) }
|
||||
if (url && url !== provider.baseURL) settings.baseURL = url
|
||||
const variants = Object.entries(record(m.variants))
|
||||
.filter(([, v]) => !record(v).disabled)
|
||||
.map(([id, v]) => {
|
||||
const { disabled: _d, ...rest } = record(json(v))
|
||||
return nonEmpty(rest) ? { id, settings: rest } : { id }
|
||||
})
|
||||
const status = ["alpha", "beta", "deprecated", "active"].includes(m.status) ? m.status : "active"
|
||||
const out = {
|
||||
id: key,
|
||||
modelID: String(m.api?.id ?? m.id ?? key),
|
||||
providerID,
|
||||
name: String(m.name ?? key),
|
||||
capabilities: {
|
||||
tools: caps.toolcall ?? m.tool_call ?? true,
|
||||
input: input.length ? input : ["text"],
|
||||
output: output.length ? output : ["text"],
|
||||
...(typeof (caps.temperature ?? m.temperature) === "boolean" ? { temperature: caps.temperature ?? m.temperature } : {}),
|
||||
},
|
||||
variants,
|
||||
time: { released: Date.parse(m.release_date ?? "") || 0 },
|
||||
cost: [{ input: money(c.input), output: money(c.output), cache: { read: money(cache.read ?? c.cache_read), write: money(cache.write ?? c.cache_write) } }],
|
||||
status,
|
||||
enabled: true,
|
||||
limit: { context: int(m.limit?.context, 128000) || 128000, output: int(m.limit?.output, 8192) || 8192 },
|
||||
}
|
||||
if (m.limit?.input) out.limit.input = int(m.limit.input)
|
||||
if (npm && npm !== provider.npm) out.package = packageOf(npm)
|
||||
if (nonEmpty(settings)) out.settings = settings
|
||||
const headers = strings(m.headers)
|
||||
if (nonEmpty(headers)) out.headers = headers
|
||||
return out
|
||||
}
|
||||
|
||||
// ---- requests -----------------------------------------------------------
|
||||
|
||||
const urlOf = (input) => (typeof input === "string" ? input : input instanceof URL ? input.href : input?.url ?? String(input))
|
||||
|
||||
// wrapFetch sends a request the SDK made from the provider's settings the
|
||||
// way 1.x would have sent it with the loader's options: the loader's base
|
||||
// URL in place of the configured one, the account's key in place of the
|
||||
// placeholder, the loader's headers added, through the loader's fetch.
|
||||
export function wrapFetch(next, base, options) {
|
||||
return async (input, init = {}) => {
|
||||
const o = await options()
|
||||
let url = urlOf(input)
|
||||
const from = String(base ?? "").replace(/\/+$/, "")
|
||||
const to = o.baseURL ? String(o.baseURL).replace(/\/+$/, "") : ""
|
||||
if (from && to && from !== to && url.startsWith(from)) url = to + url.slice(from.length)
|
||||
const req = input instanceof Request ? input : null
|
||||
const headers = new Headers(init.headers ?? req?.headers ?? undefined)
|
||||
for (const [k, v] of [...headers.entries()]) {
|
||||
if (!v.includes(PLACEHOLDER)) continue
|
||||
if (o.key) headers.set(k, v.replaceAll(PLACEHOLDER, o.key))
|
||||
else headers.delete(k)
|
||||
}
|
||||
for (const [k, v] of Object.entries(strings(o.headers))) headers.set(k, v)
|
||||
const send = typeof o.fetch === "function" ? o.fetch : next ?? fetch
|
||||
if (req && init.body === undefined) {
|
||||
const body = req.method === "GET" || req.method === "HEAD" ? undefined : await req.text()
|
||||
return send(url, { method: req.method, headers, body, signal: init.signal ?? req.signal })
|
||||
}
|
||||
return send(url, { ...init, headers })
|
||||
}
|
||||
}
|
||||
|
||||
// ---- one plugin ---------------------------------------------------------
|
||||
|
||||
async function setupPlugin(ctx, fn, live) {
|
||||
const directory = ctx?.location?.directory ?? process.cwd()
|
||||
// the active account each provider was last read for, and the renewed
|
||||
// auth a plugin saved for it (2.x has no way for a plugin to write a
|
||||
// credential back, so it is kept in the plugin's storage, under the
|
||||
// credential it renews and the token it was renewed from)
|
||||
const current = new Map()
|
||||
const saved = new Map()
|
||||
const signingIn = new Map()
|
||||
const storeKey = (id, key) => `v1auth/${id}/${key}`
|
||||
|
||||
const client = {
|
||||
auth: {
|
||||
async set(arg) {
|
||||
const id = arg?.path?.id
|
||||
const body = json(arg?.body)
|
||||
const cur = id && current.get(id)
|
||||
// a sign-in's own saves belong to the credential it is about to
|
||||
// make, not the one that was active when it started
|
||||
if (!cur || !body || signingIn.get(id) > 0) return { data: true }
|
||||
const entry = { fp: cur.fp, auth: body }
|
||||
saved.set(storeKey(id, cur.key), entry)
|
||||
await Promise.resolve()
|
||||
.then(() => ctx.storage?.set?.(storeKey(id, cur.key), entry))
|
||||
.catch(() => {})
|
||||
return { data: true }
|
||||
},
|
||||
async get() {
|
||||
return { data: undefined }
|
||||
},
|
||||
},
|
||||
app: { log: async () => ({ data: true }) },
|
||||
}
|
||||
|
||||
const hooks = (await fn({ client, directory, worktree: directory, project: {}, serverUrl: undefined, $: undefined }, {})) ?? {}
|
||||
const cfg = { provider: {} }
|
||||
try {
|
||||
await hooks.config?.(cfg)
|
||||
} catch {}
|
||||
const auth = hooks.auth
|
||||
const authID = auth?.provider ? String(auth.provider) : undefined
|
||||
const providers = record(cfg.provider)
|
||||
|
||||
// getAuth reads the active account: the credential 2.x holds, or what the
|
||||
// plugin last saved renewing it.
|
||||
const getAuth = async (id) => {
|
||||
const connection = await ctx.integration.connection.active(id).catch(() => undefined)
|
||||
if (!connection) {
|
||||
current.delete(id)
|
||||
return undefined
|
||||
}
|
||||
const value = await ctx.integration.connection.resolve(connection).catch(() => undefined)
|
||||
const base = authOfValue(value)
|
||||
if (!base) {
|
||||
current.delete(id)
|
||||
return undefined
|
||||
}
|
||||
const key = connKey(connection)
|
||||
const fp = fingerprint(base)
|
||||
// ours: a credential one of this plugin's own sign-ins made
|
||||
const ours = value?.type === "oauth" && !!record(value.metadata).v1
|
||||
current.set(id, { key, fp, ours })
|
||||
const sk = storeKey(id, key)
|
||||
let entry = saved.get(sk)
|
||||
if (!entry) {
|
||||
entry = await Promise.resolve()
|
||||
.then(() => ctx.storage?.get?.(sk))
|
||||
.catch(() => undefined)
|
||||
if (entry) saved.set(sk, entry)
|
||||
}
|
||||
return entry && entry.fp === fp && entry.auth ? entry.auth : base
|
||||
}
|
||||
|
||||
// the sign-in methods
|
||||
if (authID && Array.isArray(auth.methods) && auth.methods.length) {
|
||||
const label = (c) => {
|
||||
const a = authOfValue(c)
|
||||
const name = a?.name ?? a?.email ?? a?.metadata?.name ?? a?.metadata?.email ?? a?.account
|
||||
return typeof name === "string" && name ? name : undefined
|
||||
}
|
||||
const begin = () => signingIn.set(authID, (signingIn.get(authID) ?? 0) + 1)
|
||||
const end = () => signingIn.set(authID, Math.max(0, (signingIn.get(authID) ?? 1) - 1))
|
||||
const title = record(providers[authID]).name
|
||||
// 2.x runs a transform again on every reload, from nothing
|
||||
await ctx.integration.transform((editor) => {
|
||||
let keyed = false
|
||||
// the integration 2.x makes for an id it doesn't know is named by the
|
||||
// id; the provider's own name reads better in the sign-in list
|
||||
if (typeof title === "string" && title)
|
||||
try {
|
||||
editor.update?.(authID, (i) => {
|
||||
if (i && (!i.name || i.name === authID)) i.name = title
|
||||
})
|
||||
} catch {}
|
||||
auth.methods.forEach((m, i) => {
|
||||
if (!m) return
|
||||
const methodID = `v1-${i}`
|
||||
const form = fieldsOf(m.prompts)
|
||||
if (m.type === "api" && typeof m.authorize !== "function") {
|
||||
if (keyed) return
|
||||
keyed = true
|
||||
editor.method.update({ integrationID: authID, method: { type: "key", label: String(m.label ?? "API key"), ...(form ? { form } : {}) } })
|
||||
return
|
||||
}
|
||||
if (typeof m.authorize !== "function") return
|
||||
editor.method.update({
|
||||
integrationID: authID,
|
||||
method: { id: methodID, type: "oauth", label: String(m.label ?? authID), ...(form ? { form } : {}) },
|
||||
async authorize(answer) {
|
||||
begin()
|
||||
let ended = false
|
||||
const done = () => {
|
||||
if (!ended) end()
|
||||
ended = true
|
||||
}
|
||||
try {
|
||||
const inputs = Object.fromEntries(Object.entries(record(answer)).map(([k, v]) => [k, String(v)]))
|
||||
const r = await m.authorize(inputs)
|
||||
if (m.type === "api") {
|
||||
done()
|
||||
return { url: "", instructions: "", mode: "auto", callback: Promise.resolve().then(() => credentialOf(methodID, r)) }
|
||||
}
|
||||
if (r?.method === "code")
|
||||
return {
|
||||
url: String(r.url ?? ""),
|
||||
instructions: String(r.instructions ?? ""),
|
||||
mode: "code",
|
||||
callback: async (code) => {
|
||||
try {
|
||||
return credentialOf(methodID, await r.callback(code))
|
||||
} finally {
|
||||
done()
|
||||
}
|
||||
},
|
||||
}
|
||||
const callback = Promise.resolve()
|
||||
.then(() => r.callback())
|
||||
.then((res) => credentialOf(methodID, res))
|
||||
.finally(done)
|
||||
callback.catch(() => {})
|
||||
return { url: String(r?.url ?? ""), instructions: String(r?.instructions ?? ""), mode: "auto", callback }
|
||||
} catch (e) {
|
||||
done()
|
||||
throw e
|
||||
}
|
||||
},
|
||||
label,
|
||||
})
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
// the loader's options for the account signed in now, read again when
|
||||
// the account changes
|
||||
let loaded = null
|
||||
const loaderOptions = async (id) => {
|
||||
if (id !== authID || typeof auth?.loader !== "function") {
|
||||
const a = authID === id ? await getAuth(id) : undefined
|
||||
return { key: a?.type === "api" ? a.key : undefined }
|
||||
}
|
||||
const a = await getAuth(id)
|
||||
if (!a) return {}
|
||||
const fp = current.get(id)?.key + "\0" + fingerprint(a)
|
||||
if (loaded?.fp !== fp) {
|
||||
const p = Promise.resolve()
|
||||
.then(() => auth.loader(() => getAuth(id), providerOf(id)))
|
||||
.then((o) => record(o))
|
||||
loaded = { fp, p }
|
||||
p.catch(() => {
|
||||
if (loaded?.fp === fp) loaded = null
|
||||
})
|
||||
}
|
||||
const o = await loaded.p
|
||||
const key = typeof o.apiKey === "string" && o.apiKey ? o.apiKey : a.type === "api" ? a.key : undefined
|
||||
return { baseURL: o.baseURL, key, headers: o.headers, fetch: o.fetch }
|
||||
}
|
||||
|
||||
// the providers, with the list the account's own read last gave each
|
||||
const source = new Map()
|
||||
// providerOf is a provider as 1.x hands it to provider.models and
|
||||
// auth.loader
|
||||
const providerOf = (id) => {
|
||||
const conf = record(providers[id])
|
||||
const models = Object.fromEntries(Object.entries(record(conf.models)).map(([k, m]) => [k, internalOf(id, conf, k, record(m))]))
|
||||
return { id, name: conf.name ?? id, source: "config", env: [], options: record(conf.options), models }
|
||||
}
|
||||
const listed = new Set()
|
||||
for (const [id, conf0] of Object.entries(providers)) {
|
||||
const conf = record(conf0)
|
||||
// a provider entry that only names the sign-in (no package, no models)
|
||||
// is not a provider of models
|
||||
if (!conf.npm && !Object.keys(record(conf.models)).length) continue
|
||||
const options = record(conf.options)
|
||||
const { apiKey: _k, baseURL: _b, fetch: _f, headers: optHeaders, ...rest } = options
|
||||
// with no base URL the config leaves it to the loader: a name that
|
||||
// can't resolve stands in for it, and each request swaps in the
|
||||
// loader's (wrapFetch)
|
||||
const baseURL = options.baseURL ?? conf.api ?? `https://${id.replace(/[^a-z0-9-]/gi, "-")}.opencode2-v1.invalid`
|
||||
const npm = conf.npm ?? "@ai-sdk/openai-compatible"
|
||||
const info = {
|
||||
id,
|
||||
...(id === authID ? { integrationID: id } : {}),
|
||||
name: String(conf.name ?? id),
|
||||
activation: "auto",
|
||||
package: packageOf(npm),
|
||||
settings: { ...record(json(rest)), ...(baseURL ? { baseURL: String(baseURL) } : {}) },
|
||||
}
|
||||
const headers = { ...strings(conf.headers), ...strings(optHeaders) }
|
||||
if (nonEmpty(headers)) info.headers = headers
|
||||
const prov = { baseURL, npm }
|
||||
const fromConfig = () =>
|
||||
Object.entries(record(conf.models)).map(([key, m]) => modelOf(id, prov, key, internalOf(id, conf, key, record(m))))
|
||||
listed.add(id)
|
||||
await ctx.provider.transform((editor) => {
|
||||
const s = source.get(id)
|
||||
editor.add({ info, models: s?.models ?? fromConfig(), sourceConnection: s?.connection })
|
||||
})
|
||||
source.set(id, { conf, prov, models: null, connection: undefined })
|
||||
}
|
||||
|
||||
// each request: the placeholder key, and the fetch that swaps in the
|
||||
// account's. A provider the package doesn't list (one 2.x has built in
|
||||
// that the plugin only signs in to) is left to 2.x unless the plugin's
|
||||
// loader serves it and one of the plugin's own sign-ins is active.
|
||||
const own = authID && !listed.has(authID) && typeof auth?.loader === "function" ? [authID] : []
|
||||
for (const id of new Set([...listed, ...own])) {
|
||||
const base = source.get(id)?.prov.baseURL
|
||||
await ctx.aisdk.hook(
|
||||
"sdk",
|
||||
async (evt) => {
|
||||
const opts = evt.options
|
||||
if (!opts || opts.__opencode2) return
|
||||
if (!listed.has(id)) {
|
||||
await getAuth(id)
|
||||
if (!current.get(id)?.ours) return
|
||||
}
|
||||
opts.__opencode2 = true
|
||||
opts.apiKey = PLACEHOLDER
|
||||
opts.fetch = wrapFetch(opts.fetch, opts.baseURL ?? base, () => loaderOptions(id))
|
||||
},
|
||||
{ providerID: id },
|
||||
)
|
||||
}
|
||||
|
||||
// refresh reads the account's own list after a sign-in or a switch
|
||||
const listID = hooks.provider?.id ? String(hooks.provider.id) : undefined
|
||||
let refreshing = null
|
||||
let again = false
|
||||
// the account the list was last read for: a credential.updated that
|
||||
// leaves it as it was reads nothing again
|
||||
let readFor = null
|
||||
const stateOf = async () => {
|
||||
const c = await ctx.integration.connection.active(authID).catch(() => undefined)
|
||||
const a = c ? await getAuth(authID) : undefined
|
||||
return connKey(c) + "\0" + (a ? fingerprint(a) : "")
|
||||
}
|
||||
const refresh = () => {
|
||||
if (refreshing) {
|
||||
again = true
|
||||
return refreshing
|
||||
}
|
||||
refreshing = (async () => {
|
||||
try {
|
||||
if (!authID || !source.has(authID)) return
|
||||
const s = source.get(authID)
|
||||
const connection = await ctx.integration.connection.active(authID).catch(() => undefined)
|
||||
const a = connection ? await getAuth(authID) : undefined
|
||||
readFor = connKey(connection) + "\0" + (a ? fingerprint(a) : "")
|
||||
if (!a || listID !== authID || typeof hooks.provider?.models !== "function") {
|
||||
if (s.connection || s.models) {
|
||||
s.connection = undefined
|
||||
s.models = null
|
||||
await ctx.provider.reload()
|
||||
}
|
||||
return
|
||||
}
|
||||
const provider = providerOf(authID)
|
||||
let got
|
||||
try {
|
||||
got = await hooks.provider.models(provider, { auth: a })
|
||||
} catch {
|
||||
got = null
|
||||
}
|
||||
if (connKey(await ctx.integration.connection.active(authID).catch(() => undefined)) !== connKey(connection)) {
|
||||
again = true
|
||||
return
|
||||
}
|
||||
s.connection = connection
|
||||
s.models = got && typeof got === "object" ? Object.entries(got).map(([k, m]) => modelOf(authID, s.prov, k, record(m))) : null
|
||||
await ctx.provider.reload()
|
||||
await ctx.model?.reload?.()
|
||||
} finally {
|
||||
refreshing = null
|
||||
if (again && live.on) {
|
||||
again = false
|
||||
void refresh()
|
||||
}
|
||||
}
|
||||
})()
|
||||
return refreshing
|
||||
}
|
||||
|
||||
if (authID && ctx.event?.subscribe)
|
||||
void (async () => {
|
||||
try {
|
||||
// a switch names the integration; an update (a sign-in, a removal)
|
||||
// names nothing, so it reads again only when this account changed
|
||||
const types = ["credential.switched", "credential.updated"]
|
||||
for await (const event of ctx.event.subscribe({ types })) {
|
||||
if (!live.on) return
|
||||
if (event?.type === "credential.switched" && event?.data?.integrationID === authID) {
|
||||
loaded = null
|
||||
await refresh()
|
||||
} else if (event?.type === "credential.updated" && (await stateOf()) !== readFor) {
|
||||
await refresh()
|
||||
}
|
||||
}
|
||||
} catch {}
|
||||
})()
|
||||
void refresh()
|
||||
}
|
||||
|
||||
export async function setup(ctx, mod = v1) {
|
||||
const live = { on: true }
|
||||
for (const fn of pluginsOf(mod)) {
|
||||
try {
|
||||
await setupPlugin(ctx, fn, live)
|
||||
} catch (e) {
|
||||
// one plugin failing to start leaves the package's others working
|
||||
console.error(`${pkg.name}: ${e?.message ?? e}`)
|
||||
}
|
||||
}
|
||||
return () => {
|
||||
live.on = false
|
||||
}
|
||||
}
|
||||
|
||||
export default { id: pkg.name, setup: (ctx) => setup(ctx) }
|
||||
@@ -0,0 +1,25 @@
|
||||
{
|
||||
"name": "@magpie-community/opencode-warp-auth",
|
||||
"version": "0.1.0",
|
||||
"description": "OpenCode provider plugin: Warp (the terminal) AI credits through the Warp app's sign-in",
|
||||
"type": "module",
|
||||
"main": "./opencode.mjs",
|
||||
"exports": { ".": "./opencode2.mjs" },
|
||||
"files": [
|
||||
"index.mjs",
|
||||
"opencode.mjs",
|
||||
"opencode2.mjs",
|
||||
"README.md"
|
||||
],
|
||||
"keywords": [
|
||||
"opencode",
|
||||
"opencode-plugin",
|
||||
"warp"
|
||||
],
|
||||
"license": "MIT",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/magpie-community/plugins.git",
|
||||
"directory": "packages/warp"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
import { expect, test } from "bun:test"
|
||||
import { createCipheriv } from "node:crypto"
|
||||
import { join } from "node:path"
|
||||
import { _internal } from "./index.mjs"
|
||||
|
||||
const user = { email: "test@example.invalid", local_id: "test", id_token: { id_token: "fake", refresh_token: "fake-refresh" } }
|
||||
const json = Buffer.from(JSON.stringify(user))
|
||||
const absent = () => { throw Object.assign(new Error("missing"), { code: "ENOENT" }) }
|
||||
const encrypt = (plain) => {
|
||||
const iv = Buffer.alloc(12, 7)
|
||||
const cipher = createCipheriv("aes-256-gcm", Buffer.from("https://releases.warp.dev/channel_versions.json").subarray(0, 32), iv)
|
||||
return Buffer.concat([iv, cipher.update(plain), cipher.final(), cipher.getAuthTag()])
|
||||
}
|
||||
|
||||
test("platform context follows the host and its shell", () => {
|
||||
expect(_internal.platformInfo("darwin", {})).toEqual({ category: "macOS", shell: "zsh" })
|
||||
expect(_internal.platformInfo("linux", { SHELL: "/usr/bin/fish" })).toEqual({ category: "Linux", shell: "fish" })
|
||||
expect(_internal.platformInfo("win32", {})).toEqual({ category: "Windows", shell: "powershell" })
|
||||
})
|
||||
|
||||
test("macOS reads the stable GUI Keychain service and User account", async () => {
|
||||
const readUser = _internal.createUserReader({ platform: "darwin", home: "/empty", read: () => { throw new Error("must not read a file") }, run: async (cmd, args) => {
|
||||
expect(cmd).toBe("/usr/bin/security")
|
||||
expect(args).toEqual(["find-generic-password", "-s", "dev.warp.Warp-Stable", "-a", "User", "-w"])
|
||||
return { code: 0, stdout: json }
|
||||
} })
|
||||
expect(await readUser()).toEqual(user)
|
||||
})
|
||||
|
||||
test("macOS decodes hex-encoded keychain output for non-ASCII accounts", async () => {
|
||||
const named = { ...user, display_name: "程国清" }
|
||||
const hex = Buffer.from(JSON.stringify(named)).toString("hex") + "\n"
|
||||
const readUser = _internal.createUserReader({ platform: "darwin", run: async () => ({ code: 0, stdout: Buffer.from(hex) }) })
|
||||
expect(await readUser()).toEqual(named)
|
||||
})
|
||||
|
||||
test("macOS hex detection leaves plain JSON and non-hex output untouched", async () => {
|
||||
const plain = _internal.createUserReader({ platform: "darwin", run: async () => ({ code: 0, stdout: json }) })
|
||||
expect(await plain()).toEqual(user)
|
||||
const odd = _internal.createUserReader({ platform: "darwin", run: async () => ({ code: 0, stdout: Buffer.from("7b2\n") }) })
|
||||
await expect(odd()).rejects.toThrow(/did not read as an account/)
|
||||
const garbage = _internal.createUserReader({ platform: "darwin", run: async () => ({ code: 0, stdout: Buffer.from("not-an-account") }) })
|
||||
await expect(garbage()).rejects.toThrow(/did not read as an account/)
|
||||
})
|
||||
|
||||
test("macOS reports missing and inaccessible keychains without exposing output", async () => {
|
||||
const missing = _internal.createUserReader({ platform: "darwin", run: async () => ({ code: 44, stdout: Buffer.alloc(0) }) })
|
||||
expect(await missing()).toBeNull()
|
||||
const locked = _internal.createUserReader({ platform: "darwin", run: async () => ({ code: 1, stdout: Buffer.from("do-not-expose-token") }) })
|
||||
await expect(locked()).rejects.toThrow(/unlock the keychain/)
|
||||
})
|
||||
|
||||
test("Linux reads Secret Service using Warp's exact attributes", async () => {
|
||||
const readUser = _internal.createUserReader({ platform: "linux", read: () => { throw new Error("no file expected") }, run: async (cmd, args) => {
|
||||
expect(cmd).toBe("secret-tool")
|
||||
expect(args).toEqual(["lookup", "service", "dev.warp.Warp", "key", "User"])
|
||||
return { code: 0, stdout: json }
|
||||
} })
|
||||
expect(await readUser()).toEqual(user)
|
||||
})
|
||||
|
||||
test("Linux decrypts Warp's disk fallback under XDG_STATE_HOME", async () => {
|
||||
const readUser = _internal.createUserReader({ platform: "linux", home: "/unused", env: { XDG_STATE_HOME: "/sandbox/state" }, run: async () => { throw new Error("secret-tool not installed") }, read: (path) => {
|
||||
expect(path).toBe(join("/sandbox/state", "warp-terminal", "dev.warp.Warp-User"))
|
||||
return encrypt(json)
|
||||
} })
|
||||
expect(await readUser()).toEqual(user)
|
||||
})
|
||||
|
||||
test("Linux default state directory and missing login are handled", async () => {
|
||||
const readUser = _internal.createUserReader({ platform: "linux", home: "/sandbox/home", env: {}, run: async () => ({ code: 1, stdout: Buffer.alloc(0) }), read: (path) => {
|
||||
expect(path).toBe(join("/sandbox/home", ".local", "state", "warp-terminal", "dev.warp.Warp-User"))
|
||||
return absent()
|
||||
} })
|
||||
expect(await readUser()).toBeNull()
|
||||
})
|
||||
|
||||
test("Linux fallback authenticates the ciphertext and rejects truncation", () => {
|
||||
const blob = encrypt(json)
|
||||
blob[15] ^= 1
|
||||
expect(() => _internal.linuxUser(blob)).toThrow()
|
||||
expect(() => _internal.linuxUser(Buffer.alloc(10))).toThrow(/truncated/)
|
||||
})
|
||||
|
||||
test("Windows honors LOCALAPPDATA and passes encrypted bytes on stdin", async () => {
|
||||
let decrypts = 0, blob = Buffer.from("encrypted-v1")
|
||||
const readUser = _internal.createUserReader({ platform: "win32", home: "/wrong", env: { LOCALAPPDATA: "/redirected/it's-local" }, read: (path) => {
|
||||
expect(path).toBe(join("/redirected/it's-local", "warp", "Warp", "data", "dev.warp.Warp-User"))
|
||||
return blob
|
||||
}, run: async (cmd, args, script) => {
|
||||
decrypts++
|
||||
expect(cmd).toBe("C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe")
|
||||
expect(args.slice(-2)).toEqual(["-Command", "-"])
|
||||
expect(script).toContain(blob.toString("base64"))
|
||||
expect(script).not.toContain("it's-local")
|
||||
expect(script).toContain("OpenStandardOutput().Write")
|
||||
return { code: 0, stdout: json }
|
||||
} })
|
||||
expect(await readUser()).toEqual(user)
|
||||
expect(await readUser()).toEqual(user)
|
||||
expect(decrypts).toBe(1)
|
||||
blob = Buffer.from("encrypted-v2")
|
||||
await readUser()
|
||||
expect(decrypts).toBe(2)
|
||||
await readUser(true)
|
||||
expect(decrypts).toBe(3)
|
||||
})
|
||||
|
||||
test("client version follows Warp's environment, with a validated explicit override", () => {
|
||||
const native = "v0.2026.10.09.08.27.stable_01", override = "v0.2026.10.10.08.27.stable_01"
|
||||
expect(_internal.clientVersion({ WARP_CLIENT_VERSION: native })).toBe(native)
|
||||
expect(_internal.clientVersion({ WARP_CLIENT_VERSION: native, MAGPIE_WARP_CLIENT_VERSION: override })).toBe(override)
|
||||
expect(_internal.clientVersion({ WARP_CLIENT_VERSION: native + "\r\ninjected: value" })).toBe(_internal.clientVersion({}))
|
||||
})
|
||||
|
||||
test("Windows absent file never spawns PowerShell", async () => {
|
||||
const readUser = _internal.createUserReader({ platform: "win32", home: "/empty", env: {}, read: absent, run: async () => { throw new Error("must not spawn") } })
|
||||
expect(await readUser()).toBeNull()
|
||||
})
|
||||
@@ -0,0 +1,40 @@
|
||||
import { expect, test } from "bun:test"
|
||||
import { _internal as p } from "./index.mjs"
|
||||
|
||||
test("Value oneofs retain false, empty strings and null presence", () => {
|
||||
expect([...p.valueMsg(null).out()]).toEqual([8, 0])
|
||||
expect([...p.valueMsg(false).out()]).toEqual([32, 0])
|
||||
expect([...p.valueMsg("").out()]).toEqual([26, 0])
|
||||
const object = { default: false, enum: ["", null, true], nested: { number: 1.25, negative: -3.5 } }
|
||||
expect(p.structOf(p.structPB(object).out())).toEqual(object)
|
||||
})
|
||||
|
||||
test("doubles use protobuf's little endian wire representation", () => {
|
||||
expect([...p.valueMsg(1.25).out()]).toEqual([17, 0, 0, 0, 0, 0, 0, 244, 63])
|
||||
})
|
||||
|
||||
test("unsigned varints work beyond uint32 and decode the full uint64 range", () => {
|
||||
for (const n of [2 ** 32, 2 ** 40, Number.MAX_SAFE_INTEGER]) expect(p.fields(new p.PB().v(1, n).out())[0].v).toBe(n)
|
||||
expect(p.fields(Uint8Array.from([8, ...Array(9).fill(255), 1]))[0].v).toBe(2n ** 64n - 1n)
|
||||
expect(() => new p.PB().uv(-1)).toThrow()
|
||||
expect(() => new p.PB().uv(Infinity)).toThrow()
|
||||
})
|
||||
|
||||
for (const [name, bytes] of [
|
||||
["unterminated varint", [8, 128]], ["oversized uint64", [8, ...Array(10).fill(255)]],
|
||||
["truncated bytes", [10, 100, 65]], ["truncated double", [17, 0]],
|
||||
["truncated float", [13, 0]], ["zero field number", [0]], ["invalid wire type", [15]],
|
||||
]) test(`rejects ${name}`, () => expect(() => p.fields(Uint8Array.from(bytes))).toThrow())
|
||||
|
||||
test("ordinary strings remain strings, including proto-looking content", () => {
|
||||
const object = { text: "\u000fprotobuf wire type 7 [assistant]" }
|
||||
expect(p.structOf(p.structPB(object).out())).toEqual(object)
|
||||
})
|
||||
|
||||
test("a __proto__ map key remains data rather than changing the object prototype", () => {
|
||||
const object = JSON.parse('{"__proto__":{"polluted":true}}')
|
||||
const out = p.structOf(p.structPB(object).out())
|
||||
expect(Object.hasOwn(out, "__proto__")).toBe(true)
|
||||
expect(Object.getPrototypeOf(out)).toBe(Object.prototype)
|
||||
expect(out.polluted).toBeUndefined()
|
||||
})
|
||||
@@ -0,0 +1,133 @@
|
||||
// What a chat completion becomes on the wire, and what Warp's events fold
|
||||
// into: the request carries the transcript and the tools as one MCP
|
||||
// server's, and the answer's appends, tool calls and the end all map.
|
||||
import { expect, test } from "bun:test"
|
||||
import { _internal } from "./index.mjs"
|
||||
|
||||
const { PB, buildRequest, turnEvents, byNum, str, structOf, fields } = _internal
|
||||
|
||||
const chat = (over = {}) => ({
|
||||
model: "auto",
|
||||
messages: [
|
||||
{ role: "system", content: "be brief" },
|
||||
{ role: "user", content: "list the files" },
|
||||
{ role: "assistant", content: "", tool_calls: [{ id: "t1", type: "function", function: { name: "run", arguments: "{\"cmd\":\"ls\"}" } }] },
|
||||
{ role: "tool", tool_call_id: "t1", content: "a.txt\nb.txt" },
|
||||
],
|
||||
tools: [
|
||||
{
|
||||
type: "function",
|
||||
function: {
|
||||
name: "run",
|
||||
description: "run a command",
|
||||
parameters: { type: "object", properties: { cmd: { type: "string" } }, required: ["cmd"] },
|
||||
},
|
||||
},
|
||||
],
|
||||
...over,
|
||||
})
|
||||
|
||||
test("the request carries the transcript, the tools and the settings", () => {
|
||||
const { body } = buildRequest(chat())
|
||||
const nums = [...byNum(body, 2), ...byNum(body, 3), ...byNum(body, 6)].map(() => 0) // parse to catch framing
|
||||
expect(byNum(body, 1).length).toBe(0) // no conversation continuation
|
||||
expect(byNum(body, 4).length).toBe(0) // no metadata: a fresh conversation
|
||||
|
||||
const settings = byNum(body, 3)[0].data
|
||||
const modelConfig = byNum(settings, 1)[0].data
|
||||
expect(str(byNum(modelConfig, 1)[0])).toBe("auto") // model_config.base
|
||||
expect(byNum(settings, 9).map((f) => f.v)).toEqual([9]) // supported_tools: CALL_MCP_TOOL only
|
||||
|
||||
const ctx = byNum(body, 6)[0].data
|
||||
const server = byNum(ctx, 3)[0].data
|
||||
expect(str(byNum(server, 1)[0])).toBe("magpie")
|
||||
const tool = byNum(server, 4)[0].data
|
||||
expect(str(byNum(tool, 1)[0])).toBe("run")
|
||||
const schema = structOf(byNum(tool, 3)[0].data)
|
||||
expect(schema.type).toBe("object")
|
||||
expect(schema.properties.cmd.type).toBe("string")
|
||||
expect(schema.required).toEqual(["cmd"])
|
||||
|
||||
const input = byNum(body, 2)[0].data
|
||||
const userInput = byNum(byNum(input, 6)[0].data, 1)[0].data
|
||||
const userQuery = byNum(userInput, 1)[0].data
|
||||
const query = str(byNum(userQuery, 1)[0])
|
||||
expect(query).toContain("The following is the transcript")
|
||||
expect(query).toContain(JSON.stringify({ role: "system", content: "be brief" }))
|
||||
expect(query).toContain('"tool_call_id":"t1"')
|
||||
expect(query).toContain('"content":"a.txt\\nb.txt"')
|
||||
expect(query).toContain("taking the tool results into account")
|
||||
})
|
||||
|
||||
test("a data-URL image in the last user message rides as context", () => {
|
||||
const { body } = buildRequest({
|
||||
model: "auto",
|
||||
messages: [
|
||||
{ role: "user", content: [{ type: "text", text: "what is this" }, { type: "image_url", image_url: { url: "data:image/png;base64,aGk=" } }] },
|
||||
],
|
||||
})
|
||||
const input = byNum(body, 2)[0].data
|
||||
const context = byNum(input, 1)[0].data
|
||||
const images = byNum(context, 7)
|
||||
expect(images).toHaveLength(1)
|
||||
const img = fields(images[0].data)
|
||||
expect(str(img.find((f) => f.num === 1))).toBe("aGk=") // the base64 text, as Warp's client sends it
|
||||
expect(str(img.find((f) => f.num === 2))).toBe("image/png")
|
||||
})
|
||||
|
||||
test("a lone user message rides as itself, not as a transcript", () => {
|
||||
const { body } = buildRequest({ model: "auto", messages: [{ role: "user", content: "hi" }] })
|
||||
const input = byNum(body, 2)[0].data
|
||||
const userInput = byNum(byNum(input, 6)[0].data, 1)[0].data
|
||||
const query = str(byNum(byNum(userInput, 1)[0].data, 1)[0])
|
||||
expect(query).toBe("hi")
|
||||
})
|
||||
|
||||
// ---- the answer, as events ------------------------------------------------------
|
||||
|
||||
// event builds one SSE ResponseEvent: init(1), client_actions(2) or finished(3)
|
||||
const event = (num, inner) => Buffer.from(new PB().b_(num, inner.b).b).toString("base64url")
|
||||
const message = (id, oneofNum, inner) => new PB().s(1, id).m(oneofNum, inner)
|
||||
const addToTask = (...msgs) => {
|
||||
const add = new PB().s(1, "task")
|
||||
for (const m of msgs) add.m(2, m)
|
||||
return event(2, new PB().m(1, new PB().m(3, add)))
|
||||
}
|
||||
const appendTo = (msg, mask) =>
|
||||
event(2, new PB().m(1, new PB().m(5, new PB().m(1, msg).m(2, new PB().s(1, mask)).s(3, "task"))))
|
||||
|
||||
const collect = async (lines) => {
|
||||
const text = lines.map((d) => `event:data\ndata:${d}\n\n`).join("")
|
||||
const body = (async function* () { yield text })()
|
||||
const out = []
|
||||
for await (const e of turnEvents(body)) out.push(e)
|
||||
return out
|
||||
}
|
||||
|
||||
test("text streams by append, a tool call arrives whole, the end carries usage", async () => {
|
||||
const textMsg = (t) => message("m1", 3, new PB().s(1, t))
|
||||
const reasoningMsg = (t) => message("m2", 15, new PB().s(1, t))
|
||||
const toolMsg = message("m3", 4, new PB().s(1, "c1").m(12, new PB().s(1, "get_weather").m(2, new PB().m(1, new PB().s(1, "city").m(2, new PB().s(3, "Paris"))))))
|
||||
const out = await collect([
|
||||
event(1, new PB().s(1, "conv-1")),
|
||||
addToTask(textMsg("he"), reasoningMsg("think")),
|
||||
appendTo(textMsg("llo"), "agent_output.text"),
|
||||
addToTask(toolMsg),
|
||||
event(3, new PB().m(2, new PB()).m(11, new PB().v(10, 71).m(4, new PB().s(1, "a model").v(2, 20)).m(6, new PB().s(1, "another").m(2, new PB().v(2, 9).m(3, new PB().m(1, new PB().s(1, "cat").v(2, 9))))))),
|
||||
])
|
||||
expect(out.filter((e) => e.text).map((e) => e.text).join("")).toBe("hello")
|
||||
expect(out.filter((e) => e.reasoning).map((e) => e.reasoning).join("")).toBe("think")
|
||||
const tool = out.find((e) => e.tool)?.tool
|
||||
expect(tool).toMatchObject({ id: "c1", name: "get_weather", args: { city: "Paris" } })
|
||||
const end = out.at(-1).end
|
||||
expect(end.reason).toBe("done")
|
||||
expect(end.tools).toEqual([tool])
|
||||
expect(end.usage).toMatchObject({ input: 71 }) // latest input, not overlapping cumulative totals
|
||||
})
|
||||
|
||||
test("a quota end is named, and so is an internal error", async () => {
|
||||
const quota = await collect([event(3, new PB().m(4, new PB()))])
|
||||
expect(quota.at(-1).end.reason).toBe("quota")
|
||||
const err = await collect([event(3, new PB().m(7, new PB().s(1, "boom")))])
|
||||
expect(err.at(-1).end).toMatchObject({ reason: "internal", message: "boom" })
|
||||
})
|
||||
@@ -0,0 +1,71 @@
|
||||
// The two ways in, with the app reader and Google's token endpoint mocked.
|
||||
import { afterEach, expect, test } from "bun:test"
|
||||
import { _internal } from "./index.mjs"
|
||||
|
||||
const real = globalThis.fetch
|
||||
afterEach(() => (globalThis.fetch = real))
|
||||
|
||||
const client = { auth: { set: async () => {} } }
|
||||
const plugin = await _internal.createPlugin({ client }, { readUser: async () => null })
|
||||
|
||||
const b64 = (o) => Buffer.from(JSON.stringify(o)).toString("base64url")
|
||||
const fakeJwt = (claims) => `${b64({ alg: "RS256" })}.${b64(claims)}.sig`
|
||||
|
||||
test("the app's sign-in needs a stored Warp account", async () => {
|
||||
const method = plugin.auth.methods.find((m) => m.label.includes("Warp app"))
|
||||
await expect(method.authorize()).rejects.toThrow(/isn't signed in/)
|
||||
})
|
||||
|
||||
test("a refresh token is exchanged for an account", async () => {
|
||||
globalThis.fetch = async (url, init) => {
|
||||
expect(String(url)).toContain("securetoken.googleapis.com/v1/token")
|
||||
expect(String(init.body)).toContain("grant_type=refresh_token")
|
||||
expect(new URLSearchParams(init.body).get("refresh_token")).toBe("the-refresh-token")
|
||||
return Response.json({
|
||||
id_token: fakeJwt({ email: "w@warp.dev", exp: Math.floor(Date.now() / 1000) + 3600 }),
|
||||
refresh_token: "rotated",
|
||||
expires_in: "3600",
|
||||
})
|
||||
}
|
||||
const method = plugin.auth.methods[1]
|
||||
expect(method.type).toBe("oauth")
|
||||
const authorization = await method.authorize({ key: "the-refresh-token" })
|
||||
expect(authorization).toMatchObject({ method: "auto", url: "" })
|
||||
const saved = await authorization.callback()
|
||||
expect(saved.type).toBe("success")
|
||||
expect(saved.accountId).toBe("w@warp.dev")
|
||||
expect(saved.refresh).toBe("rotated")
|
||||
expect(saved.expires).toBeGreaterThan(Date.now() + 59 * 60_000)
|
||||
})
|
||||
|
||||
test("manual sign-in accepts its prompt's inputs and rejects absent values without a request", async () => {
|
||||
const method = plugin.auth.methods[1]
|
||||
let calls = 0
|
||||
globalThis.fetch = async (_url, init) => {
|
||||
calls++
|
||||
expect(new URLSearchParams(init.body).get("refresh_token")).toBe("prompt-token")
|
||||
return Response.json({ id_token: fakeJwt({ email: "w@test.invalid" }) })
|
||||
}
|
||||
const key = method.prompts[0].key
|
||||
const authorization = await method.authorize({ [key]: " prompt-token " })
|
||||
expect(calls).toBe(0)
|
||||
expect(method.prompts).toHaveLength(1)
|
||||
expect((await authorization.callback()).refresh).toBe("prompt-token")
|
||||
for (const inputs of [undefined, {}, { key: {} }, { refresh_token: " " }]) {
|
||||
await expect(method.authorize(inputs)).rejects.toThrow(/required/)
|
||||
}
|
||||
expect(calls).toBe(1)
|
||||
})
|
||||
|
||||
test("the refresh hook rotates what Google gives", async () => {
|
||||
globalThis.fetch = async () =>
|
||||
Response.json({ id_token: fakeJwt({ exp: Math.floor(Date.now() / 1000) + 3600 }), refresh_token: "next", expires_in: "3600" })
|
||||
const out = await plugin.auth.refresh({ type: "oauth", access: "", refresh: "old" })
|
||||
expect(out.refresh).toBe("next")
|
||||
expect(out.access).toContain(".")
|
||||
})
|
||||
|
||||
test("Google refusing the token says to sign in again", async () => {
|
||||
globalThis.fetch = async () => Response.json({ error: { message: "INVALID_REFRESH_TOKEN" } }, { status: 400 })
|
||||
await expect(plugin.auth.refresh({ type: "oauth", access: "", refresh: "dead" })).rejects.toThrow(/INVALID_REFRESH_TOKEN/)
|
||||
})
|
||||
@@ -0,0 +1,88 @@
|
||||
import { afterEach, expect, test } from "bun:test"
|
||||
import { _internal as w } from "./index.mjs"
|
||||
|
||||
const real = globalThis.fetch
|
||||
afterEach(() => (globalThis.fetch = real))
|
||||
const jwt = (claims) => `e30.${Buffer.from(JSON.stringify(claims)).toString("base64url")}.sig`
|
||||
const custom = jwt({ uid: "anonymous-user", aud: "https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit" })
|
||||
|
||||
for (const failure of ["network", "timeout", "503", "429", "malformed"]) {
|
||||
test(`refresh retries via Warp's proxy after ${failure}, preserving the form`, async () => {
|
||||
const calls = []
|
||||
globalThis.fetch = async (url, init) => {
|
||||
calls.push([String(url), init.body])
|
||||
expect(init.redirect).toBe("error")
|
||||
if (calls.length === 1) {
|
||||
if (failure === "network") throw new TypeError("network failure")
|
||||
if (failure === "timeout") throw new DOMException("timeout", "TimeoutError")
|
||||
if (failure === "malformed") return new Response("bad gateway", { status: 502 })
|
||||
return Response.json({ error: { message: "temporary" } }, { status: Number(failure) })
|
||||
}
|
||||
return Response.json({ id_token: "new-id", refresh_token: "rotated", expires_in: "3600" })
|
||||
}
|
||||
expect((await w.exchange("original-refresh")).refresh).toBe("rotated")
|
||||
expect(calls.length).toBe(2)
|
||||
expect(new URL(calls[0][0]).hostname).toBe("securetoken.googleapis.com")
|
||||
expect(new URL(calls[1][0]).pathname).toBe("/proxy/token")
|
||||
expect(new URL(calls[1][0]).hostname).toBe("app.warp.dev")
|
||||
expect(calls[1][1]).toBe(calls[0][1])
|
||||
expect(new URLSearchParams(calls[1][1]).get("refresh_token")).toBe("original-refresh")
|
||||
})
|
||||
}
|
||||
|
||||
test("definitive refresh rejection is not retried and never echoes the secret", async () => {
|
||||
let calls = 0
|
||||
globalThis.fetch = async () => {
|
||||
calls++
|
||||
return Response.json({ error: { message: "INVALID_REFRESH_TOKEN: secret-refresh" } }, { status: 400 })
|
||||
}
|
||||
try { await w.exchange("secret-refresh"); throw new Error("expected rejection") }
|
||||
catch (error) {
|
||||
expect(error.signIn).toBe("expired")
|
||||
expect(error.message).not.toContain("secret-refresh")
|
||||
}
|
||||
expect(calls).toBe(1)
|
||||
})
|
||||
|
||||
test("both token services being unreachable does not expire a sign-in", async () => {
|
||||
let calls = 0
|
||||
globalThis.fetch = async () => { calls++; throw new Error("synthetic network failure") }
|
||||
const error = await w.exchange("refresh").catch((error) => error)
|
||||
expect(error.status).toBe(503)
|
||||
expect(error.signIn).toBeUndefined()
|
||||
expect(calls).toBe(2)
|
||||
})
|
||||
|
||||
test("anonymous app custom tokens are recognized and exchanged for renewable credentials", async () => {
|
||||
const access = jwt({ sub: "anonymous-user", exp: Math.floor(Date.now() / 1000) + 3600, firebase: { sign_in_provider: "anonymous" } })
|
||||
const calls = []
|
||||
globalThis.fetch = async (url, init) => {
|
||||
calls.push(String(url))
|
||||
const form = new URLSearchParams(init.body)
|
||||
if (calls.length === 1) {
|
||||
expect(new URL(url).pathname).toBe("/proxy/customToken")
|
||||
expect(form.get("token")).toBe(custom)
|
||||
expect(form.get("returnSecureToken")).toBe("true")
|
||||
expect(form.has("refresh_token")).toBe(false)
|
||||
return Response.json({ idToken: access, refreshToken: "renewable", expiresIn: "3600" })
|
||||
}
|
||||
expect(new URL(url).hostname).toBe("securetoken.googleapis.com")
|
||||
expect(form.get("refresh_token")).toBe("renewable")
|
||||
return Response.json({ id_token: access, refresh_token: "renewed", expires_in: "3600" })
|
||||
}
|
||||
const p = await w.createPlugin({ client: { auth: { set: async () => {} } } }, { readUser: async () => ({
|
||||
email: "", local_id: "anonymous-user", anonymous_user_type: "NativeClientAnonymousUser", linked_at: null,
|
||||
id_token: { id_token: "expired", refresh_token: custom, expiration_time: "2000-01-01T00:00:00Z" },
|
||||
}) })
|
||||
const login = await p.auth.methods[0].authorize()
|
||||
expect(login.instructions).toContain("anonymous")
|
||||
const saved = await login.callback()
|
||||
expect(saved).toMatchObject({ accountId: "anonymous-user", refresh: "renewable", metadata: { anonymous: true, uid: "anonymous-user" } })
|
||||
expect((await p.auth.refresh(saved)).refresh).toBe("renewed")
|
||||
expect(calls.length).toBe(2)
|
||||
})
|
||||
|
||||
test("custom-token rejection is an explicit login failure rather than a refresh request", async () => {
|
||||
globalThis.fetch = async () => Response.json({ error: { message: "INVALID_CUSTOM_TOKEN" } }, { status: 400 })
|
||||
await expect(w.exchange(custom)).rejects.toMatchObject({ status: 401, signIn: "expired" })
|
||||
})
|
||||
@@ -0,0 +1,56 @@
|
||||
// Match the host's usage-window contract, with a fake GraphQL account only.
|
||||
import { afterEach, expect, test } from "bun:test"
|
||||
import { _internal as w } from "./index.mjs"
|
||||
|
||||
const real = globalThis.fetch
|
||||
afterEach(() => (globalThis.fetch = real))
|
||||
const usage = async (user) => {
|
||||
globalThis.fetch = async (_url, init) => {
|
||||
expect(JSON.parse(init.body).operationName).toBe("GetRequestLimitInfo")
|
||||
return Response.json({ data: { user: { user } } })
|
||||
}
|
||||
const p = await w.createPlugin({ client: { auth: { set: async () => {} } } }, { readUser: async () => { throw new Error("unexpected credential read") } })
|
||||
return p.auth.usage(async () => ({ type: "oauth", access: "fake", refresh: "fake", expires: Date.now() + 3600_000 }))
|
||||
}
|
||||
|
||||
test("an exhausted request allowance is a limiting window with visible counts", async () => {
|
||||
const result = await usage({ requestLimitInfo: { isUnlimited: false, requestsUsedSinceLastRefresh: 150, requestLimit: 150 } })
|
||||
const window = result.windows[0]
|
||||
expect(window.used).toBe(100)
|
||||
expect(window.aside).toBeUndefined()
|
||||
expect(window.display).toBe("150/150 requests")
|
||||
expect(result.signIn).toBe("kept")
|
||||
})
|
||||
|
||||
test("bonus usage is computed from active grants, including fully spent grants", async () => {
|
||||
const result = await usage({ bonusGrants: [
|
||||
{ requestCreditsGranted: 20, requestCreditsRemaining: 5 },
|
||||
{ requestCreditsGranted: 10, requestCreditsRemaining: 10 },
|
||||
{ requestCreditsGranted: 100, requestCreditsRemaining: 100, expiration: "2000-01-01T00:00:00Z" },
|
||||
] })
|
||||
expect(result.windows).toEqual([{ name: "Bonus credits", used: 50, display: "15/30 credits left", aside: true }])
|
||||
const spent = await usage({ bonusGrants: [{ requestCreditsGranted: 20, requestCreditsRemaining: 0 }] })
|
||||
expect(spent.windows[0]).toMatchObject({ used: 100, display: "0/20 credits left", aside: true })
|
||||
})
|
||||
|
||||
test("unlimited accounts and an empty bonus do not acquire a false allowance cap", async () => {
|
||||
expect((await usage({ requestLimitInfo: { isUnlimited: true }, bonusGrants: [] })).windows).toEqual([{ name: "Requests", used: 0 }])
|
||||
})
|
||||
|
||||
test("client version overrides reach both request headers and GraphQL context", async () => {
|
||||
const old = process.env.MAGPIE_WARP_CLIENT_VERSION
|
||||
const version = "v0.2026.10.09.08.27.stable_01"
|
||||
process.env.MAGPIE_WARP_CLIENT_VERSION = version
|
||||
try {
|
||||
expect(w.baseHeaders("fake")["x-warp-client-version"]).toBe(version)
|
||||
globalThis.fetch = async (_url, init) => {
|
||||
expect(init.headers["X-Warp-Client-Version"]).toBe(version)
|
||||
expect(JSON.parse(init.body).variables.requestContext.clientContext.version).toBe(version)
|
||||
return Response.json({ data: { user: { user: {} } } })
|
||||
}
|
||||
await w.requestWindows("fake")
|
||||
} finally {
|
||||
if (old === undefined) delete process.env.MAGPIE_WARP_CLIENT_VERSION
|
||||
else process.env.MAGPIE_WARP_CLIENT_VERSION = old
|
||||
}
|
||||
})
|
||||
@@ -50,6 +50,8 @@
|
||||
"summary": { "en": "Kiro Free, Pro, Pro+ and Power — Kiro's sign-in, kiro-cli's, or an API key.", "zh": "Kiro Free、Pro、Pro+ 与 Power:Kiro 登录、沿用 kiro-cli 的登录,或 API key。" } },
|
||||
{ "package": "@magpie-community/opencode-minimax-auth", "name": "MiniMax Code", "icon": "minimax-color", "providers": ["minimax-code", "minimax-code-global"], "community": true,
|
||||
"summary": { "en": "MiniMax Code credits and M Plan with device sign-in, native web search, image/video generation and media tools through Magpie MCP.", "zh": "MiniMax Code 积分与 M Plan、设备登录,提供原生网络搜索、生图、生视频及多模态 MCP 工具。" } },
|
||||
{ "package": "@magpie-community/opencode-warp-auth", "name": "Warp", "icon": "warp", "providers": ["warp"], "community": true,
|
||||
"summary": { "en": "Warp (the terminal) AI request credits through the Warp app's sign-in: the auto routers and every model family the account lists.", "zh": "用 Warp 终端应用的登录使用 Warp AI 请求额度:auto 路由与账户可用的全部模型家族。" } },
|
||||
{ "package": "@magpie-community/opencode-workbuddy-auth", "name": "WorkBuddy", "icon": "workbuddy-color", "providers": ["workbuddy", "workbuddy-ai"], "community": true, "replaces": "workbuddy",
|
||||
"summary": { "en": "WorkBuddy's China build (CodeBuddy plan) and its international build.", "zh": "WorkBuddy 国内版(CodeBuddy 套餐)与国际版。" } },
|
||||
{ "package": "@magpie-community/opencode-cline-auth", "name": "Cline", "icon": "cline", "providers": ["cline"], "community": true,
|
||||
|
||||
Reference in New Issue
Block a user