factory 0.1.34: Claude Code's re-read instructions reminder reaches Factory after compaction (#243)
zygs1083-dotcom (#243): after compaction, a long Claude Code session went 403 Forbidden on all three Factory accounts. Claude Code renders its instructions attachment two ways (n_t in 2.1.292 to 2.1.303): - first copy: "Codebase and user instructions are shown below. …" - changed copy (changed: true, reason compaction and others): "Instruction files were re-read after the conversation was compacted; these differ from their earlier copies — each replaces its earlier copy, and the instructions preamble above still applies:" (or "These instruction files changed — …" without a reason) Both list "Contents of ~/.claude/CLAUDE.md (user's private global instructions for all projects):", the phrase Factory refuses (magpie#634). Only the first opening was matched, so the changed copy went out as it was. - INSTRUCTIONS_REMINDER matches both openings, requiring the changed copy's full sentence and the "Contents of " that follows it. The rename is limited to the reminder itself: text joined after its close (chat completions' joined user text) stays as written. String user turns on /llm/a get it too; before, only text blocks did. - quotedToolText encodes tool output that quotes the phrase (the reporter's session read Claude Code's renderer source and went 403 from then on), losslessly, as for the other phrases. - A 403 the plugin rebuilds keeps Factory's request id (x-request-id, request-id, x-amzn-requestid, cf-ray, or the body's request_id) and the error's code and type in the message, and request_id on the Anthropic body. Headers already went back as they came. The fixtures are the literal texts the 2.1.303 bundle's n_t/Mje/bMr build and id() wraps; 2.1.301 and 2.1.302 have the same strings, and the 2.1.292 darwin-arm64 npm package has the same sentence pieces. What was run at this commit: - bun test packages/factory/: 161 pass, 0 fail. - bun scripts/check.mjs factory: ok. git diff --check: clean. - Broken by hand: with the old startsWith-only opening, the 4 changed- wrapper tests fail; without the phrase in quotedToolText, the tool-result test fails too; with upstreamIds returning nothing, the 403 test fails. - Not tried: a real Factory request with the changed reminder (no live account was used), so that Factory accepts the renamed copy is inferred from the first copy's fix in 0.1.12, not seen.
This commit is contained in:
@@ -229,6 +229,24 @@ token marker. Changed-file text supplied by hooks, quoted or incomplete
|
||||
notifications, and notices that omit the snippet are left alone. Model and
|
||||
environment metadata after non-startup hooks retain their existing adaptation.
|
||||
|
||||
Claude Code's instructions reminder names `~/.claude/CLAUDE.md` "(user's
|
||||
private global instructions for all projects)", which Factory refuses; in
|
||||
the generated reminder it becomes "(global instructions)". Claude Code
|
||||
renders that reminder two ways: the first copy opens with "Codebase and user
|
||||
instructions are shown below", and a copy re-read after the files changed
|
||||
(after compaction, a settings sync and the like) opens with "Instruction
|
||||
files were re-read …; these differ from their earlier copies" or "These
|
||||
instruction files changed". Both are adapted, in text blocks, string user
|
||||
turns and chat completions' joined user text; text after the reminder and
|
||||
a user's own mention of the phrase stay as written. A tool result that
|
||||
quotes the phrase (reading Claude Code's renderer, say) gets the lossless
|
||||
JSON encoding above.
|
||||
|
||||
When Factory still answers 403, the error magpie and the agent see keeps
|
||||
Factory's request id (from `x-request-id`, `request-id` or `cf-ray`, or the
|
||||
body) and its error code and type, and the Anthropic-route body carries
|
||||
`request_id`, so the refusal can be named to Factory.
|
||||
|
||||
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
|
||||
|
||||
@@ -410,6 +410,28 @@ function explain(status, text) {
|
||||
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"
|
||||
}
|
||||
|
||||
// upstreamIds are what Factory's refusal says to tell it apart when asking
|
||||
// Factory about it (plugins#243): the request id from its headers or body,
|
||||
// and the error's own code and type. The headers go back as they came too.
|
||||
const REQUEST_ID_HEADERS = ["x-request-id", "request-id", "x-amzn-requestid", "cf-ray"]
|
||||
function upstreamIds(text, headers) {
|
||||
let v
|
||||
try {
|
||||
v = JSON.parse(text)
|
||||
} catch {}
|
||||
const err = v && typeof v === "object" && v.error && typeof v.error === "object" ? v.error : {}
|
||||
const str = (x) => (typeof x === "string" && /^[\x21-\x7e]{1,128}$/.test(x) ? x : undefined)
|
||||
const id = str(v?.request_id) ?? str(v?.requestId) ?? str(err.request_id) ?? str(err.requestId) ??
|
||||
REQUEST_ID_HEADERS.map((h) => str(headers?.get?.(h) ?? undefined)).find(Boolean)
|
||||
const parts = []
|
||||
if (id) parts.push("request id " + id)
|
||||
const code = str(err.code) ?? str(v?.code)
|
||||
if (code) parts.push("code " + code)
|
||||
const type = str(err.type)
|
||||
if (type) parts.push("type " + type)
|
||||
return { id, said: parts.length ? " (upstream " + parts.join(", ") + ")" : "" }
|
||||
}
|
||||
|
||||
// ---- opening as droid ---------------------------------------------------------
|
||||
//
|
||||
// Factory takes a subscription's model requests only from Droid (magpie
|
||||
@@ -698,12 +720,14 @@ function tooLarge(text, left) {
|
||||
|
||||
// errorReply is an error as the API the request was for words one:
|
||||
// Anthropic's on /llm/a/, OpenAI's on the others.
|
||||
function errorReply(url, status, type, message, headers = new Headers()) {
|
||||
function errorReply(url, status, type, message, headers = new Headers(), requestId) {
|
||||
headers.set("content-type", "application/json")
|
||||
headers.delete("content-length")
|
||||
headers.delete("content-encoding")
|
||||
const anthropic = new URL(url).pathname.includes("/llm/a/")
|
||||
const body = anthropic ? { type: "error", error: { type, message } } : { error: { message, type, code: null } }
|
||||
// Anthropic's error body carries the request id beside the error
|
||||
if (anthropic && requestId) body.request_id = requestId
|
||||
return new Response(JSON.stringify(body), { status, headers })
|
||||
}
|
||||
|
||||
@@ -1159,8 +1183,24 @@ function systemModelLine(text) {
|
||||
|
||||
// The reminder carrying CLAUDE.md files names the global one with a phrase
|
||||
// Factory refuses; only that phrase in the generated reminder changes.
|
||||
const INSTRUCTIONS_REMINDER = "<system-reminder>\nCodebase and user instructions are shown below"
|
||||
// Claude Code renders the instructions attachment two ways (n_t in
|
||||
// 2.1.292/2.1.303): the first copy opens with the preamble, and a copy
|
||||
// re-read after the files changed (changed: true, with or without a
|
||||
// reason such as "compaction") opens with its own sentence before the same
|
||||
// "Contents of … (user's private global instructions for all projects):"
|
||||
// lines (plugins#243).
|
||||
const INSTRUCTIONS_REMINDER = /^<system-reminder>\n(?:Codebase and user instructions are shown below|(?:Instruction files were re-read [^\n]+; these differ from their earlier copies|These instruction files changed) \u2014 each replaces its earlier copy, and the instructions preamble above still applies:\nContents of )/
|
||||
const GLOBAL_INSTRUCTIONS = "(user's private global instructions for all projects)"
|
||||
// Only the reminder itself changes: text joined after its close (a chat
|
||||
// user message is a turn's blocks joined) stays as the user wrote it.
|
||||
function instructionsText(text) {
|
||||
if (!INSTRUCTIONS_REMINDER.test(text)) return text
|
||||
const close = text.indexOf("\n</system-reminder>")
|
||||
const end = close < 0 ? text.length : close + "\n</system-reminder>".length
|
||||
const reminder = text.slice(0, end)
|
||||
if (!reminder.includes(GLOBAL_INSTRUCTIONS)) return text
|
||||
return reminder.replaceAll(GLOBAL_INSTRUCTIONS, "(global instructions)") + text.slice(end)
|
||||
}
|
||||
|
||||
// Claude Code (2.1.291 and later) restores skills invoked before compaction
|
||||
// as one generated reminder. Factory refuses that fixed opening, and the restored
|
||||
@@ -1296,9 +1336,10 @@ function quotedToolText(text, prefix = QUOTED_TOOL_PREFIX) {
|
||||
if (![...CLAUDE_IDENTITIES].some((identity) => text.includes(identity)) &&
|
||||
!text.includes("You have been invoked in the following environment:") &&
|
||||
!text.includes("x-anthropic-billing-header: cc_version=") &&
|
||||
!text.includes(COMPACT_OPENING)) return text
|
||||
!text.includes(COMPACT_OPENING) &&
|
||||
!text.includes(GLOBAL_INSTRUCTIONS)) return text
|
||||
let encoded = JSON.stringify(text)
|
||||
for (const phrase of ["You are", "You have", "x-anthropic-billing-header", "system-reminder", COMPACT_OPENING]) {
|
||||
for (const phrase of ["You are", "You have", "x-anthropic-billing-header", "system-reminder", COMPACT_OPENING, GLOBAL_INSTRUCTIONS]) {
|
||||
encoded = encoded.replaceAll(phrase, "\\u" + phrase.charCodeAt(0).toString(16).padStart(4, "0") + phrase.slice(1))
|
||||
}
|
||||
return prefix + encoded
|
||||
@@ -1332,7 +1373,8 @@ function systemMessageText(text) {
|
||||
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)")
|
||||
const instructions = instructionsText(text)
|
||||
if (instructions !== text) return 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)) {
|
||||
@@ -1446,7 +1488,8 @@ function anthropicBody(body) {
|
||||
}
|
||||
if (message?.role !== "user") continue
|
||||
if (typeof message.content === "string") {
|
||||
const adapted = compactContext(message.content)
|
||||
const compacted = compactContext(message.content)
|
||||
const adapted = compacted !== message.content ? compacted : instructionsText(message.content)
|
||||
if (adapted !== message.content) {
|
||||
message.content = adapted
|
||||
changed = true
|
||||
@@ -1868,8 +1911,9 @@ export const FactoryAuthPlugin = async ({ client }) => {
|
||||
}
|
||||
const why = explain(res.status, text)
|
||||
// the refusal, then what to do about it, as provider.Explain joins them
|
||||
const msg = `${vendorError(text, statusLine(res.status))} — ${why}`
|
||||
return answer(errorReply(url, res.status, "permission_error", msg, new Headers(res.headers)))
|
||||
const ids = upstreamIds(text, res.headers)
|
||||
const msg = `${vendorError(text, statusLine(res.status))}${ids.said} — ${why}`
|
||||
return answer(errorReply(url, res.status, "permission_error", msg, new Headers(res.headers), ids.id))
|
||||
} catch (e) {
|
||||
// Factory refused to renew the sign-in: the built-in failed the
|
||||
// request (magpie's 502) and marked the account lapsed
|
||||
|
||||
@@ -0,0 +1,118 @@
|
||||
// plugins#243 (zygs1083-dotcom): Claude Code renders its instructions
|
||||
// attachment two ways. The first copy opens with the preamble; a copy
|
||||
// re-read after the files changed (changed: true, reason "compaction" and
|
||||
// the others) opens with its own sentence. Both name ~/.claude/CLAUDE.md
|
||||
// "(user's private global instructions for all projects)", which Factory
|
||||
// refuses (yetone/magpie#634), but only the first copy was adapted, so a
|
||||
// long session went 403 on every account after compaction.
|
||||
//
|
||||
// The texts below are what Claude Code 2.1.303's n_t()/Mje()/bMr() build
|
||||
// (the same functions as the reporter's 2.1.292), wrapped as id() wraps a
|
||||
// meta message: "<system-reminder>\n" + text + "\n</system-reminder>".
|
||||
import { afterEach, expect, test } from "bun:test"
|
||||
import { FactoryAuthPlugin } from "./index.mjs"
|
||||
|
||||
const real = globalThis.fetch
|
||||
afterEach(() => (globalThis.fetch = real))
|
||||
const messages = "https://api.factory.ai/api/llm/a/v1/messages"
|
||||
const chat = "https://api.factory.ai/api/llm/o/v1/chat/completions"
|
||||
const droid = "You are Droid, an AI software engineering agent built by Factory."
|
||||
|
||||
const GLOBAL = "(user's private global instructions for all projects)"
|
||||
const files = "Contents of /home/u/.claude/CLAUDE.md " + GLOBAL + ":\nUse tabs.\nContents of /tmp/p/CLAUDE.md (project instructions, checked into the codebase):\nRun the tests."
|
||||
const preamble = "Codebase and user instructions are shown below. Be sure to adhere to these instructions. IMPORTANT: These instructions OVERRIDE any default behavior and you MUST follow them exactly as written."
|
||||
const replaces = " — each replaces its earlier copy, and the instructions preamble above still applies:\n"
|
||||
const wrap = (t) => "<system-reminder>\n" + t + "\n</system-reminder>"
|
||||
const WRAPPERS = {
|
||||
initial: wrap(preamble + "\n" + files),
|
||||
compaction: wrap("Instruction files were re-read after the conversation was compacted; these differ from their earlier copies" + replaces + files),
|
||||
"settings sync": wrap("Instruction files were re-read after settings were synced onto this machine; these differ from their earlier copies" + replaces + files),
|
||||
"no reason": wrap("These instruction files changed" + replaces + files),
|
||||
"with a removed file": wrap("Instruction files were re-read after the conversation was compacted; these differ from their earlier copies" + replaces + files + "\nInstructions no longer present: /tmp/p/old/CLAUDE.md"),
|
||||
}
|
||||
const adapted = (t) => t.replaceAll(GLOBAL, "(global instructions)")
|
||||
|
||||
async function loaded(status = 200, reply = '{"id":"ok"}', headers = {}) {
|
||||
const seen = []
|
||||
globalThis.fetch = async (url, init) => {
|
||||
seen.push({ url: String(url), ...init })
|
||||
return new Response(reply, { status, headers })
|
||||
}
|
||||
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 }
|
||||
}
|
||||
|
||||
for (const [name, reminder] of Object.entries(WRAPPERS)) {
|
||||
test(`renames the global CLAUDE.md in the ${name} instructions reminder`, async () => {
|
||||
const { l, seen } = await loaded()
|
||||
const pasted = "Why does Claude Code write " + GLOBAL + "?"
|
||||
// Messages: text blocks, and a string user turn
|
||||
await l.fetch(messages, { method: "POST", body: JSON.stringify({ system: droid, messages: [{ role: "user", content: [{ type: "text", text: reminder }, { type: "text", text: pasted }] }, { role: "assistant", content: "ok" }, { role: "user", content: reminder }] }) })
|
||||
const sent = JSON.parse(seen.at(-1).body).messages
|
||||
expect(sent[0].content[0].text).toBe(adapted(reminder))
|
||||
expect(sent[0].content[0].text).not.toContain(GLOBAL)
|
||||
expect(sent[0].content[1].text).toBe(pasted)
|
||||
expect(sent[2].content).toBe(adapted(reminder))
|
||||
// chat completions: magpie joins a turn's text blocks into one string
|
||||
await l.fetch(chat, { method: "POST", body: JSON.stringify({ model: "glm-5", messages: [{ role: "system", content: droid }, { role: "user", content: reminder + pasted }] }) })
|
||||
expect(JSON.parse(seen.at(-1).body).messages[1].content).toBe(adapted(reminder) + pasted)
|
||||
})
|
||||
}
|
||||
|
||||
test("leaves text that only resembles the changed instructions reminder", async () => {
|
||||
const { l, seen } = await loaded()
|
||||
const near = [
|
||||
wrap("These instruction files changed and " + GLOBAL),
|
||||
"Quoted:\n" + WRAPPERS.compaction,
|
||||
wrap("Instruction files were re-read after the conversation was compacted; these differ from their earlier copies" + replaces + "Use " + GLOBAL),
|
||||
]
|
||||
for (const text of near) {
|
||||
const body = JSON.stringify({ system: droid, messages: [{ role: "user", content: [{ type: "text", text }] }] })
|
||||
await l.fetch(messages, { method: "POST", body })
|
||||
expect(seen.at(-1).body).toBe(body)
|
||||
}
|
||||
})
|
||||
|
||||
test("losslessly quotes the instructions template when a tool result shows it", async () => {
|
||||
const { l, seen } = await loaded()
|
||||
// what reading Claude Code's renderer source puts in the history
|
||||
const source = 'case"User":return" ' + GLOBAL + '"}}\ns=e.reason?`Instruction files were re-read ${Qj(e.reason)}; these differ from their earlier copies`:"These instruction files changed"\n' + WRAPPERS.compaction
|
||||
const request = { system: droid, messages: [{ role: "assistant", content: [{ type: "tool_use", id: "t1", name: "Bash", input: { command: "grep" } }] }, { role: "user", content: [{ type: "tool_result", tool_use_id: "t1", content: source }, { type: "tool_result", tool_use_id: "t2", content: [{ type: "text", text: source }] }] }] }
|
||||
await l.fetch(messages, { method: "POST", body: JSON.stringify(request) })
|
||||
const sent = JSON.parse(seen.at(-1).body).messages[1].content
|
||||
for (const encoded of [sent[0].content, sent[1].content[0].text]) {
|
||||
expect(encoded).toStartWith("Tool output encoded as a JSON string.")
|
||||
expect(encoded).not.toContain(GLOBAL)
|
||||
expect(JSON.parse(encoded.slice(encoded.indexOf("\n") + 1))).toBe(source)
|
||||
}
|
||||
// the same on chat completions' tool messages
|
||||
await l.fetch(chat, { method: "POST", body: JSON.stringify({ model: "glm-5", messages: [{ role: "system", content: droid }, { role: "tool", tool_call_id: "t1", content: source }] }) })
|
||||
const tool = JSON.parse(seen.at(-1).body).messages[1].content
|
||||
expect(tool).not.toContain(GLOBAL)
|
||||
expect(JSON.parse(tool.slice(tool.indexOf("\n") + 1))).toBe(source)
|
||||
})
|
||||
|
||||
test("a 403 keeps Factory's request id and error code", async () => {
|
||||
const { l } = await loaded(403, JSON.stringify({ error: { message: "Forbidden", code: "client_rejected", type: "forbidden" } }), { "x-request-id": "req_abc123", "cf-ray": "8f00-SJC" })
|
||||
const res = await l.fetch(messages, { method: "POST", body: JSON.stringify({ messages: [{ role: "user", content: "OK" }] }) })
|
||||
expect(res.status).toBe(403)
|
||||
expect(res.headers.get("x-request-id")).toBe("req_abc123")
|
||||
const body = await res.json()
|
||||
expect(body.request_id).toBe("req_abc123")
|
||||
expect(body.error.type).toBe("permission_error")
|
||||
expect(body.error.message).toStartWith("Forbidden (upstream request id req_abc123, code client_rejected, type forbidden) — Factory refused")
|
||||
|
||||
// a plain-text 403 with only a ray id says that, on the OpenAI route too
|
||||
const plain = await loaded(403, "Forbidden", { "cf-ray": "8f00-SJC" })
|
||||
const res2 = await plain.l.fetch(chat, { method: "POST", body: JSON.stringify({ model: "glm-5", messages: [{ role: "user", content: "OK" }] }) })
|
||||
const msg = (await res2.json()).error.message
|
||||
expect(msg).toStartWith("403 Forbidden: Forbidden (upstream request id 8f00-SJC) — Factory refused")
|
||||
|
||||
// nothing to tell: the message is as before
|
||||
const bare = await loaded(403, "Forbidden")
|
||||
const res3 = await bare.l.fetch(messages, { method: "POST", body: JSON.stringify({ messages: [{ role: "user", content: "OK" }] }) })
|
||||
const b3 = await res3.json()
|
||||
expect(b3.request_id).toBeUndefined()
|
||||
expect(b3.error.message).toStartWith("403 Forbidden: Forbidden — Factory refused")
|
||||
})
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@magpie-community/opencode-factory-auth",
|
||||
"version": "0.1.33",
|
||||
"version": "0.1.34",
|
||||
"description": "Sign in to a Factory (Droid) subscription from OpenCode or magpie",
|
||||
"type": "module",
|
||||
"main": "./index.mjs",
|
||||
|
||||
Reference in New Issue
Block a user