@caupulican/pi-adaptative 0.81.39 → 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 (667) hide show
  1. package/CHANGELOG.md +52 -0
  2. package/README.md +2 -0
  3. package/dist/bundled-resources/extensions/tmux-agent-manager/dispatch-grant.d.ts +2 -0
  4. package/dist/bundled-resources/extensions/tmux-agent-manager/dispatch-grant.d.ts.map +1 -1
  5. package/dist/bundled-resources/extensions/tmux-agent-manager/dispatch-grant.js +2 -0
  6. package/dist/bundled-resources/extensions/tmux-agent-manager/dispatch-grant.js.map +1 -1
  7. package/dist/bundled-resources/extensions/tmux-agent-manager/dispatch-grant.ts +3 -0
  8. package/dist/bundled-resources/extensions/tmux-agent-manager/index.d.ts +9 -0
  9. package/dist/bundled-resources/extensions/tmux-agent-manager/index.d.ts.map +1 -1
  10. package/dist/bundled-resources/extensions/tmux-agent-manager/index.js +290 -107
  11. package/dist/bundled-resources/extensions/tmux-agent-manager/index.js.map +1 -1
  12. package/dist/bundled-resources/extensions/tmux-agent-manager/index.ts +357 -122
  13. package/dist/bundled-resources/skills/tool-call-repair/references/repair-catalogue.md +2 -2
  14. package/dist/cli/args.d.ts +2 -0
  15. package/dist/cli/args.d.ts.map +1 -1
  16. package/dist/cli/args.js +9 -0
  17. package/dist/cli/args.js.map +1 -1
  18. package/dist/core/agent-directory-layout.d.ts +15 -0
  19. package/dist/core/agent-directory-layout.d.ts.map +1 -0
  20. package/dist/core/agent-directory-layout.js +72 -0
  21. package/dist/core/agent-directory-layout.js.map +1 -0
  22. package/dist/core/agent-paths.d.ts +19 -2
  23. package/dist/core/agent-paths.d.ts.map +1 -1
  24. package/dist/core/agent-paths.js +67 -4
  25. package/dist/core/agent-paths.js.map +1 -1
  26. package/dist/core/agent-session-runtime.d.ts +52 -8
  27. package/dist/core/agent-session-runtime.d.ts.map +1 -1
  28. package/dist/core/agent-session-runtime.js +397 -79
  29. package/dist/core/agent-session-runtime.js.map +1 -1
  30. package/dist/core/agent-session-services.d.ts +1 -0
  31. package/dist/core/agent-session-services.d.ts.map +1 -1
  32. package/dist/core/agent-session-services.js +1 -0
  33. package/dist/core/agent-session-services.js.map +1 -1
  34. package/dist/core/agent-session.d.ts +71 -136
  35. package/dist/core/agent-session.d.ts.map +1 -1
  36. package/dist/core/agent-session.js +477 -1318
  37. package/dist/core/agent-session.js.map +1 -1
  38. package/dist/core/autonomy/approval-gate.d.ts +3 -2
  39. package/dist/core/autonomy/approval-gate.d.ts.map +1 -1
  40. package/dist/core/autonomy/approval-gate.js +6 -28
  41. package/dist/core/autonomy/approval-gate.js.map +1 -1
  42. package/dist/core/autonomy/bounded-completion.d.ts +1 -1
  43. package/dist/core/autonomy/bounded-completion.d.ts.map +1 -1
  44. package/dist/core/autonomy/bounded-completion.js +1 -1
  45. package/dist/core/autonomy/bounded-completion.js.map +1 -1
  46. package/dist/core/autonomy/contracts.d.ts +20 -12
  47. package/dist/core/autonomy/contracts.d.ts.map +1 -1
  48. package/dist/core/autonomy/contracts.js.map +1 -1
  49. package/dist/core/autonomy/foreground-envelope.d.ts +8 -2
  50. package/dist/core/autonomy/foreground-envelope.d.ts.map +1 -1
  51. package/dist/core/autonomy/foreground-envelope.js +8 -25
  52. package/dist/core/autonomy/foreground-envelope.js.map +1 -1
  53. package/dist/core/autonomy/gates.d.ts.map +1 -1
  54. package/dist/core/autonomy/gates.js +8 -10
  55. package/dist/core/autonomy/gates.js.map +1 -1
  56. package/dist/core/autonomy/lane-private-paths.d.ts +2 -0
  57. package/dist/core/autonomy/lane-private-paths.d.ts.map +1 -0
  58. package/dist/core/autonomy/lane-private-paths.js +16 -0
  59. package/dist/core/autonomy/lane-private-paths.js.map +1 -0
  60. package/dist/core/autonomy/lane-tool-surface.d.ts +10 -0
  61. package/dist/core/autonomy/lane-tool-surface.d.ts.map +1 -1
  62. package/dist/core/autonomy/lane-tool-surface.js +46 -8
  63. package/dist/core/autonomy/lane-tool-surface.js.map +1 -1
  64. package/dist/core/autonomy/lane-tracker.d.ts +14 -0
  65. package/dist/core/autonomy/lane-tracker.d.ts.map +1 -1
  66. package/dist/core/autonomy/lane-tracker.js +38 -0
  67. package/dist/core/autonomy/lane-tracker.js.map +1 -1
  68. package/dist/core/autonomy/risk-assessment.d.ts +1 -2
  69. package/dist/core/autonomy/risk-assessment.d.ts.map +1 -1
  70. package/dist/core/autonomy/risk-assessment.js +1 -123
  71. package/dist/core/autonomy/risk-assessment.js.map +1 -1
  72. package/dist/core/autonomy/session-lane-record.d.ts +4 -4
  73. package/dist/core/autonomy/session-lane-record.d.ts.map +1 -1
  74. package/dist/core/autonomy/session-lane-record.js +16 -29
  75. package/dist/core/autonomy/session-lane-record.js.map +1 -1
  76. package/dist/core/autonomy/telemetry-events.d.ts +1 -1
  77. package/dist/core/autonomy/telemetry-events.d.ts.map +1 -1
  78. package/dist/core/autonomy/telemetry-events.js +1 -1
  79. package/dist/core/autonomy/telemetry-events.js.map +1 -1
  80. package/dist/core/autonomy-telemetry.d.ts +7 -7
  81. package/dist/core/autonomy-telemetry.d.ts.map +1 -1
  82. package/dist/core/autonomy-telemetry.js +9 -9
  83. package/dist/core/autonomy-telemetry.js.map +1 -1
  84. package/dist/core/background-lane-controller.d.ts +54 -236
  85. package/dist/core/background-lane-controller.d.ts.map +1 -1
  86. package/dist/core/background-lane-controller.js +140 -1273
  87. package/dist/core/background-lane-controller.js.map +1 -1
  88. package/dist/core/capability-contract.d.ts +4 -0
  89. package/dist/core/capability-contract.d.ts.map +1 -0
  90. package/dist/core/capability-contract.js +28 -0
  91. package/dist/core/capability-contract.js.map +1 -0
  92. package/dist/core/compaction-controller.d.ts +90 -0
  93. package/dist/core/compaction-controller.d.ts.map +1 -0
  94. package/dist/core/compaction-controller.js +452 -0
  95. package/dist/core/compaction-controller.js.map +1 -0
  96. package/dist/core/compaction-support.d.ts +12 -11
  97. package/dist/core/compaction-support.d.ts.map +1 -1
  98. package/dist/core/compaction-support.js.map +1 -1
  99. package/dist/core/context/context-artifacts.d.ts +6 -2
  100. package/dist/core/context/context-artifacts.d.ts.map +1 -1
  101. package/dist/core/context/context-artifacts.js +34 -2
  102. package/dist/core/context/context-artifacts.js.map +1 -1
  103. package/dist/core/context/context-store-retention.d.ts +8 -2
  104. package/dist/core/context/context-store-retention.d.ts.map +1 -1
  105. package/dist/core/context/context-store-retention.js +158 -35
  106. package/dist/core/context/context-store-retention.js.map +1 -1
  107. package/dist/core/context/okf-memory.d.ts.map +1 -1
  108. package/dist/core/context/okf-memory.js +9 -11
  109. package/dist/core/context/okf-memory.js.map +1 -1
  110. package/dist/core/context/sqlite-runtime-index.d.ts.map +1 -1
  111. package/dist/core/context/sqlite-runtime-index.js +6 -8
  112. package/dist/core/context/sqlite-runtime-index.js.map +1 -1
  113. package/dist/core/context-gc.d.ts +3 -0
  114. package/dist/core/context-gc.d.ts.map +1 -1
  115. package/dist/core/context-gc.js +10 -5
  116. package/dist/core/context-gc.js.map +1 -1
  117. package/dist/core/context-pipeline.d.ts.map +1 -1
  118. package/dist/core/context-pipeline.js +9 -4
  119. package/dist/core/context-pipeline.js.map +1 -1
  120. package/dist/core/default-tool-surface.d.ts.map +1 -1
  121. package/dist/core/default-tool-surface.js +1 -0
  122. package/dist/core/default-tool-surface.js.map +1 -1
  123. package/dist/core/delegation/managed-lane-controller.d.ts +34 -0
  124. package/dist/core/delegation/managed-lane-controller.d.ts.map +1 -0
  125. package/dist/core/delegation/managed-lane-controller.js +217 -0
  126. package/dist/core/delegation/managed-lane-controller.js.map +1 -0
  127. package/dist/core/delegation/session-worker-claim.d.ts +44 -0
  128. package/dist/core/delegation/session-worker-claim.d.ts.map +1 -0
  129. package/dist/core/delegation/session-worker-claim.js +98 -0
  130. package/dist/core/delegation/session-worker-claim.js.map +1 -0
  131. package/dist/core/delegation/worker-actions.d.ts +7 -5
  132. package/dist/core/delegation/worker-actions.d.ts.map +1 -1
  133. package/dist/core/delegation/worker-actions.js +20 -4
  134. package/dist/core/delegation/worker-actions.js.map +1 -1
  135. package/dist/core/delegation/{worker-result.d.ts → worker-claim.d.ts} +13 -13
  136. package/dist/core/delegation/worker-claim.d.ts.map +1 -0
  137. package/dist/core/delegation/{worker-result.js → worker-claim.js} +61 -51
  138. package/dist/core/delegation/worker-claim.js.map +1 -0
  139. package/dist/core/delegation/worker-delegation-controller.d.ts +110 -0
  140. package/dist/core/delegation/worker-delegation-controller.d.ts.map +1 -0
  141. package/dist/core/delegation/worker-delegation-controller.js +861 -0
  142. package/dist/core/delegation/worker-delegation-controller.js.map +1 -0
  143. package/dist/core/delegation/worker-delegation-request.d.ts +11 -0
  144. package/dist/core/delegation/worker-delegation-request.d.ts.map +1 -0
  145. package/dist/core/delegation/worker-delegation-request.js +2 -0
  146. package/dist/core/delegation/worker-delegation-request.js.map +1 -0
  147. package/dist/core/delegation/worker-dispatch-scheduler.d.ts +40 -0
  148. package/dist/core/delegation/worker-dispatch-scheduler.d.ts.map +1 -0
  149. package/dist/core/delegation/worker-dispatch-scheduler.js +93 -0
  150. package/dist/core/delegation/worker-dispatch-scheduler.js.map +1 -0
  151. package/dist/core/delegation/worker-execution-policy.d.ts +62 -0
  152. package/dist/core/delegation/worker-execution-policy.d.ts.map +1 -0
  153. package/dist/core/delegation/worker-execution-policy.js +160 -0
  154. package/dist/core/delegation/worker-execution-policy.js.map +1 -0
  155. package/dist/core/delegation/worker-lane-projection.d.ts +14 -0
  156. package/dist/core/delegation/worker-lane-projection.d.ts.map +1 -0
  157. package/dist/core/delegation/worker-lane-projection.js +100 -0
  158. package/dist/core/delegation/worker-lane-projection.js.map +1 -0
  159. package/dist/core/delegation/worker-lifecycle.d.ts +97 -0
  160. package/dist/core/delegation/worker-lifecycle.d.ts.map +1 -0
  161. package/dist/core/delegation/worker-lifecycle.js +339 -0
  162. package/dist/core/delegation/worker-lifecycle.js.map +1 -0
  163. package/dist/core/delegation/worker-notification-coordinator.d.ts +36 -0
  164. package/dist/core/delegation/worker-notification-coordinator.d.ts.map +1 -0
  165. package/dist/core/delegation/worker-notification-coordinator.js +90 -0
  166. package/dist/core/delegation/worker-notification-coordinator.js.map +1 -0
  167. package/dist/core/delegation/worker-profile-resolver.d.ts +55 -0
  168. package/dist/core/delegation/worker-profile-resolver.d.ts.map +1 -0
  169. package/dist/core/delegation/worker-profile-resolver.js +113 -0
  170. package/dist/core/delegation/worker-profile-resolver.js.map +1 -0
  171. package/dist/core/delegation/worker-runner.d.ts +25 -14
  172. package/dist/core/delegation/worker-runner.d.ts.map +1 -1
  173. package/dist/core/delegation/worker-runner.js +122 -53
  174. package/dist/core/delegation/worker-runner.js.map +1 -1
  175. package/dist/core/delegation/worker-task-label.d.ts +3 -0
  176. package/dist/core/delegation/worker-task-label.d.ts.map +1 -0
  177. package/dist/core/delegation/worker-task-label.js +11 -0
  178. package/dist/core/delegation/worker-task-label.js.map +1 -0
  179. package/dist/core/doctor.d.ts +8 -0
  180. package/dist/core/doctor.d.ts.map +1 -1
  181. package/dist/core/doctor.js +32 -1
  182. package/dist/core/doctor.js.map +1 -1
  183. package/dist/core/extensions/index.d.ts +1 -1
  184. package/dist/core/extensions/index.d.ts.map +1 -1
  185. package/dist/core/extensions/index.js.map +1 -1
  186. package/dist/core/extensions/loader.d.ts +5 -1
  187. package/dist/core/extensions/loader.d.ts.map +1 -1
  188. package/dist/core/extensions/loader.js +50 -15
  189. package/dist/core/extensions/loader.js.map +1 -1
  190. package/dist/core/extensions/runner.d.ts.map +1 -1
  191. package/dist/core/extensions/runner.js +6 -0
  192. package/dist/core/extensions/runner.js.map +1 -1
  193. package/dist/core/extensions/storage.d.ts +8 -0
  194. package/dist/core/extensions/storage.d.ts.map +1 -0
  195. package/dist/core/extensions/storage.js +28 -0
  196. package/dist/core/extensions/storage.js.map +1 -0
  197. package/dist/core/extensions/types.d.ts +70 -21
  198. package/dist/core/extensions/types.d.ts.map +1 -1
  199. package/dist/core/extensions/types.js.map +1 -1
  200. package/dist/core/failure-corpus.d.ts +1 -15
  201. package/dist/core/failure-corpus.d.ts.map +1 -1
  202. package/dist/core/failure-corpus.js +9 -37
  203. package/dist/core/failure-corpus.js.map +1 -1
  204. package/dist/core/foreground-recovery-controller.d.ts +52 -0
  205. package/dist/core/foreground-recovery-controller.d.ts.map +1 -0
  206. package/dist/core/foreground-recovery-controller.js +111 -0
  207. package/dist/core/foreground-recovery-controller.js.map +1 -0
  208. package/dist/core/gateways/channel-provider.d.ts +3 -0
  209. package/dist/core/gateways/channel-provider.d.ts.map +1 -1
  210. package/dist/core/gateways/channel-provider.js +31 -6
  211. package/dist/core/gateways/channel-provider.js.map +1 -1
  212. package/dist/core/goals/goal-acceptance.d.ts +11 -0
  213. package/dist/core/goals/goal-acceptance.d.ts.map +1 -0
  214. package/dist/core/goals/goal-acceptance.js +25 -0
  215. package/dist/core/goals/goal-acceptance.js.map +1 -0
  216. package/dist/core/goals/goal-auto-continue-controller.d.ts +27 -0
  217. package/dist/core/goals/goal-auto-continue-controller.d.ts.map +1 -0
  218. package/dist/core/goals/goal-auto-continue-controller.js +93 -0
  219. package/dist/core/goals/goal-auto-continue-controller.js.map +1 -0
  220. package/dist/core/goals/goal-continuation-controller.d.ts +1 -1
  221. package/dist/core/goals/goal-continuation-controller.d.ts.map +1 -1
  222. package/dist/core/goals/goal-continuation-controller.js +10 -0
  223. package/dist/core/goals/goal-continuation-controller.js.map +1 -1
  224. package/dist/core/goals/goal-continuation-prompt.d.ts +1 -1
  225. package/dist/core/goals/goal-continuation-prompt.d.ts.map +1 -1
  226. package/dist/core/goals/goal-continuation-prompt.js +6 -6
  227. package/dist/core/goals/goal-continuation-prompt.js.map +1 -1
  228. package/dist/core/goals/goal-lifecycle.d.ts +20 -0
  229. package/dist/core/goals/goal-lifecycle.d.ts.map +1 -0
  230. package/dist/core/goals/goal-lifecycle.js +17 -0
  231. package/dist/core/goals/goal-lifecycle.js.map +1 -0
  232. package/dist/core/goals/goal-runtime-snapshot.d.ts +11 -9
  233. package/dist/core/goals/goal-runtime-snapshot.d.ts.map +1 -1
  234. package/dist/core/goals/goal-runtime-snapshot.js +10 -8
  235. package/dist/core/goals/goal-runtime-snapshot.js.map +1 -1
  236. package/dist/core/goals/goal-state.d.ts +1 -0
  237. package/dist/core/goals/goal-state.d.ts.map +1 -1
  238. package/dist/core/goals/goal-state.js +7 -10
  239. package/dist/core/goals/goal-state.js.map +1 -1
  240. package/dist/core/goals/goal-tool-core.d.ts +8 -6
  241. package/dist/core/goals/goal-tool-core.d.ts.map +1 -1
  242. package/dist/core/goals/goal-tool-core.js +11 -41
  243. package/dist/core/goals/goal-tool-core.js.map +1 -1
  244. package/dist/core/goals/session-goal-state.d.ts +2 -4
  245. package/dist/core/goals/session-goal-state.d.ts.map +1 -1
  246. package/dist/core/goals/session-goal-state.js +10 -33
  247. package/dist/core/goals/session-goal-state.js.map +1 -1
  248. package/dist/core/human-input.d.ts +100 -0
  249. package/dist/core/human-input.d.ts.map +1 -0
  250. package/dist/core/human-input.js +362 -0
  251. package/dist/core/human-input.js.map +1 -0
  252. package/dist/core/index.d.ts +9 -1
  253. package/dist/core/index.d.ts.map +1 -1
  254. package/dist/core/index.js +9 -1
  255. package/dist/core/index.js.map +1 -1
  256. package/dist/core/{telemetry.d.ts → install-telemetry.d.ts} +1 -1
  257. package/dist/core/install-telemetry.d.ts.map +1 -0
  258. package/dist/core/{telemetry.js → install-telemetry.js} +1 -1
  259. package/dist/core/install-telemetry.js.map +1 -0
  260. package/dist/core/keybindings.d.ts +17 -1
  261. package/dist/core/keybindings.d.ts.map +1 -1
  262. package/dist/core/keybindings.js +24 -6
  263. package/dist/core/keybindings.js.map +1 -1
  264. package/dist/core/learning/learning-audit.d.ts +2 -4
  265. package/dist/core/learning/learning-audit.d.ts.map +1 -1
  266. package/dist/core/learning/learning-audit.js +9 -29
  267. package/dist/core/learning/learning-audit.js.map +1 -1
  268. package/dist/core/learning/learning-gate.d.ts.map +1 -1
  269. package/dist/core/learning/learning-gate.js +1 -6
  270. package/dist/core/learning/learning-gate.js.map +1 -1
  271. package/dist/core/learning/session-learning-decision.d.ts +2 -4
  272. package/dist/core/learning/session-learning-decision.d.ts.map +1 -1
  273. package/dist/core/learning/session-learning-decision.js +9 -29
  274. package/dist/core/learning/session-learning-decision.js.map +1 -1
  275. package/dist/core/memory-controller.d.ts.map +1 -1
  276. package/dist/core/memory-controller.js +4 -4
  277. package/dist/core/memory-controller.js.map +1 -1
  278. package/dist/core/model-capability.d.ts.map +1 -1
  279. package/dist/core/model-capability.js +1 -0
  280. package/dist/core/model-capability.js.map +1 -1
  281. package/dist/core/model-resolver.d.ts +1 -1
  282. package/dist/core/model-resolver.d.ts.map +1 -1
  283. package/dist/core/model-resolver.js +6 -9
  284. package/dist/core/model-resolver.js.map +1 -1
  285. package/dist/core/model-router/intent-classifier.d.ts +1 -4
  286. package/dist/core/model-router/intent-classifier.d.ts.map +1 -1
  287. package/dist/core/model-router/intent-classifier.js +1 -156
  288. package/dist/core/model-router/intent-classifier.js.map +1 -1
  289. package/dist/core/model-router-controller.d.ts.map +1 -1
  290. package/dist/core/model-router-controller.js +2 -2
  291. package/dist/core/model-router-controller.js.map +1 -1
  292. package/dist/core/model-selection-controller.d.ts +4 -4
  293. package/dist/core/model-selection-controller.d.ts.map +1 -1
  294. package/dist/core/model-selection-controller.js.map +1 -1
  295. package/dist/core/model-tool-protocol.d.ts +23 -0
  296. package/dist/core/model-tool-protocol.d.ts.map +1 -0
  297. package/dist/core/model-tool-protocol.js +43 -0
  298. package/dist/core/model-tool-protocol.js.map +1 -0
  299. package/dist/core/models/adaptation-store.d.ts +4 -6
  300. package/dist/core/models/adaptation-store.d.ts.map +1 -1
  301. package/dist/core/models/adaptation-store.js +95 -83
  302. package/dist/core/models/adaptation-store.js.map +1 -1
  303. package/dist/core/models/fitness-store.d.ts +2 -12
  304. package/dist/core/models/fitness-store.d.ts.map +1 -1
  305. package/dist/core/models/fitness-store.js +84 -57
  306. package/dist/core/models/fitness-store.js.map +1 -1
  307. package/dist/core/models/host-state-store.d.ts +34 -0
  308. package/dist/core/models/host-state-store.d.ts.map +1 -0
  309. package/dist/core/models/host-state-store.js +86 -0
  310. package/dist/core/models/host-state-store.js.map +1 -0
  311. package/dist/core/orchestration/agent-resume.d.ts +24 -0
  312. package/dist/core/orchestration/agent-resume.d.ts.map +1 -0
  313. package/dist/core/orchestration/agent-resume.js +90 -0
  314. package/dist/core/orchestration/agent-resume.js.map +1 -0
  315. package/dist/core/orchestration/capability-gateway.d.ts +61 -0
  316. package/dist/core/orchestration/capability-gateway.d.ts.map +1 -0
  317. package/dist/core/orchestration/capability-gateway.js +152 -0
  318. package/dist/core/orchestration/capability-gateway.js.map +1 -0
  319. package/dist/core/orchestration/contracts.d.ts +343 -0
  320. package/dist/core/orchestration/contracts.d.ts.map +1 -0
  321. package/dist/core/orchestration/contracts.js +135 -0
  322. package/dist/core/orchestration/contracts.js.map +1 -0
  323. package/dist/core/orchestration/delegation-ledger.d.ts +56 -0
  324. package/dist/core/orchestration/delegation-ledger.d.ts.map +1 -0
  325. package/dist/core/orchestration/delegation-ledger.js +197 -0
  326. package/dist/core/orchestration/delegation-ledger.js.map +1 -0
  327. package/dist/core/orchestration/event-store.d.ts +83 -0
  328. package/dist/core/orchestration/event-store.d.ts.map +1 -0
  329. package/dist/core/orchestration/event-store.js +560 -0
  330. package/dist/core/orchestration/event-store.js.map +1 -0
  331. package/dist/core/orchestration/lane-tool-manifests.d.ts +9 -0
  332. package/dist/core/orchestration/lane-tool-manifests.d.ts.map +1 -0
  333. package/dist/core/orchestration/lane-tool-manifests.js +37 -0
  334. package/dist/core/orchestration/lane-tool-manifests.js.map +1 -0
  335. package/dist/core/orchestration/model-binding.d.ts +15 -0
  336. package/dist/core/orchestration/model-binding.d.ts.map +1 -0
  337. package/dist/core/orchestration/model-binding.js +29 -0
  338. package/dist/core/orchestration/model-binding.js.map +1 -0
  339. package/dist/core/orchestration/policy-compiler.d.ts +49 -0
  340. package/dist/core/orchestration/policy-compiler.d.ts.map +1 -0
  341. package/dist/core/orchestration/policy-compiler.js +191 -0
  342. package/dist/core/orchestration/policy-compiler.js.map +1 -0
  343. package/dist/core/orchestration/policy-gate.d.ts +18 -0
  344. package/dist/core/orchestration/policy-gate.d.ts.map +1 -0
  345. package/dist/core/orchestration/policy-gate.js +24 -0
  346. package/dist/core/orchestration/policy-gate.js.map +1 -0
  347. package/dist/core/orchestration/profile-registry.d.ts +51 -0
  348. package/dist/core/orchestration/profile-registry.d.ts.map +1 -0
  349. package/dist/core/orchestration/profile-registry.js +393 -0
  350. package/dist/core/orchestration/profile-registry.js.map +1 -0
  351. package/dist/core/orchestration/profile-store.d.ts +31 -0
  352. package/dist/core/orchestration/profile-store.d.ts.map +1 -0
  353. package/dist/core/orchestration/profile-store.js +136 -0
  354. package/dist/core/orchestration/profile-store.js.map +1 -0
  355. package/dist/core/orchestration/risk-budget.d.ts +9 -0
  356. package/dist/core/orchestration/risk-budget.d.ts.map +1 -0
  357. package/dist/core/orchestration/risk-budget.js +48 -0
  358. package/dist/core/orchestration/risk-budget.js.map +1 -0
  359. package/dist/core/orchestration/task-runtime.d.ts +168 -0
  360. package/dist/core/orchestration/task-runtime.d.ts.map +1 -0
  361. package/dist/core/orchestration/task-runtime.js +1600 -0
  362. package/dist/core/orchestration/task-runtime.js.map +1 -0
  363. package/dist/core/orchestration/work-state-projection.d.ts +32 -0
  364. package/dist/core/orchestration/work-state-projection.d.ts.map +1 -0
  365. package/dist/core/orchestration/work-state-projection.js +116 -0
  366. package/dist/core/orchestration/work-state-projection.js.map +1 -0
  367. package/dist/core/orchestration/worker-execution-contract.d.ts +21 -0
  368. package/dist/core/orchestration/worker-execution-contract.d.ts.map +1 -0
  369. package/dist/core/orchestration/worker-execution-contract.js +179 -0
  370. package/dist/core/orchestration/worker-execution-contract.js.map +1 -0
  371. package/dist/core/orchestration/worker-result-adapter.d.ts +21 -0
  372. package/dist/core/orchestration/worker-result-adapter.d.ts.map +1 -0
  373. package/dist/core/orchestration/worker-result-adapter.js +109 -0
  374. package/dist/core/orchestration/worker-result-adapter.js.map +1 -0
  375. package/dist/core/process-identity.d.ts +11 -0
  376. package/dist/core/process-identity.d.ts.map +1 -0
  377. package/dist/core/process-identity.js +26 -0
  378. package/dist/core/process-identity.js.map +1 -0
  379. package/dist/core/process-matrix/codes.d.ts +14 -3
  380. package/dist/core/process-matrix/codes.d.ts.map +1 -1
  381. package/dist/core/process-matrix/codes.js.map +1 -1
  382. package/dist/core/process-matrix/resume-launcher.d.ts +26 -0
  383. package/dist/core/process-matrix/resume-launcher.d.ts.map +1 -0
  384. package/dist/core/process-matrix/resume-launcher.js +62 -0
  385. package/dist/core/process-matrix/resume-launcher.js.map +1 -0
  386. package/dist/core/process-matrix/runtime.d.ts +37 -22
  387. package/dist/core/process-matrix/runtime.d.ts.map +1 -1
  388. package/dist/core/process-matrix/runtime.js +399 -76
  389. package/dist/core/process-matrix/runtime.js.map +1 -1
  390. package/dist/core/process-matrix/store.d.ts +5 -2
  391. package/dist/core/process-matrix/store.d.ts.map +1 -1
  392. package/dist/core/process-matrix/store.js +123 -14
  393. package/dist/core/process-matrix/store.js.map +1 -1
  394. package/dist/core/process-matrix/supervisor.d.ts +10 -7
  395. package/dist/core/process-matrix/supervisor.d.ts.map +1 -1
  396. package/dist/core/process-matrix/supervisor.js +45 -14
  397. package/dist/core/process-matrix/supervisor.js.map +1 -1
  398. package/dist/core/profile-registry.d.ts.map +1 -1
  399. package/dist/core/profile-registry.js +6 -8
  400. package/dist/core/profile-registry.js.map +1 -1
  401. package/dist/core/reflection-controller.d.ts +4 -4
  402. package/dist/core/reflection-controller.d.ts.map +1 -1
  403. package/dist/core/reflection-controller.js +2 -1
  404. package/dist/core/reflection-controller.js.map +1 -1
  405. package/dist/core/reload-blockers.d.ts.map +1 -1
  406. package/dist/core/reload-blockers.js +6 -8
  407. package/dist/core/reload-blockers.js.map +1 -1
  408. package/dist/core/research/evidence-bundle.d.ts.map +1 -1
  409. package/dist/core/research/evidence-bundle.js +1 -6
  410. package/dist/core/research/evidence-bundle.js.map +1 -1
  411. package/dist/core/research/lane-model-resolver.d.ts +33 -0
  412. package/dist/core/research/lane-model-resolver.d.ts.map +1 -0
  413. package/dist/core/research/lane-model-resolver.js +65 -0
  414. package/dist/core/research/lane-model-resolver.js.map +1 -0
  415. package/dist/core/research/model-fitness-controller.d.ts +38 -0
  416. package/dist/core/research/model-fitness-controller.d.ts.map +1 -0
  417. package/dist/core/research/model-fitness-controller.js +106 -0
  418. package/dist/core/research/model-fitness-controller.js.map +1 -0
  419. package/dist/core/research/model-fitness.d.ts +1 -1
  420. package/dist/core/research/model-fitness.d.ts.map +1 -1
  421. package/dist/core/research/model-fitness.js +4 -4
  422. package/dist/core/research/model-fitness.js.map +1 -1
  423. package/dist/core/research/research-gate.d.ts.map +1 -1
  424. package/dist/core/research/research-gate.js +7 -7
  425. package/dist/core/research/research-gate.js.map +1 -1
  426. package/dist/core/research/research-lane-controller.d.ts +62 -0
  427. package/dist/core/research/research-lane-controller.d.ts.map +1 -0
  428. package/dist/core/research/research-lane-controller.js +292 -0
  429. package/dist/core/research/research-lane-controller.js.map +1 -0
  430. package/dist/core/research/session-evidence-bundle.d.ts +2 -4
  431. package/dist/core/research/session-evidence-bundle.d.ts.map +1 -1
  432. package/dist/core/research/session-evidence-bundle.js +10 -46
  433. package/dist/core/research/session-evidence-bundle.js.map +1 -1
  434. package/dist/core/resource-loader.d.ts.map +1 -1
  435. package/dist/core/resource-loader.js +7 -2
  436. package/dist/core/resource-loader.js.map +1 -1
  437. package/dist/core/risk-classifier.d.ts +6 -0
  438. package/dist/core/risk-classifier.d.ts.map +1 -0
  439. package/dist/core/risk-classifier.js +225 -0
  440. package/dist/core/risk-classifier.js.map +1 -0
  441. package/dist/core/runtime-builder.d.ts +26 -20
  442. package/dist/core/runtime-builder.d.ts.map +1 -1
  443. package/dist/core/runtime-builder.js +237 -178
  444. package/dist/core/runtime-builder.js.map +1 -1
  445. package/dist/core/sdk.d.ts +6 -3
  446. package/dist/core/sdk.d.ts.map +1 -1
  447. package/dist/core/sdk.js +61 -24
  448. package/dist/core/sdk.js.map +1 -1
  449. package/dist/core/session-analytics.d.ts.map +1 -1
  450. package/dist/core/session-analytics.js +28 -1
  451. package/dist/core/session-analytics.js.map +1 -1
  452. package/dist/core/session-image-store.d.ts +33 -0
  453. package/dist/core/session-image-store.d.ts.map +1 -0
  454. package/dist/core/session-image-store.js +283 -0
  455. package/dist/core/session-image-store.js.map +1 -0
  456. package/dist/core/session-role.d.ts +6 -4
  457. package/dist/core/session-role.d.ts.map +1 -1
  458. package/dist/core/session-role.js +10 -4
  459. package/dist/core/session-role.js.map +1 -1
  460. package/dist/core/session-snapshot.d.ts +34 -0
  461. package/dist/core/session-snapshot.d.ts.map +1 -0
  462. package/dist/core/session-snapshot.js +68 -0
  463. package/dist/core/session-snapshot.js.map +1 -0
  464. package/dist/core/session-supervision-runtime.d.ts +31 -0
  465. package/dist/core/session-supervision-runtime.d.ts.map +1 -0
  466. package/dist/core/session-supervision-runtime.js +97 -0
  467. package/dist/core/session-supervision-runtime.js.map +1 -0
  468. package/dist/core/settings-manager.d.ts +9 -4
  469. package/dist/core/settings-manager.d.ts.map +1 -1
  470. package/dist/core/settings-manager.js +80 -28
  471. package/dist/core/settings-manager.js.map +1 -1
  472. package/dist/core/tasks/session-task-state.d.ts +2 -4
  473. package/dist/core/tasks/session-task-state.d.ts.map +1 -1
  474. package/dist/core/tasks/session-task-state.js +10 -28
  475. package/dist/core/tasks/session-task-state.js.map +1 -1
  476. package/dist/core/tasks/task-projection.d.ts +20 -0
  477. package/dist/core/tasks/task-projection.d.ts.map +1 -0
  478. package/dist/core/tasks/task-projection.js +47 -0
  479. package/dist/core/tasks/task-projection.js.map +1 -0
  480. package/dist/core/tasks/task-state.d.ts +4 -0
  481. package/dist/core/tasks/task-state.d.ts.map +1 -1
  482. package/dist/core/tasks/task-state.js +28 -11
  483. package/dist/core/tasks/task-state.js.map +1 -1
  484. package/dist/core/tool-capability-policy.d.ts +13 -0
  485. package/dist/core/tool-capability-policy.d.ts.map +1 -0
  486. package/dist/core/tool-capability-policy.js +85 -0
  487. package/dist/core/tool-capability-policy.js.map +1 -0
  488. package/dist/core/tool-protocol-controller.d.ts +91 -0
  489. package/dist/core/tool-protocol-controller.d.ts.map +1 -0
  490. package/dist/core/tool-protocol-controller.js +512 -0
  491. package/dist/core/tool-protocol-controller.js.map +1 -0
  492. package/dist/core/tool-recovery-log-records.d.ts +2 -3
  493. package/dist/core/tool-recovery-log-records.d.ts.map +1 -1
  494. package/dist/core/tool-recovery-log-records.js +9 -35
  495. package/dist/core/tool-recovery-log-records.js.map +1 -1
  496. package/dist/core/tool-selection/tool-performance-store.d.ts +3 -7
  497. package/dist/core/tool-selection/tool-performance-store.d.ts.map +1 -1
  498. package/dist/core/tool-selection/tool-performance-store.js +97 -138
  499. package/dist/core/tool-selection/tool-performance-store.js.map +1 -1
  500. package/dist/core/tools/ask-question.d.ts +124 -0
  501. package/dist/core/tools/ask-question.d.ts.map +1 -0
  502. package/dist/core/tools/ask-question.js +693 -0
  503. package/dist/core/tools/ask-question.js.map +1 -0
  504. package/dist/core/tools/delegate-status.d.ts +31 -3
  505. package/dist/core/tools/delegate-status.d.ts.map +1 -1
  506. package/dist/core/tools/delegate-status.js +149 -29
  507. package/dist/core/tools/delegate-status.js.map +1 -1
  508. package/dist/core/tools/delegate.d.ts +15 -13
  509. package/dist/core/tools/delegate.d.ts.map +1 -1
  510. package/dist/core/tools/delegate.js +108 -23
  511. package/dist/core/tools/delegate.js.map +1 -1
  512. package/dist/core/tools/extensionify.d.ts.map +1 -1
  513. package/dist/core/tools/extensionify.js +1 -0
  514. package/dist/core/tools/extensionify.js.map +1 -1
  515. package/dist/core/tools/goal.d.ts +5 -5
  516. package/dist/core/tools/goal.d.ts.map +1 -1
  517. package/dist/core/tools/goal.js +10 -10
  518. package/dist/core/tools/goal.js.map +1 -1
  519. package/dist/core/tools/model-fitness.d.ts.map +1 -1
  520. package/dist/core/tools/model-fitness.js +2 -2
  521. package/dist/core/tools/model-fitness.js.map +1 -1
  522. package/dist/core/tools/orchestration-panel.d.ts +43 -0
  523. package/dist/core/tools/orchestration-panel.d.ts.map +1 -0
  524. package/dist/core/tools/orchestration-panel.js +168 -0
  525. package/dist/core/tools/orchestration-panel.js.map +1 -0
  526. package/dist/core/tools/run-process.d.ts +26 -0
  527. package/dist/core/tools/run-process.d.ts.map +1 -0
  528. package/dist/core/tools/run-process.js +138 -0
  529. package/dist/core/tools/run-process.js.map +1 -0
  530. package/dist/core/tools/task-steps.d.ts +2 -0
  531. package/dist/core/tools/task-steps.d.ts.map +1 -1
  532. package/dist/core/tools/task-steps.js +102 -0
  533. package/dist/core/tools/task-steps.js.map +1 -1
  534. package/dist/core/tools/tmux-dispatch.d.ts +3 -5
  535. package/dist/core/tools/tmux-dispatch.d.ts.map +1 -1
  536. package/dist/core/tools/tmux-dispatch.js +4 -4
  537. package/dist/core/tools/tmux-dispatch.js.map +1 -1
  538. package/dist/core/tools/windows-shell-engine.d.ts.map +1 -1
  539. package/dist/core/tools/windows-shell-engine.js +4 -6
  540. package/dist/core/tools/windows-shell-engine.js.map +1 -1
  541. package/dist/core/util/bounded-jsonl.d.ts +10 -0
  542. package/dist/core/util/bounded-jsonl.d.ts.map +1 -0
  543. package/dist/core/util/bounded-jsonl.js +75 -0
  544. package/dist/core/util/bounded-jsonl.js.map +1 -0
  545. package/dist/core/util/value-guards.d.ts +5 -0
  546. package/dist/core/util/value-guards.d.ts.map +1 -0
  547. package/dist/core/util/value-guards.js +12 -0
  548. package/dist/core/util/value-guards.js.map +1 -0
  549. package/dist/core/worktree-sync/store.d.ts +3 -3
  550. package/dist/core/worktree-sync/store.d.ts.map +1 -1
  551. package/dist/core/worktree-sync/store.js +10 -5
  552. package/dist/core/worktree-sync/store.js.map +1 -1
  553. package/dist/index.d.ts +13 -3
  554. package/dist/index.d.ts.map +1 -1
  555. package/dist/index.js +12 -2
  556. package/dist/index.js.map +1 -1
  557. package/dist/main.d.ts.map +1 -1
  558. package/dist/main.js +128 -44
  559. package/dist/main.js.map +1 -1
  560. package/dist/migrations.d.ts +4 -6
  561. package/dist/migrations.d.ts.map +1 -1
  562. package/dist/migrations.js +186 -28
  563. package/dist/migrations.js.map +1 -1
  564. package/dist/modes/interactive/clipboard-input.d.ts +7 -1
  565. package/dist/modes/interactive/clipboard-input.d.ts.map +1 -1
  566. package/dist/modes/interactive/clipboard-input.js +44 -6
  567. package/dist/modes/interactive/clipboard-input.js.map +1 -1
  568. package/dist/modes/interactive/components/settings-selector.d.ts.map +1 -1
  569. package/dist/modes/interactive/components/settings-selector.js +2 -2
  570. package/dist/modes/interactive/components/settings-selector.js.map +1 -1
  571. package/dist/modes/interactive/config-backup.d.ts.map +1 -1
  572. package/dist/modes/interactive/config-backup.js +5 -4
  573. package/dist/modes/interactive/config-backup.js.map +1 -1
  574. package/dist/modes/interactive/extension-ui-host.d.ts +14 -0
  575. package/dist/modes/interactive/extension-ui-host.d.ts.map +1 -1
  576. package/dist/modes/interactive/extension-ui-host.js +76 -15
  577. package/dist/modes/interactive/extension-ui-host.js.map +1 -1
  578. package/dist/modes/interactive/interactive-mode.d.ts +3 -0
  579. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  580. package/dist/modes/interactive/interactive-mode.js +63 -1
  581. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  582. package/dist/modes/interactive/key-handlers.d.ts.map +1 -1
  583. package/dist/modes/interactive/key-handlers.js +1 -1
  584. package/dist/modes/interactive/key-handlers.js.map +1 -1
  585. package/dist/modes/interactive/profile-menu-controller.d.ts.map +1 -1
  586. package/dist/modes/interactive/profile-menu-controller.js +7 -7
  587. package/dist/modes/interactive/profile-menu-controller.js.map +1 -1
  588. package/dist/modes/interactive/report-commands.d.ts.map +1 -1
  589. package/dist/modes/interactive/report-commands.js +21 -0
  590. package/dist/modes/interactive/report-commands.js.map +1 -1
  591. package/dist/modes/interactive/session-flow-commands.d.ts +17 -2
  592. package/dist/modes/interactive/session-flow-commands.d.ts.map +1 -1
  593. package/dist/modes/interactive/session-flow-commands.js +50 -17
  594. package/dist/modes/interactive/session-flow-commands.js.map +1 -1
  595. package/dist/modes/interactive/session-io-commands.d.ts.map +1 -1
  596. package/dist/modes/interactive/session-io-commands.js +16 -6
  597. package/dist/modes/interactive/session-io-commands.js.map +1 -1
  598. package/dist/modes/interactive/session-replacement-errors.d.ts +7 -0
  599. package/dist/modes/interactive/session-replacement-errors.d.ts.map +1 -0
  600. package/dist/modes/interactive/session-replacement-errors.js +15 -0
  601. package/dist/modes/interactive/session-replacement-errors.js.map +1 -0
  602. package/dist/modes/interactive/startup-checks.d.ts.map +1 -1
  603. package/dist/modes/interactive/startup-checks.js +1 -1
  604. package/dist/modes/interactive/startup-checks.js.map +1 -1
  605. package/dist/modes/rpc/rpc-mode.d.ts.map +1 -1
  606. package/dist/modes/rpc/rpc-mode.js +82 -23
  607. package/dist/modes/rpc/rpc-mode.js.map +1 -1
  608. package/dist/modes/rpc/rpc-types.d.ts +15 -0
  609. package/dist/modes/rpc/rpc-types.d.ts.map +1 -1
  610. package/dist/modes/rpc/rpc-types.js +138 -1
  611. package/dist/modes/rpc/rpc-types.js.map +1 -1
  612. package/dist/utils/clipboard-image.d.ts.map +1 -1
  613. package/dist/utils/clipboard-image.js +2 -13
  614. package/dist/utils/clipboard-image.js.map +1 -1
  615. package/dist/utils/clipboard-native.d.ts +1 -0
  616. package/dist/utils/clipboard-native.d.ts.map +1 -1
  617. package/dist/utils/clipboard-native.js.map +1 -1
  618. package/dist/utils/clipboard.d.ts +1 -0
  619. package/dist/utils/clipboard.d.ts.map +1 -1
  620. package/dist/utils/clipboard.js +52 -1
  621. package/dist/utils/clipboard.js.map +1 -1
  622. package/dist/utils/platform.d.ts +3 -0
  623. package/dist/utils/platform.d.ts.map +1 -0
  624. package/dist/utils/platform.js +8 -0
  625. package/dist/utils/platform.js.map +1 -0
  626. package/dist/utils/work-directory.d.ts +11 -0
  627. package/dist/utils/work-directory.d.ts.map +1 -1
  628. package/dist/utils/work-directory.js +30 -9
  629. package/dist/utils/work-directory.js.map +1 -1
  630. package/docs/UI_POLISH_ORCHESTRATION.md +44 -0
  631. package/docs/UI_QUALITY_ORCHESTRATION.md +30 -0
  632. package/docs/docs.json +4 -0
  633. package/docs/extensions.md +62 -2
  634. package/docs/harness-architecture.md +156 -0
  635. package/docs/keybindings.md +11 -1
  636. package/docs/process-matrix.md +59 -26
  637. package/docs/rpc.md +45 -2
  638. package/docs/sessions.md +15 -0
  639. package/docs/settings.md +125 -11
  640. package/docs/task-steps.md +8 -0
  641. package/docs/telemetry.md +19 -0
  642. package/docs/tmux-agent-manager.md +10 -3
  643. package/docs/ui-reference/README.md +9 -0
  644. package/docs/ui-reference/orchestration-after.txt +7 -0
  645. package/docs/ui-reference/orchestration-before.txt +7 -0
  646. package/docs/ui-reference/orchestration-reference.txt +6 -0
  647. package/docs/usage.md +14 -2
  648. package/docs/work-directory.md +19 -8
  649. package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
  650. package/examples/extensions/custom-provider-anthropic/package.json +1 -1
  651. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  652. package/examples/extensions/question.ts +34 -245
  653. package/examples/extensions/questionnaire.ts +41 -407
  654. package/examples/extensions/sandbox/package-lock.json +2 -2
  655. package/examples/extensions/sandbox/package.json +1 -1
  656. package/examples/extensions/with-deps/package-lock.json +2 -2
  657. package/examples/extensions/with-deps/package.json +1 -1
  658. package/npm-shrinkwrap.json +12 -12
  659. package/package.json +4 -4
  660. package/dist/core/delegation/session-worker-result.d.ts +0 -46
  661. package/dist/core/delegation/session-worker-result.d.ts.map +0 -1
  662. package/dist/core/delegation/session-worker-result.js +0 -113
  663. package/dist/core/delegation/session-worker-result.js.map +0 -1
  664. package/dist/core/delegation/worker-result.d.ts.map +0 -1
  665. package/dist/core/delegation/worker-result.js.map +0 -1
  666. package/dist/core/telemetry.d.ts.map +0 -1
  667. package/dist/core/telemetry.js.map +0 -1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mB,CAAC,IAAY,EAA8B;IAC7E,IAAI,CAAC;QACJ,MAAM,MAAM,GAAY,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;QACzC,OAAO,gBAAgB,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,mBAAmB,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;IAC3E,CAAC;IAAC,MAAM,CAAC;QACR,OAAO,SAAS,CAAC;IAClB,CAAC;AAAA,CACD","sourcesContent":["export const TASK_STEP_STATUSES = [\"pending\", \"in_progress\", \"completed\", \"blocked\", \"cancelled\"] as const;\nexport type TaskStepStatus = (typeof TASK_STEP_STATUSES)[number];\n\nexport const TASK_STEP_PRIORITIES = [\"low\", \"normal\", \"high\"] as const;\nexport type TaskStepPriority = (typeof TASK_STEP_PRIORITIES)[number];\n\nexport const MAX_TASK_STEPS = 100;\nexport const MAX_TASK_STEP_CONTENT_LENGTH = 2_000;\nconst MAX_TASK_STEP_NOTE_LENGTH = 4_000;\nconst MAX_TASK_STEP_OWNER_LENGTH = 200;\nconst MAX_TASK_STEP_EVIDENCE = 32;\nconst MAX_TASK_STEP_EVIDENCE_LENGTH = 2_000;\n\nexport interface TaskStepInput {\n\tcontent: string;\n\tactiveForm?: string;\n\tstatus?: TaskStepStatus;\n\tpriority?: TaskStepPriority;\n\towner?: string;\n\tnote?: string;\n\tnotes?: readonly string[];\n\tevidence?: readonly string[];\n}\n\nexport interface TaskStep {\n\tid: string;\n\tcontent: string;\n\tactiveForm?: string;\n\tstatus: TaskStepStatus;\n\tpriority?: TaskStepPriority;\n\towner?: string;\n\tnotes: readonly string[];\n\tevidence: readonly string[];\n\tcreatedAt: string;\n\tupdatedAt: string;\n}\n\nexport interface TaskStepsArchive {\n\tcompleted: number;\n\tcancelled: number;\n\tcompactedAt?: string;\n}\n\nexport interface TaskStepsState {\n\tversion: 1;\n\trevision: number;\n\tnextStepNumber: number;\n\tsteps: readonly TaskStep[];\n\tarchive: TaskStepsArchive;\n\tcreatedAt: string;\n\tupdatedAt: string;\n}\n\nexport interface TaskStepUpdate {\n\tcontent?: string;\n\tactiveForm?: string;\n\tstatus?: TaskStepStatus;\n\tpriority?: TaskStepPriority;\n\towner?: string;\n\tnote?: string;\n\tevidence?: readonly string[];\n}\n\nexport class TaskStepsError extends Error {\n\tconstructor(message: string) {\n\t\tsuper(message);\n\t\tthis.name = \"TaskStepsError\";\n\t}\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\tif (!value || typeof value !== \"object\" || Array.isArray(value)) return false;\n\tconst prototype = Object.getPrototypeOf(value);\n\treturn prototype === Object.prototype || prototype === null;\n}\n\nfunction isTaskStepStatus(value: unknown): value is TaskStepStatus {\n\treturn TASK_STEP_STATUSES.some((status) => status === value);\n}\n\nfunction isTaskStepPriority(value: unknown): value is TaskStepPriority {\n\treturn TASK_STEP_PRIORITIES.some((priority) => priority === value);\n}\n\nfunction hasOptionalString(record: Record<string, unknown>, key: string, maxLength: number): boolean {\n\tconst value = record[key];\n\treturn value === undefined || (typeof value === \"string\" && value.length <= maxLength);\n}\n\nfunction isBoundedStringArray(value: unknown, maxItems: number, maxLength: number): value is readonly string[] {\n\treturn (\n\t\tArray.isArray(value) &&\n\t\tvalue.length <= maxItems &&\n\t\tvalue.every((item) => typeof item === \"string\" && item.length > 0 && item.length <= maxLength)\n\t);\n}\n\nfunction isTaskStep(value: unknown): value is TaskStep {\n\tif (!isRecord(value)) return false;\n\treturn (\n\t\ttypeof value.id === \"string\" &&\n\t\t/^step-[1-9]\\d*$/.test(value.id) &&\n\t\ttypeof value.content === \"string\" &&\n\t\tvalue.content.length > 0 &&\n\t\tvalue.content.length <= MAX_TASK_STEP_CONTENT_LENGTH &&\n\t\thasOptionalString(value, \"activeForm\", MAX_TASK_STEP_CONTENT_LENGTH) &&\n\t\tisTaskStepStatus(value.status) &&\n\t\t(value.priority === undefined || isTaskStepPriority(value.priority)) &&\n\t\thasOptionalString(value, \"owner\", MAX_TASK_STEP_OWNER_LENGTH) &&\n\t\tisBoundedStringArray(value.notes, MAX_TASK_STEP_EVIDENCE, MAX_TASK_STEP_NOTE_LENGTH) &&\n\t\tisBoundedStringArray(value.evidence, MAX_TASK_STEP_EVIDENCE, MAX_TASK_STEP_EVIDENCE_LENGTH) &&\n\t\ttypeof value.createdAt === \"string\" &&\n\t\ttypeof value.updatedAt === \"string\"\n\t);\n}\n\nfunction isTaskStepsArchive(value: unknown): value is TaskStepsArchive {\n\tif (!isRecord(value)) return false;\n\treturn (\n\t\tNumber.isInteger(value.completed) &&\n\t\tNumber(value.completed) >= 0 &&\n\t\tNumber.isInteger(value.cancelled) &&\n\t\tNumber(value.cancelled) >= 0 &&\n\t\thasOptionalString(value, \"compactedAt\", 100)\n\t);\n}\n\nexport function isTaskStepsState(value: unknown): value is TaskStepsState {\n\tif (!isRecord(value)) return false;\n\tif (\n\t\tvalue.version !== 1 ||\n\t\t!Number.isInteger(value.revision) ||\n\t\tNumber(value.revision) < 0 ||\n\t\t!Number.isInteger(value.nextStepNumber) ||\n\t\tNumber(value.nextStepNumber) < 1 ||\n\t\t!Array.isArray(value.steps) ||\n\t\tvalue.steps.length > MAX_TASK_STEPS ||\n\t\t!value.steps.every(isTaskStep) ||\n\t\t!isTaskStepsArchive(value.archive) ||\n\t\ttypeof value.createdAt !== \"string\" ||\n\t\ttypeof value.updatedAt !== \"string\"\n\t) {\n\t\treturn false;\n\t}\n\tconst ids = new Set(value.steps.map((step) => step.id));\n\treturn ids.size === value.steps.length && value.steps.filter((step) => step.status === \"in_progress\").length <= 1;\n}\n\nfunction cloneTaskStep(step: TaskStep): TaskStep {\n\treturn { ...step, notes: [...step.notes], evidence: [...step.evidence] };\n}\n\nexport function cloneTaskStepsState(state: TaskStepsState): TaskStepsState {\n\treturn {\n\t\t...state,\n\t\tsteps: state.steps.map(cloneTaskStep),\n\t\tarchive: { ...state.archive },\n\t};\n}\n\nexport function createTaskStepsState(now: string): TaskStepsState {\n\treturn {\n\t\tversion: 1,\n\t\trevision: 0,\n\t\tnextStepNumber: 1,\n\t\tsteps: [],\n\t\tarchive: { completed: 0, cancelled: 0 },\n\t\tcreatedAt: now,\n\t\tupdatedAt: now,\n\t};\n}\n\nfunction requireBoundedText(value: string, label: string, maxLength: number): string {\n\tconst normalized = value.trim();\n\tif (!normalized) throw new TaskStepsError(`${label} is required.`);\n\tif (normalized.length > maxLength) throw new TaskStepsError(`${label} must be at most ${maxLength} characters.`);\n\treturn normalized;\n}\n\nfunction optionalBoundedText(value: string | undefined, label: string, maxLength: number): string | undefined {\n\tif (value === undefined) return undefined;\n\tconst normalized = value.trim();\n\tif (!normalized) return undefined;\n\tif (normalized.length > maxLength) throw new TaskStepsError(`${label} must be at most ${maxLength} characters.`);\n\treturn normalized;\n}\n\nfunction normalizeStrings(values: readonly string[] | undefined, label: string, maxLength: number): string[] {\n\tif (!values) return [];\n\tconst normalized: string[] = [];\n\tfor (const value of values) {\n\t\tconst item = requireBoundedText(value, label, maxLength);\n\t\tif (!normalized.includes(item)) normalized.push(item);\n\t}\n\tif (normalized.length > MAX_TASK_STEP_EVIDENCE) {\n\t\tthrow new TaskStepsError(`${label} supports at most ${MAX_TASK_STEP_EVIDENCE} entries.`);\n\t}\n\treturn normalized;\n}\n\nfunction appendUniqueStrings(\n\tcurrent: readonly string[],\n\tvalues: readonly string[] | undefined,\n\tlabel: string,\n\tmaxLength: number,\n): string[] {\n\tconst appended = [...current];\n\tfor (const value of normalizeStrings(values, label, maxLength)) {\n\t\tif (!appended.includes(value)) appended.push(value);\n\t}\n\tif (appended.length > MAX_TASK_STEP_EVIDENCE) {\n\t\tthrow new TaskStepsError(`${label} supports at most ${MAX_TASK_STEP_EVIDENCE} entries.`);\n\t}\n\treturn appended;\n}\n\nfunction normalizeInputNotes(input: TaskStepInput): string[] {\n\tconst notes = normalizeStrings(input.notes, \"Task step note\", MAX_TASK_STEP_NOTE_LENGTH);\n\tconst note = optionalBoundedText(input.note, \"Task step note\", MAX_TASK_STEP_NOTE_LENGTH);\n\tif (note && !notes.includes(note)) notes.push(note);\n\treturn notes;\n}\n\n/**\n * Find an OPEN (non-terminal) step whose content matches `content` case-insensitively.\n * Terminal steps (completed/cancelled) are deliberately excluded so a legitimate re-add of\n * previously finished work still creates a new step.\n */\nexport function findOpenDuplicateStep(steps: readonly TaskStep[], content: string): TaskStep | undefined {\n\tconst normalized = content.trim().toLocaleLowerCase();\n\tif (!normalized) return undefined;\n\treturn steps.find(\n\t\t(step) =>\n\t\t\tstep.status !== \"completed\" && step.status !== \"cancelled\" && step.content.toLocaleLowerCase() === normalized,\n\t);\n}\n\n/** True when a completed step has no evidence attached (a verification nudge candidate). */\nexport function hasUnverifiedCompletedStep(state: TaskStepsState): boolean {\n\treturn state.steps.some((step) => step.status === \"completed\" && step.evidence.length === 0);\n}\n\nfunction demoteOtherActiveSteps(steps: TaskStep[], activeIndex: number): void {\n\tfor (let index = 0; index < steps.length; index++) {\n\t\tif (index !== activeIndex && steps[index].status === \"in_progress\") {\n\t\t\tsteps[index] = { ...steps[index], status: \"pending\" };\n\t\t}\n\t}\n}\n\nfunction nextState(state: TaskStepsState, steps: readonly TaskStep[], now: string): TaskStepsState {\n\treturn {\n\t\t...state,\n\t\trevision: state.revision + 1,\n\t\tsteps: steps.map(cloneTaskStep),\n\t\tarchive: { ...state.archive },\n\t\tupdatedAt: now,\n\t};\n}\n\nfunction createStep(args: {\n\tinput: TaskStepInput;\n\tid: string;\n\tcreatedAt: string;\n\tupdatedAt: string;\n\texisting?: TaskStep;\n}): TaskStep {\n\tconst existing = args.existing;\n\tconst notes =\n\t\targs.input.note === undefined && args.input.notes === undefined\n\t\t\t? [...(existing?.notes ?? [])]\n\t\t\t: normalizeInputNotes(args.input);\n\tconst evidence =\n\t\targs.input.evidence === undefined\n\t\t\t? [...(existing?.evidence ?? [])]\n\t\t\t: normalizeStrings(args.input.evidence, \"Task step evidence\", MAX_TASK_STEP_EVIDENCE_LENGTH);\n\treturn {\n\t\tid: args.id,\n\t\tcontent: requireBoundedText(args.input.content, \"Task step content\", MAX_TASK_STEP_CONTENT_LENGTH),\n\t\tactiveForm:\n\t\t\targs.input.activeForm === undefined\n\t\t\t\t? existing?.activeForm\n\t\t\t\t: optionalBoundedText(args.input.activeForm, \"Task step active form\", MAX_TASK_STEP_CONTENT_LENGTH),\n\t\tstatus: args.input.status ?? existing?.status ?? \"pending\",\n\t\tpriority: args.input.priority ?? existing?.priority,\n\t\towner:\n\t\t\targs.input.owner === undefined\n\t\t\t\t? existing?.owner\n\t\t\t\t: optionalBoundedText(args.input.owner, \"Task step owner\", MAX_TASK_STEP_OWNER_LENGTH),\n\t\tnotes,\n\t\tevidence,\n\t\tcreatedAt: args.createdAt,\n\t\tupdatedAt: args.updatedAt,\n\t};\n}\n\nexport function setTaskSteps(state: TaskStepsState, inputs: readonly TaskStepInput[], now: string): TaskStepsState {\n\tif (inputs.length > MAX_TASK_STEPS) {\n\t\tthrow new TaskStepsError(`Task steps supports at most ${MAX_TASK_STEPS} steps.`);\n\t}\n\tconst existingByContent = new Map<string, TaskStep[]>();\n\tfor (const step of state.steps) {\n\t\tconst key = step.content.toLocaleLowerCase();\n\t\tconst matches = existingByContent.get(key) ?? [];\n\t\tmatches.push(step);\n\t\texistingByContent.set(key, matches);\n\t}\n\n\tlet nextStepNumber = state.nextStepNumber;\n\tconst steps = inputs.map((input) => {\n\t\tconst content = requireBoundedText(input.content, \"Task step content\", MAX_TASK_STEP_CONTENT_LENGTH);\n\t\tconst matches = existingByContent.get(content.toLocaleLowerCase());\n\t\tconst existing = matches?.shift();\n\t\tconst id = existing?.id ?? `step-${nextStepNumber++}`;\n\t\treturn createStep({\n\t\t\tinput: { ...input, content },\n\t\t\tid,\n\t\t\tcreatedAt: existing?.createdAt ?? now,\n\t\t\tupdatedAt: now,\n\t\t\texisting,\n\t\t});\n\t});\n\tconst activeIndex = steps.findLastIndex((step) => step.status === \"in_progress\");\n\tif (activeIndex >= 0) demoteOtherActiveSteps(steps, activeIndex);\n\treturn { ...nextState(state, steps, now), nextStepNumber };\n}\n\nexport function addTaskStep(state: TaskStepsState, input: TaskStepInput, now: string): TaskStepsState {\n\t// Dedupe against OPEN steps only, before the capacity check: a duplicate re-add of an\n\t// already-open step is a no-op regardless of whether the list happens to be full. Terminal\n\t// (completed/cancelled) matches are excluded so a legitimate re-add still creates a step.\n\tif (findOpenDuplicateStep(state.steps, input.content)) return state;\n\tif (state.steps.length >= MAX_TASK_STEPS) {\n\t\tthrow new TaskStepsError(`Task steps already has the maximum ${MAX_TASK_STEPS} steps.`);\n\t}\n\tconst step = createStep({ input, id: `step-${state.nextStepNumber}`, createdAt: now, updatedAt: now });\n\tconst steps = [...state.steps.map(cloneTaskStep), step];\n\tif (step.status === \"in_progress\") demoteOtherActiveSteps(steps, steps.length - 1);\n\treturn { ...nextState(state, steps, now), nextStepNumber: state.nextStepNumber + 1 };\n}\n\nexport function resolveTaskStepSelector(steps: readonly TaskStep[], selector: string): TaskStep {\n\tconst normalized = selector.trim().toLocaleLowerCase();\n\tif (!normalized) throw new TaskStepsError(\"Task step selector is required.\");\n\tif (normalized === \"current\" || normalized === \"active\") {\n\t\tconst active = steps.find((step) => step.status === \"in_progress\");\n\t\tif (!active) throw new TaskStepsError(\"No in_progress task step was found.\");\n\t\treturn active;\n\t}\n\n\tconst exactId = steps.find((step) => step.id.toLocaleLowerCase() === normalized);\n\tif (exactId) return exactId;\n\tconst idPrefix = steps.filter((step) => step.id.toLocaleLowerCase().startsWith(normalized));\n\tif (idPrefix.length === 1) return idPrefix[0];\n\tif (idPrefix.length > 1) {\n\t\tthrow new TaskStepsError(`Task step selector is ambiguous: ${idPrefix.map((step) => step.id).join(\", \")}.`);\n\t}\n\n\tconst exactContent = steps.filter((step) => step.content.toLocaleLowerCase() === normalized);\n\tif (exactContent.length === 1) return exactContent[0];\n\tconst contentMatches = steps.filter((step) => step.content.toLocaleLowerCase().includes(normalized));\n\tif (contentMatches.length === 1) return contentMatches[0];\n\tif (exactContent.length > 1 || contentMatches.length > 1) {\n\t\tconst matches = exactContent.length > 1 ? exactContent : contentMatches;\n\t\tthrow new TaskStepsError(`Task step selector is ambiguous: ${matches.map((step) => step.id).join(\", \")}.`);\n\t}\n\tthrow new TaskStepsError(`Task step not found for selector: ${selector}.`);\n}\n\nexport function updateTaskStep(\n\tstate: TaskStepsState,\n\tselector: string,\n\tupdate: TaskStepUpdate,\n\tnow: string,\n): TaskStepsState {\n\tconst selected = resolveTaskStepSelector(state.steps, selector);\n\tconst selectedIndex = state.steps.findIndex((step) => step.id === selected.id);\n\tconst steps = state.steps.map(cloneTaskStep);\n\tconst current = steps[selectedIndex];\n\tconst note = optionalBoundedText(update.note, \"Task step note\", MAX_TASK_STEP_NOTE_LENGTH);\n\tconst notes = note\n\t\t? appendUniqueStrings(current.notes, [note], \"Task step note\", MAX_TASK_STEP_NOTE_LENGTH)\n\t\t: [...current.notes];\n\tconst evidence = appendUniqueStrings(\n\t\tcurrent.evidence,\n\t\tupdate.evidence,\n\t\t\"Task step evidence\",\n\t\tMAX_TASK_STEP_EVIDENCE_LENGTH,\n\t);\n\tsteps[selectedIndex] = {\n\t\t...current,\n\t\tcontent:\n\t\t\tupdate.content === undefined\n\t\t\t\t? current.content\n\t\t\t\t: requireBoundedText(update.content, \"Task step content\", MAX_TASK_STEP_CONTENT_LENGTH),\n\t\tactiveForm:\n\t\t\tupdate.activeForm === undefined\n\t\t\t\t? current.activeForm\n\t\t\t\t: optionalBoundedText(update.activeForm, \"Task step active form\", MAX_TASK_STEP_CONTENT_LENGTH),\n\t\tstatus: update.status ?? current.status,\n\t\tpriority: update.priority ?? current.priority,\n\t\towner:\n\t\t\tupdate.owner === undefined\n\t\t\t\t? current.owner\n\t\t\t\t: optionalBoundedText(update.owner, \"Task step owner\", MAX_TASK_STEP_OWNER_LENGTH),\n\t\tnotes,\n\t\tevidence,\n\t\tupdatedAt: now,\n\t};\n\tif (steps[selectedIndex].status === \"in_progress\") demoteOtherActiveSteps(steps, selectedIndex);\n\treturn nextState(state, steps, now);\n}\n\nexport function clearTaskSteps(state: TaskStepsState, now: string): TaskStepsState {\n\treturn {\n\t\t...nextState(state, [], now),\n\t\tarchive: { completed: 0, cancelled: 0 },\n\t};\n}\n\nexport function compactTaskSteps(state: TaskStepsState, now: string): TaskStepsState {\n\tconst completed = state.steps.filter((step) => step.status === \"completed\").length;\n\tconst cancelled = state.steps.filter((step) => step.status === \"cancelled\").length;\n\tconst open = state.steps.filter((step) => step.status !== \"completed\" && step.status !== \"cancelled\");\n\treturn {\n\t\t...nextState(state, open, now),\n\t\tarchive: {\n\t\t\tcompleted: state.archive.completed + completed,\n\t\t\tcancelled: state.archive.cancelled + cancelled,\n\t\t\tcompactedAt: now,\n\t\t},\n\t};\n}\n\nexport function formatTaskSteps(\n\tstate: TaskStepsState,\n\toptions: { includeTerminal?: boolean; maxItems?: number } = {},\n): string {\n\tconst visible = options.includeTerminal\n\t\t? state.steps\n\t\t: state.steps.filter((step) => step.status !== \"completed\" && step.status !== \"cancelled\");\n\tconst maxItems = Math.max(1, Math.min(MAX_TASK_STEPS, Math.floor(options.maxItems ?? 20)));\n\tconst statusMarker: Record<TaskStepStatus, string> = {\n\t\tpending: \" \",\n\t\tin_progress: \">\",\n\t\tcompleted: \"x\",\n\t\tblocked: \"!\",\n\t\tcancelled: \"-\",\n\t};\n\tconst lines = [`Task steps (${visible.length} visible, ${state.steps.length} tracked):`];\n\tfor (const step of visible.slice(0, maxItems)) {\n\t\tconst details = [step.priority, step.owner].filter(Boolean).join(\", \");\n\t\tlines.push(\n\t\t\t`- [${statusMarker[step.status]}] ${step.id} ${step.activeForm || step.content}${details ? ` (${details})` : \"\"}`,\n\t\t);\n\t\tfor (const note of step.notes.slice(-2)) lines.push(` note: ${note}`);\n\t\tfor (const evidence of step.evidence.slice(-2)) lines.push(` evidence: ${evidence}`);\n\t}\n\tif (visible.length > maxItems) lines.push(`- … ${visible.length - maxItems} more`);\n\tif (state.archive.completed || state.archive.cancelled) {\n\t\tlines.push(\n\t\t\t`Archived terminal steps: ${state.archive.completed} completed, ${state.archive.cancelled} cancelled.`,\n\t\t);\n\t}\n\treturn lines.join(\"\\n\");\n}\n\nexport function formatTaskStepsContext(state: TaskStepsState, maxItems = 12): string | undefined {\n\tconst open = state.steps.filter((step) => step.status !== \"completed\" && step.status !== \"cancelled\");\n\tif (open.length === 0) return undefined;\n\tconst limit = Math.max(1, Math.min(MAX_TASK_STEPS, Math.floor(maxItems)));\n\tconst lines = [\n\t\t\"Current native task_steps context for this session:\",\n\t\t\"Open task_steps:\",\n\t\t...open.slice(0, limit).map((step) => `- [${step.status}] ${step.activeForm || step.content}`),\n\t];\n\tif (open.length > limit) lines.push(`- … ${open.length - limit} more open step(s)`);\n\tconst active = open.find((step) => step.status === \"in_progress\");\n\tlines.push(\n\t\t\"\",\n\t\tactive\n\t\t\t? `Continue the in_progress step first: ${active.activeForm || active.content}. Update it completed, blocked, or cancelled as soon as evidence is known.`\n\t\t\t: `No step is in_progress. Start the first open step before unrelated work: ${open[0].activeForm || open[0].content}.`,\n\t\t\"Use task_steps to keep this checklist current and leave no stale in_progress step before the final response.\",\n\t);\n\tif (hasUnverifiedCompletedStep(state)) {\n\t\tlines.push(\n\t\t\t\"A completed step has no evidence attached; attach evidence via task_steps update before treating it as verified.\",\n\t\t);\n\t}\n\t// Wrapped in a marker (mirrors the <memory_context> precedent) so context-gc's\n\t// semantic-memory packer can recognize this as a deterministic, re-derivable context page and\n\t// pack stale copies down to the most recent one instead of letting a full page accumulate every\n\t// turn. The revision (monotonic per mutation) lets a reader tell which page is current.\n\treturn `<task_steps_context revision=${state.revision}>\\n${lines.join(\"\\n\")}\\n</task_steps_context>`;\n}\n\nexport function serializeTaskStepsState(state: TaskStepsState): string {\n\treturn JSON.stringify(cloneTaskStepsState(state), null, 2);\n}\n\nexport function parseTaskStepsState(text: string): TaskStepsState | undefined {\n\ttry {\n\t\tconst parsed: unknown = JSON.parse(text);\n\t\treturn isTaskStepsState(parsed) ? cloneTaskStepsState(parsed) : undefined;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n"]}
