@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
@@ -30,7 +30,10 @@ import type { AgentEvent } from "../shared/agent-event.ts";
30
30
  import { assertTaskShapeSupported } from "./engine/common/capability-gate.ts";
31
31
  import { HOST_TIMEOUT_ABORT_REASON } from "./engine/common/kill-chain.ts";
32
32
  import { JOURNAL_INITIAL_POOL_KEY, wireEventJournal } from "./engine/common/journal-wiring.ts";
33
- import { createPiEngine } from "./engine/engines/pi/registration.ts";
33
+ // [W6 R1 MF-5] pi EnginePort 解析改经 host 公共面(engine/host/pi-host-binding.ts):
34
+ // registry cli 形态经 descriptor 路由(W3 双模 getEngine),inproc/未注册回落 per-session
35
+ // DI 直构(行为与改线前 createPiEngine 逐点一致)。
36
+ import { resolveHostPiEnginePort } from "./engine/host/pi-host-binding.ts";
34
37
  import type { EnginePort, RunContext } from "./engine/port.ts";
35
38
  import { validateModelForEngine } from "./engine/model-validation.ts";
36
39
  import { routeEngineForHost, type EngineRouteResult, type EngineRoutingInput } from "./engine/routing.ts";
@@ -39,7 +42,9 @@ import type { AgentOutcome } from "./engine/types.ts";
39
42
  import { getModelConfigService } from "./model-config-service.ts";
40
43
  import type { ModelInfo } from "./model-resolver.ts";
41
44
  import { modelRefFromVerified } from "../shared/model-ref";
42
- import { registerSpawnedChildForRecord } from "./engine/engines/pi/session-runner.ts";
45
+ // [W6 R1 MF-5] 子进程注册改经 spawnedChildren 状态镜像公共面(engine/host/
46
+ // spawned-children.ts——镜像 + inproc 过渡委托,不再深路径 import inproc pi 引擎目录)。
47
+ import { registerSpawnedChildForRecord } from "./engine/host/spawned-children.ts";
43
48
  import type { SubagentStream } from "./stream-sink.ts";
44
49
  import type { SubagentService } from "./subagent-service.ts";
45
50
  import { toErrorMessage } from "../core/error-message.ts";
@@ -95,7 +100,8 @@ export class SubprocessAgentRunner implements AgentRunner {
95
100
  this.subagentService = deps.subagentService;
96
101
  this.ctxModel = deps.ctxModel;
97
102
  // [D4 聚合连带] 经 asEngineService 显式视图适配(原结构化直绑依赖查询面 public)。
98
- this.piEngine = createPiEngine(() => this.subagentService.asEngineService);
103
+ // [W6] 解析经 host 公共面(descriptor 路由 / inproc DI,见 pi-host-binding 注释)。
104
+ this.piEngine = resolveHostPiEnginePort(() => this.subagentService.asEngineService);
99
105
  }
100
106
 
