zed 0.1.4: a streamed reply is held until it says something, as the built-in's relayStatus holds it, and a failure before that is answered with its status rather than a 200 carrying it — Zed's failed status keeps the status its code names (upstream_http_401 a 401, http_403 a 403, billing a 402, where magpie read the old stream's chat and Responses errors as 502s), the provider's own error event is a 502 with its message, a reply ended with nothing said is a 502 "Zed ended without an answer" and one cut short a 502; a whole reply carrying the provider's error is that error (it was a 200 with nothing in it), and a code outside 400–599 is a 502. errors.test.mjs fails without the change.
This commit is contained in:
@@ -0,0 +1,90 @@
|
||||
// A request that fails before the reply says anything is answered with the
|
||||
// status magpie's built-in Zed account answers it with (relayStatus over
|
||||
// internal/gateway/zed.go), not a 200 whose stream carries the failure:
|
||||
// magpie's gateway moves on to the next account or member just as it did.
|
||||
import { afterEach, expect, test } from "bun:test"
|
||||
import { _internal } from "./index.mjs"
|
||||
|
||||
const real = globalThis.fetch
|
||||
afterEach(() => {
|
||||
globalThis.fetch = real
|
||||
_internal.tokens.clear()
|
||||
})
|
||||
|
||||
const s = { userId: "4242", access: "plain-access", systemId: "", org: "org-me", plan: "zed_pro", who: "octo" }
|
||||
|
||||
const URLS = {
|
||||
anthropic: "https://cloud.zed.dev/v1/messages",
|
||||
responses: "https://cloud.zed.dev/v1/responses",
|
||||
chat: "https://cloud.zed.dev/v1/chat/completions",
|
||||
}
|
||||
const MODEL = { anthropic: "claude-sonnet-5", responses: "gpt-5.5", chat: "grok-4.7" }
|
||||
|
||||
// ask sends one request on wire, Zed's /completions answering with lines
|
||||
// (each a JSON value, one a line) in its status-message form.
|
||||
async function ask(wire, lines, stream = true) {
|
||||
globalThis.fetch = async (url) => {
|
||||
const path = new URL(String(url)).pathname
|
||||
if (path === "/client/llm_tokens") return Response.json({ token: "llm-token" })
|
||||
if (path === "/completions")
|
||||
return new Response(lines.map((l) => JSON.stringify(l)).join("\n") + "\n", { headers: { "x-zed-server-supports-status-messages": "true" } })
|
||||
return new Response("", { status: 404 })
|
||||
}
|
||||
const res = await _internal.complete(s, URLS[wire], {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ model: MODEL[wire], stream, messages: [{ role: "user", content: "hi" }], max_tokens: 100 }),
|
||||
})
|
||||
const text = await res.text()
|
||||
return { status: res.status, text }
|
||||
}
|
||||
|
||||
const msgOf = (text) => {
|
||||
const j = JSON.parse(text)
|
||||
return j.error?.message
|
||||
}
|
||||
|
||||
const start = { event: { type: "message_start", message: { id: "msg_1", type: "message", role: "assistant", content: [], model: "claude-sonnet-5", usage: { input_tokens: 5, output_tokens: 0 } } } }
|
||||
const textStart = { event: { type: "content_block_start", index: 0, content_block: { type: "text", text: "" } } }
|
||||
|
||||
test("a rate limit Zed reports after the reply's start is the 429 it stands for", async () => {
|
||||
const r = await ask("anthropic", [{ status: "started" }, start, textStart, { status: { failed: { code: "upstream_http_429", message: "Rate limited" } } }])
|
||||
expect(r.status).toBe(429)
|
||||
expect(JSON.parse(r.text)).toEqual({ type: "error", error: { type: "rate_limit_error", message: "Rate limited" } })
|
||||
})
|
||||
|
||||
test("a failure keeps the status its code names on every API: 401 on chat, 403 on Responses, 402 for billing", async () => {
|
||||
const chat = await ask("chat", [{ status: "started" }, { status: { failed: { code: "upstream_http_401", message: "bad key upstream" } } }])
|
||||
expect([chat.status, msgOf(chat.text)]).toEqual([401, "bad key upstream"])
|
||||
const resp = await ask("responses", [{ event: { type: "response.created", response: { id: "r1" } } }, { status: { failed: { code: "http_403", message: "no" } } }])
|
||||
expect([resp.status, msgOf(resp.text)]).toEqual([403, "no"])
|
||||
const bill = await ask("anthropic", [start, { status: { failed: { code: "billing_limit", message: "" } } }])
|
||||
expect([bill.status, msgOf(bill.text)]).toEqual([402, "billing_limit"])
|
||||
})
|
||||
|
||||
test("the provider's own error event before any content is a 502 with its message, as the built-in's decoders read it", async () => {
|
||||
const r = await ask("anthropic", [start, { event: { type: "error", error: { type: "overloaded_error", message: "Overloaded" } } }])
|
||||
expect([r.status, msgOf(r.text)]).toEqual([502, "Overloaded"])
|
||||
const c = await ask("chat", [{ event: { id: "c", choices: [{ index: 0, delta: { role: "assistant", content: "" } }] } }, { event: { error: { message: "upstream went away" } } }])
|
||||
expect([c.status, msgOf(c.text)]).toEqual([502, "upstream went away"])
|
||||
})
|
||||
|
||||
test("a reply that ends with nothing said, or breaks off before it, is a 502", async () => {
|
||||
const none = await ask("anthropic", [start, textStart, { status: "stream_ended" }])
|
||||
expect([none.status, msgOf(none.text)]).toEqual([502, "Zed ended without an answer"])
|
||||
const cut = await ask("anthropic", [start])
|
||||
expect([cut.status, msgOf(cut.text)]).toEqual([502, "the reply ended before it was complete"])
|
||||
})
|
||||
|
||||
test("a reply that says something streams with its start, and a failure after it stays in the stream", async () => {
|
||||
const delta = { event: { type: "content_block_delta", index: 0, delta: { type: "text_delta", text: "Hi" } } }
|
||||
const r = await ask("anthropic", [start, textStart, delta, { status: { failed: { code: "upstream_http_429", message: "Rate limited" } } }])
|
||||
expect(r.status).toBe(200)
|
||||
expect(r.text.split("event: ").map((e) => e.split("\n")[0]).filter(Boolean)).toEqual(["message_start", "content_block_start", "content_block_delta", "error"])
|
||||
})
|
||||
|
||||
test("a whole reply carrying the provider's error is that error, and an out-of-range code is a 502", async () => {
|
||||
const r = await ask("anthropic", [start, { event: { type: "error", error: { type: "overloaded_error", message: "Overloaded" } } }, { status: "stream_ended" }], false)
|
||||
expect([r.status, msgOf(r.text)]).toEqual([502, "Overloaded"])
|
||||
const odd = await ask("anthropic", [start, { status: { failed: { code: "http_999", message: "odd" } } }], false)
|
||||
expect([odd.status, msgOf(odd.text)]).toEqual([502, "odd"])
|
||||
})
|
||||
+122
-6
@@ -560,9 +560,113 @@ function errorBody(wire, status, message) {
|
||||
const errorResponse = (wire, status, message) =>
|
||||
new Response(JSON.stringify(errorBody(wire, status, message)), { status, headers: { "content-type": "application/json" } })
|
||||
|
||||
// said tells whether one of the provider's own events says anything —
|
||||
// text, reasoning, a call, a finish — rather than only framing the reply,
|
||||
// as magpie's decoders tell a reply begun from its lead (message_start,
|
||||
// response.created, a role-only chunk).
|
||||
function said(wire, ev) {
|
||||
if (!ev || typeof ev !== "object") return true
|
||||
switch (wire) {
|
||||
case "anthropic":
|
||||
switch (ev.type) {
|
||||
case "message_start":
|
||||
case "ping":
|
||||
case "content_block_stop":
|
||||
return false
|
||||
case "content_block_start":
|
||||
return !["text", "thinking", "redacted_thinking"].includes(ev.content_block?.type) || !!(ev.content_block?.text || ev.content_block?.thinking)
|
||||
case "content_block_delta": {
|
||||
const d = ev.delta ?? {}
|
||||
return !(d.text === "" || d.thinking === "" || d.partial_json === "")
|
||||
}
|
||||
}
|
||||
return true
|
||||
case "responses":
|
||||
switch (ev.type) {
|
||||
case "response.created":
|
||||
case "response.in_progress":
|
||||
case "response.queued":
|
||||
case "response.content_part.added":
|
||||
case "response.reasoning_summary_part.added":
|
||||
return false
|
||||
case "response.output_item.added":
|
||||
return !["message", "reasoning"].includes(ev.item?.type)
|
||||
case "response.output_text.delta":
|
||||
case "response.reasoning_summary_text.delta":
|
||||
case "response.reasoning_text.delta":
|
||||
return ev.delta !== ""
|
||||
}
|
||||
return true
|
||||
case "chat":
|
||||
if (ev.error) return true
|
||||
if (!Array.isArray(ev.choices)) return false // usage alone
|
||||
return ev.choices.some((c) => {
|
||||
const d = c?.delta ?? {}
|
||||
return !!(c?.finish_reason || d.content || d.reasoning_content || d.reasoning || d.tool_calls?.length)
|
||||
})
|
||||
case "gemini":
|
||||
if (ev.error) return true
|
||||
return (ev.candidates ?? []).some((c) => c?.finishReason || (c?.content?.parts ?? []).some((p) => p?.text || p?.functionCall || p?.thought))
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// eventError is the message of an error the provider's own stream carries
|
||||
// (Anthropic's error event, a failed response, a chat or Gemini chunk's
|
||||
// error), undefined for any other event.
|
||||
function eventError(wire, ev) {
|
||||
if (!ev || typeof ev !== "object") return undefined
|
||||
if (wire === "anthropic" && ev.type === "error") return String(ev.error?.message ?? "")
|
||||
if (wire === "responses") {
|
||||
if (["response.completed", "response.incomplete", "response.failed"].includes(ev.type) && ev.response?.error) return String(ev.response.error.message ?? "")
|
||||
if (ev.type === "error") return String((ev.error ? ev.error.message : ev.message) ?? "")
|
||||
return undefined
|
||||
}
|
||||
if ((wire === "chat" || wire === "gemini") && ev.error) return String(ev.error?.message ?? "")
|
||||
return undefined
|
||||
}
|
||||
|
||||
// streamed turns Zed's lines into the provider's own server-sent events.
|
||||
function streamed(wire, res) {
|
||||
// What comes before the reply says anything is held, as magpie's built-in
|
||||
// holds it (relayStatus): a failure there — a failed status, the
|
||||
// provider's own error event, a reply that broke off or ended without an
|
||||
// answer — is answered as a refused request with its status (a 429, a 402
|
||||
// is another account's turn), not a 200 whose stream carries it.
|
||||
async function streamed(wire, res) {
|
||||
const wrapped = !!res.headers.get("x-zed-server-supports-status-messages")
|
||||
const it = lines(res.body, wrapped)
|
||||
const head = []
|
||||
let ended = false
|
||||
let first = null // the first line that says something
|
||||
try {
|
||||
for (;;) {
|
||||
const r = await it.next()
|
||||
if (r.done) break
|
||||
const l = r.value
|
||||
if (l.ended) {
|
||||
ended = true
|
||||
continue
|
||||
}
|
||||
if (l.failed) {
|
||||
let status = failedStatus(l.failed.code)
|
||||
if (status < 400 || status > 599) status = 502
|
||||
return errorResponse(wire, status, l.failed.message || l.failed.code)
|
||||
}
|
||||
const bad = eventError(wire, l.event)
|
||||
if (bad !== undefined) return errorResponse(wire, 502, bad)
|
||||
if (said(wire, l.event)) {
|
||||
first = l
|
||||
break
|
||||
}
|
||||
head.push(l.event)
|
||||
}
|
||||
} catch (e) {
|
||||
return errorResponse(wire, 502, String(e?.message ?? e).replace(/^Zed: /, ""))
|
||||
}
|
||||
if (!first) {
|
||||
if (wrapped && !ended) return errorResponse(wire, 502, "the reply ended before it was complete")
|
||||
return errorResponse(wire, 502, "Zed ended without an answer")
|
||||
}
|
||||
const enc = new TextEncoder()
|
||||
const body = new ReadableStream({
|
||||
async start(ctl) {
|
||||
@@ -572,9 +676,13 @@ function streamed(wire, res) {
|
||||
else if (wire === "responses") put(`event: error\ndata: ${JSON.stringify(errorBody(wire, status, message))}\n\n`)
|
||||
else put(`data: ${JSON.stringify(errorBody(wire, status, message))}\n\n`)
|
||||
}
|
||||
let ended = false
|
||||
for (const ev of head) put(sse(wire, ev))
|
||||
put(sse(wire, first.event))
|
||||
try {
|
||||
for await (const l of lines(res.body, wrapped)) {
|
||||
for (;;) {
|
||||
const r = await it.next()
|
||||
if (r.done) break
|
||||
const l = r.value
|
||||
if (l.ended) ended = true
|
||||
else if (l.failed) {
|
||||
fail(failedStatus(l.failed.code), l.failed.message || l.failed.code)
|
||||
@@ -594,6 +702,7 @@ function streamed(wire, res) {
|
||||
}
|
||||
},
|
||||
cancel() {
|
||||
it.return?.().catch?.(() => {})
|
||||
res.body?.cancel?.().catch(() => {})
|
||||
},
|
||||
})
|
||||
@@ -701,8 +810,15 @@ async function whole(wire, res) {
|
||||
try {
|
||||
for await (const l of lines(res.body, wrapped)) {
|
||||
if (l.ended) ended = true
|
||||
else if (l.failed) return errorResponse(wire, failedStatus(l.failed.code), l.failed.message || l.failed.code)
|
||||
else events.push(l.event)
|
||||
else if (l.failed) {
|
||||
const n = failedStatus(l.failed.code)
|
||||
return errorResponse(wire, n >= 400 && n <= 599 ? n : 502, l.failed.message || l.failed.code)
|
||||
} else {
|
||||
// the provider's own error, as the built-in's decoders read it
|
||||
const bad = eventError(wire, l.event)
|
||||
if (bad !== undefined) return errorResponse(wire, 502, bad)
|
||||
events.push(l.event)
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
return errorResponse(wire, 502, String(e?.message ?? e).replace(/^Zed: /, ""))
|
||||
@@ -860,4 +976,4 @@ export async function ZedAuthPlugin({ client } = {}) {
|
||||
}
|
||||
|
||||
// for tests
|
||||
export const _internal = { stateOf, parseModels, entry, providerRequest, wireOf, refusal, failedStatus, decrypt, padded, signedInWith, complete, vendors, tokens, lists, orgOf, who, planName, usage }
|
||||
export const _internal = { said, eventError, stateOf, parseModels, entry, providerRequest, wireOf, refusal, failedStatus, decrypt, padded, signedInWith, complete, vendors, tokens, lists, orgOf, who, planName, usage }
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@magpie-community/opencode-zed-auth",
|
||||
"version": "0.1.3",
|
||||
"version": "0.1.4",
|
||||
"description": "Sign in to a Zed subscription (Zed Pro, trial, student, business) from OpenCode or magpie",
|
||||
"type": "module",
|
||||
"main": "./index.mjs",
|
||||
|
||||
Reference in New Issue
Block a user