@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,303 +0,0 @@
1
- // src/execution/subprocess-agent-runner.ts
2
- //
3
- // Wave 4: SubprocessAgentRunner 委托重写
4
- //
5
- // 从"自己 spawn pi"改为"委托 SubagentService.executeAndAwait"。
6
- // MF-3: 从 orchestration/infra 迁入 execution,同层委托 SubagentService。
7
- //
8
- // 接线层级:
9
- // [跨模块 port] implements AgentRunner(orchestration/models/ports.ts)
10
- // [模块内直调] mapToExecuteOptions + mergeTimeoutSignal(execute-options-mapper)
11
- // [P4 路由层] engine/routing.ts routeEngine(三层优先级 + probe + fallback 三守卫,D9)
12
- // [引擎层] EnginePort.run(pi = 本地 DI 绑定实例;非 pi = registry.getEngine 动态获取)
13
- // [模块内直调] this.subagentService.executeAndAwait(PiEngine 内部委托目标)
14
- //
15
- // 设计基线:
16
- // D-A2(映射归 adapter)/ D-A8(onEvent 桥接)/ D-A9(timeoutMs 合并 signal)/
17
- // D-008(model 填底,不调 resolveModel)/ BC-9(timeoutMs 行为)/ BC-10(live-record 进度)
18
-
19
- import type { AgentRunner } from "../orchestration/models/ports.ts";
20
- import type { AgentCallOpts, AgentResult } from "../orchestration/models/types.ts";
21
- import type { AgentEvent } from "../shared/agent-event.ts";
22
- import { getEngineDataDir } from "./engine/common/data-dir.ts";
23
- import { JournalWriter } from "./engine/common/event-journal.ts";
24
- import { createPiEngine, PI_POOL_KEY } from "./engine/engines/pi/registration.ts";
25
- import { executeOptionsToTaskSpec } from "./engine/engines/pi/task-spec-mapper.ts";
26
- import { resolveJournalPath } from "./engine/paths.ts";
27
- import type { EnginePort, RunContext } from "./engine/port.ts";
28
- import { routeEngine, resolveEngineRouting, type EngineRouteResult, type EngineRoutingInput } from "./engine/routing.ts";
29
- import { getEngine, hasEngine, listEngines } from "./engine/registry.ts";
30
- import type { AgentOutcome, EngineHandle } from "./engine/types.ts";
31
- import { mapToExecuteOptions, mergeTimeoutSignal } from "./execute-options-mapper.ts";
32
- import { getModelConfigService } from "./model-config-service.ts";
33
- import type { ModelInfo } from "./model-resolver.ts";
34
- import { registerSpawnedChildForRecord } from "./session-runner.ts";
35
- import type { SubagentStream } from "./stream-sink.ts";
36
- import type { SubagentService } from "./subagent-service.ts";
37
- import type { ExecuteOptions } from "./types.ts";
38
-
39
- // ── 构造依赖(per-session 注入)──
40
-
41
- /**
42
- * SAR 构造参数。
43
- *
44
- * per-session(makeDeps 时创建,随 session 销毁):
45
- * - subagentService: 进程单例(getSubagentService()),委托目标
46
- * - ctxModel: 当前 session 主 agent 模型(D-008 model 填底,opts.model 空时用此)
47
- *
48
- * resolveAgentOpts 在 orchestration 层完成(M2 修正后单参数,只处理 schema SO 指令 + skill),
49
- * 结果填进 AgentCallOpts.skillPath/schemaEnv/appendSystemPrompt,SAR 收已解析的 opts。
50
- * 不含 agent/session 目录/临时文件集合依赖(agent ref 交 resolveIdentity,无临时文件)。
51
- */
52
- export interface SubprocessAgentRunnerDeps {
53
- subagentService: SubagentService;
54
- ctxModel?: ModelInfo;
55
- }
56
-
57
- /**
58
- * AgentRunner port 实现——委托 SubagentService.executeAndAwait。
59
- *
60
- * 层归属:execution(MF-3 从 orchestration 迁入)。implements orchestration 层 port。
61
- *
62
- * 行为契约(BC-1/BC-2/BC-9/BC-10):
63
- * - opts 形状不变(AgentCallOpts,含 resolveAgentOpts 填的 skillPath/schemaEnv)
64
- * - result 形状不变(workflow AgentResult: content/parsedOutput/usage/error/toolCalls)
65
- * - 不 reject——失败信息入 result.error(与 executeAgentCall 契约一致)
66
- * - timeoutMs 合并 signal(D-A9);onEvent 桥接 AgentEvent→workflow liveRecord(D-A8)
67
- *
68
- * [P1 引擎接线] 执行经 EnginePort。pi 引擎绑定本 SAR 的服务引用(per-session DI——
69
- * 单测注入 mock 时全局单例不可见;生产环境两者是同一进程单例对象),行为零变化;
70
- * 非 pi 引擎(P4 路由可达:frontmatter/调用参数/全局默认指定)经 registry.getEngine
71
- * 动态获取——「引擎身份」的归属边界在注册表,SAR 不感知具体引擎实现。
72
- *
73
- * [P4 配置路由] 每次运行经 engine/routing.ts 解析三层优先级(调用参数 opts.engine >
74
- * agent frontmatter engine > 全局默认 'pi')+ probe + fallback 三守卫(D9)。路由失败
75
- * (engine_not_found / engine_probe_failed / model_not_available)不 reject,入
76
- * result.error——与 executeAgentCall 契约一致。
77
- */
78
- export class SubprocessAgentRunner implements AgentRunner {
79
- private readonly subagentService: SubagentService;
80
- private ctxModel: ModelInfo | undefined;
81
- /** pi 引擎(per-session DI 绑定,缺省执行路径——见类注释)。 */
82
- private readonly piEngine: EnginePort;
83
-
84
- constructor(deps: SubprocessAgentRunnerDeps) {
85
- this.subagentService = deps.subagentService;
86
- this.ctxModel = deps.ctxModel;
87
- this.piEngine = createPiEngine(() => this.subagentService);
88
- }
89
-
90
- /**
91
- * 刷新主 agent model 缓存。model_select 事件时由 index.ts 调用。
92
- * H1 修复:旧实现 ctxModel 是 readonly,session_start 后固化,
93
- * model_select 只刷新 ModelConfigService._ctxModel 不更新 SAR →
94
- * workflow 路径用过期模型。
95
- */
96
- updateCtxModel(model: ModelInfo | undefined): void {
97
- this.ctxModel = model;
98
- }
99
-
100
- /**
101
- * 执行单次 agent 调用:路由(P4)→ EnginePort.run → PiEngine 委托
102
- * SubagentService.executeAndAwait。
103
- *
104
- * 接线链路:
105
- * routeEngine(三层 + probe + 守卫)→ mergeTimeoutSignal → mapToExecuteOptions →
106
- * AgentTaskSpec → engine.run(PiEngine:spec → ExecuteOptions 还原 + engine 留痕)→
107
- * executeAndAwait → AgentOutcome → AgentResult
108
- *
109
- * 错误处理:不 reject。
110
- * - 路由失败(未注册 id / probe 失败 + 守卫或 strict)→ AgentResult.error(错误码前缀)
111
- * - executeAndAwait 内部失败 → 返回 AgentResult(success:false) → 已映射 error 字段
112
- * - executeAndAwait throw(嵌套超限 BC-12)→ catch → AgentResult.error
113
- * - spawn 级失败已由 runSpawn 内部收口为 failed AgentResult(不逃逸)
114
- */
115
- async run(
116
- opts: AgentCallOpts,
117
- signal: AbortSignal,
118
- onEvent?: (event: AgentEvent) => void,
119
- stream?: SubagentStream,
120
- ): Promise<AgentResult> {
121
- const startedAt = Date.now();
122
-
123
- // ── P4 路由:三层优先级 + probe + fallback 三守卫(D9①/D7)──
124
- // 路由在最前——引擎身份决定 journal 路径与后续一切执行面;失败(未注册 id /
125
- // probe 失败 + strict/守卫)按「不 reject」契约转 result.error。
126
- // pi 快路径同步短路(不经 routeEngine 的 await):pi 恒免探、无 fallback 可言、
127
- // engineFor('pi') 本地 DI 绑定恒可用——不引入微任务边界,缺省路径时序与 P1 接线
128
- // 前完全一致(下游依赖「run 内首个 await 前已触达 executeAndAwait」的时序契约)。
129
- let routingInput: EngineRoutingInput;
130
- let route: EngineRouteResult;
131
- try {
132
- routingInput = this.buildRoutingInput(opts);
133
- const routing = resolveEngineRouting(routingInput);
134
- if (routing.engineId === "pi") {
135
- route = {
136
- engine: this.piEngine,
137
- engineId: "pi",
138
- requestedEngineId: "pi",
139
- source: routing.source,
140
- };
141
- } else {
142
- route = await routeEngine({
143
- routing: routingInput,
144
- taskModel: opts.model,
145
- strict: getModelConfigService()?.getGlobalConfig().engineRouting?.strict === true,
146
- probe: (engineId) => this.engineFor(engineId).probe(),
147
- getEngineFn: (engineId) => this.engineFor(engineId),
148
- // pi 经本地 DI 绑定恒可用(不依赖 registry 全局注册态——SAR 持有服务引用),
149
- // has/list 注入同一口径,engine_not_found 文案不会把本地 pi 漏报成未注册
150
- hasEngineFn: (engineId) => engineId === "pi" || hasEngine(engineId),
151
- listEnginesFn: () => (hasEngine("pi") ? listEngines() : ["pi", ...listEngines()]),
152
- });
153
- }
154
- } catch (err) {
155
- // buildRoutingInput 的 agent 解析期校验(未注册 frontmatter engine)与路由失败
156
- // (probe + strict/守卫)一并在此收口——「不 reject」契约
157
- return errorResult(err, startedAt);
158
- }
159
-
160
- // ── P2 event journal 接线(设计 D6 第②级;对齐点③:路径权威 = 引擎池 key)──
161
- // host 在 onEvent 回调内统一落盘(全引擎免费获得②级数据源)。初始 poolKey 用 pi
162
- // 缺省占位(pi 恒 'shared');非池化稳定引擎(zcode)在 prepare 期经
163
- // RunContext.onPoolResolved 声明实际池 key → writer.retarget——保证 journal 落盘
164
- // 路径与 handle.poolKey 同源(handle.journalPath 由本方法 run 返回后回填)。
165
- //
166
- // taskId 为宿主侧任务标识(journal 文件名与池引用计数 key)——executeAndAwait
167
- // 不外露内部 record id(取真实 id 需 hook record store 且改 createRecordForMode
168
- // 签名,影响面大;P4 决策:保留占位,`sa-` 前缀与 record id 同构。影响面:record
169
- // GC 时无法按 taskId 联动删 journal(journal 依赖 30 天 TTL 自然回收),read ②级
170
- // 经 handle.journalPath 自描述定位不受影响)。
171
- const taskId = `sa-${crypto.randomUUID()}`;
172
- const journal = new JournalWriter({
173
- path: resolveJournalPath(getEngineDataDir(), route.engineId, PI_POOL_KEY, taskId),
174
- taskId,
175
- engineId: route.engineId,
176
- });
177
- const retargetJournal = (poolKey: string): void => {
178
- journal.retarget(resolveJournalPath(getEngineDataDir(), route.engineId, poolKey, taskId));
179
- };
180
- // 包装:先写 journal 再转发原 onEvent(原 onEvent 未传时也恒传包装版——
181
- // 下游 onEvent 通道是事件生成后的纯转发,无行为分支,仅多一次入队)
182
- const journalingOnEvent = (event: AgentEvent): void => {
183
- journal.append(event);
184
- onEvent?.(event);
185
- };
186
-
187
- try {
188
- // ── D-A9: timeoutMs 合并 signal(超时 abort 带 HOST_TIMEOUT_ABORT_REASON 标记)──
189
- const mergedSignal = mergeTimeoutSignal(signal, opts.timeoutMs);
190
-
191
- // ── D-A2 + D-008: AgentCallOpts → ExecuteOptions 映射 ──
192
- const mappedOpts: ExecuteOptions = mapToExecuteOptions(opts, this.ctxModel);
193
-
194
- // ── P1/P4 引擎接线:EnginePort.run ──
195
- const runCtx: RunContext = {
196
- taskId,
197
- poolKey: PI_POOL_KEY,
198
- signal: mergedSignal,
199
- onEvent: journalingOnEvent,
200
- ctxModel: this.ctxModel,
201
- ...(route.engineFallback !== undefined ? { engineFallback: route.engineFallback } : {}),
202
- onPoolResolved: retargetJournal,
203
- // [U0 D10] 终止链路径①:引擎 spawn 的子进程注册进 session-runner 的
204
- // spawnedChildren 记账(dispose killAll 收割兜底对 workflow 域引擎任务生效);
205
- // taskId('sa-' 前缀)即记账 key,与 chat 域 kickOffEngineRun 的 record.id 同构
206
- onChildSpawned: (child) => registerSpawnedChildForRecord(taskId, child),
207
- ...(stream !== undefined ? { stream } : {}),
208
- // 解耦形态(有 schemaEnv 无 schema)的兜底通道——耦合形态下引擎从 task.schema
209
- // 派生等值,此值被忽略(见 RunContext.schemaEnv 注释)
210
- ...(mappedOpts.schemaEnv !== undefined ? { schemaEnv: mappedOpts.schemaEnv } : {}),
211
- };
212
- const { handle, outcome } = await route.engine.run(
213
- // 泛化为中立声明(PiEngine 内部再还原回 ExecuteOptions——往返保真,
214
- // 由 engines/pi/__tests__/task-spec-mapper.test.ts 逐字段锁定)
215
- executeOptionsToTaskSpec(mappedOpts),
216
- runCtx,
217
- );
218
- // handle.journalPath 回填(§3.3.6:read ②级的自描述定位符——运行期落盘路径
219
- // 权威在 writer,handle 记录最终路径供跨重启 read 消费)
220
- backfillJournalPath(handle, journal.path);
221
- return outcomeToRunnerResult(outcome);
222
- } catch (err) {
223
- // executeAndAwait throw(嵌套超限 ForkDepthExceededError,BC-12)或未预期异常 → 不 reject,入 error。
224
- const message = err instanceof Error ? err.message : String(err);
225
- return {
226
- content: "",
227
- durationMs: Date.now() - startedAt,
228
- error: message,
229
- toolCalls: [],
230
- };
231
- } finally {
232
- // run 终态后 flush + fsync 一次(§3.3.6 写入纪律);写失败已由 writer 内部
233
- // warn + failed 收口,close 不抛(journal 是②级尽力而为数据源)
234
- await journal.close();
235
- }
236
- }
237
-
238
- // ── 内部 ──
239
-
240
- /**
241
- * 引擎获取:pi 走 per-session DI 绑定(mock 语义 + 生产同单例,P1 行为零变化);
242
- * 非 pi 经 registry.getEngine 动态获取(P4:引擎身份归属注册表,未注册 id 抛
243
- * EngineNotFoundError——路由期已前置校验,这里是防御性兜底)。
244
- */
245
- private engineFor(engineId: string): EnginePort {
246
- if (engineId === "pi") return this.piEngine;
247
- return getEngine(engineId);
248
- }
249
-
250
- /**
251
- * 三层路由输入装配(D9):调用参数(opts.engine,workflow step 级透传)> agent
252
- * frontmatter(ModelConfigService.getAgentConfig——loadByPath mtime 缓存,幂等)>
253
- * 全局默认(config.json defaultEngine)。单例未就绪(session_start 前/测试 mock)
254
- * 时各层缺省——落内置 'pi'。
255
- */
256
- private buildRoutingInput(opts: AgentCallOpts): EngineRoutingInput {
257
- const service = getModelConfigService();
258
- const agentEngine =
259
- opts.agent !== undefined && opts.agent !== "" ? service?.getAgentConfig(opts.agent)?.engine : undefined;
260
- const globalDefault = service?.getGlobalConfig().defaultEngine;
261
- return {
262
- ...(opts.engine !== undefined && opts.engine !== "" ? { callEngine: opts.engine } : {}),
263
- ...(agentEngine !== undefined && agentEngine !== "" ? { agentEngine } : {}),
264
- ...(globalDefault !== undefined && globalDefault !== "" ? { globalDefaultEngine: globalDefault } : {}),
265
- };
266
- }
267
- }
268
-
269
- /** 路由期错误 → AgentResult.error(错误码前缀格式保留——engine_not_found 等)。 */
270
- function errorResult(err: unknown, startedAt: number): AgentResult {
271
- return {
272
- content: "",
273
- durationMs: Date.now() - startedAt,
274
- error: err instanceof Error ? err.message : String(err),
275
- toolCalls: [],
276
- };
277
- }
278
-
279
- /** handle.journalPath 回填(一次写者:SAR 是 handle 的首个消费者)。 */
280
- function backfillJournalPath(handle: EngineHandle, journalPath: string): void {
281
- handle.data.journalPath = journalPath;
282
- }
283
-
284
- /**
285
- * AgentOutcome → workflow AgentResult:剥离引擎层新增字段(engineId/engineFallback/
286
- * exitCode——engineFallback 经 record(pi 路径)/outcome(zcode 路径)留痕,GUI 投影
287
- * 通道在后续 wave 接线,workflow 引擎不消费)。其余字段由 PiEngine 从 executeAndAwait
288
- * 的返回值逐字段映射而来,字段全集完整性由 pi-engine 单测锁定(缺字段会在该处转红,
289
- * 不会静默丢失)。
290
- */
291
- function outcomeToRunnerResult(outcome: AgentOutcome): AgentResult {
292
- return {
293
- content: outcome.content,
294
- parsedOutput: outcome.parsedOutput,
295
- usage: outcome.usage,
296
- durationMs: outcome.durationMs,
297
- error: outcome.error,
298
- sessionId: outcome.sessionId,
299
- sessionFile: outcome.sessionFile,
300
- worktreePath: outcome.worktreePath,
301
- toolCalls: outcome.toolCalls,
302
- };
303
- }
@@ -1,62 +0,0 @@
1
- // src/core/temp-prompt.ts
2
- //
3
- // 将 agent systemPrompt 写入临时文件,供 pi CLI --append-system-prompt 使用。
4
- // Core 叶子原语(node 内置 + 同目录 bestEffort 清理 helper)。注意 bestEffort
5
- // 经 extension-logger 有到 pi 的传递依赖(仅日志通路,无 pi 运行时调用)。
6
- //
7
- // pi CLI 的 --append-system-prompt 接受文件路径(非内联字符串),故 spawn 前
8
- // 需把 systemPrompt 落盘。每次调用创建唯一临时目录,用完由 runSpawn 清理。
9
- //
10
- // 移植自 nicobailon subagent example,去掉 withFileMutationQueue(目录已唯一,
11
- // 无并发写入风险,queue 冗余)。
12
-
13
- import * as fs from "node:fs";
14
- import * as os from "node:os";
15
- import * as path from "node:path";
16
-
17
- import { bestEffort } from "./best-effort.ts";
18
-
19
- /** 临时 prompt 文件创建结果。dir 供调用方清理。 */
20
- export interface TempPromptFile {
21
- /** 临时目录绝对路径(mkdtemp 创建,调用方负责删除)。 */
22
- dir: string;
23
- /** prompt 文件绝对路径(dir 下)。 */
24
- filePath: string;
25
- }
26
-
27
- /**
28
- * 将 systemPrompt 写入临时文件。
29
- *
30
- * @param agentName agent 名称(用于文件名,非法字符替换为 _)
31
- * @param prompt systemPrompt 全文
32
- * @returns 临时文件信息(dir + filePath)
33
- *
34
- * 安全:文件权限 0o600(仅 owner 读写),防止其他用户读取 prompt 内容。
35
- * 目录用 mkdtemp 保证唯一,无需额外锁。
36
- */
37
- export async function writePromptToTempFile(
38
- agentName: string,
39
- prompt: string,
40
- ): Promise<TempPromptFile> {
41
- const dir = await fs.promises.mkdtemp(path.join(os.tmpdir(), "pi-subagent-"));
42
- const safeName = agentName.replace(/[^\w.-]+/g, "_");
43
- const filePath = path.join(dir, `prompt-${safeName}.md`);
44
- await fs.promises.writeFile(filePath, prompt, { encoding: "utf-8", mode: 0o600 });
45
- return { dir, filePath };
46
- }
47
-
48
- /**
49
- * 删除临时 prompt 目录(含文件)。best-effort,失败不抛。
50
- *
51
- * runSpawn 的 finally 调用,确保临时文件不泄漏。子进程可能仍持有文件句柄
52
- * (--append-system-prompt 读取后即释放),rm 用 recursive 容错。
53
- */
54
- export async function cleanupTempPrompt(file: TempPromptFile): Promise<void> {
55
- try {
56
- await fs.promises.rm(file.dir, { recursive: true, force: true });
57
- } catch (err) {
58
- // best-effort:临时文件泄漏不影响功能,OS tmpdir 清理机制兜底;失败经
59
- // bestEffort 记 debug 日志(对齐 idle-gc / finalize-record 的清理惯例)
60
- bestEffort(err, `cleanup temp prompt dir ${file.dir}`);
61
- }
62
- }
@@ -1,72 +0,0 @@
1
- // src/runtime/execution/tombstone-store.ts
2
- //
3
- // Cancelled 状态的 sidecar 持久化。
4
- //
5
- // 背景:用户 cancel background subagent 时 session.abort() → prompt() reject →
6
- // session.jsonl 被中途截断(无最终 assistant message,无 stopReason 标记)。所以
7
- // cancelled 状态无法从 session.jsonl 可靠检测。本模块在 session.jsonl 旁写一个
8
- // `.cancelled` sidecar 文件(单行 JSON),collectRecords 重建时读它 override status。
9
- //
10
- // 设计:单条 cancelled = 单 sidecar,无全局 index 可损坏,无并发问题,被现有
11
- // session-file-gc 的目录扫描自然清理(GC 已扩展为也清理 .cancelled)。YAGNI 更重方案。
12
-
13
- import * as fs from "node:fs";
14
-
15
- // ============================================================
16
- // 类型
17
- // ============================================================
18
-
19
- /** Tombstone 内容(单行 JSON)。 */
20
- export interface CancelledTombstone {
21
- id: string;
22
- status: "cancelled";
23
- agent: string;
24
- startedAt: number;
25
- endedAt: number;
26
- }
27
-
28
- // ============================================================
29
- // 公开函数
30
- // ============================================================
31
-
32
- /**
33
- * 在 session.jsonl 旁写 cancelled tombstone。
34
- * best-effort:任何 I/O 错误静默(cancel 已成功,持久化是次要的——内存 record 即将被
35
- * archive 淘汰,下次读靠 tombstone 标记 cancelled)。
36
- */
37
- export function writeCancelledTombstone(sessionFile: string, meta: CancelledTombstone): void {
38
- try {
39
- const tombstonePath = `${sessionFile}.cancelled`;
40
- fs.writeFileSync(tombstonePath, `${JSON.stringify(meta)}\n`, "utf-8");
41
- } catch (_e) {
42
- void _e; // 静默:写失败不阻断 cancel 主流程(status 已在内存 record 上设好)。
43
- }
44
- }
45
-
46
- /**
47
- * 读 session.jsonl 旁的 cancelled tombstone。
48
- * 返回 undefined:sidecar 不存在 / 损坏 / 解析失败。
49
- */
50
- export function readCancelledTombstone(sessionFile: string): CancelledTombstone | undefined {
51
- let raw: string;
52
- try {
53
- raw = fs.readFileSync(`${sessionFile}.cancelled`, "utf-8");
54
- } catch {
55
- return undefined; // sidecar 不存在(正常——非 cancelled record 无 sidecar)。
56
- }
57
- try {
58
- const parsed = JSON.parse(raw) as Partial<CancelledTombstone>;
59
- if (
60
- typeof parsed.id === "string" &&
61
- parsed.status === "cancelled" &&
62
- typeof parsed.agent === "string" &&
63
- typeof parsed.startedAt === "number" &&
64
- typeof parsed.endedAt === "number"
65
- ) {
66
- return parsed as CancelledTombstone;
67
- }
68
- return undefined; // 结构不合法 → 降级。
69
- } catch {
70
- return undefined; // JSON 损坏 → 降级。
71
- }
72
- }
@@ -1,102 +0,0 @@
1
- // src/core/turn-limiter.ts
2
- //
3
- // soft/hard turn 限制器。maxTurns 到达 → steer 提醒收尾;
4
- // graceTurns 后仍不结束 → abort。
5
-
6
- /** steer 提醒消息:要求 agent 总结已完成/未完成/下一步,不得谎报完成。 */
7
- const WRAP_UP_MESSAGE = [
8
- "You have reached your turn limit. Wrap up now:",
9
- "1. Summarize what you have completed (with evidence: file paths, command output).",
10
- "2. List what remains undone and why.",
11
- "3. State the single most important next step for whoever continues.",
12
- "Do NOT claim the task is complete if any part remains unfinished.",
13
- ].join(" ");
14
-
15
- /**
16
- * 预防性 wrap-up 提示(启动时注入 --append-system-prompt)。
17
- *
18
- * spawn 模式下 runSpawn 无法在达 maxTurns 时运行时注入 steer(pi `--mode json` 是
19
- * single-shot,无 stdin 命令通道;见 session-runner.ts limiter 注释)。作为短期补偿,
20
- * 在启动时预置此预防性指令,让 agent 在感知接近上限时主动收尾。
21
- *
22
- * 长期方案是切到 pi `--mode rpc`(支持运行时 steer 命令),见 follow-up。
23
- */
24
- export const WRAP_UP_HINT = [
25
- `You have a turn limit. As you sense you are approaching it, proactively wrap up:`,
26
- "1. Summarize what you have completed (with evidence: file paths, command output).",
27
- "2. List what remains undone and why.",
28
- "3. State the single most important next step for whoever continues.",
29
- "Do NOT claim the task is complete if any part remains unfinished.",
30
- ].join(" ");
31
-
32
- /** turn limiter 配置。 */
33
- export interface TurnLimiterOptions {
34
- maxTurns: number;
35
- graceTurns: number;
36
- steer: (msg: string) => void;
37
- abort: () => void;
38
- }
39
-
40
- /**
41
- * soft/hard turn 限制。
42
- *
43
- * onTurnEnd(currentTurns):
44
- * 已 aborted 或 maxTurns<=0(禁用)→ 直接 return
45
- * currentTurns >= maxTurns 且未 steer → steer(WRAP_UP_MESSAGE)(仅一次)
46
- * 已 steer 且 currentTurns >= maxTurns + graceTurns → abort()(仅一次)
47
- *
48
- * maxTurns<=0 表示不限(limit=Infinity,永不触发)。
49
- * graceTurns<=0 时 steer 后下一 turn 即 abort。
50
- */
51
- export interface TurnLimiter {
52
- /** 每次 turn_end 调用。 */
53
- onTurnEnd(currentTurns: number): void;
54
- /**
55
- * 重置 steered/aborted 标志(新一轮开始)。
56
- *
57
- * chatMode 下 agent_settled 时调用——每轮(message → agent_settled)独立计数,
58
- * maxTurns 不跨轮累计(续聊本质是无限轮,累计上限违背 G1)。
59
- * 非 chatMode 不调用,行为不变(全程累计)。
60
- */
61
- reset(): void;
62
- /** 是否已发过 steer(诊断用)。 */
63
- readonly didSteer: boolean;
64
- /** 是否已 abort(诊断用)。 */
65
- readonly didAbort: boolean;
66
- }
67
-
68
- /** 工厂函数。 */
69
- export function createTurnLimiter(opts: TurnLimiterOptions): TurnLimiter {
70
- let steered = false;
71
- let aborted = false;
72
- const limit = opts.maxTurns > 0 ? opts.maxTurns : Infinity;
73
- const grace = opts.graceTurns > 0 ? opts.graceTurns : 0;
74
-
75
- const onTurnEnd = (turn: number): void => {
76
- if (aborted || !Number.isFinite(limit)) return;
77
- if (!steered && turn >= limit) {
78
- steered = true;
79
- opts.steer(WRAP_UP_MESSAGE);
80
- }
81
- if (steered && turn >= limit + grace) {
82
- aborted = true;
83
- opts.abort();
84
- }
85
- };
86
-
87
- const reset = (): void => {
88
- steered = false;
89
- aborted = false;
90
- };
91
-
92
- return {
93
- onTurnEnd,
94
- reset,
95
- get didSteer(): boolean {
96
- return steered;
97
- },
98
- get didAbort(): boolean {
99
- return aborted;
100
- },
101
- };
102
- }