diff --git a/packages/codex-history/PROVENANCE.json b/packages/codex-history/PROVENANCE.json index 4d1a402..319317d 100644 --- a/packages/codex-history/PROVENANCE.json +++ b/packages/codex-history/PROVENANCE.json @@ -1,20 +1,43 @@ { - "source": "https://github.com/unisong/codex-filter-manager", - "commit": "40f98308f364ca8533c30c11a2cede4ea00542f3", - "version": "v1.0.5", + "source": "https://github.com/unisong/magpie-codex-history-filter", + "commit": "43e0b5c8d5e1542a4bb58054f1c3c7f6ee0e7120", + "version": "0.1.2", "license": "MIT", "files": { - "magpie-plugin/history-filter.mjs": { - "sha256": "45d969daf0a6185fba2cbf8b76910d7bcb63e012d4767c46863b520f17c80925" + "codex-history.middleware.js": { + "sha256": "155522beab703641b4ba57f43f347b5a50aeab191463cfcdb0a93cb7e91f56f5" }, - "magpie-plugin/history.middleware.js": { - "sha256": "b4da0d27961861904ba8577633717c6e14c36e78508ff95074fa24fb98d76a06" + "history/portable-web-search.mjs": { + "sha256": "3ba488941254df46f4ea3aeda5fa0e325d6cb579f2f504a13c005f7f657c5f9d" + }, + "README.md": { + "sha256": "97cbb2a1179e4f801b9e50b177a963d5297388c48dbf1ee27a628e3507117c83" + }, + "package.json": { + "sha256": "e0552938d8c2e3352c5b512b5f135d6696b82c228f896d6fba3449aa66a1db42" + }, + "LICENSE": { + "sha256": "3ce553a5ba020d6cbae538031d05c0700d67ad4d673d832d51022566a9ead2e1" + } + }, + "derivedFrom": { + "source": "https://github.com/unisong/codex-filter-manager", + "commit": "40f98308f364ca8533c30c11a2cede4ea00542f3", + "version": "v1.0.5", + "files": { + "magpie-plugin/history-filter.mjs": { + "sha256": "45d969daf0a6185fba2cbf8b76910d7bcb63e012d4767c46863b520f17c80925" + }, + "magpie-plugin/history.middleware.js": { + "sha256": "b4da0d27961861904ba8577633717c6e14c36e78508ff95074fa24fb98d76a06" + } } }, "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.", - "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." + "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.", + "Version 0.1.2 exports onProvider: a request through a Magpie group or fallback is filtered on each provider try with the tried provider's rule. onRequest and onProvider are the only exports.", + "The files above are byte-identical to the pinned commit in the source repository. derivedFrom names the original baseline; that commit is no longer on a branch or tag since the source repository's public history was rebuilt." ] } diff --git a/packages/codex-history/README.md b/packages/codex-history/README.md index e8eaf95..7a8dbbf 100644 --- a/packages/codex-history/README.md +++ b/packages/codex-history/README.md @@ -14,7 +14,7 @@ magpie plugin add @magpie-community/middleware-codex-history ``` -社区版本只发布历史过滤中间件;模型工作台单独本地维护,不包含在本包中。无需启动 Codex Filter Manager,不要同时启用两份过滤插件。需要支持 gateway middleware 的 Magpie;本包已在 0.1.1265 的隔离实例中验证,其他版本需核对插件加载状态。 +社区版本只发布历史过滤中间件;模型工作台单独本地维护,不包含在本包中。无需启动 Codex Filter Manager,不要同时启用两份过滤插件。需要支持 gateway middleware 及 `onProvider` 钩子的 Magpie;v0.1.2 已在 0.1.2131 的隔离实例中验证,其他版本需核对插件加载状态。 ## 设置 @@ -37,12 +37,13 @@ magpie plugin add @magpie-community/middleware-codex-history ``` - 请求模型为 `demo/gpt-6-astra` 时,使用 `magpie:demo` 的规则;ID 是模型前缀,不是供应商显示名称。 +- 通过 Magpie 路由组或 fallback 发出的请求(模型名是分组),在每次实际尝试某个供应商时,按该供应商 ID 的规则过滤。不需要、也不应该为路由组单独建规则。 - `historyFilter: true` 开启过滤;`false`、删除该规则或空配置均为直通。不同会话按各自请求独立处理,可同时过滤多个供应商。 - `preserveEncryptedInclude: true` 保留客户端对**新响应**中 `reasoning.encrypted_content` 的请求,推荐开启。它不会保留**旧历史**中的密文。省略或设置为 `false` 会移除这一 include 值,不影响其他 include 项。 -- 供应商改名后,旧会话可能仍发送旧前缀;可设置 `"aliases": {"old-demo": "demo"}`。别名只用于选择过滤规则,不改写请求模型,也不替代 Magpie 自己的路由别名。 +- 供应商改名后,旧会话可能仍发送旧前缀;可设置 `"aliases": {"old-demo": "demo"}`。别名同样作用于路由组中实际尝试的供应商 ID,只用于选择过滤规则,不改写请求模型,也不替代 Magpie 自己的路由别名。 - 无 `供应商/模型` 前缀或非 Responses 协议的请求保持原样。未配置的供应商不会被自动过滤。 -保存 Options 后,Magpie 在后续请求加载规则。无需另开网页或重启 Codex;是否成功加载以 Magpie 插件页的错误与调用统计为准。 +保存 Options 后,Magpie 在后续请求加载规则。无需另开网页或重启 Codex;是否成功加载以 Magpie 插件页的错误统计为准。插件页的调用次数统计每次钩子调用:每个 Responses 请求经过 `onRequest`,每次供应商尝试经过 `onProvider`,没有命中规则、原样放行的请求也会计入,它不表示过滤次数。 ## 原理与边界 @@ -50,12 +51,14 @@ magpie plugin add @magpie-community/middleware-codex-history **v0.1.1:历史搜索兼容修复。** 原生 `web_search_call` 可能依赖已删除的 reasoning,导致上游提示 `was provided without its required reasoning item`。开启过滤后,历史搜索条目转为带标记的助手文字,保留已记录的动作、查询、状态和来源数据,去除服务器条目 ID 与内部回合元数据;后续结论、引用及普通工具调用配对保持原样。不重新搜索、不补造未记录的结果。该处理适用于携带明文历史的普通对话和文字总结,不解密压缩历史。 +**v0.1.2:路由组与 fallback 兼容修复。** 经 Magpie 路由组或 fallback 发出的请求,模型名是分组而不是供应商,路由前的前缀匹配找不到规则,旧密文和条目 ID 会原样发给已开启过滤的成员,上游返回 `created under a different Azure OpenAI resource` 等错误。现在 `onProvider` 在每次供应商尝试时按该供应商规则过滤;直接选择供应商的请求仍在 `onRequest` 过滤,并通过 `ctx.state` 标记,不会重复处理。 + `previous_response_id`、`conversation`、`item_reference`、加密压缩历史和 `/responses/compact` 无法安全跨资源迁移时,会明确拒绝,提示整理文字摘要后新建会话,不会静默丢弃这些上下文。 - 不能解密旧密文、迁移所有服务器资源引用,或保证消除全部 Azure 历史错误。移除内部推理状态也可能影响长任务连续性。 - Magpie 请求钩子限时 250 毫秒;加载失败、异常或超时可能按 Magpie 的机制放行原请求。插件不是强制安全边界。 - 只覆盖进入 Magpie agent middleware 的 Responses 请求;Magpie 自身的标题、分类器等内部请求不经过此钩子。WebSocket、Chat Completions、Lite HTTP 标头修改不在本插件范围内。 -- 规则按进入钩子时的模型前缀选择。自动路由组、fallback、其他插件随后改写路由时,不保证规则对应最终上游。 +- 直接选择供应商时按模型前缀选择规则;路由组和 fallback 按每次实际尝试的供应商选择。`onProvider` 不能拒绝请求,所以上述无法迁移的内容经路由组发出时只能原样发送,由上游报错;直接选择供应商时仍会被明确拒绝。其他插件若在本插件之后再改写请求,结果不受本插件控制。 - 不采集或保存凭据、请求正文,不执行检测、重试或模型调用。上游正常请求仍按上游规则计费。 ## 停用、升级与旧版迁移 @@ -70,19 +73,21 @@ magpie plugin add @magpie-community/middleware-codex-history Opt-in Magpie gateway middleware for Codex Responses history after switching providers or accounts. It strips old reasoning/encrypted items and optional server IDs from portable history, preserving readable content and tool-call pairing. **History filtering only: no model detector, guard, background server, credentials or extra upstream calls.** -Install from **Plugins → Discover → Gateway middleware**, or run `magpie plugin add @magpie-community/middleware-codex-history`. In the plugin's **Options**, configure `providers["magpie:"]` as shown above. Every provider defaults to passthrough. The request's `provider/model` prefix selects its rule; requests from different sessions remain independent. `aliases` maps an old prefix to a rule ID only. `preserveEncryptedInclude: true` keeps requests for new encrypted response content while still removing historical ciphertext. +Install from **Plugins → Discover → Gateway middleware**, or run `magpie plugin add @magpie-community/middleware-codex-history`. In the plugin's **Options**, configure `providers["magpie:"]` as shown above. Every provider defaults to passthrough. A request to `provider/model` uses that prefix's rule. A request through a Magpie group or fallback is filtered on each provider try with the tried provider's rule, so a group needs no rule of its own. Requests from different sessions remain independent. `aliases` maps an old prefix or provider ID to a rule ID only. `preserveEncryptedInclude: true` keeps requests for new encrypted response content while still removing historical ciphertext. -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. +Unsafe server-only references and encrypted compaction are rejected explicitly when a provider is chosen directly. A provider try can't be refused, so through a group they are sent as they were. Magpie may fail open on plugin errors/timeouts. The Plugins page counts every hook call, passed-through requests included, not filtered requests. 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. +Version 0.1.2 filters group and fallback requests on each provider try (`onProvider`). Before it, a request named after a group matched no rule, so old ciphertext and item IDs reached providers whose filter was on. A direct request filtered by `onRequest` is marked in `ctx.state` and isn't filtered again. + ## 开发与来源 ```sh bun test packages/codex-history ``` -测试只使用本地虚构数据,不调用模型。核心代码来自 [Codex Filter Manager v1.0.5](https://github.com/unisong/codex-filter-manager/tree/v1.0.5),来源和 SHA-256 记录于 [PROVENANCE.json](PROVENANCE.json)。为匹配社区 middleware 包格式,将共用算法与请求钩子合并为单个无 import 文件。 +测试只使用本地虚构数据,不调用模型。核心代码来自 [Codex Filter Manager](https://github.com/unisong/codex-filter-manager)(MIT),本包的镜像源码在 [magpie-codex-history-filter](https://github.com/unisong/magpie-codex-history-filter),来源提交和 SHA-256 记录于 [PROVENANCE.json](PROVENANCE.json)。为匹配社区 middleware 包格式,将共用算法与请求钩子合并为单个无 import 文件。 接口参考:[Magpie middleware 文档](https://usemagpie.ai/docs/plugins#middleware)。 diff --git a/packages/codex-history/cases.json b/packages/codex-history/cases.json index 17b43e2..3bc0b51 100644 --- a/packages/codex-history/cases.json +++ b/packages/codex-history/cases.json @@ -1440,5 +1440,968 @@ ], "store": false } + }, + { + "name": "group try filters with the tried provider's rule", + "ctx": { + "protocol": "responses", + "path": "/v1/responses" + }, + "options": { + "providers": { + "magpie:demo": { + "historyFilter": true, + "preserveEncryptedInclude": true + } + } + }, + "request": { + "model": "group/sol-dedicated", + "reasoning": { + "effort": "high" + }, + "include": [ + "reasoning.encrypted_content", + "message.output_text.logprobs" + ], + "input": [ + { + "type": "reasoning", + "id": "rs_old", + "encrypted_content": "foreign" + }, + { + "type": "message", + "id": "msg_old", + "role": "assistant", + "content": [ + { + "type": "output_text", + "text": "Keep answer." + }, + { + "type": "encrypted_content", + "data": "foreign" + } + ] + }, + { + "type": "function_call", + "id": "fc_old", + "call_id": "pair", + "name": "lookup", + "arguments": "{\"id\":\"business\"}" + }, + { + "type": "function_call_output", + "id": "out_old", + "call_id": "pair", + "output": "keep result" + }, + { + "type": "message", + "role": "user", + "content": [ + { + "type": "input_file", + "file_id": "file_keep" + } + ] + } + ] + }, + "provider": { + "id": "demo", + "name": "demo", + "model": "gpt-6-astra" + }, + "expect_request": { + "model": "group/sol-dedicated", + "reasoning": { + "effort": "high" + }, + "include": [ + "reasoning.encrypted_content", + "message.output_text.logprobs" + ], + "input": [ + { + "type": "message", + "role": "assistant", + "content": [ + { + "type": "output_text", + "text": "Keep answer." + } + ] + }, + { + "type": "function_call", + "call_id": "pair", + "name": "lookup", + "arguments": "{\"id\":\"business\"}" + }, + { + "type": "function_call_output", + "call_id": "pair", + "output": "keep result" + }, + { + "type": "message", + "role": "user", + "content": [ + { + "type": "input_file", + "file_id": "file_keep" + } + ] + } + ], + "store": false + } + }, + { + "name": "fallback try uses that provider's own include preference", + "ctx": { + "protocol": "responses", + "path": "/v1/responses" + }, + "options": { + "providers": { + "magpie:demo": { + "historyFilter": true, + "preserveEncryptedInclude": true + }, + "magpie:backup": { + "historyFilter": true, + "preserveEncryptedInclude": false + } + } + }, + "request": { + "model": "group/sol-dedicated", + "reasoning": { + "effort": "high" + }, + "include": [ + "reasoning.encrypted_content", + "message.output_text.logprobs" + ], + "input": [ + { + "type": "reasoning", + "id": "rs_old", + "encrypted_content": "foreign" + }, + { + "type": "message", + "id": "msg_old", + "role": "assistant", + "content": [ + { + "type": "output_text", + "text": "Keep answer." + }, + { + "type": "encrypted_content", + "data": "foreign" + } + ] + }, + { + "type": "function_call", + "id": "fc_old", + "call_id": "pair", + "name": "lookup", + "arguments": "{\"id\":\"business\"}" + }, + { + "type": "function_call_output", + "id": "out_old", + "call_id": "pair", + "output": "keep result" + }, + { + "type": "message", + "role": "user", + "content": [ + { + "type": "input_file", + "file_id": "file_keep" + } + ] + } + ] + }, + "provider": { + "id": "backup", + "name": "backup", + "model": "gpt-6-astra" + }, + "expect_request": { + "model": "group/sol-dedicated", + "reasoning": { + "effort": "high" + }, + "include": [ + "message.output_text.logprobs" + ], + "input": [ + { + "type": "message", + "role": "assistant", + "content": [ + { + "type": "output_text", + "text": "Keep answer." + } + ] + }, + { + "type": "function_call", + "call_id": "pair", + "name": "lookup", + "arguments": "{\"id\":\"business\"}" + }, + { + "type": "function_call_output", + "call_id": "pair", + "output": "keep result" + }, + { + "type": "message", + "role": "user", + "content": [ + { + "type": "input_file", + "file_id": "file_keep" + } + ] + } + ], + "store": false + } + }, + { + "name": "group search history becomes text on a filtered provider try", + "ctx": { + "protocol": "responses", + "path": "/v1/responses" + }, + "options": { + "providers": { + "magpie:demo": { + "historyFilter": true, + "preserveEncryptedInclude": true + } + } + }, + "request": { + "model": "group/sol-dedicated", + "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" + } + ] + }, + "provider": { + "id": "demo", + "name": "demo", + "model": "gpt-6-astra" + }, + "expect_request": { + "model": "group/sol-dedicated", + "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 + } + }, + { + "name": "group try alias selects the renamed provider's rule", + "ctx": { + "protocol": "responses", + "path": "/v1/responses" + }, + "options": { + "providers": { + "magpie:demo": { + "historyFilter": true, + "preserveEncryptedInclude": true + } + }, + "aliases": { + "old-demo": "demo" + } + }, + "request": { + "model": "group/sol-dedicated", + "reasoning": { + "effort": "high" + }, + "include": [ + "reasoning.encrypted_content", + "message.output_text.logprobs" + ], + "input": [ + { + "type": "reasoning", + "id": "rs_old", + "encrypted_content": "foreign" + }, + { + "type": "message", + "id": "msg_old", + "role": "assistant", + "content": [ + { + "type": "output_text", + "text": "Keep answer." + }, + { + "type": "encrypted_content", + "data": "foreign" + } + ] + }, + { + "type": "function_call", + "id": "fc_old", + "call_id": "pair", + "name": "lookup", + "arguments": "{\"id\":\"business\"}" + }, + { + "type": "function_call_output", + "id": "out_old", + "call_id": "pair", + "output": "keep result" + }, + { + "type": "message", + "role": "user", + "content": [ + { + "type": "input_file", + "file_id": "file_keep" + } + ] + } + ] + }, + "provider": { + "id": "old-demo", + "name": "old-demo", + "model": "gpt-6-astra" + }, + "expect_request": { + "model": "group/sol-dedicated", + "reasoning": { + "effort": "high" + }, + "include": [ + "reasoning.encrypted_content", + "message.output_text.logprobs" + ], + "input": [ + { + "type": "message", + "role": "assistant", + "content": [ + { + "type": "output_text", + "text": "Keep answer." + } + ] + }, + { + "type": "function_call", + "call_id": "pair", + "name": "lookup", + "arguments": "{\"id\":\"business\"}" + }, + { + "type": "function_call_output", + "call_id": "pair", + "output": "keep result" + }, + { + "type": "message", + "role": "user", + "content": [ + { + "type": "input_file", + "file_id": "file_keep" + } + ] + } + ], + "store": false + } + }, + { + "name": "direct request is filtered once and its provider try keeps it", + "ctx": { + "protocol": "responses", + "path": "/v1/responses" + }, + "options": { + "providers": { + "magpie:demo": { + "historyFilter": true, + "preserveEncryptedInclude": true + } + } + }, + "request": { + "model": "demo/gpt-6-astra", + "reasoning": { + "effort": "high" + }, + "include": [ + "reasoning.encrypted_content", + "message.output_text.logprobs" + ], + "input": [ + { + "type": "reasoning", + "id": "rs_old", + "encrypted_content": "foreign" + }, + { + "type": "message", + "id": "msg_old", + "role": "assistant", + "content": [ + { + "type": "output_text", + "text": "Keep answer." + }, + { + "type": "encrypted_content", + "data": "foreign" + } + ] + }, + { + "type": "function_call", + "id": "fc_old", + "call_id": "pair", + "name": "lookup", + "arguments": "{\"id\":\"business\"}" + }, + { + "type": "function_call_output", + "id": "out_old", + "call_id": "pair", + "output": "keep result" + }, + { + "type": "message", + "role": "user", + "content": [ + { + "type": "input_file", + "file_id": "file_keep" + } + ] + } + ] + }, + "provider": { + "id": "demo", + "name": "demo", + "model": "gpt-6-astra" + }, + "expect_request": { + "model": "demo/gpt-6-astra", + "reasoning": { + "effort": "high" + }, + "include": [ + "reasoning.encrypted_content", + "message.output_text.logprobs" + ], + "input": [ + { + "type": "message", + "role": "assistant", + "content": [ + { + "type": "output_text", + "text": "Keep answer." + } + ] + }, + { + "type": "function_call", + "call_id": "pair", + "name": "lookup", + "arguments": "{\"id\":\"business\"}" + }, + { + "type": "function_call_output", + "call_id": "pair", + "output": "keep result" + }, + { + "type": "message", + "role": "user", + "content": [ + { + "type": "input_file", + "file_id": "file_keep" + } + ] + } + ], + "store": false + } + }, + { + "name": "group try on a provider without a rule passes unchanged", + "ctx": { + "protocol": "responses", + "path": "/v1/responses" + }, + "options": { + "providers": { + "magpie:demo": { + "historyFilter": true, + "preserveEncryptedInclude": true + } + } + }, + "request": { + "model": "group/sol-dedicated", + "reasoning": { + "effort": "high" + }, + "include": [ + "reasoning.encrypted_content", + "message.output_text.logprobs" + ], + "input": [ + { + "type": "reasoning", + "id": "rs_old", + "encrypted_content": "foreign" + }, + { + "type": "message", + "id": "msg_old", + "role": "assistant", + "content": [ + { + "type": "output_text", + "text": "Keep answer." + }, + { + "type": "encrypted_content", + "data": "foreign" + } + ] + }, + { + "type": "function_call", + "id": "fc_old", + "call_id": "pair", + "name": "lookup", + "arguments": "{\"id\":\"business\"}" + }, + { + "type": "function_call_output", + "id": "out_old", + "call_id": "pair", + "output": "keep result" + }, + { + "type": "message", + "role": "user", + "content": [ + { + "type": "input_file", + "file_id": "file_keep" + } + ] + } + ] + }, + "provider": { + "id": "other", + "name": "other", + "model": "gpt-6-astra" + } + }, + { + "name": "group try on a disabled provider passes unchanged", + "ctx": { + "protocol": "responses", + "path": "/v1/responses" + }, + "options": { + "providers": { + "magpie:demo": { + "historyFilter": false, + "preserveEncryptedInclude": true + } + } + }, + "request": { + "model": "group/sol-dedicated", + "reasoning": { + "effort": "high" + }, + "include": [ + "reasoning.encrypted_content", + "message.output_text.logprobs" + ], + "input": [ + { + "type": "reasoning", + "id": "rs_old", + "encrypted_content": "foreign" + }, + { + "type": "message", + "id": "msg_old", + "role": "assistant", + "content": [ + { + "type": "output_text", + "text": "Keep answer." + }, + { + "type": "encrypted_content", + "data": "foreign" + } + ] + }, + { + "type": "function_call", + "id": "fc_old", + "call_id": "pair", + "name": "lookup", + "arguments": "{\"id\":\"business\"}" + }, + { + "type": "function_call_output", + "id": "out_old", + "call_id": "pair", + "output": "keep result" + }, + { + "type": "message", + "role": "user", + "content": [ + { + "type": "input_file", + "file_id": "file_keep" + } + ] + } + ] + }, + "provider": { + "id": "demo", + "name": "demo", + "model": "gpt-6-astra" + } + }, + { + "name": "group try on another protocol passes unchanged", + "ctx": { + "protocol": "anthropic" + }, + "options": { + "providers": { + "magpie:demo": { + "historyFilter": true, + "preserveEncryptedInclude": true + } + } + }, + "request": { + "model": "group/sol-dedicated", + "reasoning": { + "effort": "high" + }, + "include": [ + "reasoning.encrypted_content", + "message.output_text.logprobs" + ], + "input": [ + { + "type": "reasoning", + "id": "rs_old", + "encrypted_content": "foreign" + }, + { + "type": "message", + "id": "msg_old", + "role": "assistant", + "content": [ + { + "type": "output_text", + "text": "Keep answer." + }, + { + "type": "encrypted_content", + "data": "foreign" + } + ] + }, + { + "type": "function_call", + "id": "fc_old", + "call_id": "pair", + "name": "lookup", + "arguments": "{\"id\":\"business\"}" + }, + { + "type": "function_call_output", + "id": "out_old", + "call_id": "pair", + "output": "keep result" + }, + { + "type": "message", + "role": "user", + "content": [ + { + "type": "input_file", + "file_id": "file_keep" + } + ] + } + ] + }, + "provider": { + "id": "demo", + "name": "demo", + "model": "gpt-6-astra" + } + }, + { + "name": "group try leaves history it cannot move as sent", + "ctx": { + "protocol": "responses", + "path": "/v1/responses" + }, + "options": { + "providers": { + "magpie:demo": { + "historyFilter": true, + "preserveEncryptedInclude": true + } + } + }, + "request": { + "model": "group/sol-dedicated", + "reasoning": { + "effort": "high" + }, + "include": [ + "reasoning.encrypted_content", + "message.output_text.logprobs" + ], + "input": [ + { + "type": "reasoning", + "id": "rs_old", + "encrypted_content": "foreign" + }, + { + "type": "message", + "id": "msg_old", + "role": "assistant", + "content": [ + { + "type": "output_text", + "text": "Keep answer." + }, + { + "type": "encrypted_content", + "data": "foreign" + } + ] + }, + { + "type": "function_call", + "id": "fc_old", + "call_id": "pair", + "name": "lookup", + "arguments": "{\"id\":\"business\"}" + }, + { + "type": "function_call_output", + "id": "out_old", + "call_id": "pair", + "output": "keep result" + }, + { + "type": "message", + "role": "user", + "content": [ + { + "type": "input_file", + "file_id": "file_keep" + } + ] + } + ], + "previous_response_id": "resp_old" + }, + "provider": { + "id": "demo", + "name": "demo", + "model": "gpt-6-astra" + } + }, + { + "name": "group try on the compact endpoint passes unchanged", + "ctx": { + "protocol": "responses", + "path": "/v1/responses/compact" + }, + "options": { + "providers": { + "magpie:demo": { + "historyFilter": true, + "preserveEncryptedInclude": true + } + } + }, + "request": { + "model": "group/sol-dedicated", + "reasoning": { + "effort": "high" + }, + "include": [ + "reasoning.encrypted_content", + "message.output_text.logprobs" + ], + "input": [ + { + "type": "reasoning", + "id": "rs_old", + "encrypted_content": "foreign" + }, + { + "type": "message", + "id": "msg_old", + "role": "assistant", + "content": [ + { + "type": "output_text", + "text": "Keep answer." + }, + { + "type": "encrypted_content", + "data": "foreign" + } + ] + }, + { + "type": "function_call", + "id": "fc_old", + "call_id": "pair", + "name": "lookup", + "arguments": "{\"id\":\"business\"}" + }, + { + "type": "function_call_output", + "id": "out_old", + "call_id": "pair", + "output": "keep result" + }, + { + "type": "message", + "role": "user", + "content": [ + { + "type": "input_file", + "file_id": "file_keep" + } + ] + } + ] + }, + "provider": { + "id": "demo", + "name": "demo", + "model": "gpt-6-astra" + } } ] diff --git a/packages/codex-history/codex-history.middleware.js b/packages/codex-history/codex-history.middleware.js index 24a68fd..d5b3907 100644 --- a/packages/codex-history/codex-history.middleware.js +++ b/packages/codex-history/codex-history.middleware.js @@ -34,7 +34,7 @@ function filterResponsesRequest(body, {preserveEncryptedInclude = false} = {}) { const clean = {...body, store: false}; let removed = 0, removedItemIds = 0, removedEncryptedContentItems = 0; // include controls the NEW response, not the historical ciphertext in input. - // AnyRouter rejects Codex requests when this requested response field is removed. + // Some upstreams reject Codex requests when this requested response field is removed. if (body.include) clean.include = preserveEncryptedInclude ? [...body.include] : body.include.filter(value => value !== 'reasoning.encrypted_content'); if (Array.isArray(body.input)) { @@ -101,21 +101,30 @@ function removeEncryptedContent(value, onRemoved) { return copy; } +// The rule for a provider ID or model prefix, after aliases; only an explicit +// historyFilter: true turns filtering on. +function enabledRule(name, options) { + const aliases = options.aliases || {}; + const id = Object.prototype.hasOwnProperty.call(aliases, name) ? aliases[name] : name; + const rules = options.providers || {}; + if (!Object.prototype.hasOwnProperty.call(rules, 'magpie:' + id)) return; + const rule = rules['magpie:' + id]; + return rule?.historyFilter === true ? rule : undefined; +} + export function onRequest(body, ctx) { if (ctx.protocol !== 'responses' || !body || typeof body.model !== 'string' || !/^[^/]+\/.+/.test(body.model)) return; - const prefix = body.model.split('/')[0]; - const options = ctx.options || {}; - const aliases = options.aliases || {}; - const id = Object.prototype.hasOwnProperty.call(aliases, prefix) ? aliases[prefix] : prefix; - const rules = options.providers || {}; - const rule = rules['magpie:' + id]; - if (!Object.prototype.hasOwnProperty.call(rules, 'magpie:' + id) || rule?.historyFilter !== true) return; + const rule = enabledRule(body.model.split('/')[0], ctx.options || {}); + if (!rule) return; try { if (/\/compact\/?$/.test(ctx.path || '')) { ctx.reject(409, 'Codex history filter: encrypted compaction cannot cross resources. Use a text summary and a new session.'); return; } - return filterResponsesRequest(body, {preserveEncryptedInclude: rule.preserveEncryptedInclude === true}).body; + const filtered = filterResponsesRequest(body, {preserveEncryptedInclude: rule.preserveEncryptedInclude === true}).body; + // A direct provider/model request is filtered here; its provider tries skip it. + if (ctx.state && typeof ctx.state === 'object') ctx.state.historyFiltered = true; + return filtered; } catch (error) { // Explicit rejection is required: Magpie forwards the original request if // a hook throws. Never silently discard non-portable context references. @@ -123,3 +132,21 @@ export function onRequest(body, ctx) { 'Codex history filter: ' + (error instanceof FilterError ? error.message : 'history could not be safely filtered.')); } } + +// A request sent through a Magpie group or fallback names the group, not a +// provider, so onRequest finds no rule. Each try on a provider applies that +// provider's own rule. A try can't be turned away, so history that can't move +// is sent as it was; only a direct provider/model request is refused. +export function onProvider(body, ctx) { + const provider = ctx?.provider; + if (ctx?.state?.historyFiltered === true || ctx?.protocol !== 'responses') return; + if (!body || typeof body !== 'object' || Array.isArray(body) || typeof provider?.id !== 'string') return; + if (/\/compact\/?$/.test(ctx.path || '')) return; + const rule = enabledRule(provider.id, ctx.options || {}); + if (!rule) return; + try { + return filterResponsesRequest(body, {preserveEncryptedInclude: rule.preserveEncryptedInclude === true}).body; + } catch { + return; + } +} diff --git a/packages/codex-history/group-routing.test.mjs b/packages/codex-history/group-routing.test.mjs new file mode 100644 index 0000000..2c787fa --- /dev/null +++ b/packages/codex-history/group-routing.test.mjs @@ -0,0 +1,48 @@ +import {test} from 'node:test'; +import assert from 'node:assert/strict'; +import * as middleware from './codex-history.middleware.js'; + +const options = {providers: {'magpie:demo': {historyFilter: true, preserveEncryptedInclude: true}}, aliases: {}}; +const history = model => ({model, include: ['reasoning.encrypted_content'], input: [ + {type: 'reasoning', id: 'rs_old', encrypted_content: 'FOREIGN', summary: []}, + {type: 'message', id: 'msg_old', role: 'assistant', content: [{type: 'output_text', text: 'KEEP'}]}, + {type: 'function_call', id: 'fc_old', call_id: 'pair', name: 'shell', arguments: '{}'}, + {type: 'function_call_output', id: 'fco_old', call_id: 'pair', output: 'KEEP_RESULT'}, + {role: 'user', content: 'next'}, +]}); +const context = (extra = {}) => ({protocol: 'responses', path: '/v1/responses', options, state: {}, + reject: () => assert.fail('a provider try cannot refuse a request'), ...extra}); + +test('a group try is sent what a direct request to that provider is', () => { + const group = history('group/sol-dedicated'); + const before = structuredClone(group); + assert.equal(middleware.onRequest(group, context()), undefined, 'a group prefix has no rule of its own'); + const direct = middleware.onRequest(history('demo/gpt-6-astra'), context()); + const sent = middleware.onProvider(group, context({provider: {id: 'demo', name: 'demo', model: 'gpt-6-astra'}})); + assert.deepEqual(sent, {...direct, model: group.model}); + assert.deepEqual(group, before, 'the hook does not change the body it is given'); +}); + +test('a request filtered by its own prefix is not filtered again on its try', () => { + const ctx = context(); + const filtered = middleware.onRequest(history('demo/gpt-6-astra'), ctx); + assert.equal(ctx.state.historyFiltered, true); + const provider = {id: 'demo', name: 'demo', model: 'gpt-6-astra'}; + assert.equal(middleware.onProvider(filtered, {...ctx, provider}), undefined); + assert.deepEqual(middleware.onProvider(structuredClone(filtered), context({provider})), filtered, + 'filtering the filtered body again changes nothing'); +}); + +test('a try that has no rule, is off, or carries history that cannot move stays byte-identical', () => { + for (const [label, request, extra] of [ + ['no rule', history('group/sol-dedicated'), {provider: {id: 'other', model: 'gpt-6-astra'}}], + ['rule off', history('group/sol-dedicated'), {provider: {id: 'demo', model: 'gpt-6-astra'}, + options: {providers: {'magpie:demo': {historyFilter: false}}}}], + ['cannot move', {...history('group/sol-dedicated'), previous_response_id: 'resp_old'}, + {provider: {id: 'demo', model: 'gpt-6-astra'}}], + ]) { + const bytes = JSON.stringify(request); + assert.equal(middleware.onProvider(request, context(extra)), undefined, label); + assert.equal(JSON.stringify(request), bytes, label); + } +}); diff --git a/packages/codex-history/package.json b/packages/codex-history/package.json index 88c9ffc..f26c25e 100644 --- a/packages/codex-history/package.json +++ b/packages/codex-history/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/middleware-codex-history", - "version": "0.1.1", + "version": "0.1.2", "description": "Opt-in, per-provider Codex Responses history compatibility for Magpie", "type": "module", "license": "MIT", diff --git a/packages/codex-history/web-search.test.mjs b/packages/codex-history/web-search.test.mjs index 38d7974..213f2c5 100644 --- a/packages/codex-history/web-search.test.mjs +++ b/packages/codex-history/web-search.test.mjs @@ -98,10 +98,10 @@ test('search adaptation keeps unsafe context rejection and explicit encrypted-co assert.match(text, /RECORDED_TEXT/); }); -test('the shipped middleware remains a small import-free package with only the request hook', () => { +test('the shipped middleware remains a small import-free package with request and provider-try hooks', () => { 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.equal(pkg.version, '0.1.2'); + assert.deepEqual(Object.keys(middleware), ['onProvider', '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);