@magpie-community/opencode-factory-auth 0.1.24 → 0.1.26

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 +18 -5
  2. package/index.mjs +184 -8
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -63,19 +63,32 @@ Each model is served on the one API droid uses for it:
63
63
 
64
64
  | API | Models |
65
65
  |---|---|
66
- | Anthropic Messages (`/api/llm/a`) | Fable 5.1, Fable 5, Opus 5.5, Opus 5, Opus 4.8, Sonnet 5.5, Sonnet 5, Sonnet 4.6, Haiku 4.5, MiniMax M2.7 |
66
+ | Anthropic Messages (`/api/llm/a`) | Fable 5.1, Fable 5, Opus 5.5, Opus 5, Opus 4.8, Sonnet 5.5, Sonnet 5, Sonnet 4.6, Haiku 5.5, Haiku 4.5, MiniMax M2.7 |
67
67
  | OpenAI Responses (`/api/llm/o/v1`) | GPT-6.1 Sol, GPT-6 Sol/Astra/Luna, GPT-5.6 Sol/Terra/Luna, GPT-5.5, GPT-5.4, GPT-5.3-Codex, Grok 4.7, Grok 4.6 |
68
- | Chat completions (`/api/llm/o/v1`) | GLM-5.3, GLM-5.3-Flash, GLM-5.2, Kimi K3, DeepSeek V4.1 Flash, Qwen3.8 Max, MiniMax M3, Mistral Medium 3.5, Nemotron 3 Ultra |
68
+ | Chat completions (`/api/llm/o/v1`) | GLM-5.3, GLM-5.3-Flash, GLM-5.2, Kimi K3, DeepSeek V4.1 Flash, Qwen3.8 Max, MiniMax M3, Mistral Large 4, Mistral Medium 3.5, Nemotron 3 Ultra |
69
+ | Gemini generate (`/api/llm/g/v1/generate`) | Gemini 4 Argon, Gemini 3.1 Pro, Gemini 3.8/3.7/3.6/3.5 Flash, Gemini 3 Flash |
69
70
 
70
71
  Reasoning efforts are the variants droid offers for each model. DeepSeek V4.1
71
72
  Flash, Kimi K3 and GLM-5.2 have `none`, droid's "off": they stop thinking.
72
73
  Reasoning is mandatory on GLM-5.3 and GLM-5.3-Flash (Fireworks turns `none`
73
74
  away), so `low` is their least.
74
75
 
75
- The list is not included:
76
+ Gemini's requests go to Factory's generate route with the model in the
77
+ body, droid's line opening the system instruction. Gemini 4 Argon is behind
78
+ a Factory feature flag in droid 0.241.1, so an account it isn't on for may
79
+ be refused it.
76
80
 
77
- - Gemini, which Factory sends on a route of its own.
78
- - auto, which droid picks on the client side.
81
+ auto is not included: droid picks it on the client side.
82
+
83
+ ## Requests too large
84
+
85
+ Factory refuses a request body over its size limit with 413 "Request
86
+ Entity Too Large". The limit is on bytes, not on the model's context, and
87
+ images reach it first. On a 413 the plugin sends the request once more with
88
+ every image and file but the newest replaced by a line saying it was left
89
+ out, each tool result kept beside its call, as droid does. If that is still
90
+ too large, or there was nothing to leave out, the error says it is
91
+ Factory's byte limit: compact the conversation or start a new one.
79
92
 
80
93
  ## Use
81
94
 
package/index.mjs CHANGED
@@ -27,15 +27,25 @@ const ASK_AGAIN = 10 * 60 * 1000
27
27
  const ANTHROPIC = { npm: "@ai-sdk/anthropic", api: API + "/api/llm/a/v1" }
28
28
  const RESPONSES = { npm: "@ai-sdk/openai", api: API + "/api/llm/o/v1" }
29
29
  const CHAT = { npm: "@ai-sdk/openai-compatible", api: API + "/api/llm/o/v1" }
30
+ // Gemini's go to Factory's /api/llm/g/v1/generate, the model in the body
31
+ // (geminiBody); the AI SDK's Google package asks for :streamGenerateContent
32
+ // under models/, which send() takes there
33
+ const GEMINI = { npm: "@ai-sdk/google", api: API + "/api/llm/g/v1" }
30
34
 
31
35
  const E5 = ["low", "medium", "high", "xhigh", "max"]
32
36
  const E6 = ["none", "low", "medium", "high", "xhigh", "max"]
33
37
  const E4 = ["low", "medium", "high", "xhigh"]
34
38
 
