From 0c7275a140b9831607b15c74c2bb04bf352c5776 Mon Sep 17 00:00:00 2001 From: yetone Date: Thu, 1 Oct 2026 03:07:40 +0800 Subject: [PATCH] =?UTF-8?q?grok=200.1.2:=20a=20usage=20fetch=20that=20fail?= =?UTF-8?q?s=20or=20a=20reply=20that=20isn't=20JSON=20is=20the=20card's=20?= =?UTF-8?q?error,=20as=20grok=5Fusage.go=20says=20it=20(Go's=20`Get=20"":=20=E2=80=A6`=20with=20no=20such=20host=20/=20connection=20?= =?UTF-8?q?refused=20/=20timeout=20/=20EOF=20for=20magpie's=20keepLast,=20?= =?UTF-8?q?encoding/json's=20words);=20a=20status=20Go=20has=20no=20words?= =?UTF-8?q?=20for=20says=20"HTTP=20";=20a=20model=20list=20Grok=20could?= =?UTF-8?q?n't=20give=20fails=20instead=20of=20falling=20back=20to=20the?= =?UTF-8?q?=20configured=20few;=20a=20request=20body=20handed=20over=20as?= =?UTF-8?q?=20bytes=20is=20reshaped=20as=20a=20string=20one?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- packages/grok/index.mjs | 69 +++++++++++++++++++++++++++++------- packages/grok/package.json | 2 +- packages/grok/usage.test.mjs | 46 +++++++++++++++++++++++- 3 files changed, 102 insertions(+), 15 deletions(-) diff --git a/packages/grok/index.mjs b/packages/grok/index.mjs index 93d2903..d33c29e 100644 --- a/packages/grok/index.mjs +++ b/packages/grok/index.mjs @@ -174,6 +174,13 @@ async function sign(headers, key) { headers.set("User-Agent", `grok-shell/${v} (${os}; ${arch})`) } +// bodyText is a request body handed over as bytes read as the text it +// is, so it can be reshaped; any other body is as it came. +function bodyText(body) { + if (body instanceof ArrayBuffer || ArrayBuffer.isView(body)) return new TextDecoder().decode(body) + return body +} + // rewrite leaves out what Grok's backend doesn't take: tools of other // types (a freeform apply_patch, a namespace of sub-agent tools), a web // search's external_web_access, a tool_choice naming a dropped type, and a @@ -353,16 +360,52 @@ const RFC3339 = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2}) // statusText is a refused request's status as magpie says it (Go's // http.StatusText). +// http.StatusText); one Go has no words for is "HTTP ", never empty. const statusText = (s) => - ({ 413: "Request Entity Too Large", 414: "Request URI Too Long", 416: "Requested Range Not Satisfiable", 418: "I'm a teapot", 509: "" })[s] ?? STATUS_CODES[s] ?? "" + ((GO_TEXT[s] ?? STATUS_CODES[s]) || `HTTP ${s}`) +// where Go's words differ from Node's (509 Go has none for) +const GO_TEXT = { 413: "Request Entity Too Large", 414: "Request URI Too Long", 416: "Requested Range Not Satisfiable", 418: "I'm a teapot", 509: "" } + +// netError is a request that got no answer, as Go's http client words it +// (`Get "": …`), with the words magpie's keepLast looks for to keep +// the card it had: no such host, connection refused, timeout, EOF. +function netError(url, e) { + const m = String(e?.message ?? e) + const code = String(e?.code ?? e?.cause?.code ?? "") + let why = m + if (e?.name === "TimeoutError" || e?.name === "AbortError" || /timed? ?out/i.test(m)) why = "timeout" + else if (code === "ENOTFOUND" || code === "EAI_AGAIN" || /getaddrinfo|ENOTFOUND|resolve|DNS/i.test(m)) why = "dial tcp: lookup: no such host" + else if (code === "ECONNREFUSED" || /ECONNREFUSED|Unable to connect|refused/i.test(m)) why = "dial tcp: connection refused" + else if (/ECONNRESET|socket|closed|fetch failed/i.test(m + code)) why = "EOF" + return `Get "${url}": ${why}` +} + +// jsonError is JSON that won't read, as Go's encoding/json says it. +function jsonError(text) { + const c = text.trimStart()[0] + return c === undefined ? "unexpected end of JSON input" : `invalid character '${c}' looking for beginning of value` +} async function usage(key) { - const res = await fetch(`${BASE}/billing?format=credits`, { - headers: { Authorization: `Bearer ${key}`, Accept: "application/json" }, - signal: AbortSignal.timeout(15_000), - }) + const url = `${BASE}/billing?format=credits` + let res, text + try { + res = await fetch(url, { + headers: { Authorization: `Bearer ${key}`, Accept: "application/json" }, + signal: AbortSignal.timeout(15_000), + }) + if (res.ok) text = await res.text() + } catch (e) { + return { error: netError(url, e), windows: [] } + } if (!res.ok) return { error: statusText(res.status), windows: [] } - const cfg = (await res.json())?.config ?? {} + let data + try { + data = JSON.parse(text) + } catch { + return { error: jsonError(text), windows: [] } + } + const cfg = data?.config ?? {} const num = (v) => (typeof v === "number" ? v : 0) let [name, span] = ["Allowance", 0] let end = cfg.billingPeriodEnd @@ -411,7 +454,7 @@ export const GrokAuthPlugin = async ({ client }) => { const home = auth?.refresh if (!home) throw new Error("Grok is not signed in; run `grok login`") const req = new Request(input, init) - const body = rewrite(init?.body) + const body = rewrite(bodyText(init?.body)) let parsed = {} if (typeof body === "string") { try { @@ -466,12 +509,9 @@ export const GrokAuthPlugin = async ({ client }) => { async models(provider, { auth } = {}) { const have = provider?.models ?? {} if (!auth || auth.type !== "oauth" || !auth.refresh) return have - let list - try { - list = await listModels((await token(auth.refresh, false)).key) - } catch { - return have - } + // a list Grok couldn't give is a failure, not the few configured: + // magpie keeps the list it had + const list = await listModels((await token(auth.refresh, false)).key) const base = have["grok-4.7"] ?? Object.values(have)[0] ?? {} const out = {} for (const m of list) { @@ -498,3 +538,6 @@ export const GrokAuthPlugin = async ({ client }) => { }, } } + +// for tests +export const _internal = { rewrite, bodyText } diff --git a/packages/grok/package.json b/packages/grok/package.json index d3c3b4e..cb9cbb0 100644 --- a/packages/grok/package.json +++ b/packages/grok/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-grok-auth", - "version": "0.1.1", + "version": "0.1.2", "description": "OpenCode provider plugin: Grok (SuperGrok / X Premium+) through the Grok Build CLI's sign-in", "type": "module", "main": "./index.mjs", diff --git a/packages/grok/usage.test.mjs b/packages/grok/usage.test.mjs index ecdd9b3..3a93018 100644 --- a/packages/grok/usage.test.mjs +++ b/packages/grok/usage.test.mjs @@ -5,7 +5,7 @@ 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 } from "./index.mjs" +import { GrokAuthPlugin, _internal } from "./index.mjs" const real = globalThis.fetch afterEach(() => (globalThis.fetch = real)) @@ -72,3 +72,47 @@ test("a refused token is the status magpie says; no sign-in says to sign in", as expect(u).toEqual({ error: "Grok is not signed in; run `grok login`", windows: [] }) expect(seen).toEqual([]) }) + +// grok_usage.go gives the card Go's error for a request that got no +// answer or JSON that won't read; the plugin said nothing and threw +test("a fetch that fails is the card's error, worded for magpie's keepLast", async () => { + const url = "https://cli-chat-proxy.grok.com/v1/billing?format=credits" + const fail = (e) => () => { throw e } + const cases = [ + [Object.assign(new TypeError("Unable to connect. Is the computer able to access the url?"), { code: "ConnectionRefused" }), "connection refused"], + [Object.assign(new Error("connect ECONNREFUSED 127.0.0.1:443"), { code: "ECONNREFUSED" }), "connection refused"], + [Object.assign(new Error("getaddrinfo ENOTFOUND cli-chat-proxy.grok.com"), { code: "ENOTFOUND" }), "no such host"], + [new DOMException("The operation timed out.", "TimeoutError"), "timeout"], + [new TypeError("fetch failed"), "EOF"], + ] + for (const [e, said] of cases) { + const { u } = await run(auth, fail(e)) + expect(u.windows).toEqual([]) + expect(u.error.startsWith(`Get "${url}": `)).toBe(true) + expect(u.error).toMatch(/no such host|connection refused|timeout|EOF|Service Unavailable/) + expect(u.error).toContain(said) + } +}) + +test("a reply that isn't JSON is the card's error, as Go's encoding/json says it", async () => { + expect((await run(auth, () => new Response("oops"))).u).toEqual({ error: "invalid character '<' looking for beginning of value", windows: [] }) + expect((await run(auth, () => new Response(""))).u).toEqual({ error: "unexpected end of JSON input", windows: [] }) +}) + +test("a status Go has no words for still says something", async () => { + expect((await run(auth, () => new Response("", { status: 509 }))).u).toEqual({ error: "HTTP 509", windows: [] }) +}) + +test("a model list Grok couldn't give fails, not falls back to the configured few", async () => { + globalThis.fetch = async () => new Response("down", { status: 503 }) + const hooks = await GrokAuthPlugin({ client: { auth: { set: async () => {} } } }) + await expect(hooks.provider.models({ id: "grok", models: { "grok-4.7": { id: "grok-4.7" } } }, { auth })).rejects.toThrow() +}) + +test("a body in bytes is reshaped as a string one is", () => { + const { rewrite, bodyText } = _internal + const chat = { model: "grok-4.7", tools: [{ type: "function", name: "f" }, { type: "custom", name: "apply_patch" }] } + const want = rewrite(JSON.stringify(chat)) + expect(JSON.parse(want).tools.length).toBe(1) + for (const b of [Buffer.from(JSON.stringify(chat)), new TextEncoder().encode(JSON.stringify(chat))]) expect(rewrite(bodyText(b))).toBe(want) +})