@magpie-community/opencode-factory-auth 0.1.0 → 0.1.2

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 (2) hide show
  1. package/index.mjs +255 -106
  2. package/package.json +1 -1
package/index.mjs CHANGED
@@ -3,6 +3,8 @@
3
3
  // sent to Factory's API with the headers droid sends. Ported from magpie's
4
4
  // built-in Factory account (internal/provider/factory*.go).
5
5
 
6
+ import { STATUS_CODES } from "node:http"
7
+
6
8
  const PROVIDER = "factory"
7
9
 
8
10
  const WORKOS = "https://api.workos.com/user_management"
@@ -93,9 +95,10 @@ function configModels() {
93
95
  // ---- tokens -----------------------------------------------------------------
94
96
 
95
97
  class FactoryStatus extends Error {
96
- constructor(code, message) {
98
+ constructor(code, message, body) {
97
99
  super(message)
98
100
  this.code = code
101
+ this.body = body
99
102
  }
100
103
  }
101
104
 
@@ -250,8 +253,19 @@ const orgRefused = (status, text) => status === 403 && text.toLowerCase().includ
250
253
  // the request carries what droid sends.
251
254
  function explain(status, text) {
252
255
  if (status !== 403) return ""
253
- if (orgRefused(status, text)) return "the Factory account's organization changed; sign in to it again"
254
- return "Factory refused this account the request; check that `droid`, signed in to the same account and organization, can use this model (an organization's model policy or the plan may not allow it), and if it can, sign in to the Factory account again"
256
+ if (orgRefused(status, text)) return "the Factory account's organization changed; remove the account in magpie and sign in to it again"
257
+ return "Factory refused this account the request; check that `droid`, signed in to the same account and organization, can use this model (an organization's model policy or the plan may not allow it), and if it can, remove the Factory account in magpie and sign in to it again"
258
+ }
259
+
260
+ // errorReply is an error as the API the request was for words one:
261
+ // Anthropic's on /llm/a/, OpenAI's on the others.
262
+ function errorReply(url, status, type, message, headers = new Headers()) {
263
+ headers.set("content-type", "application/json")
264
+ headers.delete("content-length")
265
+ headers.delete("content-encoding")
266
+ const anthropic = new URL(url).pathname.includes("/llm/a/")
267
+ const body = anthropic ? { type: "error", error: { type, message } } : { error: { message, type, code: null } }
268
+ return new Response(JSON.stringify(body), { status, headers })
255
269
  }
256
270
 
257
271
  // ---- sign-in ----------------------------------------------------------------
@@ -345,6 +359,97 @@ async function deviceSignIn() {
345
359
  }
346
360
  }
347
361
 
362
+ // ---- usage ------------------------------------------------------------------
363
+ //
364
+ // How much of the plan the account has used, as magpie's built-in Factory
365
+ // account shows it (internal/provider/factory_usage.go) and droid's /status
366
+ // asks it: GET /api/billing/limits. Standard usage runs in rolling 5-hour,
367
+ // weekly and monthly windows, each a percent used and when it ends; Droid
368
+ // Core, the open models Factory hosts, has windows of its own; extra usage
369
+ // is a balance in cents.
370
+
371
+ // CORE are the models Droid Core's windows count: those of a vendor other
372
+ // than Anthropic, OpenAI and xAI. Standard's count every other model.
373
+ const CORE = MODELS.filter((m) => !["anthropic", "openai", "xai"].includes(m.upstream)).map((m) => m.id)
374
+
375
+ // statusLine is a status as Go's HTTP client names it, "403 Forbidden".
376
+ const statusLine = (status) => `${status} ${STATUS_CODES[status] ?? ""}`.trim()
377
+
378
+ // vendorError is the message in an error body as magpie reads it: Factory's
379
+ // {error: {message}} or {error}, {message}, {detail}, else the body cut
380
+ // short after the status.
381
+ function vendorError(text, fallback) {
382
+ let v
383
+ try {
384
+ v = JSON.parse(text)
385
+ } catch {}
386
+ if (v && typeof v === "object" && !Array.isArray(v)) {
387
+ const err = v.detail !== undefined && v.detail !== null ? v.detail : v.error
388
+ if (Array.isArray(v.errors) && typeof v.errors[0]?.message === "string" && v.errors[0].message) return v.errors[0].message
389
+ if (err && typeof err === "object" && typeof err.message === "string" && err.message) return err.message
390
+ if (typeof err === "string" && err) return err
391
+ const m = (typeof v.message === "string" && v.message) || (typeof v.msg === "string" && v.msg)
392
+ if (m) return m
393
+ }
394
+ const s = String(text ?? "").split(/\s+/).filter(Boolean).join(" ")
395
+ if (!s || s.startsWith("<")) return fallback
396
+ const r = [...s]
397
+ return fallback + ": " + (r.length > 300 ? r.slice(0, 300).join("") + "…" : s)
398
+ }
399
+
400
+ // windowEnd reads a window's end: an ISO time or epoch milliseconds, as
401
+ // droid hands either to new Date.
402
+ function windowEnd(v) {
403
+ if (typeof v === "string" && v) {
404
+ if (/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(\.\d+)?(Z|[+-]\d\d:\d\d)$/i.test(v) && !isNaN(Date.parse(v))) return new Date(v).toISOString()
405
+ if (/^[+-]?\d+$/.test(v) && Number(v) > 0) return new Date(Number(v)).toISOString()
406
+ return undefined
407
+ }
408
+ if (typeof v === "number" && v > 0) return new Date(Math.trunc(v)).toISOString()
409
+ return undefined
410
+ }
411
+
412
+ // dollars is cents as Go's $%.2f writes them: a half cent rounds to even.
413
+ function dollars(cents) {
414
+ const x = cents / 100
415
+ const tie = Number.isInteger(x * 8) && !Number.isInteger(x * 4) // .125, .375, .625, .875 exactly
416
+ if (!tie) return "$" + x.toFixed(2)
417
+ const lo = Math.floor(x * 100)
418
+ return "$" + ((lo % 2 === 0 ? lo : lo + 1) / 100).toFixed(2)
419
+ }
420
+
421
+ // limitWindows turns the limits into windows: standard's by their span,
422
+ // then Droid Core's, then the extra usage left. For routing, standard counts
423
+ // the vendors' models and Core the open ones Factory hosts; with extra usage
424
+ // to spend, a window used up stops neither.
425
+ function limitWindows(l) {
426
+ const out = []
427
+ const cents = typeof l.extraUsageBalanceCents === "number" ? l.extraUsageBalanceCents : null
428
+ const extra = l.extraUsageAllowed === true && cents !== null && cents > 0
429
+ const add = (p, prefix, core) => {
430
+ if (!p || typeof p !== "object") return
431
+ for (const [w, name, span] of [
432
+ [p.fiveHour, "5 hours", 5 * 3600],
433
+ [p.weekly, "7 days", 7 * 24 * 3600],
434
+ [p.monthly, "30 days", 30 * 24 * 3600],
435
+ ]) {
436
+ if (!w || typeof w !== "object") continue
437
+ const used = typeof w.usedPercent === "number" ? w.usedPercent : 0
438
+ const win = { name: prefix + name, used: Math.min(Math.max(used, 0), 100), span }
439
+ const end = windowEnd(w.windowEnd)
440
+ if (end) win.resetsAt = end
441
+ if (extra) win.aside = true
442
+ if (core) win.models = CORE
443
+ else win.notModels = CORE
444
+ out.push(win)
445
+ }
446
+ }
447
+ add(l.limits?.standard, "", false)
448
+ add(l.limits?.core, "Droid Core · ", true)
449
+ if (cents !== null && cents > 0) out.push({ name: "Extra usage", used: 0, display: dollars(cents), aside: true })
450
+ return out
451
+ }
452
+
348
453
  // ---- the plugin ---------------------------------------------------------------
349
454
 
350
455
  function bodyModel(body) {
@@ -368,9 +473,135 @@ export const FactoryAuthPlugin = async ({ client }) => {
368
473
  lock = run.catch(() => {})
369
474
  return run
370
475
  }
371
- // when the account last asked whoami for its org, so one whoami can't
372
- // answer doesn't ask before every request
373
- let asked = 0
476
+ // when each account last asked whoami for its org, so one whoami can't
477
+ // answer doesn't ask before every request, nor hold back the others
478
+ const asked = new Map()
479
+ const askedOf = (c) => asked.get(c.accountId || c.refresh || "") ?? 0
480
+ const ask = (c) => asked.set(c.accountId || c.refresh || "", Date.now())
481
+
482
+ // account is the account getAuth reads, with what keeps its token live
483
+ // and its org right.
484
+ const account = (getAuth) => {
485
+ const save = async (c) => {
486
+ const { type: _t, ...rest } = c
487
+ await client.auth.set({ path: { id: PROVIDER }, body: { ...rest, type: "oauth" } })
488
+ }
489
+ const current = async () => {
490
+ const a = await getAuth()
491
+ if (a?.type !== "oauth" || !a.access) throw new Error("Factory: not signed in")
492
+ return { ...a }
493
+ }
494
+
495
+ // orgOf fills in the active org when there is none: droid asks
496
+ // whoami as soon as it holds a token and sends the orgId it answers
497
+ // as X-Factory-Org-Id on every request after.
498
+ const orgOf = async (c) => {
499
+ if (c.activeOrganizationId || Date.now() - askedOf(c) < ASK_AGAIN) return c
500
+ ask(c)
501
+ if (await reconcile(c)) await save(c)
502
+ return c
503
+ }
504
+
505
+ // fresh is a live token, renewed near its end.
506
+ const fresh = () =>
507
+ locked(async () => {
508
+ const c = await current()
509
+ if ((c.expires > 0 && Date.now() < c.expires - REFRESH_LEAD) || !c.refresh) return orgOf(c)
510
+ let t
511
+ try {
512
+ t = await renew(c.refresh, "")
513
+ } catch (e) {
514
+ // a hiccup while the token still runs: go on with it
515
+ if (!refused(e) && c.expires > 0 && Date.now() < c.expires) return orgOf(c)
516
+ if (refused(e)) throw Object.assign(new Error(`${c.accountId || "the account"}'s Factory sign-in has expired — sign in again (${e.message})`), { lapsed: true })
517
+ throw e
518
+ }
519
+ c.access = t.access_token
520
+ c.expires = expiry(t.access_token)
521
+ if (t.refresh_token) c.refresh = t.refresh_token
522
+ // droid asks whoami again for each new token, keeping the org it names
523
+ await reconcile(c)
524
+ ask(c)
525
+ await save(c)
526
+ return c
527
+ })
528
+
529
+ // mendOrg answers Factory refusing a request: an active org it
530
+ // can't reach is left off and whoami asked again without it; with
531
+ // no header sent, the token is put in the first org /api/cli/org
532
+ // lists. Any other 403 to an account that sent no org asks whoami
533
+ // for one. True when the request is worth sending again.
534
+ const mendOrg = (status, text) =>
535
+ locked(async () => {
536
+ if (status !== 403) return false
537
+ const isOrg = orgRefused(status, text)
538
+ const c = await current()
539
+ if (c.activeOrganizationId) {
540
+ if (!isOrg) return false // the org was sent: the refusal is about something else
541
+ const was = c.activeOrganizationId
542
+ c.activeOrganizationId = ""
543
+ if ((await reconcile(c)) && c.activeOrganizationId === was) c.activeOrganizationId = "" // whoami names the org refused: send none
544
+ ask(c)
545
+ await save(c)
546
+ return true
547
+ }
548
+ if (!isOrg) {
549
+ ask(c)
550
+ if ((await reconcile(c)) && c.activeOrganizationId) {
551
+ await save(c)
552
+ return true
553
+ }
554
+ return false
555
+ }
556
+ if (!c.refresh) return false
557
+ let org = ""
558
+ try {
559
+ org = await firstOrg(c)
560
+ } catch {}
561
+ if (!org) return false
562
+ let t
563
+ try {
564
+ t = await renew(c.refresh, org)
565
+ } catch {
566
+ return false
567
+ }
568
+ c.access = t.access_token
569
+ c.expires = expiry(t.access_token)
570
+ c.orgId = org
571
+ if (t.refresh_token) c.refresh = t.refresh_token
572
+ await save(c)
573
+ return true
574
+ })
575
+
576
+ // usage is the account's limits, asked once more when Factory refused
577
+ // an org that was put right
578
+ const usage = async () => {
579
+ const limits = async () => {
580
+ const c = await fresh()
581
+ const h = new Headers({ Accept: "application/json" })
582
+ factoryHeaders(h, c)
583
+ const res = await fetch(base(c) + "/api/billing/limits", { headers: h, signal: AbortSignal.timeout(15_000) })
584
+ const text = await res.text()
585
+ if (res.status !== 200) throw new FactoryStatus(res.status, "Factory: " + vendorError(text, statusLine(res.status)), text)
586
+ return JSON.parse(text)
587
+ }
588
+ try {
589
+ let l
590
+ try {
591
+ l = await limits()
592
+ } catch (e) {
593
+ if (!(e instanceof FactoryStatus && e.body !== undefined && (await mendOrg(e.code, e.body).catch(() => false)))) throw e
594
+ l = await limits()
595
+ }
596
+ if (!l?.limits?.standard) return { error: "Factory: the account reported no limits" }
597
+ return { windows: limitWindows(l) }
598
+ } catch (e) {
599
+ return { error: e?.message ?? String(e) }
600
+ }
601
+ }
602
+
603
+ return { fresh, mendOrg, usage }
604
+ }
374
605
 
375
606
  return {
376
607
  config: async (config) => {
@@ -393,100 +624,15 @@ export const FactoryAuthPlugin = async ({ client }) => {
393
624
  authorize: deviceSignIn,
394
625
  },
395
626
  ],
627
+ // magpie's own hook: the account's limits
628
+ async usage(getAuth) {
629
+ return account(getAuth).usage()
630
+ },
396
631
  async loader(getAuth) {
397
632
  const first = await getAuth()
398
633
  if (first?.type !== "oauth") return {}
399
634
 
400
- const save = async (c) => {
401
- const { type: _t, ...rest } = c
402
- await client.auth.set({ path: { id: PROVIDER }, body: { ...rest, type: "oauth" } })
403
- }
404
- const current = async () => {
405
- const a = await getAuth()
406
- if (a?.type !== "oauth" || !a.access) throw new Error("Factory: not signed in")
407
- return { ...a }
408
- }
409
-
410
- // orgOf fills in the active org when there is none: droid asks
411
- // whoami as soon as it holds a token and sends the orgId it answers
412
- // as X-Factory-Org-Id on every request after.
413
- const orgOf = async (c) => {
414
- if (c.activeOrganizationId || Date.now() - asked < ASK_AGAIN) return c
415
- asked = Date.now()
416
- if (await reconcile(c)) await save(c)
417
- return c
418
- }
419
-
420
- // fresh is a live token, renewed near its end.
421
- const fresh = () =>
422
- locked(async () => {
423
- const c = await current()
424
- if ((c.expires > 0 && Date.now() < c.expires - REFRESH_LEAD) || !c.refresh) return orgOf(c)
425
- let t
426
- try {
427
- t = await renew(c.refresh, "")
428
- } catch (e) {
429
- // a hiccup while the token still runs: go on with it
430
- if (!refused(e) && c.expires > 0 && Date.now() < c.expires) return orgOf(c)
431
- if (refused(e)) throw new Error(`${c.accountId || "the account"}'s Factory sign-in has expired — sign in again (${e.message})`)
432
- throw e
433
- }
434
- c.access = t.access_token
435
- c.expires = expiry(t.access_token)
436
- if (t.refresh_token) c.refresh = t.refresh_token
437
- // droid asks whoami again for each new token, keeping the org it names
438
- await reconcile(c)
439
- asked = Date.now()
440
- await save(c)
441
- return c
442
- })
443
-
444
- // mendOrg answers Factory refusing a request: an active org it
445
- // can't reach is left off and whoami asked again without it; with
446
- // no header sent, the token is put in the first org /api/cli/org
447
- // lists. Any other 403 to an account that sent no org asks whoami
448
- // for one. True when the request is worth sending again.
449
- const mendOrg = (status, text) =>
450
- locked(async () => {
451
- if (status !== 403) return false
452
- const isOrg = orgRefused(status, text)
453
- const c = await current()
454
- if (c.activeOrganizationId) {
455
- if (!isOrg) return false // the org was sent: the refusal is about something else
456
- const was = c.activeOrganizationId
457
- c.activeOrganizationId = ""
458
- if ((await reconcile(c)) && c.activeOrganizationId === was) c.activeOrganizationId = "" // whoami names the org refused: send none
459
- asked = Date.now()
460
- await save(c)
461
- return true
462
- }
463
- if (!isOrg) {
464
- asked = Date.now()
465
- if ((await reconcile(c)) && c.activeOrganizationId) {
466
- await save(c)
467
- return true
468
- }
469
- return false
470
- }
471
- if (!c.refresh) return false
472
- let org = ""
473
- try {
474
- org = await firstOrg(c)
475
- } catch {}
476
- if (!org) return false
477
- let t
478
- try {
479
- t = await renew(c.refresh, org)
480
- } catch {
481
- return false
482
- }
483
- c.access = t.access_token
484
- c.expires = expiry(t.access_token)
485
- c.orgId = org
486
- if (t.refresh_token) c.refresh = t.refresh_token
487
- await save(c)
488
- return true
489
- })
635
+ const { fresh, mendOrg } = account(getAuth)
490
636
 
491
637
  const send = async (input, init, body) => {
492
638
  const c = await fresh()
@@ -518,7 +664,15 @@ export const FactoryAuthPlugin = async ({ client }) => {
518
664
  let body = init?.body
519
665
  if (body == null && input instanceof Request && input.body) body = new Uint8Array(await input.arrayBuffer())
520
666
  if (body instanceof ReadableStream) body = new Uint8Array(await new Response(body).arrayBuffer())
521
- let res = await send(input, init, body)
667
+ const url = input instanceof Request ? input.url : String(input)
668
+ let res
669
+ try {
670
+ res = await send(input, init, body)
671
+ } catch (e) {
672
+ // Factory refused to renew the sign-in: the account's own 401
673
+ if (e?.lapsed) return errorReply(url, 401, "authentication_error", e.message)
674
+ throw e
675
+ }
522
676
  if (res.status !== 403) return res
523
677
  let text = await res.text()
524
678
  if (await mendOrg(res.status, text).catch(() => false)) {
@@ -528,18 +682,13 @@ export const FactoryAuthPlugin = async ({ client }) => {
528
682
  }
529
683
  const why = explain(res.status, text)
530
684
  const msg = `${apiError(text, "Forbidden")}: ${why}`
531
- const headers = new Headers(res.headers)
532
- headers.set("content-type", "application/json")
533
- headers.delete("content-length")
534
- headers.delete("content-encoding")
535
- return new Response(JSON.stringify({ type: "error", error: { type: "permission_error", message: msg } }), {
536
- status: res.status,
537
- statusText: res.statusText,
538
- headers,
539
- })
685
+ return errorReply(url, res.status, "permission_error", msg, new Headers(res.headers))
540
686
  },
541
687
  }
542
688
  },
543
689
  },
544
690
  }
545
691
  }
692
+
693
+ // for tests
694
+ export const _internal = { limitWindows, windowEnd, dollars, vendorError, CORE }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@magpie-community/opencode-factory-auth",
3
- "version": "0.1.0",
3
+ "version": "0.1.2",
4
4
  "description": "Sign in to a Factory (Droid) subscription from OpenCode or magpie",
5
5
  "type": "module",
6
6
  "main": "./index.mjs",