@magpie-community/opencode-factory-auth 0.1.4 → 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.
Files changed (3) hide show
  1. package/README.md +15 -0
  2. package/index.mjs +151 -8
  3. 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.229.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"], false],
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],
@@ -245,7 +245,85 @@ const orgRefused = (status, text) => status === 403 && text.toLowerCase().includ
245
245
  function explain(status, text) {
246
246
  if (status !== 403) return ""
247
247
  if (orgRefused(status, text)) return "the Factory account's organization changed; remove the account in magpie and sign in to it again"
248
- 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"
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)
249
327
  }
250
328
 
251
329
  // errorReply is an error as the API the request was for words one:
@@ -268,6 +346,35 @@ function said(res, v) {
268
346
  return new Response(res.body, { status: res.status, statusText: res.statusText, headers: h })
269
347
  }
270
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
@@ -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.
@@ -507,6 +643,7 @@ export const FactoryAuthPlugin = async ({ client }) => {
507
643
  const fresh = (renewed) =>
508
644
  locked(async () => {
509
645
  const c = await current()
646
+ if (c.key) return keyed(c) // an API key: nothing to renew, and no org with it
510
647
  if ((c.expires > 0 && Date.now() < c.expires - REFRESH_LEAD) || !c.refresh) return orgOf(c)
511
648
  let t
512
649
  try {
@@ -539,6 +676,7 @@ export const FactoryAuthPlugin = async ({ client }) => {
539
676
  if (status !== 403) return false
540
677
  const isOrg = orgRefused(status, text)
541
678
  const c = await current()
679
+ if (c.key) return false // an API key carries no org droid would send
542
680
  if (c.activeOrganizationId) {
543
681
  if (!isOrg) return false // the org was sent: the refusal is about something else
544
682
  const was = c.activeOrganizationId
@@ -633,6 +771,8 @@ export const FactoryAuthPlugin = async ({ client }) => {
633
771
  label: "Sign in with Factory (device code)",
634
772
  authorize: deviceSignIn,
635
773
  },
774
+ // droid's FACTORY_API_KEY: the key is the bearer, never renewed
775
+ { type: "api", label: "Factory API key (fk-…)", placeholder: "fk-…" },
636
776
  ],
637
777
  // magpie's own hook: the account's limits
638
778
  async usage(getAuth) {
@@ -640,7 +780,7 @@ export const FactoryAuthPlugin = async ({ client }) => {
640
780
  },
641
781
  async loader(getAuth) {
642
782
  const first = await getAuth()
643
- if (first?.type !== "oauth") return {}
783
+ if (first?.type !== "oauth" && !isKey(first)) return {}
644
784
 
645
785
  const { fresh, mendOrg } = account(getAuth)
646
786
 
@@ -665,7 +805,10 @@ export const FactoryAuthPlugin = async ({ client }) => {
665
805
  // droid's Anthropic client is made with the key "placeholder",
666
806
  // which Anthropic's SDK sends beside the bearer token
667
807
  if (path.includes("/llm/a/")) h.set("X-Api-Key", "placeholder")
668
- return fetch(url, { ...init, method: init?.method ?? (input instanceof Request ? input.method : "POST"), headers: h, body })
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 })
669
812
  }
670
813
 
671
814
  return {
@@ -710,4 +853,4 @@ export const FactoryAuthPlugin = async ({ client }) => {
710
853
  }
711
854
 
712
855
  // for tests
713
- export const _internal = { limitWindows, windowEnd, dollars, vendorError, CORE }
856
+ export const _internal = { limitWindows, windowEnd, dollars, vendorError, CORE, droidBody, DROID_LINE }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@magpie-community/opencode-factory-auth",
3
- "version": "0.1.4",
3
+ "version": "0.1.5",
4
4
  "description": "Sign in to a Factory (Droid) subscription from OpenCode or magpie",
5
5
  "type": "module",
6
6
  "main": "./index.mjs",