kiro 0.1.37: switches to pin an Identity Center account to one credit region (#964)

Two switches in the provider's editor, "Use us-east-1 only" and "Use
eu-central-1 only" (us-east-1-only, eu-central-1-only), pin an Identity
Center account to one credit region. They are read with input.magpie.option
at each request.
- With one on, every request goes to that region. If that region is not
  enabled or is used up, the answer is a 429 naming the switch, and the
  other region is never tried.
- auth.usage counts only the pinned region. If the pinned region is not
  enabled or couldn't be read, a used-up window gives the reason, so the
  account is left out of routing.
- The not-enabled reminder names only the pinned region.
- Both off, or both on, is the default.

Run at 38c18529 merged with main 7153e59d (Windows 11, Bun 1.4.2, temp
HOME and USERPROFILE):
- bun test packages/kiro: 178 pass, 8 fail. The 8 are the EBUSY cleanup
  reds that fail the same on main on Windows (#966).
- bun scripts/check.mjs kiro: ok.
- The review's two probes, the reminder under a pin and an unenabled
  pinned region, now give the right card.
Broken by hand: dropping the pinned-reminder filter and the unenabled-pin
window turns 3 region tests red.
Not tried: a real Identity Center account in both regions, and the
switches in magpie's editor.

Co-authored-by: caozhenyuan <caozhenyuan@users.noreply.github.com>
This commit is contained in:
caozhenyuan
2026-11-11 11:35:34 +08:00
committed by GitHub
co-authored by caozhenyuan
parent 7153e59d78
commit d91f8e31a0
4 changed files with 229 additions and 11 deletions
+22
View File
@@ -297,6 +297,28 @@ again.
Builder ID, Google, GitHub and API key sign-ins keep one region.
Two switches in the provider's editor, "Use us-east-1 only" and "Use
eu-central-1 only" (`us-east-1-only`, `eu-central-1-only`), pin an Identity
Center account to one region. They are read at each request, so a change
needs no restart:
- With one on, every request goes to that region and none to the other,
whatever credits the other has. The region not enabled for the account, or
used up, is a 429 naming the switch, and magpie goes on to another
account. The other region is never tried.
- `auth.usage` counts the pinned region alone in the window magpie weighs
the account by; the other region's windows are shown only. So the account
is used up for magpie when the pinned region is, not when both are.
- Both off, or both on, is the default: the regions in turn.
Credits past a region's plan are overage, billed at $0.04 each: twice what
a plan's credits cost (a Power plan is $200 for 10000, $0.02 each), and a
plan's credits do not roll over to the next month. So when one region is
already in its overage and the other still has plan credits, pinning the
account to the other spends the cheaper credits first. Left on the first,
the account goes on into overage while the other region's plan credits
expire unused.
## Not included
- Switching between several accounts. OpenCode keeps one sign-in per
+75 -9
View File
@@ -423,6 +423,21 @@ async function profileOf(c) {
// 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
// magpie's switches for the provider (auth.options), one for each credit
// region: with one on, an Identity Center account uses that region alone.
// They are read at each request, so a change needs no restart. A request is
// never sent to the other region: this one not enabled for the account, or
// used up, is a 429 for magpie to go on to another account. Both off is the
// default, the regions in turn; both on says nothing, and is the default too.
const onlyOption = (region) => region + "-only"
const onlyRegion = (magpie) => {
try {
const on = CREDIT_REGIONS.filter((r) => magpie?.option?.(ID, onlyOption(r)) === true)
return on.length === 1 ? on[0] : ""
} catch {
return ""
}
}
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
@@ -571,7 +586,7 @@ const usageOf = (l, now = Date.now()) => readUsage(l, now).usage
// 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()) {
function regionsUsage(reads, now = Date.now(), only = "") {
const shown = []
const failed = []
const off = []
@@ -593,9 +608,20 @@ function regionsUsage(reads, now = Date.now()) {
first ??= u
if (!stop) continue
const over = stop !== plan
anyOver ||= over
allOver &&= over
// an account set to one region counts that region alone, the other
// shown only: its credits are not the account's to spend
const counted = !only || r.region === only
if (counted) {
anyOver ||= over
allOver &&= over
}
monthName ??= plan.name
if (!counted) {
shown.push({ ...plan, name: `${plan.name} (${r.region})`, aside: true })
if (over) shown.push({ ...stop, name: `${stop.name} (${r.region})`, aside: true })
regions.push({ region: r.region, full: stop.amount >= stop.limit, resetsAt: Date.parse(stop.resetsAt ?? "") > 0 ? Date.parse(stop.resetsAt) : 0 })
continue
}
amount += stop.amount
limit += stop.limit
inPlan += plan.amount
@@ -613,9 +639,19 @@ function regionsUsage(reads, now = Date.now()) {
windows.push({ name: monthName, used: (100 * inPlan) / ofPlan, ...resetsAt, display: count(inPlan, ofPlan), amount: inPlan, limit: ofPlan,
unit: "credits", span: 30 * 24 * 3600, aside: true })
let display = count(amount, limit)
if (missing.length && (100 * amount) / limit >= REMIND_SHARE) display += ` · ${missing.join(", ")} not enabled: ask your admin to enable it`
// a region the user said not to use is not asked to be enabled
const ask = only ? missing.filter((r) => r === only) : missing
if (ask.length && (100 * amount) / limit >= REMIND_SHARE) display += ` · ${ask.join(", ")} not enabled: ask your admin to enable it`
windows.push({ name: allOver ? "Overage" : monthName, used: (100 * amount) / limit, ...resetsAt,
display, amount, limit, unit: "credits", span: 30 * 24 * 3600 })
} else if (only) {
// the region the account is pinned to is not enabled or couldn't be read:
// no window to weigh, so magpie would go on asking an account every
// request of which is a 429. A window that is used up leaves it out of
// routing, and says why.
const why = reads.find((r) => r.region === only)?.error ? `${only} couldn't be read` : `${only} is not enabled`
windows.push({ name: monthName ?? "Credits", used: 100, display: `${why}, and the ${onlyOption(only)} switch is on: no other region is used`,
span: 30 * 24 * 3600 })
}
windows.push(...shown, ...failed, ...off, ...(first?.windows ?? []).filter((w) => !w.span))
const { windows: _w, ...who } = first ?? {}
@@ -647,7 +683,7 @@ async function credOf(auth) {
// sign-in read with that token (its save failed, or magpie hasn't yet
// saved what auth.refresh gave) goes on with the newer one rather than
// spending the replaced refresh token again.
function account(client) {
function account(client, magpie) {
let held = null // { id, c }
const after = new Map()
const newest = (c) => {
@@ -766,9 +802,13 @@ function account(client) {
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 only = onlyRegion(magpie)
const open = CREDIT_REGIONS.filter((r) => c.profiles[r] && (!only || r === only))
const pick = open.find((r) => !(st.spent[r] > now))
if (pick) Object.assign(a, { region: pick, profile: c.profiles[pick] })
// pinned to a region this account lacks, or has used up: no region to
// send to, which ask() answers as every region used up
else if (only) return { ...a, region: only, profile: "", key, profiles: { ...c.profiles }, open, pinned: only }
return { ...a, key, profiles: { ...c.profiles }, open }
})
// spend marks a region of an account used up till until (0: SPENT_MS from
@@ -2594,6 +2634,7 @@ async function ask(creds, auth, req, model, budget, signal, conversation) {
} catch (e) {
return { status: 401, message: e.message }
}
if (a.pinned) return { status: 429, message: pinnedUnavailable(a) }
let res
try {
res = await paced(a, await kiroBody(req, model, a.profile, budget, conversation), signal)
@@ -2631,6 +2672,7 @@ async function ask(creds, auth, req, model, budget, signal, conversation) {
} catch (e) {
return { status: 401, message: e.message }
}
if (next.pinned) return { status: 429, message: pinnedUnavailable(next) + f.message, wait: f.wait }
if (tried.has(next.region)) return { status: 429, message: regionsUsedUp(next) + f.message, wait: f.wait }
a = next
try {
@@ -2648,6 +2690,16 @@ async function ask(creds, auth, req, model, budget, signal, conversation) {
return { res, a }
}
// pinnedUnavailable heads the 429 of an account set to one region (a
// "<region>-only" switch) whose region is not enabled or used up: the other
// region is not tried, as the switch says.
function pinnedUnavailable(a) {
const enabled = a.open?.includes(a.pinned)
return enabled
? `Kiro credits used up in ${a.pinned}, the only region this account is set to use (magpie's ${onlyOption(a.pinned)} switch is on). `
: `${a.pinned} is not enabled for this account, and magpie's ${onlyOption(a.pinned)} switch is on, so no other region is used: ask your admin to enable it. `
}
// 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) {
@@ -3086,8 +3138,8 @@ async function bodyOf(input, init) {
return JSON.parse(typeof b === "string" ? b : new TextDecoder().decode(b))
}
export async function KiroAuthPlugin({ client } = {}) {
const creds = account(client)
export async function KiroAuthPlugin({ client, magpie } = {}) {
const creds = account(client, magpie)
return {
auth: {
provider: ID,
@@ -3145,7 +3197,7 @@ export async function KiroAuthPlugin({ client } = {}) {
}
}))
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)
const got = regionsUsage(reads, Date.now(), onlyRegion(magpie))
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))
@@ -3158,6 +3210,20 @@ export async function KiroAuthPlugin({ client } = {}) {
},
// labels, messages and hints are magpie's own fields: the same words
// by the window's language (OpenCode shows the English)
// magpie's switches for the provider (#2038): shown in its editor, read
// with input.magpie.option at each request
options: [
...CREDIT_REGIONS.map((region, i) => {
const other = CREDIT_REGIONS[1 - i]
return {
key: onlyOption(region),
label: `Use ${region} only`,
description: `Send every request to ${region}, none to ${other}; with it not enabled or used up, magpie moves to another account.`,
labels: { zh: `只使用 ${region}` },
descriptions: { zh: `所有请求发往 ${region},不发往 ${other};该区域未开通或额度用完时,magpie 换下一个账号。` },
}
}),
],
methods: [
{ type: "oauth", label: "Kiro (Google, GitHub, AWS Builder ID, IAM Identity Center)", labels: WORDS.browser,
prompts: [{ type: "select", key: "loginMethod", message: "Choose a sign-in method", messages: WORDS.choose, options: [
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@magpie-community/opencode-kiro-auth",
"version": "0.1.36",
"version": "0.1.37",
"description": "Kiro subscriptions (Free, Pro, Pro+, Power) in OpenCode and magpie",
"type": "module",
"main": "./opencode.mjs",
+131 -1
View File
@@ -72,7 +72,10 @@ function kiro({ profiles = { "us-east-1": [US], "eu-central-1": [EU] }, usage =
return seen
}
const hooks = (saves = []) => plugin({ client: { auth: { set: async (r) => void saves.push(r.body) } } })
// switches are the provider's "<region>-only" switches as the user has them
// in magpie, read live: changing the object changes the next request
const hooks = (saves = [], switches = {}) =>
plugin({ client: { auth: { set: async (r) => void saves.push(r.body) } }, magpie: { option: (id, key) => (id === "kiro" ? switches[key] : undefined) } })
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",
@@ -257,3 +260,130 @@ test("a social sign-in keeps one region", async () => {
expect(seen.usage).toEqual([["us-east-1", US]])
expect(u.windows.map((w) => w.name)).toEqual(["Credits", "Overage"])
})
// The "<region>-only" switches: an account uses the one region its switch
// names and never the other.
test("each region's switch sends every request to that region alone", async () => {
for (const [key, region, arn] of [["us-east-1-only", "us-east-1", US], ["eu-central-1-only", "eu-central-1", EU]]) {
const seen = kiro()
const h = await hooks([], { [key]: true })
await ask(h, auth())
await ask(h, auth())
expect(seen.chat).toEqual([[region, arn], [region, arn]])
}
})
test("both switches off, or both on, is the regions in turn", async () => {
for (const sw of [{}, { "us-east-1-only": true, "eu-central-1-only": true }]) {
const seen = kiro({ chat: { "us-east-1": USED_UP } })
await ask(await hooks([], sw), auth())
expect(seen.chat).toEqual([["us-east-1", US], ["eu-central-1", EU]])
}
})
test("a switch changed between two requests applies to the next, with no restart", async () => {
const seen = kiro()
const sw = {}
const h = await hooks([], sw)
await ask(h, auth())
sw["eu-central-1-only"] = true
await ask(h, auth())
sw["eu-central-1-only"] = false
sw["us-east-1-only"] = true
await ask(h, auth())
expect(seen.chat).toEqual([["us-east-1", US], ["eu-central-1", EU], ["us-east-1", US]])
})
test("a region used up under its switch is a 429, and the other region is not asked", async () => {
const seen = kiro({ chat: { "us-east-1": USED_UP } })
const r = await ask(await hooks([], { "us-east-1-only": true }), auth())
expect(r.status).toBe(429)
expect(r.message).toContain("used up in us-east-1")
expect(r.message).toContain("us-east-1-only")
expect(seen.chat).toEqual([["us-east-1", US]])
})
test("a region not enabled under its switch is a 429 with nothing sent to the other", async () => {
const seen = kiro({ profiles: { "us-east-1": [US] } })
const r = await ask(await hooks([], { "eu-central-1-only": true }), auth())
expect(r.status).toBe(429)
expect(r.message).toContain("eu-central-1 is not enabled")
expect(seen.chat).toEqual([])
})
test("an account set to one region counts that region alone, the other shown only", async () => {
// the window magpie weighs the account by is the one not shown only
const weighed = (u) => u.windows.find((w) => !w.aside && w.span)
// the plan is 2000 credits and the overage cap 10000: eu-central-1 has used
// 5000 of its overage, us-east-1 all of it
kiro({ usage: { "us-east-1": limits(2000 + 10000), "eu-central-1": limits(2000 + 5000) } })
const u = await (await hooks([], { "eu-central-1-only": true })).auth.usage(async () => auth())
expect(weighed(u)).toMatchObject({ name: "Overage", amount: 5000, limit: 10000, used: 50 })
const us = u.windows.filter((w) => /us-east-1/.test(w.name))
expect(us.length).toBeGreaterThan(0)
expect(us.every((w) => w.aside)).toBe(true)
// without the switch both regions are counted
kiro({ usage: { "us-east-1": limits(2000 + 10000), "eu-central-1": limits(2000 + 5000) } })
const both = await (await hooks()).auth.usage(async () => auth())
expect(weighed(both)).toMatchObject({ amount: 15000, limit: 20000, used: 75 })
// the pinned region used up makes the account used up, however much the other has
kiro({ usage: { "us-east-1": limits(2000), "eu-central-1": limits(2000 + 10000) } }) // us-east-1 has all its overage left
const v = await (await hooks([], { "eu-central-1-only": true })).auth.usage(async () => auth())
expect(weighed(v).used).toBe(100)
})
test("a social sign-in, one region only, ignores the switches", 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)" }
await ask(await hooks([], { "eu-central-1-only": true }), a)
expect(seen.chat).toEqual([["us-east-1", US]])
})
// regionsUsage with a pin (the reviewer's two cases): the region the user
// said not to use is never asked to be enabled, and a pinned region that
// can't be used leaves the account out of routing, with the reason shown.
const weighed = (u) => u.windows.find((w) => !w.aside && w.span)
test("a pinned account is not told to enable the region it was told not to use", async () => {
// us-east-1 pinned, in its overage; eu-central-1 not enabled
kiro({ profiles: { "us-east-1": [US] }, usage: { "us-east-1": limits(2000 + 8500) } })
const u = await (await hooks([], { "us-east-1-only": true })).auth.usage(async () => auth())
expect(weighed(u)).toMatchObject({ name: "Overage", amount: 8500, limit: 10000 })
expect(weighed(u).display).not.toContain("not enabled")
expect(weighed(u).display).not.toContain("eu-central-1")
// the pin is the other region and it is the one missing: that one is named
kiro({ profiles: { "eu-central-1": [EU] }, usage: { "eu-central-1": limits(2000 + 8500) } })
const v = await (await hooks([], { "us-east-1-only": true })).auth.usage(async () => auth())
expect(JSON.stringify(v.windows)).toContain("us-east-1")
})
test("a pinned region that is not enabled leaves a window that is used up, with the reason", async () => {
kiro({ profiles: { "us-east-1": [US] }, usage: { "us-east-1": limits(500) } })
const u = await (await hooks([], { "eu-central-1-only": true })).auth.usage(async () => auth())
const w = weighed(u)
expect(w).toBeDefined()
expect(w.used).toBe(100)
expect(w.display).toContain("eu-central-1 is not enabled")
expect(w.display).toContain("eu-central-1-only")
// the region it doesn't use is shown only
expect(u.windows.filter((x) => /us-east-1/.test(x.name)).every((x) => x.aside)).toBe(true)
})
test("a pinned region that couldn't be read leaves a window that is used up, with the reason", async () => {
const seen = kiro({ usage: { "us-east-1": limits(500) } })
const base = globalThis.fetch
globalThis.fetch = async (input, init) => (String(input).includes("eu-central-1") && String(input).includes("Get-Usage-Limits") ? new Response("{}", { status: 500 }) : base(input, init))
const u = await (await hooks([], { "eu-central-1-only": true })).auth.usage(async () => auth())
const w = weighed(u)
expect(w.used).toBe(100)
expect(w.display).toContain("eu-central-1 couldn't be read")
expect(seen.usage.length).toBeGreaterThan(0)
})
test("a pin that is read fine is not told it is used up", async () => {
kiro({ usage: { "us-east-1": limits(500), "eu-central-1": limits(2000 + 3000) } })
const u = await (await hooks([], { "eu-central-1-only": true })).auth.usage(async () => auth())
expect(weighed(u)).toMatchObject({ amount: 3000, limit: 10000, used: 30 })
expect(weighed(u).display).not.toContain("not enabled")
})