diff --git a/packages/kiro/README.md b/packages/kiro/README.md index b25126b..5170069 100644 --- a/packages/kiro/README.md +++ b/packages/kiro/README.md @@ -249,6 +249,33 @@ its own with its count and when it lapses. Bonus windows are shown only. Kiro spends the plan's credits first, so a month used up while a bonus has credits left is shown only too, and the account isn't taken for spent. +With overage on (`overageConfiguration.overageStatus` `ENABLED`), the +month's window counts against the overage cap (`overageCap`), which is the +month's whole limit; with it off, against the plan's credits. + +### Identity Center credit regions + +An IAM Identity Center account has a profile, and its own month of credits +with its own overage cap, in each of Kiro's regions its organization enabled +(`us-east-1`, `eu-central-1`). The plugin lists the profiles in both and +keeps them with the account (`profiles`, by region; `profileArn` is the +first). A region with no profile is not enabled, and is asked for again at +most every 10 minutes, so one an admin enables is used without signing in +again. + +- A request goes to the first enabled region with credits left. When Kiro + answers that its credits are used up (`MONTHLY_REQUEST_COUNT`, + `USAGE_LIMIT`), the region rests till its reset (an hour when none is + known) and the request is sent again in the other. A rate limit is passed + on as it is. +- With every enabled region used up, the answer is a 429 naming them, and a + region not enabled, so magpie goes on to another account. +- `auth.usage` reads both regions: a window for each, shown only, and their + sum, which magpie weighs the account by. From 80% of the sum, a region + not enabled is pointed out in its text. + +Builder ID, Google, GitHub and API key sign-ins keep one region. + ## Not included - Switching between several accounts. OpenCode keeps one sign-in per diff --git a/packages/kiro/builderid.test.mjs b/packages/kiro/builderid.test.mjs index c813f40..b9c49b1 100644 --- a/packages/kiro/builderid.test.mjs +++ b/packages/kiro/builderid.test.mjs @@ -110,7 +110,8 @@ test("Identity Center still has its profile listed", async () => { const auth = { type: "oauth", access: "t", refresh: "r", expires: later(), method: "idc", loginProvider: "Enterprise", region: "us-east-1", profileArn: "", clientId: "c", clientSecret: "s", accountId: "dev@corp.example" } await h.provider.models({ models: { auto: {} } }, { auth }) - expect(seen.profiles).toBe(1) + // asked in each credit region (region.test.mjs) + expect(seen.profiles).toBe(2) expect(seen.listedWith).toEqual([IDC]) }) diff --git a/packages/kiro/index.mjs b/packages/kiro/index.mjs index 3ba9ffd..8f729ff 100644 --- a/packages/kiro/index.mjs +++ b/packages/kiro/index.mjs @@ -392,6 +392,51 @@ async function profileOf(c) { throw last ?? new Error("Kiro has no profile for this sign-in") } +// ---- an Identity Center account's credit regions ---------------------------------- +// +// An Identity Center account has a profile, and a month's credits, in each +// of Kiro's regions its organization enabled for it: each region's credits +// are its own, with its own overage cap. A request goes to one region; once +// that region's credits are used up the account goes on in the other, and +// only with every enabled region used up is it used up for magpie. +const CREDIT_REGIONS = ["us-east-1", "eu-central-1"] +const twoRegions = (c) => c.method === "idc" && !c.builderID +const SPENT_MS = 60 * 60 * 1000 // a region Kiro said is used up, with no reset known, rests this long +const PROBE_MS = 10 * 60 * 1000 // a region with no profile is asked for one again at most this often +const REMIND_SHARE = 80 // the share at which a region not enabled is pointed out + +// regionKey names an account for its credit regions: kiro-cli's or the +// IDE's by where it is read, one signed in here by its client and name, +// which outlive its tokens +const regionKey = (auth) => (auth?.source ? "source:" + auth.source : "own:" + (auth?.clientId ?? "") + ":" + (auth?.accountId ?? "")) +const sameProfiles = (a, b) => { + const ka = Object.keys(a ?? {}), kb = Object.keys(b ?? {}) + return ka.length === kb.length && ka.every((k) => a[k] === b?.[k]) +} +const firstProfile = (profiles) => CREDIT_REGIONS.map((r) => profiles?.[r]).find(Boolean) ?? Object.values(profiles ?? {})[0] ?? "" + +// profilesOf is every profile Kiro lists for a sign-in, by its region. +async function profilesOf(c) { + const found = {} + let last + for (const region of CREDIT_REGIONS) { + try { + const out = await managementCall(region, { token: c.access, tokenType: tokenType(c) }, "List-Available-Profiles", null, {}) + for (const p of out?.profiles ?? []) if (p?.arn) found[regionOf(p.arn, region)] ??= p.arn + } catch (e) { + // a Builder ID sign-in the token didn't say was one + if (c.method === "idc" && e?.status === 403 && e.body.includes("Builder ID")) return { [regionOf(BUILDER_ID_PROFILE)]: BUILDER_ID_PROFILE } + last = e + } + } + if (!Object.keys(found).length) throw last ?? new Error("Kiro has no profile for this sign-in") + return found +} + +// usedUpSaid is whether Kiro's words say the credits are used up, rather +// than that it is asked too fast. +const usedUpSaid = (msg) => /MONTHLY_REQUEST_COUNT|USAGE_LIMIT/.test(String(msg ?? "")) + // usageLimits is Get-Usage-Limits: the plan, the account's email, credits. function usageLimits(a, email) { // an API key's, as kiro-cli asks for it: no profile, no email asked @@ -426,10 +471,18 @@ function goG(x) { // reset. They are shown only (aside). Kiro spends the plan's credits // first, then these, so a month used up while a bonus has credits left // is set aside too, and the account isn't taken for spent. +// +// With overage on, Kiro goes on past the plan's credits up to the overage +// cap, which is the month's whole limit (a 2000-credit plan used 4104, of +// them 2104 overage, under a cap of 10000), so the month's window counts +// against the cap. With overage off the cap Kiro still sends means nothing. +const count = (used, limit) => used.toFixed(2).replace(/0+$/, "").replace(/\.$/, "") + " / " + goG(limit) +const overageOn = (l) => + String(l?.overageConfiguration?.overageStatus ?? "").toUpperCase() === "ENABLED" || l?.overageConfiguration?.overageEnabled === true function usageOf(l, now = Date.now()) { const at = (secs) => (secs > 0 ? new Date(Math.trunc(secs) * 1000).toISOString() : undefined) - const count = (used, limit) => used.toFixed(2).replace(/0+$/, "").replace(/\.$/, "") + " / " + goG(limit) const num = (x) => (typeof x === "number" && Number.isFinite(x) ? x : 0) + const overage = overageOn(l) const windows = [] for (const u of l?.usageBreakdownList ?? []) { const t = u?.freeTrialInfo @@ -446,7 +499,8 @@ function usageOf(l, now = Date.now()) { bonuses.push({ name: b?.displayName || "Bonus credits", used: (100 * used) / limit, display: count(used, limit), amount: used, limit, unit: "credits", ...(expires > 0 && left > 0 ? { runsOutAt: at(expires), runsOut: left } : {}), aside: true }) } - const used = num(u?.currentUsageWithPrecision), limit = num(u?.usageLimitWithPrecision) + const used = num(u?.currentUsageWithPrecision) + const limit = Math.max(num(u?.usageLimitWithPrecision), overage ? num(u?.overageCapWithPrecision) || num(u?.overageCap) : 0) if (limit > 0) { const reset = num(u?.nextDateReset) || num(l?.nextDateReset) const carried = used >= limit && bonuses.some((b) => b.amount < b.limit) @@ -459,6 +513,57 @@ function usageOf(l, now = Date.now()) { return { plan: planName(l?.subscriptionInfo?.subscriptionTitle), ...(typeof email === "string" && email ? { user: email } : {}), windows } } +// regionsUsage is an Identity Center account's credits from each region's +// read (reads: { region, l } read, { region, error } not, { region, +// missing } with no profile, not enabled): each region's month shown only, +// and their sum the window magpie weighs the account by, used up only when +// every region read is. A free trial or bonus credits are the first read +// region's. regions says, of each region read, whether it is used up and +// when it resets. Regions read come first, then those that couldn't be read, +// then those not enabled: a card that shows only the first few windows then +// shows the credits an account has. +function regionsUsage(reads, now = Date.now()) { + const shown = [] + const failed = [] + const off = [] + const regions = [] + const missing = [] + let amount = 0, limit = 0, resets = 0, first, monthName + for (const r of reads) { + const name = `Credits (${r.region})` + if (r.error) { + failed.push({ name, display: "couldn't be read", aside: true }) + continue + } + if (!r.l) { + missing.push(r.region) + off.push({ name, display: "not enabled", aside: true }) + continue + } + const u = usageOf(r.l, now) + first ??= u + const month = u.windows.find((w) => w.span) + if (!month) continue + monthName ??= month.name + amount += month.amount + limit += month.limit + const at = Date.parse(month.resetsAt ?? "") + if (at > 0 && (!resets || at < resets)) resets = at + shown.push({ ...month, name: `${month.name} (${r.region})`, aside: true }) + regions.push({ region: r.region, full: month.amount >= month.limit, resetsAt: at > 0 ? at : 0 }) + } + const windows = [] + if (limit > 0) { + let display = count(amount, limit) + if (missing.length && (100 * amount) / limit >= REMIND_SHARE) display += ` ยท ${missing.join(", ")} not enabled: ask your admin to enable it` + windows.push({ name: monthName, used: (100 * amount) / limit, ...(resets ? { resetsAt: new Date(resets).toISOString() } : {}), + display, amount, limit, unit: "credits", span: 30 * 24 * 3600 }) + } + windows.push(...shown, ...failed, ...off, ...(first?.windows ?? []).filter((w) => !w.span)) + const { windows: _w, ...who } = first ?? {} + return { usage: { ...who, windows }, regions, missing } +} + // ---- the account, as the plugin holds it ------------------------------------------- // credOf is the sign-in a stored auth names: a key, one signed in here, or @@ -472,7 +577,8 @@ async function credOf(auth) { if (!auth.access) return null return { access: auth.access, refresh: auth.refresh ?? "", expires: auth.expires ?? 0, method: auth.method || "social", region: auth.region || "us-east-1", profile: auth.profileArn ?? "", clientId: auth.clientId ?? "", clientSecret: auth.clientSecret ?? "", - builderID: isBuilderID(auth.loginProvider), own: true } + builderID: isBuilderID(auth.loginProvider), own: true, + ...(auth.profiles && typeof auth.profiles === "object" && !Array.isArray(auth.profiles) ? { profiles: { ...auth.profiles } } : {}) } } // Account holds the credentials in use, refreshing them when near their @@ -515,7 +621,16 @@ function account(client) { if (!c.own || !client?.auth?.set) return const { type: _t, ...rest } = auth await client.auth.set({ path: { id: ID }, body: { ...rest, type: "oauth", access: c.access, refresh: c.refresh, expires: c.expires, - profileArn: c.profile, region: c.region, ...idFields(auth) } }).catch(() => {}) + profileArn: c.profile, region: c.region, ...(c.profiles ? { profiles: c.profiles } : {}), ...idFields(auth) } }).catch(() => {}) + } + // each account's credit regions (twoRegions), by regionKey: their + // profiles, when they were last asked for, and the regions used up till + // when. One plugin serves every account, so this is kept by account. + const regionStates = new Map() + const stateOf = (key) => { + let st = regionStates.get(key) + if (!st) regionStates.set(key, (st = { profiles: {}, probed: 0, spent: {}, builderID: false })) + return st } const creds = (auth, stale = false) => locked(async () => { @@ -545,6 +660,29 @@ function account(client) { saved = true } } + const key = regionKey(auth) + const st = stateOf(key) + if (twoRegions(c) && !st.builderID) { + c.profiles = { ...st.profiles, ...c.profiles } + if (c.profile) c.profiles[regionOf(c.profile, c.region)] ??= c.profile + if (CREDIT_REGIONS.some((r) => !c.profiles[r]) && Date.now() - st.probed > PROBE_MS) { + st.probed = Date.now() + try { + const found = await profilesOf(c) + if (Object.values(found).includes(BUILDER_ID_PROFILE)) { + st.builderID = true + c.profile ||= BUILDER_ID_PROFILE + } else c.profiles = { ...c.profiles, ...found } + } catch {} + } + st.profiles = c.profiles + if (st.builderID) delete c.profiles + if (!c.profile) c.profile = firstProfile(c.profiles) + if (!saved && c.own && c.profile && (st.builderID ? !auth?.profileArn : !sameProfiles(c.profiles, auth?.profiles))) { + await save(auth, c) + saved = true + } + } if (c.method === "apikey") { if (!c.asked) { c.profile = await keyProfile(c) @@ -566,8 +704,22 @@ function account(client) { // kiro-cli names no profile in an API key's calls, even one GetProfile // found; the profile only says the key's region const profile = c.method === "apikey" ? "" : c.profile - return { token: c.access, tokenType: tokenType(c), profile, region: regionOf(c.profile, c.region) } + const a = { token: c.access, tokenType: tokenType(c), profile, region: regionOf(c.profile, c.region) } + if (!twoRegions(c) || st.builderID || !c.profiles) return a + // the first enabled region with credits left, in CREDIT_REGIONS' order + const now = Date.now() + const open = CREDIT_REGIONS.filter((r) => c.profiles[r]) + const pick = open.find((r) => !(st.spent[r] > now)) + if (pick) Object.assign(a, { region: pick, profile: c.profiles[pick] }) + return { ...a, key, profiles: { ...c.profiles }, open } }) + // spend marks a region of an account used up till until (0: SPENT_MS from + // now), or, with until -1, as having credits again + creds.spend = (key, region, until = 0) => { + const st = stateOf(key) + if (until < 0) delete st.spent[region] + else st.spent[region] = until > Date.now() ? until : Date.now() + SPENT_MS + } // renew is auth.refresh's: a sign-in kept here (not kiro-cli's or the // IDE's, which their owners keep) renewed under the same lock as the // requests' refresh, so the two never spend one refresh token. It saves @@ -1903,6 +2055,31 @@ async function ask(creds, auth, req, model, budget, signal) { return { status: 502, message: e.message } } } + // an Identity Center account whose region's credits are used up goes on + // in its other enabled region, once each; with none left it is used up + // for magpie, and says which regions are and which aren't enabled + 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) } + if (!usedUpSaid(f.message)) return f + tried.add(a.region) + creds.spend(a.key, a.region) + let next + try { + next = await creds(auth) + } catch (e) { + return { status: 401, message: e.message } + } + 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), signal) + } catch (e) { + if (e?.name === "AbortError") throw e + return { status: 502, message: e.message } + } + } 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) @@ -1911,6 +2088,13 @@ async function ask(creds, auth, req, model, budget, signal) { return { res, a } } +// regionsUsedUp heads the 429 of an account with every enabled region used +// up: the regions, and those not enabled, which an admin may enable. +function regionsUsedUp(a) { + const off = CREDIT_REGIONS.filter((r) => !a.open?.includes(r)) + return `Kiro credits used up in ${(a.open ?? []).join(", ")}` + (off.length ? `; ${off.join(", ")} not enabled: ask your admin to enable it` : "") + ". " +} + const aborted = () => Object.assign(new Error("the request was cancelled"), { name: "AbortError" }) // searching is events for a request offering the hosted web search, over @@ -2387,7 +2571,23 @@ export async function KiroAuthPlugin({ client } = {}) { const auth = await getAuth() if (!(auth?.type === "api" && auth.key) && auth?.type !== "oauth") return { error: "not signed in", signIn: "kept" } try { - const u = usageOf(await usageLimits(await creds(auth), true)) + const a = await creds(auth) + let u + if (a.key) { + // every credit region, the ones not enabled told as such + const reads = await Promise.all(CREDIT_REGIONS.map(async (region) => { + if (!a.profiles[region]) return { region } + try { + return { region, l: await usageLimits({ ...a, region, profile: a.profiles[region] }, true) } + } catch (error) { + return { region, error } + } + })) + if (reads.every((r) => r.error || !r.l)) throw reads.find((r) => r.error)?.error ?? new Error("Kiro read no credits") + const got = regionsUsage(reads) + for (const r of got.regions) creds.spend(a.key, r.region, r.full ? r.resetsAt || 0 : -1) + u = got.usage + } else u = usageOf(await usageLimits(a, true)) // named as the account is if (u.user && auth.type === "oauth" && !auth.source) u.user = nameOf(u.user, auth.loginProvider) return { ...u, signIn: "renewed" } diff --git a/packages/kiro/package.json b/packages/kiro/package.json index 2d165c1..3a313b3 100644 --- a/packages/kiro/package.json +++ b/packages/kiro/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-kiro-auth", - "version": "0.1.27", + "version": "0.1.28", "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 new file mode 100644 index 0000000..9a26a11 --- /dev/null +++ b/packages/kiro/region.test.mjs @@ -0,0 +1,212 @@ +// An Identity Center account's two credit regions: a profile and a month's +// credits in each of us-east-1 and eu-central-1, each with its own overage +// cap. A request goes on in the other region once one is used up; only both +// used up is a 429 for magpie. A region with no profile is not enabled. +import { test, expect, afterAll, beforeAll, afterEach } from "bun:test" +import { homedir, tmpdir } from "node:os" +import { realpathSync } from "node:fs" + +let plugin, _internal +beforeAll(async () => { + // Bun reads HOME once, at start: run as HOME=$(mktemp -d) bun test, so + // 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")) +}) +const offline = async () => { throw new Error("no network in tests") } +const real = globalThis.fetch +globalThis.fetch = offline +afterAll(() => (globalThis.fetch = real)) +afterEach(() => (globalThis.fetch = offline)) + +const US = "arn:aws:codewhisperer:us-east-1:333333333333:profile/US" +const EU = "arn:aws:codewhisperer:eu-central-1:333333333333:profile/EU" +const RESET = 1796083200 +const later = () => Date.now() + 60 * 60_000 +const auth = () => ({ type: "oauth", access: "t", refresh: "r", expires: later(), method: "idc", loginProvider: "Enterprise", + region: "us-east-1", profileArn: "", clientId: "c", clientSecret: "s", accountId: "dev@corp.example (IAM Identity Center)" }) + +// limits is Get-Usage-Limits' answer for a month of used credits, a plan +// of 2000 with overage on up to 10000, as Kiro answers it +const limits = (used, { overage = true } = {}) => ({ + subscriptionInfo: { subscriptionTitle: "KIRO POWER" }, userInfo: { email: "dev@corp.example" }, nextDateReset: RESET, + overageConfiguration: { overageStatus: overage ? "ENABLED" : "DISABLED" }, + usageBreakdownList: [{ displayName: "Credit", displayNamePlural: "Credits", currentUsageWithPrecision: used, usageLimitWithPrecision: 2000, + usageLimit: 2000, overageCap: 10000, overageCapWithPrecision: 10000, currentOverages: Math.max(0, used - 2000), nextDateReset: RESET }], +}) +const USED_UP = { status: 402, body: { message: "You have reached the limit.", reason: "MONTHLY_REQUEST_COUNT" } } +const THROTTLED = { status: 429, body: { message: "Too many requests, please wait." }, headers: { "x-amzn-kiro-ratelimit-retry-after": "12500" } } +const STOP = { status: 500, body: { message: "stop here" } } +const MAX_ASKS = 6 + +// kiro is Kiro's API with the profiles each region lists, each region's +// credits, and how each region's runtime answers a chat +function kiro({ profiles = { "us-east-1": [US], "eu-central-1": [EU] }, usage = {}, chat = {} } = {}) { + const seen = { profiles: 0, usage: [], chat: [] } + globalThis.fetch = async (input, init = {}) => { + const url = new URL(String(input)) + const region = url.host.split(".")[1] + if (url.pathname === "/List-Available-Profiles") { + seen.profiles++ + return Response.json({ profiles: (profiles[region] ?? []).map((arn) => ({ arn })) }) + } + if (url.pathname === "/Get-Usage-Limits") { + seen.usage.push([region, url.searchParams.get("profileArn")]) + return Response.json(usage[region] ?? limits(0)) + } + if (url.pathname === "/generateAssistantResponse") { + // a region loop that doesn't end fails here, not on a timeout + if (seen.chat.length >= MAX_ASKS) throw new Error(`Kiro asked more than ${MAX_ASKS} times for one request`) + seen.chat.push([region, JSON.parse(init.body).profileArn]) + const r = chat[region] ?? STOP + return new Response(JSON.stringify(r.body), { status: r.status, headers: r.headers }) + } + throw new Error("unexpected " + url) + } + return seen +} + +const hooks = (saves = []) => plugin({ client: { auth: { set: async (r) => void saves.push(r.body) } } }) +const ask = async (h, a) => { + const l = await h.auth.loader(async () => a) + const res = await l.fetch("https://kiro.invalid/v1/messages", { method: "POST", + body: JSON.stringify({ model: "claude-sonnet-5.5", messages: [{ role: "user", content: "hi" }] }) }) + return { status: res.status, wait: res.headers.get("Retry-After"), message: (await res.json())?.error?.message ?? "" } +} + +test("overage on counts the month against the overage cap", () => { + const u = _internal.usageOf(limits(4104.73)) + expect(u.windows[0]).toMatchObject({ name: "Credits", amount: 4104.73, limit: 10000, display: "4104.73 / 10000" }) + expect(u.windows[0].used).toBeCloseTo(41.0473) + // and off, the plan's credits alone + expect(_internal.usageOf(limits(1500, { overage: false })).windows[0]).toMatchObject({ limit: 2000, used: 75 }) +}) + +test("both regions' profiles are found and kept with the account", async () => { + const seen = kiro() + const saves = [] + const h = await hooks(saves) + await h.auth.usage(async () => auth()) + expect(seen.profiles).toBe(2) + expect(saves.at(-1)).toMatchObject({ profileArn: US, profiles: { "us-east-1": US, "eu-central-1": EU } }) + // kept, they aren't asked for again + seen.profiles = 0 + const kept = { ...auth(), profileArn: US, profiles: { "us-east-1": US, "eu-central-1": EU } } + await (await hooks()).auth.usage(async () => kept) + expect(seen.profiles).toBe(0) +}) + +test("each region's credits are shown, and their sum is the account's", async () => { + const seen = kiro({ usage: { "us-east-1": limits(10000), "eu-central-1": limits(2500) } }) + const u = await (await hooks()).auth.usage(async () => auth()) + expect(seen.usage).toEqual(expect.arrayContaining([["us-east-1", US], ["eu-central-1", EU]])) + expect(u.user).toBe("dev@corp.example (IAM Identity Center)") + const [sum, us, eu] = u.windows + expect(sum).toMatchObject({ name: "Credits", amount: 12500, limit: 20000, used: 62.5, resetsAt: new Date(RESET * 1000).toISOString() }) + expect(sum.aside).toBeUndefined() + expect(us).toMatchObject({ name: "Credits (us-east-1)", used: 100, aside: true }) + expect(eu).toMatchObject({ name: "Credits (eu-central-1)", used: 25, aside: true }) +}) + +test("a region used up per the usage read is skipped by the next request", async () => { + const seen = kiro({ usage: { "us-east-1": limits(10000), "eu-central-1": limits(100) } }) + const h = await hooks() + await h.auth.usage(async () => auth()) + await ask(h, auth()) + expect(seen.chat).toEqual([["eu-central-1", EU]]) +}) + +test("a region Kiro says is used up goes on in the other, and stays there", async () => { + const seen = kiro({ chat: { "us-east-1": USED_UP } }) + const h = await hooks() + const r = await ask(h, auth()) + expect(r.status).toBe(500) // the other region's own answer + expect(seen.chat).toEqual([["us-east-1", US], ["eu-central-1", EU]]) + seen.chat.length = 0 + await ask(h, auth()) + expect(seen.chat).toEqual([["eu-central-1", EU]]) +}) + +test("both regions used up is a 429 that says so, with Kiro's wait", async () => { + const seen = kiro({ chat: { "us-east-1": USED_UP, "eu-central-1": { ...USED_UP, headers: { "retry-after": "60" } } } }) + const r = await ask(await hooks(), auth()) + expect(r.status).toBe(429) + expect(r.wait).toBe("60") + expect(r.message).toContain("Kiro credits used up in us-east-1, eu-central-1") + expect(seen.chat).toEqual([["us-east-1", US], ["eu-central-1", EU]]) +}) + +test("every region used up ends the request at once, however often it is asked", async () => { + const seen = kiro({ chat: { "us-east-1": USED_UP, "eu-central-1": USED_UP } }) + const h = await hooks() + for (let i = 0; i < 3; i++) { + seen.chat.length = 0 + const r = await ask(h, auth()) + expect(r.status).toBe(429) + expect(seen.chat.length).toBeLessThanOrEqual(2) + } +}) + +test("a region not enabled is asked for again only after PROBE_MS", async () => { + const seen = kiro({ profiles: { "us-east-1": [US] } }) + const h = await hooks() + await ask(h, auth()) + expect(seen.profiles).toBe(2) + await ask(h, auth()) + await ask(h, auth()) + expect(seen.profiles).toBe(2) +}) + +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 } }) + 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]]) +}) + +test("a region not enabled is shown so, pointed out near the end, and named when the other is used up", async () => { + kiro({ profiles: { "us-east-1": [US] }, usage: { "us-east-1": limits(8500) } }) + const u = await (await hooks()).auth.usage(async () => auth()) + expect(u.windows[0]).toMatchObject({ amount: 8500, limit: 10000 }) + expect(u.windows[0].display).toContain("eu-central-1 not enabled: ask your admin to enable it") + expect(u.windows[2]).toMatchObject({ name: "Credits (eu-central-1)", display: "not enabled", aside: true }) + + const seen = kiro({ profiles: { "us-east-1": [US] }, chat: { "us-east-1": USED_UP } }) + const r = await ask(await hooks(), auth()) + expect(r.status).toBe(429) + expect(r.message).toContain("Kiro credits used up in us-east-1; eu-central-1 not enabled: ask your admin to enable it") + expect(seen.chat).toEqual([["us-east-1", US]]) +}) + +test("the region enabled comes before the one not enabled, whichever it is", async () => { + kiro({ profiles: { "eu-central-1": [EU] }, usage: { "eu-central-1": limits(2744.89) } }) + const u = await (await hooks()).auth.usage(async () => auth()) + expect(u.windows.map((w) => [w.name, w.display])).toEqual([ + ["Credits", "2744.89 / 10000"], + ["Credits (eu-central-1)", "2744.89 / 10000"], + ["Credits (us-east-1)", "not enabled"], + ]) +}) + +test("a region enabled later is found and used", async () => { + const seen = kiro({ profiles: { "us-east-1": [US] } }) + const saves = [] + const h = await hooks(saves) + await h.auth.usage(async () => auth()) + expect(saves.at(-1).profiles).toEqual({ "us-east-1": US }) + // enabled by the admin; a new plugin asks again at once + kiro() + await (await hooks(saves)).auth.usage(async () => ({ ...auth(), profileArn: US, profiles: { "us-east-1": US } })) + expect(saves.at(-1).profiles).toEqual({ "us-east-1": US, "eu-central-1": EU }) +}) + +test("a social sign-in keeps one region", async () => { + const seen = kiro() + const a = { type: "oauth", access: "t", refresh: "r", expires: later(), method: "social", loginProvider: "Github", region: "us-east-1", + profileArn: US, accountId: "me@example.com (GitHub)" } + const u = await (await hooks()).auth.usage(async () => a) + expect(seen.profiles).toBe(0) + expect(seen.usage).toEqual([["us-east-1", US]]) + expect(u.windows.map((w) => w.name)).toEqual(["Credits"]) +})