@magpie-community/opencode-kiro-auth 0.1.35 → 0.1.37

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 +32 -5
  2. package/index.mjs +139 -37
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -257,9 +257,13 @@ its own with its count and when it lapses. Bonus windows are shown only.
257
257
  Kiro spends the plan's credits first, so a month used up while a bonus has
258
258
  credits left is shown only too, and the account isn't taken for spent.
259
259
 
260
- With overage on (`overageConfiguration.overageStatus` `ENABLED`), the
261
- month's window counts against the overage cap (`overageCap`), which is the
262
- month's whole limit; with it off, against the plan's credits.
260
+ With overage on (`overageConfiguration.overageStatus` `ENABLED`), the month
261
+ is two windows, as the Kiro IDE shows it: the plan's credits, shown only
262
+ (using them up doesn't stop the account), then the overage
263
+ (`currentOveragesWithPrecision`) against the overage cap (`overageCap`),
264
+ which counts the overage alone, not the plan's credits with it. A Power
265
+ account that used 12589.24 shows `10000 / 10000` and `2589.24 / 37500`.
266
+ With overage off, the plan's credits are the month.
263
267
 
264
268
  Each request's cost is what Kiro's `meteringEvent`s say, in credits, summed
265
269
  over the request (a web search's turns included). Kiro has already applied
@@ -287,11 +291,34 @@ again.
287
291
  - With every enabled region used up, the answer is a 429 naming them, and a
288
292
  region not enabled, so magpie goes on to another account.
289
293
  - `auth.usage` reads both regions: a window for each, shown only, and their
290
- sum, which magpie weighs the account by. From 80% of the sum, a region
291
- not enabled is pointed out in its text.
294
+ sum, which magpie weighs the account by. With overage on, the plans' sum
295
+ comes first, shown only, and the overages' sum is the one magpie weighs.
296
+ From 80% of the sum, a region not enabled is pointed out in its text.
292
297
 
293
298
  Builder ID, Google, GitHub and API key sign-ins keep one region.
294
299
 
300
+ Two switches in the provider's editor, "Use us-east-1 only" and "Use
301
+ eu-central-1 only" (`us-east-1-only`, `eu-central-1-only`), pin an Identity
302
+ Center account to one region. They are read at each request, so a change
303
+ needs no restart:
304
+
305
+ - With one on, every request goes to that region and none to the other,
306
+ whatever credits the other has. The region not enabled for the account, or
307
+ used up, is a 429 naming the switch, and magpie goes on to another
308
+ account. The other region is never tried.
309
+ - `auth.usage` counts the pinned region alone in the window magpie weighs
310
+ the account by; the other region's windows are shown only. So the account
311
+ is used up for magpie when the pinned region is, not when both are.
312
+ - Both off, or both on, is the default: the regions in turn.
313
+
314
+ Credits past a region's plan are overage, billed at $0.04 each: twice what
315
+ a plan's credits cost (a Power plan is $200 for 10000, $0.02 each), and a
316
+ plan's credits do not roll over to the next month. So when one region is
317
+ already in its overage and the other still has plan credits, pinning the
318
+ account to the other spends the cheaper credits first. Left on the first,
319
+ the account goes on into overage while the other region's plan credits
320
+ expire unused.
321
+
295
322
  ## Not included
296
323
 
297
324
  - Switching between several accounts. OpenCode keeps one sign-in per
package/index.mjs CHANGED
@@ -423,6 +423,21 @@ async function profileOf(c) {
423
423
  // only with every enabled region used up is it used up for magpie.
424
424
  const CREDIT_REGIONS = ["us-east-1", "eu-central-1"]
425
425
  const twoRegions = (c) => c.method === "idc" && !c.builderID
426
+ // magpie's switches for the provider (auth.options), one for each credit
427
+ // region: with one on, an Identity Center account uses that region alone.
428
+ // They are read at each request, so a change needs no restart. A request is
429
+ // never sent to the other region: this one not enabled for the account, or
430
+ // used up, is a 429 for magpie to go on to another account. Both off is the
431
+ // default, the regions in turn; both on says nothing, and is the default too.
432
+ const onlyOption = (region) => region + "-only"
433
+ const onlyRegion = (magpie) => {
434
+ try {
435
+ const on = CREDIT_REGIONS.filter((r) => magpie?.option?.(ID, onlyOption(r)) === true)
436
+ return on.length === 1 ? on[0] : ""
437
+ } catch {
438
+ return ""
439
+ }
440
+ }
426
441
  const SPENT_MS = 60 * 60 * 1000 // a region Kiro said is used up, with no reset known, rests this long
427
442
  const PROBE_MS = 10 * 60 * 1000 // a region with no profile is asked for one again at most this often
428
443
  const REMIND_SHARE = 80 // the share at which a region not enabled is pointed out
@@ -494,18 +509,28 @@ function goG(x) {
494
509
  // first, then these, so a month used up while a bonus has credits left
495
510
  // is set aside too, and the account isn't taken for spent.
496
511
  //
497
- // With overage on, Kiro goes on past the plan's credits up to the overage
498
- // cap, which is the month's whole limit (a 2000-credit plan used 4104, of
499
- // them 2104 overage, under a cap of 10000), so the month's window counts
500
- // against the cap. With overage off the cap Kiro still sends means nothing.
512
+ // With overage on, Kiro goes on past the plan's credits, billed as post-paid
513
+ // credits, until those reach the overage cap. The cap counts the overage
514
+ // alone, not the plan's credits with it: it is the profile's "maximum
515
+ // allowed overage" quota (in USD, $0.04 a credit; $400 is 10000 credits).
516
+ // So with overage on the month is two windows, as the Kiro IDE shows it:
517
+ // the plan's credits (12589.24 used of a 10000 plan is "10000 / 10000"),
518
+ // shown only, as using them up doesn't stop the account, and the overage
519
+ // (2589.24 / 37500), which does (wizcheu on X). With overage off the cap Kiro
520
+ // still sends means nothing, and the plan's credits are the month.
501
521
  const count = (used, limit) => used.toFixed(2).replace(/0+$/, "").replace(/\.$/, "") + " / " + goG(limit)
522
+ const num = (x) => (typeof x === "number" && Number.isFinite(x) ? x : 0)
502
523
  const overageOn = (l) =>
503
524
  String(l?.overageConfiguration?.overageStatus ?? "").toUpperCase() === "ENABLED" || l?.overageConfiguration?.overageEnabled === true
504
- function usageOf(l, now = Date.now()) {
525
+
526
+ // readUsage is usageOf with the month's windows named: plan, the plan's
527
+ // credits, and stop, the window that stops the account (the overage's
528
+ // with overage on, else plan itself).
529
+ function readUsage(l, now = Date.now()) {
505
530
  const at = (secs) => (secs > 0 ? new Date(Math.trunc(secs) * 1000).toISOString() : undefined)
506
- const num = (x) => (typeof x === "number" && Number.isFinite(x) ? x : 0)
507
531
  const overage = overageOn(l)
508
532
  const windows = []
533
+ let plan, stop
509
534
  for (const u of l?.usageBreakdownList ?? []) {
510
535
  const t = u?.freeTrialInfo
511
536
  if (t && String(t.freeTrialStatus ?? "").toUpperCase() === "ACTIVE" && num(t.usageLimitWithPrecision) > 0) {
@@ -521,36 +546,53 @@ function usageOf(l, now = Date.now()) {
521
546
  bonuses.push({ name: b?.displayName || "Bonus credits", used: (100 * used) / limit, display: count(used, limit),
522
547
  amount: used, limit, unit: "credits", ...(expires > 0 && left > 0 ? { runsOutAt: at(expires), runsOut: left } : {}), aside: true })
523
548
  }
524
- const used = num(u?.currentUsageWithPrecision)
525
- const limit = Math.max(num(u?.usageLimitWithPrecision), overage ? num(u?.overageCapWithPrecision) || num(u?.overageCap) : 0)
526
- if (limit > 0) {
527
- const reset = num(u?.nextDateReset) || num(l?.nextDateReset)
528
- const carried = used >= limit && bonuses.some((b) => b.amount < b.limit)
529
- windows.push({ name: u?.displayNamePlural || u?.displayName || "Credits", used: (100 * used) / limit, resetsAt: at(reset),
530
- display: count(used, limit), amount: used, limit, unit: "credits", span: 30 * 24 * 3600, ...(carried ? { aside: true } : {}) })
549
+ const used = num(u?.currentUsageWithPrecision), limit = num(u?.usageLimitWithPrecision)
550
+ const cap = overage ? num(u?.overageCapWithPrecision) || num(u?.overageCap) : 0
551
+ const reset = at(num(u?.nextDateReset) || num(l?.nextDateReset))
552
+ const month = { resetsAt: reset, unit: "credits", span: 30 * 24 * 3600 }
553
+ const name = u?.displayNamePlural || u?.displayName || "Credits"
554
+ const left = bonuses.some((b) => b.amount < b.limit)
555
+ if (cap > 0) {
556
+ // what Kiro says of the overage, else what is past the plan
557
+ const said = typeof u?.currentOveragesWithPrecision === "number" ? u.currentOveragesWithPrecision : u?.currentOverages
558
+ const over = typeof said === "number" && Number.isFinite(said) ? said : Math.max(0, used - limit)
559
+ const inPlan = Math.min(used, limit)
560
+ plan = limit > 0 ? { name, used: (100 * inPlan) / limit, display: count(inPlan, limit), amount: inPlan, limit, ...month, aside: true } : undefined
561
+ stop = { name: "Overage", used: (100 * over) / cap, display: count(over, cap), amount: over, limit: cap, ...month,
562
+ ...(over >= cap && left ? { aside: true } : {}) }
563
+ windows.push(...(plan ? [plan] : []), stop)
564
+ plan ??= stop
565
+ } else if (limit > 0) {
566
+ plan = stop = { name, used: (100 * used) / limit, display: count(used, limit), amount: used, limit, ...month,
567
+ ...(used >= limit && left ? { aside: true } : {}) }
568
+ windows.push(plan)
531
569
  }
532
570
  windows.push(...bonuses)
533
571
  }
534
572
  const email = l?.userInfo?.email
535
- return { plan: planName(l?.subscriptionInfo?.subscriptionTitle), ...(typeof email === "string" && email ? { user: email } : {}), windows }
573
+ const usage = { plan: planName(l?.subscriptionInfo?.subscriptionTitle), ...(typeof email === "string" && email ? { user: email } : {}), windows }
574
+ return { usage, plan, stop }
536
575
  }
537
576
 
577
+ const usageOf = (l, now = Date.now()) => readUsage(l, now).usage
578
+
538
579
  // regionsUsage is an Identity Center account's credits from each region's
539
580
  // read (reads: { region, l } read, { region, error } not, { region,
540
581
  // missing } with no profile, not enabled): each region's month shown only,
541
582
  // and their sum the window magpie weighs the account by, used up only when
542
- // every region read is. A free trial or bonus credits are the first read
543
- // region's. regions says, of each region read, whether it is used up and
544
- // when it resets. Regions read come first, then those that couldn't be read,
545
- // then those not enabled: a card that shows only the first few windows then
546
- // shows the credits an account has.
547
- function regionsUsage(reads, now = Date.now()) {
583
+ // every region read is. With overage on, the plans' sum comes first, shown
584
+ // only, then the overages' sum weighs the account. A free trial or bonus
585
+ // credits are the first read region's. regions says, of each region read,
586
+ // whether it is used up and when it resets. Regions read come first, then
587
+ // those that couldn't be read, then those not enabled: a card that shows
588
+ // only the first few windows then shows the credits an account has.
589
+ function regionsUsage(reads, now = Date.now(), only = "") {
548
590
  const shown = []
549
591
  const failed = []
550
592
  const off = []
551
593
  const regions = []
552
594
  const missing = []
553
- let amount = 0, limit = 0, resets = 0, first, monthName
595
+ let amount = 0, limit = 0, inPlan = 0, ofPlan = 0, resets = 0, first, monthName, anyOver = false, allOver = true
554
596
  for (const r of reads) {
555
597
  const name = `Credits (${r.region})`
556
598
  if (r.error) {
@@ -562,24 +604,54 @@ function regionsUsage(reads, now = Date.now()) {
562
604
  off.push({ name, display: "not enabled", aside: true })
563
605
  continue
564
606
  }
565
- const u = usageOf(r.l, now)
607
+ const { usage: u, plan, stop } = readUsage(r.l, now)
566
608
  first ??= u
567
- const month = u.windows.find((w) => w.span)
568
- if (!month) continue
569
- monthName ??= month.name
570
- amount += month.amount
571
- limit += month.limit
572
- const at = Date.parse(month.resetsAt ?? "")
609
+ if (!stop) continue
610
+ const over = stop !== plan
611
+ // an account set to one region counts that region alone, the other
612
+ // shown only: its credits are not the account's to spend
613
+ const counted = !only || r.region === only
614
+ if (counted) {
615
+ anyOver ||= over
616
+ allOver &&= over
617
+ }
618
+ monthName ??= plan.name
619
+ if (!counted) {
620
+ shown.push({ ...plan, name: `${plan.name} (${r.region})`, aside: true })
621
+ if (over) shown.push({ ...stop, name: `${stop.name} (${r.region})`, aside: true })
622
+ regions.push({ region: r.region, full: stop.amount >= stop.limit, resetsAt: Date.parse(stop.resetsAt ?? "") > 0 ? Date.parse(stop.resetsAt) : 0 })
623
+ continue
624
+ }
625
+ amount += stop.amount
626
+ limit += stop.limit
627
+ inPlan += plan.amount
628
+ ofPlan += plan.limit
629
+ const at = Date.parse(stop.resetsAt ?? "")
573
630
  if (at > 0 && (!resets || at < resets)) resets = at
574
- shown.push({ ...month, name: `${month.name} (${r.region})`, aside: true })
575
- regions.push({ region: r.region, full: month.amount >= month.limit, resetsAt: at > 0 ? at : 0 })
631
+ shown.push({ ...plan, name: `${plan.name} (${r.region})`, aside: true })
632
+ if (over) shown.push({ ...stop, name: `${stop.name} (${r.region})`, aside: true })
633
+ regions.push({ region: r.region, full: stop.amount >= stop.limit, resetsAt: at > 0 ? at : 0 })
576
634
  }
577
635
  const windows = []
636
+ const resetsAt = resets ? { resetsAt: new Date(resets).toISOString() } : {}
578
637
  if (limit > 0) {
638
+ if (anyOver && ofPlan > 0)
639
+ windows.push({ name: monthName, used: (100 * inPlan) / ofPlan, ...resetsAt, display: count(inPlan, ofPlan), amount: inPlan, limit: ofPlan,
640
+ unit: "credits", span: 30 * 24 * 3600, aside: true })
579
641
  let display = count(amount, limit)
580
- if (missing.length && (100 * amount) / limit >= REMIND_SHARE) display += ` · ${missing.join(", ")} not enabled: ask your admin to enable it`
581
- windows.push({ name: monthName, used: (100 * amount) / limit, ...(resets ? { resetsAt: new Date(resets).toISOString() } : {}),
642
+ // a region the user said not to use is not asked to be enabled
643
+ const ask = only ? missing.filter((r) => r === only) : missing
644
+ if (ask.length && (100 * amount) / limit >= REMIND_SHARE) display += ` · ${ask.join(", ")} not enabled: ask your admin to enable it`
645
+ windows.push({ name: allOver ? "Overage" : monthName, used: (100 * amount) / limit, ...resetsAt,
582
646
  display, amount, limit, unit: "credits", span: 30 * 24 * 3600 })
647
+ } else if (only) {
648
+ // the region the account is pinned to is not enabled or couldn't be read:
649
+ // no window to weigh, so magpie would go on asking an account every
650
+ // request of which is a 429. A window that is used up leaves it out of
651
+ // routing, and says why.
652
+ const why = reads.find((r) => r.region === only)?.error ? `${only} couldn't be read` : `${only} is not enabled`
653
+ windows.push({ name: monthName ?? "Credits", used: 100, display: `${why}, and the ${onlyOption(only)} switch is on: no other region is used`,
654
+ span: 30 * 24 * 3600 })
583
655
  }
584
656
  windows.push(...shown, ...failed, ...off, ...(first?.windows ?? []).filter((w) => !w.span))
585
657
  const { windows: _w, ...who } = first ?? {}
@@ -611,7 +683,7 @@ async function credOf(auth) {
611
683
  // sign-in read with that token (its save failed, or magpie hasn't yet
612
684
  // saved what auth.refresh gave) goes on with the newer one rather than
613
685
  // spending the replaced refresh token again.
614
- function account(client) {
686
+ function account(client, magpie) {
615
687
  let held = null // { id, c }
616
688
  const after = new Map()
617
689
  const newest = (c) => {
@@ -730,9 +802,13 @@ function account(client) {
730
802
  if (!twoRegions(c) || st.builderID || !c.profiles) return a
731
803
  // the first enabled region with credits left, in CREDIT_REGIONS' order
732
804
  const now = Date.now()
733
- const open = CREDIT_REGIONS.filter((r) => c.profiles[r])
805
+ const only = onlyRegion(magpie)
806
+ const open = CREDIT_REGIONS.filter((r) => c.profiles[r] && (!only || r === only))
734
807
  const pick = open.find((r) => !(st.spent[r] > now))
735
808
  if (pick) Object.assign(a, { region: pick, profile: c.profiles[pick] })
809
+ // pinned to a region this account lacks, or has used up: no region to
810
+ // send to, which ask() answers as every region used up
811
+ else if (only) return { ...a, region: only, profile: "", key, profiles: { ...c.profiles }, open, pinned: only }
736
812
  return { ...a, key, profiles: { ...c.profiles }, open }
737
813
  })
738
814
  // spend marks a region of an account used up till until (0: SPENT_MS from
@@ -2558,6 +2634,7 @@ async function ask(creds, auth, req, model, budget, signal, conversation) {
2558
2634
  } catch (e) {
2559
2635
  return { status: 401, message: e.message }
2560
2636
  }
2637
+ if (a.pinned) return { status: 429, message: pinnedUnavailable(a) }
2561
2638
  let res
2562
2639
  try {
2563
2640
  res = await paced(a, await kiroBody(req, model, a.profile, budget, conversation), signal)
@@ -2595,6 +2672,7 @@ async function ask(creds, auth, req, model, budget, signal, conversation) {
2595
2672
  } catch (e) {
2596
2673
  return { status: 401, message: e.message }
2597
2674
  }
2675
+ if (next.pinned) return { status: 429, message: pinnedUnavailable(next) + f.message, wait: f.wait }
2598
2676
  if (tried.has(next.region)) return { status: 429, message: regionsUsedUp(next) + f.message, wait: f.wait }
2599
2677
  a = next
2600
2678
  try {
@@ -2612,6 +2690,16 @@ async function ask(creds, auth, req, model, budget, signal, conversation) {
2612
2690
  return { res, a }
2613
2691
  }
2614
2692
 
2693
+ // pinnedUnavailable heads the 429 of an account set to one region (a
2694
+ // "<region>-only" switch) whose region is not enabled or used up: the other
2695
+ // region is not tried, as the switch says.
2696
+ function pinnedUnavailable(a) {
2697
+ const enabled = a.open?.includes(a.pinned)
2698
+ return enabled
2699
+ ? `Kiro credits used up in ${a.pinned}, the only region this account is set to use (magpie's ${onlyOption(a.pinned)} switch is on). `
2700
+ : `${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. `
2701
+ }
2702
+
2615
2703
  // regionsUsedUp heads the 429 of an account with every enabled region used
2616
2704
  // up: the regions, and those not enabled, which an admin may enable.
2617
2705
  function regionsUsedUp(a) {
@@ -3050,8 +3138,8 @@ async function bodyOf(input, init) {
3050
3138
  return JSON.parse(typeof b === "string" ? b : new TextDecoder().decode(b))
3051
3139
  }
3052
3140
 
3053
- export async function KiroAuthPlugin({ client } = {}) {
3054
- const creds = account(client)
3141
+ export async function KiroAuthPlugin({ client, magpie } = {}) {
3142
+ const creds = account(client, magpie)
3055
3143
  return {
3056
3144
  auth: {
3057
3145
  provider: ID,
@@ -3109,7 +3197,7 @@ export async function KiroAuthPlugin({ client } = {}) {
3109
3197
  }
3110
3198
  }))
3111
3199
  if (reads.every((r) => r.error || !r.l)) throw reads.find((r) => r.error)?.error ?? new Error("Kiro read no credits")
3112
- const got = regionsUsage(reads)
3200
+ const got = regionsUsage(reads, Date.now(), onlyRegion(magpie))
3113
3201
  for (const r of got.regions) creds.spend(a.key, r.region, r.full ? r.resetsAt || 0 : -1)
3114
3202
  u = got.usage
3115
3203
  } else u = usageOf(await usageLimits(a, true))
@@ -3122,6 +3210,20 @@ export async function KiroAuthPlugin({ client } = {}) {
3122
3210
  },
3123
3211
  // labels, messages and hints are magpie's own fields: the same words
3124
3212
  // by the window's language (OpenCode shows the English)
3213
+ // magpie's switches for the provider (#2038): shown in its editor, read
3214
+ // with input.magpie.option at each request
3215
+ options: [
3216
+ ...CREDIT_REGIONS.map((region, i) => {
3217
+ const other = CREDIT_REGIONS[1 - i]
3218
+ return {
3219
+ key: onlyOption(region),
3220
+ label: `Use ${region} only`,
3221
+ description: `Send every request to ${region}, none to ${other}; with it not enabled or used up, magpie moves to another account.`,
3222
+ labels: { zh: `只使用 ${region}` },
3223
+ descriptions: { zh: `所有请求发往 ${region},不发往 ${other};该区域未开通或额度用完时,magpie 换下一个账号。` },
3224
+ }
3225
+ }),
3226
+ ],
3125
3227
  methods: [
3126
3228
  { type: "oauth", label: "Kiro (Google, GitHub, AWS Builder ID, IAM Identity Center)", labels: WORDS.browser,
3127
3229
  prompts: [{ type: "select", key: "loginMethod", message: "Choose a sign-in method", messages: WORDS.choose, options: [
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@magpie-community/opencode-kiro-auth",
3
- "version": "0.1.35",
3
+ "version": "0.1.37",
4
4
  "description": "Kiro subscriptions (Free, Pro, Pro+, Power) in OpenCode and magpie",
5
5
  "type": "module",
6
6
  "main": "./opencode.mjs",