@zhushanwen/pi-subagent-workflow 8.3.0 → 8.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +18 -4
- package/relay/relay.mjs +390 -0
- package/skills/subagent-ext-config/SKILL.md +80 -0
- package/src/execution/__tests__/agent-registry.test.ts +110 -0
- package/src/execution/__tests__/chat-engine-routing.test.ts +597 -0
- package/src/execution/__tests__/execution-record.test.ts +127 -1
- package/src/execution/__tests__/pi-invocation.test.ts +62 -1
- package/src/execution/__tests__/relay-agent.test.ts +448 -0
- package/src/execution/__tests__/relay-env.test.ts +42 -0
- package/src/execution/__tests__/startup-config-declaration.test.ts +35 -0
- package/src/execution/__tests__/stream-sink-retirement.test.ts +261 -0
- package/src/execution/__tests__/subprocess-agent-runner-routing.test.ts +310 -0
- package/src/execution/__tests__/subprocess-agent-runner.test.ts +53 -5
- package/src/execution/agent-registry.ts +10 -0
- package/src/execution/config.ts +25 -2
- package/src/execution/engine/__tests__/common/data-dir.test.ts +53 -0
- package/src/execution/engine/__tests__/common/errors.test.ts +132 -0
- package/src/execution/engine/__tests__/common/event-journal.test.ts +177 -0
- package/src/execution/engine/__tests__/common/kill-chain.test.ts +192 -0
- package/src/execution/engine/__tests__/common/nesting-guard.test.ts +81 -0
- package/src/execution/engine/__tests__/common/persona-router.test.ts +123 -0
- package/src/execution/engine/__tests__/common/pool-manager.test.ts +154 -0
- package/src/execution/engine/__tests__/common/schema-emulation.test.ts +128 -0
- package/src/execution/engine/__tests__/conformance/__fixtures__/pi-golden-events.json +28 -0
- package/src/execution/engine/__tests__/conformance/agent-event-invariants.ts +141 -0
- package/src/execution/engine/__tests__/conformance/contract.abort.test.ts +109 -0
- package/src/execution/engine/__tests__/conformance/contract.agent-events.test.ts +101 -0
- package/src/execution/engine/__tests__/conformance/contract.probe.test.ts +77 -0
- package/src/execution/engine/__tests__/conformance/contract.read-degradation.test.ts +104 -0
- package/src/execution/engine/__tests__/conformance/contract.relay.test.ts +342 -0
- package/src/execution/engine/__tests__/conformance/engine-conformance.live.test.ts +201 -0
- package/src/execution/engine/__tests__/conformance/golden-replay.pi.test.ts +76 -0
- package/src/execution/engine/__tests__/conformance/golden-replay.zcode.test.ts +79 -0
- package/src/execution/engine/__tests__/engine-discovery.test.ts +87 -0
- package/src/execution/engine/__tests__/engines-declaration.test.ts +36 -0
- package/src/execution/engine/__tests__/model-prompt.test.ts +85 -0
- package/src/execution/engine/__tests__/paths.test.ts +39 -0
- package/src/execution/engine/__tests__/registry.test.ts +120 -0
- package/src/execution/engine/__tests__/routing.test.ts +231 -0
- package/src/execution/engine/common/data-dir.ts +62 -0
- package/src/execution/engine/common/errors.ts +183 -0
- package/src/execution/engine/common/event-journal.ts +254 -0
- package/src/execution/engine/common/journal-replay.ts +62 -0
- package/src/execution/engine/common/kill-chain.ts +221 -0
- package/src/execution/engine/common/nesting-guard.ts +50 -0
- package/src/execution/engine/common/persona-router.ts +108 -0
- package/src/execution/engine/common/pool-manager.ts +226 -0
- package/src/execution/engine/common/schema-emulation.ts +189 -0
- package/src/execution/engine/common/session-view-projection.ts +51 -0
- package/src/execution/engine/engine-discovery.ts +65 -0
- package/src/execution/engine/engines/pi/__tests__/pi-engine.test.ts +469 -0
- package/src/execution/engine/engines/pi/__tests__/reader.test.ts +155 -0
- package/src/execution/engine/engines/pi/__tests__/task-spec-mapper.test.ts +164 -0
- package/src/execution/engine/engines/pi/pi-engine.ts +415 -0
- package/src/execution/engine/engines/pi/reader.ts +48 -0
- package/src/execution/engine/engines/pi/registration.ts +35 -0
- package/src/execution/engine/engines/pi/task-spec-mapper.ts +100 -0
- package/src/execution/engine/engines/zcode/__tests__/__fixtures__/zcode-golden-spawn.json +39 -0
- package/src/execution/engine/engines/zcode/__tests__/launcher.test.ts +150 -0
- package/src/execution/engine/engines/zcode/__tests__/parser.test.ts +246 -0
- package/src/execution/engine/engines/zcode/__tests__/preparer.test.ts +228 -0
- package/src/execution/engine/engines/zcode/__tests__/reader.test.ts +210 -0
- package/src/execution/engine/engines/zcode/__tests__/registration.test.ts +64 -0
- package/src/execution/engine/engines/zcode/__tests__/zcode-engine.live.test.ts +127 -0
- package/src/execution/engine/engines/zcode/__tests__/zcode-engine.test.ts +567 -0
- package/src/execution/engine/engines/zcode/constants.ts +43 -0
- package/src/execution/engine/engines/zcode/golden-sample.ts +39 -0
- package/src/execution/engine/engines/zcode/launcher.ts +161 -0
- package/src/execution/engine/engines/zcode/parser.ts +436 -0
- package/src/execution/engine/engines/zcode/preparer.ts +363 -0
- package/src/execution/engine/engines/zcode/reader.ts +381 -0
- package/src/execution/engine/engines/zcode/registration.ts +37 -0
- package/src/execution/engine/engines/zcode/zcode-engine.ts +648 -0
- package/src/execution/engine/host-task-spec.ts +47 -0
- package/src/execution/engine/model-prompt.ts +59 -0
- package/src/execution/engine/paths.ts +42 -0
- package/src/execution/engine/port.ts +153 -0
- package/src/execution/engine/registry.ts +123 -0
- package/src/execution/engine/routing.ts +218 -0
- package/src/execution/engine/types.ts +304 -0
- package/src/execution/execute-options-mapper.ts +5 -1
- package/src/execution/execution-record.ts +6 -0
- package/src/execution/model-resolver.ts +6 -0
- package/src/execution/pi-invocation.ts +32 -2
- package/src/execution/record-entry.ts +14 -0
- package/src/execution/record-store.ts +34 -0
- package/src/execution/relay-env.ts +37 -0
- package/src/execution/session-runner.ts +24 -0
- package/src/execution/stream-sink.ts +26 -0
- package/src/execution/subagent-service.ts +249 -11
- package/src/execution/subprocess-agent-runner.ts +196 -14
- package/src/execution/types.ts +56 -0
- package/src/index.ts +46 -1
- package/src/interface/command-actions.ts +72 -8
- package/src/interface/subagent-actions.ts +8 -2
- package/src/interface/subagent-tool.ts +6 -0
- package/src/interface/subagents.ts +198 -30
- package/src/orchestration/__tests__/__fixtures__/worker-template.snapshot.txt +5 -2
- package/src/orchestration/__tests__/worker-script-template-snapshot.test.ts +3 -3
- package/src/orchestration/models/types.ts +7 -0
- package/src/orchestration/worker-script-builder.ts +5 -2
- package/src/shared/meta-parser.ts +5 -1
- package/src/shared/resource-meta.ts +5 -0
|
@@ -20,7 +20,8 @@ import {
|
|
|
20
20
|
tryTransition,
|
|
21
21
|
updateFromEvent,
|
|
22
22
|
} from "../execution-record.ts";
|
|
23
|
-
import type { AgentResult, ExecutionRecord, Turn } from "../types.ts";
|
|
23
|
+
import type { AgentResult, ExecutionRecord, SubagentRecord, Turn } from "../types.ts";
|
|
24
|
+
import { toSubagentRecordEntry } from "../record-entry.ts";
|
|
24
25
|
|
|
25
26
|
// ── 常量(与源码 module-private 值对齐,测试用字面量)──
|
|
26
27
|
const TURN_SUMMARY_MAX = 80;
|
|
@@ -1156,3 +1157,128 @@ describe("tool_end running index [perf]", () => {
|
|
|
1156
1157
|
expect(record.turns[1]!.toolCalls[0]).toMatchObject({ toolName: "write", result: "w-done", _status: "done" });
|
|
1157
1158
|
});
|
|
1158
1159
|
});
|
|
1160
|
+
|
|
1161
|
+
// ============================================================
|
|
1162
|
+
// P4 引擎留痕字段(engine / engineFallback,D9①)
|
|
1163
|
+
// ============================================================
|
|
1164
|
+
|
|
1165
|
+
describe("createRecord 引擎留痕字段(P4)", () => {
|
|
1166
|
+
it("identity 带 engine/engineFallback 时进 record,JSON 序列化保留(持久化语义)", () => {
|
|
1167
|
+
const record = createRecord("sa-engine-1", {
|
|
1168
|
+
agent: "reviewer",
|
|
1169
|
+
model: "p/m",
|
|
1170
|
+
mode: "background",
|
|
1171
|
+
task: "t",
|
|
1172
|
+
slug: "s",
|
|
1173
|
+
startedAt: 1,
|
|
1174
|
+
engine: "pi",
|
|
1175
|
+
engineFallback: { from: "zcode", reason: "engine_probe_failed" },
|
|
1176
|
+
});
|
|
1177
|
+
expect(record.engine).toBe("pi");
|
|
1178
|
+
expect(record.engineFallback).toEqual({ from: "zcode", reason: "engine_probe_failed" });
|
|
1179
|
+
const serialized = JSON.parse(JSON.stringify(record)) as Record<string, unknown>;
|
|
1180
|
+
expect(serialized["engine"]).toBe("pi");
|
|
1181
|
+
expect(serialized["engineFallback"]).toEqual({ from: "zcode", reason: "engine_probe_failed" });
|
|
1182
|
+
});
|
|
1183
|
+
|
|
1184
|
+
it("不传时两字段缺省(存量 record 消费方零影响——序列化后无键产生)", () => {
|
|
1185
|
+
const record = createRecord("sa-engine-2", {
|
|
1186
|
+
agent: "worker",
|
|
1187
|
+
model: "p/m",
|
|
1188
|
+
mode: "background",
|
|
1189
|
+
task: "t",
|
|
1190
|
+
slug: "s",
|
|
1191
|
+
startedAt: 1,
|
|
1192
|
+
});
|
|
1193
|
+
expect(record.engine).toBeUndefined();
|
|
1194
|
+
expect(record.engineFallback).toBeUndefined();
|
|
1195
|
+
const serialized = JSON.parse(JSON.stringify(record)) as Record<string, unknown>;
|
|
1196
|
+
expect("engine" in serialized).toBe(false);
|
|
1197
|
+
expect("engineFallback" in serialized).toBe(false);
|
|
1198
|
+
});
|
|
1199
|
+
|
|
1200
|
+
it("SubagentRecord → entry 投影保留两字段(record-entry 持久化链)", () => {
|
|
1201
|
+
const base: SubagentRecord = {
|
|
1202
|
+
id: "sa-engine-3",
|
|
1203
|
+
agent: "reviewer",
|
|
1204
|
+
task: "t",
|
|
1205
|
+
slug: "s",
|
|
1206
|
+
status: "running",
|
|
1207
|
+
mode: "background",
|
|
1208
|
+
startedAt: 1,
|
|
1209
|
+
rootSessionId: undefined,
|
|
1210
|
+
parentRecordId: undefined,
|
|
1211
|
+
depth: 0,
|
|
1212
|
+
endedAt: undefined,
|
|
1213
|
+
turns: 0,
|
|
1214
|
+
totalTokens: 0,
|
|
1215
|
+
model: "p/m",
|
|
1216
|
+
thinkingLevel: undefined,
|
|
1217
|
+
eventLog: [],
|
|
1218
|
+
displayItems: [],
|
|
1219
|
+
};
|
|
1220
|
+
const entry = toSubagentRecordEntry({ ...base, engine: "pi", engineFallback: { from: "zcode", reason: "engine_probe_failed" } });
|
|
1221
|
+
expect(entry.engine).toBe("pi");
|
|
1222
|
+
expect(entry.engineFallback).toEqual({ from: "zcode", reason: "engine_probe_failed" });
|
|
1223
|
+
// 存量 record(无字段)投影后同样缺省——消费方按 pi 投影,零迁移
|
|
1224
|
+
expect(toSubagentRecordEntry(base).engine).toBeUndefined();
|
|
1225
|
+
});
|
|
1226
|
+
});
|
|
1227
|
+
|
|
1228
|
+
// ============================================================
|
|
1229
|
+
// U1 engine 三字段 entry 往返(engineHandle 贯通)
|
|
1230
|
+
// ============================================================
|
|
1231
|
+
describe("SubagentRecord ↔ subagent-record entry 往返(U1 engineHandle)", () => {
|
|
1232
|
+
const base: SubagentRecord = {
|
|
1233
|
+
id: "sa-engine-4",
|
|
1234
|
+
agent: "reviewer",
|
|
1235
|
+
task: "t",
|
|
1236
|
+
slug: "s",
|
|
1237
|
+
status: "running",
|
|
1238
|
+
mode: "background",
|
|
1239
|
+
startedAt: 1,
|
|
1240
|
+
rootSessionId: undefined,
|
|
1241
|
+
parentRecordId: undefined,
|
|
1242
|
+
depth: 0,
|
|
1243
|
+
endedAt: undefined,
|
|
1244
|
+
turns: 0,
|
|
1245
|
+
totalTokens: 0,
|
|
1246
|
+
model: "p/m",
|
|
1247
|
+
thinkingLevel: undefined,
|
|
1248
|
+
eventLog: [],
|
|
1249
|
+
displayItems: [],
|
|
1250
|
+
};
|
|
1251
|
+
const handle = { sessionRef: { sessionId: "s-1", dbPath: "pool/zcode.db" }, journalPath: "/abs/journal.jsonl", poolKey: "p1" };
|
|
1252
|
+
|
|
1253
|
+
it("record 含三字段 → entry JSON → 解析回 deep equal(sessionRef 键不枚举整体透传)", () => {
|
|
1254
|
+
const entry = toSubagentRecordEntry({ ...base, engine: "zcode", engineFallback: { from: "zcode", reason: "engine_probe_failed" }, engineHandle: handle });
|
|
1255
|
+
const roundTripped = JSON.parse(JSON.stringify(entry));
|
|
1256
|
+
expect(roundTripped).toEqual({
|
|
1257
|
+
v: 1,
|
|
1258
|
+
id: "sa-engine-4",
|
|
1259
|
+
agent: "reviewer",
|
|
1260
|
+
task: "t",
|
|
1261
|
+
slug: "s",
|
|
1262
|
+
status: "running",
|
|
1263
|
+
mode: "background",
|
|
1264
|
+
startedAt: 1,
|
|
1265
|
+
depth: 0,
|
|
1266
|
+
turns: 0,
|
|
1267
|
+
totalTokens: 0,
|
|
1268
|
+
model: "p/m",
|
|
1269
|
+
eventLog: [],
|
|
1270
|
+
displayItems: [],
|
|
1271
|
+
engine: "zcode",
|
|
1272
|
+
engineFallback: { from: "zcode", reason: "engine_probe_failed" },
|
|
1273
|
+
engineHandle: handle,
|
|
1274
|
+
});
|
|
1275
|
+
expect(toSubagentRecordEntry({ ...base, engineHandle: handle }).engineHandle).toEqual(handle);
|
|
1276
|
+
});
|
|
1277
|
+
|
|
1278
|
+
it("record 无三字段 → entry JSON 不含对应键(undefined 经 JSON.stringify 自然省略,存量零迁移)", () => {
|
|
1279
|
+
const serialized = JSON.parse(JSON.stringify(toSubagentRecordEntry(base))) as Record<string, unknown>;
|
|
1280
|
+
expect("engine" in serialized).toBe(false);
|
|
1281
|
+
expect("engineFallback" in serialized).toBe(false);
|
|
1282
|
+
expect("engineHandle" in serialized).toBe(false);
|
|
1283
|
+
});
|
|
1284
|
+
});
|
|
@@ -3,9 +3,10 @@ import * as fs from "node:fs";
|
|
|
3
3
|
import * as os from "node:os";
|
|
4
4
|
import * as path from "node:path";
|
|
5
5
|
|
|
6
|
-
import { afterEach,describe, expect, it } from "vitest";
|
|
6
|
+
import { afterEach, describe, expect, it } from "vitest";
|
|
7
7
|
|
|
8
8
|
import { getPiInvocation } from "../pi-invocation.ts";
|
|
9
|
+
import { RELAY_ENV_NODE, RELAY_ENV_SCRIPT, RELAY_ENV_SOCKET } from "../relay-env.ts";
|
|
9
10
|
|
|
10
11
|
describe("getPiInvocation", () => {
|
|
11
12
|
const originalArgv = process.argv;
|
|
@@ -71,3 +72,63 @@ describe("getPiInvocation", () => {
|
|
|
71
72
|
expect(result.args).toEqual([]);
|
|
72
73
|
});
|
|
73
74
|
});
|
|
75
|
+
|
|
76
|
+
describe("getPiInvocation relay 分支(E 方案 §5.1)", () => {
|
|
77
|
+
const originalArgv = process.argv;
|
|
78
|
+
const originalExecPath = process.execPath;
|
|
79
|
+
const RELAY_ENVS = [RELAY_ENV_SOCKET, RELAY_ENV_NODE, RELAY_ENV_SCRIPT] as const;
|
|
80
|
+
/** 三 env 齐备的基准值(改 argv/execPath 隔离直连分支,只测 relay 判定本身)。 */
|
|
81
|
+
const RELAY_FULL: Record<string, string> = {
|
|
82
|
+
[RELAY_ENV_SOCKET]: "/tmp/relay-test.sock",
|
|
83
|
+
[RELAY_ENV_NODE]: "/usr/bin/relay-node",
|
|
84
|
+
[RELAY_ENV_SCRIPT]: "/opt/relay/relay.mjs",
|
|
85
|
+
};
|
|
86
|
+
|
|
87
|
+
afterEach(() => {
|
|
88
|
+
Object.defineProperty(process, "argv", { value: originalArgv, configurable: true });
|
|
89
|
+
Object.defineProperty(process, "execPath", { value: originalExecPath, configurable: true });
|
|
90
|
+
for (const key of RELAY_ENVS) delete process.env[key];
|
|
91
|
+
});
|
|
92
|
+
|
|
93
|
+
/** 形态 1:三 env 齐备 + 默认 opts → relay invocation(command=NODE、args[0]=SCRIPT)。 */
|
|
94
|
+
it("三 env 齐备(无 opts)→ 代理形态 <NODE> <SCRIPT> <userArgs>", () => {
|
|
95
|
+
Object.assign(process.env, RELAY_FULL);
|
|
96
|
+
const result = getPiInvocation(["--mode", "rpc"]);
|
|
97
|
+
expect(result.command).toBe(RELAY_FULL[RELAY_ENV_NODE]);
|
|
98
|
+
expect(result.args).toEqual([RELAY_FULL[RELAY_ENV_SCRIPT], "--mode", "rpc"]);
|
|
99
|
+
});
|
|
100
|
+
|
|
101
|
+
/** 形态 1 变体:opts.relay === true 显式开启,行为与缺省一致。 */
|
|
102
|
+
it("三 env 齐备 + opts.relay=true → 同缺省(显式开启非必填)", () => {
|
|
103
|
+
Object.assign(process.env, RELAY_FULL);
|
|
104
|
+
const result = getPiInvocation(["--mode", "rpc"], { relay: true });
|
|
105
|
+
expect(result.command).toBe(RELAY_FULL[RELAY_ENV_NODE]);
|
|
106
|
+
expect(result.args[0]).toBe(RELAY_FULL[RELAY_ENV_SCRIPT]);
|
|
107
|
+
});
|
|
108
|
+
|
|
109
|
+
/** 形态 2:三缺一逐个枚举 → 回落现状直连(全有或全无,E-TUI 零回归)。 */
|
|
110
|
+
it("三缺一(逐个枚举)→ 现状直连分支", () => {
|
|
111
|
+
// 直连分支落到「node + 不存在脚本 → pi-in-PATH」可稳定断言(不依赖测试机 execPath 形态)
|
|
112
|
+
Object.defineProperty(process, "argv", { value: ["node", "/nonexistent"], configurable: true });
|
|
113
|
+
Object.defineProperty(process, "execPath", { value: "/usr/bin/node", configurable: true });
|
|
114
|
+
for (const missing of RELAY_ENVS) {
|
|
115
|
+
const partial = { ...RELAY_FULL };
|
|
116
|
+
delete partial[missing];
|
|
117
|
+
for (const key of RELAY_ENVS) delete process.env[key];
|
|
118
|
+
Object.assign(process.env, partial);
|
|
119
|
+
const result = getPiInvocation(["--mode", "rpc"]);
|
|
120
|
+
expect(result.command).toBe("pi"); // 分支 3:通用 runtime + 脚本不存在 → PATH
|
|
121
|
+
expect(result.args).toEqual(["--mode", "rpc"]);
|
|
122
|
+
}
|
|
123
|
+
});
|
|
124
|
+
|
|
125
|
+
/** 形态 3:probe 排除——显式 relay:false 时即便三 env 齐备也直连。 */
|
|
126
|
+
it("relay:false 强制直连(probe 语义:探 pi 本体,不探 runtime 健康)", () => {
|
|
127
|
+
Object.assign(process.env, RELAY_FULL);
|
|
128
|
+
Object.defineProperty(process, "argv", { value: ["node", "/nonexistent"], configurable: true });
|
|
129
|
+
Object.defineProperty(process, "execPath", { value: "/usr/bin/node", configurable: true });
|
|
130
|
+
const result = getPiInvocation(["--version"], { relay: false });
|
|
131
|
+
expect(result.command).toBe("pi");
|
|
132
|
+
expect(result.args).toEqual(["--version"]);
|
|
133
|
+
});
|
|
134
|
+
});
|
|
@@ -0,0 +1,448 @@
|
|
|
1
|
+
// src/execution/__tests__/relay-agent.test.ts
|
|
2
|
+
//
|
|
3
|
+
// relay.mjs 代理 CLI 协议行为集成测试(E-1 验收)——本地环回 socket + 伪 runtime
|
|
4
|
+
// (net.createServer 模拟 runtime 侧行为),spawn 真实代理进程逐条断言:
|
|
5
|
+
// 1. 启动自检:归属 env(SESSION_ID/RECORD_ID)缺失 / socket env 缺失 → 退出码 13
|
|
6
|
+
// 2. socket 不可达(重试一次后仍失败)→ 退出码 11 + stderr 含路径与恢复指引
|
|
7
|
+
// 3. 握手帧字段完整(v/kind/mainSessionId/recordId/argv/env/cwd)
|
|
8
|
+
// 4. down/up/up-stderr 字节往返保真(中文/换行/空字节的二进制 buffer)
|
|
9
|
+
// 5. exit 帧退出码传播 / 退出前 stdout 已 flush
|
|
10
|
+
// 6. exit 帧 signal 传播(spawn 方观察到 (code=null, signal))
|
|
11
|
+
// 7. socket 断 → 退出码 12(崩溃矩阵②的 extension 侧感知机制)
|
|
12
|
+
// 8. reject version → 退出码 10 + 重装指引;reject 其他 reason → 12
|
|
13
|
+
// 9. 背压:1MB 随机字节经代理双向环回(stdin→down→server→up→stdout)收齐无丢字节
|
|
14
|
+
|
|
15
|
+
import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process";
|
|
16
|
+
import * as crypto from "node:crypto";
|
|
17
|
+
import * as fs from "node:fs";
|
|
18
|
+
import * as net from "node:net";
|
|
19
|
+
import * as os from "node:os";
|
|
20
|
+
import * as path from "node:path";
|
|
21
|
+
import { fileURLToPath } from "node:url";
|
|
22
|
+
|
|
23
|
+
import { afterEach, describe, expect, it } from "vitest";
|
|
24
|
+
|
|
25
|
+
import {
|
|
26
|
+
RELAY_ENV_NODE,
|
|
27
|
+
RELAY_ENV_RECORD_ID,
|
|
28
|
+
RELAY_ENV_SCRIPT,
|
|
29
|
+
RELAY_ENV_SESSION_ID,
|
|
30
|
+
RELAY_ENV_SOCKET,
|
|
31
|
+
RELAY_EXIT_CODES,
|
|
32
|
+
RELAY_PROTOCOL_VERSION,
|
|
33
|
+
} from "../relay-env.ts";
|
|
34
|
+
|
|
35
|
+
/** 被测脚本:包根 relay/relay.mjs(与 src/ 平行的零依赖脚本,不参与 TS 编译)。 */
|
|
36
|
+
const RELAY_SCRIPT_PATH = path.resolve(
|
|
37
|
+
path.dirname(fileURLToPath(import.meta.url)),
|
|
38
|
+
"../../../relay/relay.mjs",
|
|
39
|
+
);
|
|
40
|
+
|
|
41
|
+
/** 协议帧(代理 ↔ runtime JSONL)。字段全部可选除 kind——按 kind 分支后逐字段断言。 */
|
|
42
|
+
interface RelayFrame {
|
|
43
|
+
kind: string;
|
|
44
|
+
v?: unknown;
|
|
45
|
+
dir?: unknown;
|
|
46
|
+
b64?: unknown;
|
|
47
|
+
code?: unknown;
|
|
48
|
+
signal?: unknown;
|
|
49
|
+
reason?: unknown;
|
|
50
|
+
supported?: unknown;
|
|
51
|
+
mainSessionId?: unknown;
|
|
52
|
+
recordId?: unknown;
|
|
53
|
+
argv?: unknown;
|
|
54
|
+
env?: unknown;
|
|
55
|
+
cwd?: unknown;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** JSON.parse + 运行时守卫(禁裸 as):非对象或无 string kind 视为不可解析。 */
|
|
59
|
+
function parseFrame(line: string): RelayFrame | null {
|
|
60
|
+
let parsed: unknown;
|
|
61
|
+
try {
|
|
62
|
+
parsed = JSON.parse(line);
|
|
63
|
+
} catch {
|
|
64
|
+
return null;
|
|
65
|
+
}
|
|
66
|
+
if (typeof parsed !== "object" || parsed === null) return null;
|
|
67
|
+
const kind = (parsed as Record<string, unknown>).kind;
|
|
68
|
+
if (typeof kind !== "string") return null;
|
|
69
|
+
return { ...(parsed as Record<string, unknown>), kind };
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
interface FakeRuntime {
|
|
73
|
+
socketPath: string;
|
|
74
|
+
server: net.Server;
|
|
75
|
+
conn: net.Socket | null;
|
|
76
|
+
/** 第一帧 handshake(默认 respond 逻辑 accept 后 resolve;自定义 respond 也 resolve)。 */
|
|
77
|
+
handshakePromise: Promise<RelayFrame>;
|
|
78
|
+
/** 收到的全部 down 帧解码后的字节块。 */
|
|
79
|
+
downChunks: Buffer[];
|
|
80
|
+
downTotal: () => number;
|
|
81
|
+
send: (frame: Record<string, unknown>) => boolean;
|
|
82
|
+
destroyConn: () => void;
|
|
83
|
+
close: () => Promise<void>;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** 默认 runtime 行为:收 handshake → 回 accept。 */
|
|
87
|
+
function defaultRespond(_handshake: RelayFrame, rt: FakeRuntime): void {
|
|
88
|
+
rt.send({ v: RELAY_PROTOCOL_VERSION, kind: "accept" });
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function startFakeRuntime(
|
|
92
|
+
socketPath: string,
|
|
93
|
+
respond: (handshake: RelayFrame, rt: FakeRuntime) => void = defaultRespond,
|
|
94
|
+
): Promise<FakeRuntime> {
|
|
95
|
+
// handshake 的 settle 状态(resolve 回调 + 已收到帧),供「仅首个 handshake 帧响应」判定
|
|
96
|
+
const handshakeState: { resolve: ((f: RelayFrame) => void) | null; frame: RelayFrame | null } = {
|
|
97
|
+
resolve: null,
|
|
98
|
+
frame: null,
|
|
99
|
+
};
|
|
100
|
+
const handshakePromise = new Promise<RelayFrame>((resolve) => {
|
|
101
|
+
handshakeState.resolve = resolve;
|
|
102
|
+
});
|
|
103
|
+
let connRef: net.Socket | null = null;
|
|
104
|
+
const downChunks: Buffer[] = [];
|
|
105
|
+
const server = net.createServer((conn) => {
|
|
106
|
+
connRef = conn;
|
|
107
|
+
let lineBuf = "";
|
|
108
|
+
conn.setEncoding("utf8");
|
|
109
|
+
conn.on("data", (chunk: string) => {
|
|
110
|
+
lineBuf += chunk;
|
|
111
|
+
let nl: number;
|
|
112
|
+
while ((nl = lineBuf.indexOf("\n")) >= 0) {
|
|
113
|
+
const line = lineBuf.slice(0, nl);
|
|
114
|
+
lineBuf = lineBuf.slice(nl + 1);
|
|
115
|
+
if (!line.trim()) continue;
|
|
116
|
+
const frame = parseFrame(line);
|
|
117
|
+
if (!frame) continue;
|
|
118
|
+
if (frame.kind === "handshake") {
|
|
119
|
+
// 仅首个 handshake 帧响应 + settle(单连接单握手是协议形态)
|
|
120
|
+
if (handshakeState.frame === null) {
|
|
121
|
+
handshakeState.frame = frame;
|
|
122
|
+
respond(frame, rt);
|
|
123
|
+
handshakeState.resolve?.(frame);
|
|
124
|
+
}
|
|
125
|
+
continue;
|
|
126
|
+
}
|
|
127
|
+
if (frame.kind === "data" && frame.dir === "down" && typeof frame.b64 === "string") {
|
|
128
|
+
downChunks.push(Buffer.from(frame.b64, "base64"));
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
});
|
|
132
|
+
});
|
|
133
|
+
const rt: FakeRuntime = {
|
|
134
|
+
socketPath,
|
|
135
|
+
server,
|
|
136
|
+
get conn() {
|
|
137
|
+
return connRef;
|
|
138
|
+
},
|
|
139
|
+
downChunks,
|
|
140
|
+
downTotal: () => downChunks.reduce((sum, c) => sum + c.length, 0),
|
|
141
|
+
send: (frame) => {
|
|
142
|
+
if (!connRef || connRef.destroyed) throw new Error("fake runtime: no live connection");
|
|
143
|
+
return connRef.write(JSON.stringify(frame) + "\n");
|
|
144
|
+
},
|
|
145
|
+
destroyConn: () => {
|
|
146
|
+
connRef?.destroy();
|
|
147
|
+
},
|
|
148
|
+
handshakePromise,
|
|
149
|
+
close: () =>
|
|
150
|
+
new Promise<void>((resolve) => {
|
|
151
|
+
server.close(() => resolve());
|
|
152
|
+
}),
|
|
153
|
+
};
|
|
154
|
+
return new Promise<FakeRuntime>((resolve, reject) => {
|
|
155
|
+
server.once("error", reject);
|
|
156
|
+
server.listen(socketPath, () => {
|
|
157
|
+
activeServers.push(server);
|
|
158
|
+
resolve(rt);
|
|
159
|
+
});
|
|
160
|
+
});
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
interface SpawnOpts {
|
|
164
|
+
/** undefined = 不注入该 env(测缺失路径)。 */
|
|
165
|
+
socketPath?: string;
|
|
166
|
+
sessionId?: string;
|
|
167
|
+
recordId?: string;
|
|
168
|
+
argv?: string[];
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/**
|
|
172
|
+
* spawn 代理进程(node 直跑 relay.mjs,env 精确控制 5 个 relay 变量)。
|
|
173
|
+
* stdout/stderr 收集器随 spawn 立即挂上——对齐真实契约(extension 的 stdout pump
|
|
174
|
+
* 从 spawn 起消费;若测试侧不读,代理的 stdout 背压会正确地暂停 socket,测试卡死)。
|
|
175
|
+
*/
|
|
176
|
+
interface CollectedChild {
|
|
177
|
+
child: ChildProcessWithoutNullStreams;
|
|
178
|
+
stdoutChunks: Buffer[];
|
|
179
|
+
stderrChunks: Buffer[];
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
function spawnRelay(opts: SpawnOpts): CollectedChild {
|
|
183
|
+
const env: NodeJS.ProcessEnv = { ...process.env };
|
|
184
|
+
delete env[RELAY_ENV_SOCKET];
|
|
185
|
+
delete env[RELAY_ENV_NODE];
|
|
186
|
+
delete env[RELAY_ENV_SCRIPT];
|
|
187
|
+
delete env[RELAY_ENV_SESSION_ID];
|
|
188
|
+
delete env[RELAY_ENV_RECORD_ID];
|
|
189
|
+
if (opts.socketPath !== undefined) env[RELAY_ENV_SOCKET] = opts.socketPath;
|
|
190
|
+
if (opts.sessionId !== undefined) env[RELAY_ENV_SESSION_ID] = opts.sessionId;
|
|
191
|
+
if (opts.recordId !== undefined) env[RELAY_ENV_RECORD_ID] = opts.recordId;
|
|
192
|
+
const child = spawn(process.execPath, [RELAY_SCRIPT_PATH, ...(opts.argv ?? ["--mode", "rpc"])], {
|
|
193
|
+
env,
|
|
194
|
+
stdio: ["pipe", "pipe", "pipe"],
|
|
195
|
+
});
|
|
196
|
+
const collected: CollectedChild = {
|
|
197
|
+
child,
|
|
198
|
+
stdoutChunks: [],
|
|
199
|
+
stderrChunks: [],
|
|
200
|
+
};
|
|
201
|
+
child.stdout.on("data", (c: Buffer) => collected.stdoutChunks.push(c));
|
|
202
|
+
child.stderr.on("data", (c: Buffer) => collected.stderrChunks.push(c));
|
|
203
|
+
activeChildren.push(child);
|
|
204
|
+
return collected;
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
interface ExitResult {
|
|
208
|
+
code: number | null;
|
|
209
|
+
signal: NodeJS.Signals | null;
|
|
210
|
+
stderr: string;
|
|
211
|
+
stdout: Buffer;
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
/** 等 child close,输出取自 spawn 时挂起的收集器(close 时数据已齐)。 */
|
|
215
|
+
function waitForExit({ child, stdoutChunks, stderrChunks }: CollectedChild): Promise<ExitResult> {
|
|
216
|
+
return new Promise((resolve, reject) => {
|
|
217
|
+
child.on("error", reject);
|
|
218
|
+
child.on("close", (code, signal) => {
|
|
219
|
+
resolve({
|
|
220
|
+
code,
|
|
221
|
+
signal,
|
|
222
|
+
stdout: Buffer.concat(stdoutChunks),
|
|
223
|
+
stderr: Buffer.concat(stderrChunks).toString("utf8"),
|
|
224
|
+
});
|
|
225
|
+
});
|
|
226
|
+
});
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
/** 轮询等待条件成立(25ms 间隔;超时抛错)。 */
|
|
230
|
+
async function pollUntil(predicate: () => boolean, timeoutMs: number, what: string): Promise<void> {
|
|
231
|
+
const deadline = Date.now() + timeoutMs;
|
|
232
|
+
while (!predicate()) {
|
|
233
|
+
if (Date.now() > deadline) throw new Error(`timeout waiting for ${what}`);
|
|
234
|
+
await new Promise((r) => setTimeout(r, 25));
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
/** 分块发送大 up 帧(64KB/帧 + socket drain 等待,驱动代理侧 socket→stdout 背压路径)。 */
|
|
239
|
+
async function sendLargeUp(rt: FakeRuntime, data: Buffer): Promise<void> {
|
|
240
|
+
const CHUNK = 64 * 1024;
|
|
241
|
+
for (let i = 0; i < data.length; i += CHUNK) {
|
|
242
|
+
const frame = {
|
|
243
|
+
v: RELAY_PROTOCOL_VERSION,
|
|
244
|
+
kind: "data",
|
|
245
|
+
dir: "up",
|
|
246
|
+
b64: data.subarray(i, i + CHUNK).toString("base64"),
|
|
247
|
+
};
|
|
248
|
+
if (!rt.send(frame)) {
|
|
249
|
+
await new Promise<void>((resolve) => {
|
|
250
|
+
const c = rt.conn;
|
|
251
|
+
if (!c) return resolve();
|
|
252
|
+
c.once("drain", () => resolve());
|
|
253
|
+
});
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
const activeServers: net.Server[] = [];
|
|
259
|
+
const activeChildren: ChildProcessWithoutNullStreams[] = [];
|
|
260
|
+
const activeTmpDirs: string[] = [];
|
|
261
|
+
|
|
262
|
+
function makeSocketPath(): string {
|
|
263
|
+
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "relay-agent-test-"));
|
|
264
|
+
activeTmpDirs.push(dir);
|
|
265
|
+
return path.join(dir, "relay.sock");
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
afterEach(async () => {
|
|
269
|
+
for (const child of activeChildren) {
|
|
270
|
+
if (!child.killed) child.kill("SIGKILL");
|
|
271
|
+
}
|
|
272
|
+
activeChildren.length = 0;
|
|
273
|
+
await Promise.all(
|
|
274
|
+
activeServers.map(
|
|
275
|
+
(s) => new Promise<void>((resolve) => s.close(() => resolve())),
|
|
276
|
+
),
|
|
277
|
+
);
|
|
278
|
+
activeServers.length = 0;
|
|
279
|
+
for (const dir of activeTmpDirs) fs.rmSync(dir, { recursive: true, force: true });
|
|
280
|
+
activeTmpDirs.length = 0;
|
|
281
|
+
});
|
|
282
|
+
|
|
283
|
+
describe("relay agent CLI (relay.mjs)", () => {
|
|
284
|
+
it("identity env missing → exit 13 + stderr names the env vars", { timeout: 10_000 }, async () => {
|
|
285
|
+
const child = spawnRelay({});
|
|
286
|
+
const res = await waitForExit(child);
|
|
287
|
+
expect(res.code).toBe(RELAY_EXIT_CODES.MISSING_IDENTITY);
|
|
288
|
+
expect(res.stderr).toContain(RELAY_ENV_SESSION_ID);
|
|
289
|
+
expect(res.stderr).toContain(RELAY_ENV_RECORD_ID);
|
|
290
|
+
});
|
|
291
|
+
|
|
292
|
+
it("socket env missing (identity present) → exit 13", { timeout: 10_000 }, async () => {
|
|
293
|
+
const child = spawnRelay({ sessionId: "sess-1", recordId: "rec-1" });
|
|
294
|
+
const res = await waitForExit(child);
|
|
295
|
+
expect(res.code).toBe(RELAY_EXIT_CODES.MISSING_IDENTITY);
|
|
296
|
+
expect(res.stderr).toContain(RELAY_ENV_SOCKET);
|
|
297
|
+
});
|
|
298
|
+
|
|
299
|
+
it("socket unreachable → retry once then exit 11 with path + recovery hint", { timeout: 15_000 }, async () => {
|
|
300
|
+
const socketPath = path.join(makeSocketPath(), "never-listening.sock");
|
|
301
|
+
const child = spawnRelay({ socketPath, sessionId: "sess-1", recordId: "rec-1" });
|
|
302
|
+
const res = await waitForExit(child);
|
|
303
|
+
expect(res.code).toBe(RELAY_EXIT_CODES.SOCKET_UNREACHABLE);
|
|
304
|
+
expect(res.stderr).toContain(socketPath);
|
|
305
|
+
expect(res.stderr).toContain("重试任务");
|
|
306
|
+
expect(res.stderr).toContain("重启 xyz-agent");
|
|
307
|
+
});
|
|
308
|
+
|
|
309
|
+
it("handshake frame carries full spawn spec (v/kind/mainSessionId/recordId/argv/env/cwd)", { timeout: 15_000 }, async () => {
|
|
310
|
+
const socketPath = makeSocketPath();
|
|
311
|
+
const rt = await startFakeRuntime(socketPath);
|
|
312
|
+
const argv = ["--mode", "rpc", "--model", "test/model"];
|
|
313
|
+
const child = spawnRelay({ socketPath, sessionId: "sess-42", recordId: "rec-99", argv });
|
|
314
|
+
const hs = await rt.handshakePromise;
|
|
315
|
+
expect(hs.kind).toBe("handshake");
|
|
316
|
+
expect(hs.v).toBe(RELAY_PROTOCOL_VERSION);
|
|
317
|
+
expect(hs.mainSessionId).toBe("sess-42");
|
|
318
|
+
expect(hs.recordId).toBe("rec-99");
|
|
319
|
+
expect(hs.argv).toEqual(argv);
|
|
320
|
+
expect(hs.cwd).toBe(process.cwd());
|
|
321
|
+
// env 全量转发:含注入的归属 env 与 socket env(runtime spawn 真实 pi 原样使用)
|
|
322
|
+
expect(hs.env).toBeTypeOf("object");
|
|
323
|
+
expect(hs.env).toHaveProperty(RELAY_ENV_SESSION_ID, "sess-42");
|
|
324
|
+
expect(hs.env).toHaveProperty(RELAY_ENV_RECORD_ID, "rec-99");
|
|
325
|
+
expect(hs.env).toHaveProperty(RELAY_ENV_SOCKET, socketPath);
|
|
326
|
+
// 收尾:默认 respond 已 accept,发 exit 让子进程退出
|
|
327
|
+
rt.send({ kind: "exit", code: 0 });
|
|
328
|
+
const res = await waitForExit(child);
|
|
329
|
+
expect(res.code).toBe(0);
|
|
330
|
+
});
|
|
331
|
+
|
|
332
|
+
it("byte roundtrip fidelity: down/up/up-stderr with CJK, newlines, NUL bytes", { timeout: 15_000 }, async () => {
|
|
333
|
+
const socketPath = makeSocketPath();
|
|
334
|
+
const rt = await startFakeRuntime(socketPath);
|
|
335
|
+
const child = spawnRelay({ socketPath, sessionId: "s", recordId: "r" });
|
|
336
|
+
await rt.handshakePromise;
|
|
337
|
+
|
|
338
|
+
// 下行字节:JSON 命令行 + 中文 + 换行(挑战 JSONL 行协议)+ 空字节(挑战文本假设)
|
|
339
|
+
const downBytes = Buffer.concat([
|
|
340
|
+
Buffer.from('{"type":"prompt","message":"你好,世界\n', "utf8"),
|
|
341
|
+
Buffer.from([0x00, 0x01, 0xff, 0xfe]),
|
|
342
|
+
Buffer.from('第二行"}\n', "utf8"),
|
|
343
|
+
]);
|
|
344
|
+
child.child.stdin.write(downBytes);
|
|
345
|
+
await pollUntil(() => rt.downTotal() === downBytes.length, 5_000, "down bytes");
|
|
346
|
+
expect(Buffer.concat(rt.downChunks)).toEqual(downBytes);
|
|
347
|
+
|
|
348
|
+
// 上行 stdout / stderr 字节保真
|
|
349
|
+
const upBytes = Buffer.concat([
|
|
350
|
+
Buffer.from("stdout 流式输出\nline2\0", "utf8"),
|
|
351
|
+
crypto.randomBytes(64),
|
|
352
|
+
]);
|
|
353
|
+
const upStderrBytes = Buffer.concat([
|
|
354
|
+
Buffer.from("stderr 诊断\n\0字节", "utf8"),
|
|
355
|
+
crypto.randomBytes(32),
|
|
356
|
+
]);
|
|
357
|
+
rt.send({ v: RELAY_PROTOCOL_VERSION, kind: "data", dir: "up", b64: upBytes.toString("base64") });
|
|
358
|
+
rt.send({
|
|
359
|
+
v: RELAY_PROTOCOL_VERSION,
|
|
360
|
+
kind: "data",
|
|
361
|
+
dir: "up-stderr",
|
|
362
|
+
b64: upStderrBytes.toString("base64"),
|
|
363
|
+
});
|
|
364
|
+
rt.send({ kind: "exit", code: 3 });
|
|
365
|
+
const res = await waitForExit(child);
|
|
366
|
+
expect(res.stdout).toEqual(upBytes);
|
|
367
|
+
expect(res.stderr).toEqual(upStderrBytes.toString("utf8"));
|
|
368
|
+
expect(res.code).toBe(3);
|
|
369
|
+
});
|
|
370
|
+
|
|
371
|
+
it("exit frame code propagation flushes stdout first", { timeout: 10_000 }, async () => {
|
|
372
|
+
const socketPath = makeSocketPath();
|
|
373
|
+
const rt = await startFakeRuntime(socketPath);
|
|
374
|
+
const child = spawnRelay({ socketPath, sessionId: "s", recordId: "r" });
|
|
375
|
+
await rt.handshakePromise;
|
|
376
|
+
const upBytes = Buffer.from("final bytes before exit\n", "utf8");
|
|
377
|
+
rt.send({ v: RELAY_PROTOCOL_VERSION, kind: "data", dir: "up", b64: upBytes.toString("base64") });
|
|
378
|
+
rt.send({ kind: "exit", code: 7 });
|
|
379
|
+
const res = await waitForExit(child);
|
|
380
|
+
expect(res.code).toBe(7);
|
|
381
|
+
expect(res.stdout).toEqual(upBytes);
|
|
382
|
+
});
|
|
383
|
+
|
|
384
|
+
it("exit frame signal propagation → close(null, SIGTERM)", { timeout: 10_000 }, async () => {
|
|
385
|
+
const socketPath = makeSocketPath();
|
|
386
|
+
const rt = await startFakeRuntime(socketPath);
|
|
387
|
+
const child = spawnRelay({ socketPath, sessionId: "s", recordId: "r" });
|
|
388
|
+
await rt.handshakePromise;
|
|
389
|
+
rt.send({ kind: "exit", signal: "SIGTERM" });
|
|
390
|
+
const res = await waitForExit(child);
|
|
391
|
+
expect(res.signal).toBe("SIGTERM");
|
|
392
|
+
expect(res.code).toBeNull();
|
|
393
|
+
});
|
|
394
|
+
|
|
395
|
+
it("socket closed by runtime → exit 12", { timeout: 10_000 }, async () => {
|
|
396
|
+
const socketPath = makeSocketPath();
|
|
397
|
+
const rt = await startFakeRuntime(socketPath);
|
|
398
|
+
const child = spawnRelay({ socketPath, sessionId: "s", recordId: "r" });
|
|
399
|
+
await rt.handshakePromise;
|
|
400
|
+
rt.destroyConn();
|
|
401
|
+
const res = await waitForExit(child);
|
|
402
|
+
expect(res.code).toBe(RELAY_EXIT_CODES.SOCKET_CLOSED);
|
|
403
|
+
expect(res.stderr).toContain("closed");
|
|
404
|
+
});
|
|
405
|
+
|
|
406
|
+
it("reject reason=version → exit 10 + reinstall recovery hint", { timeout: 10_000 }, async () => {
|
|
407
|
+
const socketPath = makeSocketPath();
|
|
408
|
+
const rt = await startFakeRuntime(socketPath, (_hs, r) => {
|
|
409
|
+
r.send({ kind: "reject", reason: "version", supported: [RELAY_PROTOCOL_VERSION] });
|
|
410
|
+
});
|
|
411
|
+
const child = spawnRelay({ socketPath, sessionId: "s", recordId: "r" });
|
|
412
|
+
const res = await waitForExit(child);
|
|
413
|
+
expect(res.code).toBe(RELAY_EXIT_CODES.VERSION_MISMATCH);
|
|
414
|
+
expect(res.stderr).toContain("version mismatch");
|
|
415
|
+
expect(res.stderr).toContain("重装应用");
|
|
416
|
+
});
|
|
417
|
+
|
|
418
|
+
it("reject with non-version reason → exit 12", { timeout: 10_000 }, async () => {
|
|
419
|
+
const socketPath = makeSocketPath();
|
|
420
|
+
const rt = await startFakeRuntime(socketPath, (_hs, r) => {
|
|
421
|
+
r.send({ kind: "reject", reason: "handshake_invalid" });
|
|
422
|
+
});
|
|
423
|
+
const child = spawnRelay({ socketPath, sessionId: "s", recordId: "r" });
|
|
424
|
+
const res = await waitForExit(child);
|
|
425
|
+
expect(res.code).toBe(RELAY_EXIT_CODES.SOCKET_CLOSED);
|
|
426
|
+
expect(res.stderr).toContain("handshake_invalid");
|
|
427
|
+
});
|
|
428
|
+
|
|
429
|
+
it("backpressure: 1MB random bytes survive full down→up roundtrip", { timeout: 60_000 }, async () => {
|
|
430
|
+
const socketPath = makeSocketPath();
|
|
431
|
+
const rt = await startFakeRuntime(socketPath);
|
|
432
|
+
const child = spawnRelay({ socketPath, sessionId: "s", recordId: "r" });
|
|
433
|
+
await rt.handshakePromise;
|
|
434
|
+
|
|
435
|
+
const payload = crypto.randomBytes(1024 * 1024);
|
|
436
|
+
child.child.stdin.write(payload);
|
|
437
|
+
await pollUntil(() => rt.downTotal() === payload.length, 30_000, "1MB down bytes");
|
|
438
|
+
const receivedDown = Buffer.concat(rt.downChunks);
|
|
439
|
+
expect(receivedDown).toEqual(payload);
|
|
440
|
+
|
|
441
|
+
// 同一 payload 分 64KB up 帧回发(驱动代理 socket→stdout 背压 + 行缓冲路径)
|
|
442
|
+
await sendLargeUp(rt, receivedDown);
|
|
443
|
+
rt.send({ kind: "exit", code: 0 });
|
|
444
|
+
const res = await waitForExit(child);
|
|
445
|
+
expect(res.code).toBe(0);
|
|
446
|
+
expect(res.stdout).toEqual(payload);
|
|
447
|
+
});
|
|
448
|
+
});
|