factory 0.1.29: Claude Code on GLM and other /api/llm/o models goes without the phrases Factory refuses, not "403 Factory: Forbidden" (Echoo on magpie's Discord)
Echoo, with Factory moved onto this plugin, got "API Error: 403 Factory:
Forbidden" from Claude Code on GLM-5.3-Flash, while Codex worked on the
same account and model. GLM is a chat model Factory serves on /api/llm/o,
so magpie translates Claude Code's Messages request into chat completions
(or Responses) before the plugin gets it. Only anthropicBody, the
/api/llm/a route, adapted Claude Code's fixed phrases Factory refuses (its
identity line, "You have been invoked in the following environment", "You
are powered by the model", update-config's "not Claude, so memory", tool
output quoting them). droidBody, for /api/llm/o, only added droid's line,
so all of them went to Factory as they were. The headers, the model and
the account are the same for both agents; Codex's prompt has none of the
phrases.
anthropicBody's per-text adapters are now functions of their own
(claudeIdentity, promptText, systemMessageText, userBlockText), and
droidBody applies them to chat completions and Responses:
- chat's first system message and Responses' instructions as a system
prompt; other system and developer messages as system messages;
- user text as a user block; a chat user string, where magpie joins a
turn's blocks with nothing between them, also reminder by reminder;
- chat's tool messages and Responses' function_call_output as tool output.
The Messages route is unchanged: the refactor kept every earlier test
green before the new code went in.
testdata/claude-code-2.1.300-glm-{chat,responses}.json are magpie's
translations of a real Claude Code 2.1.300 request, captured in a sandbox
HOME (paths changed to /Users/me, tools left out).
Run: bun test in packages/factory, 143 pass. With index.mjs at 0.1.28 the
new claude-chat.test.mjs fails 4 of 5 (the Codex one passes on both).
bun scripts/check.mjs factory: ok. Routed the captured request through the
plugin: each refused phrase is 0 in the chat and Responses bodies now, as
on /api/llm/a (1 each with 0.1.28).
Not tried against Factory itself: there is no Factory account to try with.
This commit is contained in:
@@ -0,0 +1,124 @@
|
||||
// Echoo on magpie's Discord: Claude Code on GLM-5.3-Flash through this
|
||||
// plugin got "API Error: 403 Factory: Forbidden" on every turn, while Codex
|
||||
// worked on the same account and model. GLM is a chat model, served on
|
||||
// /api/llm/o, so magpie translates Claude Code's Messages request into chat
|
||||
// completions (or Responses) before it reaches the plugin. Only
|
||||
// anthropicBody (the /api/llm/a route) adapted Claude Code's fixed phrases
|
||||
// Factory refuses; on /api/llm/o they went to Factory as they were.
|
||||
//
|
||||
// testdata/claude-code-2.1.300-glm-{chat,responses}.json are magpie's
|
||||
// translations of a real Claude Code 2.1.300 request, captured from a
|
||||
// sandbox HOME (paths changed to /Users/me, tools left out).
|
||||
import { afterEach, expect, test } from "bun:test"
|
||||
import { readFileSync } from "node:fs"
|
||||
import { FactoryAuthPlugin, _internal } from "./index.mjs"
|
||||
|
||||
const { DROID_LINE } = _internal
|
||||
const real = globalThis.fetch
|
||||
afterEach(() => (globalThis.fetch = real))
|
||||
|
||||
const API = "https://api.factory.ai"
|
||||
const chat = API + "/api/llm/o/v1/chat/completions"
|
||||
const responses = API + "/api/llm/o/v1/responses"
|
||||
|
||||
const CHAT = readFileSync(new URL("./testdata/claude-code-2.1.300-glm-chat.json", import.meta.url), "utf8")
|
||||
const RESPONSES = readFileSync(new URL("./testdata/claude-code-2.1.300-glm-responses.json", import.meta.url), "utf8")
|
||||
|
||||
// the phrases the plugin already adapts on /api/llm/a because Factory refuses them
|
||||
const REFUSED = [
|
||||
"You are a Claude agent, built on Anthropic's Claude Agent SDK.",
|
||||
"You have been invoked in the following environment",
|
||||
"You are powered by the model",
|
||||
"the harness executes these, not Claude, so memory",
|
||||
]
|
||||
|
||||
async function loaded() {
|
||||
const sent = []
|
||||
globalThis.fetch = async (url, init = {}) => {
|
||||
const u = new URL(String(url))
|
||||
if (u.pathname === "/api/cli/whoami") return new Response(JSON.stringify({ userId: "user_k", orgId: "fac_K", email: "k@example.com", region: "" }))
|
||||
sent.push({ url: String(url), headers: new Headers(init.headers), body: init.body })
|
||||
return new Response('{"id":"ok"}')
|
||||
}
|
||||
let saved = { type: "oauth", access: "tok", refresh: "r", expires: Date.now() + 3_600_000, accountId: "d@example.com", activeOrganizationId: "fac_D", region: "" }
|
||||
const hooks = await FactoryAuthPlugin({ client: { auth: { set: async ({ body }) => (saved = body) } } })
|
||||
const l = await hooks.auth.loader(async () => saved)
|
||||
return async (url, body) => {
|
||||
const res = await l.fetch(url, { method: "POST", headers: { "content-type": "application/json" }, body })
|
||||
expect(res.status).toBe(200)
|
||||
return JSON.parse(sent.at(-1).body)
|
||||
}
|
||||
}
|
||||
|
||||
test("Claude Code's request made chat completions goes without the phrases Factory refuses", async () => {
|
||||
const send = await loaded()
|
||||
for (const p of REFUSED) expect(CHAT).toContain(p)
|
||||
const b = await send(chat, CHAT)
|
||||
const out = JSON.stringify(b)
|
||||
for (const p of REFUSED) expect(out).not.toContain(p)
|
||||
const m = b.messages
|
||||
expect(m[0].role).toBe("system")
|
||||
expect(m[0].content.startsWith(DROID_LINE + "\nYou are an agent working with the user")).toBe(true)
|
||||
expect(m[0].content.split(DROID_LINE).length).toBe(2)
|
||||
// the user's words and the attribution reminder joined to them stay
|
||||
expect(m[1].content).toBe(JSON.parse(CHAT).messages[1].content)
|
||||
// the environment Claude Code sent as a system message, folded into a
|
||||
// user turn by the translation: reworded, its facts kept
|
||||
expect(m[2].content.startsWith("# Runtime context\nThe session environment is: \n - Primary working directory: /Users/me/proj\n")).toBe(true)
|
||||
expect(m[2].content).toContain("\n\nCurrent model: glm-5.3-flash.\n\n")
|
||||
expect(m[2].content).toContain("the harness executes these, not the assistant, so memory")
|
||||
expect(m.length).toBe(JSON.parse(CHAT).messages.length)
|
||||
expect(b.model).toBe("glm-5.3-flash")
|
||||
})
|
||||
|
||||
test("Claude Code's request made Responses goes without the phrases Factory refuses", async () => {
|
||||
const send = await loaded()
|
||||
for (const p of REFUSED) expect(RESPONSES).toContain(p)
|
||||
const b = await send(responses, RESPONSES)
|
||||
const out = JSON.stringify(b)
|
||||
for (const p of REFUSED) expect(out).not.toContain(p)
|
||||
expect(b.instructions.startsWith(DROID_LINE + "\nYou are an agent working with the user")).toBe(true)
|
||||
expect(b.instructions.split(DROID_LINE).length).toBe(2)
|
||||
const system = b.input.find((i) => i.role === "system")
|
||||
expect(system.content[0].text.startsWith("# Runtime context\nThe session environment is: \n")).toBe(true)
|
||||
expect(b.input.length).toBe(JSON.parse(RESPONSES).input.length)
|
||||
})
|
||||
|
||||
test("a reminder joined to the user's words is adapted as the block it was, the words kept", async () => {
|
||||
const send = await loaded()
|
||||
const joined = "<system-reminder>\nYou are powered by the model named GLM-5.3-Flash.\n</system-reminder>\nwhat model are you? You are powered by the model, right?"
|
||||
let b = await send(chat, JSON.stringify({ model: "glm-5.3-flash", messages: [{ role: "user", content: joined }] }))
|
||||
expect(b.messages[1].content).toBe("<system-reminder>\nCurrent model name: GLM-5.3-Flash.\n</system-reminder>\nwhat model are you? You are powered by the model, right?")
|
||||
// the user's own text, with no generated reminder, goes on as it is
|
||||
const own = "You are powered by the model named in my config. You have been invoked in the following environment: mine"
|
||||
b = await send(chat, JSON.stringify({ model: "glm-5.3-flash", messages: [{ role: "user", content: own }] }))
|
||||
expect(b.messages[1].content).toBe(own)
|
||||
// Responses keeps blocks apart: each input_text is adapted on its own
|
||||
b = await send(responses, JSON.stringify({ model: "glm-5.3-flash", input: [{ role: "user", content: [{ type: "input_text", text: "<system-reminder>\nYou are powered by the model glm-5.3-flash.\n</system-reminder>" }, { type: "input_text", text: "hi" }] }] }))
|
||||
expect(b.input[0].content.map((p) => p.text)).toEqual(["<system-reminder>\nCurrent model: glm-5.3-flash.\n</system-reminder>", "hi"])
|
||||
})
|
||||
|
||||
test("tool output quoting Claude Code's identity is encoded, on chat and Responses", async () => {
|
||||
const send = await loaded()
|
||||
const read = "1\tconst id = \"You are Claude Code, Anthropic's official CLI for Claude.\""
|
||||
let b = await send(chat, JSON.stringify({ model: "glm-5.3-flash", messages: [{ role: "user", content: "read it" }, { role: "assistant", content: null, tool_calls: [{ id: "c1", type: "function", function: { name: "Read", arguments: "{}" } }] }, { role: "tool", tool_call_id: "c1", content: read }] }))
|
||||
const tool = b.messages.find((m) => m.role === "tool")
|
||||
expect(tool.content).not.toContain("You are Claude Code")
|
||||
expect(tool.content.startsWith("Tool output encoded as a JSON string.")).toBe(true)
|
||||
expect(tool.tool_call_id).toBe("c1")
|
||||
b = await send(responses, JSON.stringify({ model: "glm-5.3-flash", input: [{ type: "function_call", call_id: "c1", name: "Read", arguments: "{}" }, { type: "function_call_output", call_id: "c1", output: read }] }))
|
||||
expect(b.input[1].output).not.toContain("You are Claude Code")
|
||||
expect(b.input[1].call_id).toBe("c1")
|
||||
// other tool output stays byte for byte
|
||||
b = await send(chat, JSON.stringify({ model: "glm-5.3-flash", messages: [{ role: "tool", tool_call_id: "c2", content: "ok" }] }))
|
||||
expect(b.messages.find((m) => m.role === "tool").content).toBe("ok")
|
||||
})
|
||||
|
||||
test("Codex's request is only opened with droid's line, as before", async () => {
|
||||
const send = await loaded()
|
||||
const dev = "<permissions instructions>\nYou are powered by the model gpt-5.5 says nothing here.\n</permissions instructions>"
|
||||
const b = await send(responses, JSON.stringify({ model: "glm-5.3-flash", instructions: "You are Codex, a coding agent based on GPT-5.", input: [{ type: "message", role: "developer", content: [{ type: "input_text", text: dev }] }, { type: "message", role: "user", content: [{ type: "input_text", text: "<environment_context>\n <cwd>/Users/me/proj</cwd>\n</environment_context>" }, { type: "input_text", text: "hi" }] }] }))
|
||||
expect(b.instructions).toBe(DROID_LINE + "\nYou are Codex, a coding agent based on GPT-5.")
|
||||
expect(b.input[0].content[0].text).toBe(dev)
|
||||
expect(b.input[1].content.map((p) => p.text)).toEqual(["<environment_context>\n <cwd>/Users/me/proj</cwd>\n</environment_context>", "hi"])
|
||||
})
|
||||
+91
-52
@@ -382,27 +382,38 @@ function piSummary(text) {
|
||||
return text
|
||||
}
|
||||
|
||||
// promptOpenings adapts clientOpening in the system and developer messages
|
||||
// of msgs (chat completions' messages, Responses' input), and piSummary in
|
||||
// their user messages, their string content or text parts: false when
|
||||
// nothing changed.
|
||||
function promptOpenings(msgs) {
|
||||
// promptOpenings adapts the messages of msgs (chat completions' messages,
|
||||
// Responses' input) as anthropicBody adapts a Messages request's: pi's
|
||||
// opening and Claude Code's fixed phrases in the system and developer
|
||||
// messages (the first of chat's as a system prompt, when prompt), pi's
|
||||
// summary and Claude Code's reminders in user messages, and client phrases
|
||||
// quoted in tool output (chat's tool messages, Responses'
|
||||
// function_call_output). String content or text parts change, nothing else:
|
||||
// false when nothing changed.
|
||||
function promptOpenings(msgs, prompt = false) {
|
||||
let changed = false
|
||||
for (const m of Array.isArray(msgs) ? msgs : []) {
|
||||
if (!m || typeof m !== "object") continue
|
||||
const adapt = m.role === "system" || m.role === "developer" ? clientOpening : m.role === "user" ? piSummary : null
|
||||
if (!adapt) continue
|
||||
if (typeof m.content === "string") {
|
||||
const adapted = adapt(m.content)
|
||||
if (adapted !== m.content) (m.content = adapted), (changed = true)
|
||||
} else if (Array.isArray(m.content)) {
|
||||
for (const p of m.content) {
|
||||
const list = Array.isArray(msgs) ? msgs : []
|
||||
list.forEach((m, i) => {
|
||||
if (!m || typeof m !== "object") return
|
||||
let adapt, field = "content"
|
||||
if (m.role === "system" || m.role === "developer") adapt = prompt && i === 0 && m.role === "system" ? promptText : systemMessageText
|
||||
else if (m.role === "user") adapt = (t) => userText(piSummary(t))
|
||||
else if (m.role === "tool") adapt = (t) => quotedToolText(t)
|
||||
else if (m.type === "function_call_output") (adapt = (t) => quotedToolText(t)), (field = "output")
|
||||
else return
|
||||
const c = m[field]
|
||||
if (typeof c === "string") {
|
||||
const adapted = adapt(c)
|
||||
if (adapted !== c) (m[field] = adapted), (changed = true)
|
||||
} else if (Array.isArray(c)) {
|
||||
for (const p of c) {
|
||||
if (!p || typeof p !== "object" || typeof p.text !== "string") continue
|
||||
const adapted = adapt(p.text)
|
||||
// a part is a block of its own: no joined reminders to look into
|
||||
const adapted = m.role === "user" ? userBlockText(piSummary(p.text)) : adapt(p.text)
|
||||
if (adapted !== p.text) (p.text = adapted), (changed = true)
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
return changed
|
||||
}
|
||||
|
||||
@@ -459,13 +470,13 @@ function droidBody(path, body) {
|
||||
const v = m.instructions
|
||||
if (v !== undefined && v !== null && typeof v !== "string") return body // not something droid sends
|
||||
const opened = promptOpenings(m.input)
|
||||
const ins = clientOpening(v ?? "")
|
||||
const ins = promptText(v ?? "")
|
||||
if (!ins.startsWith(DROID_LINE)) m.instructions = ins.trim() === "" ? DROID_LINE : DROID_LINE + "\n" + ins
|
||||
else if (ins !== v || opened) m.instructions = ins
|
||||
else return body
|
||||
} else if (path.endsWith("/chat/completions")) {
|
||||
if (!Array.isArray(m.messages)) return body
|
||||
const opened = promptOpenings(m.messages)
|
||||
const opened = promptOpenings(m.messages, true)
|
||||
if (!droidChat(m.messages) && !opened) return body
|
||||
} else return body
|
||||
return JSON.stringify(m)
|
||||
@@ -1191,6 +1202,62 @@ function quotedToolText(text, prefix = QUOTED_TOOL_PREFIX) {
|
||||
return prefix + encoded
|
||||
}
|
||||
|
||||
// The adapters below are shared by both of Factory's routes. Claude Code's
|
||||
// request reaches /api/llm/a as Messages, but a model Factory serves on
|
||||
// /api/llm/o (GLM, Kimi and other chat models) gets it translated by magpie
|
||||
// into chat completions or Responses, carrying the same fixed phrases.
|
||||
// Factory refuses them there too (Echoo on magpie's Discord: GLM-5.3-Flash,
|
||||
// Claude Code 403 while Codex worked on the same account).
|
||||
|
||||
// claudeIdentity opens text with droid's line in place of Claude Code's
|
||||
// fixed first line, when text is that line alone or opens with it.
|
||||
function claudeIdentity(text) {
|
||||
const identity = [...CLAUDE_IDENTITIES].find((line) => text === line || text.startsWith(line + "\n"))
|
||||
return identity ? DROID_LINE + text.slice(identity.length) : text
|
||||
}
|
||||
|
||||
// promptText adapts a system prompt's text.
|
||||
function promptText(text) {
|
||||
return clientOpening(systemModelLine(claudeIdentity(text)))
|
||||
}
|
||||
|
||||
// systemMessageText adapts a system message's text after the prompt.
|
||||
function systemMessageText(text) {
|
||||
return bareSkills(clientOpening(systemContext(text)))
|
||||
}
|
||||
|
||||
// userBlockText adapts one text block of a user turn.
|
||||
function userBlockText(text) {
|
||||
const compacted = compactContext(text)
|
||||
if (compacted !== text) return compacted
|
||||
if (text.startsWith(INSTRUCTIONS_REMINDER) && text.includes(GLOBAL_INSTRUCTIONS)) return text.replaceAll(GLOBAL_INSTRUCTIONS, "(global instructions)")
|
||||
// a system message folded into the user's turn on its way here
|
||||
if (HOOK_OUTPUT.test(text) || SYSTEM_ENV_CONTEXT.test(text)) return systemContext(text)
|
||||
if (ENV_REMINDER.test(text)) {
|
||||
return text.replace("# Environment", "# Runtime context")
|
||||
.replace("You have been invoked in the following environment:", "The session environment is:")
|
||||
}
|
||||
if (MODEL_REMINDER.test(text)) {
|
||||
return text.replace("You are powered by the model named", "Current model name:")
|
||||
.replace("You are powered by the model", "Current model:")
|
||||
.replace("The exact model ID is", "Model ID:")
|
||||
.replace("Assistant knowledge cutoff is", "Model knowledge cutoff:")
|
||||
}
|
||||
if (SKILL_REMINDER.test(text)) return text.replace("\n" + CONFIG_SKILL_METADATA, "\n" + CONFIG_SKILL_COMPAT)
|
||||
return text
|
||||
}
|
||||
|
||||
// A chat completions user message is one string: magpie joins a Messages
|
||||
// turn's text blocks with nothing between them, so a reminder block and the
|
||||
// user's words arrive as one text. Adapted whole first, then each complete
|
||||
// reminder in it as the block it was; the rest stays as it is.
|
||||
const REMINDER_BLOCK = /<system-reminder>\n[\s\S]*?\n<\/system-reminder>/g
|
||||
function userText(text) {
|
||||
const adapted = userBlockText(text)
|
||||
if (adapted !== text || !text.includes("<system-reminder>\n")) return adapted
|
||||
return text.replace(REMINDER_BLOCK, (block) => userBlockText(block))
|
||||
}
|
||||
|
||||
function anthropicBody(body) {
|
||||
let request
|
||||
try {
|
||||
@@ -1226,9 +1293,7 @@ function anthropicBody(body) {
|
||||
if (block?.type === "text") {
|
||||
// The gateway may join the identity and instructions into one block.
|
||||
// Only the complete fixed first line is metadata; keep the rest.
|
||||
const identity = [...CLAUDE_IDENTITIES].find((line) => block.text === line || block.text.startsWith(line + "\n"))
|
||||
const text = identity ? DROID_LINE + block.text.slice(identity.length) : block.text
|
||||
const adapted = clientOpening(systemModelLine(text))
|
||||
const adapted = promptText(block.text)
|
||||
if (adapted !== block.text) {
|
||||
block.text = adapted
|
||||
changed = true
|
||||
@@ -1256,7 +1321,7 @@ function anthropicBody(body) {
|
||||
|
||||
for (const message of request.messages) {
|
||||
if (message?.role === "system" && typeof message.content === "string") {
|
||||
const adapted = bareSkills(clientOpening(systemContext(message.content)))
|
||||
const adapted = systemMessageText(message.content)
|
||||
if (adapted !== message.content) {
|
||||
message.content = adapted
|
||||
changed = true
|
||||
@@ -1269,7 +1334,7 @@ function anthropicBody(body) {
|
||||
if (message?.role === "system" && Array.isArray(message.content)) {
|
||||
for (const block of message.content) {
|
||||
if (block?.type !== "text" || typeof block.text !== "string") continue
|
||||
const adapted = bareSkills(clientOpening(systemContext(block.text)))
|
||||
const adapted = systemMessageText(block.text)
|
||||
if (adapted !== block.text) {
|
||||
block.text = adapted
|
||||
changed = true
|
||||
@@ -1308,36 +1373,10 @@ function anthropicBody(body) {
|
||||
continue
|
||||
}
|
||||
if (block?.type !== "text" || typeof block.text !== "string") continue
|
||||
const compacted = compactContext(block.text)
|
||||
if (compacted !== block.text) {
|
||||
block.text = compacted
|
||||
const adapted = userBlockText(block.text)
|
||||
if (adapted !== block.text) {
|
||||
block.text = adapted
|
||||
changed = true
|
||||
} else if (block.text.startsWith(INSTRUCTIONS_REMINDER) && block.text.includes(GLOBAL_INSTRUCTIONS)) {
|
||||
block.text = block.text.replaceAll(GLOBAL_INSTRUCTIONS, "(global instructions)")
|
||||
changed = true
|
||||
} else if (HOOK_OUTPUT.test(block.text) || SYSTEM_ENV_CONTEXT.test(block.text)) {
|
||||
// a system message folded into the user's turn on its way here
|
||||
const adapted = systemContext(block.text)
|
||||
if (adapted !== block.text) {
|
||||
block.text = adapted
|
||||
changed = true
|
||||
}
|
||||
} else if (ENV_REMINDER.test(block.text)) {
|
||||
block.text = block.text.replace("# Environment", "# Runtime context")
|
||||
.replace("You have been invoked in the following environment:", "The session environment is:")
|
||||
changed = true
|
||||
} else if (MODEL_REMINDER.test(block.text)) {
|
||||
block.text = block.text.replace("You are powered by the model named", "Current model name:")
|
||||
.replace("You are powered by the model", "Current model:")
|
||||
.replace("The exact model ID is", "Model ID:")
|
||||
.replace("Assistant knowledge cutoff is", "Model knowledge cutoff:")
|
||||
changed = true
|
||||
} else if (SKILL_REMINDER.test(block.text)) {
|
||||
const adapted = block.text.replace("\n" + CONFIG_SKILL_METADATA, "\n" + CONFIG_SKILL_COMPAT)
|
||||
if (adapted !== block.text) {
|
||||
block.text = adapted
|
||||
changed = true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@magpie-community/opencode-factory-auth",
|
||||
"version": "0.1.28",
|
||||
"version": "0.1.29",
|
||||
"description": "Sign in to a Factory (Droid) subscription from OpenCode or magpie",
|
||||
"type": "module",
|
||||
"main": "./index.mjs",
|
||||
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
Reference in New Issue
Block a user