grok 0.2.6: a stream cut before its first byte is asked again (#852)

A Responses stream from Grok that dies before its first byte (the
connection reset, nothing sent yet) is asked again, up to three times,
before the answer is returned. A retry's own answer is noted, so a 429
or 401 on a retry comes back as itself, not folded into a 200.

Once a byte has arrived, response.created and reasoning included, the
stream is passed on at once, one upstream chunk per pull, and cancelling
it cancels the upstream read. A later cut is not asked again and nothing
is written in its place: the stream ends, and magpie 0.1.3298 or newer
(yetone/magpie 29bfd5dc8) closes it as a whole response.failed with
created_at and sequence_number. The frames 0.2.6's first version wrote
had no sequence_number, and Grok Build failed the turn on them. An
upstream response.failed, error or response.incomplete is passed on
unchanged, and an end with no bytes is not asked again.

Run on mote (macOS 27), at 463afb79, each in a temp HOME:
- packages/grok `bun test`: 107 pass, 0 fail.
- `bun scripts/check.mjs grok`: ok.
- Repo-root `bun test` with HOME=$(mktemp -d): 6878 pass, 20 skip,
  0 fail. A first run with HOME under /tmp had 21 reds in devin, zcode
  and sap-aicore. Those tests refuse a HOME outside $TMPDIR, and
  plugins main ecab8396 had the same reds under that HOME.
- Broken by hand, cut-retry.test.mjs goes red:
  - STREAM_TRIES=1: 3 fail;
  - the retry's note() removed: the 429 test fails;
  - cancel() not passed upstream: the cancel test fails;
  - "aborted" counted as a cut: the abort test fails;
  - a later cut erroring the stream instead of ending it: 2 fail.
  Asking again after a zero-byte clean end is the one break no test
  catches.
- Real chain: Grok Build 1.0.67 and 1.0.77 (x.ai's own build, the
  reporter's version), then magpie eef99e4bb (`magpie serve`, sandbox
  HOME), then this plugin (BASE pointed at a fake), then a fake Grok
  upstream:
  - ok: "pong".
  - Cut before the first byte, then ok: "pong", with the retry inside
    the plugin.
  - Cut, then 429: magpie logs a 429 from Grok, and Grok Build retries
    on "rate limited".
  - Always cut before a byte: an empty 200, which magpie reports as a
    retryable 502. Grok Build retries it as server_error.
  - Cut after response.created, and cut after text: magpie's
    response.failed ("the reply ended before it was complete"). Grok
    Build reads it and retries it as server_error. No "missing field"
    in either version.
  - Upstream response.failed: one call, and Grok Build shows the
    vendor's own message.

Not tried: a live Grok stream cut by the real vendor.
This commit is contained in:
lxyer
2026-11-08 12:42:31 +08:00
committed by GitHub
parent ecab839688
commit ae51883634
4 changed files with 397 additions and 2 deletions
+12
View File
@@ -107,6 +107,18 @@ API (`@ai-sdk/openai`), signed as the CLI signs them:
- `x-grok-doom-loop-check: 1024` and `x-grok-exact-repetition-check: 64`
on a Responses request, as Grok Build sends them: the proxy then stops a
reply that repeats itself after ~1K tokens instead of letting it run on.
- A Responses stream that dies before its first byte (the connection
reset, with nothing sent yet) is asked again, up to three times. The
retry goes out before the answer is returned, so a 429 or a 401 comes
back as itself. Once a byte has arrived, `response.created` and
reasoning included, it is passed on at once. A later cut is not asked
again and not rewritten: the stream ends, and magpie 0.1.3298 or newer
closes it as `response.failed` with `created_at` and `sequence_number`.
The frame this plugin used to write had `created_at` and still no
`sequence_number`, so Grok Build reported
`missing field sequence_number`. An upstream `response.failed`,
`error` or `response.incomplete` is passed on unchanged. Cancelling
the turn stops the read and is not asked again.
The backend turns away some of what a request may carry, so the plugin
leaves these out:
+264
View File
@@ -0,0 +1,264 @@
import { noRealGrok } from "./nocli.mjs"
import { afterAll, afterEach, expect, test } from "bun:test"
import { mkdtempSync, rmSync, writeFileSync } from "node:fs"
import { tmpdir } from "node:os"
import { join } from "node:path"
import { GrokAuthPlugin, _internal } from "./index.mjs"
noRealGrok()
// A cut before the first byte is asked again. Once a byte has arrived the
// stream is passed on, and a later cut just ends: magpie 0.1.3298+ writes
// the response.failed. This plugin must not invent one (it had no
// sequence_number, and Grok Build rejected it).
const realFetch = globalThis.fetch
const realWarn = console.warn
afterEach(() => {
globalThis.fetch = realFetch
console.warn = realWarn
_internal.limited.clear()
})
const home = mkdtempSync(join(tmpdir(), "grok-cut-retry-"))
afterAll(() => rmSync(home, { recursive: true, force: true }))
const expires = Date.now() + 24 * 3600_000
writeFileSync(join(home, "auth.json"), JSON.stringify({
test: { key: "test-token", email: "test@example.invalid", expires_at: new Date(expires).toISOString() },
}))
const auth = { type: "oauth", refresh: home, access: "test-token", expires, accountId: "test@example.invalid" }
function event(type, fields = {}) {
return `event: ${type}\ndata: ${JSON.stringify({ type, ...fields })}\n\n`
}
function created(id = "resp_test") {
return event("response.created", {
response: { id, object: "response", created_at: 1_700_000_000, status: "in_progress", model: "grok-4.7" },
})
}
function sse(parts, { fail } = {}) {
const enc = new TextEncoder()
let index = 0
const stream = new ReadableStream({
pull(controller) {
if (index < parts.length) {
controller.enqueue(enc.encode(parts[index]))
index += 1
return
}
if (fail) controller.error(new Error(fail))
else controller.close()
},
})
return new Response(stream, { status: 200, headers: { "content-type": "text/event-stream" } })
}
function die(message) {
const stream = new ReadableStream({
pull(controller) {
controller.error(new Error(message))
},
})
return new Response(stream, { status: 200, headers: { "content-type": "text/event-stream" } })
}
function eventsOf(text) {
const events = []
for (const line of text.split(/\r?\n/)) {
const data = line.startsWith("data:") ? line.slice(5).trim() : ""
if (!data.startsWith("{")) continue
events.push(JSON.parse(data))
}
return events
}
async function ask(attempts) {
let calls = 0
console.warn = () => {}
globalThis.fetch = async () => {
const make = attempts[calls]
calls += 1
if (!make) throw new Error(`unexpected fetch ${calls}`)
return make()
}
const hooks = await GrokAuthPlugin({ client: {} })
const opts = await hooks.auth.loader(async () => auth)
const res = await opts.fetch("https://cli-chat-proxy.grok.com/v1/responses", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ model: "grok-4.7", input: "hi", stream: true }),
})
const text = await res.text()
return { calls, res, text }
}
test("a stream cut before any byte is asked again", async () => {
const { calls, res, text } = await ask([
() => die("ECONNRESET"),
() => sse([
created("resp_b"),
event("response.output_text.delta", { delta: "pong" }),
event("response.completed", { response: { id: "resp_b", created_at: 1_700_000_001, status: "completed" } }),
]),
])
expect(calls).toBe(2)
expect(res.status).toBe(200)
expect(text).toContain("pong")
expect(text).toContain("resp_b")
expect(eventsOf(text).some((item) => item.type === "response.failed")).toBe(false)
})
test("a stream that ends before output is not asked again", async () => {
const { calls, text } = await ask([
() => sse([created("resp_empty")]),
() => sse([event("response.output_text.delta", { delta: "nope" })]),
])
expect(calls).toBe(1)
expect(text).toContain("resp_empty")
expect(text).not.toContain("nope")
})
test("three cuts before any byte invent no response.failed", async () => {
const { calls, res, text } = await ask([
() => die("ECONNRESET"),
() => die("socket connection was closed unexpectedly"),
() => die("unexpected EOF"),
])
expect(calls).toBe(3)
expect(res.status).toBe(200)
expect(text).toBe("")
expect(text).not.toContain("response.failed")
expect(text).not.toContain("created_at")
})
test("reasoning is forwarded and a later cut is not asked again", async () => {
const { calls, text } = await ask([
() => sse([
created("resp_think"),
event("response.reasoning_summary_text.delta", { delta: "thinking-once" }),
], { fail: "ECONNRESET" }),
() => sse([event("response.output_text.delta", { delta: "should-not-retry" })]),
])
expect(calls).toBe(1)
expect(text).toContain("thinking-once")
expect(text).toContain("resp_think")
expect(text).not.toContain("should-not-retry")
expect(text).not.toContain("response.failed")
})
test("a cut after output is not asked again and invents no event", async () => {
const { calls, text } = await ask([
() => sse([
created("resp_out"),
event("response.output_text.delta", { delta: "pong" }),
], { fail: "ECONNRESET" }),
() => sse([event("response.output_text.delta", { delta: "should-not-retry" })]),
])
expect(calls).toBe(1)
expect(text).toContain("pong")
expect(text).toContain("resp_out")
expect(text).not.toContain("should-not-retry")
expect(eventsOf(text).map((item) => item.type)).toEqual(["response.created", "response.output_text.delta"])
})
test("an upstream response.failed is passed on", async () => {
const { calls, text } = await ask([
() => sse([
created("resp_no"),
event("response.failed", {
response: { id: "resp_no", created_at: 5, status: "failed", error: { message: "context too long" } },
}),
]),
() => sse([event("response.output_text.delta", { delta: "nope" })]),
])
expect(calls).toBe(1)
expect(text).toContain("context too long")
expect(text).not.toContain("nope")
expect(text).not.toContain("stream ended before output")
})
test("an upstream error event is passed on", async () => {
const { calls, text } = await ask([
() => sse([event("error", { error: { type: "server_error", message: "upstream said no" } })]),
() => sse([event("response.output_text.delta", { delta: "nope" })]),
])
expect(calls).toBe(1)
expect(text).toContain("upstream said no")
expect(text).not.toContain("nope")
})
test("a 429 after a cut before any byte is the real answer", async () => {
const { calls, res, text } = await ask([
() => die("ECONNRESET"),
() => new Response("slow down", { status: 429, headers: { "content-type": "text/plain", "retry-after": "12" } }),
])
expect(calls).toBe(2)
expect(res.status).toBe(429)
expect(text).toBe("slow down")
expect(res.headers.get("x-magpie-sign-in")).toBe("kept")
expect(text).not.toContain("response.failed")
const held = _internal.limited.get(home)
expect(held?.until).toBeGreaterThan(Date.now())
})
test("an aborted stream is not asked again", async () => {
const { calls, text } = await ask([
() => die("The operation was aborted."),
() => sse([event("response.output_text.delta", { delta: "nope" })]),
])
expect(calls).toBe(1)
expect(text).toBe("")
expect(text).not.toContain("nope")
expect(text).not.toContain("response.failed")
})
test("cancelling the stream stops the upstream read", async () => {
let pulls = 0
let cancelled = false
const enc = new TextEncoder()
console.warn = () => {}
globalThis.fetch = async () => new Response(new ReadableStream({
pull(controller) {
pulls += 1
controller.enqueue(enc.encode(event("response.output_text.delta", { delta: "x" })))
},
cancel() { cancelled = true },
}), { status: 200, headers: { "content-type": "text/event-stream" } })
const hooks = await GrokAuthPlugin({ client: {} })
const opts = await hooks.auth.loader(async () => auth)
const res = await opts.fetch("https://cli-chat-proxy.grok.com/v1/responses", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ model: "grok-4.7", input: "hi", stream: true }),
})
const reader = res.body.getReader()
const first = await reader.read()
expect(new TextDecoder().decode(first.value)).toContain('"delta":"x"')
const pulled = pulls
await reader.cancel()
await new Promise((resolve) => setTimeout(resolve, 30))
expect(cancelled).toBe(true)
expect(pulls).toBe(pulled)
expect(pulls).toBeLessThan(5)
})
test("a JSON answer is not retried or rewritten", async () => {
let calls = 0
console.warn = () => {}
globalThis.fetch = async () => {
calls += 1
return Response.json({ output: [{ type: "message" }] })
}
const hooks = await GrokAuthPlugin({ client: {} })
const opts = await hooks.auth.loader(async () => auth)
const res = await opts.fetch("https://cli-chat-proxy.grok.com/v1/responses", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ model: "grok-4.7", input: "hi" }),
})
const body = await res.json()
expect(calls).toBe(1)
expect(body.output[0].type).toBe("message")
expect(res.headers.get("x-grok-auth-hold")).toBeNull()
expect(res.headers.get("x-magpie-sign-in")).toBe("kept")
})
+120 -1
View File
@@ -958,6 +958,121 @@ function kept(res) {
// ---- the plugin ---------------------------------------------------------------
// A Responses stream that dies before its first byte is asked again, up
// to three times, before this answer is returned. A retry's 429 or 401
// is that answer: note sees it, and it is not folded into a 200. Once a
// byte has arrived, response.created and reasoning included, it is
// passed on at once. A later cut is not asked again and not rewritten.
// The stream just ends. magpie 0.1.3298 and newer closes a Responses
// stream that ends short as response.failed, with the stream's id,
// created_at and the next sequence_number (yetone/magpie 29bfd5dc8).
// The frame this plugin used to write had created_at and still no
// sequence_number, and Grok Build failed the turn on it. An upstream
// response.failed, error or response.incomplete is passed on unchanged.
// Cancelling stops the upstream read.
const STREAM_TRIES = 3
const CUT = /ECONNRESET|EPIPE|ETIMEDOUT|ECONNABORTED|socket connection was closed|connection lost|unexpected EOF|terminated|other side closed|UND_ERR|network connection|ECONNREFUSED/i
function eventStream(res) {
const type = res?.headers?.get?.("content-type") || ""
return res?.status === 200 && !!res?.body && /text\/event-stream/i.test(type)
}
// firstByte reads one chunk. A failure here is still before anything was
// sent, so the caller can ask again. The reader stays open when a chunk
// did arrive: the rest of the body follows it.
async function firstByte(body) {
const reader = body.getReader()
try {
const { done, value } = await reader.read()
if (done) return { kind: "end", reader }
return { kind: "byte", value, reader }
} catch (cause) {
const reason = String(cause?.message || cause)
try { await reader.cancel(cause) } catch {}
return { kind: "cut", reason }
}
}
function bare(res, stream) {
const headers = new Headers(res.headers)
headers.delete("content-length")
headers.delete("content-encoding")
return new Response(stream, { status: res.status, statusText: res.statusText, headers })
}
// passThrough sends the chunk already read, then one upstream chunk per
// pull. Nothing is buffered past that, and cancel stops the upstream read.
function passThrough(res, reader, first) {
let lead = first
let leadWaiting = true
const stream = new ReadableStream({
async pull(controller) {
if (leadWaiting) {
leadWaiting = false
if (lead) controller.enqueue(lead)
lead = undefined
return
}
try {
const { done, value } = await reader.read()
if (done) {
controller.close()
return
}
controller.enqueue(value)
} catch (cause) {
const reason = String(cause?.message || cause)
try { await reader.cancel(cause) } catch {}
// cancel already closed this stream: nothing more to report
if (controller.desiredSize === null) return
console.warn(`[grok-auth] stream failed (${reason.slice(0, 160)})`)
try { controller.close() } catch {}
}
},
cancel(reason) {
return reader.cancel(reason)
},
})
return bare(res, stream)
}
function ended(res) {
return bare(res, new ReadableStream({
start(controller) { controller.close() },
}))
}
async function cutRetry(res, again, { tries = STREAM_TRIES } = {}) {
let current = res
for (let attempt = 1; attempt <= tries; attempt++) {
if (attempt > 1) {
try {
current = await again()
} catch (cause) {
const said = String(cause?.message || cause)
console.warn(`[grok-auth] retry ${attempt}/${tries} did not start: ${said.slice(0, 160)}`)
if (!CUT.test(said) || attempt === tries) return ended(res)
continue
}
}
if (!eventStream(current)) return current
const read = await firstByte(current.body)
if (read.kind === "byte") return passThrough(current, read.reader, read.value)
if (read.kind === "end") {
try { await read.reader.cancel() } catch {}
return ended(current)
}
const reason = read.reason
if (!CUT.test(reason) || attempt === tries) {
console.warn(`[grok-auth] stream failed (${reason.slice(0, 160)})`)
return ended(current)
}
console.warn(`[grok-auth] stream cut before any byte (${reason.slice(0, 140)}); retry ${attempt + 1}/${tries}`)
}
return ended(current)
}
export const GrokAuthPlugin = async ({ client, magpie }) => {
const remember = async (auth, c) => {
if (auth.access === c.key && auth.expires === c.expires) return
@@ -1106,7 +1221,11 @@ export const GrokAuthPlugin = async ({ client, magpie }) => {
res = await send(c.key)
}
note(home, res)
return kept(res)
return kept(await cutRetry(res, async () => {
const next = await send(c.key)
note(home, next)
return next
}))
},
}
},
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@magpie-community/opencode-grok-auth",
"version": "0.2.5",
"version": "0.2.6",
"description": "OpenCode provider plugin: Grok (SuperGrok / X Premium+) through the Grok Build CLI's sign-in",
"type": "module",
"main": "./opencode.mjs",