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

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 +227 -91
  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
 
@@ -345,6 +348,97 @@ async function deviceSignIn() {
345
348
  }
346
349
  }
347
350
 
351
+ // ---- usage ------------------------------------------------------------------
352
+ //
353
+ // How much of the plan the account has used, as magpie's built-in Factory
354
+ // account shows it (internal/provider/factory_usage.go) and droid's /status
355
+ // asks it: GET /api/billing/limits. Standard usage runs in rolling 5-hour,
356
+ // weekly and monthly windows, each a percent used and when it ends; Droid
357
+ // Core, the open models Factory hosts, has windows of its own; extra usage
358
+ // is a balance in cents.
359
+
360
+ // CORE are the models Droid Core's windows count: those of a vendor other
361
+ // than Anthropic, OpenAI and xAI. Standard's count every other model.
362
+ const CORE = MODELS.filter((m) => !["anthropic", "openai", "xai"].includes(m.upstream)).map((m) => m.id)
363
+
364
+ // statusLine is a status as Go's HTTP client names it, "403 Forbidden".
365
+ const statusLine = (status) => `${status} ${STATUS_CODES[status] ?? ""}`.trim()
366
+
367
+ // vendorError is the message in an error body as magpie reads it: Factory's
368
+ // {error: {message}} or {error}, {message}, {detail}, else the body cut
369
+ // short after the status.
370
+ function vendorError(text, fallback) {
371
+ let v
372
+ try {
373
+ v = JSON.parse(text)
374
+ } catch {}
375
+ if (v && typeof v === "object" && !Array.isArray(v)) {
376
+ const err = v.detail !== undefined && v.detail !== null ? v.detail : v.error
377
+ if (Array.isArray(v.errors) && typeof v.errors[0]?.message === "string" && v.errors[0].message) return v.errors[0].message
378
+ if (err && typeof err === "object" && typeof err.message === "string" && err.message) return err.message
379
+ if (typeof err === "string" && err) return err
380
+ const m = (typeof v.message === "string" && v.message) || (typeof v.msg === "string" && v.msg)
381
+ if (m) return m
382
+ }
383
+ const s = String(text ?? "").split(/\s+/).filter(Boolean).join(" ")
384
+ if (!s || s.startsWith("<")) return fallback
385
+ const r = [...s]
386
+ return fallback + ": " + (r.length > 300 ? r.slice(0, 300).join("") + "…" : s)
387
+ }
388
+
389
+ // windowEnd reads a window's end: an ISO time or epoch milliseconds, as
390
+ // droid hands either to new Date.
391
+ function windowEnd(v) {
392
+ if (typeof v === "string" && v) {
393
+ 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()
394
+ if (/^[+-]?\d+$/.test(v) && Number(v) > 0) return new Date(Number(v)).toISOString()
395
+ return undefined
396
+ }
397
+ if (typeof v === "number" && v > 0) return new Date(Math.trunc(v)).toISOString()
398
+ return undefined
399
+ }
400
+
401
+ // dollars is cents as Go's $%.2f writes them: a half cent rounds to even.
402
+ function dollars(cents) {
403
+ const x = cents / 100
404
+ const tie = Number.isInteger(x * 8) && !Number.isInteger(x * 4) // .125, .375, .625, .875 exactly
405
+ if (!tie) return "$" + x.toFixed(2)
406
+ const lo = Math.floor(x * 100)
407
+ return "$" + ((lo % 2 === 0 ? lo : lo + 1) / 100).toFixed(2)
408
+ }
409
+
410
+ // limitWindows turns the limits into windows: standard's by their span,
411
+ // then Droid Core's, then the extra usage left. For routing, standard counts
412
+ // the vendors' models and Core the open ones Factory hosts; with extra usage
413
+ // to spend, a window used up stops neither.
414
+ function limitWindows(l) {
415
+ const out = []
416
+ const cents = typeof l.extraUsageBalanceCents === "number" ? l.extraUsageBalanceCents : null
417
+ const extra = l.extraUsageAllowed === true && cents !== null && cents > 0
418
+ const add = (p, prefix, core) => {
419
+ if (!p || typeof p !== "object") return
420
+ for (const [w, name, span] of [
421
+ [p.fiveHour, "5 hours", 5 * 3600],
422
+ [p.weekly, "7 days", 7 * 24 * 3600],
423
+ [p.monthly, "30 days", 30 * 24 * 3600],
424
+ ]) {
425
+ if (!w || typeof w !== "object") continue
426
+ const used = typeof w.usedPercent === "number" ? w.usedPercent : 0
427
+ const win = { name: prefix + name, used: Math.min(Math.max(used, 0), 100), span }
428
+ const end = windowEnd(w.windowEnd)
429
+ if (end) win.resetsAt = end
430
+ if (extra) win.aside = true
431
+ if (core) win.models = CORE
432
+ else win.notModels = CORE
433
+ out.push(win)
434
+ }
435
+ }
436
+ add(l.limits?.standard, "", false)
437
+ add(l.limits?.core, "Droid Core · ", true)
438
+ if (cents !== null && cents > 0) out.push({ name: "Extra usage", used: 0, display: dollars(cents), aside: true })
439
+ return out
440
+ }
441
+
348
442
  // ---- the plugin ---------------------------------------------------------------
