@zhushanwen/pi-subagent-workflow 8.5.0 → 8.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 (336) hide show
  1. package/package.json +13 -16
  2. package/relay/relay.mjs +1 -1
  3. package/src/host/__tests__/pi-host.test.ts +214 -0
  4. package/src/host/pi-host.ts +109 -0
  5. package/src/index.ts +142 -32
  6. package/src/injectors/__tests__/engine-awareness.test.ts +292 -0
  7. package/src/injectors/__tests__/engine-section-stability.test.ts +341 -0
  8. package/src/injectors/__tests__/subagent-list-injector.test.ts +5 -5
  9. package/src/injectors/__tests__/workflow-list-injector.test.ts +5 -5
  10. package/src/injectors/engine-awareness.ts +123 -0
  11. package/src/injectors/model-list-injector.ts +1 -1
  12. package/src/injectors/subagent-list-injector.ts +8 -8
  13. package/src/injectors/workflow-list-injector.ts +8 -8
  14. package/src/interface/__tests__/detectors.test.ts +3 -3
  15. package/src/interface/__tests__/subagent-tool-path-guard.test.ts +157 -0
  16. package/src/interface/__tests__/subagent-tool-prompt.test.ts +12 -0
  17. package/src/interface/__tests__/tool-workflow-script-generate.test.ts +2 -2
  18. package/src/interface/__tests__/tool-workflow-throw-paths.test.ts +1 -1
  19. package/src/interface/bg-notify-render.ts +34 -13
  20. package/src/interface/commands.ts +3 -3
  21. package/src/interface/format.ts +2 -2
  22. package/src/interface/helpers.ts +3 -3
  23. package/src/interface/list-component.ts +4 -4
  24. package/src/interface/list-shared.ts +2 -2
  25. package/src/interface/list-view.ts +2 -2
  26. package/src/interface/subagent-actions.ts +288 -19
  27. package/src/interface/subagent-tool-schema.ts +163 -0
  28. package/src/interface/subagent-tool.ts +65 -129
  29. package/src/interface/subagents.ts +5 -5
  30. package/src/interface/tool-render.ts +34 -2
  31. package/src/interface/tool-workflow-script.ts +4 -4
  32. package/src/interface/tool-workflow.ts +6 -6
  33. package/src/interface/views/WorkflowsView.ts +5 -5
  34. package/src/interface/views/__tests__/WorkflowsView-signature.test.ts +3 -3
  35. package/src/interface/views/__tests__/detail-content-session-file.test.ts +2 -2
  36. package/src/interface/views/detail-content.ts +4 -4
  37. package/src/interface/views/format.ts +4 -4
  38. package/src/{orchestration/jsonl-run-store.ts → jsonl-run-store.ts} +132 -18
  39. package/src/execution/__tests__/__fixtures__/notifier-golden-snapshots.json +0 -53
  40. package/src/execution/__tests__/__fixtures__/truncline.snapshot.json +0 -1
  41. package/src/execution/__tests__/agent-registry.test.ts +0 -363
  42. package/src/execution/__tests__/agent-result-mapper.test.ts +0 -150
  43. package/src/execution/__tests__/alive-store.test.ts +0 -147
  44. package/src/execution/__tests__/ask-user-transit-e2e.test.ts +0 -490
  45. package/src/execution/__tests__/before-agent-start-injection.test.ts +0 -132
  46. package/src/execution/__tests__/bg-notify-render.test.ts +0 -256
  47. package/src/execution/__tests__/channel-registry-handshake.test.ts +0 -243
  48. package/src/execution/__tests__/chat-engine-routing.test.ts +0 -597
  49. package/src/execution/__tests__/chatmode-first-round-closure-service.test.ts +0 -365
  50. package/src/execution/__tests__/chatmode-first-round-closure-spawn.test.ts +0 -190
  51. package/src/execution/__tests__/chatmode-round-notify-real-chain.test.ts +0 -215
  52. package/src/execution/__tests__/concurrency-pool.test.ts +0 -250
  53. package/src/execution/__tests__/config.test.ts +0 -110
  54. package/src/execution/__tests__/conversation-wiring.test.ts +0 -198
  55. package/src/execution/__tests__/crash-recovery.test.ts +0 -320
  56. package/src/execution/__tests__/delivery-methods.test.ts +0 -385
  57. package/src/execution/__tests__/dialog-queue.test.ts +0 -299
  58. package/src/execution/__tests__/epipe-fallback.test.ts +0 -241
  59. package/src/execution/__tests__/execute-and-await-worktree.test.ts +0 -243
  60. package/src/execution/__tests__/execute-nesting.test.ts +0 -323
  61. package/src/execution/__tests__/execute-options-mapper.test.ts +0 -189
  62. package/src/execution/__tests__/execution-record.test.ts +0 -1284
  63. package/src/execution/__tests__/finalize-record.test.ts +0 -368
  64. package/src/execution/__tests__/finalized-marker.test.ts +0 -82
  65. package/src/execution/__tests__/format-schema-instruction.test.ts +0 -138
  66. package/src/execution/__tests__/format.test.ts +0 -458
  67. package/src/execution/__tests__/gc-timer.test.ts +0 -184
  68. package/src/execution/__tests__/get-record-for-action-restart.test.ts +0 -254
  69. package/src/execution/__tests__/gui-mode-dispatch.test.ts +0 -59
  70. package/src/execution/__tests__/helpers/mock-extension-api.ts +0 -30
  71. package/src/execution/__tests__/helpers/spawn-mock.ts +0 -238
  72. package/src/execution/__tests__/host-mode.test.ts +0 -87
  73. package/src/execution/__tests__/index-session-start-identity.test.ts +0 -371
  74. package/src/execution/__tests__/index-session-start.test.ts +0 -593
  75. package/src/execution/__tests__/lifecycle-manager-lock.test.ts +0 -211
  76. package/src/execution/__tests__/lifecycle-manager.test.ts +0 -337
  77. package/src/execution/__tests__/lifecycle-predicates.test.ts +0 -116
  78. package/src/execution/__tests__/list-component.test.ts +0 -401
  79. package/src/execution/__tests__/list-fields.test.ts +0 -109
  80. package/src/execution/__tests__/manifest-parentid.test.ts +0 -117
  81. package/src/execution/__tests__/model-resolver.test.ts +0 -413
  82. package/src/execution/__tests__/nested-visibility-env-propagation.test.ts +0 -287
  83. package/src/execution/__tests__/nested-visibility.test.ts +0 -325
  84. package/src/execution/__tests__/notifier-flush.test.ts +0 -574
  85. package/src/execution/__tests__/notifier-golden-snapshot.test.ts +0 -261
  86. package/src/execution/__tests__/one-shot-upgrade.test.ts +0 -205
  87. package/src/execution/__tests__/output-collector.test.ts +0 -61
  88. package/src/execution/__tests__/parent-child-matrix.test.ts +0 -336
  89. package/src/execution/__tests__/path-encoding.test.ts +0 -104
  90. package/src/execution/__tests__/pi-invocation.test.ts +0 -134
  91. package/src/execution/__tests__/record-store.test.ts +0 -1057
  92. package/src/execution/__tests__/records-cwd-isolation.test.ts +0 -91
  93. package/src/execution/__tests__/recursive-visibility-baseline.test.ts +0 -339
  94. package/src/execution/__tests__/recursive-visibility-env.test.ts +0 -273
  95. package/src/execution/__tests__/relay-agent.test.ts +0 -448
  96. package/src/execution/__tests__/relay-env.test.ts +0 -42
  97. package/src/execution/__tests__/resource-policy.test.ts +0 -109
  98. package/src/execution/__tests__/rpc-mode.test.ts +0 -89
  99. package/src/execution/__tests__/run-and-finalize-chatmode.test.ts +0 -267
  100. package/src/execution/__tests__/run-spawn-chatmode-settled.test.ts +0 -253
  101. package/src/execution/__tests__/run-spawn-edges.test.ts +0 -644
  102. package/src/execution/__tests__/run-spawn-integration.test.ts +0 -933
  103. package/src/execution/__tests__/run-spawn-resume.test.ts +0 -322
  104. package/src/execution/__tests__/run-spawn-rpc-mode.test.ts +0 -196
  105. package/src/execution/__tests__/sdk-contract.test.ts +0 -273
  106. package/src/execution/__tests__/session-context-resolver.test.ts +0 -167
  107. package/src/execution/__tests__/session-file-gc.test.ts +0 -293
  108. package/src/execution/__tests__/session-pending.test.ts +0 -197
  109. package/src/execution/__tests__/session-reconstructor.test.ts +0 -379
  110. package/src/execution/__tests__/session-runner-epipe.test.ts +0 -178
  111. package/src/execution/__tests__/session-runner-schema-env.test.ts +0 -311
  112. package/src/execution/__tests__/session-start-reaper.test.ts +0 -233
  113. package/src/execution/__tests__/spawn-args.test.ts +0 -434
  114. package/src/execution/__tests__/spawn-event-adapter-rpc.test.ts +0 -189
  115. package/src/execution/__tests__/spawn-event-adapter.test.ts +0 -167
  116. package/src/execution/__tests__/spawn-worktree-guidance.test.ts +0 -207
  117. package/src/execution/__tests__/spawned-children.test.ts +0 -92
  118. package/src/execution/__tests__/startup-config-declaration.test.ts +0 -35
  119. package/src/execution/__tests__/status-refactor.test.ts +0 -345
  120. package/src/execution/__tests__/stdin-writer.test.ts +0 -463
  121. package/src/execution/__tests__/stream-sink-retirement.test.ts +0 -261
  122. package/src/execution/__tests__/subagent-service-abort.test.ts +0 -60
  123. package/src/execution/__tests__/subagent-service-message-close.test.ts +0 -629
  124. package/src/execution/__tests__/subagent-service-parent-guard.test.ts +0 -180
  125. package/src/execution/__tests__/subagent-service.test.ts +0 -788
  126. package/src/execution/__tests__/subprocess-agent-runner-routing.test.ts +0 -310
  127. package/src/execution/__tests__/subprocess-agent-runner.test.ts +0 -506
  128. package/src/execution/__tests__/temp-prompt.test.ts +0 -53
  129. package/src/execution/__tests__/timeout-integration.test.ts +0 -397
  130. package/src/execution/__tests__/tombstone-store.test.ts +0 -73
  131. package/src/execution/__tests__/tool-action.test.ts +0 -385
  132. package/src/execution/__tests__/truncline-snapshot.test.ts +0 -81
  133. package/src/execution/__tests__/turn-limiter-semantics.test.ts +0 -194
  134. package/src/execution/__tests__/turn-limiter.test.ts +0 -65
  135. package/src/execution/__tests__/ui-channels.test.ts +0 -187
  136. package/src/execution/__tests__/ui-interaction-model.test.ts +0 -67
  137. package/src/execution/__tests__/ui-request-handler-factory.test.ts +0 -370
  138. package/src/execution/__tests__/ui-request-handler.test.ts +0 -204
  139. package/src/execution/__tests__/ui-request-observability.test.ts +0 -114
  140. package/src/execution/__tests__/ui-request-queue.test.ts +0 -133
  141. package/src/execution/__tests__/worktree-manager.test.ts +0 -633
  142. package/src/execution/__tests__/worktree-pid-registration.integration.test.ts +0 -229
  143. package/src/execution/__tests__/worktree-reconcile.integration.test.ts +0 -181
  144. package/src/execution/__tests__/worktree-registry.test.ts +0 -199
  145. package/src/execution/agent-registry.ts +0 -193
  146. package/src/execution/agent-result-mapper.ts +0 -90
  147. package/src/execution/alive-store.ts +0 -92
  148. package/src/execution/argv-mirror.ts +0 -109
  149. package/src/execution/best-effort.ts +0 -38
  150. package/src/execution/channel-registry-access.ts +0 -144
  151. package/src/execution/concurrency-pool.ts +0 -116
  152. package/src/execution/config.ts +0 -96
  153. package/src/execution/dialog-queue.ts +0 -330
  154. package/src/execution/engine/__tests__/common/data-dir.test.ts +0 -53
  155. package/src/execution/engine/__tests__/common/errors.test.ts +0 -132
  156. package/src/execution/engine/__tests__/common/event-journal.test.ts +0 -177
  157. package/src/execution/engine/__tests__/common/kill-chain.test.ts +0 -192
  158. package/src/execution/engine/__tests__/common/nesting-guard.test.ts +0 -81
  159. package/src/execution/engine/__tests__/common/persona-router.test.ts +0 -123
  160. package/src/execution/engine/__tests__/common/pool-manager.test.ts +0 -154
  161. package/src/execution/engine/__tests__/common/schema-emulation.test.ts +0 -128
  162. package/src/execution/engine/__tests__/conformance/__fixtures__/pi-golden-events.json +0 -28
  163. package/src/execution/engine/__tests__/conformance/agent-event-invariants.ts +0 -141
  164. package/src/execution/engine/__tests__/conformance/contract.abort.test.ts +0 -109
  165. package/src/execution/engine/__tests__/conformance/contract.agent-events.test.ts +0 -101
  166. package/src/execution/engine/__tests__/conformance/contract.probe.test.ts +0 -77
  167. package/src/execution/engine/__tests__/conformance/contract.read-degradation.test.ts +0 -104
  168. package/src/execution/engine/__tests__/conformance/contract.relay.test.ts +0 -342
  169. package/src/execution/engine/__tests__/conformance/engine-conformance.live.test.ts +0 -201
  170. package/src/execution/engine/__tests__/conformance/golden-replay.pi.test.ts +0 -76
  171. package/src/execution/engine/__tests__/conformance/golden-replay.zcode.test.ts +0 -79
  172. package/src/execution/engine/__tests__/engine-discovery.test.ts +0 -87
  173. package/src/execution/engine/__tests__/engines-declaration.test.ts +0 -36
  174. package/src/execution/engine/__tests__/model-prompt.test.ts +0 -85
  175. package/src/execution/engine/__tests__/paths.test.ts +0 -39
  176. package/src/execution/engine/__tests__/registry.test.ts +0 -120
  177. package/src/execution/engine/__tests__/routing.test.ts +0 -231
  178. package/src/execution/engine/common/data-dir.ts +0 -62
  179. package/src/execution/engine/common/errors.ts +0 -183
  180. package/src/execution/engine/common/event-journal.ts +0 -254
  181. package/src/execution/engine/common/journal-replay.ts +0 -62
  182. package/src/execution/engine/common/kill-chain.ts +0 -221
  183. package/src/execution/engine/common/nesting-guard.ts +0 -50
  184. package/src/execution/engine/common/persona-router.ts +0 -108
  185. package/src/execution/engine/common/pool-manager.ts +0 -226
  186. package/src/execution/engine/common/schema-emulation.ts +0 -189
  187. package/src/execution/engine/common/session-view-projection.ts +0 -51
  188. package/src/execution/engine/engine-discovery.ts +0 -65
  189. package/src/execution/engine/engines/pi/__tests__/pi-engine.test.ts +0 -469
  190. package/src/execution/engine/engines/pi/__tests__/reader.test.ts +0 -155
  191. package/src/execution/engine/engines/pi/__tests__/task-spec-mapper.test.ts +0 -164
  192. package/src/execution/engine/engines/pi/pi-engine.ts +0 -415
  193. package/src/execution/engine/engines/pi/reader.ts +0 -48
  194. package/src/execution/engine/engines/pi/registration.ts +0 -35
  195. package/src/execution/engine/engines/pi/task-spec-mapper.ts +0 -100
  196. package/src/execution/engine/engines/zcode/__tests__/__fixtures__/zcode-golden-spawn.json +0 -39
  197. package/src/execution/engine/engines/zcode/__tests__/launcher.test.ts +0 -150
  198. package/src/execution/engine/engines/zcode/__tests__/parser.test.ts +0 -246
  199. package/src/execution/engine/engines/zcode/__tests__/preparer.test.ts +0 -228
  200. package/src/execution/engine/engines/zcode/__tests__/reader.test.ts +0 -210
  201. package/src/execution/engine/engines/zcode/__tests__/registration.test.ts +0 -64
  202. package/src/execution/engine/engines/zcode/__tests__/zcode-engine.live.test.ts +0 -127
  203. package/src/execution/engine/engines/zcode/__tests__/zcode-engine.test.ts +0 -567
  204. package/src/execution/engine/engines/zcode/constants.ts +0 -43
  205. package/src/execution/engine/engines/zcode/golden-sample.ts +0 -39
  206. package/src/execution/engine/engines/zcode/launcher.ts +0 -161
  207. package/src/execution/engine/engines/zcode/parser.ts +0 -436
  208. package/src/execution/engine/engines/zcode/preparer.ts +0 -363
  209. package/src/execution/engine/engines/zcode/reader.ts +0 -381
  210. package/src/execution/engine/engines/zcode/registration.ts +0 -37
  211. package/src/execution/engine/engines/zcode/zcode-engine.ts +0 -648
  212. package/src/execution/engine/host-task-spec.ts +0 -47
  213. package/src/execution/engine/model-prompt.ts +0 -59
  214. package/src/execution/engine/paths.ts +0 -42
  215. package/src/execution/engine/port.ts +0 -153
  216. package/src/execution/engine/registry.ts +0 -123
  217. package/src/execution/engine/routing.ts +0 -218
  218. package/src/execution/engine/types.ts +0 -304
  219. package/src/execution/execute-options-mapper.ts +0 -111
  220. package/src/execution/execution-record.ts +0 -906
  221. package/src/execution/finalize-record.ts +0 -251
  222. package/src/execution/finalized-marker.ts +0 -51
  223. package/src/execution/get-state-handshake.ts +0 -104
  224. package/src/execution/host-mode.ts +0 -56
  225. package/src/execution/idle-gc.ts +0 -47
  226. package/src/execution/lifecycle-manager.ts +0 -491
  227. package/src/execution/lifecycle-predicates.ts +0 -65
  228. package/src/execution/manifest-store.ts +0 -256
  229. package/src/execution/model-config-service.ts +0 -204
  230. package/src/execution/model-resolver.ts +0 -276
  231. package/src/execution/notifier.ts +0 -260
  232. package/src/execution/output-collector.ts +0 -88
  233. package/src/execution/path-encoding.ts +0 -60
  234. package/src/execution/pi-invocation.ts +0 -120
  235. package/src/execution/record-entry.ts +0 -132
  236. package/src/execution/record-store.ts +0 -1234
  237. package/src/execution/relay-env.ts +0 -37
  238. package/src/execution/session-context-resolver.ts +0 -64
  239. package/src/execution/session-file-gc.ts +0 -120
  240. package/src/execution/session-pending.ts +0 -164
  241. package/src/execution/session-reconstructor.ts +0 -678
  242. package/src/execution/session-runner.ts +0 -1548
  243. package/src/execution/sessions-index.ts +0 -304
  244. package/src/execution/spawn-event-adapter.ts +0 -363
  245. package/src/execution/stdin-writer.ts +0 -198
  246. package/src/execution/stream-sink.ts +0 -126
  247. package/src/execution/subagent-service.ts +0 -2119
  248. package/src/execution/subprocess-agent-runner.ts +0 -303
  249. package/src/execution/temp-prompt.ts +0 -62
  250. package/src/execution/tombstone-store.ts +0 -72
  251. package/src/execution/turn-limiter.ts +0 -102
  252. package/src/execution/types.ts +0 -910
  253. package/src/execution/ui-channels.ts +0 -216
  254. package/src/execution/ui-interaction-model.ts +0 -48
  255. package/src/execution/ui-request-handler-factory.ts +0 -212
  256. package/src/execution/ui-request-observability.ts +0 -81
  257. package/src/execution/ui-request-queue.ts +0 -174
  258. package/src/execution/worktree-manager.ts +0 -688
  259. package/src/execution/worktree-registry.ts +0 -222
  260. package/src/orchestration/__tests__/__fixtures__/worker-template.snapshot.txt +0 -336
  261. package/src/orchestration/__tests__/agent-call-catch-fallback.test.ts +0 -208
  262. package/src/orchestration/__tests__/agent-call-stream.test.ts +0 -157
  263. package/src/orchestration/__tests__/args-validator.test.ts +0 -143
  264. package/src/orchestration/__tests__/concurrency-gate.test.ts +0 -125
  265. package/src/orchestration/__tests__/config-loader.test.ts +0 -503
  266. package/src/orchestration/__tests__/error-recovery-handlers.test.ts +0 -724
  267. package/src/orchestration/__tests__/error-recovery-postmessage-defense.test.ts +0 -405
  268. package/src/orchestration/__tests__/error-recovery-serialize-failed-result.test.ts +0 -56
  269. package/src/orchestration/__tests__/error-recovery-workflow-call.test.ts +0 -166
  270. package/src/orchestration/__tests__/execute-agent-call.test.ts +0 -314
  271. package/src/orchestration/__tests__/jsonl-run-store-loadall-sources.test.ts +0 -171
  272. package/src/orchestration/__tests__/jsonl-run-store-session-file.test.ts +0 -1030
  273. package/src/orchestration/__tests__/launcher-nested-workflow.test.ts +0 -277
  274. package/src/orchestration/__tests__/lifecycle-runid-injection.test.ts +0 -96
  275. package/src/orchestration/__tests__/lifecycle.test.ts +0 -625
  276. package/src/orchestration/__tests__/review-fix-loop-e2e.test.ts +0 -1971
  277. package/src/orchestration/__tests__/script-lint.test.ts +0 -831
  278. package/src/orchestration/__tests__/skill-discovery.test.ts +0 -157
  279. package/src/orchestration/__tests__/test-mocks.ts +0 -197
  280. package/src/orchestration/__tests__/worker-host.test.ts +0 -120
  281. package/src/orchestration/__tests__/worker-returnmeta-passthrough.test.ts +0 -164
  282. package/src/orchestration/__tests__/worker-script-builder-runtime.test.ts +0 -520
  283. package/src/orchestration/__tests__/worker-script-builder.test.ts +0 -309
  284. package/src/orchestration/__tests__/worker-script-template-snapshot.test.ts +0 -110
  285. package/src/orchestration/__tests__/workflow-nesting-e2e.test.ts +0 -317
  286. package/src/orchestration/__tests__/workflow-script-lint-memo.test.ts +0 -110
  287. package/src/orchestration/__tests__/workflows-e2e.test.ts +0 -537
  288. package/src/orchestration/agent-opts-resolver.ts +0 -93
  289. package/src/orchestration/args-validator.ts +0 -127
  290. package/src/orchestration/concurrency-gate.ts +0 -69
  291. package/src/orchestration/config-loader.ts +0 -315
  292. package/src/orchestration/error-recovery.ts +0 -862
  293. package/src/orchestration/execute-agent-call.ts +0 -217
  294. package/src/orchestration/launcher.ts +0 -410
  295. package/src/orchestration/lifecycle.ts +0 -396
  296. package/src/orchestration/models/__tests__/budget.test.ts +0 -367
  297. package/src/orchestration/models/__tests__/trace.test.ts +0 -408
  298. package/src/orchestration/models/agent-call.ts +0 -83
  299. package/src/orchestration/models/budget.ts +0 -148
  300. package/src/orchestration/models/ports.ts +0 -164
  301. package/src/orchestration/models/run-runtime.ts +0 -89
  302. package/src/orchestration/models/run-spec.ts +0 -83
  303. package/src/orchestration/models/run-state.ts +0 -44
  304. package/src/orchestration/models/trace.ts +0 -183
  305. package/src/orchestration/models/types.ts +0 -292
  306. package/src/orchestration/models/workflow-run.ts +0 -254
  307. package/src/orchestration/models/workflow-script-registry.ts +0 -35
  308. package/src/orchestration/models/workflow-script.ts +0 -117
  309. package/src/orchestration/script-lint.ts +0 -766
  310. package/src/orchestration/skill-discovery.ts +0 -92
  311. package/src/orchestration/worker-handle.ts +0 -115
  312. package/src/orchestration/worker-host.ts +0 -98
  313. package/src/orchestration/worker-script-builder.ts +0 -408
  314. package/src/orchestration/workflow-files.ts +0 -85
  315. package/src/orchestration/workflow-script-registry-impl.ts +0 -133
  316. package/src/shared/__tests__/agent-ref.test.ts +0 -34
  317. package/src/shared/__tests__/meta-parser.test.ts +0 -304
  318. package/src/shared/__tests__/resource-discovery-manifest-cache.test.ts +0 -280
  319. package/src/shared/__tests__/resource-discovery.test.ts +0 -736
  320. package/src/shared/__tests__/resource-meta.test.ts +0 -51
  321. package/src/shared/__tests__/schema-jsonify.test.ts +0 -81
  322. package/src/shared/agent-event.ts +0 -13
  323. package/src/shared/agent-ref.ts +0 -57
  324. package/src/shared/meta-parser.ts +0 -261
  325. package/src/shared/resource-discovery.ts +0 -811
  326. package/src/shared/resource-meta.ts +0 -65
  327. package/src/shared/schema-jsonify.ts +0 -56
  328. package/src/shared/xml-injection.ts +0 -35
  329. package/workflows/README.md +0 -81
  330. package/workflows/_shared/agent-refs.cjs +0 -40
  331. package/workflows/chain.js +0 -131
  332. package/workflows/map-reduce.js +0 -174
  333. package/workflows/parallel.js +0 -148
  334. package/workflows/review-fix-loop-utils.cjs +0 -1307
  335. package/workflows/review-fix-loop.js +0 -1396
  336. package/workflows/scatter-gather.js +0 -178
