feat(lua): 适配器共享前导 —— 消除 12680 字节的逐字重复

问题(实测证据,按钩子做字节级哈希分组):
  transform_response      github/groq/mistral 三份完全相同(2207B × 3)
  transform_stream_chunk  github/groq/kimicode/mistral 四份相同(2211B × 4)
  transform_error         deepseek/github/groq/kimicode 四份相同(293B × 4)
  合计 12680 字节完全重复。openai.lua 自己的注释就写着
  「(anthropic.lua carries the same helper; Lua adapters have no shared
  prelude.)」—— safe_tool_id 在 openai.lua 与 anthropic.lua 各复制了一份。

参考插件有 src/openai-compat.ts(1196 行,12 个 adapter 里 8 个 import),
我们没有对应物。本提交补上这一层。

做法:**编译期把一份中性助手库拼在适配器脚本前面**,注入点在
LoadAdapterSource —— 适配器有三个编译点(worker boot / HasFn 探针 /
inspectScript),全部源自这里存进 pool 的 script 文本,拼一处即全覆盖;
且不像运行时 SetGlobal 那样会在热重载/池重建时丢失。

助手只做**协议层面的中立清理与组装**,不含任何厂商名(守住内核零厂商名
纪律):decode_body / strip_control(剥内核私有控制字段 —— 那是网关内部
约定,v2 改一次就要改 12 个文件)/ unified_skeleton / finish_reason /
usage(含 cache 细分,属协议族已知变体)/ choices / tool_id(路由器性质:
坏 id 会被回放到每个 Claude 上游,一票否决整条 AUTO 链)/ derive_key。

判据两条:
- TestAdapterPreludeInjectedAndCorrect:不只断言存在,抽查**语义值**
  (end_turn→stop、tool_use→tool_calls、合法 id 原样透传、非法 id 带摘要
  改写、cache_hit 从 prompt_cache_hit_tokens 取)
- TestAdapterPreludeDoesNotChangeExistingAdapters:旧适配器(自己实现全部
  钩子、不引用前导)输出逐字节不变

回归:internal/lua + internal/provider 全绿(16 个适配器行为不变)。
This commit is contained in:
JianFeeeee
2026-10-13 22:34:13 +08:00
parent ed1e250452
commit 741edfea98
3 changed files with 312 additions and 0 deletions

View File

@ -873,6 +873,12 @@ func (v *VM) LoadAdapterSource(name, code string) error {
if err := ValidateAdapterName(name, nil); err != nil {
return err
}
// 共享前导注入点 —— 只此一处。适配器源码有三个编译点
//(worker boot / HasFn 探针 / inspectScript),它们全部源自这里存进
// pool 的 script 文本,所以拼在这里就同时覆盖三条路径,且不改变 Lua
// 作用域语义(运行时 SetGlobal 会在热重载/池重建时丢失)。
// 见 adapter_prelude.go 的开篇:12 个适配器里有 12680 字节的逐字重复。
code = withAdapterPrelude(code)
static, err := inspectScript(name, code)
if err != nil {
return err