@zhushanwen/subagent-core 0.6.0 → 0.7.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.
Files changed (278) hide show
  1. package/README.md +1 -1
  2. package/dist/chunk-KXVBIVOU.js +16 -0
  3. package/dist/chunk-T2SYBW3I.js +24 -0
  4. package/dist/chunk-VURUAGMM.js +2305 -0
  5. package/dist/{types-C3fE3R9x.d.cts → engine-discovery-scan-ocpM8FmI.d.cts} +770 -668
  6. package/dist/{types-C3fE3R9x.d.ts → engine-discovery-scan-ocpM8FmI.d.ts} +770 -668
  7. package/dist/execution/engine/engine-discovery-scan.cjs +2210 -0
  8. package/dist/execution/engine/engine-discovery-scan.d.cts +4 -0
  9. package/dist/execution/engine/engine-discovery-scan.d.ts +4 -0
  10. package/dist/execution/engine/engine-discovery-scan.js +20 -0
  11. package/dist/execution/engine/paths.cjs +6 -23
  12. package/dist/execution/engine/paths.d.cts +1 -8
  13. package/dist/execution/engine/paths.d.ts +1 -8
  14. package/dist/execution/engine/paths.js +1 -1
  15. package/dist/execution/relay-env.cjs +12 -28
  16. package/dist/execution/relay-env.d.cts +1 -33
  17. package/dist/execution/relay-env.d.ts +1 -33
  18. package/dist/execution/relay-env.js +5 -3
  19. package/dist/index.cjs +14045 -16059
  20. package/dist/index.d.cts +1035 -1579
  21. package/dist/index.d.ts +1035 -1579
  22. package/dist/index.js +9838 -13800
  23. package/dist.bundle/index.cjs +28875 -30323
  24. package/package.json +20 -26
  25. package/src/__tests__/record-store-last-line.test.ts +16 -7
  26. package/src/core/error-message.ts +7 -6
  27. package/src/core/host-services.ts +8 -2
  28. package/src/core/notify-ports.ts +17 -2
  29. package/src/execution/__tests__/chat-engine-routing.test.ts +62 -28
  30. package/src/execution/__tests__/chat-round-first-round-watchdog.test.ts +255 -0
  31. package/src/execution/__tests__/collect-coordinator-service.test.ts +36 -47
  32. package/src/execution/__tests__/collect-mixed-dispatch.test.ts +20 -53
  33. package/src/execution/__tests__/delivery-methods.test.ts +179 -237
  34. package/src/execution/__tests__/execute-and-await-worktree.test.ts +0 -2
  35. package/src/execution/__tests__/execute-nesting.test.ts +20 -13
  36. package/src/execution/__tests__/explicit-agent-ref-guard.test.ts +20 -33
  37. package/src/execution/__tests__/gc-timer.test.ts +7 -22
  38. package/src/execution/__tests__/get-record-for-action-restart.test.ts +20 -10
  39. package/src/execution/__tests__/helpers/fake-engine-port.ts +187 -0
  40. package/src/execution/__tests__/helpers/spawn-mock.ts +36 -9
  41. package/src/execution/__tests__/helpers/subagent-service-mocks.ts +1 -1
  42. package/src/execution/__tests__/idle-gc.test.ts +200 -0
  43. package/src/execution/__tests__/lifecycle-predicates.test.ts +26 -21
  44. package/src/execution/__tests__/nested-visibility-env-propagation.test.ts +5 -2
  45. package/src/execution/__tests__/reconcile-sweep.test.ts +200 -0
  46. package/src/execution/__tests__/record-store.test.ts +60 -6
  47. package/src/execution/__tests__/recursive-visibility-baseline.test.ts +20 -13
  48. package/src/execution/__tests__/round-supervisor.test.ts +293 -0
  49. package/src/execution/__tests__/session-pending.test.ts +119 -17
  50. package/src/execution/__tests__/stream-sink-retirement.test.ts +10 -10
  51. package/src/execution/__tests__/subagent-service-multiproc-guard.test.ts +1 -11
  52. package/src/execution/__tests__/subagent-service-notify-gate.test.ts +33 -30
  53. package/src/execution/__tests__/subagent-service-parent-guard.test.ts +2 -9
  54. package/src/execution/__tests__/subagent-service-recovery-bounds.test.ts +59 -129
  55. package/src/execution/__tests__/subagent-service.test.ts +2 -2
  56. package/src/execution/__tests__/subprocess-agent-runner-routing.test.ts +109 -7
  57. package/src/execution/__tests__/subprocess-agent-runner.test.ts +108 -36
  58. package/src/execution/__tests__/sync-collect-recovery.test.ts +21 -36
  59. package/src/execution/__tests__/workflow-state-root.test.ts +232 -0
  60. package/src/execution/agent-registry.ts +6 -2
  61. package/src/execution/dialog-queue.ts +6 -73
  62. package/src/execution/engine/__tests__/common/capability-gate.test.ts +115 -15
  63. package/src/execution/engine/__tests__/common/errors.test.ts +11 -18
  64. package/src/execution/engine/__tests__/common/kill-chain.test.ts +7 -0
  65. package/src/execution/engine/__tests__/common/nesting-guard.test.ts +9 -3
  66. package/src/execution/engine/__tests__/common/session-view-service.test.ts +90 -3
  67. package/src/execution/engine/__tests__/conformance/H9-test-disposition.md +116 -0
  68. package/src/execution/engine/__tests__/conformance/__fixtures__/engine-protocol/fake-engine-protocol.mjs +377 -0
  69. package/src/execution/engine/__tests__/conformance/__fixtures__/engine-protocol/recorded.fixture.json +331 -0
  70. package/src/execution/engine/__tests__/conformance/__fixtures__/engine-protocol/smoke-run.fixture.json +213 -0
  71. package/src/execution/engine/__tests__/conformance/chat-round-protocol.test.ts +230 -0
  72. package/src/execution/engine/__tests__/conformance/contract.abort.test.ts +69 -42
  73. package/src/execution/engine/__tests__/conformance/contract.agent-events.test.ts +4 -81
  74. package/src/execution/engine/__tests__/conformance/contract.probe.test.ts +67 -44
  75. package/src/execution/engine/__tests__/conformance/contract.read-degradation.test.ts +81 -54
  76. package/src/execution/engine/__tests__/conformance/engine-conformance.live.test.ts +133 -70
  77. package/src/execution/engine/__tests__/conformance/engine-crash.test.ts +143 -0
  78. package/src/execution/engine/__tests__/conformance/fake-engine-capabilities.ts +19 -0
  79. package/src/execution/engine/__tests__/conformance/golden-replay.pi.test.ts +7 -2
  80. package/src/execution/engine/__tests__/conformance/golden-replay.zcode.test.ts +6 -5
  81. package/src/execution/engine/__tests__/conformance/protocol-blackbox.test.ts +398 -0
  82. package/src/execution/engine/__tests__/conformance/registry-fork-filter.test.ts +221 -0
  83. package/src/execution/engine/__tests__/conformance/round-liveness-supervisor.test.ts +302 -0
  84. package/src/execution/engine/__tests__/conformance/static-spawn-guard.test.ts +58 -0
  85. package/src/execution/engine/__tests__/engine-discovery-scan.test.ts +558 -0
  86. package/src/execution/engine/__tests__/host-task-spec.test.ts +45 -0
  87. package/src/execution/engine/__tests__/model-ref-split.test.ts +74 -0
  88. package/src/execution/engine/__tests__/registry.test.ts +206 -1
  89. package/src/execution/engine/__tests__/routing.test.ts +97 -0
  90. package/src/execution/engine/__tests__/run-failure-worktree-cleanup.test.ts +97 -0
  91. package/src/execution/engine/client/__tests__/__fixtures__/fake-engine.mjs +294 -0
  92. package/src/execution/engine/client/__tests__/engine-client.test.ts +516 -0
  93. package/src/execution/engine/client/__tests__/mirror.test.ts +67 -0
  94. package/src/execution/engine/client/__tests__/pid-file.test.ts +257 -0
  95. package/src/execution/engine/client/__tests__/protocol-closure.test.ts +95 -0
  96. package/src/execution/engine/client/__tests__/remote-engine.test.ts +457 -0
  97. package/src/execution/engine/client/client-options.ts +103 -0
  98. package/src/execution/engine/client/engine-client.ts +687 -0
  99. package/src/execution/engine/client/mirror.ts +167 -0
  100. package/src/execution/engine/client/pid-file.ts +392 -0
  101. package/src/execution/engine/client/reaper.ts +95 -0
  102. package/src/execution/engine/client/remote-engine.ts +441 -0
  103. package/src/execution/engine/client/reverse-router.ts +255 -0
  104. package/src/execution/engine/common/capability-gate.ts +109 -22
  105. package/src/execution/engine/common/errors.ts +9 -25
  106. package/src/execution/engine/common/event-journal.ts +4 -50
  107. package/src/execution/engine/common/journal-replay.ts +3 -1
  108. package/src/execution/engine/common/kill-chain.ts +18 -251
  109. package/src/execution/engine/common/nesting-guard.ts +18 -114
  110. package/src/execution/engine/common/pool-manager.ts +4 -0
  111. package/src/execution/engine/common/session-view-service.ts +56 -84
  112. package/src/execution/engine/config.ts +151 -0
  113. package/src/execution/engine/d8-compat.ts +346 -0
  114. package/src/execution/engine/engine-discovery-roots.ts +107 -0
  115. package/src/execution/engine/engine-discovery-scan.ts +269 -0
  116. package/src/execution/engine/engine-discovery.ts +30 -7
  117. package/src/execution/engine/engine-inspect-package.ts +282 -0
  118. package/src/execution/engine/engine-manifest.ts +244 -0
  119. package/src/execution/engine/host/__tests__/host-askuser-endpoint.test.ts +123 -0
  120. package/src/execution/engine/host/__tests__/host-bridge.test.ts +135 -0
  121. package/src/execution/engine/host/__tests__/spawned-children.test.ts +73 -0
  122. package/src/execution/engine/host/host-bridge.ts +150 -0
  123. package/src/execution/engine/host/host-ui-endpoint.ts +47 -0
  124. package/src/execution/engine/host/pi-host-binding.ts +91 -0
  125. package/src/execution/engine/host/spawned-children.ts +139 -0
  126. package/src/execution/engine/host-task-spec.ts +29 -2
  127. package/src/execution/engine/model-validation.ts +55 -2
  128. package/src/execution/engine/paths.ts +16 -41
  129. package/src/execution/engine/port.ts +48 -2
  130. package/src/execution/engine/registry.ts +153 -34
  131. package/src/execution/engine/routing.ts +225 -52
  132. package/src/execution/engine/types.ts +25 -200
  133. package/src/execution/finalize-record.ts +25 -0
  134. package/src/execution/idle-gc.ts +89 -14
  135. package/src/execution/lifecycle-manager.ts +10 -7
  136. package/src/execution/lifecycle-predicates.ts +10 -8
  137. package/src/execution/record-store.ts +29 -2
  138. package/src/execution/relay-env.ts +19 -36
  139. package/src/execution/round-supervisor/domain.ts +89 -0
  140. package/src/execution/round-supervisor/index.ts +33 -0
  141. package/src/execution/round-supervisor/notify-accounting.ts +87 -0
  142. package/src/execution/round-supervisor/reconcile-sweep.ts +235 -0
  143. package/src/execution/round-supervisor/service-binding.test.ts +661 -0
  144. package/src/execution/round-supervisor/service-binding.ts +273 -0
  145. package/src/execution/round-supervisor/supervisor.ts +426 -0
  146. package/src/execution/session-pending.ts +68 -74
  147. package/src/execution/settled-watchdog.ts +39 -0
  148. package/src/execution/subagent-service.ts +746 -400
  149. package/src/execution/subprocess-agent-runner.ts +16 -8
  150. package/src/execution/types.ts +41 -117
  151. package/src/execution/ui-channels.ts +13 -214
  152. package/src/execution/ui-request-handler-factory.ts +7 -4
  153. package/src/execution/ui-request-observability.ts +2 -2
  154. package/src/execution/workflow-state-root.ts +67 -0
  155. package/src/execution/worktree-git-ops.ts +5 -0
  156. package/src/execution/worktree-manager.ts +11 -1
  157. package/src/index.ts +55 -26
  158. package/src/orchestration/__tests__/execute-agent-call.test.ts +1 -1
  159. package/src/orchestration/execute-agent-call.ts +1 -1
  160. package/src/orchestration/file-run-store.ts +144 -59
  161. package/src/orchestration/models/types.ts +43 -42
  162. package/src/shared/zcode-model-ref.ts +31 -0
  163. package/dist/chunk-43ONBFZX.js +0 -240
  164. package/dist/chunk-A4IVZWVX.js +0 -31
  165. package/dist/chunk-APZY4IME.js +0 -27
  166. package/dist/chunk-V3VHZ2VX.js +0 -59
  167. package/dist/execution/engine/engines/zcode/constants.cjs +0 -107
  168. package/dist/execution/engine/engines/zcode/constants.d.cts +0 -135
  169. package/dist/execution/engine/engines/zcode/constants.d.ts +0 -135
  170. package/dist/execution/engine/engines/zcode/constants.js +0 -54
  171. package/dist/execution/engine/engines/zcode/reader.cjs +0 -276
  172. package/dist/execution/engine/engines/zcode/reader.d.cts +0 -21
  173. package/dist/execution/engine/engines/zcode/reader.d.ts +0 -21
  174. package/dist/execution/engine/engines/zcode/reader.js +0 -9
  175. package/src/__tests__/append-system-prompt-assembly.test.ts +0 -243
  176. package/src/__tests__/fr4-get-state-handshake.test.ts +0 -125
  177. package/src/__tests__/session-runner.test.ts +0 -69
  178. package/src/execution/__tests__/ask-user-transit-e2e.test.ts +0 -490
  179. package/src/execution/__tests__/chatmode-first-round-closure-spawn.test.ts +0 -191
  180. package/src/execution/__tests__/descendant-sweep-guards.test.ts +0 -220
  181. package/src/execution/__tests__/descendant-sweep.test.ts +0 -269
  182. package/src/execution/__tests__/engine-model-validation.test.ts +0 -741
  183. package/src/execution/__tests__/epipe-fallback.test.ts +0 -248
  184. package/src/execution/__tests__/execution-runtime-face.test.ts +0 -272
  185. package/src/execution/__tests__/get-state-handshake.test.ts +0 -127
  186. package/src/execution/__tests__/helpers/session-runner-mocks.ts +0 -113
  187. package/src/execution/__tests__/keep-alive-no-progress.test.ts +0 -280
  188. package/src/execution/__tests__/kill-all-escalation.test.ts +0 -196
  189. package/src/execution/__tests__/max-turns-to-watchdog-ms.test.ts +0 -113
  190. package/src/execution/__tests__/output-collector.test.ts +0 -469
  191. package/src/execution/__tests__/pi-invocation.test.ts +0 -166
  192. package/src/execution/__tests__/recursive-visibility-env.test.ts +0 -149
  193. package/src/execution/__tests__/rpc-mode.test.ts +0 -89
  194. package/src/execution/__tests__/run-and-finalize-anchoring.test.ts +0 -387
  195. package/src/execution/__tests__/run-and-finalize-chatmode.test.ts +0 -277
  196. package/src/execution/__tests__/run-spawn-chatmode-settled.test.ts +0 -254
  197. package/src/execution/__tests__/run-spawn-edges.test.ts +0 -1079
  198. package/src/execution/__tests__/run-spawn-integration.test.ts +0 -933
  199. package/src/execution/__tests__/run-spawn-resume.test.ts +0 -322
  200. package/src/execution/__tests__/run-spawn-rpc-mode.test.ts +0 -196
  201. package/src/execution/__tests__/run-spawn-stdout-callback-throw.test.ts +0 -207
  202. package/src/execution/__tests__/service-kill-escalation.test.ts +0 -91
  203. package/src/execution/__tests__/session-runner-branch-cache-lru.test.ts +0 -110
  204. package/src/execution/__tests__/session-runner-close-prune.test.ts +0 -181
  205. package/src/execution/__tests__/session-runner-dispatch.test.ts +0 -489
  206. package/src/execution/__tests__/session-runner-epipe.test.ts +0 -179
  207. package/src/execution/__tests__/session-runner-heartbeat-idle-fallback.test.ts +0 -227
  208. package/src/execution/__tests__/session-runner-lifecycle-helpers.test.ts +0 -290
  209. package/src/execution/__tests__/session-runner-schema-env.test.ts +0 -352
  210. package/src/execution/__tests__/settled-watchdog.test.ts +0 -524
  211. package/src/execution/__tests__/spawn-args.test.ts +0 -446
  212. package/src/execution/__tests__/spawn-event-adapter-rpc.test.ts +0 -192
  213. package/src/execution/__tests__/spawn-event-adapter.test.ts +0 -167
  214. package/src/execution/__tests__/spawn-worktree-guidance.test.ts +0 -208
  215. package/src/execution/__tests__/spawned-children.test.ts +0 -236
  216. package/src/execution/__tests__/start-sync-model-guard.test.ts +0 -150
  217. package/src/execution/__tests__/stdin-writer.test.ts +0 -464
  218. package/src/execution/__tests__/subagent-service-message-close.test.ts +0 -693
  219. package/src/execution/__tests__/temp-prompt.test.ts +0 -53
  220. package/src/execution/__tests__/timeout-integration.test.ts +0 -616
  221. package/src/execution/__tests__/turn-limiter-semantics.test.ts +0 -194
  222. package/src/execution/__tests__/turn-limiter.test.ts +0 -65
  223. package/src/execution/__tests__/ui-request-handler.test.ts +0 -205
  224. package/src/execution/__tests__/ui-request-queue.test.ts +0 -298
  225. package/src/execution/__tests__/worktree-pid-registration.integration.test.ts +0 -230
  226. package/src/execution/engine/__tests__/common/schema-emulation.test.ts +0 -128
  227. package/src/execution/engine/__tests__/common/session-view-service-zcode-dbpath.test.ts +0 -149
  228. package/src/execution/engine/__tests__/conformance/__fixtures__/pi-golden-events.json +0 -28
  229. package/src/execution/engine/__tests__/conformance/zcode-appserver-harness.ts +0 -128
  230. package/src/execution/engine/__tests__/paths.test.ts +0 -39
  231. package/src/execution/engine/common/schema-emulation.ts +0 -189
  232. package/src/execution/engine/common/session-view-projection.ts +0 -51
  233. package/src/execution/engine/engines/pi/__tests__/pi-engine.test.ts +0 -615
  234. package/src/execution/engine/engines/pi/__tests__/reader.test.ts +0 -155
  235. package/src/execution/engine/engines/pi/__tests__/spawn-opts-direct.test.ts +0 -257
  236. package/src/execution/engine/engines/pi/argv-mirror.ts +0 -135
  237. package/src/execution/engine/engines/pi/get-state-handshake.ts +0 -179
  238. package/src/execution/engine/engines/pi/output-collector.ts +0 -317
  239. package/src/execution/engine/engines/pi/pi-engine.ts +0 -811
  240. package/src/execution/engine/engines/pi/pi-invocation.ts +0 -120
  241. package/src/execution/engine/engines/pi/reader.ts +0 -59
  242. package/src/execution/engine/engines/pi/registration.ts +0 -37
  243. package/src/execution/engine/engines/pi/session-runner.ts +0 -2840
  244. package/src/execution/engine/engines/pi/spawn-event-adapter.ts +0 -404
  245. package/src/execution/engine/engines/pi/stdin-writer.ts +0 -199
  246. package/src/execution/engine/engines/pi/temp-prompt.ts +0 -62
  247. package/src/execution/engine/engines/pi/turn-limiter.ts +0 -102
  248. package/src/execution/engine/engines/zcode/__tests__/__fixtures__/fake-appserver.mjs +0 -301
  249. package/src/execution/engine/engines/zcode/__tests__/__fixtures__/zcode-golden-appserver.json +0 -36
  250. package/src/execution/engine/engines/zcode/__tests__/appserver-launcher.test.ts +0 -321
  251. package/src/execution/engine/engines/zcode/__tests__/connection.test.ts +0 -473
  252. package/src/execution/engine/engines/zcode/__tests__/parser.test.ts +0 -43
  253. package/src/execution/engine/engines/zcode/__tests__/preparer.test.ts +0 -124
  254. package/src/execution/engine/engines/zcode/__tests__/reader.test.ts +0 -210
  255. package/src/execution/engine/engines/zcode/__tests__/registration.test.ts +0 -71
  256. package/src/execution/engine/engines/zcode/__tests__/session-channel-dispose-harvest.test.ts +0 -247
  257. package/src/execution/engine/engines/zcode/__tests__/session-channel-turn-timers.test.ts +0 -451
  258. package/src/execution/engine/engines/zcode/__tests__/session-channel.test.ts +0 -792
  259. package/src/execution/engine/engines/zcode/__tests__/zcode-engine-appserver.test.ts +0 -782
  260. package/src/execution/engine/engines/zcode/__tests__/zcode-engine-degrade.test.ts +0 -168
  261. package/src/execution/engine/engines/zcode/__tests__/zcode-engine-dispose.test.ts +0 -210
  262. package/src/execution/engine/engines/zcode/__tests__/zcode-engine-retry.test.ts +0 -353
  263. package/src/execution/engine/engines/zcode/__tests__/zcode-engine-status.test.ts +0 -282
  264. package/src/execution/engine/engines/zcode/__tests__/zcode-engine-timeout.test.ts +0 -372
  265. package/src/execution/engine/engines/zcode/__tests__/zcode-engine.live.test.ts +0 -145
  266. package/src/execution/engine/engines/zcode/appserver-launcher.ts +0 -167
  267. package/src/execution/engine/engines/zcode/connection.ts +0 -598
  268. package/src/execution/engine/engines/zcode/constants.ts +0 -176
  269. package/src/execution/engine/engines/zcode/golden-sample.ts +0 -47
  270. package/src/execution/engine/engines/zcode/parser.ts +0 -102
  271. package/src/execution/engine/engines/zcode/preparer.ts +0 -235
  272. package/src/execution/engine/engines/zcode/reader.ts +0 -381
  273. package/src/execution/engine/engines/zcode/registration.ts +0 -37
  274. package/src/execution/engine/engines/zcode/session-channel.ts +0 -968
  275. package/src/execution/engine/engines/zcode/zcode-engine.ts +0 -1431
  276. package/src/execution/round-settlement.ts +0 -93
  277. package/src/execution/ui-request-queue.ts +0 -215
  278. package/src/shared/schema-env.ts +0 -44
