@magpie-community/opencode-kiro-auth 0.1.26 → 0.1.28

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +27 -0
  2. package/index.mjs +239 -12
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -249,6 +249,33 @@ its own with its count and when it lapses. Bonus windows are shown only.
249
249
  Kiro spends the plan's credits first, so a month used up while a bonus has
250
250
  credits left is shown only too, and the account isn't taken for spent.
251
251
 
252
+ With overage on (`overageConfiguration.overageStatus` `ENABLED`), the
253
+ month's window counts against the overage cap (`overageCap`), which is the
254
+ month's whole limit; with it off, against the plan's credits.
255
+
256
+ ### Identity Center credit regions
257
+
258
+ An IAM Identity Center account has a profile, and its own month of credits
259
+ with its own overage cap, in each of Kiro's regions its organization enabled
260
+ (`us-east-1`, `eu-central-1`). The plugin lists the profiles in both and
261
+ keeps them with the account (`profiles`, by region; `profileArn` is the
262
+ first). A region with no profile is not enabled, and is asked for again at
263
+ most every 10 minutes, so one an admin enables is used without signing in
264
+ again.
265
+
266
+ - A request goes to the first enabled region with credits left. When Kiro
267
+ answers that its credits are used up (`MONTHLY_REQUEST_COUNT`,
268
+ `USAGE_LIMIT`), the region rests till its reset (an hour when none is
269
+ known) and the request is sent again in the other. A rate limit is passed
270
+ on as it is.
271
+ - With every enabled region used up, the answer is a 429 naming them, and a
272
+ region not enabled, so magpie goes on to another account.
273
+ - `auth.usage` reads both regions: a window for each, shown only, and their
274
+ sum, which magpie weighs the account by. From 80% of the sum, a region
275
+ not enabled is pointed out in its text.
276
+
277
+ Builder ID, Google, GitHub and API key sign-ins keep one region.
278
+
252
279
  ## Not included
253
280
 
254
281
  - Switching between several accounts. OpenCode keeps one sign-in per
package/index.mjs CHANGED
@@ -392,6 +392,51 @@ async function profileOf(c) {
392
392
  throw last ?? new Error("Kiro has no profile for this sign-in")
393
393
  }
394
394
 
395
+ // ---- an Identity Center account's credit regions ----------------------------------
396
+ //
397
+ // An Identity Center account has a profile, and a month's credits, in each
398
+ // of Kiro's regions its organization enabled for it: each region's credits
399
+ // are its own, with its own overage cap. A request goes to one region; once
400
+ // that region's credits are used up the account goes on in the other, and
401
+ // only with every enabled region used up is it used up for magpie.
402
+ const CREDIT_REGIONS = ["us-east-1", "eu-central-1"]
403
+ const twoRegions = (c) => c.method === "idc" && !c.builderID
404
+ const SPENT_MS = 60 * 60 * 1000 // a region Kiro said is used up, with no reset known, rests this long
405
+ const PROBE_MS = 10 * 60 * 1000 // a region with no profile is asked for one again at most this often
406
+ const REMIND_SHARE = 80 // the share at which a region not enabled is pointed out
407
+
408
+ // regionKey names an account for its credit regions: kiro-cli's or the
409
+ // IDE's by where it is read, one signed in here by its client and name,
410
+ // which outlive its tokens
411
+ const regionKey = (auth) => (auth?.source ? "source:" + auth.source : "own:" + (auth?.clientId ?? "") + ":" + (auth?.accountId ?? ""))
412
+ const sameProfiles = (a, b) => {
413
+ const ka = Object.keys(a ?? {}), kb = Object.keys(b ?? {})
414
+ return ka.length === kb.length && ka.every((k) => a[k] === b?.[k])
415
+ }
416
+ const firstProfile = (profiles) => CREDIT_REGIONS.map((r) => profiles?.[r]).find(Boolean) ?? Object.values(profiles ?? {})[0] ?? ""
417
+
418
+ // profilesOf is every profile Kiro lists for a sign-in, by its region.
419
+ async function profilesOf(c) {
420
+ const found = {}
421
+ let last
422
+ for (const region of CREDIT_REGIONS) {
423
+ try {
424
+ const out = await managementCall(region, { token: c.access, tokenType: tokenType(c) }, "List-Available-Profiles", null, {})
425
+ for (const p of out?.profiles ?? []) if (p?.arn) found[regionOf(p.arn, region)] ??= p.arn
426
+ } catch (e) {
427
+ // a Builder ID sign-in the token didn't say was one
428
+ if (c.method === "idc" && e?.status === 403 && e.body.includes("Builder ID")) return { [regionOf(BUILDER_ID_PROFILE)]: BUILDER_ID_PROFILE }
429
+ last = e
430
+ }
431
+ }
432
+ if (!Object.keys(found).length) throw last ?? new Error("Kiro has no profile for this sign-in")
433
+ return found
434
+ }
435
+
436
+ // usedUpSaid is whether Kiro's words say the credits are used up, rather
437
+ // than that it is asked too fast.
438
+ const usedUpSaid = (msg) => /MONTHLY_REQUEST_COUNT|USAGE_LIMIT/.test(String(msg ?? ""))
439
+
395
440
  // usageLimits is Get-Usage-Limits: the plan, the account's email, credits.
