@magpie-community/opencode-factory-auth 0.1.5 → 0.1.9

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 +42 -3
  2. package/index.mjs +144 -4
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -44,9 +44,9 @@ droid sends opens its system prompt with "You are Droid, an AI software
44
44
  engineering agent built by Factory.", so another agent's request to
45
45
  Factory's OpenAI-shaped API (`/api/llm/o`: GPT and Grok on Responses, the
46
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.
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
50
 
51
51
  ## Models
52
52
 
@@ -71,3 +71,42 @@ The list is not included:
71
71
  magpie plugin add @magpie-community/opencode-factory-auth
72
72
  magpie plugin login factory
73
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
+ After `/model` switches, Claude Code can send model-only system updates
94
+ without the initial environment paragraph. Updates beginning with the known
95
+ model paragraph and containing complete generated token metadata are
96
+ adapted too, including accumulated switches when resuming a conversation.
97
+ Token budgets, permission instructions and conversation history are preserved.
98
+
99
+ Use magpie's Claude Code integration to select the Factory provider.
100
+ magpie manages the provider-specific client settings, including capability
101
+ and permission configuration. Fields such as `safeguards` and
102
+ `context_management` are forwarded for Factory to validate; the request
103
+ adapter preserves them along with the other request options.
104
+
105
+ The same metadata adaptation applies to `/messages` and
106
+ `/messages/count_tokens`, so token counting sees the prompt used for
107
+ inference. Serving the counting endpoint still depends on the host and
108
+ upstream. Model and feature availability depend on the Factory account,
109
+ organization region and upstream API. Connectivity has been verified with
110
+ Sonnet 4.6, Sonnet 5.5 and Opus 5.5. Two-turn Read tool calls with Claude
111
+ Code's default tool set have been verified with Sonnet 4.6 and Sonnet 5.5,
112
+ including Sonnet 5.5 selected through a routing group.
package/index.mjs CHANGED
@@ -245,7 +245,7 @@ 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 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"
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
249
  }
250
250
 
251
251
  // ---- opening as droid ---------------------------------------------------------
@@ -260,8 +260,8 @@ function explain(status, text) {
260
260
  // system message first, joined the same way). So another agent's request to
261
261
  // /api/llm/o opens with the line too, as the built-in's factoryDroidBody
262
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.
263
+ // (/api/llm/a) uses anthropicBody below to adapt fixed client metadata.
264
+ // A native Droid request goes on byte for byte.
265
265
 
266
266
  const DROID_LINE = "You are Droid, an AI software engineering agent built by Factory."
267
267
 
@@ -569,6 +569,145 @@ function bodyModel(body) {
569
569
  }
570
570
  }