101
107
  /**
@@ -138,10 +144,12 @@ export class SubprocessAgentRunner implements AgentRunner {
138
144
 
139
145
  // ── P4 路由(D3-② 单点:routeEngineForHost)+ D3-④ 预检 ──
140
146
  // 路由在最前——引擎身份决定 journal 路径与后续一切执行面。pi 快路径同步短路
141
- //(routed 非 Promise,零微任务——缺省路径时序与 P1 接线前完全一致,下游依赖
142
- // 「run 内首个 await 前已触达 executeAndAwait」的时序契约)。路由失败(未注册
143
- // id / probe 失败 + strict/守卫)与预检命中(capabilities 驱动,含 worktree——
144
- // workflow 域漏拦缺口修复)一并按「不 reject」契约转 result.error。
147
+ //(routed 非 Promise,零微任务)——首个 await 前完成**路由决策**(engine id 已定,
148
+ // A2 观测点);其后的执行经进程边界(cli 形态 spawn + 握手 + 帧往返必经 await),
149
+ // 旧「run 内首个 await 前已触达 executeAndAwait」时序契约由引擎协议化设计
150
+ // §3.5.3 作废放宽。路由失败(未注册 id / probe 失败 + strict/守卫)与预检命中
151
+ //(capabilities 驱动,含 worktree——workflow 域漏拦缺口修复)一并按「不 reject」
152
+ // 契约转 result.error。
145
153
  let route: EngineRouteResult;
146
154
  try {
147
155
  const routed = routeEngineForHost({
@@ -227,7 +235,7 @@ export class SubprocessAgentRunner implements AgentRunner {
227
235
  const { handle, outcome } = await route.engine.run(
228
236
  // [D6 合流] opts 直传——AgentCallOpts 即 EnginePort 任务形状(缺省路径零映射;
229
237
  // pi 边界一次直出由 PiEngine.agentCallToExecuteOptions 承担,逐字段等值由
230
- // engines/pi/__tests__/spawn-opts-direct.test.ts 对照表锁定)
238
+ // inproc pi 引擎目录/__tests__/spawn-opts-direct.test.ts 对照表锁定)
231
239
  opts,
232
240
  runCtx,
233
241
  );
@@ -8,6 +8,14 @@
8
8
  // - TUI 只读 Record/Details 快照,永不持有可变引用
9
9
 
10
10
  import type { GuiRenderResult } from "@xyz-agent/extension-protocol";
11
+ import type {
12
+ AgentUsage,
13
+ AgentUsageTotal,
14
+ ToolCall,
15
+ ToolCallResult,
16
+ Turn,
17
+ WorktreeHandle,
18
+ } from "@zhushanwen/subagent-engine-sdk";
11
19
 
12
20
  import type { AgentFailureKind } from "../orchestration/models/types.ts";
13
21
  import type { ModelInfo, ModelRegistryLike } from "./model-resolver.ts";
@@ -146,47 +154,35 @@ export type ExecutionMode = "background";
146
154
  // Agent 事件流(Core → Record 的唯一更新驱动)
147
155
  // ============================================================
148
156
 
149
- /**
150
- * Pi session.subscribe 上报的事件。Runtime 把它喂给 updateFromEvent。
151
- *
152
- * 设计:AgentEvent 携带 updateFromEvent 收口进 record 所需的**全部数据**——
153
- * tool_end 带 result(供 turn.toolCalls 存完整 ToolCall),无需翻译层旁路累积。
154
- *
155
- * ACP 词汇对照(D11 注记级校准,零行为变更;新引擎实现者按本表对齐语义,
156
- * 详见 docs/architecture/subagent-engine-gui-visibility.md §3.3 D11):
157
- * text_delta / thinking_delta ACP content blocks(text / thinking)
158
- * tool_start / tool_end ↔ ACP tool_call / tool_call_update
159
- * turn_end / message_end ACP prompt turn 终态(stop_reason + usage)
160
- * compaction ↔ ACP session/compaction
161
- * 本协议以 pi 为语义锚点(D3)——命名不迁移,对照表仅保证未来 AcpEngine 适配器
162
- * 与跨引擎 trace 映射的翻译成本最低。
163
- */
164
- export type AgentEvent =
165
- | { type: "tool_start"; toolName: string; args?: unknown }
166
- | { type: "tool_end"; toolName: string; args?: unknown; result?: ToolCallResult; isError?: boolean }
167
- | { type: "text_delta"; delta: string }
168
- | { type: "thinking_delta"; delta: string }
169
- | { type: "turn_end"; summary?: string }
170
- | { type: "message_end"; usage?: AgentUsage; error?: string }
171
- | { type: "compaction" }
172
- | { type: "error"; message: string };
173
-
174
- /** token 用量(message_end 时由 Core 累加进 record.totalTokens)。 */
175
- export interface AgentUsage {
176
- input: number;
177
- output: number;
178
- cacheRead: number;
179
- cacheWrite: number;
180
- /** 本 message 的成本(USD,来自 SDK usage.cost.total)。可选——无成本数据时缺省。 */
181
- cost?: number;
182
- }
183
-
184
- export interface AgentUsageTotal extends AgentUsage {
185
- /** 上述四项之和。投影时不再手工求和。 */
186
- total: number;
187
- /** 累计成本(USD,来自 SdkEvent.message.usage.cost.total 求和)。无成本数据时为 0。 */
188
- cost: number;
189
- }
157
+ // [S4 簇 3 收编] 事件面契约类型单源化(type-only):AgentEvent / AgentUsage /
158
+ // AgentUsageTotal / ToolCallResult / ToolCall / InternalToolCall / Turn 的本地定义
159
+ // 已删除,自 @zhushanwen/subagent-engine-sdk re-export(SDK protocol/contract-types.ts
160
+ // 是类型闭包 SSOT,core 反向 re-export 保上层消费面——import 方路径零改动;
161
+ // shared/agent-event.ts 转发层链条保持)。结构等价由 protocol-closure.test.ts
162
+ // 断言族守卫。
163
+ //
164
+ // AgentEvent 语义锚定(SDK 侧注释指向本处的对照权威源,勿删):
165
+ // - Pi session.subscribe 上报的事件。Runtime 把它喂给 updateFromEvent。
166
+ // - 设计:AgentEvent 携带 updateFromEvent 收口进 record 所需的**全部数据**——
167
+ // tool_end result(供 turn.toolCalls 存完整 ToolCall),无需翻译层旁路累积。
168
+ //
169
+ // ACP 词汇对照(D11 注记级校准,零行为变更;新引擎实现者按本表对齐语义,
170
+ // 详见 docs/architecture/subagent-engine-gui-visibility.md §3.3 D11):
171
+ // text_delta / thinking_delta ↔ ACP content blocks(text / thinking)
172
+ // tool_start / tool_end ↔ ACP tool_call / tool_call_update
173
+ // turn_end / message_end ↔ ACP prompt turn 终态(stop_reason + usage)
174
+ // compaction ↔ ACP session/compaction
175
+ // 本协议以 pi 为语义锚点(D3)——命名不迁移,对照表仅保证未来 AcpEngine 适配器
176
+ // 与跨引擎 trace 映射的翻译成本最低。
177
+ export type {
178
+ AgentEvent,
179
+ AgentUsage,
180
+ AgentUsageTotal,
181
+ InternalToolCall,
182
+ ToolCall,
183
+ ToolCallResult,
184
+ Turn,
185
+ } from "@zhushanwen/subagent-engine-sdk";
190
186
 