@@ -1,648 +0,0 @@
1
- // src/execution/engine/engines/zcode/zcode-engine.ts
2
- //
3
- // ZcodeEngine(P3):zcode CLI spawn 单轮模式的 EnginePort 实现。设计权威源:
4
- // docs/architecture/subagent-engine-abstraction.md D10(MVP 引擎集 + zcode 首期只做
5
- // spawn 单轮)、§3.3.4(reviewer@zcode 物理数据流)、§3.3.5(run 错误语义三条)。
6
- //
7
- // 职责编排(四件套的消费方):
8
- // preparer(隔离 HOME 池 + 凭据 config)→ launcher(argv/env/spawn/杀链)
9
- // → parser(stdout 收集 + 终 JSON + coarse 事件合成)→ reader(read 第①级 sqlite)。
10
- //
11
- // run 错误语义(设计 §3.3.5):
12
- // ① prepare 期错误(credential_missing / model_not_available / prompt_too_large /
13
- // capability 拒绝)在进程创建前 reject,不产生 handle;
14
- // ② 运行中失败不 reject——合成 engine_run_failed outcome + 正常 handle 返回
15
- // (record 必须收尾);
16
- // ③ abort 走杀链(SIGTERM→grace→SIGKILL,interrupt: kill-only 无原生中断)后同 ②
17
- // (exitCode=null + error 含杀链标记)。
18
- //
19
- // schema 仿真接线(D4 emulated 侧):common/schema-emulation.ts(并行任务 P2 交付,
20
- // 2026-08-25 已就绪并接线)——spawn 前拼 prompt 仿真段、终态后三级容错提取 + ajv
21
- // 校验、失败强化重试一次、仍失败报 schema_emulation_failed。read 第②级 journal 降级
22
- // 已接线(P4 对齐点①:common/journal-replay 复用 live reducer)。
23
-
24
- import { execFile } from "node:child_process";
25
- import * as fs from "node:fs";
26
- import * as path from "node:path";
27
-
28
- import { getLogger } from "@zhushanwen/pi-extension-logger";
29
-
30
- import {
31
- buildSchemaEmulationSegment,
32
- extractAndValidateStructuredOutput,
33
- } from "../../common/schema-emulation.ts";
34
- import { HOST_TIMEOUT_ABORT_REASON, synthesizeTimeoutOutcome } from "../../common/kill-chain.ts";
35
- import { engineTimeoutDetail } from "../../common/errors.ts";
36
- import { replayJournalToSessionView } from "../../common/journal-replay.ts";
37
- import type { EnginePort, EngineRunResult, RunContext } from "../../port.ts";
38
- import type {
39
- AgentEvent,
40
- AgentOutcome,
41
- AgentTaskSpec,
42
- EngineCapabilities,
43
- EngineHandle,
44
- InteractAction,
45
- InteractResult,
46
- ProbeReport,
47
- SessionView,
48
- } from "../../types.ts";
49
- import { resolvePoolDir } from "../../paths.ts";
50
- import {
51
- ZCODE_ADAPTER_VERSION,
52
- ZCODE_CLI_DEFAULT_PATH,
53
- ZCODE_ENGINE_ID,
54
- ZCODE_ERROR_TAIL_CHARS,
55
- ZCODE_KILL_GRACE_MS,
56
- ZCODE_POOL_DB_RELATIVE_PATH,
57
- } from "./constants.ts";
58
- import { ZCODE_GOLDEN_STDOUT } from "./golden-sample.ts";
59
- import {
60
- buildZcodeArgv,
61
- buildZcodeEnv,
62
- assertZcodeArgvBudget,
63
- launchZcodeProcess,
64
- type ZcodeLaunchedProcess,
65
- } from "./launcher.ts";
66
- import {
67
- buildRunFailedMessage,
68
- collectZcodeOutput,
69
- parseZcodeTerminal,
70
- synthesizeCoarseEvents,
71
- type ZcodeCollectedOutput,
72
- type ZcodeTerminalPayload,
73
- } from "./parser.ts";
74
- import { listZcodeModels, prepareZcodeHome, resolveZcodeModelRef, type ZcodeSourcePaths } from "./preparer.ts";
75
- import { readZcodeSessionView } from "./reader.ts";
76
-
77
- const logger = getLogger("subagents");
78
-
79
- /** probe 的版本探测超时(ms)——二进制无响应按探针失败处理,不静默挂死。 */
80
- const PROBE_VERSION_TIMEOUT_MS = 15_000;
81
-
82
- /** ZcodeEngine 构造依赖(全部可注入——测试不依赖真机 CLI/真凭据)。 */
83
- export interface ZcodeEngineDeps {
84
- /**
85
- * 引擎数据目录(池根:<dir>/engines/zcode/<poolKey>/)。来源通道(宿主 dataDir)
86
- * 由并行任务/W3 解决——本引擎只消费,见 registration.ts 缺省解析。
87
- */
88
- engineDataDir: () => string;
89
- /** zcode CLI 路径;缺省 ZCODE_CLI_DEFAULT_PATH。 */
90
- cliPath?: string;
91
- /** 源 config 路径覆盖(测试注入临时源;缺省读 ~/.zcode)。 */
92
- sources?: ZcodeSourcePaths;
93
- /** 版本探测执行器(probe check "version";测试注入 fake 防真实子进程)。 */
94
- probeVersion?: (cliPath: string) => Promise<string | undefined>;
95
- /** spawn 执行器(测试注入 fake 进程)。 */
96
- launch?: (opts: { cliPath: string; args: string[]; env: NodeJS.ProcessEnv }) => ZcodeLaunchedProcess;
97
- /** env 基底(测试注入;缺省 process.env)。 */
98
- processEnv?: NodeJS.ProcessEnv;
99
- }
100
-
101
- /** zcode 引擎适配器。 */
102
- export class ZcodeEngine implements EnginePort {
103
- readonly id = ZCODE_ENGINE_ID;
104
-
105
- private readonly deps: ZcodeEngineDeps;
106
- private probeCache: ProbeReport | undefined;
107
-
108
- constructor(deps: ZcodeEngineDeps) {
109
- this.deps = deps;
110
- }
111
-
112
- /**
113
- * zcode 链路首期实际接通的能力(D3 链路口径)。声明升级(如 schema 仿真段接入
114
- * common 层后仍为 emulated;app-server 常驻化后 eventGranularity 升 stream)必须
115
- * 先改链路再改声明。
116
- */
117
- capabilities(): EngineCapabilities {
118
- return {
119
- // 无 --json-schema 类通道;公共 schema 仿真层(prompt 约定 + 容错提取 + ajv)
120
- schemaEnforcement: "emulated",
121
- // argv-only spawn,无运行中插话通道(app-server 属引擎内部优化,首期不接)
122
- steer: "unsupported",
123
- // 无同进程 idle 复用;--resume 是冷启动
124
- conversation: "unsupported",
125
- // 无 --append-system-prompt flag(实测拒收)——persona 只能拼进 prompt
126
- personaInjection: "prompt",
127
- // stdout 只有终态单 JSON(message_end/turn_end 合成)
128
- eventGranularity: "coarse",
129
- // 首期未接 worktree 隔离(公共层 worktree-manager 接入后升 emulated)
130
- sandbox: "none",
131
- // sqlite 三级 JOIN 完整重建 turns(reader 实测)
132
- sessionRead: "full",
133
- // --resume 冷启动可用(实测)
134
- resume: "cold",
135
- // 无原生中断——AbortSignal 走公共杀链(SIGTERM→grace→SIGKILL)
136
- interrupt: "kill-only",
137
- // --mode build/edit/plan/yolo 原生权限档位
138
- permissionMode: "native",
139
- };
140
- }
141
-
142
- /** 探针(D7):二进制存在 + 版本解析 + golden 样本干跑回归(zsub 式逆向契约引擎必做)。 */
143
- async probe(opts?: { force?: boolean }): Promise<ProbeReport> {
144
- if (!opts?.force && this.probeCache) return this.probeCache;
145
-
146
- const cliPath = this.deps.cliPath ?? ZCODE_CLI_DEFAULT_PATH;
147
- // check 1:二进制存在(不在 PATH,固定绝对路径形态——存在性即可用性的第一道判据)
148
- const binary = this.probeBinaryCheck(cliPath);
149
- const checks: ProbeReport["checks"] = [binary];
150
-
151
- // check 2:版本解析(存在才尝试——必败进程不再 spawn)
152
- let engineVersion = "";
153
- if (binary.ok) {
154
- const version = await this.probeVersionCheck(cliPath);
155
- checks.push(version.check);
156
- engineVersion = version.engineVersion;
157
- }
158
-
159
- // check 3:golden 样本干跑回归(parser 对实录样本解析——格式漂移入口拦截)
160
- checks.push(this.probeGoldenCheck());
161
-
162
- const ok = checks.every((c) => c.ok);
163
- const report: ProbeReport = {
164
- ok,
165
- engineVersion,
166
- checks,
167
- ...(ok ? {} : { error: this.probeFailureRecovery(cliPath) }),
168
- };
169
- this.probeCache = report;
170
- return report;
171
- }
172
-
173
- /** check 1:二进制存在性(isFile 才算——同名目录不是可执行入口)。 */
174
- private probeBinaryCheck(cliPath: string): ProbeReport["checks"][number] {
175
- const binaryOk = fs.existsSync(cliPath) && fs.statSync(cliPath).isFile();
176
- return {
177
- name: "binary",
178
- ok: binaryOk,
179
- detail: binaryOk ? cliPath : `zcode CLI 不存在:${cliPath}`,
180
- };
181
- }
182
-
183
- /** check 2:`--version` 解析(probeVersion 可注入——测试 fake 防真实子进程)。 */
184
- private async probeVersionCheck(
185
- cliPath: string,
186
- ): Promise<{ check: ProbeReport["checks"][number]; engineVersion: string }> {
187
- const runVersion = this.deps.probeVersion ?? defaultProbeVersion;
188
- const version = await runVersion(cliPath);
189
- const versionOk = version !== undefined && version.length > 0;
190
- return {
191
- check: {
192
- name: "version",
193
- ok: versionOk,
194
- detail: versionOk ? version : "zcode --version 返回空或失败",
195
- },
196
- engineVersion: version ?? "",
197
- };
198
- }
199
-
200
- /** check 3:golden 样本干跑(parser 对实录样本解析——stdout 格式漂移的入口拦截)。 */
201
- private probeGoldenCheck(): ProbeReport["checks"][number] {
202
- const golden = parseZcodeTerminal(ZCODE_GOLDEN_STDOUT);
203
- const goldenOk = golden.ok && golden.payload.sessionId !== undefined && golden.payload.usage !== undefined;
204
- return {
205
- name: "golden-regression",
206
- ok: goldenOk,
207
- detail: goldenOk
208
- ? "parser 对 0.16.5 实录样本回归通过(sessionId/response/usage 形状完整)"
209
- : `解析实录样本失败:${golden.ok ? "字段缺失(sessionId/usage)" : golden.reason}`,
210
- };
211
- }
212
-
213
- /** 探针失败的恢复指引(§3.3.3 终态四:版本确认命令 + 探针重跑 + 调研文档路径)。 */
214
- private probeFailureRecovery(cliPath: string): NonNullable<ProbeReport["error"]> {
215
- return {
216
- code: "engine_probe_failed",
217
- recovery:
218
- `Run \`node ${cliPath} --version\` 确认 zcode CLI 可用且版本未漂移,然后重跑探针(重新初始化引擎或 probe({force:true}))。` +
219
- `若 stdout 格式已变:把新样本补录进 golden 库(__tests__/__fixtures__/zcode-golden-spawn.json 与 golden-sample.ts)并更新 parser。` +
220
- `参照 docs/research/agent-engine-zcode.md。`,
221
- };
222
- }
223
-
224
- /** D1 主语义:preparer → launcher → parser →(schema 仿真校验 + 一次重试)→ outcome/handle。 */
225
- async run(task: AgentTaskSpec, ctx: RunContext): Promise<EngineRunResult> {
226
- const startedAt = Date.now();
227
- this.rejectUnsupportedTaskShapes(task);
228
-
229
- // ① prepare 期:模型解析(provider 体系校验)+ 隔离 HOME 池引导(凭据 + model.main)
230
- const modelRef = resolveZcodeModelRef(task.model, this.deps.sources);
231
- const prepared = prepareZcodeHome({
232
- engineDataDir: this.deps.engineDataDir(),
233
- modelRef,
234
- sources: this.deps.sources,
235
- });
236
- // 对齐点③:把实际池 key 声明给宿主(journal writer 重定向到 handle.poolKey 同源
237
- // 的路径——单一权威,宿主不再两边推导);须在首个事件 emit 前(终态后合成,天然满足)
238
- ctx.onPoolResolved?.(prepared.poolKey);
239
- logger.debug("[zcode-engine] isolated home prepared", {
240
- poolKey: prepared.poolKey,
241
- wroteConfig: prepared.wroteConfig,
242
- modelRef,
243
- taskId: ctx.taskId,
244
- });
245
-
246
- const cwd = task.cwd ?? process.cwd();
247
- const schema = isPlainObject(task.schema) ? task.schema : undefined;
248
- const basePrompt = this.buildPrompt(task, schema);
249
-
250
- // ②-④ 首轮执行;schema 任务校验失败时重试一次(强化 JSON 输出指令——与
251
- // structured-output 的重试语义对齐,设计 §3.3.3 schema_emulation_failed 行)。
252
- // 重试轮产生的新 session 是独立 LLM 调用:token 计入 outcome.usage 总量,
253
- // 事件只在最终轮终态后一次性合成(不变量 5:事件 emit 完成先于 run resolve)。
254
- const usageAcc = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, has: false };
255
- let final = await this.attemptOnce(task, ctx, prepared, cwd, basePrompt);
256
- accumulateUsage(usageAcc, final);
257
- if (final.kind === "parsed" && final.schemaResult !== undefined && !final.schemaResult.ok && schema !== undefined) {
258
- const retryPrompt = appendSchemaRetryDirective(basePrompt, final.schemaResult.error);
259
- const retry = await this.attemptOnce(task, ctx, prepared, cwd, retryPrompt);
260
- accumulateUsage(usageAcc, retry);
261
- final = retry;
262
- }
263
-
264
- const outcome = this.finalizeOutcome(task, ctx, final, usageAcc, startedAt);
265
-
266
- const handle: EngineHandle = {
267
- data: {
268
- v: 1,
269
- engineId: ZCODE_ENGINE_ID,
270
- sessionRef: {
271
- // 相对池目录自描述(设计 §3.3.6)——read 时经 resolvePoolDir + 此相对路径重定位
272
- dbPath: ZCODE_POOL_DB_RELATIVE_PATH,
273
- ...(outcome.sessionId !== undefined ? { sessionId: outcome.sessionId } : {}),
274
- },
275
- poolKey: prepared.poolKey,
276
- ...(this.probeCache?.engineVersion !== undefined && this.probeCache.engineVersion !== ""
277
- ? { engineVersion: this.probeCache.engineVersion }
278
- : {}),
279
- adapterVersion: ZCODE_ADAPTER_VERSION,
280
- },
281
- };
282
- return { handle, outcome };
283
- }
284
-
285
- /** 终态合成(extension-conventions 函数 80 行上限,从 run 提取):aborted / run-failed / parsed 三分支。 */
286
- private finalizeOutcome(
287
- task: AgentTaskSpec,
288
- ctx: RunContext,
289
- final: AttemptResult,
290
- usageAcc: { input: number; output: number; cacheRead: number; cacheWrite: number; has: boolean },
291
- startedAt: number,
292
- ): AgentOutcome {
293
- const outcome: AgentOutcome = {
294
- engineId: ZCODE_ENGINE_ID,
295
- content: "",
296
- durationMs: Date.now() - startedAt,
297
- ...(typeof task.worktree === "object" && task.worktree !== null ? { worktreePath: task.worktree.path } : {}),
298
- // D9① fallback 留痕:路由层经 RunContext 投影(zcode 无 record 通路,outcome 是
299
- // 唯一留痕面;pi 引擎另有 record 投影)
300
- ...(ctx.engineFallback !== undefined ? { engineFallback: ctx.engineFallback } : {}),
301
- };
302
- const emit = (event: AgentEvent): void => {
303
- ctx.onEvent?.(event);
304
- };
305
-
306
- if (final.kind === "aborted") {
307
- this.applyAbortedOutcome(outcome, task, ctx, final, emit);
308
- } else if (final.kind === "run-failed") {
309
- this.applyRunFailedOutcome(outcome, final, emit);
310
- } else {
311
- this.applyParsedOutcome(outcome, final, usageAcc, emit);
312
- }
313
- return outcome;
314
- }
315
-
316
- /** abort 合成终态:exitCode=null(record 正常收尾,不留僵尸)。 */
317
- private applyAbortedOutcome(
318
- outcome: AgentOutcome,
319
- task: AgentTaskSpec,
320
- ctx: RunContext,
321
- final: Extract<AttemptResult, { kind: "aborted" }>,
322
- emit: (event: AgentEvent) => void,
323
- ): void {
324
- outcome.exitCode = null;
325
- // 对齐点④:宿主超时(mergeTimeoutSignal 的 timeout abort)统一走公共合成终态
326
- // (common/kill-chain.synthesizeTimeoutOutcome——engine_timeout 文案 SSOT:stdout
327
- // 尾部 + 「可用 engine: pi 重跑」建议);用户主动 cancel 维持 engine_run_failed
328
- // 中止标记(非超时语义,不冒充超时)。?? 兜底是类型收窄(合成器恒写 error)
329
- outcome.error = isHostTimeoutAbort(ctx)
330
- ? synthesizeTimeoutOutcome(task, final.output.stdoutText, ZCODE_ENGINE_ID).error ??
331
- engineTimeoutDetail(final.output.stdoutText)
332
- : `engine_run_failed: zcode 任务被中止(杀链 SIGTERM→${ZCODE_KILL_GRACE_MS}ms→SIGKILL,宿主合成终态)。` +
333
- `stdout 尾部: ${final.output.stdoutText.slice(-ZCODE_ERROR_TAIL_CHARS)}`;
334
- emit({ type: "error", message: outcome.error });
335
- }
336
-
337
- /** run-failed 合成终态:错误信息由 buildRunFailedMessage 产出(已含恢复指引),直接透传。 */
338
- private applyRunFailedOutcome(
339
- outcome: AgentOutcome,
340
- final: Extract<AttemptResult, { kind: "run-failed" }>,
341
- emit: (event: AgentEvent) => void,
342
- ): void {
343
- outcome.exitCode = final.output.exitCode;
344
- outcome.error = final.message;
345
- emit({ type: "error", message: outcome.error });
346
- }
347
-
348
- /** parsed 合成终态:content/sessionId/usage 落位 + schema 校验分流 + coarse 事件。 */
349
- private applyParsedOutcome(
350
- outcome: AgentOutcome,
351
- final: Extract<AttemptResult, { kind: "parsed" }>,
352
- usageAcc: { input: number; output: number; cacheRead: number; cacheWrite: number; has: boolean },
353
- emit: (event: AgentEvent) => void,
354
- ): void {
355
- const payload = final.payload;
356
- outcome.content = payload.response;
357
- outcome.exitCode = final.output.exitCode;
358
- if (payload.sessionId !== undefined) outcome.sessionId = payload.sessionId;
359
- // usage:token 四项取两轮之和(重试的 LLM 调用真实发生),contextTokens/turns 取末轮
360
- if (usageAcc.has) {
361
- const last = payload.outcomeUsage;
362
- outcome.usage = {
363
- input: usageAcc.input,
364
- output: usageAcc.output,
365
- cacheRead: usageAcc.cacheRead,
366
- cacheWrite: usageAcc.cacheWrite,
367
- cost: 0,
368
- contextTokens: last?.contextTokens ?? usageAcc.input + usageAcc.output + usageAcc.cacheRead + usageAcc.cacheWrite,
369
- turns: last?.turns ?? 1,
370
- };
371
- }
372
- if (final.schemaResult !== undefined) {
373
- if (final.schemaResult.ok) {
374
- // D4 硬分流的 emulated 侧产出:公共仿真层的 ajv 校验结果即 parsedOutput
375
- outcome.parsedOutput = final.schemaResult.parsed;
376
- } else {
377
- // 两轮(原始 + 强化重试)均未通过三级容错提取/ajv 校验
378
- outcome.error =
379
- `schema_emulation_failed: zcode 输出经两轮(含强化 prompt 重试)仍未通过 schema 校验。` +
380
- `末轮失败原因: ${final.schemaResult.error}。原始输出尾部: ${final.schemaResult.tail}。` +
381
- `恢复指引:简化 schema 或拆小任务后重派;需要强 schema 约束时改用 engine: pi(native schema 注入)。`;
382
- emit({ type: "error", message: outcome.error });
383
- }
384
- }
385
- // coarse 事件(不变量 5:事件 emit 完成先于 run resolve——journal 完整性)
386
- for (const ev of synthesizeCoarseEvents(payload.response, payload.usage)) emit(ev);
387
- }
388
-
389
- /**
390
- * 单轮执行(launch → collect → parse → schema 校验)。产出三态之一给 run 编排:
391
- * aborted(我方杀链)/ run-failed(非零退出或解析失败)/ parsed(含 schema 校验结果)。
392
- */
393
- private async attemptOnce(
394
- task: AgentTaskSpec,
395
- ctx: RunContext,
396
- prepared: ReturnType<typeof prepareZcodeHome>,
397
- cwd: string,
398
- prompt: string,
399
- ): Promise<AttemptResult> {
400
- // ② argv 组装 + 字节估算(超限抛 prompt_too_large——进程创建前;公共预算权威)
401
- const args = buildZcodeArgv({ cwd, prompt, denyTools: task.denyTools });
402
- const cliPath = this.deps.cliPath ?? ZCODE_CLI_DEFAULT_PATH;
403
- assertZcodeArgvBudget("node", cliPath, args);
404
-
405
- // ③ launch:spawn 单轮(stdin ignore;HOME=池目录;嵌套标记经公共 nesting-guard)
406
- const launch = this.deps.launch ?? launchZcodeProcess;
407
- const env = buildZcodeEnv(prepared.homeDir, this.deps.processEnv ?? process.env);
408
- let proc: ZcodeLaunchedProcess;
409
- try {
410
- proc = launch({ cliPath, args, env });
411
- } catch (err) {
412
- // spawn 同步失败(node 缺失等):进程未创建,按 prepare 期语义 reject
413
- throw new Error(
414
- `[engine_run_failed] 无法启动 zcode CLI(${cliPath}):${err instanceof Error ? err.message : String(err)}。` +
415
- `恢复指引:确认 node 在 PATH 且 ${cliPath} 存在(probe 可探测),或改用 engine: pi。`,
416
- );
417
- }
418
-
419
- // [U0 D10] 终止链路径①:spawn 成功后同步注册子进程句柄进宿主 spawnedChildren
420
- // 记账(port.ts 契约「spawn 成功后同步回调」)——cancelBackground SIGTERM /
421
- // dispose killAll 收割兜底对引擎 record 生效,防 controller 丢失/竞态场景下孤儿进程
422
- ctx.onChildSpawned?.(proc.child);
423
-
424
- // abort 分级(D1):zcode 无原生中断(interrupt: kill-only),AbortSignal 直通
425
- // SIGTERM → grace → SIGKILL 杀链,终态由宿主合成
426
- const onAbort = (): void => {
427
- void proc.abort(ZCODE_KILL_GRACE_MS);
428
- };
429
- if (ctx.signal !== undefined) {
430
- if (ctx.signal.aborted) onAbort();
431
- else ctx.signal.addEventListener("abort", onAbort, { once: true });
432
- }
433
-
434
- // ④ parser:有界收集 + 终 JSON
435
- const output = await collectZcodeOutput(proc);
436
- if (ctx.signal !== undefined) ctx.signal.removeEventListener("abort", onAbort);
437
-
438
- if (proc.killedByUs()) return { kind: "aborted", output };
439
- if (output.exitCode !== 0) {
440
- return {
441
- kind: "run-failed",
442
- output,
443
- message: buildRunFailedMessage({
444
- cliPath,
445
- exitCode: output.exitCode,
446
- stdoutTail: output.stdoutText,
447
- stderrTail: output.stderrTail,
448
- modelRef: prepared.modelRef,
449
- configPath: prepared.configPath,
450
- }),
451
- };
452
- }
453
- const terminal = parseZcodeTerminal(output.stdoutText);
454
- if (!terminal.ok) {
455
- return {
456
- kind: "run-failed",
457
- output,
458
- message: buildRunFailedMessage({
459
- cliPath,
460
- exitCode: output.exitCode,
461
- stdoutTail: output.stdoutText,
462
- stderrTail: output.stderrTail,
463
- parseReason: terminal.reason,
464
- modelRef: prepared.modelRef,
465
- configPath: prepared.configPath,
466
- }),
467
- };
468
- }
469
- const schema = isPlainObject(task.schema) ? task.schema : undefined;
470
- return {
471
- kind: "parsed",
472
- output,
473
- payload: terminal.payload,
474
- ...(schema !== undefined
475
- ? { schemaResult: extractAndValidateStructuredOutput(terminal.payload.response, schema) }
476
- : {}),
477
- };
478
- }
479
-
480
- /**
481
- * D1 可选面:zcode 首期不支持 conversation(capabilities 声明)——同步拒绝、
482
- * 不创建进程,文案给可操作建议(A11)。
483
- */
484
- async interact(_handle: EngineHandle, _action: InteractAction): Promise<InteractResult> {
485
- return {
486
- ok: false,
487
- code: "engine_capability_unsupported",
488
- message:
489
- "zcode 引擎不支持 conversation 交互控制面(capabilities.conversation = 'unsupported'," +
490
- "spawn 单轮模式无同进程 idle 复用)。恢复指引:改用单次 subagent 调用重新派发任务," +
491
- "或使用 engine: 'pi'(chatMode idle 复用,支持 message/close/cancel)。",
492
- };
493
- }
494
-
495
- /**
496
- * D6 read 三级降级:①sqlite 原生读取 → ②宿主 event journal 重放(对齐点①接线:
497
- * replayJournalToSessionView 复用 live reducer,重放等价性见 §3.3.6)→ ③outcome-only。
498
- * sessionId 缺失(解析失败的 run 无法在共享池 db 内定位 session)跳过①级;②级
499
- * 依赖 handle.journalPath(宿主 run 后回填)。
500
- */
501
- /** [U7] 模型可发现性:v2 桌面登录态聚合(带凭据 provider × models),失败安全返回清单本身可能为空。 */
502
- listModels(): Array<{ id: string; name?: string }> {
503
- return listZcodeModels(this.deps.sources);
504
- }
505
-
506
- async read(handle: EngineHandle): Promise<SessionView> {
507
- if (handle.data.engineId !== ZCODE_ENGINE_ID) {
508
- return { engineId: ZCODE_ENGINE_ID, turns: [], source: "outcome-only" };
509
- }
510
- const sessionId = handle.data.sessionRef["sessionId"];
511
- const dbPathRaw = handle.data.sessionRef["dbPath"];
512
- if (typeof sessionId === "string" && typeof dbPathRaw === "string") {
513
- // 相对路径锚定池目录(handle.poolKey 自描述);绝对路径(未来形态)直用
514
- const dbPath = path.isAbsolute(dbPathRaw)
515
- ? dbPathRaw
516
- : path.join(resolvePoolDir(this.deps.engineDataDir(), ZCODE_ENGINE_ID, handle.data.poolKey), dbPathRaw);
517
- try {
518
- return await readZcodeSessionView(dbPath, sessionId);
519
- } catch (err) {
520
- logger.warn("[zcode-engine] native session read failed, degrade to journal replay", {
521
- dbPath,
522
- sessionId,
523
- reason: err instanceof Error ? err.message : String(err),
524
- });
525
- }
526
- }
527
- // ②级:journal 重放(journalPath 缺省 / 文件不存在 / 无事件 → undefined 落③级)
528
- const journaled = replayJournalToSessionView(handle, ZCODE_ENGINE_ID);
529
- if (journaled !== undefined) return journaled;
530
- return { engineId: ZCODE_ENGINE_ID, turns: [], source: "outcome-only" };
531
- }
532
-
533
- // ── 内部 ──
534
-
535
- /**
536
- * prepare 期的能力拒绝(进程创建前):fork 是 pi 专属(AgentTaskSpec.fork 契约:
537
- * 其他引擎按 capabilities 拒绝);conversation 是 interact 控制面的 task 标志,
538
- * zcode 无此面(A11:同步拒绝 + 可操作建议,无进程创建)。
539
- */
540
- private rejectUnsupportedTaskShapes(task: AgentTaskSpec): void {
541
- if (task.fork === true) {
542
- throw new ZcodeTaskShapeError(
543
- "engine_capability_unsupported",
544
- "zcode 引擎不支持 fork(pi 专属会话分叉语义)。恢复指引:去掉 fork 参数重派,或使用 engine: 'pi'。",
545
- );
546
- }
547
- if (task.conversation === true) {
548
- throw new ZcodeTaskShapeError(
549
- "engine_capability_unsupported",
550
- "zcode 引擎不支持 conversation 模式(spawn 单轮,无同进程 idle 复用)。" +
551
- "恢复指引:改用单次调用(去掉 conversation),或使用 engine: 'pi'。",
552
- );
553
- }
554
- }
555
-
556
- /**
557
- * persona 拼接后的完整 prompt(personaInjection: 'prompt'——zcode 无 flag 通道):
558
- * appendSystemPrompt 段在前(人设/约束语境),task 正文居中,schema 仿真段尾置
559
- * (common/schema-emulation 公共层产出,D4 emulated 侧——zcode 无 native schema 通道)。
560
- */
561
- private buildPrompt(task: AgentTaskSpec, schema: object | undefined): string {
562
- const segments: string[] = [...(task.persona?.appendSystemPrompt ?? [])];
563
- segments.push(task.task);
564
- if (schema !== undefined) segments.push(buildSchemaEmulationSegment(schema));
565
- return segments.join("\n\n");
566
- }
567
- }
568
-
569
- // ── 模块级辅助(run 的重试编排件) ──
570
-
571
- /** attemptOnce 的三态产物(run 按序编排重试与终态合成)。 */
572
- type AttemptResult =
573
- | { kind: "aborted"; output: ZcodeCollectedOutput }
574
- | { kind: "run-failed"; output: ZcodeCollectedOutput; message: string }
575
- | {
576
- kind: "parsed";
577
- output: ZcodeCollectedOutput;
578
- payload: ZcodeTerminalPayload;
579
- schemaResult?: { ok: true; parsed: unknown } | { ok: false; error: string; tail: string };
580
- };
581
-
582
- /** Record 形状 guard(task.schema 的运行时窄化——Record<string, unknown> 不满足 ajv 的 object 入参)。 */
583
- function isPlainObject(v: unknown): v is object {
584
- return typeof v === "object" && v !== null && !Array.isArray(v);
585
- }
586
-
587
- /** 跨重试轮累计 token 用量(重试的 LLM 调用真实发生)。 */
588
- function accumulateUsage(acc: { input: number; output: number; cacheRead: number; cacheWrite: number; has: boolean }, r: AttemptResult): void {
589
- if (r.kind !== "parsed") return;
590
- const u = r.payload.usage;
591
- if (u === undefined) return;
592
- acc.has = true;
593
- acc.input += u.input;
594
- acc.output += u.output;
595
- acc.cacheRead += u.cacheRead;
596
- acc.cacheWrite += u.cacheWrite;
597
- }
598
-
599
- /** 强化重试 prompt:首战校验失败后追加更明确的 JSON 输出指令(structured-output 重试语义)。 */
600
- function appendSchemaRetryDirective(basePrompt: string, validationError: string): string {
601
- return (
602
- basePrompt +
603
- "\n\n## Retry: Structured Output Failed\n" +
604
- `Your previous answer failed schema validation: ${validationError}\n` +
605
- "Answer again. Output ONLY the JSON value conforming to the schema above — " +
606
- "no prose, no markdown fences, no extra text."
607
- );
608
- }
609
-
610
- /** prepare 期能力拒绝的载体(code 进 message 前缀,调用方可程序化分流)。 */
611
- class ZcodeTaskShapeError extends Error {
612
- readonly code: string;
613
-
614
- constructor(code: string, message: string) {
615
- super(`[${code}] ${message}`);
616
- this.name = "ZcodeTaskShapeError";
617
- this.code = code;
618
- }
619
- }
620
-
621
- /** 宿主超时 abort 判别(对齐点④):signal.reason 带超时标记 = 超时杀链合成终态路径。 */
622
- function isHostTimeoutAbort(ctx: RunContext): boolean {
623
- return ctx.signal?.aborted === true && ctx.signal.reason === HOST_TIMEOUT_ABORT_REASON;
624
- }
625
-
626
- /** 默认版本探测:`node <cli> --version`(首行 trim;超时按探针失败处理)。 */
627
- async function defaultProbeVersion(cliPath: string): Promise<string | undefined> {
628
- try {
629
- return await new Promise<string | undefined>((resolve, reject) => {
630
- execFile(
631
- "node",
632
- [cliPath, "--version"],
633
- { encoding: "utf8", timeout: PROBE_VERSION_TIMEOUT_MS },
634
- (err: Error | null, stdout: string) => {
635
- if (err) reject(err);
636
- else resolve(stdout.trim().split("\n")[0]?.trim() || undefined);
637
- },
638
- );
639
- });
640
- } catch (err) {
641
- logger.debug(
642
- `[zcode-engine] probe version check failed (best-effort continue): ${
643
- err instanceof Error ? err.message : String(err)
644
- }`,
645
- );
646
- return undefined;
647
- }
648
- }