diff --git a/packages/fovea/CHANGELOG.md b/packages/fovea/CHANGELOG.md new file mode 100644 index 0000000..977cff5 --- /dev/null +++ b/packages/fovea/CHANGELOG.md @@ -0,0 +1,49 @@ +# Changelog + +本文件记录 fovea 的对外变化。格式遵循 [Keep a Changelog](https://keepachangelog.com/zh-CN/1.1.0/),版本遵循语义化版本。 + +## [0.2.2] — 2026-11-04 + +### Fixed + +- `saccade: "auto"` 的话题判定改用与任务豁免同一口径的「任务」:首条回答之前的前导 user 消息中的最后一条。Codex 形状下首条 user 是 AGENTS.md,旧规则拿它比对,于是同一任务的跟进被判成换话题、任务与工具输出整段折叠;反过来,真换题但碰巧与 AGENTS.md 同词时又不折叠。两向各有用例。 + +### Changed + +- `live-benchmark.mjs` 不再随包发布(它会改写运行中 magpie 的插件选项),只留在仓库里。 +- README 快速上手不再预设 `saccade: "auto"`,改为说明默认 `off` 适合带缓存的长工具循环,`auto` 的取舍写在旁边。 + +## [0.2.1] — 2026-11-03 + +### Fixed + +- 旧图片换成注记时保留块的 `cache_control`——那是供应商缓存的一个断点,静默丢掉会少一个命中位(两模式均保留,有用例)。 +- 任务豁免从「第一条 user 消息」改为「首条回答之前的整段前导」:Codex 形状下 AGENTS.md 与 environment_context 在任务之前,旧规则保护的是 AGENTS.md、裁的是真任务;新规则在首条 assistant 回复 / 工具调用 / reasoning 处截止。 + +## [0.2.0] — 2026-11-02 + +fovea 首个版本。前身是本仓的 `context-slim` 草稿(PR #467,已关闭),在[独立开发仓 webkubor/fovea](https://github.com/webkubor/fovea) 成型后回到这里;与该仓同源同版。 + +### Added + +- `cut_step`:裁剪边界按块移动,块内已裁前缀逐字节稳定,供应商 prompt cache 可连续命中;不足一块不动。附连续两轮与跨块边界的回归测试。 +- `saccade`(`off` / `auto` / `always`):最新问题与首条任务词面重叠趋近零时,旧上下文折叠为一行 `[fovea: prior topic not carried]`;「继续」类短跟进不触发。 +- `state_marker`:agent 自带结构化状态块的契约——带标记的消息在两种模式下都完整,且原始任务消息随之可裁。 +- `protect` 正则在折叠模式下同样生效。 +- Responses API `function_call_output` 的数组 `output` 与字符串形式对称处理,`call_id` 永不动。 +- 证据体系:`benchmark.mjs`(同一请求前后对照、共同前缀占比、已裁前缀逐字稳定)、`live-benchmark.mjs`(同模型 ABBA 受控实测,退出恢复插件选项)、插件内证据页(零权限、不联网、不保存正文)。 +- `keep_recent_tokens` 预算窗口;品牌资产(logo 双色 / banner);`bun test` 27 例离线全绿。 + +### Changed + +- 更名 `context-slim` → `fovea`,标记从 `[context-slim: …]` 改为 `[fovea: …]`;名字即机制——中央凹看得清、周边视野只剩轮廓,saccade 是视线跳向新目标。 + +### Fixed + +- 早期草稿中 `cut_step` 把不足一块的历史量化到 0、从不裁剪的问题。 +- `keep_recent_tokens` 走窗停在溢出消息上、恰好保护了预算本应放弃的巨型消息的问题(评审 §1 修复过程中发现)。 +- 旧版 `isImage` 把 document 块当图片换成注记的问题;代理对在头尾两端的劈开问题。 + +## [0.1.0] — 2026-10-28 + +- 初版:旧工具输出与长文本留头尾,旧图换注记,消息条数/顺序/id/配对不变。 diff --git a/packages/fovea/LICENSE b/packages/fovea/LICENSE new file mode 100644 index 0000000..af1ca36 --- /dev/null +++ b/packages/fovea/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 webkubor + +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/fovea/README.md b/packages/fovea/README.md new file mode 100644 index 0000000..838cf2d --- /dev/null +++ b/packages/fovea/README.md @@ -0,0 +1,100 @@ +
+ +fovea — keep the recent window sharp + +# @magpie-community/middleware-fovea + +**magpie 网关中间件:最近窗口看得清,之前的旧历史只带轮廓。** + +[![License: MIT](https://img.shields.io/badge/License-MIT-2f63a2.svg?style=for-the-badge)](LICENSE) +[![Release](https://img.shields.io/badge/release-v0.2.2-2f63a2.svg?style=for-the-badge)](https://github.com/webkubor/fovea/releases) +[![Tests](https://img.shields.io/badge/tests-31%2F31-brightgreen?style=for-the-badge)](#证据三层各管什么) +[![Platform](https://img.shields.io/badge/magpie-middleware-8a6bbf?style=for-the-badge)](https://usemagpie.ai) +[![Runtime](https://img.shields.io/badge/runtime-moejs%20%C2%B7%20zero%20deps-4a5568?style=for-the-badge)](fovea.middleware.js) + +
+ +--- + +一个会读文件、跑命令的 coding agent,历史很快堆到几十万 token——其中大头是很多轮之前的工具输出。**这些内容每发一次请求都要重新计费一次,而它们是整段历史里寿命最短的部分。** fovea 在网关上把它裁薄:最近窗口原样保留,旧工具输出和长文本只留头尾,几轮前的图换成一行注记。 + +## 🏆 为什么是 fovea + +| | 整段历史重发 | agent 自带 `/compact` | [history-trim](https://github.com/magpie-community/plugins/tree/main/packages/history-trim) | **fovea** | +|---|:---:|:---:|:---:|:---:| +| 旧工具输出留头尾、中间省略 | ❌ | ❌ 交给摘要 | ❌ 只折空白/去重 | ✅ | +| 换话题时不携带旧上下文(saccade) | ❌ | 部分,打断式 | ❌ | ✅ | +| 缓存友好的裁剪边界(cut_step 分块) | — | ❌ 摘要必失配 | ❌ | ✅ | +| 工具调用配对永远完整(三种请求形状) | ✅ | ⚠️ 摘要丢失 | ✅ | ✅ | +| Provider 无关,agent 零改造 | ✅ | ❌ 每个 agent 各自实现 | ✅ | ✅ | +| 自带证据页:前后对照 / 缓存稳定性 / A/B | ❌ | ❌ | ❌ | ✅ | + +## 🔥 四件事 + +- 👁️ **中央凹视觉模型** —— 最近 `keep_recent` 条消息逐字不动;更早的内容像周边视野,只剩轮廓(头+尾+省略标记)。消息条数、顺序、id、工具配对一个不少。 +- 📦 **saccade:换话题就不带旧的** —— 最新问题与首条任务几乎无共同词时,旧上下文折叠成一行注记。「继续」这类短跟进不会误触发。 +- 🧊 **cut_step:为 prompt cache 而生** —— 裁剪边界只按块移动,块内已裁前缀逐字节稳定,缓存能连续命中;跨块才失效一次(这是对上游评审 §1 的正面回答,有两轮回归测试锁死)。 +- 🧾 **state_marker:你的结构化状态取代原始任务消息** —— agent 自己维护的任务/约束/决策 JSON 块永不被裁,同时原始任务原文不再享受豁免,按普通旧内容裁掉。 + +## ⚡ 30 秒上手 + +```sh +magpie plugin add @magpie-community/middleware-fovea +magpie plugin options fovea '{"state_marker":""}' +``` + +默认 `saccade: "off"`,适合带 prompt cache 的长工具循环(coding agent 的常态)。话题经常切换、又不在乎缓存的对话,可以设成 `"auto"`:换话题时旧上下文整段不带,代价是每次判定为换题都会打断一次缓存前缀。 + +装完在 magpie 窗口 **Plugins › Fovea evidence** 打开证据页:粘贴你自己的请求 JSON,浏览器里现算前后差异(不联网、不保存正文)。想先看代码再装: + +```sh +git clone https://github.com/magpie-community/plugins && bun test packages/fovea # 31/31 +``` + +--- + +## 它怎么工作 + +`onRequest` 收到请求后:请求小于 `threshold` 原样放行;否则窗口(按条数与 token 预算取宽者)之前的旧消息逐条裁剪。Chat(`role:"tool"`)、Anthropic(`tool_result` 块)、Responses API(`function_call_output`)三种形状各自处理;无法识别的形状原样通过。已经带 `[fovea: …]` 标记的内容不再二次裁剪。失败即放行(fail open)。 + +| 选项 | 默认 | 含义 | +|---|---|---| +| `threshold` | `96000` | 请求字符数超过才动手(约 24k token;`0` 总是动手) | +| `keep_recent` / `keep_recent_tokens` | `12` / `16000` | 最近窗口,按条数与 token 预算取更宽者;`0` 关闭预算 | +| `cut_step` | `24` | 裁剪边界按块移动,块内前缀逐字稳定;不足一块不动(省缓存),要随裁随减设 `1` | +| `tool_head` / `tool_tail` | `600` / `300` | 旧工具输出保留的头尾 | +| `text_head` / `text_tail` | `1200` / `400` | 旧文本保留的头尾 | +| `drop_old_images` | `true` | 窗口外的旧图换成 `[fovea: old image omitted]` | +| `protect` | `[]` | 命中即整段保全的正则(两种模式都生效),如 `["^diff --git ", "BEGIN .*PRIVATE KEY"]` | +| `saccade` | `"off"` | `off` 留头尾;`auto` 词面判定换话题后折叠旧内容;`always` 总是折叠 | +| `state_marker` | `""` | 你的结构化状态块的标记;带标记的消息永不裁,且任务原文随之可裁 | + +裁剪长这样: + +``` +…600 chars… +[fovea: 48213 chars of old tool output omitted] +…300 chars… +``` + +## 证据三层,各管什么 + +1. **规则正确性** —— `bun test`:31 个确定性用例(离线、零依赖)。覆盖三种形状的工具配对、protect 在两种模式下生效、代理对不劈开、document 块不动、标记幂等、连续两轮已裁前缀逐字节相同。 +2. **同一请求确实变小** —— `bun benchmark.mjs [request.json] [options]`,或直接在证据页粘贴你的请求。合成样例:47,777 → 14,148 字符,已裁的 27 条消息逐字稳定。 +3. **真实 token / 缓存 / 费用** —— `FOVEA_GATEWAY_KEY=<临时key> bun live-benchmark.mjs`:同模型、同请求、ABBA 四连发,记录供应商返回的 input / cache_read / output token 与耗时,只看暖缓存的第二次。0.1.0 时代的一次实测:163,143 → 42,358 prompt tokens,中位延迟 7.1s → 2.5s(因历史形状与供应商缓存而异)。**账单以 `magpie usage --csv` 的 `cost_usd` 为准;字符百分比不是美元。** + +## 结构化状态优于压缩 + +最便宜的历史是根本不用发的历史。`state_marker` 是两边之间的契约:状态块永不被裁,任务原文不再豁免。[`state-block.example.json`](state-block.example.json) 给了固定维度的形状(目标/验收/约束/决策/带出处的事实/未决问题)。两条让它便宜的规则: + +- **分两层**:少变的字段(目标、约束、决策)进块、放请求前部;每轮变的(当前步、最近命令结果)放最后一条消息——每轮重写整个块会把它之后的缓存全部打掉。 +- **每条事实带出处**:替换能去掉旧值,但去不掉错值——新不等于对。带出处的错能被便宜地重读发现。 + +## 什么时候不该用 + +窗口按条数+预算共同划定,最近窗口里的巨型消息仍然原样保留。裁剪是机械的:它不知道哪条旧细节重要,只知道头尾在哪——如果 agent 的工作依赖逐字重读旧输出,调大 `tool_head`/`tool_tail` 或暂时关掉。`saccade: auto` 是词面判定不是语义理解:改述会被误判、同词异题会漏判,长缓存循环建议 `off`。放在 system/developer 或最近窗口里的压缩摘要不归 fovea 管——那要在生成请求之前决定。缩短历史是否影响答案质量,请在你自己的负载上以开/关对照验证。 + +## 发布物 + +- [CHANGELOG.md](CHANGELOG.md) · [LICENSE](LICENSE)(MIT)· banner 与品牌资产在[独立开发仓](https://github.com/webkubor/fovea/tree/main/brand),包内只带页面图标 +- 致谢:yetone 对早期草稿与本次 PR 的评审直接塑造了缓存边界、document、代理对、cache_control 与前导任务保护 diff --git a/packages/fovea/benchmark.mjs b/packages/fovea/benchmark.mjs new file mode 100644 index 0000000..0c95c43 --- /dev/null +++ b/packages/fovea/benchmark.mjs @@ -0,0 +1,111 @@ +// A reproducible, offline A/B on the same request. No prompt body is +// written to the report: only counts and prefix comparisons leave here. +// +// bun packages/fovea/benchmark.mjs +// bun packages/fovea/benchmark.mjs /path/to/request.json +// bun packages/fovea/benchmark.mjs /path/to/request.json '{"saccade":"auto"}' +// +// The report is read by this package's page. It is not a cost claim: +// actual provider input/cache tokens and cost need a controlled live A/B. +import { readFileSync, writeFileSync } from "node:fs" +import { dirname, join } from "node:path" +import { fileURLToPath } from "node:url" +import { onRequest } from "./fovea.middleware.js" + +const HERE = dirname(fileURLToPath(import.meta.url)) +const DEFAULTS = { + threshold: 0, keep_recent: 4, keep_recent_tokens: 0, cut_step: 4, + tool_head: 80, tool_tail: 40, text_head: 120, text_tail: 60, + saccade: "off", +} +const clone = (v) => JSON.parse(JSON.stringify(v)) +const chars = (v) => JSON.stringify(v).length + +function fixture(rounds = 16, question = "Finish the module and explain the result") { + const messages = [{ role: "user", content: "Implement a parser and check every test" }] + for (let n = 0; n < rounds; n++) { + messages.push({ role: "assistant", content: "Read the next file", tool_calls: [ + { id: `read_${n}`, type: "function", function: { name: "read_file", arguments: "{}" } }, + ] }) + messages.push({ role: "tool", tool_call_id: `read_${n}`, content: `FILE ${n}\n` + `line ${n}: parser trace and test result\n`.repeat(72) }) + } + messages.push({ role: "user", content: question }) + return { model: "example-model", messages } +} + +function transform(raw, options) { + const body = clone(raw) + onRequest(body, { options }) + return body +} + +function commonPrefix(a, b) { + const max = Math.min(a.length, b.length) + let i = 0 + while (i < max && a.charCodeAt(i) === b.charCodeAt(i)) i++ + return i +} + +function messages(body) { + return Array.isArray(body.messages) ? body.messages : Array.isArray(body.input) ? body.input : [] +} + +function compare(raw, options) { + const result = transform(raw, options) + const a = messages(raw) + const b = messages(result) + return { + before: chars(raw), after: chars(result), + saved: chars(raw) - chars(result), + changed: a.reduce((n, item, i) => n + (JSON.stringify(item) !== JSON.stringify(b[i]) ? 1 : 0), 0), + messages: a.length, + } +} + +export function benchmark(raw = fixture(), options = DEFAULTS, source = "synthetic") { + if (!raw || (!Array.isArray(raw.messages) && !Array.isArray(raw.input))) throw new Error("request must have messages or input array") + const fixed = { ...DEFAULTS, ...options } + const before = compare(raw, { ...fixed, threshold: 1_000_000_000 }) + const after = compare(raw, fixed) + const pairA = fixture(15) + const pairB = fixture(16) + const baselineA = JSON.stringify(pairA) + const baselineB = JSON.stringify(pairB) + const transformedA = transform(pairA, fixed) + const transformedB = transform(pairB, fixed) + const processedA = JSON.stringify(transformedA) + const processedB = JSON.stringify(transformedB) + const baselinePrefix = commonPrefix(baselineA, baselineB) + const processedPrefix = commonPrefix(processedA, processedB) + const oldA = messages(pairA) + const slimA = messages(transformedA) + const slimB = messages(transformedB) + let cutEnd = 0 + for (let i = 0; i < oldA.length; i++) { + if (JSON.stringify(oldA[i]) !== JSON.stringify(slimA[i])) cutEnd = i + 1 + } + const stablePrefix = cutEnd > 0 && JSON.stringify(slimA.slice(0, cutEnd)) === JSON.stringify(slimB.slice(0, cutEnd)) + return { + version: 1, source, options: fixed, + request: { before: before.before, after: after.after, saved: after.saved, changed: after.changed, messages: after.messages }, + consecutive: { + first_messages: oldA.length, second_messages: messages(pairB).length, + baseline_prefix_chars: baselinePrefix, fovea_prefix_chars: processedPrefix, + baseline_prefix_share: baselinePrefix / baselineA.length, + fovea_prefix_share: processedPrefix / processedA.length, + stable_cut_messages: cutEnd, + stable_cut_prefix: stablePrefix, + }, + limits: "字符数与共同前缀占比是确定性的代理指标,不是计费 token、缓存命中、延迟或实际美元;system/developer 与最近窗口里的摘要仍会发送。", + } +} + +if (process.argv[1] === fileURLToPath(import.meta.url)) { + const arg = process.argv[2] + const raw = arg ? JSON.parse(readFileSync(arg, "utf8")) : fixture() + const options = process.argv[3] ? JSON.parse(process.argv[3]) : DEFAULTS + const report = benchmark(raw, options, arg ? "local request (content omitted)" : "synthetic") + const out = join(HERE, "page", "report.js") + writeFileSync(out, `globalThis.FoveaReport = ${JSON.stringify(report, null, 2)};\n`) + console.log(JSON.stringify({ report: out, ...report.request, consecutive: report.consecutive }, null, 2)) +} diff --git a/packages/fovea/build.mjs b/packages/fovea/build.mjs new file mode 100644 index 0000000..7403e42 --- /dev/null +++ b/packages/fovea/build.mjs @@ -0,0 +1,23 @@ +// Builds page/measure.js from fovea.middleware.js: the middleware is one +// file with one export and no imports, so the page's copy is the same +// source with the export turned into a global. magpie serves a page's own +// folder only — ../fovea.middleware.js is a 404 inside the sandbox — so +// the page needs this bundle beside it. +// +// The test suite regenerates and compares, so a stale bundle fails CI, +// not the page. Run after changing the middleware: +// +// bun build.mjs +import { readFileSync, writeFileSync } from "node:fs" +import { dirname, join } from "node:path" +import { fileURLToPath } from "node:url" + +const HERE = dirname(fileURLToPath(import.meta.url)) +const src = readFileSync(join(HERE, "fovea.middleware.js"), "utf8") +const out = src.replace( + "export function onRequest(", + "function onRequest(", +) + "\nglobalThis.FoveaOnRequest = onRequest;\n" +if (out === src) throw new Error("fovea.middleware.js no longer exports onRequest the way build.mjs expects") +writeFileSync(join(HERE, "page", "measure.js"), out) +console.log("page/measure.js written,", out.length, "bytes") diff --git a/packages/fovea/cases.json b/packages/fovea/cases.json new file mode 100644 index 0000000..f2a4a62 --- /dev/null +++ b/packages/fovea/cases.json @@ -0,0 +1,1036 @@ +[ + { + "name": "under the threshold the request passes as it came", + "options": {}, + "request": { + "model": "m", + "messages": [ + { + "role": "user", + "content": "hi" + }, + { + "role": "assistant", + "content": "hello" + } + ] + } + }, + { + "name": "an old Chat tool result is cut to head and tail; ids, tool_calls and the recent window stay", + "options": { + "threshold": 0, + "keep_recent": 1, + "keep_recent_tokens": 0, + "tool_head": 10, + "tool_tail": 5, + "text_head": 20, + "text_tail": 5, + "cut_step": 1 + }, + "request": { + "model": "m", + "messages": [ + { + "role": "user", + "content": "read the logs" + }, + { + "role": "assistant", + "content": "reading", + "tool_calls": [ + { + "id": "call_1", + "type": "function", + "function": { + "name": "read", + "arguments": "{}" + } + } + ] + }, + { + "role": "tool", + "tool_call_id": "call_1", + "content": "LLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL" + }, + { + "role": "assistant", + "content": "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" + }, + { + "role": "user", + "content": "summarize" + } + ] + }, + "expect_request": { + "model": "m", + "messages": [ + { + "role": "user", + "content": "read the logs" + }, + { + "role": "assistant", + "content": "reading", + "tool_calls": [ + { + "id": "call_1", + "type": "function", + "function": { + "name": "read", + "arguments": "{}" + } + } + ] + }, + { + "role": "tool", + "tool_call_id": "call_1", + "content": "LLLLLLLLLL\n[fovea: 285 chars of old tool output omitted]\nLLLLL" + }, + { + "role": "assistant", + "content": "XXXXXXXXXXXXXXXXXXXX\n[fovea: 275 chars of old text omitted]\nXXXXX" + }, + { + "role": "user", + "content": "summarize" + } + ] + } + }, + { + "name": "the first user message is kept whole, an old reply is cut", + "options": { + "threshold": 0, + "keep_recent": 1, + "keep_recent_tokens": 0, + "tool_head": 10, + "tool_tail": 5, + "text_head": 20, + "text_tail": 5, + "cut_step": 1 + }, + "request": { + "model": "m", + "messages": [ + { + "role": "user", + "content": "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" + }, + { + "role": "assistant", + "content": "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" + }, + { + "role": "user", + "content": "ok" + } + ] + }, + "expect_request": { + "model": "m", + "messages": [ + { + "role": "user", + "content": "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" + }, + { + "role": "assistant", + "content": "XXXXXXXXXXXXXXXXXXXX\n[fovea: 275 chars of old text omitted]\nXXXXX" + }, + { + "role": "user", + "content": "ok" + } + ] + } + }, + { + "name": "an image older than the window becomes a note; a recent image stays", + "options": { + "threshold": 0, + "keep_recent": 1, + "keep_recent_tokens": 0, + "tool_head": 10, + "tool_tail": 5, + "text_head": 20, + "text_tail": 5, + "cut_step": 1 + }, + "request": { + "model": "m", + "messages": [ + { + "role": "user", + "content": "we will look at a chart later" + }, + { + "role": "assistant", + "content": "ok" + }, + { + "role": "user", + "content": [ + { + "type": "text", + "text": "look" + }, + { + "type": "image_url", + "image_url": { + "url": "data:image/png;base64,AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + } + } + ] + }, + { + "role": "assistant", + "content": "seen" + }, + { + "role": "user", + "content": [ + { + "type": "image_url", + "image_url": { + "url": "data:image/png;base64,BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB" + } + } + ] + } + ] + }, + "expect_request": { + "model": "m", + "messages": [ + { + "role": "user", + "content": "we will look at a chart later" + }, + { + "role": "assistant", + "content": "ok" + }, + { + "role": "user", + "content": [ + { + "type": "text", + "text": "look" + }, + { + "type": "text", + "text": "[fovea: old image omitted]" + } + ] + }, + { + "role": "assistant", + "content": "seen" + }, + { + "role": "user", + "content": [ + { + "type": "image_url", + "image_url": { + "url": "data:image/png;base64,BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB" + } + } + ] + } + ] + } + }, + { + "name": "an old Anthropic tool_result is cut and its image noted; tool_use and system stay whole", + "options": { + "threshold": 0, + "keep_recent": 1, + "keep_recent_tokens": 0, + "tool_head": 10, + "tool_tail": 5, + "text_head": 20, + "text_tail": 5, + "cut_step": 1 + }, + "request": { + "model": "m", + "system": "be brief", + "messages": [ + { + "role": "user", + "content": [ + { + "type": "text", + "text": "read it" + } + ] + }, + { + "role": "assistant", + "content": [ + { + "type": "text", + "text": "calling" + }, + { + "type": "tool_use", + "id": "tu_1", + "name": "read", + "input": { + "path": "a.log" + } + } + ] + }, + { + "role": "user", + "content": [ + { + "type": "tool_result", + "tool_use_id": "tu_1", + "content": [ + { + "type": "text", + "text": "LLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL" + }, + { + "type": "image", + "source": { + "type": "base64", + "data": "CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC" + } + } + ] + }, + { + "type": "text", + "text": "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" + } + ] + }, + { + "role": "user", + "content": "go on" + } + ] + }, + "expect_request": { + "model": "m", + "system": "be brief", + "messages": [ + { + "role": "user", + "content": [ + { + "type": "text", + "text": "read it" + } + ] + }, + { + "role": "assistant", + "content": [ + { + "type": "text", + "text": "calling" + }, + { + "type": "tool_use", + "id": "tu_1", + "name": "read", + "input": { + "path": "a.log" + } + } + ] + }, + { + "role": "user", + "content": [ + { + "type": "tool_result", + "tool_use_id": "tu_1", + "content": [ + { + "type": "text", + "text": "LLLLLLLLLL\n[fovea: 285 chars of old tool output omitted]\nLLLLL" + }, + { + "type": "text", + "text": "[fovea: old image omitted]" + } + ] + }, + { + "type": "text", + "text": "XXXXXXXXXXXXXXXXXXXX\n[fovea: 275 chars of old text omitted]\nXXXXX" + } + ] + }, + { + "role": "user", + "content": "go on" + } + ] + } + }, + { + "name": "content already carrying the marker is left alone", + "options": { + "threshold": 0, + "keep_recent": 1, + "keep_recent_tokens": 0, + "tool_head": 10, + "tool_tail": 5, + "text_head": 20, + "text_tail": 5, + "cut_step": 1 + }, + "request": { + "model": "m", + "messages": [ + { + "role": "user", + "content": "task" + }, + { + "role": "tool", + "tool_call_id": "c", + "content": "LLLLLLLLLL\n[fovea: 285 chars of old tool output omitted]\nLLLLL" + }, + { + "role": "user", + "content": "ok" + } + ] + } + }, + { + "name": "a history inside the window is untouched", + "options": { + "threshold": 0, + "keep_recent": 5, + "keep_recent_tokens": 0, + "tool_head": 10, + "tool_tail": 5, + "cut_step": 1 + }, + "request": { + "model": "m", + "messages": [ + { + "role": "user", + "content": "task" + }, + { + "role": "tool", + "tool_call_id": "c", + "content": "LLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL" + }, + { + "role": "user", + "content": "ok" + } + ] + } + }, + { + "name": "null content, empty tool output and tool_calls pass unchanged", + "options": { + "threshold": 0, + "keep_recent": 1, + "keep_recent_tokens": 0, + "tool_head": 10, + "tool_tail": 5, + "text_head": 20, + "text_tail": 5, + "cut_step": 1 + }, + "request": { + "model": "m", + "messages": [ + { + "role": "user", + "content": "task" + }, + { + "role": "assistant", + "content": null, + "tool_calls": [ + { + "id": "c", + "type": "function", + "function": { + "name": "f", + "arguments": "{}" + } + } + ] + }, + { + "role": "tool", + "tool_call_id": "c", + "content": "" + }, + { + "role": "user", + "content": "ok" + } + ] + } + }, + { + "name": "system messages are never touched", + "options": { + "threshold": 0, + "keep_recent": 1, + "keep_recent_tokens": 0, + "tool_head": 10, + "tool_tail": 5, + "text_head": 20, + "text_tail": 5, + "cut_step": 1 + }, + "request": { + "model": "m", + "messages": [ + { + "role": "system", + "content": "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" + }, + { + "role": "user", + "content": "task" + }, + { + "role": "assistant", + "content": "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" + }, + { + "role": "user", + "content": "ok" + } + ] + }, + "expect_request": { + "model": "m", + "messages": [ + { + "role": "system", + "content": "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" + }, + { + "role": "user", + "content": "task" + }, + { + "role": "assistant", + "content": "XXXXXXXXXXXXXXXXXXXX\n[fovea: 275 chars of old text omitted]\nXXXXX" + }, + { + "role": "user", + "content": "ok" + } + ] + } + }, + { + "name": "a token budget keeps few but large recent messages whole", + "options": { + "threshold": 0, + "keep_recent": 1, + "keep_recent_tokens": 150, + "tool_head": 10, + "tool_tail": 5, + "text_head": 20, + "text_tail": 5, + "cut_step": 1 + }, + "request": { + "model": "m", + "messages": [ + { + "role": "user", + "content": "task" + }, + { + "role": "tool", + "tool_call_id": "c", + "content": "LLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL" + }, + { + "role": "user", + "content": "ok" + }, + { + "role": "assistant", + "content": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + }, + { + "role": "user", + "content": "final" + } + ] + }, + "expect_request": { + "model": "m", + "messages": [ + { + "role": "user", + "content": "task" + }, + { + "role": "tool", + "tool_call_id": "c", + "content": "LLLLLLLLLL\n[fovea: 285 chars of old tool output omitted]\nLLLLL" + }, + { + "role": "user", + "content": "ok" + }, + { + "role": "assistant", + "content": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + }, + { + "role": "user", + "content": "final" + } + ] + } + }, + { + "name": "a protect pattern keeps a matching tool result whole", + "options": { + "threshold": 0, + "keep_recent": 1, + "keep_recent_tokens": 0, + "tool_head": 10, + "tool_tail": 5, + "text_head": 20, + "text_tail": 5, + "protect": [ + "^diff --git " + ], + "cut_step": 1 + }, + "request": { + "model": "m", + "messages": [ + { + "role": "user", + "content": "task" + }, + { + "role": "tool", + "tool_call_id": "c", + "content": "diff --git a/x b/x\n++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++" + }, + { + "role": "user", + "content": "ok" + } + ] + } + }, + { + "name": "a Responses API function_call_output is cut, call_id and function_call stay", + "options": { + "threshold": 0, + "keep_recent": 1, + "keep_recent_tokens": 0, + "tool_head": 10, + "tool_tail": 5, + "text_head": 20, + "text_tail": 5, + "cut_step": 1 + }, + "request": { + "model": "m", + "input": [ + { + "type": "message", + "role": "user", + "content": [ + { + "type": "input_text", + "text": "read it" + } + ] + }, + { + "type": "function_call", + "call_id": "c1", + "name": "read", + "arguments": "{}" + }, + { + "type": "function_call_output", + "call_id": "c1", + "output": "LLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL" + }, + { + "type": "message", + "role": "user", + "content": [ + { + "type": "input_text", + "text": "final" + } + ] + } + ] + }, + "expect_request": { + "model": "m", + "input": [ + { + "type": "message", + "role": "user", + "content": [ + { + "type": "input_text", + "text": "read it" + } + ] + }, + { + "type": "function_call", + "call_id": "c1", + "name": "read", + "arguments": "{}" + }, + { + "type": "function_call_output", + "call_id": "c1", + "output": "LLLLLLLLLL\n[fovea: 285 chars of old tool output omitted]\nLLLLL" + }, + { + "type": "message", + "role": "user", + "content": [ + { + "type": "input_text", + "text": "final" + } + ] + } + ] + } + }, + { + "name": "an invalid protect pattern is ignored, the rest still cuts", + "options": { + "threshold": 0, + "keep_recent": 1, + "keep_recent_tokens": 0, + "tool_head": 10, + "tool_tail": 5, + "text_head": 20, + "text_tail": 5, + "protect": [ + "([" + ], + "cut_step": 1 + }, + "request": { + "model": "m", + "messages": [ + { + "role": "user", + "content": "task" + }, + { + "role": "tool", + "tool_call_id": "c", + "content": "LLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL" + }, + { + "role": "user", + "content": "ok" + } + ] + }, + "expect_request": { + "model": "m", + "messages": [ + { + "role": "user", + "content": "task" + }, + { + "role": "tool", + "tool_call_id": "c", + "content": "LLLLLLLLLL\n[fovea: 285 chars of old tool output omitted]\nLLLLL" + }, + { + "role": "user", + "content": "ok" + } + ] + } + }, + { + "name": "saccade always: old tool output and old text collapse to one note; short ack, ids, tool_calls and the window stay", + "options": { + "threshold": 0, + "keep_recent": 1, + "keep_recent_tokens": 0, + "tool_head": 10, + "tool_tail": 5, + "text_head": 20, + "text_tail": 5, + "saccade": "always", + "cut_step": 1 + }, + "request": { + "model": "m", + "messages": [ + { + "role": "user", + "content": "deploy the terraform stack to fly io region iad and check the dns records afterwards please" + }, + { + "role": "assistant", + "content": "reading", + "tool_calls": [ + { + "id": "call_1", + "type": "function", + "function": { + "name": "read", + "arguments": "{}" + } + } + ] + }, + { + "role": "tool", + "tool_call_id": "call_1", + "content": "LLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL" + }, + { + "role": "assistant", + "content": "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" + }, + { + "role": "user", + "content": "what next" + } + ] + }, + "expect_request": { + "model": "m", + "messages": [ + { + "role": "user", + "content": "deploy the terraform stack to fly io region iad and check the dns records afterwards please" + }, + { + "role": "assistant", + "content": "reading", + "tool_calls": [ + { + "id": "call_1", + "type": "function", + "function": { + "name": "read", + "arguments": "{}" + } + } + ] + }, + { + "role": "tool", + "tool_call_id": "call_1", + "content": "[fovea: prior topic not carried]" + }, + { + "role": "assistant", + "content": "[fovea: prior topic not carried]" + }, + { + "role": "user", + "content": "what next" + } + ] + } + }, + { + "name": "saccade auto: a new topic in the newest question drops the old context; tool pairing survives as notes", + "options": { + "threshold": 0, + "keep_recent": 1, + "keep_recent_tokens": 0, + "tool_head": 10, + "tool_tail": 5, + "text_head": 20, + "text_tail": 5, + "saccade": "auto", + "cut_step": 1 + }, + "request": { + "model": "m", + "messages": [ + { + "role": "user", + "content": "deploy the terraform stack to fly io region iad" + }, + { + "role": "assistant", + "content": "reading", + "tool_calls": [ + { + "id": "call_1", + "type": "function", + "function": { + "name": "read", + "arguments": "{}" + } + } + ] + }, + { + "role": "tool", + "tool_call_id": "call_1", + "content": "LLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL" + }, + { + "role": "assistant", + "content": "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" + }, + { + "role": "user", + "content": "推荐三道家常菜的做法 番茄炒蛋 蛋炒饭 紫菜汤" + } + ] + }, + "expect_request": { + "model": "m", + "messages": [ + { + "role": "user", + "content": "deploy the terraform stack to fly io region iad" + }, + { + "role": "assistant", + "content": "reading", + "tool_calls": [ + { + "id": "call_1", + "type": "function", + "function": { + "name": "read", + "arguments": "{}" + } + } + ] + }, + { + "role": "tool", + "tool_call_id": "call_1", + "content": "[fovea: prior topic not carried]" + }, + { + "role": "assistant", + "content": "[fovea: prior topic not carried]" + }, + { + "role": "user", + "content": "推荐三道家常菜的做法 番茄炒蛋 蛋炒饭 紫菜汤" + } + ] + } + }, + { + "name": "saccade auto: a related question keeps the default head-and-tail thinning", + "options": { + "threshold": 0, + "keep_recent": 1, + "keep_recent_tokens": 0, + "tool_head": 10, + "tool_tail": 5, + "text_head": 20, + "text_tail": 5, + "saccade": "auto", + "cut_step": 1 + }, + "request": { + "model": "m", + "messages": [ + { + "role": "user", + "content": "deploy the terraform stack to fly io region iad" + }, + { + "role": "assistant", + "content": "reading", + "tool_calls": [ + { + "id": "call_1", + "type": "function", + "function": { + "name": "read", + "arguments": "{}" + } + } + ] + }, + { + "role": "tool", + "tool_call_id": "call_1", + "content": "LLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL" + }, + { + "role": "assistant", + "content": "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" + }, + { + "role": "user", + "content": "terraform stack fly io region iad dns records check please" + } + ] + }, + "expect_request": { + "model": "m", + "messages": [ + { + "role": "user", + "content": "deploy the terraform stack to fly io region iad" + }, + { + "role": "assistant", + "content": "reading", + "tool_calls": [ + { + "id": "call_1", + "type": "function", + "function": { + "name": "read", + "arguments": "{}" + } + } + ] + }, + { + "role": "tool", + "tool_call_id": "call_1", + "content": "LLLLLLLLLL\n[fovea: 285 chars of old tool output omitted]\nLLLLL" + }, + { + "role": "assistant", + "content": "XXXXXXXXXXXXXXXXXXXX\n[fovea: 175 chars of old text omitted]\nXXXXX" + }, + { + "role": "user", + "content": "terraform stack fly io region iad dns records check please" + } + ] + } + } +] diff --git a/packages/fovea/fovea.middleware.js b/packages/fovea/fovea.middleware.js new file mode 100644 index 0000000..515057e --- /dev/null +++ b/packages/fovea/fovea.middleware.js @@ -0,0 +1,506 @@ +// fovea — the focal centre of the eye. The window a request works in +// stays sharp; the history around it, like peripheral vision, stays +// present but carries only its outline. An agent that keeps its whole +// history — which is most of them, and right — stops paying to re-read +// every old file and command output on every turn. magpie's gateway does +// it on the request. Message count, order, ids and tool pairing stay as +// the agent sent them, and what is recent stays whole. Under the +// threshold the body passes as it came. +// +// {"threshold": 96000} chars of request to act above (~24k +// tokens; 0 acts on every request) +// {"keep_recent": 12} messages at the end kept whole +// {"keep_recent_tokens": 16000} the same window as a token budget; the +// larger of the two windows is kept +// {"cut_step": 24} cut boundary advances only in blocks of +// this many messages, so cached prefixes +// stay byte-identical across nearby turns +// {"tool_head": 600, "tool_tail": 300} an old tool result's kept ends +// {"text_head": 1200, "text_tail": 400} an old text message's kept ends +// {"drop_old_images": true} images older than the window → a note +// {"protect": []} regexes whose matches are left whole +// (e.g. "^diff --git ", "BEGIN .*PRIVATE KEY") +// {"state_marker": ""} a marker the agent's own structured +// state block carries. A message with the +// marker is never touched, in either mode, +// and its presence means the raw task +// message no longer needs protecting: the +// state carries the task, so that message +// is thinned like any other old content +// {"saccade": "off"} off | auto | always. A saccade is the +// eye jumping to a new target: when the +// newest question is a different topic, +// the old context is not carried at all — +// every old message long enough to matter +// collapses to one line instead of +// keeping its head and tail. "auto" judges +// by word overlap between the newest +// question and the first task message +// (a "继续" or an "ok" has no direction of +// its own and keeps the old context); +// "always" collapses on every request +// above the threshold. +// +// The system prompt and the recent window are never touched. In the +// default mode the first user message (the task) is kept whole too; on a +// saccade it is the old task, and collapses with the rest. Tool calls and +// their ids are never touched — an old tool result is shortened or +// noted, not removed, so every tool_call still has its answer. +// Already-shortened content carries the marker and is left alone, so a +// history re-sent each turn is cut once, not again. A reply is never +// touched: what the agent keeps from it is the agent's to keep. +// +// Chat (role:"tool"), Anthropic (tool_result blocks) and the Responses API +// (function_call_output items) are read in their own shapes; a body in +// none of them passes as it came. + +const MARK = "fovea" +const NOTE = "[" + MARK + ": prior topic not carried]" +const NOTE_MIN = 160 // below this a saccade leaves old text as it is +const SHIFT_OVERLAP = 0.08 // shared-word ratio under which a topic counts as new + +export function onRequest(body, ctx) { + try { + if (!body || typeof body !== "object") return + const o = ctx && ctx.options && typeof ctx.options === "object" ? ctx.options : {} + const cfg = { + threshold: num(o.threshold, 96000), + keepRecent: num(o.keep_recent, 12), + keepTokens: num(o.keep_recent_tokens, 16000), + cutStep: Math.max(1, num(o.cut_step, 24)), + toolHead: num(o.tool_head, 600), + toolTail: num(o.tool_tail, 300), + textHead: num(o.text_head, 1200), + textTail: num(o.text_tail, 400), + dropImages: o.drop_old_images !== false, + protect: patterns(o.protect), + stateMarker: typeof o.state_marker === "string" ? o.state_marker : "", + saccade: o.saccade === "auto" || o.saccade === "always" ? o.saccade : "off", + } + + // Chat and Anthropic both carry body.messages; the Responses API + // carries body.input. Size is measured by walking, not by + // stringifying: a 5MB body would otherwise allocate 5MB of string on + // every request, on the request path. + const list = Array.isArray(body.messages) ? body.messages : Array.isArray(body.input) ? body.input : null + if (!list) return + if (cfg.threshold > 0 && sizeOf(body) < cfg.threshold) return + + const at = windowStart(list, cfg.keepRecent, cfg.keepTokens) + // The boundary lands only on multiples of cut_step: while the window + // slides a round a turn, the cut prefix stays byte-identical for many + // turns and the provider's prompt cache settles. Under one block + // nothing is cut yet — a history that small reads cheap whole, and + // cutting it would churn the cache every turn (yetone's review, PR + // #467: with the boundary sliding, a cached loop costs more, not + // less). Options that want thinning at any size set cut_step: 1. + const start = Math.floor(at / cfg.cutStep) * cfg.cutStep + if (start <= 0) return + + const saccade = cfg.saccade === "always" || (cfg.saccade === "auto" && topicShifted(list)) + // A structured state block (the agent's own JSON of task, constraints, + // decisions and verified facts) replaces the raw task message: it + // carries what that message carried, so the message no longer earns + // its protection and can be thinned like any other old content. The + // block itself is never touched — in either mode. + const hasState = cfg.stateMarker ? hasStateBlock(list, cfg.stateMarker) : false + const taskEnd = hasState ? 0 : leadingUserEnd(list, start) + let changed = false + for (let i = 0; i < start; i++) { + if (!saccade && i < taskEnd) continue + const item = list[i] + if (cfg.stateMarker && carriesState(item, cfg.stateMarker)) continue + if (list === body.input) changed = (saccade ? collapseInput : slimInput)(item, cfg) || changed + else changed = (saccade ? collapseMessage : slimMessage)(item, cfg) || changed + } + return changed ? body : undefined + } catch { + // fail open: whatever went wrong, the agent's request goes on as it was + } +} + +// The earliest index the window must keep: the count and the token budget +// each name one, and the larger window wins — a few huge recent messages +// must not be cut just because they are few. +function windowStart(list, keepCount, keepTokens) { + const byCount = Math.max(0, list.length - keepCount) + if (keepTokens <= 0) return byCount + let used = 0 + let i = list.length - 1 + for (; i >= 0; i--) { + used += Math.ceil(sizeOf(list[i]) / 4) + // the message that tips the budget over does not fit: the window + // starts after it, not on it — stopping on it shielded exactly the + // huge old message the budget was meant to give up + if (used > keepTokens) break + } + return Math.min(byCount, Math.max(0, i + 1)) +} + +// The task a history serves can be several leading items, not one: Codex +// sends AGENTS.md instructions and an environment_context before the task +// itself, all as user items. Everything before the first answer — an +// assistant reply, a function_call or a reasoning item, whichever comes +// first — is that preamble and stays whole; the history proper begins at +// the answer. +function leadingUserEnd(list, start) { + for (let i = 0; i < start; i++) { + const it = list[i] + if (!it || typeof it !== "object") continue + if (it.role === "assistant" || it.role === "tool" || it.type === "function_call" || + it.type === "reasoning" || it.type === "function_call_output") return i + } + return start +} + +// A state block is one message carrying the marker. It is found in the +// text of the message, wherever the agent put it. +function hasStateBlock(list, marker) { + for (const item of list) { + if (carriesState(item, marker)) return true + } + return false +} + +function carriesState(item, marker) { + if (!item || typeof item !== "object" || !marker) return false + if (typeof item.content === "string") return item.content.includes(marker) + if (!Array.isArray(item.content)) return false + for (const b of item.content) { + if (b && typeof b === "object" && typeof b.text === "string" && b.text.includes(marker)) return true + } + return false +} + +// ── peripheral: the default mode, head and tail with a marker ────────── + +function slimMessage(m, cfg) { + if (!m || typeof m !== "object") return false + if (m.role === "system" || m.role === "developer") return false + if (m.role === "tool") return slimContent(m, "content", cfg.toolHead, cfg.toolTail, cfg) + if (m.role === "assistant") { + // tool_calls are the pairing half of the tool results below; thinking + // blocks carry signatures their next turn checks. Neither is ours. + let changed = false + if (typeof m.content === "string") { + const u = cut(m.content, cfg.textHead, cfg.textTail, "text", cfg) + if (u !== m.content) { m.content = u; changed = true } + } else if (Array.isArray(m.content)) { + for (const b of m.content) { + if (b && b.type === "text" && typeof b.text === "string") { + const u = cut(b.text, cfg.textHead, cfg.textTail, "text", cfg) + if (u !== b.text) { b.text = u; changed = true } + } + } + } + return changed + } + if (m.role === "user" || m.role === undefined) { + if (typeof m.content === "string") { + const u = cut(m.content, cfg.textHead, cfg.textTail, "text", cfg) + if (u !== m.content) { m.content = u; return true } + return false + } + if (!Array.isArray(m.content)) return false + let changed = false + for (const b of m.content) { + if (!b || typeof b !== "object") continue + if (b.type === "tool_result") { + // the answer half of a tool_use: kept, only shortened + changed = slimContent(b, "content", cfg.toolHead, cfg.toolTail, cfg) || changed + } else if (b.type === "text" && typeof b.text === "string") { + const u = cut(b.text, cfg.textHead, cfg.textTail, "text", cfg) + if (u !== b.text) { b.text = u; changed = true } + } else if (cfg.dropImages && isImage(b.type)) { + note(b, b.type === "input_image", "[" + MARK + ": old image omitted]") + changed = true + } + } + return changed + } + return false +} + +// A Responses API item: function_call_output carries the tool result +// (call_id is the pairing, kept), message carries the text. function_call +// and reasoning items are left as they are. +function slimInput(it, cfg) { + if (!it || typeof it !== "object") return false + if (it.type === "function_call_output" || it.type === "custom_tool_call_output") return slimContent(it, "output", cfg.toolHead, cfg.toolTail, cfg) + if (it.role === "system" || it.role === "developer") return false + if (it.type === "message" || it.role === "user" || it.role === "assistant") { + if (typeof it.content === "string") { + const u = cut(it.content, cfg.textHead, cfg.textTail, "text", cfg) + if (u !== it.content) { it.content = u; return true } + return false + } + if (!Array.isArray(it.content)) return false + let changed = false + for (const b of it.content) { + if (!b || typeof b !== "object") continue + if (typeof b.text === "string") { + const u = cut(b.text, cfg.textHead, cfg.textTail, "text", cfg) + if (u !== b.text) { b.text = u; changed = true } + } else if (cfg.dropImages && isImage(b.type)) { + note(b, b.type === "input_image", "[" + MARK + ": old image omitted]") + changed = true + } + } + return changed + } + return false +} + +// The payload of a tool result, as a string or as parts: {role:"tool", +// content} in Chat, a tool_result block's content in Anthropic, +// function_call_output's output in the Responses API. +function slimContent(holder, key, head, tail, cfg) { + const c = holder[key] + if (typeof c === "string") { + const u = cut(c, head, tail, "tool output", cfg) + if (u !== c) { holder[key] = u; return true } + return false + } + if (!Array.isArray(c)) return false + let changed = false + for (const part of c) { + if (!part || typeof part !== "object") continue + if ((part.type === "text" || part.type === "input_text") && typeof part.text === "string") { + const u = cut(part.text, head, tail, "tool output", cfg) + if (u !== part.text) { part.text = u; changed = true } + } else if (cfg.dropImages && isImage(part.type)) { + note(part, part.type === "input_image", "[" + MARK + ": old image omitted]") + changed = true + } + } + return changed +} + +// ── saccade: a new topic, and the old context is not carried ─────────── +// Long-enough old content becomes one line; short acks stay as they are +// (they cost nothing and keep the flow readable). Pairing survives the +// same way as in the default mode: tool calls and ids untouched, tool +// results noted, not removed. + +function collapseMessage(m, cfg) { + if (!m || typeof m !== "object") return false + if (m.role === "system" || m.role === "developer") return false + if (m.role === "tool") return collapseContent(m, "content", cfg) + if (m.role === "assistant") { + let changed = false + if (typeof m.content === "string") changed = collapseText(m, "content", cfg) + else if (Array.isArray(m.content)) { + for (const b of m.content) { + if (b && b.type === "text" && typeof b.text === "string") changed = collapseText(b, "text", cfg) || changed + } + } + return changed + } + if (m.role === "user" || m.role === undefined) { + if (typeof m.content === "string") return collapseText(m, "content", cfg) + if (!Array.isArray(m.content)) return false + let changed = false + for (const b of m.content) { + if (!b || typeof b !== "object") continue + if (b.type === "tool_result") changed = collapseContent(b, "content", cfg) || changed + else if (b.type === "text" && typeof b.text === "string") changed = collapseText(b, "text", cfg) || changed + else if (isImage(b.type)) { note(b, b.type === "input_image", NOTE); changed = true } + } + return changed + } + return false +} + +function collapseInput(it, cfg) { + if (!it || typeof it !== "object") return false + if (it.type === "function_call_output" || it.type === "custom_tool_call_output") return collapseContent(it, "output", cfg) + if (it.role === "system" || it.role === "developer") return false + if (it.type === "message" || it.role === "user" || it.role === "assistant") { + if (typeof it.content === "string") return collapseText(it, "content", cfg) + if (!Array.isArray(it.content)) return false + let changed = false + for (const b of it.content) { + if (!b || typeof b !== "object") continue + if (typeof b.text === "string") changed = collapseText(b, "text", cfg) || changed + else if (isImage(b.type)) { note(b, b.type === "input_image", NOTE); changed = true } + } + return changed + } + return false +} + +function collapseContent(holder, key, cfg) { + const c = holder[key] + if (typeof c === "string") return collapseText(holder, key, cfg) + if (!Array.isArray(c)) return false + let changed = false + for (const part of c) { + if (!part || typeof part !== "object") continue + if ((part.type === "text" || part.type === "input_text") && typeof part.text === "string") changed = collapseText(part, "text", cfg) || changed + else if (isImage(part.type)) { note(part, part.type === "input_image", NOTE); changed = true } + } + return changed +} + +function collapseText(holder, key, cfg) { + const t = holder[key] + if (typeof t !== "string" || t === NOTE || t.length <= NOTE_MIN) return false + if (cfg.protect.some((re) => re.test(t))) return false + holder[key] = NOTE + return true +} + +// ── the saccade judgement ────────────────────────────────────────────── +// The newest question against the task the history serves: shared words +// (latin words of 3+, each CJK char) tell same-topic from new-topic. +// Both sides need at least four words to judge on — a "继续" or an "ok" +// keeps the old context carried, which is the safe way round. A question +// inside an Anthropic tool_result carrier is not a question; textOf +// reads only text parts, so those carriers never speak for the topic. + +function topicShifted(list) { + const last = lastQuestion(list) + const first = firstTask(list) + if (!last || !first) return false + const a = words(last) + const b = words(first) + if (a.size < 4 || b.size < 4) return false + let shared = 0 + for (const w of a) if (b.has(w)) shared++ + return shared / Math.min(a.size, b.size) < SHIFT_OVERLAP +} + +// The task is read the way the exemption reads it (leadingUserEnd): the +// leading user items before the first answer, and of those the last one. +// Codex puts AGENTS.md and an environment_context ahead of the task, all as +// user items; judging the topic against the first of them judged it +// against AGENTS.md, so a follow-up to the same task looked like a new +// topic (yetone's probe on PR #640). +function firstTask(list) { + const end = leadingUserEnd(list, list.length) + for (let i = end - 1; i >= 0; i--) { + const it = list[i] + if (it && it.role === "user") { + const t = textOf(it) + if (t) return t + } + } + for (const it of list) { + if (it && it.role === "user") { + const t = textOf(it) + if (t) return t + } + } + return null +} + +function lastQuestion(list) { + for (let i = list.length - 1; i >= 0; i--) { + const it = list[i] + if (!it || it.role !== "user") continue + const t = textOf(it) + if (t) return t + } + return null +} + +// An item's own words: a string content, or the text parts of an array — +// tool_result content and image payloads are the machinery, not the +// question. +function textOf(it) { + if (typeof it.content === "string") return it.content + if (!Array.isArray(it.content)) return null + let out = "" + for (const b of it.content) { + if (b && (b.type === "text" || b.type === "input_text") && typeof b.text === "string") out += " " + b.text + } + return out.trim() || null +} + +function words(text) { + const out = new Set() + for (const w of String(text).toLowerCase().match(/[a-z0-9_]{3,}|[\u4e00-\u9fff]/g) || []) out.add(w) + return out +} + +// ── shared ───────────────────────────────────────────────────────────── + +function isImage(type) { + return type === "image" || type === "image_url" || type === "input_image" +} + +// Turn an image part into a text note in place, dropping the payload keys +// but keeping a cache_control the request asked for: it marks a breakpoint +// the provider caches by, and losing it silently drops one of them. +function note(part, responses, text) { + const cacheControl = part && part.cache_control && typeof part.cache_control === "object" ? part.cache_control : null + const type = responses ? "input_text" : "text" + for (const k of Object.keys(part)) delete part[k] + part.type = type + part.text = text + if (cacheControl) part.cache_control = cacheControl +} + +// Head and tail with a marker in between. Content already carrying the +// marker was cut on an earlier turn (the agent sends its history back each +// time) and is left as it is — idempotent, and the marker tells the agent +// what happened. Nothing to do when it already fits, or when a protect +// pattern says this text must stay whole. +function cut(text, head, tail, what, cfg) { + if (typeof text !== "string" || text.length <= head + tail + 80) return text + if (text.includes("[" + MARK + ":")) return text + if (cfg.protect.length && cfg.protect.some((re) => re.test(text))) return text + const headEnd = safeHead(text, head) + const tailStart = safeTail(text, text.length - tail) + if (tailStart <= headEnd) return text + const endStart = tailStart + const omitted = endStart - headEnd + return text.slice(0, headEnd) + + "\n[" + MARK + ": " + omitted + " chars of old " + what + " omitted]\n" + + text.slice(endStart) +} + +function safeHead(text, n) { + if (n > 0 && n < text.length && high(text.charCodeAt(n - 1)) && low(text.charCodeAt(n))) return n - 1 + return n +} + +function safeTail(text, n) { + if (n > 0 && n < text.length && high(text.charCodeAt(n - 1)) && low(text.charCodeAt(n))) return n + 1 + return n +} + +function high(c) { return c >= 0xD800 && c <= 0xDBFF } +function low(c) { return c >= 0xDC00 && c <= 0xDFFF } + + +// Sum of the body's string lengths, plus a little per node, without +// building the joined string. Enough to decide "is this request big", and +// ~4 chars a token for the window budget. +function sizeOf(v) { + if (v === null || v === undefined) return 0 + if (typeof v === "string") return v.length + if (typeof v !== "object") return 8 + let n = 8 + if (Array.isArray(v)) { + for (const x of v) n += sizeOf(x) + return n + } + for (const k of Object.keys(v)) n += k.length + 2 + sizeOf(v[k]) + return n +} + +function patterns(v) { + if (!Array.isArray(v)) return [] + const out = [] + for (const p of v) { + if (typeof p !== "string" || !p) continue + try { out.push(new RegExp(p)) } catch { /* an invalid pattern protects nothing */ } + } + return out +} + +function num(v, d) { + const n = typeof v === "number" && isFinite(v) && v >= 0 ? Math.floor(v) : NaN + return isNaN(n) ? d : n +} diff --git a/packages/fovea/fovea.test.mjs b/packages/fovea/fovea.test.mjs new file mode 100644 index 0000000..9dbdb3a --- /dev/null +++ b/packages/fovea/fovea.test.mjs @@ -0,0 +1,262 @@ +import { test, expect } from "bun:test" +import { readFileSync } from "node:fs" +import { join } from "node:path" +import * as mod from "./fovea.middleware.js" +import { check, run } from "../../scripts/middleware.mjs" +import { benchmark } from "./benchmark.mjs" + +check(import.meta.dir, mod) + +test("the same-request report excludes prompt text and distinguishes size from cache evidence", () => { + const report = benchmark() + expect(report.request.before).toBeGreaterThan(report.request.after) + expect(report.consecutive.stable_cut_prefix).toBe(true) + expect(report.consecutive.baseline_prefix_share).toBeGreaterThan(0) + expect(report.consecutive.fovea_prefix_share).toBeGreaterThan(0) + expect(report.limits).toContain("不是计费 token") + const privateText = "sample-private-prompt-text-".repeat(8) + const custom = benchmark({ messages: [ + { role: "user", content: "task" }, + { role: "assistant", content: privateText }, + { role: "user", content: "next" }, + ] }, { threshold: 0, keep_recent: 1, keep_recent_tokens: 0, cut_step: 1 }) + expect(JSON.stringify(custom)).not.toContain(privateText) +}) + +const options = { + threshold: 0, keep_recent: 4, keep_recent_tokens: 0, cut_step: 4, + tool_head: 10, tool_tail: 5, text_head: 20, text_tail: 5, +} + +function turn(rounds) { + const messages = [{ role: "user", content: "task" }] + for (let n = 0; n < rounds; n++) { + messages.push({ role: "assistant", content: "reading", tool_calls: [ + { id: `c${n}`, type: "function", function: { name: "read", arguments: "{}" } }, + ] }) + messages.push({ role: "tool", tool_call_id: `c${n}`, content: "L".repeat(300) }) + } + messages.push({ role: "user", content: "go on" }) + return { model: "m", messages } +} + +test("two consecutive rounds keep the already-cut prefix byte-identical", async () => { + // 7 rounds: at=12; 8 rounds: at=14. With cut_step=4 both start at 12. + const a = (await run(mod, { options, request: turn(7) })).request + const b = (await run(mod, { options, request: turn(8) })).request + expect(JSON.stringify(a.messages.slice(0, 12))).toBe(JSON.stringify(b.messages.slice(0, 12))) + expect(a.messages[2].content).toContain("[fovea:") + expect(b.messages[12].content).toBe("L".repeat(300)) +}) + +test("a block boundary changes the prefix only once", async () => { + const a = (await run(mod, { options, request: turn(8) })).request + const b = (await run(mod, { options, request: turn(9) })).request + // at=14 -> start=12; at=16 -> start=16. + expect(a.messages[14].content).toBe("L".repeat(300)) + expect(b.messages[14].content).toContain("[fovea:") + expect(JSON.stringify(a.messages.slice(0, 12))).toBe(JSON.stringify(b.messages.slice(0, 12))) +}) + +test("saccade respects protect even for an old tool result", async () => { + const protectedOutput = "-----BEGIN PROTECTED BLOCK-----\n" + "S".repeat(300) + const request = { messages: [ + { role: "user", content: "task" }, + { role: "assistant", tool_calls: [{ id: "one", type: "function", function: { name: "read", arguments: "{}" } }] }, + { role: "tool", tool_call_id: "one", content: protectedOutput }, + { role: "user", content: "new topic" }, + ] } + const r = (await run(mod, { options: { ...options, keep_recent: 1, cut_step: 1, saccade: "always", protect: ["BEGIN PROTECTED BLOCK"] }, request })).request + expect(r.messages[2].content).toBe(protectedOutput) + expect(r.messages[2].tool_call_id).toBe("one") +}) + +test("saccade collapses array function_call_output without losing call_id", async () => { + const request = { input: [ + { type: "message", role: "user", content: "task" }, + { type: "function_call", call_id: "call_a", name: "read", arguments: "{}" }, + { type: "function_call_output", call_id: "call_a", output: [{ type: "text", text: "L".repeat(300) }] }, + { type: "message", role: "user", content: "new topic" }, + ] } + const r = (await run(mod, { options: { ...options, keep_recent: 1, cut_step: 1, saccade: "always" }, request })).request + expect(r.input[2].output).toEqual([{ type: "text", text: "[fovea: prior topic not carried]" }]) + expect(r.input[2].call_id).toBe("call_a") + expect(r.input[1]).toEqual(request.input[1]) +}) + +test("a PDF document is preserved in both modes", async () => { + for (const saccade of ["off", "always"]) { + const document = { type: "document", source: { type: "base64", media_type: "application/pdf", data: "Z".repeat(400) } } + const request = { messages: [ + { role: "user", content: "task" }, + { role: "user", content: [document] }, + { role: "assistant", content: "thinking" }, + { role: "user", content: "new topic" }, + ] } + const r = (await run(mod, { options: { ...options, keep_recent: 1, cut_step: 1, saccade }, request })).request + expect(r.messages[1].content[0]).toEqual(document) + } +}) + +test("cuts never split a UTF-16 surrogate pair at head or tail", async () => { + const text = "x".repeat(599) + "😀" + "y".repeat(2000) + "😀" + "z".repeat(100) + const request = { messages: [ + { role: "user", content: "task" }, + { role: "tool", tool_call_id: "a", content: text }, + { role: "user", content: "now" }, + ] } + const r = (await run(mod, { options: { ...options, keep_recent: 1, cut_step: 1, tool_head: 600, tool_tail: 101 }, request })).request + const cut = r.messages[1].content + expect(cut.startsWith("x".repeat(599) + "\n[fovea:")).toBe(true) + // tail_start points at the low surrogate; safeTail skips it along with + // the high surrogate, so the complete emoji is omitted instead of split. + expect(cut.endsWith("z".repeat(100))).toBe(true) + expect(/[\ud800-\udbff](?![\udc00-\udfff])|(? { + const summary = "Previous compressed context: " + "S".repeat(1000) + const request = { messages: [ + { role: "system", content: summary }, + { role: "user", content: "task" }, + { role: "assistant", content: "A".repeat(300) }, + { role: "user", content: "new question" }, + ] } + const r = (await run(mod, { options: { ...options, keep_recent: 1, cut_step: 1, saccade: "always" }, request })).request + expect(r.messages[0].content).toBe(summary) + expect(r.messages[3].content).toBe("new question") +}) + +const STATE = "" + +test("a state block is never touched and lets the raw task message be thinned", async () => { + const state = STATE + "\n" + JSON.stringify({ task: "ship the parser", done: ["read the file"] }) + const task = "T".repeat(400) + const request = { messages: [ + { role: "user", content: task }, + { role: "assistant", content: state }, + { role: "assistant", content: "A".repeat(300) }, + { role: "user", content: "next" }, + ] } + const r = (await run(mod, { options: { ...options, keep_recent: 1, cut_step: 1, state_marker: STATE }, request })).request + expect(r.messages[1].content).toBe(state) + expect(r.messages[0].content).toContain("[fovea:") + expect(r.messages[0].content).not.toBe(task) +}) + +test("without a state block the raw task message stays protected", async () => { + const task = "T".repeat(400) + const request = { messages: [ + { role: "user", content: task }, + { role: "assistant", content: "A".repeat(300) }, + { role: "user", content: "next" }, + ] } + const r = (await run(mod, { options: { ...options, keep_recent: 1, cut_step: 1, state_marker: STATE }, request })).request + expect(r.messages[0].content).toBe(task) +}) + +test("a state block survives a saccade that collapses everything else", async () => { + const state = STATE + "\n" + JSON.stringify({ task: "ship the parser" }) + const request = { messages: [ + { role: "user", content: "T".repeat(400) }, + { role: "assistant", content: state }, + { role: "user", content: "完全不同的新话题 番茄炒蛋 蛋炒饭 紫菜汤" }, + ] } + const r = (await run(mod, { options: { ...options, keep_recent: 1, cut_step: 1, saccade: "always", state_marker: STATE }, request })).request + expect(r.messages[1].content).toBe(state) + expect(r.messages[0].content).toBe("[fovea: prior topic not carried]") +}) + +test("the page is wired and offline: every id app.js uses exists, and no page file references the network", () => { + const html = readFileSync(join(import.meta.dir, "page", "index.html"), "utf8") + const js = readFileSync(join(import.meta.dir, "page", "app.js"), "utf8") + for (const id of [...js.matchAll(/\$\("([a-z-]+)"\)/g)].map((m) => m[1])) { + expect(html.includes(`id="${id}"`)).toBe(true) + } + for (const f of ["index.html", "style.css", "app.js", "report.js", "live.js"]) { + const t = readFileSync(join(import.meta.dir, "page", f), "utf8") + expect(t.includes("http://")).toBe(false) + expect(t.includes("https://")).toBe(false) + } +}) + +test("page/measure.js is the middleware, freshly built — a stale bundle fails here, not in magpie", async () => { + const src = readFileSync(join(import.meta.dir, "fovea.middleware.js"), "utf8") + const expected = src.replace("export function onRequest(", "function onRequest(") + "\nglobalThis.FoveaOnRequest = onRequest;\n" + const got = readFileSync(join(import.meta.dir, "page", "measure.js"), "utf8") + expect(got).toBe(expected) + expect(got.includes("globalThis.FoveaOnRequest")).toBe(true) +}) + +test("an old image's cache_control survives the note, in both modes", async () => { + for (const saccade of ["off", "always"]) { + const cc = { type: "ephemeral" } + const image = { type: "image", source: { type: "base64", media_type: "image/png", data: "i" + "V".repeat(400) }, cache_control: cc } + const request = { messages: [ + { role: "user", content: "task" }, + { role: "assistant", content: "ack" }, + { role: "user", content: [image] }, + { role: "assistant", content: "seen" }, + { role: "user", content: "next" }, + ] } + const r = (await run(mod, { options: { ...options, keep_recent: 1, cut_step: 1, saccade }, request })).request + const noted = r.messages[2].content[0] + expect(noted.type).toBe("text") + expect(noted.cache_control).toEqual(cc) + expect(noted.text).toContain("[fovea:") + } +}) + +test("Codex shape: AGENTS.md, environment_context and the task all stay whole; the first tool output is cut", async () => { + const agents = "# AGENTS.md instructions\n" + "A".repeat(300) + const env = "\n" + "E".repeat(300) + const task = "T".repeat(400) + const request = { input: [ + { type: "message", role: "developer", content: "policy" }, + { type: "message", role: "user", content: agents }, + { type: "message", role: "user", content: env }, + { type: "message", role: "user", content: task }, + { type: "function_call", call_id: "c1", name: "read", arguments: "{}" }, + { type: "function_call_output", call_id: "c1", output: "L".repeat(300) }, + { type: "message", role: "user", content: "go on" }, + ] } + const r = (await run(mod, { options: { ...options, keep_recent: 1, cut_step: 1 }, request })).request + expect(r.input[1].content).toBe(agents) + expect(r.input[3].content).toBe(task) + expect(r.input[5].output).toContain("[fovea:") +}) + +// yetone's probe on PR #640: on Codex the first user item is AGENTS.md, so +// saccade: auto judged the topic against it, not against the task. +function codexBody(question) { + const agents = "# AGENTS.md instructions\nUse pnpm for packages, prefer small commits, document every public function in the module header. " + "A".repeat(300) + const env = "\n/repo\n" + "E".repeat(300) + const task = "Fix the flaky scheduler test in internal/sched: the retry timing assertion fails under load. " + "T".repeat(300) + const input = [ + { type: "message", role: "developer", content: "policy" }, + { type: "message", role: "user", content: agents }, + { type: "message", role: "user", content: env }, + { type: "message", role: "user", content: task }, + ] + for (let i = 0; i < 6; i++) { + input.push({ type: "function_call", call_id: "c" + i, name: "read", arguments: "{}" }) + input.push({ type: "function_call_output", call_id: "c" + i, output: "L".repeat(400) }) + } + input.push({ type: "message", role: "user", content: question }) + return { agents, env, task, request: { input } } +} + +test("Codex shape, saccade auto: a follow-up to the task (third user item) is not a new topic", async () => { + const { agents, task, request } = codexBody("scheduler retry timing assertion still fails in internal/sched, fix it") + const r = (await run(mod, { options: { ...options, keep_recent: 1, cut_step: 1, saccade: "auto" }, request })).request + expect(r.input[1].content).toBe(agents) + expect(r.input[3].content).toBe(task) + expect(JSON.stringify(r)).not.toContain("prior topic not carried") + expect(r.input[5].output).toContain("[fovea:") +}) + +test("Codex shape, saccade auto: a new topic that shares words with AGENTS.md still collapses", async () => { + const { request } = codexBody("document every public function using pnpm commits header module") + const r = (await run(mod, { options: { ...options, keep_recent: 1, cut_step: 1, saccade: "auto" }, request })).request + expect(r.input[5].output).toContain("prior topic not carried") +}) diff --git a/packages/fovea/live-benchmark.mjs b/packages/fovea/live-benchmark.mjs new file mode 100644 index 0000000..0979ece --- /dev/null +++ b/packages/fovea/live-benchmark.mjs @@ -0,0 +1,84 @@ +// Controlled live A/B through the same local magpie gateway and same model. +// ⚠️ A run killed midway (Ctrl-C, crash) leaves the plugin's options as +// the last state it wrote — re-run to completion, or restore with +// `magpie plugin options ''`. +// Temporarily switches only this plugin's options, restores them in finally. +// The request is synthetic. The report stores usage and timing, never keys +// or prompt bodies. Run when other agents are idle: options are global. +// +// FOVEA_GATEWAY_KEY= bun packages/fovea/live-benchmark.mjs +// FOVEA_GATEWAY_KEY=<...> FOVEA_MODEL=deepseek/deepseek-flash bun packages/fovea/live-benchmark.mjs +import { execFileSync } from "node:child_process" +import { writeFileSync } from "node:fs" +import { dirname, join } from "node:path" +import { fileURLToPath } from "node:url" + +const HERE = dirname(fileURLToPath(import.meta.url)) +const SPEC = process.env.FOVEA_PLUGIN_SPEC || HERE +const URL = process.env.FOVEA_GATEWAY_URL || "http://127.0.0.1:3425/v1/chat/completions" +const MODEL = process.env.FOVEA_MODEL || "deepseek/deepseek-flash" +const KEY = process.env.FOVEA_GATEWAY_KEY +const pause = (ms) => new Promise((resolve) => setTimeout(resolve, ms)) +const cli = (...args) => execFileSync("magpie", args, { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }).trim() + +function request() { + const messages = [{ role: "system", content: "Reply with OK. No other words." }] + for (let i = 0; i < 8; i++) { + messages.push({ role: "user", content: `Read log part ${i}. ` + "The parser found a row and a test result. ".repeat(20) }) + messages.push({ role: "assistant", content: "Recorded part " + i + "." }) + } + messages.push({ role: "user", content: "Reply with OK." }) + return { model: MODEL, max_tokens: 128, messages } +} + +async function call(mode, sequence) { + const started = Date.now() + const res = await fetch(URL, { + method: "POST", + headers: { Authorization: `Bearer ${KEY}`, "content-type": "application/json" }, + body: JSON.stringify(request()), + signal: AbortSignal.timeout(90_000), + }) + const body = await res.json() + if (!res.ok) throw new Error(`${mode} request ${res.status}: ${JSON.stringify(body).slice(0, 180)}`) + const usage = body.usage || {} + return { + mode, sequence, model: body.model || MODEL, status: res.status, + elapsed_ms: Date.now() - started, + input_tokens: usage.prompt_tokens ?? usage.input_tokens ?? null, + output_tokens: usage.completion_tokens ?? usage.output_tokens ?? null, + cache_read_tokens: usage.prompt_cache_hit_tokens ?? usage.cache_read_input_tokens ?? usage.prompt_tokens_details?.cached_tokens ?? null, + cache_write_tokens: usage.prompt_cache_miss_tokens ?? usage.cache_creation_input_tokens ?? null, + answer: String(body.choices?.[0]?.message?.content || "").slice(0, 32), + } +} + +async function main() { + if (!KEY) throw new Error("FOVEA_GATEWAY_KEY must hold a temporary local gateway key") + const saved = JSON.parse(cli("plugin", "options", SPEC)) + const raw = { ...saved, threshold: 1_000_000_000 } + const slim = { ...saved, threshold: 0, keep_recent: 4, keep_recent_tokens: 0, cut_step: 4, saccade: "off", text_head: 80, text_tail: 40 } + const results = [] + try { + for (const [mode, options, sequence] of [["raw", raw, 1], ["fovea", slim, 1], ["fovea", slim, 2], ["raw", raw, 2]]) { + cli("plugin", "options", SPEC, JSON.stringify(options)) + await pause(1500) // gateway reloads middleware config within a second + results.push(await call(mode, sequence)) + } + } finally { + cli("plugin", "options", SPEC, JSON.stringify(saved)) + } + const sameModel = new Set(results.map((r) => r.model)).size === 1 + const report = { + version: 1, source: "local gateway controlled A/B", model: MODEL, + measured_at: new Date().toISOString(), + same_model: sameModel, + samples: results, + limits: "Same synthetic request, same model, ABBA order. Provider caches and routing can still differ; use the warm second call and Magpie usage CSV for billed cost. This report stores no prompt or key.", + } + const out = join(HERE, "page", "live.js") + writeFileSync(out, `globalThis.FoveaLive = ${JSON.stringify(report, null, 2)};\n`) + console.log(JSON.stringify(report, null, 2)) +} + +main().catch((err) => { console.error(err.message); process.exitCode = 1 }) diff --git a/packages/fovea/package.json b/packages/fovea/package.json new file mode 100644 index 0000000..a120a1d --- /dev/null +++ b/packages/fovea/package.json @@ -0,0 +1,63 @@ +{ + "name": "@magpie-community/middleware-fovea", + "version": "0.2.2", + "description": "magpie gateway middleware: keep the recent window sharp, thin old history to head and tail, and on a saccade drop the old context on a new topic — with an evidence page", + "type": "module", + "files": [ + "CHANGELOG.md", + "LICENSE", + "README.md", + "benchmark.mjs", + "build.mjs", + "cases.json", + "fovea.middleware.js", + "fovea.test.mjs", + "page/*", + "preview.mjs", + "state-block.example.json" + ], + "keywords": [ + "magpie", + "magpie-middleware", + "context", + "history", + "compaction", + "tool-results", + "token-budget", + "saccade", + "llm-gateway" + ], + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/magpie-community/plugins.git", + "directory": "packages/fovea" + }, + "magpie": { + "middleware": "./fovea.middleware.js", + "page": { + "title": "Fovea evidence", + "titles": { + "zh": "Fovea 对照证据" + }, + "file": "page/index.html", + "icon": "page/icon.svg" + }, + "permissions": [], + "options": { + "threshold": 96000, + "keep_recent": 12, + "keep_recent_tokens": 16000, + "tool_head": 600, + "tool_tail": 300, + "text_head": 1200, + "text_tail": 400, + "drop_old_images": true, + "protect": [], + "saccade": "off", + "state_marker": "", + "cut_step": 24 + }, + "icon": "data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAxMjggMTI4IiByb2xlPSJpbWciIGFyaWEtbGFiZWw9IkZvdmVhIGxvZ28gZm9yIGRhcmsgYmFja2dyb3VuZHMiPgogIDx0aXRsZT5Gb3ZlYSDigJQgc2hhcnAgY2VudHJlLCBmYWRpbmcgcGVyaXBoZXJ5IChkYXJrKTwvdGl0bGU+CiAgPGNpcmNsZSBjeD0iNjQiIGN5PSI2NCIgcj0iNTgiIGZpbGw9Im5vbmUiIHN0cm9rZT0iI2U4ZWVmNSIgc3Ryb2tlLW9wYWNpdHk9IjAuMjIiIHN0cm9rZS13aWR0aD0iNiIvPgogIDxjaXJjbGUgY3g9IjY0IiBjeT0iNjQiIHI9IjQyIiBmaWxsPSJub25lIiBzdHJva2U9IiNlOGVlZjUiIHN0cm9rZS1vcGFjaXR5PSIwLjUiIHN0cm9rZS13aWR0aD0iNyIvPgogIDxjaXJjbGUgY3g9IjY0IiBjeT0iNjQiIHI9IjI1IiBmaWxsPSJub25lIiBzdHJva2U9IiNlOGVlZjUiIHN0cm9rZS1vcGFjaXR5PSIwLjkiIHN0cm9rZS13aWR0aD0iOCIvPgogIDxjaXJjbGUgY3g9IjY0IiBjeT0iNjQiIHI9IjEwIiBmaWxsPSIjOGRiYmY1Ii8+Cjwvc3ZnPgo=" + } +} diff --git a/packages/fovea/page/app.js b/packages/fovea/page/app.js new file mode 100644 index 0000000..fccdc6c --- /dev/null +++ b/packages/fovea/page/app.js @@ -0,0 +1,122 @@ +// Offline A/B evidence for one request. No prompt content is kept: only +// counts, percentages and prefix lengths are shown. The paste-in form is +// parsed and measured in this frame, never stored or sent anywhere. +// +// The report cards render from report.js/live.js data alone. The paste-in +// A/B needs the middleware itself, which loads on demand and degrades to +// a friendly note when the page is opened where plugin files beyond the +// page folder are not served (e.g. straight from the filesystem). +(async () => { + const $ = (id) => document.getElementById(id) + const nf = new Intl.NumberFormat(undefined, { maximumFractionDigits: 0 }) + const fmt = (n) => nf.format(Math.round(n)) + const pct = (n) => `${Math.round(n * 100)}%` + + function paintBar(fill, value, max, output) { + fill.style.width = `${Math.max(1.5, Math.round((value / (max || 1)) * 100))}%` + output.textContent = fmt(value) + } + + function paintSummary(m) { + $("before").textContent = fmt(m.before) + $("after").textContent = fmt(m.after) + $("saved").textContent = fmt(m.saved) + $("changed").textContent = `${fmt(m.changed)} / ${fmt(m.messages)} 条消息被裁` + $("ratio").textContent = `缩小到 ${pct(Math.min(1, m.after / m.before))}` + $("strip-note").textContent = `${fmt(m.messages)} 条消息 · ${fmt(m.messages - m.changed)} 条原样保留` + paintBar(document.querySelector(".fill.raw"), m.before, m.before, $("raw-bar")) + paintBar($("slim-fill"), m.after, m.before, $("slim-bar")) + } + + const report = globalThis.FoveaReport + if (report) { + $("source").textContent = report.source || "synthetic" + paintSummary(report.request) + const c = report.consecutive + const maxPrefix = Math.max(c.baseline_prefix_share, c.fovea_prefix_share) + paintBar($("baseline-prefix-fill"), c.baseline_prefix_share * 100, maxPrefix * 100, $("baseline-prefix")) + paintBar($("fovea-prefix-fill"), c.fovea_prefix_share * 100, maxPrefix * 100, $("fovea-prefix")) + $("baseline-prefix").textContent = pct(c.baseline_prefix_share) + $("fovea-prefix").textContent = pct(c.fovea_prefix_share) + const badge = $("prefix-badge") + badge.textContent = c.stable_cut_prefix ? `${fmt(c.stable_cut_messages)} 条已裁消息逐字稳定` : "未验证稳定的已裁前缀" + badge.classList.toggle("bad", !c.stable_cut_prefix) + if (report.limits) $("limits").textContent = report.limits + } + + const live = globalThis.FoveaLive + if (live?.samples?.length === 4) { + $("live-source").textContent = live.same_model ? `${live.model} · ${live.measured_at}` : "两次调用不是同一个模型,结果不可比" + const warm = [live.samples[3], live.samples[2]] // ABBA: raw2, fovea2 + const labels = ["原始 · 暖缓存", "fovea · 暖缓存"] + $("live-summary").replaceChildren(...warm.map((sample, i) => { + const card = document.createElement("div") + card.className = "live-card" + const title = document.createElement("h3") + title.textContent = labels[i] + card.append(title) + for (const [label, value] of [ + ["输入 token", sample.input_tokens], + ["缓存读取 token", sample.cache_read_tokens], + ["响应毫秒", sample.elapsed_ms], + ]) { + const row = document.createElement("div") + const key = document.createElement("span") + key.textContent = label + const num = document.createElement("strong") + num.textContent = value == null ? "未提供" : fmt(value) + row.append(key, num) + card.append(row) + } + return card + })) + } + + $("clear").addEventListener("click", () => { $("input").value = ""; $("error").textContent = "" }) + + let onRequest = globalThis.FoveaOnRequest + if (!onRequest) { + try { ({ onRequest } = await import("../fovea.middleware.js")) } catch { /* page folder only, as in magpie's sandbox */ } + } + try { + if (!onRequest) throw new Error("no middleware") + const measure = (raw, options) => { + const list = Array.isArray(raw.messages) ? raw.messages : raw.input + if (!list) throw new Error("shape") + const before = JSON.stringify(raw).length + const body = JSON.parse(JSON.stringify(raw)) + onRequest(body, { options }) + const after = JSON.stringify(body).length + const out = Array.isArray(body.messages) ? body.messages : body.input + const changed = list.reduce((n, m, i) => n + (JSON.stringify(m) !== JSON.stringify(out[i]) ? 1 : 0), 0) + return { before, after, saved: before - after, changed, messages: list.length } + } + $("analyze").addEventListener("click", () => { + const err = $("error") + err.textContent = "" + try { + const raw = JSON.parse($("input").value) + const options = { + threshold: 0, + keep_recent: Number($("keep").value) || 0, + cut_step: Math.max(1, Number($("step").value) || 4), + saccade: $("mode").value, + tool_head: 80, tool_tail: 40, text_head: 120, text_tail: 60, + } + paintSummary(measure(raw, options)) + $("source").textContent = "本机粘贴的请求(内容不显示)" + } catch (e) { + err.textContent = e.message === "shape" + ? "没找到消息列表:请粘贴包含 messages 或 input 的整段请求。" + : "这段内容读不出来:请粘贴完整的请求 JSON(从 { 到 } 整段复制)。" + } + }) + } catch { + const note = document.createElement("p") + note.className = "cap" + note.textContent = "当前环境加载不了裁剪逻辑,粘贴复验暂不可用;上方的对照数字不受影响。" + $("try-title")?.closest("section")?.append(note) + $("analyze").disabled = true + $("analyze").textContent = "此环境不可用" + } +})() diff --git a/packages/fovea/page/icon.svg b/packages/fovea/page/icon.svg new file mode 100644 index 0000000..759944a --- /dev/null +++ b/packages/fovea/page/icon.svg @@ -0,0 +1,10 @@ + + Fovea — recent context held, old context shortened + + + + + + + + diff --git a/packages/fovea/page/index.html b/packages/fovea/page/index.html new file mode 100644 index 0000000..631c03f --- /dev/null +++ b/packages/fovea/page/index.html @@ -0,0 +1,97 @@ + + + + + + Fovea · 对照证据 + + + + + + + +
+
+ +
+

