@magpie-community/opencode-factory-auth 0.1.4 → 0.1.8
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 +49 -0
- package/index.mjs +285 -8
- 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. On Anthropic's Messages (`/api/llm/a`), the plugin adapts
|
|
48
|
+
fixed client metadata while preserving the task instructions and history;
|
|
49
|
+
see [Claude Code through magpie](#claude-code-through-magpie) below.
|
|
50
|
+
|
|
36
51
|
## Models
|
|
37
52
|
|
|
38
53
|
Each model is served on the one API droid uses for it:
|
|
@@ -56,3 +71,37 @@ The list is not included:
|
|
|
56
71
|
magpie plugin add @magpie-community/opencode-factory-auth
|
|
57
72
|
magpie plugin login factory
|
|
58
73
|
```
|
|
74
|
+
|
|
75
|
+
## Claude Code through magpie
|
|
76
|
+
|
|
77
|
+
Factory's Anthropic route requires Droid's fixed client preamble and
|
|
78
|
+
refuses some of Claude Code's fixed environment, model and built-in skill
|
|
79
|
+
metadata. The plugin adapts that metadata while preserving the coding
|
|
80
|
+
instructions, environment values, tool definitions, tool results, images
|
|
81
|
+
and reasoning options. Native Droid requests remain unchanged, and OpenAI
|
|
82
|
+
routes keep their existing request adapter.
|
|
83
|
+
|
|
84
|
+
For the built-in `update-config` skill, the adapter changes only the known
|
|
85
|
+
self-reference "not Claude" to "not the assistant" inside a complete
|
|
86
|
+
generated skill-list reminder. Its configuration instructions, other
|
|
87
|
+
skill descriptions, tools and caller text are preserved.
|
|
88
|
+
|
|
89
|
+
Claude 5 can send runtime metadata in string-content `system` messages
|
|
90
|
+
instead of user-message reminders. The plugin adapts the known environment,
|
|
91
|
+
model and configuration-skill metadata in that shape too, preserving the
|
|
92
|
+
message role, environment values and session instructions.
|
|
93
|
+
|
|
94
|
+
Use magpie's Claude Code integration to select the Factory provider.
|
|
95
|
+
magpie manages the provider-specific client settings, including capability
|
|
96
|
+
and permission configuration. Fields such as `safeguards` and
|
|
97
|
+
`context_management` are forwarded for Factory to validate; the request
|
|
98
|
+
adapter preserves them along with the other request options.
|
|
99
|
+
|
|
100
|
+
The same metadata adaptation applies to `/messages` and
|
|
101
|
+
`/messages/count_tokens`, so token counting sees the prompt used for
|
|
102
|
+
inference. Serving the counting endpoint still depends on the host and
|
|
103
|
+
upstream. Model and feature availability depend on the Factory account,
|
|
104
|
+
organization region and upstream API. Connectivity has been verified with
|
|
105
|
+
Sonnet 4.6, Sonnet 5.5 and Opus 5.5. Two-turn Read tool calls with Claude
|
|
106
|
+
Code's default tool set have been verified with Sonnet 4.6 and Sonnet 5.5,
|
|
107
|
+
including Sonnet 5.5 selected through a routing group.
|
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],
|
|
@@ -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
|
|
248
|
+
return "Factory refused the request. magpie adapts fixed client metadata on both OpenAI and Anthropic routes. Factory may still refuse unsupported fields or wrappers; check the upstream error, the organization's model policy, plan and regional provider availability, and compare the same model in Droid"
|
|
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) uses anthropicBody below to adapt fixed client metadata.
|
|
264
|
+
// A native Droid request 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
|
|
@@ -462,6 +569,139 @@ function bodyModel(body) {
|
|
|
462
569
|
}
|
|
463
570
|
}
|
|
464
571
|
|
|
572
|
+
// Factory's Anthropic route accepts Droid's client preamble. Keep the
|
|
573
|
+
// caller's instructions, tools and history, adapting only fixed client
|
|
574
|
+
// metadata that Factory refuses (including Claude Code's wrappers).
|
|
575
|
+
const CLAUDE_IDENTITIES = new Set([
|
|
576
|
+
"You are Claude Code, Anthropic's official CLI for Claude.",
|
|
577
|
+
"You are Claude Code, Anthropic's official CLI for Claude, running within the Claude Agent SDK.",
|
|
578
|
+
"You are a Claude agent, built on Anthropic's Claude Agent SDK.",
|
|
579
|
+
])
|
|
580
|
+
|
|
581
|
+
// Match a complete generated block, not a pasted reminder followed by a
|
|
582
|
+
// user's question, or an incomplete fragment of one.
|
|
583
|
+
const ENV_REMINDER = /^<system-reminder>\n# Environment\nYou have been invoked in the following environment:[ \t]*\n(?: {1,2}- [^\n]*\n)+<\/system-reminder>$/
|
|
584
|
+
const MODEL_REMINDER = /^<system-reminder>\nYou are powered by the model (?:named )?[^\n<>]+\.\n<\/system-reminder>$/
|
|
585
|
+
const SKILL_REMINDER = /^<system-reminder>\nThe following skills are available for use with the Skill tool:\n\n(?:(?!<\/?system-reminder>)[\s\S])*\n<\/system-reminder>$/
|
|
586
|
+
// Factory also refuses this fixed self-reference in Claude Code 2.1.287's
|
|
587
|
+
// built-in update-config description. Keep its instructions and the rest
|
|
588
|
+
// of the skill list intact; only the known line in a complete listing changes.
|
|
589
|
+
const CONFIG_SKILL_METADATA = '- update-config: Use this skill to configure the Claude Code harness via settings.json. Automated behaviors ("from now on when X", "each time X", "whenever X", "before/after X") require hooks configured in settings.json - the harness executes these, not Claude, so memory/preferences cannot fulfill them.'
|
|
590
|
+
const CONFIG_SKILL_COMPAT = CONFIG_SKILL_METADATA.replace("not Claude", "not the assistant")
|
|
591
|
+
|
|
592
|
+
// Claude 5 also sends its runtime metadata as a string-content system
|
|
593
|
+
// message, instead of user-message reminders. Preserve that role and all
|
|
594
|
+
// instructions; only the known environment paragraph opens this adapter.
|
|
595
|
+
const SYSTEM_ENV_CONTEXT = /^# Environment\nYou have been invoked in the following environment:[ \t]*\n(?: {1,2}- [^\n]*\n)+(?=\n|$)/
|
|
596
|
+
const SYSTEM_MODEL_CONTEXT = /(^|\n\n)You are powered by the model (?:named )?[^\n<>]+\.(?=\n\n|$)/g
|
|
597
|
+
function systemContext(text) {
|
|
598
|
+
if (!SYSTEM_ENV_CONTEXT.test(text)) return text
|
|
599
|
+
let out = text.replace("# Environment", "# Runtime context")
|
|
600
|
+
.replace("You have been invoked in the following environment:", "The session environment is:")
|
|
601
|
+
.replace(SYSTEM_MODEL_CONTEXT, (paragraph) => paragraph
|
|
602
|
+
.replace("You are powered by the model named", "Current model name:")
|
|
603
|
+
.replace("You are powered by the model", "Current model:")
|
|
604
|
+
.replace("The exact model ID is", "Model ID:")
|
|
605
|
+
.replace("Assistant knowledge cutoff is", "Model knowledge cutoff:"))
|
|
606
|
+
const skillHeader = "\n\nThe following skills are available for use with the Skill tool:\n\n"
|
|
607
|
+
const skills = out.indexOf(skillHeader)
|
|
608
|
+
if (skills >= 0) {
|
|
609
|
+
const start = skills + skillHeader.length - 1
|
|
610
|
+
out = out.slice(0, start) + out.slice(start).replace("\n" + CONFIG_SKILL_METADATA, "\n" + CONFIG_SKILL_COMPAT)
|
|
611
|
+
}
|
|
612
|
+
return out
|
|
613
|
+
}
|
|
614
|
+
|
|
615
|
+
function anthropicBody(body) {
|
|
616
|
+
let request
|
|
617
|
+
try {
|
|
618
|
+
const text = typeof body === "string" ? body
|
|
619
|
+
: body instanceof ArrayBuffer ? Buffer.from(body).toString("utf8")
|
|
620
|
+
: ArrayBuffer.isView(body) ? Buffer.from(body.buffer, body.byteOffset, body.byteLength).toString("utf8") : ""
|
|
621
|
+
request = JSON.parse(text)
|
|
622
|
+
} catch {
|
|
623
|
+
return body
|
|
624
|
+
}
|
|
625
|
+
// As in droidBody, JSON round-tripping uses JavaScript Numbers: integer
|
|
626
|
+
// tokens above 2^53 can lose precision when a body needs adapting. A
|
|
627
|
+
// body that needs no changes is returned byte-for-byte instead.
|
|
628
|
+
if (!request || !Array.isArray(request.messages)) return body
|
|
629
|
+
if (request.system != null && typeof request.system !== "string" && !Array.isArray(request.system)) return body
|
|
630
|
+
if (Array.isArray(request.system) && request.system.some((b) => b?.type === "text" && typeof b.text !== "string")) return body
|
|
631
|
+
|
|
632
|
+
let changed = false
|
|
633
|
+
const system = typeof request.system === "string" ? [{ type: "text", text: request.system }] : request.system ?? []
|
|
634
|
+
if (typeof request.system === "string" && !request.system.startsWith(DROID_LINE)) changed = true
|
|
635
|
+
const kept = []
|
|
636
|
+
for (const block of system) {
|
|
637
|
+
if (block?.type === "text" && block.text.trim() === "") {
|
|
638
|
+
changed = true
|
|
639
|
+
continue
|
|
640
|
+
}
|
|
641
|
+
// Attribution is consumed here; Factory does not strip Anthropic's
|
|
642
|
+
// billing block and requires the Droid identity to be first.
|
|
643
|
+
if (block?.type === "text" && block.text?.startsWith("x-anthropic-billing-header: cc_version=")) {
|
|
644
|
+
changed = true
|
|
645
|
+
continue
|
|
646
|
+
}
|
|
647
|
+
if (block?.type === "text" && CLAUDE_IDENTITIES.has(block.text)) {
|
|
648
|
+
block.text = DROID_LINE
|
|
649
|
+
changed = true
|
|
650
|
+
}
|
|
651
|
+
kept.push(block)
|
|
652
|
+
}
|
|
653
|
+
const identity = kept.findIndex((b) => b?.type === "text" && b.text.startsWith(DROID_LINE))
|
|
654
|
+
if (identity < 0) {
|
|
655
|
+
kept.unshift({ type: "text", text: DROID_LINE })
|
|
656
|
+
changed = true
|
|
657
|
+
} else if (identity > 0) {
|
|
658
|
+
kept.unshift(...kept.splice(identity, 1))
|
|
659
|
+
changed = true
|
|
660
|
+
}
|
|
661
|
+
// Drop only duplicate identity-only blocks. A block that also contains
|
|
662
|
+
// task instructions stays intact.
|
|
663
|
+
for (let i = kept.length - 1; i > 0; i--) {
|
|
664
|
+
if (kept[i]?.type === "text" && kept[i].text === DROID_LINE) {
|
|
665
|
+
kept.splice(i, 1)
|
|
666
|
+
changed = true
|
|
667
|
+
}
|
|
668
|
+
}
|
|
669
|
+
if (changed) request.system = kept
|
|
670
|
+
|
|
671
|
+
for (const message of request.messages) {
|
|
672
|
+
if (message?.role === "system" && typeof message.content === "string") {
|
|
673
|
+
const adapted = systemContext(message.content)
|
|
674
|
+
if (adapted !== message.content) {
|
|
675
|
+
message.content = adapted
|
|
676
|
+
changed = true
|
|
677
|
+
}
|
|
678
|
+
continue
|
|
679
|
+
}
|
|
680
|
+
if (message?.role !== "user" || !Array.isArray(message.content)) continue
|
|
681
|
+
for (const block of message.content) {
|
|
682
|
+
if (block?.type !== "text" || typeof block.text !== "string") continue
|
|
683
|
+
if (ENV_REMINDER.test(block.text)) {
|
|
684
|
+
block.text = block.text.replace("# Environment", "# Runtime context")
|
|
685
|
+
.replace("You have been invoked in the following environment:", "The session environment is:")
|
|
686
|
+
changed = true
|
|
687
|
+
} else if (MODEL_REMINDER.test(block.text)) {
|
|
688
|
+
block.text = block.text.replace("You are powered by the model named", "Current model name:")
|
|
689
|
+
.replace("You are powered by the model", "Current model:")
|
|
690
|
+
.replace("The exact model ID is", "Model ID:")
|
|
691
|
+
.replace("Assistant knowledge cutoff is", "Model knowledge cutoff:")
|
|
692
|
+
changed = true
|
|
693
|
+
} else if (SKILL_REMINDER.test(block.text)) {
|
|
694
|
+
const adapted = block.text.replace("\n" + CONFIG_SKILL_METADATA, "\n" + CONFIG_SKILL_COMPAT)
|
|
695
|
+
if (adapted !== block.text) {
|
|
696
|
+
block.text = adapted
|
|
697
|
+
changed = true
|
|
698
|
+
}
|
|
699
|
+
}
|
|
700
|
+
}
|
|
701
|
+
}
|
|
702
|
+
return changed ? JSON.stringify(request) : body
|
|
703
|
+
}
|
|
704
|
+
|
|
465
705
|
export const FactoryAuthPlugin = async ({ client }) => {
|
|
466
706
|
// the session id this process's requests carry
|
|
467
707
|
const session = crypto.randomUUID()
|
|
@@ -476,8 +716,8 @@ export const FactoryAuthPlugin = async ({ client }) => {
|
|
|
476
716
|
// when each account last asked whoami for its org, so one whoami can't
|
|
477
717
|
// answer doesn't ask before every request, nor hold back the others
|
|
478
718
|
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())
|
|
719
|
+
const askedOf = (c) => asked.get(c.accountId || c.refresh || c.access || "") ?? 0
|
|
720
|
+
const ask = (c) => asked.set(c.accountId || c.refresh || c.access || "", Date.now())
|
|
481
721
|
|
|
482
722
|
// account is the account getAuth reads, with what keeps its token live
|
|
483
723
|
// and its org right.
|
|
@@ -488,10 +728,39 @@ export const FactoryAuthPlugin = async ({ client }) => {
|
|
|
488
728
|
}
|
|
489
729
|
const current = async () => {
|
|
490
730
|
const a = await getAuth()
|
|
731
|
+
if (isKey(a)) return keyAccount(a)
|
|
491
732
|
if (a?.type !== "oauth" || !a.access) throw new Error("Factory: not signed in")
|
|
492
733
|
return { ...a }
|
|
493
734
|
}
|
|
494
735
|
|
|
736
|
+
// keyed is a key account with where Factory serves its org: whoami,
|
|
737
|
+
// asked with the key and no org (droid's st() is null for a key), as
|
|
738
|
+
// droid's yP checks a key before it is used, and as the built-in asks
|
|
739
|
+
// it when the key is added. What it names is kept in the key's
|
|
740
|
+
// metadata, so magpie shows whose the key is; a whoami that fails is
|
|
741
|
+
// asked again ASK_AGAIN later, the request going on meanwhile.
|
|
742
|
+
const keyed = async (c) => {
|
|
743
|
+
if (c.whoKnown || Date.now() - askedOf(c) < ASK_AGAIN) return c
|
|
744
|
+
ask(c)
|
|
745
|
+
let who
|
|
746
|
+
try {
|
|
747
|
+
who = await whoami({ ...c, activeOrganizationId: "" })
|
|
748
|
+
} catch {
|
|
749
|
+
return c
|
|
750
|
+
}
|
|
751
|
+
c.region = who.region ?? ""
|
|
752
|
+
c.premBaseHost = who.premBaseHostV2 ?? ""
|
|
753
|
+
c.email ||= who.email ?? ""
|
|
754
|
+
c.userId ||= who.userId ?? ""
|
|
755
|
+
c.whoKnown = true
|
|
756
|
+
const a = await getAuth()
|
|
757
|
+
if (isKey(a) && a.key === c.access) {
|
|
758
|
+
const metadata = { ...(a.metadata ?? {}), email: c.email, userId: c.userId, region: c.region, premBaseHost: c.premBaseHost }
|
|
759
|
+
await client.auth.set({ path: { id: PROVIDER }, body: { ...a, metadata } }).catch(() => {})
|
|
760
|
+
}
|
|
761
|
+
return c
|
|
762
|
+
}
|
|
763
|
+
|
|
495
764
|
// orgOf fills in the active org when there is none: droid asks
|
|
496
765
|
// whoami as soon as it holds a token and sends the orgId it answers
|
|
497
766
|
// as X-Factory-Org-Id on every request after.
|
|
@@ -507,6 +776,7 @@ export const FactoryAuthPlugin = async ({ client }) => {
|
|
|
507
776
|
const fresh = (renewed) =>
|
|
508
777
|
locked(async () => {
|
|
509
778
|
const c = await current()
|
|
779
|
+
if (c.key) return keyed(c) // an API key: nothing to renew, and no org with it
|
|
510
780
|
if ((c.expires > 0 && Date.now() < c.expires - REFRESH_LEAD) || !c.refresh) return orgOf(c)
|
|
511
781
|
let t
|
|
512
782
|
try {
|
|
@@ -539,6 +809,7 @@ export const FactoryAuthPlugin = async ({ client }) => {
|
|
|
539
809
|
if (status !== 403) return false
|
|
540
810
|
const isOrg = orgRefused(status, text)
|
|
541
811
|
const c = await current()
|
|
812
|
+
if (c.key) return false // an API key carries no org droid would send
|
|
542
813
|
if (c.activeOrganizationId) {
|
|
543
814
|
if (!isOrg) return false // the org was sent: the refusal is about something else
|
|
544
815
|
const was = c.activeOrganizationId
|
|
@@ -633,6 +904,8 @@ export const FactoryAuthPlugin = async ({ client }) => {
|
|
|
633
904
|
label: "Sign in with Factory (device code)",
|
|
634
905
|
authorize: deviceSignIn,
|
|
635
906
|
},
|
|
907
|
+
// droid's FACTORY_API_KEY: the key is the bearer, never renewed
|
|
908
|
+
{ type: "api", label: "Factory API key (fk-…)", placeholder: "fk-…" },
|
|
636
909
|
],
|
|
637
910
|
// magpie's own hook: the account's limits
|
|
638
911
|
async usage(getAuth) {
|
|
@@ -640,7 +913,7 @@ export const FactoryAuthPlugin = async ({ client }) => {
|
|
|
640
913
|
},
|
|
641
914
|
async loader(getAuth) {
|
|
642
915
|
const first = await getAuth()
|
|
643
|
-
if (first?.type !== "oauth") return {}
|
|
916
|
+
if (first?.type !== "oauth" && !isKey(first)) return {}
|
|
644
917
|
|
|
645
918
|
const { fresh, mendOrg } = account(getAuth)
|
|
646
919
|
|
|
@@ -665,7 +938,11 @@ export const FactoryAuthPlugin = async ({ client }) => {
|
|
|
665
938
|
// droid's Anthropic client is made with the key "placeholder",
|
|
666
939
|
// which Anthropic's SDK sends beside the bearer token
|
|
667
940
|
if (path.includes("/llm/a/")) h.set("X-Api-Key", "placeholder")
|
|
668
|
-
|
|
941
|
+
// another agent's request opens as droid's does (droidBody)
|
|
942
|
+
const out = path.includes("/llm/a/") && (path.endsWith("/messages") || path.endsWith("/messages/count_tokens"))
|
|
943
|
+
? anthropicBody(body) : droidBody(path, body)
|
|
944
|
+
if (out !== body) h.delete("content-length")
|
|
945
|
+
return fetch(url, { ...init, method: init?.method ?? (input instanceof Request ? input.method : "POST"), headers: h, body: out })
|
|
669
946
|
}
|
|
670
947
|
|
|
671
948
|
return {
|
|
@@ -710,4 +987,4 @@ export const FactoryAuthPlugin = async ({ client }) => {
|
|
|
710
987
|
}
|
|
711
988
|
|
|
712
989
|
// for tests
|
|
713
|
-
export const _internal = { limitWindows, windowEnd, dollars, vendorError, CORE }
|
|
990
|
+
export const _internal = { limitWindows, windowEnd, dollars, vendorError, CORE, droidBody, DROID_LINE }
|