diff --git a/packages/output-strategy/.gitignore b/packages/output-strategy/.gitignore index a107174..406e2da 100644 --- a/packages/output-strategy/.gitignore +++ b/packages/output-strategy/.gitignore @@ -1,5 +1,4 @@ node_modules/ -page/stats.js *.tmp *.bak .DS_Store diff --git a/packages/output-strategy/PROVENANCE.json b/packages/output-strategy/PROVENANCE.json index 2f9ea19..7fba1f5 100644 --- a/packages/output-strategy/PROVENANCE.json +++ b/packages/output-strategy/PROVENANCE.json @@ -56,6 +56,12 @@ "revision": "v3.8.52", "license": "MIT" }, + "ANTISLOP_BOUNDARIES": { + "repository": "https://github.com/diegosouzapw/OmniRoute", + "path": "open-sse/services/compression/outputStyles/antislop.ts", + "revision": "v3.8.52", + "license": "MIT" + }, "apply-design": { "repository": "https://github.com/diegosouzapw/OmniRoute", "path": "open-sse/services/compression/outputStyles/apply.ts", diff --git a/packages/output-strategy/README.md b/packages/output-strategy/README.md index 0a9fe43..8573074 100644 --- a/packages/output-strategy/README.md +++ b/packages/output-strategy/README.md @@ -38,7 +38,7 @@ No options, an empty options object, or all styles off leaves a request unchange - **Anthropic and Chat Completions:** append one static style block to the existing system prompt, or create the protocol-appropriate system field when none exists. - **Responses:** leave `instructions` completely untouched, including Codex's identity and base instructions. Add the style block as a separate `developer` input item. -- **An existing `[Output Strategy]` marker:** the body is already considered injected and is left unchanged; old blocks are never stripped or replaced. +- **An existing `[Output Strategy]` marker:** the body is already considered injected and is left unchanged; old blocks are never stripped or replaced. If an agent replays that marker in its history, the saved style remains part of that conversation; turning a style off does not rewrite history. Start a new conversation to begin without the old style block. - **Cache stability:** a selected style injects consistently across turns. The former `autoClarity` and media-history bypasses are removed because they made the cached system prefix appear and disappear. - **Unknown or unsupported shapes:** pass through unchanged. Middleware errors fail open. diff --git a/packages/output-strategy/apply.js b/packages/output-strategy/apply.js index 81f5fec..f5dbb9f 100644 --- a/packages/output-strategy/apply.js +++ b/packages/output-strategy/apply.js @@ -6,20 +6,6 @@ import { export const OUTPUT_STYLE_MARKER = "[Output Strategy]" -const MEDIA_PART_TYPES = new Set([ - "image", - "document", - "image_url", - "input_audio", - "audio_url", - "file", - "input_image", - "input_file", -]) -const MEDIA_PART_KEYS = ["inlineData", "inline_data", "fileData", "file_data"] -const NESTED_PART_KEYS = ["content", "output", "parts"] -const MAX_DEPTH = 4 - function isRecord(value) { return typeof value === "object" && value !== null && !Array.isArray(value) } @@ -49,47 +35,19 @@ export function buildOutputStylesInstruction(selection) { return `${OUTPUT_STYLE_MARKER}\n${instructions.join("\n\n")}\n\n${boundaries.join("\n")}` } -function nodeHasMedia(node, depth) { - if (!isRecord(node) || depth > MAX_DEPTH) return false - if (typeof node.type === "string" && MEDIA_PART_TYPES.has(node.type)) return true - for (const key of MEDIA_PART_KEYS) { - if (isRecord(node[key])) return true - } - for (const key of NESTED_PART_KEYS) { - const nested = node[key] - if (Array.isArray(nested) && nested.some((child) => nodeHasMedia(child, depth + 1))) { - return true - } - } - return false -} - -export function hasMediaBlocks(body) { - if (!isRecord(body)) return false - for (const key of ["messages", "input", "contents"]) { - const items = body[key] - if (Array.isArray(items) && items.some((item) => nodeHasMedia(item, 0))) return true - } - return false -} - function contentIncludesMarker(content) { if (typeof content === "string") return content.includes(OUTPUT_STYLE_MARKER) if (!Array.isArray(content)) return false return content.some((block) => isRecord(block) && contentIncludesMarker(typeof block.text === "string" ? block.text : block.content)) } -function systemFieldIncludesMarker(system) { - return contentIncludesMarker(system) -} - // Scan every place injection can land, regardless of which request shape the // body currently takes, so a body re-shaped between pipeline stages is never // injected twice. User-authored text is deliberately not scanned: a user // quoting the marker must not disable injection. function bodyIncludesMarker(body) { if (contentIncludesMarker(body.instructions)) return true - if (systemFieldIncludesMarker(body.system)) return true + if (contentIncludesMarker(body.system)) return true if (Array.isArray(body.messages)) { if (body.messages.some((message) => isRecord(message) && (message.role === "system" || message.role === "developer") && contentIncludesMarker(message.content))) return true } @@ -100,7 +58,8 @@ function bodyIncludesMarker(body) { } function appendInstruction(existing, instruction) { - return `${existing.trimEnd()}\n\n${instruction}` + const trimmed = existing.trimEnd() + return trimmed ? `${trimmed}\n\n${instruction}` : instruction } function placeSystemInstruction(messages, system, instruction, protocol) { @@ -138,7 +97,7 @@ function placeSystemInstruction(messages, system, instruction, protocol) { function placeOrSkip(body, messages, instruction, protocol, resolved) { const placed = placeSystemInstruction(messages, body.system, instruction, protocol) if (!placed) return { body, applied: false, skippedReason: "unsupported_system_shape" } - return appliedResult({ ...body, ...placed }, resolved, instruction) + return appliedResult({ ...body, ...placed }, resolved) } function responsesInput(body, instruction) { @@ -146,22 +105,8 @@ function responsesInput(body, instruction) { return Array.isArray(body.input) ? [message, ...body.input] : [message, { role: "user", content: body.input }] } -function utf8Bytes(text) { - let bytes = 0 - for (let i = 0; i < text.length; i++) { - const code = text.charCodeAt(i) - if (code < 0x80) bytes += 1 - else if (code < 0x800) bytes += 2 - else if (code >= 0xd800 && code <= 0xdbff && i + 1 < text.length && text.charCodeAt(i + 1) >= 0xdc00 && text.charCodeAt(i + 1) <= 0xdfff) { - bytes += 4 - i++ - } else bytes += 3 - } - return bytes -} - -function appliedResult(body, appliedStyles, instruction) { - return { body, applied: true, appliedStyles, addedBytes: utf8Bytes(instruction) } +function appliedResult(body, appliedStyles) { + return { body, applied: true, appliedStyles } } export function applyOutputStyles(body, selection) { @@ -186,7 +131,7 @@ export function applyOutputStyles(body, selection) { if (typeof body.input !== "string" && !Array.isArray(body.input)) { return { body, applied: false, skippedReason: "no_messages" } } - return appliedResult({ ...body, input: responsesInput(body, instruction) }, resolved, instruction) + return appliedResult({ ...body, input: responsesInput(body, instruction) }, resolved) } if (!messages) return { body, applied: false, skippedReason: "no_messages" } diff --git a/packages/output-strategy/output-strategy.test.mjs b/packages/output-strategy/output-strategy.test.mjs index b0c4e74..2b8168d 100644 --- a/packages/output-strategy/output-strategy.test.mjs +++ b/packages/output-strategy/output-strategy.test.mjs @@ -1,9 +1,4 @@ import * as mod from "./output-strategy.middleware.js" +import { check } from "../../scripts/middleware.mjs" -// The community repository owns the shared harness. A standalone checkout -// keeps its behavioral tests in test/ and has no community-only test file. -const harness = new URL("../../scripts/middleware.mjs", import.meta.url) -if (await Bun.file(harness).exists()) { - const { check } = await import(harness.href) - check(import.meta.dir, mod) -} +check(import.meta.dir, mod) diff --git a/packages/output-strategy/package.json b/packages/output-strategy/package.json index ae231a9..164d563 100644 --- a/packages/output-strategy/package.json +++ b/packages/output-strategy/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/middleware-output-strategy", - "version": "0.2.0", + "version": "0.2.1", "description": "Composable output-style instructions injected before the model call, with a small selection panel", "type": "module", "license": "MIT", diff --git a/packages/output-strategy/page/app.js b/packages/output-strategy/page/app.js index aeac444..7a6248d 100644 --- a/packages/output-strategy/page/app.js +++ b/packages/output-strategy/page/app.js @@ -71,6 +71,10 @@ } function renderCatalog() { + var checked = Object.create(null) + catalog.forEach(function (style) { + if (inputs[style.id]) checked[style.id] = inputs[style.id].checked === true + }) clear(list) inputs = Object.create(null) renderCatalogState() @@ -88,6 +92,7 @@ input.type = "checkbox" input.id = "style-" + style.id input.name = style.id + input.checked = checked[style.id] === true input.setAttribute("data-style-id", style.id) input.addEventListener("change", function () { dirty = true diff --git a/packages/output-strategy/page/i18n.js b/packages/output-strategy/page/i18n.js index 5abf28b..5c0dbad 100644 --- a/packages/output-strategy/page/i18n.js +++ b/packages/output-strategy/page/i18n.js @@ -41,17 +41,36 @@ } function normalize(value) { - return String(value || "").toLowerCase().indexOf("zh") === 0 ? "zh" : "en" + var lower = String(value || "").toLowerCase() + return lower === "zh" || lower === "zh-cn" || lower === "zh-hans" ? "zh" : "en" + } + + function languageTag(value) { + var lower = String(value || "").toLowerCase() + if (lower === "zh-tw" || lower === "zh-hant") return "zh-TW" + return lang === "zh" ? "zh-CN" : "en" } var lang = "en" var listeners = [] + var sourceText = typeof WeakMap === "undefined" ? null : new WeakMap() + var translatedText = typeof WeakMap === "undefined" ? null : new WeakMap() function translate(root) { if (!root) return if (root.nodeType === 3) { - var text = root.nodeValue.trim() - if (lang === "zh" && ZH[text]) root.nodeValue = root.nodeValue.replace(text, ZH[text]) + if (sourceText && translatedText && root.nodeValue !== translatedText.get(root)) { + sourceText.delete(root) + } + var text = sourceText ? sourceText.get(root) : root.nodeValue + if (text === undefined) { + text = root.nodeValue + if (sourceText) sourceText.set(root, text) + } + var trimmed = text.trim() + var next = lang === "zh" && ZH[trimmed] ? text.replace(trimmed, ZH[trimmed]) : text + if (translatedText) translatedText.set(root, next) + root.nodeValue = next return } if (root.nodeType !== 1 || root.tagName === "SCRIPT" || root.tagName === "STYLE") return @@ -65,7 +84,8 @@ function applyTheme(theme) { lang = normalize(theme && theme.lang) if (typeof document !== "undefined" && document.documentElement) { - document.documentElement.lang = lang === "zh" ? "zh-CN" : "en" + document.documentElement.lang = languageTag(theme && theme.lang) + document.title = lang === "zh" ? "输出策略" : "Output Strategy" translate(document.body) } listeners.forEach(function (listener) { listener(lang) }) @@ -80,8 +100,8 @@ } var host = globalThis.magpie + applyTheme(host && host.theme) if (host) { - if (host.theme) applyTheme(host.theme) if (host.ready && typeof host.ready.then === "function") host.ready.then(applyTheme).catch(function () {}) if (typeof host.onTheme === "function") host.onTheme(applyTheme) } diff --git a/packages/output-strategy/page/style.css b/packages/output-strategy/page/style.css index 69a17c7..5584d93 100644 --- a/packages/output-strategy/page/style.css +++ b/packages/output-strategy/page/style.css @@ -30,34 +30,6 @@ button, label, input { -webkit-tap-highlight-color: transparent; } -.lang-row { - display: flex; - gap: 8px; -} - -.intro-side { - display: flex; - flex-direction: column; - align-items: flex-end; - gap: 8px; - flex: none; - margin-left: auto; -} - -.lang-toggle { - min-height: 0; - padding: 3px 14px; - border: 1px solid var(--line); - background: var(--surface); - color: var(--ink); - font-size: 12px; - font-weight: 500; -} - -.lang-toggle:hover:not(:disabled) { - background: var(--accent-soft); -} - .shell { width: min(100% - 48px, 780px); margin: 0 auto; @@ -112,12 +84,7 @@ h1 { line-height: 1.2; } -.workspace { - display: grid; - grid-template-columns: minmax(0, 1fr) 280px; - gap: 48px; - padding-top: 28px; -} +.styles-section { padding-top: 28px; } .section-heading { display: flex; @@ -255,78 +222,6 @@ button:disabled { cursor: not-allowed; } -.stats-section { - padding-left: 24px; - border-left: 1px solid var(--line); -} - -.stats-section .section-heading { - display: block; -} - -.stats-section .section-heading p { - margin-top: 4px; - text-align: left; -} - -.totals { - display: grid; - grid-template-columns: 1fr 1fr; - margin: 20px 0 27px; - border-top: 1px solid var(--line); - border-left: 1px solid var(--line); -} - -.totals div { - min-width: 0; - padding: 11px 12px; - border-right: 1px solid var(--line); - border-bottom: 1px solid var(--line); - background: var(--surface); -} - -.totals dt { - overflow-wrap: anywhere; - color: var(--muted); - font-size: 11px; -} - -.totals dd { - margin: 3px 0 0; - font-size: 20px; - font-variant-numeric: tabular-nums; - font-weight: 650; - line-height: 1.3; -} - -.stats-section h3 { - margin-bottom: 8px; - font-size: 13px; - font-weight: 650; -} - -.style-stats { - margin: 0; - padding: 0; - list-style: none; -} - -.style-stats li { - display: flex; - align-items: baseline; - justify-content: space-between; - gap: 16px; - padding: 7px 0; - border-bottom: 1px solid var(--line); - font-size: 12px; -} - -.style-stats output { - flex: none; - font-variant-numeric: tabular-nums; - font-weight: 650; -} - .empty-state { margin: 0; padding: 22px 0; @@ -351,24 +246,6 @@ button:disabled { width: min(100% - 32px, 600px); padding-top: 28px; } - - .workspace { - grid-template-columns: 1fr; - gap: 36px; - } - - .stats-section { - padding-top: 24px; - padding-left: 0; - border-top: 1px solid var(--line); - border-left: 0; - } - - .stats-section .section-heading { - display: flex; - } - - .stats-section .section-heading p { text-align: right; } } @media (max-width: 460px) { @@ -376,13 +253,9 @@ button:disabled { .lede { font-size: 13px; } .selection-count strong { font-size: 19px; } - .section-heading, - .stats-section .section-heading { - display: block; - } + .section-heading { display: block; } - .section-heading p, - .stats-section .section-heading p { + .section-heading p { margin-top: 4px; text-align: left; } diff --git a/packages/output-strategy/test/output-strategy.test.mjs b/packages/output-strategy/test/output-strategy.test.mjs index 34e8749..0f671cd 100644 --- a/packages/output-strategy/test/output-strategy.test.mjs +++ b/packages/output-strategy/test/output-strategy.test.mjs @@ -12,7 +12,6 @@ import { OUTPUT_STYLE_MARKER, applyOutputStyles, buildOutputStylesInstruction, - hasMediaBlocks, } from "../apply.js" import { onRequest } from "../output-strategy.middleware.js" @@ -274,6 +273,15 @@ describe("skip behavior", () => { } }) + test("empty and non-object system blocks do not create invalid marker containers", () => { + for (const system of [null, { type: "text", text: "Rules" }]) { + const result = applyOutputStyles({ ...chat(), system }, ["ponytail"]) + expect(result.body.system).toBe(system) + if (system) expect(result.applied).toBe(false) + else expect(result.body.messages[0].role).toBe("system") + } + }) + test("does not overwrite non-string Responses instructions", () => { const instructions = [{ type: "input_text", text: "Existing rules" }] const body = { input: [{ role: "user", content: "Fix it" }], instructions } @@ -292,6 +300,11 @@ describe("skip behavior", () => { expect(result.body.system).toBe(system) }) + test("does not introduce an empty system message or leading newlines", () => { + const result = applyOutputStyles({ messages: [{ role: "system", content: "" }, { role: "user", content: "Hi" }] }, ["ponytail"]) + expect(result.body.messages[0].content.startsWith(OUTPUT_STYLE_MARKER)).toBe(true) + }) + test("a marker in instructions leaves a chat-shaped body unchanged", () => { const body = { ...chat(), instructions: `Old rules\n\n${OUTPUT_STYLE_MARKER}\nmore` } const result = applyOutputStyles(body, ["terse-prose"]) @@ -299,7 +312,7 @@ describe("skip behavior", () => { expect(result.body).toBe(body) }) - test("media remains detectable but cannot turn injection off", () => { + test("media does not turn injection off", () => { for (const part of [ { type: "image_url", image_url: { url: "data:image/png;base64,AA==" } }, { type: "input_audio", input_audio: { data: "AA==", format: "wav" } }, @@ -312,7 +325,7 @@ describe("skip behavior", () => { } }) - test("skips Anthropic images, documents and images nested in tool results", () => { + test("Anthropic images, documents and tool results retain a stable style block", () => { for (const content of [ [{ type: "image", source: { type: "base64", data: "AA==" } }], [{ type: "document", source: { type: "base64", data: "AA==" } }], @@ -323,19 +336,16 @@ describe("skip behavior", () => { } }) - test("skips Responses input_image and input_file", () => { + test("Responses media keeps instructions untouched and adds the style separately", () => { for (const part of [{ type: "input_image", image_url: "data:image/png;base64,AA==" }, { type: "input_file", file_data: "AA==" }]) { const body = { input: [{ role: "user", content: [part] }] } expect(applyOutputStyles(body, ["terse-prose"]).applied).toBe(true) } }) - test("detects Gemini inlineData and fileData without treating Gemini as an injectable shape", () => { - for (const key of ["inlineData", "inline_data", "fileData", "file_data"]) { - const body = { contents: [{ parts: [{ [key]: { data: "AA==" } }] }] } - expect(hasMediaBlocks(body)).toBe(true) - expect(applyOutputStyles(body, ["terse-prose"]).skippedReason).toBe("no_messages") - } + test("an unsupported Gemini body passes through", () => { + const body = { contents: [{ parts: [{ text: "Hello" }] }] } + expect(applyOutputStyles(body, ["terse-prose"]).skippedReason).toBe("no_messages") }) test("text-only turns and tool schemas mentioning image still inject", () => { @@ -355,7 +365,7 @@ describe("prompt-cache stability and result metadata", () => { { type: "text", text: "Claude Code rules", cache_control: { type: "ephemeral" } }, { type: "text", text: "Environment", cache_control: { type: "ephemeral" } }, ] - const turns = ["Fix the bug", "Delete the obsolete file", "Explain the next step"] + const turns = ["Fix the bug", "Delete the obsolete file", "delete the temporary cache", "Explain the next step"] for (const text of turns) { const result = applyOutputStyles({ system: originalBlocks, ...chat(text) }, { styles: { ponytail: true } }) expect(result.applied).toBe(true) @@ -379,12 +389,11 @@ describe("prompt-cache stability and result metadata", () => { expect(withImage.body.system).toBe(first.body.system) }) - test("counts UTF-8 bytes rather than UTF-16 code units", () => { + test("returns only the styles actually applied", () => { const result = applyOutputStyles(chat(), { styles: { "terse-cjk": true } }) expect(result.applied).toBe(true) - const instruction = result.body.messages[0].content - expect(result.addedBytes).toBe(Buffer.byteLength(instruction, "utf8")) - expect(result.addedBytes).toBeGreaterThan(instruction.length) + expect(result.appliedStyles).toEqual(["terse-cjk"]) + expect(result.addedBytes).toBeUndefined() }) }) diff --git a/packages/output-strategy/test/page.test.mjs b/packages/output-strategy/test/page.test.mjs index b7c7842..9ca9346 100644 --- a/packages/output-strategy/test/page.test.mjs +++ b/packages/output-strategy/test/page.test.mjs @@ -11,6 +11,7 @@ const sampleCatalog = ids.map(id => ({ id, label: `Label ${id}`, description: `D class FakeElement { constructor(tagName, id = "") { this.tagName = tagName.toUpperCase() + this.nodeType = 1 this.id = id this.children = [] this.parentNode = null @@ -37,8 +38,8 @@ class FakeElement { } get firstChild() { return this.children[0] || null } get nextSibling() { - if (!this.parentNode) return null - return this.parentNode.children[this.parentNode.children.indexOf(this) + 1] || null + const siblings = this.parentNode ? this.parentNode.children : [] + return siblings[siblings.indexOf(this) + 1] || null } set textContent(value) { this._textContent = String(value) @@ -160,6 +161,52 @@ describe("host language", () => { expect(document.documentElement.lang).toBe("en") expect(document.nodes.saveButton.textContent).toBe("Save changes") expect(document.nodes.formMessage.textContent).toBe("Pick styles and save.") + setLang("zh-TW") + expect(document.documentElement.lang).toBe("zh-TW") + expect(document.nodes.saveButton.textContent).toBe("Save changes") + }) + + test("preserves unsaved choices when host language changes", async () => { + const { document, setLang } = await boot({ current: { styles: {} }, lang: "en" }) + const before = descendants(document.nodes.stylesList).filter(node => node.tagName === "INPUT") + before[0].checked = true + before[0].dispatch("change") + setLang("zh-CN") + setLang("en") + const after = descendants(document.nodes.stylesList).filter(node => node.tagName === "INPUT") + expect(after[0].checked).toBe(true) + expect(document.nodes.saveButton.disabled).toBe(false) + expect(document.nodes.formMessage.textContent).toBe("Unsaved changes.") + }) + + test("translates static English text to Chinese and back to its original text", () => { + const body = new FakeElement("body") + const text = { nodeType: 3, nodeValue: "Output Strategy", parentNode: body } + body.append(text) + const document = { documentElement: {}, body } + let repaint + const sandbox = { document, magpie: { theme: { lang: "zh" }, onTheme(callback) { repaint = callback } } } + vm.createContext(sandbox) + vm.runInContext(i18nSource, sandbox) + expect(text.nodeValue).toBe("输出策略") + repaint({ lang: "en" }) + expect(text.nodeValue).toBe("Output Strategy") + }) + + test("closes each responsive media block and increments the shipping version", () => { + const css = readFileSync(new URL("../page/style.css", import.meta.url), "utf8") + const opens = (css.match(/{/g) || []).length + const closes = (css.match(/}/g) || []).length + expect(closes).toBe(opens) + expect(css).toContain("padding-top: 28px;\n }\n}\n\n@media (max-width: 460px)") + expect(JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version).toBe("0.2.1") + }) + + test("falls back safely when host theme is missing", () => { + const sandbox = { document: { documentElement: {}, body: null }, magpie: { theme: null } } + vm.createContext(sandbox) + expect(() => vm.runInContext(i18nSource, sandbox)).not.toThrow() + expect(sandbox.document.documentElement.lang).toBe("en") }) test("ships English HTML and no private stats or local language switch", () => {