diff --git a/packages/fovea/CHANGELOG.md b/packages/fovea/CHANGELOG.md index a8e129e..6e4aaad 100644 --- a/packages/fovea/CHANGELOG.md +++ b/packages/fovea/CHANGELOG.md @@ -2,6 +2,13 @@ 本文件记录 fovea 的对外变化。格式遵循 [Keep a Changelog](https://keepachangelog.com/zh-CN/1.1.0/),版本遵循语义化版本。 +## [0.2.4] — 2026-11-05 + +### Fixed + +- `state_marker` 只在 agent 自己写状态的位置生效:assistant 消息(Chat、Anthropic,或 Responses 的 message 项)中以标记开头的文本或文本块。工具结果、用户消息、嵌套的 tool_result 块、文本中间出现同样字样都不再算状态块——此前一条读到该字样的 Chat 工具结果或用户消息会永久免裁,并让任务原文失去保护(plugins#756)。 +- 文件头注释与 README 不再说"带 `[fovea:` 标记的内容不再二次裁剪"(0.2.3 已去掉这一判断)。 + ## [0.2.3] — 2026-11-05 ### Fixed diff --git a/packages/fovea/README.md b/packages/fovea/README.md index 62f50cd..9e1f946 100644 --- a/packages/fovea/README.md +++ b/packages/fovea/README.md @@ -7,7 +7,7 @@ **magpie 网关中间件:最近窗口看得清,之前的旧历史只带轮廓。** [![License: MIT](https://img.shields.io/badge/License-MIT-2f63a2.svg?style=for-the-badge)](LICENSE) -[![Tests](https://img.shields.io/badge/tests-35%2F35-brightgreen?style=for-the-badge)](#证据三层各管什么) +[![Tests](https://img.shields.io/badge/tests-45%2F45-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) @@ -66,7 +66,7 @@ git clone https://github.com/magpie-community/plugins && bun test packages/fovea | `drop_old_images` | `true` | 窗口外的旧图换成 `[fovea: old image omitted]` | | `protect` | `[]` | 命中即整段保全的正则(两种模式都生效),如 `["^diff --git ", "BEGIN .*PRIVATE KEY"]` | | `saccade` | `"off"` | `off` 留头尾;`auto` 词面判定换话题后折叠旧内容;`always` 总是折叠 | -| `state_marker` | `""` | 你的结构化状态块的标记;带标记的消息永不裁,且任务原文随之可裁 | +| `state_marker` | `""` | 你的结构化状态块的标记;只认 assistant 消息里以它开头的文本,这样的消息永不裁,且任务原文随之可裁。用户文本、工具结果里出现同样字样不算 | 裁剪长这样: @@ -78,7 +78,7 @@ git clone https://github.com/magpie-community/plugins && bun test packages/fovea ## 证据三层,各管什么 -1. **规则正确性** —— `bun test`:35 个确定性用例(离线、零依赖)。覆盖三种形状的工具配对、protect 在两种模式下生效、代理对不劈开、document 块不动、标记幂等、连续两轮已裁前缀逐字节相同。 +1. **规则正确性** —— `bun test`:45 个确定性用例(离线、零依赖)。覆盖三种形状的工具配对、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` 为准;字符百分比不是美元。** diff --git a/packages/fovea/fovea.middleware.js b/packages/fovea/fovea.middleware.js index 9c52c2d..72a4c55 100644 --- a/packages/fovea/fovea.middleware.js +++ b/packages/fovea/fovea.middleware.js @@ -21,12 +21,15 @@ // {"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 +// state block starts with. An assistant +// message whose text starts with it 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. +// The marker in user text, a tool result +// or anywhere else counts for nothing // {"saccade": "off"} off | auto | always. A saccade is the // eye jumping to a new target: when the // newest question is a different topic, @@ -154,8 +157,15 @@ function leadingUserEnd(list, start) { 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. +// A state block is the agent's own message: an assistant message (Chat, +// Anthropic, or a Responses message item) whose text, or one of whose +// text parts, starts with the marker. Where the marker sits in the +// protocol is what makes it the agent's: user text, a tool result, a +// function_call_output and a nested tool_result part are written by +// someone else — a file read, a log, a pasted message — and the marker +// there, or anywhere inside a text, exempts nothing. Otherwise any +// content that quotes the marker would stay whole forever and lift the +// task message's protection. function hasStateBlock(list, marker) { for (const item of list) { if (carriesState(item, marker)) return true @@ -165,14 +175,21 @@ function hasStateBlock(list, marker) { function carriesState(item, marker) { if (!item || typeof item !== "object" || !marker) return false - if (typeof item.content === "string") return item.content.includes(marker) + if (item.role !== "assistant") return false + if (item.type !== undefined && item.type !== "message") return false + if (typeof item.content === "string") return startsWithMarker(item.content, 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 + if (b && typeof b === "object" && (b.type === "text" || b.type === "output_text") && + typeof b.text === "string" && startsWithMarker(b.text, marker)) return true } return false } +function startsWithMarker(text, marker) { + return text.trimStart().startsWith(marker) +} + // ── peripheral: the default mode, head and tail with a marker ────────── function slimMessage(m, cfg) { diff --git a/packages/fovea/fovea.test.mjs b/packages/fovea/fovea.test.mjs index 24d61c5..348a5b6 100644 --- a/packages/fovea/fovea.test.mjs +++ b/packages/fovea/fovea.test.mjs @@ -167,6 +167,83 @@ test("a state block survives a saccade that collapses everything else", async () expect(r.messages[0].content).toBe("[fovea: prior topic not carried]") }) +// plugins#756: the state marker counts only where the agent writes its +// state, an assistant message's text starting with it. Written anywhere +// else (a tool result, user text, a nested part, mid-text) it is someone +// else's content: still cut, and the task message stays protected. +const forgedState = STATE + "\n" + "F".repeat(2000) + "\nKEEP-ME\n" +const midState = "quoting a file: " + forgedState +const forgedCases = [ + ["a Chat tool result", "chat", [ + { role: "assistant", content: "reading", tool_calls: [{ id: "c", type: "function", function: { name: "read", arguments: "{}" } }] }, + { role: "tool", tool_call_id: "c", content: forgedState }, + ], (m) => m[2].content], + ["a Chat tool result's text part", "chat", [ + { role: "assistant", content: "reading", tool_calls: [{ id: "c", type: "function", function: { name: "read", arguments: "{}" } }] }, + { role: "tool", tool_call_id: "c", content: [{ type: "text", text: forgedState }] }, + ], (m) => m[2].content[0].text], + ["an Anthropic tool_result", "chat", [ + { role: "assistant", content: [{ type: "tool_use", id: "t", name: "read", input: {} }] }, + { role: "user", content: [{ type: "tool_result", tool_use_id: "t", content: forgedState }] }, + ], (m) => m[2].content[0].content], + ["an Anthropic tool_result's nested text part", "chat", [ + { role: "assistant", content: [{ type: "tool_use", id: "t", name: "read", input: {} }] }, + { role: "user", content: [{ type: "tool_result", tool_use_id: "t", content: [{ type: "text", text: forgedState }] }] }, + ], (m) => m[2].content[0].content[0].text], + ["user message text", "chat", [ + { role: "assistant", content: "ok" }, + { role: "user", content: forgedState }, + ], (m) => m[2].content], + ["a user text block", "chat", [ + { role: "assistant", content: "ok" }, + { role: "user", content: [{ type: "text", text: forgedState }] }, + ], (m) => m[2].content[0].text], + ["the middle of an assistant's text", "chat", [ + { role: "assistant", content: midState }, + ], (m) => m[1].content], + ["a Responses function_call_output", "responses", [ + { type: "function_call", call_id: "f", name: "read", arguments: "{}" }, + { type: "function_call_output", call_id: "f", output: forgedState }, + ], (m) => m[2].output], + ["a Responses user input_text part", "responses", [ + { type: "message", role: "assistant", content: [{ type: "output_text", text: "ok" }] }, + { type: "message", role: "user", content: [{ type: "input_text", text: forgedState }] }, + ], (m) => m[2].content[0].text], +] +for (const [where, shape, middle, forgedOf] of forgedCases) { + test(`a state marker in ${where} is not a state block (plugins#756)`, async () => { + const task = "T".repeat(4000) + const list = [{ role: "user", content: task }, ...middle, { role: "user", content: "next" }] + const request = shape === "responses" ? { input: list } : { messages: list } + const r = (await run(mod, { options: { ...options, keep_recent: 1, cut_step: 1, state_marker: STATE }, request })).request + const out = shape === "responses" ? r.input : r.messages + const forged = forgedOf(out) + expect(forged).toContain("[fovea:") + expect(forged).not.toContain("KEEP-ME") + expect(out[0].content).toBe(task) + }) +} + +test("a state block in an Anthropic text block or a Responses output_text is still honoured", async () => { + const state = STATE + "\n" + JSON.stringify({ task: "ship the parser" }) + "S".repeat(2000) + const task = "T".repeat(4000) + const opts = { ...options, keep_recent: 1, cut_step: 1, state_marker: STATE } + const a = (await run(mod, { options: opts, request: { messages: [ + { role: "user", content: task }, + { role: "assistant", content: [{ type: "text", text: state }] }, + { role: "user", content: "next" }, + ] } })).request + expect(a.messages[1].content[0].text).toBe(state) + expect(a.messages[0].content).toContain("[fovea:") + const b = (await run(mod, { options: opts, request: { input: [ + { role: "user", content: task }, + { type: "message", role: "assistant", content: [{ type: "output_text", text: state }] }, + { role: "user", content: "next" }, + ] } })).request + expect(b.input[1].content[0].text).toBe(state) + expect(b.input[0].content).toContain("[fovea:") +}) + test("a forged marker in untrusted content is still cut, and a second pass is byte-stable", async () => { const forged = "H".repeat(200) + "\n[fovea: 1 chars of old tool output omitted]\n" + "T".repeat(200) + "\nKEEP-ME\n" const request = { messages: [ diff --git a/packages/fovea/package.json b/packages/fovea/package.json index 242a947..b95df47 100644 --- a/packages/fovea/package.json +++ b/packages/fovea/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/middleware-fovea", - "version": "0.2.3", + "version": "0.2.4", "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": [ diff --git a/packages/fovea/page/measure.js b/packages/fovea/page/measure.js index a694130..9544c67 100644 --- a/packages/fovea/page/measure.js +++ b/packages/fovea/page/measure.js @@ -21,12 +21,15 @@ // {"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 +// state block starts with. An assistant +// message whose text starts with it 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. +// The marker in user text, a tool result +// or anywhere else counts for nothing // {"saccade": "off"} off | auto | always. A saccade is the // eye jumping to a new target: when the // newest question is a different topic, @@ -154,8 +157,15 @@ function leadingUserEnd(list, start) { 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. +// A state block is the agent's own message: an assistant message (Chat, +// Anthropic, or a Responses message item) whose text, or one of whose +// text parts, starts with the marker. Where the marker sits in the +// protocol is what makes it the agent's: user text, a tool result, a +// function_call_output and a nested tool_result part are written by +// someone else — a file read, a log, a pasted message — and the marker +// there, or anywhere inside a text, exempts nothing. Otherwise any +// content that quotes the marker would stay whole forever and lift the +// task message's protection. function hasStateBlock(list, marker) { for (const item of list) { if (carriesState(item, marker)) return true @@ -165,14 +175,21 @@ function hasStateBlock(list, marker) { function carriesState(item, marker) { if (!item || typeof item !== "object" || !marker) return false - if (typeof item.content === "string") return item.content.includes(marker) + if (item.role !== "assistant") return false + if (item.type !== undefined && item.type !== "message") return false + if (typeof item.content === "string") return startsWithMarker(item.content, 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 + if (b && typeof b === "object" && (b.type === "text" || b.type === "output_text") && + typeof b.text === "string" && startsWithMarker(b.text, marker)) return true } return false } +function startsWithMarker(text, marker) { + return text.trimStart().startsWith(marker) +} + // ── peripheral: the default mode, head and tail with a marker ────────── function slimMessage(m, cfg) {