fix(bridges): 续谈失败静默 + duplicate_relay 静默挂死(两个都是「人那边什么都收不到」)
同一类问题在两个地方:出事的当下看不出来,表现是「信发出去了,然后再无音讯」。
## 1)pi 的续谈失败不回失败信(实测缺口)
模型侧 402(余额不足)时,**新会话**那条路会回一封「处理失败」,而**续谈**那条路
只写日志就 `throw` —— 发件人什么都收不到。邮件驱动的会话没有本地界面可以看,
没有这封信就等于静默挂死。复现条件很普通:往一条**已存在**的会话再发一封信。
修法与邻居一致:续谈失败也回失败信。但**不能复用**共用库的 `renderFailureReport`
——那段文案说「划定范围内的模型全部调用失败」并建议「调整可用模型范围」,
而续谈是**故意不降级**的(换模型=换会话=丢掉上下文,而上下文正是发件人指定
这条会话的原因)。照抄等于让人去调一个在这里无效的旋钮,他会去改配置,
然后发现依然失败。新增 `renderResumeFailure`:点明是续谈、附上游错误原文、
建议「确实要换模型就新建一条会话」。
**活体验证**(模型侧仍是 402,失败本身就是测试条件):发一封进 pi 的已有会话,
5 秒内收到失败信,内容含 402 原文且不再出现「调整模型范围」。
顺带把 pi 里 2 处没 clamp 的 relay_key 收敛(上一轮审计只看了权限键)。
## 2)duplicate_relay:只有 zcode 认,另三桥会等一个永远不会来的决策
网关对重复的 relay_key 回 **HTTP 200 `{status:"duplicate_relay"}` 并提前返回**:
不建请求、不发邮件、**永远不会有人来决策**。zcode 桥认它并当场失败,而
pi/opencode/dsh 把它当成功,接着等 `permission_decision` 事件 —— pi 那句
`await new Promise(...)` 连超时都没有。这是 zcode 上一轮那个缺陷的同类,
只是发生在另三个桥上。
- `lib/relay-key.js`(**共用**,四处逐字节同源)新增 `isDuplicateRelay` /
`DUPLICATE_RELAY_STATUS`:它长得像成功(200),所以必须单独认;对「发信」
那一侧重复就该当成功(幂等),但对「等一个决定」那一侧它与故障后果相同。
- pi / opencode / dsh 三桥在权限转发处接上判据并**当场拒绝**
(各自用自己的拒绝形状:`block: true` / `output.status = "deny"` / `'rejected'`)。
- zcode 里那份本地实现收敛到共用库(同一判据不该有两个定义)。
## 3)新增接线断言(带判据自检)
`test/permission-forward-wiring.test.mjs`(pi/opencode/dsh 三份同一内容):
纯函数测试对这类缺口天生无能为力(函数是对的,只是没人调用它),所以它读源码
验形态,钉住「判据在、落在权限转发这条路上、给出本桥形状的拒绝」。
三条自检都在写的过程中抓到了我自己的错:
- 第一次 `ROOT` 算错 → 过滤后 0 个桥、循环全不跑而「全绿」→ 加了
「找不到装着各桥的目录就判红」;
- 顺序判据写成「在文件里最早的 await 之前」,量到了别处的等待 → 三桥全红,
改成「必须在上报之后」;
- dsh 是**两段式**(`.then` 里抛、`catch` 的 `duplicateRelay` 分支里拒),
第一版抽取套错了分支 → 永远找不到 `return 'rejected'`。
扰动验证:把 pi 的判据禁用后该条变红,还原即绿(改动前后都核对了字节数)。
而 dsh 那条也暴露了:我把返回形状写成了 opencode 的 `{status:'deny'}`,
**`tsc` 没报错**(返回类型是宽联合),只有对着邻居读才发现 DSH 要的是
`'rejected'` 字符串 + `noteDenial`。
## 4)部署脚本:zcode 分支现在会重启驱动
`redeploy-plugin.sh` 的 zcode 分支只切软链(宿主是 ZCode 应用,不能重启它),
但**驱动是我们自己的 unit** —— 不重启它,进程里跑的还是切换前的代码。
这个由刚写的 `check-deploy-drift.mjs` 当场抓到(它比进程启动时刻与软链切换时刻),
而当时所有其它检查都是绿的。已补上重启并验证。
## 复查
四桥全量 413 / 321 / 370 / 380 全绿;共用库四方同源;部署漂移四项全通过;
四桥真发真收冒烟(dsh/opencode/zcode 正常回信;pi 因模型侧 402 回失败信 ——
这正是上面第 1 条要修的路径)。
另:写这段时踩到一个自伤 —— 用 `npx asar extract-file <asar> dist/index.html`
检查包内容时,它把文件**写进了 cwd**,正好覆盖掉 Vite 的源码模板
`client/electron/index.html`(下次构建会拿被污染的模板去构建)。已还原并重建,
产物哈希与之前一致。要看 asar 内容请用 `@electron/asar` 的 API(返回 Buffer),
别用这个 CLI 子命令。
This commit is contained in:
@ -227,6 +227,29 @@ mcp_handshake() {
|
|||||||
MIN_NAMES=11
|
MIN_NAMES=11
|
||||||
|
|
||||||
if [ "$HOST" = "zcode" ]; then
|
if [ "$HOST" = "zcode" ]; then
|
||||||
|
# 宿主是 ZCode 应用(不能重启它),但**驱动是我们自己的 unit** —— 必须重启它。
|
||||||
|
#
|
||||||
|
# 只切软链不重启驱动的后果是**静默跑旧代码**:进程持有的是启动那一刻加载进内存的
|
||||||
|
# 模块,`current` 指向哪对已启动的进程毫无影响。实测被 `check-deploy-drift.mjs`
|
||||||
|
# 当场抓到(它比进程启动时刻与软链切换时刻),而那时所有其它检查都是绿的。
|
||||||
|
if systemctl list-unit-files 2>/dev/null | grep -q '^zcode-mail-bridge.service'; then
|
||||||
|
if systemctl is-active --quiet zcode-mail-bridge 2>/dev/null; then
|
||||||
|
systemctl restart zcode-mail-bridge
|
||||||
|
sleep 4
|
||||||
|
if systemctl is-active --quiet zcode-mail-bridge; then
|
||||||
|
ok "已重启驱动 zcode-mail-bridge(否则它仍在跑切换前的代码)"
|
||||||
|
else
|
||||||
|
bad "重启 zcode-mail-bridge 失败(服务未 active)"
|
||||||
|
rollback
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
else
|
||||||
|
info "驱动 zcode-mail-bridge 未运行,跳过重启(需要时 systemctl start 它)"
|
||||||
|
fi
|
||||||
|
else
|
||||||
|
info "未安装 zcode-mail-bridge.service,跳过重启"
|
||||||
|
fi
|
||||||
|
|
||||||
say "后置验证(zcode:宿主是应用,不能重启它)"
|
say "后置验证(zcode:宿主是应用,不能重启它)"
|
||||||
TOOLS=$(mcp_handshake "$DEST/current")
|
TOOLS=$(mcp_handshake "$DEST/current")
|
||||||
if [ "${TOOLS:-0}" -ge "$MIN_NAMES" ]; then
|
if [ "${TOOLS:-0}" -ge "$MIN_NAMES" ]; then
|
||||||
|
|||||||
12
plugins/dsh-mail-bridge/lib/relay-key.d.ts
vendored
12
plugins/dsh-mail-bridge/lib/relay-key.d.ts
vendored
@ -18,3 +18,15 @@ export function clampRelayKey(key: string | null | undefined, limit?: number): s
|
|||||||
* 4xx(除 408 / 429)= 永久;408 / 429 / 5xx / 无 status = 暂时。
|
* 4xx(除 408 / 429)= 永久;408 / 429 / 5xx / 无 status = 暂时。
|
||||||
*/
|
*/
|
||||||
export function isPermanentFailure(err: { status?: number | string } | null | undefined): boolean;
|
export function isPermanentFailure(err: { status?: number | string } | null | undefined): boolean;
|
||||||
|
|
||||||
|
/** 网关把重复的 relay_key 判为**幂等命中**时的回包标识。 */
|
||||||
|
export const DUPLICATE_RELAY_STATUS: string;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 这个回包是不是「重复键,什么都没发生」。
|
||||||
|
*
|
||||||
|
* 网关对重复键回 HTTP 200 + `{status:"duplicate_relay"}` 并**提前返回**:
|
||||||
|
* 不建请求、不发邮件,也永远不会有人来决策。长得像成功,但等决策的那一侧
|
||||||
|
* 会永远等下去(静默挂死),所以必须单独认。
|
||||||
|
*/
|
||||||
|
export function isDuplicateRelay(res: unknown): boolean;
|
||||||
|
|||||||
@ -125,3 +125,41 @@ export function isPermanentFailure(err) {
|
|||||||
if (status === 408 || status === 429) return false; // 超时 / 限流 → 暂时
|
if (status === 408 || status === 429) return false; // 超时 / 限流 → 暂时
|
||||||
return status >= 400 && status < 500;
|
return status >= 400 && status < 500;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 网关把重复的 relay_key 判为**幂等命中**时的回包标识。
|
||||||
|
*
|
||||||
|
* 两个出口都会这么答(权限询问与代发邮件),且都是 **HTTP 200 且提前返回**:
|
||||||
|
* 不建请求、不发邮件,**也永远不会有人来决策**。
|
||||||
|
*/
|
||||||
|
export const DUPLICATE_RELAY_STATUS = 'duplicate_relay';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 这个回包是不是「重复键,什么都没发生」。
|
||||||
|
*
|
||||||
|
* ## 为什么必须单独认它
|
||||||
|
*
|
||||||
|
* 它长得像成功(200),所以「发完就等决策」的实现会一直等下去。实测过的形态:
|
||||||
|
* pi 的 worker 在 `post('/permission/request')` 之后无条件
|
||||||
|
* `await new Promise(resolve => pending.set(relayKey, resolve))`,而那个 resolve
|
||||||
|
* 只由 `permission_decision` 事件触发 —— 重复的键永远不会带来决策,
|
||||||
|
* 于是那封邮件**静默挂死**(模型干等,人以为在跑)。
|
||||||
|
*
|
||||||
|
* 什么时候会重复(都是**正常**的重试,不是故障):
|
||||||
|
*
|
||||||
|
* - 插件重启后重放同一轮(键是确定性的,这正是它的设计目的)
|
||||||
|
* - SDK / 上游重放同一个 tool call
|
||||||
|
* - 上一次询问已经被人决定过,而这一侧没收到那个决策(重启、断线)
|
||||||
|
*
|
||||||
|
* 对「发信」那一侧,重复就该当成功(幂等,这正是网关返回 200 的意思);
|
||||||
|
* 但对「等一个决定」那一侧,它与故障的后果完全一样:永远等不到。
|
||||||
|
* 所以两边的处置必须分开写,而不是共用一个「发成功了」的判定。
|
||||||
|
*
|
||||||
|
* @param {unknown} res 网关的响应体(不是 HTTP 响应对象)
|
||||||
|
* @returns {boolean}
|
||||||
|
*/
|
||||||
|
export function isDuplicateRelay(res) {
|
||||||
|
return Boolean(
|
||||||
|
res && typeof res === 'object' && !Array.isArray(res) && res.status === DUPLICATE_RELAY_STATUS
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|||||||
@ -28,7 +28,7 @@ import {
|
|||||||
replyInstruction,
|
replyInstruction,
|
||||||
inboundHeadline,
|
inboundHeadline,
|
||||||
} from '../lib/relay-policy.js';
|
} from '../lib/relay-policy.js';
|
||||||
import { clampRelayKey, isPermanentFailure } from '../lib/relay-key.js';
|
import { clampRelayKey, isPermanentFailure, isDuplicateRelay } from '../lib/relay-key.js';
|
||||||
import { BoundedMap, BoundedSet, MAX_TRACKED_MAILS, MAX_TRACKED_SESSIONS } from '../lib/bounded.js';
|
import { BoundedMap, BoundedSet, MAX_TRACKED_MAILS, MAX_TRACKED_SESSIONS } from '../lib/bounded.js';
|
||||||
import {
|
import {
|
||||||
userMessage,
|
userMessage,
|
||||||
@ -1737,23 +1737,54 @@ export function apply(ctx: any, config: PluginConfig): void {
|
|||||||
// 无人可问则 409)。插件若把来信人当决策人,Agent 之间转派任务时
|
// 无人可问则 409)。插件若把来信人当决策人,Agent 之间转派任务时
|
||||||
// (A 把活分给 B)权限邮件会发给 Agent 自己 —— Agent 不可能在界面上点
|
// (A 把活分给 B)权限邮件会发给 Agent 自己 —— Agent 不可能在界面上点
|
||||||
// 「同意」,于是下面那个 await 永不 resolve,会话无声挂死。
|
// 「同意」,于是下面那个 await 永不 resolve,会话无声挂死。
|
||||||
await client.post('/permission/request', {
|
await client.post('/permission/request', {
|
||||||
question: `请求执行 ${req.toolName}`,
|
question: `请求执行 ${req.toolName}`,
|
||||||
options: ['同意', '拒绝'],
|
options: ['同意', '拒绝'],
|
||||||
context: [
|
context: [
|
||||||
`工具:${req.toolName}`,
|
`工具:${req.toolName}`,
|
||||||
req.callId ? `调用 ID:${req.callId}` : '',
|
req.callId ? `调用 ID:${req.callId}` : '',
|
||||||
req.reason ? `理由:${req.reason}` : '',
|
req.reason ? `理由:${req.reason}` : '',
|
||||||
// 决策人未必是这条会话的参与者(Agent 转派出来的会话,人从没见过它),
|
// 决策人未必是这条会话的参与者(Agent 转派出来的会话,人从没见过它),
|
||||||
// 只给工具名无从判断,得说明这活是谁派的、为的什么事(B-8.4)。
|
// 只给工具名无从判断,得说明这活是谁派的、为的什么事(B-8.4)。
|
||||||
mctx?.subject ? `触发任务:${mctx.subject}` : '',
|
mctx?.subject ? `触发任务:${mctx.subject}` : '',
|
||||||
mctx?.replyTo ? `任务来自:${mctx.replyTo}` : '',
|
mctx?.replyTo ? `任务来自:${mctx.replyTo}` : '',
|
||||||
].filter(Boolean).join('\n'),
|
].filter(Boolean).join('\n'),
|
||||||
session_id: mailSessionID,
|
session_id: mailSessionID,
|
||||||
relay_key: relayKey,
|
relay_key: relayKey,
|
||||||
});
|
}).then((accepted: any) => {
|
||||||
} catch (e: any) {
|
// ★ 幂等命中:网关回 200 `{status:"duplicate_relay"}` 并**提前返回** ——
|
||||||
// 409 = 服务端已判定这条任务链上没有人类,永远不会有人来点头。
|
// 没有产生新的询问,也永远不会有人来决策,而下游只等
|
||||||
|
// `permission_decision` 事件。不认它的代价是静默挂死
|
||||||
|
// (与上面那个「把权限邮件发给 Agent 自己」是同一个后果,不同成因)。
|
||||||
|
// 详见 lib/relay-key.js 的 isDuplicateRelay。
|
||||||
|
if (isDuplicateRelay(accepted)) {
|
||||||
|
console.error(
|
||||||
|
`[dsh-mail-bridge] 权限询问被判为重复 ${relayKey},本次没有产生新请求`
|
||||||
|
);
|
||||||
|
throw Object.assign(new Error('duplicate_relay'), { duplicateRelay: true, relayKey });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
} catch (e: any) {
|
||||||
|
// 幂等命中(键重复)与 409(无人可问)都是「永远不会有人来决策」,
|
||||||
|
// 必须当场表态;两者的原因文案不同,但落点一致:不能 `return next()`。
|
||||||
|
if (e?.duplicateRelay) {
|
||||||
|
console.error(
|
||||||
|
`[dsh-mail-bridge] 权限询问被判为重复 ${relayKey},本次没有产生新请求`
|
||||||
|
);
|
||||||
|
// 原因走 noteDenial:DSH 把 approval 的 'rejected' 翻译成 dsh-tools 里
|
||||||
|
// 写死的一句「the user rejected tool X」,而这里**没有任何用户拒绝过它**。
|
||||||
|
// 与上面 409 / 4xx 两条分支同一手法。
|
||||||
|
noteDenial(agentId, req.callId, [
|
||||||
|
`这个授权询问之前已经发过一次(key=${relayKey}),本次没有产生新的询问。`,
|
||||||
|
'可能原因:插件重启后重放同一轮,或上一次询问已经有人决定过但这个决策没有回到这里。',
|
||||||
|
'请改用不需要授权的方式完成,或在回信里说明需要人工执行哪一步。',
|
||||||
|
].join('\n'));
|
||||||
|
// 返回 DSH 的 ApprovalOutcome,而不是某个对象 —— 这里与 409 / 4xx
|
||||||
|
// 两条分支一致(写成对象能被 tsc 放过,因为返回类型是宽联合,
|
||||||
|
// 但 DSH 会把它归一化成 'unavailable',拒绝就变成了“不可用”)。
|
||||||
|
return 'rejected';
|
||||||
|
}
|
||||||
|
// 409 = 服务端已判定这条任务链上没有人类,永远不会有人来点头。
|
||||||
//
|
//
|
||||||
// 不能 `return next()`:下一个 answerer 是本地 UI,而邮件驱动的会话
|
// 不能 `return next()`:下一个 answerer 是本地 UI,而邮件驱动的会话
|
||||||
// 根本没有 UI,waterfall 跑到尾以后依旧无人应答 —— 这正是生产事故
|
// 根本没有 UI,waterfall 跑到尾以后依旧无人应答 —— 这正是生产事故
|
||||||
|
|||||||
199
plugins/dsh-mail-bridge/test/permission-forward-wiring.test.mjs
Normal file
199
plugins/dsh-mail-bridge/test/permission-forward-wiring.test.mjs
Normal file
@ -0,0 +1,199 @@
|
|||||||
|
/**
|
||||||
|
* 接线断言:「网关把重复 relay_key 判为幂等命中」时,各桥必须**当场拒绝**,
|
||||||
|
* 而不是把那句 `await 决策` 一直等下去。
|
||||||
|
*
|
||||||
|
* # 为什么需要一条这样的测试
|
||||||
|
*
|
||||||
|
* 判据本身(`isDuplicateRelay`)在 `lib/relay-key.js` 里有单测 —— 但那次缺口
|
||||||
|
* 不在判据,而在**接线**:只有 zcode 桥认这个回包,pi/opencode/dsh 把它当成功,
|
||||||
|
* 然后等一个永远不会来的 `permission_decision`,表现为静默挂死。
|
||||||
|
* 纯函数测试对这种缺口天生无能为力:函数是对的,只是没人调用它。
|
||||||
|
*
|
||||||
|
* # 为什么读源码而不是跑起来
|
||||||
|
*
|
||||||
|
* 三个桥的入口都**不是可导入的模块**:pi 的 worker 是子进程、opencode 把入口的
|
||||||
|
* 每个导出当插件工厂检查、dsh 的入口拉起整个 Cordis 插件。让它们可测需要把
|
||||||
|
* 这些路径重构成可注入的形状,那是更大的改动面 —— 而这里要钉住的只有一件事:
|
||||||
|
* 「那个判断还在、且落在权限转发这条路上」。
|
||||||
|
*
|
||||||
|
* 与 `narrow-layout.test.mjs` 同一取舍:**验形态,不验行为**。
|
||||||
|
* 代价是它对重构敏感(改动这一段的写法时这里会红),这正是它该做的提醒。
|
||||||
|
*
|
||||||
|
* # 这条测试自己也有判据自检
|
||||||
|
*
|
||||||
|
* 一个「永远为真」的接线断言比没有更糟:它会让下一个人以为这里被覆盖着。
|
||||||
|
* 所以下面先证明「拿一段没有该判断的源码喂给它,它会红」。
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { test } from 'node:test';
|
||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import { readFileSync, existsSync } from 'node:fs';
|
||||||
|
import { dirname, join } from 'node:path';
|
||||||
|
import { fileURLToPath } from 'node:url';
|
||||||
|
|
||||||
|
const HERE = dirname(fileURLToPath(import.meta.url));
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 向上找到「装着各桥的那个目录」。
|
||||||
|
*
|
||||||
|
* 不写死 `../..`:这个文件会被复制到每个桥的 test/ 下,也可能被从别的 cwd 跑。
|
||||||
|
* 找不到时**必须判红**,不能静默返回空列表 —— 那会让下面每条断言都不执行,
|
||||||
|
* 而结果看起来是「全绿」(这条自检第一次跑就是这么逮住我自己的:过滤后 0 个桥)。
|
||||||
|
*/
|
||||||
|
function findPluginsDir(start) {
|
||||||
|
let dir = start;
|
||||||
|
for (let i = 0; i < 6; i++) {
|
||||||
|
if (existsSync(join(dir, 'pi-mail-bridge')) && existsSync(join(dir, 'opencode-mail-bridge'))) return dir;
|
||||||
|
const up = dirname(dir);
|
||||||
|
if (up === dir) break;
|
||||||
|
dir = up;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const PLUGINS_DIR = findPluginsDir(HERE);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 各桥的入口文件与它自己的「拒绝」写法。
|
||||||
|
*
|
||||||
|
* 三家的返回形状**各不相同**(pi 是 `{block:true, reason}`、opencode 是
|
||||||
|
* `output.status = "deny"`、dsh 是返回 DSH 的 ApprovalOutcome 字符串 `'rejected'`),
|
||||||
|
* 所以这里逐个列出来 —— 我第一版给 dsh 写成了 opencode 的形状,
|
||||||
|
* 而 `tsc` **没报错**(返回类型是宽联合),只有对着邻居读才发现。
|
||||||
|
*/
|
||||||
|
const BRIDGES = [
|
||||||
|
{
|
||||||
|
name: 'pi-mail-bridge',
|
||||||
|
source: 'src/worker.mjs',
|
||||||
|
// pi 在同一个分支里既判又拒
|
||||||
|
branch: /if\s*\(\s*isDuplicateRelay\(/,
|
||||||
|
denyShape: /block:\s*true/,
|
||||||
|
denyShapeDesc: 'block: true'
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'opencode-mail-bridge',
|
||||||
|
source: 'index.js',
|
||||||
|
branch: /if\s*\(\s*isDuplicateRelay\(/,
|
||||||
|
denyShape: /output\.status\s*=\s*"deny"/,
|
||||||
|
denyShapeDesc: 'output.status = "deny"'
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'dsh-mail-bridge',
|
||||||
|
source: 'src/index.ts',
|
||||||
|
// dsh 是**两段式**:.then 里把重复转成异常抛出去,catch 的 duplicateRelay
|
||||||
|
// 分支里才写拒绝。所以「分支」要取 catch 那一段(第一版取到了 .then 那段,
|
||||||
|
// 于是永远找不到 return 'rejected' —— 是判据错了,不是代码错了)。
|
||||||
|
branch: /if\s*\(\s*e\?\.duplicateRelay\s*\)/,
|
||||||
|
denyShape: /return\s+'rejected'/,
|
||||||
|
denyShapeDesc: "return 'rejected'",
|
||||||
|
// 同时要求它确实认得这个回包(.then 那段)
|
||||||
|
alsoNeeds: /isDuplicateRelay\(/
|
||||||
|
}
|
||||||
|
].filter(b => PLUGINS_DIR && existsSync(join(PLUGINS_DIR, b.name)));
|
||||||
|
|
||||||
|
/** 取出「重复回包 → 拒绝」那个分支的源码片段(从 if 到下一个同级收尾)。 */
|
||||||
|
export function duplicateBranchOf(source, branch) {
|
||||||
|
const m = source.match(branch || /if\s*\(\s*isDuplicateRelay\(/);
|
||||||
|
if (!m) return null;
|
||||||
|
const start = m.index;
|
||||||
|
let depth = 0;
|
||||||
|
let i = source.indexOf('{', start);
|
||||||
|
if (i < 0) return null;
|
||||||
|
for (let j = i; j < source.length; j++) {
|
||||||
|
if (source[j] === '{') depth++;
|
||||||
|
else if (source[j] === '}') {
|
||||||
|
depth--;
|
||||||
|
if (depth === 0) return source.slice(start, j + 1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 权限转发必须**先**判重复:判据要出现在等决策之前。 */
|
||||||
|
export function handlerChecksDuplicateFirst(source, denyShape, branchPattern) {
|
||||||
|
const branch = duplicateBranchOf(source, branchPattern);
|
||||||
|
if (!branch) return { ok: false, why: '源码里找不到处理重复回包的分支' };
|
||||||
|
if (!denyShape.test(branch)) {
|
||||||
|
return { ok: false, why: `重复分支里没有出现本桥的拒绝形状(期望 ${denyShape})` };
|
||||||
|
}
|
||||||
|
return { ok: true, why: '' };
|
||||||
|
}
|
||||||
|
|
||||||
|
test('★ 判据自检:拿没有该判断的源码喂进来必须判红', () => {
|
||||||
|
const PI = /if\s*\(\s*isDuplicateRelay\(/;
|
||||||
|
// ① 找不到分支 → 红
|
||||||
|
assert.equal(handlerChecksDuplicateFirst('const x = 1;', /block:\s*true/, PI).ok, false);
|
||||||
|
// ② 有分支但没有拒绝形状 → 红
|
||||||
|
assert.equal(
|
||||||
|
handlerChecksDuplicateFirst('if (isDuplicateRelay(accepted)) {\n console.error("重复");\n}', /block:\s*true/, PI).ok,
|
||||||
|
false
|
||||||
|
);
|
||||||
|
// 反向对照:形状写对时判绿(否则上面两条可能只是因为断言恒假)
|
||||||
|
assert.equal(
|
||||||
|
handlerChecksDuplicateFirst(
|
||||||
|
'if (isDuplicateRelay(accepted)) {\n return { block: true, reason: "x" };\n}',
|
||||||
|
/block:\s*true/,
|
||||||
|
PI
|
||||||
|
).ok,
|
||||||
|
true
|
||||||
|
);
|
||||||
|
// dsh 那种两段式形态:branch 正则必须能取到 catch 那一段
|
||||||
|
const DSH = /if\s*\(\s*e\?\.duplicateRelay\s*\)/;
|
||||||
|
assert.equal(
|
||||||
|
handlerChecksDuplicateFirst(
|
||||||
|
"if (e?.duplicateRelay) {\n noteDenial(a, b, 'x');\n return 'rejected';\n}",
|
||||||
|
/return\s+'rejected'/,
|
||||||
|
DSH
|
||||||
|
).ok,
|
||||||
|
true
|
||||||
|
);
|
||||||
|
// 同一段源码,用错 branch 正则(取到 .then 那段)应当判红 —— 这正是第一版
|
||||||
|
assert.equal(
|
||||||
|
handlerChecksDuplicateFirst(
|
||||||
|
"if (isDuplicateRelay(accepted)) {\n throw new Error('dup');\n}",
|
||||||
|
/return\s+'rejected'/,
|
||||||
|
DSH
|
||||||
|
).ok,
|
||||||
|
false
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('★ 判据自检:源码位置读取本身是真的(不是空跑)', () => {
|
||||||
|
// 若过滤逻辑把所有桥都滤掉了,下面的循环会一条都不跑而「全绿」——
|
||||||
|
// 这条自检第一次跑就是这么逮住我自己的(路径写错 → 0 个桥)。
|
||||||
|
assert.ok(PLUGINS_DIR, `找不到装着各桥的目录(从 ${HERE} 向上找了 6 层)`);
|
||||||
|
assert.ok(BRIDGES.length >= 3, `应当至少覆盖三个桥,实际 ${BRIDGES.length}`);
|
||||||
|
});
|
||||||
|
|
||||||
|
for (const b of BRIDGES) {
|
||||||
|
test(`★ ${b.name}:权限转发遇到 duplicate_relay 当场拒绝(而不是等一个不会来的决策)`, () => {
|
||||||
|
const file = join(PLUGINS_DIR, b.name, b.source);
|
||||||
|
assert.ok(existsSync(file), `找不到入口:${file}`);
|
||||||
|
const src = readFileSync(file, 'utf8');
|
||||||
|
|
||||||
|
// ① 必须认得这个回包(导入并在权限路径上用)
|
||||||
|
assert.match(
|
||||||
|
src,
|
||||||
|
/isDuplicateRelay/,
|
||||||
|
`${b.name} 没有认 duplicate_relay —— 网关对重复键回 HTTP 200 并提前返回,` +
|
||||||
|
'不认它就会一直等 permission_decision,表现为静默挂死'
|
||||||
|
);
|
||||||
|
|
||||||
|
// ② 该判断必须落在权限转发这条路上,并且给出本桥形状的拒绝
|
||||||
|
const r = handlerChecksDuplicateFirst(src, b.denyShape, b.branch);
|
||||||
|
assert.ok(r.ok, `${b.name}:${r.why}(期望 ${b.denyShapeDesc})`);
|
||||||
|
|
||||||
|
// ③ 两段式桥(dsh)还要认得这个回包
|
||||||
|
if (b.alsoNeeds) {
|
||||||
|
assert.match(src, b.alsoNeeds, `${b.name}:没有认 duplicate_relay 回包`);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ④ 顺序:判据必须在**发出请求之后**。
|
||||||
|
// 第一版写成「在文件里最早的 await 之前」,量到的是别处的等待,
|
||||||
|
// 于是三个桥全红 —— 判据量错了对象,不是代码错了。
|
||||||
|
const postAt = src.indexOf('/permission/request');
|
||||||
|
const dupAt = src.search(b.branch);
|
||||||
|
assert.ok(postAt > 0, `${b.name}:找不到权限上报调用`);
|
||||||
|
assert.ok(dupAt > postAt, `${b.name}:重复判据出现在上报之前(${dupAt} < ${postAt})`);
|
||||||
|
});
|
||||||
|
}
|
||||||
@ -21,6 +21,8 @@ import {
|
|||||||
truncateToBytes,
|
truncateToBytes,
|
||||||
clampRelayKey,
|
clampRelayKey,
|
||||||
isPermanentFailure,
|
isPermanentFailure,
|
||||||
|
isDuplicateRelay,
|
||||||
|
DUPLICATE_RELAY_STATUS,
|
||||||
} from '../lib/relay-key.js';
|
} from '../lib/relay-key.js';
|
||||||
|
|
||||||
// ─── byteLength ───
|
// ─── byteLength ───
|
||||||
@ -192,3 +194,42 @@ test('2xx / 3xx 不算永久失败(本不该走到这里,但不能误判成
|
|||||||
assert.equal(isPermanentFailure({ status: 200 }), false);
|
assert.equal(isPermanentFailure({ status: 200 }), false);
|
||||||
assert.equal(isPermanentFailure({ status: 302 }), false);
|
assert.equal(isPermanentFailure({ status: 302 }), false);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// ─── isDuplicateRelay ─────────────────────────────────────────────────────
|
||||||
|
//
|
||||||
|
// 这一组来自一个**静默挂死**:网关对重复的 relay_key 返回 HTTP 200 +
|
||||||
|
// `{status:"duplicate_relay"}` 并提前返回(不建请求、不发邮件、永远不会有人决策),
|
||||||
|
// 而 pi 的 worker 在 post 之后无条件等着 `permission_decision` 事件 ——
|
||||||
|
// 长得像成功,实际永远等不到。所以「发成功了」与「什么都没发生」必须分得开。
|
||||||
|
|
||||||
|
test('★ 认得出幂等命中(权限询问与代发邮件两个出口都是这个回包)', () => {
|
||||||
|
assert.equal(
|
||||||
|
isDuplicateRelay({ status: DUPLICATE_RELAY_STATUS, relay_key: 'k', detail: '该权限询问已转发过,本次调用未产生新邮件' }),
|
||||||
|
true
|
||||||
|
);
|
||||||
|
// 邮件出口的措辞不同,status 相同 —— 判定只看 status,不看 detail
|
||||||
|
assert.equal(
|
||||||
|
isDuplicateRelay({ status: DUPLICATE_RELAY_STATUS, relay: 'summary', detail: '该上游消息已转发过,本次调用未产生新邮件' }),
|
||||||
|
true
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('★ 反向对照:正常的 200 回包不能被当成幂等命中', () => {
|
||||||
|
// 误判的代价是反的:把正常请求当重复 ⇒ 明明发出去了却当场拒绝。
|
||||||
|
for (const res of [{}, { status: 'ok' }, { status: 'pending' }, { status: 'decided' }, { status: '' }]) {
|
||||||
|
assert.equal(isDuplicateRelay(res), false, JSON.stringify(res));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test('★ 非对象输入不炸也不误判', () => {
|
||||||
|
for (const v of [null, undefined, '', 'duplicate_relay', 0, false, [], ['duplicate_relay']]) {
|
||||||
|
assert.equal(isDuplicateRelay(v), false, JSON.stringify(v));
|
||||||
|
}
|
||||||
|
// 数组即使带 status 字段也不算(防止把响应列表当成单个响应)
|
||||||
|
assert.equal(isDuplicateRelay([{ status: DUPLICATE_RELAY_STATUS }]), false);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('status 常量与服务端字面量一致(改一处会两边不认,这条钉住)', () => {
|
||||||
|
// gateway 侧:server/internal/handler/{permission,mail}.go 都写字面量 "duplicate_relay"
|
||||||
|
assert.equal(DUPLICATE_RELAY_STATUS, 'duplicate_relay');
|
||||||
|
});
|
||||||
|
|||||||
@ -36,7 +36,7 @@ import {
|
|||||||
} from "./lib/relay-dedup.js";
|
} from "./lib/relay-dedup.js";
|
||||||
import { adoptedSessionID, adoptMissingMessage } from "./lib/adopt.js";
|
import { adoptedSessionID, adoptMissingMessage } from "./lib/adopt.js";
|
||||||
import { autoRelayDecision, replyInstruction, inboundHeadline } from "./lib/relay-policy.js";
|
import { autoRelayDecision, replyInstruction, inboundHeadline } from "./lib/relay-policy.js";
|
||||||
import { clampRelayKey, isPermanentFailure } from "./lib/relay-key.js";
|
import { clampRelayKey, isPermanentFailure, isDuplicateRelay } from "./lib/relay-key.js";
|
||||||
import { BoundedMap, BoundedSet, MAX_TRACKED_MAILS, MAX_TRACKED_SESSIONS } from "./lib/bounded.js";
|
import { BoundedMap, BoundedSet, MAX_TRACKED_MAILS, MAX_TRACKED_SESSIONS } from "./lib/bounded.js";
|
||||||
import { appendRenameProposal, renameProposalNote } from "./lib/rename-proposal.js";
|
import { appendRenameProposal, renameProposalNote } from "./lib/rename-proposal.js";
|
||||||
import { createSSEClient } from "./lib/sse-client.js";
|
import { createSSEClient } from "./lib/sse-client.js";
|
||||||
@ -1244,7 +1244,11 @@ export default async function mailBridge(input) {
|
|||||||
try {
|
try {
|
||||||
// opencode 的权限语义是三态,映射成人类看得懂的选项:
|
// opencode 的权限语义是三态,映射成人类看得懂的选项:
|
||||||
// 「同意」= once(仅这次),「一直同意」= always(后续同类不再问),「拒绝」= reject
|
// 「同意」= once(仅这次),「一直同意」= always(后续同类不再问),「拒绝」= reject
|
||||||
await relayPermission({
|
// ★ 幂等命中:网关回 200 `{status:"duplicate_relay"}` 并**提前返回** ——
|
||||||
|
// 没有产生新的询问,也永远不会有人来决策,而这里只等
|
||||||
|
// `permission_decision` 事件。不认它的代价是静默挂死。
|
||||||
|
// 详见 lib/relay-key.js 的 isDuplicateRelay。
|
||||||
|
const accepted = await relayPermission({
|
||||||
question: input.title || `请求执行 ${input.type}`,
|
question: input.title || `请求执行 ${input.type}`,
|
||||||
options: ["同意", "一直同意", "拒绝"],
|
options: ["同意", "一直同意", "拒绝"],
|
||||||
context: [
|
context: [
|
||||||
@ -1256,6 +1260,17 @@ export default async function mailBridge(input) {
|
|||||||
].filter(Boolean).join("\n"),
|
].filter(Boolean).join("\n"),
|
||||||
relayKey: clampRelayKey(input.id),
|
relayKey: clampRelayKey(input.id),
|
||||||
});
|
});
|
||||||
|
if (isDuplicateRelay(accepted)) {
|
||||||
|
console.error(`[mail-bridge] 权限询问被判为重复 ${input.id},本次没有产生新请求`);
|
||||||
|
pendingPermissions.delete(input.id);
|
||||||
|
output.status = "deny";
|
||||||
|
output.reason = [
|
||||||
|
`这个授权询问之前已经发过一次(key=${clampRelayKey(input.id)}),本次没有产生新的询问。`,
|
||||||
|
"可能原因:插件重启后重放同一轮,或上一次询问已经有人决定过但这个决策没有回到这里。",
|
||||||
|
"请改用不需要授权的方式完成,或在回信里说明需要人工执行哪一步。",
|
||||||
|
].join("\n");
|
||||||
|
return;
|
||||||
|
}
|
||||||
console.error(`[mail-bridge] 权限询问已转邮件 ${input.id}(${input.type})`);
|
console.error(`[mail-bridge] 权限询问已转邮件 ${input.id}(${input.type})`);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
pendingPermissions.delete(input.id);
|
pendingPermissions.delete(input.id);
|
||||||
|
|||||||
@ -125,3 +125,41 @@ export function isPermanentFailure(err) {
|
|||||||
if (status === 408 || status === 429) return false; // 超时 / 限流 → 暂时
|
if (status === 408 || status === 429) return false; // 超时 / 限流 → 暂时
|
||||||
return status >= 400 && status < 500;
|
return status >= 400 && status < 500;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 网关把重复的 relay_key 判为**幂等命中**时的回包标识。
|
||||||
|
*
|
||||||
|
* 两个出口都会这么答(权限询问与代发邮件),且都是 **HTTP 200 且提前返回**:
|
||||||
|
* 不建请求、不发邮件,**也永远不会有人来决策**。
|
||||||
|
*/
|
||||||
|
export const DUPLICATE_RELAY_STATUS = 'duplicate_relay';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 这个回包是不是「重复键,什么都没发生」。
|
||||||
|
*
|
||||||
|
* ## 为什么必须单独认它
|
||||||
|
*
|
||||||
|
* 它长得像成功(200),所以「发完就等决策」的实现会一直等下去。实测过的形态:
|
||||||
|
* pi 的 worker 在 `post('/permission/request')` 之后无条件
|
||||||
|
* `await new Promise(resolve => pending.set(relayKey, resolve))`,而那个 resolve
|
||||||
|
* 只由 `permission_decision` 事件触发 —— 重复的键永远不会带来决策,
|
||||||
|
* 于是那封邮件**静默挂死**(模型干等,人以为在跑)。
|
||||||
|
*
|
||||||
|
* 什么时候会重复(都是**正常**的重试,不是故障):
|
||||||
|
*
|
||||||
|
* - 插件重启后重放同一轮(键是确定性的,这正是它的设计目的)
|
||||||
|
* - SDK / 上游重放同一个 tool call
|
||||||
|
* - 上一次询问已经被人决定过,而这一侧没收到那个决策(重启、断线)
|
||||||
|
*
|
||||||
|
* 对「发信」那一侧,重复就该当成功(幂等,这正是网关返回 200 的意思);
|
||||||
|
* 但对「等一个决定」那一侧,它与故障的后果完全一样:永远等不到。
|
||||||
|
* 所以两边的处置必须分开写,而不是共用一个「发成功了」的判定。
|
||||||
|
*
|
||||||
|
* @param {unknown} res 网关的响应体(不是 HTTP 响应对象)
|
||||||
|
* @returns {boolean}
|
||||||
|
*/
|
||||||
|
export function isDuplicateRelay(res) {
|
||||||
|
return Boolean(
|
||||||
|
res && typeof res === 'object' && !Array.isArray(res) && res.status === DUPLICATE_RELAY_STATUS
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|||||||
@ -0,0 +1,199 @@
|
|||||||
|
/**
|
||||||
|
* 接线断言:「网关把重复 relay_key 判为幂等命中」时,各桥必须**当场拒绝**,
|
||||||
|
* 而不是把那句 `await 决策` 一直等下去。
|
||||||
|
*
|
||||||
|
* # 为什么需要一条这样的测试
|
||||||
|
*
|
||||||
|
* 判据本身(`isDuplicateRelay`)在 `lib/relay-key.js` 里有单测 —— 但那次缺口
|
||||||
|
* 不在判据,而在**接线**:只有 zcode 桥认这个回包,pi/opencode/dsh 把它当成功,
|
||||||
|
* 然后等一个永远不会来的 `permission_decision`,表现为静默挂死。
|
||||||
|
* 纯函数测试对这种缺口天生无能为力:函数是对的,只是没人调用它。
|
||||||
|
*
|
||||||
|
* # 为什么读源码而不是跑起来
|
||||||
|
*
|
||||||
|
* 三个桥的入口都**不是可导入的模块**:pi 的 worker 是子进程、opencode 把入口的
|
||||||
|
* 每个导出当插件工厂检查、dsh 的入口拉起整个 Cordis 插件。让它们可测需要把
|
||||||
|
* 这些路径重构成可注入的形状,那是更大的改动面 —— 而这里要钉住的只有一件事:
|
||||||
|
* 「那个判断还在、且落在权限转发这条路上」。
|
||||||
|
*
|
||||||
|
* 与 `narrow-layout.test.mjs` 同一取舍:**验形态,不验行为**。
|
||||||
|
* 代价是它对重构敏感(改动这一段的写法时这里会红),这正是它该做的提醒。
|
||||||
|
*
|
||||||
|
* # 这条测试自己也有判据自检
|
||||||
|
*
|
||||||
|
* 一个「永远为真」的接线断言比没有更糟:它会让下一个人以为这里被覆盖着。
|
||||||
|
* 所以下面先证明「拿一段没有该判断的源码喂给它,它会红」。
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { test } from 'node:test';
|
||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import { readFileSync, existsSync } from 'node:fs';
|
||||||
|
import { dirname, join } from 'node:path';
|
||||||
|
import { fileURLToPath } from 'node:url';
|
||||||
|
|
||||||
|
const HERE = dirname(fileURLToPath(import.meta.url));
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 向上找到「装着各桥的那个目录」。
|
||||||
|
*
|
||||||
|
* 不写死 `../..`:这个文件会被复制到每个桥的 test/ 下,也可能被从别的 cwd 跑。
|
||||||
|
* 找不到时**必须判红**,不能静默返回空列表 —— 那会让下面每条断言都不执行,
|
||||||
|
* 而结果看起来是「全绿」(这条自检第一次跑就是这么逮住我自己的:过滤后 0 个桥)。
|
||||||
|
*/
|
||||||
|
function findPluginsDir(start) {
|
||||||
|
let dir = start;
|
||||||
|
for (let i = 0; i < 6; i++) {
|
||||||
|
if (existsSync(join(dir, 'pi-mail-bridge')) && existsSync(join(dir, 'opencode-mail-bridge'))) return dir;
|
||||||
|
const up = dirname(dir);
|
||||||
|
if (up === dir) break;
|
||||||
|
dir = up;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const PLUGINS_DIR = findPluginsDir(HERE);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 各桥的入口文件与它自己的「拒绝」写法。
|
||||||
|
*
|
||||||
|
* 三家的返回形状**各不相同**(pi 是 `{block:true, reason}`、opencode 是
|
||||||
|
* `output.status = "deny"`、dsh 是返回 DSH 的 ApprovalOutcome 字符串 `'rejected'`),
|
||||||
|
* 所以这里逐个列出来 —— 我第一版给 dsh 写成了 opencode 的形状,
|
||||||
|
* 而 `tsc` **没报错**(返回类型是宽联合),只有对着邻居读才发现。
|
||||||
|
*/
|
||||||
|
const BRIDGES = [
|
||||||
|
{
|
||||||
|
name: 'pi-mail-bridge',
|
||||||
|
source: 'src/worker.mjs',
|
||||||
|
// pi 在同一个分支里既判又拒
|
||||||
|
branch: /if\s*\(\s*isDuplicateRelay\(/,
|
||||||
|
denyShape: /block:\s*true/,
|
||||||
|
denyShapeDesc: 'block: true'
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'opencode-mail-bridge',
|
||||||
|
source: 'index.js',
|
||||||
|
branch: /if\s*\(\s*isDuplicateRelay\(/,
|
||||||
|
denyShape: /output\.status\s*=\s*"deny"/,
|
||||||
|
denyShapeDesc: 'output.status = "deny"'
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'dsh-mail-bridge',
|
||||||
|
source: 'src/index.ts',
|
||||||
|
// dsh 是**两段式**:.then 里把重复转成异常抛出去,catch 的 duplicateRelay
|
||||||
|
// 分支里才写拒绝。所以「分支」要取 catch 那一段(第一版取到了 .then 那段,
|
||||||
|
// 于是永远找不到 return 'rejected' —— 是判据错了,不是代码错了)。
|
||||||
|
branch: /if\s*\(\s*e\?\.duplicateRelay\s*\)/,
|
||||||
|
denyShape: /return\s+'rejected'/,
|
||||||
|
denyShapeDesc: "return 'rejected'",
|
||||||
|
// 同时要求它确实认得这个回包(.then 那段)
|
||||||
|
alsoNeeds: /isDuplicateRelay\(/
|
||||||
|
}
|
||||||
|
].filter(b => PLUGINS_DIR && existsSync(join(PLUGINS_DIR, b.name)));
|
||||||
|
|
||||||
|
/** 取出「重复回包 → 拒绝」那个分支的源码片段(从 if 到下一个同级收尾)。 */
|
||||||
|
export function duplicateBranchOf(source, branch) {
|
||||||
|
const m = source.match(branch || /if\s*\(\s*isDuplicateRelay\(/);
|
||||||
|
if (!m) return null;
|
||||||
|
const start = m.index;
|
||||||
|
let depth = 0;
|
||||||
|
let i = source.indexOf('{', start);
|
||||||
|
if (i < 0) return null;
|
||||||
|
for (let j = i; j < source.length; j++) {
|
||||||
|
if (source[j] === '{') depth++;
|
||||||
|
else if (source[j] === '}') {
|
||||||
|
depth--;
|
||||||
|
if (depth === 0) return source.slice(start, j + 1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 权限转发必须**先**判重复:判据要出现在等决策之前。 */
|
||||||
|
export function handlerChecksDuplicateFirst(source, denyShape, branchPattern) {
|
||||||
|
const branch = duplicateBranchOf(source, branchPattern);
|
||||||
|
if (!branch) return { ok: false, why: '源码里找不到处理重复回包的分支' };
|
||||||
|
if (!denyShape.test(branch)) {
|
||||||
|
return { ok: false, why: `重复分支里没有出现本桥的拒绝形状(期望 ${denyShape})` };
|
||||||
|
}
|
||||||
|
return { ok: true, why: '' };
|
||||||
|
}
|
||||||
|
|
||||||
|
test('★ 判据自检:拿没有该判断的源码喂进来必须判红', () => {
|
||||||
|
const PI = /if\s*\(\s*isDuplicateRelay\(/;
|
||||||
|
// ① 找不到分支 → 红
|
||||||
|
assert.equal(handlerChecksDuplicateFirst('const x = 1;', /block:\s*true/, PI).ok, false);
|
||||||
|
// ② 有分支但没有拒绝形状 → 红
|
||||||
|
assert.equal(
|
||||||
|
handlerChecksDuplicateFirst('if (isDuplicateRelay(accepted)) {\n console.error("重复");\n}', /block:\s*true/, PI).ok,
|
||||||
|
false
|
||||||
|
);
|
||||||
|
// 反向对照:形状写对时判绿(否则上面两条可能只是因为断言恒假)
|
||||||
|
assert.equal(
|
||||||
|
handlerChecksDuplicateFirst(
|
||||||
|
'if (isDuplicateRelay(accepted)) {\n return { block: true, reason: "x" };\n}',
|
||||||
|
/block:\s*true/,
|
||||||
|
PI
|
||||||
|
).ok,
|
||||||
|
true
|
||||||
|
);
|
||||||
|
// dsh 那种两段式形态:branch 正则必须能取到 catch 那一段
|
||||||
|
const DSH = /if\s*\(\s*e\?\.duplicateRelay\s*\)/;
|
||||||
|
assert.equal(
|
||||||
|
handlerChecksDuplicateFirst(
|
||||||
|
"if (e?.duplicateRelay) {\n noteDenial(a, b, 'x');\n return 'rejected';\n}",
|
||||||
|
/return\s+'rejected'/,
|
||||||
|
DSH
|
||||||
|
).ok,
|
||||||
|
true
|
||||||
|
);
|
||||||
|
// 同一段源码,用错 branch 正则(取到 .then 那段)应当判红 —— 这正是第一版
|
||||||
|
assert.equal(
|
||||||
|
handlerChecksDuplicateFirst(
|
||||||
|
"if (isDuplicateRelay(accepted)) {\n throw new Error('dup');\n}",
|
||||||
|
/return\s+'rejected'/,
|
||||||
|
DSH
|
||||||
|
).ok,
|
||||||
|
false
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('★ 判据自检:源码位置读取本身是真的(不是空跑)', () => {
|
||||||
|
// 若过滤逻辑把所有桥都滤掉了,下面的循环会一条都不跑而「全绿」——
|
||||||
|
// 这条自检第一次跑就是这么逮住我自己的(路径写错 → 0 个桥)。
|
||||||
|
assert.ok(PLUGINS_DIR, `找不到装着各桥的目录(从 ${HERE} 向上找了 6 层)`);
|
||||||
|
assert.ok(BRIDGES.length >= 3, `应当至少覆盖三个桥,实际 ${BRIDGES.length}`);
|
||||||
|
});
|
||||||
|
|
||||||
|
for (const b of BRIDGES) {
|
||||||
|
test(`★ ${b.name}:权限转发遇到 duplicate_relay 当场拒绝(而不是等一个不会来的决策)`, () => {
|
||||||
|
const file = join(PLUGINS_DIR, b.name, b.source);
|
||||||
|
assert.ok(existsSync(file), `找不到入口:${file}`);
|
||||||
|
const src = readFileSync(file, 'utf8');
|
||||||
|
|
||||||
|
// ① 必须认得这个回包(导入并在权限路径上用)
|
||||||
|
assert.match(
|
||||||
|
src,
|
||||||
|
/isDuplicateRelay/,
|
||||||
|
`${b.name} 没有认 duplicate_relay —— 网关对重复键回 HTTP 200 并提前返回,` +
|
||||||
|
'不认它就会一直等 permission_decision,表现为静默挂死'
|
||||||
|
);
|
||||||
|
|
||||||
|
// ② 该判断必须落在权限转发这条路上,并且给出本桥形状的拒绝
|
||||||
|
const r = handlerChecksDuplicateFirst(src, b.denyShape, b.branch);
|
||||||
|
assert.ok(r.ok, `${b.name}:${r.why}(期望 ${b.denyShapeDesc})`);
|
||||||
|
|
||||||
|
// ③ 两段式桥(dsh)还要认得这个回包
|
||||||
|
if (b.alsoNeeds) {
|
||||||
|
assert.match(src, b.alsoNeeds, `${b.name}:没有认 duplicate_relay 回包`);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ④ 顺序:判据必须在**发出请求之后**。
|
||||||
|
// 第一版写成「在文件里最早的 await 之前」,量到的是别处的等待,
|
||||||
|
// 于是三个桥全红 —— 判据量错了对象,不是代码错了。
|
||||||
|
const postAt = src.indexOf('/permission/request');
|
||||||
|
const dupAt = src.search(b.branch);
|
||||||
|
assert.ok(postAt > 0, `${b.name}:找不到权限上报调用`);
|
||||||
|
assert.ok(dupAt > postAt, `${b.name}:重复判据出现在上报之前(${dupAt} < ${postAt})`);
|
||||||
|
});
|
||||||
|
}
|
||||||
@ -21,6 +21,8 @@ import {
|
|||||||
truncateToBytes,
|
truncateToBytes,
|
||||||
clampRelayKey,
|
clampRelayKey,
|
||||||
isPermanentFailure,
|
isPermanentFailure,
|
||||||
|
isDuplicateRelay,
|
||||||
|
DUPLICATE_RELAY_STATUS,
|
||||||
} from '../lib/relay-key.js';
|
} from '../lib/relay-key.js';
|
||||||
|
|
||||||
// ─── byteLength ───
|
// ─── byteLength ───
|
||||||
@ -192,3 +194,42 @@ test('2xx / 3xx 不算永久失败(本不该走到这里,但不能误判成
|
|||||||
assert.equal(isPermanentFailure({ status: 200 }), false);
|
assert.equal(isPermanentFailure({ status: 200 }), false);
|
||||||
assert.equal(isPermanentFailure({ status: 302 }), false);
|
assert.equal(isPermanentFailure({ status: 302 }), false);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// ─── isDuplicateRelay ─────────────────────────────────────────────────────
|
||||||
|
//
|
||||||
|
// 这一组来自一个**静默挂死**:网关对重复的 relay_key 返回 HTTP 200 +
|
||||||
|
// `{status:"duplicate_relay"}` 并提前返回(不建请求、不发邮件、永远不会有人决策),
|
||||||
|
// 而 pi 的 worker 在 post 之后无条件等着 `permission_decision` 事件 ——
|
||||||
|
// 长得像成功,实际永远等不到。所以「发成功了」与「什么都没发生」必须分得开。
|
||||||
|
|
||||||
|
test('★ 认得出幂等命中(权限询问与代发邮件两个出口都是这个回包)', () => {
|
||||||
|
assert.equal(
|
||||||
|
isDuplicateRelay({ status: DUPLICATE_RELAY_STATUS, relay_key: 'k', detail: '该权限询问已转发过,本次调用未产生新邮件' }),
|
||||||
|
true
|
||||||
|
);
|
||||||
|
// 邮件出口的措辞不同,status 相同 —— 判定只看 status,不看 detail
|
||||||
|
assert.equal(
|
||||||
|
isDuplicateRelay({ status: DUPLICATE_RELAY_STATUS, relay: 'summary', detail: '该上游消息已转发过,本次调用未产生新邮件' }),
|
||||||
|
true
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('★ 反向对照:正常的 200 回包不能被当成幂等命中', () => {
|
||||||
|
// 误判的代价是反的:把正常请求当重复 ⇒ 明明发出去了却当场拒绝。
|
||||||
|
for (const res of [{}, { status: 'ok' }, { status: 'pending' }, { status: 'decided' }, { status: '' }]) {
|
||||||
|
assert.equal(isDuplicateRelay(res), false, JSON.stringify(res));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test('★ 非对象输入不炸也不误判', () => {
|
||||||
|
for (const v of [null, undefined, '', 'duplicate_relay', 0, false, [], ['duplicate_relay']]) {
|
||||||
|
assert.equal(isDuplicateRelay(v), false, JSON.stringify(v));
|
||||||
|
}
|
||||||
|
// 数组即使带 status 字段也不算(防止把响应列表当成单个响应)
|
||||||
|
assert.equal(isDuplicateRelay([{ status: DUPLICATE_RELAY_STATUS }]), false);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('status 常量与服务端字面量一致(改一处会两边不认,这条钉住)', () => {
|
||||||
|
// gateway 侧:server/internal/handler/{permission,mail}.go 都写字面量 "duplicate_relay"
|
||||||
|
assert.equal(DUPLICATE_RELAY_STATUS, 'duplicate_relay');
|
||||||
|
});
|
||||||
|
|||||||
@ -125,3 +125,41 @@ export function isPermanentFailure(err) {
|
|||||||
if (status === 408 || status === 429) return false; // 超时 / 限流 → 暂时
|
if (status === 408 || status === 429) return false; // 超时 / 限流 → 暂时
|
||||||
return status >= 400 && status < 500;
|
return status >= 400 && status < 500;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 网关把重复的 relay_key 判为**幂等命中**时的回包标识。
|
||||||
|
*
|
||||||
|
* 两个出口都会这么答(权限询问与代发邮件),且都是 **HTTP 200 且提前返回**:
|
||||||
|
* 不建请求、不发邮件,**也永远不会有人来决策**。
|
||||||
|
*/
|
||||||
|
export const DUPLICATE_RELAY_STATUS = 'duplicate_relay';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 这个回包是不是「重复键,什么都没发生」。
|
||||||
|
*
|
||||||
|
* ## 为什么必须单独认它
|
||||||
|
*
|
||||||
|
* 它长得像成功(200),所以「发完就等决策」的实现会一直等下去。实测过的形态:
|
||||||
|
* pi 的 worker 在 `post('/permission/request')` 之后无条件
|
||||||
|
* `await new Promise(resolve => pending.set(relayKey, resolve))`,而那个 resolve
|
||||||
|
* 只由 `permission_decision` 事件触发 —— 重复的键永远不会带来决策,
|
||||||
|
* 于是那封邮件**静默挂死**(模型干等,人以为在跑)。
|
||||||
|
*
|
||||||
|
* 什么时候会重复(都是**正常**的重试,不是故障):
|
||||||
|
*
|
||||||
|
* - 插件重启后重放同一轮(键是确定性的,这正是它的设计目的)
|
||||||
|
* - SDK / 上游重放同一个 tool call
|
||||||
|
* - 上一次询问已经被人决定过,而这一侧没收到那个决策(重启、断线)
|
||||||
|
*
|
||||||
|
* 对「发信」那一侧,重复就该当成功(幂等,这正是网关返回 200 的意思);
|
||||||
|
* 但对「等一个决定」那一侧,它与故障的后果完全一样:永远等不到。
|
||||||
|
* 所以两边的处置必须分开写,而不是共用一个「发成功了」的判定。
|
||||||
|
*
|
||||||
|
* @param {unknown} res 网关的响应体(不是 HTTP 响应对象)
|
||||||
|
* @returns {boolean}
|
||||||
|
*/
|
||||||
|
export function isDuplicateRelay(res) {
|
||||||
|
return Boolean(
|
||||||
|
res && typeof res === 'object' && !Array.isArray(res) && res.status === DUPLICATE_RELAY_STATUS
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|||||||
@ -199,3 +199,46 @@ export function relayKeyFor(piSessionId, leafId) {
|
|||||||
export function sessionDirLabel(cwd) {
|
export function sessionDirLabel(cwd) {
|
||||||
return `--${String(cwd ?? '').replace(/\//g, '-')}--`;
|
return `--${String(cwd ?? '').replace(/\//g, '-')}--`;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 续谈失败的回报正文。
|
||||||
|
*
|
||||||
|
* ## 为什么不直接复用共用库的 `renderFailureReport`
|
||||||
|
*
|
||||||
|
* 那句文案说「**划定范围内的模型全部调用失败**」并建议「调整可用模型范围」——
|
||||||
|
* 那是「新会话逐个试过所有模型」那条路的事实。而续谈这条路是**故意不降级**的:
|
||||||
|
* 换模型就要换会话,那会丢掉整条上下文,而上下文正是发件人指定这条会话的原因。
|
||||||
|
* 拿那段文案回过去等于告诉人去调一个在这里无效的旋钮 —— 他会去改配置,
|
||||||
|
* 然后发现依然失败。真正要做的是看上游错误原文。
|
||||||
|
*
|
||||||
|
* ## 为什么必须回这封信
|
||||||
|
*
|
||||||
|
* 实测缺口(2026-09-12,模型侧 402 余额不足):新会话失败会回「处理失败」,
|
||||||
|
* 而续谈这条路只写日志就 throw —— 发件人**什么都收不到**。
|
||||||
|
* 邮件驱动的会话没有本地界面可以看,没有这封信就等于
|
||||||
|
* 「信发出去了,然后再无音讯」。复现条件很普通:往一条**已存在**的会话
|
||||||
|
* 再发一封信,而模型侧报错。
|
||||||
|
*
|
||||||
|
* @param {string} subject 原邮件主题
|
||||||
|
* @param {string} error 上游错误原文
|
||||||
|
* @returns {string} Markdown 正文
|
||||||
|
*/
|
||||||
|
export function renderResumeFailure(subject, error) {
|
||||||
|
return [
|
||||||
|
`本次未能处理「${subject || '(无主题)'}」:这条会话的**续谈**失败了。`,
|
||||||
|
'',
|
||||||
|
'上游错误原文:',
|
||||||
|
'',
|
||||||
|
'```',
|
||||||
|
String(error ?? '未知错误'),
|
||||||
|
'```',
|
||||||
|
'',
|
||||||
|
'说明:续谈**不会**换用其它模型 —— 续谈必须用原会话,换模型就等于换会话,',
|
||||||
|
'会丢掉整条上下文(而上下文正是你指定这条会话的原因)。',
|
||||||
|
'所以这里只有一个上游错误,不是「范围内的模型都试过了」。',
|
||||||
|
'',
|
||||||
|
'可以这样做:',
|
||||||
|
'- 先看上面的错误原文(常见的:余额不足、密钥失效、上游限流)',
|
||||||
|
'- 若确实要换模型,请**新建**一条会话(新会话会按范围逐个尝试)',
|
||||||
|
].join('\n');
|
||||||
|
}
|
||||||
|
|||||||
@ -46,7 +46,7 @@ import { ModelRuntime } from '@earendil-works/pi-coding-agent';
|
|||||||
import { GatewayClient } from './gateway.mjs';
|
import { GatewayClient } from './gateway.mjs';
|
||||||
import { createMailTools } from './tools.mjs';
|
import { createMailTools } from './tools.mjs';
|
||||||
import { openSession, runTurn } from './session-pool.mjs';
|
import { openSession, runTurn } from './session-pool.mjs';
|
||||||
import { buildMailPrompt, lastAssistantText, replySubject, relayKeyFor, describeError } from './turn.mjs';
|
import { buildMailPrompt, lastAssistantText, replySubject, relayKeyFor, describeError, renderResumeFailure } from './turn.mjs';
|
||||||
import { planNamingSync, planWriteBack } from './naming.mjs';
|
import { planNamingSync, planWriteBack } from './naming.mjs';
|
||||||
import { resolveWorkspaceCwd, ensureCwd } from '../lib/workspace.js';
|
import { resolveWorkspaceCwd, ensureCwd } from '../lib/workspace.js';
|
||||||
import { modelAttemptOrder, renderFailureReport } from '../lib/model-scope.js';
|
import { modelAttemptOrder, renderFailureReport } from '../lib/model-scope.js';
|
||||||
@ -55,7 +55,7 @@ import { autoRelayDecision } from '../lib/relay-policy.js';
|
|||||||
import { adoptedSessionID, adoptMissingMessage } from '../lib/adopt.js';
|
import { adoptedSessionID, adoptMissingMessage } from '../lib/adopt.js';
|
||||||
import { isApproval, isAlwaysDecision } from '../lib/permission-grants.js';
|
import { isApproval, isAlwaysDecision } from '../lib/permission-grants.js';
|
||||||
import { normalizeMode, MODE_FULL, MODE_PLAN } from '../lib/permission-mode.js';
|
import { normalizeMode, MODE_FULL, MODE_PLAN } from '../lib/permission-mode.js';
|
||||||
import { clampRelayKey, isPermanentFailure } from '../lib/relay-key.js';
|
import { clampRelayKey, isPermanentFailure, isDuplicateRelay } from '../lib/relay-key.js';
|
||||||
|
|
||||||
// ─── 与主进程的通道 ───
|
// ─── 与主进程的通道 ───
|
||||||
|
|
||||||
@ -145,7 +145,7 @@ function permissionExtension() {
|
|||||||
try {
|
try {
|
||||||
// 不传 `to`:决策人由服务端按 会话 owner → 线索里最近的人类 → 409
|
// 不传 `to`:决策人由服务端按 会话 owner → 线索里最近的人类 → 409
|
||||||
// 解析。插件只有本地上下文,猜不出「这条 Agent 链最初是谁派的活」。
|
// 解析。插件只有本地上下文,猜不出「这条 Agent 链最初是谁派的活」。
|
||||||
await client.post('/permission/request', {
|
const accepted = await client.post('/permission/request', {
|
||||||
question: `是否允许执行 ${event.toolName}?`,
|
question: `是否允许执行 ${event.toolName}?`,
|
||||||
options: ['同意', '一直同意', '拒绝'],
|
options: ['同意', '一直同意', '拒绝'],
|
||||||
context: [
|
context: [
|
||||||
@ -156,6 +156,29 @@ function permissionExtension() {
|
|||||||
session_id: job.data?.session_id || '',
|
session_id: job.data?.session_id || '',
|
||||||
relay_key: relayKey,
|
relay_key: relayKey,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// ★ 幂等命中:网关回 200 `{status:"duplicate_relay"}` 并**提前返回** ——
|
||||||
|
// 没有产生新的询问,也永远不会有人来决策。而下面的 `await` 只由
|
||||||
|
// `permission_decision` 事件唤醒,重复的键永远等不到它。
|
||||||
|
//
|
||||||
|
// 不认这个回包的代价是**静默挂死**:模型干等、人以为在跑,
|
||||||
|
// 直到回合超时才以「处理失败」出现(而不是以「没人可问」出现,
|
||||||
|
// 于是排查方向从一开始就是错的)。
|
||||||
|
//
|
||||||
|
// 为什么会出现重复:键是确定性的(会话 + toolCallId),所以插件重启
|
||||||
|
// 后重放同一轮、SDK 重放同一个 tool call、以及上一次询问已被人决定过
|
||||||
|
// 而这一侧没收到那个决策(重启/断线)都会命中它。这些都是正常重试。
|
||||||
|
if (isDuplicateRelay(accepted)) {
|
||||||
|
log(`权限询问被判定为重复(key=${relayKey}),本次没有产生新请求`);
|
||||||
|
return {
|
||||||
|
block: true,
|
||||||
|
reason: [
|
||||||
|
`这个授权询问之前已经发过一次(key=${relayKey}),本次没有产生新的询问。`,
|
||||||
|
'可能原因:插件重启后重放同一轮,或上一次询问已经有人决定过但这个决策没有回到这里。',
|
||||||
|
'请改用不需要授权的方式完成,或在回信里说明需要人工执行哪一步(也可以请对方重新发一次任务)。',
|
||||||
|
].join('\n'),
|
||||||
|
};
|
||||||
|
}
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
// 409 = 服务端判定这条任务链上没有人类,永远不会有人来点头。
|
// 409 = 服务端判定这条任务链上没有人类,永远不会有人来点头。
|
||||||
// 当场 block 并把服务端建议原文当 reason:模型从工具报错里看到
|
// 当场 block 并把服务端建议原文当 reason:模型从工具报错里看到
|
||||||
@ -483,15 +506,42 @@ async function run() {
|
|||||||
// 一轮跑几分钟很正常,60 秒返回会让转发落在一个还没说完的结论上。
|
// 一轮跑几分钟很正常,60 秒返回会让转发落在一个还没说完的结论上。
|
||||||
const turnTimeout = job.config.turnTimeoutMs;
|
const turnTimeout = job.config.turnTimeoutMs;
|
||||||
|
|
||||||
if (reused) {
|
if (reused) {
|
||||||
// 续谈不做模型降级:换模型要换会话,会丢掉整条上下文 —— 而上下文正是
|
// 续谈不做模型降级:换模型要换会话,会丢掉整条上下文 —— 而上下文正是
|
||||||
// 发件人指定这条会话的原因。但失败要可见。
|
// 发件人指定这条会话的原因。但失败要可见。
|
||||||
const outcome = await runTurn(session, prompt, turnTimeout);
|
const outcome = await runTurn(session, prompt, turnTimeout);
|
||||||
log(`续谈 ${piSessionId}(mail ${data.mail_id}${outcome.queued ? ',已排队' : ''})`);
|
log(`续谈 ${piSessionId}(mail ${data.mail_id}${outcome.queued ? ',已排队' : ''})`);
|
||||||
if (!outcome.ok) throw new Error(`续谈失败: ${outcome.error}`);
|
if (!outcome.ok) {
|
||||||
await relaySummary(session, sessionManager, adopted);
|
// ★ 续谈失败**也必须回一封失败信**,与新会话那条路一致(B-6)。
|
||||||
return;
|
//
|
||||||
}
|
// 实测缺口(2026-09-12):模型侧 402(余额不足)时,新会话那条路
|
||||||
|
// 会回「处理失败」,而续谈这条路只写了日志就 throw —— 发件人那边
|
||||||
|
// **什么也不会收到**(续谈不触发自动转发,因为会话里没有新的
|
||||||
|
// assistant 文本),而邮件驱动的会话没有本地界面可以看。
|
||||||
|
//
|
||||||
|
// 复现条件很普通:往一条**已存在**的会话再发一封信,此时模型侧报错。
|
||||||
|
if (kind === 'mail' && data.from_name) {
|
||||||
|
try {
|
||||||
|
await client.post('/mail/send', {
|
||||||
|
to: data.from_name,
|
||||||
|
subject: `处理失败: ${data.subject || '(无主题)'}`,
|
||||||
|
// 用续谈专用文案:共用那段说的是「范围内的模型都试过了」,
|
||||||
|
// 而这条路**故意不降级**,照抄等于让人去调一个无效的旋钮。
|
||||||
|
body: renderResumeFailure(data.subject, outcome.error),
|
||||||
|
reply_to: data.mail_id || '',
|
||||||
|
relay: 'summary',
|
||||||
|
relay_key: clampRelayKey(`model-failure:${data.mail_id || piSessionId}`),
|
||||||
|
});
|
||||||
|
log(`已回报续谈失败给 ${data.from_name}`);
|
||||||
|
} catch (e) {
|
||||||
|
log(`失败回报也发不出去: ${describeError(e)}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
throw new Error(`续谈失败: ${outcome.error}`);
|
||||||
|
}
|
||||||
|
await relaySummary(session, sessionManager, adopted);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
// 按管理员划定的范围逐个尝试(D-3)。
|
// 按管理员划定的范围逐个尝试(D-3)。
|
||||||
// 关键点:`prompt()` resolve **不代表模型跑成功了** —— 无凭证的 provider
|
// 关键点:`prompt()` resolve **不代表模型跑成功了** —— 无凭证的 provider
|
||||||
@ -551,7 +601,7 @@ async function run() {
|
|||||||
body: renderFailureReport(failures, data.subject),
|
body: renderFailureReport(failures, data.subject),
|
||||||
reply_to: data.mail_id || '',
|
reply_to: data.mail_id || '',
|
||||||
relay: 'summary',
|
relay: 'summary',
|
||||||
relay_key: `model-failure:${data.mail_id || piSessionId}`,
|
relay_key: clampRelayKey(`model-failure:${data.mail_id || piSessionId}`),
|
||||||
});
|
});
|
||||||
log(`已回报模型调用失败给 ${data.from_name}`);
|
log(`已回报模型调用失败给 ${data.from_name}`);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
|
|||||||
199
plugins/pi-mail-bridge/test/permission-forward-wiring.test.mjs
Normal file
199
plugins/pi-mail-bridge/test/permission-forward-wiring.test.mjs
Normal file
@ -0,0 +1,199 @@
|
|||||||
|
/**
|
||||||
|
* 接线断言:「网关把重复 relay_key 判为幂等命中」时,各桥必须**当场拒绝**,
|
||||||
|
* 而不是把那句 `await 决策` 一直等下去。
|
||||||
|
*
|
||||||
|
* # 为什么需要一条这样的测试
|
||||||
|
*
|
||||||
|
* 判据本身(`isDuplicateRelay`)在 `lib/relay-key.js` 里有单测 —— 但那次缺口
|
||||||
|
* 不在判据,而在**接线**:只有 zcode 桥认这个回包,pi/opencode/dsh 把它当成功,
|
||||||
|
* 然后等一个永远不会来的 `permission_decision`,表现为静默挂死。
|
||||||
|
* 纯函数测试对这种缺口天生无能为力:函数是对的,只是没人调用它。
|
||||||
|
*
|
||||||
|
* # 为什么读源码而不是跑起来
|
||||||
|
*
|
||||||
|
* 三个桥的入口都**不是可导入的模块**:pi 的 worker 是子进程、opencode 把入口的
|
||||||
|
* 每个导出当插件工厂检查、dsh 的入口拉起整个 Cordis 插件。让它们可测需要把
|
||||||
|
* 这些路径重构成可注入的形状,那是更大的改动面 —— 而这里要钉住的只有一件事:
|
||||||
|
* 「那个判断还在、且落在权限转发这条路上」。
|
||||||
|
*
|
||||||
|
* 与 `narrow-layout.test.mjs` 同一取舍:**验形态,不验行为**。
|
||||||
|
* 代价是它对重构敏感(改动这一段的写法时这里会红),这正是它该做的提醒。
|
||||||
|
*
|
||||||
|
* # 这条测试自己也有判据自检
|
||||||
|
*
|
||||||
|
* 一个「永远为真」的接线断言比没有更糟:它会让下一个人以为这里被覆盖着。
|
||||||
|
* 所以下面先证明「拿一段没有该判断的源码喂给它,它会红」。
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { test } from 'node:test';
|
||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import { readFileSync, existsSync } from 'node:fs';
|
||||||
|
import { dirname, join } from 'node:path';
|
||||||
|
import { fileURLToPath } from 'node:url';
|
||||||
|
|
||||||
|
const HERE = dirname(fileURLToPath(import.meta.url));
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 向上找到「装着各桥的那个目录」。
|
||||||
|
*
|
||||||
|
* 不写死 `../..`:这个文件会被复制到每个桥的 test/ 下,也可能被从别的 cwd 跑。
|
||||||
|
* 找不到时**必须判红**,不能静默返回空列表 —— 那会让下面每条断言都不执行,
|
||||||
|
* 而结果看起来是「全绿」(这条自检第一次跑就是这么逮住我自己的:过滤后 0 个桥)。
|
||||||
|
*/
|
||||||
|
function findPluginsDir(start) {
|
||||||
|
let dir = start;
|
||||||
|
for (let i = 0; i < 6; i++) {
|
||||||
|
if (existsSync(join(dir, 'pi-mail-bridge')) && existsSync(join(dir, 'opencode-mail-bridge'))) return dir;
|
||||||
|
const up = dirname(dir);
|
||||||
|
if (up === dir) break;
|
||||||
|
dir = up;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const PLUGINS_DIR = findPluginsDir(HERE);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 各桥的入口文件与它自己的「拒绝」写法。
|
||||||
|
*
|
||||||
|
* 三家的返回形状**各不相同**(pi 是 `{block:true, reason}`、opencode 是
|
||||||
|
* `output.status = "deny"`、dsh 是返回 DSH 的 ApprovalOutcome 字符串 `'rejected'`),
|
||||||
|
* 所以这里逐个列出来 —— 我第一版给 dsh 写成了 opencode 的形状,
|
||||||
|
* 而 `tsc` **没报错**(返回类型是宽联合),只有对着邻居读才发现。
|
||||||
|
*/
|
||||||
|
const BRIDGES = [
|
||||||
|
{
|
||||||
|
name: 'pi-mail-bridge',
|
||||||
|
source: 'src/worker.mjs',
|
||||||
|
// pi 在同一个分支里既判又拒
|
||||||
|
branch: /if\s*\(\s*isDuplicateRelay\(/,
|
||||||
|
denyShape: /block:\s*true/,
|
||||||
|
denyShapeDesc: 'block: true'
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'opencode-mail-bridge',
|
||||||
|
source: 'index.js',
|
||||||
|
branch: /if\s*\(\s*isDuplicateRelay\(/,
|
||||||
|
denyShape: /output\.status\s*=\s*"deny"/,
|
||||||
|
denyShapeDesc: 'output.status = "deny"'
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'dsh-mail-bridge',
|
||||||
|
source: 'src/index.ts',
|
||||||
|
// dsh 是**两段式**:.then 里把重复转成异常抛出去,catch 的 duplicateRelay
|
||||||
|
// 分支里才写拒绝。所以「分支」要取 catch 那一段(第一版取到了 .then 那段,
|
||||||
|
// 于是永远找不到 return 'rejected' —— 是判据错了,不是代码错了)。
|
||||||
|
branch: /if\s*\(\s*e\?\.duplicateRelay\s*\)/,
|
||||||
|
denyShape: /return\s+'rejected'/,
|
||||||
|
denyShapeDesc: "return 'rejected'",
|
||||||
|
// 同时要求它确实认得这个回包(.then 那段)
|
||||||
|
alsoNeeds: /isDuplicateRelay\(/
|
||||||
|
}
|
||||||
|
].filter(b => PLUGINS_DIR && existsSync(join(PLUGINS_DIR, b.name)));
|
||||||
|
|
||||||
|
/** 取出「重复回包 → 拒绝」那个分支的源码片段(从 if 到下一个同级收尾)。 */
|
||||||
|
export function duplicateBranchOf(source, branch) {
|
||||||
|
const m = source.match(branch || /if\s*\(\s*isDuplicateRelay\(/);
|
||||||
|
if (!m) return null;
|
||||||
|
const start = m.index;
|
||||||
|
let depth = 0;
|
||||||
|
let i = source.indexOf('{', start);
|
||||||
|
if (i < 0) return null;
|
||||||
|
for (let j = i; j < source.length; j++) {
|
||||||
|
if (source[j] === '{') depth++;
|
||||||
|
else if (source[j] === '}') {
|
||||||
|
depth--;
|
||||||
|
if (depth === 0) return source.slice(start, j + 1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 权限转发必须**先**判重复:判据要出现在等决策之前。 */
|
||||||
|
export function handlerChecksDuplicateFirst(source, denyShape, branchPattern) {
|
||||||
|
const branch = duplicateBranchOf(source, branchPattern);
|
||||||
|
if (!branch) return { ok: false, why: '源码里找不到处理重复回包的分支' };
|
||||||
|
if (!denyShape.test(branch)) {
|
||||||
|
return { ok: false, why: `重复分支里没有出现本桥的拒绝形状(期望 ${denyShape})` };
|
||||||
|
}
|
||||||
|
return { ok: true, why: '' };
|
||||||
|
}
|
||||||
|
|
||||||
|
test('★ 判据自检:拿没有该判断的源码喂进来必须判红', () => {
|
||||||
|
const PI = /if\s*\(\s*isDuplicateRelay\(/;
|
||||||
|
// ① 找不到分支 → 红
|
||||||
|
assert.equal(handlerChecksDuplicateFirst('const x = 1;', /block:\s*true/, PI).ok, false);
|
||||||
|
// ② 有分支但没有拒绝形状 → 红
|
||||||
|
assert.equal(
|
||||||
|
handlerChecksDuplicateFirst('if (isDuplicateRelay(accepted)) {\n console.error("重复");\n}', /block:\s*true/, PI).ok,
|
||||||
|
false
|
||||||
|
);
|
||||||
|
// 反向对照:形状写对时判绿(否则上面两条可能只是因为断言恒假)
|
||||||
|
assert.equal(
|
||||||
|
handlerChecksDuplicateFirst(
|
||||||
|
'if (isDuplicateRelay(accepted)) {\n return { block: true, reason: "x" };\n}',
|
||||||
|
/block:\s*true/,
|
||||||
|
PI
|
||||||
|
).ok,
|
||||||
|
true
|
||||||
|
);
|
||||||
|
// dsh 那种两段式形态:branch 正则必须能取到 catch 那一段
|
||||||
|
const DSH = /if\s*\(\s*e\?\.duplicateRelay\s*\)/;
|
||||||
|
assert.equal(
|
||||||
|
handlerChecksDuplicateFirst(
|
||||||
|
"if (e?.duplicateRelay) {\n noteDenial(a, b, 'x');\n return 'rejected';\n}",
|
||||||
|
/return\s+'rejected'/,
|
||||||
|
DSH
|
||||||
|
).ok,
|
||||||
|
true
|
||||||
|
);
|
||||||
|
// 同一段源码,用错 branch 正则(取到 .then 那段)应当判红 —— 这正是第一版
|
||||||
|
assert.equal(
|
||||||
|
handlerChecksDuplicateFirst(
|
||||||
|
"if (isDuplicateRelay(accepted)) {\n throw new Error('dup');\n}",
|
||||||
|
/return\s+'rejected'/,
|
||||||
|
DSH
|
||||||
|
).ok,
|
||||||
|
false
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('★ 判据自检:源码位置读取本身是真的(不是空跑)', () => {
|
||||||
|
// 若过滤逻辑把所有桥都滤掉了,下面的循环会一条都不跑而「全绿」——
|
||||||
|
// 这条自检第一次跑就是这么逮住我自己的(路径写错 → 0 个桥)。
|
||||||
|
assert.ok(PLUGINS_DIR, `找不到装着各桥的目录(从 ${HERE} 向上找了 6 层)`);
|
||||||
|
assert.ok(BRIDGES.length >= 3, `应当至少覆盖三个桥,实际 ${BRIDGES.length}`);
|
||||||
|
});
|
||||||
|
|
||||||
|
for (const b of BRIDGES) {
|
||||||
|
test(`★ ${b.name}:权限转发遇到 duplicate_relay 当场拒绝(而不是等一个不会来的决策)`, () => {
|
||||||
|
const file = join(PLUGINS_DIR, b.name, b.source);
|
||||||
|
assert.ok(existsSync(file), `找不到入口:${file}`);
|
||||||
|
const src = readFileSync(file, 'utf8');
|
||||||
|
|
||||||
|
// ① 必须认得这个回包(导入并在权限路径上用)
|
||||||
|
assert.match(
|
||||||
|
src,
|
||||||
|
/isDuplicateRelay/,
|
||||||
|
`${b.name} 没有认 duplicate_relay —— 网关对重复键回 HTTP 200 并提前返回,` +
|
||||||
|
'不认它就会一直等 permission_decision,表现为静默挂死'
|
||||||
|
);
|
||||||
|
|
||||||
|
// ② 该判断必须落在权限转发这条路上,并且给出本桥形状的拒绝
|
||||||
|
const r = handlerChecksDuplicateFirst(src, b.denyShape, b.branch);
|
||||||
|
assert.ok(r.ok, `${b.name}:${r.why}(期望 ${b.denyShapeDesc})`);
|
||||||
|
|
||||||
|
// ③ 两段式桥(dsh)还要认得这个回包
|
||||||
|
if (b.alsoNeeds) {
|
||||||
|
assert.match(src, b.alsoNeeds, `${b.name}:没有认 duplicate_relay 回包`);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ④ 顺序:判据必须在**发出请求之后**。
|
||||||
|
// 第一版写成「在文件里最早的 await 之前」,量到的是别处的等待,
|
||||||
|
// 于是三个桥全红 —— 判据量错了对象,不是代码错了。
|
||||||
|
const postAt = src.indexOf('/permission/request');
|
||||||
|
const dupAt = src.search(b.branch);
|
||||||
|
assert.ok(postAt > 0, `${b.name}:找不到权限上报调用`);
|
||||||
|
assert.ok(dupAt > postAt, `${b.name}:重复判据出现在上报之前(${dupAt} < ${postAt})`);
|
||||||
|
});
|
||||||
|
}
|
||||||
@ -21,6 +21,8 @@ import {
|
|||||||
truncateToBytes,
|
truncateToBytes,
|
||||||
clampRelayKey,
|
clampRelayKey,
|
||||||
isPermanentFailure,
|
isPermanentFailure,
|
||||||
|
isDuplicateRelay,
|
||||||
|
DUPLICATE_RELAY_STATUS,
|
||||||
} from '../lib/relay-key.js';
|
} from '../lib/relay-key.js';
|
||||||
|
|
||||||
// ─── byteLength ───
|
// ─── byteLength ───
|
||||||
@ -192,3 +194,42 @@ test('2xx / 3xx 不算永久失败(本不该走到这里,但不能误判成
|
|||||||
assert.equal(isPermanentFailure({ status: 200 }), false);
|
assert.equal(isPermanentFailure({ status: 200 }), false);
|
||||||
assert.equal(isPermanentFailure({ status: 302 }), false);
|
assert.equal(isPermanentFailure({ status: 302 }), false);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// ─── isDuplicateRelay ─────────────────────────────────────────────────────
|
||||||
|
//
|
||||||
|
// 这一组来自一个**静默挂死**:网关对重复的 relay_key 返回 HTTP 200 +
|
||||||
|
// `{status:"duplicate_relay"}` 并提前返回(不建请求、不发邮件、永远不会有人决策),
|
||||||
|
// 而 pi 的 worker 在 post 之后无条件等着 `permission_decision` 事件 ——
|
||||||
|
// 长得像成功,实际永远等不到。所以「发成功了」与「什么都没发生」必须分得开。
|
||||||
|
|
||||||
|
test('★ 认得出幂等命中(权限询问与代发邮件两个出口都是这个回包)', () => {
|
||||||
|
assert.equal(
|
||||||
|
isDuplicateRelay({ status: DUPLICATE_RELAY_STATUS, relay_key: 'k', detail: '该权限询问已转发过,本次调用未产生新邮件' }),
|
||||||
|
true
|
||||||
|
);
|
||||||
|
// 邮件出口的措辞不同,status 相同 —— 判定只看 status,不看 detail
|
||||||
|
assert.equal(
|
||||||
|
isDuplicateRelay({ status: DUPLICATE_RELAY_STATUS, relay: 'summary', detail: '该上游消息已转发过,本次调用未产生新邮件' }),
|
||||||
|
true
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('★ 反向对照:正常的 200 回包不能被当成幂等命中', () => {
|
||||||
|
// 误判的代价是反的:把正常请求当重复 ⇒ 明明发出去了却当场拒绝。
|
||||||
|
for (const res of [{}, { status: 'ok' }, { status: 'pending' }, { status: 'decided' }, { status: '' }]) {
|
||||||
|
assert.equal(isDuplicateRelay(res), false, JSON.stringify(res));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test('★ 非对象输入不炸也不误判', () => {
|
||||||
|
for (const v of [null, undefined, '', 'duplicate_relay', 0, false, [], ['duplicate_relay']]) {
|
||||||
|
assert.equal(isDuplicateRelay(v), false, JSON.stringify(v));
|
||||||
|
}
|
||||||
|
// 数组即使带 status 字段也不算(防止把响应列表当成单个响应)
|
||||||
|
assert.equal(isDuplicateRelay([{ status: DUPLICATE_RELAY_STATUS }]), false);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('status 常量与服务端字面量一致(改一处会两边不认,这条钉住)', () => {
|
||||||
|
// gateway 侧:server/internal/handler/{permission,mail}.go 都写字面量 "duplicate_relay"
|
||||||
|
assert.equal(DUPLICATE_RELAY_STATUS, 'duplicate_relay');
|
||||||
|
});
|
||||||
|
|||||||
@ -17,6 +17,7 @@ import {
|
|||||||
describeError,
|
describeError,
|
||||||
buildMailPrompt,
|
buildMailPrompt,
|
||||||
relayKeyFor,
|
relayKeyFor,
|
||||||
|
renderResumeFailure,
|
||||||
} from '../src/turn.mjs';
|
} from '../src/turn.mjs';
|
||||||
|
|
||||||
// ─── 主题 ───
|
// ─── 主题 ───
|
||||||
@ -288,3 +289,35 @@ test('不变量:叶子 id 缺失时仍产出稳定键', () => {
|
|||||||
assert.equal(relayKeyFor('sess-1', null), 'sess-1:noleaf');
|
assert.equal(relayKeyFor('sess-1', null), 'sess-1:noleaf');
|
||||||
assert.equal(relayKeyFor('sess-1', undefined), 'sess-1:noleaf');
|
assert.equal(relayKeyFor('sess-1', undefined), 'sess-1:noleaf');
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// ─── 续谈失败的回报正文 ─────────────────────────────────────────────────
|
||||||
|
//
|
||||||
|
// 这组来自一个真实缺口(2026-09-12):模型侧 402 时,**新会话**那条路会回
|
||||||
|
// 「处理失败」,而**续谈**那条路只写日志就 throw —— 发件人什么都收不到。
|
||||||
|
// 邮件驱动的会话没有本地界面,没有这封信就等于「信发出去了,然后再无音讯」。
|
||||||
|
//
|
||||||
|
// 另有一个「文案不能撒谎」的点:共用库的 renderFailureReport 说
|
||||||
|
// 「划定范围内的模型全部调用失败」并建议「调整可用模型范围」——
|
||||||
|
// 那是新会话那条路的事实;续谈**故意不降级**,照抄会让人去调一个无效的旋钮。
|
||||||
|
|
||||||
|
test('★ 续谈失败回报:说清是续谈失败,并带上上游错误原文', () => {
|
||||||
|
const body = renderResumeFailure('四桥冒烟 SMOKE4-x-pi', '402: Insufficient Balance');
|
||||||
|
assert.match(body, /续谈/);
|
||||||
|
assert.match(body, /SMOKE4-x-pi/);
|
||||||
|
assert.match(body, /402: Insufficient Balance/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('★ 续谈失败回报不能说「范围内的模型都试过了」(那是另一条路的事实)', () => {
|
||||||
|
const body = renderResumeFailure('主题', '上游错误');
|
||||||
|
assert.doesNotMatch(body, /划定范围内的模型全部调用失败/);
|
||||||
|
assert.doesNotMatch(body, /调整可用模型范围/);
|
||||||
|
// 反向对照:必须给出**这条路真正可行**的建议,而不是让人去改一个无效的旋钮
|
||||||
|
assert.match(body, /新建/);
|
||||||
|
assert.match(body, /不会\*\*换用其它模型|不会\*\*换/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('续谈失败回报在主题/错误缺失时也不崩', () => {
|
||||||
|
const body = renderResumeFailure(undefined, undefined);
|
||||||
|
assert.match(body, /\(无主题\)/);
|
||||||
|
assert.match(body, /未知错误/);
|
||||||
|
});
|
||||||
|
|||||||
@ -38,7 +38,7 @@
|
|||||||
|
|
||||||
import { createSSEClient } from './sse-client.js';
|
import { createSSEClient } from './sse-client.js';
|
||||||
import { randomUUID } from 'node:crypto';
|
import { randomUUID } from 'node:crypto';
|
||||||
import { clampRelayKey, isPermanentFailure } from './relay-key.js';
|
import { clampRelayKey, isPermanentFailure, isDuplicateRelay } from './relay-key.js';
|
||||||
import { isApproval, isAlwaysDecision } from './permission-grants.js';
|
import { isApproval, isAlwaysDecision } from './permission-grants.js';
|
||||||
import { normalizeMode, DEFAULT_MODE, MODE_FULL, MODE_PLAN } from './permission-mode.js';
|
import { normalizeMode, DEFAULT_MODE, MODE_FULL, MODE_PLAN } from './permission-mode.js';
|
||||||
/** 等待人工决策的默认上限。调用方应保证它**明显小于**自己的杀进程上限,
|
/** 等待人工决策的默认上限。调用方应保证它**明显小于**自己的杀进程上限,
|
||||||
@ -95,10 +95,9 @@ export function relayKeyForCall({ seed, sessionId, toolName, nonce }) {
|
|||||||
return clampRelayKey(`${head}:${tail}`);
|
return clampRelayKey(`${head}:${tail}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 网关在幂等命中时的回包形状(实测):建请求被跳过,不会有任何人来决策。 */
|
// `isDuplicateRelay` 与 `DUPLICATE_RELAY_STATUS` 已挪到 **共用库** `lib/relay-key.js`:
|
||||||
export function isDuplicateRelay(res) {
|
// 四个桥都要认这个回包,各写一份必然分叉(而这个判据是「静默挂死」与
|
||||||
return Boolean(res && typeof res === 'object' && res.status === 'duplicate_relay');
|
// 「当场拒绝」的分界)。这里只 import。
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 询问人类。
|
* 询问人类。
|
||||||
|
|||||||
@ -125,3 +125,41 @@ export function isPermanentFailure(err) {
|
|||||||
if (status === 408 || status === 429) return false; // 超时 / 限流 → 暂时
|
if (status === 408 || status === 429) return false; // 超时 / 限流 → 暂时
|
||||||
return status >= 400 && status < 500;
|
return status >= 400 && status < 500;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 网关把重复的 relay_key 判为**幂等命中**时的回包标识。
|
||||||
|
*
|
||||||
|
* 两个出口都会这么答(权限询问与代发邮件),且都是 **HTTP 200 且提前返回**:
|
||||||
|
* 不建请求、不发邮件,**也永远不会有人来决策**。
|
||||||
|
*/
|
||||||
|
export const DUPLICATE_RELAY_STATUS = 'duplicate_relay';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 这个回包是不是「重复键,什么都没发生」。
|
||||||
|
*
|
||||||
|
* ## 为什么必须单独认它
|
||||||
|
*
|
||||||
|
* 它长得像成功(200),所以「发完就等决策」的实现会一直等下去。实测过的形态:
|
||||||
|
* pi 的 worker 在 `post('/permission/request')` 之后无条件
|
||||||
|
* `await new Promise(resolve => pending.set(relayKey, resolve))`,而那个 resolve
|
||||||
|
* 只由 `permission_decision` 事件触发 —— 重复的键永远不会带来决策,
|
||||||
|
* 于是那封邮件**静默挂死**(模型干等,人以为在跑)。
|
||||||
|
*
|
||||||
|
* 什么时候会重复(都是**正常**的重试,不是故障):
|
||||||
|
*
|
||||||
|
* - 插件重启后重放同一轮(键是确定性的,这正是它的设计目的)
|
||||||
|
* - SDK / 上游重放同一个 tool call
|
||||||
|
* - 上一次询问已经被人决定过,而这一侧没收到那个决策(重启、断线)
|
||||||
|
*
|
||||||
|
* 对「发信」那一侧,重复就该当成功(幂等,这正是网关返回 200 的意思);
|
||||||
|
* 但对「等一个决定」那一侧,它与故障的后果完全一样:永远等不到。
|
||||||
|
* 所以两边的处置必须分开写,而不是共用一个「发成功了」的判定。
|
||||||
|
*
|
||||||
|
* @param {unknown} res 网关的响应体(不是 HTTP 响应对象)
|
||||||
|
* @returns {boolean}
|
||||||
|
*/
|
||||||
|
export function isDuplicateRelay(res) {
|
||||||
|
return Boolean(
|
||||||
|
res && typeof res === 'object' && !Array.isArray(res) && res.status === DUPLICATE_RELAY_STATUS
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|||||||
@ -21,6 +21,8 @@ import {
|
|||||||
truncateToBytes,
|
truncateToBytes,
|
||||||
clampRelayKey,
|
clampRelayKey,
|
||||||
isPermanentFailure,
|
isPermanentFailure,
|
||||||
|
isDuplicateRelay,
|
||||||
|
DUPLICATE_RELAY_STATUS,
|
||||||
} from '../lib/relay-key.js';
|
} from '../lib/relay-key.js';
|
||||||
|
|
||||||
// ─── byteLength ───
|
// ─── byteLength ───
|
||||||
@ -192,3 +194,42 @@ test('2xx / 3xx 不算永久失败(本不该走到这里,但不能误判成
|
|||||||
assert.equal(isPermanentFailure({ status: 200 }), false);
|
assert.equal(isPermanentFailure({ status: 200 }), false);
|
||||||
assert.equal(isPermanentFailure({ status: 302 }), false);
|
assert.equal(isPermanentFailure({ status: 302 }), false);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// ─── isDuplicateRelay ─────────────────────────────────────────────────────
|
||||||
|
//
|
||||||
|
// 这一组来自一个**静默挂死**:网关对重复的 relay_key 返回 HTTP 200 +
|
||||||
|
// `{status:"duplicate_relay"}` 并提前返回(不建请求、不发邮件、永远不会有人决策),
|
||||||
|
// 而 pi 的 worker 在 post 之后无条件等着 `permission_decision` 事件 ——
|
||||||
|
// 长得像成功,实际永远等不到。所以「发成功了」与「什么都没发生」必须分得开。
|
||||||
|
|
||||||
|
test('★ 认得出幂等命中(权限询问与代发邮件两个出口都是这个回包)', () => {
|
||||||
|
assert.equal(
|
||||||
|
isDuplicateRelay({ status: DUPLICATE_RELAY_STATUS, relay_key: 'k', detail: '该权限询问已转发过,本次调用未产生新邮件' }),
|
||||||
|
true
|
||||||
|
);
|
||||||
|
// 邮件出口的措辞不同,status 相同 —— 判定只看 status,不看 detail
|
||||||
|
assert.equal(
|
||||||
|
isDuplicateRelay({ status: DUPLICATE_RELAY_STATUS, relay: 'summary', detail: '该上游消息已转发过,本次调用未产生新邮件' }),
|
||||||
|
true
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('★ 反向对照:正常的 200 回包不能被当成幂等命中', () => {
|
||||||
|
// 误判的代价是反的:把正常请求当重复 ⇒ 明明发出去了却当场拒绝。
|
||||||
|
for (const res of [{}, { status: 'ok' }, { status: 'pending' }, { status: 'decided' }, { status: '' }]) {
|
||||||
|
assert.equal(isDuplicateRelay(res), false, JSON.stringify(res));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test('★ 非对象输入不炸也不误判', () => {
|
||||||
|
for (const v of [null, undefined, '', 'duplicate_relay', 0, false, [], ['duplicate_relay']]) {
|
||||||
|
assert.equal(isDuplicateRelay(v), false, JSON.stringify(v));
|
||||||
|
}
|
||||||
|
// 数组即使带 status 字段也不算(防止把响应列表当成单个响应)
|
||||||
|
assert.equal(isDuplicateRelay([{ status: DUPLICATE_RELAY_STATUS }]), false);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('status 常量与服务端字面量一致(改一处会两边不认,这条钉住)', () => {
|
||||||
|
// gateway 侧:server/internal/handler/{permission,mail}.go 都写字面量 "duplicate_relay"
|
||||||
|
assert.equal(DUPLICATE_RELAY_STATUS, 'duplicate_relay');
|
||||||
|
});
|
||||||
|
|||||||
Reference in New Issue
Block a user