Compare commits

...

6 Commits

Author SHA1 Message Date
b871c0c713 fix(zcode): 日期块对齐参考的两条规则(幂等 + 只看第一条),修 off-by-one
通读参考 zcode-identity.ts 的 withContextPrefix 后发现我的实现漏了两条官方行为,
且其中一条藏着真实 bug:

## ① ★ 幂等判断 off-by-one(真 bug)
`"<system-reminder>"` 是 **17** 个字符,而我写的是 `c:sub(1, 16) == SR`
—— 判断**永远为假** ⇒ 幂等完全失效:同一请求重试/多次 transform 时日期块
会叠加成多层,改变 content 的前缀结构(上游检查的正是这个结构)。
修法:用 `#SR` 算长度,不写死数字。

## ② 只看**第一条**消息,且它必须 role == "user"
我原来实现成「往后扫第一个 user 消息」。官方行为是:只处理 `messages[0]`,
且若它不是 user 就**完全不动** —— 不是去找后面那条 user。已对齐。

## ③ 其它类型兜底
参考对非字符串/非数组的 content 也会置为 `[prefix]`,照做。

判据 2 条(新增):
- TestZcodeContextPrefixIsIdempotent     已含日期块时不重复插
- TestZcodeContextPrefixOnlyTouchesFirstMessage  首条非 user 时不动、首条 user 时插入
变异 2/2 咬住:把 #SR 改回写死的 16 → 报红;去掉幂等判断 → 报红。

★ 我自己在写这条判据时又犯了一个错并当场自查出来:断言「文本 content 应保持
字符串」,而 anthropic 基座把文本转成块数组是**正常**的协议转换行为 —— 差点把
正确的实现判成错。判据要验的是「**日期块**有没有被插进来」这个事实,不是
content 的容器类型。

验证:internal/core 335s + internal/gateway 207s 全绿。
2026-10-16 01:13:11 +08:00
8b318a8507 feat(zcode): 身份块适配器 + 修复调度器泄漏 + codearts 目录 + 备份裁剪泛化
## 1. ★ zcode 身份块适配器(channels-zcode)—— 准入的唯一开关
参考实测(三账号 17 次请求):zcode 的 /zcode-plan/anthropic 通道做**请求体
内容检查**,system 缺官方身份块结构时直接 HTTP 405 + {"code":3012}:

    无 system                        → 3012 ✗
    仅 cliPrefix(42 字符)           → 3012 ✗
    cliPrefix + stable(约 2898 字符)→ 200  ✓

⇒ 判据是「身份块结构是否存在」,与 HTTP 头、版本号、频率、多轮历史、tools
声明、运行时全部无关。我们此前用通用 anthropic 适配器 ⇒ **即使拿到 zcode
账号也必然被拒**(现在 0 账号,但这是能不能用起来的前提)。

实现:插件自装 channels-zcode —— 读内核 anthropic.lua 执行取基座,**只覆盖
transform_request** 注入身份块(协议转换始终与 anthropic 那一份一致,不漂移):
  block[1] cliPrefix(42) / block[2] stable(2852) / block[3] Environment 段
  / block[4] 调用方 system(**必须追加在最后**:上游看的是前缀结构)
  只给最后一块打 cache_control(Anthropic 上限 4 断点,逐块打会占满预算)
  日期块插入首条 user 的 content **数组**最前(拼进字符串会改变结构)
文本与参考**逐字节一致**(已核对:42 + 2856 = 2898)。
★ 基座读不到时**响亮失败**,不静默退化 —— 否则会产出"身份块看着对、工具/图像
全没转换"的请求,上游可能 200 但模型拿不到工具定义,症状是"模型变笨了",
与准入毫不相干、排查完全跑偏。

判据 4 条 + 变异 2/2:不注入 → 报红;截断到 100 字符 → 报红。
另加"协议转换不退化"判据(工具 input_schema / 图像块存活)。

## 2. ★★ 同一缺陷家族第 3 个实例:Close() 不停调度器
修完 on_unload 后全量回归 internal/lua **600s 超时**,goroutine 快照显示
**69 个卡在 stateSaver.loop 与 PluginRuntime.loop**。
根因:Runtime.Stop() **只在单插件 Unload 里调**,Close() 不调 ⇒ 每个插件的
调度循环在"进程关闭/测试结束"路径上永不停止。与 on_unload 完全同一形状。
修法:Close() 新增 stopSchedulersAll(),顺序 = 停调度 → 落盘 → on_unload
(调度器必须停在落盘之前,否则它写一个已收尾的 state)。
★ 顺带:Stop() 不幂等(裸 close 会 panic: close of closed channel),
两处都调之后可达 —— 用 sync.Once 加固。给函数加第二个调用点前先查幂等性。
实测 internal/lua 从 600s 超时 → 62s 通过。

## 3. codearts 模型目录:补两个**必须 AK/SK 签名**的端点
codearts 有 10 个账号但目录里只有硬编码 1 个模型。参考打两个端点:
  ① opengw.../gateway/config  → result.models(benefit)
  ② snap-access.../v1/model/builtin → builtinModels(常规)
而 refreshRemoteModels **只支持 Bearer** ⇒ 这两端点从来没被打过。
已加 ep.sign="codearts" 分支 + 两个解析形态 + opengw host 白名单。
判据:两端点各自真实命中 + 每请求带 SDK-HMAC-SHA256 头 + **合并**(非取其一)。

## 4. TRAE PKCE 候选来源补齐(3 → 5)
参考 authCodeCandidates 有 5 个来源,我们只有 3(漏了 authCodeInfo 为 JSON 的
authCode 字段、以及**纯字符串**形态)。★ 且不能写成 `a or b or c` 链 ——
jsonField 取不到时返回**空串**,Lua 里空串是真值,链会在第一个空串处短路。
判据 5 个参数化用例 + 变异 2/2 咬住(正是 or 链取不到的两个形态)。

## 5. ★ 部署脚本:备份裁剪只修了一半("两处只修一处"再现)
prune_adapter_backups 有完整实现(含数量硬上限),但**只针对 adapters.bak**;
sync_plugins 同样每次建 plugins.bak.* —— 修了 adapters 的堆积、plugins 继续涨。
实测线上 plugins.bak **36 个**、/etc/llmsproxy 192M。
泛化为 prune_backups <prefix> + prune_all_backups(两个前缀都裁),加空前缀守卫。
判据不止逐字检查,而是**扫描脚本里所有 .bak.$(date) 创建点**,要求每个前缀都在
裁剪范围内 —— 将来新增第三种备份目录会立刻报红,而不是等它涨到几百兆。
变异 2/2 咬住(只裁 adapters / 去掉守卫)。

## 6. 上游客观缺口钉成可执行判据(TestUpstreamGapsAreDocumented)
qoder 加密端点需 .wasm(**参考仓库里也不存在**)、TRAE PKCE 参考**明确不支持**、
zcode 滑块需真实浏览器交互。写成判据:任何人(包括未来的我)想"补"这些能力,
必须先让判据失败 —— 即先推翻事实再动手。防的正是我前两轮的反复误判。

清理:channels-buddy.lua(0 字节历史遗留,每次启动报 must return a table)。
2026-10-16 00:56:14 +08:00
69da3c9b92 fix(kernel): Close() 从不调 on_unload —— 孤儿进程与回调文件泄漏
## 症状
本机积累 **995 个 llmsproxy-loopback.py 进程**(828 个超 24 小时),全是
/tmp/Test*/ 与 .build-work/Test*/ 下的测试残留;生产 /etc/llmsproxy/plugins/
另有 **18 个孤儿 callback-*.port**(对应 .json 早已消失),且永远清不掉。

## 真因(两层)
1. **回环回收本是惰性的**:reapLoopback 只在**会话过期**时被 sweepSessions
   触发。测试跑完直接退出 ⇒ 会话从未「过期」⇒ 进程常驻。生产会话真会过期,
   所以生产不漏进程 —— 但见第 2 条。
2. **★ 根因在内核**:Plugins.Close() 只关 shard 与 saver,**从不调用
   on_unload** —— 而 on_unload 只在**单插件 Unload** 时调。于是「进程关闭/
   测试结束」这条路径上,起了 OS 进程的插件永远收不了尾。插件的
   plugin.on_unload(回收浏览器栈 + 回环)写得完全正确,只是从不被调用。
   这是「两处只修一处」缺陷的又一例:Unload 有、Close 没有。

## 修法
- 抽 invokeOnUnload(p, name) 助手,**Unload 与 Close 共用同一份实现**
  (两处各写一遍必然漂移,本次缺陷形状正是如此);Close() 新增
  callOnUnloadAll()。
- ★ 顺序:shards.Shutdown() → save.Close()(落盘)→ callOnUnloadAll()。
  落盘必须在前 —— saver 的最终写入要读插件的 Lua 表,on_unload 之后 state
  已关,读到的就是空,最后一个区间的累积静默丢失(TestCloseFlushesTail 正是
  为守住这一点而存在)。我第一版把顺序写反,被该测试当场咬住。
- channels:启动清扫上一进程留下的孤儿 callback-*.port/.json。loopbacks
  追踪表只活在内存,进程被强杀时 on_unload 没机会跑,重启后内存表为空 ⇒
  reapLoopback 无从知晓 ⇒ 那 18 个文件永久残留。
- channels:补 reap_loopbacks 端点(生产运维也可用:不必等会话过期)。
- channels:__set_loopback_probe 从**覆盖**改为**合并**条目 —— 覆盖会丢掉
  真实会话的 pid/port_file,让 reapLoopback 杀不掉接收器,**探针自己成为
  泄漏源**(实测:其他测试已归零,只有它留 1 个孤儿)。

## 判据(均做变异验证)
- internal/lua/plugin_unload_on_close_test.go
    TestPluginsCloseCallsOnUnload      看真实外部效应(插件在 on_unload 写磁盘
                                       marker),而非「钩子被调用过」这类内部信号
    TestPluginsCloseSurvivesFailingOnUnload  best-effort 契约
- internal/core/channels_orphan_callback_test.go
    TestPluginLoadSweepsOrphanCallbackFiles  看目录真实状态:孤儿必须消失,
                                       非回调文件(.channels-store.json)不得误删
- 变异均咬住:注释掉 callOnUnloadAll → 报红;清扫改 no-op → 报红。

## 实测
修复前跑一次起会话的测试批次留 7×N 个残留进程 → 修复后 **0 个**;全量回归
(go test -tags luajit ./... 10 包)后回环/VNC 残留均为 0。

## 过程中自查出的两处疏漏(已修)
1. 判据顺序又写反一次(同上 TestCloseFlushesTail 咬住)。
2. **两枚变异残渣留在工作区**未还原:internal/gateway/discover.go 里
   `add(raw, "/models", 0)` 被删、`classifyAuthStatus` 的 `|| len(body) >= 0`
   恒真注入。已 git checkout 还原。教训:变异测试必须逐次收尾,别靠记忆。
2026-10-15 22:43:08 +08:00
1be34557dd fix(trae): 登录失败真因 —— 虚构的「授权码交换」+ 空 client_id
用户报「TRAE 登录后显示失败」。定位到三处偏差,其中一处是核心缺陷:

① ★ **虚构了一次不存在的「授权码交换」**(核心)
   poll_login 的 trae 分支自己发明了一段逻辑:回调只带 code 时,拿
   exchange_body 去打 ExchangeToken。但:
     · ExchangeToken 的签名是 RefreshToken,不是 code;
     · exchange_body 里根本没有 {code} 占位符,那次替换是空操作;
     · client_id 当时是空串。
   于是稳定 400,日志回一句误导性的「Trae 授权码交换失败: 400」——
   把真因「上游走了 PKCE 流程」掩盖成「交换出错了」,排查方向完全错。

   按参考实现(trae-oauth.ts parseTraeCallbackDetailed)修正:带 code 的
   回调是**合法回调**,只是不支持的 PKCE 分支,必须明确报出来。
   删除虚构交换,两条路径共用 traeCallback 内建的 PKCE 判定。

② client_id 从空串改为实测真值 en1oxy7wnw8j9n(对齐参考 trae-product.ts
   的 clientId;ExchangeToken 请求体里 ClientID 必填,留空稳定 400)。

③ 两条路径(oauth_callback / poll_login)现在共用同一结论,不再漂移 ——
   这正是缺陷能藏住的原因:修复只覆盖一条、另一条继续错。

测试支撑:
- 新增 __set_loopback_probe(注入 loopback 回调文件),否则无法驱动
  poll_login 的 callback 分支(那才是真实登录走的路径)。
- 判据 4 条,全部做变异验证:
    TestTraePkceCallbackIsReportedNotExchanged  打 poll_login,断言没打 ExchangeToken 且点名 PKCE
    TestTraeExchangeSendsRealClientID           token 直传真调交换,请求体形状正确
    TestTraeClientIDIsNotBlank                  client_id 必须是实测真值
    TestTraeCallbackPathsAgreeOnPkce            两条路径必须共用 traeCallback
- 变异 2/2 咬住:client_id 改回空串 → 报红;虚构交换加回去 → 「实际打了 1 次
  ExchangeToken」。

★ 我在过程中自己犯的两个错(均由变异测试揭穿,已修正):
1. **判据打错了路径** —— 第一版打 oauth_callback(那条一直是对的),注入缺陷后
   判据**仍绿**。改成打 poll_login 才咬住。教训:判据必须打**真实被使用的那条
   路径**,否则等于没测。
2. **判据写错了契约** —— poll_login 用 HTTP 200 + json.state 表达终态,我按
   status != 200 断言,把正确的实现判成了错。

回归:go test -tags luajit ./... 10 包全绿。
2026-10-15 22:04:01 +08:00
9e5fec08b8 feat(opencode): Zen 免费层可用 —— 门禁四要素 + id 公式逆出
问题:localzen 源(opencode Zen)整个免费池恒 403 FreeTierError
("free tier can only be used from within OpenCode"),space-bunny-free
等免费模型全部失效。

排查(装官方 CLI 抓包 + 逆其本地 opencode.db,见下):门禁是**四条请求形状
条件**,与 TLS 指纹 / UA / 凭据来源 / system 内容 / 消息条数全部无关:

  1. 端点必须是 /inference/v1/chat/completions(原来打的 /zen/v1 恒 403)
  2. 必须同时发 x-opencode-session 与 x-opencode-session-id(值相同)
  3. tools 里必须有一个名为 read 的工具,且其 parameters.properties **非空**
     (实测:抽掉官方 11 个工具中任意一个仍 200,**只有抽掉 read 变 403**;
      properties 里放任意属性名即可,描述/$schema/required 都不需要;
      改成 properties:{} 或只有 type:object 则 403)
  4. stream 必须为 true(同 body 改 false 恒 403)

★ 两个 id 的 12 位 hex 段由**确定公式**给出(逆自 opencode.db 的 session 表,
用 11/12 条真实 id 逐条比对完全一致):

  MASK = 2^48-1 ; K = 0x1afffffffffffe   (注意不是 27<<48,两者差 2)
  session 段 = (K - now_ms*4096) & MASK   ← 倒计时式,Δseg/Δms ≡ -2^12
  request 段 = (now_ms*16) & MASK

  时间容差实测 ≥1 小时(-3600s 仍 200),故 os.time() 的秒精度足够;
  now_ms*4096 ≈ 7.3e15 < 2^53,在 double 安全整数范围内。

实现:
- id 生成换成上述公式(原用 sha256 派生,完全不符)
- 补 x-opencode-session-id;两个头同值
- 会话号按**整分钟桶**取:既满足门禁的倒计时公式,又保留上游前缀缓存命中
  (实测 cached_tokens: 256 生效)
- tools 兜底:客户端没带 tools 时注入带非空 properties 的 read 桩;
  用户自带 read 则原样保留,不覆盖其定义
- 强制 stream=true
- ★ transform_response 支持 SSE 聚合:免费层只能流式,而客户端可能发非流式,
  此时内核按客户端意图走 Chat/transform_response(期望 JSON)⇒ 必须自行把
  SSE 聚合成 chat.completion,否则报 "invalid character 'd'"

配置(已在生产落地):
- localzen base_url: /zen/v1 → /inference/v1(billing 规则同步)
- 免费模型 1 个 → 8 个(含 deepseek-v4.1-flash-free)
- 适配器移入 internal/lua/adapters/,随 deploy.sh 自动投放

判据(4 条):
- TestOpencodeZenAdapterE2E                       头公式/两头部同值/tools 兜底/不覆盖
- TestOpencodeZenAggregatesSSEForNonStreamClient   SSE → chat.completion 聚合
- TestOpencodeZenLiveE2E                          ★真上游:纯对话/自定义system/多轮/算术
- TestOpencodeZenLiveStreamThroughAdapter         ★真上游:完整流解析链(25 chunk)
  (后两条需 LLMSPROXY_LIVE_ZEN=1 + 真实凭据,默认 skip)

生产 e2e 实测:非流式返回 GW-NONSTREAM-OK(usage 含 cached_tokens 256);
流式原生 SSE 透传;多轮+工具返回正确结果(12*12=144 → 144+1=145)。

回归:go test -tags luajit ./... 10 包全绿。

★ 方法论教训(本轮绕了 4 轮、自我推翻 3 次):
- 一次只改一个变量。我多次同时改 system+条数+tools,拟合出"消息条数上限 3"
  这种假规律,后续每次反转都源于此 —— 真相是那些测试**都缺 tools**。
- 重放成功 ≠ 解释成功。第一次逐字节重放就 200,我却当"重放了官方刚发的请求",
  继续追 TLS 指纹/端点/形状。正确做法:一旦重放成功立刻做**单变量消去**。
- "毒药短语"陷阱:我二分到 963/964 字符精度锁定 Never use tools 是触发点,
  但它单独出现全 200 —— 真相是缺 read 的 properties。凡"某内容触发"的规律
  必须交叉验证。
2026-10-15 20:30:33 +08:00
68446fb6fe fix(vnc): noVNC 的 path 必须用相对名,否则 WebSocket 路径重复拼接
真实缺陷(白屏真因之一):view_url 里传了**站点根路径**作为 noVNC 的
path 参数:

  .../proxy/<id>/vnc.html?path=api%2Fplugins%2Fhttp%2Fchannels%2Fbrowser%2Fproxy%2F<id>%2Fwebsockify

但 noVNC 用 `new URL(path, location.href)` 解析它(app/ui.js 的 connect()),
即**相对 vnc.html 所在目录**解析,默认值就是相对名 "websockify"。传根路径
会被当相对路径 ⇒ 实际请求变成路径重复拼接:

  .../proxy/<id>/api/plugins/http/channels/browser/proxy/<id>/websockify

于是 WebSocket 永远连不上,noVNC 显示连接失败,页面看似白屏。

修法:只传相对名 path=websockify,与 noVNC 默认值一致。

★ 判据:必须解析**产品自己给出的 URL**(而不是测试里手拼)。我上一轮验证时
手拼 URL 并省掉了 path 参数(默认值恰好正确)⇒ 掩盖了这个真实缺陷。
新判据断言:path 存在、不以 / 开头、且 ResolveReference 后等于同级 websockify。
2026-10-15 20:30:33 +08:00
16 changed files with 2810 additions and 79 deletions

View File

