@zhushanwen/subagent-core 0.2.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 (330) hide show
  1. package/README.md +114 -0
  2. package/dist/chunk-3VOERJPJ.js +22 -0
  3. package/dist/chunk-A4IVZWVX.js +31 -0
  4. package/dist/execution/engine/engines/zcode/constants.cjs +54 -0
  5. package/dist/execution/engine/engines/zcode/constants.d.cts +31 -0
  6. package/dist/execution/engine/engines/zcode/constants.d.ts +31 -0
  7. package/dist/execution/engine/engines/zcode/constants.js +22 -0
  8. package/dist/execution/engine/engines/zcode/reader.cjs +276 -0
  9. package/dist/execution/engine/engines/zcode/reader.d.cts +20 -0
  10. package/dist/execution/engine/engines/zcode/reader.d.ts +20 -0
  11. package/dist/execution/engine/engines/zcode/reader.js +239 -0
  12. package/dist/execution/engine/paths.cjs +55 -0
  13. package/dist/execution/engine/paths.d.cts +8 -0
  14. package/dist/execution/engine/paths.d.ts +8 -0
  15. package/dist/execution/engine/paths.js +26 -0
  16. package/dist/execution/relay-env.cjs +62 -0
  17. package/dist/execution/relay-env.d.cts +33 -0
  18. package/dist/execution/relay-env.d.ts +33 -0
  19. package/dist/execution/relay-env.js +20 -0
  20. package/dist/index.cjs +1852 -0
  21. package/dist/index.d.cts +1184 -0
  22. package/dist/index.d.ts +1184 -0
  23. package/dist/index.js +1810 -0
  24. package/dist/types-BxyAidGf.d.cts +875 -0
  25. package/dist/types-BxyAidGf.d.ts +875 -0
  26. package/package.json +99 -0
  27. package/src/__tests__/agent-opts-resolver-schema-prompt.test.ts +142 -0
  28. package/src/__tests__/append-system-prompt-assembly.test.ts +242 -0
  29. package/src/__tests__/builtin-workflows-structure.test.ts +180 -0
  30. package/src/__tests__/derive-closed-display-parity.test.ts +93 -0
  31. package/src/__tests__/fr4-get-state-handshake.test.ts +125 -0
  32. package/src/__tests__/fr8-orphan-recovery.test.ts +259 -0
  33. package/src/__tests__/m2-append-content-probe.test.ts +73 -0
  34. package/src/__tests__/manifest-store.test.ts +368 -0
  35. package/src/__tests__/record-store-cache.test.ts +335 -0
  36. package/src/__tests__/record-store-index.test.ts +560 -0
  37. package/src/__tests__/record-store-last-line.test.ts +129 -0
  38. package/src/__tests__/review-fix-loop-script.test.ts +288 -0
  39. package/src/__tests__/review-fix-loop-utils.test.ts +2377 -0
  40. package/src/__tests__/robustness-low-batch1.test.ts +286 -0
  41. package/src/__tests__/robustness-medium-batch1.test.ts +69 -0
  42. package/src/__tests__/robustness-medium-batch2.test.ts +65 -0
  43. package/src/__tests__/robustness-medium-batch3.test.ts +30 -0
  44. package/src/__tests__/robustness-medium-batch4.test.ts +358 -0
  45. package/src/__tests__/session-runner.test.ts +69 -0
  46. package/src/__tests__/smoke.test.ts +9 -0
  47. package/src/__tests__/stream-sink.test.ts +203 -0
  48. package/src/core/__tests__/host-services.test.ts +144 -0
  49. package/src/core/__tests__/logger.test.ts +78 -0
  50. package/src/core/__tests__/notify-ports.test.ts +104 -0
  51. package/src/core/host-services.ts +97 -0
  52. package/src/core/logger.ts +47 -0
  53. package/src/core/notify-ports.ts +126 -0
  54. package/src/execution/__tests__/__fixtures__/notifier-golden-snapshots.json +53 -0
  55. package/src/execution/__tests__/__fixtures__/truncline.snapshot.json +1 -0
  56. package/src/execution/__tests__/agent-result-mapper.test.ts +150 -0
  57. package/src/execution/__tests__/alive-store.test.ts +147 -0
  58. package/src/execution/__tests__/ask-user-transit-e2e.test.ts +490 -0
  59. package/src/execution/__tests__/channel-registry-handshake.test.ts +242 -0
  60. package/src/execution/__tests__/chat-engine-routing.test.ts +610 -0
  61. package/src/execution/__tests__/chatmode-first-round-closure-spawn.test.ts +190 -0
  62. package/src/execution/__tests__/concurrency-pool.test.ts +250 -0
  63. package/src/execution/__tests__/config.test.ts +302 -0
  64. package/src/execution/__tests__/delivery-methods.test.ts +424 -0
  65. package/src/execution/__tests__/dialog-queue.test.ts +299 -0
  66. package/src/execution/__tests__/epipe-fallback.test.ts +241 -0
  67. package/src/execution/__tests__/execute-and-await-worktree.test.ts +243 -0
  68. package/src/execution/__tests__/execute-nesting.test.ts +323 -0
  69. package/src/execution/__tests__/execute-options-mapper.test.ts +200 -0
  70. package/src/execution/__tests__/execution-record.test.ts +1394 -0
  71. package/src/execution/__tests__/explicit-agent-ref-guard.test.ts +171 -0
  72. package/src/execution/__tests__/finalize-record.test.ts +367 -0
  73. package/src/execution/__tests__/finalized-marker.test.ts +104 -0
  74. package/src/execution/__tests__/format-schema-instruction.test.ts +169 -0
  75. package/src/execution/__tests__/gc-timer.test.ts +184 -0
  76. package/src/execution/__tests__/get-record-for-action-restart.test.ts +254 -0
  77. package/src/execution/__tests__/helpers/mock-extension-api.ts +30 -0
  78. package/src/execution/__tests__/helpers/spawn-mock.ts +242 -0
  79. package/src/execution/__tests__/host-mode.test.ts +87 -0
  80. package/src/execution/__tests__/lifecycle-manager-lock.test.ts +211 -0
  81. package/src/execution/__tests__/lifecycle-manager.test.ts +383 -0
  82. package/src/execution/__tests__/lifecycle-predicates.test.ts +116 -0
  83. package/src/execution/__tests__/manifest-parentid.test.ts +117 -0
  84. package/src/execution/__tests__/model-resolver.test.ts +465 -0
  85. package/src/execution/__tests__/nested-visibility-env-propagation.test.ts +287 -0
  86. package/src/execution/__tests__/nested-visibility.test.ts +325 -0
  87. package/src/execution/__tests__/output-collector.test.ts +358 -0
  88. package/src/execution/__tests__/path-encoding.test.ts +104 -0
  89. package/src/execution/__tests__/pi-invocation.test.ts +134 -0
  90. package/src/execution/__tests__/record-store.test.ts +1057 -0
  91. package/src/execution/__tests__/records-cwd-isolation.test.ts +91 -0
  92. package/src/execution/__tests__/recursive-visibility-baseline.test.ts +339 -0
  93. package/src/execution/__tests__/recursive-visibility-env.test.ts +273 -0
  94. package/src/execution/__tests__/relay-env.test.ts +42 -0
  95. package/src/execution/__tests__/resource-policy.test.ts +109 -0
  96. package/src/execution/__tests__/rpc-mode.test.ts +89 -0
  97. package/src/execution/__tests__/run-and-finalize-chatmode.test.ts +267 -0
  98. package/src/execution/__tests__/run-spawn-chatmode-settled.test.ts +253 -0
  99. package/src/execution/__tests__/run-spawn-edges.test.ts +687 -0
  100. package/src/execution/__tests__/run-spawn-integration.test.ts +933 -0
  101. package/src/execution/__tests__/run-spawn-resume.test.ts +322 -0
  102. package/src/execution/__tests__/run-spawn-rpc-mode.test.ts +196 -0
  103. package/src/execution/__tests__/run-spawn-stdout-callback-throw.test.ts +199 -0
  104. package/src/execution/__tests__/session-context-resolver.test.ts +167 -0
  105. package/src/execution/__tests__/session-file-gc.test.ts +293 -0
  106. package/src/execution/__tests__/session-reconstructor.test.ts +379 -0
  107. package/src/execution/__tests__/session-runner-epipe.test.ts +178 -0
  108. package/src/execution/__tests__/session-runner-schema-env.test.ts +350 -0
  109. package/src/execution/__tests__/spawn-args.test.ts +445 -0
  110. package/src/execution/__tests__/spawn-event-adapter-rpc.test.ts +189 -0
  111. package/src/execution/__tests__/spawn-event-adapter.test.ts +167 -0
  112. package/src/execution/__tests__/spawn-worktree-guidance.test.ts +207 -0
  113. package/src/execution/__tests__/spawned-children.test.ts +92 -0
  114. package/src/execution/__tests__/start-sync-model-guard.test.ts +150 -0
  115. package/src/execution/__tests__/stdin-writer.test.ts +462 -0
  116. package/src/execution/__tests__/stream-sink-retirement.test.ts +261 -0
  117. package/src/execution/__tests__/subagent-service-abort.test.ts +60 -0
  118. package/src/execution/__tests__/subagent-service-message-close.test.ts +629 -0
  119. package/src/execution/__tests__/subagent-service-parent-guard.test.ts +180 -0
  120. package/src/execution/__tests__/subagent-service.test.ts +788 -0
  121. package/src/execution/__tests__/subprocess-agent-runner-routing.test.ts +310 -0
  122. package/src/execution/__tests__/subprocess-agent-runner.test.ts +612 -0
  123. package/src/execution/__tests__/temp-prompt.test.ts +53 -0
  124. package/src/execution/__tests__/timeout-integration.test.ts +615 -0
  125. package/src/execution/__tests__/tombstone-store.test.ts +73 -0
  126. package/src/execution/__tests__/turn-limiter-semantics.test.ts +194 -0
  127. package/src/execution/__tests__/turn-limiter.test.ts +65 -0
  128. package/src/execution/__tests__/ui-channels.test.ts +187 -0
  129. package/src/execution/__tests__/ui-interaction-model.test.ts +67 -0
  130. package/src/execution/__tests__/ui-request-handler-factory.test.ts +369 -0
  131. package/src/execution/__tests__/ui-request-handler.test.ts +204 -0
  132. package/src/execution/__tests__/ui-request-observability.test.ts +113 -0
  133. package/src/execution/__tests__/ui-request-queue.test.ts +133 -0
  134. package/src/execution/__tests__/worktree-manager.test.ts +633 -0
  135. package/src/execution/__tests__/worktree-pid-registration.integration.test.ts +229 -0
  136. package/src/execution/__tests__/worktree-reconcile.integration.test.ts +181 -0
  137. package/src/execution/__tests__/worktree-registry.test.ts +199 -0
  138. package/src/execution/agent-registry.ts +199 -0
  139. package/src/execution/agent-result-mapper.ts +90 -0
  140. package/src/execution/alive-store.ts +119 -0
  141. package/src/execution/argv-mirror.ts +113 -0
  142. package/src/execution/best-effort.ts +38 -0
  143. package/src/execution/channel-registry-access.ts +144 -0
  144. package/src/execution/concurrency-pool.ts +116 -0
  145. package/src/execution/config.ts +165 -0
  146. package/src/execution/dialog-queue.ts +330 -0
  147. package/src/execution/engine/__tests__/common/data-dir.test.ts +78 -0
  148. package/src/execution/engine/__tests__/common/errors.test.ts +132 -0
  149. package/src/execution/engine/__tests__/common/event-journal.test.ts +177 -0
  150. package/src/execution/engine/__tests__/common/kill-chain.test.ts +192 -0
  151. package/src/execution/engine/__tests__/common/nesting-guard.test.ts +81 -0
  152. package/src/execution/engine/__tests__/common/persona-router.test.ts +123 -0
  153. package/src/execution/engine/__tests__/common/pool-manager.test.ts +154 -0
  154. package/src/execution/engine/__tests__/common/schema-emulation.test.ts +128 -0
  155. package/src/execution/engine/__tests__/conformance/__fixtures__/pi-golden-events.json +28 -0
  156. package/src/execution/engine/__tests__/conformance/agent-event-invariants.ts +141 -0
  157. package/src/execution/engine/__tests__/conformance/contract.abort.test.ts +109 -0
  158. package/src/execution/engine/__tests__/conformance/contract.agent-events.test.ts +101 -0
  159. package/src/execution/engine/__tests__/conformance/contract.probe.test.ts +77 -0
  160. package/src/execution/engine/__tests__/conformance/contract.read-degradation.test.ts +104 -0
  161. package/src/execution/engine/__tests__/conformance/engine-conformance.live.test.ts +201 -0
  162. package/src/execution/engine/__tests__/conformance/golden-replay.pi.test.ts +76 -0
  163. package/src/execution/engine/__tests__/conformance/golden-replay.zcode.test.ts +79 -0
  164. package/src/execution/engine/__tests__/engine-discovery.test.ts +87 -0
  165. package/src/execution/engine/__tests__/model-prompt.test.ts +197 -0
  166. package/src/execution/engine/__tests__/paths.test.ts +39 -0
  167. package/src/execution/engine/__tests__/registry.test.ts +120 -0
  168. package/src/execution/engine/__tests__/routing.test.ts +231 -0
  169. package/src/execution/engine/common/data-dir.ts +66 -0
  170. package/src/execution/engine/common/errors.ts +183 -0
  171. package/src/execution/engine/common/event-journal.ts +254 -0
  172. package/src/execution/engine/common/journal-replay.ts +62 -0
  173. package/src/execution/engine/common/kill-chain.ts +221 -0
  174. package/src/execution/engine/common/nesting-guard.ts +50 -0
  175. package/src/execution/engine/common/persona-router.ts +108 -0
  176. package/src/execution/engine/common/pool-manager.ts +226 -0
  177. package/src/execution/engine/common/schema-emulation.ts +189 -0
  178. package/src/execution/engine/common/session-view-projection.ts +51 -0
  179. package/src/execution/engine/engine-discovery.ts +65 -0
  180. package/src/execution/engine/engines/pi/__tests__/pi-engine.test.ts +469 -0
  181. package/src/execution/engine/engines/pi/__tests__/reader.test.ts +155 -0
  182. package/src/execution/engine/engines/pi/__tests__/task-spec-mapper.test.ts +164 -0
  183. package/src/execution/engine/engines/pi/pi-engine.ts +415 -0
  184. package/src/execution/engine/engines/pi/reader.ts +48 -0
  185. package/src/execution/engine/engines/pi/registration.ts +35 -0
  186. package/src/execution/engine/engines/pi/task-spec-mapper.ts +100 -0
  187. package/src/execution/engine/engines/zcode/__tests__/__fixtures__/zcode-golden-spawn.json +39 -0
  188. package/src/execution/engine/engines/zcode/__tests__/launcher.test.ts +150 -0
  189. package/src/execution/engine/engines/zcode/__tests__/parser.test.ts +246 -0
  190. package/src/execution/engine/engines/zcode/__tests__/preparer.test.ts +228 -0
  191. package/src/execution/engine/engines/zcode/__tests__/reader.test.ts +210 -0
  192. package/src/execution/engine/engines/zcode/__tests__/registration.test.ts +71 -0
  193. package/src/execution/engine/engines/zcode/__tests__/zcode-engine.live.test.ts +127 -0
  194. package/src/execution/engine/engines/zcode/__tests__/zcode-engine.test.ts +580 -0
  195. package/src/execution/engine/engines/zcode/constants.ts +43 -0
  196. package/src/execution/engine/engines/zcode/golden-sample.ts +39 -0
  197. package/src/execution/engine/engines/zcode/launcher.ts +161 -0
  198. package/src/execution/engine/engines/zcode/parser.ts +436 -0
  199. package/src/execution/engine/engines/zcode/preparer.ts +363 -0
  200. package/src/execution/engine/engines/zcode/reader.ts +381 -0
  201. package/src/execution/engine/engines/zcode/registration.ts +37 -0
  202. package/src/execution/engine/engines/zcode/zcode-engine.ts +658 -0
  203. package/src/execution/engine/host-task-spec.ts +47 -0
  204. package/src/execution/engine/model-prompt.ts +158 -0
  205. package/src/execution/engine/paths.ts +42 -0
  206. package/src/execution/engine/port.ts +153 -0
  207. package/src/execution/engine/registry.ts +133 -0
  208. package/src/execution/engine/routing.ts +218 -0
  209. package/src/execution/engine/types.ts +309 -0
  210. package/src/execution/execute-options-mapper.ts +115 -0
  211. package/src/execution/execution-record.ts +984 -0
  212. package/src/execution/finalize-record.ts +254 -0
  213. package/src/execution/finalized-marker.ts +70 -0
  214. package/src/execution/get-state-handshake.ts +104 -0
  215. package/src/execution/host-mode.ts +56 -0
  216. package/src/execution/idle-gc.ts +47 -0
  217. package/src/execution/lifecycle-manager.ts +513 -0
  218. package/src/execution/lifecycle-predicates.ts +65 -0
  219. package/src/execution/manifest-store.ts +256 -0
  220. package/src/execution/model-config-service.ts +250 -0
  221. package/src/execution/model-resolver.ts +248 -0
  222. package/src/execution/notifier.ts +372 -0
  223. package/src/execution/notify-ledger.ts +580 -0
  224. package/src/execution/output-collector.ts +228 -0
  225. package/src/execution/path-encoding.ts +60 -0
  226. package/src/execution/pi-invocation.ts +120 -0
  227. package/src/execution/record-entry.ts +132 -0
  228. package/src/execution/record-store.ts +1265 -0
  229. package/src/execution/relay-env.ts +37 -0
  230. package/src/execution/session-context-resolver.ts +64 -0
  231. package/src/execution/session-file-gc.ts +120 -0
  232. package/src/execution/session-pending.ts +170 -0
  233. package/src/execution/session-reconstructor.ts +678 -0
  234. package/src/execution/session-runner.ts +1789 -0
  235. package/src/execution/sessions-index.ts +304 -0
  236. package/src/execution/spawn-event-adapter.ts +363 -0
  237. package/src/execution/stdin-writer.ts +198 -0
  238. package/src/execution/stream-sink.ts +126 -0
  239. package/src/execution/subagent-service.ts +2268 -0
  240. package/src/execution/subprocess-agent-runner.ts +317 -0
  241. package/src/execution/temp-prompt.ts +62 -0
  242. package/src/execution/tombstone-store.ts +72 -0
  243. package/src/execution/turn-limiter.ts +102 -0
  244. package/src/execution/types.ts +1023 -0
  245. package/src/execution/ui-channels.ts +216 -0
  246. package/src/execution/ui-interaction-model.ts +48 -0
  247. package/src/execution/ui-request-handler-factory.ts +243 -0
  248. package/src/execution/ui-request-observability.ts +81 -0
  249. package/src/execution/ui-request-queue.ts +184 -0
  250. package/src/execution/worktree-manager.ts +688 -0
  251. package/src/execution/worktree-registry.ts +279 -0
  252. package/src/index.ts +87 -0
  253. package/src/orchestration/__tests__/__fixtures__/worker-template.snapshot.txt +349 -0
  254. package/src/orchestration/__tests__/agent-call-catch-fallback.test.ts +202 -0
  255. package/src/orchestration/__tests__/agent-call-stream.test.ts +152 -0
  256. package/src/orchestration/__tests__/args-validator.test.ts +143 -0
  257. package/src/orchestration/__tests__/config-loader.test.ts +503 -0
  258. package/src/orchestration/__tests__/error-recovery-handlers.test.ts +809 -0
  259. package/src/orchestration/__tests__/error-recovery-postmessage-defense.test.ts +404 -0
  260. package/src/orchestration/__tests__/error-recovery-serialize-failed-result.test.ts +56 -0
  261. package/src/orchestration/__tests__/error-recovery-workflow-call.test.ts +166 -0
  262. package/src/orchestration/__tests__/execute-agent-call.test.ts +451 -0
  263. package/src/orchestration/__tests__/launcher-nested-workflow.test.ts +600 -0
  264. package/src/orchestration/__tests__/lifecycle-runid-injection.test.ts +96 -0
  265. package/src/orchestration/__tests__/lifecycle.test.ts +659 -0
  266. package/src/orchestration/__tests__/non-cloneable-return-e2e.test.ts +95 -0
  267. package/src/orchestration/__tests__/review-fix-loop-scriptpath-failfast.test.ts +183 -0
  268. package/src/orchestration/__tests__/script-lint.test.ts +831 -0
  269. package/src/orchestration/__tests__/skill-discovery.test.ts +210 -0
  270. package/src/orchestration/__tests__/test-mocks.ts +197 -0
  271. package/src/orchestration/__tests__/worker-exit-without-result.test.ts +368 -0
  272. package/src/orchestration/__tests__/worker-host.test.ts +120 -0
  273. package/src/orchestration/__tests__/worker-returnmeta-passthrough.test.ts +164 -0
  274. package/src/orchestration/__tests__/worker-script-builder-runtime.test.ts +563 -0
  275. package/src/orchestration/__tests__/worker-script-builder.test.ts +309 -0
  276. package/src/orchestration/__tests__/worker-script-template-snapshot.test.ts +129 -0
  277. package/src/orchestration/__tests__/workflow-nesting-e2e.test.ts +317 -0
  278. package/src/orchestration/__tests__/workflow-script-lint-memo.test.ts +110 -0
  279. package/src/orchestration/agent-opts-resolver.ts +174 -0
  280. package/src/orchestration/args-validator.ts +127 -0
  281. package/src/orchestration/config-loader.ts +316 -0
  282. package/src/orchestration/error-recovery.ts +1018 -0
  283. package/src/orchestration/execute-agent-call.ts +256 -0
  284. package/src/orchestration/launcher.ts +455 -0
  285. package/src/orchestration/lifecycle.ts +399 -0
  286. package/src/orchestration/models/__tests__/budget.test.ts +307 -0
  287. package/src/orchestration/models/agent-call.ts +83 -0
  288. package/src/orchestration/models/budget.ts +118 -0
  289. package/src/orchestration/models/ports.ts +164 -0
  290. package/src/orchestration/models/run-runtime.ts +104 -0
  291. package/src/orchestration/models/run-spec.ts +83 -0
  292. package/src/orchestration/models/run-state.ts +44 -0
  293. package/src/orchestration/models/trace.ts +183 -0
  294. package/src/orchestration/models/types.ts +301 -0
  295. package/src/orchestration/models/workflow-run.ts +254 -0
  296. package/src/orchestration/models/workflow-script-registry.ts +35 -0
  297. package/src/orchestration/models/workflow-script.ts +117 -0
  298. package/src/orchestration/script-lint.ts +766 -0
  299. package/src/orchestration/skill-discovery.ts +135 -0
  300. package/src/orchestration/worker-handle.ts +115 -0
  301. package/src/orchestration/worker-host.ts +98 -0
  302. package/src/orchestration/worker-script-builder.ts +421 -0
  303. package/src/orchestration/workflow-files.ts +85 -0
  304. package/src/orchestration/workflow-script-registry-impl.ts +133 -0
  305. package/src/shared/__tests__/agent-ref.test.ts +34 -0
  306. package/src/shared/__tests__/meta-parser.test.ts +304 -0
  307. package/src/shared/__tests__/model-ref.test.ts +306 -0
  308. package/src/shared/__tests__/resource-discovery-manifest-cache.test.ts +288 -0
  309. package/src/shared/__tests__/resource-discovery.test.ts +749 -0
  310. package/src/shared/__tests__/resource-meta.test.ts +51 -0
  311. package/src/shared/__tests__/schema-jsonify.test.ts +81 -0
  312. package/src/shared/__tests__/timer-delay.test.ts +61 -0
  313. package/src/shared/agent-event.ts +13 -0
  314. package/src/shared/agent-ref.ts +57 -0
  315. package/src/shared/meta-parser.ts +261 -0
  316. package/src/shared/model-ref.ts +286 -0
  317. package/src/shared/resource-discovery.ts +835 -0
  318. package/src/shared/resource-meta.ts +65 -0
  319. package/src/shared/schema-env.ts +44 -0
  320. package/src/shared/schema-jsonify.ts +58 -0
  321. package/src/shared/timer-delay.ts +54 -0
  322. package/src/shared/xml-injection.ts +35 -0
  323. package/workflows/README.md +81 -0
  324. package/workflows/_shared/agent-refs.cjs +40 -0
  325. package/workflows/chain.js +137 -0
  326. package/workflows/map-reduce.js +180 -0
  327. package/workflows/parallel.js +154 -0
  328. package/workflows/review-fix-loop-utils.cjs +1542 -0
  329. package/workflows/review-fix-loop.js +1605 -0
  330. package/workflows/scatter-gather.js +184 -0
