@caupulican/pi-adaptative 0.81.38 → 0.81.40

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 (881) hide show
  1. package/CHANGELOG.md +131 -0
  2. package/README.md +2 -0
  3. package/dist/bundled-resources/extensions/tmux-agent-manager/README.md +18 -1
  4. package/dist/bundled-resources/extensions/tmux-agent-manager/dispatch-grant.d.ts +133 -0
  5. package/dist/bundled-resources/extensions/tmux-agent-manager/dispatch-grant.d.ts.map +1 -0
  6. package/dist/bundled-resources/extensions/tmux-agent-manager/dispatch-grant.js +198 -0
  7. package/dist/bundled-resources/extensions/tmux-agent-manager/dispatch-grant.js.map +1 -0
  8. package/dist/bundled-resources/extensions/tmux-agent-manager/dispatch-grant.ts +311 -0
  9. package/dist/bundled-resources/extensions/tmux-agent-manager/index.d.ts +31 -2
  10. package/dist/bundled-resources/extensions/tmux-agent-manager/index.d.ts.map +1 -1
  11. package/dist/bundled-resources/extensions/tmux-agent-manager/index.js +823 -79
  12. package/dist/bundled-resources/extensions/tmux-agent-manager/index.js.map +1 -1
  13. package/dist/bundled-resources/extensions/tmux-agent-manager/index.ts +1043 -86
  14. package/dist/bundled-resources/runtimes/pi-shell-engine/commands/__init__.py +43 -0
  15. package/dist/bundled-resources/runtimes/pi-shell-engine/commands/fs.py +270 -0
  16. package/dist/bundled-resources/runtimes/pi-shell-engine/commands/search.py +252 -0
  17. package/dist/bundled-resources/runtimes/pi-shell-engine/commands/strings.py +399 -0
  18. package/dist/bundled-resources/runtimes/pi-shell-engine/commands/text.py +575 -0
  19. package/dist/bundled-resources/runtimes/pi-shell-engine/context.py +52 -0
  20. package/dist/bundled-resources/runtimes/pi-shell-engine/errors.py +49 -0
  21. package/dist/bundled-resources/runtimes/pi-shell-engine/exec.py +734 -0
  22. package/dist/bundled-resources/runtimes/pi-shell-engine/expand.py +238 -0
  23. package/dist/bundled-resources/runtimes/pi-shell-engine/main.py +132 -0
  24. package/dist/bundled-resources/runtimes/pi-shell-engine/nodes.py +116 -0
  25. package/dist/bundled-resources/runtimes/pi-shell-engine/parser.py +287 -0
  26. package/dist/bundled-resources/runtimes/pi-shell-engine/proc.py +137 -0
  27. package/dist/bundled-resources/runtimes/pi-shell-engine/state.py +100 -0
  28. package/dist/bundled-resources/runtimes/pi-shell-engine/tokens.py +579 -0
  29. package/dist/bundled-resources/skills/tool-call-repair/SKILL.md +19 -9
  30. package/dist/bundled-resources/skills/tool-call-repair/references/failure-grammar.md +22 -5
  31. package/dist/bundled-resources/skills/tool-call-repair/references/repair-catalogue.md +7 -7
  32. package/dist/bundled-resources/skills/tool-call-repair/references/text-protocol-grammar.md +28 -7
  33. package/dist/cli/args.d.ts +5 -0
  34. package/dist/cli/args.d.ts.map +1 -1
  35. package/dist/cli/args.js +24 -0
  36. package/dist/cli/args.js.map +1 -1
  37. package/dist/core/agent-directory-layout.d.ts +15 -0
  38. package/dist/core/agent-directory-layout.d.ts.map +1 -0
  39. package/dist/core/agent-directory-layout.js +72 -0
  40. package/dist/core/agent-directory-layout.js.map +1 -0
  41. package/dist/core/agent-paths.d.ts +66 -0
  42. package/dist/core/agent-paths.d.ts.map +1 -0
  43. package/dist/core/agent-paths.js +170 -0
  44. package/dist/core/agent-paths.js.map +1 -0
  45. package/dist/core/agent-session-runtime.d.ts +52 -8
  46. package/dist/core/agent-session-runtime.d.ts.map +1 -1
  47. package/dist/core/agent-session-runtime.js +397 -79
  48. package/dist/core/agent-session-runtime.js.map +1 -1
  49. package/dist/core/agent-session-services.d.ts +1 -0
  50. package/dist/core/agent-session-services.d.ts.map +1 -1
  51. package/dist/core/agent-session-services.js +4 -3
  52. package/dist/core/agent-session-services.js.map +1 -1
  53. package/dist/core/agent-session.d.ts +255 -103
  54. package/dist/core/agent-session.d.ts.map +1 -1
  55. package/dist/core/agent-session.js +754 -1173
  56. package/dist/core/agent-session.js.map +1 -1
  57. package/dist/core/autonomy/approval-gate.d.ts +3 -2
  58. package/dist/core/autonomy/approval-gate.d.ts.map +1 -1
  59. package/dist/core/autonomy/approval-gate.js +6 -28
  60. package/dist/core/autonomy/approval-gate.js.map +1 -1
  61. package/dist/core/autonomy/bounded-completion.d.ts +1 -1
  62. package/dist/core/autonomy/bounded-completion.d.ts.map +1 -1
  63. package/dist/core/autonomy/bounded-completion.js +1 -1
  64. package/dist/core/autonomy/bounded-completion.js.map +1 -1
  65. package/dist/core/autonomy/contracts.d.ts +26 -9
  66. package/dist/core/autonomy/contracts.d.ts.map +1 -1
  67. package/dist/core/autonomy/contracts.js.map +1 -1
  68. package/dist/core/autonomy/foreground-envelope.d.ts +8 -2
  69. package/dist/core/autonomy/foreground-envelope.d.ts.map +1 -1
  70. package/dist/core/autonomy/foreground-envelope.js +8 -25
  71. package/dist/core/autonomy/foreground-envelope.js.map +1 -1
  72. package/dist/core/autonomy/gates.d.ts.map +1 -1
  73. package/dist/core/autonomy/gates.js +8 -10
  74. package/dist/core/autonomy/gates.js.map +1 -1
  75. package/dist/core/autonomy/lane-private-paths.d.ts +2 -0
  76. package/dist/core/autonomy/lane-private-paths.d.ts.map +1 -0
  77. package/dist/core/autonomy/lane-private-paths.js +16 -0
  78. package/dist/core/autonomy/lane-private-paths.js.map +1 -0
  79. package/dist/core/autonomy/lane-tool-surface.d.ts +10 -0
  80. package/dist/core/autonomy/lane-tool-surface.d.ts.map +1 -1
  81. package/dist/core/autonomy/lane-tool-surface.js +46 -8
  82. package/dist/core/autonomy/lane-tool-surface.js.map +1 -1
  83. package/dist/core/autonomy/lane-tracker.d.ts +24 -1
  84. package/dist/core/autonomy/lane-tracker.d.ts.map +1 -1
  85. package/dist/core/autonomy/lane-tracker.js +43 -1
  86. package/dist/core/autonomy/lane-tracker.js.map +1 -1
  87. package/dist/core/autonomy/risk-assessment.d.ts +1 -2
  88. package/dist/core/autonomy/risk-assessment.d.ts.map +1 -1
  89. package/dist/core/autonomy/risk-assessment.js +1 -123
  90. package/dist/core/autonomy/risk-assessment.js.map +1 -1
  91. package/dist/core/autonomy/session-lane-record.d.ts +4 -4
  92. package/dist/core/autonomy/session-lane-record.d.ts.map +1 -1
  93. package/dist/core/autonomy/session-lane-record.js +16 -29
  94. package/dist/core/autonomy/session-lane-record.js.map +1 -1
  95. package/dist/core/autonomy/telemetry-events.d.ts +1 -1
  96. package/dist/core/autonomy/telemetry-events.d.ts.map +1 -1
  97. package/dist/core/autonomy/telemetry-events.js +1 -1
  98. package/dist/core/autonomy/telemetry-events.js.map +1 -1
  99. package/dist/core/autonomy-telemetry.d.ts +7 -7
  100. package/dist/core/autonomy-telemetry.d.ts.map +1 -1
  101. package/dist/core/autonomy-telemetry.js +9 -9
  102. package/dist/core/autonomy-telemetry.js.map +1 -1
  103. package/dist/core/background-lane-controller.d.ts +90 -156
  104. package/dist/core/background-lane-controller.d.ts.map +1 -1
  105. package/dist/core/background-lane-controller.js +192 -968
  106. package/dist/core/background-lane-controller.js.map +1 -1
  107. package/dist/core/bash-execution-controller.d.ts +4 -0
  108. package/dist/core/bash-execution-controller.d.ts.map +1 -1
  109. package/dist/core/bash-execution-controller.js +7 -1
  110. package/dist/core/bash-execution-controller.js.map +1 -1
  111. package/dist/core/capability-contract.d.ts +4 -0
  112. package/dist/core/capability-contract.d.ts.map +1 -0
  113. package/dist/core/capability-contract.js +28 -0
  114. package/dist/core/capability-contract.js.map +1 -0
  115. package/dist/core/compaction-controller.d.ts +90 -0
  116. package/dist/core/compaction-controller.d.ts.map +1 -0
  117. package/dist/core/compaction-controller.js +452 -0
  118. package/dist/core/compaction-controller.js.map +1 -0
  119. package/dist/core/compaction-support.d.ts +24 -13
  120. package/dist/core/compaction-support.d.ts.map +1 -1
  121. package/dist/core/compaction-support.js +43 -7
  122. package/dist/core/compaction-support.js.map +1 -1
  123. package/dist/core/context/context-artifacts.d.ts +6 -2
  124. package/dist/core/context/context-artifacts.d.ts.map +1 -1
  125. package/dist/core/context/context-artifacts.js +34 -2
  126. package/dist/core/context/context-artifacts.js.map +1 -1
  127. package/dist/core/context/context-audit.d.ts +33 -1
  128. package/dist/core/context/context-audit.d.ts.map +1 -1
  129. package/dist/core/context/context-audit.js +31 -5
  130. package/dist/core/context/context-audit.js.map +1 -1
  131. package/dist/core/context/context-store-retention.d.ts +8 -2
  132. package/dist/core/context/context-store-retention.d.ts.map +1 -1
  133. package/dist/core/context/context-store-retention.js +158 -35
  134. package/dist/core/context/context-store-retention.js.map +1 -1
  135. package/dist/core/context/okf-memory.d.ts.map +1 -1
  136. package/dist/core/context/okf-memory.js +9 -11
  137. package/dist/core/context/okf-memory.js.map +1 -1
  138. package/dist/core/context/sqlite-runtime-index.d.ts.map +1 -1
  139. package/dist/core/context/sqlite-runtime-index.js +6 -8
  140. package/dist/core/context/sqlite-runtime-index.js.map +1 -1
  141. package/dist/core/context-gc.d.ts +3 -0
  142. package/dist/core/context-gc.d.ts.map +1 -1
  143. package/dist/core/context-gc.js +26 -6
  144. package/dist/core/context-gc.js.map +1 -1
  145. package/dist/core/context-pipeline.d.ts +26 -4
  146. package/dist/core/context-pipeline.d.ts.map +1 -1
  147. package/dist/core/context-pipeline.js +146 -18
  148. package/dist/core/context-pipeline.js.map +1 -1
  149. package/dist/core/cost-guard.d.ts +19 -3
  150. package/dist/core/cost-guard.d.ts.map +1 -1
  151. package/dist/core/cost-guard.js +18 -3
  152. package/dist/core/cost-guard.js.map +1 -1
  153. package/dist/core/default-tool-surface.d.ts.map +1 -1
  154. package/dist/core/default-tool-surface.js +1 -0
  155. package/dist/core/default-tool-surface.js.map +1 -1
  156. package/dist/core/delegation/managed-lane-controller.d.ts +34 -0
  157. package/dist/core/delegation/managed-lane-controller.d.ts.map +1 -0
  158. package/dist/core/delegation/managed-lane-controller.js +217 -0
  159. package/dist/core/delegation/managed-lane-controller.js.map +1 -0
  160. package/dist/core/delegation/session-worker-claim.d.ts +44 -0
  161. package/dist/core/delegation/session-worker-claim.d.ts.map +1 -0
  162. package/dist/core/delegation/session-worker-claim.js +98 -0
  163. package/dist/core/delegation/session-worker-claim.js.map +1 -0
  164. package/dist/core/delegation/worker-actions.d.ts +7 -5
  165. package/dist/core/delegation/worker-actions.d.ts.map +1 -1
  166. package/dist/core/delegation/worker-actions.js +20 -4
  167. package/dist/core/delegation/worker-actions.js.map +1 -1
  168. package/dist/core/delegation/worker-claim.d.ts +56 -0
  169. package/dist/core/delegation/worker-claim.d.ts.map +1 -0
  170. package/dist/core/delegation/worker-claim.js +239 -0
  171. package/dist/core/delegation/worker-claim.js.map +1 -0
  172. package/dist/core/delegation/worker-delegation-controller.d.ts +110 -0
  173. package/dist/core/delegation/worker-delegation-controller.d.ts.map +1 -0
  174. package/dist/core/delegation/worker-delegation-controller.js +861 -0
  175. package/dist/core/delegation/worker-delegation-controller.js.map +1 -0
  176. package/dist/core/delegation/worker-delegation-request.d.ts +11 -0
  177. package/dist/core/delegation/worker-delegation-request.d.ts.map +1 -0
  178. package/dist/core/delegation/worker-delegation-request.js +2 -0
  179. package/dist/core/delegation/worker-delegation-request.js.map +1 -0
  180. package/dist/core/delegation/worker-dispatch-scheduler.d.ts +40 -0
  181. package/dist/core/delegation/worker-dispatch-scheduler.d.ts.map +1 -0
  182. package/dist/core/delegation/worker-dispatch-scheduler.js +93 -0
  183. package/dist/core/delegation/worker-dispatch-scheduler.js.map +1 -0
  184. package/dist/core/delegation/worker-execution-policy.d.ts +62 -0
  185. package/dist/core/delegation/worker-execution-policy.d.ts.map +1 -0
  186. package/dist/core/delegation/worker-execution-policy.js +160 -0
  187. package/dist/core/delegation/worker-execution-policy.js.map +1 -0
  188. package/dist/core/delegation/worker-lane-projection.d.ts +14 -0
  189. package/dist/core/delegation/worker-lane-projection.d.ts.map +1 -0
  190. package/dist/core/delegation/worker-lane-projection.js +100 -0
  191. package/dist/core/delegation/worker-lane-projection.js.map +1 -0
  192. package/dist/core/delegation/worker-lifecycle.d.ts +97 -0
  193. package/dist/core/delegation/worker-lifecycle.d.ts.map +1 -0
  194. package/dist/core/delegation/worker-lifecycle.js +339 -0
  195. package/dist/core/delegation/worker-lifecycle.js.map +1 -0
  196. package/dist/core/delegation/worker-notification-coordinator.d.ts +36 -0
  197. package/dist/core/delegation/worker-notification-coordinator.d.ts.map +1 -0
  198. package/dist/core/delegation/worker-notification-coordinator.js +90 -0
  199. package/dist/core/delegation/worker-notification-coordinator.js.map +1 -0
  200. package/dist/core/delegation/worker-profile-resolver.d.ts +55 -0
  201. package/dist/core/delegation/worker-profile-resolver.d.ts.map +1 -0
  202. package/dist/core/delegation/worker-profile-resolver.js +113 -0
  203. package/dist/core/delegation/worker-profile-resolver.js.map +1 -0
  204. package/dist/core/delegation/worker-runner.d.ts +25 -14
  205. package/dist/core/delegation/worker-runner.d.ts.map +1 -1
  206. package/dist/core/delegation/worker-runner.js +122 -53
  207. package/dist/core/delegation/worker-runner.js.map +1 -1
  208. package/dist/core/delegation/worker-task-label.d.ts +3 -0
  209. package/dist/core/delegation/worker-task-label.d.ts.map +1 -0
  210. package/dist/core/delegation/worker-task-label.js +11 -0
  211. package/dist/core/delegation/worker-task-label.js.map +1 -0
  212. package/dist/core/doctor.d.ts +8 -0
  213. package/dist/core/doctor.d.ts.map +1 -1
  214. package/dist/core/doctor.js +32 -1
  215. package/dist/core/doctor.js.map +1 -1
  216. package/dist/core/extensions/index.d.ts +1 -1
  217. package/dist/core/extensions/index.d.ts.map +1 -1
  218. package/dist/core/extensions/index.js.map +1 -1
  219. package/dist/core/extensions/loader.d.ts +5 -1
  220. package/dist/core/extensions/loader.d.ts.map +1 -1
  221. package/dist/core/extensions/loader.js +68 -13
  222. package/dist/core/extensions/loader.js.map +1 -1
  223. package/dist/core/extensions/runner.d.ts.map +1 -1
  224. package/dist/core/extensions/runner.js +7 -0
  225. package/dist/core/extensions/runner.js.map +1 -1
  226. package/dist/core/extensions/storage.d.ts +8 -0
  227. package/dist/core/extensions/storage.d.ts.map +1 -0
  228. package/dist/core/extensions/storage.js +28 -0
  229. package/dist/core/extensions/storage.js.map +1 -0
  230. package/dist/core/extensions/types.d.ts +101 -1
  231. package/dist/core/extensions/types.d.ts.map +1 -1
  232. package/dist/core/extensions/types.js.map +1 -1
  233. package/dist/core/failure-corpus.d.ts +1 -15
  234. package/dist/core/failure-corpus.d.ts.map +1 -1
  235. package/dist/core/failure-corpus.js +9 -37
  236. package/dist/core/failure-corpus.js.map +1 -1
  237. package/dist/core/foreground-recovery-controller.d.ts +52 -0
  238. package/dist/core/foreground-recovery-controller.d.ts.map +1 -0
  239. package/dist/core/foreground-recovery-controller.js +111 -0
  240. package/dist/core/foreground-recovery-controller.js.map +1 -0
  241. package/dist/core/gateways/channel-provider.d.ts +3 -0
  242. package/dist/core/gateways/channel-provider.d.ts.map +1 -1
  243. package/dist/core/gateways/channel-provider.js +31 -6
  244. package/dist/core/gateways/channel-provider.js.map +1 -1
  245. package/dist/core/goal-loop-controller.d.ts +17 -1
  246. package/dist/core/goal-loop-controller.d.ts.map +1 -1
  247. package/dist/core/goal-loop-controller.js +79 -11
  248. package/dist/core/goal-loop-controller.js.map +1 -1
  249. package/dist/core/goals/goal-acceptance.d.ts +11 -0
  250. package/dist/core/goals/goal-acceptance.d.ts.map +1 -0
  251. package/dist/core/goals/goal-acceptance.js +25 -0
  252. package/dist/core/goals/goal-acceptance.js.map +1 -0
  253. package/dist/core/goals/goal-auto-continue-controller.d.ts +27 -0
  254. package/dist/core/goals/goal-auto-continue-controller.d.ts.map +1 -0
  255. package/dist/core/goals/goal-auto-continue-controller.js +93 -0
  256. package/dist/core/goals/goal-auto-continue-controller.js.map +1 -0
  257. package/dist/core/goals/goal-continuation-controller.d.ts +48 -2
  258. package/dist/core/goals/goal-continuation-controller.d.ts.map +1 -1
  259. package/dist/core/goals/goal-continuation-controller.js +87 -0
  260. package/dist/core/goals/goal-continuation-controller.js.map +1 -1
  261. package/dist/core/goals/goal-continuation-defaults.d.ts +39 -0
  262. package/dist/core/goals/goal-continuation-defaults.d.ts.map +1 -1
  263. package/dist/core/goals/goal-continuation-defaults.js +42 -0
  264. package/dist/core/goals/goal-continuation-defaults.js.map +1 -1
  265. package/dist/core/goals/goal-continuation-prompt.d.ts +5 -1
  266. package/dist/core/goals/goal-continuation-prompt.d.ts.map +1 -1
  267. package/dist/core/goals/goal-continuation-prompt.js +56 -15
  268. package/dist/core/goals/goal-continuation-prompt.js.map +1 -1
  269. package/dist/core/goals/goal-lifecycle.d.ts +20 -0
  270. package/dist/core/goals/goal-lifecycle.d.ts.map +1 -0
  271. package/dist/core/goals/goal-lifecycle.js +17 -0
  272. package/dist/core/goals/goal-lifecycle.js.map +1 -0
  273. package/dist/core/goals/goal-runtime-snapshot.d.ts +105 -4
  274. package/dist/core/goals/goal-runtime-snapshot.d.ts.map +1 -1
  275. package/dist/core/goals/goal-runtime-snapshot.js +91 -6
  276. package/dist/core/goals/goal-runtime-snapshot.js.map +1 -1
  277. package/dist/core/goals/goal-state.d.ts +90 -1
  278. package/dist/core/goals/goal-state.d.ts.map +1 -1
  279. package/dist/core/goals/goal-state.js +78 -15
  280. package/dist/core/goals/goal-state.js.map +1 -1
  281. package/dist/core/goals/goal-tool-core.d.ts +58 -2
  282. package/dist/core/goals/goal-tool-core.d.ts.map +1 -1
  283. package/dist/core/goals/goal-tool-core.js +82 -6
  284. package/dist/core/goals/goal-tool-core.js.map +1 -1
  285. package/dist/core/goals/session-goal-state.d.ts +13 -6
  286. package/dist/core/goals/session-goal-state.d.ts.map +1 -1
  287. package/dist/core/goals/session-goal-state.js +20 -28
  288. package/dist/core/goals/session-goal-state.js.map +1 -1
  289. package/dist/core/human-input.d.ts +100 -0
  290. package/dist/core/human-input.d.ts.map +1 -0
  291. package/dist/core/human-input.js +362 -0
  292. package/dist/core/human-input.js.map +1 -0
  293. package/dist/core/index.d.ts +9 -1
  294. package/dist/core/index.d.ts.map +1 -1
  295. package/dist/core/index.js +9 -1
  296. package/dist/core/index.js.map +1 -1
  297. package/dist/core/{telemetry.d.ts → install-telemetry.d.ts} +1 -1
  298. package/dist/core/install-telemetry.d.ts.map +1 -0
  299. package/dist/core/{telemetry.js → install-telemetry.js} +1 -1
  300. package/dist/core/install-telemetry.js.map +1 -0
  301. package/dist/core/keybindings.d.ts +27 -1
  302. package/dist/core/keybindings.d.ts.map +1 -1
  303. package/dist/core/keybindings.js +34 -8
  304. package/dist/core/keybindings.js.map +1 -1
  305. package/dist/core/learning/learning-audit.d.ts +2 -4
  306. package/dist/core/learning/learning-audit.d.ts.map +1 -1
  307. package/dist/core/learning/learning-audit.js +9 -29
  308. package/dist/core/learning/learning-audit.js.map +1 -1
  309. package/dist/core/learning/learning-gate.d.ts.map +1 -1
  310. package/dist/core/learning/learning-gate.js +1 -6
  311. package/dist/core/learning/learning-gate.js.map +1 -1
  312. package/dist/core/learning/observation-store.d.ts +12 -3
  313. package/dist/core/learning/observation-store.d.ts.map +1 -1
  314. package/dist/core/learning/observation-store.js +30 -15
  315. package/dist/core/learning/observation-store.js.map +1 -1
  316. package/dist/core/learning/session-learning-decision.d.ts +2 -4
  317. package/dist/core/learning/session-learning-decision.d.ts.map +1 -1
  318. package/dist/core/learning/session-learning-decision.js +9 -29
  319. package/dist/core/learning/session-learning-decision.js.map +1 -1
  320. package/dist/core/learning/skill-curator.d.ts +5 -1
  321. package/dist/core/learning/skill-curator.d.ts.map +1 -1
  322. package/dist/core/learning/skill-curator.js +21 -19
  323. package/dist/core/learning/skill-curator.js.map +1 -1
  324. package/dist/core/local-runtime-controller.d.ts +65 -3
  325. package/dist/core/local-runtime-controller.d.ts.map +1 -1
  326. package/dist/core/local-runtime-controller.js +186 -26
  327. package/dist/core/local-runtime-controller.js.map +1 -1
  328. package/dist/core/memory/providers/file-store.d.ts +1 -1
  329. package/dist/core/memory/providers/file-store.d.ts.map +1 -1
  330. package/dist/core/memory/providers/file-store.js +6 -6
  331. package/dist/core/memory/providers/file-store.js.map +1 -1
  332. package/dist/core/memory-controller.d.ts.map +1 -1
  333. package/dist/core/memory-controller.js +4 -4
  334. package/dist/core/memory-controller.js.map +1 -1
  335. package/dist/core/model-capability.d.ts +34 -0
  336. package/dist/core/model-capability.d.ts.map +1 -1
  337. package/dist/core/model-capability.js +43 -1
  338. package/dist/core/model-capability.js.map +1 -1
  339. package/dist/core/model-resolver.d.ts +1 -1
  340. package/dist/core/model-resolver.d.ts.map +1 -1
  341. package/dist/core/model-resolver.js +6 -9
  342. package/dist/core/model-resolver.js.map +1 -1
  343. package/dist/core/model-router/intent-classifier.d.ts +1 -4
  344. package/dist/core/model-router/intent-classifier.d.ts.map +1 -1
  345. package/dist/core/model-router/intent-classifier.js +1 -156
  346. package/dist/core/model-router/intent-classifier.js.map +1 -1
  347. package/dist/core/model-router/tool-escalation.d.ts +15 -0
  348. package/dist/core/model-router/tool-escalation.d.ts.map +1 -1
  349. package/dist/core/model-router/tool-escalation.js +23 -1
  350. package/dist/core/model-router/tool-escalation.js.map +1 -1
  351. package/dist/core/model-router-controller.d.ts +34 -7
  352. package/dist/core/model-router-controller.d.ts.map +1 -1
  353. package/dist/core/model-router-controller.js +95 -16
  354. package/dist/core/model-router-controller.js.map +1 -1
  355. package/dist/core/model-selection-controller.d.ts +4 -4
  356. package/dist/core/model-selection-controller.d.ts.map +1 -1
  357. package/dist/core/model-selection-controller.js.map +1 -1
  358. package/dist/core/model-tool-protocol.d.ts +23 -0
  359. package/dist/core/model-tool-protocol.d.ts.map +1 -0
  360. package/dist/core/model-tool-protocol.js +43 -0
  361. package/dist/core/model-tool-protocol.js.map +1 -0
  362. package/dist/core/models/adaptation-store.d.ts +10 -5
  363. package/dist/core/models/adaptation-store.d.ts.map +1 -1
  364. package/dist/core/models/adaptation-store.js +129 -81
  365. package/dist/core/models/adaptation-store.js.map +1 -1
  366. package/dist/core/models/default-model-suggestions.d.ts.map +1 -1
  367. package/dist/core/models/default-model-suggestions.js +17 -0
  368. package/dist/core/models/default-model-suggestions.js.map +1 -1
  369. package/dist/core/models/fitness-store.d.ts +4 -11
  370. package/dist/core/models/fitness-store.d.ts.map +1 -1
  371. package/dist/core/models/fitness-store.js +87 -51
  372. package/dist/core/models/fitness-store.js.map +1 -1
  373. package/dist/core/models/host-state-store.d.ts +34 -0
  374. package/dist/core/models/host-state-store.d.ts.map +1 -0
  375. package/dist/core/models/host-state-store.js +86 -0
  376. package/dist/core/models/host-state-store.js.map +1 -0
  377. package/dist/core/models/llamacpp-runtime.d.ts +180 -0
  378. package/dist/core/models/llamacpp-runtime.d.ts.map +1 -0
  379. package/dist/core/models/llamacpp-runtime.js +475 -0
  380. package/dist/core/models/llamacpp-runtime.js.map +1 -0
  381. package/dist/core/models/local-registration.d.ts +40 -0
  382. package/dist/core/models/local-registration.d.ts.map +1 -1
  383. package/dist/core/models/local-registration.js +94 -5
  384. package/dist/core/models/local-registration.js.map +1 -1
  385. package/dist/core/models/local-runtime.d.ts.map +1 -1
  386. package/dist/core/models/local-runtime.js +6 -5
  387. package/dist/core/models/local-runtime.js.map +1 -1
  388. package/dist/core/models/model-ref.d.ts +7 -0
  389. package/dist/core/models/model-ref.d.ts.map +1 -1
  390. package/dist/core/models/model-ref.js +26 -0
  391. package/dist/core/models/model-ref.js.map +1 -1
  392. package/dist/core/models/needle-runtime.d.ts +257 -0
  393. package/dist/core/models/needle-runtime.d.ts.map +1 -0
  394. package/dist/core/models/needle-runtime.js +519 -0
  395. package/dist/core/models/needle-runtime.js.map +1 -0
  396. package/dist/core/models/prism-llamacpp-lifecycle.d.ts +89 -0
  397. package/dist/core/models/prism-llamacpp-lifecycle.d.ts.map +1 -0
  398. package/dist/core/models/prism-llamacpp-lifecycle.js +121 -0
  399. package/dist/core/models/prism-llamacpp-lifecycle.js.map +1 -0
  400. package/dist/core/orchestration/agent-resume.d.ts +24 -0
  401. package/dist/core/orchestration/agent-resume.d.ts.map +1 -0
  402. package/dist/core/orchestration/agent-resume.js +90 -0
  403. package/dist/core/orchestration/agent-resume.js.map +1 -0
  404. package/dist/core/orchestration/capability-gateway.d.ts +61 -0
  405. package/dist/core/orchestration/capability-gateway.d.ts.map +1 -0
  406. package/dist/core/orchestration/capability-gateway.js +152 -0
  407. package/dist/core/orchestration/capability-gateway.js.map +1 -0
  408. package/dist/core/orchestration/contracts.d.ts +343 -0
  409. package/dist/core/orchestration/contracts.d.ts.map +1 -0
  410. package/dist/core/orchestration/contracts.js +135 -0
  411. package/dist/core/orchestration/contracts.js.map +1 -0
  412. package/dist/core/orchestration/delegation-ledger.d.ts +56 -0
  413. package/dist/core/orchestration/delegation-ledger.d.ts.map +1 -0
  414. package/dist/core/orchestration/delegation-ledger.js +197 -0
  415. package/dist/core/orchestration/delegation-ledger.js.map +1 -0
  416. package/dist/core/orchestration/event-store.d.ts +83 -0
  417. package/dist/core/orchestration/event-store.d.ts.map +1 -0
  418. package/dist/core/orchestration/event-store.js +560 -0
  419. package/dist/core/orchestration/event-store.js.map +1 -0
  420. package/dist/core/orchestration/lane-tool-manifests.d.ts +9 -0
  421. package/dist/core/orchestration/lane-tool-manifests.d.ts.map +1 -0
  422. package/dist/core/orchestration/lane-tool-manifests.js +37 -0
  423. package/dist/core/orchestration/lane-tool-manifests.js.map +1 -0
  424. package/dist/core/orchestration/model-binding.d.ts +15 -0
  425. package/dist/core/orchestration/model-binding.d.ts.map +1 -0
  426. package/dist/core/orchestration/model-binding.js +29 -0
  427. package/dist/core/orchestration/model-binding.js.map +1 -0
  428. package/dist/core/orchestration/policy-compiler.d.ts +49 -0
  429. package/dist/core/orchestration/policy-compiler.d.ts.map +1 -0
  430. package/dist/core/orchestration/policy-compiler.js +191 -0
  431. package/dist/core/orchestration/policy-compiler.js.map +1 -0
  432. package/dist/core/orchestration/policy-gate.d.ts +18 -0
  433. package/dist/core/orchestration/policy-gate.d.ts.map +1 -0
  434. package/dist/core/orchestration/policy-gate.js +24 -0
  435. package/dist/core/orchestration/policy-gate.js.map +1 -0
  436. package/dist/core/orchestration/profile-registry.d.ts +51 -0
  437. package/dist/core/orchestration/profile-registry.d.ts.map +1 -0
  438. package/dist/core/orchestration/profile-registry.js +393 -0
  439. package/dist/core/orchestration/profile-registry.js.map +1 -0
  440. package/dist/core/orchestration/profile-store.d.ts +31 -0
  441. package/dist/core/orchestration/profile-store.d.ts.map +1 -0
  442. package/dist/core/orchestration/profile-store.js +136 -0
  443. package/dist/core/orchestration/profile-store.js.map +1 -0
  444. package/dist/core/orchestration/risk-budget.d.ts +9 -0
  445. package/dist/core/orchestration/risk-budget.d.ts.map +1 -0
  446. package/dist/core/orchestration/risk-budget.js +48 -0
  447. package/dist/core/orchestration/risk-budget.js.map +1 -0
  448. package/dist/core/orchestration/task-runtime.d.ts +168 -0
  449. package/dist/core/orchestration/task-runtime.d.ts.map +1 -0
  450. package/dist/core/orchestration/task-runtime.js +1600 -0
  451. package/dist/core/orchestration/task-runtime.js.map +1 -0
  452. package/dist/core/orchestration/work-state-projection.d.ts +32 -0
  453. package/dist/core/orchestration/work-state-projection.d.ts.map +1 -0
  454. package/dist/core/orchestration/work-state-projection.js +116 -0
  455. package/dist/core/orchestration/work-state-projection.js.map +1 -0
  456. package/dist/core/orchestration/worker-execution-contract.d.ts +21 -0
  457. package/dist/core/orchestration/worker-execution-contract.d.ts.map +1 -0
  458. package/dist/core/orchestration/worker-execution-contract.js +179 -0
  459. package/dist/core/orchestration/worker-execution-contract.js.map +1 -0
  460. package/dist/core/orchestration/worker-result-adapter.d.ts +21 -0
  461. package/dist/core/orchestration/worker-result-adapter.d.ts.map +1 -0
  462. package/dist/core/orchestration/worker-result-adapter.js +109 -0
  463. package/dist/core/orchestration/worker-result-adapter.js.map +1 -0
  464. package/dist/core/package-manager.d.ts.map +1 -1
  465. package/dist/core/package-manager.js +11 -10
  466. package/dist/core/package-manager.js.map +1 -1
  467. package/dist/core/process-identity.d.ts +11 -0
  468. package/dist/core/process-identity.d.ts.map +1 -0
  469. package/dist/core/process-identity.js +26 -0
  470. package/dist/core/process-identity.js.map +1 -0
  471. package/dist/core/process-matrix/codes.d.ts +83 -0
  472. package/dist/core/process-matrix/codes.d.ts.map +1 -0
  473. package/dist/core/process-matrix/codes.js +15 -0
  474. package/dist/core/process-matrix/codes.js.map +1 -0
  475. package/dist/core/process-matrix/resume-launcher.d.ts +26 -0
  476. package/dist/core/process-matrix/resume-launcher.d.ts.map +1 -0
  477. package/dist/core/process-matrix/resume-launcher.js +62 -0
  478. package/dist/core/process-matrix/resume-launcher.js.map +1 -0
  479. package/dist/core/process-matrix/runtime.d.ts +78 -0
  480. package/dist/core/process-matrix/runtime.d.ts.map +1 -0
  481. package/dist/core/process-matrix/runtime.js +633 -0
  482. package/dist/core/process-matrix/runtime.js.map +1 -0
  483. package/dist/core/process-matrix/store.d.ts +25 -0
  484. package/dist/core/process-matrix/store.d.ts.map +1 -0
  485. package/dist/core/process-matrix/store.js +189 -0
  486. package/dist/core/process-matrix/store.js.map +1 -0
  487. package/dist/core/process-matrix/supervisor.d.ts +75 -0
  488. package/dist/core/process-matrix/supervisor.d.ts.map +1 -0
  489. package/dist/core/process-matrix/supervisor.js +161 -0
  490. package/dist/core/process-matrix/supervisor.js.map +1 -0
  491. package/dist/core/profile-registry.d.ts +7 -0
  492. package/dist/core/profile-registry.d.ts.map +1 -1
  493. package/dist/core/profile-registry.js +25 -7
  494. package/dist/core/profile-registry.js.map +1 -1
  495. package/dist/core/python-runtime.d.ts.map +1 -1
  496. package/dist/core/python-runtime.js +3 -3
  497. package/dist/core/python-runtime.js.map +1 -1
  498. package/dist/core/reflection-controller.d.ts +33 -9
  499. package/dist/core/reflection-controller.d.ts.map +1 -1
  500. package/dist/core/reflection-controller.js +217 -127
  501. package/dist/core/reflection-controller.js.map +1 -1
  502. package/dist/core/reload-blockers.d.ts +36 -0
  503. package/dist/core/reload-blockers.d.ts.map +1 -1
  504. package/dist/core/reload-blockers.js +50 -8
  505. package/dist/core/reload-blockers.js.map +1 -1
  506. package/dist/core/research/evidence-bundle.d.ts.map +1 -1
  507. package/dist/core/research/evidence-bundle.js +1 -6
  508. package/dist/core/research/evidence-bundle.js.map +1 -1
  509. package/dist/core/research/lane-model-resolver.d.ts +33 -0
  510. package/dist/core/research/lane-model-resolver.d.ts.map +1 -0
  511. package/dist/core/research/lane-model-resolver.js +65 -0
  512. package/dist/core/research/lane-model-resolver.js.map +1 -0
  513. package/dist/core/research/model-fitness-controller.d.ts +38 -0
  514. package/dist/core/research/model-fitness-controller.d.ts.map +1 -0
  515. package/dist/core/research/model-fitness-controller.js +106 -0
  516. package/dist/core/research/model-fitness-controller.js.map +1 -0
  517. package/dist/core/research/model-fitness.d.ts +1 -1
  518. package/dist/core/research/model-fitness.d.ts.map +1 -1
  519. package/dist/core/research/model-fitness.js +4 -4
  520. package/dist/core/research/model-fitness.js.map +1 -1
  521. package/dist/core/research/research-gate.d.ts.map +1 -1
  522. package/dist/core/research/research-gate.js +7 -7
  523. package/dist/core/research/research-gate.js.map +1 -1
  524. package/dist/core/research/research-lane-controller.d.ts +62 -0
  525. package/dist/core/research/research-lane-controller.d.ts.map +1 -0
  526. package/dist/core/research/research-lane-controller.js +292 -0
  527. package/dist/core/research/research-lane-controller.js.map +1 -0
  528. package/dist/core/research/session-evidence-bundle.d.ts +2 -4
  529. package/dist/core/research/session-evidence-bundle.d.ts.map +1 -1
  530. package/dist/core/research/session-evidence-bundle.js +10 -46
  531. package/dist/core/research/session-evidence-bundle.js.map +1 -1
  532. package/dist/core/resource-loader.d.ts.map +1 -1
  533. package/dist/core/resource-loader.js +15 -9
  534. package/dist/core/resource-loader.js.map +1 -1
  535. package/dist/core/risk-classifier.d.ts +6 -0
  536. package/dist/core/risk-classifier.d.ts.map +1 -0
  537. package/dist/core/risk-classifier.js +225 -0
  538. package/dist/core/risk-classifier.js.map +1 -0
  539. package/dist/core/runtime-builder.d.ts +76 -17
  540. package/dist/core/runtime-builder.d.ts.map +1 -1
  541. package/dist/core/runtime-builder.js +367 -124
  542. package/dist/core/runtime-builder.js.map +1 -1
  543. package/dist/core/scout-controller.d.ts +6 -0
  544. package/dist/core/scout-controller.d.ts.map +1 -1
  545. package/dist/core/scout-controller.js +66 -52
  546. package/dist/core/scout-controller.js.map +1 -1
  547. package/dist/core/sdk.d.ts +6 -3
  548. package/dist/core/sdk.d.ts.map +1 -1
  549. package/dist/core/sdk.js +64 -27
  550. package/dist/core/sdk.js.map +1 -1
  551. package/dist/core/session-analytics.d.ts.map +1 -1
  552. package/dist/core/session-analytics.js +28 -1
  553. package/dist/core/session-analytics.js.map +1 -1
  554. package/dist/core/session-image-store.d.ts +33 -0
  555. package/dist/core/session-image-store.d.ts.map +1 -0
  556. package/dist/core/session-image-store.js +283 -0
  557. package/dist/core/session-image-store.js.map +1 -0
  558. package/dist/core/session-role.d.ts +33 -0
  559. package/dist/core/session-role.d.ts.map +1 -0
  560. package/dist/core/session-role.js +58 -0
  561. package/dist/core/session-role.js.map +1 -0
  562. package/dist/core/session-snapshot.d.ts +34 -0
  563. package/dist/core/session-snapshot.d.ts.map +1 -0
  564. package/dist/core/session-snapshot.js +68 -0
  565. package/dist/core/session-snapshot.js.map +1 -0
  566. package/dist/core/session-supervision-runtime.d.ts +31 -0
  567. package/dist/core/session-supervision-runtime.d.ts.map +1 -0
  568. package/dist/core/session-supervision-runtime.js +97 -0
  569. package/dist/core/session-supervision-runtime.js.map +1 -0
  570. package/dist/core/settings-manager.d.ts +51 -7
  571. package/dist/core/settings-manager.d.ts.map +1 -1
  572. package/dist/core/settings-manager.js +168 -82
  573. package/dist/core/settings-manager.js.map +1 -1
  574. package/dist/core/system-prompt-builder.d.ts +12 -0
  575. package/dist/core/system-prompt-builder.d.ts.map +1 -1
  576. package/dist/core/system-prompt-builder.js +6 -0
  577. package/dist/core/system-prompt-builder.js.map +1 -1
  578. package/dist/core/system-prompt.d.ts +14 -1
  579. package/dist/core/system-prompt.d.ts.map +1 -1
  580. package/dist/core/system-prompt.js +20 -3
  581. package/dist/core/system-prompt.js.map +1 -1
  582. package/dist/core/tasks/session-task-state.d.ts +13 -6
  583. package/dist/core/tasks/session-task-state.d.ts.map +1 -1
  584. package/dist/core/tasks/session-task-state.js +20 -22
  585. package/dist/core/tasks/session-task-state.js.map +1 -1
  586. package/dist/core/tasks/task-contract-monitor.d.ts +45 -0
  587. package/dist/core/tasks/task-contract-monitor.d.ts.map +1 -0
  588. package/dist/core/tasks/task-contract-monitor.js +56 -0
  589. package/dist/core/tasks/task-contract-monitor.js.map +1 -0
  590. package/dist/core/tasks/task-projection.d.ts +20 -0
  591. package/dist/core/tasks/task-projection.d.ts.map +1 -0
  592. package/dist/core/tasks/task-projection.js +47 -0
  593. package/dist/core/tasks/task-projection.js.map +1 -0
  594. package/dist/core/tasks/task-state.d.ts +12 -0
  595. package/dist/core/tasks/task-state.d.ts.map +1 -1
  596. package/dist/core/tasks/task-state.js +56 -12
  597. package/dist/core/tasks/task-state.js.map +1 -1
  598. package/dist/core/tool-capability-policy.d.ts +13 -0
  599. package/dist/core/tool-capability-policy.d.ts.map +1 -0
  600. package/dist/core/tool-capability-policy.js +85 -0
  601. package/dist/core/tool-capability-policy.js.map +1 -0
  602. package/dist/core/tool-gate-controller.d.ts.map +1 -1
  603. package/dist/core/tool-gate-controller.js +5 -0
  604. package/dist/core/tool-gate-controller.js.map +1 -1
  605. package/dist/core/tool-protocol-controller.d.ts +91 -0
  606. package/dist/core/tool-protocol-controller.d.ts.map +1 -0
  607. package/dist/core/tool-protocol-controller.js +512 -0
  608. package/dist/core/tool-protocol-controller.js.map +1 -0
  609. package/dist/core/tool-recovery-log-records.d.ts +6 -0
  610. package/dist/core/tool-recovery-log-records.d.ts.map +1 -1
  611. package/dist/core/tool-recovery-log-records.js +13 -31
  612. package/dist/core/tool-recovery-log-records.js.map +1 -1
  613. package/dist/core/tool-selection/promotion.d.ts +54 -0
  614. package/dist/core/tool-selection/promotion.d.ts.map +1 -0
  615. package/dist/core/tool-selection/promotion.js +81 -0
  616. package/dist/core/tool-selection/promotion.js.map +1 -0
  617. package/dist/core/tool-selection/tool-performance-store.d.ts +39 -6
  618. package/dist/core/tool-selection/tool-performance-store.d.ts.map +1 -1
  619. package/dist/core/tool-selection/tool-performance-store.js +153 -110
  620. package/dist/core/tool-selection/tool-performance-store.js.map +1 -1
  621. package/dist/core/tool-selection/tool-selection-controller.d.ts +45 -0
  622. package/dist/core/tool-selection/tool-selection-controller.d.ts.map +1 -1
  623. package/dist/core/tool-selection/tool-selection-controller.js +96 -0
  624. package/dist/core/tool-selection/tool-selection-controller.js.map +1 -1
  625. package/dist/core/tools/ask-question.d.ts +124 -0
  626. package/dist/core/tools/ask-question.d.ts.map +1 -0
  627. package/dist/core/tools/ask-question.js +693 -0
  628. package/dist/core/tools/ask-question.js.map +1 -0
  629. package/dist/core/tools/bash.d.ts +18 -0
  630. package/dist/core/tools/bash.d.ts.map +1 -1
  631. package/dist/core/tools/bash.js +95 -16
  632. package/dist/core/tools/bash.js.map +1 -1
  633. package/dist/core/tools/delegate-status.d.ts +44 -2
  634. package/dist/core/tools/delegate-status.d.ts.map +1 -1
  635. package/dist/core/tools/delegate-status.js +214 -19
  636. package/dist/core/tools/delegate-status.js.map +1 -1
  637. package/dist/core/tools/delegate.d.ts +15 -13
  638. package/dist/core/tools/delegate.d.ts.map +1 -1
  639. package/dist/core/tools/delegate.js +124 -22
  640. package/dist/core/tools/delegate.js.map +1 -1
  641. package/dist/core/tools/extensionify.d.ts.map +1 -1
  642. package/dist/core/tools/extensionify.js +1 -0
  643. package/dist/core/tools/extensionify.js.map +1 -1
  644. package/dist/core/tools/goal.d.ts +94 -3
  645. package/dist/core/tools/goal.d.ts.map +1 -1
  646. package/dist/core/tools/goal.js +165 -15
  647. package/dist/core/tools/goal.js.map +1 -1
  648. package/dist/core/tools/model-fitness.d.ts +7 -0
  649. package/dist/core/tools/model-fitness.d.ts.map +1 -1
  650. package/dist/core/tools/model-fitness.js +4 -4
  651. package/dist/core/tools/model-fitness.js.map +1 -1
  652. package/dist/core/tools/orchestration-panel.d.ts +43 -0
  653. package/dist/core/tools/orchestration-panel.d.ts.map +1 -0
  654. package/dist/core/tools/orchestration-panel.js +168 -0
  655. package/dist/core/tools/orchestration-panel.js.map +1 -0
  656. package/dist/core/tools/run-process.d.ts +26 -0
  657. package/dist/core/tools/run-process.d.ts.map +1 -0
  658. package/dist/core/tools/run-process.js +138 -0
  659. package/dist/core/tools/run-process.js.map +1 -0
  660. package/dist/core/tools/shell-contract-router.d.ts +6 -1
  661. package/dist/core/tools/shell-contract-router.d.ts.map +1 -1
  662. package/dist/core/tools/shell-contract-router.js +23 -2
  663. package/dist/core/tools/shell-contract-router.js.map +1 -1
  664. package/dist/core/tools/shell-session.d.ts +89 -0
  665. package/dist/core/tools/shell-session.d.ts.map +1 -0
  666. package/dist/core/tools/shell-session.js +432 -0
  667. package/dist/core/tools/shell-session.js.map +1 -0
  668. package/dist/core/tools/task-steps.d.ts +6 -0
  669. package/dist/core/tools/task-steps.d.ts.map +1 -1
  670. package/dist/core/tools/task-steps.js +165 -8
  671. package/dist/core/tools/task-steps.js.map +1 -1
  672. package/dist/core/tools/tmux-dispatch.d.ts +84 -0
  673. package/dist/core/tools/tmux-dispatch.d.ts.map +1 -0
  674. package/dist/core/tools/tmux-dispatch.js +91 -0
  675. package/dist/core/tools/tmux-dispatch.js.map +1 -0
  676. package/dist/core/tools/windows-shell-engine.d.ts +42 -0
  677. package/dist/core/tools/windows-shell-engine.d.ts.map +1 -0
  678. package/dist/core/tools/windows-shell-engine.js +151 -0
  679. package/dist/core/tools/windows-shell-engine.js.map +1 -0
  680. package/dist/core/tools/windows-shell-state.d.ts +40 -0
  681. package/dist/core/tools/windows-shell-state.d.ts.map +1 -0
  682. package/dist/core/tools/windows-shell-state.js +59 -0
  683. package/dist/core/tools/windows-shell-state.js.map +1 -0
  684. package/dist/core/tools/worktree-sync.d.ts +24 -0
  685. package/dist/core/tools/worktree-sync.d.ts.map +1 -0
  686. package/dist/core/tools/worktree-sync.js +338 -0
  687. package/dist/core/tools/worktree-sync.js.map +1 -0
  688. package/dist/core/trust-manager.d.ts +4 -1
  689. package/dist/core/trust-manager.d.ts.map +1 -1
  690. package/dist/core/trust-manager.js +20 -2
  691. package/dist/core/trust-manager.js.map +1 -1
  692. package/dist/core/util/atomic-file.d.ts +55 -0
  693. package/dist/core/util/atomic-file.d.ts.map +1 -0
  694. package/dist/core/util/atomic-file.js +255 -0
  695. package/dist/core/util/atomic-file.js.map +1 -0
  696. package/dist/core/util/bounded-jsonl.d.ts +10 -0
  697. package/dist/core/util/bounded-jsonl.d.ts.map +1 -0
  698. package/dist/core/util/bounded-jsonl.js +75 -0
  699. package/dist/core/util/bounded-jsonl.js.map +1 -0
  700. package/dist/core/util/minimatch-cache.d.ts +33 -0
  701. package/dist/core/util/minimatch-cache.d.ts.map +1 -0
  702. package/dist/core/util/minimatch-cache.js +0 -0
  703. package/dist/core/util/minimatch-cache.js.map +1 -0
  704. package/dist/core/util/value-guards.d.ts +5 -0
  705. package/dist/core/util/value-guards.d.ts.map +1 -0
  706. package/dist/core/util/value-guards.js +12 -0
  707. package/dist/core/util/value-guards.js.map +1 -0
  708. package/dist/core/worktree-sync/codes.d.ts +227 -0
  709. package/dist/core/worktree-sync/codes.d.ts.map +1 -0
  710. package/dist/core/worktree-sync/codes.js +14 -0
  711. package/dist/core/worktree-sync/codes.js.map +1 -0
  712. package/dist/core/worktree-sync/git-engine.d.ts +156 -0
  713. package/dist/core/worktree-sync/git-engine.d.ts.map +1 -0
  714. package/dist/core/worktree-sync/git-engine.js +1191 -0
  715. package/dist/core/worktree-sync/git-engine.js.map +1 -0
  716. package/dist/core/worktree-sync/lane-gate.d.ts +75 -0
  717. package/dist/core/worktree-sync/lane-gate.d.ts.map +1 -0
  718. package/dist/core/worktree-sync/lane-gate.js +360 -0
  719. package/dist/core/worktree-sync/lane-gate.js.map +1 -0
  720. package/dist/core/worktree-sync/runtime.d.ts +47 -0
  721. package/dist/core/worktree-sync/runtime.d.ts.map +1 -0
  722. package/dist/core/worktree-sync/runtime.js +96 -0
  723. package/dist/core/worktree-sync/runtime.js.map +1 -0
  724. package/dist/core/worktree-sync/store.d.ts +69 -0
  725. package/dist/core/worktree-sync/store.d.ts.map +1 -0
  726. package/dist/core/worktree-sync/store.js +252 -0
  727. package/dist/core/worktree-sync/store.js.map +1 -0
  728. package/dist/core/worktree-sync/watcher.d.ts +29 -0
  729. package/dist/core/worktree-sync/watcher.d.ts.map +1 -0
  730. package/dist/core/worktree-sync/watcher.js +93 -0
  731. package/dist/core/worktree-sync/watcher.js.map +1 -0
  732. package/dist/index.d.ts +13 -3
  733. package/dist/index.d.ts.map +1 -1
  734. package/dist/index.js +12 -2
  735. package/dist/index.js.map +1 -1
  736. package/dist/main.d.ts.map +1 -1
  737. package/dist/main.js +179 -1
  738. package/dist/main.js.map +1 -1
  739. package/dist/migrations.d.ts +7 -0
  740. package/dist/migrations.d.ts.map +1 -1
  741. package/dist/migrations.js +197 -1
  742. package/dist/migrations.js.map +1 -1
  743. package/dist/modes/interactive/auto-learn-controller.d.ts +16 -1
  744. package/dist/modes/interactive/auto-learn-controller.d.ts.map +1 -1
  745. package/dist/modes/interactive/auto-learn-controller.js +50 -8
  746. package/dist/modes/interactive/auto-learn-controller.js.map +1 -1
  747. package/dist/modes/interactive/clipboard-input.d.ts +7 -1
  748. package/dist/modes/interactive/clipboard-input.d.ts.map +1 -1
  749. package/dist/modes/interactive/clipboard-input.js +44 -6
  750. package/dist/modes/interactive/clipboard-input.js.map +1 -1
  751. package/dist/modes/interactive/components/profile-resource-editor.d.ts.map +1 -1
  752. package/dist/modes/interactive/components/profile-resource-editor.js +23 -1
  753. package/dist/modes/interactive/components/profile-resource-editor.js.map +1 -1
  754. package/dist/modes/interactive/components/settings-selector.d.ts.map +1 -1
  755. package/dist/modes/interactive/components/settings-selector.js +2 -2
  756. package/dist/modes/interactive/components/settings-selector.js.map +1 -1
  757. package/dist/modes/interactive/config-backup.d.ts.map +1 -1
  758. package/dist/modes/interactive/config-backup.js +5 -4
  759. package/dist/modes/interactive/config-backup.js.map +1 -1
  760. package/dist/modes/interactive/extension-ui-host.d.ts +14 -0
  761. package/dist/modes/interactive/extension-ui-host.d.ts.map +1 -1
  762. package/dist/modes/interactive/extension-ui-host.js +76 -15
  763. package/dist/modes/interactive/extension-ui-host.js.map +1 -1
  764. package/dist/modes/interactive/interactive-mode.d.ts +4 -0
  765. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  766. package/dist/modes/interactive/interactive-mode.js +67 -1
  767. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  768. package/dist/modes/interactive/key-handlers.d.ts.map +1 -1
  769. package/dist/modes/interactive/key-handlers.js +1 -1
  770. package/dist/modes/interactive/key-handlers.js.map +1 -1
  771. package/dist/modes/interactive/local-model-commands.d.ts +43 -0
  772. package/dist/modes/interactive/local-model-commands.d.ts.map +1 -1
  773. package/dist/modes/interactive/local-model-commands.js +290 -3
  774. package/dist/modes/interactive/local-model-commands.js.map +1 -1
  775. package/dist/modes/interactive/profile-menu-controller.d.ts.map +1 -1
  776. package/dist/modes/interactive/profile-menu-controller.js +7 -7
  777. package/dist/modes/interactive/profile-menu-controller.js.map +1 -1
  778. package/dist/modes/interactive/report-commands.d.ts.map +1 -1
  779. package/dist/modes/interactive/report-commands.js +21 -0
  780. package/dist/modes/interactive/report-commands.js.map +1 -1
  781. package/dist/modes/interactive/session-flow-commands.d.ts +17 -2
  782. package/dist/modes/interactive/session-flow-commands.d.ts.map +1 -1
  783. package/dist/modes/interactive/session-flow-commands.js +74 -21
  784. package/dist/modes/interactive/session-flow-commands.js.map +1 -1
  785. package/dist/modes/interactive/session-io-commands.d.ts.map +1 -1
  786. package/dist/modes/interactive/session-io-commands.js +16 -6
  787. package/dist/modes/interactive/session-io-commands.js.map +1 -1
  788. package/dist/modes/interactive/session-replacement-errors.d.ts +7 -0
  789. package/dist/modes/interactive/session-replacement-errors.d.ts.map +1 -0
  790. package/dist/modes/interactive/session-replacement-errors.js +15 -0
  791. package/dist/modes/interactive/session-replacement-errors.js.map +1 -0
  792. package/dist/modes/interactive/startup-checks.d.ts.map +1 -1
  793. package/dist/modes/interactive/startup-checks.js +1 -1
  794. package/dist/modes/interactive/startup-checks.js.map +1 -1
  795. package/dist/modes/rpc/rpc-mode.d.ts.map +1 -1
  796. package/dist/modes/rpc/rpc-mode.js +82 -23
  797. package/dist/modes/rpc/rpc-mode.js.map +1 -1
  798. package/dist/modes/rpc/rpc-types.d.ts +15 -0
  799. package/dist/modes/rpc/rpc-types.d.ts.map +1 -1
  800. package/dist/modes/rpc/rpc-types.js +138 -1
  801. package/dist/modes/rpc/rpc-types.js.map +1 -1
  802. package/dist/utils/clipboard-image.d.ts.map +1 -1
  803. package/dist/utils/clipboard-image.js +2 -13
  804. package/dist/utils/clipboard-image.js.map +1 -1
  805. package/dist/utils/clipboard-native.d.ts +1 -0
  806. package/dist/utils/clipboard-native.d.ts.map +1 -1
  807. package/dist/utils/clipboard-native.js.map +1 -1
  808. package/dist/utils/clipboard.d.ts +1 -0
  809. package/dist/utils/clipboard.d.ts.map +1 -1
  810. package/dist/utils/clipboard.js +52 -1
  811. package/dist/utils/clipboard.js.map +1 -1
  812. package/dist/utils/fs-watch.d.ts +11 -0
  813. package/dist/utils/fs-watch.d.ts.map +1 -1
  814. package/dist/utils/fs-watch.js +20 -2
  815. package/dist/utils/fs-watch.js.map +1 -1
  816. package/dist/utils/highlight-js-languages.d.ts +4 -0
  817. package/dist/utils/highlight-js-languages.d.ts.map +1 -0
  818. package/dist/utils/highlight-js-languages.js +573 -0
  819. package/dist/utils/highlight-js-languages.js.map +1 -0
  820. package/dist/utils/platform.d.ts +3 -0
  821. package/dist/utils/platform.d.ts.map +1 -0
  822. package/dist/utils/platform.js +8 -0
  823. package/dist/utils/platform.js.map +1 -0
  824. package/dist/utils/shell.d.ts +7 -1
  825. package/dist/utils/shell.d.ts.map +1 -1
  826. package/dist/utils/shell.js +21 -6
  827. package/dist/utils/shell.js.map +1 -1
  828. package/dist/utils/syntax-highlight.d.ts.map +1 -1
  829. package/dist/utils/syntax-highlight.js +53 -5
  830. package/dist/utils/syntax-highlight.js.map +1 -1
  831. package/dist/utils/tools-manager.d.ts.map +1 -1
  832. package/dist/utils/tools-manager.js +112 -1
  833. package/dist/utils/tools-manager.js.map +1 -1
  834. package/dist/utils/work-directory.d.ts +11 -0
  835. package/dist/utils/work-directory.d.ts.map +1 -1
  836. package/dist/utils/work-directory.js +30 -9
  837. package/dist/utils/work-directory.js.map +1 -1
  838. package/docs/UI_POLISH_ORCHESTRATION.md +44 -0
  839. package/docs/UI_QUALITY_ORCHESTRATION.md +30 -0
  840. package/docs/docs.json +4 -0
  841. package/docs/extensions.md +62 -2
  842. package/docs/harness-architecture.md +156 -0
  843. package/docs/keybindings.md +11 -1
  844. package/docs/process-matrix.md +153 -0
  845. package/docs/rpc.md +45 -2
  846. package/docs/sessions.md +15 -0
  847. package/docs/settings.md +128 -11
  848. package/docs/task-steps.md +8 -0
  849. package/docs/telemetry.md +19 -0
  850. package/docs/tmux-agent-manager.md +92 -2
  851. package/docs/ui-reference/README.md +9 -0
  852. package/docs/ui-reference/orchestration-after.txt +7 -0
  853. package/docs/ui-reference/orchestration-before.txt +7 -0
  854. package/docs/ui-reference/orchestration-reference.txt +6 -0
  855. package/docs/usage.md +14 -2
  856. package/docs/windows.md +52 -3
  857. package/docs/work-directory.md +42 -2
  858. package/docs/worktree-sync.md +250 -0
  859. package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
  860. package/examples/extensions/custom-provider-anthropic/package.json +1 -1
  861. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  862. package/examples/extensions/question.ts +34 -245
  863. package/examples/extensions/questionnaire.ts +41 -407
  864. package/examples/extensions/sandbox/package-lock.json +2 -2
  865. package/examples/extensions/sandbox/package.json +1 -1
  866. package/examples/extensions/with-deps/package-lock.json +2 -2
  867. package/examples/extensions/with-deps/package.json +1 -1
  868. package/npm-shrinkwrap.json +12 -12
  869. package/package.json +10 -4
  870. package/dist/core/delegation/session-worker-result.d.ts +0 -16
  871. package/dist/core/delegation/session-worker-result.d.ts.map +0 -1
  872. package/dist/core/delegation/session-worker-result.js +0 -53
  873. package/dist/core/delegation/session-worker-result.js.map +0 -1
  874. package/dist/core/delegation/worker-result.d.ts +0 -15
  875. package/dist/core/delegation/worker-result.d.ts.map +0 -1
  876. package/dist/core/delegation/worker-result.js +0 -161
  877. package/dist/core/delegation/worker-result.js.map +0 -1
  878. package/dist/core/telemetry.d.ts.map +0 -1
  879. package/dist/core/telemetry.js.map +0 -1
  880. package/docs/integration-sweep-builder-blueprint-2026-07-09.md +0 -365
  881. package/docs/integration-sweep-resume-2026-07-09.md +0 -407