571
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. A model switch sends a separate update without the
595
+ // environment paragraph; require its opening model paragraph and complete
596
+ // generated token context before adapting that shape.
597
+ const SYSTEM_ENV_CONTEXT = /^# Environment\nYou have been invoked in the following environment:[ \t]*\n(?: {1,2}- [^\n]*\n)+(?=\n|$)/
598
+ const SYSTEM_MODEL_CONTEXT = /(^|\n\n)You are powered by the model (?:named )?[^\n<>]+\.(?=\n\n|$)/g
599
+ const SYSTEM_MODEL_UPDATE = /^You are powered by the model (?:named )?[^\n<>]+\.(?=\n\n|$)/
600
+ const SYSTEM_TOKEN_CONTEXT = /(?:^|\n\n)<total_tokens>\d+ tokens left<\/total_tokens>(?=\n\n|$)/
601
+ function systemContext(text) {
602
+ const environment = SYSTEM_ENV_CONTEXT.test(text)
603
+ if (!environment && !(SYSTEM_MODEL_UPDATE.test(text) && SYSTEM_TOKEN_CONTEXT.test(text))) return text
604
+ let out = text.replace(SYSTEM_MODEL_CONTEXT, (paragraph) => paragraph
605
+ .replace("You are powered by the model named", "Current model name:")
606
+ .replace("You are powered by the model", "Current model:")
607
+ .replace("The exact model ID is", "Model ID:")
608
+ .replace("Assistant knowledge cutoff is", "Model knowledge cutoff:"))
609
+ if (!environment) return out
610
+ out = out.replace("# Environment", "# Runtime context")
611
+ .replace("You have been invoked in the following environment:", "The session environment is:")
612
+ const skillHeader = "\n\nThe following skills are available for use with the Skill tool:\n\n"
613
+ const skills = out.indexOf(skillHeader)
614
+ if (skills >= 0) {
615
+ const start = skills + skillHeader.length - 1
616
+ out = out.slice(0, start) + out.slice(start).replace("\n" + CONFIG_SKILL_METADATA, "\n" + CONFIG_SKILL_COMPAT)
617
+ }
618
+ return out
619
+ }
620
+
621
+ function anthropicBody(body) {
622
+ let request
623
+ try {
624
+ const text = typeof body === "string" ? body
625
+ : body instanceof ArrayBuffer ? Buffer.from(body).toString("utf8")
626
+ : ArrayBuffer.isView(body) ? Buffer.from(body.buffer, body.byteOffset, body.byteLength).toString("utf8") : ""
627
+ request = JSON.parse(text)
628
+ } catch {
629
+ return body
630
+ }
631
+ // As in droidBody, JSON round-tripping uses JavaScript Numbers: integer
632
+ // tokens above 2^53 can lose precision when a body needs adapting. A
633
+ // body that needs no changes is returned byte-for-byte instead.
634
+ if (!request || !Array.isArray(request.messages)) return body
635
+ if (request.system != null && typeof request.system !== "string" && !Array.isArray(request.system)) return body
636
+ if (Array.isArray(request.system) && request.system.some((b) => b?.type === "text" && typeof b.text !== "string")) return body
637
+
638
+ let changed = false
639
+ const system = typeof request.system === "string" ? [{ type: "text", text: request.system }] : request.system ?? []
640
+ if (typeof request.system === "string" && !request.system.startsWith(DROID_LINE)) changed = true
641
+ const kept = []
642
+ for (const block of system) {
643
+ if (block?.type === "text" && block.text.trim() === "") {
644
+ changed = true
645
+ continue
646
+ }
647
+ // Attribution is consumed here; Factory does not strip Anthropic's
648
+ // billing block and requires the Droid identity to be first.
649
+ if (block?.type === "text" && block.text?.startsWith("x-anthropic-billing-header: cc_version=")) {
650
+ changed = true
651
+ continue
652
+ }
653
+ if (block?.type === "text" && CLAUDE_IDENTITIES.has(block.text)) {
654
+ block.text = DROID_LINE
655
+ changed = true
656
+ }
657
+ kept.push(block)
658
+ }
659
+ const identity = kept.findIndex((b) => b?.type === "text" && b.text.startsWith(DROID_LINE))
660
+ if (identity < 0) {
661
+ kept.unshift({ type: "text", text: DROID_LINE })
662
+ changed = true
663
+ } else if (identity > 0) {
664
+ kept.unshift(...kept.splice(identity, 1))
665
+ changed = true
666
+ }
667
+ // Drop only duplicate identity-only blocks. A block that also contains
668
+ // task instructions stays intact.
669
+ for (let i = kept.length - 1; i > 0; i--) {
670
+ if (kept[i]?.type === "text" && kept[i].text === DROID_LINE) {
671
+ kept.splice(i, 1)
672
+ changed = true
673
+ }
674
+ }
675
+ if (changed) request.system = kept
676
+
677
+ for (const message of request.messages) {
678
+ if (message?.role === "system" && typeof message.content === "string") {
679
+ const adapted = systemContext(message.content)
680
+ if (adapted !== message.content) {
681
+ message.content = adapted
682
+ changed = true
683
+ }
684
+ continue
685
+ }
686
+ if (message?.role !== "user" || !Array.isArray(message.content)) continue
687
+ for (const block of message.content) {
688
+ if (block?.type !== "text" || typeof block.text !== "string") continue
689
+ if (ENV_REMINDER.test(block.text)) {
690
+ block.text = block.text.replace("# Environment", "# Runtime context")
691
+ .replace("You have been invoked in the following environment:", "The session environment is:")
692
+ changed = true
693
+ } else if (MODEL_REMINDER.test(block.text)) {
694
+ block.text = block.text.replace("You are powered by the model named", "Current model name:")
695
+ .replace("You are powered by the model", "Current model:")
696
+ .replace("The exact model ID is", "Model ID:")
697
+ .replace("Assistant knowledge cutoff is", "Model knowledge cutoff:")
698
+ changed = true
699
+ } else if (SKILL_REMINDER.test(block.text)) {
700
+ const adapted = block.text.replace("\n" + CONFIG_SKILL_METADATA, "\n" + CONFIG_SKILL_COMPAT)
701
+ if (adapted !== block.text) {
702
+ block.text = adapted
703
+ changed = true
704
+ }
705
+ }
706
+ }
707
+ }
708
+ return changed ? JSON.stringify(request) : body
709
+ }
710
+
572
711
  export const FactoryAuthPlugin = async ({ client }) => {
573
712
  // the session id this process's requests carry
574
713
  const session = crypto.randomUUID()
@@ -806,7 +945,8 @@ export const FactoryAuthPlugin = async ({ client }) => {
806
945
  // which Anthropic's SDK sends beside the bearer token
807
946
  if (path.includes("/llm/a/")) h.set("X-Api-Key", "placeholder")
808
947
  // another agent's request opens as droid's does (droidBody)
809
- const out = droidBody(path, body)
948
+ const out = path.includes("/llm/a/") && (path.endsWith("/messages") || path.endsWith("/messages/count_tokens"))
949
+ ? anthropicBody(body) : droidBody(path, body)
810
950
  if (out !== body) h.delete("content-length")
811
951
  return fetch(url, { ...init, method: init?.method ?? (input instanceof Request ? input.method : "POST"), headers: h, body: out })
812
952
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@magpie-community/opencode-factory-auth",
3
- "version": "0.1.5",
3
+ "version": "0.1.9",
4
4
  "description": "Sign in to a Factory (Droid) subscription from OpenCode or magpie",
5
5
  "type": "module",
6
6
  "main": "./index.mjs",