fovea 对照证据

+

同一份请求,裁剪前后放在一起看。

+
+ — +
+ +
+
原始请求—字符
+
经过 fovea—字符
+
减少——
+
+ +
+

消息带

—
+ +

浅色是旧消息(只剩头尾),深色是最近窗口(逐字保留)。省下的就是中间那段省略号。

+
+ +
+

请求体积

—
+
原始
—
+
裁剪后
—
+

这是本地请求的字符数,不是模型实际计费的 token。

+
+ +
+

相邻两轮的共同前缀

—
+
不开插件
—
+
开启插件
—
+

共同前缀占比高,缓存命中率才有指望。它检验裁剪边界是否稳定,不替代供应商的缓存读数。

+
+ +
+

用你的请求复验

只在本机计算
+

粘贴一份请求(messages 或 input),页面只显示数字,不保存也不发送正文。

+
+ + + +
+ +
+ + + +
+
+ +
+

真实网关 A/B

尚未运行
+
+

在装了 fovea 的机器上运行 live-benchmark.mjs,这里会显示同模型、同请求的两次暖缓存调用结果。

+
+

供应商不回缓存字段时,卡片会写「未提供」,不用字符数推算命中。

+
+ +
+

实际省钱怎么证明

+

字符变少只说明请求变短。要证明省钱,看同模型两次暖缓存调用的输入 token 与缓存读取 token,费用以 magpie 的用量记录为准。

