@magpie-community/opencode-factory-auth 0.1.3 → 0.1.5
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.
- package/README.md +15 -0
- package/index.mjs +208 -47
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -9,6 +9,10 @@ model requests to Factory's API the way `droid` sends them. Provider id:
|
|
|
9
9
|
- **Sign in with Factory (device code).** This is WorkOS's device flow
|
|
10
10
|
under droid's own client. The browser opens Factory's page with the code
|
|
11
11
|
filled in. Confirm it there, and the plugin picks up the tokens.
|
|
12
|
+
- **Factory API key.** A key (`fk-…`), as droid takes one from
|
|
13
|
+
`FACTORY_API_KEY`. It is sent as the bearer token with droid's headers
|
|
14
|
+
and never renewed. A key carries no organization header; `whoami`, asked
|
|
15
|
+
once with the key, says whose it is and where its organization is served.
|
|
12
16
|
- **Organization.** A token that isn't in an organization yet is put in
|
|
13
17
|
the first one your account belongs to.
|
|
14
18
|
- **Whoami.** The plugin asks `whoami` for your active organization, its
|
|
@@ -33,6 +37,17 @@ at once.
|
|
|
33
37
|
plugin asks `whoami` again and resends the request once. If the refusal
|
|
34
38
|
stands, the error says what to check.
|
|
35
39
|
|
|
40
|
+
## Requests from other agents
|
|
41
|
+
|
|
42
|
+
Factory serves a subscription's model requests to Droid. Every request
|
|
43
|
+
droid sends opens its system prompt with "You are Droid, an AI software
|
|
44
|
+
engineering agent built by Factory.", so another agent's request to
|
|
45
|
+
Factory's OpenAI-shaped API (`/api/llm/o`: GPT and Grok on Responses, the
|
|
46
|
+
open models on chat completions) opens with that line too, the agent's own
|
|
47
|
+
prompt after it. Claude models (and MiniMax M2.7) on Anthropic's Messages
|
|
48
|
+
are sent as the agent sent them, and Factory may refuse them from agents
|
|
49
|
+
other than Droid.
|
|
50
|
+
|
|
36
51
|
## Models
|
|
37
52
|
|
|
38
53
|
Each model is served on the one API droid uses for it:
|
package/index.mjs
CHANGED
|
@@ -13,7 +13,7 @@ const API_EU = "https://api.eu.factory.ai"
|
|
|
13
13
|
// droid's WorkOS client, production
|
|
14
14
|
const CLIENT_ID = "client_01HNM792M5G5G1A2THWPXKFMXB"
|
|
15
15
|
// the droid release the requests say they are
|
|
16
|
-
const VERSION = "0.
|
|
16
|
+
const VERSION = "0.231.0"
|
|
17
17
|
// how long before an access token lapses it is renewed (droid: a minute)
|
|
18
18
|
const REFRESH_LEAD = 2 * 60 * 1000
|
|
19
19
|
// how long an account whose whoami failed waits before asking again
|
|
@@ -53,7 +53,7 @@ const MODELS = [
|
|
|
53
53
|
["grok-4.7", "Grok 4.7", RESPONSES, "xai", 500000, 63356, E4, true],
|
|
54
54
|
["grok-4.6", "Grok 4.6", RESPONSES, "xai", 200000, 63356, E4, true],
|
|
55
55
|
["glm-5.3", "GLM-5.3", CHAT, "fireworks", 1040000, 131072, ["low", "high", "max"], false],
|
|
56
|
-
["glm-5.3-flash", "GLM-5.3-Flash", CHAT, "fireworks", 1048576, 131072, ["low", "high", "max"],
|
|
56
|
+
["glm-5.3-flash", "GLM-5.3-Flash", CHAT, "fireworks", 1048576, 131072, ["low", "high", "max"], true],
|
|
57
57
|
["glm-5.2", "GLM-5.2", CHAT, "baseten", 1040000, 131072, ["high", "max"], false],
|
|
58
58
|
["kimi-k3", "Kimi K3", CHAT, "fireworks", 262144, 65536, ["low", "high", "max"], true],
|
|
59
59
|
["deepseek-v4.1-flash", "DeepSeek V4.1 Flash", CHAT, "fireworks", 1040000, 131072, ["low", "high", "max"], true],
|
|
@@ -123,15 +123,6 @@ function expiry(access) {
|
|
|
123
123
|
return typeof exp === "number" && exp > 0 ? Math.floor(exp) * 1000 : 0
|
|
124
124
|
}
|
|
125
125
|
|
|
126
|
-
function apiError(text, fallback) {
|
|
127
|
-
try {
|
|
128
|
-
const j = JSON.parse(text)
|
|
129
|
-
const m = j?.error?.message ?? j?.error_description ?? j?.message ?? j?.detail ?? (typeof j?.error === "string" ? j.error : "")
|
|
130
|
-
if (m) return String(m)
|
|
131
|
-
} catch {}
|
|
132
|
-
return text.trim().slice(0, 300) || fallback
|
|
133
|
-
}
|
|
134
|
-
|
|
135
126
|
// workos posts a form to WorkOS: the answer and its status.
|
|
136
127
|
async function workos(path, form, signal) {
|
|
137
128
|
const res = await fetch(WORKOS + path, {
|
|
@@ -152,7 +143,7 @@ async function authenticate(form, signal) {
|
|
|
152
143
|
t = JSON.parse(text) ?? {}
|
|
153
144
|
} catch {}
|
|
154
145
|
t.status = status
|
|
155
|
-
if (status !== 200 && !t.error) throw new FactoryStatus(status, "Factory sign-in: " +
|
|
146
|
+
if (status !== 200 && !t.error) throw new FactoryStatus(status, "Factory sign-in: " + vendorError(text, STATUS_CODES[status] ?? ""))
|
|
156
147
|
return t
|
|
157
148
|
}
|
|
158
149
|
|
|
@@ -198,7 +189,7 @@ async function factoryGet(c, path) {
|
|
|
198
189
|
factoryHeaders(h, c)
|
|
199
190
|
const res = await fetch(base(c) + path, { headers: h, signal: AbortSignal.timeout(30_000) })
|
|
200
191
|
const text = await res.text()
|
|
201
|
-
if (res.status !== 200) throw new FactoryStatus(res.status, "Factory: " +
|
|
192
|
+
if (res.status !== 200) throw new FactoryStatus(res.status, "Factory: " + vendorError(text, statusLine(res.status)))
|
|
202
193
|
return JSON.parse(text)
|
|
203
194
|
}
|
|
204
195
|
|
|
@@ -217,7 +208,7 @@ async function whoami(c, signal) {
|
|
|
217
208
|
if (c.activeOrganizationId) h["X-Factory-Org-Id"] = c.activeOrganizationId
|
|
218
209
|
const res = await fetch(base(c) + "/api/cli/whoami", { headers: h, signal: signal ?? AbortSignal.timeout(10_000) })
|
|
219
210
|
const text = await res.text()
|
|
220
|
-
if (res.status !== 200) throw new FactoryStatus(res.status, "Factory: " +
|
|
211
|
+
if (res.status !== 200) throw new FactoryStatus(res.status, "Factory: " + vendorError(text, statusLine(res.status)))
|
|
221
212
|
return JSON.parse(text) ?? {}
|
|
222
213
|
}
|
|
223
214
|
|
|
@@ -254,7 +245,85 @@ const orgRefused = (status, text) => status === 403 && text.toLowerCase().includ
|
|
|
254
245
|
function explain(status, text) {
|
|
255
246
|
if (status !== 403) return ""
|
|
256
247
|
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
|
|
248
|
+
return "Factory takes a Factory subscription's requests only from Droid itself. magpie opens other agents' requests to Factory's GPT, Grok and open models (GLM, Kimi…) as Droid's do, but Factory may still tell them apart, and Claude models (and MiniMax M2.7) are sent as the agent sent them, so Claude Code's and other agents' are refused there; use the model from Droid, and if Droid is refused it too, the organization's model policy or the plan doesn't allow this model"
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
// ---- opening as droid ---------------------------------------------------------
|
|
252
|
+
//
|
|
253
|
+
// Factory takes a subscription's model requests only from Droid (magpie
|
|
254
|
+
// #242, #506): the same account's GPT, Grok and GLM answered Droid every
|
|
255
|
+
// time and refused Codex, Grok Build and Claude Code every time, on the same
|
|
256
|
+
// models, efforts, endpoint and headers, the body the only difference. Every
|
|
257
|
+
// request droid sends opens its system prompt with one line (droid 0.231.0:
|
|
258
|
+
// its system blocks are [that line, the agent's prompt, …], sent as
|
|
259
|
+
// Responses' instructions joined with "\n", and on chat completions as one
|
|
260
|
+
// system message first, joined the same way). So another agent's request to
|
|
261
|
+
// /api/llm/o opens with the line too, as the built-in's factoryDroidBody
|
|
262
|
+
// (internal/provider/factory_client.go) has it. Anthropic's Messages
|
|
263
|
+
// (/api/llm/a) is left as the agent sent it, and so is a request that
|
|
264
|
+
// already opens with the line: droid's own goes on byte for byte.
|
|
265
|
+
|
|
266
|
+
const DROID_LINE = "You are Droid, an AI software engineering agent built by Factory."
|
|
267
|
+
|
|
268
|
+
// droidChat opens msgs' first system message with droid's line, or puts one
|
|
269
|
+
// before them with the line alone: false when it opens so already.
|
|
270
|
+
function droidChat(msgs) {
|
|
271
|
+
const first = msgs[0]
|
|
272
|
+
if (first && typeof first === "object" && first.role === "system") {
|
|
273
|
+
const c = first.content
|
|
274
|
+
if (typeof c === "string") {
|
|
275
|
+
if (c.startsWith(DROID_LINE)) return false
|
|
276
|
+
first.content = c.trim() === "" ? DROID_LINE : DROID_LINE + "\n" + c
|
|
277
|
+
return true
|
|
278
|
+
}
|
|
279
|
+
if (Array.isArray(c)) {
|
|
280
|
+
// droid sends a string, its blocks joined with "\n": text parts
|
|
281
|
+
// alone are joined so
|
|
282
|
+
let texts = [DROID_LINE]
|
|
283
|
+
for (let i = 0; i < c.length; i++) {
|
|
284
|
+
const p = c[i]
|
|
285
|
+
if (!p || typeof p !== "object" || p.type !== "text" || typeof p.text !== "string") {
|
|
286
|
+
texts = null
|
|
287
|
+
break
|
|
288
|
+
}
|
|
289
|
+
if (i === 0 && p.text.startsWith(DROID_LINE)) return false
|
|
290
|
+
texts.push(p.text)
|
|
291
|
+
}
|
|
292
|
+
first.content = texts ? texts.join("\n") : [{ type: "text", text: DROID_LINE }, ...c]
|
|
293
|
+
return true
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
msgs.unshift({ role: "system", content: DROID_LINE })
|
|
297
|
+
return true
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
// droidBody is body, a request to Factory's /api/llm/o at path, as droid
|
|
301
|
+
// would open it: Responses' instructions, or chat completions' first system
|
|
302
|
+
// message, starting with droid's line. Anything else, a body that can't be
|
|
303
|
+
// read, or one that already starts so is returned as it is.
|
|
304
|
+
function droidBody(path, body) {
|
|
305
|
+
if (!path.includes("/llm/o/") || body == null) return body
|
|
306
|
+
let text
|
|
307
|
+
if (typeof body === "string") text = body
|
|
308
|
+
else if (body instanceof ArrayBuffer || ArrayBuffer.isView(body)) text = Buffer.from(body instanceof ArrayBuffer ? body : body.buffer.slice(body.byteOffset, body.byteOffset + body.byteLength)).toString("utf8")
|
|
309
|
+
else return body
|
|
310
|
+
let m
|
|
311
|
+
try {
|
|
312
|
+
m = JSON.parse(text)
|
|
313
|
+
} catch {
|
|
314
|
+
return body
|
|
315
|
+
}
|
|
316
|
+
if (!m || typeof m !== "object" || Array.isArray(m)) return body
|
|
317
|
+
if (path.endsWith("/responses")) {
|
|
318
|
+
const v = m.instructions
|
|
319
|
+
if (v !== undefined && v !== null && typeof v !== "string") return body // not something droid sends
|
|
320
|
+
const ins = v ?? ""
|
|
321
|
+
if (ins.startsWith(DROID_LINE)) return body
|
|
322
|
+
m.instructions = ins.trim() === "" ? DROID_LINE : DROID_LINE + "\n" + ins
|
|
323
|
+
} else if (path.endsWith("/chat/completions")) {
|
|
324
|
+
if (!Array.isArray(m.messages) || !droidChat(m.messages)) return body
|
|
325
|
+
} else return body
|
|
326
|
+
return JSON.stringify(m)
|
|
258
327
|
}
|
|
259
328
|
|
|
260
329
|
// errorReply is an error as the API the request was for words one:
|
|
@@ -268,6 +337,44 @@ function errorReply(url, status, type, message, headers = new Headers()) {
|
|
|
268
337
|
return new Response(JSON.stringify(body), { status, headers })
|
|
269
338
|
}
|
|
270
339
|
|
|
340
|
+
// said is an answer with magpie's X-Magpie-Sign-In, which tells what it
|
|
341
|
+
// means for the account's sign-in whatever its status: "expired" marks it
|
|
342
|
+
// lapsed, "kept" leaves it be. magpie takes it off before the agent sees it.
|
|
343
|
+
function said(res, v) {
|
|
344
|
+
const h = new Headers(res.headers)
|
|
345
|
+
h.set("X-Magpie-Sign-In", v)
|
|
346
|
+
return new Response(res.body, { status: res.status, statusText: res.statusText, headers: h })
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
// ---- API keys -----------------------------------------------------------------
|
|
350
|
+
//
|
|
351
|
+
// A Factory API key (fk-…), as droid takes one from FACTORY_API_KEY: its
|
|
352
|
+
// om() hands the key on as the token, sent as "Authorization: Bearer fk-…"
|
|
353
|
+
// with the headers every request carries, and never renewed. droid's active
|
|
354
|
+
// org (st(), X-Factory-Org-Id) is what a sign-in stored, so a key alone
|
|
355
|
+
// sends none. As the built-in's factory_key.go keeps one.
|
|
356
|
+
|
|
357
|
+
const isKey = (a) => a?.type === "api" && typeof a.key === "string" && a.key.trim() !== ""
|
|
358
|
+
|
|
359
|
+
// keyAccount is a key as the account the requests are signed with.
|
|
360
|
+
function keyAccount(a) {
|
|
361
|
+
const md = a.metadata ?? {}
|
|
362
|
+
const key = a.key.trim()
|
|
363
|
+
return {
|
|
364
|
+
key: true,
|
|
365
|
+
access: key,
|
|
366
|
+
refresh: "",
|
|
367
|
+
expires: 0,
|
|
368
|
+
accountId: md.email || md.userId || "",
|
|
369
|
+
email: md.email ?? "",
|
|
370
|
+
userId: md.userId ?? "",
|
|
371
|
+
activeOrganizationId: "",
|
|
372
|
+
region: md.region ?? "",
|
|
373
|
+
premBaseHost: md.premBaseHost ?? "",
|
|
374
|
+
whoKnown: typeof md.region === "string",
|
|
375
|
+
}
|
|
376
|
+
}
|
|
377
|
+
|
|
271
378
|
// ---- sign-in ----------------------------------------------------------------
|
|
272
379
|
|
|
273
380
|
// signedInWith is the account WorkOS just signed in, as droid keeps it: a
|
|
@@ -319,7 +426,7 @@ async function signedInWith(t) {
|
|
|
319
426
|
|
|
320
427
|
async function deviceSignIn() {
|
|
321
428
|
const { text, status } = await workos("/authorize/device", { client_id: CLIENT_ID })
|
|
322
|
-
if (status !== 200) throw new FactoryStatus(status, "Factory sign-in: " +
|
|
429
|
+
if (status !== 200) throw new FactoryStatus(status, "Factory sign-in: " + vendorError(text, STATUS_CODES[status] ?? ""))
|
|
323
430
|
const dc = JSON.parse(text)
|
|
324
431
|
if (!dc.device_code || !dc.user_code) throw new Error("Factory's sign-in gave no device code")
|
|
325
432
|
let interval = Math.max(dc.interval ?? 0, 1) * 1000
|
|
@@ -476,8 +583,8 @@ export const FactoryAuthPlugin = async ({ client }) => {
|
|
|
476
583
|
// when each account last asked whoami for its org, so one whoami can't
|
|
477
584
|
// answer doesn't ask before every request, nor hold back the others
|
|
478
585
|
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())
|
|
586
|
+
const askedOf = (c) => asked.get(c.accountId || c.refresh || c.access || "") ?? 0
|
|
587
|
+
const ask = (c) => asked.set(c.accountId || c.refresh || c.access || "", Date.now())
|
|
481
588
|
|
|
482
589
|
// account is the account getAuth reads, with what keeps its token live
|
|
483
590
|
// and its org right.
|
|
@@ -488,10 +595,39 @@ export const FactoryAuthPlugin = async ({ client }) => {
|
|
|
488
595
|
}
|
|
489
596
|
const current = async () => {
|
|
490
597
|
const a = await getAuth()
|
|
598
|
+
if (isKey(a)) return keyAccount(a)
|
|
491
599
|
if (a?.type !== "oauth" || !a.access) throw new Error("Factory: not signed in")
|
|
492
600
|
return { ...a }
|
|
493
601
|
}
|
|
494
602
|
|
|
603
|
+
// keyed is a key account with where Factory serves its org: whoami,
|
|
604
|
+
// asked with the key and no org (droid's st() is null for a key), as
|
|
605
|
+
// droid's yP checks a key before it is used, and as the built-in asks
|
|
606
|
+
// it when the key is added. What it names is kept in the key's
|
|
607
|
+
// metadata, so magpie shows whose the key is; a whoami that fails is
|
|
608
|
+
// asked again ASK_AGAIN later, the request going on meanwhile.
|
|
609
|
+
const keyed = async (c) => {
|
|
610
|
+
if (c.whoKnown || Date.now() - askedOf(c) < ASK_AGAIN) return c
|
|
611
|
+
ask(c)
|
|
612
|
+
let who
|
|
613
|
+
try {
|
|
614
|
+
who = await whoami({ ...c, activeOrganizationId: "" })
|
|
615
|
+
} catch {
|
|
616
|
+
return c
|
|
617
|
+
}
|
|
618
|
+
c.region = who.region ?? ""
|
|
619
|
+
c.premBaseHost = who.premBaseHostV2 ?? ""
|
|
620
|
+
c.email ||= who.email ?? ""
|
|
621
|
+
c.userId ||= who.userId ?? ""
|
|
622
|
+
c.whoKnown = true
|
|
623
|
+
const a = await getAuth()
|
|
624
|
+
if (isKey(a) && a.key === c.access) {
|
|
625
|
+
const metadata = { ...(a.metadata ?? {}), email: c.email, userId: c.userId, region: c.region, premBaseHost: c.premBaseHost }
|
|
626
|
+
await client.auth.set({ path: { id: PROVIDER }, body: { ...a, metadata } }).catch(() => {})
|
|
627
|
+
}
|
|
628
|
+
return c
|
|
629
|
+
}
|
|
630
|
+
|
|
495
631
|
// orgOf fills in the active org when there is none: droid asks
|
|
496
632
|
// whoami as soon as it holds a token and sends the orgId it answers
|
|
497
633
|
// as X-Factory-Org-Id on every request after.
|
|
@@ -502,10 +638,12 @@ export const FactoryAuthPlugin = async ({ client }) => {
|
|
|
502
638
|
return c
|
|
503
639
|
}
|
|
504
640
|
|
|
505
|
-
// fresh is a live token, renewed near its end
|
|
506
|
-
|
|
641
|
+
// fresh is a live token, renewed near its end; renewed is told when
|
|
642
|
+
// it was, the built-in's clearing of the account's lapse.
|
|
643
|
+
const fresh = (renewed) =>
|
|
507
644
|
locked(async () => {
|
|
508
645
|
const c = await current()
|
|
646
|
+
if (c.key) return keyed(c) // an API key: nothing to renew, and no org with it
|
|
509
647
|
if ((c.expires > 0 && Date.now() < c.expires - REFRESH_LEAD) || !c.refresh) return orgOf(c)
|
|
510
648
|
let t
|
|
511
649
|
try {
|
|
@@ -523,6 +661,7 @@ export const FactoryAuthPlugin = async ({ client }) => {
|
|
|
523
661
|
await reconcile(c)
|
|
524
662
|
ask(c)
|
|
525
663
|
await save(c)
|
|
664
|
+
renewed?.()
|
|
526
665
|
return c
|
|
527
666
|
})
|
|
528
667
|
|
|
@@ -530,12 +669,14 @@ export const FactoryAuthPlugin = async ({ client }) => {
|
|
|
530
669
|
// can't reach is left off and whoami asked again without it; with
|
|
531
670
|
// no header sent, the token is put in the first org /api/cli/org
|
|
532
671
|
// 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
|
-
|
|
672
|
+
// for one. True when the request is worth sending again; renewed is
|
|
673
|
+
// told when the token was.
|
|
674
|
+
const mendOrg = (status, text, renewed) =>
|
|
535
675
|
locked(async () => {
|
|
536
676
|
if (status !== 403) return false
|
|
537
677
|
const isOrg = orgRefused(status, text)
|
|
538
678
|
const c = await current()
|
|
679
|
+
if (c.key) return false // an API key carries no org droid would send
|
|
539
680
|
if (c.activeOrganizationId) {
|
|
540
681
|
if (!isOrg) return false // the org was sent: the refusal is about something else
|
|
541
682
|
const was = c.activeOrganizationId
|
|
@@ -570,14 +711,20 @@ export const FactoryAuthPlugin = async ({ client }) => {
|
|
|
570
711
|
c.orgId = org
|
|
571
712
|
if (t.refresh_token) c.refresh = t.refresh_token
|
|
572
713
|
await save(c)
|
|
714
|
+
renewed?.()
|
|
573
715
|
return true
|
|
574
716
|
})
|
|
575
717
|
|
|
576
718
|
// usage is the account's limits, asked once more when Factory refused
|
|
577
|
-
// an org that was put right
|
|
719
|
+
// an org that was put right. signIn is what the read did to the
|
|
720
|
+
// built-in's lapse mark: a renewal took it off whatever came after, a
|
|
721
|
+
// refused one put it on, a read that renewed nothing left it be (a
|
|
722
|
+
// clean read too)
|
|
578
723
|
const usage = async () => {
|
|
724
|
+
let signIn = "kept"
|
|
725
|
+
const onRenew = () => (signIn = "renewed")
|
|
579
726
|
const limits = async () => {
|
|
580
|
-
const c = await fresh()
|
|
727
|
+
const c = await fresh(onRenew)
|
|
581
728
|
const h = new Headers({ Accept: "application/json" })
|
|
582
729
|
factoryHeaders(h, c)
|
|
583
730
|
const res = await fetch(base(c) + "/api/billing/limits", { headers: h, signal: AbortSignal.timeout(15_000) })
|
|
@@ -590,13 +737,14 @@ export const FactoryAuthPlugin = async ({ client }) => {
|
|
|
590
737
|
try {
|
|
591
738
|
l = await limits()
|
|
592
739
|
} catch (e) {
|
|
593
|
-
if (!(e instanceof FactoryStatus && e.body !== undefined && (await mendOrg(e.code, e.body).catch(() => false)))) throw e
|
|
740
|
+
if (!(e instanceof FactoryStatus && e.body !== undefined && (await mendOrg(e.code, e.body, onRenew).catch(() => false)))) throw e
|
|
594
741
|
l = await limits()
|
|
595
742
|
}
|
|
596
|
-
if (!l?.limits?.standard) return { error: "Factory: the account reported no limits" }
|
|
597
|
-
return { windows: limitWindows(l) }
|
|
743
|
+
if (!l?.limits?.standard) return { error: "Factory: the account reported no limits", signIn }
|
|
744
|
+
return { windows: limitWindows(l), signIn }
|
|
598
745
|
} catch (e) {
|
|
599
|
-
|
|
746
|
+
if (e?.lapsed) signIn = "expired"
|
|
747
|
+
return { error: e?.message ?? String(e), signIn }
|
|
600
748
|
}
|
|
601
749
|
}
|
|
602
750
|
|
|
@@ -623,6 +771,8 @@ export const FactoryAuthPlugin = async ({ client }) => {
|
|
|
623
771
|
label: "Sign in with Factory (device code)",
|
|
624
772
|
authorize: deviceSignIn,
|
|
625
773
|
},
|
|
774
|
+
// droid's FACTORY_API_KEY: the key is the bearer, never renewed
|
|
775
|
+
{ type: "api", label: "Factory API key (fk-…)", placeholder: "fk-…" },
|
|
626
776
|
],
|
|
627
777
|
// magpie's own hook: the account's limits
|
|
628
778
|
async usage(getAuth) {
|
|
@@ -630,12 +780,12 @@ export const FactoryAuthPlugin = async ({ client }) => {
|
|
|
630
780
|
},
|
|
631
781
|
async loader(getAuth) {
|
|
632
782
|
const first = await getAuth()
|
|
633
|
-
if (first?.type !== "oauth") return {}
|
|
783
|
+
if (first?.type !== "oauth" && !isKey(first)) return {}
|
|
634
784
|
|
|
635
785
|
const { fresh, mendOrg } = account(getAuth)
|
|
636
786
|
|
|
637
|
-
const send = async (input, init, body) => {
|
|
638
|
-
const c = await fresh()
|
|
787
|
+
const send = async (input, init, body, renewed) => {
|
|
788
|
+
const c = await fresh(renewed)
|
|
639
789
|
let url = input instanceof Request ? input.url : String(input)
|
|
640
790
|
// an EU org is served from Factory's EU region, an on-prem one
|
|
641
791
|
// from its own host: the request goes there
|
|
@@ -655,7 +805,10 @@ export const FactoryAuthPlugin = async ({ client }) => {
|
|
|
655
805
|
// droid's Anthropic client is made with the key "placeholder",
|
|
656
806
|
// which Anthropic's SDK sends beside the bearer token
|
|
657
807
|
if (path.includes("/llm/a/")) h.set("X-Api-Key", "placeholder")
|
|
658
|
-
|
|
808
|
+
// another agent's request opens as droid's does (droidBody)
|
|
809
|
+
const out = droidBody(path, body)
|
|
810
|
+
if (out !== body) h.delete("content-length")
|
|
811
|
+
return fetch(url, { ...init, method: init?.method ?? (input instanceof Request ? input.method : "POST"), headers: h, body: out })
|
|
659
812
|
}
|
|
660
813
|
|
|
661
814
|
return {
|
|
@@ -665,25 +818,33 @@ export const FactoryAuthPlugin = async ({ client }) => {
|
|
|
665
818
|
if (body == null && input instanceof Request && input.body) body = new Uint8Array(await input.arrayBuffer())
|
|
666
819
|
if (body instanceof ReadableStream) body = new Uint8Array(await new Response(body).arrayBuffer())
|
|
667
820
|
const url = input instanceof Request ? input.url : String(input)
|
|
821
|
+
// the built-in takes an account's lapse off when it renews the
|
|
822
|
+
// token, whatever the request then meets, and never for an
|
|
823
|
+
// answer: a 401 of Factory's leaves it be, and so does a success
|
|
824
|
+
// with no renewal on the way
|
|
825
|
+
let renewed = false
|
|
826
|
+
const onRenew = () => (renewed = true)
|
|
827
|
+
const answer = (res) => said(res, renewed ? "renewed" : "kept")
|
|
668
828
|
let res
|
|
669
829
|
try {
|
|
670
|
-
res = await send(input, init, body)
|
|
830
|
+
res = await send(input, init, body, onRenew)
|
|
831
|
+
if (res.status !== 403) return answer(res)
|
|
832
|
+
let text = await res.text()
|
|
833
|
+
if (await mendOrg(res.status, text, onRenew).catch(() => false)) {
|
|
834
|
+
res = await send(input, init, body, onRenew)
|
|
835
|
+
if (res.status !== 403) return answer(res)
|
|
836
|
+
text = await res.text()
|
|
837
|
+
}
|
|
838
|
+
const why = explain(res.status, text)
|
|
839
|
+
// the refusal, then what to do about it, as provider.Explain joins them
|
|
840
|
+
const msg = `${vendorError(text, statusLine(res.status))} — ${why}`
|
|
841
|
+
return answer(errorReply(url, res.status, "permission_error", msg, new Headers(res.headers)))
|
|
671
842
|
} catch (e) {
|
|
672
|
-
// Factory refused to renew the sign-in: the
|
|
673
|
-
|
|
843
|
+
// Factory refused to renew the sign-in: the built-in failed the
|
|
844
|
+
// request (magpie's 502) and marked the account lapsed
|
|
845
|
+
if (e?.lapsed) return said(errorReply(url, 502, "api_error", e.message), "expired")
|
|
674
846
|
throw e
|
|
675
847
|
}
|
|
676
|
-
if (res.status !== 403) return res
|
|
677
|
-
let text = await res.text()
|
|
678
|
-
if (await mendOrg(res.status, text).catch(() => false)) {
|
|
679
|
-
res = await send(input, init, body)
|
|
680
|
-
if (res.status !== 403) return res
|
|
681
|
-
text = await res.text()
|
|
682
|
-
}
|
|
683
|
-
const why = explain(res.status, text)
|
|
684
|
-
// the refusal, then what to do about it, as provider.Explain joins them
|
|
685
|
-
const msg = `${apiError(text, "403 Forbidden")} — ${why}`
|
|
686
|
-
return errorReply(url, res.status, "permission_error", msg, new Headers(res.headers))
|
|
687
848
|
},
|
|
688
849
|
}
|
|
689
850
|
},
|
|
@@ -692,4 +853,4 @@ export const FactoryAuthPlugin = async ({ client }) => {
|
|
|
692
853
|
}
|
|
693
854
|
|
|
694
855
|
// for tests
|
|
695
|
-
export const _internal = { limitWindows, windowEnd, dollars, vendorError, CORE }
|
|
856
|
+
export const _internal = { limitWindows, windowEnd, dollars, vendorError, CORE, droidBody, DROID_LINE }
|