@@ -0,0 +1,65 @@
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;
@@ -0,0 +1,44 @@
1
+ /**
2
+ * schema env 跨包契约常量(零依赖叶子模块)。
3
+ *
4
+ * 抽取自 session-runner.ts(S5 记账项):session-runner 依赖树沉重(pi SDK /
5
+ * spawn 链),跨包契约测试若从它 import 常量会把整条依赖树拖进测试进程。
6
+ * 本模块只含常量与纯函数、零 import,为 structured-output 侧(及任何消费者)
7
+ * 的跨包契约测试提供稳定 import 点。
8
+ *
9
+ * 层归属:Shared(orchestration 与 execution 共用,先例 timer-delay.ts)。
10
+ */
11
+
12
+ /**
13
+ * 跨包契约 env 名:workflow 子进程把权威 JSON Schema 通过此 env 传给 structured-output 扩展。
14
+ *
15
+ * [跨包契约 SSOT] 此字面量是两个独立 npm 包(@zhushanwen/pi-subagent-workflow 与
16
+ * @zhushanwen/pi-structured-output)之间的隐式 env 契约。structured-output 包内同名常量为
17
+ * `ENV_SCHEMA = "PI_WORKFLOW_SCHEMA"`(见 extensions/universal/structured-output/src/index.ts)。
18
+ * 两包是独立 npm 包不能直接 import,故各自保留常量但显式标注此契约关系——
19
+ * 任一端改名必须同步另一端,否则权威 schema 注入会静默断桥(子进程不注册 tool/hook)。
20
+ */
21
+ export const SCHEMA_ENV_VAR = "PI_WORKFLOW_SCHEMA";
22
+
23
+ /**
24
+ * schema env 值的字节上限(256 KiB):超过则注入前 fail-fast 拒绝。
25
+ *
26
+ * 背景(SO-DATA-4):schema 经 childEnv 注入子进程,env 值随 spawn argv/env 块走
27
+ * execve 语义——单条 env 值过大叠加全量继承的 process.env 时可能触发 E2BIG
28
+ *(ARG_MAX 约束,Linux 通常 ~2MB 总上限,macOS 更紧),spawn 直接失败且错误难归因
29
+ *(E2BIG 报在 spawn 调用点,与 schema 内容无关的表象)。256KB 对 JSON Schema 是
30
+ * 宽裕上限(正常 schema 数 KB),提前拒绝把「难归因的 spawn 失败」变成
31
+ * 「注入点处含实际大小的明确报错」。
32
+ */
33
+ /** 1 KiB 字节数(换算基数,SCHEMA_ENV_MAX_BYTES 组合用)。 */
34
+ const BYTES_PER_KIB = 1024;
35
+ /** 上限的 KiB 形态(256 KiB = 262144 bytes,注释与文档引用值)。 */
36
+ const SCHEMA_ENV_MAX_KIB = 256;
37
+ export const SCHEMA_ENV_MAX_BYTES = SCHEMA_ENV_MAX_KIB * BYTES_PER_KIB;
38
+
39
+ /**
40
+ * 计算 schema env 值的 UTF-8 字节长度(注入大小 = 该值,用于超限判定与错误消息)。
41
+ */
42
+ export function schemaEnvByteLength(schemaEnv: string): number {
43
+ return Buffer.byteLength(schemaEnv, "utf8");
44
+ }
@@ -0,0 +1,58 @@
1
+ /**
2
+ * Schema JSON 序列化缓存(IF7/#13,TC6/DM4)。
3
+ *
4
+ * 同一 schema 对象引用的重复 JSON.stringify 消除:resolver(compact,instruction
5
+ * 与 schemaEnv 复用同串,formatSchemaInstruction 现居 resolver)在单次 agent call
6
+ * 内对同一 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
+ * pretty 为预留模式,当前生产仅 compact 消费(resolver instruction 与 schemaEnv
30
+ * 复用同串;pretty 暂无生产调用方,仅供测试/未来调试通道)。
31
+ */
32
+ export function stringifySchemaCached(schema: object, mode: "compact" | "pretty"): string {
33
+ let entry = cache.get(schema);
34
+ if (!entry) {
35
+ entry = {};
36
+ cache.set(schema, entry);
37
+ }
38
+ const hit = entry[mode];
39
+ if (hit !== undefined) return hit;
40
+ // [review 修复] TS lib 盲区:lib 对 object 参数声明 JSON.stringify 返回 string,但
41
+ // schema 含 `toJSON: () => undefined` 钩子时运行时返回 undefined——直接违反本函数
42
+ // 声明的 string 返回类型,且 `entry[mode] = undefined` 赋值不生效(缓存永不命中,
43
+ // 重复 stringify 仅是性能损耗)。显式标注 string | undefined 捕获该窗口,fail-loud
44
+ // 抛含恢复指引的错误——不回退 String(value)("[object Object]" 会静默拼进 LLM
45
+ // 指令,比崩溃更难排查)。抛错时 entry[mode] 未被赋值,缓存无毒化。
46
+ const serialized: string | undefined =
47
+ mode === "compact" ? JSON.stringify(schema) : JSON.stringify(schema, null, PRETTY_PRINT_INDENT_SPACES);
48
+ if (serialized === undefined) {
49
+ throw new Error(
50
+ `[subagent-workflow] stringifySchemaCached: JSON.stringify returned undefined (mode=${mode}) — ` +
51
+ `the schema object defines a toJSON hook returning undefined. ` +
52
+ `Recovery: check the schema source (agent definition / workflow script), remove that toJSON ` +
53
+ `or make it return a JSON-serializable value.`,
54
+ );
55
+ }
56
+ entry[mode] = serialized;
57
+ return serialized;
58
+ }
@@ -0,0 +1,54 @@
1
+ /**
2
+ * setTimeout delay 安全域校验(Shared 层,无 Pi 依赖)。
3
+ *
4
+ * Node 的 setTimeout 对超出 32 位有符号整数上限(2^31-1 = 2147483647)的 delay
5
+ * 会把定时器置为 **1ms**(TimerOverflowWarning 路径,实测 setTimeout(fn, 3e9) 约
6
+ * 3ms 触发)——语义完全反转:调用方想表达的「近乎不限时」变成立即触发。对 watchdog
7
+ * / 预算计时器而言即「刚启动就误杀」。
8
+ *
9
+ * 本包三个 timer 挂载/解析入口(budgetTimeMs → lifecycle.scheduleTimeBudget、
10
+ * XYZ_SUBAGENT_SPAWN_WATCHDOG_MS → session-runner.resolveSpawnWatchdogMs、
11
+ * idleTimeoutMs → lifecycle-manager.armIdleTimer)统一在值流入 setTimeout 前调
12
+ * assertSafeTimerDelay fail-fast——不静默 clamp(clamp 把配置错误变成静默语义漂移,
13
+ * 比崩溃更难排查;用户应显式决定 clamp 到多少)。
14
+ *
15
+ * 层归属:Shared(orchestration 与 execution 共用,先例 schema-jsonify.ts)。
16
+ */
17
+
18
+ /** Node setTimeout delay 的安全上限(2^31 - 1,超出的 delay 被置 1ms 立即触发)。 */
19
+ export const MAX_TIMER_DELAY_MS = 2_147_483_647;
20
+
21
+ /**
22
+ * 校验即将流入 setTimeout 的 delay 值在安全域内,越界 fail-fast。
23
+ *
24
+ * 错误信息含上限值与恢复指引(建议 clamp 后重试)——不静默 clamp:调用方须显式
25
+ * 决定 clamp 目标值(语义归属调用方,helper 不替用户做语义决定)。
26
+ *
27
+ * [F-3 NaN 穿透修复] 非有限数(Number.isFinite 为 false:NaN / ±Infinity)同样
28
+ * fail-fast——旧实现只挡 `> MAX`,NaN 的 `NaN > MAX` 为 false 静默放行,
29
+ * setTimeout(fn, NaN) 被 Node 塌缩为 1ms 立即触发(语义反转:watchdog 刚启动就误杀)。
30
+ * 错误消息区分「非有限值」与「超出上限」两种指引,恢复动作各自可达。
31
+ *
32
+ * @param ms 即将作为 setTimeout delay 的毫秒值(调用方保证已过 undefined/<=0 分流;
33
+ * 本函数只防溢出域与非有限值,0/负值的「禁用/不限」语义由各入口自行处理)
34
+ * @param source 值的来源标识(进错误信息,定位用,如 "budgetTimeMs" / env 名)
35
+ * @throws Error 当 ms 非有限(NaN/±Infinity)或超出 MAX_TIMER_DELAY_MS
36
+ */
37
+ export function assertSafeTimerDelay(ms: number, source: string): void {
38
+ if (!Number.isFinite(ms)) {
39
+ throw new Error(
40
+ `[subagent-workflow] ${source} = ${ms} is not a finite number (NaN/±Infinity). ` +
41
+ "Non-finite delays collapse to 1ms in Node setTimeout and fire immediately. " +
42
+ "Recovery: fix the upstream computation that produced this value " +
43
+ "(e.g. guard division/parse results before passing them in) and retry.",
44
+ );
45
+ }
46
+ if (ms > MAX_TIMER_DELAY_MS) {
47
+ throw new Error(
48
+ `[subagent-workflow] ${source} = ${ms} exceeds the Node setTimeout limit ` +
49
+ `(${MAX_TIMER_DELAY_MS} ms = 2^31-1); larger delays silently collapse to 1ms and fire immediately. ` +
50
+ `Recovery: clamp the value to <= ${MAX_TIMER_DELAY_MS} (e.g. omit the option for "unlimited" ` +
51
+ `semantics, or clamp explicitly) and retry.`,
52
+ );
53
+ }
54
+ }
@@ -0,0 +1,35 @@
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
+ }
@@ -0,0 +1,81 @@
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"的决策
@@ -0,0 +1,40 @@
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 };
@@ -0,0 +1,137 @@
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
+ // scriptPath 注入是 worker 契约的显式前提(D1 加固),缺席即 fail-fast,
41
+ // 不回退 cwd——消除从用户目录误加载/被植入同名 _shared/agent-refs.cjs 的代码加载面。
42
+ if (typeof workerData === "undefined" || !workerData || typeof workerData.scriptPath !== "string") {
43
+ throw new Error("chain: core_module_load_failed: workerData.scriptPath 缺失,无法定位 workflows/_shared/agent-refs.cjs。" +
44
+ "恢复动作:worker 宿主(WorkerHost)启动 worker 时必须经 workerData 注入 scriptPath" +
45
+ "(指向本脚本真实路径,注入点见 src/orchestration/worker-host.ts 的 workerData 组装处)," +
46
+ "禁止依赖 process.cwd() 巧合。");
47
+ }
48
+ const SCRIPT_DIR = require("path").dirname(workerData.scriptPath);
49
+ const { parseAgentRefs, agentRefAt } = require(SCRIPT_DIR + "/_shared/agent-refs.cjs");
50
+ const agentRefs = parseAgentRefs($ARGS.agents);
51
+ const stepAgent = (i) => { const ref = agentRefAt(agentRefs, i); return ref ? { agent: ref } : {}; };
52
+
53
+ log("chain 开始,task=" + task + (agentRefs.length ? ",agents=" + agentRefs.join(",") : ""));
54
+
55
+ let currentPhase = "init";
56
+ let outcome;
57
+
58
+ try {
59
+ // ── 段 1:analyze(分析任务,提取关键点)─────────────────────────
60
+ phase("analyze");
61
+ currentPhase = "analyze";
62
+ const analysis = await agent({
63
+ prompt: "分析以下任务,提取核心洞察和关键点:\n\n" + task,
64
+ schema: {
65
+ type: "object",
66
+ properties: {
67
+ insights: { type: "string", description: "对任务的核心洞察" },
68
+ keyPoints: {
69
+ type: "array",
70
+ items: { type: "string" },
71
+ description: "关键点列表",
72
+ },
73
+ },
74
+ required: ["insights", "keyPoints"],
75
+ },
76
+ description: "chain-analyze",
77
+ ...stepAgent(0),
78
+ });
79
+
80
+ // ── 段 2:transform(基于分析产出方案)───────────────────────────
81
+ phase("transform");
82
+ currentPhase = "transform";
83
+ const plan = await agent({
84
+ prompt:
85
+ "基于以下分析结果,产出可执行方案:\n\n洞察:" + (analysis?.insights ?? "(分析无结果)") +
86
+ "\n关键点:" + JSON.stringify(analysis?.keyPoints ?? []),
87
+ schema: {
88
+ type: "object",
89
+ properties: {
90
+ plan: { type: "string", description: "执行方案" },
91
+ actions: {
92
+ type: "array",
93
+ items: { type: "string" },
94
+ description: "具体行动步骤",
95
+ },
96
+ },
97
+ required: ["plan", "actions"],
98
+ },
99
+ description: "chain-transform",
100
+ ...stepAgent(1),
101
+ });
102
+
103
+ // ── 段 3:synthesize(综合方案输出最终结论)─────────────────────
104
+ phase("synthesize");
105
+ currentPhase = "synthesize";
106
+ const final = await agent({
107
+ prompt:
108
+ "综合以下方案,输出最终结论和建议:\n\n方案:" + (plan?.plan ?? "(方案无结果)") +
109
+ "\n行动步骤:" + JSON.stringify(plan?.actions ?? []),
110
+ schema: {
111
+ type: "object",
112
+ properties: {
113
+ summary: { type: "string", description: "最终总结" },
114
+ recommendation: { type: "string", description: "核心建议" },
115
+ },
116
+ required: ["summary", "recommendation"],
117
+ },
118
+ description: "chain-synthesize",
119
+ ...stepAgent(2),
120
+ });
121
+
122
+ outcome = {
123
+ status: "ok",
124
+ phases_run: ["analyze", "transform", "synthesize"],
125
+ final: { summary: (final?.summary ?? "(综合无结果)"), recommendation: (final?.recommendation ?? "(综合无结果)") },
126
+ message: "chain 完成:analyze → transform → synthesize 全绿",
127
+ };
128
+ } catch (err) {
129
+ outcome = {
130
+ status: "error",
131
+ phase: currentPhase,
132
+ error: err && err.message ? err.message : String(err),
133
+ message: "chain 在 " + currentPhase + " 段失败",
134
+ };
135
+ }
136
+
137
+ return outcome;