@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,446 +0,0 @@
1
- // src/__tests__/spawn-args.test.ts
2
- import { spawnSync } from "node:child_process";
3
- import * as fs from "node:fs";
4
- import * as os from "node:os";
5
- import * as path from "node:path";
6
-
7
- import { afterEach, beforeEach, describe, expect, it } from "vitest";
8
-
9
- import { mirrorMainProcessFlags } from "../engine/engines/pi/argv-mirror.ts";
10
- import { MAX_FORK_DEPTH } from "../session-context-resolver.ts";
11
- import { buildEnvBlock, buildSpawnArgs } from "../engine/engines/pi/session-runner.ts";
12
-
13
- describe("buildSpawnArgs", () => {
14
- // [U1 D2] modelRef 为必填(spawn 前置守卫:未经裁决的裸字符串类型层面不可达)。
15
- // 类型直接锚定 buildSpawnArgs 入参(thinkingLevel 是 ThinkingLevel 枚举,非裸 string)
16
- const baseParams: Parameters<typeof buildSpawnArgs>[0] = {
17
- modelRef: { provider: "openai", id: "gpt-4o" },
18
- thinkingLevel: undefined,
19
- agentTools: undefined,
20
- appendSystemPromptPath: undefined,
21
- sessionDir: "/sessions/dir",
22
- forkSource: undefined,
23
- skillPaths: undefined,
24
- };
25
-
26
- it("基础参数:--mode rpc --session-dir + --model provider/id,不含 -p 也不含 task(task 经 stdin 传)", () => {
27
- const args = buildSpawnArgs(baseParams);
28
- expect(args).toEqual([
29
- "--mode", "rpc", "--session-dir", "/sessions/dir", "--model", "openai/gpt-4o",
30
- ]);
31
- });
32
-
33
- it("不含 -p / --print(rpc mode 下 -p 被 resolveAppMode 无视,是死代码)", () => {
34
- const args = buildSpawnArgs(baseParams);
35
- expect(args).not.toContain("-p");
36
- expect(args).not.toContain("--print");
37
- });
38
-
39
- it("modelRef → --model 值恒为 `${provider}/${id}`(全等拼接,不重写输入)", () => {
40
- // 含大小写差异的 provider/id 原样拼接(大小写敏感规则:放行即全等回显)
41
- const args = buildSpawnArgs({
42
- ...baseParams,
43
- modelRef: { provider: "zai-coding-cn", id: "GLM-5.3-Flash" },
44
- });
45
- const idx = args.indexOf("--model");
46
- expect(args[idx + 1]).toBe("zai-coding-cn/GLM-5.3-Flash");
47
- });
48
-
49
- it("modelRef + thinkingLevel → model 后缀 :level", () => {
50
- const args = buildSpawnArgs(
51
- { ...baseParams, thinkingLevel: "high" },
52
- );
53
- const idx = args.indexOf("--model");
54
- expect(args[idx + 1]).toBe("openai/gpt-4o:high");
55
- });
56
-
57
- it("agentTools → --tools 逗号分隔", () => {
58
- const args = buildSpawnArgs(
59
- { ...baseParams, agentTools: ["read", "bash", "edit"] },
60
- );
61
- const idx = args.indexOf("--tools");
62
- expect(args[idx + 1]).toBe("read,bash,edit");
63
- });
64
-
65
- it("appendSystemPromptPath → --append-system-prompt <path>", () => {
66
- const args = buildSpawnArgs(
67
- { ...baseParams, appendSystemPromptPath: "/tmp/prompt.md" },
68
- );
69
- const idx = args.indexOf("--append-system-prompt");
70
- expect(args[idx + 1]).toBe("/tmp/prompt.md");
71
- });
72
-
73
- it("forkSource → --fork <path>", () => {
74
- const args = buildSpawnArgs(
75
- { ...baseParams, forkSource: "/sessions/parent.jsonl" },
76
- );
77
- const idx = args.indexOf("--fork");
78
- expect(args[idx + 1]).toBe("/sessions/parent.jsonl");
79
- });
80
-
81
- it("skillPaths 多个 → 每个 push --skill <path>", () => {
82
- const args = buildSpawnArgs(
83
- { ...baseParams, skillPaths: ["/skills/a", "/skills/b", "/skills/c"] },
84
- );
85
- // 三个 --skill token,后跟各自路径,顺序保留
86
- const skillIdxs = args
87
- .map((a, i) => (a === "--skill" ? i : -1))
88
- .filter((i) => i >= 0);
89
- expect(skillIdxs).toHaveLength(3);
90
- expect(args[skillIdxs[0] + 1]).toBe("/skills/a");
91
- expect(args[skillIdxs[1] + 1]).toBe("/skills/b");
92
- expect(args[skillIdxs[2] + 1]).toBe("/skills/c");
93
- });
94
-
95
- it("skillPaths 空数组 → 不含 --skill", () => {
96
- const args = buildSpawnArgs(
97
- { ...baseParams, skillPaths: [] },
98
- );
99
- expect(args).not.toContain("--skill");
100
- });
101
-
102
- it("skillPaths undefined → 不含 --skill", () => {
103
- const args = buildSpawnArgs(baseParams);
104
- expect(args).not.toContain("--skill");
105
- });
106
-
107
- it("全参数组合:所有 flag 存在,不含 -p 也不含 positional task", () => {
108
- const args = buildSpawnArgs(
109
- {
110
- ...baseParams,
111
- thinkingLevel: "low",
112
- agentTools: ["read"],
113
- appendSystemPromptPath: "/tmp/p.md",
114
- sessionDir: "/s",
115
- forkSource: "/parent.jsonl",
116
- skillPaths: ["/skills/x"],
117
- },
118
- );
119
- // 末尾应是最后一个 --skill 的路径(task 不再作为 positional arg 出现)
120
- expect(args[args.length - 1]).toBe("/skills/x");
121
- expect(args).toContain("--fork");
122
- expect(args).toContain("--tools");
123
- expect(args).toContain("--skill");
124
- expect(args).not.toContain("-p");
125
- });
126
-
127
- it("空 tools 数组不追加 --tools", () => {
128
- const args = buildSpawnArgs(
129
- { ...baseParams, agentTools: [] },
130
- );
131
- expect(args).not.toContain("--tools");
132
- });
133
-
134
- it("含未注册扩展工具名(如 ask_user)正常透传 — 子进程 Pi 静默忽略未注册的 allowlist 项", () => {
135
- // 场景:orchestrator 模板声明了 ask_user,但用户环境未装 pi-ask-user 扩展。
136
- // 期望:subagent-workflow 不做特殊处理,仅原样透传给 pi CLI;
137
- // 静默兼容的责任在 Pi(args.ts 不校验、agent-session 的 _rebuildSystemPrompt
138
- // 对未注册工具名静默过滤)。本测试钉死这个透传行为,避免有人擅自加
139
- // 「未注册工具检测」导致原本兼容的场景崩溃。
140
- const args = buildSpawnArgs({
141
- ...baseParams,
142
- agentTools: ["todo", "goal_control", "workflow", "subagent", "ask_user"],
143
- });
144
- const idx = args.indexOf("--tools");
145
- expect(idx).toBeGreaterThanOrEqual(0);
146
- expect(args[idx + 1]).toBe(
147
- "todo,goal_control,workflow,subagent,ask_user",
148
- );
149
- });
150
-
151
- // ============================================================
152
- // mirrorFlags 透传:子进程镜像主进程 extension/approve flag
153
- // ============================================================
154
-
155
- it("mirrorFlags 透传:noExtensions+approve+noContextFiles+extensionPaths 全量 push(TC5)", () => {
156
- const args = buildSpawnArgs({
157
- ...baseParams,
158
- mirrorFlags: { noExtensions: true, approve: true, noContextFiles: true, extensionPaths: ["/e1", "/e2"] },
159
- });
160
- expect(args).toContain("--no-extensions");
161
- expect(args).toContain("--approve");
162
- expect(args).toContain("--no-context-files");
163
- // 每个 extension 独立 token,顺序保留
164
- const extIdxs = args.map((a, i) => (a === "--extension" ? i : -1)).filter((i) => i >= 0);
165
- expect(extIdxs).toHaveLength(2);
166
- expect(args[extIdxs[0] + 1]).toBe("/e1");
167
- expect(args[extIdxs[1] + 1]).toBe("/e2");
168
- });
169
-
170
- it("mirrorFlags 全 false/空 → 不追加任何目标 flag(TC6)", () => {
171
- const args = buildSpawnArgs({
172
- ...baseParams,
173
- mirrorFlags: { noExtensions: false, approve: false, noContextFiles: false, extensionPaths: [] },
174
- });
175
- expect(args).not.toContain("--no-extensions");
176
- expect(args).not.toContain("--approve");
177
- expect(args).not.toContain("--extension");
178
- expect(args).not.toContain("--no-context-files");
179
- // 仅基础参数
180
- expect(args).toEqual(["--mode", "rpc", "--session-dir", "/sessions/dir", "--model", "openai/gpt-4o"]);
181
- });
182
-
183
- it("mirrorFlags undefined → 行为等同旧版(TC7)", () => {
184
- const args = buildSpawnArgs(baseParams);
185
- expect(args).toEqual(["--mode", "rpc", "--session-dir", "/sessions/dir", "--model", "openai/gpt-4o"]);
186
- expect(args).not.toContain("--extension");
187
- expect(args).not.toContain("--no-extensions");
188
- expect(args).not.toContain("--approve");
189
- expect(args).not.toContain("--no-context-files");
190
- });
191
-
192
- it("noContextFiles 镜像:主进程 argv 含 --no-context-files → 子进程 args 含该 flag", () => {
193
- // 端到端链路断言:主 pi 进程以 --no-context-files 启动(用户 opt-out context files)
194
- // → mirrorMainProcessFlags 解析 → buildSpawnArgs 产出同 flag 给每个 subagent。
195
- // 缺此镜像时,--extension 镜像带入的 @zhushanwen/pi-system-prompt 检查子进程
196
- // 自己的 argv(无 flag)→ 全局 AGENTS.md 注入在 subagent system prompt 照常生效,
197
- // 用户 opt-out 被绕过。
198
- const mainArgv = [
199
- "bun", "/pi", "--mode", "rpc", "--no-context-files",
200
- "--extension", "/staged/@zhushanwen/pi-system-prompt/index.js",
201
- ];
202
- const args = buildSpawnArgs({ ...baseParams, mirrorFlags: mirrorMainProcessFlags(mainArgv) });
203
- expect(args).toContain("--no-context-files");
204
- // extension 镜像照常(两者共存才构成完整契约)
205
- const extIdx = args.indexOf("--extension");
206
- expect(args[extIdx + 1]).toBe("/staged/@zhushanwen/pi-system-prompt/index.js");
207
- });
208
-
209
- it("noContextFiles 不镜像:主进程 argv 不含 flag → 子进程 args 不含(默认行为不变)", () => {
210
- const mainArgv = ["bun", "/pi", "--mode", "rpc"];
211
- const args = buildSpawnArgs({ ...baseParams, mirrorFlags: mirrorMainProcessFlags(mainArgv) });
212
- expect(args).not.toContain("--no-context-files");
213
- });
214
-
215
- // ============================================================
216
- // sessionFile(M1 resume 基建):--session <file> 紧跟 --session-dir
217
- // ============================================================
218
-
219
- it("sessionFile 存在 → 紧跟 --session-dir 追加 --session <file>", () => {
220
- const args = buildSpawnArgs({
221
- ...baseParams,
222
- sessionFile: "/sessions/sub/abc.jsonl",
223
- });
224
- const idx = args.indexOf("--session");
225
- expect(idx).toBeGreaterThan(-1);
226
- expect(args[idx + 1]).toBe("/sessions/sub/abc.jsonl");
227
- // 位置紧跟 --session-dir <dir> 之后(--model 之前)
228
- const sessionDirIdx = args.indexOf("--session-dir");
229
- expect(idx).toBe(sessionDirIdx + 2);
230
- });
231
-
232
- it("sessionFile undefined → 不含 --session(向后兼容)", () => {
233
- const args = buildSpawnArgs(baseParams);
234
- expect(args).not.toContain("--session");
235
- expect(args).toEqual(["--mode", "rpc", "--session-dir", "/sessions/dir", "--model", "openai/gpt-4o"]);
236
- });
237
-
238
- it("sessionFile + modelRef + thinkingLevel → 三者都进 args(resume 全参数)", () => {
239
- const args = buildSpawnArgs({
240
- ...baseParams,
241
- sessionFile: "/sessions/sub/resume.jsonl",
242
- thinkingLevel: "high",
243
- });
244
- // --session <file>
245
- const sessionIdx = args.indexOf("--session");
246
- expect(sessionIdx).toBeGreaterThan(-1);
247
- expect(args[sessionIdx + 1]).toBe("/sessions/sub/resume.jsonl");
248
- // --model provider/id:level(thinkingLevel 作 model 后缀)
249
- const modelIdx = args.indexOf("--model");
250
- expect(modelIdx).toBeGreaterThan(-1);
251
- expect(args[modelIdx + 1]).toBe("openai/gpt-4o:high");
252
- });
253
- });
254
-
255
- // ============================================================
256
- // mirrorMainProcessFlags:从主进程 argv 解析可镜像的 flag
257
- // ============================================================
258
-
259
- describe("mirrorMainProcessFlags", () => {
260
- it("--extension 多次出现(空格分隔)+ 布尔 flag(TC1)", () => {
261
- const r = mirrorMainProcessFlags([
262
- "bun", "/pi", "--mode", "rpc", "--no-extensions", "--approve",
263
- "--extension", "/a", "--extension", "/b",
264
- ]);
265
- expect(r).toEqual({ noExtensions: true, approve: true, extensionPaths: ["/a", "/b"], noContextFiles: false });
266
- });
267
-
268
- it("--extension=path 等号形式 + 短形式 -e/-ne/-a(TC2)", () => {
269
- const r = mirrorMainProcessFlags([
270
- "bun", "/pi", "--extension=/x", "-ne", "-a",
271
- ]);
272
- expect(r).toEqual({ noExtensions: true, approve: true, extensionPaths: ["/x"], noContextFiles: false });
273
- });
274
-
275
- it("混合形式(空格 + 等号),顺序保留(TC3)", () => {
276
- const r = mirrorMainProcessFlags([
277
- "bun", "/pi", "--extension", "/a", "--extension=/b", "--extension", "/c",
278
- ]);
279
- expect(r.extensionPaths).toEqual(["/a", "/b", "/c"]);
280
- expect(r.noExtensions).toBe(false);
281
- expect(r.approve).toBe(false);
282
- expect(r.noContextFiles).toBe(false);
283
- });
284
-
285
- it("无目标 flag → 全空/全 false(向后兼容,TC4)", () => {
286
- const r = mirrorMainProcessFlags(["bun", "/pi", "--mode", "rpc"]);
287
- expect(r).toEqual({ noExtensions: false, approve: false, extensionPaths: [], noContextFiles: false });
288
- });
289
-
290
- it("--no-context-files 长形式解析 → noContextFiles: true", () => {
291
- const r = mirrorMainProcessFlags([
292
- "bun", "/pi", "--mode", "rpc", "--no-context-files",
293
- "--extension", "/staged/@zhushanwen/pi-system-prompt/index.js",
294
- ]);
295
- expect(r.noContextFiles).toBe(true);
296
- // 与 extension 镜像共存(实际 xyz-agent 启动形态:两 flag 同时出现)
297
- expect(r.extensionPaths).toEqual(["/staged/@zhushanwen/pi-system-prompt/index.js"]);
298
- expect(r.noExtensions).toBe(false);
299
- expect(r.approve).toBe(false);
300
- });
301
-
302
- it("-nc 短形式解析 → noContextFiles: true(pi CLI 等价短形式)", () => {
303
- const r = mirrorMainProcessFlags(["bun", "/pi", "--mode", "rpc", "-nc"]);
304
- expect(r.noContextFiles).toBe(true);
305
- });
306
-
307
- it("不误吃其他 flag 值与 positional 参数(TC8)", () => {
308
- const r = mirrorMainProcessFlags([
309
- "bun", "/pi", "--no-extensions", "--skill", "/sk", "some prompt text",
310
- ]);
311
- expect(r.noExtensions).toBe(true);
312
- expect(r.extensionPaths).toEqual([]);
313
- // --skill 的 /sk 不混入 extensionPaths;positional prompt 被忽略
314
- });
315
-
316
- it("空 argv / 仅前导两项 → 全空", () => {
317
- expect(mirrorMainProcessFlags([])).toEqual({ noExtensions: false, approve: false, extensionPaths: [], noContextFiles: false });
318
- expect(mirrorMainProcessFlags(["bun", "/pi"])).toEqual({
319
- noExtensions: false, approve: false, extensionPaths: [], noContextFiles: false,
320
- });
321
- });
322
-
323
- it("--extension 末尾无值 → 跳过(不越界、不误吃下一个 token)", () => {
324
- const r = mirrorMainProcessFlags(["bun", "/pi", "--extension"]);
325
- expect(r.extensionPaths).toEqual([]);
326
- });
327
-
328
- it("-e 短形式多次 + 等号混用", () => {
329
- const r = mirrorMainProcessFlags(["bun", "/pi", "-e", "/a", "-e=/b", "-e", "/c"]);
330
- expect(r.extensionPaths).toEqual(["/a", "/b", "/c"]);
331
- });
332
-
333
- // [MF-7a] flag 判定收窄为 startsWith("--"):单 - 开头的合法路径不被误判为 flag。
334
- it("[MF-7a] - 开头的路径被当值镜像(不误判 flag)", () => {
335
- const r = mirrorMainProcessFlags(["bun", "/pi", "--extension", "-weird-dir/ext.js"]);
336
- expect(r.extensionPaths).toEqual(["-weird-dir/ext.js"]);
337
- });
338
-
339
- // [MF-7a] -- 开头的真 flag 仍正确跳过:--extension 后跟 --flag 时不吃值、不越界。
340
- it("[MF-7a] --extension 后跟 -- 开头真 flag → 不吃值", () => {
341
- const r = mirrorMainProcessFlags([
342
- "bun", "/pi", "--extension", "--approve", "--extension", "/real.js",
343
- ]);
344
- expect(r.extensionPaths).toEqual(["/real.js"]);
345
- expect(r.approve).toBe(true);
346
- });
347
- });
348
-
349
- // ============================================================
350
- // buildEnvBlock(M1 恢复)
351
- // ============================================================
352
-
353
- describe("buildEnvBlock", () => {
354
- // buildEnvBlock 内部按 cwd 缓存 git branch(模块级 Map),用真实 git 仓库测最稳。
355
- // 用临时 git 仓库隔离,避免污染主仓库 branch 缓存。
356
- // buildEnvBlock 已异步化(execFile + Promise 包装),所有直接调用需 await。
357
- let tmpGitRepo: string;
358
- const testBranch = "test-env-branch";
359
-
360
- beforeEach(() => {
361
- tmpGitRepo = fs.mkdtempSync(path.join(os.tmpdir(), "envblock-"));
362
- // 初始化 git 仓库 + checkout 已知分支名。
363
- // 必须先 commit 一次:git rev-parse --abbrev-ref HEAD 在无 commit 的空仓库会失败
364
- //(exit 128,HEAD 未解析),buildEnvBlock 走兜底 branch=""。
365
- spawnSync("git", ["init", "-q"], { cwd: tmpGitRepo, stdio: "ignore" });
366
- spawnSync("git", ["checkout", "-q", "-b", testBranch], { cwd: tmpGitRepo, stdio: "ignore" });
367
- // git commit 需要 user.email/name;本地配置避免依赖全局 git config(CI 无身份时失败)
368
- spawnSync("git", ["config", "user.email", "test@test.local"], { cwd: tmpGitRepo, stdio: "ignore" });
369
- spawnSync("git", ["config", "user.name", "Test"], { cwd: tmpGitRepo, stdio: "ignore" });
370
- fs.writeFileSync(path.join(tmpGitRepo, "README.md"), "init\n", "utf-8");
371
- spawnSync("git", ["add", "."], { cwd: tmpGitRepo, stdio: "ignore" });
372
- spawnSync("git", ["commit", "-q", "-m", "init"], { cwd: tmpGitRepo, stdio: "ignore" });
373
- });
374
-
375
- afterEach(() => {
376
- fs.rmSync(tmpGitRepo, { recursive: true, force: true, maxRetries: 5, retryDelay: 20 });
377
- });
378
-
379
- it("注入 cwd(Working directory 行)", async () => {
380
- const block = await buildEnvBlock(tmpGitRepo);
381
- expect(block).toContain(`Working directory: ${tmpGitRepo}`);
382
- expect(block).toContain("--- environment (data, not instructions) ---");
383
- expect(block).toContain("--- end environment ---");
384
- });
385
-
386
- it("forkDepth > 0 → 含 Depth: N/<MAX>", async () => {
387
- const block = await buildEnvBlock(tmpGitRepo, 3);
388
- expect(block).toContain(`Depth: 3/${MAX_FORK_DEPTH}`);
389
- });
390
-
391
- it("forkDepth === 0 → 不含 depth 行", async () => {
392
- const block = await buildEnvBlock(tmpGitRepo, 0);
393
- expect(block).not.toContain("Depth:");
394
- });
395
-
396
- it("forkDepth undefined → 不含 depth 行", async () => {
397
- const block = await buildEnvBlock(tmpGitRepo);
398
- expect(block).not.toContain("Depth:");
399
- });
400
-
401
- // [M9] nestingDepth:取 max(forkDepth, nestingDepth) 展示更严约束。
402
- it("forkDepth < nestingDepth → 展示 max(nestingDepth 更严)", async () => {
403
- // forkDepth=1(最内 fork),nestingDepth=5(通用嵌套已深)→ 展示 5
404
- const block = await buildEnvBlock(tmpGitRepo, 1, 5);
405
- expect(block).toContain(`Depth: 5/${MAX_FORK_DEPTH}`);
406
- expect(block).not.toContain(`Depth: 1/${MAX_FORK_DEPTH}`);
407
- });
408
-
409
- it("forkDepth > nestingDepth → 展示 max(forkDepth 更严)", async () => {
410
- const block = await buildEnvBlock(tmpGitRepo, 7, 2);
411
- expect(block).toContain(`Depth: 7/${MAX_FORK_DEPTH}`);
412
- });
413
-
414
- it("forkDepth=0 + nestingDepth>0 → 展示 nestingDepth(非 fork 嵌套也计入)", async () => {
415
- // 非 fork 但有嵌套(如顶层 → 子 → 孙),nestingDepth=2 应展示
416
- const block = await buildEnvBlock(tmpGitRepo, undefined, 2);
417
- expect(block).toContain(`Depth: 2/${MAX_FORK_DEPTH}`);
418
- });
419
-
420
- it("git branch 存在 → 含 Git branch 行", async () => {
421
- const block = await buildEnvBlock(tmpGitRepo);
422
- expect(block).toContain(`Git branch: ${testBranch}`);
423
- });
424
-
425
- it("非 git 目录 → 不含 Git branch 行(git 失败兜底空串)", async () => {
426
- const nonGitDir = fs.mkdtempSync(path.join(os.tmpdir(), "envblock-nogit-"));
427
- try {
428
- const block = await buildEnvBlock(nonGitDir);
429
- expect(block).not.toContain("Git branch:");
430
- // 但仍含 working directory(环境块始终输出)
431
- expect(block).toContain(`Working directory: ${nonGitDir}`);
432
- } finally {
433
- fs.rmSync(nonGitDir, { recursive: true, force: true, maxRetries: 5, retryDelay: 20 });
434
- }
435
- });
436
-
437
- it("git 失败(execFile err 回调)→ 不崩,静默省略 branch", async () => {
438
- // 旧版 spy 挂在测试本地对象字面量上(同名同步 git API 的对象包装),从未真正拦截
439
- // session-runner 的模块绑定——此前通过是靠 /some/cwd 不存在使真实 git 失败的副作用。
440
- // 异步化后改为显式用不存在的 cwd 触发 execFile err 回调(err → reject → catch →
441
- // branch=""),覆盖同一条失败路径,断言不变。
442
- const block = await buildEnvBlock("/some/cwd");
443
- expect(block).not.toContain("Git branch:");
444
- expect(block).toContain("Working directory: /some/cwd");
445
- });
446
- });
@@ -1,192 +0,0 @@
1
- // src/__tests__/spawn-event-adapter-rpc.test.ts
2
- //
3
- // W1 红灯测试:spawn-event-adapter.ts 协议层重写 — Pi 原生格式 + method 平铺。
4
- //
5
- // 测试对象:packages/subagent-core/src/execution/engine/engines/pi/spawn-event-adapter.ts(改造)
6
- // 契约来源:.fix-plans/00-master-summary.md §二(统一接口契约)+ §一冲突 2/判定顺序
7
- //
8
- // 核心改动:
9
- // 1. isExtensionUiRequest 重写:判 type==="extension_ui_request" + id:string + method:string
10
- // (删 jsonrpc==="2.0" 守卫 + params 守卫 — Pi 原生格式是平铺字段)
11
- // 2. extension_ui_request 分支:从 {id, params:Record} 改为 {id, request: ExtensionUiRequest}
12
- // request 按 method 平铺(title/options/message/... 与 Pi rpc-types.ts 1:1)
13
- // 3. isRpcResponse 重写:判 type==="response" + command:string + success:boolean(SR-1 根因 1b)
14
- // 4. 判定顺序:isExtensionUiRequest 必须在 event 分支之前(否则被 typeof obj.type===string 吞)
15
- //
16
- // 红灯原因:spawn-event-adapter.ts 当前用旧 JSON-RPC 2.0 守卫,对 Pi 原生格式样本
17
- // 无法识别为 extension_ui_request(会落到 event 分支)。改造后这些断言才绿。
18
-
19
- import { describe, expect, it } from "vitest";
20
-
21
- import { parseSpawnLine } from "../engine/engines/pi/spawn-event-adapter.ts";
22
-
23
- // ── Pi 原生协议样本构造(来源:rpc-types.ts L230-265 真实类型) ──────────
24
- // 10 种 method,全部 {type:"extension_ui_request", id, method, ...平铺字段}。
25
- // 注意:无 jsonrpc 字段、无 params 包裹、method 在顶层(非 method:"extension_ui_request")。
26
-
27
- function piLine(methodFields: Record<string, unknown>): string {
28
- return JSON.stringify({ type: "extension_ui_request", id: "req-001", ...methodFields });
29
- }
30
-
31
-
32
- /** 判别收窄辅助:string-fallback 变体(method: string)使 !== 收窄失效,
33
- * 用 Extract 条件类型(可赋值方向)精确取变体。 */
34
- function asVariant<M extends string>(
35
- req: import("../engine/engines/pi/spawn-event-adapter.ts").ExtensionUiRequest,
36
- method: M,
37
- ): Extract<import("../engine/engines/pi/spawn-event-adapter.ts").ExtensionUiRequest, { method: M }> {
38
- if (req.method !== method) throw new Error(`request.method 应为 ${method}`);
39
- return req as Extract<import("../engine/engines/pi/spawn-event-adapter.ts").ExtensionUiRequest, { method: M }>;
40
- }
41
-
42
- describe("parseSpawnLine — 10 种 method 真实样本分类(Pi 原生格式)", () => {
43
- describe("dialog 类(select/confirm/input/editor)", () => {
44
- it("select → kind=extension_ui_request + request.method=select + title/options 平铺", () => {
45
- const result = parseSpawnLine(piLine({
46
- method: "select", title: "Pick one", options: ["a", "b"], timeout: 30000,
47
- }));
48
- expect(result?.kind).toBe("extension_ui_request");
49
- if (result?.kind !== "extension_ui_request") return;
50
- expect(result.id).toBe("req-001");
51
- const req = asVariant(result.request, "select");
52
- });
53
-
54
- it("confirm → request.method=confirm + title/message 平铺", () => {
55
- const result = parseSpawnLine(piLine({
56
- method: "confirm", title: "Sure?", message: "Proceed?", timeout: 10000,
57
- }));
58
- expect(result?.kind).toBe("extension_ui_request");
59
- if (result?.kind !== "extension_ui_request") return;
60
- const req = asVariant(result.request, "confirm");
61
- });
62
-
63
- it("input → request.method=input + title + placeholder", () => {
64
- const result = parseSpawnLine(piLine({
65
- method: "input", title: "Name", placeholder: "type here",
66
- }));
67
- expect(result?.kind).toBe("extension_ui_request");
68
- if (result?.kind !== "extension_ui_request") return;
69
- const req = asVariant(result.request, "input");
70
- });
71
-
72
- it("editor → request.method=editor + title + prefill", () => {
73
- const result = parseSpawnLine(piLine({
74
- method: "editor", title: "Edit", prefill: "initial text",
75
- }));
76
- expect(result?.kind).toBe("extension_ui_request");
77
- if (result?.kind !== "extension_ui_request") return;
78
- const req = asVariant(result.request, "editor");
79
- });
80
- });
81
-
82
- describe("fire-and-forget 类(notify/setStatus/setWidget/setTitle/set_editor_text)", () => {
83
- it("notify → request.method=notify + message + notifyType", () => {
84
- const result = parseSpawnLine(piLine({
85
- method: "notify", message: "hi", notifyType: "info",
86
- }));
87
- expect(result?.kind).toBe("extension_ui_request");
88
- if (result?.kind !== "extension_ui_request") return;
89
- const req = asVariant(result.request, "notify");
90
- });
91
-
92
- it("setStatus → request.method=setStatus + statusKey/statusText", () => {
93
- const result = parseSpawnLine(piLine({
94
- method: "setStatus", statusKey: "k", statusText: "running",
95
- }));
96
- expect(result?.kind).toBe("extension_ui_request");
97
- if (result?.kind !== "extension_ui_request") return;
98
- const req = asVariant(result.request, "setStatus");
99
- expect(req.statusKey).toBe("k");
100
- });
101
-
102
- it("setWidget → request.method=setWidget + widgetKey/widgetLines/widgetPlacement", () => {
103
- const result = parseSpawnLine(piLine({
104
- method: "setWidget", widgetKey: "w1",
105
- widgetLines: ["line1"], widgetPlacement: "aboveEditor",
106
- }));
107
- expect(result?.kind).toBe("extension_ui_request");
108
- if (result?.kind !== "extension_ui_request") return;
109
- const req = asVariant(result.request, "setWidget");
110
- expect(req.widgetKey).toBe("w1");
111
- expect(req.widgetPlacement).toBe("aboveEditor");
112
- });
113
-
114
- it("setTitle → request.method=setTitle + title", () => {
115
- const result = parseSpawnLine(piLine({ method: "setTitle", title: "My Title" }));
116
- expect(result?.kind).toBe("extension_ui_request");
117
- if (result?.kind !== "extension_ui_request") return;
118
- const req = asVariant(result.request, "setTitle");
119
- expect(req.title).toBe("My Title");
120
- });
121
-
122
- it("set_editor_text → request.method=set_editor_text + text", () => {
123
- const result = parseSpawnLine(piLine({ method: "set_editor_text", text: "body" }));
124
- expect(result?.kind).toBe("extension_ui_request");
125
- if (result?.kind !== "extension_ui_request") return;
126
- const req = asVariant(result.request, "set_editor_text");
127
- });
128
- });
129
- });
130
-
131
- describe("parseSpawnLine — 旧 JSON-RPC 2.0 格式不再被识别(守卫已删)", () => {
132
- it("jsonrpc+method:extension_ui_request+params 旧格式 → 不归类为 extension_ui_request", () => {
133
- // 旧格式(错误假设):会被识别为 event 或 invalid,因为新守卫不认 jsonrpc
134
- const oldFormat = JSON.stringify({
135
- jsonrpc: "2.0", id: "x", method: "extension_ui_request", params: { foo: "bar" },
136
- });
137
- const result = parseSpawnLine(oldFormat);
138
- // 旧格式的 method 字段值是 "extension_ui_request",无 type 字段 → invalid
139
- // (这是有意的:强制对齐 Pi 原生格式)
140
- expect(result?.kind).not.toBe("extension_ui_request");
141
- });
142
- });
143
-
144
- describe("parseSpawnLine — 判定顺序:isExtensionUiRequest 先于 event 分支", () => {
145
- it("extension_ui_request 不被 typeof obj.type===string 吞为 event", () => {
146
- // 关键 bug:extension_ui_request 有 type 字段,若 event 分支在前会被当 event
147
- const result = parseSpawnLine(piLine({ method: "notify", message: "x" }));
148
- // 必须是 extension_ui_request,不能是 event
149
- expect(result?.kind).toBe("extension_ui_request");
150
- expect(result?.kind).not.toBe("event");
151
- });
152
- });
153
-
154
- describe("parseSpawnLine — RPC response(isRpcResponse 重写,SR-1 根因 1b)", () => {
155
- it("Pi response 格式 {type:response, command, success} → kind=response", () => {
156
- const result = parseSpawnLine(JSON.stringify({
157
- type: "response", id: "r1", command: "run_tool", success: true,
158
- }));
159
- expect(result?.kind).toBe("response");
160
- if (result?.kind !== "response") return;
161
- expect(result.id).toBe("r1");
162
- expect(result.command).toBe("run_tool");
163
- expect(result.success).toBe(true);
164
- });
165
-
166
- it("Pi response 失败 {type:response, command, success:false, error}", () => {
167
- const result = parseSpawnLine(JSON.stringify({
168
- type: "response", command: "run_tool", success: false, error: "boom",
169
- }));
170
- expect(result?.kind).toBe("response");
171
- if (result?.kind !== "response") return;
172
- expect(result.success).toBe(false);
173
- expect(result.error).toBe("boom");
174
- });
175
-
176
- it("response 含 data 字段 → 保留", () => {
177
- const result = parseSpawnLine(JSON.stringify({
178
- type: "response", command: "read", success: true, data: { out: 42 },
179
- }));
180
- expect(result?.kind).toBe("response");
181
- if (result?.kind !== "response") return;
182
- expect(result.data).toEqual({ out: 42 });
183
- });
184
-
185
- it("旧 JSON-RPC 2.0 response(jsonrpc+id+result)→ 不再归类为 response", () => {
186
- const oldRpc = JSON.stringify({
187
- jsonrpc: "2.0", id: "x", result: { answers: [] },
188
- });
189
- const result = parseSpawnLine(oldRpc);
190
- expect(result?.kind).not.toBe("response");
191
- });
192
- });