kiro 0.1.4: an exception Kiro sends before any of the answer (a throttle, a quota, a server error) is a status, not a 200 stream holding an error event, as the built-in's relay answers it: a 429 when it reads as a quota or rate limit (magpie's quotaWords), else a 502, so magpie moves on to the next account exactly as it did; unstreamed, what was said before a later exception is the answer, as the built-in's collector gives it, where the plugin answered 502. errors.test.mjs fails without the change.

This commit is contained in:
yetone
2026-10-01 03:45:12 +08:00
parent f62d7d1057
commit 8efe85163c
3 changed files with 124 additions and 13 deletions
+86
View File
@@ -0,0 +1,86 @@
// A reply that fails before any of its answer fails as magpie's built-in
// Kiro relay failed it (internal/gateway/claude_subscription.go relay): a
// status, not a stream — a 429 when the error reads as a quota or rate limit
// (quotaWords), else a 502 — so magpie's gateway moves on to the next account.
import { test, expect } from "bun:test"
import { _internal } from "./index.mjs"
const { events, reply } = _internal
// frame is one AWS event-stream message with string headers.
function frame(headers, payload) {
const enc = new TextEncoder()
const hs = []
for (const [k, v] of Object.entries(headers)) {
const name = enc.encode(k)
const val = enc.encode(v)
const h = new Uint8Array(1 + name.length + 1 + 2 + val.length)
h[0] = name.length
h.set(name, 1)
h[1 + name.length] = 7
new DataView(h.buffer).setUint16(2 + name.length, val.length)
h.set(val, 4 + name.length)
hs.push(h)
}
const hlen = hs.reduce((n, h) => n + h.length, 0)
const body = enc.encode(JSON.stringify(payload))
const total = 12 + hlen + body.length + 4
const out = new Uint8Array(total)
const v = new DataView(out.buffer)
v.setUint32(0, total)
v.setUint32(4, hlen)
let i = 12
for (const h of hs) {
out.set(h, i)
i += h.length
}
out.set(body, i)
return out
}
const stream = (...fs) =>
new ReadableStream({
start(c) {
for (const f of fs) c.enqueue(f)
c.close()
},
})
const exception = (type, message) => frame({ ":message-type": "exception", ":exception-type": type }, { message })
const text = (content) => frame({ ":message-type": "event", ":event-type": "assistantResponseEvent" }, { content })
const ask = (body, streaming) => reply(events(body, "claude-sonnet-4.5", 0), "claude-sonnet-4.5", streaming)
test("a throttling exception before the answer is a 429, streamed or not", async () => {
for (const s of [true, false]) {
const res = await ask(stream(exception("ThrottlingException", "Too many requests")), s)
expect(res.status).toBe(429)
const b = await res.json()
expect(b.error.message).toBe("rate limited: Too many requests")
}
})
test("a quota exception before the answer is a 429", async () => {
const res = await ask(stream(exception("ServiceQuotaExceededException", "You have reached the limit")), true)
expect(res.status).toBe(429)
})
test("another exception before the answer is a 502, not a stream", async () => {
const res = await ask(stream(exception("ValidationException", "Input is too long.")), true)
expect(res.status).toBe(502)
expect((await res.json()).error.message).toBe("ValidationException: Input is too long.")
})
test("an exception after the answer began ends the stream with an error event", async () => {
const res = await ask(stream(text("Hello"), exception("ThrottlingException", "slow down")), true)
expect(res.status).toBe(200)
const sse = await res.text()
expect(sse).toContain("Hello")
expect(sse).toContain("event: error")
})
test("unstreamed, what was said before an exception is the answer", async () => {
const res = await ask(stream(text("Hello"), exception("InternalServerException", "boom")), false)
expect(res.status).toBe(200)
expect((await res.json()).content).toEqual([{ type: "text", text: "Hello" }])
})
+37 -12
View File
@@ -952,6 +952,19 @@ async function* events(body, model, budget) {
yield { kind: "stop", reason, usage }
}
// finished is the message's blocks with each call's arguments read.
function finished(content) {
for (const b of content)
if (b.type === "tool_use") {
try {
b.input = b.input ? JSON.parse(b.input) : {}
} catch {
b.input = {}
}
}
return content
}
const anthropicUsage = (u) => ({
input_tokens: u.input,
output_tokens: u.output,
@@ -959,6 +972,16 @@ const anthropicUsage = (u) => ({
cache_creation_input_tokens: u.cacheWrite,
})
// quotaWords are magpie's (internal/gateway/fallback.go): how a vendor says
// "out of quota" or "slow down".
const QUOTA_WORDS = /quota|insufficient|balance|credit|billing|exceeded|rate.?limit|usage.?limit|limit.?reached|hit your .*limit|limit.{0,24}resets|too many requests|overloaded|余额|额度|欠费|限流|频率|套餐|用量|上限/i
// failedBefore is the reply to an error before any of the answer, as
// magpie's built-in relay gives it: a status, not a stream, so another
// account can take over — a 429 when it reads as a quota or rate limit,
// else a 502.
const failedBefore = (text) => errorResponse(QUOTA_WORDS.test(text) ? 429 : 502, text)
// reply answers the Messages request from Kiro's events: a stream of
// Messages' events, or one message.
async function reply(it, model, stream) {
@@ -982,23 +1005,24 @@ async function reply(it, model, stream) {
} else if (e.kind === "toolStart") add({ type: "tool_use", id: e.id, name: e.name, input: "" })
else if (e.kind === "toolArgs") {
if (last?.type === "tool_use") last.input += e.text
} else if (e.kind === "error") return errorResponse(502, e.text)
else if (e.kind === "stop") {
for (const b of content)
if (b.type === "tool_use") {
try {
b.input = b.input ? JSON.parse(b.input) : {}
} catch {
b.input = {}
}
}
return Response.json({ id, type: "message", role: "assistant", model, content, stop_reason: e.reason, stop_sequence: null,
} else if (e.kind === "error") {
// with none of the answer said, a status; else what was said
if (!content.length) return failedBefore(e.text)
return Response.json({ id, type: "message", role: "assistant", model, content: finished(content), stop_reason: "end_turn",
stop_sequence: null, usage: anthropicUsage({ input: 0, output: 0, cacheRead: 0, cacheWrite: 0 }) })
} else if (e.kind === "stop") {
return Response.json({ id, type: "message", role: "assistant", model, content: finished(content), stop_reason: e.reason, stop_sequence: null,
usage: anthropicUsage(e.usage) })
}
}
return errorResponse(502, "the reply ended before it was complete")
}
// an error before any of the answer is a status, as the built-in's
const head = await it.next()
if (head.value?.kind === "error") return failedBefore(head.value.text)
let pending = head
const enc = new TextEncoder()
const sse = (type, data) => enc.encode(`event: ${type}\ndata: ${JSON.stringify({ type, ...data })}\n\n`)
let index = -1
@@ -1022,7 +1046,8 @@ async function reply(it, model, stream) {
open = kind
ctl.enqueue(sse("content_block_start", { index, content_block: block }))
}
const r = await it.next()
const r = pending ?? (await it.next())
pending = null
if (r.done) return ctl.close()
const e = r.value
switch (e.kind) {
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@magpie-community/opencode-kiro-auth",
"version": "0.1.3",
"version": "0.1.4",
"description": "Kiro subscriptions (Free, Pro, Pro+, Power) in OpenCode and magpie",
"type": "module",
"main": "./index.mjs",