diff --git a/packages/kiro/errors.test.mjs b/packages/kiro/errors.test.mjs index 0619b17..86d2bf6 100644 --- a/packages/kiro/errors.test.mjs +++ b/packages/kiro/errors.test.mjs @@ -141,7 +141,11 @@ test("unstreamed, what was said before an exception is the answer", async () => // Failing before any of the answer, a request is answered with the built-in's // status (internal/gateway/kiro.go askKiro), and X-Magpie-Sign-In: kept, // as the built-in marked no Kiro account lapsed, even one Kiro refused. -const { generate, refresh, failure } = _internal +const { generate, refresh, failure, timing, TRIES } = _internal +// a throttle's pauses (paced) are counted here, not waited +const pauses = [] +const realSleep = timing.sleep +timing.sleep = async (ms) => void pauses.push(ms) const msgReq = { model: "claude-sonnet-4.5", messages: [{ role: "user", content: "hi" }] } const gone = (msg) => Object.assign(new Error(msg), { gone: true }) @@ -299,3 +303,108 @@ test("an account's request rate in the stream is the same plain 429, with a wait expect(m).toContain("(USER_REQUEST_RATE_EXCEEDED)") } }) + +// onemezao on Discord: a "hi" answered, and the next message straight +// after was Kiro's 429 USER_REQUEST_RATE_EXCEEDED, while the Kiro IDE on +// the same account and model took two messages in a row. The IDE doesn't +// get fewer of these: its client (agent 1.1.787, QClientRetryStrategy) +// waits a throttle out, 1s then 2s or Kiro's retryAfterMilliseconds, and +// tries again, up to 3 tries. The plugin sent the first 429 back at once. +const limitedBody = JSON.stringify({ message: "Too many requests, please wait before trying again.", reason: "USER_REQUEST_RATE_EXCEEDED" }) +const answered = () => + new Response(new ReadableStream({ start(c) { c.enqueue(text("hello")); c.close() } }), { status: 200 }) +const lower = (h) => Object.fromEntries(Object.entries(h).map(([k, v]) => [k.toLowerCase(), v])) + +test("a throttle is waited out and tried again, as the Kiro IDE does, each try counted under one invocation", async () => { + pauses.length = 0 + const tries = [] + await withFetch((url, init) => { + tries.push(lower(init.headers)) + return tries.length === 1 ? new Response(limitedBody, { status: 429 }) : answered() + }, async () => { + const res = await generate(creds(), {}, msgReq) + expect(res.status).toBe(200) + expect(JSON.stringify(await res.json())).toContain("hello") + }) + expect(tries.length).toBe(2) + expect(tries.map((h) => h["amz-sdk-request"])).toEqual(["attempt=1; max=3", "attempt=2; max=3"]) + expect(tries.map((h) => h["x-amzn-kiro-attempt"])).toEqual(["1;max=3", "2;max=3"]) + expect(tries[1]["amz-sdk-invocation-id"]).toBe(tries[0]["amz-sdk-invocation-id"]) + // the IDE's throttling pause: 1s, 20% either way + expect(pauses.length).toBe(1) + expect(pauses[0]).toBeWithin(800, 1200.001) +}) + +test("a throttle that outlasts the IDE's tries is the plain 429, after 1s and 2s", async () => { + for (const reason of ["USER_REQUEST_RATE_EXCEEDED", "CREDIT_CONSUMPTION_RATE_EXCEEDED", "SERVICE_REQUEST_RATE_EXCEEDED"]) { + pauses.length = 0 + let n = 0 + await withFetch(() => (n++, new Response(JSON.stringify({ message: "Too many requests", reason }), { status: 429 })), async () => { + const res = await generate(creds(), {}, msgReq) + expect(res.status).toBe(429) + expect((await res.json()).error.message).toContain(reason) + }) + expect(n).toBe(TRIES) + expect(pauses.length).toBe(2) + expect(pauses[0]).toBeWithin(800, 1200.001) + expect(pauses[1]).toBeWithin(1600, 2400.001) + } +}) + +test("Kiro's own wait is the pause, and one past 20s goes back to magpie untried", async () => { + pauses.length = 0 + let n = 0 + const said = JSON.stringify({ message: "Too many requests", reason: "USER_REQUEST_RATE_EXCEEDED", retryAfterMilliseconds: 3500 }) + await withFetch(() => (n++ ? answered() : new Response(said, { status: 429 })), async () => { + expect((await generate(creds(), {}, msgReq)).status).toBe(200) + }) + expect(pauses).toEqual([3500]) + + pauses.length = 0 + n = 0 + await withFetch(() => (n++, new Response(limitedBody, { status: 429, headers: { "x-amzn-kiro-ratelimit-retry-after": "45000" } })), async () => { + const res = await generate(creds(), {}, msgReq) + expect(res.status).toBe(429) + expect(res.headers.get("Retry-After")).toBe("45") + }) + expect(n).toBe(1) + expect(pauses).toEqual([]) +}) + +test("a usage limit, a model's capacity or another 4xx is not tried again", async () => { + const cases = [ + [429, { message: "Monthly limit", reason: "MONTHLY_REQUEST_COUNT" }], + [429, { message: "Daily limit", reason: "DAILY_REQUEST_COUNT" }], + [429, { message: "busy", reason: "INSUFFICIENT_MODEL_CAPACITY" }], + [400, { message: "Improperly formed request." }], + ] + for (const [status, body] of cases) { + pauses.length = 0 + let n = 0 + await withFetch(() => (n++, new Response(JSON.stringify(body), { status })), async () => { + const res = await generate(creds(), {}, msgReq) + expect(res.status).not.toBe(200) + }) + expect(n).toBe(1) + expect(pauses).toEqual([]) + } +}) + +test("a request cancelled while a throttle is waited out ends at once, and isn't sent again", async () => { + let n = 0 + const ctl = new AbortController() + timing.sleep = (ms, signal) => { + queueMicrotask(() => ctl.abort()) + return realSleep(60_000, signal) + } + try { + await withFetch(() => (n++, new Response(limitedBody, { status: 429 })), async () => { + const t0 = Date.now() + await expect(generate(creds(), {}, msgReq, ctl.signal)).rejects.toThrow("cancelled") + expect(Date.now() - t0).toBeLessThan(5000) + }) + } finally { + timing.sleep = async (ms) => void pauses.push(ms) + } + expect(n).toBe(1) +}) diff --git a/packages/kiro/index.mjs b/packages/kiro/index.mjs index 733e206..7632765 100644 --- a/packages/kiro/index.mjs +++ b/packages/kiro/index.mjs @@ -1338,8 +1338,8 @@ function sessionOf(input, init) { // is the AWS SDK for JavaScript's: the SDK's user agent, m/N for the // endpoint the IDE names itself, then the IDE's own "KiroIDE // " with KAS/ and acp-client/kiro-ide, spaces made -// "-". Its retry budget is 3 tries at a conversation's start, said in -// amz-sdk-request and x-amzn-kiro-attempt; the plugin tries once. +// "-". Its retry budget is 3 tries, said in amz-sdk-request and +// x-amzn-kiro-attempt, which count up on each (see paced). const IDE_VERSION = "1.4.121" const IDE_KAS = "0.66.89" const IDE_NODE = "24.22.1" @@ -1350,11 +1350,11 @@ const IDE_SDK_UA = `aws-sdk-js/1.0.0 ua/2.1 os/${sdkPart(platform())}#${sdkPart( // sdkHeaders are the AWS SDK's headers on a call to Kiro's runtime, as the // Kiro IDE's client sends them: who is calling, and as which client. The // IDE names a Builder ID or Identity Center token's kind (SSO_OIDC) too. -function sdkHeaders(a) { +function sdkHeaders(a, attempt = 1, invocation = randomUUID()) { const h = { ...authHeaders(a), - "amz-sdk-invocation-id": randomUUID(), - "amz-sdk-request": "attempt=1; max=3", + "amz-sdk-invocation-id": invocation, + "amz-sdk-request": `attempt=${attempt}; max=${TRIES}`, "x-amz-user-agent": `aws-sdk-js/1.0.0 ${IDE_APP}`, "User-Agent": IDE_SDK_UA, "x-amzn-kiro-client-attribution": "kiro-ide", @@ -1363,16 +1363,77 @@ function sdkHeaders(a) { return h } -function sendKiro(a, body, signal) { +function sendKiro(a, body, signal, attempt = 1, invocation) { return fetch(runtime(a.region) + "/generateAssistantResponse", { method: "POST", - headers: { ...sdkHeaders(a), "x-amzn-kiro-attempt": "1;max=3", "x-amzn-codewhisperer-optout": "true", "x-amzn-kiro-agent-mode": "vibe", - "Content-Type": "application/json", Accept: "application/vnd.amazon.eventstream" }, + headers: { ...sdkHeaders(a, attempt, invocation), "x-amzn-kiro-attempt": `${attempt};max=${TRIES}`, "x-amzn-codewhisperer-optout": "true", + "x-amzn-kiro-agent-mode": "vibe", "Content-Type": "application/json", Accept: "application/vnd.amazon.eventstream" }, body, signal, }) } +// TRIES is the Kiro IDE's tries of one chat call (its QClientRetryStrategy, +// agent 1.1.787, QAf), the first included. +const TRIES = 3 +// PACE is the IDE's pause before the nth try after a throttle (its +// throttling backoff: 1s doubling, 20% either way, at most 20s), unless +// Kiro said how long (retryAfterMilliseconds and the like). +const PACE = { base: 1000, jitter: 0.2, max: 20_000 } +const paceOf = (n) => Math.min(PACE.max, PACE.base * 2 ** (n - 1)) * (1 - PACE.jitter + Math.random() * 2 * PACE.jitter) +// THROTTLES are the reasons the IDE takes a 429 for a throttle it waits +// out and tries again (its C1p and ServiceThrottleError): a throttle +// Kiro gives no reason for is one too. A daily, monthly or usage limit +// is not (usedUpSaid), nor is INSUFFICIENT_MODEL_CAPACITY. +const THROTTLES = new Set(["USER_REQUEST_RATE_EXCEEDED", "CREDIT_CONSUMPTION_RATE_EXCEEDED", "SERVICE_REQUEST_RATE_EXCEEDED"]) +function throttleSaid(text) { + let e = {} + try { + e = JSON.parse(text) ?? {} + } catch {} + if (e.reason) return THROTTLES.has(e.reason) + return !usedUpSaid(text) && !/INSUFFICIENT_MODEL_CAPACITY/.test(text) && /too many requests|throttl/i.test(text) +} + +// timing is how the plugin waits; tests make it instant. +const timing = { + sleep: (ms, signal) => + new Promise((resolve, reject) => { + if (signal?.aborted) return reject(aborted()) + const t = setTimeout(() => { + signal?.removeEventListener("abort", stop) + resolve() + }, ms) + const stop = () => { + clearTimeout(t) + reject(aborted()) + } + signal?.addEventListener("abort", stop, { once: true }) + }), +} + +// paced is sendKiro as the Kiro IDE sends a chat call: a 429 throttle is +// waited out and tried again, up to TRIES in all, each try said in +// amz-sdk-request and x-amzn-kiro-attempt under one invocation id. The +// IDE answers its own USER_REQUEST_RATE_EXCEEDED so ("Retrying in N +// seconds"), which is why a burst it rides out reached magpie's agent +// as a 429 (onemezao on Discord). A wait Kiro says is longer than PACE.max +// isn't held here: the 429 goes back with it, for magpie to rest the +// account. The answer of the last try is the answer. +async function paced(a, body, signal) { + const invocation = randomUUID() + for (let n = 1; ; n++) { + const res = await sendKiro(a, body, signal, n, invocation) + if (res.status !== 429 || n >= TRIES) return res + const text = (await res.text()).slice(0, 1 << 20) + const again = () => new Response(text, { status: res.status, statusText: res.statusText, headers: res.headers }) + if (!throttleSaid(text)) return again() + const said = saidWait(res.headers, text) + if (said > PACE.max) return again() + await timing.sleep(said ?? paceOf(n), signal) + } +} + // tooLongSaid is whether Kiro's words say the conversation is past the // model's window: its ValidationException "Input is too long." with reason // CONTENT_LENGTH_EXCEEDS_THRESHOLD, as an HTTP answer or as an exception @@ -1447,6 +1508,14 @@ const requestID = (headers) => headers.get("x-amzn-requestid") || headers.get("x // seconds or as a date. Unsaid, magpie keeps to its own pauses, but for // an account's request rate (USER_RATE_WAIT). function waitOf(headers, body) { + let w = saidWait(headers, body) + if (w === undefined && String(body ?? "").includes(USER_RATE)) w = USER_RATE_WAIT + return w +} + +// saidWait is the wait Kiro itself said, if any (waitOf, but none of +// magpie's own). +function saidWait(headers, body) { const ms = (v) => { const n = v == null || v === "" ? NaN : Number(v) return Number.isFinite(n) && n > 0 ? n : undefined @@ -1461,7 +1530,6 @@ function waitOf(headers, body) { const secs = ms(ra) w = secs !== undefined ? secs * 1000 : ms(Date.parse(ra) - Date.now()) } - if (w === undefined && String(body ?? "").includes(USER_RATE)) w = USER_RATE_WAIT return w } @@ -2125,7 +2193,7 @@ async function ask(creds, auth, req, model, budget, signal, conversation) { } let res try { - res = await sendKiro(a, await kiroBody(req, model, a.profile, budget, conversation), signal) + res = await paced(a, await kiroBody(req, model, a.profile, budget, conversation), signal) } catch (e) { if (e?.name === "AbortError") throw e return { status: 502, message: e.message } @@ -2138,7 +2206,7 @@ async function ask(creds, auth, req, model, budget, signal, conversation) { return { status: 502, message: e.message } } try { - res = await sendKiro(a, await kiroBody(req, model, a.profile, budget, conversation), signal) + res = await paced(a, await kiroBody(req, model, a.profile, budget, conversation), signal) } catch (e) { if (e?.name === "AbortError") throw e return { status: 502, message: e.message } @@ -2163,7 +2231,7 @@ async function ask(creds, auth, req, model, budget, signal, conversation) { if (tried.has(next.region)) return { status: 429, message: regionsUsedUp(next) + f.message, wait: f.wait } a = next try { - res = await sendKiro(a, await kiroBody(req, model, a.profile, budget, conversation), signal) + res = await paced(a, await kiroBody(req, model, a.profile, budget, conversation), signal) } catch (e) { if (e?.name === "AbortError") throw e return { status: 502, message: e.message } @@ -2735,4 +2803,4 @@ export async function KiroAuthPlugin({ client } = {}) { } // for tests -export const _internal = { generate, waitOf, refresh, usageOf, buildKiro, kiroBody, IMAGE_LIMIT, events, reply, failure, toolID, toolName, toolNames, thinking, nativeFields, listModels, contextFirst, configModel, runtimeModel, readCLI, readIDE, regionOf, planName, frames } +export const _internal = { generate, waitOf, timing, TRIES, refresh, usageOf, buildKiro, kiroBody, IMAGE_LIMIT, events, reply, failure, toolID, toolName, toolNames, thinking, nativeFields, listModels, contextFirst, configModel, runtimeModel, readCLI, readIDE, regionOf, planName, frames } diff --git a/packages/kiro/package.json b/packages/kiro/package.json index 326c6b2..25a44c2 100644 --- a/packages/kiro/package.json +++ b/packages/kiro/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-kiro-auth", - "version": "0.1.31", + "version": "0.1.32", "description": "Kiro subscriptions (Free, Pro, Pro+, Power) in OpenCode and magpie", "type": "module", "main": "./opencode.mjs", diff --git a/packages/kiro/region.test.mjs b/packages/kiro/region.test.mjs index 9a26a11..f128524 100644 --- a/packages/kiro/region.test.mjs +++ b/packages/kiro/region.test.mjs @@ -12,7 +12,13 @@ beforeAll(async () => { // no real sign-in is ever read if (![tmpdir(), realpathSync(tmpdir())].some((t) => homedir().startsWith(t))) throw new Error("run with HOME=$(mktemp -d) bun test") ;({ KiroAuthPlugin: plugin, _internal } = await import("./index.mjs")) + // a throttle's pauses (paced) are counted, not waited + sleep = _internal.timing.sleep + _internal.timing.sleep = async (ms) => void pauses.push(ms) }) +let sleep +const pauses = [] +afterAll(() => (_internal.timing.sleep = sleep)) const offline = async () => { throw new Error("no network in tests") } const real = globalThis.fetch globalThis.fetch = offline @@ -159,10 +165,13 @@ test("a region not enabled is asked for again only after PROBE_MS", async () => test("a rate limit isn't taken for credits used up: no other region is asked", async () => { const seen = kiro({ chat: { "us-east-1": THROTTLED } }) + pauses.length = 0 const r = await ask(await hooks(), auth()) expect(r.status).toBe(429) expect(r.wait).toBe("13") // Kiro's wait goes on as Retry-After - expect(seen.chat).toEqual([["us-east-1", US]]) + // waited out and tried again in the same region, as the Kiro IDE does + expect(seen.chat).toEqual([["us-east-1", US], ["us-east-1", US], ["us-east-1", US]]) + expect(pauses).toEqual([12500, 12500]) }) test("a region not enabled is shown so, pointed out near the end, and named when the other is used up", async () => {