1
+ {"version":3,"file":"task-state.js","sourceRoot":"","sources":["../../../src/core/tasks/task-state.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,yBAAyB,CAAC;AAExD,MAAM,CAAC,MAAM,kBAAkB,GAAG,CAAC,SAAS,EAAE,aAAa,EAAE,WAAW,EAAE,SAAS,EAAE,WAAW,CAAU,CAAC;AAG3G,MAAM,CAAC,MAAM,oBAAoB,GAAG,CAAC,KAAK,EAAE,QAAQ,EAAE,MAAM,CAAU,CAAC;AAGvE,MAAM,CAAC,MAAM,cAAc,GAAG,GAAG,CAAC;AAClC,MAAM,CAAC,MAAM,4BAA4B,GAAG,KAAK,CAAC;AAClD,MAAM,yBAAyB,GAAG,KAAK,CAAC;AACxC,MAAM,0BAA0B,GAAG,GAAG,CAAC;AACvC,MAAM,sBAAsB,GAAG,EAAE,CAAC;AAClC,MAAM,6BAA6B,GAAG,KAAK,CAAC;AAC5C,MAAM,0BAA0B,GAAG,EAAE,CAAC;AACtC,MAAM,mCAAmC,GAAG,GAAG,CAAC;AAwDhD,MAAM,OAAO,cAAe,SAAQ,KAAK;IACxC,YAAY,OAAe,EAAE;QAC5B,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,IAAI,GAAG,gBAAgB,CAAC;IAAA,CAC7B;CACD;AAED,SAAS,gBAAgB,CAAC,KAAc,EAA2B;IAClE,OAAO,kBAAkB,CAAC,IAAI,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,MAAM,KAAK,KAAK,CAAC,CAAC;AAAA,CAC7D;AAED,SAAS,kBAAkB,CAAC,KAAc,EAA6B;IACtE,OAAO,oBAAoB,CAAC,IAAI,CAAC,CAAC,QAAQ,EAAE,EAAE,CAAC,QAAQ,KAAK,KAAK,CAAC,CAAC;AAAA,CACnE;AAED,SAAS,iBAAiB,CAAC,MAA+B,EAAE,GAAW,EAAE,SAA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AAC,wCAAwC,MAAM,CAAC,UAAU,IAAI,MAAM,CAAC,OAAO,4EAA4E;QACzJ,CAAC,CAAC,4EAA4E,IAAI,CAAC,CAAC,CAAC,CAAC,UAAU,IAAI,IAAI,CAAC,CAAC,CAAC,CAAC,OAAO,GAAG,EACvH,8GAA8G,CAC9G,CAAC;IACF,IAAI,0BAA0B,CAAC,KAAK,CAAC,EAAE,CAAC;QACvC,KAAK,CAAC,IAAI,CACT,kHAAkH,CAClH,CAAC;IACH,CAAC;IACD,+EAA+E;IAC/E,8FAA8F;IAC9F,gGAAgG;IAChG,wFAAwF;IACxF,OAAO,gCAAgC,KAAK,CAAC,QAAQ,MAAM,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,yBAAyB,CAAC;AAAA,CACrG;AAED,MAAM,UAAU,uBAAuB,CAAC,KAAqB,EAAU;IACtE,OAAO,IAAI,CAAC,SAAS,CAAC,mBAAmB,CAAC,KAAK,CAAC,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC;AAAA,CAC3D;AAED,MAAM,UAAU,mBAAmB,CAAC,IAAY,EAA8B;IAC7E,IAAI,CAAC;QACJ,MAAM,MAAM,GAAY,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;QACzC,OAAO,gBAAgB,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,mBAAmB,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;IAC3E,CAAC;IAAC,MAAM,CAAC;QACR,OAAO,SAAS,CAAC;IAClB,CAAC;AAAA,CACD","sourcesContent":["import { isPlainRecord } from \"../util/value-guards.ts\";\n\nexport const TASK_STEP_STATUSES = [\"pending\", \"in_progress\", \"completed\", \"blocked\", \"cancelled\"] as const;\nexport type TaskStepStatus = (typeof TASK_STEP_STATUSES)[number];\n\nexport const TASK_STEP_PRIORITIES = [\"low\", \"normal\", \"high\"] as const;\nexport type TaskStepPriority = (typeof TASK_STEP_PRIORITIES)[number];\n\nexport const MAX_TASK_STEPS = 100;\nexport const MAX_TASK_STEP_CONTENT_LENGTH = 2_000;\nconst MAX_TASK_STEP_NOTE_LENGTH = 4_000;\nconst MAX_TASK_STEP_OWNER_LENGTH = 200;\nconst MAX_TASK_STEP_EVIDENCE = 32;\nconst MAX_TASK_STEP_EVIDENCE_LENGTH = 2_000;\nconst MAX_TASK_STEP_REQUIREMENTS = 32;\nconst MAX_TASK_STEP_REQUIREMENT_ID_LENGTH = 200;\n\nexport interface TaskStepInput {\n\tcontent: string;\n\tactiveForm?: string;\n\tstatus?: TaskStepStatus;\n\tpriority?: TaskStepPriority;\n\towner?: string;\n\trequirementIds?: readonly string[];\n\tnote?: string;\n\tnotes?: readonly string[];\n\tevidence?: readonly string[];\n}\n\nexport interface TaskStep {\n\tid: string;\n\tcontent: string;\n\tactiveForm?: string;\n\tstatus: TaskStepStatus;\n\tpriority?: TaskStepPriority;\n\towner?: string;\n\t/** Goal requirements this foreground step advances. Optional only for snapshots from older sessions. */\n\trequirementIds?: readonly string[];\n\tnotes: readonly string[];\n\tevidence: readonly string[];\n\tcreatedAt: string;\n\tupdatedAt: string;\n}\n\nexport interface TaskStepsArchive {\n\tcompleted: number;\n\tcancelled: number;\n\tcompactedAt?: string;\n}\n\nexport interface TaskStepsState {\n\tversion: 1;\n\trevision: number;\n\tnextStepNumber: number;\n\tsteps: readonly TaskStep[];\n\tarchive: TaskStepsArchive;\n\tcreatedAt: string;\n\tupdatedAt: string;\n}\n\nexport interface TaskStepUpdate {\n\tcontent?: string;\n\tactiveForm?: string;\n\tstatus?: TaskStepStatus;\n\tpriority?: TaskStepPriority;\n\towner?: string;\n\trequirementIds?: readonly string[];\n\tnote?: string;\n\tevidence?: readonly string[];\n}\n\nexport class TaskStepsError extends Error {\n\tconstructor(message: string) {\n\t\tsuper(message);\n\t\tthis.name = \"TaskStepsError\";\n\t}\n}\n\nfunction isTaskStepStatus(value: unknown): value is TaskStepStatus {\n\treturn TASK_STEP_STATUSES.some((status) => status === value);\n}\n\nfunction isTaskStepPriority(value: unknown): value is TaskStepPriority {\n\treturn TASK_STEP_PRIORITIES.some((priority) => priority === value);\n}\n\nfunction hasOptionalString(record: Record<string, unknown>, key: string, maxLength: number): boolean {\n\tconst value = record[key];\n\treturn value === undefined || (typeof value === \"string\" && value.length <= maxLength);\n}\n\nfunction isBoundedStringArray(value: unknown, maxItems: number, maxLength: number): value is readonly string[] {\n\treturn (\n\t\tArray.isArray(value) &&\n\t\tvalue.length <= maxItems &&\n\t\tvalue.every((item) => typeof item === \"string\" && item.length > 0 && item.length <= maxLength)\n\t);\n}\n\nfunction isTaskStep(value: unknown): value is TaskStep {\n\tif (!isPlainRecord(value)) return false;\n\treturn (\n\t\ttypeof value.id === \"string\" &&\n\t\t/^step-[1-9]\\d*$/.test(value.id) &&\n\t\ttypeof value.content === \"string\" &&\n\t\tvalue.content.length > 0 &&\n\t\tvalue.content.length <= MAX_TASK_STEP_CONTENT_LENGTH &&\n\t\thasOptionalString(value, \"activeForm\", MAX_TASK_STEP_CONTENT_LENGTH) &&\n\t\tisTaskStepStatus(value.status) &&\n\t\t(value.priority === undefined || isTaskStepPriority(value.priority)) &&\n\t\thasOptionalString(value, \"owner\", MAX_TASK_STEP_OWNER_LENGTH) &&\n\t\t(value.requirementIds === undefined ||\n\t\t\tisBoundedStringArray(value.requirementIds, MAX_TASK_STEP_REQUIREMENTS, MAX_TASK_STEP_REQUIREMENT_ID_LENGTH)) &&\n\t\tisBoundedStringArray(value.notes, MAX_TASK_STEP_EVIDENCE, MAX_TASK_STEP_NOTE_LENGTH) &&\n\t\tisBoundedStringArray(value.evidence, MAX_TASK_STEP_EVIDENCE, MAX_TASK_STEP_EVIDENCE_LENGTH) &&\n\t\ttypeof value.createdAt === \"string\" &&\n\t\ttypeof value.updatedAt === \"string\"\n\t);\n}\n\nfunction isTaskStepsArchive(value: unknown): value is TaskStepsArchive {\n\tif (!isPlainRecord(value)) return false;\n\treturn (\n\t\tNumber.isInteger(value.completed) &&\n\t\tNumber(value.completed) >= 0 &&\n\t\tNumber.isInteger(value.cancelled) &&\n\t\tNumber(value.cancelled) >= 0 &&\n\t\thasOptionalString(value, \"compactedAt\", 100)\n\t);\n}\n\nexport function isTaskStepsState(value: unknown): value is TaskStepsState {\n\tif (!isPlainRecord(value)) return false;\n\tif (\n\t\tvalue.version !== 1 ||\n\t\t!Number.isInteger(value.revision) ||\n\t\tNumber(value.revision) < 0 ||\n\t\t!Number.isInteger(value.nextStepNumber) ||\n\t\tNumber(value.nextStepNumber) < 1 ||\n\t\t!Array.isArray(value.steps) ||\n\t\tvalue.steps.length > MAX_TASK_STEPS ||\n\t\t!value.steps.every(isTaskStep) ||\n\t\t!isTaskStepsArchive(value.archive) ||\n\t\ttypeof value.createdAt !== \"string\" ||\n\t\ttypeof value.updatedAt !== \"string\"\n\t) {\n\t\treturn false;\n\t}\n\tconst ids = new Set(value.steps.map((step) => step.id));\n\treturn ids.size === value.steps.length && value.steps.filter((step) => step.status === \"in_progress\").length <= 1;\n}\n\nfunction cloneTaskStep(step: TaskStep): TaskStep {\n\treturn {\n\t\t...step,\n\t\trequirementIds: [...(step.requirementIds ?? [])],\n\t\tnotes: [...step.notes],\n\t\tevidence: [...step.evidence],\n\t};\n}\n\nexport function cloneTaskStepsState(state: TaskStepsState): TaskStepsState {\n\treturn {\n\t\t...state,\n\t\tsteps: state.steps.map(cloneTaskStep),\n\t\tarchive: { ...state.archive },\n\t};\n}\n\nexport function createTaskStepsState(now: string): TaskStepsState {\n\treturn {\n\t\tversion: 1,\n\t\trevision: 0,\n\t\tnextStepNumber: 1,\n\t\tsteps: [],\n\t\tarchive: { completed: 0, cancelled: 0 },\n\t\tcreatedAt: now,\n\t\tupdatedAt: now,\n\t};\n}\n\nfunction requireBoundedText(value: string, label: string, maxLength: number): string {\n\tconst normalized = value.trim();\n\tif (!normalized) throw new TaskStepsError(`${label} is required.`);\n\tif (normalized.length > maxLength) throw new TaskStepsError(`${label} must be at most ${maxLength} characters.`);\n\treturn normalized;\n}\n\nfunction optionalBoundedText(value: string | undefined, label: string, maxLength: number): string | undefined {\n\tif (value === undefined) return undefined;\n\tconst normalized = value.trim();\n\tif (!normalized) return undefined;\n\tif (normalized.length > maxLength) throw new TaskStepsError(`${label} must be at most ${maxLength} characters.`);\n\treturn normalized;\n}\n\nfunction normalizeStrings(values: readonly string[] | undefined, label: string, maxLength: number): string[] {\n\tif (!values) return [];\n\tconst normalized: string[] = [];\n\tfor (const value of values) {\n\t\tconst item = requireBoundedText(value, label, maxLength);\n\t\tif (!normalized.includes(item)) normalized.push(item);\n\t}\n\tif (normalized.length > MAX_TASK_STEP_EVIDENCE) {\n\t\tthrow new TaskStepsError(`${label} supports at most ${MAX_TASK_STEP_EVIDENCE} entries.`);\n\t}\n\treturn normalized;\n}\n\nfunction appendUniqueStrings(\n\tcurrent: readonly string[],\n\tvalues: readonly string[] | undefined,\n\tlabel: string,\n\tmaxLength: number,\n): string[] {\n\tconst appended = [...current];\n\tfor (const value of normalizeStrings(values, label, maxLength)) {\n\t\tif (!appended.includes(value)) appended.push(value);\n\t}\n\tif (appended.length > MAX_TASK_STEP_EVIDENCE) {\n\t\tthrow new TaskStepsError(`${label} supports at most ${MAX_TASK_STEP_EVIDENCE} entries.`);\n\t}\n\treturn appended;\n}\n\nfunction normalizeInputNotes(input: TaskStepInput): string[] {\n\tconst notes = normalizeStrings(input.notes, \"Task step note\", MAX_TASK_STEP_NOTE_LENGTH);\n\tconst note = optionalBoundedText(input.note, \"Task step note\", MAX_TASK_STEP_NOTE_LENGTH);\n\tif (note && !notes.includes(note)) notes.push(note);\n\treturn notes;\n}\n\n/**\n * Find an OPEN (non-terminal) step whose content matches `content` case-insensitively.\n * Terminal steps (completed/cancelled) are deliberately excluded so a legitimate re-add of\n * previously finished work still creates a new step.\n */\nexport function findOpenDuplicateStep(steps: readonly TaskStep[], content: string): TaskStep | undefined {\n\tconst normalized = content.trim().toLocaleLowerCase();\n\tif (!normalized) return undefined;\n\treturn steps.find(\n\t\t(step) =>\n\t\t\tstep.status !== \"completed\" && step.status !== \"cancelled\" && step.content.toLocaleLowerCase() === normalized,\n\t);\n}\n\n/** True when a completed step has no evidence attached (a verification nudge candidate). */\nexport function hasUnverifiedCompletedStep(state: TaskStepsState): boolean {\n\treturn state.steps.some((step) => step.status === \"completed\" && step.evidence.length === 0);\n}\n\nfunction demoteOtherActiveSteps(steps: TaskStep[], activeIndex: number): void {\n\tfor (let index = 0; index < steps.length; index++) {\n\t\tif (index !== activeIndex && steps[index].status === \"in_progress\") {\n\t\t\tsteps[index] = { ...steps[index], status: \"pending\" };\n\t\t}\n\t}\n}\n\nfunction nextState(state: TaskStepsState, steps: readonly TaskStep[], now: string): TaskStepsState {\n\treturn {\n\t\t...state,\n\t\trevision: state.revision + 1,\n\t\tsteps: steps.map(cloneTaskStep),\n\t\tarchive: { ...state.archive },\n\t\tupdatedAt: now,\n\t};\n}\n\nfunction createStep(args: {\n\tinput: TaskStepInput;\n\tid: string;\n\tcreatedAt: string;\n\tupdatedAt: string;\n\texisting?: TaskStep;\n}): TaskStep {\n\tconst existing = args.existing;\n\tconst notes =\n\t\targs.input.note === undefined && args.input.notes === undefined\n\t\t\t? [...(existing?.notes ?? [])]\n\t\t\t: normalizeInputNotes(args.input);\n\tconst evidence =\n\t\targs.input.evidence === undefined\n\t\t\t? [...(existing?.evidence ?? [])]\n\t\t\t: normalizeStrings(args.input.evidence, \"Task step evidence\", MAX_TASK_STEP_EVIDENCE_LENGTH);\n\tconst requirementIds =\n\t\targs.input.requirementIds === undefined\n\t\t\t? [...(existing?.requirementIds ?? [])]\n\t\t\t: normalizeStrings(args.input.requirementIds, \"Task step requirement id\", MAX_TASK_STEP_REQUIREMENT_ID_LENGTH);\n\treturn {\n\t\tid: args.id,\n\t\tcontent: requireBoundedText(args.input.content, \"Task step content\", MAX_TASK_STEP_CONTENT_LENGTH),\n\t\tactiveForm:\n\t\t\targs.input.activeForm === undefined\n\t\t\t\t? existing?.activeForm\n\t\t\t\t: optionalBoundedText(args.input.activeForm, \"Task step active form\", MAX_TASK_STEP_CONTENT_LENGTH),\n\t\tstatus: args.input.status ?? existing?.status ?? \"pending\",\n\t\tpriority: args.input.priority ?? existing?.priority,\n\t\towner:\n\t\t\targs.input.owner === undefined\n\t\t\t\t? existing?.owner\n\t\t\t\t: optionalBoundedText(args.input.owner, \"Task step owner\", MAX_TASK_STEP_OWNER_LENGTH),\n\t\trequirementIds,\n\t\tnotes,\n\t\tevidence,\n\t\tcreatedAt: args.createdAt,\n\t\tupdatedAt: args.updatedAt,\n\t};\n}\n\nexport function setTaskSteps(state: TaskStepsState, inputs: readonly TaskStepInput[], now: string): TaskStepsState {\n\tif (inputs.length > MAX_TASK_STEPS) {\n\t\tthrow new TaskStepsError(`Task steps supports at most ${MAX_TASK_STEPS} steps.`);\n\t}\n\tconst existingByContent = new Map<string, TaskStep[]>();\n\tfor (const step of state.steps) {\n\t\tconst key = step.content.toLocaleLowerCase();\n\t\tconst matches = existingByContent.get(key) ?? [];\n\t\tmatches.push(step);\n\t\texistingByContent.set(key, matches);\n\t}\n\n\tlet nextStepNumber = state.nextStepNumber;\n\tconst steps = inputs.map((input) => {\n\t\tconst content = requireBoundedText(input.content, \"Task step content\", MAX_TASK_STEP_CONTENT_LENGTH);\n\t\tconst matches = existingByContent.get(content.toLocaleLowerCase());\n\t\tconst existing = matches?.shift();\n\t\tconst id = existing?.id ?? `step-${nextStepNumber++}`;\n\t\treturn createStep({\n\t\t\tinput: { ...input, content },\n\t\t\tid,\n\t\t\tcreatedAt: existing?.createdAt ?? now,\n\t\t\tupdatedAt: now,\n\t\t\texisting,\n\t\t});\n\t});\n\tconst activeIndex = steps.findLastIndex((step) => step.status === \"in_progress\");\n\tif (activeIndex >= 0) demoteOtherActiveSteps(steps, activeIndex);\n\treturn { ...nextState(state, steps, now), nextStepNumber };\n}\n\nexport function addTaskStep(state: TaskStepsState, input: TaskStepInput, now: string): TaskStepsState {\n\t// Dedupe against OPEN steps only, before the capacity check: a duplicate re-add of an\n\t// already-open step is a no-op regardless of whether the list happens to be full. Terminal\n\t// (completed/cancelled) matches are excluded so a legitimate re-add still creates a step.\n\tif (findOpenDuplicateStep(state.steps, input.content)) return state;\n\tif (state.steps.length >= MAX_TASK_STEPS) {\n\t\tthrow new TaskStepsError(`Task steps already has the maximum ${MAX_TASK_STEPS} steps.`);\n\t}\n\tconst step = createStep({ input, id: `step-${state.nextStepNumber}`, createdAt: now, updatedAt: now });\n\tconst steps = [...state.steps.map(cloneTaskStep), step];\n\tif (step.status === \"in_progress\") demoteOtherActiveSteps(steps, steps.length - 1);\n\treturn { ...nextState(state, steps, now), nextStepNumber: state.nextStepNumber + 1 };\n}\n\nexport function resolveTaskStepSelector(steps: readonly TaskStep[], selector: string): TaskStep {\n\tconst normalized = selector.trim().toLocaleLowerCase();\n\tif (!normalized) throw new TaskStepsError(\"Task step selector is required.\");\n\tif (normalized === \"current\" || normalized === \"active\") {\n\t\tconst active = steps.find((step) => step.status === \"in_progress\");\n\t\tif (!active) throw new TaskStepsError(\"No in_progress task step was found.\");\n\t\treturn active;\n\t}\n\n\tconst exactId = steps.find((step) => step.id.toLocaleLowerCase() === normalized);\n\tif (exactId) return exactId;\n\tconst idPrefix = steps.filter((step) => step.id.toLocaleLowerCase().startsWith(normalized));\n\tif (idPrefix.length === 1) return idPrefix[0];\n\tif (idPrefix.length > 1) {\n\t\tthrow new TaskStepsError(`Task step selector is ambiguous: ${idPrefix.map((step) => step.id).join(\", \")}.`);\n\t}\n\n\tconst exactContent = steps.filter((step) => step.content.toLocaleLowerCase() === normalized);\n\tif (exactContent.length === 1) return exactContent[0];\n\tconst contentMatches = steps.filter((step) => step.content.toLocaleLowerCase().includes(normalized));\n\tif (contentMatches.length === 1) return contentMatches[0];\n\tif (exactContent.length > 1 || contentMatches.length > 1) {\n\t\tconst matches = exactContent.length > 1 ? exactContent : contentMatches;\n\t\tthrow new TaskStepsError(`Task step selector is ambiguous: ${matches.map((step) => step.id).join(\", \")}.`);\n\t}\n\tthrow new TaskStepsError(`Task step not found for selector: ${selector}.`);\n}\n\nexport function updateTaskStep(\n\tstate: TaskStepsState,\n\tselector: string,\n\tupdate: TaskStepUpdate,\n\tnow: string,\n): TaskStepsState {\n\tconst selected = resolveTaskStepSelector(state.steps, selector);\n\tconst selectedIndex = state.steps.findIndex((step) => step.id === selected.id);\n\tconst steps = state.steps.map(cloneTaskStep);\n\tconst current = steps[selectedIndex];\n\tconst note = optionalBoundedText(update.note, \"Task step note\", MAX_TASK_STEP_NOTE_LENGTH);\n\tconst notes = note\n\t\t? appendUniqueStrings(current.notes, [note], \"Task step note\", MAX_TASK_STEP_NOTE_LENGTH)\n\t\t: [...current.notes];\n\tconst evidence = appendUniqueStrings(\n\t\tcurrent.evidence,\n\t\tupdate.evidence,\n\t\t\"Task step evidence\",\n\t\tMAX_TASK_STEP_EVIDENCE_LENGTH,\n\t);\n\tsteps[selectedIndex] = {\n\t\t...current,\n\t\tcontent:\n\t\t\tupdate.content === undefined\n\t\t\t\t? current.content\n\t\t\t\t: requireBoundedText(update.content, \"Task step content\", MAX_TASK_STEP_CONTENT_LENGTH),\n\t\tactiveForm:\n\t\t\tupdate.activeForm === undefined\n\t\t\t\t? current.activeForm\n\t\t\t\t: optionalBoundedText(update.activeForm, \"Task step active form\", MAX_TASK_STEP_CONTENT_LENGTH),\n\t\tstatus: update.status ?? current.status,\n\t\tpriority: update.priority ?? current.priority,\n\t\towner:\n\t\t\tupdate.owner === undefined\n\t\t\t\t? current.owner\n\t\t\t\t: optionalBoundedText(update.owner, \"Task step owner\", MAX_TASK_STEP_OWNER_LENGTH),\n\t\trequirementIds:\n\t\t\tupdate.requirementIds === undefined\n\t\t\t\t? [...(current.requirementIds ?? [])]\n\t\t\t\t: normalizeStrings(update.requirementIds, \"Task step requirement id\", MAX_TASK_STEP_REQUIREMENT_ID_LENGTH),\n\t\tnotes,\n\t\tevidence,\n\t\tupdatedAt: now,\n\t};\n\tif (steps[selectedIndex].status === \"in_progress\") demoteOtherActiveSteps(steps, selectedIndex);\n\treturn nextState(state, steps, now);\n}\n\nexport function clearTaskSteps(state: TaskStepsState, now: string): TaskStepsState {\n\treturn {\n\t\t...nextState(state, [], now),\n\t\tarchive: { completed: 0, cancelled: 0 },\n\t};\n}\n\nexport function compactTaskSteps(state: TaskStepsState, now: string): TaskStepsState {\n\tconst completed = state.steps.filter((step) => step.status === \"completed\").length;\n\tconst cancelled = state.steps.filter((step) => step.status === \"cancelled\").length;\n\tconst open = state.steps.filter((step) => step.status !== \"completed\" && step.status !== \"cancelled\");\n\treturn {\n\t\t...nextState(state, open, now),\n\t\tarchive: {\n\t\t\tcompleted: state.archive.completed + completed,\n\t\t\tcancelled: state.archive.cancelled + cancelled,\n\t\t\tcompactedAt: now,\n\t\t},\n\t};\n}\n\nexport function formatTaskSteps(\n\tstate: TaskStepsState,\n\toptions: { includeTerminal?: boolean; maxItems?: number } = {},\n): string {\n\tconst visible = options.includeTerminal\n\t\t? state.steps\n\t\t: state.steps.filter((step) => step.status !== \"completed\" && step.status !== \"cancelled\");\n\tconst maxItems = Math.max(1, Math.min(MAX_TASK_STEPS, Math.floor(options.maxItems ?? 20)));\n\tconst statusMarker: Record<TaskStepStatus, string> = {\n\t\tpending: \" \",\n\t\tin_progress: \">\",\n\t\tcompleted: \"x\",\n\t\tblocked: \"!\",\n\t\tcancelled: \"-\",\n\t};\n\tconst lines = [`Task steps (${visible.length} visible, ${state.steps.length} tracked):`];\n\tfor (const step of visible.slice(0, maxItems)) {\n\t\tconst details = [\n\t\t\tstep.priority,\n\t\t\tstep.owner,\n\t\t\tstep.requirementIds?.length ? `requirements: ${step.requirementIds.join(\", \")}` : undefined,\n\t\t]\n\t\t\t.filter(Boolean)\n\t\t\t.join(\", \");\n\t\tlines.push(\n\t\t\t`- [${statusMarker[step.status]}] ${step.id} ${step.activeForm || step.content}${details ? ` (${details})` : \"\"}`,\n\t\t);\n\t\tfor (const note of step.notes.slice(-2)) lines.push(` note: ${note}`);\n\t\tfor (const evidence of step.evidence.slice(-2)) lines.push(` evidence: ${evidence}`);\n\t}\n\tif (visible.length > maxItems) lines.push(`- … ${visible.length - maxItems} more`);\n\tif (state.archive.completed || state.archive.cancelled) {\n\t\tlines.push(\n\t\t\t`Archived terminal steps: ${state.archive.completed} completed, ${state.archive.cancelled} cancelled.`,\n\t\t);\n\t}\n\treturn lines.join(\"\\n\");\n}\n\nexport function formatTaskStepsContext(state: TaskStepsState, maxItems = 12): string | undefined {\n\tconst open = state.steps.filter((step) => step.status !== \"completed\" && step.status !== \"cancelled\");\n\tif (open.length === 0) return undefined;\n\tconst limit = Math.max(1, Math.min(MAX_TASK_STEPS, Math.floor(maxItems)));\n\tconst lines = [\n\t\t\"Current native task_steps context for this session:\",\n\t\t\"Open task_steps:\",\n\t\t...open.slice(0, limit).map((step) => `- [${step.status}] ${step.activeForm || step.content}`),\n\t];\n\tif (open.length > limit) lines.push(`- … ${open.length - limit} more open step(s)`);\n\tconst active = open.find((step) => step.status === \"in_progress\");\n\tlines.push(\n\t\t\"\",\n\t\tactive\n\t\t\t? `Continue the in_progress step first: ${active.activeForm || active.content}. Update it completed, blocked, or cancelled as soon as evidence is known.`\n\t\t\t: `No step is in_progress. Start the first open step before unrelated work: ${open[0].activeForm || open[0].content}.`,\n\t\t\"Use task_steps to keep this checklist current and leave no stale in_progress step before the final response.\",\n\t);\n\tif (hasUnverifiedCompletedStep(state)) {\n\t\tlines.push(\n\t\t\t\"A completed step has no evidence attached; attach evidence via task_steps update before treating it as verified.\",\n\t\t);\n\t}\n\t// Wrapped in a marker (mirrors the <memory_context> precedent) so context-gc's\n\t// semantic-memory packer can recognize this as a deterministic, re-derivable context page and\n\t// pack stale copies down to the most recent one instead of letting a full page accumulate every\n\t// turn. The revision (monotonic per mutation) lets a reader tell which page is current.\n\treturn `<task_steps_context revision=${state.revision}>\\n${lines.join(\"\\n\")}\\n</task_steps_context>`;\n}\n\nexport function serializeTaskStepsState(state: TaskStepsState): string {\n\treturn JSON.stringify(cloneTaskStepsState(state), null, 2);\n}\n\nexport function parseTaskStepsState(text: string): TaskStepsState | undefined {\n\ttry {\n\t\tconst parsed: unknown = JSON.parse(text);\n\t\treturn isTaskStepsState(parsed) ? cloneTaskStepsState(parsed) : undefined;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n"]}
@@ -0,0 +1,13 @@
1
+ import type { HarnessCapability } from "./capability-contract.ts";
2
+ import type { CapabilityEnforcementKind, OrchestrationProfile } from "./orchestration/contracts.ts";
3
+ export interface ToolCapabilityPolicy {
4
+ capabilityCandidates: readonly HarnessCapability[];
5
+ enforcement: CapabilityEnforcementKind;
6
+ }
7
+ export declare function getToolCapabilityPolicy(toolName: string): ToolCapabilityPolicy | undefined;
8
+ export declare function hasToolCapabilityPolicy(toolName: string): boolean;
9
+ export declare function requiredEnvelopeCapabilities(toolName: string, args?: unknown): readonly HarnessCapability[];
10
+ export declare function envelopeHasToolCapability(capabilities: readonly HarnessCapability[], toolName: string, args?: unknown): boolean;
11
+ export declare function resolveProfileToolCapability(profile: Pick<OrchestrationProfile, "capabilityCeiling">, toolName: string): HarnessCapability | undefined;
12
+ export declare function describeToolCapabilityAuthority(toolName: string): string;
13
+ //# sourceMappingURL=tool-capability-policy.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tool-capability-policy.d.ts","sourceRoot":"","sources":["../../src/core/tool-capability-policy.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,0BAA0B,CAAC;AAClE,OAAO,KAAK,EAAE,yBAAyB,EAAE,oBAAoB,EAAE,MAAM,8BAA8B,CAAC;AAEpG,MAAM,WAAW,oBAAoB;IACpC,oBAAoB,EAAE,SAAS,iBAAiB,EAAE,CAAC;IACnD,WAAW,EAAE,yBAAyB,CAAC;CACvC;AAkCD,wBAAgB,uBAAuB,CAAC,QAAQ,EAAE,MAAM,GAAG,oBAAoB,GAAG,SAAS,CAE1F;AAED,wBAAgB,uBAAuB,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAEjE;AAED,wBAAgB,4BAA4B,CAAC,QAAQ,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,OAAO,GAAG,SAAS,iBAAiB,EAAE,CAE3G;AAED,wBAAgB,yBAAyB,CACxC,YAAY,EAAE,SAAS,iBAAiB,EAAE,EAC1C,QAAQ,EAAE,MAAM,EAChB,IAAI,CAAC,EAAE,OAAO,GACZ,OAAO,CAGT;AAED,wBAAgB,4BAA4B,CAC3C,OAAO,EAAE,IAAI,CAAC,oBAAoB,EAAE,mBAAmB,CAAC,EACxD,QAAQ,EAAE,MAAM,GACd,iBAAiB,GAAG,SAAS,CAI/B;AAED,wBAAgB,+BAA+B,CAAC,QAAQ,EAAE,MAAM,GAAG,MAAM,CAqCxE","sourcesContent":["import type { HarnessCapability } from \"./capability-contract.ts\";\nimport type { CapabilityEnforcementKind, OrchestrationProfile } from \"./orchestration/contracts.ts\";\n\nexport interface ToolCapabilityPolicy {\n\tcapabilityCandidates: readonly HarnessCapability[];\n\tenforcement: CapabilityEnforcementKind;\n}\n\nfunction policy(\n\tcapabilityCandidates: readonly HarnessCapability[],\n\tenforcement: CapabilityEnforcementKind,\n): ToolCapabilityPolicy {\n\treturn Object.freeze({\n\t\tcapabilityCandidates: Object.freeze([...capabilityCandidates]),\n\t\tenforcement,\n\t});\n}\n\nconst READ_POLICY = policy([\"filesystem.read\", \"worktree.read\"], \"path-scope\");\nconst WRITE_POLICY = policy([\"filesystem.write\", \"worktree.mutate\"], \"path-scope\");\nconst PROCESS_POLICY = policy([\"process.exec\", \"tests.execute\"], \"process-launcher\");\nconst NETWORK_POLICY = policy([\"network.http\", \"service.mcp\"], \"service-proxy\");\nconst DELEGATE_POLICY = policy([\"workflow.delegate\"], \"control-plane\");\n\nconst TOOL_CAPABILITY_POLICIES = new Map<string, ToolCapabilityPolicy>([\n\t...[\"read\", \"ls\", \"grep\", \"find\"].map((toolName) => [toolName, READ_POLICY] as const),\n\t...[\"write\", \"edit\", \"edit-diff\"].map((toolName) => [toolName, WRITE_POLICY] as const),\n\t...[\"bash\", \"python\", \"powershell\", \"shell\", \"run_toolkit_script\", \"run_process\"].map(\n\t\t(toolName) => [toolName, PROCESS_POLICY] as const,\n\t),\n\t...[\"fetch\", \"web_search\"].map((toolName) => [toolName, NETWORK_POLICY] as const),\n\t[\"skill_audit\", policy([\"skill.read\"], \"path-scope\")],\n\t[\"skillify\", policy([\"skill.write\"], \"path-scope\")],\n\t[\"extensionify\", policy([\"source.write\"], \"path-scope\")],\n\t[\"goal\", policy([\"memory.mutate\"], \"memory-broker\")],\n\t[\"memory\", policy([\"memory.mutate\", \"memory.query\"], \"memory-broker\")],\n\t...[\"delegate\", \"delegate_status\"].map((toolName) => [toolName, DELEGATE_POLICY] as const),\n\t[\"model_fitness\", policy([\"research.execute\"], \"control-plane\")],\n]);\n\nexport function getToolCapabilityPolicy(toolName: string): ToolCapabilityPolicy | undefined {\n\treturn TOOL_CAPABILITY_POLICIES.get(toolName.toLowerCase());\n}\n\nexport function hasToolCapabilityPolicy(toolName: string): boolean {\n\treturn getToolCapabilityPolicy(toolName) !== undefined;\n}\n\nexport function requiredEnvelopeCapabilities(toolName: string, args?: unknown): readonly HarnessCapability[] {\n\treturn toolCapabilityCandidates(toolName, args).slice(0, 1);\n}\n\nexport function envelopeHasToolCapability(\n\tcapabilities: readonly HarnessCapability[],\n\ttoolName: string,\n\targs?: unknown,\n): boolean {\n\tconst candidates = toolCapabilityCandidates(toolName, args);\n\treturn candidates.length > 0 && candidates.some((capability) => capabilities.includes(capability));\n}\n\nexport function resolveProfileToolCapability(\n\tprofile: Pick<OrchestrationProfile, \"capabilityCeiling\">,\n\ttoolName: string,\n): HarnessCapability | undefined {\n\treturn getToolCapabilityPolicy(toolName)?.capabilityCandidates.find((capability) =>\n\t\tprofile.capabilityCeiling.includes(capability),\n\t);\n}\n\nexport function describeToolCapabilityAuthority(toolName: string): string {\n\tswitch (getToolCapabilityPolicy(toolName)?.capabilityCandidates[0]) {\n\t\tcase \"filesystem.read\":\n\t\tcase \"worktree.read\":\n\t\t\treturn \"read\";\n\t\tcase \"filesystem.write\":\n\t\tcase \"worktree.mutate\":\n\t\t\treturn \"write\";\n\t\tcase \"process.exec\":\n\t\tcase \"tests.execute\":\n\t\t\treturn \"process\";\n\t\tcase \"network.http\":\n\t\tcase \"service.mcp\":\n\t\t\treturn \"network\";\n\t\tcase \"memory.query\":\n\t\tcase \"memory.mutate\":\n\t\t\treturn \"memory\";\n\t\tcase \"workflow.delegate\":\n\t\t\treturn \"delegation\";\n\t\tcase \"skill.read\":\n\t\tcase \"skill.write\":\n\t\t\treturn \"skill\";\n\t\tcase \"source.read\":\n\t\tcase \"source.write\":\n\t\t\treturn \"source\";\n\t\tcase \"research.execute\":\n\t\t\treturn \"research\";\n\t\tcase \"settings.read\":\n\t\tcase \"settings.write\":\n\t\t\treturn \"settings\";\n\t\tcase \"publish.execute\":\n\t\t\treturn \"publish\";\n\t\tcase \"credentials.modify\":\n\t\t\treturn \"authentication\";\n\t\tdefault:\n\t\t\treturn \"capability\";\n\t}\n}\n\nfunction toolCapabilityCandidates(toolName: string, args?: unknown): readonly HarnessCapability[] {\n\tif (toolName.toLowerCase() === \"memory\") {\n\t\treturn args && typeof args === \"object\" && \"query\" in args ? [\"memory.query\"] : [\"memory.mutate\"];\n\t}\n\treturn getToolCapabilityPolicy(toolName)?.capabilityCandidates ?? [];\n}\n"]}
@@ -0,0 +1,85 @@
1
+ function policy(capabilityCandidates, enforcement) {
2
+ return Object.freeze({
3
+ capabilityCandidates: Object.freeze([...capabilityCandidates]),
4
+ enforcement,
5
+ });
6
+ }
7
+ const READ_POLICY = policy(["filesystem.read", "worktree.read"], "path-scope");
8
+ const WRITE_POLICY = policy(["filesystem.write", "worktree.mutate"], "path-scope");
9
+ const PROCESS_POLICY = policy(["process.exec", "tests.execute"], "process-launcher");
10
+ const NETWORK_POLICY = policy(["network.http", "service.mcp"], "service-proxy");
11
+ const DELEGATE_POLICY = policy(["workflow.delegate"], "control-plane");
12
+ const TOOL_CAPABILITY_POLICIES = new Map([
13
+ ...["read", "ls", "grep", "find"].map((toolName) => [toolName, READ_POLICY]),
14
+ ...["write", "edit", "edit-diff"].map((toolName) => [toolName, WRITE_POLICY]),
15
+ ...["bash", "python", "powershell", "shell", "run_toolkit_script", "run_process"].map((toolName) => [toolName, PROCESS_POLICY]),
16
+ ...["fetch", "web_search"].map((toolName) => [toolName, NETWORK_POLICY]),
17
+ ["skill_audit", policy(["skill.read"], "path-scope")],
18
+ ["skillify", policy(["skill.write"], "path-scope")],
19
+ ["extensionify", policy(["source.write"], "path-scope")],
20
+ ["goal", policy(["memory.mutate"], "memory-broker")],
21
+ ["memory", policy(["memory.mutate", "memory.query"], "memory-broker")],
22
+ ...["delegate", "delegate_status"].map((toolName) => [toolName, DELEGATE_POLICY]),
23
+ ["model_fitness", policy(["research.execute"], "control-plane")],
24
+ ]);
25
+ export function getToolCapabilityPolicy(toolName) {
26
+ return TOOL_CAPABILITY_POLICIES.get(toolName.toLowerCase());
27
+ }
28
+ export function hasToolCapabilityPolicy(toolName) {
29
+ return getToolCapabilityPolicy(toolName) !== undefined;
30
+ }
31
+ export function requiredEnvelopeCapabilities(toolName, args) {
32
+ return toolCapabilityCandidates(toolName, args).slice(0, 1);
33
+ }
34
+ export function envelopeHasToolCapability(capabilities, toolName, args) {
35
+ const candidates = toolCapabilityCandidates(toolName, args);
36
+ return candidates.length > 0 && candidates.some((capability) => capabilities.includes(capability));
37
+ }
38
+ export function resolveProfileToolCapability(profile, toolName) {
39
+ return getToolCapabilityPolicy(toolName)?.capabilityCandidates.find((capability) => profile.capabilityCeiling.includes(capability));
40
+ }
41
+ export function describeToolCapabilityAuthority(toolName) {
42
+ switch (getToolCapabilityPolicy(toolName)?.capabilityCandidates[0]) {
43
+ case "filesystem.read":
44
+ case "worktree.read":
45
+ return "read";
46
+ case "filesystem.write":
47
+ case "worktree.mutate":
48
+ return "write";
49
+ case "process.exec":
50
+ case "tests.execute":
51
+ return "process";
52
+ case "network.http":
53
+ case "service.mcp":
54
+ return "network";
55
+ case "memory.query":
56
+ case "memory.mutate":
57
+ return "memory";
58
+ case "workflow.delegate":
59
+ return "delegation";
60
+ case "skill.read":
61
+ case "skill.write":
62
+ return "skill";
63
+ case "source.read":
64
+ case "source.write":
65
+ return "source";
66
+ case "research.execute":
67
+ return "research";
68
+ case "settings.read":
69
+ case "settings.write":
70
+ return "settings";
71
+ case "publish.execute":
72
+ return "publish";
73
+ case "credentials.modify":
74
+ return "authentication";
75
+ default:
76
+ return "capability";
77
+ }
78
+ }
79
+ function toolCapabilityCandidates(toolName, args) {
80
+ if (toolName.toLowerCase() === "memory") {
81
+ return args && typeof args === "object" && "query" in args ? ["memory.query"] : ["memory.mutate"];
82
+ }
83
+ return getToolCapabilityPolicy(toolName)?.capabilityCandidates ?? [];
84
+ }
85
+ //# sourceMappingURL=tool-capability-policy.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tool-capability-policy.js","sourceRoot":"","sources":["../../src/core/tool-capability-policy.ts"],"names":[],"mappings":"AAQA,SAAS,MAAM,CACd,oBAAkD,EAClD,WAAsC,EACf;IACvB,OAAO,MAAM,CAAC,MAAM,CAAC;QACpB,oBAAoB,EAAE,MAAM,CAAC,MAAM,CAAC,CAAC,GAAG,oBAAoB,CAAC,CAAC;QAC9D,WAAW;KACX,CAAC,CAAC;AAAA,CACH;AAED,MAAM,WAAW,GAAG,MAAM,CAAC,CAAC,iBAAiB,EAAE,eAAe,CAAC,EAAE,YAAY,CAAC,CAAC;AAC/E,MAAM,YAAY,GAAG,MAAM,CAAC,CAAC,kBAAkB,EAAE,iBAAiB,CAAC,EAAE,YAAY,CAAC,CAAC;AACnF,MAAM,cAAc,GAAG,MAAM,CAAC,CAAC,cAAc,EAAE,eAAe,CAAC,EAAE,kBAAkB,CAAC,CAAC;AACrF,MAAM,cAAc,GAAG,MAAM,CAAC,CAAC,cAAc,EAAE,aAAa,CAAC,EAAE,eA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AAE,CAAC;QACpE,KAAK,iBAAiB,CAAC;QACvB,KAAK,eAAe;YACnB,OAAO,MAAM,CAAC;QACf,KAAK,kBAAkB,CAAC;QACxB,KAAK,iBAAiB;YACrB,OAAO,OAAO,CAAC;QAChB,KAAK,cAAc,CAAC;QACpB,KAAK,eAAe;YACnB,OAAO,SAAS,CAAC;QAClB,KAAK,cAAc,CAAC;QACpB,KAAK,aAAa;YACjB,OAAO,SAAS,CAAC;QAClB,KAAK,cAAc,CAAC;QACpB,KAAK,eAAe;YACnB,OAAO,QAAQ,CAAC;QACjB,KAAK,mBAAmB;YACvB,OAAO,YAAY,CAAC;QACrB,KAAK,YAAY,CAAC;QAClB,KAAK,aAAa;YACjB,OAAO,OAAO,CAAC;QAChB,KAAK,aAAa,CAAC;QACnB,KAAK,cAAc;YAClB,OAAO,QAAQ,CAAC;QACjB,KAAK,kBAAkB;YACtB,OAAO,UAAU,CAAC;QACnB,KAAK,eAAe,CAAC;QACrB,KAAK,gBAAgB;YACpB,OAAO,UAAU,CAAC;QACnB,KAAK,iBAAiB;YACrB,OAAO,SAAS,CAAC;QAClB,KAAK,oBAAoB;YACxB,OAAO,gBAAgB,CAAC;QACzB;YACC,OAAO,YAAY,CAAC;IACtB,CAAC;AAAA,CACD;AAED,SAAS,wBAAwB,CAAC,QAAgB,EAAE,IAAc,EAAgC;IACjG,IAAI,QAAQ,CAAC,WAAW,EAAE,KAAK,QAAQ,EAAE,CAAC;QACzC,OAAO,IAAI,IAAI,OAAO,IAAI,KAAK,QAAQ,IAAI,OAAO,IAAI,IAAI,CAAC,CAAC,CAAC,CAAC,cAAc,CAAC,CAAC,CAAC,CAAC,CAAC,eAAe,CAAC,CAAC;IACnG,CAAC;IACD,OAAO,uBAAuB,CAAC,QAAQ,CAAC,EAAE,oBAAoB,IAAI,EAAE,CAAC;AAAA,CACrE","sourcesContent":["import type { HarnessCapability } from \"./capability-contract.ts\";\nimport type { CapabilityEnforcementKind, OrchestrationProfile } from \"./orchestration/contracts.ts\";\n\nexport interface ToolCapabilityPolicy {\n\tcapabilityCandidates: readonly HarnessCapability[];\n\tenforcement: CapabilityEnforcementKind;\n}\n\nfunction policy(\n\tcapabilityCandidates: readonly HarnessCapability[],\n\tenforcement: CapabilityEnforcementKind,\n): ToolCapabilityPolicy {\n\treturn Object.freeze({\n\t\tcapabilityCandidates: Object.freeze([...capabilityCandidates]),\n\t\tenforcement,\n\t});\n}\n\nconst READ_POLICY = policy([\"filesystem.read\", \"worktree.read\"], \"path-scope\");\nconst WRITE_POLICY = policy([\"filesystem.write\", \"worktree.mutate\"], \"path-scope\");\nconst PROCESS_POLICY = policy([\"process.exec\", \"tests.execute\"], \"process-launcher\");\nconst NETWORK_POLICY = policy([\"network.http\", \"service.mcp\"], \"service-proxy\");\nconst DELEGATE_POLICY = policy([\"workflow.delegate\"], \"control-plane\");\n\nconst TOOL_CAPABILITY_POLICIES = new Map<string, ToolCapabilityPolicy>([\n\t...[\"read\", \"ls\", \"grep\", \"find\"].map((toolName) => [toolName, READ_POLICY] as const),\n\t...[\"write\", \"edit\", \"edit-diff\"].map((toolName) => [toolName, WRITE_POLICY] as const),\n\t...[\"bash\", \"python\", \"powershell\", \"shell\", \"run_toolkit_script\", \"run_process\"].map(\n\t\t(toolName) => [toolName, PROCESS_POLICY] as const,\n\t),\n\t...[\"fetch\", \"web_search\"].map((toolName) => [toolName, NETWORK_POLICY] as const),\n\t[\"skill_audit\", policy([\"skill.read\"], \"path-scope\")],\n\t[\"skillify\", policy([\"skill.write\"], \"path-scope\")],\n\t[\"extensionify\", policy([\"source.write\"], \"path-scope\")],\n\t[\"goal\", policy([\"memory.mutate\"], \"memory-broker\")],\n\t[\"memory\", policy([\"memory.mutate\", \"memory.query\"], \"memory-broker\")],\n\t...[\"delegate\", \"delegate_status\"].map((toolName) => [toolName, DELEGATE_POLICY] as const),\n\t[\"model_fitness\", policy([\"research.execute\"], \"control-plane\")],\n]);\n\nexport function getToolCapabilityPolicy(toolName: string): ToolCapabilityPolicy | undefined {\n\treturn TOOL_CAPABILITY_POLICIES.get(toolName.toLowerCase());\n}\n\nexport function hasToolCapabilityPolicy(toolName: string): boolean {\n\treturn getToolCapabilityPolicy(toolName) !== undefined;\n}\n\nexport function requiredEnvelopeCapabilities(toolName: string, args?: unknown): readonly HarnessCapability[] {\n\treturn toolCapabilityCandidates(toolName, args).slice(0, 1);\n}\n\nexport function envelopeHasToolCapability(\n\tcapabilities: readonly HarnessCapability[],\n\ttoolName: string,\n\targs?: unknown,\n): boolean {\n\tconst candidates = toolCapabilityCandidates(toolName, args);\n\treturn candidates.length > 0 && candidates.some((capability) => capabilities.includes(capability));\n}\n\nexport function resolveProfileToolCapability(\n\tprofile: Pick<OrchestrationProfile, \"capabilityCeiling\">,\n\ttoolName: string,\n): HarnessCapability | undefined {\n\treturn getToolCapabilityPolicy(toolName)?.capabilityCandidates.find((capability) =>\n\t\tprofile.capabilityCeiling.includes(capability),\n\t);\n}\n\nexport function describeToolCapabilityAuthority(toolName: string): string {\n\tswitch (getToolCapabilityPolicy(toolName)?.capabilityCandidates[0]) {\n\t\tcase \"filesystem.read\":\n\t\tcase \"worktree.read\":\n\t\t\treturn \"read\";\n\t\tcase \"filesystem.write\":\n\t\tcase \"worktree.mutate\":\n\t\t\treturn \"write\";\n\t\tcase \"process.exec\":\n\t\tcase \"tests.execute\":\n\t\t\treturn \"process\";\n\t\tcase \"network.http\":\n\t\tcase \"service.mcp\":\n\t\t\treturn \"network\";\n\t\tcase \"memory.query\":\n\t\tcase \"memory.mutate\":\n\t\t\treturn \"memory\";\n\t\tcase \"workflow.delegate\":\n\t\t\treturn \"delegation\";\n\t\tcase \"skill.read\":\n\t\tcase \"skill.write\":\n\t\t\treturn \"skill\";\n\t\tcase \"source.read\":\n\t\tcase \"source.write\":\n\t\t\treturn \"source\";\n\t\tcase \"research.execute\":\n\t\t\treturn \"research\";\n\t\tcase \"settings.read\":\n\t\tcase \"settings.write\":\n\t\t\treturn \"settings\";\n\t\tcase \"publish.execute\":\n\t\t\treturn \"publish\";\n\t\tcase \"credentials.modify\":\n\t\t\treturn \"authentication\";\n\t\tdefault:\n\t\t\treturn \"capability\";\n\t}\n}\n\nfunction toolCapabilityCandidates(toolName: string, args?: unknown): readonly HarnessCapability[] {\n\tif (toolName.toLowerCase() === \"memory\") {\n\t\treturn args && typeof args === \"object\" && \"query\" in args ? [\"memory.query\"] : [\"memory.mutate\"];\n\t}\n\treturn getToolCapabilityPolicy(toolName)?.capabilityCandidates ?? [];\n}\n"]}
@@ -0,0 +1,91 @@
1
+ import type { Agent, StreamFn } from "@caupulican/pi-agent-core";
2
+ import type { Api, AssistantMessage, Model, TextToolProtocolParseEvent, TextToolProtocolVariant, ToolArgumentValidationTelemetryEvent, Usage } from "@caupulican/pi-ai";
3
+ import type { ModelRegistry } from "./model-registry.ts";
4
+ import { type ModelToolProtocolResolution } from "./model-tool-protocol.ts";
5
+ import type { ModelAdaptationRule, ModelAdaptationStore, ModelToolProbeVerdict, NativeToolProbeGrade } from "./models/adaptation-store.ts";
6
+ import type { SettingsManager } from "./settings-manager.ts";
7
+ import type { ToolRecoveryLoggerStats } from "./tool-recovery-logger.ts";
8
+ export type ToolProbeVerdict = "native" | "text-protocol" | "none";
9
+ export interface ToolProbeResult {
10
+ model: string;
11
+ verdict: ToolProbeVerdict;
12
+ variant?: TextToolProtocolVariant;
13
+ nativeGrade?: NativeToolProbeGrade;
14
+ diagnostic?: string;
15
+ }
16
+ export interface ToolProbeReport {
17
+ results: ToolProbeResult[];
18
+ table: string;
19
+ }
20
+ export interface ToolProtocolControllerDeps {
21
+ agent: Agent;
22
+ agentDir: string;
23
+ settingsManager: SettingsManager;
24
+ getModelRegistry(): ModelRegistry;
25
+ adaptationStore: ModelAdaptationStore;
26
+ isRawStreamSimple(fn: StreamFn): boolean;
27
+ getRequiredRequestAuth(model: Model<Api>): Promise<{
28
+ apiKey: string;
29
+ headers?: Record<string, string>;
30
+ }>;
31
+ addSpawnedUsage(usage: Usage, opts: {
32
+ label?: string;
33
+ reportId: string;
34
+ }): string | undefined;
35
+ emitWarning(message: string): void;
36
+ sendCorrectiveSteer(message: string): Promise<void>;
37
+ findLastAssistantMessage(): AssistantMessage | undefined;
38
+ isDisposed(): boolean;
39
+ probeForAuto(model: Model<Api>): Promise<ToolProbeResult>;
40
+ }
41
+ /** Owns model tool-protocol selection, probing, circuit breaking, and repair teaching. */
42
+ export declare class ToolProtocolController {
43
+ private readonly repairModeSessionCounts;
44
+ private readonly parseFailures;
45
+ private parseObservedThisTurn;
46
+ private correctiveSteerCount;
47
+ private probeUsageReportSeq;
48
+ private readonly autoProbedModels;
49
+ private validationOutcomeThisTurn;
50
+ private readonly deps;
51
+ constructor(deps: ToolProtocolControllerDeps);
52
+ applyRepairLayerSettings(): void;
53
+ resetTurnState(): void;
54
+ getAdaptationRulesForPrompt(): ModelAdaptationRule[];
55
+ resolveModelToolProtocol(model: Model<Api>): ModelToolProtocolResolution;
56
+ ensureActiveModelProtocol(): Promise<void>;
57
+ getToolProbeVerdict(model: Model<Api>): ModelToolProbeVerdict | undefined;
58
+ probeToolCalling(target?: string): Promise<ToolProbeReport>;
59
+ probeToolCallingForModel(model: Model<Api>): Promise<ToolProbeResult>;
60
+ handleTextProtocolParse(event: TextToolProtocolParseEvent): void;
61
+ handleValidationOutcome(event: ToolArgumentValidationTelemetryEvent): void;
62
+ recordParseOutcomeFromLastAssistant(): void;
63
+ tagAdaptationRuleTeaching(event: ToolArgumentValidationTelemetryEvent): ToolArgumentValidationTelemetryEvent;
64
+ handleAdaptationTelemetry(event: ToolArgumentValidationTelemetryEvent): void;
65
+ maybeAutoProbe(model: Model<Api>): void;
66
+ formatRepairHealth(stats?: ToolRecoveryLoggerStats): string;
67
+ removeRepairRule(model: string, mode: string): boolean;
68
+ resetProtocolCalibration(model: string): boolean;
69
+ getRepairSettings(): import("./tool-repair-settings.ts").ResolvedToolRepairSettings;
70
+ private modelKey;
71
+ private modelRef;
72
+ private streamForProbe;
73
+ private nextProbeUsageReportId;
74
+ private resolveProbeStreamCountingUsage;
75
+ private textProtocolCalibrationContext;
76
+ private messageHasToolCallWithStringArgument;
77
+ private nativeToolProbeSystemPrompt;
78
+ private runNativeReadTaskProbeTrial;
79
+ private runNativeEchoToolProbeTrial;
80
+ private gradeNativeToolCallingForModel;
81
+ private runTextProtocolTrial;
82
+ private calibrateTextToolProtocolForModel;
83
+ private formatToolProbeReport;
84
+ private storeToolProbe;
85
+ private resolveToolProbeModels;
86
+ private maybeInjectCorrectiveSteer;
87
+ private looksLikeTextProtocolAttempt;
88
+ private repairSessionCount;
89
+ private hasFreshToolProbeVerdict;
90
+ }
91
+ //# sourceMappingURL=tool-protocol-controller.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tool-protocol-controller.d.ts","sourceRoot":"","sources":["../../src/core/tool-protocol-controller.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,KAAK,EAAE,QAAQ,EAAE,MAAM,2BAA2B,CAAC;AACjE,OAAO,KAAK,EACX,GAAG,EACH,gBAAgB,EAGhB,KAAK,EAGL,0BAA0B,EAC1B,uBAAuB,EAEvB,oCAAoC,EAEpC,KAAK,EACL,MAAM,mBAAmB,CAAC;AAU3B,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACzD,OAAO,EAEN,KAAK,2BAA2B,EAEhC,MAAM,0BAA0B,CAAC;AAClC,OAAO,KAAK,EACX,mBAAmB,EACnB,oBAAoB,EAEpB,qBAAqB,EACrB,oBAAoB,EACpB,MAAM,8BAA8B,CAAC;AACtC,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AAC7D,OAAO,KAAK,EAAE,uBAAuB,EAAE,MAAM,2BAA2B,CAAC;AAoBzE,MAAM,MAAM,gBAAgB,GAAG,QAAQ,GAAG,eAAe,GAAG,MAAM,CAAC;AAEnE,MAAM,WAAW,eAAe;IAC/B,KAAK,EAAE,MAAM,CAAC;IACd,OAAO,EAAE,g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E,IAAI,EAAE,MAAM,GAAG,OAAO,CAErD;IAED,wBAAwB,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAI/C;IAED,iBAAiB,mEAEhB;IAED,OAAO,CAAC,QAAQ;IAIhB,OAAO,CAAC,QAAQ;YAIF,cAAc;IAa5B,OAAO,CAAC,sBAAsB;YAIhB,+BAA+B;IAa7C,OAAO,CAAC,8BAA8B;IAStC,OAAO,CAAC,oCAAoC;IAkB5C,OAAO,CAAC,2BAA2B;YAKrB,2BAA2B;YAqB3B,2BAA2B;YAqB3B,8BAA8B;YAe9B,oBAAoB;YA0BpB,iCAAiC;IA0C/C,OAAO,CAAC,qBAAqB;IAoB7B,OAAO,CAAC,cAAc;YAIR,sBAAsB;IAapC,OAAO,CAAC,0BAA0B;IAWlC,OAAO,CAAC,4BAA4B;IAIpC,OAAO,CAAC,kBAAkB;IAO1B,OAAO,CAAC,wBAAwB;CAMhC","sourcesContent":["import { rmSync, writeFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport type { Agent, StreamFn } from \"@caupulican/pi-agent-core\";\nimport type {\n\tApi,\n\tAssistantMessage,\n\tAssistantMessageEventStream,\n\tContext,\n\tModel,\n\tSimpleStreamOptions,\n\tTextContent,\n\tTextToolProtocolParseEvent,\n\tTextToolProtocolVariant,\n\tTool,\n\tToolArgumentValidationTelemetryEvent,\n\tToolRepairModeName,\n\tUsage,\n} from \"@caupulican/pi-ai\";\nimport {\n\tformatToolRepairStandingRule,\n\tformatVariantEnvelope,\n\tgenerateTextToolProtocolPrimer,\n\tparseTextToolCalls,\n\tTEXT_TOOL_PROTOCOL_VARIANTS,\n} from \"@caupulican/pi-ai\";\nimport { Type } from \"typebox\";\nimport { getProcessWorkRun } from \"../utils/work-directory.ts\";\nimport type { ModelRegistry } from \"./model-registry.ts\";\nimport {\n\tMODEL_TOOL_PROTOCOL_VERSION,\n\ttype ModelToolProtocolResolution,\n\tresolveModelToolProtocol,\n} from \"./model-tool-protocol.ts\";\nimport type {\n\tModelAdaptationRule,\n\tModelAdaptationStore,\n\tModelToolProbe,\n\tModelToolProbeVerdict,\n\tNativeToolProbeGrade,\n} from \"./models/adaptation-store.ts\";\nimport type { SettingsManager } from \"./settings-manager.ts\";\nimport type { ToolRecoveryLoggerStats } from \"./tool-recovery-logger.ts\";\nimport { formatToolRepairHealthReport } from \"./tool-repair-health.ts\";\nimport { resolveCurrentToolRepairSettings } from \"./tool-repair-settings.ts\";\n\nconst MODEL_ADAPTATION_REPAIR_THRESHOLD = 3;\nconst TEXT_TOOL_PROTOCOL_TRIALS_PER_VARIANT = 2;\nconst TEXT_TOOL_PROTOCOL_PARSE_FAILURE_THRESHOLD = 3;\nconst TEXT_TOOL_PROTOCOL_STEER_INTERVAL = 5;\nconst AUTO_TOOL_PROBE_FRESHNESS_MS = 15 * 60 * 1000;\nconst TEXT_TOOL_PROTOCOL_ECHO_TOOL = {\n\tname: \"echo\",\n\tdescription: \"Echo calibration data\",\n\tparameters: Type.Object({ data: Type.String() }),\n} satisfies Tool;\nconst NATIVE_TOOL_PROBE_READ_TOOL = {\n\tname: \"read\",\n\tdescription: \"Read file contents\",\n\tparameters: Type.Object({ path: Type.String() }),\n} satisfies Tool;\n\nexport type ToolProbeVerdict = \"native\" | \"text-protocol\" | \"none\";\n\nexport interface ToolProbeResult {\n\tmodel: string;\n\tverdict: ToolProbeVerdict;\n\tvariant?: TextToolProtocolVariant;\n\tnativeGrade?: NativeToolProbeGrade;\n\tdiagnostic?: string;\n}\n\nexport interface ToolProbeReport {\n\tresults: ToolProbeResult[];\n\ttable: string;\n}\n\nexport interface ToolProtocolControllerDeps {\n\tagent: Agent;\n\tagentDir: string;\n\tsettingsManager: SettingsManager;\n\tgetModelRegistry(): ModelRegistry;\n\tadaptationStore: ModelAdaptationStore;\n\tisRawStreamSimple(fn: StreamFn): boolean;\n\tgetRequiredRequestAuth(model: Model<Api>): Promise<{ apiKey: string; headers?: Record<string, string> }>;\n\taddSpawnedUsage(usage: Usage, opts: { label?: string; reportId: string }): string | undefined;\n\temitWarning(message: string): void;\n\tsendCorrectiveSteer(message: string): Promise<void>;\n\tfindLastAssistantMessage(): AssistantMessage | undefined;\n\tisDisposed(): boolean;\n\tprobeForAuto(model: Model<Api>): Promise<ToolProbeResult>;\n}\n\n/** Owns model tool-protocol selection, probing, circuit breaking, and repair teaching. */\nexport class ToolProtocolController {\n\tprivate readonly repairModeSessionCounts = new Map<string, number>();\n\tprivate readonly parseFailures = new Map<string, { signature: string; repeats: number }>();\n\tprivate parseObservedThisTurn = false;\n\tprivate correctiveSteerCount = 0;\n\tprivate probeUsageReportSeq = 0;\n\tprivate readonly autoProbedModels = new Set<string>();\n\tprivate validationOutcomeThisTurn: TextToolProtocolParseEvent | undefined;\n\tprivate readonly deps: ToolProtocolControllerDeps;\n\n\tconstructor(deps: ToolProtocolControllerDeps) {\n\t\tthis.deps = deps;\n\t}\n\n\tapplyRepairLayerSettings(): void {\n\t\tthis.deps.agent.toolArgumentTeachEnabled = this.getRepairSettings().teach;\n\t}\n\n\tresetTurnState(): void {\n\t\tthis.parseObservedThisTurn = false;\n\t\tthis.validationOutcomeThisTurn = undefined;\n\t}\n\n\tgetAdaptationRulesForPrompt(): ModelAdaptationRule[] {\n\t\tif (!this.getRepairSettings().teach) return [];\n\t\tconst modelKey = this.modelKey(this.deps.agent.state.model);\n\t\treturn modelKey ? this.deps.adaptationStore.get(modelKey).rules : [];\n\t}\n\n\tresolveModelToolProtocol(model: Model<Api>): ModelToolProtocolResolution {\n\t\treturn resolveModelToolProtocol({\n\t\t\tmodel,\n\t\t\tsettingsOverride: this.getRepairSettings().textProtocol,\n\t\t\tadaptation: this.deps.adaptationStore.get(this.modelRef(model)),\n\t\t});\n\t}\n\n\tasync ensureActiveModelProtocol(): Promise<void> {\n\t\tconst model = this.deps.agent.state.model;\n\t\tconst resolution = this.resolveModelToolProtocol(model);\n\t\tthis.deps.agent.textToolCallProtocol = resolution.protocol;\n\t\tif (\n\t\t\tresolution.reasonCode !== \"probe_calibration_missing\" &&\n\t\t\tresolution.reasonCode !== \"probe_calibration_failed\" &&\n\t\t\tresolution.reasonCode !== \"probe_calibration_invalid\"\n\t\t) {\n\t\t\treturn;\n\t\t}\n\t\tconst modelKey = this.modelRef(model);\n\t\tthis.deps.emitWarning(\n\t\t\tresolution.reasonCode === \"probe_calibration_failed\"\n\t\t\t\t? `Text tool protocol calibration for ${modelKey} previously failed (variants tried: ${(resolution.variantsTried ?? []).join(\", \")}); falling back to native tool calls this turn. Run /toolprobe ${modelKey} to recalibrate.`\n\t\t\t\t: `Text tool protocol for ${modelKey} has no valid calibration on record; falling back to native tool calls this turn. Run /toolprobe ${modelKey} to calibrate.`,\n\t\t);\n\t}\n\n\tgetToolProbeVerdict(model: Model<Api>): ModelToolProbeVerdict | undefined {\n\t\treturn this.deps.adaptationStore.get(this.modelRef(model)).toolProbe?.status;\n\t}\n\n\tasync probeToolCalling(target?: string): Promise<ToolProbeReport> {\n\t\tconst models = await this.resolveToolProbeModels(target);\n\t\tif (models.length === 0) throw new Error(\"No available models to probe.\");\n\t\tconst results: ToolProbeResult[] = [];\n\t\tfor (const model of models) results.push(await this.probeToolCallingForModel(model));\n\t\treturn { results, table: this.formatToolProbeReport(results) };\n\t}\n\n\tasync probeToolCallingForModel(model: Model<Api>): Promise<ToolProbeResult> {\n\t\tconst modelKey = this.modelRef(model);\n\t\tconst probedAt = new Date().toISOString();\n\t\tlet nativeGrade: NativeToolProbeGrade = \"absent\";\n\t\tlet diagnostic: string | undefined;\n\t\ttry {\n\t\t\tnativeGrade = await this.gradeNativeToolCallingForModel(model, \"pi-native-probe\");\n\t\t\tif (nativeGrade === \"task\") {\n\t\t\t\tthis.storeToolProbe(modelKey, {\n\t\t\t\t\tversion: MODEL_TOOL_PROTOCOL_VERSION,\n\t\t\t\t\tstatus: \"native\",\n\t\t\t\t\tprobedAt,\n\t\t\t\t\tnativeGrade,\n\t\t\t\t});\n\t\t\t\treturn { model: modelKey, verdict: \"native\", nativeGrade };\n\t\t\t}\n\t\t\tdiagnostic =\n\t\t\t\tnativeGrade === \"echo-only\"\n\t\t\t\t\t? \"Native echo probe passed but task-scale read probe failed.\"\n\t\t\t\t\t: \"Native task-scale read and echo probes did not produce provider-native tool calls.\";\n\t\t} catch (error) {\n\t\t\tdiagnostic = error instanceof Error ? error.message : String(error);\n\t\t}\n\n\t\ttry {\n\t\t\tconst calibrated = await this.calibrateTextToolProtocolForModel(model, modelKey, { persistFailure: false });\n\t\t\tif (calibrated.status === \"calibrated\") {\n\t\t\t\tthis.storeToolProbe(modelKey, {\n\t\t\t\t\tversion: MODEL_TOOL_PROTOCOL_VERSION,\n\t\t\t\t\tstatus: \"text-protocol\",\n\t\t\t\t\tprobedAt: calibrated.calibratedAt,\n\t\t\t\t\tvariant: calibrated.variant,\n\t\t\t\t\tnativeGrade,\n\t\t\t\t\tdiagnostic,\n\t\t\t\t});\n\t\t\t\treturn { model: modelKey, verdict: \"text-protocol\", variant: calibrated.variant, nativeGrade, diagnostic };\n\t\t\t}\n\t\t\tdiagnostic = `${diagnostic ? `${diagnostic} ` : \"\"}Text protocol variants failed: ${calibrated.variantsTried.join(\", \")}`;\n\t\t} catch (error) {\n\t\t\tdiagnostic = error instanceof Error ? error.message : String(error);\n\t\t}\n\n\t\tthis.storeToolProbe(modelKey, {\n\t\t\tversion: MODEL_TOOL_PROTOCOL_VERSION,\n\t\t\tstatus: \"none\",\n\t\t\tprobedAt,\n\t\t\tnativeGrade,\n\t\t\tdiagnostic,\n\t\t});\n\t\treturn { model: modelKey, verdict: \"none\", nativeGrade, diagnostic };\n\t}\n\n\thandleTextProtocolParse(event: TextToolProtocolParseEvent): void {\n\t\tthis.parseObservedThisTurn = true;\n\t\tconst modelKey = `${event.provider}/${event.model}`;\n\t\tif (event.status === \"parsed\") return;\n\t\tthis.maybeInjectCorrectiveSteer(event.variant);\n\t\tconst signature = `${event.variant}:${event.reason ?? \"failed\"}`;\n\t\tconst previous = this.parseFailures.get(modelKey);\n\t\tconst repeats = previous?.signature === signature ? previous.repeats + 1 : 1;\n\t\tthis.parseFailures.set(modelKey, { signature, repeats });\n\t\tif (repeats < TEXT_TOOL_PROTOCOL_PARSE_FAILURE_THRESHOLD) return;\n\n\t\tconst profile = this.deps.adaptationStore.get(modelKey);\n\t\tif (profile.protocol?.version === MODEL_TOOL_PROTOCOL_VERSION && profile.protocol.status !== \"failed\") {\n\t\t\tthis.deps.adaptationStore.removeProtocol(modelKey);\n\t\t\tthis.deps.agent.textToolCallProtocol = undefined;\n\t\t}\n\t\tthis.parseFailures.delete(modelKey);\n\t\tconst probedAt = new Date().toISOString();\n\t\tthis.deps.adaptationStore.setToolProbe(\n\t\t\tmodelKey,\n\t\t\t{\n\t\t\t\tversion: MODEL_TOOL_PROTOCOL_VERSION,\n\t\t\t\tstatus: \"none\",\n\t\t\t\tprobedAt,\n\t\t\t\tnativeGrade: profile.toolProbe?.nativeGrade,\n\t\t\t\tdiagnostic: `Text protocol parsing failed ${TEXT_TOOL_PROTOCOL_PARSE_FAILURE_THRESHOLD}x in a row with signature \"${signature}\".`,\n\t\t\t},\n\t\t\tprobedAt,\n\t\t);\n\t\tthis.deps.emitWarning(\n\t\t\t`Text tool protocol for ${modelKey} stopped parsing after ${TEXT_TOOL_PROTOCOL_PARSE_FAILURE_THRESHOLD} attempts; demoted to native fallback. Run /toolprobe ${modelKey} to recalibrate.`,\n\t\t);\n\t}\n\n\thandleValidationOutcome(event: ToolArgumentValidationTelemetryEvent): void {\n\t\tif (event.source !== \"text-protocol\") return;\n\t\tconst protocol = this.deps.agent.textToolCallProtocol;\n\t\tconst variant = protocol === true ? \"tool-tag\" : protocol ? protocol.variant : undefined;\n\t\tif (!variant) return;\n\t\tconst status = event.outcome === \"bounced\" ? \"failed\" : \"parsed\";\n\t\tif (this.validationOutcomeThisTurn?.status === \"parsed\" && status === \"failed\") return;\n\t\tthis.validationOutcomeThisTurn = {\n\t\t\tprovider: event.provider ?? this.deps.agent.state.model.provider,\n\t\t\tmodel: event.model ?? this.deps.agent.state.model.id,\n\t\t\tvariant,\n\t\t\tstatus,\n\t\t\tcallCount: 1,\n\t\t\ttextLength: 0,\n\t\t\t...(status === \"failed\" && {\n\t\t\t\treason: event.errorKeywords?.includes(\"unknown_tool\") ? \"unknown-tool\" : \"validation-failed\",\n\t\t\t}),\n\t\t};\n\t}\n\n\trecordParseOutcomeFromLastAssistant(): void {\n\t\tconst validationOutcome = this.validationOutcomeThisTurn;\n\t\tthis.validationOutcomeThisTurn = undefined;\n\t\tif (validationOutcome?.status === \"parsed\") {\n\t\t\tthis.parseObservedThisTurn = true;\n\t\t\tthis.parseFailures.delete(`${validationOutcome.provider}/${validationOutcome.model}`);\n\t\t\treturn;\n\t\t}\n\t\tif (validationOutcome) {\n\t\t\tthis.handleTextProtocolParse(validationOutcome);\n\t\t\treturn;\n\t\t}\n\t\tif (this.parseObservedThisTurn) return;\n\t\tconst protocol = this.deps.agent.textToolCallProtocol;\n\t\tif (protocol === false || protocol === true || !protocol?.variant) return;\n\t\tconst response = this.deps.findLastAssistantMessage();\n\t\tif (!response) return;\n\t\tconst responseText = response.content\n\t\t\t.filter((content): content is TextContent => content.type === \"text\")\n\t\t\t.map((content) => content.text)\n\t\t\t.join(\"\\n\");\n\t\tif (!responseText) return;\n\n\t\tconst parsed = parseTextToolCalls(responseText, this.deps.agent.state.tools);\n\t\tconst attempted = parsed.attempted || this.looksLikeTextProtocolAttempt(responseText);\n\t\tif (!attempted) return;\n\t\tthis.handleTextProtocolParse({\n\t\t\tprovider: this.deps.agent.state.model.provider,\n\t\t\tmodel: this.deps.agent.state.model.id,\n\t\t\tvariant: protocol.variant,\n\t\t\tstatus: parsed.calls.length > 0 ? \"parsed\" : \"failed\",\n\t\t\treason: parsed.failure,\n\t\t\tcallCount: parsed.calls.length,\n\t\t\ttextLength: responseText.length,\n\t\t});\n\t}\n\n\ttagAdaptationRuleTeaching(event: ToolArgumentValidationTelemetryEvent): ToolArgumentValidationTelemetryEvent {\n\t\tif (!this.getRepairSettings().teach || event.taught !== \"none\") return event;\n\t\tconst modelKey =\n\t\t\tevent.provider && event.model\n\t\t\t\t? `${event.provider}/${event.model}`\n\t\t\t\t: this.modelKey(this.deps.agent.state.model);\n\t\tif (!modelKey) return event;\n\t\ttry {\n\t\t\tconst rules = this.deps.adaptationStore.get(modelKey).rules;\n\t\t\tconst modes = new Set([...event.failureModes, ...event.repairsApplied]);\n\t\t\tif (rules.some((rule) => modes.has(rule.mode as ToolRepairModeName))) return { ...event, taught: \"rule\" };\n\t\t} catch {\n\t\t\t// Best-effort telemetry tagging.\n\t\t}\n\t\treturn event;\n\t}\n\n\thandleAdaptationTelemetry(event: ToolArgumentValidationTelemetryEvent): void {\n\t\tif (!this.getRepairSettings().teach || event.outcome !== \"repaired\" || event.repairsApplied.length === 0) return;\n\t\tconst modelKey =\n\t\t\tevent.provider && event.model\n\t\t\t\t? `${event.provider}/${event.model}`\n\t\t\t\t: this.modelKey(this.deps.agent.state.model);\n\t\tif (!modelKey) return;\n\t\ttry {\n\t\t\tfor (const mode of [...new Set(event.repairsApplied)]) {\n\t\t\t\tconst profile = this.deps.adaptationStore.get(modelKey);\n\t\t\t\tconst stats = profile.teachStats[mode] ?? { taught: 0, recurrenceBefore: 0, recurrenceAfter: 0 };\n\t\t\t\tif (profile.rules.some((rule) => rule.mode === mode)) {\n\t\t\t\t\tthis.deps.adaptationStore.markRuleFired(modelKey, mode);\n\t\t\t\t\tthis.deps.adaptationStore.setTeachStats(modelKey, mode, {\n\t\t\t\t\t\t...stats,\n\t\t\t\t\t\trecurrenceAfter: stats.recurrenceAfter + 1,\n\t\t\t\t\t});\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tconst recurrenceBefore = stats.recurrenceBefore + 1;\n\t\t\t\tthis.deps.adaptationStore.setTeachStats(modelKey, mode, { ...stats, recurrenceBefore });\n\t\t\t\tconst sessionCount = this.repairSessionCount(modelKey, mode);\n\t\t\t\tif (\n\t\t\t\t\tsessionCount >= MODEL_ADAPTATION_REPAIR_THRESHOLD ||\n\t\t\t\t\trecurrenceBefore >= MODEL_ADAPTATION_REPAIR_THRESHOLD\n\t\t\t\t) {\n\t\t\t\t\tthis.deps.adaptationStore.addRule(modelKey, { mode, text: formatToolRepairStandingRule(mode) });\n\t\t\t\t\tthis.deps.adaptationStore.setTeachStats(modelKey, mode, {\n\t\t\t\t\t\t...stats,\n\t\t\t\t\t\ttaught: stats.taught + 1,\n\t\t\t\t\t\trecurrenceBefore,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t} catch {\n\t\t\t// Best-effort adaptation persistence.\n\t\t}\n\t}\n\n\tmaybeAutoProbe(model: Model<Api>): void {\n\t\tconst modelKey = this.modelRef(model);\n\t\tif (this.autoProbedModels.has(modelKey) || this.hasFreshToolProbeVerdict(modelKey)) return;\n\t\tthis.autoProbedModels.add(modelKey);\n\t\tvoid this.deps\n\t\t\t.probeForAuto(model)\n\t\t\t.then((result) => {\n\t\t\t\tif (this.deps.isDisposed()) return;\n\t\t\t\tconst detail =\n\t\t\t\t\tresult.verdict === \"text-protocol\"\n\t\t\t\t\t\t? ` (variant ${result.variant}); it will use the text tool protocol starting next turn`\n\t\t\t\t\t\t: result.verdict === \"none\"\n\t\t\t\t\t\t\t? \" — no working tool-call path was found; run /toolprobe for details\"\n\t\t\t\t\t\t\t: \"; native tool calls stay in use\";\n\t\t\t\tthis.deps.emitWarning(\n\t\t\t\t\t`Auto-probed ${modelKey} after repeated native tool-call validation failures: verdict \"${result.verdict}\"${detail}.`,\n\t\t\t\t);\n\t\t\t})\n\t\t\t.catch((error) => {\n\t\t\t\tif (this.deps.isDisposed()) return;\n\t\t\t\tthis.deps.emitWarning(\n\t\t\t\t\t`Auto-probe for ${modelKey} (triggered by repeated tool-call validation failures) did not complete: ${error instanceof Error ? error.message : String(error)}.`,\n\t\t\t\t);\n\t\t\t});\n\t}\n\n\tformatRepairHealth(stats?: ToolRecoveryLoggerStats): string {\n\t\treturn formatToolRepairHealthReport(this.deps.adaptationStore, new Date(), stats);\n\t}\n\n\tremoveRepairRule(model: string, mode: string): boolean {\n\t\treturn this.deps.adaptationStore.removeRule(model, mode);\n\t}\n\n\tresetProtocolCalibration(model: string): boolean {\n\t\tconst removed = this.deps.adaptationStore.removeProtocol(model);\n\t\tthis.parseFailures.delete(model);\n\t\treturn removed;\n\t}\n\n\tgetRepairSettings() {\n\t\treturn resolveCurrentToolRepairSettings(this.deps.settingsManager.settings);\n\t}\n\n\tprivate modelKey(model: Model<Api> | undefined): string | undefined {\n\t\treturn model ? this.modelRef(model) : undefined;\n\t}\n\n\tprivate modelRef(model: Model<Api>): string {\n\t\treturn `${model.provider}/${model.id}`;\n\t}\n\n\tprivate async streamForProbe(model: Model<Api>, context: Context, options: SimpleStreamOptions) {\n\t\tlet requestOptions = options;\n\t\tif (this.deps.isRawStreamSimple(this.deps.agent.streamFn)) {\n\t\t\tconst auth = await this.deps.getRequiredRequestAuth(model);\n\t\t\trequestOptions = {\n\t\t\t\t...options,\n\t\t\t\tapiKey: auth.apiKey,\n\t\t\t\theaders: auth.headers || options.headers ? { ...auth.headers, ...options.headers } : undefined,\n\t\t\t};\n\t\t}\n\t\treturn this.deps.agent.streamFn(model, context, requestOptions);\n\t}\n\n\tprivate nextProbeUsageReportId(model: Model<Api>, kind: string): string {\n\t\treturn `tool-probe:${this.modelRef(model)}:${kind}:${this.probeUsageReportSeq++}`;\n\t}\n\n\tprivate async resolveProbeStreamCountingUsage(\n\t\tstream: AssistantMessageEventStream,\n\t\tlabel: string,\n\t\treportId: string,\n\t): Promise<AssistantMessage> {\n\t\tconst message = await stream.result();\n\t\tconst usage = message.usage;\n\t\tif (usage && (usage.cost.total > 0 || usage.totalTokens > 0)) {\n\t\t\tthis.deps.addSpawnedUsage(usage, { label, reportId });\n\t\t}\n\t\treturn message;\n\t}\n\n\tprivate textProtocolCalibrationContext(variant: TextToolProtocolVariant, token: string): Context {\n\t\tconst primer = generateTextToolProtocolPrimer([TEXT_TOOL_PROTOCOL_ECHO_TOOL], { variant });\n\t\tconst instruction = `Text tool protocol calibration trial. Using the protocol above, call echo with data exactly \"${token}\". Output only the tool-call envelope.`;\n\t\treturn {\n\t\t\tsystemPrompt: `${primer}\\n\\n${instruction}`,\n\t\t\tmessages: [{ role: \"user\", content: [{ type: \"text\", text: instruction }], timestamp: Date.now() }],\n\t\t};\n\t}\n\n\tprivate messageHasToolCallWithStringArgument(\n\t\tmessage: AssistantMessage,\n\t\ttoolName: string,\n\t\targName: string,\n\t\targValue: string,\n\t): boolean {\n\t\treturn message.content.some((block) => {\n\t\t\tif (block.type !== \"toolCall\" || block.name !== toolName) return false;\n\t\t\tconst args = block.arguments as unknown;\n\t\t\treturn (\n\t\t\t\ttypeof args === \"object\" &&\n\t\t\t\targs !== null &&\n\t\t\t\t!Array.isArray(args) &&\n\t\t\t\t(args as Record<string, unknown>)[argName] === argValue\n\t\t\t);\n\t\t});\n\t}\n\n\tprivate nativeToolProbeSystemPrompt(instruction: string): string {\n\t\tconst base = (this.deps.agent.state.systemPrompt ?? \"\").trim();\n\t\treturn base ? `${base}\\n\\n${instruction}` : instruction;\n\t}\n\n\tprivate async runNativeReadTaskProbeTrial(model: Model<Api>, path: string): Promise<boolean> {\n\t\tconst instruction =\n\t\t\t`Native tool-call capability probe: task-scale read. Use provider-native tool calling, not prose. ` +\n\t\t\t`Call read exactly once with path exactly \"${path}\".`;\n\t\tconst stream = await this.streamForProbe(\n\t\t\tmodel,\n\t\t\t{\n\t\t\t\tsystemPrompt: this.nativeToolProbeSystemPrompt(instruction),\n\t\t\t\tmessages: [{ role: \"user\", content: [{ type: \"text\", text: instruction }], timestamp: Date.now() }],\n\t\t\t\ttools: [NATIVE_TOOL_PROBE_READ_TOOL],\n\t\t\t},\n\t\t\t{ textToolCallProtocol: false, maxRetries: 0, temperature: 0, maxTokens: 768 },\n\t\t);\n\t\tconst message = await this.resolveProbeStreamCountingUsage(\n\t\t\tstream,\n\t\t\t\"tool-probe\",\n\t\t\tthis.nextProbeUsageReportId(model, \"read-task\"),\n\t\t);\n\t\treturn this.messageHasToolCallWithStringArgument(message, \"read\", \"path\", path);\n\t}\n\n\tprivate async runNativeEchoToolProbeTrial(model: Model<Api>, token: string): Promise<boolean> {\n\t\tconst instruction =\n\t\t\t`Native tool-call capability probe: echo-only. Use provider-native tool calling, not prose. ` +\n\t\t\t`Call echo with data exactly \"${token}\".`;\n\t\tconst stream = await this.streamForProbe(\n\t\t\tmodel,\n\t\t\t{\n\t\t\t\tsystemPrompt: this.nativeToolProbeSystemPrompt(instruction),\n\t\t\t\tmessages: [{ role: \"user\", content: [{ type: \"text\", text: instruction }], timestamp: Date.now() }],\n\t\t\t\ttools: [TEXT_TOOL_PROTOCOL_ECHO_TOOL],\n\t\t\t},\n\t\t\t{ textToolCallProtocol: false, maxRetries: 0, temperature: 0, maxTokens: 256 },\n\t\t);\n\t\tconst message = await this.resolveProbeStreamCountingUsage(\n\t\t\tstream,\n\t\t\t\"tool-probe\",\n\t\t\tthis.nextProbeUsageReportId(model, \"echo\"),\n\t\t);\n\t\treturn this.messageHasToolCallWithStringArgument(message, \"echo\", \"data\", token);\n\t}\n\n\tprivate async gradeNativeToolCallingForModel(model: Model<Api>, token: string): Promise<NativeToolProbeGrade> {\n\t\tconst path = join(\n\t\t\tgetProcessWorkRun(this.deps.agentDir, \"probes\", \"native-tools\").path,\n\t\t\t`pi-native-probe-${process.pid}-${Date.now()}.txt`,\n\t\t);\n\t\twriteFileSync(path, token, \"utf-8\");\n\t\ttry {\n\t\t\tif (await this.runNativeReadTaskProbeTrial(model, path)) return \"task\";\n\t\t\tif (await this.runNativeEchoToolProbeTrial(model, token)) return \"echo-only\";\n\t\t\treturn \"absent\";\n\t\t} finally {\n\t\t\trmSync(path, { force: true });\n\t\t}\n\t}\n\n\tprivate async runTextProtocolTrial(\n\t\tmodel: Model<Api>,\n\t\tvariant: TextToolProtocolVariant,\n\t\ttoken: string,\n\t): Promise<boolean> {\n\t\tconst stream = await this.streamForProbe(model, this.textProtocolCalibrationContext(variant, token), {\n\t\t\ttextToolCallProtocol: false,\n\t\t\tmaxRetries: 0,\n\t\t\ttemperature: 0,\n\t\t\tmaxTokens: 256,\n\t\t});\n\t\tconst message = await this.resolveProbeStreamCountingUsage(\n\t\t\tstream,\n\t\t\t\"text-protocol-calibration\",\n\t\t\tthis.nextProbeUsageReportId(model, `text-protocol:${variant}`),\n\t\t);\n\t\tconst text = message.content\n\t\t\t.filter((block): block is TextContent => block.type === \"text\")\n\t\t\t.map((block) => block.text)\n\t\t\t.join(\"\\n\")\n\t\t\t.trim();\n\t\tif (!text) return false;\n\t\tconst parsed = parseTextToolCalls(text, [TEXT_TOOL_PROTOCOL_ECHO_TOOL]);\n\t\treturn parsed.calls.some((call) => call.name === \"echo\" && call.arguments.data === token);\n\t}\n\n\tprivate async calibrateTextToolProtocolForModel(\n\t\tmodel: Model<Api>,\n\t\tmodelKey: string | undefined,\n\t\toptions: { persistFailure: boolean },\n\t): Promise<\n\t\t| { status: \"calibrated\"; variant: TextToolProtocolVariant; calibratedAt: string }\n\t\t| { status: \"failed\"; attemptedAt: string; variantsTried: string[] }\n\t> {\n\t\tconst variantsTried: string[] = [];\n\t\tfor (const variant of TEXT_TOOL_PROTOCOL_VARIANTS) {\n\t\t\tvariantsTried.push(variant);\n\t\t\tlet passed = true;\n\t\t\tfor (let trial = 0; trial < TEXT_TOOL_PROTOCOL_TRIALS_PER_VARIANT; trial++) {\n\t\t\t\tif (!(await this.runTextProtocolTrial(model, variant, `pi-calibration-${trial + 1}`))) {\n\t\t\t\t\tpassed = false;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (passed) {\n\t\t\t\tconst calibratedAt = new Date().toISOString();\n\t\t\t\tif (modelKey) {\n\t\t\t\t\tthis.deps.adaptationStore.setProtocol(\n\t\t\t\t\t\tmodelKey,\n\t\t\t\t\t\t{ version: MODEL_TOOL_PROTOCOL_VERSION, status: \"calibrated\", variant, calibratedAt },\n\t\t\t\t\t\tcalibratedAt,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\treturn { status: \"calibrated\", variant, calibratedAt };\n\t\t\t}\n\t\t}\n\n\t\tconst attemptedAt = new Date().toISOString();\n\t\tif (modelKey && options.persistFailure) {\n\t\t\tthis.deps.adaptationStore.setProtocol(\n\t\t\t\tmodelKey,\n\t\t\t\t{ version: MODEL_TOOL_PROTOCOL_VERSION, status: \"failed\", attemptedAt, variantsTried },\n\t\t\t\tattemptedAt,\n\t\t\t);\n\t\t}\n\t\treturn { status: \"failed\", attemptedAt, variantsTried };\n\t}\n\n\tprivate formatToolProbeReport(results: readonly ToolProbeResult[]): string {\n\t\tconst lines = [\n\t\t\t\"Tool probe results:\",\n\t\t\t\"Model | Verdict | Variant | Native grade | Diagnostic\",\n\t\t\t\"--- | --- | --- | --- | ---\",\n\t\t];\n\t\tfor (const result of results) {\n\t\t\tlines.push(\n\t\t\t\t[\n\t\t\t\t\tresult.model,\n\t\t\t\t\tresult.verdict,\n\t\t\t\t\tresult.variant ?? \"-\",\n\t\t\t\t\tresult.nativeGrade ?? \"-\",\n\t\t\t\t\tresult.diagnostic ? result.diagnostic.replace(/\\s+/g, \" \").slice(0, 160) : \"-\",\n\t\t\t\t].join(\" | \"),\n\t\t\t);\n\t\t}\n\t\treturn lines.join(\"\\n\");\n\t}\n\n\tprivate storeToolProbe(modelKey: string, probe: ModelToolProbe): void {\n\t\tthis.deps.adaptationStore.setToolProbe(modelKey, probe, probe.probedAt);\n\t}\n\n\tprivate async resolveToolProbeModels(target?: string): Promise<Model<Api>[]> {\n\t\tconst trimmed = target?.trim();\n\t\tif (!trimmed) return this.deps.getModelRegistry().getAvailable();\n\t\tconst [provider, ...modelParts] = trimmed.split(\"/\");\n\t\tconst modelId = modelParts.join(\"/\");\n\t\tif (!provider || !modelId) throw new Error(\"Usage: /toolprobe [provider/model]\");\n\t\tconst exact = this.deps.getModelRegistry().find(provider, modelId);\n\t\tif (exact) return [exact];\n\t\tconst current = this.deps.agent.state.model;\n\t\tif (current?.provider === provider && current.id === modelId) return [current];\n\t\tthrow new Error(`Model not found: ${trimmed}`);\n\t}\n\n\tprivate maybeInjectCorrectiveSteer(variant: TextToolProtocolVariant): void {\n\t\tthis.correctiveSteerCount++;\n\t\tif (this.correctiveSteerCount !== 1 && this.correctiveSteerCount % TEXT_TOOL_PROTOCOL_STEER_INTERVAL !== 0) {\n\t\t\treturn;\n\t\t}\n\t\tconst reminder = `Reminder: to call a tool, emit exactly this envelope shape: ${formatVariantEnvelope(variant, \"TOOL\", '{\"arg\":\"value\"}')} — no other format is recognized. Reasoning may appear as prose before the envelope, never inside it.`;\n\t\tthis.deps.sendCorrectiveSteer(reminder).catch(() => {\n\t\t\t// Best-effort steer.\n\t\t});\n\t}\n\n\tprivate looksLikeTextProtocolAttempt(text: string): boolean {\n\t\treturn /<pi:call\\b|<tool_call\\b|```(?:tool|tool_call)[\\s\\S]*\"name\"\\s*:/i.test(text);\n\t}\n\n\tprivate repairSessionCount(modelKey: string, mode: ToolRepairModeName): number {\n\t\tconst key = `${modelKey}\\0${mode}`;\n\t\tconst count = (this.repairModeSessionCounts.get(key) ?? 0) + 1;\n\t\tthis.repairModeSessionCounts.set(key, count);\n\t\treturn count;\n\t}\n\n\tprivate hasFreshToolProbeVerdict(modelKey: string): boolean {\n\t\tconst probedAt = this.deps.adaptationStore.get(modelKey).toolProbe?.probedAt;\n\t\tif (!probedAt) return false;\n\t\tconst age = Date.now() - new Date(probedAt).getTime();\n\t\treturn Number.isFinite(age) && age >= 0 && age < AUTO_TOOL_PROBE_FRESHNESS_MS;\n\t}\n}\n"]}