@@ -1,150 +0,0 @@
1
- // src/execution/__tests__/start-sync-model-guard.test.ts
2
- //
3
- // [U1 验收 3] start 同步期裁决:非全等 model 入参在 start 工具调用同步期 isError——
4
- // 无 spawn、无子 session、record 不落盘。
5
- //
6
- // 用真实 SubagentService(tmpdir + mock pi)走 execute 全链路,断言:
7
- // 1. execute 在 IDENTITY 解析(resolveModel 裁决)阶段 reject(问句式报错);
8
- // 2. buildSpawnArgs 从未被调用(vi.mock spy 包装真实实现)——spawn 前置守卫的结构性证据;
9
- // 3. node:child_process.spawn 从未被调用——无子进程;
10
- // 4. pi.appendEntry 从未被调用——record 未创建(emitPendingRegister 未发生)。
11
- //
12
- // 放行路径(全等 → 裁决通过)由 model-ref.test.ts / model-resolver.test.ts 锁定,
13
- // 全链路放行的 spawn 行为由 run-spawn-* 契约测试覆盖。
14
-
15
- import { spawn } from "node:child_process";
16
- import * as fs from "node:fs";
17
- import * as os from "node:os";
18
- import * as path from "node:path";
19
-
20
- import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
21
-
22
- vi.mock("node:child_process", async () => {
23
- const actual = await import("node:child_process");
24
- return {
25
- ...actual,
26
- spawn: vi.fn(() => {
27
- throw new Error("spawn must not be called on sync-model rejection");
28
- }),
29
- };
30
- });
31
-
32
- // buildSpawnArgs 包装为 spy(保留真实实现)——「非全等拒单不触达 spawn 参数组装」的承重断言。
33
- vi.mock("../engine/engines/pi/session-runner.ts", async (importOriginal) => {
34
- const actual = await importOriginal<typeof import("../engine/engines/pi/session-runner.ts")>();
35
- return { ...actual, buildSpawnArgs: vi.fn(actual.buildSpawnArgs) };
36
- });
37
-
38
- import { ModelConfigService } from "../model-config-service.ts";
39
- import type { ModelInfo, ModelRegistryLike } from "../model-resolver.ts";
40
- import { buildSpawnArgs } from "../engine/engines/pi/session-runner.ts";
41
- import type { PiLike } from "../subagent-service.ts";
42
- import { SubagentService } from "../subagent-service.ts";
43
-
44
- const mockSpawn = vi.mocked(spawn);
45
- const mockBuildSpawnArgs = vi.mocked(buildSpawnArgs);
46
-
47
- // ── 工具 ──
48
-
49
- function makeModel(over: Partial<ModelInfo> = {}): ModelInfo {
50
- return {
51
- id: over.id ?? "GLM-5.3-Flash",
52
- name: over.name ?? "GLM 5.3 Flash",
53
- provider: over.provider ?? "zai-coding-cn",
54
- reasoning: over.reasoning ?? false,
55
- ...over,
56
- };
57
- }
58
-
59
- /** registry 快照:真实形态(大小写混合 id),无孪生(P-A2 放行快照形态)。 */
60
- function makeRegistry(models: ModelInfo[]): ModelRegistryLike {
61
- return {
62
- getAvailable: () => models,
63
- find: (provider, modelId) => models.find((m) => m.provider === provider && m.id === modelId),
64
- hasConfiguredAuth: () => true,
65
- };
66
- }
67
-
68
- function makePi(): PiLike {
69
- return {
70
- appendEntry: vi.fn(),
71
- events: { emit: vi.fn() },
72
- sendMessage: vi.fn(),
73
- } as unknown as PiLike;
74
- }
75
-
76
- describe("start 同步期裁决(U1 验收 3:非全等 → isError 且无 spawn 无子 session)", () => {
77
- let tmpDir: string;
78
- let service: SubagentService;
79
- let pi: PiLike;
80
-
81
- beforeEach(() => {
82
- vi.clearAllMocks();
83
- tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "sw-start-guard-"));
84
- const modelService = new ModelConfigService({ agentDir: tmpDir, cwd: tmpDir });
85
- modelService.initModel({
86
- modelRegistry: makeRegistry([makeModel()]),
87
- sessionId: "guard-session",
88
- });
89
- service = new SubagentService({ cwd: tmpDir, modelService });
90
- pi = makePi();
91
- service.initSession({ pi, sessionId: "guard-session" });
92
- });
93
-
94
- afterEach(() => {
95
- vi.restoreAllMocks();
96
- fs.rmSync(tmpDir, { recursive: true, force: true, maxRetries: 5, retryDelay: 20 });
97
- });
98
-
99
- it("小写变体入参 → execute 同步 reject(问句式报错),buildSpawnArgs/spawn/appendEntry 均未被调", async () => {
100
- await expect(
101
- service.execute({
102
- task: "probe task",
103
- slug: "guard",
104
- model: "zai-coding-cn/glm-5.3-flash",
105
- }),
106
- ).rejects.toThrow(/is not a registry entry.*Did you mean one of these\?/s);
107
-
108
- // spawn 链路零触达:参数组装(buildSpawnArgs)与进程创建(spawn)都未发生
109
- expect(mockBuildSpawnArgs).not.toHaveBeenCalled();
110
- expect(mockSpawn).not.toHaveBeenCalled();
111
- // record 未创建(emitPendingRegister 未发生)→ 无子 session 前置状态
112
- expect(pi.appendEntry).not.toHaveBeenCalled();
113
- });
114
-
115
- it("错误含 case variant 首位建议 + 继承指引(可直接重发的合法串)", async () => {
116
- let msg = "";
117
- try {
118
- await service.execute({
119
- task: "probe task",
120
- slug: "guard",
121
- model: "zai-coding-cn/glm-5.3-flash",
122
- });
123
- } catch (e) {
124
- msg = (e as Error).message;
125
- }
126
- expect(msg).toContain('zai-coding-cn/GLM-5.3-Flash ← case variant of "glm-5.3-flash"');
127
- expect(msg).toMatch(/Or omit the `model` param to inherit the main agent model\./);
128
- });
129
-
130
- it("全等入参通过裁决(reject 不发生,放行链路触达 spawn 参数组装)——守卫零误伤对照", async () => {
131
- // 放行路径会进入轮次 kick-off(detached);execute resolve 即视为裁决放行。
132
- // spawn 本身由 FakeChild 缺失抛错收口——本断言只关心「越过了同步裁决」:
133
- // execute 不 reject,且 buildSpawnArgs 已被调(或即将被调的 record 已创建)。
134
- const promise = service.execute({
135
- task: "probe task",
136
- slug: "guard-exact",
137
- model: "zai-coding-cn/GLM-5.3-Flash",
138
- });
139
- // 放行路径:裁决不抛(execute 最终可能因 mock 环境子进程收尾而 reject,
140
- // 但错误不能是模型裁决错误)
141
- try {
142
- await promise;
143
- } catch (e) {
144
- expect((e as Error).message).not.toMatch(/is not a registry entry/);
145
- expect((e as Error).message).not.toMatch(/ambiguous case variants/);
146
- }
147
- // 全等放行 → record 已创建(emitPendingRegister 发生)——与拒单路径形成对照
148
- expect(pi.appendEntry).toHaveBeenCalled();
149
- });
150
- });
@@ -1,464 +0,0 @@
1
- // src/execution/__tests__/stdin-writer.test.ts
2
- //
3
- // stdin-writer.ts 单元测试——覆盖 respond(UiResponse 4 分支 + 序列化降级)+
4
- // sendPromptCommand + sendGetStateCommand + writeStdinLine 背压。
5
- //
6
- // stdin-writer 是 spawn 改造的叶子 helper,向 rpc 子进程 stdin 写 JSON 命令。
7
- // 与 run-spawn-integration.test.ts 的集成视角不同:本文件只测「给定 child + 入参,
8
- // stdin 收到的确切字节内容」,逐分支验证协议格式正确性。
9
- //
10
- // 测试策略:
11
- // - 用 PassThrough 模拟 child.stdin(buffered,可事后读出 write 的字节)。
12
- // - 用 minimal ChildProcess 形状({ stdin: PassThrough })作 respond/sendPrompt 入参。
13
- // - respond 的 4 分支:value/confirmed/cancelled/ack。ack 不写 stdin(fire-and-forget)。
14
- // - JSON.stringify 降级(#16):out.value 含循环引用 → 降级 cancelled + warn。
15
- // - sendPromptCommand:写 {type:"prompt",message,id} 一行。
16
- // - sendGetStateCommand:返回 reqId,写 {type:"get_state",id} 一行。
17
- // - writeStdinLine 背压:mock child.stdin.write 返回 false → warn 但不 throw。
18
-
19
- import type { ChildProcess } from "node:child_process";
20
- import { PassThrough } from "node:stream";
21
-
22
- import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
23
-
24
- // Mock 共享 logger,让 logger.warn 可被 spy(源码已从 console.warn 改为 logger.warn)
25
- const { loggerMock } = vi.hoisted(() => ({
26
- loggerMock: {
27
- debug: vi.fn(),
28
- warn: vi.fn(),
29
- error: vi.fn(),
30
- },
31
- }));
32
- vi.mock("../../core/logger.ts", () => ({
33
- getLogger: () => loggerMock,
34
- }));
35
-
36
- import { respond, sendGetStateCommand, sendPromptCommand } from "../engine/engines/pi/stdin-writer.ts";
37
-
38
- // ── helpers ──
39
-
40
- /** 用 PassThrough 构造最小合法的 ChildProcess(只测 stdin 写入)。 */
41
- function makeChild(overrides: Partial<Pick<ChildProcess, "stdin">> = {}): ChildProcess {
42
- return {
43
- stdin: new PassThrough(),
44
- ...overrides,
45
- } as unknown as ChildProcess;
46
- }
47
-
48
- /**
49
- * 读出 child.stdin 已缓冲的全部字节(字符串)。
50
- *
51
- * PassThrough 默认是 flowing 模式,attach 'data' listener 后会 flush 缓冲。
52
- * 这里用 readable 状态:pause + read 取出全部缓冲。
53
- */
54
- function readStdin(child: ChildProcess): string {
55
- const stream = child.stdin as unknown as PassThrough;
56
- stream.pause();
57
- return stream.read()?.toString() ?? "";
58
- }
59
-
60
- /** 从 child.stdin 已缓冲内容按行拆分(去空行),返回 JSON.parse 后的对象数组。 */
61
- function readStdinLines(child: ChildProcess): unknown[] {
62
- const text = readStdin(child);
63
- return text
64
- .split("\n")
65
- .map((l) => l.trim())
66
- .filter((l) => l.length > 0)
67
- .map((l) => JSON.parse(l));
68
- }
69
-
70
- // vi.fn() 的返回类型原生含 .mock.calls——无需双重断言(ReturnType<typeof vi.fn> 已是强类型)。
71
- let warnSpy: ReturnType<typeof vi.fn>;
72
-
73
- beforeEach(() => {
74
- // stdin-writer 在背压 / 序列化失败时 logger.warn;测试 mock logger 避免噪声,且可断言调用。
75
- loggerMock.warn.mockClear();
76
- warnSpy = loggerMock.warn;
77
- });
78
-
79
- afterEach(() => {
80
- vi.restoreAllMocks();
81
- });
82
-
83
- // ============================================================
84
- // respond:UiResponse 4 分支
85
- // ============================================================
86
-
87
- describe("respond — UiResponse 4 分支", () => {
88
- describe("value 分支", () => {
89
- it("out={value:'hello'} → stdin 收到 extension_ui_response 含 value 字段", () => {
90
- const child = makeChild();
91
- respond(child, "req-1", { value: "hello" });
92
-
93
- const lines = readStdinLines(child);
94
- expect(lines).toHaveLength(1);
95
- expect(lines[0]).toEqual({ type: "extension_ui_response", id: "req-1", value: "hello" });
96
- });
97
-
98
- it("value 为含 JSON 特殊字符的字符串 → 原样透传(不二次转义)", () => {
99
- // out.value 是字符串,JSON.stringify({value: out.value}) 会正确序列化。
100
- // 关键:out.value 本身不被 JSON.parse 二次处理——它就是字符串值。
101
- const child = makeChild();
102
- const payload = JSON.stringify({ q: "ans", n: 1 }); // 合法 JSON 字符串作为 value
103
- respond(child, "req-2", { value: payload });
104
-
105
- const lines = readStdinLines(child);
106
- expect(lines[0]).toEqual({ type: "extension_ui_response", id: "req-2", value: payload });
107
- });
108
- });
109
-
110
- describe("confirmed 分支", () => {
111
- it("out={confirmed:true} → stdin 收到 confirmed:true", () => {
112
- const child = makeChild();
113
- respond(child, "req-3", { confirmed: true });
114
-
115
- const lines = readStdinLines(child);
116
- expect(lines).toHaveLength(1);
117
- expect(lines[0]).toEqual({ type: "extension_ui_response", id: "req-3", confirmed: true });
118
- });
119
-
120
- it("out={confirmed:false} → stdin 收到 confirmed:false(用户拒绝 confirm)", () => {
121
- const child = makeChild();
122
- respond(child, "req-4", { confirmed: false });
123
-
124
- const lines = readStdinLines(child);
125
- expect(lines[0]).toEqual({ type: "extension_ui_response", id: "req-4", confirmed: false });
126
- });
127
- });
128
-
129
- describe("cancelled 分支", () => {
130
- it("out={cancelled:true} → stdin 收到 cancelled:true", () => {
131
- const child = makeChild();
132
- respond(child, "req-5", { cancelled: true });
133
-
134
- const lines = readStdinLines(child);
135
- expect(lines).toHaveLength(1);
136
- expect(lines[0]).toEqual({ type: "extension_ui_response", id: "req-5", cancelled: true });
137
- });
138
- });
139
-
140
- describe("ack 分支(fire-and-forget)", () => {
141
- it("out={ack:true} → 不写 stdin(SR-5:fire-and-forget 不期待响应)", () => {
142
- const child = makeChild();
143
- respond(child, "req-6", { ack: true });
144
-
145
- // ack 分支 line 保持 undefined → writeStdinLine 不被调 → stdin 无数据
146
- expect(readStdin(child)).toBe("");
147
- expect(warnSpy).not.toHaveBeenCalled();
148
- });
149
- });
150
- });
151
-
152
- // ============================================================
153
- // respond:JSON.stringify 降级(#16)
154
- // ============================================================
155
-
156
- describe("respond — JSON.stringify 失败降级为 cancelled (#16)", () => {
157
- it("out.value 含循环引用 → 降级 cancelled:true + warn,不让父进程崩溃", () => {
158
- // 构造循环引用对象:JSON.stringify 会抛 Converting circular structure to JSON
159
- const circular: Record<string, unknown> = { a: 1 };
160
- circular.self = circular;
161
-
162
- const child = makeChild();
163
- respond(child, "req-circular", { value: circular } as never);
164
-
165
- // 降级为 cancelled
166
- const lines = readStdinLines(child);
167
- expect(lines).toHaveLength(1);
168
- expect(lines[0]).toEqual({
169
- type: "extension_ui_response",
170
- id: "req-circular",
171
- cancelled: true,
172
- });
173
- // warn 被调用(含 request id)
174
- expect(warnSpy).toHaveBeenCalledTimes(1);
175
- const warnArg = warnSpy.mock.calls[0]?.[0] as string;
176
- expect(warnArg).toContain("req-circular");
177
- expect(warnArg).toContain("JSON.stringify failed");
178
- });
179
-
180
- it("out.value 含 BigInt → JSON.stringify 抛 → 降级 cancelled + warn", () => {
181
- // BigInt 不可 JSON 序列化(JSON.stringify 抛 TypeError: Do not know how to serialize a BigInt)
182
- const child = makeChild();
183
- respond(child, "req-bigint", { value: BigInt(123) } as never);
184
-
185
- const lines = readStdinLines(child);
186
- expect(lines[0]).toEqual({
187
- type: "extension_ui_response",
188
- id: "req-bigint",
189
- cancelled: true,
190
- });
191
- expect(warnSpy).toHaveBeenCalledTimes(1);
192
- });
193
-
194
- it("降级后的 cancelled 响应格式与正常 cancelled 分支一致(协议兼容)", () => {
195
- // 确保降级走的是同一个 cancelled 格式(子进程解析逻辑无需区分「真取消」vs「序列化失败」)
196
- const circular: Record<string, unknown> = {};
197
- circular.self = circular;
198
-
199
- const childFail = makeChild();
200
- const childCancel = makeChild();
201
- respond(childFail, "same-id", { value: circular } as never);
202
- respond(childCancel, "same-id", { cancelled: true });
203
-
204
- const failLine = readStdinLines(childFail)[0];
205
- const cancelLine = readStdinLines(childCancel)[0];
206
- expect(failLine).toEqual(cancelLine);
207
- });
208
- });
209
-
210
- // ============================================================
211
- // respond:signal.aborted 守卫
212
- // ============================================================
213
-
214
- describe("respond — signal 已 aborted 跳过写入", () => {
215
- it("signal.aborted=true → 不写 stdin", () => {
216
- const child = makeChild();
217
- const controller = new AbortController();
218
- controller.abort();
219
-
220
- respond(child, "req-aborted", { value: "x" }, controller.signal);
221
-
222
- expect(readStdin(child)).toBe("");
223
- });
224
-
225
- it("signal.aborted=false → 正常写入", () => {
226
- const child = makeChild();
227
- const controller = new AbortController();
228
-
229
- respond(child, "req-active", { value: "x" }, controller.signal);
230
-
231
- const lines = readStdinLines(child);
232
- expect(lines).toHaveLength(1);
233
- expect(lines[0]).toEqual({ type: "extension_ui_response", id: "req-active", value: "x" });
234
- });
235
- });
236
-
237
- // ============================================================
238
- // sendPromptCommand
239
- // ============================================================
240
-
241
- describe("sendPromptCommand", () => {
242
- it("写入 {type:'prompt',message,id} 一行,message 含完整 task 文本", () => {
243
- const child = makeChild();
244
- const task = "Task: do something complex\nwith newline";
245
- sendPromptCommand(child, task);
246
-
247
- const lines = readStdinLines(child);
248
- expect(lines).toHaveLength(1);
249
- const cmd = lines[0] as { type: string; message: string; id: string };
250
- expect(cmd.type).toBe("prompt");
251
- expect(cmd.message).toBe(task); // 多行 task 原样透传
252
- expect(typeof cmd.id).toBe("string");
253
- expect(cmd.id.length).toBeGreaterThan(0); // crypto.randomUUID 生成
254
- });
255
-
256
- it("每次调用生成不同 id(crypto.randomUUID)", () => {
257
- const child = makeChild();
258
- sendPromptCommand(child, "task-1");
259
- sendPromptCommand(child, "task-2");
260
-
261
- const lines = readStdinLines(child);
262
- expect(lines).toHaveLength(2);
263
- const id1 = (lines[0] as { id: string }).id;
264
- const id2 = (lines[1] as { id: string }).id;
265
- expect(id1).not.toBe(id2);
266
- });
267
-
268
- it("写入以 \\n 结尾(rpc 子进程按行读 stdin)", () => {
269
- const child = makeChild();
270
- sendPromptCommand(child, "task");
271
-
272
- // 直接查 raw 字节,验证末尾换行
273
- const raw = readStdin(child);
274
- expect(raw.endsWith("\n")).toBe(true);
275
- });
276
-
277
- it("child.stdin 已 destroyed → 静默跳过(guard 生效,不抛错)", () => {
278
- const stdin = new PassThrough();
279
- stdin.destroy();
280
- const child = { stdin } as unknown as ChildProcess;
281
-
282
- expect(() => sendPromptCommand(child, "task")).not.toThrow();
283
- // destroyed 后 write 无效,但函数安全返回
284
- });
285
-
286
- it("child.stdin 为 null/undefined → 静默跳过(guard 生效)", () => {
287
- const child = { stdin: null } as unknown as ChildProcess;
288
- expect(() => sendPromptCommand(child, "task")).not.toThrow();
289
- });
290
-
291
- // [V2 决策 3] streamingBehavior 可选参数:chatMode 统一投递热路径用 prompt+streamingBehavior
292
- it("options.streamingBehavior='followUp' → 写入 streamingBehavior:followUp 字段", () => {
293
- const child = makeChild();
294
- sendPromptCommand(child, "queue this", { streamingBehavior: "followUp" });
295
-
296
- const lines = readStdinLines(child);
297
- expect(lines).toHaveLength(1);
298
- const cmd = lines[0] as { type: string; message: string; streamingBehavior?: string };
299
- expect(cmd.type).toBe("prompt");
300
- expect(cmd.message).toBe("queue this");
301
- expect(cmd.streamingBehavior).toBe("followUp");
302
- });
303
-
304
- it("options.streamingBehavior='steer' → 写入 streamingBehavior:steer 字段", () => {
305
- const child = makeChild();
306
- sendPromptCommand(child, "interrupt now", { streamingBehavior: "steer" });
307
-
308
- const lines = readStdinLines(child);
309
- const cmd = lines[0] as { streamingBehavior?: string };
310
- expect(cmd.streamingBehavior).toBe("steer");
311
- });
312
-
313
- it("省略 options → 不写入 streamingBehavior 字段(向后兼容,首帧 prompt / 非 chatMode 调用方)", () => {
314
- const child = makeChild();
315
- sendPromptCommand(child, "first task");
316
-
317
- const lines = readStdinLines(child);
318
- const cmd = lines[0] as { streamingBehavior?: string };
319
- expect(cmd.streamingBehavior).toBeUndefined();
320
- });
321
- });
322
-
323
- // ============================================================
324
- // sendGetStateCommand
325
- // ============================================================
326
-
327
- describe("sendGetStateCommand", () => {
328
- it("写入 {type:'get_state',id} 一行并返回相同 id(用于匹配 response)", () => {
329
- const child = makeChild();
330
- const returnedId = sendGetStateCommand(child);
331
-
332
- const lines = readStdinLines(child);
333
- expect(lines).toHaveLength(1);
334
- const cmd = lines[0] as { type: string; id: string };
335
- expect(cmd.type).toBe("get_state");
336
- expect(cmd.id).toBe(returnedId); // 返回值与写入的 id 一致
337
- expect(typeof cmd.id).toBe("string");
338
- // get_state 命令不含其他字段(只有 type + id)
339
- expect(Object.keys(cmd).sort()).toEqual(["id", "type"]);
340
- });
341
-
342
- it("写入以 \\n 结尾", () => {
343
- const child = makeChild();
344
- sendGetStateCommand(child);
345
-
346
- const raw = readStdin(child);
347
- expect(raw.endsWith("\n")).toBe(true);
348
- });
349
-
350
- it("每次调用返回不同 id(crypto.randomUUID)", () => {
351
- const child = makeChild();
352
- const id1 = sendGetStateCommand(child);
353
- const id2 = sendGetStateCommand(child);
354
- expect(id1).not.toBe(id2);
355
- });
356
- });
357
-
358
- // ============================================================
359
- // writeStdinLine 背压(间接经 respond 测)
360
- // ============================================================
361
-
362
- describe("writeStdinLine 背压 — write 返回 false 时 warn 不 throw", () => {
363
- it("child.stdin.write 返回 false → warn 一次,函数正常返回(不 throw)", () => {
364
- // 构造 write 永远返回 false 的假 stream(模拟内核缓冲满/HWM 到达)
365
- // 保留 vi.fn 引用(经 PassThrough 视图后 write 的 mock 面不可达)
366
- const fakeWrite = vi.fn((_chunk: unknown) => false);
367
- const fakeStdin = {
368
- write: fakeWrite,
369
- destroyed: false,
370
- } as unknown as PassThrough;
371
- const child = { stdin: fakeStdin } as unknown as ChildProcess;
372
-
373
- expect(() => respond(child, "req-backpressure", { value: "x" })).not.toThrow();
374
-
375
- // write 被调一次(写入 command 行)
376
- expect(fakeWrite).toHaveBeenCalledTimes(1);
377
- const writtenArg = fakeWrite.mock.calls[0]![0] as string;
378
- expect(writtenArg).toContain("extension_ui_response");
379
- expect(writtenArg).toContain("req-backpressure");
380
- expect(writtenArg.endsWith("\n")).toBe(true);
381
- // warn 被调(背压告警)
382
- expect(warnSpy).toHaveBeenCalledTimes(1);
383
- const warnMsg = warnSpy.mock.calls[0]?.[0] as string;
384
- expect(warnMsg).toContain("backpressure");
385
- });
386
-
387
- it("child.stdin.write 返回 true → 不 warn(正常路径)", () => {
388
- const fakeStdin = {
389
- write: vi.fn(() => true),
390
- destroyed: false,
391
- } as unknown as PassThrough;
392
- const child = { stdin: fakeStdin } as unknown as ChildProcess;
393
-
394
- respond(child, "req-ok", { value: "x" });
395
-
396
- expect(warnSpy).not.toHaveBeenCalled();
397
- });
398
- });
399
-
400
- // [review 修复 round2] 已删除 sendFollowUpCommand / sendSteerCommand 两 describe——
401
- // 随 deliverToRunning(S2)死亡后两函数成零生产调用方的死 export,一并移除。
402
- // busy 投递语义由 prompt + streamingBehavior("followUp"/"steer",sendPromptCommand)承担。
403
-
404
- // ============================================================
405
- // writeStdinLine EPIPE / ERR_STREAM_DESTROYED 检测(R3)
406
- // ============================================================
407
-
408
- describe("writeStdinLine EPIPE 检测 — EPIPE / ERR_STREAM_DESTROYED throw", () => {
409
- it("child.stdin.write 抛 {code:'EPIPE'} → throw 含 EPIPE 关键词", () => {
410
- const fakeStdin = {
411
- write: vi.fn(() => {
412
- const err = Object.assign(new Error("write after end"), { code: "EPIPE" });
413
- throw err;
414
- }),
415
- destroyed: false,
416
- } as unknown as PassThrough;
417
- const child = { stdin: fakeStdin } as unknown as ChildProcess;
418
-
419
- expect(() => respond(child, "req-epipe", { value: "x" })).toThrow(/EPIPE/);
420
- });
421
-
422
- it("child.stdin.write 抛 {code:'ERR_STREAM_DESTROYED'} → throw 含 EPIPE 关键词", () => {
423
- const fakeStdin = {
424
- write: vi.fn(() => {
425
- const err = Object.assign(new Error("Stream is destroyed"), {
426
- code: "ERR_STREAM_DESTROYED",
427
- });
428
- throw err;
429
- }),
430
- destroyed: false,
431
- } as unknown as PassThrough;
432
- const child = { stdin: fakeStdin } as unknown as ChildProcess;
433
-
434
- expect(() => sendPromptCommand(child, "task")).toThrow(/EPIPE/);
435
- });
436
-
437
- it("child.stdin.destroyed=true → 静默跳过(guard 生效,不触发 write)", () => {
438
- const fakeStdin = {
439
- write: vi.fn(),
440
- destroyed: true,
441
- } as unknown as PassThrough;
442
- const child = { stdin: fakeStdin } as unknown as ChildProcess;
443
-
444
- expect(() => respond(child, "req-destroyed", { value: "x" })).not.toThrow();
445
- // destroyed guard 生效,write 不被调用
446
- expect(fakeStdin.write).not.toHaveBeenCalled();
447
- });
448
-
449
- it("child.stdin.write 抛非 EPIPE 错误 → warn 降级不 throw(兜底)", () => {
450
- const fakeStdin = {
451
- write: vi.fn(() => {
452
- throw new Error("some other error");
453
- }),
454
- destroyed: false,
455
- } as unknown as PassThrough;
456
- const child = { stdin: fakeStdin } as unknown as ChildProcess;
457
-
458
- // 非 EPIPE 错误应 warn 降级,不 throw
459
- expect(() => respond(child, "req-other-err", { value: "x" })).not.toThrow();
460
- expect(warnSpy).toHaveBeenCalledTimes(1);
461
- const warnMsg = warnSpy.mock.calls[0]?.[0] as string;
462
- expect(warnMsg).toContain("unexpected stdin write error");
463
- });
464
- });