diff --git a/packages/factory/README.md b/packages/factory/README.md index c5baba6..0fadefd 100644 --- a/packages/factory/README.md +++ b/packages/factory/README.md @@ -209,8 +209,9 @@ incomplete and hook-owned forms are left alone. Factory can also refuse fixed client phrases quoted in tool results, such as the identity/environment definitions printed when inspecting this plugin's -source, or the compaction opening embedded in a historical session JSONL -record. Those text results are represented as JSON strings with explicit +source, the compaction opening embedded in a historical session JSONL +record, or pi's opening sentence in a model snapshot of its own system +prompt. Those text results are represented as JSON strings with explicit decoding instructions and Unicode escapes for the fixed phrases. Decoding the string recovers the exact original output, including quotes, backslashes and Unicode; the plugin does not delete the output or replace its identities diff --git a/packages/factory/client-phrases.json b/packages/factory/client-phrases.json new file mode 100644 index 0000000..187cd50 --- /dev/null +++ b/packages/factory/client-phrases.json @@ -0,0 +1,16 @@ +{ + "//": "Fixed client phrases Factory refuses in a request body. Each phrase's first character is a JSON \\uXXXX escape: the file is safe to read (a Droid session reading it does not 403), and JSON.parse yields the real phrase. anywhere: refused in any text (system, user, assistant, tool_use). toolOnly: refused in tool output; the prompt adapters keep them.", + "anywhere": [ + "\u0059ou are an expert coding assistant operating inside pi, a coding agent harness.", + "\u0054he conversation history before this point was compacted into the following summary:" + ], + "toolOnly": [ + "\u0059ou are Claude Code, Anthropic's official CLI for Claude.", + "\u0059ou are Claude Code, Anthropic's official CLI for Claude, running within the Claude Agent SDK.", + "\u0059ou are a Claude agent, built on Anthropic's Claude Agent SDK.", + "\u0059ou have been invoked in the following environment:", + "\u0078-anthropic-billing-header: cc_version=", + "\u0054his session is being continued from a previous conversation that ran out of context.", + "\u0028user's private global instructions for all projects)" + ] +} diff --git a/packages/factory/gemini.test.mjs b/packages/factory/gemini.test.mjs index 91b2780..4c5e85e 100644 --- a/packages/factory/gemini.test.mjs +++ b/packages/factory/gemini.test.mjs @@ -69,3 +69,22 @@ test("an EU org's Gemini request goes to Factory's EU region's generate route", expect(new URL(seen[0].url).pathname).toBe("/api/llm/g/v1/generate") expect(seen[0].url.startsWith("https://api.factory.ai/")).toBe(false) }) + +// Gemini's route has no tool-output adaptation of its own: every refused +// phrase in its parts is escaped before the request leaves. +test("Gemini tool output and system instruction escape every refused phrase", async () => { + const { l, seen } = await loaded() + const env = "You have been invoked in the following environment:" + const pi = "You are an expert coding assistant operating inside pi, a coding agent harness." + const body = { + contents: [{ role: "user", parts: [{ functionResponse: { name: "Read", response: { text: env + " / " + pi } } }] }], + systemInstruction: { role: "user", parts: [{ text: env }] }, + } + await l.fetch("https://api.factory.ai/api/llm/g/v1/models/gemini-4-argon:streamGenerateContent?alt=sse", { method: "POST", body: JSON.stringify(body) }) + const sent = JSON.parse(seen[0].body) + const part = sent.contents[0].parts[0].functionResponse.response.text + expect(part).toBe("\\u0059ou have been invoked in the following environment: / \\u0059ou are an expert coding assistant operating inside pi, a coding agent harness.") + expect(sent.systemInstruction.parts[0].text).toContain("\\u0059ou have been invoked") + expect(JSON.stringify(sent)).not.toContain(env) + expect(JSON.stringify(sent)).not.toContain(pi) +}) diff --git a/packages/factory/index.mjs b/packages/factory/index.mjs index 5cc44bc..cdd2da4 100644 --- a/packages/factory/index.mjs +++ b/packages/factory/index.mjs @@ -4,6 +4,7 @@ // built-in Factory account (internal/provider/factory*.go). import { STATUS_CODES } from "node:http" +import { readFileSync } from "node:fs" import { parseToolJSON, wrapAnthropicTools, unwrapAnthropicTools } from "./anthropic-tools.mjs" const PROVIDER = "factory" @@ -481,6 +482,48 @@ function piSummary(text) { return text } +// Factory refuses pi's opening and its compaction opening wherever they +// appear, not only as the system prompt or the whole summary: a tool result +// that prints pi's system prompt, or a historical session record, carries +// them too, and every later turn of that conversation is 403. +// +// The list lives in client-phrases.json so the guard and the sanitizer read +// the same one. Its entries are written with a \uXXXX first character, so the +// file is safe to read from a Droid session; JSON.parse here yields the real +// phrase. "anywhere" is refused in any text (pi turns a compaction into one +// user text), "toolOnly" is refused in tool output while the prompt adapters +// keep them. +const FALLBACK_PHRASES = { + anywhere: [ + "You are an expert coding assistant operating inside pi, a coding agent harness.", + PI_SUMMARIES[0][0].split("\n\n")[0], + ], + toolOnly: [ + "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.", + "You have been invoked in the following environment:", + "x-anthropic-billing-header: cc_version=", + "This session is being continued from a previous conversation that ran out of context.", + "(user's private global instructions for all projects)", + ], +} +function loadClientPhrases() { + try { + const parsed = JSON.parse(readFileSync(new URL("./client-phrases.json", import.meta.url), "utf8")) + const anywhere = Array.isArray(parsed?.anywhere) ? parsed.anywhere.filter((p) => typeof p === "string" && p) : [] + const toolOnly = Array.isArray(parsed?.toolOnly) ? parsed.toolOnly.filter((p) => typeof p === "string" && p) : [] + // either group missing would silently drop protection, so use the + // built-in list instead + if (anywhere.length === 0 || toolOnly.length === 0) throw new Error("client-phrases.json needs both groups") + return { anywhere, toolOnly } + } catch { + return FALLBACK_PHRASES + } +} +const CLIENT_PHRASES = loadClientPhrases() +const PI_QUOTED_IN_TOOL = CLIENT_PHRASES.anywhere + // 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 @@ -632,6 +675,9 @@ function geminiBody(model, body) { si.parts = [{ text: joined.trim() === "" ? DROID_LINE : DROID_LINE + "\n" + joined }, ...rest] } m.systemInstruction = si + // Gemini's route has no tool-output adaptation: escape every refused + // phrase in its parts (functionResponse, systemInstruction) here. + escapeDeep(m, REFUSED_PHRASES) return JSON.stringify(m) } @@ -1332,19 +1378,89 @@ function changedFileContext(text) { // rather than deleting or rewriting the file's contents. Other output and // the tool's id, error/cache markers and non-text blocks stay untouched. const QUOTED_TOOL_PREFIX = "Tool output encoded as a JSON string. Decode the JSON string to recover the exact original text before using it:\n" +// the phrases Factory refuses wherever they appear +const REFUSED_PHRASES = [ + ...CLIENT_PHRASES.anywhere, + ...CLIENT_PHRASES.toolOnly, +] +// The substrings whose first character is escaped in tool output: every +// refused phrase from the list, plus the shorter prefixes the old loop +// escaped and the reminder marker. Longest first, so a full sentence is +// escaped before its own prefix (escaping the prefix first would hide it). +const ESCAPE_IN_TOOL = [...new Set([...REFUSED_PHRASES, COMPACT_OPENING, GLOBAL_INSTRUCTIONS, "system-reminder", "You have", "You are", "x-anthropic-billing-header"])] + .sort((a, b) => b.length - a.length) 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) && - !text.includes(GLOBAL_INSTRUCTIONS)) return text + if (!REFUSED_PHRASES.some((phrase) => text.includes(phrase))) return text let encoded = JSON.stringify(text) - for (const phrase of ["You are", "You have", "x-anthropic-billing-header", "system-reminder", COMPACT_OPENING, GLOBAL_INSTRUCTIONS]) { + for (const phrase of ESCAPE_IN_TOOL) { encoded = encoded.replaceAll(phrase, "\\u" + phrase.charCodeAt(0).toString(16).padStart(4, "0") + phrase.slice(1)) } return prefix + encoded } +// Factory refuses these phrases anywhere in the body, not only in tool +// output: pi turns a compaction into one user text, and an assistant +// message or a tool_use argument can quote a file too. escapePhrases +// rewrites the first character of each phrase as \uXXXX without wrapping the +// text, so a poisoned conversation can still be compacted or replayed. +// Tool output keeps the JSON-wrapped, lossless form above. +function escapePhrases(text, phrases = PI_QUOTED_IN_TOOL) { + let out = text + // By default only the phrases proven to be refused outside tool output + // (pi's opening and its compaction opening): escaping generated reminders + // such as GLOBAL_INSTRUCTIONS or Claude Code's environment line would + // rewrite text the adapters deliberately keep. Gemini's route passes the + // full list, because its tool output has no quotedToolText of its own. + for (const phrase of phrases) { + if (out.includes(phrase)) out = out.replaceAll(phrase, "\\u" + phrase.charCodeAt(0).toString(16).padStart(4, "0") + phrase.slice(1)) + } + return out +} + +// escapeDeep applies escapePhrases to every string in a JSON body, in place. +// true when something changed. Tool results are already escaped, so a +// second pass changes nothing. +function escapeDeep(value, phrases = PI_QUOTED_IN_TOOL) { + if (typeof value === "string") return false // strings are replaced by their parent + if (Array.isArray(value)) { + let changed = false + for (let i = 0; i < value.length; i++) { + if (typeof value[i] === "string") { + const out = escapePhrases(value[i], phrases) + if (out !== value[i]) (value[i] = out), (changed = true) + } else if (escapeDeep(value[i], phrases)) changed = true + } + return changed + } + if (value && typeof value === "object") { + let changed = false + for (const key of Object.keys(value)) { + const v = value[key] + if (typeof v === "string") { + const out = escapePhrases(v, phrases) + if (out !== v) (value[key] = out), (changed = true) + } else if (escapeDeep(v, phrases)) changed = true + } + return changed + } + return false +} + +// sanitizeBody is the last pass before a request leaves: every string in the +// body gets escapePhrases. Handles Messages, Responses, chat and Gemini. +function sanitizeBody(body) { + const text = bodyText(body) + if (text == null) return body + let parsed + try { + parsed = JSON.parse(text) + } catch { + return body + } + if (!escapeDeep(parsed)) return body + return JSON.stringify(parsed) +} + // 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 @@ -1864,7 +1980,7 @@ export const FactoryAuthPlugin = async ({ client }) => { // another agent's request opens as droid's does (droidBody) const anthropic = path.includes("/llm/a/") && (path.endsWith("/messages") || path.endsWith("/messages/count_tokens")) const adapted = anthropic ? wrapAnthropicTools(anthropicBody(body)) : { body: droidBody(path, body), names: new Set() } - const out = adapted.body + const out = sanitizeBody(adapted.body) // the caller's length is of the body it sent, not of this one if (out !== init?.body) h.delete("content-length") const res = await fetch(url, { ...init, method: init?.method ?? (input instanceof Request ? input.method : "POST"), headers: h, body: out }) diff --git a/packages/factory/package.json b/packages/factory/package.json index afa1dd1..e70e498 100644 --- a/packages/factory/package.json +++ b/packages/factory/package.json @@ -1,10 +1,10 @@ { "name": "@magpie-community/opencode-factory-auth", - "version": "0.1.34", + "version": "0.1.35", "description": "Sign in to a Factory (Droid) subscription from OpenCode or magpie", "type": "module", "main": "./index.mjs", - "files": ["index.mjs", "anthropic-tools.mjs", "README.md"], + "files": ["index.mjs", "anthropic-tools.mjs", "client-phrases.json", "README.md"], "keywords": ["opencode", "opencode-plugin", "magpie", "factory", "droid"], "license": "MIT", "repository": { "type": "git", "url": "git+https://github.com/magpie-community/plugins.git", "directory": "packages/factory" } diff --git a/packages/factory/pi.test.mjs b/packages/factory/pi.test.mjs index f15a359..83cce00 100644 --- a/packages/factory/pi.test.mjs +++ b/packages/factory/pi.test.mjs @@ -16,6 +16,8 @@ const chat = API + "/api/llm/o/v1/chat/completions" const responses = API + "/api/llm/o/v1/responses" const messages = API + "/api/llm/a/v1/messages?beta=true" +const ESCAPED_OPENING = "\\u0059ou are an expert coding assistant operating inside pi, a coding agent harness." +const ESCAPED_COMPACTED = "\\u0054he conversation history before this point was compacted into the following summary:" const OPENING = "You are an expert coding assistant operating inside pi, a coding agent harness." const REST = " You help users by reading files, executing commands, editing code, and writing new files.\n\nAvailable tools:\n- read: Read file contents" const PI = OPENING + REST @@ -73,17 +75,42 @@ test("pi's opening sentence is adapted in Responses' instructions and input", as expect(b.instructions).toBe(DROID_LINE + "\n" + ADAPTED) }) -test("the sentence quoted by the user, or only part of it, goes on as it is", async () => { +test("pi's opening quoted in user, assistant or system text is escaped, a fragment kept", async () => { const send = await loaded() - const user = "Why does pi say: " + OPENING - let b = await send(chat, { model: "kimi-k3", messages: [{ role: "system", content: "Be brief." }, { role: "user", content: user }] }) - expect(b.messages[1]).toEqual({ role: "user", content: user }) - b = await send(messages, { model: "claude-opus-5-5", max_tokens: 100, system: [{ type: "text", text: "You are an expert coding assistant operating inside pi." }], messages: [{ role: "user", content: [{ type: "text", text: user }] }] }) - expect(b.system[1].text).toBe("You are an expert coding assistant operating inside pi.") - expect(b.messages[0].content[0].text).toBe(user) - // mid-line in a system prompt: not pi's opening - b = await send(messages, { model: "claude-opus-5-5", max_tokens: 100, system: [{ type: "text", text: "Quote: " + OPENING }], messages: [{ role: "user", content: [{ type: "text", text: "hi" }] }] }) - expect(b.system[1].text).toBe("Quote: " + OPENING) + const quoted = "Why does pi say: " + OPENING + const partial = "You are an expert coding assistant operating inside pi." + const b = await send(messages, { model: "claude-opus-5-5", max_tokens: 100, system: [{ type: "text", text: "Quote: " + OPENING }], messages: [ + { role: "user", content: [{ type: "text", text: quoted }] }, + { role: "assistant", content: [{ type: "text", text: quoted }] }, + { role: "user", content: [{ type: "text", text: partial }] }, + ] }) + // Factory refuses the sentence in user and assistant text too, so the last + // pass escapes it everywhere; only the complete sentence changes. + expect(b.system[1].text).toBe("Quote: " + ESCAPED_OPENING) + expect(b.messages[0].content[0].text).toBe("Why does pi say: " + ESCAPED_OPENING) + expect(b.messages[1].content[0].text).toBe("Why does pi say: " + ESCAPED_OPENING) + expect(b.messages[2].content[0].text).toBe(partial) +}) + +test("a compaction-shaped user text is escaped, so a poisoned conversation can still be summarized", async () => { + const send = await loaded() + const serialized = "Summarize this conversation:\n\n[Tool result]: " + OPENING + "\n[Assistant]: done\n" + const b = await send(messages, { model: "claude-opus-5-5", max_tokens: 100, messages: [{ role: "user", content: [{ type: "text", text: serialized }] }] }) + expect(b.messages[0].content[0].text).toBe(serialized.replace(OPENING, ESCAPED_OPENING)) + expect(b.messages[0].content[0].text).not.toContain(OPENING) + const c = await send(chat, { model: "deepseek-v4.1-flash", messages: [{ role: "user", content: serialized }] }) + expect(c.messages[1].content).toBe(serialized.replace(OPENING, ESCAPED_OPENING)) +}) + +test("a tool_use argument that quotes pi's opening is escaped too", async () => { + const send = await loaded() + const b = await send(messages, { model: "claude-opus-5-5", max_tokens: 100, messages: [ + { role: "user", content: "hi" }, + { role: "assistant", content: [{ type: "tool_use", id: "t1", name: "bash", input: { command: "echo " + OPENING } }] }, + { role: "user", content: [{ type: "tool_result", tool_use_id: "t1", content: "done" }] }, + ] }) + expect(b.messages[1].content[0].input.command).toBe("echo " + ESCAPED_OPENING) + expect(JSON.stringify(b)).not.toContain(OPENING) }) // yetone/magpie#1316: after pi compacted a session, every turn on @@ -123,19 +150,80 @@ test("pi's compaction summary opens without its fixed sentence on chat completio expect(b.input).toEqual([{ type: "message", role: "user", content: [{ type: "input_text", text: ADAPTED_COMPACTION }] }, { role: "user", content: "go on" }]) }) -test("the compaction sentence the user writes, or outside pi's whole summary, goes on as it is", async () => { +test("the compaction sentence is escaped wherever it appears, a fragment kept", async () => { const send = await loaded() for (const text of [ - "Why does pi write: " + COMPACTED, // quoted mid-text - COMPACTED + " What does that mean?", // the sentence alone, no summary - COMPACTED + "\n\n\n" + SUMMARY, // no closing tag: not pi's whole message + "Why does pi write: " + COMPACTED, + COMPACTED + " What does that mean?", + COMPACTED + "\n\n\n" + SUMMARY, ]) { + const escaped = text.replace(COMPACTED, ESCAPED_COMPACTED) const b = await send(messages, { model: "claude-opus-5-5", max_tokens: 100, messages: [{ role: "user", content: [{ type: "text", text }] }] }) - expect(b.messages[0].content[0].text).toBe(text) + expect(b.messages[0].content[0].text).toBe(escaped) const c = await send(chat, { model: "kimi-k3", messages: [{ role: "user", content: text }] }) - expect(c.messages[1]).toEqual({ role: "user", content: text }) + expect(c.messages[1].content).toBe(escaped) } - // an assistant repeating the summary is not pi's message + // an assistant repeating the summary is escaped the same way const b = await send(messages, { model: "claude-opus-5-5", max_tokens: 100, messages: [{ role: "user", content: "hi" }, { role: "assistant", content: [{ type: "text", text: PI_COMPACTION }] }, { role: "user", content: "ok" }] }) - expect(b.messages[1].content[0].text).toBe(PI_COMPACTION) + expect(b.messages[1].content[0].text).toBe(PI_COMPACTION.replace(COMPACTED, ESCAPED_COMPACTED)) + // a fragment is left alone + const fragment = "The conversation history before this point" + const c = await send(messages, { model: "claude-opus-5-5", max_tokens: 100, messages: [{ role: "user", content: fragment }] }) + expect(c.messages[0].content).toBe(fragment) +}) + +// A tool result that quotes pi's own system prompt, or a historical session +// record, carries the same fixed sentences Factory refuses in the prompt and +// in the whole summary. Epi's model snapshot (`scripts/model-snapshot.mjs`) +// prints the system prompt into a tool result, after which every turn of the +// conversation was 403 "Factory: Forbidden" on Messages and Responses alike. +const QUOTED_PREFIX = "Tool output encoded as a JSON string. Decode the JSON string to recover the exact original text before using it:\n" +const SNAPSHOT = '{\n "piVersion": "1.1.0",\n "systemPrompt": "' + OPENING + REST + '"\n}' +const RECORD = '{"role":"user","content":"' + PI_COMPACTION + '"}' + +test("pi's opening and compaction sentence in tool output are quoted, the record kept", async () => { + const send = await loaded() + const outputs = [ + { type: "tool_result", tool_use_id: "bash_1", content: SNAPSHOT, is_error: false, cache_control: { type: "ephemeral" } }, + { type: "tool_result", tool_use_id: "read_1", content: [{ type: "text", text: RECORD, cache_control: { type: "ephemeral" } }, { type: "image", source: { type: "base64", media_type: "image/png", data: "image-data" } }], is_error: true }, + ] + const b = await send(messages, { model: "claude-opus-5-5", max_tokens: 100, system: [{ type: "text", text: PI }], messages: [{ role: "assistant", content: [{ type: "tool_use", id: "bash_1", name: "Bash", input: { command: "node scripts/model-snapshot.mjs" } }] }, { role: "user", content: outputs }] }) + const first = b.messages[1].content[0] + expect(first.content).toStartWith(QUOTED_PREFIX) + expect(first).toEqual({ ...outputs[0], content: first.content }) + expect(JSON.parse(first.content.slice(QUOTED_PREFIX.length))).toBe(SNAPSHOT) + expect(first.content).not.toContain(OPENING) + const second = b.messages[1].content[1] + expect(second.content[0].text).toStartWith(QUOTED_PREFIX) + expect(JSON.parse(second.content[0].text.slice(QUOTED_PREFIX.length))).toBe(RECORD) + expect(second.content[0].text).not.toContain(COMPACTED) + expect(second).toEqual({ ...outputs[1], content: [{ ...outputs[1].content[0], text: second.content[0].text }, outputs[1].content[1]] }) +}) + +test("pi's opening in chat and Responses tool output is quoted too", async () => { + const send = await loaded() + let b = await send(chat, { model: "deepseek-v4.1-flash", messages: [{ role: "assistant", content: "called bash", tool_calls: [{ id: "c1", type: "function", function: { name: "bash", arguments: "{}" } }] }, { role: "tool", tool_call_id: "c1", content: SNAPSHOT }] }) + const quoted = b.messages[2].content + expect(quoted).toStartWith(QUOTED_PREFIX) + expect(JSON.parse(quoted.slice(QUOTED_PREFIX.length))).toBe(SNAPSHOT) + expect(quoted).not.toContain(OPENING) + b = await send(responses, { model: "gpt-6.1", instructions: PI, input: [{ type: "function_call", call_id: "c1", name: "bash", arguments: "{}" }, { type: "function_call_output", call_id: "c1", output: SNAPSHOT }] }) + const out = b.input[1].output + expect(out).toStartWith(QUOTED_PREFIX) + expect(JSON.parse(out.slice(QUOTED_PREFIX.length))).toBe(SNAPSHOT) + expect(out).not.toContain(OPENING) +}) + +test("pi's opening is escaped in user text, a fragment in tool output stays", async () => { + const send = await loaded() + const partial = "You are an expert coding assistant operating inside pi." + for (const text of ["Why does pi say: " + OPENING, ESCAPED_OPENING, partial]) { + const escaped = text.replace(OPENING, ESCAPED_OPENING) + const b = await send(messages, { model: "claude-opus-5-5", max_tokens: 100, messages: [{ role: "user", content: [{ type: "text", text }, { type: "tool_result", tool_use_id: "plain", content: partial }] }] }) + expect(b.messages[0].content[0].text).toBe(escaped) + expect(b.messages[0].content[1].content).toBe(partial) + const c = await send(chat, { model: "kimi-k3", messages: [{ role: "user", content: text }, { role: "tool", tool_call_id: "c1", content: partial }] }) + expect(c.messages[1].content).toBe(escaped) + expect(c.messages[2].content).toBe(partial) + } })