191
187
  /**
192
188
  * eventLog 条目(getEventLog 派生产出的元素)。所有字段 readonly。
@@ -249,69 +245,6 @@ export type SdkEvent = {
249
245
  reason?: string;
250
246
  };
251
247
 
252
- /** tool 调用结果(tool_execution_end 时累积,含 structured-output 的 details)。 */
253
- export interface ToolCallResult {
254
- content?: unknown[];
255
- details?: unknown;
256
- }
257
-
258
- /**
259
- * tool 调用(导出的纯净数据形状,不含内部状态)。
260
- *
261
- * tool_start 到达但 tool_end 未到时,调用为进行中;一旦 tool_end 到达,
262
- * result/isError 填充完成。对外投影(AgentResult.toolCalls / getAllToolCalls)
263
- * 一律返回此类型——**不泄漏 running/done/failed 内部状态机**。
264
- *
265
- * 进行中状态由 execution-record 内部的 `InternalToolCall`(= ToolCall + _status)承载,
266
- * 只存在于 record.turns[].toolCalls,跨边界导出时由 getAllToolCalls strip _status。
267
- */
268
- export interface ToolCall {
269
- toolName: string;
270
- args?: unknown;
271
- result?: ToolCallResult;
272
- isError?: boolean;
273
- }
274
-
275
- /**
276
- * 内部 ToolCall:在 ToolCall 基础上追加 _status 进行中状态标记与 startedTs 时间戳。
277
- *
278
- * running = tool_start 已收到但 tool_end 未到;
279
- * done/failed = tool_end 已到。
280
- *
281
- * 仅存在于 ExecutionRecord.turns[].toolCalls(Core 内部可变状态)。
282
- * 跨边界导出(getAllToolCalls → AgentResult.toolCalls / 持久化)由 getAllToolCalls
283
- * 映射回 ToolCall(丢弃 _status / startedTs),保证导出形状清洁。
284
- */
285
- export interface InternalToolCall extends ToolCall {
286
- _status: "running" | "done" | "failed";
287
- /** tool_start 到达时的墙钟时间戳(Date.now(),ms)。getEventLog 派生 tool 条目 ts 用。 */
288
- startedTs: number;
289
- }
290
-
291
- /**
292
- * 一个 turn 的完整内容(ExecutionRecord.turns[] 的元素)。
293
- *
294
- * 收口设计:text/thinking 流式累积**完整内容**(非 100 字切片),
295
- * toolCalls 存完整 ToolCall(含 result + _status 内部状态)。turn_end 到达后 closed=true,
296
- * 下次 text/thinking/tool 时开新 turn。
297
- *
298
- * eventLog / currentActivity / result 均从 turns[] 派生,不再独立存储。
299
- */
300
- export interface Turn {
301
- /** 本 turn assistant 正文(text_delta 流式累积,完整)。 */
302
- text: string;
303
- /** 本 turn 推理(thinking_delta 流式累积,完整)。 */
304
- thinking: string;
305
- /** 本 turn 工具调用(InternalToolCall:含完整 result + _status 进行中标记)。 */
306
- toolCalls: InternalToolCall[];
307
- /** 本 turn message_end 的 token 增量(聚合得 totalUsage)。 */
308
- usageDelta?: AgentUsage;
309
- /** turn_end 是否已到达。false=正在进行;true=已闭合,下次内容开新 turn。 */
310
- closed: boolean;
311
- /** turn_end 到达时的墙钟时间戳(Date.now(),ms)。getEventLog 派生 turn_end 条目 ts 用。 */
312
- closedTs?: number;
313
- }
314
-
315
248
  /** 一次 session 执行的完整结果。collectResult 产出,写入 Record.outcome。 */
