diff --git a/README.md b/README.md index b55b26b..4fd8f64 100644 --- a/README.md +++ b/README.md @@ -57,6 +57,7 @@ These packages aren't OpenCode plugins. magpie runs them in its gateway, on the | [param-override](packages/param-override) | New API's 参数覆盖 (`param_override`): set, delete, move, copy or rewrite request fields, for some models or under conditions, or turn a request away | | [model-map](packages/model-map) | New API's 模型重定向 (`model_mapping`): send a model under another name, by name or `/pattern/`; replies name the model asked for | | [system-prompt](packages/system-prompt) | Your own system prompt on every request, or on some agents' or models', in each API's own place | +| [output-strategy](packages/output-strategy) | Seven composable output styles with a selection panel; off by default, cache-stable, and Codex `instructions` stay untouched | | [word-guard](packages/word-guard) | New API's 敏感词过滤: turn away or mask words and patterns in what users send, and in replies | | [think-tags](packages/think-tags) | Take a leading ``, `` or `` block out of a reply's text, or put a Chat reply's `reasoning_content` into it (`thinking_to_content`) | | [antigravity-cloak](packages/antigravity-cloak) | Claude Code and Claude Desktop on Antigravity: break the words Antigravity turns their system prompt away for, in what Antigravity alone is sent | diff --git a/packages/output-strategy/.gitignore b/packages/output-strategy/.gitignore new file mode 100644 index 0000000..a107174 --- /dev/null +++ b/packages/output-strategy/.gitignore @@ -0,0 +1,5 @@ +node_modules/ +page/stats.js +*.tmp +*.bak +.DS_Store diff --git a/packages/output-strategy/LICENSE b/packages/output-strategy/LICENSE new file mode 100644 index 0000000..cdad971 --- /dev/null +++ b/packages/output-strategy/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 output-strategy contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/packages/output-strategy/LICENSES/9router-MIT.txt b/packages/output-strategy/LICENSES/9router-MIT.txt new file mode 100644 index 0000000..9219235 --- /dev/null +++ b/packages/output-strategy/LICENSES/9router-MIT.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2024-2026 decolua and contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/packages/output-strategy/LICENSES/OmniRoute-MIT.txt b/packages/output-strategy/LICENSES/OmniRoute-MIT.txt new file mode 100644 index 0000000..b5c9f58 --- /dev/null +++ b/packages/output-strategy/LICENSES/OmniRoute-MIT.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 diegosouzapw + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/packages/output-strategy/LICENSES/caveman-Apache-2.0.txt b/packages/output-strategy/LICENSES/caveman-Apache-2.0.txt new file mode 100644 index 0000000..d645695 --- /dev/null +++ b/packages/output-strategy/LICENSES/caveman-Apache-2.0.txt @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/packages/output-strategy/LICENSES/caveman-MIT.txt b/packages/output-strategy/LICENSES/caveman-MIT.txt new file mode 100644 index 0000000..d8c0ee8 --- /dev/null +++ b/packages/output-strategy/LICENSES/caveman-MIT.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Julius Brussee + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/packages/output-strategy/LICENSES/caveman-NOTICE.txt b/packages/output-strategy/LICENSES/caveman-NOTICE.txt new file mode 100644 index 0000000..5b6c031 --- /dev/null +++ b/packages/output-strategy/LICENSES/caveman-NOTICE.txt @@ -0,0 +1,49 @@ +Caveman +Copyright 2026 Julius Brussee + +Before Caveman 3.0.0, the parts of this repository outside the Engine-linked +runtime were licensed under the MIT License (see LICENSING.md). Contributions +made to those parts before 3.0.0 were received under the MIT License and remain +available under it. Its copyright and permission notice is retained in +LICENSE-MIT. + +This product includes third-party software: + +- engine/pixel/ is a Go port of pxpipe (https://github.com/teamchong/pxpipe), + used under the MIT License. + Copyright (c) 2026 claude-image-proxy contributors + +- The glyph atlases embedded in engine/pixel/assets/ are rasterized from: + - Spleen 5x8, Copyright (c) 2018-2026, Frederic Cambus. + BSD 2-Clause License. + - GNU Unifont 16.0.04, dual-licensed under the SIL Open Font License 1.1 and + the GNU GPL version 2 (or later) with the GNU font-embedding exception. + +- browse/ links these MIT-licensed Go modules: + - github.com/chromedp/chromedp, Copyright (c) 2016-2025 Kenneth Shaw + - github.com/chromedp/cdproto, Copyright (c) 2016-2025 Kenneth Shaw + - github.com/chromedp/sysutil, Copyright (c) 2016-2017 Kenneth Shaw + +- The runtime binaries and the container image link third-party Go modules + under the MIT, BSD-3-Clause and Apache-2.0 licenses. Their license texts, and + the Go runtime's, ship with every binary release as + THIRD_PARTY_GO_LICENSES.tar.gz and in the image under /licenses/third_party/. + +- packages/cli/src/index.ts contains a port, with changes, of Qwen Code + 0.22.3's MCP server and permission-rule matchers and its tool-name + normalization (https://github.com/QwenLM/qwen-code), used under the Apache + License, Version 2.0. + Copyright 2025 Google LLC + Copyright 2025 Qwen + +- The @caveman-ai/cli package bundles MIT-licensed npm packages + (@clack/prompts, @clack/core, sisteransi, fast-string-width, + fast-string-truncated-width, fast-wrap-ansi); see packages/cli/NOTICE. + +- extension/fonts/ holds the Geist and Geist Mono fonts, + Copyright (c) 2023 Vercel, in collaboration with basement.studio, + under the SIL Open Font License 1.1. + +Full license texts: engine/pixel/NOTICE, engine/pixel/assets/SPLEEN_LICENSE.txt, +engine/pixel/assets/UNIFONT_LICENSE.txt, browse/NOTICE, packages/cli/NOTICE, and +extension/fonts/GEIST_LICENSE.txt. diff --git a/packages/output-strategy/LICENSES/i-have-adhd-MIT.txt b/packages/output-strategy/LICENSES/i-have-adhd-MIT.txt new file mode 100644 index 0000000..19db5f1 --- /dev/null +++ b/packages/output-strategy/LICENSES/i-have-adhd-MIT.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Ayoub Ghriss + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/packages/output-strategy/LICENSES/ponytail-MIT.txt b/packages/output-strategy/LICENSES/ponytail-MIT.txt new file mode 100644 index 0000000..715d483 --- /dev/null +++ b/packages/output-strategy/LICENSES/ponytail-MIT.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 DietrichGebert + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/packages/output-strategy/PROVENANCE.json b/packages/output-strategy/PROVENANCE.json new file mode 100644 index 0000000..2f9ea19 --- /dev/null +++ b/packages/output-strategy/PROVENANCE.json @@ -0,0 +1,81 @@ +{ + "plugin": "output-strategy", + "created": "2026-11-03", + "runtimeAdaptations": [ + "Only onRequest injection is implemented; no response or SSE rewriting.", + "Skill frontmatter, slash commands, host-specific mode queries and persistence commands are removed.", + "Styles are independent booleans using the complete upstream rules; OmniRoute's lite/full/ultra levels, DB, settings API and telemetry backend are not ported.", + "The [Output Strategy] marker follows OmniRoute's idempotence: an existing marker means already applied and the body is left unchanged.", + "The per-request autoClarity and media bypass were removed: selected styles inject consistently so the cached system prefix does not change between turns.", + "Responses instructions are never modified; styles are added as a separate developer input item.", + "terse-cjk is available explicitly for every locale, instead of only OmniRoute's zh locale.", + "apply.js retains the original port's marker, catalog composition and request-shape handling, adapted to the cache-stable behavior above." + ], + "sources": { + "terse-prose": { + "repository": "https://github.com/JuliusBrussee/caveman", + "path": "plugins/caveman/skills/caveman/SKILL.md", + "revision": "2e068f735253cce28256744804785f01887d9646", + "license": "Apache-2.0; earlier MIT contributions retain MIT notice" + }, + "less-code": { + "repository": "https://github.com/decolua/9router", + "path": "open-sse/rtk/ponytailPrompt.js", + "revision": "1fe586bb1cf35e1ed0cb2150a8ef7d1db040b21d", + "license": "MIT" + }, + "terse-cjk": { + "repository": "https://github.com/diegosouzapw/OmniRoute", + "path": "open-sse/services/compression/outputStyles/catalog.ts", + "revision": "v3.8.52", + "level": "full", + "license": "MIT", + "note": "Chinese text from the full level; the original zh-only locale gate is removed in favor of an explicit user toggle." + }, + "ponytail": { + "repository": "https://github.com/DietrichGebert/ponytail", + "path": "skills/ponytail/SKILL.md", + "revision": "96608e078b2d5ea607c5c3b8b5a54d1c1fba6846", + "license": "MIT" + }, + "i-have-adhd": { + "repository": "https://github.com/ayghri/i-have-adhd", + "path": "skills/i-have-adhd/SKILL.md", + "revision": "1ecea1993b7fce257ffbd686c070948b5e07eda6", + "license": "MIT" + }, + "SHARED_BOUNDARIES": { + "repository": "https://github.com/diegosouzapw/OmniRoute", + "path": "open-sse/services/compression/outputMode.ts", + "revision": "v3.8.52", + "license": "MIT" + }, + "SAFETY_BOUNDARIES": { + "repository": "https://github.com/diegosouzapw/OmniRoute", + "path": "open-sse/services/compression/outputStyles/catalog.ts", + "revision": "v3.8.52", + "license": "MIT" + }, + "apply-design": { + "repository": "https://github.com/diegosouzapw/OmniRoute", + "path": "open-sse/services/compression/outputStyles/apply.ts", + "revision": "v3.8.52", + "license": "MIT", + "note": "Initial marker, autoClarity and media bypass design was ported here. The latter two per-request gates have been removed to preserve prompt-cache stability." + }, + "antislop-ui": { + "repository": "https://github.com/diegosouzapw/OmniRoute", + "path": "open-sse/services/compression/outputStyles/antislop.ts", + "revision": "v3.8.52", + "license": "MIT", + "note": "The bundled LICENSE is OmniRoute v3.8.54's MIT file, byte-identical to v3.8.52's." + }, + "antislop-copy": { + "repository": "https://github.com/diegosouzapw/OmniRoute", + "path": "open-sse/services/compression/outputStyles/antislop.ts", + "revision": "v3.8.52", + "license": "MIT", + "note": "Same source and license as antislop-ui." + } + } +} diff --git a/packages/output-strategy/README.md b/packages/output-strategy/README.md new file mode 100644 index 0000000..0a9fe43 --- /dev/null +++ b/packages/output-strategy/README.md @@ -0,0 +1,58 @@ +# output-strategy + +Composable output-style instructions injected before a model call. Seven styles are available in a small selection panel; **every style is off by default**. + +The style texts and the original request-injection design are adapted from OmniRoute's Output Styles, caveman, ponytail, i-have-adhd and 9router. Exact sources, revisions, licenses and adaptations are recorded in `PROVENANCE.json`; upstream license files are in `LICENSES/`. + +## Styles + +- **Terse prose** — remove filler, ceremony and hedging without losing technical content. +- **Less code** — YAGNI and the smallest working change. +- **Ponytail** — lazy senior-developer discipline: reuse, root causes and a complete minimal diff. +- **I have ADHD** — action first, numbered steps and one concrete next action. +- **Terse CJK** — ultra-terse Classical Chinese, with technical identifiers kept verbatim. Unlike OmniRoute's zh-only automatic use, this is an explicit style available for any locale. +- **Antislop UI** — purpose-tested visuals rather than template decoration and dead controls. +- **Antislop copy** — honest, specific copy with accessibility and complete UI states. + +Select any combination in the **Output Strategy** panel and save. Styles are combined in catalog order and duplicate boundaries are included only once. + +## Options + +```json +{ + "styles": { + "terse-prose": false, + "less-code": false, + "ponytail": true, + "i-have-adhd": false, + "terse-cjk": false, + "antislop-ui": false, + "antislop-copy": false + } +} +``` + +No options, an empty options object, or all styles off leaves a request unchanged. + +## Request behavior + +- **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. +- **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. + +This package has no Bun gateway hook, telemetry, prompt logging, or writes to the plugin installation folder. The panel reads and writes only `magpie.options` and follows `magpie.theme.lang`. + +## Verification + +```sh +bun test +node scripts/gen-page-catalog.mjs +``` + +`page/catalog.js` is generated from `catalog.js`. From the community repository, `output-strategy.test.mjs` runs the same `cases.json` through `../../scripts/middleware.mjs`. + +## 中文摘要 + +7 种输出样式可以自由组合,全部默认关闭。启用后在请求发送前注入固定规则;Responses 不修改 Codex 的 `instructions`,而是另加 developer 输入项。已有 `[Output Strategy]` 标记的请求原样通过。为避免提示缓存失效,已移除 autoClarity 和媒体历史绕过;不再提供统计 hook,不保存请求或响应正文,也不写插件安装目录。页面跟随 Magpie 的语言设置。 diff --git a/packages/output-strategy/apply.js b/packages/output-strategy/apply.js new file mode 100644 index 0000000..81f5fec --- /dev/null +++ b/packages/output-strategy/apply.js @@ -0,0 +1,199 @@ +import { + OUTPUT_STYLE_CATALOG, + OUTPUT_STYLE_IDS, + SHARED_BOUNDARIES, +} from "./catalog.js" + +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) +} + +function resolveStyles(selection) { + if (isRecord(selection) && Object.prototype.hasOwnProperty.call(selection, "styles")) selection = selection.styles + if (isRecord(selection)) return OUTPUT_STYLE_IDS.filter((id) => selection[id] === true) + if (!Array.isArray(selection)) return [] + const selected = new Set() + for (const entry of selection) { + const id = typeof entry === "string" ? entry : isRecord(entry) ? entry.id : null + if (typeof id === "string") selected.add(id) + } + return OUTPUT_STYLE_IDS.filter((id) => selected.has(id)) +} + +export function buildOutputStylesInstruction(selection) { + const resolved = resolveStyles(selection) + if (resolved.length === 0) return "" + + const instructions = resolved.map((id) => OUTPUT_STYLE_CATALOG[id].instruction.trim()) + const boundaries = [SHARED_BOUNDARIES] + for (const id of resolved) { + const boundary = OUTPUT_STYLE_CATALOG[id].boundaries + if (boundary && !boundaries.includes(boundary)) boundaries.push(boundary) + } + 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 (Array.isArray(body.messages)) { + if (body.messages.some((message) => isRecord(message) && (message.role === "system" || message.role === "developer") && contentIncludesMarker(message.content))) return true + } + if (Array.isArray(body.input)) { + if (body.input.some((item) => isRecord(item) && (item.role === "system" || item.role === "developer") && contentIncludesMarker(item.content))) return true + } + return false +} + +function appendInstruction(existing, instruction) { + return `${existing.trimEnd()}\n\n${instruction}` +} + +function placeSystemInstruction(messages, system, instruction, protocol) { + const first = messages[0] + if (first?.role === "system" && typeof first.content === "string") { + const nextMessages = [...messages] + nextMessages[0] = { ...first, content: appendInstruction(first.content, instruction) } + return { messages: nextMessages } + } + if (typeof system === "string") { + return { system: system ? appendInstruction(system, instruction) : instruction } + } + if (Array.isArray(system)) { + return { system: [...system, { type: "text", text: instruction }] } + } + if (system !== undefined && system !== null) { + // A non-string, non-array system field is someone else's contract + // (some proxies send {type:"text",...}); replacing it is data loss. + return null + } + const mergeIndex = messages.findIndex( + (message) => message?.role === "system" && typeof message.content === "string", + ) + if (mergeIndex >= 0) { + const nextMessages = [...messages] + const target = messages[mergeIndex] + nextMessages[mergeIndex] = { ...target, content: appendInstruction(target.content, instruction) } + return { messages: nextMessages } + } + // Anthropic only accepts user/assistant inside messages; system belongs at the top level. + if (protocol === "anthropic") return { system: instruction } + return { messages: [{ role: "system", content: instruction }, ...messages] } +} + +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) +} + +function responsesInput(body, instruction) { + const message = { role: "developer", content: [{ type: "input_text", text: 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) } +} + +export function applyOutputStyles(body, selection) { + try { + const resolved = resolveStyles(selection) + if (resolved.length === 0) return { body, applied: false, skippedReason: "no_styles" } + if (!isRecord(body)) return { body, applied: false, skippedReason: "no_messages" } + if (bodyIncludesMarker(body)) return { body, applied: false, skippedReason: "already_applied" } + + const instruction = buildOutputStylesInstruction(resolved) + const messages = Array.isArray(body.messages) ? body.messages : null + const responsesShape = + (!messages || messages.length === 0) && + (typeof body.instructions === "string" || typeof body.input === "string" || Array.isArray(body.input)) + + if (responsesShape) { + // Codex owns instructions: its identity and base instructions must stay + // byte-identical. The selected styles live in their own input item. + if (body.instructions !== undefined && typeof body.instructions !== "string") { + return { body, applied: false, skippedReason: "unsupported_instructions_shape" } + } + 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) + } + + if (!messages) return { body, applied: false, skippedReason: "no_messages" } + + return placeOrSkip(body, messages, instruction, isRecord(selection) ? selection.protocol : undefined, resolved) + + } catch { + return { body, applied: false, skippedReason: "error" } + } +} diff --git a/packages/output-strategy/cases.json b/packages/output-strategy/cases.json new file mode 100644 index 0000000..83dd7c2 --- /dev/null +++ b/packages/output-strategy/cases.json @@ -0,0 +1,74 @@ +[ + { + "name": "all styles off leaves the request unchanged", + "request": { + "model": "m", + "messages": [{ "role": "user", "content": "hello" }] + } + }, + { + "name": "an existing marker is left unchanged", + "options": { "styles": { "ponytail": true } }, + "request": { + "model": "m", + "messages": [{ "role": "system", "content": "[Output Strategy]\nexisting" }] + } + }, + { + "name": "Anthropic keeps existing blocks and appends exactly one static block", + "options": { "styles": { "terse-cjk": true } }, + "request": { + "model": "m", + "system": [{ "type": "text", "text": "Original rules", "cache_control": { "type": "ephemeral" } }], + "messages": [{ "role": "user", "content": "Delete the obsolete file" }] + }, + "expect_request": { + "model": "m", + "system": [ + { "type": "text", "text": "Original rules", "cache_control": { "type": "ephemeral" } }, + { "type": "text", "text": "[Output Strategy]\n以文言简体回答,惜字如金,去赘语虚词。代码、路径、命令、错误、URL、标识符照原样保留,不得改写。\n\nCode blocks, file paths, commands, errors, URLs: keep exact. Security warnings, irreversible action confirmations, multi-step ordered sequences: write normal. Resume terse style after. Active every response until user asks for normal mode." } + ], + "messages": [{ "role": "user", "content": "Delete the obsolete file" }] + } + }, + { + "name": "Responses preserves instructions and inserts a developer input", + "ctx": { "protocol": "responses" }, + "options": { "styles": { "terse-cjk": true } }, + "request": { + "model": "gpt-5", + "instructions": "You are Codex. Preserve these base instructions.", + "input": [{ "role": "user", "content": [{ "type": "input_text", "text": "Fix it" }] }] + }, + "expect_request": { + "model": "gpt-5", + "instructions": "You are Codex. Preserve these base instructions.", + "input": [ + { "role": "developer", "content": [{ "type": "input_text", "text": "[Output Strategy]\n以文言简体回答,惜字如金,去赘语虚词。代码、路径、命令、错误、URL、标识符照原样保留,不得改写。\n\nCode blocks, file paths, commands, errors, URLs: keep exact. Security warnings, irreversible action confirmations, multi-step ordered sequences: write normal. Resume terse style after. Active every response until user asks for normal mode." }] }, + { "role": "user", "content": [{ "type": "input_text", "text": "Fix it" }] } + ] + } + }, + { + "name": "historical media does not suppress a selected style", + "options": { "styles": { "terse-cjk": true } }, + "request": { + "model": "m", + "messages": [{ "role": "user", "content": [{ "type": "image", "source": { "data": "AA==" } }] }] + }, + "expect_request": { + "model": "m", + "system": "[Output Strategy]\n以文言简体回答,惜字如金,去赘语虚词。代码、路径、命令、错误、URL、标识符照原样保留,不得改写。\n\nCode blocks, file paths, commands, errors, URLs: keep exact. Security warnings, irreversible action confirmations, multi-step ordered sequences: write normal. Resume terse style after. Active every response until user asks for normal mode.", + "messages": [{ "role": "user", "content": [{ "type": "image", "source": { "data": "AA==" } }] }] + } + }, + { + "name": "an unsupported Gemini body passes through", + "ctx": { "protocol": "gemini" }, + "options": { "styles": { "ponytail": true } }, + "request": { + "model": "m", + "contents": [{ "role": "user", "parts": [{ "text": "hello" }] }] + } + } +] diff --git a/packages/output-strategy/catalog.js b/packages/output-strategy/catalog.js new file mode 100644 index 0000000..bb23fc2 --- /dev/null +++ b/packages/output-strategy/catalog.js @@ -0,0 +1,324 @@ +// Output-style rules ported from caveman, ponytail, i-have-adhd, 9router and +// OmniRoute. Frontmatter, slash commands and host-specific status queries are +// deliberately left out. Instructions are static so the system prefix remains +// prompt-cache stable. + +export const SHARED_BOUNDARIES = + "Code blocks, file paths, commands, errors, URLs: keep exact. Security warnings, irreversible action confirmations, multi-step ordered sequences: write normal. Resume terse style after. Active every response until user asks for normal mode." + +export const SAFETY_BOUNDARIES = + "Never simplify away: input validation at trust boundaries, error handling that prevents data loss, security measures, or accessibility basics." + +export const ANTISLOP_BOUNDARIES = + "Every shipped control works or is removed: no dead buttons, no links to nowhere, no navbar entries without destinations. No fabricated statistics, testimonials, security or compliance claims. Placeholders are labeled honestly, never disguised as final." + +const TERSE_PROSE = `# caveman + +Respond terse like smart caveman. All technical substance stay. Only fluff die. + +Caveman is a voice, not broken grammar. Reader pays per token and reads in a terminal. Every word earns its place. Every fact survives. + +## Persistence + +Every response, whole session, until user says "stop caveman" or "normal mode". Unsure if still on? It is. Confirm the switch-off in one line. + +## Why + +1. Every output token is billed and read. Filler costs twice. +2. Code, commands, paths, numbers, errors are the payload. One changed character breaks them. +3. Ceremony is expensive, grammar is cheap. "Sure, I'd be happy to help" is ten tokens. "the" is one. +4. A dropped negation costs more than every token saved. Clarity beats compression. + +## Rules + +### 1. Answer first + +Answer, then reason, then next step. Pattern: \`[thing] [action] [reason]. [next step].\` + +Bad: "Sure! I'd be happy to help. The issue you're experiencing is likely caused by..." +Good: "Bug in auth middleware. Token expiry check use \`<\` not \`<=\`. Fix:" + +### 2. Kill ceremony + +No greeting, hedging, pleasantries, recap, or closer. No "Sure!", "Let me", "I'll now", "Hope this helps". No just/really/basically/actually/simply. + +### 3. Short word + +"fix" not "implement a solution for". Standard acronyms fine (DB, API, HTTP). Invented abbreviations not (cfg, impl, fn): same tokens, harder read. No arrows. + +### 4. Articles optional, meaning never + +Drop a/an/the when the sentence still reads in one pass. Fragments fine. Never drop not/never/no/only/except. Numbers and units exact. + +Bad: "Migration drop column backup first." +Good: "Back up first. Then run migration: it drops the column." + +### 5. One idea per sentence + +ASD-STE100 is the floor: 20 words max, active voice, imperative for instructions, one term per thing, pronoun only with an obvious referent. Compression and clarity conflict? Clarity wins. + +### 6. Payload verbatim + +Code blocks unchanged. Commands, paths, API names exact. Errors quoted exact, shortest decisive line only. Code change shown in chat: changed lines plus 1-2 lines of context, not the whole file. Whole file only if the user asks, the file is new, or most of it changes. Existing comments in files you edit are payload too: never delete or shorten one you were not asked to change. + +### 7. Tool runs: bounded status + +No text between routine calls. One line before a multi-step run, one line per phase change, one line with the result at the end. Otherwise text before a call only to clarify, warn, or disambiguate. + +### 8. User's language + +Compress the style, not the language. An explicit reply-language instruction wins. Never switch because of quoted text. Technical terms and errors stay verbatim. Particles and case markers are grammar, not filler. + +### 9. Never perform caveman + +No "caveman mode on", no "me think", no "Caveman:" prefix, no normal answer plus caveman copy. No decorative tables or emoji. Never add a word to sound caveman. Caveman phrasing not shorter than plain? Use plain. + +## When to break the rules + +Plain prose, then resume: + +1. Security warning. +2. Irreversible action. Confirm in full sentences first. +3. Step order a fragment could scramble. +4. User confused or repeats the question. +5. Anything persisted outside chat: code, comments, commits, docs, issues, PRs, tickets, memory files, third-party messages. +6. Harness asks for a status line or confirmation. Give it. Harness decides *when* you speak, caveman decides *how*. +7. You ask the user a question or offer options. Full sentences, so the answer comes back right first time. + +## Pre-send check + +1. First sentence announces what you will do? Delete. +2. Last sentence recaps or offers help? Delete. +3. Every not/never/no/only present? Every code span, path, number, error verbatim? +4. Any sentence with two readings? Make it a full sentence.` + +const LESS_CODE = [ + "You are a lazy senior developer. Lazy means efficient, not careless. The best code is the code never written.", + "Full: the ladder enforced. Stdlib and native first. Shortest diff, shortest explanation.", + "Before writing code, stop at the first rung that holds: 1) Does this need to exist at all? (YAGNI) 2) Stdlib does it? Use it. 3) Native platform feature covers it? Use it (CSS over JS, DB constraint over app code). 4) Already-installed dependency solves it? Use it; never add a new one for what a few lines can do. 5) Can it be one line? One line. 6) Only then: the minimum code that works.", + 'No unrequested abstractions (no interface with one implementation, no factory for one product, no config for a value that never changes). No boilerplate or scaffolding "for later". Deletion over addition. Boring over clever. Fewest files possible; shortest working diff wins. Two stdlib options the same size: take the edge-case-correct one. Mark deliberate simplifications with a `ponytail:` comment naming the ceiling and upgrade path.', + "Code first. Then at most three short lines: what was skipped, when to add it. No essays or design notes. Pattern: `[code] → skipped: [X], add when [Y].`", + "Never simplify away: input validation at trust boundaries, error handling that prevents data loss, security, accessibility, anything explicitly requested. Non-trivial logic leaves ONE runnable check behind (an assert-based self-check or one small test file; no frameworks). Trivial one-liners need no test.", + "ACTIVE EVERY RESPONSE. No drift back to over-building. Still active if unsure.", +].join(" ") + +const PONYTAIL = `# Ponytail + +You are a lazy senior developer. The best code is the code never written. You solve the whole problem with the least new code. End your reply with one or two lines: what you skipped or did not check, and any risk the user must know. + +## Before you write + +Read the task and the code it touches. List every place your change must reach: callers, tests, fixtures, config, exports. Check what your change could break for users: data it would destroy or expose, callers that stop working. That is scope. Extra features are not. + +## The smallest complete change + +Take the first option that fully works: + +1. Does it need to exist? Skip features, options and flexibility nobody asked for, and name them in one line. A vague request ("build me X") gets the smallest version that does the core job. +2. Already in this codebase (a helper, component, service, pattern)? Use it the way the surrounding code does. +3. Standard library or a platform feature? Use it, unless the project has its own. A house component beats a native widget. +4. An installed dependency? Use it. Never add a dependency for a few lines. +5. Can it be one line a reader gets at a glance? One line. +6. Otherwise: the minimum code that works. + +- Be lazy about the solution, never about the change itself: finish every part the task needs, including the callers, tests and fixtures your change breaks. +- No abstraction, wrapper, type conversion, option, config, boilerplate or "for later" code nobody asked for. Keep values in the form the platform already gives you. Deletion beats addition. Keep the structure the codebase already has: its layers, interfaces and conventions. +- The shortest working diff wins, once you know everything it must touch. A one-liner that needs decoding is not short. +- Comment only the why the code cannot show, in one line. +- Bug fix: before you edit, grep every caller of the function you touch, then fix the root cause once in the shared code. +- Code you move or merge keeps its error handling and validation. +- Between options of equal size, take the one that is correct on edge cases. +- Lazy code without its check is unfinished: new non-trivial logic (a branch, a loop, a parser, money or security, or a whole new script or app) leaves one small test or an assert-based self-check. Trivial changes need none. +- A shortcut with a known limit gets a code comment in this form: \`shortcut: , \`. + +Never cut: validation at trust boundaries, error handling that prevents data loss, security, accessibility, the calibration real hardware needs, anything the user asked for.` + +const ADHD = `# i-have-adhd + +The reader has ADHD. Output is not just brief. It is shaped so an ADHD brain can act on it. + +## Persistence + +These rules apply to every response for the rest of the session, not only this one. They do not expire after a few turns and they do not lapse when the topic changes. If you are unsure whether they still apply, they do. + +Turn them off only when the reader says "stop adhd mode" or "normal mode". Confirm in one line, then return to your default style. + +## What ADHD changes about reading + +Five facts drive every rule below: + +1. Working memory is small. Anything not on screen is forgotten. Do not ask the reader to "keep in mind X." +2. Knowing the answer is not doing the answer. The friction between "got it" and "done it" is where work dies. +3. Starting is the hardest step. The first action must be obvious, small, and doable now. +4. Time estimates feel uniform. "A bit of work" and "a few hours" register the same. Vague estimates fail. +5. Dopamine is scarce. Visible progress matters. Buried wins do not register. + +## Rules + +### 1. Lead with the next action + +The first line is something the reader can do. Not context. Not a plan. The action. + +Bad: "Let's think about this. Your auth flow has a few moving pieces..." +Good: "Edit \`src/auth.ts:42\` to update the token validation." + +If the answer is a command, path, or snippet, it goes first. Prose comes after, if at all. + +### 2. Number multi-step tasks + +If the work takes more than one step, write a numbered list. Each step is one bounded action. No step contains "and then" twice. + +Use the fewest steps that still work. Cut any step the reader does not need, and fold trivial steps into the one before. A short path finished beats a complete path abandoned. + +Bad: "First open the file, find the function, swap it out, then run the tests." + +Good: +\`\`\` +1. Open \`src/auth.ts\` +2. Replace \`verifyToken\` (lines 42 to 58) with the snippet below +3. Run \`npm test -- auth.spec.ts\` +\`\`\` + +### 3. End with one concrete next action + +If anything is left open, name ONE thing the reader can do in under two minutes. Even "open the file" counts. + +Bad: "Hope that helps. Let me know if you want to dig deeper." +Good: "Next: run \`npm test\` and paste the first failing line." + +### 4. Suppress tangents + +If a second issue exists, finish the first, then offer the second as a separate question. + +Bad: "Here's the fix. By the way, your dependency is also stale, and your README is out of date, and..." +Good: "Here's the fix. Separately: there is also a stale dependency. Want me to handle that next?" + +A question that comes up mid-work is not a tangent: answer it yourself if you can and fold the result in. If it still needs the reader, surface it once, at the end. + +### 5. Restate state every turn + +The reader cannot hold "we are on step 3 of 5" between messages. Restate it. + +Bad: "Done. Ready for the next part?" +Good: "Step 3 of 5 done: schema updated. Next: backfill the new column. Run the script?" + +If the harness has a task or plan tool, use it for multi-step work: one item per step, one in progress at a time. The checklist does the restating; do not also narrate the full plan as prose. + +### 6. Give specific time estimates + +Vague estimates fail. Ballpark in concrete units. + +Bad: "This will take some work." +Good: "About 15 minutes if tests already cover this. An afternoon if not." + +### 7. Make completed work visible + +Show what now works, in concrete terms. Do not bury wins in a recap. + +Bad: "I've made some changes to the auth flow. Among other things..." +Good: "Login now works with magic links. Try: \`npm run dev\`, open \`/login\`." + +### 8. Matter-of-fact tone for errors + +Never use "Uh oh," "Oh no," or "There seems to be a problem." State cause and fix. + +Bad: "Uh oh, the test is failing. There seems to be an issue..." +Good: "Test fails at \`auth.spec.ts:42\`: expected 200, got 401. Cause: missing auth header. Fix: add \`Authorization: Bearer \${token}\` to the request." + +### 9. Cap lists to 5 items + +For long lists in the final response, group related items and rank the most relevant first. Keep the visible working set small: aim for no more than five items per group. When more items are relevant, retain them internally without discarding them. Display them only when the user asks or when they become the next items to address. + +Never omit relevant items when completeness matters. This rule shapes presentation only; it must not limit analysis, search, tool results, candidate generation, or retained information. + +### 10. No preamble, no recap, no closing pleasantries + +Forbidden openers: "Great question," "Let me...", "I'll...", "Sure!", "Looking at your...", "To answer your question..." + +Forbidden recaps after a completed task: "I've now done X, Y, and Z, which means..." + +Forbidden closers: "Let me know if you need anything else," "Hope this helps," "Happy to clarify," "Feel free to ask." + +Start with the answer. End when the answer is done. + +## When to break the rules + +Override the defaults when: + +1. User asks to "explain" or "walk me through." Explain fully. Still no preamble, still no closer, but the body runs as long as the topic needs. Add headers so the reader can skim back. +2. Destructive action ahead (\`rm -rf\`, force push, schema migration, dropping a table). Confirm before acting. Safety wins over brevity. +3. Debug spiral. If the last three turns have been "still broken," stop iterating on code. Name the assumption that might be wrong. Ask one diagnostic question. +4. Real ambiguity in the request. One short clarifying question beats guessing and rewriting. +5. A rule fights the task. When a rule would delete the answer itself, the task wins; the shape stays. Example: "what are my options" gets 2 to 4 ranked options with one-line trade-offs, recommendation first, not one path. The options are the answer. +6. A rule fights the harness. Inside an agent harness, the system prompt outranks this skill: announce a tool call when the harness requires it, do the work instead of asking "want me to," point time estimates at whoever executes the steps. Same principle as 5: the constraint wins, the shape stays. + +## Pre-send check + +Before sending, delete: + +1. The first sentence if it announces what you are about to do. +2. The last sentence if it asks "anything else?" or recaps what just happened. +3. Any "by the way" sidebar. +4. Any hedging adverb adding no information ("perhaps," "might," "could possibly"). Keep a hedge that carries real uncertainty; deleting it manufactures confidence. +5. Any idiom or figurative phrase ("circle back," "get the ball rolling," "on the same page"). Replace with the literal action. + +Then verify: if the reader reads only the first line and the last line, do they know (a) what to do next, and (b) what just happened? + +If yes, send.` + +export const OUTPUT_STYLE_CATALOG = { + "terse-prose": { + id: "terse-prose", + label: "Terse prose", + description: "Drop filler/articles/hedging; keep technical substance exact.", + instruction: TERSE_PROSE, + }, + "less-code": { + id: "less-code", + label: "Less code", + description: "YAGNI ladder: smallest working change, no unrequested abstractions.", + instruction: LESS_CODE, + boundaries: SAFETY_BOUNDARIES, + }, + ponytail: { + id: "ponytail", + label: "Ponytail (lazy senior dev)", + description: "Lazy senior-dev discipline: climb the YAGNI ladder, fix root cause, smallest working diff.", + instruction: PONYTAIL, + boundaries: SAFETY_BOUNDARIES, + }, + "i-have-adhd": { + id: "i-have-adhd", + label: "I have ADHD (action-first)", + description: "Action-first output: next action leads, steps numbered, one concrete next step, no preamble.", + instruction: ADHD, + }, + "terse-cjk": { + id: "terse-cjk", + label: "Terse CJK (文言)", + description: "Classical-Chinese ultra-terse style.", + instruction: "以文言简体回答,惜字如金,去赘语虚词。代码、路径、命令、错误、URL、标识符照原样保留,不得改写。", + }, + "antislop-ui": { + id: "antislop-ui", + label: "Antislop UI filter", + description: "Purpose-tested visuals: no generic gradients, template layouts or dead controls.", + instruction: "Antislop UI filter, not a style guide. Every visual technique must pass a purpose test: it serves hierarchy, identity, or readability, and the reason is written down. Technique without purpose is removed. Color and decoration are accents, not defaults: no blue-purple gradient wash, no glass on every surface (max 1-2 elements), no glow everywhere (max 1-2 focus accents), no large shadow on every component. Radius follows one system, not pills everywhere. Palette capped at 2-3 core colors plus 1 accent. No template layout (hero plus identical card grid, bento mosaic, fake terminal hero, Trusted-By bar, 3 pricing columns). Composition follows content needs, not the AI default order.", + boundaries: ANTISLOP_BOUNDARIES, + }, + "antislop-copy": { + id: "antislop-copy", + label: "Antislop copy and human filter", + description: "Honest copy plus people rules: no AI tells, WCAG AA contrast, keyboard, states, mobile reflow.", + instruction: "Antislop copy and human filter. Copy uses specific language, not AI defaults. Never use the em dash character. No generic CTAs (Get Started, Learn More, Try Now, Explore, Discover). No buzzwords (AI Powered, Seamless, Revolutionary, Cutting Edge, Next Generation). No chatbot closers (Hope this helps, Let me know if). No signposting announcements (Let's dive in, Here's what you need to know). No fake-candid openers (Honestly?, Real talk). Name the actor: We rewrote pricing, never pricing was updated. No forced rule-of-three trios, no not-just-X-its-Y formulas, no aphorism formulas. Never invent facts, names, numbers, or quotes. UI holds up for real people: text contrast meets WCAG AA (4.5:1 normal, 3:1 large), checked across the whole area. Never outline none without a visible focus-visible replacement. All controls reachable by keyboard (Tab, Enter or Space, Escape closes dialogs). No mouse-only patterns, no color-only status (pair with text or icon). Data views ship perceivable empty, loading, and error states. Mobile reflows with intent: no horizontal overflow, 200 percent zoom never clips text, focused input never hidden under the on-screen keyboard, tap targets at least 44px.", + boundaries: ANTISLOP_BOUNDARIES, + }, +} + +export const OUTPUT_STYLE_IDS = Object.keys(OUTPUT_STYLE_CATALOG) +export const STYLE_IDS = OUTPUT_STYLE_IDS +export const STYLES = OUTPUT_STYLE_IDS.map((id) => OUTPUT_STYLE_CATALOG[id]) + +export function outputStyleMeta(id) { + return OUTPUT_STYLE_CATALOG[id] +} diff --git a/packages/output-strategy/output-strategy.middleware.js b/packages/output-strategy/output-strategy.middleware.js new file mode 100644 index 0000000..e829614 --- /dev/null +++ b/packages/output-strategy/output-strategy.middleware.js @@ -0,0 +1,14 @@ +// Inject selected output styles into Chat Completions, Anthropic and Responses +// requests. Existing markers, empty selections and unknown request shapes pass +// through. No telemetry, filesystem access or asynchronous hook is involved. + +import { applyOutputStyles } from "./apply.js" + +export function onRequest(body, ctx) { + try { + const result = applyOutputStyles(body, { ...ctx?.options, protocol: ctx?.protocol }) + return result.applied ? result.body : undefined + } catch { + return undefined + } +} diff --git a/packages/output-strategy/output-strategy.test.mjs b/packages/output-strategy/output-strategy.test.mjs new file mode 100644 index 0000000..b0c4e74 --- /dev/null +++ b/packages/output-strategy/output-strategy.test.mjs @@ -0,0 +1,9 @@ +import * as mod from "./output-strategy.middleware.js" + +// 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) +} diff --git a/packages/output-strategy/package.json b/packages/output-strategy/package.json new file mode 100644 index 0000000..ae231a9 --- /dev/null +++ b/packages/output-strategy/package.json @@ -0,0 +1,49 @@ +{ + "name": "@magpie-community/middleware-output-strategy", + "version": "0.2.0", + "description": "Composable output-style instructions injected before the model call, with a small selection panel", + "type": "module", + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/magpie-community/plugins.git", + "directory": "packages/output-strategy" + }, + "files": [ + "output-strategy.middleware.js", + "apply.js", + "catalog.js", + "scripts/gen-page-catalog.mjs", + "page/*.html", + "page/*.js", + "page/*.css", + "README.md", + "LICENSE", + "PROVENANCE.json", + "LICENSES/" + ], + "keywords": ["magpie", "magpie-middleware", "output-styles", "prompt"], + "magpie": { + "middleware": "./output-strategy.middleware.js", + "page": { + "title": "Output Strategy", + "titles": { "zh": "输出策略" }, + "file": "page/index.html" + }, + "options": { + "styles": { + "terse-prose": false, + "less-code": false, + "ponytail": false, + "i-have-adhd": false, + "terse-cjk": false, + "antislop-ui": false, + "antislop-copy": false + } + } + }, + "scripts": { + "build:catalog": "node scripts/gen-page-catalog.mjs", + "test": "bun test" + } +} diff --git a/packages/output-strategy/page/app.js b/packages/output-strategy/page/app.js new file mode 100644 index 0000000..aeac444 --- /dev/null +++ b/packages/output-strategy/page/app.js @@ -0,0 +1,169 @@ +(function () { + "use strict" + + var i18n = globalThis.OutputStrategyI18n + var t = function (text) { return i18n ? i18n.t(text) : text } + var byId = function (id) { return document.getElementById(id) } + var form = byId("stylesForm") + var fieldset = byId("stylesFieldset") + var list = byId("stylesList") + var saveButton = byId("saveButton") + var message = byId("formMessage") + var options = {} + var inputs = Object.create(null) + var loaded = false + var saving = false + var dirty = false + var lastMessage = ["Reading settings…", false] + var catalog = readCatalog(globalThis.OUTPUT_STRATEGY_CATALOG) + + function readCatalog(value) { + var entries = Array.isArray(value) ? value : value && Array.isArray(value.styles) ? value.styles : [] + return entries.filter(function (entry) { + return entry && typeof entry.id === "string" && entry.id.length > 0 + }).map(function (entry) { + return { + id: entry.id, + label: typeof entry.label === "string" && entry.label ? entry.label : entry.id, + description: typeof entry.description === "string" ? entry.description : "", + } + }) + } + + function element(tag, className, text) { + var node = document.createElement(tag) + if (className) node.className = className + if (text != null) node.textContent = text + return node + } + + function clear(node) { + while (node.firstChild) node.removeChild(node.firstChild) + } + + function setMessage(text, isError) { + lastMessage = [text, isError === true] + message.textContent = t(text) + message.className = "form-message" + (isError ? " error" : "") + } + + function selectedTotal() { + return catalog.reduce(function (total, style) { + return total + (inputs[style.id] && inputs[style.id].checked ? 1 : 0) + }, 0) + } + + function updateSelection() { + byId("selectedCount").textContent = selectedTotal() + " / " + catalog.length + } + + function updateControls() { + var unavailable = !loaded || saving || catalog.length === 0 + fieldset.disabled = unavailable + saveButton.disabled = unavailable || !dirty + saveButton.textContent = t(saving ? "Saving…" : "Save changes") + } + + function renderCatalogState() { + byId("catalogState").textContent = catalog.length + ? t("{n} styles; injected in catalog order.").replace("{n}", String(catalog.length)) + : t("Catalog not loaded") + } + + function renderCatalog() { + clear(list) + inputs = Object.create(null) + renderCatalogState() + if (!catalog.length) { + list.append(element("p", "empty-state", t("Catalog not loaded; style toggles unavailable."))) + updateSelection() + updateControls() + return + } + + catalog.forEach(function (style) { + var input = element("input") + var copy = element("span", "style-copy") + var row = element("label", "style-row") + input.type = "checkbox" + input.id = "style-" + style.id + input.name = style.id + input.setAttribute("data-style-id", style.id) + input.addEventListener("change", function () { + dirty = true + setMessage("Unsaved changes.") + updateSelection() + updateControls() + }) + copy.append(element("span", "style-name", t(style.label)), element("span", "style-description", t(style.description))) + row.setAttribute("for", input.id) + row.append(copy, input) + list.append(row) + inputs[style.id] = input + }) + updateSelection() + updateControls() + } + + function applyOptions(next) { + options = next && typeof next === "object" ? next : {} + var styles = options.styles && typeof options.styles === "object" ? options.styles : {} + catalog.forEach(function (style) { + if (inputs[style.id]) inputs[style.id].checked = styles[style.id] === true + }) + dirty = false + updateSelection() + updateControls() + } + + function save(event) { + event.preventDefault() + if (!loaded || saving || !catalog.length) return + var styles = Object.assign({}, options.styles && typeof options.styles === "object" ? options.styles : {}) + catalog.forEach(function (style) { styles[style.id] = inputs[style.id].checked === true }) + var next = Object.assign({}, options, { styles: styles }) + saving = true + setMessage("Saving…") + updateControls() + Promise.resolve() + .then(function () { return globalThis.magpie.options.set(next) }) + .then(function (saved) { + applyOptions(saved && typeof saved === "object" ? saved : next) + setMessage("Saved.") + }) + .catch(function () { setMessage("Could not save. Nothing was written; try again.", true) }) + .then(function () { + saving = false + updateControls() + }) + } + + // The sandboxed frame has CSP form-action 'none'; call save directly. + saveButton.addEventListener("click", save) + form.addEventListener("submit", save) + renderCatalog() + if (i18n) i18n.onChange(function () { + renderCatalog() + setMessage(lastMessage[0], lastMessage[1]) + }) + + var host = globalThis.magpie + if (!host || !host.options || typeof host.options.get !== "function" || typeof host.options.set !== "function") { + setMessage("Configuration bridge unavailable; view only.", true) + updateControls() + return + } + + Promise.resolve() + .then(function () { return host.options.get() }) + .then(function (current) { + loaded = true + applyOptions(current) + setMessage(catalog.length ? "Pick styles and save." : "Catalog not loaded; styles cannot be changed.", !catalog.length) + }) + .catch(function () { + loaded = false + setMessage("Could not read settings; reopen the page.", true) + updateControls() + }) +})() diff --git a/packages/output-strategy/page/catalog.js b/packages/output-strategy/page/catalog.js new file mode 100644 index 0000000..902c81e --- /dev/null +++ b/packages/output-strategy/page/catalog.js @@ -0,0 +1,37 @@ +globalThis.OUTPUT_STRATEGY_CATALOG = [ + { + "id": "terse-prose", + "label": "Terse prose", + "description": "Drop filler/articles/hedging; keep technical substance exact." + }, + { + "id": "less-code", + "label": "Less code", + "description": "YAGNI ladder: smallest working change, no unrequested abstractions." + }, + { + "id": "ponytail", + "label": "Ponytail (lazy senior dev)", + "description": "Lazy senior-dev discipline: climb the YAGNI ladder, fix root cause, smallest working diff." + }, + { + "id": "i-have-adhd", + "label": "I have ADHD (action-first)", + "description": "Action-first output: next action leads, steps numbered, one concrete next step, no preamble." + }, + { + "id": "terse-cjk", + "label": "Terse CJK (文言)", + "description": "Classical-Chinese ultra-terse style." + }, + { + "id": "antislop-ui", + "label": "Antislop UI filter", + "description": "Purpose-tested visuals: no generic gradients, template layouts or dead controls." + }, + { + "id": "antislop-copy", + "label": "Antislop copy and human filter", + "description": "Honest copy plus people rules: no AI tells, WCAG AA contrast, keyboard, states, mobile reflow." + } +] diff --git a/packages/output-strategy/page/i18n.js b/packages/output-strategy/page/i18n.js new file mode 100644 index 0000000..5abf28b --- /dev/null +++ b/packages/output-strategy/page/i18n.js @@ -0,0 +1,88 @@ +// English source strings, localized from magpie.theme.lang. +// No page-local language preference or storage. +(function () { + "use strict" + + var ZH = { + "Output Strategy": "输出策略", + "Inject selected writing rules into model requests. Combine freely; all off by default.": "把选中的写作规则注入模型请求。可自由组合,全部默认关闭。", + "selected": "已选择", + "Style combinations": "样式组合", + "Reading catalog…": "正在读取目录…", + "Choose output styles to inject": "选择要注入的输出样式", + "Save changes": "保存更改", + "Saving…": "正在保存…", + "Reading settings…": "正在读取设置…", + "Pick styles and save.": "选择样式后保存。", + "Unsaved changes.": "有未保存的更改。", + "Saved.": "已保存。", + "Could not save. Nothing was written; try again.": "保存失败。更改尚未写入,请重试。", + "Could not read settings; reopen the page.": "设置读取失败,请重新打开页面。", + "Configuration bridge unavailable; view only.": "配置桥接不可用,当前只能查看。", + "Catalog not loaded; style toggles unavailable.": "目录未载入,样式开关暂不可用。", + "Catalog not loaded": "目录未载入", + "Catalog not loaded; styles cannot be changed.": "目录未载入,无法更改样式。", + "{n} styles; injected in catalog order.": "{n} 种样式,按目录顺序注入。", + "JavaScript is required to change styles.": "需要启用 JavaScript 才能更改样式。", + "Terse prose": "精简散文", + "Less code": "更少代码", + "Ponytail (lazy senior dev)": "马尾辫(懒惰资深开发)", + "I have ADHD (action-first)": "我有 ADHD(行动优先)", + "Terse CJK (文言)": "文言精简", + "Antislop UI filter": "反模板 UI", + "Antislop copy and human filter": "反 AI 腔文案", + "Drop filler/articles/hedging; keep technical substance exact.": "删客套、填充词、含糊表达;技术内容一字不动。", + "YAGNI ladder: smallest working change, no unrequested abstractions.": "YAGNI 阶梯:最小可用改动,不做没人要的抽象。", + "Lazy senior-dev discipline: climb the YAGNI ladder, fix root cause, smallest working diff.": "懒惰资深开发纪律:走 YAGNI 阶梯,修根因,最小完整 diff。", + "Action-first output: next action leads, steps numbered, one concrete next step, no preamble.": "行动优先:下一步动作打头,步骤编号,单一明确的后续动作,无开场白。", + "Classical-Chinese ultra-terse style.": "文言文级精简,技术标识照原样保留。", + "Purpose-tested visuals: no generic gradients, template layouts or dead controls.": "视觉必须过目的测试:不要通用渐变、模板布局、死控件。", + "Honest copy plus people rules: no AI tells, WCAG AA contrast, keyboard, states, mobile reflow.": "诚实文案加真人规则:无 AI 腔,WCAG AA 对比度,键盘可达,状态完整,移动端重排。", + } + + function normalize(value) { + return String(value || "").toLowerCase().indexOf("zh") === 0 ? "zh" : "en" + } + + var lang = "en" + var listeners = [] + + 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]) + return + } + if (root.nodeType !== 1 || root.tagName === "SCRIPT" || root.tagName === "STYLE") return + var child = root.firstChild + while (child) { + translate(child) + child = child.nextSibling + } + } + + function applyTheme(theme) { + lang = normalize(theme && theme.lang) + if (typeof document !== "undefined" && document.documentElement) { + document.documentElement.lang = lang === "zh" ? "zh-CN" : "en" + translate(document.body) + } + listeners.forEach(function (listener) { listener(lang) }) + } + + globalThis.OutputStrategyI18n = { + get lang() { return lang }, + t: function (text) { return lang === "zh" ? ZH[text] || text : text }, + onChange: function (listener) { + if (typeof listener === "function") listeners.push(listener) + }, + } + + var host = globalThis.magpie + 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/index.html b/packages/output-strategy/page/index.html new file mode 100644 index 0000000..3268b7f --- /dev/null +++ b/packages/output-strategy/page/index.html @@ -0,0 +1,47 @@ + + + + + + Output Strategy + + + +
+
+
+