@ -309,48 +309,60 @@ verify_master_key() {
return 1
}
# ---------- 适配器备份保留策略 ----------
# 每次部署都新建一个 adapters.bak.<时间戳> 目录,而回滚只用到最近一次
# ---------- 备份目录保留策略 ----------
# 每次部署都新建一个 <prefix>.bak.<时间戳> 目录,而回滚只用到最近一次
# ($BACKUP_BIN / $BACKUP_CONFIG 都是单文件覆盖)。多出来的目录从没人清理,
# 实测线上已积累 71 个,/etc/llmsproxy 因此涨到 122M。
#
# 保留最近 KEEP_ADAPTER_BACKUPS 份足够回滚,同时给目录数设上限——否则
# 一次误配置(比如 adapter_dir 指错)就可能在几秒内造出成百上千个目录。
# 只删名字严格匹配 adapters.bak.<14位时间戳> 的目录,避免误伤人工放的目录。
KEEP_ADAPTER_BACKUPS=5
# 保留最近 KEEP_BACKUPS 份足够回滚,同时给目录数设上限——否则一次误配置
# 就可能在几秒内造出成百上千个目录。
# 只删名字严格匹配 <prefix>.bak.<14位时间戳> 的目录,避免误伤人工放的目录。
#
# ★ 必须**同时覆盖 adapters 与 plugins**(同一缺陷的两个实例):
# 本函数最初只处理 adapters.bak,而 sync_plugins 同样每次建 plugins.bak.*
# —— 于是修了 adapters 的堆积、plugins 继续涨(实测线上 36 个、占用 192M)。
# 这正是「两处只修一处」的老形状:给一个新前缀加备份目录时,必须同步纳入
# prune_all_backups,否则它就是一个不会被清理的新泄漏点。
KEEP_BACKUPS=5
prune_adapter_backups() {
prune_backups() {
local prefix="$1"
local base="/etc/llmsproxy"
[[ -d "$base" ]] || return 0
# 防误用:前缀必须是已知的两个(避免有人传空串删掉整个目录)
case "$prefix" in
adapters|plugins) ;;
*) fail "prune_backups: 未知前缀 '$prefix'(只接受 adapters|plugins)" ;;
esac
# 先按数量上限硬裁:即使时间戳排序失效也不会无上限增长。
local all
mapfile -t all < <(find "$base" -maxdepth 1 -type d -name 'adapters.bak.*' -printf '%f\n' | sort)
local cap=$((KEEP_ADAPTER_BACKUPS * 4))
mapfile -t all < <(find "$base" -maxdepth 1 -type d -name "$prefix.bak.*" -printf '%f\n' | sort)
local cap=$((KEEP_BACKUPS * 4))
if (( ${#all[@]} > cap )); then
warn "适配器备份目录有 ${#all[@]} 个(异常),裁到 $cap"
warn "$prefix 备份目录有 ${#all[@]} 个(异常),裁到 $cap"
local i=0
for d in "${all[@]}"; do
i=$((i + 1))
# 从最旧的开始删(sort 后升序)。名字不规范的跳过不删。
if (( i <= ${#all[@]} - cap )); then
if [[ "$d" =~ ^adapters\.bak\.[0-9]{14}$ ]]; then
if [[ "$d" =~ ^"$prefix"\.bak\.[0-9]{14}$ ]]; then
rm -rf "${base:?}/$d"
else
warn "跳过名字不规范的备份目录(不删): $d"
fi
fi
done
mapfile -t all < <(find "$base" -maxdepth 1 -type d -name 'adapters.bak.*' -printf '%f\n' | sort)
mapfile -t all < <(find "$base" -maxdepth 1 -type d -name "$prefix.bak.*" -printf '%f\n' | sort)
fi
# 再按时间保留最近 KEEP_ADAPTER_BACKUPS 份(sort 后最新在末尾)。
# 再按时间保留最近 KEEP_BACKUPS 份(sort 后最新在末尾)。
local total=${#all[@]} i=0
for d in "${all[@]}"; do
i=$((i + 1))
# i <= total-KEEP 的是较旧的,要删。
if (( i <= total - KEEP_ADAPTER_BACKUPS )); then
if [[ "$d" =~ ^adapters\.bak\.[0-9]{14}$ ]]; then
if (( i <= total - KEEP_BACKUPS )); then
if [[ "$d" =~ ^"$prefix"\.bak\.[0-9]{14}$ ]]; then
rm -rf "${base:?}/$d"
else
warn "跳过名字不规范的备份目录(不删): $d"
@ -359,8 +371,15 @@ prune_adapter_backups() {
done
local left
left=$(find "$base" -maxdepth 1 -type d -name 'adapters.bak.*' | wc -l)
log " 适配器备份保留最近 $KEEP_ADAPTER_BACKUPS 份(当前剩 $left 个)"
left=$(find "$base" -maxdepth 1 -type d -name "$prefix.bak.*" | wc -l)
log " $prefix 备份保留最近 $KEEP_BACKUPS 份(当前剩 $left 个)"
}
# prune_all_backups:两个前缀都裁。
# ★ 新增任何 .bak.<时间戳> 目录的前缀时,必须在这里补上 —— 否则又一个泄漏点。
prune_all_backups() {
prune_backups adapters
prune_backups plugins
}
# ---------- 同步适配器 ----------
@ -380,7 +399,7 @@ sync_adapters() {
cp -rf "$TARGET_ADAPTERS/"*.lua "$BACKUP_DIR/" 2>/dev/null || true
log " 旧适配器已备份到 $BACKUP_DIR"
fi
prune_adapter_backups
prune_all_backups
cp -f "$SRC_ADAPTERS/"*.lua "$TARGET_ADAPTERS/"
chmod 0644 "$TARGET_ADAPTERS/"*.lua

View File

@ -0,0 +1,174 @@
package core
import (
"fmt"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
"llmsproxy/internal/lua"
)
// ★ codearts 的模型目录必须从**两个**签名端点拉取并合并。
//
// 真实缺口(本轮发现):codearts 有 10 个可用账号,但目录里只有硬编码的
// 1 个模型 "CodeArts-Pangu"。参考实现(fetchCodeArtsRemoteModels)打的是:
//
// ① opengw gateway/config → result.models(benefit 模型)
// ② snap-access /v1/model/builtin → builtinModels(常规模型)
//
// 两者都**必须 AK/SK 签名**,而我们的 refreshRemoteModels 此前只支持 Bearer
// ⇒ 这两个端点从来没有被打过。
//
// 判据看**两个端点的真实命中**(各自拉到自己的字段名),而不是"目录非空"
// —— 后者只要兜底表在就恒真。
type codeartsCatalogHarness struct {
t *testing.T
ps *lua.Plugins
mu sync.Mutex
hits map[int]int // 端点序号 → 命中次数
gateway string
builtin string
authSeen []string
}
func newCodeartsCatalogHarness(t *testing.T) *codeartsCatalogHarness {
t.Helper()
h := &codeartsCatalogHarness{t: t, hits: map[int]int{}}
mk := func(idx int, body string) *httptest.Server {
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
h.mu.Lock()
h.hits[idx]++
// ★ 必须看到 AK/SK 签名的三个特征头,否则等于没签名
authSeen := []string{
r.Header.Get("X-Sdk-Date"),
r.Header.Get("X-Sdk-Content-Sha256"),
r.Header.Get("Authorization"),
}
h.authSeen = append(h.authSeen, strings.Join(authSeen, "|"))
h.mu.Unlock()
w.Header().Set("Content-Type", "application/json")
fmt.Fprint(w, body)
}))
}
// ① gateway:benefit 模型在 result.models
gw := mk(0, `{"result":{"models":[{"model_id":"glm-5.3-flash"},{"model_id":"deepseek-v4-flash"}]}}`)
// ② snap builtin:常规模型在 builtinModels(**对象**,键为序号)
bi := mk(1, `{"count":2,"builtinModels":{"0":{"model_id":"GLM-5.2"},"1":{"model_id":"openpangu-2.0-pro"}}}`)
t.Cleanup(gw.Close)
t.Cleanup(bi.Close)
h.gateway, h.builtin = gw.URL, bi.URL
c := kernelTestCore(t)
ps := c.Plugins()
src, err := readBundledChannels(t)
if err != nil {
t.Fatal(err)
}
if err := ps.LoadSource("channels", src); err != nil {
t.Fatal(err)
}
h.ps = ps
// 把两个端点都指到假上游(顺序与平台配置一致)
if _, err := ps.Call("channels", "set_endpoints", map[string]interface{}{
"platform": "codearts",
"models_remote": map[string]interface{}{
"endpoint0": h.gateway,
"endpoint1": h.builtin,
},
}); err != nil {
t.Fatalf("set_endpoints: %v", err)
}
// 塞一个 AK/SK 账号(签名分支需要凭据,否则会走 "无可用 AK/SK 凭据")
if _, err := ps.Call("channels", "account_add", map[string]interface{}{
"platform": "codearts",
"id": "cat-test",
"credential": `{"access_key_id":"AKTEST","secret_access_key":"SKTEST",` +
`"security_token":"STTEST","user_name":"cat"}`,
}); err != nil {
t.Fatalf("account_add: %v", err)
}
return h
}
func TestCodeArtsCatalogPullsBothSignedEndpoints(t *testing.T) {
h := newCodeartsCatalogHarness(t)
if _, err := h.ps.Call("channels", "model_refresh", map[string]interface{}{"platform": "codearts"}); err != nil {
t.Fatalf("model_refresh: %v", err)
}
h.mu.Lock()
hits := map[int]int{}
for k, v := range h.hits {
hits[k] = v
}
authSeen := append([]string(nil), h.authSeen...)
h.mu.Unlock()
// ① 两个端点都必须被命中(只打一个是真实缺口)
if hits[0] == 0 {
t.Fatal("gateway/config 端点从未被调用 —— benefit 模型(glm-5.3-flash 等)永远拿不到")
}
if hits[1] == 0 {
t.Fatal("snap /v1/model/builtin 端点从未被调用 —— 常规模型(GLM-5.2 / openpangu)永远拿不到")
}
// ② 每个请求都必须带 AK/SK 签名特征头(Bearer 打不通这两个端点)
for i, seen := range authSeen {
parts := strings.Split(seen, "|")
if len(parts) != 3 || parts[0] == "" || parts[1] == "" || parts[2] == "" {
t.Fatalf("第 %d 个请求缺签名头(X-Sdk-Date/Content-Sha256/Authorization):%q", i+1, seen)
}
if !strings.Contains(parts[2], "SDK-HMAC-SHA256") {
t.Fatalf("Authorization 不是华为 SDK-HMAC-SHA256 形态,实得 %q", parts[2])
}
}
// ③ 合并结果必须同时含两个端点的模型(字段名不同:model_id,两边都要认)
got, err := h.ps.Call("channels", "model_list", map[string]interface{}{"platform": "codearts"})
if err != nil {
t.Fatal(err)
}
ids := modelIDs(t, got)
joined := strings.Join(ids, ",")
for _, want := range []string{"glm-5.3-flash", "GLM-5.2", "openpangu-2.0-pro"} {
if !strings.Contains(joined, want) {
t.Fatalf("合并目录缺 %s(两个端点必须**合并**而非只用其一):%v", want, ids)
}
}
t.Logf("✓ 两端点各命中 %d/%d 次,合并得到 %d 个模型", hits[0], hits[1], len(ids))
}
// 兜底表在远端失败时必须仍然可用(不能因为加了目录就让平台变空)。
func TestCodeArtsCatalogKeepsFallbackOnFailure(t *testing.T) {
h := newCodeartsCatalogHarness(t)
// 让两个端点都 500
dead := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(500)
}))
defer dead.Close()
if _, err := h.ps.Call("channels", "set_endpoints", map[string]interface{}{
"platform": "codearts",
"models_remote": map[string]interface{}{
"endpoint0": dead.URL, "endpoint1": dead.URL,
},
}); err != nil {
t.Fatal(err)
}
if _, err := h.ps.Call("channels", "model_refresh", map[string]interface{}{"platform": "codearts"}); err != nil {
t.Fatalf("远端失败不该让 model_refresh 报错: %v", err)
}
got, err := h.ps.Call("channels", "model_list", map[string]interface{}{"platform": "codearts"})
if err != nil {
t.Fatal(err)
}
ids := modelIDs(t, got)
if len(ids) == 0 {
t.Fatal("远端全失败时目录变空了 —— 兜底表必须补位(宁可留旧目录也别让平台变空)")
}
t.Logf("✓ 远端失败时兜底目录仍有 %d 个模型: %v", len(ids), ids)
}

View File

@ -0,0 +1,82 @@
package core
import (
"os"
"path/filepath"
"testing"
"llmsproxy/internal/lua"
)
// ★ 插件加载时必须清掉上一进程留下的孤儿回调文件。
//
// 真实事故:生产 `/etc/llmsproxy/plugins/` 攒了 **18 个 callback-*.port**
// (对应的 .json 早已消失)。它们永远不会被清,因为:
//
// · loopbacks 追踪表只活在内存(plugin.state.loopbacks);
// · 进程被强杀时 on_unload 没机会跑;
// · 重启后内存表是空的 ⇒ reapLoopback 根本不知道它们存在。
//
// 判据看的是**目录的真实状态**(孤儿必须消失、活跃会话的文件不能被误删),
// 而不是"某函数被调用过"。
func TestPluginLoadSweepsOrphanCallbackFiles(t *testing.T) {
dir := t.TempDir()
pluginDir := filepath.Join(dir, "plugins")
if err := os.MkdirAll(pluginDir, 0755); err != nil {
t.Fatal(err)
}
t.Setenv("LLMSPROXY_PLUGIN_DIR", pluginDir)
// 摆上一轮的残留(模拟上一进程被强杀后的现场)
orphans := []string{
filepath.Join(pluginDir, "callback-deadbeef0001.port"),
filepath.Join(pluginDir, "callback-deadbeef0001.json"),
filepath.Join(pluginDir, "callback-deadbeef0002.port"),
}
for _, f := range orphans {
if err := os.WriteFile(f, []byte("12345"), 0600); err != nil {
t.Fatal(err)
}
}
// 一份**不属于**回调的文件:必须不被误删(否则清扫过头会毁掉账号池)
keep := filepath.Join(pluginDir, ".channels-store.json")
if err := os.WriteFile(keep, []byte(`{"accounts":{}}`), 0600); err != nil {
t.Fatal(err)
}
// 加载插件 = 走真实启动路径
c := kernelTestCore(t)
defer c.Close()
src, err := readBundledChannels(t)
if err != nil {
t.Fatal(err)
}
ps := c.Plugins()
if err := ps.LoadSource("channels", src); err != nil {
t.Fatal(err)
}
// 顶层清扫代码在加载期就跑了;给 popen 的 rm 一点时间落盘
for i := 0; i < 50; i++ {
left := 0
for _, f := range orphans {
if _, err := os.Stat(f); err == nil {
left++
}
}
if left == 0 {
break
}
}
for _, f := range orphans {
if _, err := os.Stat(f); err == nil {
t.Fatalf("孤儿回调文件未被清扫: %s —— 它会永久留在磁盘上"+
"(真实事故:生产攒了 18 个)", filepath.Base(f))
}
}
if _, err := os.Stat(keep); err != nil {
t.Fatalf("清扫过头了:%s 被误删(账号池/索引绝不能碰)", filepath.Base(keep))
}
t.Log("✓ 孤儿回调文件被清,非回调文件保留")
}
var _ = lua.Plugins{}

View File

@ -0,0 +1,200 @@
package core
import (
"encoding/json"
"fmt"
"os"
"path/filepath"
"strings"
"sync/atomic"
"testing"
"llmsproxy/internal/lua"
)
// ★ TRAE 回调只带 code(PKCE 形态)时必须**明确报出**「暂不支持 PKCE」,
// 而不是去调 ExchangeToken 换一个不存在的码。
//
// 真实缺陷(用户报「登录后显示失败」):
// poll_login 的 trae 分支曾自己发明了一段「授权码交换」——把 {code} 塞进
// exchange_body 再打 ExchangeToken。但:
//
// · ExchangeToken 的签名是 RefreshToken,不是 code;
// · exchange_body 里根本没有 {code} 占位符,那次替换是空操作;
// · client_id 当时是空串。
//
// 于是稳定得到 400,日志回一句误导性的「Trae 授权码交换失败: 400」,
// 把真因「上游走了 PKCE 流程」掩盖成「交换出错了」——排查方向完全错。
//
// 参考实现(trae-oauth.ts parseTraeCallbackDetailed)的做法是:带 code 的回调
// 是**合法回调**,只是不支持的 PKCE 分支,必须明确报出来。
func TestTraePkceCallbackIsReportedNotExchanged(t *testing.T) {
h := newTraeHarness(t)
// ★ 必须打**真实登录用的那条路径**:poll_login(loopback 回调文件)。
// oauth_callback 那条一直是对的,判据打在那里会漏掉缺陷 —— 我第一版就
// 犯了这个错(变异测试揭穿:注入缺陷后那条判据仍绿)。
//
// poll_login 从 plugin.state.loopbacks[sessionId].file 读 {code,state},
// 故判据直接摆好那个文件再调 poll_login。
status, body := h.beginAndPollWithCallback(map[string]string{
"code": "PKCE_AUTH_CODE_XYZ",
})
// poll_login 的契约:终态用 HTTP 200 + json.state 表达(不是非 200 状态码)。
// 所以「失败」的判据是 state=failed,而不是 status != 200 —— 我第一版把
// 前者写成了后者,于是把正确的实现判成错。
if !strings.Contains(body, "state:failed") {
t.Fatalf("PKCE 回调应落定为 failed(poll_login 用 200+state 表达终态):status=%d body=%s",
status, body)
}
if n := atomic.LoadInt32(&h.exchHit); n != 0 {
t.Fatalf("不得去调 ExchangeToken —— 那是拿 code 换一个不存在的码(真实缺陷)。"+
"实际打了 %d 次", n)
}
// 错误信息必须指向真因(PKCE),而不是含糊的交换失败
blob := body
if !strings.Contains(blob, "PKCE") {
t.Fatalf("错误信息应点名 PKCE(让排查方向正确),实得 %q", blob)
}
if strings.Contains(blob, "授权码交换失败") {
t.Fatalf("不应再出现误导性的「授权码交换失败」:%q", blob)
}
t.Logf("✓ PKCE 回调被正确识别(poll_login 路径): %s", strings.TrimSpace(blob))
}
// ★ client_id 必须是实测真值 —— ExchangeToken 的请求体里 ClientID 是必填。
// 留空会让真实 token 直传场景的交换稳定 400(夹具自身也校验 ClientID 存在)。
func TestTraeExchangeSendsRealClientID(t *testing.T) {
h := newTraeHarness(t)
// 真实回调形态:带 refreshToken(token 直传)⇒ 会走 ExchangeToken。
// 夹具的 handler 已校验请求体含 ClientID / RefreshToken:<回调值> / ClientSecret。
status, body := h.beginAndCallback(map[string]string{
"refreshToken": "RT-FROM-CALLBACK",
"userInfo": `{"UserID":"u1","ScreenName":"tester","TenantID":"t1"}`,
})
if status != 200 {
t.Fatalf("token 直传回调应成功: status=%d body=%s", status, body)
}
if n := atomic.LoadInt32(&h.exchHit); n == 0 {
t.Fatal("token 直传场景必须真的调用 ExchangeToken")
}
t.Logf("✓ ExchangeToken 被调用 %d 次,请求体形状正确", atomic.LoadInt32(&h.exchHit))
}
// client_id 的真值必须是实测值 —— 这是「交换必然 400」的两个成因之一。
func TestTraeClientIDIsNotBlank(t *testing.T) {
b, err := readBundledChannels(t)
if err != nil {
t.Fatal(err)
}
src := string(b)
if !strings.Contains(src, `client_id = "en1oxy7wnw8j9n"`) {
t.Fatal("trae 的 client_id 必须是实测真值 en1oxy7wnw8j9n —— " +
"留空/占位会让 ExchangeToken 的 ClientID 为空而稳定 400")
}
}
// 两条路径(oauth_callback 与 poll_login 的 loopback)必须给**同一个**结论,
// 否则修复只覆盖一条、另一条继续漂移(这正是缺陷能藏住的原因)。
func TestTraeCallbackPathsAgreeOnPkce(t *testing.T) {
b, err := readBundledChannels(t)
if err != nil {
t.Fatal(err)
}
src := string(b)
// ① 不得再出现自己发明的交换(注释里说明历史的那句除外)
if strings.Contains(src, `cerr = "Trae 授权码交换失败`) {
t.Fatal("已删除的「授权码交换」又回来了 —— 那是拿 code 去 ExchangeToken," +
"必然 400 且把真因掩盖成交换失败")
}
// ② 两条路径都必须交给 traeCallback(它内建 PKCE 判定)
if n := strings.Count(src, "traeCallback(plat,"); n < 2 {
t.Fatalf("traeCallback 应被两条路径共用(当前 %d 处)—— 只有一条会漂移", n)
}
// ③ PKCE 判定必须仍在 traeCallback 内
if !strings.Contains(src, "本实现暂不支持该流程") {
t.Fatal("traeCallback 必须保留 PKCE 明确报错(参考实现的语义)")
}
}
// beginAndPollWithCallback 走**真实登录用的那条路径**:
// start_login 拿会话 → 摆好 loopback 回调文件(平台重定向的落地)→ poll_login。
//
// 与 beginAndCallback(打 oauth_callback)的区别很关键:poll_login 才是
// callback 流在服务端浏览器(VNC)场景下真正走的那条,真实缺陷就藏在它的
// trae 分支里。
func (h *traeHarness) beginAndPollWithCallback(cbQuery map[string]string) (int, string) {
h.t.Helper()
out, err := h.ps.InvokeHandler("channels", "start_login", &lua.HandlerRequest{
Method: "POST", Body: `{"platform":"trae"}`,
})
if err != nil {
h.t.Fatal(err)
}
j, ok := out.JSON.(map[string]interface{})
if !ok {
h.t.Fatalf("start_login 返回非对象: %#v", out.JSON)
}
sess := j["session"].(map[string]interface{})
sid, _ := sess["id"].(string)
nonce, _ := sess["nonce"].(string)
if sid == "" {
h.t.Fatalf("会话缺 id: %#v", sess)
}
// 摆好 loopback 回调文件(内容 = 平台重定向带回的 query)
rec := map[string]string{"state": nonce}
for k, v := range cbQuery {
rec[k] = v
}
b, _ := json.Marshal(rec)
cbPath := filepath.Join(h.t.TempDir(), "cb-"+sid+".json")
if err := os.WriteFile(cbPath, b, 0600); err != nil {
h.t.Fatal(err)
}
// 告诉插件「这个会话的 loopback 接收器把结果写在这里了」
if _, err := h.ps.Call("channels", "__set_loopback_probe", map[string]interface{}{
"session_id": sid, "file": cbPath,
}); err != nil {
h.t.Fatalf("设置 loopback 文件: %v", err)
}
res, err := h.ps.InvokeHandler("channels", "poll_login", &lua.HandlerRequest{
Method: "GET", Query: map[string]string{"id": sid},
})
if err != nil {
h.t.Fatal(err)
}
return res.Status, fmt.Sprintf("%v|%v", res.Body, res.JSON)
}
// ★ PKCE 探测的候选来源必须覆盖参考的 5 个(含 authCodeInfo 为**纯 code 字符串**
// 这一形态 —— 参考注释点名,解析不出 JSON 时必须回退到原始值)。
//
// 反例(我第一版就是错的):用 `q.code or q.authCode or jsonField(...)` 链,
// 而 jsonField 取不到时返回**空串**;Lua 里空串是真值 ⇒ 链在第一个空串处短路,
// 后面的来源永远取不到。
func TestTraePkceDetectsPlainStringAuthCodeInfo(t *testing.T) {
for _, tc := range []struct {
name string
q map[string]string
}{
{"code 参数", map[string]string{"code": "C1"}},
{"authCode 参数", map[string]string{"authCode": "C2"}},
{"authCodeInfo 是 JSON", map[string]string{"authCodeInfo": `{"code":"C3"}`}},
{"authCodeInfo 是 JSON(authCode)", map[string]string{"authCodeInfo": `{"authCode":"C4"}`}},
{"authCodeInfo 是纯字符串", map[string]string{"authCodeInfo": "C5"}},
} {
t.Run(tc.name, func(t *testing.T) {
h := newTraeHarness(t)
status, body := h.beginAndPollWithCallback(tc.q)
_ = status
if n := atomic.LoadInt32(&h.exchHit); n != 0 {
t.Fatalf("PKCE 形态不得去调 ExchangeToken(打了 %d 次)", n)
}
if !strings.Contains(body, "PKCE") {
t.Fatalf("应识别为 PKCE 并明确报出,实得 %q", body)
}
})
}
}

View File

@ -0,0 +1,63 @@
package core
import (
"strings"
"testing"
)
// ★ 本文件把「上游客观缺口」写成**可执行的判据**,而不是只留在文档里。
//
// 为什么需要:这些能力缺口多次被误判成"我们漏实现了"(我自己就误判了两轮),
// 于是反复派人去"补"。判据在此把事实钉住:
//
// - qoder 加密端点(agent_chat_generation)需要 `qoder-auth-wasm.wasm`
// —— 该二进制**在参考仓库里也不存在**(参考自己也是 readFileSync 一个
// 它不提供的文件)。故我们走明文端点 `/model/v1/chat/completions`,
// **不经过信封** ⇒ qoder-envelope 的解包能力在明文路径上无从生效。
// - TRAE 的 PKCE 分支参考**明确不支持**(只有"探测并拒绝",无 code→token
// 交换端点)⇒ 我们报"暂不支持"是与参考对齐的正确行为。
//
// 判据的作用是**防止误判**:任何人(包括未来的我)想"补"这些能力时,
// 必须先让这个测试失败 —— 也就是先推翻事实,再动手。
func TestUpstreamGapsAreDocumented(t *testing.T) {
src, err := readBundledChannels(t)
if err != nil {
t.Fatal(err)
}
s := string(src)
t.Run("qoder 走明文端点且不经过信封", func(t *testing.T) {
// 明文端点(OpenAI 兼容):参考 QODER_CHAT_PATH
if !strings.Contains(s, "https://api2-v2.qoder.sh/model/v1/chat/completions") {
t.Fatal("qoder 的 chat 端点变了 —— 若改成加密端点 agent_chat_generation," +
"则**必须**同时实现信封解包(qoder-envelope)与 WASM 签名," +
"否则响应会被当成畸形数据")
}
// 明文端点没有信封层,故解包**不该**存在(存在反而是死代码)
if strings.Contains(s, "unwrapQoderEnvelope") {
t.Fatal("出现了 qoder 信封解包 —— 明文端点没有信封层。" +
"要么端点已换成加密端点(那需要 wasm),要么这是死代码")
}
})
t.Run("TRAE PKCE 明确报不支持(与参考一致)", func(t *testing.T) {
if !strings.Contains(s, "本实现暂不支持该流程") {
t.Fatal("TRAE 的 PKCE 分支必须明确报出「暂不支持」—— " +
"参考 trae-oauth.ts 也只做探测+拒绝,没有 code→token 交换端点。" +
"若改为尝试交换,会拿 code 去打要 RefreshToken 的 ExchangeToken(必然 400)")
}
})
t.Run("codearts 目录打两个签名端点(本轮补上)", func(t *testing.T) {
for _, want := range []string{
"opengw.developer.huaweicloud.com/api/v1/gateway/config",
"snap-access.cn-north-4.myhuaweicloud.com/v1/model/builtin",
`sign = "codearts"`,
} {
if !strings.Contains(s, want) {
t.Fatalf("codearts 目录缺 %q —— 参考 fetchCodeArtsRemoteModels 打两个"+
"**必须 AK/SK 签名**的端点,只打一个会少一半模型", want)
}
}
})
}

View File

@ -1,6 +1,7 @@
package core
import (
"net/url"
"strings"
"testing"
@ -60,7 +61,36 @@ func TestChannelsVncStackEndToEnd(t *testing.T) {
if sess["cdp_port"] == nil {
t.Fatal("会话应带 CDP 端口(取凭据用)")
}
t.Logf("VNC 栈已起: %s (CDP %v)", view, sess["cdp_port"])
// ★ noVNC 用 `new URL(path, location.href)` 解析 path(ui.js 的 connect()),
// 即**相对 vnc.html 所在目录**解析,默认值就是相对名 'websockify'。
// 真实缺陷:传了站点根路径 ⇒ 路径被重复拼接,WebSocket 永远连不上,
// 页面看似白屏:
// .../proxy/<id>/api/plugins/http/channels/browser/proxy/<id>/websockify
// 本判据必须解析**产品自己给出的 URL**:我曾在验证时手拼 URL 并省掉
// path 参数(默认值恰好正确)⇒ 否定了真实缺陷。
u, perr := url.Parse(view)
if perr != nil {
t.Fatalf("view_url 不可解析: %v", perr)
}
q := u.Query()
wspath := q.Get("path")
if wspath == "" {
t.Fatal("view_url 必须显式声明 path=websockify:依赖 noVNC 隐式默认值" +
"会在 URL 形状变化时静默破裂")
}
if strings.HasPrefix(wspath, "/") {
t.Fatalf("path 必须是相对名(noVNC 相对 vnc.html 目录解析),"+
"以 / 开头会被当相对路径而重复拼接,实得 %q", wspath)
}
resolved := u.ResolveReference(&url.URL{Path: wspath})
pages := strings.TrimSuffix(u.Path, "/vnc.html")
if resolved.Path != pages+"/websockify" {
t.Fatalf("path 解析后应为 %q(同级 websockify),实得 %q —— 重复拼接即白屏根因",
pages+"/websockify", resolved.Path)
}
t.Logf("VNC 栈已起: %s → WebSocket %s (CDP %v)", view, resolved.Path, sess["cdp_port"])
// 收尾:回收浏览器栈(测试不留孤儿进程)
if _, err := ps.InvokeHandler("channels", "stop_browser", &lua.HandlerRequest{

View File

@ -0,0 +1,404 @@
package core
import (
"encoding/json"
"os"
"path/filepath"
"strings"
"testing"
"llmsproxy/internal/lua"
)
// ★ ZCode 的身份块是 3012 准入的**唯一开关**。
//
// 参考实测(三个账号、17 次请求):system 缺官方身份块结构时,上游直接
//
// HTTP 405 + {"code":3012,"msg":"...unusual activity."}
//
// 且与 HTTP 头、版本号、请求频率、多轮历史、tools 声明、运行时**全部无关**。
//
// 判据矩阵(照参考,逐条锁定):
//
// 无 system → 3012
// 仅 cliPrefix(42 字符) → 3012
// cliPrefix + stable(约 2898 字符)→ 200
//
// ⇒ 判据是「身份块**结构**是否存在」,不是字符数凑够。
//
// 本判据看**适配器真正产出给上游的请求体**(transform_request 的返回值),
// 而不是"适配器装了没"这类内部信号。
func TestZcodeAdapterInjectsOfficialIdentityBlocks(t *testing.T) {
h := newZcodeIdentityHarness(t)
out, err := h.transformRequest(`{"model":"glm-5.3-flash","messages":[{"role":"user","content":"hi"}]}`)
if err != nil {
t.Fatalf("transform_request: %v", err)
}
var req map[string]interface{}
if err := json.Unmarshal([]byte(out), &req); err != nil {
t.Fatalf("产出不是 JSON: %v\n%s", err, out)
}
// ① system 必须是**块数组**(官方形态),不是纯字符串
sys, ok := req["system"].([]interface{})
if !ok {
t.Fatalf("system 必须是块数组(上游检查的是这个结构),实得 %T: %v",
req["system"], req["system"])
}
if len(sys) < 3 {
t.Fatalf("system 块数至少 3(cliPrefix + stable + Environment),实得 %d", len(sys))
}
// ② block[0] 必须是官方 CLI 前缀(准入必需)
b0, _ := sys[0].(map[string]interface{})
if got, _ := b0["text"].(string); got != "You are ZCode, an interactive coding agent" {
t.Fatalf("block[0] 必须是官方 CLI 前缀(逐字),实得 %q", got)
}
// ③ block[1] 必须是官方 stable 段(准入必需),长度对得上
b1, _ := sys[1].(map[string]interface{})
stable, _ := b1["text"].(string)
if len(stable) < 2800 {
t.Fatalf("block[1](stable 段)长度 %d < 2800 —— 身份块不完整会被判为裸请求(3012)",
len(stable))
}
for _, marker := range []string{
"You are an interactive ZCode agent",
"# Harness",
"# ZCode Desktop Context",
} {
if !strings.Contains(stable, marker) {
t.Fatalf("stable 段缺 %q —— 身份块被截断/改写", marker)
}
}
// ④ block[2] 是 Environment 段(官方每会话都发;不发则模型不知 cwd/平台)
b2, _ := sys[2].(map[string]interface{})
env, _ := b2["text"].(string)
if !strings.HasPrefix(env, "# Environment") {
t.Fatalf("block[2] 必须是 Environment 段,实得 %q", env[:zcodeMin(40, len(env))])
}
for _, marker := range []string{"Primary working directory", "Platform", "powered by the model named"} {
if !strings.Contains(env, marker) {
t.Fatalf("Environment 段缺 %q:%s", marker, env)
}
}
// ⑤ 总长度必须达到参考声明的量级(2898)
total := len("You are ZCode, an interactive coding agent") + len(stable)
if total < 2800 {
t.Fatalf("身份块合计 %d 字符 < 2800(参考实测的准入值约 2898)", total)
}
// ⑥ 日期块:插到第一条 user 消息的 content **数组**最前(官方形态)
msgs, _ := req["messages"].([]interface{})
if len(msgs) == 0 {
t.Fatal("messages 为空")
}
m0, _ := msgs[0].(map[string]interface{})
content, ok := m0["content"].([]interface{})
if !ok {
t.Fatalf("首条 user 的 content 必须是**块数组**(拼进字符串会改变结构、仍被判裸请求),实得 %T",
m0["content"])
}
c0, _ := content[0].(map[string]interface{})
if got, _ := c0["text"].(string); !strings.Contains(got, "<system-reminder>") {
t.Fatalf("content[0] 必须是日期块(<system-reminder>),实得 %q", got)
}
t.Logf("✓ 身份块注入正确:块数=%d stable=%d 合计=%d", len(sys), len(stable), total)
}
// ★ 调用方的 system 必须**追加在最后**:上游检查看的是**前缀结构**,
// 官方身份块必须处在开头位置。若被前置会让身份块不在前缀而吃 3012。
func TestZcodeCallerSystemIsAppendedLast(t *testing.T) {
h := newZcodeIdentityHarness(t)
out, err := h.transformRequest(
`{"model":"glm-5.3-flash","messages":[{"role":"system","content":"CALLER_PROMPT_XYZ"},{"role":"user","content":"hi"}]}`)
if err != nil {
t.Fatal(err)
}
var req map[string]interface{}
if err := json.Unmarshal([]byte(out), &req); err != nil {
t.Fatal(err)
}
sys, _ := req["system"].([]interface{})
if len(sys) < 4 {
t.Fatalf("带调用方 system 时应为 4 块(3 官方 + 1 调用方),实得 %d", len(sys))
}
last, _ := sys[len(sys)-1].(map[string]interface{})
lt, _ := last["text"].(string)
if !strings.Contains(lt, "CALLER_PROMPT_XYZ") {
t.Fatalf("调用方 system 必须在**最后一块**(上游看前缀结构;前置会让身份块不在前缀)")
}
// 且前三块仍是官方块(身份块没有被调用方内容挤走)
b0, _ := sys[0].(map[string]interface{})
if got, _ := b0["text"].(string); got != "You are ZCode, an interactive coding agent" {
t.Fatalf("block[0] 必须仍是官方 CLI 前缀,实得 %q", got)
}
}
// 适配器自检出口:身份块长度与 anthropic 基座装载状态。
// 「装了但身份块是空的」这类问题(转义/截断/基座读不到)没有它只能靠猜。
func TestZcodeAdapterProbeReportsIdentityLength(t *testing.T) {
h := newZcodeIdentityHarness(t)
res, err := h.ps.Call("channels", "__adapter_install_probe", map[string]interface{}{})
if err != nil {
t.Fatal(err)
}
j := res.(map[string]interface{})["json"].(map[string]interface{})
zc, ok := j["zcode"].(map[string]interface{})
if !ok {
t.Fatalf("探针未报告 zcode 适配器装载结果: %v", j)
}
if zc["ok"] != true {
t.Fatalf("zcode 适配器装载失败: %v", zc["err"])
}
}
// zcodeIdentityHarness:加载插件(它会**自装** channels-zcode 适配器),
// 然后直接调那个适配器的 transform_request。
//
// 直接调已装载的适配器(而不是自己去 load 源码)更接近真实路径:判据验的是
// 「上游实际收到的请求体」,包含前导注入、桥的装载等全部环节。
type zcodeIdentityHarness struct {
t *testing.T
c *Core
ps *lua.Plugins
}
func newZcodeIdentityHarness(t *testing.T) *zcodeIdentityHarness {
t.Helper()
c := kernelTestCore(t)
ps := c.Plugins()
src, err := readBundledChannels(t)
if err != nil {
t.Fatal(err)
}
if err := ps.LoadSource("channels", src); err != nil {
t.Fatal(err)
}
return &zcodeIdentityHarness{t: t, c: c, ps: ps}
}
// transformRequest 调**已自装的** channels-zcode 适配器的 transform_request。
func (h *zcodeIdentityHarness) transformRequest(body string) (string, error) {
h.t.Helper()
vm := h.c.VM()
if vm == nil {
h.t.Fatal("VM 不可用")
}
return vm.Transform("channels-zcode", "transform_request", body)
}
func zcodeMin(a, b int) int {
if a < b {
return a
}
return b
}
// ★ 身份块注入不得破坏协议转换:工具调用、图像、流式帧仍必须走 anthropic 那一份。
//
// 为什么必须验:本适配器的手法是把 anthropic.lua 的源码读进来执行、只覆盖
// transform_request。若「读不到基座」或「覆盖时丢了字段」,协议转换会静默退化
// —— 表现为工具调用参数丢失、图像块消失,而身份块看起来完全正常。
func TestZcodeAdapterKeepsAnthropicProtocolConversion(t *testing.T) {
h := newZcodeIdentityHarness(t)
t.Run("工具定义与工具调用存活", func(t *testing.T) {
in := `{"model":"glm-5.3-flash","messages":[{"role":"user","content":"go"}],` +
`"tools":[{"type":"function","function":{"name":"get_weather",` +
`"description":"d","parameters":{"type":"object","properties":{"c":{"type":"string"}}}}}]}`
out, err := h.transformRequest(in)
if err != nil {
t.Fatal(err)
}
// anthropic 形态:tools[].name / input_schema(顶层,不是嵌套在 function 里)
if !strings.Contains(out, `"get_weather"`) {
t.Fatalf("工具定义在转换中丢失(identity 注入不该影响它):%s", out)
}
if !strings.Contains(out, `"input_schema"`) {
t.Fatalf("工具 schema 未转成 anthropic 形态(input_schema 缺失):%s", out)
}
})
t.Run("多模态图像块存活", func(t *testing.T) {
in := `{"model":"glm-5.3-flash","messages":[{"role":"user","content":[` +
`{"type":"text","text":"what"},` +
`{"type":"image_url","image_url":{"url":"data:image/png;base64,AAAA"}}]}]}`
out, err := h.transformRequest(in)
if err != nil {
t.Fatal(err)
}
if !strings.Contains(out, `"image"`) || !strings.Contains(out, `"base64"`) {
t.Fatalf("图像块在转换中丢失:%s", out)
}
})
t.Run("基座装载状态可见", func(t *testing.T) {
// 读适配器的自检出口:base_loaded 必须为 true(否则身份块虽在、
// 协议转换已退化为透传)
res, err := h.ps.Call("channels", "__adapter_install_probe", map[string]interface{}{})
if err != nil {
t.Fatal(err)
}
j := res.(map[string]interface{})["json"].(map[string]interface{})
zc := j["zcode"].(map[string]interface{})
if zc["ok"] != true {
t.Fatalf("zcode 适配器未装载: %v", zc)
}
})
}
// ★ 基座(anthropic.lua)读不到时必须**响亮失败**,不得静默退化。
//
// 反例危害:若"尽力而为"(只注入身份块、不作协议转换),会产出一个身份块
// 看着正确的请求,而 tools/图像/流式结构全未转换 —— 上游可能 200,但模型
// 拿不到工具定义,症状是"模型变笨了",与准入毫不相干,排查会完全跑偏。
//
// 判据看的是**适配器的真实产出**:把适配器目录指到空目录(基座不可得),
// transform_request 必须返回错误而不是原样透传。
func TestZcodeAdapterFailsLoudlyWithoutAnthropicBase(t *testing.T) {
// 隔离目录:插件目录下没有兄弟 adapters/ 目录 ⇒ 基座读不到
dir := t.TempDir()
pluginDir := filepath.Join(dir, "plugins")
if err := os.MkdirAll(pluginDir, 0755); err != nil {
t.Fatal(err)
}
t.Setenv("LLMSPROXY_PLUGIN_DIR", pluginDir)
c := kernelTestCore(t)
ps := c.Plugins()
src, err := readBundledChannels(t)
if err != nil {
t.Fatal(err)
}
if err := ps.LoadSource("channels", src); err != nil {
t.Fatal(err)
}
vm := c.VM()
if vm == nil {
t.Fatal("VM 不可用")
}
// 插件自装时若基座读不到,适配器仍应装载(身份块是静态的),
// 但调用必须报错
out, err := vm.Transform("channels-zcode", "transform_request",
`{"model":"m","messages":[{"role":"user","content":"hi"}]}`)
if err == nil {
t.Fatalf("基座不可得时必须报错,却成功产出了:%s", out)
}
if !strings.Contains(err.Error(), "基座") {
t.Fatalf("错误信息应点明基座问题(可定位),实得 %v", err)
}
t.Logf("✓ 基座缺失时响亮失败: %v", err)
}
// ★ 日期块必须**幂等**:已以 <system-reminder> 开头则不重复插。
//
// 不判的后果:同一请求重试/多次 transform 时日期块叠成多层,改变 content 的
// 前缀结构(上游检查的正是结构)。参考 withContextPrefix 有 startsWithSystemReminder。
func TestZcodeContextPrefixIsIdempotent(t *testing.T) {
h := newZcodeIdentityHarness(t)
// 已是插入后的形态(首条 user 的 content[0] 就是 system-reminder)
in := `{"model":"m","messages":[{"role":"user","content":[` +
`{"type":"text","text":"<system-reminder>\nOLD\n</system-reminder>"},` +
`{"type":"text","text":"hi"}]}]}`
out, err := h.transformRequest(in)
if err != nil {
t.Fatal(err)
}
var req map[string]interface{}
if err := json.Unmarshal([]byte(out), &req); err != nil {
t.Fatal(err)
}
msgs := req["messages"].([]interface{})
content := msgs[0].(map[string]interface{})["content"].([]interface{})
n := 0
for _, c := range content {
if b, ok := c.(map[string]interface{}); ok {
if s, _ := b["text"].(string); strings.Contains(s, "<system-reminder>") {
n++
}
}
}
if n != 1 {
t.Fatalf("日期块必须幂等(已存在则不重复插),实得 %d 个 system-reminder 块", n)
}
}
// ★ 日期块只处理**第一条**消息,且它必须 role == "user"。
//
// 反例(我第一版就是这样):往后扫第一个 user 消息 —— 若首条是 assistant,
// 官方行为是**不动**,而不是去找后面那条 user。判据钉住这个差别。
func TestZcodeContextPrefixOnlyTouchesFirstMessage(t *testing.T) {
h := newZcodeIdentityHarness(t)
t.Run("首条不是 user 时不动", func(t *testing.T) {
in := `{"model":"m","messages":[` +
`{"role":"assistant","content":"opening"},` +
`{"role":"user","content":"hi"}]}`
out, err := h.transformRequest(in)
if err != nil {
t.Fatal(err)
}
var req map[string]interface{}
if err := json.Unmarshal([]byte(out), &req); err != nil {
t.Fatal(err)
}
msgs := req["messages"].([]interface{})
// ⚠ 注意:文本会被 anthropic 基座转成**块数组**(协议转换的正常行为),
// 所以这里不能断言 content 仍是字符串 —— 我第一版就这么断言,把正确的
// 实现判成了错。判据要验的是「**日期块**有没有被插进来」这个事实。
noReminder := func(content interface{}) bool {
switch c := content.(type) {
case string:
return !strings.Contains(c, "<system-reminder>")
case []interface{}:
for _, e := range c {
if b, ok := e.(map[string]interface{}); ok {
if t, _ := b["text"].(string); strings.Contains(t, "<system-reminder>") {
return false
}
}
}
}
return true
}
// 首条(assistant)不该被插日期块
if !noReminder(msgs[0].(map[string]interface{})["content"]) {
t.Fatal("首条是 assistant 时不该插日期块(官方只看第一条且要求 role=user)")
}
// 后面的 user 也**不该**被插(官方不往后找)
if !noReminder(msgs[1].(map[string]interface{})["content"]) {
t.Fatal("日期块被插到了后面的 user 消息上 —— 官方只看第一条")
}
// 且原文本内容必须保留(转换不能丢内容)
b, _ := json.Marshal(msgs[0])
if !strings.Contains(string(b), "opening") {
t.Fatal("首条 assistant 的内容丢了")
}
})
t.Run("首条是 user 时插入", func(t *testing.T) {
in := `{"model":"m","messages":[{"role":"user","content":"hi"}]}`
out, err := h.transformRequest(in)
if err != nil {
t.Fatal(err)
}
var req map[string]interface{}
if err := json.Unmarshal([]byte(out), &req); err != nil {
t.Fatal(err)
}
msgs := req["messages"].([]interface{})
content, ok := msgs[0].(map[string]interface{})["content"].([]interface{})
if !ok {
t.Fatal("首条 user 的 content 应升级为块数组")
}
b0 := content[0].(map[string]interface{})
if s, _ := b0["text"].(string); !strings.Contains(s, "<system-reminder>") {
t.Fatalf("首条 user 的 content[0] 必须是日期块,实得 %q", s)
}
})
}

View File

@ -33,13 +33,13 @@ func TestDeployPruneAdapterBackups(t *testing.T) {
t.Fatalf("read deploy.sh: %v", err)
}
src := string(fn)
i := strings.Index(src, "prune_adapter_backups()")
i := strings.Index(src, "prune_backups()")
if i < 0 {
t.Fatal("prune_adapter_backups not found in deploy.sh")
t.Fatal("prune_backups not found in deploy.sh")
}
j := strings.Index(src[i:], "\n}\n")
if j < 0 {
t.Fatal("prune_adapter_backups has no closing brace")
t.Fatal("prune_backups has no closing brace")
}
body := src[i : i+j+3]
@ -47,20 +47,20 @@ func TestDeployPruneAdapterBackups(t *testing.T) {
body = strings.Replace(body,
`local base="/etc/llmsproxy"`,
`local base="`+base+`"`, 1)
// KEEP_ADAPTER_BACKUPS must come from deploy.sh itself, NOT from a literal
// KEEP_BACKUPS must come from deploy.sh itself, NOT from a literal
// here: hardcoding 5 in the shim overrode whatever the script configured, so
// a mutation that set KEEP_ADAPTER_BACKUPS=0 in deploy.sh still passed. The
// a mutation that set KEEP_BACKUPS=0 in deploy.sh still passed. The
// value is part of what is under test.
var keepRe = regexp.MustCompile(`(?m)^KEEP_ADAPTER_BACKUPS=(\d+)`)
var keepRe = regexp.MustCompile(`(?m)^KEEP_BACKUPS=(\d+)`)
keepM := keepRe.FindStringSubmatch(src)
if keepM == nil {
t.Fatal("deploy.sh no longer sets KEEP_ADAPTER_BACKUPS; the pruning " +
t.Fatal("deploy.sh no longer sets KEEP_BACKUPS; the pruning " +
"policy would be undefined")
}
keep := keepM[1]
script := "warn() { :; }\nlog() { :; }\nKEEP_ADAPTER_BACKUPS=" + keep + "\n" +
body + "\nprune_adapter_backups\n"
script := "warn() { :; }\nlog() { :; }\nfail() { echo \"$*\" >&2; exit 1; }\nKEEP_BACKUPS=" + keep + "\n" +
body + "\nprune_backups adapters\n"
scriptPath := filepath.Join(base, "fn.sh")
if err := os.WriteFile(scriptPath, []byte(script), 0o600); err != nil {
t.Fatalf("write script: %v", err)
@ -88,7 +88,7 @@ func TestDeployPruneAdapterBackups(t *testing.T) {
}
if out, err := exec.Command("bash", scriptPath).CombinedOutput(); err != nil {
t.Fatalf("prune_adapter_backups failed: %v\n%s", err, out)
t.Fatalf("prune_backups failed: %v\n%s", err, out)
}
entries, err := os.ReadDir(base)
@ -102,11 +102,11 @@ func TestDeployPruneAdapterBackups(t *testing.T) {
}
}
// 12 well-formed backups with KEEP_ADAPTER_BACKUPS=5 → the newest FIVE
// 12 well-formed backups with KEEP_BACKUPS=5 → the newest FIVE
// survive (…08 …09 …10 …11 …12) and the older seven are deleted. Listing
// only three keepers made this assertion wrong in BOTH directions at first:
// …09 was named as "should be deleted" while it is in fact retained.
// KEEP_ADAPTER_BACKUPS=5 is a cap on the TOTAL number of backups, and
// KEEP_BACKUPS=5 is a cap on the TOTAL number of backups, and
// irregular names are never deleted — so they consume slots rather than
// being ignored. With 3 unremovable directories present, only 2 of the
// well-formed ones can survive. That is the function's actual (and safe)
@ -202,3 +202,123 @@ func TestDeployBacksUpTheLiveFileBeforeOverwriting(t *testing.T) {
"captures the new file and rollback restores nothing")
}
}
// ★ 备份清理必须覆盖 plugins 前缀(真实缺陷)。
//
// 事实:backup 清理最初只处理 `adapters.bak.*`,而 `sync_plugins` 同样每次部署
// 建一个 `plugins.bak.<时间戳>` —— 于是 adapters 的堆积被修好,plugins 继续涨。
// 实测线上 plugins.bak 积累到 **36 个**、/etc/llmsproxy 涨到 192M。
//
// 这是「两处只修一处」的老形状。判据钉住:prune_all_backups 必须同时裁两个前缀,
// 且新增任何 .bak.<时间戳> 前缀时都要在这里补上(否则又是一个泄漏点)。
func TestDeployPruneCoversBothBackupPrefixes(t *testing.T) {
if _, err := os.Stat("../../deploy.sh"); err != nil {
t.Skip("deploy.sh not present (packaging-only checkout)")
}
if _, err := exec.LookPath("bash"); err != nil {
t.Skip("bash not available")
}
fn, err := os.ReadFile("../../deploy.sh")
if err != nil {
t.Fatal(err)
}
src := string(fn)
// ① prune_all_backups 必须存在且两个前缀都裁
i := strings.Index(src, "prune_all_backups()")
if i < 0 {
t.Fatal("prune_all_backups 不存在 —— 调用点若仍只裁 adapters," +
"plugins.bak 会继续无上限堆积(实测 36 个 / 192M)")
}
j := strings.Index(src[i:], "\n}\n")
if j < 0 {
t.Fatal("prune_all_backups 没有收尾大括号")
}
body := src[i : i+j+3]
for _, want := range []string{"prune_backups adapters", "prune_backups plugins"} {
if !strings.Contains(body, want) {
t.Fatalf("prune_all_backups 缺 %q —— plugins.bak 会无上限堆积", want)
}
}
// ② ★ 覆盖完整性:脚本里出现的每个 `.bak.<时间戳>` 前缀都必须在裁剪范围内。
// 这条比逐字检查两个名字更强 —— 将来有人新增第三种备份目录(比如
// runtime.bak.*),这里会立刻报红,而不是等它涨到几百兆。
prefixRe := regexp.MustCompile(`([a-z_]+)\.bak\.\$\(date`)
found := map[string]bool{}
for _, m := range prefixRe.FindAllStringSubmatch(src, -1) {
found[m[1]] = true
}
if len(found) == 0 {
t.Fatal("deploy.sh 里没找到任何 .bak.$(date …) 备份目录创建点(判据需更新)")
}
for prefix := range found {
if !strings.Contains(body, "prune_backups "+prefix) {
t.Errorf("deploy.sh 会创建 %s.bak.<时间戳> 目录,但 prune_all_backups 不裁它 "+
"—— 它就是一个无上限增长的备份泄漏点(实测 plugins.bak 涨到 36 个)", prefix)
}
}
// ③ 行为验证:用真函数裁 plugins 前缀,最新 5 份必须留下、更旧的删掉
base := t.TempDir()
k := strings.Index(src, "prune_backups()")
kj := strings.Index(src[k:], "\n}\n")
fnBody := src[k : k+kj+3]
fnBody = strings.Replace(fnBody, `local base="/etc/llmsproxy"`, `local base="`+base+`"`, 1)
keepRe := regexp.MustCompile(`(?m)^KEEP_BACKUPS=(\d+)`)
km := keepRe.FindStringSubmatch(src)
if km == nil {
t.Fatal("deploy.sh 不再设置 KEEP_BACKUPS")
}
script := "warn() { :; }\nlog() { :; }\nfail() { echo \"$*\" >&2; exit 1; }\nKEEP_BACKUPS=" +
km[1] + "\n" + fnBody + "\nprune_backups plugins\n"
sp := filepath.Join(base, "fn.sh")
if err := os.WriteFile(sp, []byte(script), 0o600); err != nil {
t.Fatal(err)
}
for _, ts := range []string{
"20260101120000", "20260201120000", "20260301120000", "20260401120000",
"20260501120000", "20260601120000", "20260701120000", "20260801120000",
} {
if err := os.MkdirAll(filepath.Join(base, "plugins.bak."+ts), 0o755); err != nil {
t.Fatal(err)
}
}
// adapters 前缀**不该被动**(防止误删别的前缀)
if err := os.MkdirAll(filepath.Join(base, "adapters.bak.20260101120000"), 0o755); err != nil {
t.Fatal(err)
}
if out, err := exec.Command("bash", sp).CombinedOutput(); err != nil {
t.Fatalf("prune_backups plugins failed: %v\n%s", err, out)
}
entries, err := os.ReadDir(base)
if err != nil {
t.Fatal(err)
}
got := map[string]bool{}
for _, e := range entries {
if e.IsDir() {
got[e.Name()] = true
}
}
if !got["plugins.bak.20260801120000"] {
t.Error("最新的 plugins 备份被删了;裁剪必须从最旧的一端开始")
}
if got["plugins.bak.20260101120000"] {
t.Error("最旧的 plugins 备份存活;裁剪没生效")
}
if !got["adapters.bak.20260101120000"] {
t.Error("裁 plugins 时误删了 adapters 备份 —— 前缀参数必须严格限定范围")
}
// ④ 未知前缀必须响亮失败(防误用:传空串会删掉整个目录)
bad := "warn() { :; }\nlog() { :; }\nfail() { echo \"$*\" >&2; exit 1; }\nKEEP_BACKUPS=" +
km[1] + "\n" + fnBody + "\nprune_backups \"\"\n"
bp := filepath.Join(base, "bad.sh")
if err := os.WriteFile(bp, []byte(bad), 0o600); err != nil {
t.Fatal(err)
}
if out, err := exec.Command("bash", bp).CombinedOutput(); err == nil {
t.Fatalf("prune_backups 接受空前缀(危险:会删整个目录),输出: %s", out)
}
}

View File

@ -0,0 +1,213 @@
package lua
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"os/exec"
"strings"
"testing"
"time"
)
// 真上游 e2e:用适配器产出的头 + body 直打 opencode /inference/v1。
// 需要真实凭据(从生产配置解密),故用 LLMSPROXY_LIVE_ZEN=1 显式开启。
func TestOpencodeZenLiveE2E(t *testing.T) {
if os.Getenv("LLMSPROXY_LIVE_ZEN") != "1" {
t.Skip("设 LLMSPROXY_LIVE_ZEN=1 开启真上游 e2e")
}
src, err := bundledAdapters.ReadFile("adapters/opencodezen.lua")
if err != nil {
t.Fatal(err)
}
vm := NewVM(t.TempDir())
defer vm.Stop()
if err := vm.LoadAdapterSource("opencodezen", string(src)); err != nil {
t.Fatal(err)
}
// 取生产凭据(解密)
out, err := exec.Command("/usr/local/bin/llmsproxy", "-show-secrets",
"-config", "/etc/llmsproxy/config.yaml").Output()
if err != nil {
t.Fatal(err)
}
apiKey := ""
for _, l := range strings.Split(string(out), "\n") {
if strings.HasPrefix(l, "source localzen") {
if i := strings.Index(l, "api_key="); i >= 0 {
apiKey = strings.TrimSpace(l[i+len("api_key="):])
}
}
}
if apiKey == "" {
t.Fatal("未取到 localzen 凭据")
}
cases := []struct {
name string
body string
want string
}{
{"纯对话(无 tools,靠适配器兜底注入)",
`{"model":"deepseek-v4.1-flash-free","stream":true,"max_tokens":60,
"messages":[{"role":"user","content":"reply with exactly: ADAPTER-OK"}]}`, "ADAPTER-OK"},
{"带自定义 system",
`{"model":"deepseek-v4.1-flash-free","stream":true,"max_tokens":60,
"messages":[{"role":"system","content":"You are terse."},{"role":"user","content":"reply with exactly: SYS-OK"}]}`, "SYS-OK"},
{"多轮",
`{"model":"deepseek-v4.1-flash-free","stream":true,"max_tokens":60,
"messages":[{"role":"user","content":"a"},{"role":"assistant","content":"b"},{"role":"user","content":"reply with exactly: MULTI-OK"}]}`, "MULTI-OK"},
{"算术(验证真推理)",
`{"model":"deepseek-v4.1-flash-free","stream":true,"max_tokens":60,
"messages":[{"role":"user","content":"What is 17*23? Reply with just the number."}]}`, "391"},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
body, err := vm.Transform("opencodezen", "transform_request", tc.body)
if err != nil {
t.Fatal(err)
}
h, err := vm.BuildHeaders("opencodezen", map[string]interface{}{
"timestamp": time.Now().Unix(), "body": body,
})
if err != nil {
t.Fatal(err)
}
req, _ := http.NewRequest("POST",
"https://opencode.ai/inference/v1/chat/completions", bytes.NewReader([]byte(body)))
for k, v := range h {
req.Header.Set(k, v)
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+apiKey)
cl := &http.Client{Timeout: 90 * time.Second}
resp, err := cl.Do(req)
if err != nil {
t.Fatal(err)
}
raw, _ := io.ReadAll(resp.Body)
resp.Body.Close()
if resp.StatusCode != 200 {
t.Fatalf("HTTP %d: %s", resp.StatusCode, string(raw)[:min(300, len(raw))])
}
// 上游现在返回 SSE(适配器强制 stream=true);判据需自己拼 delta.content。
got := ""
for _, line := range strings.Split(string(raw), "\n") {
line = strings.TrimSpace(line)
if !strings.HasPrefix(line, "data: ") {
continue
}
p := strings.TrimPrefix(line, "data: ")
if p == "[DONE]" {
continue
}
var d struct {
Choices []struct {
Delta struct{ Content string } `json:"delta"`
} `json:"choices"`
}
if json.Unmarshal([]byte(p), &d) != nil || len(d.Choices) == 0 {
continue
}
got += d.Choices[0].Delta.Content
}
if got == "" {
t.Fatalf("未从 SSE 解出内容;原始=%s", string(raw)[:min(300, len(raw))])
}
if !strings.Contains(got, tc.want) {
t.Fatalf("回复 %q 不含 %q", got, tc.want)
}
t.Logf("✓ %s → %q", tc.name, strings.TrimSpace(got))
})
}
fmt.Println("真上游 e2e 全部通过")
}
// 经适配器完整转换链:上游 SSE → transform_stream_chunk → 统一格式。
// 上一条判据直接读原始 SSE,只证明"上游放行";这条证明"适配器能解析"。
func TestOpencodeZenLiveStreamThroughAdapter(t *testing.T) {
if os.Getenv("LLMSPROXY_LIVE_ZEN") != "1" {
t.Skip("设 LLMSPROXY_LIVE_ZEN=1 开启")
}
src, err := bundledAdapters.ReadFile("adapters/opencodezen.lua")
if err != nil {
t.Fatal(err)
}
vm := NewVM(t.TempDir())
defer vm.Stop()
if err := vm.LoadAdapterSource("opencodezen", string(src)); err != nil {
t.Fatal(err)
}
out, _ := exec.Command("/usr/local/bin/llmsproxy", "-show-secrets",
"-config", "/etc/llmsproxy/config.yaml").Output()
apiKey := ""
for _, l := range strings.Split(string(out), "\n") {
if strings.HasPrefix(l, "source localzen") {
if i := strings.Index(l, "api_key="); i >= 0 {
apiKey = strings.TrimSpace(l[i+len("api_key="):])
}
}
}
body, _ := vm.Transform("opencodezen", "transform_request",
`{"model":"deepseek-v4.1-flash-free","stream":true,"max_tokens":60,
"messages":[{"role":"user","content":"reply with exactly: CHAIN-OK"}]}`)
h, _ := vm.BuildHeaders("opencodezen", map[string]interface{}{
"timestamp": time.Now().Unix(), "body": body})
req, _ := http.NewRequest("POST",
"https://opencode.ai/inference/v1/chat/completions", bytes.NewReader([]byte(body)))
for k, v := range h {
req.Header.Set(k, v)
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+apiKey)
resp, err := (&http.Client{Timeout: 90 * time.Second}).Do(req)
if err != nil {
t.Fatal(err)
}
raw, _ := io.ReadAll(resp.Body)
resp.Body.Close()
if resp.StatusCode != 200 {
t.Fatalf("HTTP %d: %s", resp.StatusCode, string(raw)[:min(300, len(raw))])
}
// 逐行喂给适配器的流解析器,累积统一格式的 content
joined := ""
n := 0
for _, line := range strings.Split(string(raw), "\n") {
line = strings.TrimSpace(line)
if !strings.HasPrefix(line, "data: ") || line == "data: [DONE]" {
continue
}
// 内核喂给适配器的是**已剥掉 data: 前缀**的载荷(见 provider.go:
// strings.TrimPrefix(line, "data:")),判据必须对齐这个契约。
payload := strings.TrimSpace(strings.TrimPrefix(line, "data:"))
unified, err := vm.Transform("opencodezen", "transform_stream_chunk", payload)
if err != nil {
t.Fatalf("transform_stream_chunk: %v (%s)", err, line[:min(120, len(line))])
}
if unified == "" || unified == "{}" {
continue
}
var u struct {
Content string `json:"content"`
}
if json.Unmarshal([]byte(unified), &u) == nil {
joined += u.Content
n++
}
}
if n == 0 {
t.Fatal("适配器未解出任何 chunk(流解析链断了)")
}
if !strings.Contains(joined, "CHAIN-OK") {
t.Fatalf("经适配器链的内容 %q 不含 CHAIN-OK(chunk 数=%d)", joined, n)
}
t.Logf("✓ 完整链:%d 个 chunk,内容=%q", n, strings.TrimSpace(joined))
}

View File

@ -0,0 +1,156 @@
package lua
import (
"encoding/json"
"strings"
"testing"
)
// E2E:加载改后的适配器,验证 (1) 头含两个 session 头且值相同;(2) id 段服从公式;
// (3) 无 tools 的请求被注入 read 桩且 properties 非空。
func TestOpencodeZenAdapterE2E(t *testing.T) {
src, err := bundledAdapters.ReadFile("adapters/opencodezen.lua")
if err != nil {
t.Fatal(err)
}
vm := NewVM(t.TempDir())
defer vm.Stop()
if err := vm.LoadAdapterSource("opencodezen", string(src)); err != nil {
t.Fatalf("加载失败: %v", err)
}
t.Run("头:两个 session 头同值", func(t *testing.T) {
h, err := vm.BuildHeaders("opencodezen", map[string]interface{}{"timestamp": int64(1792065049)})
if err != nil {
t.Fatal(err)
}
s1, s2 := h["x-opencode-session"], h["x-opencode-session-id"]
if s1 == "" || s2 == "" {
t.Fatalf("两个 session 头都必须存在: %#v", h)
}
if s1 != s2 {
t.Fatalf("必须同值: %q vs %q", s1, s2)
}
if !strings.HasPrefix(s1, "ses_") || len(s1) != 4+12+14 {
t.Fatalf("session 形状应为 ses_+12hex+14base62: %q (len=%d)", s1, len(s1))
}
if len(h["x-opencode-request"]) != 4+12+14 || !strings.HasPrefix(h["x-opencode-request"], "msg_") {
t.Fatalf("request 形状: %q", h["x-opencode-request"])
}
if !strings.Contains(h["User-Agent"], "opencode/1.19.0") {
t.Fatalf("UA 应为 1.19.0: %q", h["User-Agent"])
}
t.Logf("session=%s request=%s", s1, h["x-opencode-request"])
// 公式校验:段 = (K - bucket_ms*4096) & MASK,其中 bucket 已对齐到整分钟
// (适配器按分钟桶取会话号,以保留上游前缀缓存命中)。
// ⚠️ 判据必须算**同一个桶**,不能拿原始 ms 去比 —— 那会把正确的实现判成错。
seg := s1[4:16]
ms := int64(1792065049) * 1000
bucket := ms - (ms % 60000)
want := (int64(0x1afffffffffffe) - bucket*4096) & 0xFFFFFFFFFFFF
if got := seg; got != fmtHex12(want) {
t.Fatalf("session 段公式不符: got=%s want=%s (bucket=%d)", got, fmtHex12(want), bucket)
}
})
t.Run("tools 兜底:无 tools 时注入 read", func(t *testing.T) {
out, err := vm.Transform("opencodezen", "transform_request",
`{"model":"m","stream":true,"messages":[{"role":"user","content":"hi"}]}`)
if err != nil {
t.Fatal(err)
}
var req map[string]interface{}
if err := json.Unmarshal([]byte(out), &req); err != nil {
t.Fatal(err)
}
ts, _ := req["tools"].([]interface{})
if len(ts) == 0 {
t.Fatalf("必须注入 tools: %s", out)
}
found := false
for _, x := range ts {
fn := x.(map[string]interface{})["function"].(map[string]interface{})
if fn["name"] == "read" {
p, _ := fn["parameters"].(map[string]interface{})
props, _ := p["properties"].(map[string]interface{})
if len(props) == 0 {
t.Fatalf("read 的 properties 必须非空(门禁要求): %s", out)
}
found = true
}
}
if !found {
t.Fatalf("必须含名为 read 的工具: %s", out)
}
})
t.Run("tools 保留:用户自带 read 不被覆盖", func(t *testing.T) {
in := `{"model":"m","stream":true,"messages":[{"role":"user","content":"hi"}],
"tools":[{"type":"function","function":{"name":"read","description":"MY","parameters":{"type":"object","properties":{"a":{"type":"string"}}}}}]}`
out, err := vm.Transform("opencodezen", "transform_request", in)
if err != nil {
t.Fatal(err)
}
var req map[string]interface{}
json.Unmarshal([]byte(out), &req)
ts, _ := req["tools"].([]interface{})
if len(ts) != 1 {
t.Fatalf("不应追加(已有 read): %s", out)
}
fn := ts[0].(map[string]interface{})["function"].(map[string]interface{})
if fn["description"] != "MY" {
t.Fatalf("用户定义被覆盖: %s", out)
}
})
}
func fmtHex12(v int64) string {
const hex = "0123456789abcdef"
out := make([]byte, 12)
for i := 11; i >= 0; i-- {
out[i] = hex[v&0xF]
v >>= 4
}
return string(out)
}
// ★ 免费层只能流式(适配器强制 stream=true),而内核在客户端要非流式时
// 会调 transform_response(期望 JSON)⇒ 适配器必须能把 SSE 聚合回非流式对象。
// 这条判据钉住那个聚合:真实 SSE 片段 → 完整 chat.completion。
func TestOpencodeZenAggregatesSSEForNonStreamClient(t *testing.T) {
src, err := bundledAdapters.ReadFile("adapters/opencodezen.lua")
if err != nil {
t.Fatal(err)
}
vm := NewVM(t.TempDir())
defer vm.Stop()
if err := vm.LoadAdapterSource("opencodezen", string(src)); err != nil {
t.Fatal(err)
}
// 模仿上游真实 SSE(含 reasoning_content 与 usage 末帧)
sse := `data: {"id":"x1","object":"chat.completion.chunk","created":1,"model":"m","choices":[{"index":0,"delta":{"role":"assistant","content":"","reasoning_content":"think "}}]}
data: {"id":"x1","object":"chat.completion.chunk","created":1,"model":"m","choices":[{"index":0,"delta":{"content":"HELLO"}}]}
data: {"id":"x1","object":"chat.completion.chunk","created":1,"model":"m","choices":[{"index":0,"delta":{"content":" WORLD"},"finish_reason":"stop"}]}
data: {"id":"x1","object":"chat.completion.chunk","created":1,"model":"m","choices":[],"usage":{"prompt_tokens":7,"completion_tokens":2,"total_tokens":9}}
data: [DONE]
`
out, err := vm.Transform("opencodezen", "transform_response", sse)
if err != nil {
t.Fatal(err)
}
var u map[string]interface{}
if err := json.Unmarshal([]byte(out), &u); err != nil {
t.Fatalf("聚合产物不是 JSON: %v (%s)", err, out)
}
if u["content"] != "HELLO WORLD" {
t.Fatalf("content 应为 'HELLO WORLD',实得 %v", u["content"])
}
tu, _ := u["token_usage"].(map[string]interface{})
if tu == nil || tu["prompt"] != float64(7) {
t.Fatalf("usage 应透传: %v", u["token_usage"])
}
if u["finish_reason"] != "stop" {
t.Fatalf("finish_reason 应为 stop: %v", u["finish_reason"])
}
t.Logf("聚合 OK: content=%v usage=%v finish=%v", u["content"], tu, u["finish_reason"])
}

View File

@ -0,0 +1,484 @@
local adapter = {}
adapter.name = "opencodezen"
adapter.version = "1.0.0"
adapter.endpoint = "/chat/completions"
-- OpenCode Zen(按量付费端点,https://opencode.ai/zen/v1)
--
-- 与 OpenCode Go(opencodego.lua,https://opencode.ai/zen/go/v1)是两个不同的
-- 服务,行为要求并不相同,因此各有专用适配器:
--
-- * 本适配器(Zen)服务免费池 / 按量付费池。免费模型必须带 opencode 客户端
-- 指纹(UA + x-opencode-*),否则上游拒绝:"free tier can only be used in
-- OpenCode"。Zen 的免费池以非 thinking 模型为主,历史上回传
-- reasoning_content 会引出上游报错,故这里剥掉(Go 侧相反,见 opencodego.lua)。
-- * Go 订阅读者请看 opencodego.lua:那边**必须**回传 reasoning_content,
-- 否则 thinking 模式直接 400。
--
-- 缺 x-opencode-client/session/request/project 身份头会被判为匿名客户端,
-- 部分模型在带 tools 时上游直接失败(流式返回单 chunk
-- "finish_reason":"network_error" 空 content,非流式 503
-- "Endpoint is unavailable",表现为"空回复")。
-- ============================================================================
-- ★ opencode Zen 免费层门禁(2026-10-15 实测解出,逐条对齐官方 CLI)
--
-- 上游对免费池有**三个**必须同时满足的条件,缺任一则 403 FreeTierError
-- ("free tier can only be used from within OpenCode"),与 UA / TLS 指纹 / 凭据来源
-- 均无关:
--
-- 1. 端点必须是 /inference/v1/chat/completions(不是 /zen/v1)
-- —— 由源的 base_url 决定,不在本适配器内。
-- 2. 必须同时发 x-opencode-session **与** x-opencode-session-id(值相同)。
-- 两个 id 的 12 位 hex 段由**确定公式**给出(见下),不是随机数;
-- 时间容差实测 ≥ 60 秒,故 os.time() 的秒精度足够。
-- 3. 请求的 tools 里必须有一个名为 read 的工具,且其 parameters.properties
-- **非空**。这是唯一的 tools 要求:实测抽掉官方 11 个工具中的任意一个均为
-- 200,**只有抽掉 read 变 403**;且 properties 里放任意属性名即可,
-- 描述文字 / $schema / required 都不需要(properties 为空对象则 403)。
-- ⇒ 无 tools 的纯对话请求会被拒,故 transform_request 需兜底注入桩工具。
-- 4. **stream 必须为 true**:实测同为合法请求,stream=false 恒 403、stream=true 恒 200
-- (包括 max_tokens 20/60/200/1000/32000 均 200)。
-- ⇒ 非流式请求会被拒,故 transform_request 强制 stream=true。
--
-- 明确**不影响**通过的(均实测):system 内容(含无 system)、消息条数
-- (2/3/4/6 条均 200)、凭据(Bearer public 与普通 API key 均可)、
-- x-opencode-project / x-opencode-client / UA 里的 opencode/ 前缀。
--
-- ⚠️ 参考实现 dsh-our-free-model 的门禁桩(bash + read,但无真实 properties)
-- 恰好卡在第 3 条上 —— 即它「伪装需跟进上游更新」的真实原因。
adapter.headers = {
["User-Agent"] = "opencode/1.19.0 ai-sdk/provider-utils/4.0.23 runtime/bun/1.3.14",
}
-- rand_id:按官方的 48-bit 公式生成 12 位 hex 段 + 14 位 base62 随机段。
--
-- 公式逆自官方 CLI 本地库(~/.local/share/opencode/opencode.db 的 session 表,
-- 用 11/12 条真实 id 逐条比对完全一致):
--
-- MASK = 2^48 - 1
-- K = 0x1afffffffffffe (注意不是 27<<48,两者差 2)
-- session 段 = (K - now_ms * 4096) & MASK ← **倒计时式**:Δseg/Δms ≡ -4096
-- request 段 = (now_ms * 16) & MASK
--
-- 为什么是「倒计时」而不是时间戳:0x1afffffffffffe 减去 ms*2^12,所以 seg 随
-- 时间**递减**。用 f"{ms:012x}" 之类的正向写法必然不对(我为此错过一轮)。
--
-- ⚠️ 精度:now_ms*4096 ≈ 7.3e15 < 2^53 ≈ 9.0e15,在 double 安全整数范围内,
-- 故 LuaJIT 的默认数字类型(double)直接算即可,无需大整数库。
local B62 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
local MASK48 = 281474976710655 -- 2^48 - 1
local ID_K = 0x1afffffffffffe
local function rand_tail(n)
local out = {}
for i = 1, n do
local v = 0
if math and math.random then
v = math.random(1, 62)
else
-- 无 math 时用时间做退化熵源:只要唯一,不要求密码学强度。
v = (os.time() * 7 + i * 13) % 62 + 1
end
out[i] = B62:sub(v, v)
end
return table.concat(out)
end
-- now_ms:毫秒。沙箱只有 os.time()(秒)与 os.clock()(CPU 时间,无用),
-- 而上游时间容差实测 ≥ 60 秒,故秒精度足够;毫秒位补 0。
-- meta.timestamp 由内核给出(同为秒),优先用它以便同一请求内自洽。
local function now_ms(meta)
local t = tonumber(meta and meta.timestamp) or (os.time and os.time()) or 0
return t * 1000
end
local function rand_id(prefix, ms, kind)
local seg
if kind == "session" then
seg = (ID_K - ms * 4096) % (MASK48 + 1)
else
seg = (ms * 16) % (MASK48 + 1)
end
-- %012x:12 位十六进制,不足补零
return prefix .. string.format("%012x", seg) .. rand_tail(14)
end
-- session_bucket_ms 决定上游会话号的**稳定周期**(按整分钟对齐)。
--
-- 为什么需要稳定:上游前缀缓存是会话级的(实测:同一段 6032 token 提示词,
-- 固定会号第 2 次命中 5888;每请求换会号则恒为 0 命中)。而免费层门禁要求
-- x-opencode-session 的 12 位 hex 段服从「倒计时」公式(见 rand_id 注释),
-- 所以不能真的「随便挑一个固定值」,只能选一个**时间桶**。
--
-- 取整分钟(而非秒):同一分钟内的所有请求共享一个会话号 ⇒ 既保留缓存命中,
-- 又不超出上游的时间容差。实测容差 ≥ 1 小时(-3600s 仍 200),
-- 所以一分钟桶有很大余量,即便上游收紧到几分钟也仍然安全。
local function session_bucket_ms(meta)
local ms = now_ms(meta)
return ms - (ms % 60000)
end
function adapter.build_headers(meta)
local ms = now_ms(meta)
local bucket = session_bucket_ms(meta)
-- 免费层要求两个头都在且值相同(对齐官方 CLI;缺任一个则 403)。
local sid = rand_id("ses_", bucket, "session")
return {
["User-Agent"] = adapter.headers["User-Agent"],
["x-opencode-client"] = "cli",
-- project 固定:同网关实例共享一个工作区身份(非门禁必需,但官方也发)
["x-opencode-project"] = "global",
["x-opencode-session"] = sid,
-- ★ 两个都要:上游对免费池同时校验 x-opencode-session 与这个头。
["x-opencode-session-id"] = sid,
-- request id 每请求唯一(不参与缓存键),用当前时间而非桶,避免同桶内重复
["x-opencode-request"] = rand_id("msg_", ms, "request"),
}
end
-- ============================================================================
-- ★ 免费层 tools 兜底:上游要求 tools 里必须有一个名为 read、且
-- parameters.properties 非空的工具(实测唯一要求;抽掉它即 403)。
-- 纯对话请求(客户端没传 tools)会被拒,故这里注入一个桩工具。
--
-- 只补缺,不改用户已有的 tools:用户自带 read 时原样透传(官方 CLI 就是这么发的),
-- 用户带的其它工具保留不动。
local FREE_GATE_TOOL = "read"
local function ensure_free_gate_tool(req)
local tools = req.tools
if type(tools) ~= "table" then tools = {} req.tools = tools end
for _, t in ipairs(tools) do
if type(t) == "table" then
local fn = t["function"]
-- 注意:function 是 Lua 关键字,必须用 req["function"] 形式取下标。
if type(fn) == "table" and fn.name == FREE_GATE_TOOL then
local p = fn.parameters
-- 已有 read 但 properties 为空 ⇒ 补上;否则原样保留用户定义。
if type(p) == "table" and type(p.properties) == "table"
and next(p.properties) ~= nil then
return
end
fn.parameters = { type = "object",
properties = { filePath = { type = "string", description = "Path to read" } } }
return
end
end
end
tools[#tools + 1] = {
type = "function",
["function"] = {
name = FREE_GATE_TOOL,
description = "Read a file from the local filesystem.",
parameters = { type = "object",
properties = { filePath = { type = "string", description = "Path to read" } },
required = { "filePath" } },
},
}
end
-- OpenAI /chat/completions format (pass-through, strip provider-specific fields)
-- zen 上游 schema 只接受 text content part(无视觉/音频能力):多模态 part
-- (image_url / input_audio / file 等)一律剥离。剥离后 content 变空的消息
-- 若不再携带 tool_calls / tool_call_id 才整条丢弃(避免上游
-- "unknown variant `image_url`, expected `text`");带工具调用的必须保留,
-- 否则会把紧随其后的 tool 结果变成孤儿,模型会反复重发同一个调用。
-- zen 上游角色白名单只有 system / user / assistant / tool / latest_reminder:
-- OpenAI 的 developer(及 function 等)不在其中,直接透传会触发上游
-- "unknown variant `developer`, expected one of ..." 错误;统一归一化为 system。
local ROLE_WHITELIST = {
system = true,
user = true,
assistant = true,
tool = true,
latest_reminder = true,
}
function adapter.transform_request(raw_body)
local ok, req = pcall(json.decode, raw_body)
if not ok then return raw_body end
-- ★ 免费层 gate:tools 里必须有 read(且 parameters.properties 非空)。
-- 放在最前面:它决定本请求会不会被 403,与后面的字段清理无关。
-- 对所有模型都注入:免费池与付费池共用同一层形状检查,多一个桩工具无害
-- (官方 CLI 本来也带全套工具),但缺了它会让免费模型整体失效。
ensure_free_gate_tool(req)
-- ★ 免费层只接受流式:实测 stream=false 恒 403(同样 body 改 true 即 200)。
-- 转成流式由上游以 SSE 回应,内核本就会聚合/透传流式响应,故对客户端透明。
req.stream = true
req.disable_thinking = nil
req.extra_body = nil
-- stream_options is only valid alongside stream:true; sending it on a
-- non-streaming request is rejected by strict upstreams.
if req.stream then
if type(req.stream_options) ~= "table" then req.stream_options = {} end
req.stream_options.include_usage = true
end
if req.messages then
local kept = {}
for _, msg in ipairs(req.messages) do
if type(msg.role) == "string" and not ROLE_WHITELIST[msg.role] then
msg.role = "system"
end
-- Zen 免费池不接受回传 reasoning_content(Go 侧相反)
msg.reasoning_content = nil
local drop = false
if type(msg.content) == "table" then
local parts = {}
for _, part in ipairs(msg.content) do
if type(part) == "table" and part.type ~= nil and part.type ~= "text" then
-- multimodal part not supported by zen
else
table.insert(parts, part)
end
end
if #parts == 0 then
-- Content collapsed to nothing after stripping unsupported
-- parts. A message that still carries a tool call must
-- NEVER be dropped: the very next message is its tool
-- result, and dropping the call orphans that result. The
-- model then sees a result for a call it never made and
-- re-issues the same tool call on every turn (observed as
-- an infinite "repeated tool call" loop).
if (type(msg.tool_calls) == "table" and #msg.tool_calls > 0)
or msg.tool_call_id ~= nil then
msg.content = ""
else
drop = true
end
else
msg.content = parts
end
end
if not drop then
table.insert(kept, msg)
end
end
req.messages = kept
end
return json.encode(req)
end
-- ★ aggregate_sse:把 SSE 流(openai chat.completion.chunk 形状)聚合成一个非流式
-- 响应对象,供 transform_response 在「客户端要非流式、上游却回流式」时使用。
-- 返回 JSON 字符串;无法聚合(无任何 chunk)时返回 nil。
--
-- 只处理 content / reasoning_content / finish_reason / usage 四类增量:
-- 它们覆盖了内核需要从响应里取的全部字段(正文、结束原因、token 计数)。
local function aggregate_sse(raw)
local content, reasoning, finish = {}, {}, ""
local usage, id, model, created = nil, nil, nil, nil
local seen = false
for line in (raw .. "\n"):gmatch("([^\n]*)\n") do
local s = line:gsub("^%s+", ""):gsub("%s+$", "")
if s:sub(1, 5) == "data:" then
local payload = s:sub(6):gsub("^%s+", "")
if payload ~= "" and payload ~= "[DONE]" then
local ok, d = pcall(json.decode, payload)
if ok and type(d) == "table" then
seen = true
id = id or d.id
model = model or d.model
created = created or d.created
if type(d.usage) == "table" then usage = d.usage end
local ch = d.choices and d.choices[1]
if type(ch) == "table" then
if ch.finish_reason and ch.finish_reason ~= "" then
finish = ch.finish_reason
end
local dl = ch.delta
if type(dl) == "table" then
if type(dl.content) == "string" then content[#content + 1] = dl.content end
if type(dl.reasoning_content) == "string" then
reasoning[#reasoning + 1] = dl.reasoning_content
end
end
end
end
end
end
end
if not seen then return nil end
local msg = { role = "assistant", content = table.concat(content) }
local rc = table.concat(reasoning)
if rc ~= "" then msg.reasoning_content = rc end
local out = {
id = id or "", object = "chat.completion", created = created or 0, model = model or "",
choices = { { index = 0, message = msg, finish_reason = finish ~= "" and finish or "stop" } },
}
if usage then out.usage = usage end
local ok2, enc = pcall(json.encode, out)
if not ok2 then return nil end
return enc
end
function adapter.transform_response(raw_body)
-- ★ 免费层只接受 stream=true(见文件头门禁第 4 条),所以本适配器把每个请求
-- 都改成了流式 —— 但内核是按**客户端意图**选路径的:客户端发非流式时,
-- 内核走 Provider.Chat 并调本函数(期望 JSON),而上游回的是 SSE。
-- 若在这里直接 json.decode 就会得到 "invalid character 'd'" 错误。
--
-- 因此本函数必须先识别 SSE 并自行聚合,再走原来的 JSON 路径。
-- 这样保持内核对上游协议无感(内核不知道也不该知道上游选了流式)。
if type(raw_body) == "string" and (raw_body:sub(1, 6) == "data: " or raw_body:find("\ndata: ", 1, true)) then
local aggregated = aggregate_sse(raw_body)
if aggregated ~= nil then
local ok2, resp2 = pcall(json.decode, aggregated)
if ok2 and type(resp2) == "table" then raw_body = aggregated end
end
end
local ok, resp = pcall(json.decode, raw_body)
if not ok or resp == nil then return raw_body end
local unified = {
content = "",
finish_reason = "",
token_usage = { prompt = 0, completion = 0, total = 0 }
}
if type(resp.usage) == "table" then
unified.token_usage.prompt = resp.usage.prompt_tokens or 0
unified.token_usage.completion = resp.usage.completion_tokens or 0
unified.token_usage.total = resp.usage.total_tokens or 0
local hit = 0
if type(resp.usage.prompt_tokens_details) == "table" and resp.usage.prompt_tokens_details.cached_tokens ~= nil then
hit = resp.usage.prompt_tokens_details.cached_tokens
unified.token_usage.prompt_tokens_details = { cached_tokens = hit }
end
if (resp.usage.prompt_cache_hit_tokens or 0) > 0 then
unified.token_usage.prompt_cache_hit_tokens = resp.usage.prompt_cache_hit_tokens
unified.token_usage.prompt_cache_miss_tokens = resp.usage.prompt_cache_miss_tokens or 0
if hit == 0 then
unified.token_usage.prompt_tokens_details = { cached_tokens = resp.usage.prompt_cache_hit_tokens }
end
end
-- 上游报告输出里有多少是思考 token。不给客户端的话,无法判断
-- completion_tokens 里多少是「可见回答」、多少是「思考」(都按输出计费)。
local ctd = resp.usage.completion_tokens_details
if type(ctd) == "table" and ctd.reasoning_tokens ~= nil then
unified.token_usage.completion_tokens_details = { reasoning_tokens = ctd.reasoning_tokens }
end
end
-- 本次调用的费用,上游放在**顶层**且是**字符串**(如 "0"、"0.0012")。
-- Go 订阅是包月制,恒为 "0";只有 Zen 按量付费模型才有信息量。
-- 原样透传:网关不解析、不换算、不汇总 —— 它只是上游事实的搬运者。
if resp.cost ~= nil then
unified.cost = tostring(resp.cost)
end
if type(resp.choices) == "table" and #resp.choices > 0 then
local ch = resp.choices[1]
if type(ch.message) == "table" then
unified.content = ch.message.content or ""
local reasoning = ch.message.reasoning_content or ch.message.reasoning
if reasoning then
unified.reasoning_content = reasoning
end
if type(ch.message.tool_calls) == "table" then
local tcs = {}
for _, tc in ipairs(ch.message.tool_calls) do
local args_ok, args = pcall(json.decode, tc["function"].arguments)
if not args_ok then args = {} end
table.insert(tcs, {
id = tc.id,
type = tc.type or "function",
name = tc["function"].name,
arguments = args
})
end
unified.tool_calls = tcs
end
end
unified.finish_reason = ch.finish_reason or ""
end
return json.encode(unified)
end
function adapter.transform_stream_chunk(raw_chunk)
local ok, chunk = pcall(json.decode, raw_chunk)
if not ok then return "" end
-- OpenAI-style streams may attach usage to a chunk with empty choices
-- (the final usage chunk). Preserve it; the gateway emits it as the
-- terminal usage chunk. Note: keys must match Go's TokenUsage json tags
-- (prompt/completion/total); the gateway re-emits standard *_tokens.
local uses = nil
if type(chunk.usage) == "table" then
uses = {
prompt = chunk.usage.prompt_tokens or chunk.usage.prompt or 0,
completion = chunk.usage.completion_tokens or chunk.usage.completion or 0,
total = chunk.usage.total_tokens or chunk.usage.total or 0,
}
-- 独立字段与 prompt_tokens_details **并存**透传,不要写成 elseif:
-- 上游命中缓存时两者都发,非流式路径也是两个都带。写成 elseif 会让
-- 流式丢掉 prompt_cache_hit_tokens/miss,与同一源的**非流式**产出不一致
-- (dsh 优先读 details,但只认独立字段的老客户端会看不到缓存)。
if type(chunk.usage.prompt_tokens_details) == "table" and chunk.usage.prompt_tokens_details.cached_tokens ~= nil then
uses.prompt_tokens_details = { cached_tokens = chunk.usage.prompt_tokens_details.cached_tokens }
end
if (chunk.usage.prompt_cache_hit_tokens or 0) > 0 then
uses.prompt_cache_hit_tokens = chunk.usage.prompt_cache_hit_tokens
uses.prompt_cache_miss_tokens = chunk.usage.prompt_cache_miss_tokens or 0
if uses.prompt_tokens_details == nil then
uses.prompt_tokens_details = { cached_tokens = chunk.usage.prompt_cache_hit_tokens }
end
end
local ctd = chunk.usage.completion_tokens_details
if type(ctd) == "table" and ctd.reasoning_tokens ~= nil then
uses.completion_tokens_details = { reasoning_tokens = ctd.reasoning_tokens }
end
end
if not chunk.choices or #chunk.choices == 0 then
-- 空 choices 的帧既不是内容也不是结束信号。上游发两种:
-- {"choices":[],"usage":{...}} —— 终帧用量
-- {"choices":[],"cost":"0"} —— 单独的费用帧
-- 两者可能落在同一帧上,必须都转出去;早退只带 usage 会把费用丢干净。
local out = { done = false }
if uses ~= nil then out.usage = uses end
if chunk.cost ~= nil then out.cost = tostring(chunk.cost) end
if uses == nil and chunk.cost == nil then return "" end
return json.encode(out)
end
local delta = chunk.choices[1].delta or {}
local fr = chunk.choices[1].finish_reason
local finish = (type(fr) == "string" and fr ~= "") and fr or nil
local unified = {
content = delta.content or "",
done = (finish ~= nil)
}
if finish then
unified.finish_reason = finish
end
if uses ~= nil then
unified.usage = uses
end
-- zen 用 reasoning 字段承载推理文本(OpenAI 惯例是 reasoning_content)
local reasoning = delta.reasoning_content or delta.reasoning
if reasoning then
unified.reasoning_content = reasoning
end
if delta.tool_calls then
-- pass raw streaming fragments through; OpenAI clients accumulate index+id+name+arguments
unified.tool_calls = delta.tool_calls
end
return json.encode(unified)
end
-- 错误收敛(可选钩子):zen 错误信封固定为 {error={type,message}};
-- 免费池限流 FreeUsageLimitError 单独标注。返回 nil 走通用兜底。
function adapter.transform_error(status, body)
local ok, resp = pcall(json.decode, body)
if not ok or type(resp) ~= "table" then return nil end
local e = resp.error
if type(e) ~= "table" then return nil end
if e.type == "FreeUsageLimitError" then
return "zen free pool quota exhausted"
end
return e.message
end
return adapter

View File

@ -143,6 +143,14 @@ type PluginRuntime struct {
ps *Plugins
spec scheduleSpec
// stopOnce makes Stop idempotent. Stop closes a channel and waits on done;
// without this, a second Stop panics ("close of closed channel"). That is
// reachable in practice now that BOTH Unload and Close stop schedulers:
// unloading a plugin then closing the plugin set would otherwise abort the
// process during shutdown — the worst possible moment (a panic here masks
// whatever the operator was actually shutting down for).
stopOnce sync.Once
mu sync.Mutex
// nextDue is when each task should next fire.
nextDue map[string]time.Time
@ -457,8 +465,10 @@ func (rt *PluginRuntime) Stop() {
if rt == nil {
return
}
close(rt.stop)
<-rt.done
rt.stopOnce.Do(func() {
close(rt.stop)
<-rt.done
})
}
// callFnOn invokes a plugin function on an already-locked state.

View File

@ -0,0 +1,139 @@
package lua
import (
"os"
"path/filepath"
"runtime"
"testing"
"time"
)
// ★ Close() 必须停掉每个插件的**调度循环**。
//
// 真实缺陷(与 on_unload 同一形状的第 3 个实例):`Runtime.Stop()` 此前
// **只在单插件 Unload 里调**,Close() 不调 —— 于是「进程关闭/测试结束」
// 这条路径上,每个插件的 PluginRuntime.loop 永不停止。
//
// 实测:全量回归在 internal/lua 出现 **69 个 goroutine 卡在 saver/runtime
// 循环里**,最终 600s 超时。
//
// 判据用的是**进程里真实存在的 goroutine 数**:每 LoadSource 一个插件就
// 起一个调度循环,Close 必须让它们全部退出 —— 否则 goroutine 只增不减。
// 这比"任务被调用过"更贴近缺陷本身(缺陷就是循环不停)。
func TestPluginsCloseStopsSchedulerGoroutines(t *testing.T) {
dir := t.TempDir()
pluginDir := filepath.Join(dir, "plugins")
if err := os.MkdirAll(pluginDir, 0755); err != nil {
t.Fatal(err)
}
// 24 个带调度表的插件:每个起一个 PluginRuntime.loop
const n = 24
for i := 0; i < n; i++ {
src := `
local plugin = { name = "s` + string(rune('a'+i)) + `", version = "1.0.0", exports = {} }
function plugin.noop_task() end
plugin.schedule = { { fn = "noop_task", every = 3600 } }
return plugin
`
name := filepath.Join(pluginDir, "s"+string(rune('a'+i))+".lua")
if err := os.WriteFile(name, []byte(src), 0644); err != nil {
t.Fatal(err)
}
}
before := runtime.NumGoroutine()
ps := NewPlugins(nil, pluginDir)
if err := ps.LoadDir(); err != nil {
t.Fatalf("LoadDir: %v", err)
}
loaded := runtime.NumGoroutine()
if loaded <= before {
t.Fatalf("加载 %d 个带调度的插件后 goroutine 没涨(%d → %d)—— 夹具失效",
n, before, loaded)
}
ps.Close()
// ★ Close 之后循环必须**全部**退出,即回落到基线附近。
//
// ⚠️ 这里不能用「比 loaded 小就算过」:那只要**一个** goroutine 退出就成立
// (27 → 26 也满足),而 24 个调度循环可以全部还在跑 —— 我第一版就是
// 这么写的,被变异测试当场揭穿(去掉 stopSchedulersAll 后仍然绿)。
// 判据必须锚定**基线**,容差只留给无关的运行时 goroutine。
deadline := time.Now().Add(5 * time.Second)
for time.Now().Before(deadline) {
if runtime.NumGoroutine() <= before+2 {
break
}
time.Sleep(50 * time.Millisecond)
}
after := runtime.NumGoroutine()
if after > before+2 {
t.Fatalf("Close() 之后仍有调度循环在跑:goroutine 基线 %d、加载后 %d、Close 后 %d(加载了 %d 个插件)—— "+
"它们会一直堆积(实测全量回归堆到 69 个卡死并 600s 超时)", before, loaded, after, n)
}
t.Logf("✓ Close() 停掉了全部调度循环(goroutine 基线 %d → 加载后 %d → Close 后 %d,%d 个插件)",
before, loaded, after, n)
}
// ★ Stop() 必须幂等:Unload 与 Close 都会停调度器,重复调不得 panic。
//
// 反例:Stop 里裸 `close(rt.stop)` —— 第二次调用 `panic: close of closed channel`。
// 关闭路径上的 panic 最糟糕:它掩盖掉操作者本来在做的事(关服务/结束测试)。
func TestPluginRuntimeStopIsIdempotent(t *testing.T) {
dir := t.TempDir()
pluginDir := filepath.Join(dir, "plugins")
if err := os.MkdirAll(pluginDir, 0755); err != nil {
t.Fatal(err)
}
src := `
local plugin = { name = "sched2", version = "1.0.0", exports = {} }
function plugin.noop_task() end
plugin.schedule = { { fn = "noop_task", every = 30 } }
return plugin
`
if err := os.WriteFile(filepath.Join(pluginDir, "sched2.lua"), []byte(src), 0644); err != nil {
t.Fatal(err)
}
ps := NewPlugins(nil, pluginDir)
if err := ps.LoadDir(); err != nil {
t.Fatalf("LoadDir: %v", err)
}
defer ps.Close()
ps.mu.RLock()
var rt *PluginRuntime
for _, p := range ps.plugins {
if p.Info.Name == "sched2" {
rt = p.Runtime
}
}
ps.mu.RUnlock()
if rt == nil {
t.Fatal("插件未拿到 Runtime(夹具失效)")
}
// 连调三次:第二次若 panic,本测试就会崩掉(正是要防的行为)
rt.Stop()
rt.Stop()
rt.Stop()
}
func waitForFile(t *testing.T, path string, d time.Duration) {
t.Helper()
deadline := time.Now().Add(d)
for time.Now().Before(deadline) {
if _, err := os.Stat(path); err == nil {
return
}
time.Sleep(50 * time.Millisecond)
}
t.Fatalf("等待 %s 出现超时 —— 调度任务从未运行(夹具失效)", filepath.Base(path))
}
func fileSize(t *testing.T, path string) int64 {
t.Helper()
st, err := os.Stat(path)
if err != nil {
t.Fatalf("stat %s: %v", path, err)
}
return st.Size()
}

View File

@ -0,0 +1,77 @@
package lua
import (
"os"
"path/filepath"
"testing"
)
// ★ 关闭 Plugins 时必须给插件一次 on_unload 机会。
//
// 真实缺陷:Close() 此前只关 shard 与 saver,**从不调用 on_unload** —— 而
// on_unload 只在单插件 Unload 时调。于是「进程关闭/测试结束」这条路径上,
// 起了 OS 进程的插件(回环回调接收器、浏览器栈)永远收不了尾,留下孤儿进程。
// 实测本机积累到 995 个 python 监听器(828 个超 24 小时),全是测试残留。
//
// 这个判据看的是**真实外部效应**(插件在 on_unload 里改磁盘上的文件),
// 而不是「钩子被调用过」这类内部信号 —— 后者在钩子写错名字时也会假绿。
func TestPluginsCloseCallsOnUnload(t *testing.T) {
dir := t.TempDir()
marker := filepath.Join(dir, "unloaded.marker")
pluginDir := filepath.Join(dir, "plugins")
if err := os.MkdirAll(pluginDir, 0755); err != nil {
t.Fatal(err)
}
src := `
local plugin = { name = "leaky", version = "1.0.0", exports = {} }
plugin.ui = nil
function plugin.on_unload()
local f = io.open("` + marker + `", "w")
if f then f:write("reaped"); f:close() end
end
return plugin
`
if err := os.WriteFile(filepath.Join(pluginDir, "leaky.lua"), []byte(src), 0644); err != nil {
t.Fatal(err)
}
ps := NewPlugins(nil, pluginDir)
if err := ps.LoadDir(); err != nil {
t.Fatalf("LoadDir: %v", err)
}
// 关之前不该有标记
if _, err := os.Stat(marker); err == nil {
t.Fatal("on_unload 在 Close 之前就被调了?")
}
ps.Close()
// ★ 真判据:文件必须被写出来(= on_unload 真的跑过)
if _, err := os.Stat(marker); err != nil {
t.Fatalf("Close() 没有调用 on_unload —— 起了 OS 进程的插件会留下孤儿进程"+
"(真实缺陷:995 个 python 监听器残留)。marker 不存在: %v", err)
}
t.Log("✓ Close() 触发了 on_unload(孤儿进程不会再堆积)")
}
// on_unload 抛错不得让 Close 崩掉(best-effort 契约)。
func TestPluginsCloseSurvivesFailingOnUnload(t *testing.T) {
dir := t.TempDir()
pluginDir := filepath.Join(dir, "plugins")
if err := os.MkdirAll(pluginDir, 0755); err != nil {
t.Fatal(err)
}
src := `
local plugin = { name = "boom", version = "1.0.0", exports = {} }
function plugin.on_unload() error("故意炸") end
return plugin
`
if err := os.WriteFile(filepath.Join(pluginDir, "boom.lua"), []byte(src), 0644); err != nil {
t.Fatal(err)
}
ps := NewPlugins(nil, pluginDir)
if err := ps.LoadDir(); err != nil {
t.Fatalf("LoadDir: %v", err)
}
ps.Close() // 不得 panic
}

View File

@ -572,10 +572,101 @@ func (ps *Plugins) Close() {
if ps == nil {
return
}
// ★ 顺序至关重要:**先停调度,再落盘,最后给插件收尾**。
//
// saver 的最终写入要读每个插件的 Lua 表;on_unload 之后 state 已关,
// 读到的就是空 —— 最后一个区间的累积静默丢失(persist_test 的
// TestCloseFlushesTail 正是为守住这一点而存在)。
//
// 所以不能把 callOnUnloadAll 挪到前面,也不能把 save.Close 挪到后面。
//
// ★ 而调度器必须停在**落盘之前**:它每 tick 可能调 Lua、改状态,
// 落在 save.Close 之后就会写进一个已经收尾的 state;停在最前面也顺带
// 保证了「收尾期间不会再有新任务被派发」。
//
// 真实缺陷(与 on_unload 同一形状的第 3 个实例):Runtime.Stop() 此前
// **只在单插件 Unload 里调**,Close() 不调 —— 于是每个插件的调度循环
// (PluginRuntime.loop)在「进程关闭/测试结束」这条路径上永不停止。
// 实测全量回归在 internal/lua 出现 69 个 goroutine 卡在 saver/runtime
// 循环里并超时 600s。
ps.stopSchedulersAll()
// Shard VMs are separate golua states; leaving them open leaks a VM per
// shard on every reload.
ps.shards.Shutdown()
ps.save.Close()
ps.callOnUnloadAll()
}
// stopSchedulersAll 停掉每个插件的调度循环(best-effort,幂等)。
//
// 与 Unload 里的 Runtime.Stop() 是同一契约:Close 是它在进程退出路径上的
// 等价点,不能只有 Unload 有 —— 那正是 on_unload 缺陷的形状(“两处只修一处”)。
func (ps *Plugins) stopSchedulersAll() {
ps.mu.Lock()
plugins := make([]*Plugin, len(ps.plugins))
copy(plugins, ps.plugins)
ps.mu.Unlock()
for _, p := range plugins {
if p == nil || p.Runtime == nil {
continue
}
p.Runtime.Stop()
p.Runtime = nil
}
}
// callOnUnloadAll 依次给每个插件调 on_unload(best-effort)。
//
// 与 Unload 里的调用共用同一实现:两处若各写一遍,将来必然漂移成一个修了
// 一个没修 —— 这正是本次缺陷的形状(Unload 有、Close 没有)。
func (ps *Plugins) callOnUnloadAll() {
ps.mu.Lock()
plugins := make([]*Plugin, len(ps.plugins))
copy(plugins, ps.plugins)
ps.mu.Unlock()
for _, p := range plugins {
ps.callOnUnload(p)
}
}
// callOnUnload 调单个插件的 on_unload(存在才调),并关掉它的 Lua state。
//
// 为什么关 state 也在这里:on_unload 之后 state 就没用了,而 state 一旦关掉,
// 钩子再也调不了 —— 调用与关闭必须紧邻,否则又会漏。Unload 与 Close 各自持有
// 的 state 生命周期不同(Unload 还要 rebuild,Close 之后整体销毁),所以这里
// 只做「调用 + 置空」,由调用方决定其余步骤。
func (ps *Plugins) callOnUnload(p *Plugin) {
if p == nil {
return
}
if err := ps.invokeOnUnload(p, p.Info.Name); err != nil {
log.Printf("[plugins] %s: on_unload: %v", p.Info.Name, err)
}
}
// invokeOnUnload 真正调钩子。抽出来是为了让 Unload 与 Close 共用一份实现
// (含 state 判空与错误返回语义),避免两处契约不一致。
func (ps *Plugins) invokeOnUnload(p *Plugin, name string) error {
p.mu.Lock()
defer p.mu.Unlock()
if p.state == nil || p.state.L == nil {
return nil
}
L := p.state.L
L.GetGlobal(pluginGlobal)
if L.Type(-1) != golua.LUA_TTABLE {
L.Pop(1)
return nil
}
L.GetField(-1, "on_unload")
var err error
if L.Type(-1) == golua.LUA_TFUNCTION {
err = callFnOn(L, "on_unload")
}
L.Pop(2) // plugin table + field remnant
p.state.L.Close()
p.state = nil
return err
}
// LoadDir loads every .lua file in dir as a plugin. Files are loaded in
@ -1941,24 +2032,10 @@ func (ps *Plugins) Unload(name string) error {
// only guaranteed point where it still can. Best-effort by design — a
// hook that errors must not block an unload the operator explicitly asked
// for (a wedged plugin has its own path above).
p.mu.Lock()
if p.state != nil && p.state.L != nil {
p.state.L.GetGlobal(pluginGlobal)
if L := p.state.L; L.Type(-1) == golua.LUA_TTABLE {
L.GetField(-1, "on_unload")
if L.Type(-1) == golua.LUA_TFUNCTION {
if err := callFnOn(L, "on_unload"); err != nil {
log.Printf("[plugins] %s: on_unload: %v", name, err)
}
}
L.Pop(2) // adapter/plugin table + field remnant
} else {
L.Pop(1)
}
p.state.L.Close()
p.state = nil
}
p.mu.Unlock()
//
// 与 Close 共用 invokeOnUnload:两处各写一遍必然漂移 —— 本次缺陷正是
// 「Unload 有、Close 没有」。
_ = ps.invokeOnUnload(p, name)
ps.rebuild()
return nil
}

View File

@ -52,7 +52,7 @@ plugin.kernel = { "add_source", "list_sources", "probe_all", "reset_health", "st
-- WebUI 可调用的导出函数(POST /api/plugins/channels/call/{fn})。
-- set_endpoints 让运维把渠道端点指向自建代理/镜像;测试用它打假上游。
plugin.exports = { "set_endpoints", "account_add", "account_list", "account_update", "account_delete", "account_test", "account_refresh", "account_reorder", "account_reset", "account_retest", "account_adopt", "model_list", "model_refresh", "model_set_disabled", "model_set_disabled_many", "model_set_all_disabled", "model_clear_dead", "provider_status", "provider_set_enabled", "provider_get_order", "provider_set_order", "credits_claim_all", "credits_status", "credits_balances", "credits_permanent_lock", "backup_export", "backup_import", "backup_status", "auto_checkin", "gateway_get_enabled", "gateway_set_enabled", "usage_token_ledger", "usage_badge", "usage_badge_preference", "onboarding_status", "onboarding_claim", "__trae_derive_probe", "__codearts_sign_probe", "__qoder_machine_probe", "__qoder_refresh_probe", "__codearts_dpop_probe", "__codearts_cred_probe", "__codearts_adapter_sign_probe", "__sync_source_probe", "__trae_solo_probe", "__adapter_install_probe", "__store_dir_probe", "__is_model_gone_probe", "__rank_accounts_probe", "__inject_refresh_platform_probe", "__clear_capabilities_probe", "__qoder_claim_outcome_probe", "__is_free_probe", "__claim_covers_probe", "__schedule_probe", "__parse_capability_probe", "__inject_capability_probe", "__ttl_reset_probe", "__ttl_probe", "__ttl_invalidate_probe", "__serial_probe", "__serial_release_probe", "__set_legacy_cred_probe", "__read_cred_probe", "__clear_all_creds_probe", "credits_tier_probe", "__set_lock_permanent_probe", "__set_expiring_window_probe", "__expiring_window_probe", "__record_dead_probe", "__catalog_gate_probe", "__catalog_gate_fail_probe", "credits_capability", "claims_capable" }
plugin.exports = { "set_endpoints", "account_add", "account_list", "account_update", "account_delete", "account_test", "account_refresh", "account_reorder", "account_reset", "account_retest", "account_adopt", "model_list", "model_refresh", "model_set_disabled", "model_set_disabled_many", "model_set_all_disabled", "model_clear_dead", "provider_status", "provider_set_enabled", "provider_get_order", "provider_set_order", "credits_claim_all", "credits_status", "credits_balances", "credits_permanent_lock", "backup_export", "backup_import", "backup_status", "auto_checkin", "gateway_get_enabled", "gateway_set_enabled", "usage_token_ledger", "usage_badge", "usage_badge_preference", "onboarding_status", "onboarding_claim", "__trae_derive_probe", "__codearts_sign_probe", "__qoder_machine_probe", "__qoder_refresh_probe", "__codearts_dpop_probe", "__codearts_cred_probe", "__codearts_adapter_sign_probe", "__sync_source_probe", "__trae_solo_probe", "__adapter_install_probe", "__store_dir_probe", "__set_loopback_probe", "reap_loopbacks", "__is_model_gone_probe", "__rank_accounts_probe", "__inject_refresh_platform_probe", "__clear_capabilities_probe", "__qoder_claim_outcome_probe", "__is_free_probe", "__claim_covers_probe", "__schedule_probe", "__parse_capability_probe", "__inject_capability_probe", "__ttl_reset_probe", "__ttl_probe", "__ttl_invalidate_probe", "__serial_probe", "__serial_release_probe", "__set_legacy_cred_probe", "__read_cred_probe", "__clear_all_creds_probe", "credits_tier_probe", "__set_lock_permanent_probe", "__set_expiring_window_probe", "__expiring_window_probe", "__record_dead_probe", "__catalog_gate_probe", "__catalog_gate_fail_probe", "credits_capability", "claims_capable" }
@ -194,7 +194,9 @@ local PLATFORMS = {
mode = "trae",
exchange_url = "https://api.trae.com.cn/cloudide/api/v3/trae/oauth/ExchangeToken",
exchange_body = '{"ClientID":"{client_id}","RefreshToken":"{refresh_token}","ClientSecret":"-","UserID":""}',
client_id = "", -- 参考用 product.clientId;TRAE 回调直传形态不强制,留空
client_id = "en1oxy7wnw8j9n", -- 实测值(对齐参考 trae-product.ts 的 clientId)
-- ↑ 这个值**不是**可选的:ExchangeToken 的请求体里 ClientID 是必填,
-- 留空会让交换稳定 400(详见文件内 traeCallback 的注释)。
},
},
@ -726,7 +728,10 @@ local PLATFORMS = {
},
hosts = { "codearts.huaweicloud.com", "sts.cn-north-4.myhuaweicloud.com",
"snap-access.cn-north-4.myhuaweicloud.com",
"devcloud.cn-north-4.huaweicloud.com", "auth.huaweicloud.com" },
"devcloud.cn-north-4.huaweicloud.com", "auth.huaweicloud.com",
-- benefit 模型目录(照参考 OPENGW_GATEWAY_CONFIG_URL 的 host)。
-- 不在白名单会被 HTTP 桥拒,目录只剩第 2 个端点的那一半模型。
"opengw.developer.huaweicloud.com" },
-- codearts 的 chat 端点含 /api/v2 前缀(参考 CHAT_API_BASE = .../api/v2)。
base_url = "https://snap-access.cn-north-4.myhuaweicloud.com",
-- 本插件**自己装的**适配器(见 installCodeartsAdapter):华为云 AK/SK 签名
@ -734,7 +739,31 @@ local PLATFORMS = {
-- 签名平台:源注册要交**完整凭据 JSON**(适配器自己解 AK/SK 签名),
-- 不是裸 access token。见 syncAccountSource 的注释。
credential_shape = "full",
models = { "CodeArts-Pangu" },
-- ★ 远端模型目录(照参考 fetchCodeArtsRemoteModels 的**两个**端点)。
--
-- 缺这个曾让 codearts 只剩硬编码的 1 个模型("CodeArts-Pangu"),而
-- 10 个账号全在池里可用 —— 目录端点其实一直可达,只是我们没打。
-- 参考实测的模型(GLM-5.2 / openpangu 系列 / glm-5.2-sft-harmony 等)
-- 全都由这两个端点下发:
-- ① opengw gateway/config → result.models(benefit 模型,如 glm-5.3-flash)
-- ② snap-access /v1/model/builtin → builtinModels(常规模型)
-- 两者都**必须 AK/SK 签名**(ep.sign = "codearts" 走平台签名函数),
-- 且 ② 额外要 Agent-Type / X-Language 两个不参与签名的头。
models_remote = {
endpoints = {
{ url = "https://opengw.developer.huaweicloud.com/api/v1/gateway/config",
method = "GET", sign = "codearts", parse = "codearts_gateway" },
{ url = "https://snap-access.cn-north-4.myhuaweicloud.com/v1/model/builtin",
method = "GET", sign = "codearts", parse = "codearts_builtin",
headers = { ["Content-Type"] = "application/json",
["Agent-Type"] = "PromptCenter",
["X-Language"] = "zh-cn" } },
},
auth = "none", -- 签名由 sign 分支负责,不走 Bearer
parse = "codearts_builtin",
},
-- 兜底目录:远端不可达时仍可选中(照参考的已知可用 id)。
models = { "CodeArts-Pangu", "deepseek-v4-flash", "GLM-5.3", "GLM-5.2" },
checkin = {
url = "https://snap-access.cn-north-4.myhuaweicloud.com/snap-manager/v1/statistics/plugin",
method = "GET",
@ -873,7 +902,11 @@ local PLATFORMS = {
parse = "zcode_configs",
},
endpoint = "/api/v1/zcode-plan/anthropic/v1/messages",
adapter = "anthropic",
-- ★ 不能复用通用 anthropic:zcode 的该通道做**请求体内容检查** —— system 缺
-- 官方身份块结构时直接 405 + {"code":3012,...}(实测;与 HTTP 头、版本号、
-- 请求频率、tools 声明全无关)。本插件自装的 channels-zcode 复用 anthropic
-- 的协议转换,只额外注入身份块(见 ZCODE_ADAPTER_SRC)。
adapter = "channels-zcode",
-- 余额端点(需要 Authorization;照参考 ZCODE_BILLING_BALANCE_URL)
balance = {
url = "https://zcode.z.ai/api/v1/zcode-plan/billing/balance",
@ -2620,6 +2653,23 @@ plugin.state.log = plugin.state.log or {}
-- 字段,先填再被 or {} 覆盖就白填了)。
loadState()
-- ★ 启动清扫:删掉上一进程留下的孤儿回调文件。
--
-- 为什么需要它:loopbacks 追踪表只活在内存里(plugin.state.loopbacks),
-- 进程退出后无从得知上一轮起过哪些接收器。于是进程被强杀/SIGKILL 时,
-- 那句 on_unload 没机会跑,磁盘上就永久留下 callback-*.port / .json。
-- 实测生产攒了 18 个孤儿 .port(对应的 .json 早已消失),且**永远不会被清** ——
-- 重启后内存表是空的,reapLoopback 根本不知道它们存在。
--
-- 判据不是"文件被删了"这么弱,而是"启动后目录里不再有上一轮的残留":
-- internal/core/channels_orphan_callback_test.go。
do
local dir = storeDir()
local sh = io.popen and io.popen("rm -f " .. dir ..
"/callback-*.port " .. dir .. "/callback-*.json 2>/dev/null")
if sh then sh:close() end
end
local function logEvent(msg)
table.insert(plugin.state.log, 1, { at = os.time and os.time() or 0, msg = msg })
while #plugin.state.log > 50 do table.remove(plugin.state.log) end
@ -3068,6 +3118,27 @@ local function parseRemoteModels(kind, body, provider)
end
end
elseif kind == "codearts_builtin" then
-- 照参考 fetchCodeArtsRemoteModels 的第 2 个端点:字段是 builtinModels
-- (**对象**,键为序号;用 pairs 兼容对象/数组两形态)。
local raw = rec.builtinModels or (rec.data and rec.data.builtinModels)
if type(raw) == "table" then
for _, m in pairs(raw) do
local id = type(m) == "table" and (m.model_id or m.modelId or m.id)
if type(id) == "string" and id ~= "" then out[#out+1] = id end
end
end
elseif kind == "codearts_gateway" then
-- 照参考的第 1 个端点:result.models(benefit 模型)。
local arr = rec.result and rec.result.models
if type(arr) == "table" then
for _, m in ipairs(arr) do
local id = type(m) == "table" and (m.model_id or m.modelId or m.id)
if type(id) == "string" and id ~= "" then out[#out+1] = id end
end
end
elseif kind == "zcode_configs" then
-- 照参考 fetchZcodeModels:字段是 data.builtinModels,且它是**对象**
-- (键为序号 "0"/"1"),用 Array.isArray 判定会得到 0 个模型的假阴性。
@ -3146,9 +3217,36 @@ local function refreshRemoteModels(provider)
local extra = plat.headers_fn(tok or "", nil)
for k, v in pairs(extra or {}) do headers[k] = v end
end
local resp, err = __llmsproxy_http({
url = url, method = ep.method or "GET", headers = headers,
})
-- ★ 签名端点:codearts(华为 snap-access)的目录**必须 AK/SK 签名**,
-- 不是 Bearer。ep.sign = "codearts" 时用平台签名函数重建整个请求
-- (签名覆盖 host/x-sdk-date/x-sdk-content-sha256/x-security-token 等头,
-- 故不能「先拼头再签名」—— 必须由签名函数产出最终请求)。
local req = { url = url, method = ep.method or "GET", headers = headers }
if ep.sign == "codearts" then
local cred
for _, a in ipairs(poolList(provider)) do
if a.enabled ~= false then
local raw = __llmsproxy_secrets.get(a.credentialRef)
local okj, cj = pcall(json.decode, raw or "")
if okj and type(cj) == "table" and (cj.access_key_id or cj.access_key) then
cred = cj break
end
end
end
if not cred then
lastErr = "无可用 AK/SK 凭据"
else
local sreq, serr = codeartsSignedRequest(req.method, url, cred, nil)
if sreq then
-- 目录端点额外要求的**非签名**头(照参考 fetchSignedGet 调用点)
for k, v in pairs(ep.headers or {}) do sreq.headers[k] = v end
req = sreq
else
lastErr = tostring(serr)
end
end
end
local resp, err = __llmsproxy_http(req)
if err or not resp or resp.status ~= 200 then
lastErr = (err or ("HTTP " .. tostring(resp and resp.status)))
else
@ -4277,8 +4375,14 @@ local function spawnBrowser(start_url)
-- 客户端可能来自另一台机器(127.0.0.1 指向客户端自己)且 websockify 只绑回环,
-- 所以只能由网关同端口转发;插件只提供回环目标与绝对路径,不处理传输。
local base = "/api/plugins/http/channels/browser/proxy/" .. sess
-- noVNC 用 `new URL(path, location.href)` 解析 path(ui.js 的 connect()),
-- 即**相对 vnc.html 所在目录**解析,默认值就是相对名 'websockify'。
-- 曾传站点根路径(/api/.../websockify)→ 被当相对路径 ⇒ 路径重复拼接:
-- .../proxy/<id>/api/plugins/http/channels/browser/proxy/<id>/websockify
-- 于是 WebSocket 永远连不上(noVNC 显示连接失败,页面看似白屏)。
-- 只用相对名,与 noVNC 默认值一致。
local proxyPath = base .. "/vnc.html?autoconnect=1&resize=scale&password=" .. pass
.. "&path=" .. urlencode(base:sub(2) .. "/websockify")
.. "&path=websockify"
return {
view_url = proxyPath,
proxy_path = proxyPath,
@ -4837,25 +4941,19 @@ function plugin.poll_login(req)
elseif s.platform == "trae" then
-- Trae:回调把 token 直接放在 query 里(refreshToken/userJwt/userInfo),
-- 故把整个回调 query 交给 traeCallback(它在两条路径上共用)。
--
-- ★ 这里曾经有一段**自己发明的**「授权码交换」:回调只带 code 时,拿
-- exchange_body 去 ExchangeToken。那是错的,而且是稳定 400:
-- · ExchangeToken 的签名是 RefreshToken,不是 code;
-- · exchange_body 里根本没有 {code} 占位符,替换是空操作。
-- 结果是日志回一句误导性的「授权码交换失败: 400」,把真因
-- 「上游走了 PKCE 流程」掩盖成「交换出错了」。
--
-- 按参考实现(trae-oauth.ts parseTraeCallbackDetailed)的做法:
-- 带 code 的回调是**合法回调**,只是我们不支持的 PKCE 分支,
-- 要**明确报出来**而不是尝试一个不存在的交换。
-- traeCallback 已内建这个判定(返回「上游返回了 PKCE 授权码…」)。
credential, account, cerr = traeCallback(plat, cb, s)
if not credential and code ~= "" then
-- 回调只给了 code(PKCE 形态)→ 用 exchange 端点的标准交换
local body = (plat.callback.exchange_body or "")
:gsub("{client_id}", plat.callback.client_id or "")
:gsub("{code}", code)
:gsub("{port}", tostring(gatewayPort()))
local resp, err = __llmsproxy_http({ url = plat.callback.exchange_url,
method = "POST", headers = { ["Content-Type"] = "application/json" }, body = body })
if err or not resp or resp.status ~= 200 then
cerr = "Trae 授权码交换失败: " .. tostring(err or (resp and resp.status))
else
local ok, rec = pcall(json.decode, resp.body or "")
local access = ok and type(rec) == "table"
and (rec.Token or rec.token or rec.AccessToken or rec.access_token)
if not access then cerr = "Trae 授权码交换响应缺少 Token"
else credential, account, cerr = json.encode({ access_token = access }), "trae", nil end
end
end
else
-- Gemini 等标准 OAuth:表单交换(必带 client_secret,见 token_body 注释)
local body = (plat.callback.token_body or "")
@ -6267,6 +6365,8 @@ plugin.http = {
description = "把会话的 noVNC 静态资源与 WebSocket 经网关同端口转发(不暴露 VNC 端口)" },
{ path = "channels/browser/collect", method = "POST", handler = "collect_credentials",
roles = { "admin" }, description = "从服务端浏览器取凭据(CDP)" },
{ path = "channels/reap_loopbacks", method = "POST", handler = "reap_loopbacks",
roles = { "admin" }, description = "回收所有回环回调接收器(防测试/异常退出后泄漏)" },
{ path = "channels/browser/stop", method = "POST", handler = "stop_browser",
roles = { "admin" }, description = "回收服务端浏览器栈" },
}
@ -7493,6 +7593,24 @@ function plugin.stop_browser(req)
end
-- browser_status:当前浏览器会话状态(给 UI 显示)。
-- reap_loopbacks:回收**所有**回环接收器。
--
-- 为什么需要显式入口:回环本来只在**会话过期**时由 reapLoopback 收掉
-- (sweepSessions 是惰性的,靠读取时顺带做)。于是有一条稳定的泄漏路径:
-- 测试或运维起了 login 会话后直接退出,会话从未「过期」⇒ 接收器进程常驻。
-- 实测本机积累到 995 个(其中 828 个超过 24 小时),全是 /tmp/Test*/ 下的
-- 测试残留 —— 生产路径的会被正常回收(因为生产会话真会过期)。
--
-- 对生产也有用:浏览器/授权页关掉后想立刻清理,不必等会话过期。
function plugin.reap_loopbacks(req)
local n = 0
for sid in pairs(plugin.state.loopbacks or {}) do
reapLoopback(sid)
n = n + 1
end
return { status = 200, json = { ok = true, reaped = n } }
end
function plugin.browser_status(req)
local b = browserStack()
local s = b.session
@ -7711,7 +7829,22 @@ traeCallback = function(plat, q, s)
if account == "" then account = "trae" end
-- PKCE 形态探测:仅在 refreshToken / jwtToken 都空时才判,与参考一致。
local authCode = q.code or q.authCode or jsonField(q.authCodeInfo or "", "code")
--
-- ⚠️ 候选来源必须**逐个取第一个非空**(照参考 authCodeCandidates 的 5 个来源),
-- 不能用 `a or b or c` 链:jsonField 取不到时返回空串而非 nil,而 Lua 里
-- 空串是**真值**,链会在第一个空串处短路 —— 后续来源永远取不到。
-- authCodeInfo 可能是 JSON(含 code/authCode 字段),也可能是**纯 code 字符串**
-- (参考注释点名),故把原始值作为最后兜底。
local authCode = ""
do
local info = q.authCodeInfo or ""
for _, cand in ipairs({ q.code or "", q.authCode or "",
jsonField(info, "code"), jsonField(info, "authCode"),
info }) do
if type(cand) == "string" and cand ~= "" then authCode = cand; break end
end
authCode = authCode:gsub("^%s+", ""):gsub("%s+$", "")
end
if (not refreshToken or refreshToken == "") and (not jwtToken or jwtToken == "") then
if authCode and authCode ~= "" then
@ -8869,6 +9002,311 @@ end
return adapter
]==]
local ZCODE_ADAPTER_SRC = [===[
-- ============================================================================
-- ZCode 专用适配器(插件自装:channels-zcode)
--
-- 为什么必须自装而不是复用通用 anthropic:
-- zcode 的 /zcode-plan/anthropic 通道对请求体做**内容检查** —— system 缺少
-- 官方身份块结构时直接返回
-- HTTP 405 + {"code":3012,"msg":"request has been blocked due to unusual activity."}
-- 参考实测矩阵(同账号、同验证码来源):
-- 无 system → 405 + 3012 ✗
-- 仅 cliPrefix(42 字符) → 405 + 3012 ✗
-- cliPrefix + stable(约 2894 字符) → 200 ✓
-- ⇒ 判据是「身份块结构是否存在」,与 HTTP 头、版本号、请求频率、多轮历史、
-- tools 声明、运行时(Electron/curl/Node)**全部无关**(三个账号 17 次实测)。
--
-- ⚠ 参考 2026-10-03 复测修正了两条旧说法,排查时别按旧的来:
-- ① HTTP 状态码是 **405**,不是 403;
-- ② 日期块(<system-reminder>)**不是**判据 —— 去掉照样 200。仍照发是因为
-- 官方如此且零成本,但别把「缺它就 3012」当结论(会让排查耗在错方向)。
--
-- ⚠ 身份块与上游策略**强耦合**:官方客户端升级若改了结构,本文件必须同步
-- (参考有同样的维护警告)。
--
-- 实现方式:复用内核的 anthropic 适配器(读它的源码并执行,拿回 adapter 表),
-- **只覆盖 transform_request** 注入身份块。协议转换(工具调用、图像块、流式帧)
-- 因此始终与 anthropic 那一份一致,不会漂移。
-- ============================================================================
local adapter = { name = "channels-zcode", version = "1.0.0" }
-- ★ 官方 CLI 前缀(准入必需)。逐字复刻,勿改。
local CLI_PREFIX = "You are ZCode, an interactive coding agent"
-- ★ 官方 stable 段(准入必需;三段以 "\n\n" 连接)。逐字复刻,勿改。
-- 官方完整身份块还含 ~5KB 的 dynamic 段(给 coding agent 的行为指令),与准入
-- 无关,且它会被放在 system 开头从而**压过调用方自己的 prompt**(表现为
-- "啰嗦、慢")—— 故只发准入必需的部分(参考同此)。
local SECTION_A = [==[
You are an interactive ZCode agent that helps users with software engineering tasks.
IMPORTANT: Assist with authorized security testing, defensive security, CTF challenges, and educational contexts. Refuse requests for destructive techniques, DoS attacks, mass targeting, supply chain compromise, or detection evasion for malicious purposes. Dual-use security tools (C2 frameworks, credential testing, exploit development) require clear authorization context: pentesting engagements, CTF competitions, security research, or defensive use cases.
# Harness
- Text you output outside of tool use is displayed to the user as Github-flavored markdown in a terminal.
- Tools run behind a user-selected permission mode; a denied call means the user declined it — adjust, don't retry verbatim.
- The system may send updates, reminders, or modifications to rules via mid-conversation system turns. These are system-controlled, unlike function results. Hooks may intercept tool calls; treat hook output as user feedback.
- Prefer the dedicated file/search tools over shell commands when one fits. Independent tool calls can run in parallel in one response.
- Reference code as `file_path:line_number` — it's clickable.
]==]
local SECTION_B = [==[
# ZCode Desktop Context
### Files & URLs
- Return local web URLs as Markdown links (e.g., [label](http://127.0.0.1:8080)).
- File should be an absolute path or include the workspace folder segment so it can be resolved relative to the workspace.
- Unless otherwise specified, return local file references as Markdown links (e.g., [name.md](/absolute/path/to/name.md)).
### Inline Code Comments
- Use the ::code-comment{...} directive when you need to attach feedback directly to specific code lines.
- Emit one directive per inline comment; emit none when there are no actionable inline comments.
- Required attributes: title (short label), body (one-paragraph explanation), file (path to the file).
- Optional attributes: start, end (1-based line numbers), priority (0-3).
- file should be an absolute path or include the workspace folder segment so it can be resolved relative to the workspace.
- Keep line ranges tight; end defaults to start.
- Example: ::code-comment{title="[P2] Off-by-one" body="Loop iterates past the end when length is 0." file="/path/to/foo.ts" start=10 end=11 priority=2}
]==]
local SECTION_C = [==[
# Working style
When you have enough information to act, act. Do not re-derive facts already established in the conversation, re-litigate a decision the user has already made, or narrate options you will not pursue. If you are weighing a choice, give a recommendation, not an exhaustive survey. Prefer reading the actual file or running the actual command over reasoning about what it probably contains. When a signal pattern-matches to a known failure, check that the evidence actually supports that specific diagnosis before acting on it.
]==]
local STABLE_JOINED = SECTION_A .. "\n\n" .. SECTION_B .. "\n\n" .. SECTION_C
-- 参考声明的期望长度(2900)。用于自检:文本被改动(转义/截断)时立刻发现,
-- 而不是等到线上吃 3012 才知道。
local EXPECTED_MIN_CHARS = 2800
-- ============================================================================
-- 复用 anthropic 适配器
-- ============================================================================
-- 适配器目录 = 插件目录的**兄弟**目录(<data>/plugins 与 <data>/adapters)。
-- 由插件目录推导,不猜绝对路径(测试与多实例部署都靠它隔离)。
local function adaptersDir()
local pd = __llmsproxy_plugin_dir
if type(pd) ~= "string" or pd == "" then
pd = (os.getenv and os.getenv("LLMSPROXY_PLUGIN_DIR")) or ""
end
if type(pd) ~= "string" or pd == "" then return nil end
local base = pd:gsub("/+$", "")
local parent = base:match("^(.*)/[^/]+$")
if not parent then return nil end
return parent .. "/adapters"
end
-- loadAnthropic():在本地环境里执行内核的 anthropic 适配器源码,拿回它的表。
local function loadAnthropic()
local dir = adaptersDir()
if not dir then return nil, "无法推导适配器目录" end
local f = io.open(dir .. "/anthropic.lua", "r")
if not f then return nil, "读不到 anthropic.lua(" .. dir .. ")" end
local src = f:read("*a")
f:close()
local chunk, lerr = load(src, "anthropic.lua")
if not chunk then return nil, "anthropic.lua 无法编译: " .. tostring(lerr) end
local ok, base = pcall(chunk)
if not ok or type(base) ~= "table" then
return nil, "anthropic.lua 执行失败: " .. tostring(base)
end
return base, nil
end
local BASE, BASE_ERR = loadAnthropic()
if BASE then
for k, v in pairs(BASE) do
if adapter[k] == nil then adapter[k] = v end
end
end
adapter.name = "channels-zcode"
adapter.version = "1.0.0"
-- ============================================================================
-- 身份块构造
-- ============================================================================
-- isGitRepo(cwd):只看 .git 是否存在(照参考,廉价无副作用)。
local function isGitRepo(cwd)
if type(cwd) ~= "string" or cwd == "" then return false end
local p = cwd:gsub("/+$", "") .. "/.git"
local f = io.open(p, "r")
if f then f:close() return true end
-- .git 也可能是**目录**(普通仓库),io.open 打不开目录:用 popen 判存在
local sh = io.popen and io.popen("test -e " .. p .. " && echo y")
if sh then
local r = sh:read("*a") or ""
sh:close()
if r:match("y") then return true end
end
return false
end
-- formatLocalIsoDate():**本地时区**的 ISO 日期(官方用本地日期,不是 UTC)。
local function formatLocalIsoDate()
local t = os.date("*t")
if not t then return "" end
return string.format("%04d-%02d-%02d", t.year, t.month, t.day)
end
-- buildEnvironmentSection():官方形态的 "# Environment" 段。
-- 不发它的后果:模型答不出自己是谁、不知工作目录与平台(会用相对路径瞎猜、
-- 以为该给 bash 命令)。
local function buildEnvironmentSection(cwd, provider, model, platform)
if type(cwd) ~= "string" or cwd:gsub("%s+", "") == "" then cwd = "." end
local plat = platform or "linux"
local shell = (plat == "win32") and "powershell" or "bash"
local arch = (os.getenv and os.getenv("LLMSPROXY_ARCH")) or "x64"
return table.concat({
"# Environment",
"You have been invoked in the following environment:",
" - Primary working directory: " .. cwd,
" - Is a git repository: " .. (isGitRepo(cwd) and "yes" or "no"),
" - Platform: " .. plat,
" - Shell: " .. shell,
" - OS Version: " .. plat .. " " .. arch,
" - You are powered by the model named " .. tostring(provider or "zcode") .. "/"
.. tostring(model or "glm-5.3-flash") .. ".",
}, "\n")
end
-- buildSystemBlocks(callerSystem, opts):官方形态的 system **块数组**。
-- block[1] = cliPrefix(准入必需)
-- block[2] = stable(准入必需)
-- block[3] = Environment 段
-- block[4] = 调用方 system(**必须追加在最后**:上游看的是前缀结构)
-- 只给**最后一块**打 cache_control:Anthropic 单请求最多 4 个断点,"逐块打"
-- 会用满预算而让 tools 再也打不了点(参考 2026-09-30 改为此形态)。
local function buildSystemBlocks(callerSystem, opts)
opts = opts or {}
local blocks = {
{ type = "text", text = CLI_PREFIX },
{ type = "text", text = STABLE_JOINED },
{ type = "text", text = buildEnvironmentSection(opts.cwd, opts.provider, opts.model, opts.platform) },
}
if type(callerSystem) == "string" and callerSystem:match("%S") then
blocks[#blocks + 1] = { type = "text", text = callerSystem }
end
blocks[#blocks].cache_control = { type = "ephemeral" }
return blocks
end
-- contextPrefixBlock():<system-reminder> 日期块(官方逐字形态)。
-- ⚠ 照发但**不是准入判据**(见文件头)。形态细节勿"优化":
-- 整块是**一个** text 块、插到 content **数组**最前(不是拼进文本字符串,
-- 后者会改变结构、仍被判为裸请求);outro 前有 **6 个空格**缩进。
local function contextPrefixBlock()
local body = table.concat({
"As you answer the user's questions, you can use the following context:",
"# currentDate\nToday's date is " .. formatLocalIsoDate() .. ".",
"",
" IMPORTANT: this context may or may not be relevant to your tasks. "
.. "You should not respond to this context unless it is highly relevant to your task.",
}, "\n")
return { type = "text", text = "<system-reminder>\n" .. body .. "\n</system-reminder>" }
end
-- ============================================================================
-- 覆盖 transform_request:先做 anthropic 转换,再注入身份块
-- ============================================================================
function adapter.transform_request(raw_body)
-- ★ 基座读不到时**响亮失败**,不能静默退化。
--
-- 若在这里"尽力而为"(只注入身份块、不做协议转换),会产出一个身份块看着
-- 完全正确、而工具调用/图像/流式结构全没转换的请求 —— 上游可能 200,
-- 但模型拿不到工具定义、图像丢失,症状是"模型变笨了",与准入毫无关系,
-- 排查会完全跑偏。宁可让请求在网关侧明确报错(可定位),也不要静默发出去。
if type(BASE) ~= "table" or type(BASE.transform_request) ~= "function" then
return error("channels-zcode: anthropic 基座未装载(" .. tostring(BASE_ERR) ..
")—— 协议转换无法进行,拒绝发出未转换的请求")
end
local out = raw_body
do
local ok, res = pcall(BASE.transform_request, raw_body)
if ok and type(res) == "string" then out = res end
end
if type(out) ~= "string" or out == "" then return raw_body end
local ok, req = pcall(json.decode, out)
if not ok or type(req) ~= "table" then return out end
-- anthropic.lua 产出的 system 是**纯字符串**;上游要的是**块数组**,
-- 故在此改写成块数组(上游检查的正是这个结构)。
local caller = req.system
if type(caller) == "table" then
local parts = {}
for _, b in ipairs(caller) do
if type(b) == "table" and type(b.text) == "string" then parts[#parts + 1] = b.text end
end
caller = table.concat(parts, "\n\n")
end
local opts = {}
-- cwd 必须给**真值**:参考声明「cwd is never "unknown" in real traffic」。
opts.cwd = (os.getenv and os.getenv("PWD")) or "."
opts.provider = "zcode"
opts.model = req.model
opts.platform = "linux"
req.system = buildSystemBlocks(caller, opts)
-- ★ 日期块:只处理**第一条**消息,且它必须是 role == "user"(官方行为)。
--
-- 两条容易漏掉的规则(照参考 withContextPrefix,「优化」它们会偏离官方):
-- ① **幂等**:已以 <system-reminder> 开头则不重复插。不判的话,同一请求
-- 在重试/多次 transform 时会把日期块叠成好几层,改变前缀结构;
-- ② **只看第一条**:若首条不是 user(例如 assistant 开场),**不动** ——
-- 不是"往后找一个 user 消息"。我第一版就是往后找,与官方行为不符。
local msgs = req.messages
if type(msgs) == "table" then
local first = msgs[1]
if type(first) == "table" and first.role == "user" then
local c = first.content
-- 已插过(字符串或块数组两种形态都要判)→ 不重复插。
-- ⚠ 长度必须用 #SR 算,不能写死 —— 我第一版写 `sub(1, 16)` 而
-- "<system-reminder>" 是 **17** 字符,判断**永远为假** ⇒ 幂等失效、
-- 重试时日期块叠加(判据当场抓到)。
local SR = "<system-reminder>"
local already = false
if type(c) == "string" then
already = c:sub(1, #SR) == SR
elseif type(c) == "table" and type(c[1]) == "table" then
local t = c[1].text
already = type(t) == "string" and t:sub(1, #SR) == SR
end
if not already then
local blk = contextPrefixBlock()
if type(c) == "table" then
table.insert(c, 1, blk)
elseif type(c) == "string" then
-- 纯文本 content 转成块数组(官方就是数组形态)
first.content = { blk, { type = "text", text = c } }
else
first.content = { blk }
end
end
end
end
return json.encode(req)
end
-- 暴露给判据:身份块长度与装载状态("装了但身份块为空"这类问题没有它只能靠猜)
adapter.__identity_probe = function()
return {
base_loaded = BASE ~= nil,
base_err = BASE_ERR,
cli_prefix_len = #CLI_PREFIX,
stable_len = #STABLE_JOINED,
total_len = #CLI_PREFIX + #STABLE_JOINED,
expected_min = EXPECTED_MIN_CHARS,
}
end
return adapter
]===]
-- ============================================================================
-- Cline 专用适配器(插件自装:channels-cline)
-- ============================================================================
@ -9027,6 +9465,24 @@ local function installGeminiAdapter()
return true, nil
end
-- installZcodeAdapter():装/更新本插件自己的 zcode 适配器。
--
-- 为什么必须有:zcode 的 /zcode-plan/anthropic 通道做**请求体内容检查** ——
-- system 缺官方身份块结构直接 405 + 3012(实测),与 HTTP 头/版本/频率全无关。
-- 通用 anthropic 适配器不注入身份块 ⇒ 即使拿到 zcode 账号也**必然**被拒。
-- 幂等(update 失败退化为 install);失败只记日志,不阻断插件加载。
local function installZcodeAdapter()
if not __llmsproxy_adapters then return false, "无适配器桥(旧内核?)" end
local f, lerr = load(ZCODE_ADAPTER_SRC)
if not f then return false, "源码语法错误: " .. tostring(lerr) end
local _, uerr = __llmsproxy_adapters.update("channels-zcode", ZCODE_ADAPTER_SRC)
if uerr then
local _, ierr = __llmsproxy_adapters.install("channels-zcode", ZCODE_ADAPTER_SRC)
if ierr then return false, ierr end
end
return true, nil
end
-- installCodeartsAdapter():装/更新本插件自己的 codearts 适配器。
-- 幂等(update 失败时退化为 install);失败只记日志,不阻断插件加载 ——
-- 适配器装不上时源注册会报"未知适配器",比让整个插件加载失败更好定位。
@ -9553,6 +10009,29 @@ function plugin.__store_dir_probe()
return { json = { store_dir = storeDir() } }
end
-- plugin.__set_loopback_probe:只给测试用 —— 把某会话的 loopback 回调文件
-- 指到测试摆好的路径,以便直接驱动 poll_login 的 callback 分支。
--
-- 为什么需要它:callback 流的真实登录走 poll_login(读 loopback 文件),
-- 而那个文件平时由插件自己起的 python 接收器写入。判据要验的正是**这条路径**
-- 的转码/交换行为(真实缺陷曾藏在它的 trae 分支里),但测试不起真实接收器,
-- 故需要这个注入点。生产代码不会调用它。
function plugin.__set_loopback_probe(args)
args = args or {}
local sid = tostring(args.session_id or "")
local file = tostring(args.file or "")
if sid == "" or file == "" then return { json = { error = "need session_id and file" } } end
if type(plugin.state.loopbacks) ~= "table" then plugin.state.loopbacks = {} end
-- ★ 合并而非覆盖:真实会话的条目里带着 pid/port_file,覆盖掉它们
-- 会让 reapLoopback 杀不掉那个 python 接收器 —— 探针自己就成了泄漏源
-- (实测:覆盖写法在该测试里留下 1 个孤儿进程,而其他测试已归零)。
local cur = plugin.state.loopbacks[sid]
if type(cur) ~= "table" then cur = {} end
cur.file = file
plugin.state.loopbacks[sid] = cur
return { json = { ok = true, session_id = sid, file = file, kept_pid = cur.pid or "" } }
end
-- plugin.credits_tier_probe:只给测试用 —— 单账号的余额分档结果。
-- 暴露 expiring/permanent/tier/usable 四个值,让判据能逐条钉住分档规则
-- (含"失效包必须跳过""到期未知归永久""锁定永久积分时只剩永久的号不可用")。
@ -9903,6 +10382,7 @@ function plugin.__adapter_install_probe()
codearts = plugin._codearts_adapter,
trae = plugin._trae_adapter,
gemini = plugin._gemini_adapter,
zcode = plugin._zcode_adapter,
} }
end
@ -9994,6 +10474,9 @@ do
plugin._qoder_adapter = { ok = qok, err = qerr }
local cok, cerr = installClineAdapter()
plugin._cline_adapter = { ok = cok, err = cerr }
local zok, zerr = installZcodeAdapter()
plugin._zcode_adapter = { ok = zok, err = zerr }
if not zok then logEvent("ZCode 适配器装载失败: " .. tostring(zerr)) end
if not cok then logEvent("Cline 适配器装载失败: " .. tostring(cerr)) end
if not gok then logEvent("Gemini 适配器装载失败: " .. tostring(gerr)) end
if not qok then logEvent("Qoder 适配器装载失败: " .. tostring(qerr)) end