factory: support Claude Code on the Anthropic Messages route (#3)
* factory: adapt Claude Code Anthropic request bodies * factory: address Anthropic compatibility review * factory: handle additional directories and refresh 403 guidance
This commit is contained in:
@@ -44,9 +44,9 @@ droid sends opens its system prompt with "You are Droid, an AI software
|
||||
engineering agent built by Factory.", so another agent's request to
|
||||
Factory's OpenAI-shaped API (`/api/llm/o`: GPT and Grok on Responses, the
|
||||
open models on chat completions) opens with that line too, the agent's own
|
||||
prompt after it. Claude models (and MiniMax M2.7) on Anthropic's Messages
|
||||
are sent as the agent sent them, and Factory may refuse them from agents
|
||||
other than Droid.
|
||||
prompt after it. On Anthropic's Messages (`/api/llm/a`), the plugin adapts
|
||||
fixed client metadata while preserving the task instructions and history;
|
||||
see [Claude Code through magpie](#claude-code-through-magpie) below.
|
||||
|
||||
## Models
|
||||
|
||||
@@ -71,3 +71,26 @@ The list is not included:
|
||||
magpie plugin add @magpie-community/opencode-factory-auth
|
||||
magpie plugin login factory
|
||||
```
|
||||
|
||||
## Claude Code through magpie
|
||||
|
||||
Factory's Anthropic route requires Droid's fixed client preamble and
|
||||
refuses some of Claude Code's fixed environment and model wrappers. The
|
||||
plugin adapts that metadata while preserving the coding instructions,
|
||||
environment values, tool definitions, tool results, images and reasoning
|
||||
options. Native Droid requests remain unchanged, and OpenAI routes keep
|
||||
their existing request adapter.
|
||||
|
||||
Use magpie's Claude Code integration to select the Factory provider.
|
||||
magpie manages the provider-specific client settings, including capability
|
||||
and permission configuration. Fields such as `safeguards` and
|
||||
`context_management` are forwarded for Factory to validate; the request
|
||||
adapter preserves them along with the other request options.
|
||||
|
||||
The same metadata adaptation applies to `/messages` and
|
||||
`/messages/count_tokens`, so token counting sees the prompt used for
|
||||
inference. Serving the counting endpoint still depends on the host and
|
||||
upstream. Model and feature availability depend on the Factory account,
|
||||
organization region and upstream API. Connectivity has been verified with
|
||||
Sonnet 4.6, Sonnet 5.5 and Opus 5.5, and a two-turn Read tool call with
|
||||
Sonnet 4.6.
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
// (since v0.1.630, e413dd84) opens another agent's request to /api/llm/o as
|
||||
// droid 0.231.0 opens its own: Responses' instructions, or chat
|
||||
// completions' first system message, start with droid's line, joined with
|
||||
// "\n". droid's own requests and Anthropic's Messages go on byte for byte.
|
||||
// "\n". droid's own requests go on byte for byte on each API.
|
||||
// The cases are the built-in's TestFactoryOpensAsDroid.
|
||||
import { afterEach, expect, test } from "bun:test"
|
||||
import { FactoryAuthPlugin, _internal } from "./index.mjs"
|
||||
@@ -80,13 +80,13 @@ test("another agent's request to /api/llm/o opens with droid's line", async () =
|
||||
expect(b.instructions).toBe(DROID_LINE)
|
||||
})
|
||||
|
||||
test("droid's own requests, and Anthropic's Messages, go on byte for byte", async () => {
|
||||
test("droid's own requests go on byte for byte on each API", async () => {
|
||||
const { send } = await loaded({ ...signedIn })
|
||||
for (const [url, body] of [
|
||||
[chat, `{"model":"glm-5.3-flash","messages":[{"role":"system","content":"${DROID_LINE}\\nYou work in the user's terminal."},{"role":"user","content":"hi"}],"stream":true,"n":1.0}`],
|
||||
[responses, `{"model":"gpt-5.5","input":[],"store":false,"instructions":"${DROID_LINE}\\nYou work in the user's terminal.","stream":true}`],
|
||||
[messages, `{"model":"claude-opus-5-5","system":"You are Claude Code.","messages":[{"role":"user","content":"hi"}]}`],
|
||||
[messages, `{"model":"minimax-m2.7","messages":[{"role":"user","content":"hi"}]}`],
|
||||
[messages, `{"model":"claude-opus-5-5","system":[{"type":"text","text":"${DROID_LINE}"}],"messages":[{"role":"user","content":"hi"}]}`],
|
||||
[messages, `{"model":"minimax-m2.7","system":[{"type":"text","text":"${DROID_LINE}"}],"messages":[{"role":"user","content":"hi"}]}`],
|
||||
]) {
|
||||
const s = await send(url, body)
|
||||
expect(s.body).toBe(body)
|
||||
@@ -154,7 +154,7 @@ test("an API key account is the bearer, with no org and no renewal", async () =>
|
||||
globalThis.fetch = async () => new Response(JSON.stringify({ error: { message: "nope" } }), { status: 403 })
|
||||
const res = await l.fetch(chat, { method: "POST", body: `{"model":"glm-5.3","messages":[]}` })
|
||||
expect(res.status).toBe(403)
|
||||
expect((await res.json()).error.message).toMatch(/^nope — Factory takes/)
|
||||
expect((await res.json()).error.message).toMatch(/^nope — Factory refused/)
|
||||
})
|
||||
|
||||
test("a key account's usage reads the limits with the key", async () => {
|
||||
|
||||
@@ -245,7 +245,7 @@ const orgRefused = (status, text) => status === 403 && text.toLowerCase().includ
|
||||
function explain(status, text) {
|
||||
if (status !== 403) return ""
|
||||
if (orgRefused(status, text)) return "the Factory account's organization changed; remove the account in magpie and sign in to it again"
|
||||
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"
|
||||
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"
|
||||
}
|
||||
|
||||
// ---- opening as droid ---------------------------------------------------------
|
||||
@@ -260,8 +260,8 @@ function explain(status, text) {
|
||||
// system message first, joined the same way). So another agent's request to
|
||||
// /api/llm/o opens with the line too, as the built-in's factoryDroidBody
|
||||
// (internal/provider/factory_client.go) has it. Anthropic's Messages
|
||||
// (/api/llm/a) is left as the agent sent it, and so is a request that
|
||||
// already opens with the line: droid's own goes on byte for byte.
|
||||
// (/api/llm/a) uses anthropicBody below to adapt fixed client metadata.
|
||||
// A native Droid request goes on byte for byte.
|
||||
|
||||
const DROID_LINE = "You are Droid, an AI software engineering agent built by Factory."
|
||||
|
||||
@@ -569,6 +569,96 @@ function bodyModel(body) {
|
||||
}
|
||||
}
|
||||
|
||||
// Factory's Anthropic route accepts Droid's client preamble. Keep the
|
||||
// caller's instructions, tools and history, adapting only fixed client
|
||||
// metadata that Factory refuses (including Claude Code's wrappers).
|
||||
const CLAUDE_IDENTITIES = new Set([
|
||||
"You are Claude Code, Anthropic's official CLI for Claude.",
|
||||
"You are Claude Code, Anthropic's official CLI for Claude, running within the Claude Agent SDK.",
|
||||
"You are a Claude agent, built on Anthropic's Claude Agent SDK.",
|
||||
])
|
||||
|
||||
// Match a complete generated block, not a pasted reminder followed by a
|
||||
// user's question, or an incomplete fragment of one.
|
||||
const ENV_REMINDER = /^<system-reminder>\n# Environment\nYou have been invoked in the following environment:[ \t]*\n(?: {1,2}- [^\n]*\n)+<\/system-reminder>$/
|
||||
const MODEL_REMINDER = /^<system-reminder>\nYou are powered by the model (?:named )?[^\n<>]+\.\n<\/system-reminder>$/
|
||||
|
||||
function anthropicBody(body) {
|
||||
let request
|
||||
try {
|
||||
const text = typeof body === "string" ? body
|
||||
: body instanceof ArrayBuffer ? Buffer.from(body).toString("utf8")
|
||||
: ArrayBuffer.isView(body) ? Buffer.from(body.buffer, body.byteOffset, body.byteLength).toString("utf8") : ""
|
||||
request = JSON.parse(text)
|
||||
} catch {
|
||||
return body
|
||||
}
|
||||
// As in droidBody, JSON round-tripping uses JavaScript Numbers: integer
|
||||
// tokens above 2^53 can lose precision when a body needs adapting. A
|
||||
// body that needs no changes is returned byte-for-byte instead.
|
||||
if (!request || !Array.isArray(request.messages)) return body
|
||||
if (request.system != null && typeof request.system !== "string" && !Array.isArray(request.system)) return body
|
||||
if (Array.isArray(request.system) && request.system.some((b) => b?.type === "text" && typeof b.text !== "string")) return body
|
||||
|
||||
let changed = false
|
||||
const system = typeof request.system === "string" ? [{ type: "text", text: request.system }] : request.system ?? []
|
||||
if (typeof request.system === "string" && !request.system.startsWith(DROID_LINE)) changed = true
|
||||
const kept = []
|
||||
for (const block of system) {
|
||||
if (block?.type === "text" && block.text.trim() === "") {
|
||||
changed = true
|
||||
continue
|
||||
}
|
||||
// Attribution is consumed here; Factory does not strip Anthropic's
|
||||
// billing block and requires the Droid identity to be first.
|
||||
if (block?.type === "text" && block.text?.startsWith("x-anthropic-billing-header: cc_version=")) {
|
||||
changed = true
|
||||
continue
|
||||
}
|
||||
if (block?.type === "text" && CLAUDE_IDENTITIES.has(block.text)) {
|
||||
block.text = DROID_LINE
|
||||
changed = true
|
||||
}
|
||||
kept.push(block)
|
||||
}
|
||||
const identity = kept.findIndex((b) => b?.type === "text" && b.text.startsWith(DROID_LINE))
|
||||
if (identity < 0) {
|
||||
kept.unshift({ type: "text", text: DROID_LINE })
|
||||
changed = true
|
||||
} else if (identity > 0) {
|
||||
kept.unshift(...kept.splice(identity, 1))
|
||||
changed = true
|
||||
}
|
||||
// Drop only duplicate identity-only blocks. A block that also contains
|
||||
// task instructions stays intact.
|
||||
for (let i = kept.length - 1; i > 0; i--) {
|
||||
if (kept[i]?.type === "text" && kept[i].text === DROID_LINE) {
|
||||
kept.splice(i, 1)
|
||||
changed = true
|
||||
}
|
||||
}
|
||||
if (changed) request.system = kept
|
||||
|
||||
for (const message of request.messages) {
|
||||
if (message?.role !== "user" || !Array.isArray(message.content)) continue
|
||||
for (const block of message.content) {
|
||||
if (block?.type !== "text" || typeof block.text !== "string") continue
|
||||
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
|
||||
}
|
||||
}
|
||||
}
|
||||
return changed ? JSON.stringify(request) : body
|
||||
}
|
||||
|
||||
export const FactoryAuthPlugin = async ({ client }) => {
|
||||
// the session id this process's requests carry
|
||||
const session = crypto.randomUUID()
|
||||
@@ -806,7 +896,8 @@ export const FactoryAuthPlugin = async ({ client }) => {
|
||||
// which Anthropic's SDK sends beside the bearer token
|
||||
if (path.includes("/llm/a/")) h.set("X-Api-Key", "placeholder")
|
||||
// another agent's request opens as droid's does (droidBody)
|
||||
const out = droidBody(path, body)
|
||||
const out = path.includes("/llm/a/") && (path.endsWith("/messages") || path.endsWith("/messages/count_tokens"))
|
||||
? anthropicBody(body) : droidBody(path, body)
|
||||
if (out !== body) h.delete("content-length")
|
||||
return fetch(url, { ...init, method: init?.method ?? (input instanceof Request ? input.method : "POST"), headers: h, body: out })
|
||||
}
|
||||
|
||||
@@ -66,10 +66,10 @@ test("a refusal says what to do after an em dash, as the built-in's Explain join
|
||||
let res = await l.fetch("https://api.factory.ai/api/llm/o/v1/responses", { method: "POST", body: JSON.stringify({ model: "gpt-x" }) })
|
||||
expect(res.status).toBe(403)
|
||||
expect(res.headers.get("X-Magpie-Sign-In")).toBe("kept")
|
||||
expect((await res.json()).error.message).toMatch(/^model not allowed — Factory takes a Factory subscription's requests only from Droid itself\. /)
|
||||
expect((await res.json()).error.message).toMatch(/^model not allowed — Factory refused the request\. /)
|
||||
globalThis.fetch = async () => new Response("", { status: 403 })
|
||||
res = await l.fetch("https://api.factory.ai/api/llm/o/v1/responses", { method: "POST", body: JSON.stringify({ model: "gpt-x" }) })
|
||||
expect((await res.json()).error.message).toMatch(/^403 Forbidden — Factory takes a Factory subscription's requests only from Droid/)
|
||||
expect((await res.json()).error.message).toMatch(/^403 Forbidden — Factory refused the request\./)
|
||||
})
|
||||
|
||||
// a live account whose requests fetch answers with serve
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@magpie-community/opencode-factory-auth",
|
||||
"version": "0.1.5",
|
||||
"version": "0.1.6",
|
||||
"description": "Sign in to a Factory (Droid) subscription from OpenCode or magpie",
|
||||
"type": "module",
|
||||
"main": "./index.mjs",
|
||||
|
||||
@@ -0,0 +1,207 @@
|
||||
import { afterEach, expect, test } from "bun:test"
|
||||
import { FactoryAuthPlugin } from "./index.mjs"
|
||||
|
||||
const real = globalThis.fetch
|
||||
afterEach(() => (globalThis.fetch = real))
|
||||
const url = "https://api.factory.ai/api/llm/a/v1/messages"
|
||||
const droid = "You are Droid, an AI software engineering agent built by Factory."
|
||||
|
||||
async function loaded() {
|
||||
const seen = []
|
||||
globalThis.fetch = async (url, init) => {
|
||||
seen.push({ url: String(url), ...init })
|
||||
return new Response('event: message_stop\ndata: {"type":"message_stop"}\n\n', { headers: { "content-type": "text/event-stream" } })
|
||||
}
|
||||
const auth = { type: "oauth", access: "factory-token", expires: Date.now() + 3_600_000, activeOrganizationId: "org_A" }
|
||||
const hooks = await FactoryAuthPlugin({ client: { auth: { set: async () => {} } } })
|
||||
return { l: await hooks.auth.loader(async () => auth), seen }
|
||||
}
|
||||
|
||||
test("adapts Claude Code metadata, preserving instructions, tool turns, images and capabilities", async () => {
|
||||
const { l, seen } = await loaded()
|
||||
const request = {
|
||||
model: "claude-sonnet-4-6",
|
||||
system: [
|
||||
{ type: "text", text: "x-anthropic-billing-header: cc_version=2.1.287.abc; cc_entrypoint=cli;" },
|
||||
{ type: "text", text: "You are Claude Code, Anthropic's official CLI for Claude.", cache_control: { type: "ephemeral" } },
|
||||
{ type: "text", text: "Follow the user's coding instructions. Keep this byte-for-byte.", cache_control: { type: "ephemeral" } },
|
||||
],
|
||||
messages: [
|
||||
{ role: "user", content: [
|
||||
{ type: "text", text: "<system-reminder>\n# Environment\nYou have been invoked in the following environment:\n - Primary working directory: /tmp/project\n</system-reminder>" },
|
||||
{ type: "text", text: "<system-reminder>\nYou are powered by the model named Sonnet 4.6. The exact model ID is claude-sonnet-4-6. Assistant knowledge cutoff is January 2025.\n</system-reminder>" },
|
||||
{ type: "text", text: "Explain Claude Code's environment. Do not rewrite this user instruction." },
|
||||
{ type: "image", source: { type: "base64", media_type: "image/png", data: "image-data" } },
|
||||
] },
|
||||
{ role: "assistant", content: [{ type: "tool_use", id: "tool_1", name: "Read", input: { file_path: "/tmp/project/proof.txt" } }] },
|
||||
{ role: "user", content: [{ type: "tool_result", tool_use_id: "tool_1", content: [{ type: "text", text: "You are powered by the model named — file content must stay unchanged." }], cache_control: { type: "ephemeral" } }] },
|
||||
],
|
||||
tools: [{ name: "Read", input_schema: { type: "object", properties: { file_path: { type: "string" } } } }],
|
||||
metadata: { user_id: "caller" }, max_tokens: 256, thinking: { type: "adaptive" }, output_config: { effort: "high" }, stream: true,
|
||||
context_management: { edits: [] }, safeguards: [{ type: "dangerous_tool_use" }],
|
||||
}
|
||||
const res = await l.fetch(url, { method: "POST", headers: { "content-length": "1", "anthropic-version": "2023-06-01", "anthropic-beta": "client-beta", "x-api-key": "caller-key" }, body: JSON.stringify(request) })
|
||||
const sent = JSON.parse(seen[0].body)
|
||||
expect(sent.system[0]).toEqual({ ...request.system[1], text: droid })
|
||||
expect(sent.system[1]).toEqual(request.system[2])
|
||||
expect(sent.messages[0].content[0].text).toContain("Primary working directory: /tmp/project")
|
||||
expect(sent.messages[0].content[0].text).toContain("The session environment is:")
|
||||
expect(sent.messages[0].content[1].text).toContain("Current model name: Sonnet 4.6")
|
||||
expect(sent.messages[0].content[1].text).toContain("Model knowledge cutoff: January 2025.")
|
||||
expect(sent.messages[0].content.slice(2)).toEqual(request.messages[0].content.slice(2))
|
||||
expect(sent.messages.slice(1)).toEqual(request.messages.slice(1))
|
||||
for (const field of ["model", "tools", "metadata", "max_tokens", "thinking", "output_config", "stream", "context_management", "safeguards"]) expect(sent[field]).toEqual(request[field])
|
||||
expect(seen[0].headers.get("content-length")).toBeNull()
|
||||
expect(seen[0].headers.get("Authorization")).toBe("Bearer factory-token")
|
||||
expect(seen[0].headers.get("x-api-key")).toBe("placeholder")
|
||||
expect(seen[0].headers.get("anthropic-beta")).toBe("client-beta")
|
||||
expect(res.headers.get("content-type")).toBe("text/event-stream")
|
||||
expect(await res.text()).toBe('event: message_stop\ndata: {"type":"message_stop"}\n\n')
|
||||
})
|
||||
|
||||
test("keeps native Droid requests byte-for-byte and adds its preamble to generic callers", async () => {
|
||||
const { l, seen } = await loaded()
|
||||
const body = '{ "model": "claude-sonnet-4-6", "system": [{"type":"text","text":' + JSON.stringify(droid) + '}], "messages": [{"role":"user","content":"OK"}] }'
|
||||
await l.fetch(url, { method: "POST", body })
|
||||
expect(seen[0].body).toBe(body)
|
||||
await l.fetch(url, { method: "POST", body: JSON.stringify({ model: "claude-sonnet-4-6", system: "Keep these exact instructions.", messages: [{ role: "user", content: "OK" }] }) })
|
||||
expect(JSON.parse(seen[1].body).system).toEqual([{ type: "text", text: droid }, { type: "text", text: "Keep these exact instructions." }])
|
||||
})
|
||||
|
||||
test("handles SDK identity, request bodies and offset byte views without duplicating metadata", async () => {
|
||||
const { l, seen } = await loaded()
|
||||
const body = JSON.stringify({ model: "claude-sonnet-4-6", system: [{ type: "text", text: "You are a Claude agent, built on Anthropic's Claude Agent SDK." }], messages: [{ role: "user", content: "OK" }] })
|
||||
const bytes = Buffer.from("unused" + body + "unused")
|
||||
const view = new Uint8Array(bytes.buffer, bytes.byteOffset + 6, Buffer.byteLength(body))
|
||||
await l.fetch(url, { method: "POST", body: view })
|
||||
expect(JSON.parse(seen[0].body).system).toEqual([{ type: "text", text: droid }])
|
||||
await l.fetch(new Request(url, { method: "POST", body }))
|
||||
expect(seen[1].body).toBe(seen[0].body)
|
||||
await l.fetch(url, { method: "POST", body: seen[0].body })
|
||||
expect(seen[2].body).toBe(seen[0].body)
|
||||
})
|
||||
|
||||
test("does not change OpenAI requests, malformed JSON or invalid system schemas", async () => {
|
||||
const { l, seen } = await loaded()
|
||||
const body = JSON.stringify({ model: "gpt-6-sol", instructions: droid, input: "OK" })
|
||||
await l.fetch("https://api.factory.ai/api/llm/o/v1/responses", { method: "POST", body })
|
||||
expect(seen[0].body).toBe(body)
|
||||
for (const body of ["not-json", JSON.stringify({ model: "claude-sonnet-4-6", system: {}, messages: [] }), JSON.stringify({ system: [{ type: "text", text: 123 }], messages: [] })]) {
|
||||
await l.fetch(url, { method: "POST", body })
|
||||
expect(seen.at(-1).body).toBe(body)
|
||||
}
|
||||
})
|
||||
|
||||
test("recognizes Claude Code running within the Agent SDK", async () => {
|
||||
const { l, seen } = await loaded()
|
||||
await l.fetch(url, { method: "POST", body: JSON.stringify({
|
||||
system: [{ type: "text", text: "You are Claude Code, Anthropic's official CLI for Claude, running within the Claude Agent SDK.", cache_control: { type: "ephemeral" } }],
|
||||
messages: [{ role: "user", content: "OK" }],
|
||||
}) })
|
||||
expect(JSON.parse(seen[0].body).system).toEqual([{ type: "text", text: droid, cache_control: { type: "ephemeral" } }])
|
||||
})
|
||||
|
||||
test("adapts the complete model reminder without a marketing name", async () => {
|
||||
const { l, seen } = await loaded()
|
||||
await l.fetch(url, { method: "POST", body: JSON.stringify({
|
||||
messages: [{ role: "user", content: [{ type: "text", text: "<system-reminder>\nYou are powered by the model custom-model.\n</system-reminder>" }] }],
|
||||
}) })
|
||||
expect(JSON.parse(seen[0].body).messages[0].content[0].text).toBe("<system-reminder>\nCurrent model: custom-model.\n</system-reminder>")
|
||||
})
|
||||
|
||||
test("adapts complete environment reminders with nested additional working directories", async () => {
|
||||
const { l, seen } = await loaded()
|
||||
const reminder = "<system-reminder>\n# Environment\nYou have been invoked in the following environment:\n - Primary working directory: /tmp/project\n - Additional working directories:\n - /extra/one\n - /extra/two\n - Platform: darwin\n</system-reminder>"
|
||||
const pasted = reminder + "\nPlease explain these directories."
|
||||
const body = JSON.stringify({ messages: [{ role: "user", content: [
|
||||
{ type: "text", text: reminder, cache_control: { type: "ephemeral" } },
|
||||
{ type: "text", text: pasted },
|
||||
] }] })
|
||||
for (const endpoint of [url, url + "/count_tokens"]) {
|
||||
await l.fetch(endpoint, { method: "POST", body })
|
||||
expect(JSON.parse(seen.at(-1).body).messages[0].content).toEqual([
|
||||
{ type: "text", text: reminder.replace("# Environment", "# Runtime context").replace("You have been invoked in the following environment:", "The session environment is:"), cache_control: { type: "ephemeral" } },
|
||||
{ type: "text", text: pasted },
|
||||
])
|
||||
}
|
||||
})
|
||||
|
||||
test("explains an Anthropic 403 without claiming these clients are always refused", async () => {
|
||||
const { l } = await loaded()
|
||||
globalThis.fetch = async () => new Response(JSON.stringify({ error: { message: "Model unavailable for this organization" } }), { status: 403 })
|
||||
const res = await l.fetch(url, { method: "POST", body: JSON.stringify({ model: "claude-sonnet-4-6", messages: [{ role: "user", content: "OK" }] }) })
|
||||
expect(res.status).toBe(403)
|
||||
const message = (await res.json()).error.message
|
||||
expect(message).toStartWith("Model unavailable for this organization — Factory refused")
|
||||
expect(message).toContain("OpenAI and Anthropic")
|
||||
expect(message).toContain("regional provider availability")
|
||||
expect(message).not.toContain("are sent as the agent sent them")
|
||||
})
|
||||
|
||||
test("drops an empty or whitespace-only string system", async () => {
|
||||
const { l, seen } = await loaded()
|
||||
for (const system of ["", " \n\t", [{ type: "text", text: "" }]]) {
|
||||
await l.fetch(url, { method: "POST", body: JSON.stringify({ system, messages: [{ role: "user", content: "OK" }] }) })
|
||||
expect(JSON.parse(seen.at(-1).body).system).toEqual([{ type: "text", text: droid }])
|
||||
}
|
||||
})
|
||||
|
||||
test("preserves a native Droid string system without duplicating the preamble", async () => {
|
||||
const { l, seen } = await loaded()
|
||||
for (const system of [droid, droid + "\nKeep the user's instructions."]) {
|
||||
const body = JSON.stringify({ system, messages: [{ role: "user", content: "OK" }] })
|
||||
await l.fetch(url, { method: "POST", body })
|
||||
expect(seen.at(-1).body).toBe(body)
|
||||
}
|
||||
})
|
||||
|
||||
test("preserves pasted reminders with user text outside the complete block", async () => {
|
||||
const { l, seen } = await loaded()
|
||||
const reminders = [
|
||||
"<system-reminder>\n# Environment\nYou have been invoked in the following environment:\n - Platform: linux\n</system-reminder>",
|
||||
"<system-reminder>\nYou are powered by the model named Sonnet 4.6.\n</system-reminder>",
|
||||
"<system-reminder>\nYou are powered by the model custom-model.\n</system-reminder>",
|
||||
]
|
||||
const texts = reminders.flatMap((r) => [r + "\nPlease explain this pasted reminder.", r.replace("</system-reminder>", ""), "Please explain:\n" + r])
|
||||
await l.fetch(url, { method: "POST", body: JSON.stringify({
|
||||
messages: [{ role: "user", content: texts.map((text) => ({ type: "text", text })) }],
|
||||
}) })
|
||||
expect(JSON.parse(seen[0].body).messages[0].content).toEqual(texts.map((text) => ({ type: "text", text })))
|
||||
})
|
||||
|
||||
test("removes duplicate exact Droid identities while retaining the first block's metadata", async () => {
|
||||
const { l, seen } = await loaded()
|
||||
const identity = { type: "text", text: "You are Claude Code, Anthropic's official CLI for Claude.", cache_control: { type: "ephemeral" } }
|
||||
const native = { type: "text", text: droid }
|
||||
const instructions = { type: "text", text: "Keep all task instructions." }
|
||||
for (const system of [[identity, native, instructions], [native, identity, instructions], [native, native, instructions]]) {
|
||||
await l.fetch(url, { method: "POST", body: JSON.stringify({ system, messages: [{ role: "user", content: "OK" }] }) })
|
||||
expect(JSON.parse(seen.at(-1).body).system).toEqual([{ ...system[0], text: droid }, instructions])
|
||||
}
|
||||
})
|
||||
|
||||
test("adapts token-counting requests consistently with Messages and leaves other paths alone", async () => {
|
||||
const { l, seen } = await loaded()
|
||||
const body = JSON.stringify({ system: "Count these instructions.", messages: [{ role: "user", content: "OK" }] })
|
||||
await l.fetch(url, { method: "POST", body })
|
||||
await l.fetch(url + "/count_tokens", { method: "POST", body })
|
||||
expect(seen[1].body).toBe(seen[0].body)
|
||||
expect(seen[1].headers.get("content-length")).toBeNull()
|
||||
await l.fetch("https://api.factory.ai/api/llm/a/v1/models", { method: "POST", body })
|
||||
expect(seen[2].body).toBe(body)
|
||||
})
|
||||
|
||||
test("adapts MiniMax M2.7 on the Anthropic route while keeping its provider and options", async () => {
|
||||
const { l, seen } = await loaded()
|
||||
const options = { model: "minimax-m2.7", messages: [{ role: "user", content: "OK" }], max_tokens: 32, stream: true }
|
||||
await l.fetch(url, { method: "POST", body: JSON.stringify({ ...options, system: "You are OpenCode." }) })
|
||||
expect(JSON.parse(seen[0].body)).toEqual({ ...options, system: [{ type: "text", text: droid }, { type: "text", text: "You are OpenCode." }] })
|
||||
expect(seen[0].headers.get("x-api-provider")).toBe("fireworks")
|
||||
})
|
||||
|
||||
test("retains large integer tokens byte-for-byte in an unmodified native Droid request", async () => {
|
||||
const { l, seen } = await loaded()
|
||||
const body = '{"system":[{"type":"text","text":' + JSON.stringify(droid) + '}],"messages":[{"role":"assistant","content":[{"type":"tool_use","id":"call_1","name":"Read","input":{"id":12345678901234567890}}]}]}'
|
||||
await l.fetch(url, { method: "POST", body })
|
||||
expect(seen[0].body).toBe(body)
|
||||
})
|
||||
Reference in New Issue
Block a user