35
- // The models droid's /model picker offers, less Gemini's (sent on a route of
36
- // Factory's own) and auto (droid picks it client side): id, name, the wire
37
- // droid sends it on, the vendor it names in x-api-provider, context, output,
38
- // reasoning efforts, images.
39
+ // The models droid's /model picker offers, less auto (droid picks it client
40
+ // side): id, name, the wire droid sends it on, the vendor it names in
41
+ // x-api-provider, context, output, reasoning efforts, images. Haiku 5.5 and
42
+ // Mistral Large 4 are droid 0.240.0's (models.test.mjs reads its registry);
43
+ // GPT-6 Astra Ultra Fast, new there too, stays out: droid offers it only
44
+ // after the user accepts Factory's high-cost terms for it
45
+ // (explicitOptInRequirement). Gemini's are droid 0.241.1's, as magpie's
46
+ // built-in has them (yetone/magpie#2080); Gemini 4 Argon is behind a
47
+ // feature flag of Factory's there, so an account it isn't on for may be
48
+ // refused it.
39
49
  const MODELS = [
40
50
  ["claude-fable-5.1", "Fable 5.1", ANTHROPIC, "anthropic", 867000, 128000, E5, true],
41
51
  ["claude-fable-5", "Fable 5", ANTHROPIC, "anthropic", 867000, 128000, E5, true],
@@ -45,6 +55,7 @@ const MODELS = [
45
55
  ["claude-sonnet-5-5", "Sonnet 5.5", ANTHROPIC, "anthropic", 872000, 128000, E5, true],
46
56
  ["claude-sonnet-5", "Sonnet 5", ANTHROPIC, "anthropic", 872000, 128000, E5, true],
47
57
  ["claude-sonnet-4-6", "Sonnet 4.6", ANTHROPIC, "anthropic", 931000, 64000, ["low", "medium", "high", "max"], true],
58
+ ["claude-haiku-5-5", "Haiku 5.5", ANTHROPIC, "anthropic", 872000, 128000, E5, true],
48
59
  ["claude-haiku-4-5-20251001", "Haiku 4.5", ANTHROPIC, "anthropic", 0, 0, ["low", "medium", "high"], true],
49
60
  ["gpt-6.1-sol", "GPT-6.1 Sol", RESPONSES, "openai", 1050000, 128000, E5, true],
50
61
  ["gpt-6-sol", "GPT-6 Sol", RESPONSES, "openai", 1050000, 128000, E6, true],
@@ -69,8 +80,16 @@ const MODELS = [
69
80
  ["qwen3.8-max", "Qwen3.8 Max", CHAT, "fireworks", 262144, 131072, ["low", "medium", "xhigh"], false],
70
81
  ["minimax-m3", "MiniMax M3", CHAT, "fireworks", 512000, 64000, ["high"], true],
71
82
  ["minimax-m2.7", "MiniMax M2.7", ANTHROPIC, "fireworks", 196600, 64000, ["high"], false],
83
+ ["mistral-large-4", "Mistral Large 4", CHAT, "mistral", 524288, 64000, ["high"], true],
72
84
  ["mistral-medium-3.5", "Mistral Medium 3.5", CHAT, "mistral", 256000, 64000, ["high"], true],
73
85
  ["nemotron-3-ultra", "Nemotron 3 Ultra", CHAT, "baseten", 202000, 65536, ["high"], false],
86
+ ["gemini-4-argon", "Gemini 4 Argon", GEMINI, "google", 1000000, 65536, ["low", "medium", "high"], true],
87
+ ["gemini-3.1-pro-preview", "Gemini 3.1 Pro", GEMINI, "google", 1000000, 65536, ["low", "medium", "high"], true],
88
+ ["gemini-3.8-flash", "Gemini 3.8 Flash", GEMINI, "google", 1000000, 65536, ["low", "medium", "high"], true],
89
+ ["gemini-3.7-flash", "Gemini 3.7 Flash", GEMINI, "google", 1000000, 65536, ["low", "medium", "high"], true],
90
+ ["gemini-3.6-flash", "Gemini 3.6 Flash", GEMINI, "google", 1000000, 65536, ["low", "medium", "high"], true],
91
+ ["gemini-3.5-flash", "Gemini 3.5 Flash", GEMINI, "google", 1000000, 65536, ["minimal", "low", "medium", "high"], true],
92
+ ["gemini-3-flash-preview", "Gemini 3 Flash", GEMINI, "google", 1000000, 65536, ["minimal", "low", "medium", "high"], true],
74
93
  ].map(([id, name, wire, upstream, context, output, efforts, images]) => ({ id, name, wire, upstream, context, output, efforts, images }))
75
94
 
76
95
  const byId = new Map(MODELS.map((m) => [m.id, m]))
@@ -78,6 +97,7 @@ const byId = new Map(MODELS.map((m) => [m.id, m]))
78
97
  // variant is what the AI SDK package a model is on is given for an effort.
79
98
  function variant(npm, effort) {
80
99
  if (npm === ANTHROPIC.npm) return { effort }
100
+ if (npm === GEMINI.npm) return { thinkingConfig: { includeThoughts: true, thinkingLevel: effort } }
81
101
  return { reasoningEffort: effort }
82
102
  }
83
103
 
@@ -395,6 +415,136 @@ function droidBody(path, body) {
395
415
  return JSON.stringify(m)
396
416
  }
397
417
 
418
+ // bodyText is a request body as text, or null for one that isn't.
419
+ function bodyText(body) {
420
+ if (typeof body === "string") return body
421
+ if (body instanceof ArrayBuffer || ArrayBuffer.isView(body)) return Buffer.from(body instanceof ArrayBuffer ? body : body.buffer.slice(body.byteOffset, body.byteOffset + body.byteLength)).toString("utf8")
422
+ return null
423
+ }
424
+
425
+ // GEMINI_CALL is the AI SDK Google package's request path, the model in it.
426
+ const GEMINI_CALL = /\/models\/([^/:]+):(?:stream)?generateContent$/i
427
+
428
+ // geminiBody is body, a Gemini generateContent request for model, as
429
+ // Factory's /api/llm/g/v1/generate takes it, as magpie's built-in sends it
430
+ // (buildGemini, factoryDroidGoogle): the model in the body, the system
431
+ // instruction without a role and opening with droid's line, as one text part
432
+ // of droid's line and the instruction's text parts joined with "\n", then
433
+ // its other parts. A body that can't be read goes on as it is.
434
+ function geminiBody(model, body) {
435
+ const text = bodyText(body)
436
+ if (text == null) return body
437
+ let m
438
+ try {
439
+ m = JSON.parse(text)
440
+ } catch {
441
+ return body
442
+ }
443
+ if (!m || typeof m !== "object" || Array.isArray(m)) return body
444
+ m.model = model
445
+ delete m.stream
446
+ let si = m.systemInstruction
447
+ if (typeof si === "string") si = { parts: [{ text: si }] }
448
+ if (!si || typeof si !== "object") si = { parts: [] }
449
+ delete si.role
450
+ const parts = Array.isArray(si.parts) ? si.parts : []
451
+ if (!(typeof parts[0]?.text === "string" && parts[0].text.startsWith(DROID_LINE))) {
452
+ const texts = []
453
+ const rest = []
454
+ for (const p of parts) {
455
+ if (p && typeof p === "object" && typeof p.text === "string" && Object.keys(p).length === 1) texts.push(p.text)
456
+ else rest.push(p)
457
+ }
458
+ const joined = texts.join("\n")
459
+ si.parts = [{ text: joined.trim() === "" ? DROID_LINE : DROID_LINE + "\n" + joined }, ...rest]
460
+ }
461
+ m.systemInstruction = si
462
+ return JSON.stringify(m)
463
+ }
464
+
465
+ // ---- request size -------------------------------------------------------------
466
+ //
467
+ // Factory answers a request body over its size limit with 413 "Request
468
+ // Entity Too Large": a limit on bytes, not on the model's context, which
469
+ // the images an agent's session gathers reach long before its tokens do
470
+ // (yetone/magpie#2082: nine screenshots, ~4.5 MB of data URLs, on Opus
471
+ // 5.5). droid 0.239.0 leaves older images and PDFs out of such a request.
472
+ // The plugin does the same once, on a 413: every image and file but the
473
+ // newest KEEP_ATTACHMENTS becomes a line saying it was left out, in place,
474
+ // so each tool result stays beside its call. Failing that, the 413 says
475
+ // what it is and what to do.
476
+
477
+ const KEEP_ATTACHMENTS = 1
478
+ const LEFT_OUT = "[An earlier image or file was left out of this request: it was over Factory's request size limit.]"
479
+ // what magpie's gateway adds to a 413 (internal/gateway/gateway.go,
480
+ // writeError), said here too for OpenCode; the gateway, finding it, adds
481
+ // it no second time
482
+ const TOO_LARGE_HINT = "This is a request-body byte limit, not the model's context: compact the conversation (/compact in Codex or Claude Code), or start a new one with a short summary; fewer images or smaller tool results also help."
483
+
484
+ // dialectOf is which API's body a request to path carries, as attachments
485
+ // are found in it, or "" for one that has none to leave out.
486
+ function dialectOf(path) {
487
+ if (path.includes("/llm/a/") && path.endsWith("/messages")) return "anthropic"
488
+ if (path.endsWith("/responses")) return "responses"
489
+ if (path.endsWith("/chat/completions")) return "chat"
490
+ if (GEMINI_CALL.test(path) || path.endsWith("/llm/g/v1/generate")) return "gemini"
491
+ return ""
492
+ }
493
+
494
+ const DIALECTS = {
495
+ anthropic: { list: "messages", is: (p) => p.type === "image" || p.type === "document", text: (p) => ({ type: "text", text: LEFT_OUT, ...(p.cache_control ? { cache_control: p.cache_control } : {}) }) },
496
+ responses: { list: "input", is: (p) => p.type === "input_image" || p.type === "input_file", text: () => ({ type: "input_text", text: LEFT_OUT }) },
497
+ chat: { list: "messages", is: (p) => p.type === "image_url" || p.type === "file", text: () => ({ type: "text", text: LEFT_OUT }) },
498
+ gemini: { list: "contents", is: (p) => !!(p.inlineData || p.inline_data || p.fileData || p.file_data), text: () => ({ text: LEFT_OUT }) },
499
+ }
500
+
501
+ // leaveOutAttachments is body, a request to path, with every image and file
502
+ // but the newest KEEP_ATTACHMENTS left out, and how many were: null when
503
+ // there are none to leave out or the body can't be read.
504
+ function leaveOutAttachments(path, body) {
505
+ const d = DIALECTS[dialectOf(path)]
506
+ const text = d && bodyText(body)
507
+ if (!text) return null
508
+ let m
509
+ try {
510
+ m = JSON.parse(text)
511
+ } catch {
512
+ return null
513
+ }
514
+ if (!Array.isArray(m?.[d.list])) return null
515
+ // in the order they were sent: the array each is in, its place, and
516
+ // whether the array is a Gemini function response's parts, which take
517
+ // inline data alone
518
+ const found = []
519
+ const walk = (v, key) => {
520
+ if (Array.isArray(v)) {
521
+ v.forEach((p, i) => {
522
+ if (p && typeof p === "object" && !Array.isArray(p) && d.is(p)) found.push({ list: v, i, drop: key === "functionResponse" })
523
+ else walk(p, key)
524
+ })
525
+ } else if (v && typeof v === "object") {
526
+ for (const [k, x] of Object.entries(v)) walk(x, k === "functionResponse" ? k : key)
527
+ }
528
+ }
529
+ walk(m[d.list], "")
530
+ const out = found.slice(0, Math.max(found.length - KEEP_ATTACHMENTS, 0))
531
+ if (out.length === 0) return null
532
+ // from the last, so a part dropped doesn't move the places before it
533
+ for (const { list, i, drop } of out.reverse()) {
534
+ if (drop) list.splice(i, 1)
535
+ else list[i] = d.text(list[i])
536
+ }
537
+ return { body: JSON.stringify(m), left: out.length }
538
+ }
539
+
540
+ // tooLarge is what a 413 of Factory's says to the agent: Factory's own
541
+ // words, that the limit is on bytes, what the plugin left out, and the hint.
542
+ function tooLarge(text, left) {
543
+ const said = vendorError(text, "413")
544
+ const tried = left > 0 ? ` It was still too large with ${left} older image${left === 1 ? "" : "s"} or file${left === 1 ? "" : "s"} left out.` : ""
545
+ return `Factory refused the request as too large (${said}): it limits the size of a request's body in bytes.${tried} ${TOO_LARGE_HINT}`
546
+ }
547
+
398
548
  // errorReply is an error as the API the request was for words one:
399
549
  // Anthropic's on /llm/a/, OpenAI's on the others.
400
550
  function errorReply(url, status, type, message, headers = new Headers()) {
@@ -545,8 +695,8 @@ async function deviceSignIn() {
545
695
  // is a balance in cents.
546
696
 
547
697
  // CORE are the models Droid Core's windows count: those of a vendor other
548
- // than Anthropic, OpenAI and xAI. Standard's count every other model.
549
- const CORE = MODELS.filter((m) => !["anthropic", "openai", "xai"].includes(m.upstream)).map((m) => m.id)
698
+ // than Anthropic, OpenAI, xAI and Google. Standard's count every other model.
699
+ const CORE = MODELS.filter((m) => !["anthropic", "openai", "xai", "google"].includes(m.upstream)).map((m) => m.id)
550
700
 
551
701
  // statusLine is a status as Go's HTTP client names it, "403 Forbidden".
552
702
  const statusLine = (status) => `${status} ${STATUS_CODES[status] ?? ""}`.trim()
@@ -1427,12 +1577,23 @@ export const FactoryAuthPlugin = async ({ client }) => {
1427
1577
  const send = async (input, init, body, renewed) => {
1428
1578
  const c = await fresh(renewed)
1429
1579
  let url = input instanceof Request ? input.url : String(input)
1580
+ // Gemini's: Factory's generate route, the model in the body
1581
+ const call = GEMINI_CALL.exec(new URL(url).pathname)
1582
+ if (call) {
1583
+ const u = new URL(url)
1584
+ u.pathname = u.pathname.replace(GEMINI_CALL, "/generate")
1585
+ u.search = ""
1586
+ url = u.toString()
1587
+ body = geminiBody(decodeURIComponent(call[1]), body)
1588
+ }
1430
1589
  // an EU org is served from Factory's EU region, an on-prem one
1431
1590
  // from its own host: the request goes there
1432
1591
  const to = llmBase(c)
1433
1592
  if (to !== API && url.startsWith(API)) url = to + url.slice(API.length)
1434
1593
  const h = new Headers(init?.headers ?? (input instanceof Request ? input.headers : undefined))
1435
1594
  h.delete("x-api-key")
1595
+ // the AI SDK's Google package's, with OpenCode's placeholder key
1596
+ h.delete("x-goog-api-key")
1436
1597
  factoryHeaders(h, c)
1437
1598
  const model = byId.get(bodyModel(body))
1438
1599
  const path = new URL(url).pathname
@@ -1449,7 +1610,8 @@ export const FactoryAuthPlugin = async ({ client }) => {
1449
1610
  const anthropic = path.includes("/llm/a/") && (path.endsWith("/messages") || path.endsWith("/messages/count_tokens"))
1450
1611
  const adapted = anthropic ? wrapAnthropicTools(anthropicBody(body)) : { body: droidBody(path, body), names: new Set() }
1451
1612
  const out = adapted.body
1452
- if (out !== body) h.delete("content-length")
1613
+ // the caller's length is of the body it sent, not of this one
1614
+ if (out !== init?.body) h.delete("content-length")
1453
1615
  const res = await fetch(url, { ...init, method: init?.method ?? (input instanceof Request ? input.method : "POST"), headers: h, body: out })
1454
1616
  return path.endsWith("/messages") ? unwrapAnthropicTools(res, adapted.names) : res
1455
1617
  }
@@ -1468,9 +1630,23 @@ export const FactoryAuthPlugin = async ({ client }) => {
1468
1630
  let renewed = false
1469
1631
  const onRenew = () => (renewed = true)
1470
1632
  const answer = (res) => said(res, renewed ? "renewed" : "kept")
1633
+ // a 413: once more with the older images left out, then the
1634
+ // refusal said for what it is (leaveOutAttachments)
1635
+ const smaller = async (res) => {
1636
+ const path = new URL(url).pathname
1637
+ const less = leaveOutAttachments(path, body)
1638
+ if (less) {
1639
+ await res.body?.cancel()
1640
+ res = await send(input, init, less.body, onRenew)
1641
+ if (res.status !== 413) return res
1642
+ }
1643
+ const anthropic = path.includes("/llm/a/")
1644
+ return errorReply(url, 413, anthropic ? "request_too_large" : "invalid_request_error", tooLarge(await res.text(), less?.left ?? 0), new Headers(res.headers))
1645
+ }
1471
1646
  let res
1472
1647
  try {
1473
1648
  res = await send(input, init, body, onRenew)
1649
+ if (res.status === 413) return answer(await smaller(res))
1474
1650
  if (res.status !== 403) return answer(res)
1475
1651
  let text = await res.text()
1476
1652
  if (await mendOrg(res.status, text, onRenew).catch(() => false)) {
@@ -1496,4 +1672,4 @@ export const FactoryAuthPlugin = async ({ client }) => {
1496
1672
  }
1497
1673
 
1498
1674
  // for tests
1499
- export const _internal = { limitWindows, windowEnd, dollars, vendorError, CORE, droidBody, DROID_LINE }
1675
+ export const _internal = { limitWindows, windowEnd, dollars, vendorError, CORE, droidBody, DROID_LINE, geminiBody, leaveOutAttachments, LEFT_OUT, TOO_LARGE_HINT }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@magpie-community/opencode-factory-auth",
3
- "version": "0.1.24",
3
+ "version": "0.1.26",
4
4
  "description": "Sign in to a Factory (Droid) subscription from OpenCode or magpie",
5
5
  "type": "module",
6
6
  "main": "./index.mjs",