+

+
+
+ + diff --git a/packages/fovea/page/live.js b/packages/fovea/page/live.js new file mode 100644 index 0000000..75205e3 --- /dev/null +++ b/packages/fovea/page/live.js @@ -0,0 +1 @@ +globalThis.FoveaLive = null; diff --git a/packages/fovea/page/measure.js b/packages/fovea/page/measure.js new file mode 100644 index 0000000..d64c642 --- /dev/null +++ b/packages/fovea/page/measure.js @@ -0,0 +1,508 @@ +// fovea — the focal centre of the eye. The window a request works in +// stays sharp; the history around it, like peripheral vision, stays +// present but carries only its outline. An agent that keeps its whole +// history — which is most of them, and right — stops paying to re-read +// every old file and command output on every turn. magpie's gateway does +// it on the request. Message count, order, ids and tool pairing stay as +// the agent sent them, and what is recent stays whole. Under the +// threshold the body passes as it came. +// +// {"threshold": 96000} chars of request to act above (~24k +// tokens; 0 acts on every request) +// {"keep_recent": 12} messages at the end kept whole +// {"keep_recent_tokens": 16000} the same window as a token budget; the +// larger of the two windows is kept +// {"cut_step": 24} cut boundary advances only in blocks of +// this many messages, so cached prefixes +// stay byte-identical across nearby turns +// {"tool_head": 600, "tool_tail": 300} an old tool result's kept ends +// {"text_head": 1200, "text_tail": 400} an old text message's kept ends +// {"drop_old_images": true} images older than the window → a note +// {"protect": []} regexes whose matches are left whole +// (e.g. "^diff --git ", "BEGIN .*PRIVATE KEY") +// {"state_marker": ""} a marker the agent's own structured +// state block carries. A message with the +// marker is never touched, in either mode, +// and its presence means the raw task +// message no longer needs protecting: the +// state carries the task, so that message +// is thinned like any other old content +// {"saccade": "off"} off | auto | always. A saccade is the +// eye jumping to a new target: when the +// newest question is a different topic, +// the old context is not carried at all — +// every old message long enough to matter +// collapses to one line instead of +// keeping its head and tail. "auto" judges +// by word overlap between the newest +// question and the first task message +// (a "继续" or an "ok" has no direction of +// its own and keeps the old context); +// "always" collapses on every request +// above the threshold. +// +// The system prompt and the recent window are never touched. In the +// default mode the first user message (the task) is kept whole too; on a +// saccade it is the old task, and collapses with the rest. Tool calls and +// their ids are never touched — an old tool result is shortened or +// noted, not removed, so every tool_call still has its answer. +// Already-shortened content carries the marker and is left alone, so a +// history re-sent each turn is cut once, not again. A reply is never +// touched: what the agent keeps from it is the agent's to keep. +// +// Chat (role:"tool"), Anthropic (tool_result blocks) and the Responses API +// (function_call_output items) are read in their own shapes; a body in +// none of them passes as it came. + +const MARK = "fovea" +const NOTE = "[" + MARK + ": prior topic not carried]" +const NOTE_MIN = 160 // below this a saccade leaves old text as it is +const SHIFT_OVERLAP = 0.08 // shared-word ratio under which a topic counts as new + +function onRequest(body, ctx) { + try { + if (!body || typeof body !== "object") return + const o = ctx && ctx.options && typeof ctx.options === "object" ? ctx.options : {} + const cfg = { + threshold: num(o.threshold, 96000), + keepRecent: num(o.keep_recent, 12), + keepTokens: num(o.keep_recent_tokens, 16000), + cutStep: Math.max(1, num(o.cut_step, 24)), + toolHead: num(o.tool_head, 600), + toolTail: num(o.tool_tail, 300), + textHead: num(o.text_head, 1200), + textTail: num(o.text_tail, 400), + dropImages: o.drop_old_images !== false, + protect: patterns(o.protect), + stateMarker: typeof o.state_marker === "string" ? o.state_marker : "", + saccade: o.saccade === "auto" || o.saccade === "always" ? o.saccade : "off", + } + + // Chat and Anthropic both carry body.messages; the Responses API + // carries body.input. Size is measured by walking, not by + // stringifying: a 5MB body would otherwise allocate 5MB of string on + // every request, on the request path. + const list = Array.isArray(body.messages) ? body.messages : Array.isArray(body.input) ? body.input : null + if (!list) return + if (cfg.threshold > 0 && sizeOf(body) < cfg.threshold) return + + const at = windowStart(list, cfg.keepRecent, cfg.keepTokens) + // The boundary lands only on multiples of cut_step: while the window + // slides a round a turn, the cut prefix stays byte-identical for many + // turns and the provider's prompt cache settles. Under one block + // nothing is cut yet — a history that small reads cheap whole, and + // cutting it would churn the cache every turn (yetone's review, PR + // #467: with the boundary sliding, a cached loop costs more, not + // less). Options that want thinning at any size set cut_step: 1. + const start = Math.floor(at / cfg.cutStep) * cfg.cutStep + if (start <= 0) return + + const saccade = cfg.saccade === "always" || (cfg.saccade === "auto" && topicShifted(list)) + // A structured state block (the agent's own JSON of task, constraints, + // decisions and verified facts) replaces the raw task message: it + // carries what that message carried, so the message no longer earns + // its protection and can be thinned like any other old content. The + // block itself is never touched — in either mode. + const hasState = cfg.stateMarker ? hasStateBlock(list, cfg.stateMarker) : false + const taskEnd = hasState ? 0 : leadingUserEnd(list, start) + let changed = false + for (let i = 0; i < start; i++) { + if (!saccade && i < taskEnd) continue + const item = list[i] + if (cfg.stateMarker && carriesState(item, cfg.stateMarker)) continue + if (list === body.input) changed = (saccade ? collapseInput : slimInput)(item, cfg) || changed + else changed = (saccade ? collapseMessage : slimMessage)(item, cfg) || changed + } + return changed ? body : undefined + } catch { + // fail open: whatever went wrong, the agent's request goes on as it was + } +} + +// The earliest index the window must keep: the count and the token budget +// each name one, and the larger window wins — a few huge recent messages +// must not be cut just because they are few. +function windowStart(list, keepCount, keepTokens) { + const byCount = Math.max(0, list.length - keepCount) + if (keepTokens <= 0) return byCount + let used = 0 + let i = list.length - 1 + for (; i >= 0; i--) { + used += Math.ceil(sizeOf(list[i]) / 4) + // the message that tips the budget over does not fit: the window + // starts after it, not on it — stopping on it shielded exactly the + // huge old message the budget was meant to give up + if (used > keepTokens) break + } + return Math.min(byCount, Math.max(0, i + 1)) +} + +// The task a history serves can be several leading items, not one: Codex +// sends AGENTS.md instructions and an environment_context before the task +// itself, all as user items. Everything before the first answer — an +// assistant reply, a function_call or a reasoning item, whichever comes +// first — is that preamble and stays whole; the history proper begins at +// the answer. +function leadingUserEnd(list, start) { + for (let i = 0; i < start; i++) { + const it = list[i] + if (!it || typeof it !== "object") continue + if (it.role === "assistant" || it.role === "tool" || it.type === "function_call" || + it.type === "reasoning" || it.type === "function_call_output") return i + } + return start +} + +// A state block is one message carrying the marker. It is found in the +// text of the message, wherever the agent put it. +function hasStateBlock(list, marker) { + for (const item of list) { + if (carriesState(item, marker)) return true + } + return false +} + +function carriesState(item, marker) { + if (!item || typeof item !== "object" || !marker) return false + if (typeof item.content === "string") return item.content.includes(marker) + if (!Array.isArray(item.content)) return false + for (const b of item.content) { + if (b && typeof b === "object" && typeof b.text === "string" && b.text.includes(marker)) return true + } + return false +} + +// ── peripheral: the default mode, head and tail with a marker ────────── + +function slimMessage(m, cfg) { + if (!m || typeof m !== "object") return false + if (m.role === "system" || m.role === "developer") return false + if (m.role === "tool") return slimContent(m, "content", cfg.toolHead, cfg.toolTail, cfg) + if (m.role === "assistant") { + // tool_calls are the pairing half of the tool results below; thinking + // blocks carry signatures their next turn checks. Neither is ours. + let changed = false + if (typeof m.content === "string") { + const u = cut(m.content, cfg.textHead, cfg.textTail, "text", cfg) + if (u !== m.content) { m.content = u; changed = true } + } else if (Array.isArray(m.content)) { + for (const b of m.content) { + if (b && b.type === "text" && typeof b.text === "string") { + const u = cut(b.text, cfg.textHead, cfg.textTail, "text", cfg) + if (u !== b.text) { b.text = u; changed = true } + } + } + } + return changed + } + if (m.role === "user" || m.role === undefined) { + if (typeof m.content === "string") { + const u = cut(m.content, cfg.textHead, cfg.textTail, "text", cfg) + if (u !== m.content) { m.content = u; return true } + return false + } + if (!Array.isArray(m.content)) return false + let changed = false + for (const b of m.content) { + if (!b || typeof b !== "object") continue + if (b.type === "tool_result") { + // the answer half of a tool_use: kept, only shortened + changed = slimContent(b, "content", cfg.toolHead, cfg.toolTail, cfg) || changed + } else if (b.type === "text" && typeof b.text === "string") { + const u = cut(b.text, cfg.textHead, cfg.textTail, "text", cfg) + if (u !== b.text) { b.text = u; changed = true } + } else if (cfg.dropImages && isImage(b.type)) { + note(b, b.type === "input_image", "[" + MARK + ": old image omitted]") + changed = true + } + } + return changed + } + return false +} + +// A Responses API item: function_call_output carries the tool result +// (call_id is the pairing, kept), message carries the text. function_call +// and reasoning items are left as they are. +function slimInput(it, cfg) { + if (!it || typeof it !== "object") return false + if (it.type === "function_call_output" || it.type === "custom_tool_call_output") return slimContent(it, "output", cfg.toolHead, cfg.toolTail, cfg) + if (it.role === "system" || it.role === "developer") return false + if (it.type === "message" || it.role === "user" || it.role === "assistant") { + if (typeof it.content === "string") { + const u = cut(it.content, cfg.textHead, cfg.textTail, "text", cfg) + if (u !== it.content) { it.content = u; return true } + return false + } + if (!Array.isArray(it.content)) return false + let changed = false + for (const b of it.content) { + if (!b || typeof b !== "object") continue + if (typeof b.text === "string") { + const u = cut(b.text, cfg.textHead, cfg.textTail, "text", cfg) + if (u !== b.text) { b.text = u; changed = true } + } else if (cfg.dropImages && isImage(b.type)) { + note(b, b.type === "input_image", "[" + MARK + ": old image omitted]") + changed = true + } + } + return changed + } + return false +} + +// The payload of a tool result, as a string or as parts: {role:"tool", +// content} in Chat, a tool_result block's content in Anthropic, +// function_call_output's output in the Responses API. +function slimContent(holder, key, head, tail, cfg) { + const c = holder[key] + if (typeof c === "string") { + const u = cut(c, head, tail, "tool output", cfg) + if (u !== c) { holder[key] = u; return true } + return false + } + if (!Array.isArray(c)) return false + let changed = false + for (const part of c) { + if (!part || typeof part !== "object") continue + if ((part.type === "text" || part.type === "input_text") && typeof part.text === "string") { + const u = cut(part.text, head, tail, "tool output", cfg) + if (u !== part.text) { part.text = u; changed = true } + } else if (cfg.dropImages && isImage(part.type)) { + note(part, part.type === "input_image", "[" + MARK + ": old image omitted]") + changed = true + } + } + return changed +} + +// ── saccade: a new topic, and the old context is not carried ─────────── +// Long-enough old content becomes one line; short acks stay as they are +// (they cost nothing and keep the flow readable). Pairing survives the +// same way as in the default mode: tool calls and ids untouched, tool +// results noted, not removed. + +function collapseMessage(m, cfg) { + if (!m || typeof m !== "object") return false + if (m.role === "system" || m.role === "developer") return false + if (m.role === "tool") return collapseContent(m, "content", cfg) + if (m.role === "assistant") { + let changed = false + if (typeof m.content === "string") changed = collapseText(m, "content", cfg) + else if (Array.isArray(m.content)) { + for (const b of m.content) { + if (b && b.type === "text" && typeof b.text === "string") changed = collapseText(b, "text", cfg) || changed + } + } + return changed + } + if (m.role === "user" || m.role === undefined) { + if (typeof m.content === "string") return collapseText(m, "content", cfg) + if (!Array.isArray(m.content)) return false + let changed = false + for (const b of m.content) { + if (!b || typeof b !== "object") continue + if (b.type === "tool_result") changed = collapseContent(b, "content", cfg) || changed + else if (b.type === "text" && typeof b.text === "string") changed = collapseText(b, "text", cfg) || changed + else if (isImage(b.type)) { note(b, b.type === "input_image", NOTE); changed = true } + } + return changed + } + return false +} + +function collapseInput(it, cfg) { + if (!it || typeof it !== "object") return false + if (it.type === "function_call_output" || it.type === "custom_tool_call_output") return collapseContent(it, "output", cfg) + if (it.role === "system" || it.role === "developer") return false + if (it.type === "message" || it.role === "user" || it.role === "assistant") { + if (typeof it.content === "string") return collapseText(it, "content", cfg) + if (!Array.isArray(it.content)) return false + let changed = false + for (const b of it.content) { + if (!b || typeof b !== "object") continue + if (typeof b.text === "string") changed = collapseText(b, "text", cfg) || changed + else if (isImage(b.type)) { note(b, b.type === "input_image", NOTE); changed = true } + } + return changed + } + return false +} + +function collapseContent(holder, key, cfg) { + const c = holder[key] + if (typeof c === "string") return collapseText(holder, key, cfg) + if (!Array.isArray(c)) return false + let changed = false + for (const part of c) { + if (!part || typeof part !== "object") continue + if ((part.type === "text" || part.type === "input_text") && typeof part.text === "string") changed = collapseText(part, "text", cfg) || changed + else if (isImage(part.type)) { note(part, part.type === "input_image", NOTE); changed = true } + } + return changed +} + +function collapseText(holder, key, cfg) { + const t = holder[key] + if (typeof t !== "string" || t === NOTE || t.length <= NOTE_MIN) return false + if (cfg.protect.some((re) => re.test(t))) return false + holder[key] = NOTE + return true +} + +// ── the saccade judgement ────────────────────────────────────────────── +// The newest question against the task the history serves: shared words +// (latin words of 3+, each CJK char) tell same-topic from new-topic. +// Both sides need at least four words to judge on — a "继续" or an "ok" +// keeps the old context carried, which is the safe way round. A question +// inside an Anthropic tool_result carrier is not a question; textOf +// reads only text parts, so those carriers never speak for the topic. + +function topicShifted(list) { + const last = lastQuestion(list) + const first = firstTask(list) + if (!last || !first) return false + const a = words(last) + const b = words(first) + if (a.size < 4 || b.size < 4) return false + let shared = 0 + for (const w of a) if (b.has(w)) shared++ + return shared / Math.min(a.size, b.size) < SHIFT_OVERLAP +} + +// The task is read the way the exemption reads it (leadingUserEnd): the +// leading user items before the first answer, and of those the last one. +// Codex puts AGENTS.md and an environment_context ahead of the task, all as +// user items; judging the topic against the first of them judged it +// against AGENTS.md, so a follow-up to the same task looked like a new +// topic (yetone's probe on PR #640). +function firstTask(list) { + const end = leadingUserEnd(list, list.length) + for (let i = end - 1; i >= 0; i--) { + const it = list[i] + if (it && it.role === "user") { + const t = textOf(it) + if (t) return t + } + } + for (const it of list) { + if (it && it.role === "user") { + const t = textOf(it) + if (t) return t + } + } + return null +} + +function lastQuestion(list) { + for (let i = list.length - 1; i >= 0; i--) { + const it = list[i] + if (!it || it.role !== "user") continue + const t = textOf(it) + if (t) return t + } + return null +} + +// An item's own words: a string content, or the text parts of an array — +// tool_result content and image payloads are the machinery, not the +// question. +function textOf(it) { + if (typeof it.content === "string") return it.content + if (!Array.isArray(it.content)) return null + let out = "" + for (const b of it.content) { + if (b && (b.type === "text" || b.type === "input_text") && typeof b.text === "string") out += " " + b.text + } + return out.trim() || null +} + +function words(text) { + const out = new Set() + for (const w of String(text).toLowerCase().match(/[a-z0-9_]{3,}|[\u4e00-\u9fff]/g) || []) out.add(w) + return out +} + +// ── shared ───────────────────────────────────────────────────────────── + +function isImage(type) { + return type === "image" || type === "image_url" || type === "input_image" +} + +// Turn an image part into a text note in place, dropping the payload keys +// but keeping a cache_control the request asked for: it marks a breakpoint +// the provider caches by, and losing it silently drops one of them. +function note(part, responses, text) { + const cacheControl = part && part.cache_control && typeof part.cache_control === "object" ? part.cache_control : null + const type = responses ? "input_text" : "text" + for (const k of Object.keys(part)) delete part[k] + part.type = type + part.text = text + if (cacheControl) part.cache_control = cacheControl +} + +// Head and tail with a marker in between. Content already carrying the +// marker was cut on an earlier turn (the agent sends its history back each +// time) and is left as it is — idempotent, and the marker tells the agent +// what happened. Nothing to do when it already fits, or when a protect +// pattern says this text must stay whole. +function cut(text, head, tail, what, cfg) { + if (typeof text !== "string" || text.length <= head + tail + 80) return text + if (text.includes("[" + MARK + ":")) return text + if (cfg.protect.length && cfg.protect.some((re) => re.test(text))) return text + const headEnd = safeHead(text, head) + const tailStart = safeTail(text, text.length - tail) + if (tailStart <= headEnd) return text + const endStart = tailStart + const omitted = endStart - headEnd + return text.slice(0, headEnd) + + "\n[" + MARK + ": " + omitted + " chars of old " + what + " omitted]\n" + + text.slice(endStart) +} + +function safeHead(text, n) { + if (n > 0 && n < text.length && high(text.charCodeAt(n - 1)) && low(text.charCodeAt(n))) return n - 1 + return n +} + +function safeTail(text, n) { + if (n > 0 && n < text.length && high(text.charCodeAt(n - 1)) && low(text.charCodeAt(n))) return n + 1 + return n +} + +function high(c) { return c >= 0xD800 && c <= 0xDBFF } +function low(c) { return c >= 0xDC00 && c <= 0xDFFF } + + +// Sum of the body's string lengths, plus a little per node, without +// building the joined string. Enough to decide "is this request big", and +// ~4 chars a token for the window budget. +function sizeOf(v) { + if (v === null || v === undefined) return 0 + if (typeof v === "string") return v.length + if (typeof v !== "object") return 8 + let n = 8 + if (Array.isArray(v)) { + for (const x of v) n += sizeOf(x) + return n + } + for (const k of Object.keys(v)) n += k.length + 2 + sizeOf(v[k]) + return n +} + +function patterns(v) { + if (!Array.isArray(v)) return [] + const out = [] + for (const p of v) { + if (typeof p !== "string" || !p) continue + try { out.push(new RegExp(p)) } catch { /* an invalid pattern protects nothing */ } + } + return out +} + +function num(v, d) { + const n = typeof v === "number" && isFinite(v) && v >= 0 ? Math.floor(v) : NaN + return isNaN(n) ? d : n +} + +globalThis.FoveaOnRequest = onRequest; diff --git a/packages/fovea/page/report.js b/packages/fovea/page/report.js new file mode 100644 index 0000000..5d6952e --- /dev/null +++ b/packages/fovea/page/report.js @@ -0,0 +1,33 @@ +globalThis.FoveaReport = { + "version": 1, + "source": "synthetic", + "options": { + "threshold": 0, + "keep_recent": 4, + "keep_recent_tokens": 0, + "cut_step": 4, + "tool_head": 80, + "tool_tail": 40, + "text_head": 120, + "text_tail": 60, + "saccade": "off" + }, + "request": { + "before": 47777, + "after": 14148, + "saved": 33629, + "changed": 13, + "messages": 34 + }, + "consecutive": { + "first_messages": 32, + "second_messages": 34, + "baseline_prefix_chars": 44694, + "fovea_prefix_chars": 11065, + "baseline_prefix_share": 0.9986370237962239, + "fovea_prefix_share": 0.9945173467553479, + "stable_cut_messages": 27, + "stable_cut_prefix": true + }, + "limits": "字符数与共同前缀占比是确定性的代理指标,不是计费 token、缓存命中、延迟或实际美元;system/developer 与最近窗口里的摘要仍会发送。" +}; diff --git a/packages/fovea/page/style.css b/packages/fovea/page/style.css new file mode 100644 index 0000000..27dcd47 --- /dev/null +++ b/packages/fovea/page/style.css @@ -0,0 +1,104 @@ +:root{ + color-scheme: light dark; + --bg:#f4f6f9; --surface:#ffffff; --text:#13202e; --sub:#64748b; + --line:#e3e9f0; --ink:#2f63a2; --soft:#ecf3fb; --raw:#b6c2ce; + --shadow:0 10px 34px rgba(19,32,46,.06); +} +@media (prefers-color-scheme: dark){ + :root{ --bg:#0f151d; --surface:#18212c; --text:#eef3f8; --sub:#9db0c2; + --line:#2b3a4a; --ink:#8dbbf5; --soft:#21334a; + --raw:#5d738a; --shadow:0 10px 34px rgba(0,0,0,.22); } +} +*{box-sizing:border-box} +body{margin:0;background:var(--bg);color:var(--text); + font:14px/1.6 -apple-system,BlinkMacSystemFont,"PingFang SC","Segoe UI",sans-serif; + -webkit-font-smoothing:antialiased} +main{width:min(840px,calc(100% - 32px));margin:0 auto;padding:26px 0 56px} + +/* ── hero ─────────────────────────────────────────── */ +.hero{display:flex;align-items:center;gap:16px;margin:6px 0 22px} +.eye{width:46px;height:46px;color:var(--ink);flex:none} +.eye .dot{fill:var(--ink)} +.hero-text h1{margin:0;font-size:21px;letter-spacing:-.02em} +.hero-text h1 span{color:var(--sub);font-weight:500} +.hero-text p{margin:0;color:var(--sub);font-size:13px} +.pill{margin-left:auto;background:var(--soft);color:var(--ink);padding:5px 11px; + border-radius:999px;font-size:12px;white-space:nowrap;flex:none} +.pill.bad{background:#f6e3e3;color:#a04040} +@media (prefers-color-scheme: dark){.pill.bad{background:#3d2426;color:#e2a2a2}} + +/* ── stat cards ───────────────────────────────────── */ +.stats{display:grid;grid-template-columns:repeat(3,1fr);gap:10px;margin-bottom:10px} +.stat{background:var(--surface);border:1px solid var(--line);border-radius:14px; + padding:16px 18px;box-shadow:var(--shadow);display:flex;flex-direction:column} +.stat .label{color:var(--sub);font-size:12px} +.stat strong{font-size:30px;line-height:1.25;font-variant-numeric:tabular-nums; + letter-spacing:-.03em} +.stat small{font-size:12px;color:var(--sub)} +.stat.accent{background:var(--soft);border-color:transparent} +.stat.accent strong{color:var(--ink)} + +/* ── panels ───────────────────────────────────────── */ +.panel{background:var(--surface);border:1px solid var(--line);border-radius:14px; + padding:18px 20px;margin:10px 0;box-shadow:var(--shadow)} +.head{display:flex;align-items:center;justify-content:space-between;gap:12px;margin-bottom:14px} +.head h2,.note h2{font-size:15px;margin:0;font-weight:650} +.hint{color:var(--sub);font-size:12px} +.cap{color:var(--sub);font-size:12px;margin:12px 0 0} +.note{border-left:3px solid var(--ink)} +.note p{margin:10px 0 0;color:var(--sub)} +.note p:last-child{margin-bottom:0} +code{font:12px ui-monospace,SFMono-Regular,Consolas,monospace;background:var(--soft); + padding:2px 5px;border-radius:4px;color:var(--text)} + +/* ── message strip ────────────────────────────────── */ +.strip{display:flex;align-items:center;gap:6px;padding:6px 2px} +.m{height:26px;border-radius:6px} +.m.old{flex:1;background:var(--soft);border:1px dashed var(--line)} +.m.win{flex:1;background:var(--ink);opacity:.92} +.dots{display:flex;gap:5px;padding:0 6px} +.dots b{width:5px;height:5px;border-radius:50%;background:var(--sub);opacity:.6} + +/* ── bars ─────────────────────────────────────────── */ +.bar{display:flex;align-items:center;gap:12px;margin:12px 0;font-size:12px} +.bar>span{width:64px;flex:none;color:var(--sub)} +.track{height:12px;background:var(--bg);border-radius:8px;flex:1;overflow:hidden} +.fill{display:block;height:100%;width:100%;border-radius:8px;transition:width .3s ease} +.fill.raw{background:var(--raw)} +.fill.slim{background:var(--ink)} +.bar output{width:86px;text-align:right;font-variant-numeric:tabular-nums} + +/* ── try-it form ──────────────────────────────────── */ +.controls{display:flex;gap:14px;flex-wrap:wrap;margin:14px 0 10px} +.controls label{display:flex;flex-direction:column;gap:5px;color:var(--sub);font-size:12px} +select,input,textarea{background:var(--bg);color:var(--text);border:1px solid var(--line); + border-radius:9px;padding:8px 10px;font:inherit} +input{width:104px} +textarea{width:100%;min-height:120px;resize:vertical; + font:12px/1.5 ui-monospace,SFMono-Regular,Consolas,monospace} +textarea:focus,select:focus,input:focus{outline:2px solid var(--soft);border-color:var(--ink)} +.actions{display:flex;align-items:center;gap:10px;margin-top:12px;flex-wrap:wrap} +button{border:0;border-radius:9px;background:var(--ink);color:var(--bg);padding:9px 16px; + font:inherit;font-weight:600;cursor:pointer} +button.quiet{background:var(--soft);color:var(--ink)} +#error{color:#a04040;font-size:12px} + +/* ── live cards ───────────────────────────────────── */ +.live-grid{display:grid;grid-template-columns:repeat(2,1fr);gap:10px} +.live-card{background:var(--bg);border:1px solid var(--line);border-radius:11px;padding:12px 14px} +.live-card h3{font-size:13px;margin:0 0 10px;font-weight:650} +.live-card>div{display:flex;justify-content:space-between;gap:12px;margin:4px 0;font-size:12px} +.live-card span{color:var(--sub)} +.live-card strong{font-variant-numeric:tabular-nums} + +@media (max-width:640px){ + main{width:min(100% - 24px,840px);padding-top:16px} + .stats{grid-template-columns:1fr 1fr} + .stat.accent{grid-column:span 2} + .stat strong{font-size:24px} + .panel{padding:15px 16px} + .bar>span{width:54px} + .bar output{width:64px} + .live-grid{grid-template-columns:1fr} + .pill{display:none} +} diff --git a/packages/fovea/preview.mjs b/packages/fovea/preview.mjs new file mode 100644 index 0000000..243e436 --- /dev/null +++ b/packages/fovea/preview.mjs @@ -0,0 +1,77 @@ +// What fovea would do to a request, without sending it anywhere. +// +// bun packages/fovea/preview.mjs --demo +// bun packages/fovea/preview.mjs path/to/request.json +// bun packages/fovea/preview.mjs path/to/request.json '{"keep_recent":4}' +// +// Prints, per message, what is kept and what is cut, then the totals. The +// body is never sent; the numbers are estimates from the same sizeOf() the +// middleware uses, so they match what the gateway decides. + +import { readFileSync } from "node:fs" +import * as mod from "./fovea.middleware.js" + +function size(v) { + if (v === null || v === undefined) return 0 + if (typeof v === "string") return v.length + if (typeof v !== "object") return 8 + let n = 8 + if (Array.isArray(v)) return v.reduce((a, x) => a + size(x), n) + for (const k of Object.keys(v)) n += k.length + 2 + size(v[k]) + return n +} +const tok = (chars) => Math.round(chars / 4).toLocaleString("en-US") +const fmt = (n) => n.toLocaleString("en-US") + +const argv = process.argv.slice(2) +const file = argv.find((a) => !a.startsWith("{") && !a.startsWith("-")) +const options = argv.find((a) => a.startsWith("{")) ? JSON.parse(argv.find((a) => a.startsWith("{"))) : {} +const body = file ? JSON.parse(readFileSync(file, "utf8")) : demo() + +const list = Array.isArray(body.messages) ? body.messages : Array.isArray(body.input) ? body.input : [] +const before = list.map((m) => size(m)) +const beforeTotal = size(body) + +const out = mod.onRequest(body, { options }) +const afterList = out ? (Array.isArray(out.messages) ? out.messages : out.input) : list +const afterTotal = out ? size(out) : beforeTotal + +const rows = afterList.map((m, i) => ({ + i, + role: m.role || m.type || "?", + before: before[i] ?? 0, + after: size(m), +})) +const cut = rows.filter((r) => r.after !== r.before) +const mark = (s) => (String(s).match(/\[fovea: [^\]]+\]/) || ["", ""])[0] + +console.log(`请求:${list.length} 条消息,${fmt(beforeTotal)} 字符(约 ${tok(beforeTotal)} tokens)`) +console.log(`中间件:${out ? "改写" : "原样放行"},选项 ${JSON.stringify(options) || "默认"}`) +if (cut.length) { + console.log("\n被处理的旧消息:") + for (const r of cut) { + console.log(` #${String(r.i).padStart(3)} ${String(r.role).padEnd(10)} ${fmt(r.before).padStart(9)} → ${fmt(r.after).padStart(9)} ${mark(JSON.stringify(afterList[r.i])).slice(0, 60)}`) + } +} else { + console.log("\n没有消息被改动(在阈值内,或全在最近窗口里)。") +} +const saved = beforeTotal - afterTotal +console.log(`\n合计:${fmt(beforeTotal)} → ${fmt(afterTotal)} 字符(约 ${tok(beforeTotal)} → ${tok(afterTotal)} tokens,省 ${saved > 0 ? ((saved / beforeTotal) * 100).toFixed(1) : "0.0"}%)`) + +// A history shaped like a coding agent's: a task, 150 tool round-trips with +// file-sized outputs, then the turn being sent. +function demo() { + const filler = ("An agent reads a log line, notes the timestamp, checks the retry count, " + + "compares it with the previous entry and moves on. ").repeat(40) + const msgs = [ + { role: "system", content: "You are a coding agent. Be brief." }, + { role: "user", content: "Audit the gateway logs from last night and summarize each incident." }, + ] + for (let i = 0; i < 150; i++) { + msgs.push({ role: "assistant", content: `checking batch ${i}`, tool_calls: [{ id: `call_${i}`, type: "function", function: { name: "read_logs", arguments: `{"batch":${i}}` } }] }) + msgs.push({ role: "tool", tool_call_id: `call_${i}`, content: filler }) + } + msgs.push({ role: "assistant", content: "done reading, 150 batches checked" }) + msgs.push({ role: "user", content: "Now summarize the incidents in one line." }) + return { model: "demo", messages: msgs, max_tokens: 100 } +} diff --git a/packages/fovea/state-block.example.json b/packages/fovea/state-block.example.json new file mode 100644 index 0000000..5b161ec --- /dev/null +++ b/packages/fovea/state-block.example.json @@ -0,0 +1,28 @@ +{ + "_comment": "Tier A of the structured state: the fields that change rarely. Keep them small, fixed and front-loaded so the provider's cached prefix survives. Volatile fields (current step, last command result) belong in the last message, not here.", + "goal": "one sentence: what this session is for", + "acceptance": [ + "what must be true when it is done" + ], + "constraints": [ + "stack / version pins, paths that must not change, do-not-touch areas" + ], + "decisions": [ + { + "id": "D1", + "choice": "the option taken", + "why": "the reason, in one line", + "at": "2026-11-02" + } + ], + "verified": [ + { + "fact": "a fact that was checked, not guessed", + "source": "path:line, or the command whose output showed it", + "verified_at": "2026-11-02" + } + ], + "open": [ + "unresolved question, with who or what can answer it" + ] +} diff --git a/registry.json b/registry.json index 42bed05..cf11aba 100644 --- a/registry.json +++ b/registry.json @@ -85,6 +85,8 @@ "summary": { "en": "Kilo Code (kilo.ai) on magpie's Agents page: pick one of magpie's models for it, and switch it off to put its config back.", "zh": "把 Kilo Code(kilo.ai)加到 magpie 的 Agent 页:选择 magpie 的模型,关掉即恢复原来的配置。" } }, { "package": "@magpie-community/middleware-antigravity-cloak", "name": "Antigravity Cloak", "kind": "middleware", "community": true, "summary": { "en": "Claude Code and Claude Desktop on an Antigravity account: the words Antigravity refuses their system prompt for are broken up, in what Antigravity alone is sent.", "zh": "让 Claude Code 和 Claude Desktop 能用 Antigravity 账号:只在发给 Antigravity 的请求里拆开它据以拒绝系统提示词的那几个词。" } }, + { "package": "@magpie-community/middleware-fovea", "name": "Fovea", "kind": "middleware", "community": true, + "summary": { "en": "Thin an agent's old history while preserving a recent window and tool pairing. Optional saccade collapses old content on a new topic; a structured state block replaces the raw task message; cut boundaries move in blocks to keep provider prompt caches settling.", "zh": "裁薄 Agent 旧历史,保留最近窗口与工具配对;可选 saccade 在新话题时折叠旧内容,结构化状态块替代原始任务消息,裁剪边界分块移动以保护 prompt cache。" } }, { "package": "@magpie-community/middleware-codex-history", "name": "Codex History Filter", "kind": "middleware", "community": true, "summary": { "en": "Opt-in, per-provider Codex Responses history filtering after switching providers. Preserves readable content and tool-call pairing; no model probes.", "zh": "按供应商开关 Codex Responses 历史过滤,缓解切换上游后的密文和历史 ID 兼容问题;保留正文与工具配对,不运行模型检测。" } }, { "package": "@magpie-community/middleware-history-trim", "name": "History Trim", "kind": "middleware", "community": true,