Files
plugins/packages/warp/schema.test.mjs
T
guoqchen1001andguoqchen1001 54a55b8b67 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>
2026-11-06 17:36:54 +08:00

134 lines
6.0 KiB
JavaScript

// 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" })
})