@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,65 +0,0 @@
1
- /**
2
- * ResourceMeta — 资源元数据统一类型族(v5 §4.1 / DM1)
3
- *
4
- * workflow 与 agent 两类资源共用同一数据格式(YAML),仅 kind 判别 + 专属字段不同。
5
- * skills 显式 out-of-scope(归 pi core)。
6
- *
7
- * 设计:
8
- * - 整对象透传——config-loader.toCachedMeta / registry-impl.toScript 改为 meta: parsedMeta
9
- * 不再 {name,description,phases} 解构重建(消灭 3 重映射丢字段 bug)。
10
- * - workflow 的 parameters(JSON Schema)由 args-validator(m3)按 schema 校验 args;
11
- * usage(markdown)覆盖 schema 表达不了的语义约束 + 真实合法示例命令。
12
- * - agent 的 tools/model 供 AgentRegistry 执行侧 spawn 子进程用,不进 system prompt 注入段。
13
- *
14
- * 层归属:shared(L1 统一资源模型)。
15
- */
16
-
17
- /** 资源种类。skills 归 pi core,本 extension 仅 workflow + agent。 */
18
- export type ResourceKind = "workflow" | "agent";
19
-
20
- /** 两类资源共有的路由字段。 */
21
- export interface ResourceMetaBase {
22
- kind: ResourceKind;
23
- /** 路由用一句话(受 SSOT lint W1/W2 约束:≤200 字符、不含参数引用语法)。 */
24
- name: string;
25
- description: string;
26
- /** "Use when ..." 正向路由提示(PromptBudget 最后保)。 */
27
- when?: string;
28
- /** "Not for ..." 负向路由提示。 */
29
- notFor?: string;
30
- }
31
-
32
- /** workflow 专属:phases + 参数契约 + 语义说明。 */
33
- export interface WorkflowMeta extends ResourceMetaBase {
34
- kind: "workflow";
35
- phases: (string | { title: string; detail?: string })[];
36
- /** 参数契约(JSON Schema draft-07)。未声明则 $ARGS 透传不校验(向后兼容)。 */
37
- parameters?: Record<string, unknown>;
38
- /** markdown,覆盖 schema 表达不了的语义约束 + 真实合法示例命令。 */
39
- usage?: string;
40
- }
41
-
42
- /** agent 路由样本(结构化,非嵌入 description 字符串)。 */
43
- export interface RoutingExample {
44
- match: string;
45
- action: string;
46
- /** true=应触发,false=不应触发(正反各一)。 */
47
- positive: boolean;
48
- }
49
-
50
- /** agent 专属:路由样本 + 执行配置。 */
51
- export interface AgentMeta extends ResourceMetaBase {
52
- kind: "agent";
53
- examples?: RoutingExample[];
54
- /** 供 AgentRegistry 执行侧 spawn 时注入,不进 system prompt 注入段。 */
55
- tools?: string[];
56
- model?: string;
57
- /**
58
- * 执行引擎 id(D9 per-agent 主通道:调用参数 engine > 本字段 > 全局默认)。
59
- * 与 model 字段同风格——路由字段(不进 system prompt),执行侧(P4 路由层)消费。
60
- */
61
- engine?: string;
62
- }
63
-
64
- /** 判别联合(kind 判别)。 */
65
- export type ResourceMeta = WorkflowMeta | AgentMeta;
@@ -1,56 +0,0 @@
1
- /**
2
- * Schema JSON 序列化缓存(IF7/#13,TC6/DM4)。
3
- *
4
- * 同一 schema 对象引用的重复 JSON.stringify 消除:resolver(compact,instruction
5
- * 与 schemaEnv 复用同串)与 session-runner formatSchemaInstruction(pretty)在
6
- * 单次 agent call 内对同一 schema 对象各 stringify 一次;error-recovery 重试路径
7
- * 再加一次。本 helper 用 WeakMap 按对象引用缓存两种格式,命中返回缓存串。
8
- *
9
- * 返回值与直接 JSON.stringify 逐字节一致(compact = JSON.stringify(x)、
10
- * pretty = JSON.stringify(x, null, 2))。
11
- *
12
- * 失效语义:无。WeakMap 键随 schema/opts 对象 GC 自动回收;单 call 生命周期内
13
- * schema 对象引用稳定(resolver/runner 均只读),引用稳定即值稳定;postMessage
14
- * 克隆使跨 call 恒为新对象,天然隔离(DM4)。
15
- *
16
- * 层归属:Shared(resolver 与 session-runner 共用,无 Pi 依赖)。
17
- */
18
-
19
- const cache = new WeakMap<object, { compact?: string; pretty?: string }>();
20
-
21
- /** pretty 格式(JSON.stringify(x, null, N))的缩进空格数。 */
22
- const PRETTY_PRINT_INDENT_SPACES = 2;
23
-
24
- /**
25
- * JSON.stringify(schema) 的引用级缓存版。
26
- *
27
- * @param schema schema 对象(调用方 if 守卫保证非 undefined,helper 不判空)
28
- * @param mode "compact" = JSON.stringify(x);"pretty" = JSON.stringify(x, null, 2)
29
- */
30
- export function stringifySchemaCached(schema: object, mode: "compact" | "pretty"): string {
31
- let entry = cache.get(schema);
32
- if (!entry) {
33
- entry = {};
34
- cache.set(schema, entry);
35
- }
36
- const hit = entry[mode];
37
- if (hit !== undefined) return hit;
38
- // [review 修复] TS lib 盲区:lib 对 object 参数声明 JSON.stringify 返回 string,但
39
- // schema 含 `toJSON: () => undefined` 钩子时运行时返回 undefined——直接违反本函数
40
- // 声明的 string 返回类型,且 `entry[mode] = undefined` 赋值不生效(缓存永不命中,
41
- // 重复 stringify 仅是性能损耗)。显式标注 string | undefined 捕获该窗口,fail-loud
42
- // 抛含恢复指引的错误——不回退 String(value)("[object Object]" 会静默拼进 LLM
43
- // 指令,比崩溃更难排查)。抛错时 entry[mode] 未被赋值,缓存无毒化。
44
- const serialized: string | undefined =
45
- mode === "compact" ? JSON.stringify(schema) : JSON.stringify(schema, null, PRETTY_PRINT_INDENT_SPACES);
46
- if (serialized === undefined) {
47
- throw new Error(
48
- `[subagent-workflow] stringifySchemaCached: JSON.stringify returned undefined (mode=${mode}) — ` +
49
- `the schema object defines a toJSON hook returning undefined. ` +
50
- `Recovery: check the schema source (agent definition / workflow script), remove that toJSON ` +
51
- `or make it return a JSON-serializable value.`,
52
- );
53
- }
54
- entry[mode] = serialized;
55
- return serialized;
56
- }
@@ -1,35 +0,0 @@
1
- // src/shared/xml-injection.ts
2
- //
3
- // XML 注入段渲染共享原语——subagent / workflow / model 三个 injector 的 format
4
- // 函数曾是三份手写同构(escapeXml 逐字重复 + 同一段落骨架),提取此模块消除重复。
5
- // 调用方保留各自的排序契约与条目渲染(字段差异大,不强行归一)。
6
-
7
- /**
8
- * 转义 XML 特殊字符(注入段进每 turn system prompt,内容含 < > & 等会破坏
9
- * XML 结构——全部字段过一遍转义防注入段破碎)。
10
- */
11
- export function escapeXml(str: string): string {
12
- return str
13
- .replace(/&/g, "&amp;")
14
- .replace(/</g, "&lt;")
15
- .replace(/>/g, "&gt;")
16
- .replace(/"/g, "&quot;")
17
- .replace(/'/g, "&apos;");
18
- }
19
-
20
- /**
21
- * XML 注入段渲染骨架:`"\n\n<tag>"` 前导(衔接宿主 prompt 末尾)+ 引导语 +
22
- * 条目行 + 闭合标签,以 "\n" join。空条目返回空串(不注入)。
23
- *
24
- * 三个 injector 共用此骨架保证段落结构逐字节同构;KV-cache 契约(顺序稳定 =
25
- * 注入段字节稳定)由调用方排序保证,本函数不重排。
26
- */
27
- export function renderXmlSection(section: {
28
- tag: string;
29
- guide: string;
30
- items: string[];
31
- }): string {
32
- if (section.items.length === 0) return "";
33
- const lines = [`\n\n<${section.tag}>`, section.guide, ...section.items, `</${section.tag}>`];
34
- return lines.join("\n");
35
- }
@@ -1,81 +0,0 @@
1
- # 内置通用编排 Workflow
2
-
3
- 4 个开箱即用的通用 subagent 编排 workflow,覆盖日常常见的多 agent 协作模式。每个脚本用 `agent()`/`parallel()` 自包含实现,`workflow run <name>` 直接执行,无需额外定义子 workflow。
4
-
5
- ## 文件清单
6
-
7
- | workflow | 模式 | 必需参数 | 适用场景 |
8
- |----------|------|----------|----------|
9
- | `chain.js` | analyze → transform → synthesize 顺序链 | `task` | 多阶段处理:先分析、再变换、最后综合 |
10
- | `parallel.js` | 多视角并行分析 → 聚合汇总 | `target`(可选 `perspectives`) | 多维度评估同一目标(安全/性能/可维护性等) |
11
- | `scatter-gather.js` | scatter 拆分 → parallel 处理 → gather 合并 | `task` | 大任务先拆成子任务再并行处理 |
12
- | `map-reduce.js` | parallel map → reduce 归约 | `items`/`itemsJson` + `operation` | 对已知数组批量变换后归约成单一结果 |
13
- | `review-fix-loop.js` | 多批串行(批内并行 review → aggregate → fix → 重审) | `targetType` + `target`(可选 `batch1..batchN`) | 代码/文档审查并修复直到 clean;前置检查先行(fallow 等) |
14
-
15
- > ⚠️ **review-fix-loop 是唯一带写操作的内置 workflow**(fix 阶段修改文件,`autoCommit=true` 才 commit)。其他 4 个均为只读分析。
16
-
17
- ## 用法
18
-
19
- ### chain — 顺序多步处理
20
-
21
- ```
22
- workflow run chain --args task="把这段需求文档拆成技术任务:..."
23
- ```
24
-
25
- 三段 agent 调用:分析任务 → 基于分析产出方案 → 综合方案输出结论。每步用 `schema` 拿结构化输出,上一步输出拼进下一步 prompt。
26
-
27
- ### parallel — 并行多视角分析
28
-
29
- ```
30
- workflow run parallel --args target="src/auth/login.ts"
31
- workflow run parallel --args target="..." --args 'perspectives=["security","readability"]'
32
- ```
33
-
34
- `perspectives` 默认 `["security","performance","maintainability"]`。每个视角一个并行 agent,各自返回评分+发现的问题,最后纯代码拼接各视角的 findings。
35
-
36
- > **Note (breaking)**: `outcome.aggregate` is now a concatenated string of each perspective's findings (format: `[perspective] finding1; finding2`, joined by newlines). Previously it was an LLM-produced object `{overallScore, topIssues, consensus}`. If you have generated workflows or downstream tools parsing the old object shape, update them to read `outcome.per_perspective` for structured per-perspective scores/findings, or treat `outcome.aggregate` as plain text.
37
-
38
- ### scatter-gather — 分发-收集
39
-
40
- ```
41
- workflow run scatter-gather --args task="重构认证模块,涉及 session/jwt/oauth 三块"
42
- ```
43
-
44
- 三段:第一个 agent 把大任务拆成 2-4 个可并行子任务 → `parallel()` 并行处理每个子任务 → gather 阶段用 `agent()` 把各子任务结果合并成最终结论(LLM 合并,非纯代码拼接)。
45
-
46
- ### map-reduce — 映射-归约
47
-
48
- ```
49
- workflow run map-reduce --args 'items=["file1.ts","file2.ts","file3.ts"]' --args operation="审查代码风格"
50
- workflow run map-reduce --args itemsJson=/path/to/items.json --args operation="..."
51
- ```
52
-
53
- `items` 直接传 JSON 数组,或 `itemsJson` 传 JSON 文件路径(二选一)。`parallel()` 对每个 item 并行执行 `operation` → reduce 阶段用 `agent()` 把各 item 的 map 结果归约成单一结论(LLM 归约,非纯代码拼接)。
54
-
55
- ### review-fix-loop — 多批审查-修复循环
56
-
57
- ```
58
- workflow run review-fix-loop --args targetType=git-diff target=main \
59
- --args batch1=fallow-scan --args batch2=reviewer --args autoCommit=true
60
- workflow run review-fix-loop --args targetType=file target=/path/to/doc.md \
61
- --args batch1=doc-reviewer
62
- ```
63
-
64
- - `targetType` 枚举:`git-diff`(target=base ref)/ `file`(target=路径)/ `dir`(target=目录)/ `text`(target=自由描述)
65
- - `batch1..batchN`:批串行,批内并行 review → aggregate → fix → 重审直到 clean;批次用于前置依赖(如 `fallow-scan` 静态分析先行,后续审查才有意义)
66
- - 批内某 agent 无 must-fix 后后续轮跳过(`skipCleanAgents` 默认 true + `recheckAfterFix` 默认 false):clean agent 下轮跳过不重派;显式传 `recheckAfterFix=true` 启用强回归模式——fix 后重派全批,clean agent 走限定 prompt(只审 modifiedFiles ∪ 自检关联点,不诱导全量重扫)
67
- - agent 项支持:AgentRegistry 名(如 `reviewer`)/ 自定义 .md 文件路径(如 `batch1=/path/to/reviewer.md`)/ 内置 `fallow-scan` / **内置 `doc-reviewer`**(文档场景推荐:`targetType=file/dir` + `batch1=doc-reviewer`,四遍审查方法论:事实锚点核实/逻辑断言验证/落地清单完备性/边界与迁移;无 write 工具,报告经 schema 返回由 workflow 落盘)
68
- - `fixAgent`(可选):fix 阶段加载指定 agent(内置名或 .md 路径);代码场景可在该 agent.md 内写 verify 命令(typecheck/test 实测)当轮拦截编译类回归。⚠️ agent.md 内写的 verify 命令**必须确认能在目标项目可运行**(target 的包管理器/目录结构未知),否则命令失败会误报 fix 状态
69
- - `maxFixAttempts`(可选,默认 2):needs-redesign 阈值。问题经 maxFixAttempts 次修复仍未收敛(regressed)→ 终止该批,terminated="needs-redesign"(结构性问题需人工介入,非继续补丁能解决)
70
- - `convergeNewIssues`(可选,默认 1)+ `convergeRounds`(可选,默认 2):新发现率收敛阈值。连续 convergeRounds 轮新发现问题 ≤ convergeNewIssues **且**无 open/regressed 活跃条目 → terminated="converged"(推进下一批)。收敛不等于问题全清——需同时满足无活跃条目才终止
71
- - ⚠️ **fix 阶段会修改文件;`autoCommit` 默认 false(不 commit)**,需要提交时显式 `autoCommit=true`
72
-
73
- ## 编排 API
74
-
75
- 这些 workflow 内部使用的编排函数(`agent()` / `parallel()` / `pipeline()` / `workflow()`)由 worker 线程注入,完整 API 参考见 `skills/workflow-script-format/SKILL.md`。
76
-
77
- ## 相关文档
78
-
79
- - `skills/workflow-script-format/SKILL.md` — workflow script 完整 API(agent/parallel/pipeline/workflow 签名、$ARGS/$BUDGET、lint 规则)
80
- - `docs/extensions/adr/pi-ext-030-subagents-workflow-merge.md` — 合并决策(决策 3 分层配额 + workflow 嵌套)
81
- - `docs/extensions/adr/pi-ext-032-builtin-orchestration-workflows.md` — 从"参考模板"改为"内置通用编排 workflow"的决策
@@ -1,40 +0,0 @@
1
- // workflows/_shared/agent-refs.cjs
2
- //
3
- // 编排 workflow 共用的 agentRef 参数解析(S4 路径统一)。
4
- //
5
- // agentRef = .md 绝对路径(注入段 <available_subagents> 的 <location>)。
6
- // agents 参数 = 逗号分隔的 agentRef 列表,按阶段顺序一一映射。
7
- // 缺省(未传/空)= 不指定 agent(默认执行者)——编排骨架不强制指定执行者。
8
- //
9
- // 注意:本模块只做「字符串 → 路径数组」的纯解析,不读文件。agent 内容的加载
10
- // 由主线程 resolveAgentOpts(agent-call 时按路径读 + systemPrompt 注入)统一完成。
11
- "use strict";
12
-
13
- /**
14
- * 解析 agents 参数为 agentRef 路径数组。
15
- *
16
- * @param raw 逗号分隔字符串(如 "/a/x.md,/b/y.md");undefined/null/空 → []
17
- * @returns 路径数组(trim + 去空项)
18
- */
19
- function parseAgentRefs(raw) {
20
- if (raw === undefined || raw === null) return [];
21
- if (typeof raw !== "string") return [];
22
- const refs = raw
23
- .split(",")
24
- .map((s) => s.trim())
25
- .filter(Boolean);
26
- return refs;
27
- }
28
-
29
- /**
30
- * 按阶段索引取 agentRef(缺省 undefined = 不指定 agent)。
31
- *
32
- * @param refs parseAgentRefs 结果
33
- * @param index 阶段索引(0-based)
34
- * @returns agentRef 或 undefined
35
- */
36
- function agentRefAt(refs, index) {
37
- return refs.length > index ? refs[index] : undefined;
38
- }
39
-
40
- module.exports = { parseAgentRefs, agentRefAt };
@@ -1,131 +0,0 @@
1
- // chain.js — 顺序多步处理(通用 subagent 编排)
2
- //
3
- // 模式:analyze → transform → synthesize,每步 agent() 输出作下步输入。
4
- // 适用于需要"先分析、再变换、最后综合"的多阶段任务。
5
- //
6
- // 用法:
7
- // workflow run chain --args task="把这段需求文档拆成技术任务:..."
8
- //
9
- // ⚠️ lintScript 约束(本脚本已遵守):
10
- // - 含 agent() 入口
11
- // - 禁止 bare IIFE(用 top-level await)
12
- // - 禁止用 result 作变量名
13
-
14
- /* @pi-meta
15
- name: chain
16
- description: 通用编排:analyze → transform → synthesize 顺序三步链
17
- phases: [analyze, transform, synthesize]
18
- parameters:
19
- type: object
20
- properties:
21
- task: { type: string, minLength: 1 }
22
- agents: { type: string }
23
- required: [task]
24
- usage: |
25
- ## 使用说明
26
- - 顺序三步链:analyze(提取要点)→ transform(产出方案)→ synthesize(合成结论)
27
- - agents:逗号分隔的 agent .md 绝对路径,按顺序对应三步(少于 3 个尾部用默认执行者)
28
- - 示例:workflow run chain --args task="<任务描述>" agents="/path/analyzer.md,/path/planner.md"
29
- */
30
-
31
- // ── 入参($ARGS)──────────────────────────────────────────────────
32
- const task = $ARGS.task;
33
- if (typeof task !== "string" || task.trim() === "") {
34
- throw new Error("chain 缺少必需参数 task(非空字符串)。用法:workflow run chain --args task=\"<描述>\"");
35
- }
36
-
37
- // S4:agents 参数 = 逗号分隔的 agentRef 路径数组,按阶段顺序对应三步
38
- // worker 沙箱为 eval 模式:require 相对路径以 cwd 为基准(非脚本目录),
39
- // 必须用 workerData.scriptPath 锚定脚本目录(review-fix-loop 同模式)。
40
- const SCRIPT_DIR = workerData && workerData.scriptPath
41
- ? require("path").dirname(workerData.scriptPath)
42
- : process.cwd();
43
- const { parseAgentRefs, agentRefAt } = require(SCRIPT_DIR + "/_shared/agent-refs.cjs");
44
- const agentRefs = parseAgentRefs($ARGS.agents);
45
- const stepAgent = (i) => { const ref = agentRefAt(agentRefs, i); return ref ? { agent: ref } : {}; };
46
-
47
- log("chain 开始,task=" + task + (agentRefs.length ? ",agents=" + agentRefs.join(",") : ""));
48
-
49
- let currentPhase = "init";
50
- let outcome;
51
-
52
- try {
53
- // ── 段 1:analyze(分析任务,提取关键点)─────────────────────────
54
- phase("analyze");
55
- currentPhase = "analyze";
56
- const analysis = await agent({
57
- prompt: "分析以下任务,提取核心洞察和关键点:\n\n" + task,
58
- schema: {
59
- type: "object",
60
- properties: {
61
- insights: { type: "string", description: "对任务的核心洞察" },
62
- keyPoints: {
63
- type: "array",
64
- items: { type: "string" },
65
- description: "关键点列表",
66
- },
67
- },
68
- required: ["insights", "keyPoints"],
69
- },
70
- description: "chain-analyze",
71
- ...stepAgent(0),
72
- });
73
-
74
- // ── 段 2:transform(基于分析产出方案)───────────────────────────
75
- phase("transform");
76
- currentPhase = "transform";
77
- const plan = await agent({
78
- prompt:
79
- "基于以下分析结果,产出可执行方案:\n\n洞察:" + (analysis?.insights ?? "(分析无结果)") +
80
- "\n关键点:" + JSON.stringify(analysis?.keyPoints ?? []),
81
- schema: {
82
- type: "object",
83
- properties: {
84
- plan: { type: "string", description: "执行方案" },
85
- actions: {
86
- type: "array",
87
- items: { type: "string" },
88
- description: "具体行动步骤",
89
- },
90
- },
91
- required: ["plan", "actions"],
92
- },
93
- description: "chain-transform",
94
- ...stepAgent(1),
95
- });
96
-
97
- // ── 段 3:synthesize(综合方案输出最终结论)─────────────────────
98
- phase("synthesize");
99
- currentPhase = "synthesize";
100
- const final = await agent({
101
- prompt:
102
- "综合以下方案,输出最终结论和建议:\n\n方案:" + (plan?.plan ?? "(方案无结果)") +
103
- "\n行动步骤:" + JSON.stringify(plan?.actions ?? []),
104
- schema: {
105
- type: "object",
106
- properties: {
107
- summary: { type: "string", description: "最终总结" },
108
- recommendation: { type: "string", description: "核心建议" },
109
- },
110
- required: ["summary", "recommendation"],
111
- },
112
- description: "chain-synthesize",
113
- ...stepAgent(2),
114
- });
115
-
116
- outcome = {
117
- status: "ok",
118
- phases_run: ["analyze", "transform", "synthesize"],
119
- final: { summary: (final?.summary ?? "(综合无结果)"), recommendation: (final?.recommendation ?? "(综合无结果)") },
120
- message: "chain 完成:analyze → transform → synthesize 全绿",
121
- };
122
- } catch (err) {
123
- outcome = {
124
- status: "error",
125
- phase: currentPhase,
126
- error: err && err.message ? err.message : String(err),
127
- message: "chain 在 " + currentPhase + " 段失败",
128
- };
129
- }
130
-
131
- return outcome;
@@ -1,174 +0,0 @@
1
- // map-reduce.js — 映射-归约(通用 subagent 编排)
2
- //
3
- // 模式(两段):
4
- // 段 1 map: parallel() 对每个 item 并行执行 operation
5
- // 段 2 reduce: agent() 把所有 map 结果归约成单一结果
6
- //
7
- // 与 scatter-gather 的区别:scatter-gather 强调"拆分"(scatter 决定子任务数);
8
- // map-reduce 强调对"已知 items 数组"的变换+聚合(items 已有,map 变换、reduce 归约)。
9
- //
10
- // 用法:
11
- // workflow run map-reduce --args 'items=["file1.ts","file2.ts","file3.ts"]' --args operation="审查代码风格"
12
- // workflow run map-reduce --args itemsJson=/path/to/items.json --args operation="..."
13
- //
14
- // ⚠️ lintScript 约束(本脚本已遵守):含 parallel() 入口(兼 agent 嵌套),禁止 bare IIFE
15
-
16
- /* @pi-meta
17
- name: map-reduce
18
- description: 通用编排:parallel map → reduce 两段,处理已知 items 数组
19
- phases: [map, reduce]
20
- parameters:
21
- type: object
22
- properties:
23
- items: { type: array, items: { type: string } }
24
- itemsJson: { type: string }
25
- operation: { type: string }
26
- agents: { type: string }
27
- required: [operation]
28
- oneOf:
29
- - required: [items]
30
- - required: [itemsJson]
31
- usage: |
32
- ## 使用说明
33
- - items 与 itemsJson 至少一个:items 直接传字符串数组,itemsJson 传文件路径(内容为 JSON 数组)
34
- - agents:逗号分隔的 agent .md 绝对路径,按顺序对应 map/reduce 两段
35
- - 示例:workflow run map-reduce --args operation="<对每个 item 做什么>" itemsJson="/path/items.json" agents="/path/mapper.md,/path/reducer.md"
36
- */
37
-
38
- const fs = require("fs");
39
-
40
- // ── 入参($ARGS)──────────────────────────────────────────────────
41
- const operation = $ARGS.operation;
42
- if (!operation) {
43
- throw new Error(
44
- 'map-reduce 缺少必需参数 operation。用法:workflow run map-reduce --args operation="<对每个 item 做什么>"',
45
- );
46
- }
47
-
48
- // items 来源:直接数组 或 itemsJson 文件路径(二选一)
49
- let items = $ARGS.items;
50
- if (!items) {
51
- const itemsPath = $ARGS.itemsJson;
52
- if (!itemsPath) {
53
- throw new Error(
54
- 'map-reduce 需要 items(直接数组)或 itemsJson(JSON 文件路径)参数',
55
- );
56
- }
57
- if (!fs.existsSync(itemsPath)) {
58
- throw new Error("itemsJson 文件不存在: " + itemsPath);
59
- }
60
- items = JSON.parse(fs.readFileSync(itemsPath, "utf-8"));
61
- }
62
-
63
- if (!Array.isArray(items) || items.length === 0) {
64
- throw new Error("items 不是数组或为空");
65
- }
66
-
67
- log("map-reduce 开始,items=" + items.length + " 个,operation=" + operation);
68
-
69
- // S4:agents 参数 = 逗号分隔的 agentRef 路径数组,按顺序对应 map/reduce 两段
70
- // worker 沙箱为 eval 模式:require 相对路径以 cwd 为基准(非脚本目录),
71
- // 必须用 workerData.scriptPath 锚定脚本目录(review-fix-loop 同模式)。
72
- const SCRIPT_DIR = workerData && workerData.scriptPath
73
- ? require("path").dirname(workerData.scriptPath)
74
- : process.cwd();
75
- const { parseAgentRefs, agentRefAt } = require(SCRIPT_DIR + "/_shared/agent-refs.cjs");
76
- const agentRefs = parseAgentRefs($ARGS.agents);
77
- const stepAgent = (i) => { const ref = agentRefAt(agentRefs, i); return ref ? { agent: ref } : {}; };
78
-
79
- let currentPhase = "init";
80
- let outcome;
81
-
82
- try {
83
- // ── 段 1:map(parallel 对每个 item 并行变换)────────────────────
84
- phase("map");
85
- currentPhase = "map";
86
-
87
- // 每个 item 字符串化,便于拼进 prompt
88
- const mappedRaw = await parallel(
89
- items.map((item, idx) =>
90
- agent({
91
- prompt:
92
- "对以下 item 执行操作:\n\noperation:" + operation +
93
- "\nitem:" + (typeof item === "string" ? item : JSON.stringify(item)),
94
- schema: {
95
- type: "object",
96
- properties: {
97
- itemIndex: { type: "number", description: "item 序号" },
98
- mapped: { type: "string", description: "map 后的结果" },
99
- },
100
- required: ["itemIndex", "mapped"],
101
- },
102
- description: "map-reduce-map-" + idx,
103
- ...stepAgent(0),
104
- })
105
- ),
106
- );
107
-
108
- const mapped = [];
109
- let mapFailed = 0;
110
- for (let i = 0; i < mappedRaw.length; i++) {
111
- const r = mappedRaw[i];
112
- if (!r || r.status === "failed" || r.error) {
113
- mapped.push({
114
- itemIndex: i,
115
- item: items[i],
116
- status: "failed",
117
- error: r ? (r.error || "agent 返回 failed 状态") : "agent 无返回",
118
- });
119
- mapFailed++;
120
- } else {
121
- mapped.push({
122
- itemIndex: i,
123
- item: items[i],
124
- status: "ok",
125
- mapped: (typeof r.mapped === "string" ? r.mapped : "(无结果)"),
126
- });
127
- }
128
- }
129
- if (mapFailed === items.length) {
130
- throw new Error("全部 map 失败(" + mapFailed + "/" + items.length + ")");
131
- }
132
- log("map 完成:ok=" + (items.length - mapFailed) + " failed=" + mapFailed);
133
-
134
- // ── 段 2:reduce(agent 归约所有 map 结果)──────────────────────
135
- phase("reduce");
136
- currentPhase = "reduce";
137
-
138
- const reducedResult = await agent({
139
- prompt:
140
- "以下是对 " + items.length + " 个 item 执行「" + operation + "」的结果,请归约成单一结论:\n\n" +
141
- JSON.stringify(mapped, null, 2),
142
- schema: {
143
- type: "object",
144
- properties: {
145
- reduced: { type: "string", description: "归约后的最终结果" },
146
- stats: { type: "string", description: "统计摘要(成功率/共性发现等)" },
147
- },
148
- required: ["reduced", "stats"],
149
- },
150
- description: "map-reduce-reduce",
151
- ...stepAgent(1),
152
- });
153
-
154
- outcome = {
155
- status: mapFailed > 0 ? "partial" : "ok",
156
- phases_run: ["map", "reduce"],
157
- items_total: items.length,
158
- items_mapped: items.length - mapFailed,
159
- reduced: {
160
- reduced: (reducedResult?.reduced ?? "(归约无结果)"),
161
- stats: (reducedResult?.stats ?? "(归约无结果)"),
162
- },
163
- message: "map-reduce 完成:map " + items.length + " 项(失败 " + mapFailed + ")→ reduce",
164
- };
165
- } catch (err) {
166
- outcome = {
167
- status: "error",
168
- phase: currentPhase,
169
- error: err && err.message ? err.message : String(err),
170
- message: "map-reduce 在 " + currentPhase + " 段失败",
171
- };
172
- }
173
-
174
- return outcome;