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.
85 lines
4.3 KiB
JavaScript
85 lines
4.3 KiB
JavaScript
// 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 <spec> '<json>'`.
|
|
// 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=<temporary 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 })
|