From b83e3dee368b0cda9c1f6e37e87eaeeb70a11606 Mon Sep 17 00:00:00 2001 From: William WANG <85057366+William-AIdev@users.noreply.github.com> Date: Thu, 29 Oct 2026 21:09:00 +0800 Subject: [PATCH] factory 0.1.41: ZCode's environment paragraph reaches Factory as runtime context, not refused (#211, William-AIdev) ZCode embeds its generated environment paragraph, with unindented bullets, inside a larger system prompt. No runtime-context adapter matched it, so "You have been invoked in the following environment:" and "You are powered by the model named" reached Factory unchanged in the system prompt (403). This renames a complete standalone paragraph in system prompts, later system messages and Gemini's system instruction, keeping every value. Also releases factory 0.1.41, which carries #213. Reviewed at d4ef7d4e; the maintainer commits on top (eb016a4d) merge main b76a577, keep main's Gemini escape test beside this one, expect main's #258 escape in the Gemini user part, add a fenced-paragraph case and bump to 0.1.41. - On main b76a577, a probe through _internal.droidBody still sends the paragraph unchanged on Responses and Messages; the PR's new tests fail there. - At eb016a4d: `bun test` in packages/factory (sandbox HOME, on mote): 189 pass, 0 fail. `bun scripts/check.mjs factory`: ok. - Broken by hand: zcodeRuntimeContext returning its input turns 5 tests red (Responses, Chat, Messages, Gemini, no-Shell). Dropping the insideFence check passed every original test (the fenced inputs never matched); the added fenced case goes red with it, green with it back. - Not tried: a live Factory account (the PR body records the 403 on all four routes). --- packages/factory/gemini.test.mjs | 14 ++++ packages/factory/index.mjs | 29 ++++++- packages/factory/package.json | 2 +- packages/factory/zcode-runtime.test.mjs | 103 ++++++++++++++++++++++++ 4 files changed, 144 insertions(+), 4 deletions(-) create mode 100644 packages/factory/zcode-runtime.test.mjs diff --git a/packages/factory/gemini.test.mjs b/packages/factory/gemini.test.mjs index 4c5e85e..8a5316d 100644 --- a/packages/factory/gemini.test.mjs +++ b/packages/factory/gemini.test.mjs @@ -88,3 +88,17 @@ test("Gemini tool output and system instruction escape every refused phrase", as expect(JSON.stringify(sent)).not.toContain(env) expect(JSON.stringify(sent)).not.toContain(pi) }) + +test("adapts ZCode generated Gemini system context while preserving values and user content", async () => { + const { l, seen } = await loaded() + const context = "# Environment\nYou have been invoked in the following environment:\n- Primary working directory: /tmp/project\n- Is a git repository: no\n- Platform: darwin\n- Shell: zsh\n- OS Version: darwin 27.0.0 arm64\n- You are powered by the model named test-model.\n" + const body = { systemInstruction: { parts: [{ text: context }] }, contents: [{ role: "user", parts: [{ text: context }] }] } + const url = "https://api.factory.ai/api/llm/g/v1/models/gemini-3-flash-preview:generateContent" + await l.fetch(url, { method: "POST", body: JSON.stringify(body) }) + const sent = JSON.parse(seen[0].body) + expect(sent.systemInstruction.parts[0].text).toBe(droid + "\n" + context.replace("# Environment", "# Runtime context").replace("You have been invoked in the following environment:", "The session environment is:").replace("- You are powered by the model named", "- Current model name:")) + // user parts are not adapted; the Gemini route escapes the refused phrase in them (#258) + expect(sent.contents).toEqual([{ role: "user", parts: [{ text: context.replace("You have been invoked", "\\u0059ou have been invoked") }] }]) + await l.fetch(url, { method: "POST", body: JSON.stringify(sent) }) + expect(JSON.parse(seen[1].body)).toEqual(sent) +}) diff --git a/packages/factory/index.mjs b/packages/factory/index.mjs index 405c126..3b257d3 100644 --- a/packages/factory/index.mjs +++ b/packages/factory/index.mjs @@ -682,7 +682,9 @@ function geminiBody(model, body) { if (typeof si === "string") si = { parts: [{ text: si }] } if (!si || typeof si !== "object") si = { parts: [] } delete si.role - const parts = Array.isArray(si.parts) ? si.parts : [] + const parts = Array.isArray(si.parts) ? si.parts.map((part) => + part && typeof part.text === "string" ? { ...part, text: zcodeRuntimeContext(part.text) } : part) : [] + si.parts = parts if (!(typeof parts[0]?.text === "string" && parts[0].text.startsWith(DROID_LINE))) { const texts = [] const rest = [] @@ -1540,14 +1542,35 @@ function claudeIdentity(text) { return identity ? DROID_LINE + text.slice(identity.length) : text } +// ZCode embeds its generated environment paragraph, with unindented bullets, +// in a larger system prompt. Factory refuses the fixed opening. Change only a +// complete standalone generated paragraph, keeping every value and leaving +// fenced, quoted or incomplete copies alone. Shell is optional: ZCode's own +// prompt builder omits it, while the desktop prompt includes it. +const ZCODE_ENV_CONTEXT = /(^|\n\n)(# Environment\nYou have been invoked in the following environment:\n(?:- Primary working directory: [^\n]+\n(?:- Is a git repository: (?:yes|no)\n)?)?- Platform: [^\n]+\n(?:- Shell: [^\n]+\n)?- OS Version: [^\n]+\n- You are powered by the model named [^\n]+\.)(?=\n(?:\n|$)|$)/g +function insideFence(text, end) { + let fenced = false + for (const line of text.slice(0, end).split("\n")) if (/^ {0,3}(?:```|~~~)/.test(line)) fenced = !fenced + return fenced +} +function zcodeRuntimeContext(text) { + return text.replace(ZCODE_ENV_CONTEXT, (block, lead, paragraph, offset) => { + if (insideFence(text, offset + lead.length)) return block + return lead + paragraph + .replace("# Environment", "# Runtime context") + .replace("You have been invoked in the following environment:", "The session environment is:") + .replace("- You are powered by the model named", "- Current model name:") + }) +} + // promptText adapts a system prompt's text. function promptText(text) { - return configSkillText(clientOpening(systemModelLine(claudeIdentity(text)))) + return configSkillText(clientOpening(systemModelLine(claudeIdentity(zcodeRuntimeContext(text))))) } // systemMessageText adapts a system message's text after the prompt. function systemMessageText(text) { - return bareSkills(clientOpening(systemContext(text))) + return bareSkills(clientOpening(systemContext(zcodeRuntimeContext(text)))) } // userBlockText adapts one text block of a user turn. diff --git a/packages/factory/package.json b/packages/factory/package.json index 1df550e..0a5b350 100644 --- a/packages/factory/package.json +++ b/packages/factory/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-factory-auth", - "version": "0.1.40", + "version": "0.1.41", "description": "Sign in to a Factory (Droid) subscription from OpenCode or magpie", "type": "module", "main": "./index.mjs", diff --git a/packages/factory/zcode-runtime.test.mjs b/packages/factory/zcode-runtime.test.mjs new file mode 100644 index 0000000..090dc7f --- /dev/null +++ b/packages/factory/zcode-runtime.test.mjs @@ -0,0 +1,103 @@ +import { afterEach, expect, test } from "bun:test" +import { FactoryAuthPlugin, _internal } from "./index.mjs" + +const real = globalThis.fetch +afterEach(() => (globalThis.fetch = real)) + +// ZCode embeds this paragraph, with unindented bullets, in a larger system +// prompt. Its values stay; only the three fixed client phrases change. +const env = "# Environment\nYou have been invoked in the following environment:\n- Primary working directory: /tmp/project\n- Is a git repository: no\n- Platform: darwin\n- Shell: zsh\n- OS Version: darwin 27.0.0 arm64\n- You are powered by the model named magpie/factory/kimi-k3.\n" +const adapted = "# Runtime context\nThe session environment is:\n- Primary working directory: /tmp/project\n- Is a git repository: no\n- Platform: darwin\n- Shell: zsh\n- OS Version: darwin 27.0.0 arm64\n- Current model name: magpie/factory/kimi-k3.\n" +const prefix = "Keep these instructions.\n\n" + +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 () => { throw new Error("credential writes disabled") } } } }) + return { l: await hooks.auth.loader(async () => auth), seen } +} + +test("Responses instructions: adapts a complete embedded paragraph and is idempotent", () => { + const path = "/api/llm/o/v1/responses" + const instructions = prefix + env + "\n# Context management\nKeep the context." + const body = JSON.stringify({ model: "gpt-6-luna", instructions, input: [{ role: "user", content: "OK" }] }) + const out = JSON.parse(_internal.droidBody(path, body)) + expect(out.instructions).toBe(_internal.DROID_LINE + "\n" + prefix + adapted + "\n# Context management\nKeep the context.") + expect(out.input).toEqual([{ role: "user", content: "OK" }]) + const once = JSON.stringify(out) + expect(_internal.droidBody(path, once)).toBe(once) +}) + +test("Chat: adapts the first system prompt and later system messages, leaving other roles alone", () => { + const path = "/api/llm/o/v1/chat/completions" + const later = "Later system.\n\n" + env + const messages = [ + { role: "system", content: prefix + env }, + { role: "system", content: later }, + { role: "user", content: "User quote:\n\n" + env }, + { role: "assistant", content: "Assistant quote:\n\n" + env }, + { role: "tool", content: "# Environment\n- Platform: darwin" }, + ] + const body = JSON.stringify({ model: "kimi-k3", messages, max_tokens: 32 }) + const out = JSON.parse(_internal.droidBody(path, body)) + expect(out.messages[0].content).toBe(_internal.DROID_LINE + "\n" + prefix + adapted) + expect(out.messages[1].content).toBe("Later system.\n\n" + adapted) + expect(out.messages.slice(2)).toEqual(messages.slice(2)) + const once = JSON.stringify(out) + expect(_internal.droidBody(path, once)).toBe(once) +}) + +test("Messages: adapts system blocks after the prompt and keeps user/assistant blocks and values", async () => { + const { l, seen } = await loaded() + const system = [ + { type: "text", text: prefix + env, cache_control: { type: "ephemeral" } }, + { type: "text", text: env, cache_control: { type: "ephemeral" } }, + ] + const messages = [ + { role: "user", content: [{ type: "text", text: "User quote:\n\n" + env }] }, + { role: "assistant", content: [{ type: "text", text: "Assistant quote:\n\n" + env }] }, + ] + const request = { model: "claude-sonnet-4-6", system, messages } + const url = "https://api.factory.ai/api/llm/a/v1/messages" + await l.fetch(url, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(request) }) + const sent = JSON.parse(seen[0].body) + expect(sent.system[0]).toEqual({ type: "text", text: _internal.DROID_LINE }) + expect(sent.system[1]).toEqual({ ...system[0], text: prefix + adapted }) + expect(sent.system[2]).toEqual({ ...system[1], text: adapted }) + expect(sent.messages).toEqual(messages) + const once = seen[0].body + await l.fetch(url, { method: "POST", headers: { "content-type": "application/json" }, body: once }) + expect(seen[1].body).toBe(once) +}) + +test("leaves fenced, quoted, incomplete, partly given and non-system copies alone", () => { + const path = "/api/llm/o/v1/responses" + const partly = env.replace("- Shell: zsh\n", "").replace("- OS Version: darwin 27.0.0 arm64\n", "") + const inputs = [ + "Reference:\n\n```\n\n" + env + "```", + "Reference:\n\n~~~\n\n" + env + "~~~", + // a complete paragraph, blank lines on both sides, inside a fence + "Reference:\n\n```\n\n" + env + "\n```", + "Reference:\n\n> " + env.replace(/\n/g, "\n> "), + prefix + env.replace("- You are powered by the model named magpie/factory/kimi-k3.\n", ""), + prefix + partly, + "Reference:\n" + env, + ] + for (const instructions of inputs) { + const body = JSON.stringify({ model: "gpt-6-luna", instructions, input: [{ role: "user", content: "OK" }] }) + const out = JSON.parse(_internal.droidBody(path, body)) + expect(out.instructions).toBe(_internal.DROID_LINE + "\n" + instructions) + } +}) + +test("supports the ZCode plugin's environment without a Shell line", () => { + const path = "/api/llm/o/v1/responses" + const withoutShell = env.replace("- Shell: zsh\n", "") + const expected = adapted.replace("- Shell: zsh\n", "") + const body = JSON.stringify({ model: "gpt-6-luna", instructions: prefix + withoutShell, input: [] }) + expect(JSON.parse(_internal.droidBody(path, body)).instructions).toBe(_internal.DROID_LINE + "\n" + prefix + expected) +})