349
443
 
350
444
  function bodyModel(body) {
@@ -372,6 +466,130 @@ export const FactoryAuthPlugin = async ({ client }) => {
372
466
  // answer doesn't ask before every request
373
467
  let asked = 0
374
468
 
469
+ // account is the account getAuth reads, with what keeps its token live
470
+ // and its org right.
471
+ const account = (getAuth) => {
472
+ const save = async (c) => {
473
+ const { type: _t, ...rest } = c
474
+ await client.auth.set({ path: { id: PROVIDER }, body: { ...rest, type: "oauth" } })
475
+ }
476
+ const current = async () => {
477
+ const a = await getAuth()
478
+ if (a?.type !== "oauth" || !a.access) throw new Error("Factory: not signed in")
479
+ return { ...a }
480
+ }
481
+
482
+ // orgOf fills in the active org when there is none: droid asks
483
+ // whoami as soon as it holds a token and sends the orgId it answers
484
+ // as X-Factory-Org-Id on every request after.
485
+ const orgOf = async (c) => {
486
+ if (c.activeOrganizationId || Date.now() - asked < ASK_AGAIN) return c
487
+ asked = Date.now()
488
+ if (await reconcile(c)) await save(c)
489
+ return c
490
+ }
491
+
492
+ // fresh is a live token, renewed near its end.
493
+ const fresh = () =>
494
+ locked(async () => {
495
+ const c = await current()
496
+ if ((c.expires > 0 && Date.now() < c.expires - REFRESH_LEAD) || !c.refresh) return orgOf(c)
497
+ let t
498
+ try {
499
+ t = await renew(c.refresh, "")
500
+ } catch (e) {
501
+ // a hiccup while the token still runs: go on with it
502
+ if (!refused(e) && c.expires > 0 && Date.now() < c.expires) return orgOf(c)
503
+ if (refused(e)) throw new Error(`${c.accountId || "the account"}'s Factory sign-in has expired — sign in again (${e.message})`)
504
+ throw e
505
+ }
506
+ c.access = t.access_token
507
+ c.expires = expiry(t.access_token)
508
+ if (t.refresh_token) c.refresh = t.refresh_token
509
+ // droid asks whoami again for each new token, keeping the org it names
510
+ await reconcile(c)
511
+ asked = Date.now()
512
+ await save(c)
513
+ return c
514
+ })
515
+
516
+ // mendOrg answers Factory refusing a request: an active org it
517
+ // can't reach is left off and whoami asked again without it; with
518
+ // no header sent, the token is put in the first org /api/cli/org
519
+ // lists. Any other 403 to an account that sent no org asks whoami
520
+ // for one. True when the request is worth sending again.
521
+ const mendOrg = (status, text) =>
522
+ locked(async () => {
523
+ if (status !== 403) return false
524
+ const isOrg = orgRefused(status, text)
525
+ const c = await current()
526
+ if (c.activeOrganizationId) {
527
+ if (!isOrg) return false // the org was sent: the refusal is about something else
528
+ const was = c.activeOrganizationId
529
+ c.activeOrganizationId = ""
530
+ if ((await reconcile(c)) && c.activeOrganizationId === was) c.activeOrganizationId = "" // whoami names the org refused: send none
531
+ asked = Date.now()
532
+ await save(c)
533
+ return true
534
+ }
535
+ if (!isOrg) {
536
+ asked = Date.now()
537
+ if ((await reconcile(c)) && c.activeOrganizationId) {
538
+ await save(c)
539
+ return true
540
+ }
541
+ return false
542
+ }
543
+ if (!c.refresh) return false
544
+ let org = ""
545
+ try {
546
+ org = await firstOrg(c)
547
+ } catch {}
548
+ if (!org) return false
549
+ let t
550
+ try {
551
+ t = await renew(c.refresh, org)
552
+ } catch {
553
+ return false
554
+ }
555
+ c.access = t.access_token
556
+ c.expires = expiry(t.access_token)
557
+ c.orgId = org
558
+ if (t.refresh_token) c.refresh = t.refresh_token
559
+ await save(c)
560
+ return true
561
+ })
562
+
563
+ // usage is the account's limits, asked once more when Factory refused
564
+ // an org that was put right
565
+ const usage = async () => {
566
+ const limits = async () => {
567
+ const c = await fresh()
568
+ const h = new Headers({ Accept: "application/json" })
569
+ factoryHeaders(h, c)
570
+ const res = await fetch(base(c) + "/api/billing/limits", { headers: h, signal: AbortSignal.timeout(15_000) })
571
+ const text = await res.text()
572
+ if (res.status !== 200) throw new FactoryStatus(res.status, "Factory: " + vendorError(text, statusLine(res.status)), text)
573
+ return JSON.parse(text)
574
+ }
575
+ try {
576
+ let l
577
+ try {
578
+ l = await limits()
579
+ } catch (e) {
580
+ if (!(e instanceof FactoryStatus && e.body !== undefined && (await mendOrg(e.code, e.body).catch(() => false)))) throw e
581
+ l = await limits()
582
+ }
583
+ if (!l?.limits?.standard) return { error: "Factory: the account reported no limits" }
584
+ return { windows: limitWindows(l) }
585
+ } catch (e) {
586
+ return { error: e?.message ?? String(e) }
587
+ }
588
+ }
589
+
590
+ return { fresh, mendOrg, usage }
591
+ }
592
+
375
593
  return {
376
594
  config: async (config) => {
377
595
  config.provider ??= {}
@@ -393,100 +611,15 @@ export const FactoryAuthPlugin = async ({ client }) => {
393
611
  authorize: deviceSignIn,
394
612
  },
395
613
  ],
614
+ // magpie's own hook: the account's limits
615
+ async usage(getAuth) {
616
+ return account(getAuth).usage()
617
+ },
396
618
  async loader(getAuth) {
397
619
  const first = await getAuth()
398
620
  if (first?.type !== "oauth") return {}
399
621
 
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
- })
622
+ const { fresh, mendOrg } = account(getAuth)
490
623
 
491
624
  const send = async (input, init, body) => {
492
625
  const c = await fresh()
@@ -543,3 +676,6 @@ export const FactoryAuthPlugin = async ({ client }) => {
543
676
  },
544
677
  }
545
678
  }
679
+
680
+ // for tests
681
+ 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.1",
4
4
  "description": "Sign in to a Factory (Droid) subscription from OpenCode or magpie",
5
5
  "type": "module",
6
6
  "main": "./index.mjs",