Files
plugins/packages/fovea/preview.mjs
T
webkubor d4eeba4493 fovea 0.2.2: a new middleware, old history to head and tail on a cache-stable boundary (webkubor, #640)
A new gateway middleware, @magpie-community/middleware-fovea 0.2.2 (webkubor, #640): old tool output and text in a long history are cut to head and tail, with the boundary only on multiples of `cut_step` (24) so the cut prefix stays byte-identical between turns and the prompt cache holds. The leading user items before the first answer (Codex's AGENTS.md, environment_context and the task; Claude Code's first message) stay whole. `saccade` ("off" by default) drops the old context on a new topic, judged against that same task. Old images become a text note that keeps their `cache_control`. Ships an evidence page (Plugins > Fovea evidence) that computes a paste-in A/B in the frame, with no network.

What was run, at the reviewed head b9883cf206814fdc01950a00d413a36856de4e11, on mote (macOS, Bun 1.4.2, sandbox HOME):
- `bun test packages/fovea`: 33 pass, 0 fail. The two new Codex saccade cases fail with 0357f1c's middleware (and pass at the head).
- `bun scripts/check.mjs fovea` and `bun scripts/check.mjs`: pass. `page/measure.js` is byte-identical to a fresh `bun build.mjs`.
- `npm pack --dry-run`: 18 files, 131.8 kB unpacked; no brand/, no live-benchmark.mjs.
- The head merged onto origin/main 82b254f2 (registry.json auto-merged): `bun scripts/check.mjs` passes and `HOME=$(mktemp -d) bun test` (the whole repo, as pr.yml runs it): 5477 pass, 0 fail.
- A probe calling onRequest turn after turn. Codex-shaped Responses (instructions, developer permissions item, AGENTS.md, environment_context, the task as input_text, then reasoning with encrypted_content, function_call and function_call_output, 60 turns) and Claude Code-shaped Messages (system with cache_control, a first message with system-reminder, task and an image with cache_control, then thinking + signature, text, tool_use and a 6400-char tool_result with emoji, 70 turns). `instructions`, `system`, `tools`, every reasoning, function_call and assistant item, ids, counts and the cache_control count are unchanged; the four leading Codex items reach upstream byte-identical; no lone surrogate. The shared prefix breaks once per cut_step (Codex 6 of 60 turns, Messages 5 of 70; 0 without fovea), with `saccade: "auto"` too. With auto, a same-task follow-up on Codex ("scheduler retry timing assertion still fails in internal/sched, fix it") and on Messages collapses nothing; a new topic collapses from that turn on (one extra prefix break). Bodies went 16.1 MB to 9.4 MB (Codex) and 26.1 MB to 13.9 MB (Messages) over the run.
- Text the middleware adds upstream is only `[fovea: N chars of old tool output omitted]` and `[fovea: prior topic not carried]`: neither names magpie, a vendor or a limit. Codex's instructions are never touched.

Not tried: a live vendor request with real cache-hit numbers (the evidence is the byte-level prefix). pr.yml's runs were waiting on approval for a first-time contributor, so the CI record is the merged-tree run above. A new topic that shares a common word such as "the" with the task stays below the 0.08 overlap bar only when it has enough words; with saccade off by default that is a tuning note, not a blocker. @magpie-community/middleware-fovea is new to npm, so its first version needs an owner (trusted publishing can't create a package); magpie serves it from the dist branch meanwhile.
2026-11-04 16:56:37 +08:00

78 lines
3.7 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// 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 }
}