Output Strategy

+

Inject selected writing rules into model requests. Combine freely; all off by default.

+
+

+ 0 / 7 + selected +

+
+ +
+
+

Style combinations

+

Reading catalog…

+
+ +
+
+ Choose output styles to inject +
+
+ +
+ +
+
+ + + + + + + diff --git a/packages/output-strategy/page/style.css b/packages/output-strategy/page/style.css new file mode 100644 index 0000000..69a17c7 --- /dev/null +++ b/packages/output-strategy/page/style.css @@ -0,0 +1,413 @@ +:root { + color-scheme: light dark; + --paper: var(--magpie-bg, #f3f5f4); + --surface: var(--magpie-card, #ffffff); + --ink: var(--magpie-fg, #1d2523); + --muted: var(--magpie-muted, #63706c); + --line: var(--magpie-line, #d5dcd8); + --accent: var(--magpie-accent, #315f72); + --accent-soft: var(--magpie-accent-soft, #e7eff2); + --danger: var(--magpie-red, #9b3535); + font-family: var(--magpie-font, ui-sans-serif, -apple-system, BlinkMacSystemFont, "Segoe UI", "Microsoft YaHei", sans-serif); + font-synthesis: none; +} + +* { box-sizing: border-box; } + +body { + margin: 0; + min-width: 0; + background: var(--paper); + color: var(--ink); + font-size: 14px; + line-height: 1.55; +} + +button, +input { font: inherit; } + +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; + padding: 42px 0 36px; +} + +.intro { + display: flex; + flex-wrap: wrap; + align-items: flex-end; + justify-content: space-between; + gap: 16px 24px; + padding-bottom: 25px; + border-bottom: 2px solid var(--ink); +} + +h1, +h2, +h3, +p { margin-top: 0; } + +h1 { + margin-bottom: 7px; + font-size: clamp(28px, 4vw, 40px); + font-weight: 680; + line-height: 1.15; + letter-spacing: -0.035em; +} + +.lede { + max-width: 580px; + margin-bottom: 0; + color: var(--muted); + font-size: 15px; +} + +.selection-count { + display: flex; + flex-direction: column; + align-items: flex-end; + flex: none; + margin-bottom: 1px; + color: var(--muted); + font-size: 12px; +} + +.selection-count strong { + color: var(--accent); + font-size: 23px; + font-variant-numeric: tabular-nums; + font-weight: 650; + line-height: 1.2; +} + +.workspace { + display: grid; + grid-template-columns: minmax(0, 1fr) 280px; + gap: 48px; + padding-top: 28px; +} + +.section-heading { + display: flex; + align-items: baseline; + justify-content: space-between; + gap: 16px; + margin-bottom: 11px; +} + +.section-heading h2 { + flex: none; + margin-bottom: 0; + font-size: 16px; + font-weight: 650; +} + +.section-heading p { + margin-bottom: 0; + color: var(--muted); + font-size: 12px; + text-align: right; +} + +fieldset { + min-width: 0; + margin: 0; + padding: 0; + border: 0; +} + +.styles-list { + border-top: 1px solid var(--line); +} + +.style-row { + position: relative; + display: flex; + align-items: center; + justify-content: space-between; + gap: 20px; + min-height: 76px; + padding: 14px 12px 14px 16px; + border-bottom: 1px solid var(--line); + cursor: pointer; + transition: background-color 120ms ease; +} + +.style-row::before { + position: absolute; + inset: 14px auto 14px 0; + width: 3px; + background: transparent; + content: ""; +} + +.style-row:hover { background: rgb(255 255 255 / 55%); } +.style-row:has(input:checked) { background: var(--accent-soft); } +.style-row:has(input:checked)::before { background: var(--accent); } +.style-row:has(input:focus-visible) { outline: 3px solid var(--accent); outline-offset: 2px; } +.style-row:has(input:disabled) { cursor: default; opacity: 0.65; } + +.style-copy { + display: flex; + flex-direction: column; + gap: 3px; + min-width: 0; +} + +.style-name { + font-size: 15px; + font-weight: 620; +} + +.style-description { + max-width: 590px; + color: var(--muted); + font-size: 13px; + line-height: 1.45; +} + +.style-row input[type="checkbox"] { + flex: none; + width: 19px; + height: 19px; + margin: 0; + accent-color: var(--accent); + cursor: pointer; +} + +.style-row input[type="checkbox"]:focus-visible { + outline: 3px solid var(--accent); + outline-offset: 3px; +} + +.form-footer { + display: flex; + align-items: center; + justify-content: space-between; + gap: 20px; + min-height: 48px; + margin-top: 18px; +} + +.form-message { + margin-bottom: 0; + color: var(--muted); + font-size: 12px; +} + +.form-message.error, +.inline-error { color: var(--danger); } + +button { + min-height: 40px; + padding: 8px 18px; + border: 1px solid var(--accent); + border-radius: 5px; + background: var(--accent); + color: color-mix(in srgb, var(--accent) 15%, #fff); + cursor: pointer; + font-weight: 600; +} + +button:hover:not(:disabled) { background: color-mix(in srgb, var(--accent) 85%, #000); } + +button:focus-visible { + outline: 3px solid var(--ink); + outline-offset: 3px; +} + +button:disabled { + border-color: var(--line); + background: var(--line); + color: var(--muted); + 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; + border-top: 1px solid var(--line); + border-bottom: 1px solid var(--line); + color: var(--muted); +} + +.sr-only { + position: absolute; + width: 1px; + height: 1px; + padding: 0; + overflow: hidden; + clip: rect(0, 0, 0, 0); + white-space: nowrap; + border: 0; +} + +@media (max-width: 720px) { + .shell { + 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) { + .intro { align-items: flex-start; } + .lede { font-size: 13px; } + .selection-count strong { font-size: 19px; } + + .section-heading, + .stats-section .section-heading { + display: block; + } + + .section-heading p, + .stats-section .section-heading p { + margin-top: 4px; + text-align: left; + } + + .style-row { + gap: 12px; + padding-right: 6px; + } + + .form-footer { + align-items: stretch; + flex-direction: column; + gap: 12px; + } + + button { width: 100%; } +} + +@media (prefers-reduced-motion: reduce) { + *, + *::before, + *::after { + scroll-behavior: auto !important; + transition-duration: 0.01ms !important; + animation-duration: 0.01ms !important; + animation-iteration-count: 1 !important; + } +} diff --git a/packages/output-strategy/scripts/gen-page-catalog.mjs b/packages/output-strategy/scripts/gen-page-catalog.mjs new file mode 100644 index 0000000..27e771b --- /dev/null +++ b/packages/output-strategy/scripts/gen-page-catalog.mjs @@ -0,0 +1,30 @@ +import { writeFileSync } from "node:fs" +import { fileURLToPath } from "node:url" +import { resolve } from "node:path" +import { STYLES } from "../catalog.js" + +const output = fileURLToPath(new URL("../page/catalog.js", import.meta.url)) + +export function renderPageCatalog() { + if (!Array.isArray(STYLES) || STYLES.length !== 7) { + throw new Error("catalog.js must export exactly seven STYLES") + } + const ids = new Set() + const styles = STYLES.map(style => { + if (!style || typeof style.id !== "string" || !style.id || ids.has(style.id)) { + throw new Error("Each page style must have a unique id") + } + ids.add(style.id) + return { + id: style.id, + label: style.label, + description: style.description, + } + }) + return `globalThis.OUTPUT_STRATEGY_CATALOG = ${JSON.stringify(styles, null, 2)}\n` +} + +if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) { + writeFileSync(output, renderPageCatalog(), "utf8") + console.log(`wrote ${output}`) +} diff --git a/packages/output-strategy/test/output-strategy.test.mjs b/packages/output-strategy/test/output-strategy.test.mjs new file mode 100644 index 0000000..34e8749 --- /dev/null +++ b/packages/output-strategy/test/output-strategy.test.mjs @@ -0,0 +1,440 @@ +import { describe, expect, test } from "bun:test" + +import { + ANTISLOP_BOUNDARIES, + OUTPUT_STYLE_CATALOG, + OUTPUT_STYLE_IDS, + SAFETY_BOUNDARIES, + SHARED_BOUNDARIES, + outputStyleMeta, +} from "../catalog.js" +import { + OUTPUT_STYLE_MARKER, + applyOutputStyles, + buildOutputStylesInstruction, + hasMediaBlocks, +} from "../apply.js" +import { onRequest } from "../output-strategy.middleware.js" + +const ALL_STYLES = [ + "terse-prose", + "less-code", + "ponytail", + "i-have-adhd", + "terse-cjk", + "antislop-ui", + "antislop-copy", +] + +function chat(content = "Fix the bug") { + return { model: "test", messages: [{ role: "user", content }] } +} + +function injectedText(body) { + if (typeof body.instructions === "string") return body.instructions + if (typeof body.system === "string") return body.system + if (Array.isArray(body.system)) return body.system.map((block) => block.text).join("\n") + return body.messages.map((message) => message.content).filter((content) => typeof content === "string").join("\n") +} + +describe("catalog", () => { + test("exports the seven styles in deterministic catalog order", () => { + expect(OUTPUT_STYLE_IDS).toEqual(ALL_STYLES) + expect(Object.keys(OUTPUT_STYLE_CATALOG)).toEqual(ALL_STYLES) + for (const id of ALL_STYLES) { + expect(outputStyleMeta(id)).toBe(OUTPUT_STYLE_CATALOG[id]) + expect(OUTPUT_STYLE_CATALOG[id].id).toBe(id) + expect(OUTPUT_STYLE_CATALOG[id].label.length).toBeGreaterThan(0) + expect(OUTPUT_STYLE_CATALOG[id].instruction.length).toBeGreaterThan(0) + } + }) + + test("uses complete current upstream rules without host commands or frontmatter", () => { + const caveman = OUTPUT_STYLE_CATALOG["terse-prose"].instruction + expect(caveman).toContain("Existing comments in files you edit are payload too") + expect(caveman).toContain("Harness asks for a status line or confirmation") + expect(caveman).not.toContain("---\nname:") + expect(caveman).not.toContain("/caveman") + expect(caveman).not.toContain("Caveman mode:") + expect(caveman).not.toContain("not tracked by this host") + + const ponytail = OUTPUT_STYLE_CATALOG.ponytail.instruction + expect(ponytail).toContain("the calibration real hardware needs") + expect(ponytail).toContain("shortcut: , ") + expect(ponytail).not.toContain("/ponytail") + expect(ponytail).not.toContain("## Levels") + + const adhd = OUTPUT_STYLE_CATALOG["i-have-adhd"].instruction + expect(adhd).toContain("Never omit relevant items when completeness matters") + expect(adhd).toContain("Authorization: Bearer ${token}") + expect(adhd).not.toContain("---\nname:") + }) + + test("uses OmniRoute's current antislop full text", () => { + expect(OUTPUT_STYLE_CATALOG["antislop-ui"].instruction).toBe( + "Antislop UI filter, not a style guide. Every visual technique must pass a purpose test: it serves hierarchy, identity, or readability, and the reason is written down. Technique without purpose is removed. Color and decoration are accents, not defaults: no blue-purple gradient wash, no glass on every surface (max 1-2 elements), no glow everywhere (max 1-2 focus accents), no large shadow on every component. Radius follows one system, not pills everywhere. Palette capped at 2-3 core colors plus 1 accent. No template layout (hero plus identical card grid, bento mosaic, fake terminal hero, Trusted-By bar, 3 pricing columns). Composition follows content needs, not the AI default order.", + ) + expect(OUTPUT_STYLE_CATALOG["antislop-copy"].instruction).toBe( + "Antislop copy and human filter. Copy uses specific language, not AI defaults. Never use the em dash character. No generic CTAs (Get Started, Learn More, Try Now, Explore, Discover). No buzzwords (AI Powered, Seamless, Revolutionary, Cutting Edge, Next Generation). No chatbot closers (Hope this helps, Let me know if). No signposting announcements (Let's dive in, Here's what you need to know). No fake-candid openers (Honestly?, Real talk). Name the actor: We rewrote pricing, never pricing was updated. No forced rule-of-three trios, no not-just-X-its-Y formulas, no aphorism formulas. Never invent facts, names, numbers, or quotes. UI holds up for real people: text contrast meets WCAG AA (4.5:1 normal, 3:1 large), checked across the whole area. Never outline none without a visible focus-visible replacement. All controls reachable by keyboard (Tab, Enter or Space, Escape closes dialogs). No mouse-only patterns, no color-only status (pair with text or icon). Data views ship perceivable empty, loading, and error states. Mobile reflows with intent: no horizontal overflow, 200 percent zoom never clips text, focused input never hidden under the on-screen keyboard, tap targets at least 44px.", + ) + }) + + test("keeps shared, coding-safety and antislop boundaries", () => { + expect(SHARED_BOUNDARIES).toContain("Code blocks, file paths, commands, errors, URLs: keep exact") + expect(SAFETY_BOUNDARIES).toContain("input validation at trust boundaries") + expect(ANTISLOP_BOUNDARIES).toContain("No fabricated statistics") + expect(OUTPUT_STYLE_CATALOG["less-code"].boundaries).toBe(SAFETY_BOUNDARIES) + expect(OUTPUT_STYLE_CATALOG.ponytail.boundaries).toBe(SAFETY_BOUNDARIES) + expect(OUTPUT_STYLE_CATALOG["antislop-ui"].boundaries).toBe(ANTISLOP_BOUNDARIES) + expect(OUTPUT_STYLE_CATALOG["antislop-copy"].boundaries).toBe(ANTISLOP_BOUNDARIES) + }) +}) + +describe("instruction building", () => { + test("returns an empty instruction for no selection or only unknown ids", () => { + expect(buildOutputStylesInstruction()).toBe("") + expect(buildOutputStylesInstruction([])).toBe("") + expect(buildOutputStylesInstruction(["unknown"])).toBe("") + expect(buildOutputStylesInstruction("terse-prose")).toBe("") + }) + + test("combines selections in catalog order, not option order", () => { + const instruction = buildOutputStylesInstruction(["antislop-copy", "terse-prose", "ponytail"]) + const terse = instruction.indexOf(OUTPUT_STYLE_CATALOG["terse-prose"].instruction) + const ponytail = instruction.indexOf(OUTPUT_STYLE_CATALOG.ponytail.instruction) + const antislop = instruction.indexOf(OUTPUT_STYLE_CATALOG["antislop-copy"].instruction) + expect(terse).toBeGreaterThan(-1) + expect(ponytail).toBeGreaterThan(terse) + expect(antislop).toBeGreaterThan(ponytail) + }) + + test("deduplicates selected styles, marker and shared boundaries", () => { + const instruction = buildOutputStylesInstruction(["ponytail", "less-code", "ponytail", "antislop-ui", "antislop-copy"]) + expect(instruction.split(OUTPUT_STYLE_MARKER)).toHaveLength(2) + expect(instruction.split(SHARED_BOUNDARIES)).toHaveLength(2) + expect(instruction.split(SAFETY_BOUNDARIES)).toHaveLength(2) + expect(instruction.split(ANTISLOP_BOUNDARIES)).toHaveLength(2) + expect(instruction.indexOf(OUTPUT_STYLE_CATALOG["less-code"].instruction)).toBeLessThan( + instruction.indexOf(OUTPUT_STYLE_CATALOG.ponytail.instruction), + ) + }) + + test("accepts id entries without interpreting levels", () => { + const instruction = buildOutputStylesInstruction([{ id: "terse-cjk" }]) + expect(instruction).toContain(OUTPUT_STYLE_CATALOG["terse-cjk"].instruction) + }) +}) + +describe("Chat Completions and Anthropic injection", () => { + test("prepends a system message to an ordinary chat request", () => { + const original = chat() + const result = applyOutputStyles(original, ["terse-prose"]) + expect(result.applied).toBe(true) + expect(result.appliedStyles).toEqual(["terse-prose"]) + expect(result.body.messages).toHaveLength(2) + expect(result.body.messages[0].role).toBe("system") + expect(result.body.messages[0].content.startsWith(`${OUTPUT_STYLE_MARKER}\n`)).toBe(true) + expect(result.body.messages[1]).toEqual(original.messages[0]) + expect(original.messages).toHaveLength(1) + }) + + test("merges into a leading string system message in place", () => { + const body = { + messages: [ + { role: "system", content: " Existing rules. ", name: "rules" }, + { role: "user", content: "Hello" }, + ], + } + const result = applyOutputStyles(body, ["terse-prose"]) + expect(result.body.messages).toHaveLength(2) + expect(result.body.messages[0].name).toBe("rules") + expect(result.body.messages[0].content.startsWith(" Existing rules.\n\n")).toBe(true) + expect(body.messages[0].content).toBe(" Existing rules. ") + }) + + test("merges into a later string system message without creating messages[0]", () => { + const body = { + messages: [ + { role: "user", content: "Hello" }, + { role: "system", content: "Later rule" }, + ], + } + const result = applyOutputStyles(body, ["terse-prose"]) + expect(result.body.messages[0].role).toBe("user") + expect(result.body.messages).toHaveLength(2) + expect(result.body.messages[1].content).toContain(OUTPUT_STYLE_MARKER) + }) + + test("uses Anthropic top-level string system instead of messages[0]", () => { + const body = { ...chat(), system: "Anthropic rules" } + const result = applyOutputStyles(body, ["terse-prose"]) + expect(result.body.messages).toEqual(body.messages) + expect(result.body.messages[0].role).toBe("user") + expect(result.body.system.startsWith("Anthropic rules\n\n")).toBe(true) + expect(result.body.system).toContain(OUTPUT_STYLE_MARKER) + }) + + test("appends an Anthropic top-level text block without changing existing blocks", () => { + const block = { type: "text", text: "Anthropic rules", cache_control: { type: "ephemeral" } } + const body = { ...chat(), system: [block] } + const result = applyOutputStyles(body, ["antislop-ui"]) + expect(result.body.system).toHaveLength(2) + expect(result.body.system[0]).toBe(block) + expect(result.body.system[1].type).toBe("text") + expect(result.body.system[1].text).toContain(OUTPUT_STYLE_MARKER) + expect(body.system).toHaveLength(1) + }) + + test("uses a system message for an empty chat messages array", () => { + const result = applyOutputStyles({ messages: [] }, ["terse-prose"]) + expect(result.applied).toBe(true) + expect(result.body.messages).toHaveLength(1) + expect(result.body.messages[0].role).toBe("system") + expect(result.body.messages[0].content).toContain(OUTPUT_STYLE_MARKER) + }) + + test("uses top-level system for Anthropic without an existing system", () => { + const result = applyOutputStyles(chat(), { styles: { "terse-prose": true }, protocol: "anthropic" }) + expect(result.applied).toBe(true) + expect(result.body.system).toContain(OUTPUT_STYLE_MARKER) + expect(result.body.messages).toHaveLength(1) + expect(result.body.messages[0].role).toBe("user") + }) + + test("does not treat a marker in a user message as an injected system marker", () => { + const result = applyOutputStyles(chat(OUTPUT_STYLE_MARKER), ["terse-prose"]) + expect(result.applied).toBe(true) + }) +}) + +describe("Responses injection", () => { + const instructions = "You are Codex, a coding assistant.\nFollow the existing base instructions exactly." + const allOn = { styles: Object.fromEntries(ALL_STYLES.map(id => [id, true])) } + + test("keeps Codex instructions byte-identical with every style on", () => { + for (const input of [ + "Fix the bug", + [{ role: "user", content: [{ type: "input_text", text: "Fix it" }] }], + ]) { + const body = { input, instructions, model: "gpt-5" } + const result = applyOutputStyles(body, allOn) + expect(result.applied).toBe(true) + expect(result.body.instructions).toBe(instructions) + expect(Buffer.from(result.body.instructions).equals(Buffer.from(instructions))).toBe(true) + expect(result.body.input[0].role).toBe("developer") + expect(result.body.input[0].content[0].text).toContain(OUTPUT_STYLE_MARKER) + if (Array.isArray(input)) expect(result.body.input.at(-1)).toBe(input[0]) + else expect(result.body.input[1]).toEqual({ role: "user", content: input }) + expect(body.input).toEqual(input) + } + }) + + test("uses a separate developer input item rather than creating instructions", () => { + const result = applyOutputStyles({ messages: [], input: "Fix it" }, ["terse-prose"]) + expect(result.body.instructions).toBeUndefined() + expect(result.body.system).toBeUndefined() + expect(result.body.input[0].role).toBe("developer") + expect(result.body.input[1]).toEqual({ role: "user", content: "Fix it" }) + }) +}) + +describe("skip behavior", () => { + test("no selection and unknown selections return the original body", () => { + const body = chat() + expect(applyOutputStyles(body, []).body).toBe(body) + expect(applyOutputStyles(body, []).skippedReason).toBe("no_styles") + expect(applyOutputStyles(body, ["missing"]).applied).toBe(false) + expect(applyOutputStyles(body, null).applied).toBe(false) + }) + + test("unknown request shapes pass through", () => { + for (const body of [{ model: "test" }, { contents: [{ parts: [{ text: "Hello" }] }] }, { input: 42 }, null, "body"]) { + const result = applyOutputStyles(body, ["terse-prose"]) + expect(result.applied).toBe(false) + expect(result.body).toBe(body) + expect(result.skippedReason).toBe("no_messages") + } + }) + + test("an existing marker leaves every request shape byte-identical", () => { + const bodies = [ + { ...chat(), system: `Rules\n\n${OUTPUT_STYLE_MARKER}\nexisting` }, + { ...chat(), system: [{ type: "text", text: `${OUTPUT_STYLE_MARKER}\nexisting` }] }, + { input: "Fix it", instructions: `Codex rules\n\n${OUTPUT_STYLE_MARKER}\nexisting` }, + { input: [{ role: "developer", content: `${OUTPUT_STYLE_MARKER}\nexisting` }, { role: "user", content: "Fix it" }] }, + { ...chat(), instructions: `Old rules\n\n${OUTPUT_STYLE_MARKER}\nmore` }, + ] + for (const body of bodies) { + const serialized = JSON.stringify(body) + const result = applyOutputStyles(body, ["ponytail"]) + expect(result.applied).toBe(false) + expect(result.skippedReason).toBe("already_applied") + expect(result.body).toBe(body) + expect(JSON.stringify(result.body)).toBe(serialized) + } + }) + + 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 } + const result = applyOutputStyles(body, ["terse-prose"]) + expect(result.applied).toBe(false) + expect(result.skippedReason).toBe("unsupported_instructions_shape") + expect(result.body.instructions).toBe(instructions) + }) + + test("does not overwrite a non-string non-array system object", () => { + const system = { type: "text", text: "Proxy system" } + const body = { ...chat(), system } + const result = applyOutputStyles(body, ["terse-prose"]) + expect(result.applied).toBe(false) + expect(result.skippedReason).toBe("unsupported_system_shape") + expect(result.body.system).toBe(system) + }) + + 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"]) + expect(result.applied).toBe(false) + expect(result.body).toBe(body) + }) + + test("media remains detectable but cannot 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" } }, + { type: "file", file: { file_data: "AA==" } }, + ]) { + const body = { messages: [{ role: "user", content: [{ type: "text", text: "Inspect" }, part] }] } + const result = applyOutputStyles(body, ["terse-prose"]) + expect(result.applied).toBe(true) + expect(result.body.messages[0].role).toBe("system") + } + }) + + test("skips Anthropic images, documents and images nested in tool results", () => { + for (const content of [ + [{ type: "image", source: { type: "base64", data: "AA==" } }], + [{ type: "document", source: { type: "base64", data: "AA==" } }], + [{ type: "tool_result", content: [{ type: "image", source: { data: "AA==" } }] }], + ]) { + const body = { messages: [{ role: "user", content }] } + expect(applyOutputStyles(body, ["terse-prose"]).applied).toBe(true) + } + }) + + test("skips Responses input_image and input_file", () => { + 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("text-only turns and tool schemas mentioning image still inject", () => { + const body = { + ...chat(), + tools: [{ type: "function", function: { name: "image", parameters: { properties: { image_url: { type: "string" } } } } }], + } + const result = applyOutputStyles(body, ["terse-prose"]) + expect(result.applied).toBe(true) + expect(result.body.tools).toBe(body.tools) + }) +}) + +describe("prompt-cache stability and result metadata", () => { + test("keeps the same system blocks across turns, regardless of user wording", () => { + const originalBlocks = [ + { 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"] + for (const text of turns) { + const result = applyOutputStyles({ system: originalBlocks, ...chat(text) }, { styles: { ponytail: true } }) + expect(result.applied).toBe(true) + expect(result.body.system.slice(0, -1)).toEqual(originalBlocks) + expect(result.body.system).toHaveLength(3) + expect(result.body.system[2].text).toBe(buildOutputStylesInstruction(["ponytail"])) + } + }) + + test("an image in history does not suppress a later system block", () => { + const first = applyOutputStyles({ ...chat("Inspect"), system: "Rules" }, ["ponytail"]) + const withImage = applyOutputStyles({ + messages: [ + { role: "user", content: [{ type: "image", source: { data: "AA==" } }] }, + { role: "assistant", content: "Done" }, + { role: "user", content: "Next" }, + ], + system: "Rules", + }, ["ponytail"]) + expect(withImage.applied).toBe(true) + expect(withImage.body.system).toBe(first.body.system) + }) + + test("counts UTF-8 bytes rather than UTF-16 code units", () => { + 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) + }) +}) + +describe("middleware interface and fail-open behavior", () => { + test("onRequest returns a transformed body only when injection applies", () => { + const body = chat() + const result = onRequest(body, { options: { styles: ["terse-prose"] } }) + expect(result).not.toBe(body) + expect(injectedText(result)).toContain(OUTPUT_STYLE_MARKER) + }) + + test("onRequest returns undefined for no selection and unknown shapes", () => { + expect(onRequest(chat(), { options: { styles: [] } })).toBeUndefined() + expect(onRequest(chat(), {})).toBeUndefined() + expect(onRequest({ model: "test" }, { options: { styles: ["terse-prose"] } })).toBeUndefined() + }) + + test("onRequest leaves a previous Output Strategy block untouched", () => { + const marked = applyOutputStyles(chat(), ["terse-prose"]).body + const result = onRequest(marked, { options: { styles: ["ponytail"] } }) + expect(result).toBeUndefined() + expect(injectedText(marked)).toContain("# caveman") + expect(injectedText(marked)).not.toContain("Ponytail") + }) + + test("applyOutputStyles fails open on invalid bodies and thrown property access", () => { + expect(applyOutputStyles(undefined, ["terse-prose"]).applied).toBe(false) + const body = new Proxy({}, { + get() { + throw new Error("boom") + }, + }) + expect(() => applyOutputStyles(body, ["terse-prose"])).not.toThrow() + expect(applyOutputStyles(body, ["terse-prose"])).toEqual({ body, applied: false, skippedReason: "error" }) + }) + + test("onRequest fails open when options access throws", () => { + const ctx = new Proxy({}, { + get() { + throw new Error("boom") + }, + }) + expect(onRequest(chat(), ctx)).toBeUndefined() + }) + + test("each catalog style can be injected through the public middleware interface", () => { + for (const id of OUTPUT_STYLE_IDS) { + const result = onRequest(chat(), { options: { styles: [id] } }) + expect(result).toBeDefined() + expect(injectedText(result)).toContain(OUTPUT_STYLE_CATALOG[id].instruction) + } + }) +}) diff --git a/packages/output-strategy/test/page.test.mjs b/packages/output-strategy/test/page.test.mjs new file mode 100644 index 0000000..b7c7842 --- /dev/null +++ b/packages/output-strategy/test/page.test.mjs @@ -0,0 +1,174 @@ +import { describe, expect, test } from "bun:test" +import { readFileSync } from "node:fs" +import vm from "node:vm" +import { renderPageCatalog } from "../scripts/gen-page-catalog.mjs" + +const appSource = readFileSync(new URL("../page/app.js", import.meta.url), "utf8") +const i18nSource = readFileSync(new URL("../page/i18n.js", import.meta.url), "utf8") +const ids = ["terse-prose", "less-code", "ponytail", "i-have-adhd", "terse-cjk", "antislop-ui", "antislop-copy"] +const sampleCatalog = ids.map(id => ({ id, label: `Label ${id}`, description: `Description ${id}` })) + +class FakeElement { + constructor(tagName, id = "") { + this.tagName = tagName.toUpperCase() + this.id = id + this.children = [] + this.parentNode = null + this.attributes = {} + this.listeners = {} + this.className = "" + this.disabled = false + this.checked = false + this.type = "" + this.name = "" + this._textContent = "" + } + append(...nodes) { + for (const node of nodes) { + node.parentNode = this + this.children.push(node) + } + } + removeChild(node) { + const index = this.children.indexOf(node) + if (index !== -1) this.children.splice(index, 1) + node.parentNode = null + return node + } + 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 + } + set textContent(value) { + this._textContent = String(value) + this.children = [] + } + get textContent() { return this._textContent + this.children.map(child => child.textContent).join("") } + setAttribute(name, value) { this.attributes[name] = String(value) } + addEventListener(type, listener) { + if (!this.listeners[type]) this.listeners[type] = [] + this.listeners[type].push(listener) + } + dispatch(type) { + const event = { preventDefault() { this.defaultPrevented = true }, defaultPrevented: false } + for (const listener of this.listeners[type] || []) listener(event) + return event + } +} + +class FakeDocument { + constructor() { + this.nodes = {} + this.documentElement = {} + for (const id of ["stylesForm", "stylesFieldset", "stylesList", "saveButton", "formMessage", "selectedCount", "catalogState"]) { + this.nodes[id] = new FakeElement("div", id) + } + } + getElementById(id) { return this.nodes[id] || null } + createElement(tagName) { return new FakeElement(tagName) } +} + +function descendants(root) { return [root, ...root.children.flatMap(descendants)] } +async function settle() { + await new Promise(resolve => setTimeout(resolve, 0)) + await new Promise(resolve => setTimeout(resolve, 0)) +} + +async function boot({ catalog = sampleCatalog, current, lang = "en", failGet = false } = {}) { + const document = new FakeDocument() + const writes = [] + let onTheme + const sandbox = { + console, + document, + magpie: { + theme: { lang }, + ready: Promise.resolve({ lang }), + onTheme(callback) { onTheme = callback }, + options: { + get() { return failGet ? Promise.reject(new Error("read failed")) : Promise.resolve(current) }, + set(value) { writes.push(value); return Promise.resolve(value) }, + }, + }, + } + if (catalog !== undefined) sandbox.OUTPUT_STRATEGY_CATALOG = catalog + vm.createContext(sandbox) + vm.runInContext(i18nSource, sandbox, { filename: "page/i18n.js" }) + vm.runInContext(appSource, sandbox, { filename: "page/app.js" }) + await settle() + return { document, writes, setLang(value) { onTheme({ lang: value }) } } +} + +describe("generated page catalog", () => { + test("is current and exposes only style metadata", () => { + const source = readFileSync(new URL("../page/catalog.js", import.meta.url), "utf8") + expect(source).toBe(renderPageCatalog()) + const sandbox = {} + vm.createContext(sandbox) + vm.runInContext(source, sandbox) + expect(sandbox.OUTPUT_STRATEGY_CATALOG).toHaveLength(7) + for (const style of sandbox.OUTPUT_STRATEGY_CATALOG) { + expect(Object.keys(style).sort()).toEqual(["description", "id", "label"]) + expect(style.prompt).toBeUndefined() + } + }) +}) + +describe("page save flow", () => { + test("loads and saves complete options without inventing telemetry", async () => { + const current = { untouched: { nested: "keep" }, styles: { "terse-prose": true, "future-style": true } } + const { document, writes } = await boot({ current }) + const inputs = descendants(document.nodes.stylesList).filter(node => node.tagName === "INPUT") + expect(inputs).toHaveLength(7) + expect(inputs[0].checked).toBe(true) + expect(inputs[1].checked).toBe(false) + inputs[1].checked = true + inputs[1].dispatch("change") + const submit = document.nodes.stylesForm.dispatch("submit") + await settle() + expect(submit.defaultPrevented).toBe(true) + expect(writes).toEqual([{ + ...current, + styles: { + "terse-prose": true, "future-style": true, "less-code": true, + ponytail: false, "i-have-adhd": false, "terse-cjk": false, + "antislop-ui": false, "antislop-copy": false, + }, + }]) + expect(document.nodes.formMessage.textContent).toBe("Saved.") + expect(document.nodes.saveButton.disabled).toBe(true) + }) + + test("renders without catalog and fails closed for editing", async () => { + const { document, writes } = await boot({ catalog: null, current: { styles: {} }, failGet: true }) + expect(document.nodes.catalogState.textContent).toBe("Catalog not loaded") + expect(document.nodes.formMessage.textContent).toBe("Could not read settings; reopen the page.") + expect(document.nodes.stylesFieldset.disabled).toBe(true) + expect(document.nodes.saveButton.disabled).toBe(true) + expect(writes).toHaveLength(0) + }) +}) + +describe("host language", () => { + test("uses magpie.theme.lang and follows changes without a toggle", async () => { + const { document, setLang } = await boot({ current: { styles: {} }, lang: "zh-CN" }) + expect(document.documentElement.lang).toBe("zh-CN") + expect(document.nodes.saveButton.textContent).toBe("保存更改") + expect(document.nodes.formMessage.textContent).toBe("选择样式后保存。") + setLang("en") + expect(document.documentElement.lang).toBe("en") + expect(document.nodes.saveButton.textContent).toBe("Save changes") + expect(document.nodes.formMessage.textContent).toBe("Pick styles and save.") + }) + + test("ships English HTML and no private stats or local language switch", () => { + const html = readFileSync(new URL("../page/index.html", import.meta.url), "utf8") + expect(html).toContain('') + expect(html).not.toContain("stats.js") + expect(html).not.toContain("lang-toggle") + expect(appSource).not.toContain("__OUTPUT_STRATEGY_STATS__") + expect(i18nSource).not.toContain("localStorage") + expect(i18nSource).not.toContain("data-lang-toggle") + }) +}) diff --git a/registry.json b/registry.json index 6228c1c..f0ec104 100644 --- a/registry.json +++ b/registry.json @@ -84,6 +84,8 @@ "summary": { "en": "New API's model redirection: send a model under another name, by name or pattern; replies keep the name asked for.", "zh": "New API 的模型重定向:按名称或正则把模型换成另一个发出,回复里仍是原来的名字。" } }, { "package": "@magpie-community/middleware-system-prompt", "name": "System Prompt", "kind": "middleware", "community": true, "summary": { "en": "Add your own system prompt to every request, or only some agents' or models', in each API's own place.", "zh": "给每个请求(或指定 agent、模型)加上自己的系统提示词,放在各 API 自己的位置。" } }, + { "package": "@magpie-community/middleware-output-strategy", "name": "Output Strategy", "kind": "middleware", "community": true, + "summary": { "en": "Seven composable output styles, all off by default, with a selection panel and prompt-cache-stable injection that preserves Codex instructions.", "zh": "七种可组合的输出样式,全部默认关闭;带选择面板,注入不破坏提示缓存,也不改写 Codex instructions。" } }, { "package": "@magpie-community/middleware-word-guard", "name": "Word Guard", "kind": "middleware", "community": true, "summary": { "en": "New API's sensitive-word filter: turn away or mask words and patterns in what you send, and in replies.", "zh": "New API 的敏感词过滤:拒绝或替换你发出的内容和回复里的词与正则。" } }, { "package": "@magpie-community/middleware-think-tags", "name": "Think Tags", "kind": "middleware", "community": true,