@@ -0,0 +1,432 @@
1
+ /**
2
+ * Persistent shell sessions for the bash tool.
3
+ *
4
+ * One long-lived shell process per agent (keyed registry) replaces process-per-command spawning.
5
+ * On Windows every command previously paid a full PowerShell boot; a persistent session pays it
6
+ * once. Shell state (current directory, environment variables) persists across an agent's
7
+ * commands; each key gets an isolated session so concurrently running agents never share state.
8
+ *
9
+ * Protocol: commands stream to the session over stdin and are terminated by a per-command
10
+ * sentinel carrying a random nonce and the exit code. Bash wraps commands in an eval of a quoted
11
+ * heredoc (arbitrary content stays data; syntax errors stay contained in eval); PowerShell runs a
12
+ * ReadLine loop decoding base64 lines (no external binaries involved). On bash, command stderr is
13
+ * merged into stdout at the shell so sentinel ordering is guaranteed on one pipe.
14
+ *
15
+ * PowerShell runs each command as a bare `Invoke-Expression`, NOT piped into `Out-Default`: piping
16
+ * a native command's output into another pipeline stage forces PowerShell's NativeCommandProcessor
17
+ * to capture that child's stdout/stderr into an internal pipe and read it to EOF before the
18
+ * pipeline completes. A detached grandchild that inherited those handles (e.g. `start /b` holding
19
+ * stdio open) then keeps that internal pipe's write end open, so the sentinel — written after the
20
+ * pipeline "completes" — waits for the grandchild to die instead of the direct child. The bare
21
+ * invocation lets a native command's stdout/stderr handles be inherited directly by the child
22
+ * process; the direct child's own exit is what unblocks the sentinel line, exactly like the
23
+ * per-command backend and like bash's stdio inheritance above. The bounded consequence: a native
24
+ * command's stderr no longer merges into the session's stdout pipe (there is no capturing pipeline
25
+ * stage to merge it) — it arrives on the session's own stderr pipe instead, forwarded via
26
+ * `onStderr` -> `onData` same as the shell's own diagnostics. PowerShell 5.1's habit of wrapping
27
+ * redirected stderr text in a `NativeCommandError` record also disappears, which is an accuracy
28
+ * improvement (the raw stderr bytes are reported, not a wrapped/duplicated rendering of them).
29
+ *
30
+ * Kill semantics: timeout/abort/silence kill the WHOLE session process tree (a hung foreground
31
+ * command cannot be killed individually without job control) and the next exec respawns a fresh
32
+ * session, losing accumulated shell state by design. A command that exits the shell itself
33
+ * (`exit 3`) reports the shell's exit code and also respawns lazily afterwards.
34
+ */
35
+ import { randomBytes } from "node:crypto";
36
+ import { basename } from "node:path";
37
+ import { createSilenceWatchdog } from "@caupulican/pi-agent-core";
38
+ import { spawn } from "child_process";
39
+ import { getShellConfig, getShellEnv, killProcessTree, trackDetachedChildPid, untrackDetachedChildPid, } from "../../utils/shell.js";
40
+ const SENTINEL_BYTE = 0x1e;
41
+ /** Longest possible sentinel: "\n" + 0x1e + 16-hex nonce + ":" + exit code digits + 0x1e. */
42
+ const SENTINEL_HOLDBACK_BYTES = 64;
43
+ function escapeSingleQuotesPosix(value) {
44
+ return value.replace(/'/g, "'\\''");
45
+ }
46
+ function escapeSingleQuotesPowerShell(value) {
47
+ return value.replace(/'/g, "''");
48
+ }
49
+ /**
50
+ * The whole command is heredoc-quoted data: eval keeps syntax errors contained (a raw syntax
51
+ * error on the session's stdin would abort the shell), and the random delimiter makes content
52
+ * collisions with agent output practically impossible. `< /dev/null` gives commands the same
53
+ * EOF-stdin the per-command backend's `stdio: ["ignore", ...]` provided.
54
+ */
55
+ export function buildBashWire(command, nonce, cdTo) {
56
+ const body = cdTo ? `command cd -- '${escapeSingleQuotesPosix(cdTo)}' && {\n${command}\n}` : command;
57
+ return [
58
+ `{ eval "$(cat <<'PI_EOF_${nonce}'`,
59
+ body,
60
+ `PI_EOF_${nonce}`,
61
+ `)"; } < /dev/null 2>&1`,
62
+ `printf '\\n\\036%s:%s\\036' '${nonce}' "$?"`,
63
+ "",
64
+ ].join("\n");
65
+ }
66
+ /** One protocol line: `<nonce> <base64(utf8 command)>`. Base64 keeps arbitrary multi-line commands line-safe. */
67
+ export function buildPowerShellWire(command, nonce, cdTo) {
68
+ const body = cdTo
69
+ ? `Set-Location -LiteralPath '${escapeSingleQuotesPowerShell(cdTo)}' -ErrorAction Stop\n${command}`
70
+ : command;
71
+ return `${nonce} ${Buffer.from(body, "utf8").toString("base64")}\n`;
72
+ }
73
+ /**
74
+ * PowerShell 5.1-compatible REPL bootstrap. Exit code mirrors `-Command` semantics as closely as
75
+ * a loop can: a native command's $LASTEXITCODE wins, a terminating error forces 1, otherwise 0.
76
+ * Passed via -EncodedCommand so quoting and newlines never touch the process command line.
77
+ *
78
+ * The command runs as a bare `Invoke-Expression` (no `2>&1 | Out-Default` capture pipeline) — see
79
+ * the module doc header for why: a native command's stdio handles are inherited directly by its
80
+ * child process instead of being captured through a PowerShell-internal pipe, so the sentinel is
81
+ * unblocked by the direct child's own exit rather than by any grandchild holding those handles.
82
+ */
83
+ const POWERSHELL_BOOTSTRAP = [
84
+ "$ProgressPreference = 'SilentlyContinue'",
85
+ "try { [Console]::OutputEncoding = [System.Text.Encoding]::UTF8 } catch {}",
86
+ "$__pi_in = [Console]::In",
87
+ "while ($true) {",
88
+ "\t$__pi_line = $__pi_in.ReadLine()",
89
+ "\tif ($null -eq $__pi_line) { break }",
90
+ "\t$__pi_sp = $__pi_line.IndexOf(' ')",
91
+ "\tif ($__pi_sp -lt 1) { continue }",
92
+ "\t$__pi_nonce = $__pi_line.Substring(0, $__pi_sp)",
93
+ "\t$__pi_cmd = [System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String($__pi_line.Substring($__pi_sp + 1)))",
94
+ "\t$global:LASTEXITCODE = 0",
95
+ "\t$__pi_thrown = $false",
96
+ "\ttry { Invoke-Expression $__pi_cmd } catch { $__pi_thrown = $true; $__pi_msg = ($_ | Out-String).TrimEnd(); if ($__pi_msg) { [Console]::Out.WriteLine($__pi_msg) } }",
97
+ "\t$__pi_code = $global:LASTEXITCODE",
98
+ "\tif ($null -eq $__pi_code) { $__pi_code = 0 }",
99
+ "\tif ($__pi_thrown -and ($__pi_code -eq 0)) { $__pi_code = 1 }",
100
+ "\t[Console]::Out.Write(('{0}{1}{2}:{3}{1}' -f [char]10, [char]30, $__pi_nonce, $__pi_code))",
101
+ "}",
102
+ ].join("\n");
103
+ function shallowEnvEquals(a, b) {
104
+ const aKeys = Object.keys(a);
105
+ const bKeys = Object.keys(b);
106
+ if (aKeys.length !== bKeys.length)
107
+ return false;
108
+ for (const key of aKeys) {
109
+ if (a[key] !== b[key])
110
+ return false;
111
+ }
112
+ return true;
113
+ }
114
+ export class PersistentShellSession {
115
+ key;
116
+ kind;
117
+ child = null;
118
+ childEnv = null;
119
+ lastRequestedCwd = null;
120
+ activeExec = null;
121
+ queue = Promise.resolve();
122
+ disposed = false;
123
+ constructor(key, kind) {
124
+ this.key = key;
125
+ this.kind = kind;
126
+ }
127
+ get sessionKind() {
128
+ return this.kind;
129
+ }
130
+ /** Serialized: one command at a time per session, later calls queue behind earlier ones. */
131
+ exec(command, cwd, options) {
132
+ const run = this.queue.then(() => this.execNow(command, cwd, options));
133
+ this.queue = run.then(() => undefined, () => undefined);
134
+ return run;
135
+ }
136
+ dispose() {
137
+ this.disposed = true;
138
+ this.killChild();
139
+ }
140
+ /** Synchronous best-effort kill for process-exit hooks (async spawn never runs during exit).
141
+ * `killProcessTree` is itself synchronous (blocking `spawnSync` on Windows, `process.kill` on
142
+ * POSIX), so it is safe to call directly from a `process.on("exit", ...)` handler. */
143
+ killForProcessExit() {
144
+ const pid = this.child?.pid;
145
+ this.child = null;
146
+ if (!pid)
147
+ return;
148
+ untrackDetachedChildPid(pid);
149
+ killProcessTree(pid);
150
+ }
151
+ async execNow(command, cwd, { onData, signal, timeoutSeconds, silenceMs, env }) {
152
+ if (this.disposed)
153
+ throw new Error(`Shell session "${this.key}" is disposed`);
154
+ if (signal?.aborted)
155
+ throw new Error("aborted");
156
+ const resolvedEnv = env ?? getShellEnv();
157
+ // The environment is spawn-time shell config: an env that differs from the running
158
+ // session's (e.g. a spawn hook rewriting it per command) requires a fresh shell.
159
+ if (this.child && this.childEnv && !shallowEnvEquals(this.childEnv, resolvedEnv)) {
160
+ this.killChild();
161
+ }
162
+ // Re-enter the host-requested cwd only when it CHANGES between calls; an unchanged
163
+ // request preserves the agent's own in-session `cd` (that persistence is the feature).
164
+ let cdTo = null;
165
+ if (!this.child) {
166
+ this.spawnChild(cwd, resolvedEnv);
167
+ }
168
+ else if (this.lastRequestedCwd !== cwd) {
169
+ cdTo = cwd;
170
+ }
171
+ this.lastRequestedCwd = cwd;
172
+ const child = this.child;
173
+ if (!child?.stdin || !child.stdout || !child.stderr) {
174
+ this.killChild();
175
+ throw new Error(`Failed to start ${this.kind} session`);
176
+ }
177
+ const nonce = randomBytes(8).toString("hex");
178
+ const wire = this.kind === "powershell" ? buildPowerShellWire(command, nonce, cdTo) : buildBashWire(command, nonce, cdTo);
179
+ const sentinelPrefix = Buffer.from(`\n\x1e${nonce}:`, "latin1");
180
+ this.setLoopRef(true);
181
+ try {
182
+ return await new Promise((resolve, reject) => {
183
+ let settled = false;
184
+ let pending = Buffer.alloc(0);
185
+ let timeoutTimer;
186
+ const silenceWatchdog = timeoutSeconds === undefined && silenceMs !== undefined && silenceMs > 0
187
+ ? createSilenceWatchdog({
188
+ silenceMs,
189
+ onSilence: () => {
190
+ this.killChild();
191
+ settle(() => reject(new Error(`silence:${silenceMs / 1000}`)));
192
+ },
193
+ })
194
+ : undefined;
195
+ const settle = (finish) => {
196
+ if (settled)
197
+ return;
198
+ settled = true;
199
+ if (timeoutTimer)
200
+ clearTimeout(timeoutTimer);
201
+ silenceWatchdog?.disarm();
202
+ if (signal)
203
+ signal.removeEventListener("abort", onAbort);
204
+ this.activeExec = null;
205
+ finish();
206
+ };
207
+ const onAbort = () => {
208
+ this.killChild();
209
+ settle(() => reject(new Error("aborted")));
210
+ };
211
+ const emitPending = (upTo) => {
212
+ if (upTo <= 0)
213
+ return;
214
+ onData(pending.subarray(0, upTo));
215
+ pending = pending.subarray(upTo);
216
+ };
217
+ this.activeExec = {
218
+ onStdout: (data) => {
219
+ silenceWatchdog?.touch();
220
+ pending = pending.length === 0 ? data : Buffer.concat([pending, data]);
221
+ const prefixIndex = pending.indexOf(sentinelPrefix);
222
+ if (prefixIndex !== -1) {
223
+ const closeIndex = pending.indexOf(SENTINEL_BYTE, prefixIndex + sentinelPrefix.length);
224
+ if (closeIndex !== -1) {
225
+ const codeText = pending
226
+ .subarray(prefixIndex + sentinelPrefix.length, closeIndex)
227
+ .toString("latin1");
228
+ emitPending(prefixIndex);
229
+ const parsed = Number.parseInt(codeText, 10);
230
+ // Defer the settle by one microtask turn: with the bare Invoke-Expression
231
+ // form a native command's stderr now arrives on the session's OWN stderr
232
+ // pipe (see module doc header) instead of being pre-merged into the same
233
+ // stdout bytes the sentinel rides on. Node fires already-queued stream
234
+ // 'data' events in event-loop order; queueing the resolution behind a
235
+ // microtask guarantees any stderr chunk the kernel delivered alongside (or
236
+ // just before) this stdout chunk has already run its 'data' handler — and
237
+ // thus reached `onData` — before the promise settles, so callers never see a
238
+ // truncated stderr tail immediately after resolution.
239
+ queueMicrotask(() => settle(() => resolve({ exitCode: Number.isNaN(parsed) ? null : parsed })));
240
+ return;
241
+ }
242
+ }
243
+ // Stream promptly but retain a tail large enough to hold any split sentinel.
244
+ emitPending(pending.length - SENTINEL_HOLDBACK_BYTES);
245
+ },
246
+ onStderr: (data) => {
247
+ // The command's stderr is merged into stdout at the shell; this pipe only
248
+ // carries the session shell's own diagnostics. Forward for visibility.
249
+ silenceWatchdog?.touch();
250
+ onData(data);
251
+ },
252
+ onChildClose: (code) => {
253
+ // The command terminated the shell itself (e.g. `exit 3`) or the shell
254
+ // crashed: report its exit code like the per-command backend would.
255
+ emitPending(pending.length);
256
+ settle(() => resolve({ exitCode: code }));
257
+ },
258
+ fail: (error) => {
259
+ this.killChild();
260
+ settle(() => reject(error));
261
+ },
262
+ };
263
+ if (signal)
264
+ signal.addEventListener("abort", onAbort, { once: true });
265
+ if (timeoutSeconds !== undefined && timeoutSeconds > 0) {
266
+ timeoutTimer = setTimeout(() => {
267
+ this.killChild();
268
+ settle(() => reject(new Error(`timeout:${timeoutSeconds}`)));
269
+ }, timeoutSeconds * 1000);
270
+ }
271
+ child.stdin?.write(wire, (error) => {
272
+ if (!error)
273
+ return;
274
+ this.killChild();
275
+ settle(() => reject(new Error(`Failed to write to ${this.kind} session: ${error.message}`)));
276
+ });
277
+ });
278
+ }
279
+ finally {
280
+ this.setLoopRef(false);
281
+ }
282
+ }
283
+ spawnChild(cwd, env) {
284
+ const { shell } = getShellConfig(undefined, this.kind);
285
+ const args = this.kind === "powershell"
286
+ ? [
287
+ "-NoLogo",
288
+ "-NoProfile",
289
+ "-NonInteractive",
290
+ "-EncodedCommand",
291
+ Buffer.from(POWERSHELL_BOOTSTRAP, "utf16le").toString("base64"),
292
+ ]
293
+ : basename(shell).toLowerCase().includes("bash")
294
+ ? ["--noprofile", "--norc"]
295
+ : [];
296
+ const child = spawn(shell, args, {
297
+ cwd,
298
+ env,
299
+ detached: process.platform !== "win32",
300
+ stdio: ["pipe", "pipe", "pipe"],
301
+ windowsHide: true,
302
+ });
303
+ if (child.pid)
304
+ trackDetachedChildPid(child.pid);
305
+ // Every listener gates on the child still being the session's current one: after a
306
+ // timeout/abort kill replaced it, the dead shell's late data/close events are stale noise
307
+ // that must never reach the NEXT command's handlers.
308
+ child.stdout?.on("data", (data) => {
309
+ if (this.child === child)
310
+ this.activeExec?.onStdout(data);
311
+ });
312
+ child.stderr?.on("data", (data) => {
313
+ if (this.child === child)
314
+ this.activeExec?.onStderr(data);
315
+ });
316
+ child.on("error", (error) => {
317
+ if (this.child !== child)
318
+ return;
319
+ this.clearChild(child);
320
+ this.activeExec?.fail(error instanceof Error ? error : new Error(String(error)));
321
+ });
322
+ // Settle the shell-died path on "exit" (process death), not "close" (stdio streams ended):
323
+ // a live detached grandchild that inherited these pipes (e.g. `sleep 30 &` before `exit 3`)
324
+ // keeps them open indefinitely even though the shell itself is already gone, and Node only
325
+ // fires "close" once every stdio stream has ended. Waiting for "close" here would hang for
326
+ // as long as the grandchild lives. The per-command backend
327
+ // (waitForChildProcessWithTermination in ../../utils/child-process.ts) faces the identical
328
+ // hazard and settles on "exit" for the same reason.
329
+ //
330
+ // "exit" can fire before Node has delivered already-buffered stdout/stderr "data" events for
331
+ // bytes the kernel handed over just before the process died (e.g. the sentinel line itself).
332
+ // Defer the settlement by one setImmediate turn: Node drains the poll phase (which is where
333
+ // pending stream "data" events run) before the check phase (where setImmediate callbacks
334
+ // run), so by the time this callback executes, every "data" event for bytes already received
335
+ // has already reached onStdout/onStderr, and thus onData, before we resolve/reject. This is
336
+ // not a hang-fix timer — it never waits on anything and does not run if the grandchild is
337
+ // gone and "close" (or a replacement child) got there first.
338
+ child.on("exit", (code) => {
339
+ if (this.child !== child)
340
+ return;
341
+ setImmediate(() => {
342
+ if (this.child !== child)
343
+ return;
344
+ this.clearChild(child);
345
+ this.activeExec?.onChildClose(code);
346
+ });
347
+ });
348
+ // Kept alongside "exit" for the genuine fast-close case (no lingering grandchild): whichever
349
+ // event reaches its guard first wins and nulls out this.child, making the other a no-op, so
350
+ // settlement stays idempotent regardless of which fires first or whether both fire.
351
+ child.on("close", (code) => {
352
+ if (this.child !== child)
353
+ return;
354
+ this.clearChild(child);
355
+ this.activeExec?.onChildClose(code);
356
+ });
357
+ this.child = child;
358
+ this.childEnv = env;
359
+ this.lastRequestedCwd = cwd;
360
+ }
361
+ clearChild(child) {
362
+ if (child.pid)
363
+ untrackDetachedChildPid(child.pid);
364
+ this.child = null;
365
+ this.childEnv = null;
366
+ this.lastRequestedCwd = null;
367
+ }
368
+ killChild() {
369
+ const child = this.child;
370
+ if (!child)
371
+ return;
372
+ this.clearChild(child);
373
+ if (child.pid)
374
+ killProcessTree(child.pid);
375
+ }
376
+ /**
377
+ * An idle session must not keep the Node event loop alive (one-shot modes have to exit
378
+ * naturally); during a command the child and its pipes are re-referenced so the loop stays
379
+ * alive even without an armed timer.
380
+ */
381
+ setLoopRef(active) {
382
+ const child = this.child;
383
+ if (!child)
384
+ return;
385
+ // Stdio pipes are Sockets at runtime (ref/unref exist) but are typed as plain streams.
386
+ const streams = [child.stdin, child.stdout, child.stderr];
387
+ if (active) {
388
+ child.ref();
389
+ for (const stream of streams)
390
+ stream?.ref?.();
391
+ }
392
+ else {
393
+ child.unref();
394
+ for (const stream of streams)
395
+ stream?.unref?.();
396
+ }
397
+ }
398
+ }
399
+ const shellSessions = new Map();
400
+ let exitHookInstalled = false;
401
+ function installExitHook() {
402
+ if (exitHookInstalled)
403
+ return;
404
+ exitHookInstalled = true;
405
+ // Detached sessions outlive the parent on clean exits unless explicitly killed; shutdown
406
+ // signals are already covered by the tracked-detached-children mechanism.
407
+ process.on("exit", () => {
408
+ for (const session of shellSessions.values()) {
409
+ session.killForProcessExit();
410
+ }
411
+ });
412
+ }
413
+ /** Get or lazily create the persistent session for a key. A kind change replaces the session. */
414
+ export function acquirePersistentShellSession(key, kind) {
415
+ installExitHook();
416
+ const existing = shellSessions.get(key);
417
+ if (existing && existing.sessionKind === kind)
418
+ return existing;
419
+ existing?.dispose();
420
+ const session = new PersistentShellSession(key, kind);
421
+ shellSessions.set(key, session);
422
+ return session;
423
+ }
424
+ /** Kill and forget a session (agent teardown). Safe to call for keys that never spawned. */
425
+ export function disposePersistentShellSession(key) {
426
+ const session = shellSessions.get(key);
427
+ if (!session)
428
+ return;
429
+ shellSessions.delete(key);
430
+ session.dispose();
431
+ }
432
+ //# sourceMappingURL=shell-session.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"shell-session.js","sourceRoot":"","sources":["../../../src/core/tools/shell-session.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAiCG;AAEH,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAC1C,OAAO,EAAE,QAAQ,E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Aa,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;IACxC,IAAI,QAAQ,IAAI,QAAQ,CAAC,WAAW,KAAK,IAAI;QAAE,OAAO,QAAQ,CAAC;IAC/D,QAAQ,EAAE,OAAO,EAAE,CAAC;IACpB,MAAM,OAAO,GAAG,IAAI,sBAAsB,CAAC,GAAG,EAAE,IAAI,CAAC,CAAC;IACtD,aAAa,CAAC,GAAG,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC;IAChC,OAAO,OAAO,CAAC;AAAA,CACf;AAED,4FAA4F;AAC5F,MAAM,UAAU,6BAA6B,CAAC,GAAW,EAAQ;IAChE,MAAM,OAAO,GAAG,aAAa,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;IACvC,IAAI,CAAC,OAAO;QAAE,OAAO;IACrB,aAAa,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;IAC1B,OAAO,CAAC,OAAO,EAAE,CAAC;AAAA,CAClB","sourcesContent":["/**\n * Persistent shell sessions for the bash tool.\n *\n * One long-lived shell process per agent (keyed registry) replaces process-per-command spawning.\n * On Windows every command previously paid a full PowerShell boot; a persistent session pays it\n * once. Shell state (current directory, environment variables) persists across an agent's\n * commands; each key gets an isolated session so concurrently running agents never share state.\n *\n * Protocol: commands stream to the session over stdin and are terminated by a per-command\n * sentinel carrying a random nonce and the exit code. Bash wraps commands in an eval of a quoted\n * heredoc (arbitrary content stays data; syntax errors stay contained in eval); PowerShell runs a\n * ReadLine loop decoding base64 lines (no external binaries involved). On bash, command stderr is\n * merged into stdout at the shell so sentinel ordering is guaranteed on one pipe.\n *\n * PowerShell runs each command as a bare `Invoke-Expression`, NOT piped into `Out-Default`: piping\n * a native command's output into another pipeline stage forces PowerShell's NativeCommandProcessor\n * to capture that child's stdout/stderr into an internal pipe and read it to EOF before the\n * pipeline completes. A detached grandchild that inherited those handles (e.g. `start /b` holding\n * stdio open) then keeps that internal pipe's write end open, so the sentinel — written after the\n * pipeline \"completes\" — waits for the grandchild to die instead of the direct child. The bare\n * invocation lets a native command's stdout/stderr handles be inherited directly by the child\n * process; the direct child's own exit is what unblocks the sentinel line, exactly like the\n * per-command backend and like bash's stdio inheritance above. The bounded consequence: a native\n * command's stderr no longer merges into the session's stdout pipe (there is no capturing pipeline\n * stage to merge it) — it arrives on the session's own stderr pipe instead, forwarded via\n * `onStderr` -> `onData` same as the shell's own diagnostics. PowerShell 5.1's habit of wrapping\n * redirected stderr text in a `NativeCommandError` record also disappears, which is an accuracy\n * improvement (the raw stderr bytes are reported, not a wrapped/duplicated rendering of them).\n *\n * Kill semantics: timeout/abort/silence kill the WHOLE session process tree (a hung foreground\n * command cannot be killed individually without job control) and the next exec respawns a fresh\n * session, losing accumulated shell state by design. A command that exits the shell itself\n * (`exit 3`) reports the shell's exit code and also respawns lazily afterwards.\n */\n\nimport { randomBytes } from \"node:crypto\";\nimport { basename } from \"node:path\";\nimport { createSilenceWatchdog } from \"@caupulican/pi-agent-core\";\nimport { type ChildProcess, spawn } from \"child_process\";\nimport {\n\tgetShellConfig,\n\tgetShellEnv,\n\tkillProcessTree,\n\ttype PlatformShellToolName,\n\ttrackDetachedChildPid,\n\tuntrackDetachedChildPid,\n} from \"../../utils/shell.ts\";\n\nconst SENTINEL_BYTE = 0x1e;\n/** Longest possible sentinel: \"\\n\" + 0x1e + 16-hex nonce + \":\" + exit code digits + 0x1e. */\nconst SENTINEL_HOLDBACK_BYTES = 64;\n\nexport interface ShellSessionExecOptions {\n\tonData: (data: Buffer) => void;\n\tsignal?: AbortSignal;\n\t/** Wall-clock bound in seconds; when set, a breach kills the session and throws `timeout:<s>`. */\n\ttimeoutSeconds?: number;\n\t/** Output-silence bound in ms; when set, silence kills the session and throws `silence:<s>`. */\n\tsilenceMs?: number;\n\tenv?: NodeJS.ProcessEnv;\n}\n\nfunction escapeSingleQuotesPosix(value: string): string {\n\treturn value.replace(/'/g, \"'\\\\''\");\n}\n\nfunction escapeSingleQuotesPowerShell(value: string): string {\n\treturn value.replace(/'/g, \"''\");\n}\n\n/**\n * The whole command is heredoc-quoted data: eval keeps syntax errors contained (a raw syntax\n * error on the session's stdin would abort the shell), and the random delimiter makes content\n * collisions with agent output practically impossible. `< /dev/null` gives commands the same\n * EOF-stdin the per-command backend's `stdio: [\"ignore\", ...]` provided.\n */\nexport function buildBashWire(command: string, nonce: string, cdTo: string | null): string {\n\tconst body = cdTo ? `command cd -- '${escapeSingleQuotesPosix(cdTo)}' && {\\n${command}\\n}` : command;\n\treturn [\n\t\t`{ eval \"$(cat <<'PI_EOF_${nonce}'`,\n\t\tbody,\n\t\t`PI_EOF_${nonce}`,\n\t\t`)\"; } < /dev/null 2>&1`,\n\t\t`printf '\\\\n\\\\036%s:%s\\\\036' '${nonce}' \"$?\"`,\n\t\t\"\",\n\t].join(\"\\n\");\n}\n\n/** One protocol line: `<nonce> <base64(utf8 command)>`. Base64 keeps arbitrary multi-line commands line-safe. */\nexport function buildPowerShellWire(command: string, nonce: string, cdTo: string | null): string {\n\tconst body = cdTo\n\t\t? `Set-Location -LiteralPath '${escapeSingleQuotesPowerShell(cdTo)}' -ErrorAction Stop\\n${command}`\n\t\t: command;\n\treturn `${nonce} ${Buffer.from(body, \"utf8\").toString(\"base64\")}\\n`;\n}\n\n/**\n * PowerShell 5.1-compatible REPL bootstrap. Exit code mirrors `-Command` semantics as closely as\n * a loop can: a native command's $LASTEXITCODE wins, a terminating error forces 1, otherwise 0.\n * Passed via -EncodedCommand so quoting and newlines never touch the process command line.\n *\n * The command runs as a bare `Invoke-Expression` (no `2>&1 | Out-Default` capture pipeline) — see\n * the module doc header for why: a native command's stdio handles are inherited directly by its\n * child process instead of being captured through a PowerShell-internal pipe, so the sentinel is\n * unblocked by the direct child's own exit rather than by any grandchild holding those handles.\n */\nconst POWERSHELL_BOOTSTRAP = [\n\t\"$ProgressPreference = 'SilentlyContinue'\",\n\t\"try { [Console]::OutputEncoding = [System.Text.Encoding]::UTF8 } catch {}\",\n\t\"$__pi_in = [Console]::In\",\n\t\"while ($true) {\",\n\t\"\\t$__pi_line = $__pi_in.ReadLine()\",\n\t\"\\tif ($null -eq $__pi_line) { break }\",\n\t\"\\t$__pi_sp = $__pi_line.IndexOf(' ')\",\n\t\"\\tif ($__pi_sp -lt 1) { continue }\",\n\t\"\\t$__pi_nonce = $__pi_line.Substring(0, $__pi_sp)\",\n\t\"\\t$__pi_cmd = [System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String($__pi_line.Substring($__pi_sp + 1)))\",\n\t\"\\t$global:LASTEXITCODE = 0\",\n\t\"\\t$__pi_thrown = $false\",\n\t\"\\ttry { Invoke-Expression $__pi_cmd } catch { $__pi_thrown = $true; $__pi_msg = ($_ | Out-String).TrimEnd(); if ($__pi_msg) { [Console]::Out.WriteLine($__pi_msg) } }\",\n\t\"\\t$__pi_code = $global:LASTEXITCODE\",\n\t\"\\tif ($null -eq $__pi_code) { $__pi_code = 0 }\",\n\t\"\\tif ($__pi_thrown -and ($__pi_code -eq 0)) { $__pi_code = 1 }\",\n\t\"\\t[Console]::Out.Write(('{0}{1}{2}:{3}{1}' -f [char]10, [char]30, $__pi_nonce, $__pi_code))\",\n\t\"}\",\n].join(\"\\n\");\n\nfunction shallowEnvEquals(a: NodeJS.ProcessEnv, b: NodeJS.ProcessEnv): boolean {\n\tconst aKeys = Object.keys(a);\n\tconst bKeys = Object.keys(b);\n\tif (aKeys.length !== bKeys.length) return false;\n\tfor (const key of aKeys) {\n\t\tif (a[key] !== b[key]) return false;\n\t}\n\treturn true;\n}\n\ninterface ActiveExec {\n\tonStdout(data: Buffer): void;\n\tonStderr(data: Buffer): void;\n\tonChildClose(code: number | null): void;\n\tfail(error: Error): void;\n}\n\nexport class PersistentShellSession {\n\tprivate readonly key: string;\n\tprivate readonly kind: PlatformShellToolName;\n\tprivate child: ChildProcess | null = null;\n\tprivate childEnv: NodeJS.ProcessEnv | null = null;\n\tprivate lastRequestedCwd: string | null = null;\n\tprivate activeExec: ActiveExec | null = null;\n\tprivate queue: Promise<void> = Promise.resolve();\n\tprivate disposed = false;\n\n\tconstructor(key: string, kind: PlatformShellToolName) {\n\t\tthis.key = key;\n\t\tthis.kind = kind;\n\t}\n\n\tget sessionKind(): PlatformShellToolName {\n\t\treturn this.kind;\n\t}\n\n\t/** Serialized: one command at a time per session, later calls queue behind earlier ones. */\n\texec(command: string, cwd: string, options: ShellSessionExecOptions): Promise<{ exitCode: number | null }> {\n\t\tconst run = this.queue.then(() => this.execNow(command, cwd, options));\n\t\tthis.queue = run.then(\n\t\t\t() => undefined,\n\t\t\t() => undefined,\n\t\t);\n\t\treturn run;\n\t}\n\n\tdispose(): void {\n\t\tthis.disposed = true;\n\t\tthis.killChild();\n\t}\n\n\t/** Synchronous best-effort kill for process-exit hooks (async spawn never runs during exit).\n\t * `killProcessTree` is itself synchronous (blocking `spawnSync` on Windows, `process.kill` on\n\t * POSIX), so it is safe to call directly from a `process.on(\"exit\", ...)` handler. */\n\tkillForProcessExit(): void {\n\t\tconst pid = this.child?.pid;\n\t\tthis.child = null;\n\t\tif (!pid) return;\n\t\tuntrackDetachedChildPid(pid);\n\t\tkillProcessTree(pid);\n\t}\n\n\tprivate async execNow(\n\t\tcommand: string,\n\t\tcwd: string,\n\t\t{ onData, signal, timeoutSeconds, silenceMs, env }: ShellSessionExecOptions,\n\t): Promise<{ exitCode: number | null }> {\n\t\tif (this.disposed) throw new Error(`Shell session \"${this.key}\" is disposed`);\n\t\tif (signal?.aborted) throw new Error(\"aborted\");\n\n\t\tconst resolvedEnv = env ?? getShellEnv();\n\t\t// The environment is spawn-time shell config: an env that differs from the running\n\t\t// session's (e.g. a spawn hook rewriting it per command) requires a fresh shell.\n\t\tif (this.child && this.childEnv && !shallowEnvEquals(this.childEnv, resolvedEnv)) {\n\t\t\tthis.killChild();\n\t\t}\n\n\t\t// Re-enter the host-requested cwd only when it CHANGES between calls; an unchanged\n\t\t// request preserves the agent's own in-session `cd` (that persistence is the feature).\n\t\tlet cdTo: string | null = null;\n\t\tif (!this.child) {\n\t\t\tthis.spawnChild(cwd, resolvedEnv);\n\t\t} else if (this.lastRequestedCwd !== cwd) {\n\t\t\tcdTo = cwd;\n\t\t}\n\t\tthis.lastRequestedCwd = cwd;\n\n\t\tconst child = this.child;\n\t\tif (!child?.stdin || !child.stdout || !child.stderr) {\n\t\t\tthis.killChild();\n\t\t\tthrow new Error(`Failed to start ${this.kind} session`);\n\t\t}\n\n\t\tconst nonce = randomBytes(8).toString(\"hex\");\n\t\tconst wire =\n\t\t\tthis.kind === \"powershell\" ? buildPowerShellWire(command, nonce, cdTo) : buildBashWire(command, nonce, cdTo);\n\t\tconst sentinelPrefix = Buffer.from(`\\n\\x1e${nonce}:`, \"latin1\");\n\n\t\tthis.setLoopRef(true);\n\t\ttry {\n\t\t\treturn await new Promise<{ exitCode: number | null }>((resolve, reject) => {\n\t\t\t\tlet settled = false;\n\t\t\t\tlet pending: Buffer = Buffer.alloc(0);\n\t\t\t\tlet timeoutTimer: NodeJS.Timeout | undefined;\n\n\t\t\t\tconst silenceWatchdog =\n\t\t\t\t\ttimeoutSeconds === undefined && silenceMs !== undefined && silenceMs > 0\n\t\t\t\t\t\t? createSilenceWatchdog({\n\t\t\t\t\t\t\t\tsilenceMs,\n\t\t\t\t\t\t\t\tonSilence: () => {\n\t\t\t\t\t\t\t\t\tthis.killChild();\n\t\t\t\t\t\t\t\t\tsettle(() => reject(new Error(`silence:${silenceMs / 1000}`)));\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t: undefined;\n\n\t\t\t\tconst settle = (finish: () => void) => {\n\t\t\t\t\tif (settled) return;\n\t\t\t\t\tsettled = true;\n\t\t\t\t\tif (timeoutTimer) clearTimeout(timeoutTimer);\n\t\t\t\t\tsilenceWatchdog?.disarm();\n\t\t\t\t\tif (signal) signal.removeEventListener(\"abort\", onAbort);\n\t\t\t\t\tthis.activeExec = null;\n\t\t\t\t\tfinish();\n\t\t\t\t};\n\n\t\t\t\tconst onAbort = () => {\n\t\t\t\t\tthis.killChild();\n\t\t\t\t\tsettle(() => reject(new Error(\"aborted\")));\n\t\t\t\t};\n\n\t\t\t\tconst emitPending = (upTo: number) => {\n\t\t\t\t\tif (upTo <= 0) return;\n\t\t\t\t\tonData(pending.subarray(0, upTo));\n\t\t\t\t\tpending = pending.subarray(upTo);\n\t\t\t\t};\n\n\t\t\t\tthis.activeExec = {\n\t\t\t\t\tonStdout: (data) => {\n\t\t\t\t\t\tsilenceWatchdog?.touch();\n\t\t\t\t\t\tpending = pending.length === 0 ? data : Buffer.concat([pending, data]);\n\t\t\t\t\t\tconst prefixIndex = pending.indexOf(sentinelPrefix);\n\t\t\t\t\t\tif (prefixIndex !== -1) {\n\t\t\t\t\t\t\tconst closeIndex = pending.indexOf(SENTINEL_BYTE, prefixIndex + sentinelPrefix.length);\n\t\t\t\t\t\t\tif (closeIndex !== -1) {\n\t\t\t\t\t\t\t\tconst codeText = pending\n\t\t\t\t\t\t\t\t\t.subarray(prefixIndex + sentinelPrefix.length, closeIndex)\n\t\t\t\t\t\t\t\t\t.toString(\"latin1\");\n\t\t\t\t\t\t\t\temitPending(prefixIndex);\n\t\t\t\t\t\t\t\tconst parsed = Number.parseInt(codeText, 10);\n\t\t\t\t\t\t\t\t// Defer the settle by one microtask turn: with the bare Invoke-Expression\n\t\t\t\t\t\t\t\t// form a native command's stderr now arrives on the session's OWN stderr\n\t\t\t\t\t\t\t\t// pipe (see module doc header) instead of being pre-merged into the same\n\t\t\t\t\t\t\t\t// stdout bytes the sentinel rides on. Node fires already-queued stream\n\t\t\t\t\t\t\t\t// 'data' events in event-loop order; queueing the resolution behind a\n\t\t\t\t\t\t\t\t// microtask guarantees any stderr chunk the kernel delivered alongside (or\n\t\t\t\t\t\t\t\t// just before) this stdout chunk has already run its 'data' handler — and\n\t\t\t\t\t\t\t\t// thus reached `onData` — before the promise settles, so callers never see a\n\t\t\t\t\t\t\t\t// truncated stderr tail immediately after resolution.\n\t\t\t\t\t\t\t\tqueueMicrotask(() => settle(() => resolve({ exitCode: Number.isNaN(parsed) ? null : parsed })));\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// Stream promptly but retain a tail large enough to hold any split sentinel.\n\t\t\t\t\t\temitPending(pending.length - SENTINEL_HOLDBACK_BYTES);\n\t\t\t\t\t},\n\t\t\t\t\tonStderr: (data) => {\n\t\t\t\t\t\t// The command's stderr is merged into stdout at the shell; this pipe only\n\t\t\t\t\t\t// carries the session shell's own diagnostics. Forward for visibility.\n\t\t\t\t\t\tsilenceWatchdog?.touch();\n\t\t\t\t\t\tonData(data);\n\t\t\t\t\t},\n\t\t\t\t\tonChildClose: (code) => {\n\t\t\t\t\t\t// The command terminated the shell itself (e.g. `exit 3`) or the shell\n\t\t\t\t\t\t// crashed: report its exit code like the per-command backend would.\n\t\t\t\t\t\temitPending(pending.length);\n\t\t\t\t\t\tsettle(() => resolve({ exitCode: code }));\n\t\t\t\t\t},\n\t\t\t\t\tfail: (error) => {\n\t\t\t\t\t\tthis.killChild();\n\t\t\t\t\t\tsettle(() => reject(error));\n\t\t\t\t\t},\n\t\t\t\t};\n\n\t\t\t\tif (signal) signal.addEventListener(\"abort\", onAbort, { once: true });\n\t\t\t\tif (timeoutSeconds !== undefined && timeoutSeconds > 0) {\n\t\t\t\t\ttimeoutTimer = setTimeout(() => {\n\t\t\t\t\t\tthis.killChild();\n\t\t\t\t\t\tsettle(() => reject(new Error(`timeout:${timeoutSeconds}`)));\n\t\t\t\t\t}, timeoutSeconds * 1000);\n\t\t\t\t}\n\n\t\t\t\tchild.stdin?.write(wire, (error) => {\n\t\t\t\t\tif (!error) return;\n\t\t\t\t\tthis.killChild();\n\t\t\t\t\tsettle(() => reject(new Error(`Failed to write to ${this.kind} session: ${error.message}`)));\n\t\t\t\t});\n\t\t\t});\n\t\t} finally {\n\t\t\tthis.setLoopRef(false);\n\t\t}\n\t}\n\n\tprivate spawnChild(cwd: string, env: NodeJS.ProcessEnv): void {\n\t\tconst { shell } = getShellConfig(undefined, this.kind);\n\t\tconst args =\n\t\t\tthis.kind === \"powershell\"\n\t\t\t\t? [\n\t\t\t\t\t\t\"-NoLogo\",\n\t\t\t\t\t\t\"-NoProfile\",\n\t\t\t\t\t\t\"-NonInteractive\",\n\t\t\t\t\t\t\"-EncodedCommand\",\n\t\t\t\t\t\tBuffer.from(POWERSHELL_BOOTSTRAP, \"utf16le\").toString(\"base64\"),\n\t\t\t\t\t]\n\t\t\t\t: basename(shell).toLowerCase().includes(\"bash\")\n\t\t\t\t\t? [\"--noprofile\", \"--norc\"]\n\t\t\t\t\t: [];\n\t\tconst child = spawn(shell, args, {\n\t\t\tcwd,\n\t\t\tenv,\n\t\t\tdetached: process.platform !== \"win32\",\n\t\t\tstdio: [\"pipe\", \"pipe\", \"pipe\"],\n\t\t\twindowsHide: true,\n\t\t});\n\t\tif (child.pid) trackDetachedChildPid(child.pid);\n\t\t// Every listener gates on the child still being the session's current one: after a\n\t\t// timeout/abort kill replaced it, the dead shell's late data/close events are stale noise\n\t\t// that must never reach the NEXT command's handlers.\n\t\tchild.stdout?.on(\"data\", (data: Buffer) => {\n\t\t\tif (this.child === child) this.activeExec?.onStdout(data);\n\t\t});\n\t\tchild.stderr?.on(\"data\", (data: Buffer) => {\n\t\t\tif (this.child === child) this.activeExec?.onStderr(data);\n\t\t});\n\t\tchild.on(\"error\", (error) => {\n\t\t\tif (this.child !== child) return;\n\t\t\tthis.clearChild(child);\n\t\t\tthis.activeExec?.fail(error instanceof Error ? error : new Error(String(error)));\n\t\t});\n\t\t// Settle the shell-died path on \"exit\" (process death), not \"close\" (stdio streams ended):\n\t\t// a live detached grandchild that inherited these pipes (e.g. `sleep 30 &` before `exit 3`)\n\t\t// keeps them open indefinitely even though the shell itself is already gone, and Node only\n\t\t// fires \"close\" once every stdio stream has ended. Waiting for \"close\" here would hang for\n\t\t// as long as the grandchild lives. The per-command backend\n\t\t// (waitForChildProcessWithTermination in ../../utils/child-process.ts) faces the identical\n\t\t// hazard and settles on \"exit\" for the same reason.\n\t\t//\n\t\t// \"exit\" can fire before Node has delivered already-buffered stdout/stderr \"data\" events for\n\t\t// bytes the kernel handed over just before the process died (e.g. the sentinel line itself).\n\t\t// Defer the settlement by one setImmediate turn: Node drains the poll phase (which is where\n\t\t// pending stream \"data\" events run) before the check phase (where setImmediate callbacks\n\t\t// run), so by the time this callback executes, every \"data\" event for bytes already received\n\t\t// has already reached onStdout/onStderr, and thus onData, before we resolve/reject. This is\n\t\t// not a hang-fix timer — it never waits on anything and does not run if the grandchild is\n\t\t// gone and \"close\" (or a replacement child) got there first.\n\t\tchild.on(\"exit\", (code) => {\n\t\t\tif (this.child !== child) return;\n\t\t\tsetImmediate(() => {\n\t\t\t\tif (this.child !== child) return;\n\t\t\t\tthis.clearChild(child);\n\t\t\t\tthis.activeExec?.onChildClose(code);\n\t\t\t});\n\t\t});\n\t\t// Kept alongside \"exit\" for the genuine fast-close case (no lingering grandchild): whichever\n\t\t// event reaches its guard first wins and nulls out this.child, making the other a no-op, so\n\t\t// settlement stays idempotent regardless of which fires first or whether both fire.\n\t\tchild.on(\"close\", (code) => {\n\t\t\tif (this.child !== child) return;\n\t\t\tthis.clearChild(child);\n\t\t\tthis.activeExec?.onChildClose(code);\n\t\t});\n\t\tthis.child = child;\n\t\tthis.childEnv = env;\n\t\tthis.lastRequestedCwd = cwd;\n\t}\n\n\tprivate clearChild(child: ChildProcess): void {\n\t\tif (child.pid) untrackDetachedChildPid(child.pid);\n\t\tthis.child = null;\n\t\tthis.childEnv = null;\n\t\tthis.lastRequestedCwd = null;\n\t}\n\n\tprivate killChild(): void {\n\t\tconst child = this.child;\n\t\tif (!child) return;\n\t\tthis.clearChild(child);\n\t\tif (child.pid) killProcessTree(child.pid);\n\t}\n\n\t/**\n\t * An idle session must not keep the Node event loop alive (one-shot modes have to exit\n\t * naturally); during a command the child and its pipes are re-referenced so the loop stays\n\t * alive even without an armed timer.\n\t */\n\tprivate setLoopRef(active: boolean): void {\n\t\tconst child = this.child;\n\t\tif (!child) return;\n\t\t// Stdio pipes are Sockets at runtime (ref/unref exist) but are typed as plain streams.\n\t\tconst streams = [child.stdin, child.stdout, child.stderr] as unknown as Array<{\n\t\t\tref?: () => void;\n\t\t\tunref?: () => void;\n\t\t} | null>;\n\t\tif (active) {\n\t\t\tchild.ref();\n\t\t\tfor (const stream of streams) stream?.ref?.();\n\t\t} else {\n\t\t\tchild.unref();\n\t\t\tfor (const stream of streams) stream?.unref?.();\n\t\t}\n\t}\n}\n\nconst shellSessions = new Map<string, PersistentShellSession>();\nlet exitHookInstalled = false;\n\nfunction installExitHook(): void {\n\tif (exitHookInstalled) return;\n\texitHookInstalled = true;\n\t// Detached sessions outlive the parent on clean exits unless explicitly killed; shutdown\n\t// signals are already covered by the tracked-detached-children mechanism.\n\tprocess.on(\"exit\", () => {\n\t\tfor (const session of shellSessions.values()) {\n\t\t\tsession.killForProcessExit();\n\t\t}\n\t});\n}\n\n/** Get or lazily create the persistent session for a key. A kind change replaces the session. */\nexport function acquirePersistentShellSession(key: string, kind: PlatformShellToolName): PersistentShellSession {\n\tinstallExitHook();\n\tconst existing = shellSessions.get(key);\n\tif (existing && existing.sessionKind === kind) return existing;\n\texisting?.dispose();\n\tconst session = new PersistentShellSession(key, kind);\n\tshellSessions.set(key, session);\n\treturn session;\n}\n\n/** Kill and forget a session (agent teardown). Safe to call for keys that never spawned. */\nexport function disposePersistentShellSession(key: string): void {\n\tconst session = shellSessions.get(key);\n\tif (!session) return;\n\tshellSessions.delete(key);\n\tsession.dispose();\n}\n"]}
@@ -9,6 +9,7 @@ declare const taskStepsSchema: Type.TObject<{
9
9
  status: Type.TOptional<Type.TUnion<[Type.TLiteral<"pending">, Type.TLiteral<"in_progress">, Type.TLiteral<"completed">, Type.TLiteral<"blocked">, Type.TLiteral<"cancelled">]>>;
10
10
  priority: Type.TOptional<Type.TUnion<[Type.TLiteral<"low">, Type.TLiteral<"normal">, Type.TLiteral<"high">]>>;
11
11
  owner: Type.TOptional<Type.TString>;
12
+ requirementIds: Type.TOptional<Type.TArray<Type.TString>>;
12
13
  note: Type.TOptional<Type.TString>;
13
14
  evidence: Type.TOptional<Type.TArray<Type.TString>>;
14
15
  }>>>;
@@ -18,6 +19,7 @@ declare const taskStepsSchema: Type.TObject<{
18
19
  status: Type.TOptional<Type.TUnion<[Type.TLiteral<"pending">, Type.TLiteral<"in_progress">, Type.TLiteral<"completed">, Type.TLiteral<"blocked">, Type.TLiteral<"cancelled">]>>;
19
20
  priority: Type.TOptional<Type.TUnion<[Type.TLiteral<"low">, Type.TLiteral<"normal">, Type.TLiteral<"high">]>>;
20
21
  owner: Type.TOptional<Type.TString>;
22
+ requirementIds: Type.TOptional<Type.TArray<Type.TString>>;
21
23
  note: Type.TOptional<Type.TString>;
22
24
  evidence: Type.TOptional<Type.TArray<Type.TString>>;
23
25
  clearCompleted: Type.TOptional<Type.TBoolean>;
@@ -35,6 +37,10 @@ export interface TaskStepsToolDetails {
35
37
  openStepCount?: number;
36
38
  verificationNudgeNeeded?: boolean;
37
39
  showCompleted?: boolean;
40
+ /** Set when `add` was a no-op because an open step already carries this content. */
41
+ duplicateOfStepId?: string;
42
+ /** Step ids silently demoted to pending because another step became active in this call. */
43
+ demotedStepIds?: readonly string[];
38
44
  }
39
45
  export interface TaskStepsToolDependencies {
40
46
  getTaskStepsState: () => TaskStepsState | undefined;
@@ -1 +1 @@
1
- {"version":3,"file":"task-steps.d.ts","sourceRoot":"","sources":["../../../src/core/tools/task-steps.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,MAAM,EAAE,IAAI,EAAE,MAAM,SAAS,CAAC;AAC5C,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,wBAAwB,CAAC;AAC7D,OAAO,EASN,KAAK,cAAc,EAEnB,MAAM,wBAAwB,CAAC;AA2BhC,QAAA,MAAM,eAAe;;;;;;;;;;;;;;;;;;;;;;EAuCpB,CAAC;AAEF,MAAM,MAAM,kBAAkB,GAAG,MAAM,CAAC,OAAO,eAAe,CAAC,CAAC;AAChE,MAAM,MAAM,eAAe,GAAG,kBAAkB,CAAC,QAAQ,CAAC,CAAC;AAE3D,MAAM,WAAW,oBAAoB;IACpC,MAAM,EAAE,eAAe,CAAC;IACxB,OAAO,EAAE,OAAO,CAAC;IACjB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,KAAK,CAAC,EAAE,cAAc,CAAC;IACvB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,uBAAuB,CAAC,EAAE,OAAO,CAAC;IAClC,aAAa,CAAC,EAAE,OAAO,CAAC;CACxB;AAED,MAAM,WAAW,yBAAyB;IACzC,iBAAiB,EAAE,MAAM,cAAc,GAAG,SAAS,CAAC;IACpD,kBAAkB,EAAE,CAAC,KAAK,EAAE,cAAc,KAAK,IAAI,CAAC;IACpD,GAAG,CAAC,EAAE,MAAM,MAAM,CAAC;CACnB;AAkCD,wBAAgB,6BAA6B,CAAC,IAAI,EAAE,yBAAyB,GAAG,cAAc,CA4F7F","sourcesContent":["import { type Static, Type } from \"typebox\";\nimport type { ToolDefinition } from \"../extensions/types.ts\";\nimport {\n\taddTaskStep,\n\tclearTaskSteps,\n\tcompactTaskSteps,\n\tcreateTaskStepsState,\n\tformatTaskSteps,\n\tMAX_TASK_STEPS,\n\tsetTaskSteps,\n\ttype TaskStepInput,\n\ttype TaskStepsState,\n\tupdateTaskStep,\n} from \"../tasks/task-state.ts\";\n\nconst statusSchema = Type.Union([\n\tType.Literal(\"pending\"),\n\tType.Literal(\"in_progress\"),\n\tType.Literal(\"completed\"),\n\tType.Literal(\"blocked\"),\n\tType.Literal(\"cancelled\"),\n]);\n\nconst prioritySchema = Type.Union([Type.Literal(\"low\"), Type.Literal(\"normal\"), Type.Literal(\"high\")]);\n\nconst stepInputSchema = Type.Object(\n\t{\n\t\tcontent: Type.String({ minLength: 1, maxLength: 2_000, description: \"Imperative task step text.\" }),\n\t\tactiveForm: Type.Optional(\n\t\t\tType.String({ minLength: 1, maxLength: 2_000, description: \"Short present-progress label for active UI.\" }),\n\t\t),\n\t\tstatus: Type.Optional(statusSchema),\n\t\tpriority: Type.Optional(prioritySchema),\n\t\towner: Type.Optional(Type.String({ maxLength: 200 })),\n\t\tnote: Type.Optional(Type.String({ maxLength: 4_000 })),\n\t\tevidence: Type.Optional(Type.Array(Type.String({ minLength: 1, maxLength: 2_000 }), { maxItems: 32 })),\n\t},\n\t{ additionalProperties: false },\n);\n\nconst taskStepsSchema = Type.Object(\n\t{\n\t\taction: Type.Union(\n\t\t\t[\n\t\t\t\tType.Literal(\"set\"),\n\t\t\t\tType.Literal(\"add\"),\n\t\t\t\tType.Literal(\"update\"),\n\t\t\t\tType.Literal(\"list\"),\n\t\t\t\tType.Literal(\"clear\"),\n\t\t\t\tType.Literal(\"compact\"),\n\t\t\t\tType.Literal(\"intake\"),\n\t\t\t],\n\t\t\t{ description: \"Checklist action. Use list to read without mutation.\" },\n\t\t),\n\t\tsteps: Type.Optional(\n\t\t\tType.Array(stepInputSchema, {\n\t\t\t\tmaxItems: MAX_TASK_STEPS,\n\t\t\t\tdescription: \"Complete replacement list for set/intake. Intake preserves every supplied item in order.\",\n\t\t\t}),\n\t\t),\n\t\tid: Type.Optional(\n\t\t\tType.String({\n\t\t\t\tdescription: \"For update: current/active, exact step id, unique id prefix, or unique content selector.\",\n\t\t\t}),\n\t\t),\n\t\tcontent: Type.Optional(Type.String({ minLength: 1, maxLength: 2_000 })),\n\t\tactiveForm: Type.Optional(Type.String({ maxLength: 2_000 })),\n\t\tstatus: Type.Optional(statusSchema),\n\t\tpriority: Type.Optional(prioritySchema),\n\t\towner: Type.Optional(Type.String({ maxLength: 200 })),\n\t\tnote: Type.Optional(Type.String({ maxLength: 4_000 })),\n\t\tevidence: Type.Optional(Type.Array(Type.String({ minLength: 1, maxLength: 2_000 }), { maxItems: 32 })),\n\t\tclearCompleted: Type.Optional(\n\t\t\tType.Boolean({ description: \"For list: compact completed and cancelled steps before rendering.\" }),\n\t\t),\n\t\tshowCompleted: Type.Optional(Type.Boolean({ description: \"Include completed and cancelled steps in output.\" })),\n\t\tmaxItems: Type.Optional(Type.Integer({ minimum: 1, maximum: MAX_TASK_STEPS })),\n\t},\n\t{ additionalProperties: false },\n);\n\nexport type TaskStepsToolInput = Static<typeof taskStepsSchema>;\nexport type TaskStepsAction = TaskStepsToolInput[\"action\"];\n\nexport interface TaskStepsToolDetails {\n\taction: TaskStepsAction;\n\tapplied: boolean;\n\terror?: string;\n\tstate?: TaskStepsState;\n\tstepCount?: number;\n\topenStepCount?: number;\n\tverificationNudgeNeeded?: boolean;\n\tshowCompleted?: boolean;\n}\n\nexport interface TaskStepsToolDependencies {\n\tgetTaskStepsState: () => TaskStepsState | undefined;\n\tsaveTaskStepsState: (state: TaskStepsState) => void;\n\tnow?: () => string;\n}\n\nfunction toTaskStepInput(input: TaskStepsToolInput): TaskStepInput {\n\treturn {\n\t\tcontent: input.content ?? \"\",\n\t\tactiveForm: input.activeForm,\n\t\tstatus: input.status,\n\t\tpriority: input.priority,\n\t\towner: input.owner,\n\t\tnote: input.note,\n\t\tevidence: input.evidence,\n\t};\n}\n\nfunction counts(\n\tstate: TaskStepsState,\n): Pick<TaskStepsToolDetails, \"stepCount\" | \"openStepCount\" | \"verificationNudgeNeeded\"> {\n\tconst openStepCount = state.steps.filter(\n\t\t(step) => step.status !== \"completed\" && step.status !== \"cancelled\",\n\t).length;\n\treturn {\n\t\tstepCount: state.steps.length,\n\t\topenStepCount,\n\t\tverificationNudgeNeeded: state.steps.some((step) => step.status === \"completed\" && step.evidence.length === 0),\n\t};\n}\n\nfunction errorResult(action: TaskStepsAction, error: string, state?: TaskStepsState) {\n\treturn {\n\t\tcontent: [{ type: \"text\" as const, text: `task_steps ${action} failed: ${error}` }],\n\t\tdetails: { action, applied: false, error, state, ...(state ? counts(state) : {}) } satisfies TaskStepsToolDetails,\n\t};\n}\n\nexport function createTaskStepsToolDefinition(deps: TaskStepsToolDependencies): ToolDefinition {\n\tconst now = deps.now ?? (() => new Date().toISOString());\n\treturn {\n\t\tname: \"task_steps\",\n\t\tlabel: \"Task Steps\",\n\t\tdescription:\n\t\t\t\"Maintain the current session's native ordered checklist for multi-step work. Supports pending, in_progress, completed, blocked, and cancelled steps with notes and evidence. State is isolated to and persisted with the active session; use native goal for durable outcome requirements and native delegate/delegate_status for background workers.\",\n\t\tpromptSnippet: \"Track and drain multi-step work with a native session checklist.\",\n\t\tpromptGuidelines: [\n\t\t\t\"Use task_steps for complex work, explicit task-tracking requests, and harness/self-improvement work; keep exactly one step in_progress while actively working.\",\n\t\t\t\"Always address the first open task step before unrelated work: start it, complete/block/cancel it with evidence, ask one clarifying question, or explicitly defer or reorder it.\",\n\t\t\t\"Mark steps completed as soon as evidence is gathered, and attach concise evidence or a blocker reason through update.\",\n\t\t\t\"Use action=intake with a complete steps array when preserving a raw multi-item dump; retain every item and do not silently drop entries.\",\n\t\t\t\"Drain task_steps before final responses: leave no stale in_progress step, and explicitly discuss or defer remaining pending or blocked work.\",\n\t\t\t\"Use goal for the durable goal ledger and delegate/delegate_status for worker lanes; do not emulate background execution inside task_steps.\",\n\t\t],\n\t\tparameters: taskStepsSchema,\n\t\tasync execute(_toolCallId, input: TaskStepsToolInput) {\n\t\t\tconst timestamp = now();\n\t\t\tconst current = deps.getTaskStepsState();\n\t\t\tlet state = current ?? createTaskStepsState(timestamp);\n\t\t\ttry {\n\t\t\t\tswitch (input.action) {\n\t\t\t\t\tcase \"set\":\n\t\t\t\t\t\tif (!input.steps) return errorResult(input.action, \"set requires steps[].\", current);\n\t\t\t\t\t\tstate = setTaskSteps(state, input.steps, timestamp);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"intake\":\n\t\t\t\t\t\tif (!input.steps)\n\t\t\t\t\t\t\treturn errorResult(input.action, \"intake requires a complete steps[] list.\", current);\n\t\t\t\t\t\tstate = setTaskSteps(state, input.steps, timestamp);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"add\":\n\t\t\t\t\t\tstate = addTaskStep(state, toTaskStepInput(input), timestamp);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"update\":\n\t\t\t\t\t\tif (!input.id?.trim())\n\t\t\t\t\t\t\treturn errorResult(input.action, \"update requires id or a unique selector.\", current);\n\t\t\t\t\t\tstate = updateTaskStep(\n\t\t\t\t\t\t\tstate,\n\t\t\t\t\t\t\tinput.id,\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tcontent: input.content,\n\t\t\t\t\t\t\t\tactiveForm: input.activeForm,\n\t\t\t\t\t\t\t\tstatus: input.status,\n\t\t\t\t\t\t\t\tpriority: input.priority,\n\t\t\t\t\t\t\t\towner: input.owner,\n\t\t\t\t\t\t\t\tnote: input.note,\n\t\t\t\t\t\t\t\tevidence: input.evidence,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\ttimestamp,\n\t\t\t\t\t\t);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"clear\":\n\t\t\t\t\t\tstate = clearTaskSteps(state, timestamp);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"compact\":\n\t\t\t\t\t\tstate = compactTaskSteps(state, timestamp);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"list\":\n\t\t\t\t\t\tif (input.clearCompleted) state = compactTaskSteps(state, timestamp);\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tconst mutated = input.action !== \"list\" || input.clearCompleted === true;\n\t\t\t\tif (mutated) deps.saveTaskStepsState(state);\n\t\t\t\treturn {\n\t\t\t\t\tcontent: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ttype: \"text\" as const,\n\t\t\t\t\t\t\ttext: `${input.action === \"list\" ? \"\" : `task_steps ${input.action} recorded.\\n`}${formatTaskSteps(\n\t\t\t\t\t\t\t\tstate,\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tincludeTerminal: input.showCompleted,\n\t\t\t\t\t\t\t\t\tmaxItems: input.maxItems,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t)}`,\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t\t\tdetails: {\n\t\t\t\t\t\taction: input.action,\n\t\t\t\t\t\tapplied: true,\n\t\t\t\t\t\tstate,\n\t\t\t\t\t\t...counts(state),\n\t\t\t\t\t\tshowCompleted: input.showCompleted,\n\t\t\t\t\t} satisfies TaskStepsToolDetails,\n\t\t\t\t};\n\t\t\t} catch (error) {\n\t\t\t\treturn errorResult(input.action, error instanceof Error ? error.message : String(error), current);\n\t\t\t}\n\t\t},\n\t};\n}\n"]}
1
+ {"version":3,"file":"task-steps.d.ts","sourceRoot":"","sources":["../../../src/core/tools/task-steps.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,MAAM,EAAE,IAAI,EAAE,MAAM,SAAS,CAAC;AAC5C,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,wBAAwB,CAAC;AAC7D,OAAO,EAaN,KAAK,cAAc,EAEnB,MAAM,wBAAwB,CAAC;AAuChC,QAAA,MAAM,eAAe;;;;;;;;;;;;;;;;;;;;;;;;EA6CpB,CAAC;AAEF,MAAM,MAAM,kBAAkB,GAAG,MAAM,CAAC,OAAO,eAAe,CAAC,CAAC;AAChE,MAAM,MAAM,eAAe,GAAG,kBAAkB,CAAC,QAAQ,CAAC,CAAC;AAE3D,MAAM,WAAW,oBAAoB;IACpC,MAAM,EAAE,eAAe,CAAC;IACxB,OAAO,EAAE,OAAO,CAAC;IACjB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,KAAK,CAAC,EAAE,cAAc,CAAC;IACvB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,uBAAuB,CAAC,EAAE,OAAO,CAAC;IAClC,aAAa,CAAC,EAAE,OAAO,CAAC;IACxB,oFAAoF;IACpF,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAC3B,4FAA4F;IAC5F,cAAc,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;CACnC;AAED,MAAM,WAAW,yBAAyB;IACzC,iBAAiB,EAAE,MAAM,cAAc,GAAG,SAAS,CAAC;IACpD,kBAAkB,EAAE,CAAC,KAAK,EAAE,cAAc,KAAK,IAAI,CAAC;IACpD,GAAG,CAAC,EAAE,MAAM,MAAM,CAAC;CACnB;AAmID,wBAAgB,6BAA6B,CAAC,IAAI,EAAE,yBAAyB,GAAG,cAAc,CAiK7F","sourcesContent":["import { type Static, Type } from \"typebox\";\nimport type { ToolDefinition } from \"../extensions/types.ts\";\nimport {\n\taddTaskStep,\n\tclearTaskSteps,\n\tcompactTaskSteps,\n\tcreateTaskStepsState,\n\tfindOpenDuplicateStep,\n\tformatTaskSteps,\n\thasUnverifiedCompletedStep,\n\tMAX_TASK_STEPS,\n\tresolveTaskStepSelector,\n\tsetTaskSteps,\n\ttype TaskStep,\n\ttype TaskStepInput,\n\ttype TaskStepsState,\n\tupdateTaskStep,\n} from \"../tasks/task-state.ts\";\nimport {\n\temptyOrchestrationCall,\n\tOrchestrationPanelComponent,\n\ttype OrchestrationPanelModel,\n\ttaskStepPanelRow,\n} from \"./orchestration-panel.ts\";\n\nconst statusSchema = Type.Union([\n\tType.Literal(\"pending\"),\n\tType.Literal(\"in_progress\"),\n\tType.Literal(\"completed\"),\n\tType.Literal(\"blocked\"),\n\tType.Literal(\"cancelled\"),\n]);\n\nconst prioritySchema = Type.Union([Type.Literal(\"low\"), Type.Literal(\"normal\"), Type.Literal(\"high\")]);\n\nconst stepInputSchema = Type.Object(\n\t{\n\t\tcontent: Type.String({ minLength: 1, maxLength: 2_000, description: \"Imperative task step text.\" }),\n\t\tactiveForm: Type.Optional(\n\t\t\tType.String({ minLength: 1, maxLength: 2_000, description: \"Short present-progress label for active UI.\" }),\n\t\t),\n\t\tstatus: Type.Optional(statusSchema),\n\t\tpriority: Type.Optional(prioritySchema),\n\t\towner: Type.Optional(Type.String({ maxLength: 200 })),\n\t\trequirementIds: Type.Optional(\n\t\t\tType.Array(Type.String({ minLength: 1, maxLength: 200 }), {\n\t\t\t\tmaxItems: 32,\n\t\t\t\tdescription: \"Goal requirement ids this foreground step advances.\",\n\t\t\t}),\n\t\t),\n\t\tnote: Type.Optional(Type.String({ maxLength: 4_000 })),\n\t\tevidence: Type.Optional(Type.Array(Type.String({ minLength: 1, maxLength: 2_000 }), { maxItems: 32 })),\n\t},\n\t{ additionalProperties: false },\n);\n\nconst taskStepsSchema = Type.Object(\n\t{\n\t\taction: Type.Union(\n\t\t\t[\n\t\t\t\tType.Literal(\"set\"),\n\t\t\t\tType.Literal(\"add\"),\n\t\t\t\tType.Literal(\"update\"),\n\t\t\t\tType.Literal(\"list\"),\n\t\t\t\tType.Literal(\"clear\"),\n\t\t\t\tType.Literal(\"compact\"),\n\t\t\t\tType.Literal(\"intake\"),\n\t\t\t],\n\t\t\t{ description: \"Checklist action. Use list to read without mutation.\" },\n\t\t),\n\t\tsteps: Type.Optional(\n\t\t\tType.Array(stepInputSchema, {\n\t\t\t\tmaxItems: MAX_TASK_STEPS,\n\t\t\t\tdescription: \"Complete replacement list for set/intake. Intake preserves every supplied item in order.\",\n\t\t\t}),\n\t\t),\n\t\tid: Type.Optional(\n\t\t\tType.String({\n\t\t\t\tdescription: \"For update: current/active, exact step id, unique id prefix, or unique content selector.\",\n\t\t\t}),\n\t\t),\n\t\tcontent: Type.Optional(Type.String({ minLength: 1, maxLength: 2_000 })),\n\t\tactiveForm: Type.Optional(Type.String({ maxLength: 2_000 })),\n\t\tstatus: Type.Optional(statusSchema),\n\t\tpriority: Type.Optional(prioritySchema),\n\t\towner: Type.Optional(Type.String({ maxLength: 200 })),\n\t\trequirementIds: Type.Optional(\n\t\t\tType.Array(Type.String({ minLength: 1, maxLength: 200 }), {\n\t\t\t\tmaxItems: 32,\n\t\t\t\tdescription: \"Goal requirement ids this foreground step advances; [] clears existing links.\",\n\t\t\t}),\n\t\t),\n\t\tnote: Type.Optional(Type.String({ maxLength: 4_000 })),\n\t\tevidence: Type.Optional(Type.Array(Type.String({ minLength: 1, maxLength: 2_000 }), { maxItems: 32 })),\n\t\tclearCompleted: Type.Optional(\n\t\t\tType.Boolean({ description: \"For list: compact completed and cancelled steps before rendering.\" }),\n\t\t),\n\t\tshowCompleted: Type.Optional(Type.Boolean({ description: \"Include completed and cancelled steps in output.\" })),\n\t\tmaxItems: Type.Optional(Type.Integer({ minimum: 1, maximum: MAX_TASK_STEPS })),\n\t},\n\t{ additionalProperties: false },\n);\n\nexport type TaskStepsToolInput = Static<typeof taskStepsSchema>;\nexport type TaskStepsAction = TaskStepsToolInput[\"action\"];\n\nexport interface TaskStepsToolDetails {\n\taction: TaskStepsAction;\n\tapplied: boolean;\n\terror?: string;\n\tstate?: TaskStepsState;\n\tstepCount?: number;\n\topenStepCount?: number;\n\tverificationNudgeNeeded?: boolean;\n\tshowCompleted?: boolean;\n\t/** Set when `add` was a no-op because an open step already carries this content. */\n\tduplicateOfStepId?: string;\n\t/** Step ids silently demoted to pending because another step became active in this call. */\n\tdemotedStepIds?: readonly string[];\n}\n\nexport interface TaskStepsToolDependencies {\n\tgetTaskStepsState: () => TaskStepsState | undefined;\n\tsaveTaskStepsState: (state: TaskStepsState) => void;\n\tnow?: () => string;\n}\n\nfunction toTaskStepInput(input: TaskStepsToolInput): TaskStepInput {\n\treturn {\n\t\tcontent: input.content ?? \"\",\n\t\tactiveForm: input.activeForm,\n\t\tstatus: input.status,\n\t\tpriority: input.priority,\n\t\towner: input.owner,\n\t\trequirementIds: input.requirementIds,\n\t\tnote: input.note,\n\t\tevidence: input.evidence,\n\t};\n}\n\nfunction counts(\n\tstate: TaskStepsState,\n): Pick<TaskStepsToolDetails, \"stepCount\" | \"openStepCount\" | \"verificationNudgeNeeded\"> {\n\tconst openStepCount = state.steps.filter(\n\t\t(step) => step.status !== \"completed\" && step.status !== \"cancelled\",\n\t).length;\n\treturn {\n\t\tstepCount: state.steps.length,\n\t\topenStepCount,\n\t\tverificationNudgeNeeded: hasUnverifiedCompletedStep(state),\n\t};\n}\n\n/** Ids (from `resultSteps`, index-aligned with `inputs`) whose status was set explicitly by the caller. */\nfunction explicitStatusStepIds(inputs: readonly TaskStepInput[], resultSteps: readonly TaskStep[]): Set<string> {\n\tconst ids = new Set<string>();\n\tinputs.forEach((stepInput, index) => {\n\t\tif (stepInput.status !== undefined) {\n\t\t\tconst id = resultSteps[index]?.id;\n\t\t\tif (id) ids.add(id);\n\t\t}\n\t});\n\treturn ids;\n}\n\n/**\n * Steps that were in_progress before this call and are pending after, excluding any step whose\n * new status was set explicitly by the caller (an explicit change is not a \"silent\" demotion).\n */\nfunction computeDemotedStepIds(\n\tbefore: TaskStepsState,\n\tafter: TaskStepsState,\n\texcludeIds: ReadonlySet<string>,\n): string[] {\n\tconst beforeActiveIds = new Set(before.steps.filter((step) => step.status === \"in_progress\").map((step) => step.id));\n\treturn after.steps\n\t\t.filter((step) => beforeActiveIds.has(step.id) && step.status === \"pending\" && !excludeIds.has(step.id))\n\t\t.map((step) => step.id);\n}\n\nfunction errorResult(action: TaskStepsAction, error: string, state?: TaskStepsState) {\n\treturn {\n\t\tcontent: [{ type: \"text\" as const, text: `task_steps ${action} failed: ${error}` }],\n\t\tdetails: { action, applied: false, error, state, ...(state ? counts(state) : {}) } satisfies TaskStepsToolDetails,\n\t};\n}\n\nfunction taskStepsPanelModel(details: TaskStepsToolDetails, expanded: boolean): OrchestrationPanelModel {\n\tconst state = details.state;\n\tif (!state) {\n\t\treturn {\n\t\t\tlabel: \"task steps\",\n\t\t\taction: details.action,\n\t\t\tstatus: details.error ? \"error\" : \"idle\",\n\t\t\temptyText: details.error ?? \"No checklist state.\",\n\t\t};\n\t}\n\tconst active = state.steps.filter((step) => step.status === \"in_progress\");\n\tconst blocked = state.steps.filter((step) => step.status === \"blocked\");\n\tconst pending = state.steps.filter((step) => step.status === \"pending\");\n\tconst completed = state.steps.filter((step) => step.status === \"completed\");\n\tconst cancelled = state.steps.filter((step) => step.status === \"cancelled\");\n\tconst open = [...active, ...blocked, ...pending];\n\tconst terminal = details.showCompleted ? [...completed, ...cancelled] : [];\n\tconst candidates = [...open, ...terminal];\n\tconst limit = expanded ? 24 : 8;\n\tconst rows = candidates.slice(0, limit).map(taskStepPanelRow);\n\tconst archivedDone = state.archive.completed + state.archive.cancelled;\n\tconst done = completed.length + state.archive.completed;\n\tconst summary = [\n\t\tactive.length ? `${active.length} working` : undefined,\n\t\t`${open.length} open`,\n\t\t`${done} done`,\n\t\tblocked.length ? `${blocked.length} blocked` : undefined,\n\t\tarchivedDone ? `${archivedDone} archived` : undefined,\n\t].filter((value): value is string => value !== undefined);\n\tconst notices = [];\n\tif (!details.showCompleted && completed.length + cancelled.length > 0) {\n\t\tnotices.push({\n\t\t\tstatus: \"info\" as const,\n\t\t\ttext: `${completed.length + cancelled.length} finished step${completed.length + cancelled.length === 1 ? \"\" : \"s\"} hidden`,\n\t\t});\n\t}\n\tif (details.duplicateOfStepId) {\n\t\tnotices.push({ status: \"info\" as const, text: \"Duplicate open step ignored.\" });\n\t}\n\tif (details.demotedStepIds?.length) {\n\t\tnotices.push({\n\t\t\tstatus: \"info\" as const,\n\t\t\ttext: `${details.demotedStepIds.length} previous working step${details.demotedStepIds.length === 1 ? \"\" : \"s\"} returned to pending.`,\n\t\t});\n\t}\n\tif (details.verificationNudgeNeeded) {\n\t\tnotices.push({ status: \"warning\" as const, text: \"Completed work still needs attached evidence.\" });\n\t}\n\tconst status = details.error\n\t\t? \"error\"\n\t\t: blocked.length > 0\n\t\t\t? \"warning\"\n\t\t\t: active.length > 0\n\t\t\t\t? \"running\"\n\t\t\t\t: open.length === 0 && state.steps.length > 0\n\t\t\t\t\t? \"success\"\n\t\t\t\t\t: \"idle\";\n\treturn {\n\t\tlabel: \"task steps\",\n\t\taction: details.action,\n\t\tstatus,\n\t\tsummary,\n\t\trows,\n\t\tnotices,\n\t\temptyText: state.steps.length === 0 ? \"No tracked steps.\" : \"All open steps are done.\",\n\t\thiddenRowCount: Math.max(0, candidates.length - rows.length),\n\t};\n}\n\nexport function createTaskStepsToolDefinition(deps: TaskStepsToolDependencies): ToolDefinition {\n\tconst now = deps.now ?? (() => new Date().toISOString());\n\treturn {\n\t\tname: \"task_steps\",\n\t\tlabel: \"Task Steps\",\n\t\tdescription:\n\t\t\t\"Maintain the current session's native ordered checklist for multi-step work. Supports pending, in_progress, completed, blocked, and cancelled steps with notes and evidence. State is isolated to and persisted with the active session; use native goal for durable outcome requirements and native delegate/delegate_status for background workers.\",\n\t\tpromptSnippet: \"Track and drain multi-step work with a native session checklist.\",\n\t\tpromptGuidelines: [\n\t\t\t\"Use task_steps for complex work, explicit task-tracking requests, and harness/self-improvement work; keep exactly one step in_progress while actively working.\",\n\t\t\t\"Always address the first open task step before unrelated work: start it, complete/block/cancel it with evidence, ask one clarifying question, or explicitly defer or reorder it.\",\n\t\t\t\"Mark steps completed as soon as evidence is gathered, and attach concise evidence or a blocker reason through update.\",\n\t\t\t\"Use action=intake with a complete steps array when preserving a raw multi-item dump; retain every item and do not silently drop entries.\",\n\t\t\t\"When a goal is active, set requirementIds on each step that advances a goal requirement; do not rely on repeating requirement text.\",\n\t\t\t\"Drain task_steps before final responses: leave no stale in_progress step, and explicitly discuss or defer remaining pending or blocked work.\",\n\t\t\t\"Use goal for the durable goal ledger and delegate/delegate_status for worker lanes; do not emulate background execution inside task_steps.\",\n\t\t],\n\t\tparameters: taskStepsSchema,\n\t\trenderShell: \"self\",\n\t\trenderCall() {\n\t\t\treturn emptyOrchestrationCall();\n\t\t},\n\t\trenderResult(result, { expanded, isPartial }, theme) {\n\t\t\tif (isPartial) {\n\t\t\t\treturn new OrchestrationPanelComponent(theme, {\n\t\t\t\t\tlabel: \"task steps\",\n\t\t\t\t\taction: \"updating\",\n\t\t\t\t\tstatus: \"running\",\n\t\t\t\t});\n\t\t\t}\n\t\t\tconst details = result.details as TaskStepsToolDetails | undefined;\n\t\t\tif (!details) {\n\t\t\t\treturn new OrchestrationPanelComponent(theme, {\n\t\t\t\t\tlabel: \"task steps\",\n\t\t\t\t\tstatus: \"error\",\n\t\t\t\t\temptyText: \"No task-step details were returned.\",\n\t\t\t\t});\n\t\t\t}\n\t\t\treturn new OrchestrationPanelComponent(theme, taskStepsPanelModel(details, expanded), expanded);\n\t\t},\n\t\tasync execute(_toolCallId, input: TaskStepsToolInput) {\n\t\t\tconst timestamp = now();\n\t\t\tconst current = deps.getTaskStepsState();\n\t\t\tconst before = current ?? createTaskStepsState(timestamp);\n\t\t\tlet state = before;\n\t\t\tlet duplicateStepId: string | undefined;\n\t\t\tlet demotedStepIds: readonly string[] = [];\n\t\t\ttry {\n\t\t\t\tswitch (input.action) {\n\t\t\t\t\tcase \"set\":\n\t\t\t\t\t\tif (!input.steps) return errorResult(input.action, \"set requires steps[].\", current);\n\t\t\t\t\t\tstate = setTaskSteps(state, input.steps, timestamp);\n\t\t\t\t\t\tdemotedStepIds = computeDemotedStepIds(\n\t\t\t\t\t\t\tbefore,\n\t\t\t\t\t\t\tstate,\n\t\t\t\t\t\t\texplicitStatusStepIds(input.steps, state.steps),\n\t\t\t\t\t\t);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"intake\":\n\t\t\t\t\t\tif (!input.steps)\n\t\t\t\t\t\t\treturn errorResult(input.action, \"intake requires a complete steps[] list.\", current);\n\t\t\t\t\t\tstate = setTaskSteps(state, input.steps, timestamp);\n\t\t\t\t\t\tdemotedStepIds = computeDemotedStepIds(\n\t\t\t\t\t\t\tbefore,\n\t\t\t\t\t\t\tstate,\n\t\t\t\t\t\t\texplicitStatusStepIds(input.steps, state.steps),\n\t\t\t\t\t\t);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"add\":\n\t\t\t\t\t\tstate = addTaskStep(state, toTaskStepInput(input), timestamp);\n\t\t\t\t\t\tif (state === before) {\n\t\t\t\t\t\t\t// The reducer returned the unchanged state: an open step already carries this\n\t\t\t\t\t\t\t// content, so nothing was created. Name the existing step in the response.\n\t\t\t\t\t\t\tduplicateStepId = findOpenDuplicateStep(before.steps, input.content ?? \"\")?.id;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"update\": {\n\t\t\t\t\t\tif (!input.id?.trim())\n\t\t\t\t\t\t\treturn errorResult(input.action, \"update requires id or a unique selector.\", current);\n\t\t\t\t\t\tconst selected = resolveTaskStepSelector(before.steps, input.id);\n\t\t\t\t\t\tstate = updateTaskStep(\n\t\t\t\t\t\t\tstate,\n\t\t\t\t\t\t\tinput.id,\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tcontent: input.content,\n\t\t\t\t\t\t\t\tactiveForm: input.activeForm,\n\t\t\t\t\t\t\t\tstatus: input.status,\n\t\t\t\t\t\t\t\tpriority: input.priority,\n\t\t\t\t\t\t\t\towner: input.owner,\n\t\t\t\t\t\t\t\trequirementIds: input.requirementIds,\n\t\t\t\t\t\t\t\tnote: input.note,\n\t\t\t\t\t\t\t\tevidence: input.evidence,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\ttimestamp,\n\t\t\t\t\t\t);\n\t\t\t\t\t\t// Exclude the explicitly targeted step: its own status change was requested by\n\t\t\t\t\t\t// the caller, so it is never a \"silent\" demotion even if it moved to pending.\n\t\t\t\t\t\tdemotedStepIds = computeDemotedStepIds(before, state, new Set([selected.id]));\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tcase \"clear\":\n\t\t\t\t\t\tstate = clearTaskSteps(state, timestamp);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"compact\":\n\t\t\t\t\t\tstate = compactTaskSteps(state, timestamp);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"list\":\n\t\t\t\t\t\tif (input.clearCompleted) state = compactTaskSteps(state, timestamp);\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tconst isNoopDuplicateAdd = input.action === \"add\" && state === before;\n\t\t\t\tconst mutated = (input.action !== \"list\" || input.clearCompleted === true) && !isNoopDuplicateAdd;\n\t\t\t\tif (mutated) deps.saveTaskStepsState(state);\n\n\t\t\t\tconst stateCounts = counts(state);\n\t\t\t\tconst noticeLines: string[] = [];\n\t\t\t\tif (duplicateStepId) {\n\t\t\t\t\tnoticeLines.push(\n\t\t\t\t\t\t`Duplicate open step ignored; existing ${duplicateStepId} already tracks this content.`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tif (demotedStepIds.length > 0) {\n\t\t\t\t\tnoticeLines.push(`Demoted to pending because another step became active: ${demotedStepIds.join(\", \")}.`);\n\t\t\t\t}\n\t\t\t\tif (stateCounts.verificationNudgeNeeded) {\n\t\t\t\t\tnoticeLines.push(\n\t\t\t\t\t\t\"Reminder: a completed step has no evidence attached; attach evidence via update before treating it as verified.\",\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tconst notices = noticeLines.length > 0 ? `\\n${noticeLines.join(\"\\n\")}` : \"\";\n\n\t\t\t\tconst headerAction =\n\t\t\t\t\tinput.action === \"list\"\n\t\t\t\t\t\t? \"\"\n\t\t\t\t\t\t: `task_steps ${input.action} ${duplicateStepId ? \"ignored (duplicate)\" : \"recorded\"}.\\n`;\n\t\t\t\treturn {\n\t\t\t\t\tcontent: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ttype: \"text\" as const,\n\t\t\t\t\t\t\ttext: `${headerAction}${formatTaskSteps(state, {\n\t\t\t\t\t\t\t\tincludeTerminal: input.showCompleted,\n\t\t\t\t\t\t\t\tmaxItems: input.maxItems,\n\t\t\t\t\t\t\t})}${notices}`,\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t\t\tdetails: {\n\t\t\t\t\t\taction: input.action,\n\t\t\t\t\t\tapplied: true,\n\t\t\t\t\t\tstate,\n\t\t\t\t\t\t...stateCounts,\n\t\t\t\t\t\tshowCompleted: input.showCompleted,\n\t\t\t\t\t\tduplicateOfStepId: duplicateStepId,\n\t\t\t\t\t\tdemotedStepIds: demotedStepIds.length > 0 ? demotedStepIds : undefined,\n\t\t\t\t\t} satisfies TaskStepsToolDetails,\n\t\t\t\t};\n\t\t\t} catch (error) {\n\t\t\t\treturn errorResult(input.action, error instanceof Error ? error.message : String(error), current);\n\t\t\t}\n\t\t},\n\t};\n}\n"]}