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 @@
+
+
+
+
+
+
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,