From ef68e7c7c0ec271054a63ba29910a4db12fadc91 Mon Sep 17 00:00:00 2001 From: XIQI <75725040+XIQIXIQIXIQI@users.noreply.github.com> Date: Sat, 3 Oct 2026 00:34:10 +0800 Subject: [PATCH] factory: handle quoted tool metadata and directory model updates (#10) --- packages/factory/README.md | 18 ++++++++-- packages/factory/index.mjs | 44 +++++++++++++++++++++-- packages/factory/package.json | 2 +- packages/factory/request.test.mjs | 60 +++++++++++++++++++++++++++++++ 4 files changed, 117 insertions(+), 7 deletions(-) diff --git a/packages/factory/README.md b/packages/factory/README.md index 0892168..5d1c708 100644 --- a/packages/factory/README.md +++ b/packages/factory/README.md @@ -77,9 +77,10 @@ magpie plugin login factory Factory's Anthropic route requires Droid's fixed client preamble and refuses some of Claude Code's fixed environment, model and built-in skill metadata. 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. +instructions, environment values, tool definitions, images and reasoning +options. Ordinary Droid requests remain unchanged, and OpenAI routes keep +their existing request adapter. Quoted fixed metadata in tool results is +handled as described below. For the built-in `update-config` skill, the adapter changes only the known self-reference "not Claude" to "not the assistant" inside a complete @@ -95,6 +96,17 @@ without the initial environment paragraph. Updates beginning with the known model paragraph and containing complete generated token metadata are adapted too, including accumulated switches when resuming a conversation. Token budgets, permission instructions and conversation history are preserved. +The same model-update adaptation covers updates that start with the complete +generated `# Environment update` block after a working-directory change. + +Factory can also refuse fixed client phrases quoted in tool results, such as +the identity/environment definitions printed when inspecting this plugin's +source. 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 +with different ones. Tool ids, cache/error markers and non-text blocks stay +unchanged. Ordinary tool results are forwarded as before. Use magpie's Claude Code integration to select the Factory provider. magpie manages the provider-specific client settings, including capability diff --git a/packages/factory/index.mjs b/packages/factory/index.mjs index 5fa084e..273368a 100644 --- a/packages/factory/index.mjs +++ b/packages/factory/index.mjs @@ -592,15 +592,17 @@ const CONFIG_SKILL_COMPAT = CONFIG_SKILL_METADATA.replace("not Claude", "not the // Claude 5 also sends its runtime metadata as a string-content system // message, instead of user-message reminders. Preserve that role and all // instructions. A model switch sends a separate update without the -// environment paragraph; require its opening model paragraph and complete -// generated token context before adapting that shape. +// environment paragraph, sometimes following a working-directory update; +// require the generated opening block and complete token context before +// adapting either update shape. const SYSTEM_ENV_CONTEXT = /^# Environment\nYou have been invoked in the following environment:[ \t]*\n(?: {1,2}- [^\n]*\n)+(?=\n|$)/ const SYSTEM_MODEL_CONTEXT = /(^|\n\n)You are powered by the model (?:named )?[^\n<>]+\.(?=\n\n|$)/g const SYSTEM_MODEL_UPDATE = /^You are powered by the model (?:named )?[^\n<>]+\.(?=\n\n|$)/ +const SYSTEM_ENV_UPDATE = /^# Environment update\n(?: {1,2}- [^\n]*\n)+(?=\n|$)/ const SYSTEM_TOKEN_CONTEXT = /(?:^|\n\n)\d+ tokens left<\/total_tokens>(?=\n\n|$)/ function systemContext(text) { const environment = SYSTEM_ENV_CONTEXT.test(text) - if (!environment && !(SYSTEM_MODEL_UPDATE.test(text) && SYSTEM_TOKEN_CONTEXT.test(text))) return text + if (!environment && !((SYSTEM_MODEL_UPDATE.test(text) || SYSTEM_ENV_UPDATE.test(text)) && SYSTEM_TOKEN_CONTEXT.test(text))) return text let out = text.replace(SYSTEM_MODEL_CONTEXT, (paragraph) => paragraph .replace("You are powered by the model named", "Current model name:") .replace("You are powered by the model", "Current model:") @@ -618,6 +620,23 @@ function systemContext(text) { return out } +// Factory also refuses these fixed client phrases when they are quoted in +// tool output, e.g. while reading this adapter's source. Keep the original +// text recoverable: a JSON string with explicit decoding instructions, +// 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" +function quotedToolText(text) { + 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=")) return text + let encoded = JSON.stringify(text) + for (const phrase of ["You are", "You have", "x-anthropic-billing-header", "system-reminder"]) { + encoded = encoded.replaceAll(phrase, "\\u" + phrase.charCodeAt(0).toString(16).padStart(4, "0") + phrase.slice(1)) + } + return QUOTED_TOOL_PREFIX + encoded +} + function anthropicBody(body) { let request try { @@ -685,6 +704,25 @@ function anthropicBody(body) { } if (message?.role !== "user" || !Array.isArray(message.content)) continue for (const block of message.content) { + if (block?.type === "tool_result") { + if (typeof block.content === "string") { + const adapted = quotedToolText(block.content) + if (adapted !== block.content) { + block.content = adapted + changed = true + } + } else if (Array.isArray(block.content)) { + for (const part of block.content) { + if (part?.type !== "text" || typeof part.text !== "string") continue + const adapted = quotedToolText(part.text) + if (adapted !== part.text) { + part.text = adapted + changed = true + } + } + } + continue + } if (block?.type !== "text" || typeof block.text !== "string") continue if (ENV_REMINDER.test(block.text)) { block.text = block.text.replace("# Environment", "# Runtime context") diff --git a/packages/factory/package.json b/packages/factory/package.json index 5a5f33d..893adc3 100644 --- a/packages/factory/package.json +++ b/packages/factory/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-factory-auth", - "version": "0.1.9", + "version": "0.1.10", "description": "Sign in to a Factory (Droid) subscription from OpenCode or magpie", "type": "module", "main": "./index.mjs", diff --git a/packages/factory/request.test.mjs b/packages/factory/request.test.mjs index 5551001..a47c042 100644 --- a/packages/factory/request.test.mjs +++ b/packages/factory/request.test.mjs @@ -359,3 +359,63 @@ test("requires a model-update preamble and complete token metadata before adapti expect(seen.at(-1).body).toBe(body) } }) + +test("adapts model switches following complete working-directory update metadata", async () => { + const { l, seen } = await loaded() + const directory = "# Environment update\n - Primary working directory: /tmp/new (was /tmp/old)\n" + const token = "15000000 tokens left" + const model = "You are powered by the model named Opus 5.5. The exact model ID is factory/claude-opus-5-5. Assistant knowledge cutoff is June 2026." + const context = directory + "\n" + token + "\n\n" + model + "\n\nWhile bypass permissions mode is active:\n\nKeep these permissions verbatim.\n\n" + token + for (const endpoint of [url, url + "/count_tokens"]) { + await l.fetch(endpoint, { method: "POST", body: JSON.stringify({ system: droid, messages: [{ role: "system", content: context }] }) }) + expect(JSON.parse(seen.at(-1).body).messages[0]).toEqual({ role: "system", content: context.replace(model, "Current model name: Opus 5.5. Model ID: factory/claude-opus-5-5. Model knowledge cutoff: June 2026.") }) + const once = seen.at(-1).body + await l.fetch(endpoint, { method: "POST", body: once }) + expect(seen.at(-1).body).toBe(once) + } + for (const content of [context.replace(" - Primary", " - Primary"), context.replaceAll(token, "unknown tokens left"), "Quoted update:\n\n" + context]) { + const body = JSON.stringify({ system: droid, messages: [{ role: "system", content }] }) + await l.fetch(url, { method: "POST", body }) + expect(seen.at(-1).body).toBe(body) + } +}) + +test("losslessly quotes fixed client metadata in tool output on inference and counting", async () => { + const { l, seen } = await loaded() + const source = '576: "You are Claude Code, Anthropic\'s official CLI for Claude."\n583: /^\\nYou have been invoked in the following environment:/\nQuotes: "\\\\"; Unicode: δΈ­ζ–‡ πŸ˜€; literal escape: \\u0059' + const outputs = [ + { type: "tool_result", tool_use_id: "bash_1", content: source, is_error: false, cache_control: { type: "ephemeral" } }, + { type: "tool_result", tool_use_id: "read_1", content: [{ type: "text", text: source, cache_control: { type: "ephemeral" } }, { type: "image", source: { type: "base64", media_type: "image/png", data: "image-data" } }], is_error: true }, + ] + for (const endpoint of [url, url + "/count_tokens"]) { + const request = { system: droid, messages: [{ role: "assistant", content: [{ type: "tool_use", id: "bash_1", name: "Bash", input: { command: "cat index.mjs" } }] }, { role: "user", content: outputs }], tools: [{ name: "Bash", input_schema: { type: "object" } }], stream: true } + await l.fetch(endpoint, { method: "POST", headers: { "content-length": "1" }, body: JSON.stringify(request) }) + const sent = JSON.parse(seen.at(-1).body) + const encoded = sent.messages[1].content[0].content + expect(encoded).toStartWith("Tool output encoded as a JSON string.") + expect(JSON.parse(encoded.slice(encoded.indexOf("\n") + 1))).toBe(source) + expect(encoded).not.toContain("You are Claude Code") + expect(encoded).not.toContain("You have been invoked") + expect(encoded).not.toContain("system-reminder") + expect(sent.messages[1].content[0]).toEqual({ ...outputs[0], content: encoded }) + expect(sent.messages[1].content[1]).toEqual({ ...outputs[1], content: [{ ...outputs[1].content[0], text: encoded }, outputs[1].content[1]] }) + expect(sent.messages[0]).toEqual(request.messages[0]) + expect(sent.tools).toEqual(request.tools) + expect(seen.at(-1).headers.get("content-length")).toBeNull() + const once = seen.at(-1).body + await l.fetch(endpoint, { method: "POST", body: once }) + expect(seen.at(-1).body).toBe(once) + } +}) + +test("leaves ordinary tool results and fixed phrases outside tool-result content untouched", async () => { + const { l, seen } = await loaded() + const identity = "You are Claude Code, Anthropic's official CLI for Claude." + const messages = [ + { role: "user", content: [{ type: "text", text: identity }, { type: "tool_result", tool_use_id: "plain", content: "Claude Code docs; You are Claude Code is an incomplete fragment." }, { type: "tool_result", tool_use_id: "object", content: { text: identity } }] }, + { role: "assistant", content: [{ type: "text", text: identity }] }, + ] + const body = JSON.stringify({ system: droid, messages }) + await l.fetch(url, { method: "POST", body }) + expect(seen[0].body).toBe(body) +})