codex-history 0.1.1: historical web_search_call replayed as text after reasoning is filtered (#204)

Historical native `web_search_call` items become a labeled assistant text message (recorded status, action, queries and sources; no item id, no internal turn metadata) once the filter has removed the reasoning they depend on. Other native tools keep their ids; tool call/result pairs, unsafe-reference rejection and passthrough for providers without the rule are unchanged. Split out of #168 as asked in its review. codex-history 0.1.0 -> 0.1.1.

What was run at 61b6f0b (reviewer, bun 1.4.2, macOS):
- bun test packages/codex-history: 29 pass, 0 fail. node --test packages/codex-history/web-search.test.mjs: 6 pass. bun scripts/check.mjs codex-history: exit 0.
- Broken by hand: with the web_search_call branch disabled, 5 bun tests and 4 node tests go red.
- magpie (built from yetone/magpie main 85eef5d87) in a sandbox HOME, middleware added from the PR's package, a custom Responses provider `demo` pointing at a local fake, options {"providers":{"magpie:demo":{"historyFilter":true}}}, gateway on 127.0.0.1:18763 (moejs). A Codex-shaped request with reasoning + web_search_call + function_call pair: the fake received the search as the labeled assistant text, no rs_/ws_ ids, no PRIVATE_TURN, the call pair intact, store false. With main's 0.1.0 file swapped in, the fake received the bare web_search_call.
- Not tried: a real Codex session or real vendors.
This commit is contained in:
unisong
2026-10-17 17:54:06 +08:00
committed by GitHub
parent f6adc99a9c
commit a73237c74c
7 changed files with 269 additions and 16 deletions
+2 -1
View File
@@ -14,6 +14,7 @@
"changes": [
"Inlined the shared history algorithm and request hook into one import-free middleware file.",
"Removed helper exports; only onRequest is exported.",
"No model detection, guard, dashboard, proxy service or provider configuration is included."
"No model detection, guard, dashboard, proxy service or provider configuration is included.",
"Version 0.1.1 adds history/portable-web-search.mjs, inlined into the middleware to convert historical native web_search_call items to labeled text after reasoning is removed. Original source hashes above identify the v1.0.5 baseline, not the modified middleware."
]
}
+6 -2
View File
@@ -14,7 +14,7 @@
magpie plugin add @magpie-community/middleware-codex-history
```
也可从 [独立 GitHub 仓库](https://github.com/unisong/magpie-codex-history-filter) 安装同一份过滤代码。无需启动 Codex Filter Manager,不要同时安装两份。需要支持 gateway middleware 的 Magpie;本包已在 0.1.1265 的隔离实例中验证,其他版本需核对插件加载状态。
社区版本只发布历史过滤中间件;模型工作台单独本地维护,不包含在本包中。无需启动 Codex Filter Manager,不要同时启用两份过滤插件。需要支持 gateway middleware 的 Magpie;本包已在 0.1.1265 的隔离实例中验证,其他版本需核对插件加载状态。
## 设置
@@ -48,6 +48,8 @@ magpie plugin add @magpie-community/middleware-codex-history
开启后,插件移除旧 reasoning 条目、明确标记的加密内容,以及可独立携带内容的消息和工具条目中的可选服务器 ID;设置 `store: false`。保留正文、工具参数、结果、`call_id` 配对、文件引用及普通业务 ID,不改变请求模型或推理强度。
**v0.1.1:历史搜索兼容修复。** 原生 `web_search_call` 可能依赖已删除的 reasoning,导致上游提示 `was provided without its required reasoning item`。开启过滤后,历史搜索条目转为带标记的助手文字,保留已记录的动作、查询、状态和来源数据,去除服务器条目 ID 与内部回合元数据;后续结论、引用及普通工具调用配对保持原样。不重新搜索、不补造未记录的结果。该处理适用于携带明文历史的普通对话和文字总结,不解密压缩历史。
`previous_response_id`、`conversation`、`item_reference`、加密压缩历史和 `/responses/compact` 无法安全跨资源迁移时,会明确拒绝,提示整理文字摘要后新建会话,不会静默丢弃这些上下文。
- 不能解密旧密文、迁移所有服务器资源引用,或保证消除全部 Azure 历史错误。移除内部推理状态也可能影响长任务连续性。
@@ -62,7 +64,7 @@ magpie plugin add @magpie-community/middleware-codex-history
若此前使用 Codex Filter Manager v1.0.5 自动安装的本地 `magpie-plugin`,先在旧管理页关闭该供应商的自动保护(若有旧设置),停止旧管理服务,再在 Magpie 中停用或卸载旧的本地历史插件,最后安装本插件并复制所需历史规则。原有规则的 `stripResponsesLiteHeader` 会被忽略,可删除。不要同时启用两份历史过滤插件。
升级固定 GitHub 标签时,在 Magpie 中用新标签地址更新;现有配置存于 Magpie 的 `plugins.json`,更新前可备份自己的 Options。不要上传该文件,它可能包含其他插件的私有设置。
社区版本合并并完成 dist 发布后,可在 Magpie 插件页更新;现有 Options 无需改写,更新前可自行备份。不要上传 Magpie 的 `plugins.json`,它可能包含其他插件的私有设置。本插件不直接读写该文件,规则由宿主通过 Options 传入。
## English
@@ -72,6 +74,8 @@ Install from **Plugins → Discover → Gateway middleware**, or run `magpie plu
Unsafe server-only references and encrypted compaction are rejected explicitly. Magpie may fail open on plugin errors/timeouts, and downstream route changes are outside the plugin's control. Disable or remove it in Magpie; it never edits Codex configuration.
Version 0.1.1 converts historical native `web_search_call` items to labeled assistant text after removing old reasoning. Recorded actions, queries, status and sources remain available; native item IDs and internal turn metadata are removed. Subsequent answers and ordinary tool-call pairs remain intact. No searches are rerun, absent results are not reconstructed, and encrypted compaction is not decrypted. The community package contains only the middleware; the optional model workbench is maintained separately for local use.
## 开发与来源
```sh
+123 -12
View File
@@ -1076,13 +1076,18 @@
"model": "demo/gpt-6-astra",
"input": [
{
"type": "web_search_call",
"id": "ws_keep",
"type": "file_search_call",
"id": "fs_keep",
"status": "completed",
"action": {
"type": "search",
"query": "example"
}
"queries": [
"example"
],
"results": [
{
"id": "resource_keep",
"text": "Recorded file result"
}
]
}
]
},
@@ -1091,13 +1096,18 @@
"store": false,
"input": [
{
"type": "web_search_call",
"id": "ws_keep",
"type": "file_search_call",
"id": "fs_keep",
"status": "completed",
"action": {
"type": "search",
"query": "example"
}
"queries": [
"example"
],
"results": [
{
"id": "resource_keep",
"text": "Recorded file result"
}
]
}
]
}
@@ -1329,5 +1339,106 @@
"status": 409,
"message": "Codex history filter: encrypted compaction"
}
},
{
"name": "historical native search becomes text after reasoning filtering",
"ctx": {
"protocol": "responses",
"path": "/v1/responses"
},
"options": {
"providers": {
"magpie:demo": {
"historyFilter": true,
"preserveEncryptedInclude": true
}
}
},
"request": {
"model": "demo/gpt-6-astra",
"include": [
"reasoning.encrypted_content"
],
"reasoning": {
"effort": "xhigh"
},
"input": [
{
"type": "reasoning",
"id": "rs_foreign",
"summary": [],
"encrypted_content": "FOREIGN_CIPHERTEXT"
},
{
"type": "web_search_call",
"id": "ws_foreign",
"status": "completed",
"action": {
"type": "search",
"query": "example",
"sources": [
{
"type": "url",
"url": "https://example.invalid/rules"
}
]
},
"internal_chat_message_metadata_passthrough": {
"turn_id": "PRIVATE_TURN"
}
},
{
"type": "message",
"role": "assistant",
"content": "Recorded conclusion with citation https://example.invalid/rules"
},
{
"type": "function_call",
"id": "fc_old",
"call_id": "pair_keep",
"name": "read_file",
"arguments": "{\"id\":\"BUSINESS_ID\"}"
},
{
"type": "function_call_output",
"id": "fco_old",
"call_id": "pair_keep",
"output": "FILE_TEXT_KEEP"
}
]
},
"expect_request": {
"model": "demo/gpt-6-astra",
"include": [
"reasoning.encrypted_content"
],
"reasoning": {
"effort": "xhigh"
},
"input": [
{
"type": "message",
"role": "assistant",
"content": "[Historical web search activity; recorded data only, not a new tool call. Search results are not reconstructed.]\n{\"status\":\"completed\",\"action\":{\"type\":\"search\",\"query\":\"example\",\"sources\":[{\"type\":\"url\",\"url\":\"https://example.invalid/rules\"}]}}"
},
{
"type": "message",
"role": "assistant",
"content": "Recorded conclusion with citation https://example.invalid/rules"
},
{
"type": "function_call",
"call_id": "pair_keep",
"name": "read_file",
"arguments": "{\"id\":\"BUSINESS_ID\"}"
},
{
"type": "function_call_output",
"call_id": "pair_keep",
"output": "FILE_TEXT_KEEP"
}
],
"store": false
}
}
]
@@ -50,6 +50,10 @@ function filterResponsesRequest(body, {preserveEncryptedInclude = false} = {}) {
const isMessage = item && item.type === undefined && typeof item.role === 'string' && item.content !== undefined;
if (item && typeof item === 'object') {
const portable = removeEncryptedContent(item, () => { removedEncryptedContentItems++; });
if (item.type === 'web_search_call') {
if (Object.hasOwn(portable, 'id')) removedItemIds++;
return portableWebSearch(portable);
}
if (PORTABLE_ITEMS.has(item.type) || isMessage) {
if (Object.hasOwn(portable, 'id')) {
delete portable.id;
@@ -67,6 +71,17 @@ function filterResponsesRequest(body, {preserveEncryptedInclude = false} = {}) {
return {body: clean, removed, removedItemIds, removedEncryptedContentItems};
}
// Inlined from history/portable-web-search.mjs for the import-free gateway hook.
function portableWebSearch(item) {
const record = {...item};
delete record.type;
delete record.id;
delete record.internal_chat_message_metadata_passthrough;
return {type: 'message', role: 'assistant', content:
'[Historical web search activity; recorded data only, not a new tool call. '
+ 'Search results are not reconstructed.]\n' + JSON.stringify(record)};
}
// Historical agent/tool messages can carry account-bound ciphertext inside their
// content arrays. Remove only those explicitly typed items; ordinary IDs and
// opaque values in tool payloads remain untouched.
@@ -0,0 +1,11 @@
// Native server tools can depend on encrypted reasoning and account-bound IDs.
// Keep their recorded data as text instead of replaying an incomplete tool item.
export function portableWebSearch(item) {
const record = {...item};
delete record.type;
delete record.id;
delete record.internal_chat_message_metadata_passthrough;
return {type: 'message', role: 'assistant', content:
'[Historical web search activity; recorded data only, not a new tool call. '
+ 'Search results are not reconstructed.]\n' + JSON.stringify(record)};
}
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@magpie-community/middleware-codex-history",
"version": "0.1.0",
"version": "0.1.1",
"description": "Opt-in, per-provider Codex Responses history compatibility for Magpie",
"type": "module",
"license": "MIT",
+111
View File
@@ -0,0 +1,111 @@
import {test} from 'node:test';
import assert from 'node:assert/strict';
import {readFileSync} from 'node:fs';
import * as middleware from './codex-history.middleware.js';
import {portableWebSearch} from './history/portable-web-search.mjs';
const options = {providers: {'magpie:demo': {historyFilter: true, preserveEncryptedInclude: true}}};
const request = {model: 'demo/mock-model', include: ['reasoning.encrypted_content'],
reasoning: {effort: 'xhigh'}, instructions: 'Summarize the recorded history.', input: [
{type: 'reasoning', id: 'rs_foreign', encrypted_content: 'FOREIGN_CIPHERTEXT', summary: []},
{type: 'web_search_call', id: 'ws_foreign', status: 'completed',
action: {type: 'search', query: 'example', queries: ['example', 'another example'],
sources: [{type: 'url', url: 'https://example.invalid/rules', title: 'Recorded source'}]},
internal_chat_message_metadata_passthrough: {turn_id: 'PRIVATE_TURN'}},
{type: 'message', role: 'assistant', content: 'Recorded conclusion: https://example.invalid/rules'},
{type: 'function_call', id: 'fc_old', call_id: 'pair_keep', name: 'read_file', arguments: '{"id":"BUSINESS_ID"}'},
{type: 'function_call_output', id: 'fco_old', call_id: 'pair_keep', output: 'FILE_TEXT_KEEP'},
{role: 'user', content: 'Create a text summary without new searches.'}
]};
function filter(body, overrides = {}) {
let rejected;
const result = middleware.onRequest(body, {protocol: 'responses', path: '/v1/responses', options,
...overrides, reject: (status, message) => { rejected = {status, message}; }});
return {result, rejected};
}
test('search history retains recorded data and later answers without native reasoning dependencies', () => {
const before = structuredClone(request);
const {result, rejected} = filter(request);
assert.equal(rejected, undefined);
assert.deepEqual(result.input[0], portableWebSearch(request.input[1]));
assert.equal(result.input[0].type, 'message');
assert.equal(result.input[0].role, 'assistant');
assert.match(result.input[0].content, /recorded data only, not a new tool call/);
assert.deepEqual(JSON.parse(result.input[0].content.split('\n').slice(1).join('\n')), {
status: request.input[1].status, action: request.input[1].action
});
assert.doesNotMatch(JSON.stringify(result), /FOREIGN_CIPHERTEXT|rs_foreign|ws_foreign|PRIVATE_TURN/);
assert.deepEqual(result.input.slice(1), [request.input[2],
{type: 'function_call', call_id: 'pair_keep', name: 'read_file', arguments: '{"id":"BUSINESS_ID"}'},
{type: 'function_call_output', call_id: 'pair_keep', output: 'FILE_TEXT_KEEP'}, request.input[5]]);
assert.deepEqual(result.reasoning, request.reasoning);
assert.deepEqual(result.include, request.include);
assert.equal(result.instructions, request.instructions);
assert.equal(result.model, request.model);
assert.equal(result.store, false);
assert.deepEqual(request, before);
assert.deepEqual(filter(result).result, result);
});
test('all recorded search actions and partial status remain data without reconstructed results', () => {
for (const action of [
{type: 'search', query: 'example'},
{type: 'open_page', url: 'https://example.invalid/doc', sources: [{id: 'BUSINESS_ID'}]},
{type: 'find_in_page', url: 'https://example.invalid/doc', pattern: 'deadline'}
]) {
for (const status of ['completed', 'in_progress', 'incomplete']) {
const item = {type: 'web_search_call', id: 'ws_old', status, action};
const {result} = filter({...request, input: [item]});
assert.deepEqual(result.input[0], portableWebSearch(item));
assert.deepEqual(JSON.parse(result.input[0].content.split('\n').slice(1).join('\n')), {status, action});
}
}
assert.deepEqual(JSON.parse(portableWebSearch({type: 'web_search_call'}).content.split('\n')[1]), {});
});
test('only enabled Responses provider rules transform search history', () => {
for (const context of [
{options: {}}, {options: {providers: {'magpie:demo': {historyFilter: false}}}},
{protocol: 'chat-completions'}, {protocol: 'anthropic'}
]) assert.equal(filter(request, context).result, undefined);
assert.equal(filter({...request, model: 'other/mock-model'}).result, undefined);
assert.equal(filter({...request, model: 'mock-model'}).result, undefined);
assert.deepEqual(filter({...request, model: 'old-demo/mock-model'}, {
options: {...options, aliases: {'old-demo': 'demo'}}
}).result.input[0], portableWebSearch(request.input[1]));
});
test('other native tools keep their resource IDs and contents', () => {
const file = {type: 'file_search_call', id: 'fs_keep', queries: ['example'], results: [{id: 'resource_keep', text: 'FILE_TEXT'}]};
assert.deepEqual(filter({...request, input: [file]}).result.input, [file]);
});
test('search adaptation keeps unsafe context rejection and explicit encrypted-content cleanup', () => {
assert.equal(filter(request, {path: '/v1/responses/compact'}).rejected.status, 409);
for (const body of [
{...request, previous_response_id: 'resp_old'}, {...request, conversation: 'conv_old'},
{...request, input: [{type: 'compaction', encrypted_content: 'SEALED_CONTEXT'}]},
{...request, input: [{type: 'item_reference', id: 'ws_old'}]},
{...request, context_management: [{type: 'compaction'}]}
]) assert.ok(filter(body).rejected);
const item = {...request.input[1], content: [
{type: 'encrypted_content', encrypted_content: 'SEALED_PART'}, {type: 'input_text', text: 'RECORDED_TEXT'}
]};
const text = filter({...request, input: [item]}).result.input[0].content;
assert.doesNotMatch(text, /SEALED_PART/);
assert.match(text, /RECORDED_TEXT/);
});
test('the shipped middleware remains a small import-free package with only the request hook', () => {
const pkg = JSON.parse(readFileSync(new URL('./package.json', import.meta.url), 'utf8'));
assert.equal(pkg.version, '0.1.1');
assert.deepEqual(Object.keys(middleware), ['onRequest']);
assert.deepEqual(pkg.files, ['codex-history.middleware.js', 'README.md', 'LICENSE', 'PROVENANCE.json']);
assert.deepEqual(Object.keys(pkg.magpie).sort(), ['middleware', 'options']);
assert.equal(pkg.main, undefined);
assert.equal(pkg.dependencies, undefined);
const code = readFileSync(new URL(pkg.magpie.middleware, import.meta.url), 'utf8');
assert.doesNotMatch(code, /\bimport\s|\bfetch\s*\(|\brequire\s*\(/);
});