396
441
  function usageLimits(a, email) {
397
442
  // an API key's, as kiro-cli asks for it: no profile, no email asked
@@ -426,10 +471,18 @@ function goG(x) {
426
471
  // reset. They are shown only (aside). Kiro spends the plan's credits
427
472
  // first, then these, so a month used up while a bonus has credits left
428
473
  // is set aside too, and the account isn't taken for spent.
474
+ //
475
+ // With overage on, Kiro goes on past the plan's credits up to the overage
476
+ // cap, which is the month's whole limit (a 2000-credit plan used 4104, of
477
+ // them 2104 overage, under a cap of 10000), so the month's window counts
478
+ // against the cap. With overage off the cap Kiro still sends means nothing.
479
+ const count = (used, limit) => used.toFixed(2).replace(/0+$/, "").replace(/\.$/, "") + " / " + goG(limit)
480
+ const overageOn = (l) =>
481
+ String(l?.overageConfiguration?.overageStatus ?? "").toUpperCase() === "ENABLED" || l?.overageConfiguration?.overageEnabled === true
429
482
  function usageOf(l, now = Date.now()) {
430
483
  const at = (secs) => (secs > 0 ? new Date(Math.trunc(secs) * 1000).toISOString() : undefined)
431
- const count = (used, limit) => used.toFixed(2).replace(/0+$/, "").replace(/\.$/, "") + " / " + goG(limit)
432
484
  const num = (x) => (typeof x === "number" && Number.isFinite(x) ? x : 0)
485
+ const overage = overageOn(l)
433
486
  const windows = []
434
487
  for (const u of l?.usageBreakdownList ?? []) {
435
488
  const t = u?.freeTrialInfo
@@ -446,7 +499,8 @@ function usageOf(l, now = Date.now()) {
446
499
  bonuses.push({ name: b?.displayName || "Bonus credits", used: (100 * used) / limit, display: count(used, limit),
447
500
  amount: used, limit, unit: "credits", ...(expires > 0 && left > 0 ? { runsOutAt: at(expires), runsOut: left } : {}), aside: true })
448
501
  }
449
- const used = num(u?.currentUsageWithPrecision), limit = num(u?.usageLimitWithPrecision)
502
+ const used = num(u?.currentUsageWithPrecision)
503
+ const limit = Math.max(num(u?.usageLimitWithPrecision), overage ? num(u?.overageCapWithPrecision) || num(u?.overageCap) : 0)
450
504
  if (limit > 0) {
451
505
  const reset = num(u?.nextDateReset) || num(l?.nextDateReset)
452
506
  const carried = used >= limit && bonuses.some((b) => b.amount < b.limit)
@@ -459,6 +513,57 @@ function usageOf(l, now = Date.now()) {
459
513
  return { plan: planName(l?.subscriptionInfo?.subscriptionTitle), ...(typeof email === "string" && email ? { user: email } : {}), windows }
460
514
  }
461
515
 
516
+ // regionsUsage is an Identity Center account's credits from each region's
517
+ // read (reads: { region, l } read, { region, error } not, { region,
518
+ // missing } with no profile, not enabled): each region's month shown only,
519
+ // and their sum the window magpie weighs the account by, used up only when
520
+ // every region read is. A free trial or bonus credits are the first read
521
+ // region's. regions says, of each region read, whether it is used up and
522
+ // when it resets. Regions read come first, then those that couldn't be read,
523
+ // then those not enabled: a card that shows only the first few windows then
524
+ // shows the credits an account has.
525
+ function regionsUsage(reads, now = Date.now()) {
526
+ const shown = []
527
+ const failed = []
528
+ const off = []
529
+ const regions = []
530
+ const missing = []
531
+ let amount = 0, limit = 0, resets = 0, first, monthName
532
+ for (const r of reads) {
533
+ const name = `Credits (${r.region})`
534
+ if (r.error) {
535
+ failed.push({ name, display: "couldn't be read", aside: true })
536
+ continue
537
+ }
538
+ if (!r.l) {
539
+ missing.push(r.region)
540
+ off.push({ name, display: "not enabled", aside: true })
541
+ continue
542
+ }
543
+ const u = usageOf(r.l, now)
544
+ first ??= u
545
+ const month = u.windows.find((w) => w.span)
546
+ if (!month) continue
547
+ monthName ??= month.name
548
+ amount += month.amount
549
+ limit += month.limit
550
+ const at = Date.parse(month.resetsAt ?? "")
551
+ if (at > 0 && (!resets || at < resets)) resets = at
552
+ shown.push({ ...month, name: `${month.name} (${r.region})`, aside: true })
553
+ regions.push({ region: r.region, full: month.amount >= month.limit, resetsAt: at > 0 ? at : 0 })
554
+ }
555
+ const windows = []
556
+ if (limit > 0) {
557
+ let display = count(amount, limit)
558
+ if (missing.length && (100 * amount) / limit >= REMIND_SHARE) display += ` · ${missing.join(", ")} not enabled: ask your admin to enable it`
559
+ windows.push({ name: monthName, used: (100 * amount) / limit, ...(resets ? { resetsAt: new Date(resets).toISOString() } : {}),
560
+ display, amount, limit, unit: "credits", span: 30 * 24 * 3600 })
561
+ }
562
+ windows.push(...shown, ...failed, ...off, ...(first?.windows ?? []).filter((w) => !w.span))
563
+ const { windows: _w, ...who } = first ?? {}
564
+ return { usage: { ...who, windows }, regions, missing }
565
+ }
566
+
462
567
  // ---- the account, as the plugin holds it -------------------------------------------
463
568
 
464
569
  // credOf is the sign-in a stored auth names: a key, one signed in here, or
@@ -472,7 +577,8 @@ async function credOf(auth) {
472
577
  if (!auth.access) return null
473
578
  return { access: auth.access, refresh: auth.refresh ?? "", expires: auth.expires ?? 0, method: auth.method || "social",
474
579
  region: auth.region || "us-east-1", profile: auth.profileArn ?? "", clientId: auth.clientId ?? "", clientSecret: auth.clientSecret ?? "",
475
- builderID: isBuilderID(auth.loginProvider), own: true }
580
+ builderID: isBuilderID(auth.loginProvider), own: true,
581
+ ...(auth.profiles && typeof auth.profiles === "object" && !Array.isArray(auth.profiles) ? { profiles: { ...auth.profiles } } : {}) }
476
582
  }
477
583
 
478
584
  // Account holds the credentials in use, refreshing them when near their
@@ -515,7 +621,16 @@ function account(client) {
515
621
  if (!c.own || !client?.auth?.set) return
516
622
  const { type: _t, ...rest } = auth
517
623
  await client.auth.set({ path: { id: ID }, body: { ...rest, type: "oauth", access: c.access, refresh: c.refresh, expires: c.expires,
518
- profileArn: c.profile, region: c.region, ...idFields(auth) } }).catch(() => {})
624
+ profileArn: c.profile, region: c.region, ...(c.profiles ? { profiles: c.profiles } : {}), ...idFields(auth) } }).catch(() => {})
625
+ }
626
+ // each account's credit regions (twoRegions), by regionKey: their
627
+ // profiles, when they were last asked for, and the regions used up till
628
+ // when. One plugin serves every account, so this is kept by account.
629
+ const regionStates = new Map()
630
+ const stateOf = (key) => {
631
+ let st = regionStates.get(key)
632
+ if (!st) regionStates.set(key, (st = { profiles: {}, probed: 0, spent: {}, builderID: false }))
633
+ return st
519
634
  }
520
635
  const creds = (auth, stale = false) =>
521
636
  locked(async () => {
@@ -545,6 +660,29 @@ function account(client) {
545
660
  saved = true
546
661
  }
547
662
  }
663
+ const key = regionKey(auth)
664
+ const st = stateOf(key)
665
+ if (twoRegions(c) && !st.builderID) {
666
+ c.profiles = { ...st.profiles, ...c.profiles }
667
+ if (c.profile) c.profiles[regionOf(c.profile, c.region)] ??= c.profile
668
+ if (CREDIT_REGIONS.some((r) => !c.profiles[r]) && Date.now() - st.probed > PROBE_MS) {
669
+ st.probed = Date.now()
670
+ try {
671
+ const found = await profilesOf(c)
672
+ if (Object.values(found).includes(BUILDER_ID_PROFILE)) {
673
+ st.builderID = true
674
+ c.profile ||= BUILDER_ID_PROFILE
675
+ } else c.profiles = { ...c.profiles, ...found }
676
+ } catch {}
677
+ }
678
+ st.profiles = c.profiles
679
+ if (st.builderID) delete c.profiles
680
+ if (!c.profile) c.profile = firstProfile(c.profiles)
681
+ if (!saved && c.own && c.profile && (st.builderID ? !auth?.profileArn : !sameProfiles(c.profiles, auth?.profiles))) {
682
+ await save(auth, c)
683
+ saved = true
684
+ }
685
+ }
548
686
  if (c.method === "apikey") {
549
687
  if (!c.asked) {
550
688
  c.profile = await keyProfile(c)
@@ -566,8 +704,22 @@ function account(client) {
566
704
  // kiro-cli names no profile in an API key's calls, even one GetProfile
567
705
  // found; the profile only says the key's region
568
706
  const profile = c.method === "apikey" ? "" : c.profile
569
- return { token: c.access, tokenType: tokenType(c), profile, region: regionOf(c.profile, c.region) }
707
+ const a = { token: c.access, tokenType: tokenType(c), profile, region: regionOf(c.profile, c.region) }
708
+ if (!twoRegions(c) || st.builderID || !c.profiles) return a
709
+ // the first enabled region with credits left, in CREDIT_REGIONS' order
710
+ const now = Date.now()
711
+ const open = CREDIT_REGIONS.filter((r) => c.profiles[r])
712
+ const pick = open.find((r) => !(st.spent[r] > now))
713
+ if (pick) Object.assign(a, { region: pick, profile: c.profiles[pick] })
714
+ return { ...a, key, profiles: { ...c.profiles }, open }
570
715
  })
716
+ // spend marks a region of an account used up till until (0: SPENT_MS from
717
+ // now), or, with until -1, as having credits again
718
+ creds.spend = (key, region, until = 0) => {
719
+ const st = stateOf(key)
720
+ if (until < 0) delete st.spent[region]
721
+ else st.spent[region] = until > Date.now() ? until : Date.now() + SPENT_MS
722
+ }
571
723
  // renew is auth.refresh's: a sign-in kept here (not kiro-cli's or the
572
724
  // IDE's, which their owners keep) renewed under the same lock as the
573
725
  // requests' refresh, so the two never spend one refresh token. It saves
@@ -1202,13 +1354,39 @@ const ERROR_TYPES = { 400: "invalid_request_error", 401: "authentication_error",
1202
1354
  404: "not_found_error", 413: "request_too_large", 429: "rate_limit_error", 503: "overloaded_error", 529: "overloaded_error" }
1203
1355
  const errorType = (status) => ERROR_TYPES[status] ?? "api_error"
1204
1356
  // Each failure says X-Magpie-Sign-In: kept, as the built-in never marked
1205
- // an account lapsed (see gone).
1206
- const errorResponse = (status, message) =>
1357
+ // an account lapsed (see gone). One Kiro said when to ask again (waitOf)
1358
+ // says it as Retry-After, in whole seconds, for magpie to wait as long.
1359
+ const errorResponse = (status, message, wait) =>
1207
1360
  new Response(JSON.stringify({ type: "error", error: { type: errorType(status), message } }), {
1208
1361
  status,
1209
- headers: { "Content-Type": "application/json", "X-Magpie-Sign-In": "kept" },
1362
+ headers: { "Content-Type": "application/json", "X-Magpie-Sign-In": "kept",
1363
+ ...(wait > 0 ? { "Retry-After": String(Math.ceil(wait / 1000)) } : {}) },
1210
1364
  })
1211
1365
 
1366
+ // waitOf is the milliseconds Kiro's refusal says to wait before asking
1367
+ // again, or undefined: what Kiro's own clients read. The Kiro IDE (agent
1368
+ // 1.1.499) reads the x-amzn-kiro-ratelimit-retry-after header and the
1369
+ // body's retryAfterMilliseconds, both in milliseconds; kiro-cli's AWS SDK
1370
+ // reads x-amz-retry-after, in milliseconds; and Retry-After is HTTP's, in
1371
+ // seconds or as a date. Unsaid, magpie keeps to its own pauses.
1372
+ function waitOf(headers, body) {
1373
+ const ms = (v) => {
1374
+ const n = v == null || v === "" ? NaN : Number(v)
1375
+ return Number.isFinite(n) && n > 0 ? n : undefined
1376
+ }
1377
+ let w = ms(headers.get("x-amzn-kiro-ratelimit-retry-after")) ?? ms(headers.get("x-amz-retry-after"))
1378
+ if (w === undefined)
1379
+ try {
1380
+ w = ms(JSON.parse(body)?.retryAfterMilliseconds)
1381
+ } catch {}
1382
+ const ra = headers.get("retry-after")
1383
+ if (w === undefined && ra) {
1384
+ const secs = ms(ra)
1385
+ w = secs !== undefined ? secs * 1000 : ms(Date.parse(ra) - Date.now())
1386
+ }
1387
+ return w
1388
+ }
1389
+
1212
1390
  // kept is res saying the account is kept: a success too, which the
1213
1391
  // built-in never took for a sign-in come back.
1214
1392
  function kept(res) {
@@ -1842,7 +2020,7 @@ async function generate(creds, auth, req, signal) {
1842
2020
  const hosted = hostedSearch(req)
1843
2021
  if (hosted?.error) return errorResponse(400, hosted.error)
1844
2022
  const first = await ask(creds, auth, req, model, budget, signal)
1845
- if (!first.res) return errorResponse(first.status, first.message)
2023
+ if (!first.res) return errorResponse(first.status, first.message, first.wait)
1846
2024
  const it = hosted ? searching(creds, auth, req, model, budget, signal, hosted, first) : events(first.res.body, model, budget)
1847
2025
  return kept(await reply(it, model, req.stream === true, toolNames(req)))
1848
2026
  }
@@ -1877,13 +2055,46 @@ async function ask(creds, auth, req, model, budget, signal) {
1877
2055
  return { status: 502, message: e.message }
1878
2056
  }
1879
2057
  }
2058
+ // an Identity Center account whose region's credits are used up goes on
2059
+ // in its other enabled region, once each; with none left it is used up
2060
+ // for magpie, and says which regions are and which aren't enabled
2061
+ const tried = new Set()
2062
+ while (!res.ok && a.key && creds.spend) {
2063
+ const text = (await res.text()).slice(0, 1 << 20)
2064
+ const f = { ...failure(res.status, text), wait: waitOf(res.headers, text) }
2065
+ if (!usedUpSaid(f.message)) return f
2066
+ tried.add(a.region)
2067
+ creds.spend(a.key, a.region)
2068
+ let next
2069
+ try {
2070
+ next = await creds(auth)
2071
+ } catch (e) {
2072
+ return { status: 401, message: e.message }
2073
+ }
2074
+ if (tried.has(next.region)) return { status: 429, message: regionsUsedUp(next) + f.message, wait: f.wait }
2075
+ a = next
2076
+ try {
2077
+ res = await sendKiro(a, await kiroBody(req, model, a.profile, budget), signal)
2078
+ } catch (e) {
2079
+ if (e?.name === "AbortError") throw e
2080
+ return { status: 502, message: e.message }
2081
+ }
2082
+ }
1880
2083
  if (!res.ok) {
1881
2084
  // Kiro's own 401 is passed on, as the built-in did, the sign-in kept
1882
- return failure(res.status, (await res.text()).slice(0, 1 << 20))
2085
+ const text = (await res.text()).slice(0, 1 << 20)
2086
+ return { ...failure(res.status, text), wait: waitOf(res.headers, text) }
1883
2087
  }
1884
2088
  return { res, a }
1885
2089
  }
1886
2090
 
2091
+ // regionsUsedUp heads the 429 of an account with every enabled region used
2092
+ // up: the regions, and those not enabled, which an admin may enable.
2093
+ function regionsUsedUp(a) {
2094
+ const off = CREDIT_REGIONS.filter((r) => !a.open?.includes(r))
2095
+ return `Kiro credits used up in ${(a.open ?? []).join(", ")}` + (off.length ? `; ${off.join(", ")} not enabled: ask your admin to enable it` : "") + ". "
2096
+ }
2097
+
1887
2098
  const aborted = () => Object.assign(new Error("the request was cancelled"), { name: "AbortError" })
1888
2099
 
1889
2100
  // searching is events for a request offering the hosted web search, over
@@ -2360,7 +2571,23 @@ export async function KiroAuthPlugin({ client } = {}) {
2360
2571
  const auth = await getAuth()
2361
2572
  if (!(auth?.type === "api" && auth.key) && auth?.type !== "oauth") return { error: "not signed in", signIn: "kept" }
2362
2573
  try {
2363
- const u = usageOf(await usageLimits(await creds(auth), true))
2574
+ const a = await creds(auth)
2575
+ let u
2576
+ if (a.key) {
2577
+ // every credit region, the ones not enabled told as such
2578
+ const reads = await Promise.all(CREDIT_REGIONS.map(async (region) => {
2579
+ if (!a.profiles[region]) return { region }
2580
+ try {
2581
+ return { region, l: await usageLimits({ ...a, region, profile: a.profiles[region] }, true) }
2582
+ } catch (error) {
2583
+ return { region, error }
2584
+ }
2585
+ }))
2586
+ if (reads.every((r) => r.error || !r.l)) throw reads.find((r) => r.error)?.error ?? new Error("Kiro read no credits")
2587
+ const got = regionsUsage(reads)
2588
+ for (const r of got.regions) creds.spend(a.key, r.region, r.full ? r.resetsAt || 0 : -1)
2589
+ u = got.usage
2590
+ } else u = usageOf(await usageLimits(a, true))
2364
2591
  // named as the account is
2365
2592
  if (u.user && auth.type === "oauth" && !auth.source) u.user = nameOf(u.user, auth.loginProvider)
2366
2593
  return { ...u, signIn: "renewed" }
@@ -2418,4 +2645,4 @@ export async function KiroAuthPlugin({ client } = {}) {
2418
2645
  }
2419
2646
 
2420
2647
  // for tests
2421
- export const _internal = { generate, refresh, usageOf, buildKiro, kiroBody, IMAGE_LIMIT, events, reply, failure, toolID, toolName, toolNames, thinking, nativeFields, listModels, contextFirst, configModel, runtimeModel, readCLI, readIDE, regionOf, planName, frames }
2648
+ 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 }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@magpie-community/opencode-kiro-auth",
3
- "version": "0.1.26",
3
+ "version": "0.1.28",
4
4
  "description": "Kiro subscriptions (Free, Pro, Pro+, Power) in OpenCode and magpie",
5
5
  "type": "module",
6
6
  "main": "./opencode.mjs",