diff --git a/packages/kiro/errors.test.mjs b/packages/kiro/errors.test.mjs index 84fe672..0619b17 100644 --- a/packages/kiro/errors.test.mjs +++ b/packages/kiro/errors.test.mjs @@ -240,17 +240,62 @@ test("Kiro's wait before asking again goes on as Retry-After", async () => { [{}, JSON.stringify({ message: "Too many requests", reason: "USER_REQUEST_RATE_EXCEEDED", retryAfterMilliseconds: 20000 }), "20"], [{ "retry-after": "7" }, limited, "7"], [{ "retry-after": new Date(Date.now() + 30_000).toUTCString() }, limited, null], - [{}, limited, null], - [{ "x-amzn-kiro-ratelimit-retry-after": "soon" }, limited, null], + [{}, limited, "30"], + [{ "x-amzn-kiro-ratelimit-retry-after": "soon" }, limited, "30"], + [{}, JSON.stringify({ message: "Too many requests", reason: "SERVICE_REQUEST_RATE_EXCEEDED" }), null], ] for (const [headers, body, want] of cases) { await withFetch(() => new Response(body, { status: 429, headers }), async () => { const res = await generate(creds(), {}, msgReq) expect(res.status).toBe(429) - expect((await res.json()).error.message).toBe(JSON.parse(body).message + " (USER_REQUEST_RATE_EXCEEDED)") + expect((await res.json()).error.message).toContain(JSON.parse(body).message + " (" + JSON.parse(body).reason + ")") const got = res.headers.get("Retry-After") if (headers["retry-after"]?.includes("GMT")) expect(Number(got)).toBeWithin(28, 32) else expect(got).toBe(want) }) } }) + +// onemezao on Discord: through pi, every request of one Kiro account was +// refused with Kiro's "Too many requests, please wait before trying +// again. (USER_REQUEST_RATE_EXCEEDED)", 42s each, while the Kiro IDE +// answered on the same account. The words said neither whose limit it +// was nor what to do, and with no wait said magpie asked the same +// account again at 1, 2 and 4s, the whole request each time. +test("an account's request rate says whose limit it is, what to do and the request ID", async () => { + const body = JSON.stringify({ message: "Too many requests, please wait before trying again.", reason: "USER_REQUEST_RATE_EXCEEDED" }) + await withFetch( + () => new Response(body, { status: 429, headers: { "x-amzn-requestid": "3f1c-req" } }), + async () => { + const res = await generate(creds(), {}, msgReq) + expect(res.status).toBe(429) + // past magpie's same-account retries (longestPause, 8s) + expect(Number(res.headers.get("Retry-After"))).toBeGreaterThan(8) + const b = await res.json() + expect(b.error.type).toBe("rate_limit_error") + const m = b.error.message + expect(m).toContain("Kiro is limiting how often this Kiro account sends requests") + expect(m).toContain("(USER_REQUEST_RATE_EXCEEDED)") + expect(m).toContain("Wait a minute") + expect(m).toContain("Kiro support") + expect(m).toContain("request ID 3f1c-req") + // magpie's creditWords would take it for money owed, never retried + expect(m).not.toMatch(/balance|credit|billing|payment|suspended/i) + }, + ) +}) + +test("an account's request rate in the stream is the same plain 429, with a wait", async () => { + for (const s of [true, false]) { + const res = await ask( + stream(frame({ ":message-type": "exception", ":exception-type": "ThrottlingException" }, + { message: "Too many requests, please wait before trying again.", reason: "USER_REQUEST_RATE_EXCEEDED" })), + s, + ) + expect(res.status).toBe(429) + expect(Number(res.headers.get("Retry-After"))).toBeGreaterThan(8) + const m = (await res.json()).error.message + expect(m).toMatch(/^rate limited: Kiro is limiting how often this Kiro account sends requests/) + expect(m).toContain("(USER_REQUEST_RATE_EXCEEDED)") + } +}) diff --git a/packages/kiro/index.mjs b/packages/kiro/index.mjs index c9416cc..3bd2522 100644 --- a/packages/kiro/index.mjs +++ b/packages/kiro/index.mjs @@ -1337,7 +1337,7 @@ const TOO_LONG = "input is too long for the model's context: " // failure is the status and message for an error Kiro answered with: // {"message": "...", "reason": "..."}. -function failure(status, body) { +function failure(status, body, id) { let msg = String(body ?? "").trim() try { const e = JSON.parse(body) @@ -1347,9 +1347,33 @@ function failure(status, body) { if (tooLongSaid(msg)) return { status: 400, message: TOO_LONG + msg } if (msg.includes("INSUFFICIENT_MODEL_CAPACITY")) return { status: 503, message: msg } if (msg.includes("MONTHLY_REQUEST_COUNT") || msg.includes("USAGE_LIMIT")) return { status: 429, message: "usage limit reached: " + msg } + if (msg.includes(USER_RATE)) return { status: 429, message: userRate(msg, id) } return { status, message: msg } } +// USER_RATE is the reason Kiro gives a 429 for one account's requests +// coming too often (the Kiro IDE's ThrottlingException reasons, agent +// 1.1.499: apart from the credit rate, the service's rate and the daily +// and monthly counts). Kiro's own words, "Too many requests, please wait +// before trying again.", say neither whose limit it is nor how long: +// onemezao on Discord had it on every request of one account through pi, +// 42s each, while the Kiro IDE answered on the same account. +const USER_RATE = "USER_REQUEST_RATE_EXCEEDED" +// USER_RATE_WAIT is the wait a USER_RATE refusal says when Kiro says none: +// longer than magpie's same-account retries (8s), so the request isn't +// sent again at 1, 2 and 4s, each try one more on the account's rate. +// Other Kiro relays pause 3 to 12s for it; one that outlived those +// wasn't going to clear in magpie's next few. +const USER_RATE_WAIT = 30_000 + +// userRate is a USER_RATE refusal in plain words: whose limit, what to +// do, and the request ID Kiro support asks for. +const userRate = (msg, id) => + `rate limited: Kiro is limiting how often this Kiro account sends requests (${msg}). ` + + "Wait a minute before sending again. If it keeps coming back while the Kiro app works on the same account, " + + "the limit is on the account, and Kiro support (app.kiro.dev) can look at it" + + (id ? `, with request ID ${id}.` : ".") + const ERROR_TYPES = { 400: "invalid_request_error", 401: "authentication_error", 402: "billing_error", 403: "permission_error", 404: "not_found_error", 413: "request_too_large", 429: "rate_limit_error", 503: "overloaded_error", 529: "overloaded_error" } const errorType = (status) => ERROR_TYPES[status] ?? "api_error" @@ -1363,12 +1387,17 @@ const errorResponse = (status, message, wait) => ...(wait > 0 ? { "Retry-After": String(Math.ceil(wait / 1000)) } : {}) }, }) +// requestID is the ID Kiro gave its answer, which its support asks for: +// what the Kiro IDE reads (x-amzn-requestid, else x-request-id). +const requestID = (headers) => headers.get("x-amzn-requestid") || headers.get("x-request-id") || "" + // waitOf is the milliseconds Kiro's refusal says to wait before asking // again, or undefined: what Kiro's own clients read. The Kiro IDE (agent // 1.1.499) reads the x-amzn-kiro-ratelimit-retry-after header and the // body's retryAfterMilliseconds, both in milliseconds; kiro-cli's AWS SDK // reads x-amz-retry-after, in milliseconds; and Retry-After is HTTP's, in -// seconds or as a date. Unsaid, magpie keeps to its own pauses. +// 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) { const ms = (v) => { const n = v == null || v === "" ? NaN : Number(v) @@ -1384,6 +1413,7 @@ 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 } @@ -1464,6 +1494,7 @@ function exception(kind, payload) { } catch {} let msg = e.message || e.Message || new TextDecoder().decode(payload).trim() if (e.reason) msg += ` (${e.reason})` + if (e.reason === USER_RATE) return userRate(msg) if (String(kind).toLowerCase().includes("throttl")) return "rate limited: " + msg return kind ? `${kind}: ${msg}` : msg } @@ -1680,7 +1711,7 @@ const QUOTA_WORDS = /quota|insufficient|balance|credit|billing|exceeded|rate.?li // error, so it never compacted (ergou0954_54426 on Discord: Kiro in a // group routed by intent, "超出上下文", the turn failed). const failedBefore = (text) => - tooLongSaid(text) ? errorResponse(400, TOO_LONG + text) : errorResponse(QUOTA_WORDS.test(text) ? 429 : 502, text) + tooLongSaid(text) ? errorResponse(400, TOO_LONG + text) : text.includes(USER_RATE) ? errorResponse(429, text, USER_RATE_WAIT) : 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. names gives back the caller's name of @@ -2068,7 +2099,7 @@ async function ask(creds, auth, req, model, budget, signal) { const tried = new Set() while (!res.ok && a.key && creds.spend) { const text = (await res.text()).slice(0, 1 << 20) - const f = { ...failure(res.status, text), wait: waitOf(res.headers, text) } + const f = { ...failure(res.status, text, requestID(res.headers)), wait: waitOf(res.headers, text) } if (!usedUpSaid(f.message)) return f tried.add(a.region) creds.spend(a.key, a.region) @@ -2090,7 +2121,7 @@ async function ask(creds, auth, req, model, budget, signal) { if (!res.ok) { // Kiro's own 401 is passed on, as the built-in did, the sign-in kept const text = (await res.text()).slice(0, 1 << 20) - return { ...failure(res.status, text), wait: waitOf(res.headers, text) } + return { ...failure(res.status, text, requestID(res.headers)), wait: waitOf(res.headers, text) } } return { res, a } } diff --git a/packages/kiro/package.json b/packages/kiro/package.json index 794ef3c..74c5486 100644 --- a/packages/kiro/package.json +++ b/packages/kiro/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-kiro-auth", - "version": "0.1.29", + "version": "0.1.30", "description": "Kiro subscriptions (Free, Pro, Pro+, Power) in OpenCode and magpie", "type": "module", "main": "./opencode.mjs",