316
249
  export interface AgentResult {
317
250
  text: string;
@@ -341,19 +274,10 @@ export interface AgentResult {
341
274
  // 本 section 先声明 ExecutionRecord 的组成值对象(WorktreeHandle / AliveMarker /
342
275
  // PatchResult 等),ExecutionRecord 本体及其文档注释在 section 末尾。
343
276
 
344
- /**
345
- * worktree handle 值对象。仅 worktree:true 时持有——worktree 是独立维度,
346
- * 需显式开启,fork alone 不创建 worktree
347
- * Object.freeze 守卫保证不可变。
348
- */
349
- export interface WorktreeHandle {
350
- /** checkout 目录(子 agent 工作目录,tmpdir 下)。 */
351
- readonly path: string;
352
- readonly branch: string;
353
- readonly baseCommit: string;
354
- /** 主仓库根目录(cleanup/scan 需要,不再靠路径反推)。 */
355
- readonly mainCwd: string;
356
- }
277
+ // [S4 簇 3 收编] WorktreeHandle 本地定义已删除,自 SDK re-export(原为结构等价
278
+ // 副本,单源化后 SDK contract-types 是唯一定义点;「仅 worktree:true 时持有、
279
+ // Object.freeze 守卫不可变」的语义注释见消费方 worktree-manager / worktree-git-ops)。
280
+ export type { WorktreeHandle } from "@zhushanwen/subagent-engine-sdk";
357
281
 
358
282
  /** alive marker:子进程存活标记,用于心跳检测和 crash 推断。 */
359
283
  export interface AliveMarker {
@@ -1,216 +1,15 @@
1
1
  // src/execution/ui-channels.ts
2
2
  //
3
- // UI channel 提取(marker 解析)+ channel 注册表。
4
- //
5
- // channel 是扩展协议自定义的业务路由标识,由 NUL 前缀 marker 标记。
6
- // 已知 marker(来自 @xyz-agent/extension-protocol):
7
- // - ASK_USER_MARKER = "\0XYZ_ASK_USER" 走 select method,出现在 title
8
- // (options[0] = JSON payload {questions, allowCancel})
9
- // - GUI_WIDGET_MARKER = "\0XYZ_GUI_WIDGET:" setWidget method,出现在 widgetLines[0]
10
- // (同行 marker 后紧跟 JSON payload {component})
11
- //
12
- // channel 提取位置随 method 变(.fix-plans/00-master-summary.md §一冲突 2):
13
- // - select → 从 title 解析 NUL 前缀(payload 从 options[0] 取)
14
- // - setWidget → 从 widgetLines[0] 解析 NUL 前缀(payload 从同行 marker 后取)
15
- // - 其他 method → 无 channel(返回 {})
16
- //
17
- // channel 名规范化:去 "XYZ_" 命名空间前缀,去尾部 ":",小写化。
18
- // XYZ_ASK_USER → ask_user
19
- // XYZ_GUI_WIDGET → gui_widget
20
- //
21
- // 本模块是协议层工具(method/marker 都是协议概念),不感知业务。
22
-
23
- /** NUL 前缀字符。Pi extension-protocol 用 NUL(\0)标记控制行,
24
- * 避免与用户可见文本冲突。 */
25
- const NUL = "\0";
26
-
27
- /** channel 提取结果。channel 无 NUL 前缀、字段缺失、JSON parse 失败时
28
- * channel 与 channelPayload 均为 undefined(返回 {})。 */
29
- export interface ParsedChannel {
30
- /** 规范化后的 channel 名(如 "ask_user"、"gui_widget")。
31
- * 无 marker 或解析失败时为 undefined。 */
32
- channel?: string;
33
- /** marker 标记的结构化 payload(已 JSON.parse)。
34
- * ask_user: {questions, allowCancel};gui_widget: {component}。
35
- * payload 来源缺失或 JSON parse 失败时为 undefined(channel 仍可解析)。 */
36
- channelPayload?: unknown;
37
- }
38
-
39
- /** parseChannel 入参的最小形状。
40
- * method 是判别字段;按 method 不同,对应字段(select 的 title/options、
41
- * setWidget 的 widgetLines)可选出现。其他 method 的字段统称 [key:string]。 */
42
- export interface ExtensionUiRequestLike {
43
- method: string;
44
- /** select method:title 字段(可能含 ASK_USER_MARKER NUL 前缀)。 */
45
- title?: string;
46
- /** select method:options 数组(options[0] 可能是 channel payload 的 JSON)。 */
47
- options?: string[];
48
- /** setWidget method:widgetKey 字段。 */
49
- widgetKey?: string;
50
- /** setWidget method:widgetLines 数组(widgetLines[0] 可能含 GUI_WIDGET_MARKER)。 */
51
- widgetLines?: string[] | undefined;
52
- /** 其他 method 的任意字段(容错:允许测试和未来扩展传入额外字段)。 */
53
- [key: string]: unknown;
54
- }
55
-
56
- /** channel handler 签名:接收 UiRequest,返回 UiResponse。
57
- * 具体类型定义在 session-runner.ts(W2 工作),此处用最小形状避免循环依赖。
58
- * handler 实现方按 channel 注册,由 session-runner 按 req.channel 分派。 */
59
- export type ChannelHandler = (req: unknown) => Promise<unknown>;
60
-
61
- /** channel 注册表接口。职责单一:只管业务路由,不管排队、不管透传判定。
62
- * - register(channel, handler):注册 channel 对应的 handler(同名覆盖)
63
- * - resolve(channel):取 channel 对应的 handler,未注册返回 undefined
64
- * - list():列举所有已注册 channel 名 */
65
- export interface UiChannelRegistry {
66
- register(channel: string, handler: ChannelHandler): void;
67
- resolve(channel: string): ChannelHandler | undefined;
68
- list(): string[];
69
- }
70
-
71
- /** 规范化 channel 名。
72
- * 输入是 NUL 前缀后的字面量(如 "XYZ_ASK_USER"、"XYZ_GUI_WIDGET:")。
73
- * 规则:
74
- * 1. 去 "XYZ_" 命名空间前缀(协议命名空间标识,非业务语义)
75
- * 2. 去尾部 ":"(GUI_WIDGET 等"行内 payload"型 marker 的分隔符)
76
- * 3. 小写化(XYZ_ASK_USER → ask_user)
77
- *
78
- * 例:
79
- * "XYZ_ASK_USER" → "ask_user"
80
- * "XYZ_GUI_WIDGET:" → "gui_widget"
81
- * "FOO_BAR" → "foo_bar"(无 XYZ_ 前缀也容忍,去前缀仅当字面量以 XYZ_ 开头) */
82
- function normalizeChannelName(markerLiteral: string): string {
83
- let name = markerLiteral;
84
- // 去 "XYZ_" 命名空间前缀(仅当以此开头)
85
- if (name.startsWith("XYZ_")) {
86
- name = name.slice("XYZ_".length);
87
- }
88
- // 去尾部 ":"(行内 payload 型 marker 的分隔符)
89
- if (name.endsWith(":")) {
90
- name = name.slice(0, -1);
91
- }
92
- return name.toLowerCase();
93
- }
94
-
95
- /** 从 marker 字面量字符串解析 channel 名。
96
- * 输入 str 形如 "\0XYZ_ASK_USER"(marker 占满整个字段,payload 在别处)。
97
- * 无 NUL 前缀返回 undefined。 */
98
- function parseMarkerFromField(str: string): string | undefined {
99
- if (!str.startsWith(NUL)) return undefined;
100
- // 去掉 NUL 前缀,取剩余字面量作为 marker literal
101
- const literal = str.slice(NUL.length);
102
- if (literal === "") return undefined;
103
- return normalizeChannelName(literal);
104
- }
105
-
106
- /** 从 marker + 行内 payload 字符串解析 channel 名 + payload。
107
- * 输入 str 形如 "\0XYZ_GUI_WIDGET:{...json...}"(marker 与 payload 在同一行)。
108
- * 无 NUL 前缀返回 undefined。
109
- * payload 解析失败时不抛(返回 channel 名,payload 由调用方处理)。 */
110
- function parseInlineMarkerFromField(str: string): { channel: string } | undefined {
111
- if (!str.startsWith(NUL)) return undefined;
112
- const rest = str.slice(NUL.length);
113
- // marker literal 与 payload 的分界:第一个 ":" 或行尾
114
- // GUI_WIDGET_MARKER 格式为 "\0XYZ_GUI_WIDGET:" + json,分界是 ":"
115
- const colonIdx = rest.indexOf(":");
116
- let literal: string;
117
- if (colonIdx >= 0) {
118
- literal = rest.slice(0, colonIdx + 1); // 含 ":",normalizeChannelName 会去尾部 ":"
119
- } else {
120
- literal = rest;
121
- }
122
- if (literal === "") return undefined;
123
- return { channel: normalizeChannelName(literal) };
124
- }
125
-
126
- /** 从 select.title 解析 channel(payload 从 options[0] 取)。
127
- * - title 无 NUL 前缀 → undefined
128
- * - title 含 marker → channel 名;payload 从 options[0] JSON.parse(失败/缺失 → undefined) */
129
- function parseFromMarkerString(
130
- title: string | undefined,
131
- options: string[] | undefined,
132
- ): ParsedChannel {
133
- if (title === undefined) return {};
134
- const channel = parseMarkerFromField(title);
135
- if (channel === undefined) return {};
136
- // payload 从 options[0] 取(ask_user 协议:title 是 marker,options[0] 是 JSON payload)
137
- let payload: unknown;
138
- if (options !== undefined && options.length > 0) {
139
- try {
140
- payload = JSON.parse(options[0]);
141
- } catch {
142
- payload = undefined; // JSON parse 失败:不抛,channel 仍解析
143
- }
144
- }
145
- return { channel, channelPayload: payload };
146
- }
147
-
148
- /** 从 setWidget.widgetLines[0] 解析 channel(payload 从同行 marker 后取)。
149
- * - widgetLines 缺失/空数组/首行无 NUL 前缀 → undefined
150
- * - 首行含 marker → channel 名;payload 从 marker 后的 JSON 取(失败 → undefined) */
151
- function parseFromMarkerArray(
152
- widgetLines: string[] | undefined,
153
- ): ParsedChannel {
154
- if (widgetLines === undefined || widgetLines.length === 0) return {};
155
- const firstLine = widgetLines[0];
156
- if (typeof firstLine !== "string") return {};
157
- const parsed = parseInlineMarkerFromField(firstLine);
158
- if (parsed === undefined) return {};
159
- // payload 从 marker 后的 JSON 取(GUI_WIDGET 协议:marker 与 payload 同行)
160
- let payload: unknown;
161
- const rest = firstLine.slice(NUL.length);
162
- const colonIdx = rest.indexOf(":");
163
- if (colonIdx >= 0) {
164
- const jsonStr = rest.slice(colonIdx + 1);
165
- if (jsonStr !== "") {
166
- try {
167
- payload = JSON.parse(jsonStr);
168
- } catch {
169
- payload = undefined; // JSON parse 失败:不抛,channel 仍解析
170
- }
171
- }
172
- }
173
- return { channel: parsed.channel, channelPayload: payload };
174
- }
175
-
176
- /** 按 method 分派解析 channel。
177
- *
178
- * - select → 从 title 解析 NUL 前缀(payload 从 options[0])
179
- * - setWidget → 从 widgetLines[0] 解析 NUL 前缀(payload 从同行 marker 后)
180
- * - 其他 method → {}(无 channel 提取位置)
181
- *
182
- * 边界(均不抛错):
183
- * - title/widgetLines 字段缺失 → {}
184
- * - 无 NUL 前缀 → {}
185
- * - JSON parse 失败 → channel 仍解析,channelPayload 为 undefined
186
- *
187
- * @param req ExtensionUiRequestLike(method + 对应字段)
188
- * @returns ParsedChannel(channel/channelPayload 可选) */
189
- export function parseChannel(req: ExtensionUiRequestLike): ParsedChannel {
190
- switch (req.method) {
191
- case "select":
192
- return parseFromMarkerString(req.title, req.options);
193
- case "setWidget":
194
- return parseFromMarkerArray(req.widgetLines);
195
- default:
196
- return {};
197
- }
198
- }
199
-
200
- /** 创建 channel 注册表实例。
201
- * 进程级单例(通常由 SubagentService 持有一个实例,跨所有子进程共享)。
202
- * register 同名 channel 会覆盖旧 handler。 */
203
- export function createUiChannelRegistry(): UiChannelRegistry {
204
- const handlers = new Map<string, ChannelHandler>();
205
- return {
206
- register(channel: string, handler: ChannelHandler): void {
207
- handlers.set(channel, handler);
208
- },
209
- resolve(channel: string): ChannelHandler | undefined {
210
- return handlers.get(channel);
211
- },
212
- list(): string[] {
213
- return Array.from(handlers.keys());
214
- },
215
- };
216
- }
3
+ // UI channel 提取(marker 解析)+ channel 注册表的 re-export shim:实现体单源
4
+ // @zhushanwen/subagent-engine-sdk(自本文件逐字等价移入 SDK,round1-reuse R1;
5
+ // core SDK 边界正向合法)。core 内消费方(channel-registry-access /
6
+ // ui-request-handler-factory)import 路径保持不变,barrel 导出面零变化。
7
+
8
+ export {
9
+ type ChannelHandler,
10
+ createUiChannelRegistry,
11
+ type ExtensionUiRequestLike,
12
+ parseChannel,
13
+ type ParsedChannel,
14
+ type UiChannelRegistry,
15
+ } from "@zhushanwen/subagent-engine-sdk";
@@ -2,10 +2,13 @@
2
2
  //
3
3
  // UI 请求 handler 工厂(透传 + 排队总控)。
4
4
  //
5
- // 按 ctx.mode(ExtensionMode)创建合适的 UiRequestHandler,让 SubagentService 持有后
6
- // 经 session-runner 透传给子进程的 extension_ui_request。本模块是「handler 注入链路」的
7
- // 组装点:把 channel registry(业务路由)+ dialog queue(L2 跨子进程串行)+ mode 分流
8
- //(TUI/GUI/headless)粘合成一个 handler。
5
+ // 按 ctx.mode(ExtensionMode)创建合适的 UiRequestHandlerSubagentService 持有后经
6
+ // host-ui-endpoint 登记处注入协议客户端——引擎进程的 extension_ui_request
7
+ // host/askUser 反向通道到达本 handler([W3] inproc L1 队列 inproc UI 请求队列(已删) 随
8
+ // inproc pi 引擎目录 删除消亡,「run 生命周期内闭包队列」语义由引擎包内等价物 +
9
+ // 协议应答路径承接)。本模块是「handler 注入链路」的组装点:把 channel registry
10
+ //(业务路由)+ dialog queue(L2 跨子进程串行)+ mode 分流(TUI/GUI/headless)
11
+ // 粘合成一个 handler。
9
12
  //
10
13
  // 设计依据(.fix-plans/00-master-summary.md):
11
14
  // - §一冲突 2「透传矩阵」:
@@ -9,9 +9,9 @@ import type { ExtensionMode } from "./host-mode.ts";
9
9
 
10
10
  const logger = getLogger("subagents");
11
11
 
12
- // ── 跨模块桥接(ui-request-queue 无 ctx.service 引用时走这里) ──
12
+ // ── 跨模块桥接(inproc UI 请求队列(已删) 无 ctx.service 引用时走这里) ──
13
13
  //
14
- // ui-request-queue.handleUiRequest 在 ctx.uiRequestHandler 缺失时需要触发去重告警,
14
+ // inproc UI 请求队列 handleUiRequest(已删) 在 ctx.uiRequestHandler 缺失时需要触发去重告警,
15
15
  // 但 SessionRunnerContext 不持有 service 引用(改 ctx 签名超出本组 4 文件范围)。
16
16
  // 解法:SubagentService 构造后调 registerGlobalObservability(this.uiObservability)
17
17
  // 把进程单例挂到 globalThis;queue 走 notifyMissingHandlerGlobal 路径调到同一实例,
@@ -0,0 +1,67 @@
1
+ // src/execution/workflow-state-root.ts
2
+ //
3
+ // [F-1 修复] pi 宿主 WorkflowRun state 目录解析(与 pi 壳 JsonlRunStore 同源布局)。
4
+ //
5
+ // 为什么存在:pi 宿主 workflow 域的 run state 真实落盘 = JsonlRunStore 的
6
+ // `<sessionDir>/workflow-state/<runId>.jsonl`,sessionDir 由 extension 侧
7
+ // `extensions/universal/subagent-workflow/src/session-lifecycle.ts` 的
8
+ // resolveSessionDir() 推导。core 侧两个读侧装配点(round-supervisor 的注册对账
9
+ // sweep、idle-gc 的 WorkflowRun GC)曾用 FileRunStore 缺省根
10
+ // `<dataRoot>/workflow-state`(zcode 宿主布局)——两目录生产不相交,读侧恒 ENOENT:
11
+ // sweep 把活跃 run 判 missing 补注销(误注销活跃 run),WorkflowRun GC 恒空转。
12
+ //
13
+ // core 不能 import extension——本文件按 resolveSessionDir 同规则在 core 侧重写推导,
14
+ // 两处注释互指锚定([同步纪律] 改 sessionDir 布局时必须同批改本文件与
15
+ // session-lifecycle.ts,漂移信号 = sweep 补注销活跃 run / GC 空转)。
16
+ //
17
+ // agentDir 推导锚定 pi 实装版 0.84.4 dist config.js getAgentDir:
18
+ // `process.env.PI_CODING_AGENT_DIR || join(homedir(), ".pi", "agent")`
19
+ // (ENV_AGENT_DIR = PI_CODING_AGENT_DIR、CONFIG_DIR_NAME = piConfig.configDir = ".pi",
20
+ // 无 piConfig.name 覆盖)。pi 升级若改 getAgentDir 语义 → 本推导漂移,可见信号同上。
21
+
22
+ import { existsSync } from "node:fs";
23
+ import { homedir } from "node:os";
24
+ import { join } from "node:path";
25
+
26
+ /** pi SDK getAgentDir 的 env 覆盖通道(实装版 dist config.js ENV_AGENT_DIR)。 */
27
+ const PI_AGENT_DIR_ENV = "PI_CODING_AGENT_DIR";
28
+
29
+ /** pi SDK 缺省 agent 目录分量(实装版 dist config.js:CONFIG_DIR_NAME + "agent")。 */
30
+ const DEFAULT_PI_AGENT_DIR_PARTS = [".pi", "agent"] as const;
31
+
32
+ /** resolvePiWorkflowStateDir 的注入面(测试用;生产缺省全走真实推导)。 */
33
+ export interface PiWorkflowStateDirOptions {
34
+ /** agent 配置目录覆盖(缺省 = PI_CODING_AGENT_DIR env 或 ~/.pi/agent)。 */
35
+ agentDir?: string;
36
+ /** cwd 覆盖(缺省 process.cwd()——对齐 session-lifecycle 用进程 cwd 而非 ctx.cwd)。 */
37
+ cwd?: string;
38
+ }
39
+
40
+ /**
41
+ * 解析 pi 宿主 WorkflowRun state 目录(`<sessionDir>/workflow-state`)。
42
+ *
43
+ * sessionDir 推导(与 session-lifecycle.resolveSessionDir 逐段同构,见文件头注):
44
+ * - cwd-slug = `--<cwd 去开头分隔符、`/`→`-`>--`(extension 侧字面规则——core 的
45
+ * encodeCwd 额外折叠 `:` 与 `\`,与建目录方不一致,此处不共用);
46
+ * - `<agentDir>/sessions/<slug>` 目录存在则用之(该目录由 workflow 域首次落盘
47
+ * 创建——cwd 有过 workflow run 才存在),否则回退 agentDir 根
48
+ * (JsonlRunStore 的 mkdir recursive 使首写直接落 agentDir 根,两侧探测一致)。
49
+ *
50
+ * 只读解析(existsSync 探测),无目录创建副作用——与 FileRunStore 的 save 侧
51
+ * mkdir 职责分离。
52
+ */
53
+ export function resolvePiWorkflowStateDir(opts?: PiWorkflowStateDirOptions): string {
54
+ const agentDir = opts?.agentDir ?? resolvePiAgentDir();
55
+ const cwd = opts?.cwd ?? process.cwd();
56
+ const sessionSlug = `--${cwd.replace(/^\//, "").replace(/\//g, "-")}--`;
57
+ const sessionScopedDir = join(agentDir, "sessions", sessionSlug);
58
+ const sessionDir = existsSync(sessionScopedDir) ? sessionScopedDir : agentDir;
59
+ return join(sessionDir, "workflow-state");
60
+ }
61
+
62
+ /** pi agent 目录(getAgentDir 同语义;推导锚定见文件头注)。 */
63
+ function resolvePiAgentDir(): string {
64
+ const envDir = process.env[PI_AGENT_DIR_ENV];
65
+ if (envDir !== undefined && envDir !== "") return envDir;
66
+ return join(homedir(), ...DEFAULT_PI_AGENT_DIR_PARTS);
67
+ }
@@ -25,6 +25,8 @@
25
25
  // 职责,不在纯内核复刻——git index.lock 冲突瞬时态正好落降级路径②,而非内核故障。
26
26
 
27
27
  import { execFile } from "node:child_process";
28
+
29
+ import { buildOutboundChildEnv } from "@zhushanwen/subagent-engine-sdk";
28
30
  import * as fs from "node:fs";
29
31
 
30
32
  import { getLogger } from "../core/logger.ts";
@@ -115,6 +117,9 @@ export function gitRun(
115
117
  timeout: opts.timeout ?? GIT_TIMEOUT_MS,
116
118
  ...(opts.maxBuffer !== undefined ? { maxBuffer: opts.maxBuffer } : {}),
117
119
  encoding: "utf-8",
120
+ // 出站卫生(R3 MF-C,impl-plan §2.12):同 worktree-manager.ts gitRunAsync——
121
+ // deny 键不进 git 子进程,git hooks 后代不再可能消费 deny 键。
122
+ env: buildOutboundChildEnv({ parentEnv: process.env }),
118
123
  },
119
124
  (err, stdout, stderr) => {
120
125
  if (err) {
@@ -23,6 +23,8 @@
23
23
  // 声称的「tmpdir + 分支对账兜底」由此成为代码。
24
24
 
25
25
  import { execFile } from "node:child_process";
26
+
27
+ import { buildOutboundChildEnv } from "@zhushanwen/subagent-engine-sdk";
26
28
  import * as fs from "node:fs";
27
29
  import * as os from "node:os";
28
30
  import * as path from "node:path";
@@ -713,7 +715,15 @@ export class WorktreeManager {
713
715
  execFile(
714
716
  "git",
715
717
  args,
716
- { cwd: opts.cwd, timeout: opts.timeout ?? GIT_TIMEOUT_MS, encoding: "utf-8" },
718
+ {
719
+ cwd: opts.cwd,
720
+ timeout: opts.timeout ?? GIT_TIMEOUT_MS,
721
+ encoding: "utf-8",
722
+ // 出站卫生(R3 MF-C,impl-plan §2.12):deny 键不进 git 子进程——
723
+ // git hooks 等后代不再可能消费生命周期标志 / WS 令牌。SDK 版缺省
724
+ // 全量继承父 env + deny 剥除,行为差异仅 deny 键剥除。
725
+ env: buildOutboundChildEnv({ parentEnv: process.env }),
726
+ },
717
727
  (err, stdout, stderr) => {
718
728
  if (err) {
719
729
  const execErr = err as Error & { code?: unknown; killed?: boolean; signal?: string };