@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
@@ -2,12 +2,14 @@
2
2
  * One-time migrations that run on startup.
3
3
  */
4
4
  import chalk from "chalk";
5
- import { chmodSync, existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "fs";
5
+ import { chmodSync, existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, renameSync, rmdirSync, rmSync, unlinkSync, writeFileSync, } from "fs";
6
6
  import { dirname, join } from "path";
7
7
  import { CONFIG_DIR_NAME, getAgentDir, getBinDir } from "./config.js";
8
- import { stateDir } from "./core/agent-paths.js";
8
+ import { configBackupsDir, directoryProfilesDir, sessionsDir, stateFile } from "./core/agent-paths.js";
9
+ import { migrateLegacyContextStores, pruneContextStores } from "./core/context/context-store-retention.js";
9
10
  import { migrateKeybindingsConfig } from "./core/keybindings.js";
10
11
  import { isLegacyEnvVarNameConfigValue } from "./core/resolve-config-value.js";
12
+ import { withFileLockSync, writeFileAtomicSync } from "./core/util/atomic-file.js";
11
13
  import { stripJsonComments } from "./utils/json.js";
12
14
  const MIGRATION_GUIDE_URL = "https://github.com/earendil-works/pi-mono/blob/main/packages/coding-agent/CHANGELOG.md#extensions-migration";
13
15
  const EXTENSIONS_DOC_URL = "https://github.com/earendil-works/pi-mono/blob/main/packages/coding-agent/docs/extensions.md";
@@ -325,41 +327,197 @@ function migrateToolsToBin() {
325
327
  }
326
328
  }
327
329
  /**
328
- * Root-level machine-managed stragglers to relocate into their canonical `state/` location.
329
- * Every other machine-managed file already writes through
330
- * `state/`/`cache/`/`work/` via `core/agent-paths.ts` -- this is the one confirmed root straggler.
331
- * Deliberately NOT included: `resource-profiles/` (moving it would also require updating the two
332
- * user-visible scope descriptions in `profile-menu-controller.ts`, out of this migration's file
333
- * scope -- kept at root, recorded OPEN) and reload-coordination (verified already `work/`-scoped via
334
- * `getReloadCoordinationDir`, so it was never a root straggler to begin with).
330
+ * Root-level machine-managed trust state is relocated into `state/`. If both layouts exist, valid
331
+ * entries are merged under the canonical file's lock and canonical decisions win conflicts.
335
332
  */
336
- const AGENT_DIR_ROOT_TO_STATE_STRAGGLERS = ["trust.json"];
333
+ const MAX_SESSION_NAMESPACES_TO_PRUNE = 10_000;
334
+ const MAX_LEGACY_DIRECTORY_ENTRIES_TO_MIGRATE = 10_000;
335
+ const MAX_MIGRATION_CONFLICT_SUFFIXES = 1_000;
336
+ function readMigratedTrustFile(path) {
337
+ try {
338
+ const parsed = JSON.parse(readFileSync(path, "utf-8"));
339
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed))
340
+ return undefined;
341
+ const trust = {};
342
+ for (const [key, value] of Object.entries(parsed)) {
343
+ if (value !== true && value !== false && value !== null)
344
+ return undefined;
345
+ trust[key] = value;
346
+ }
347
+ return trust;
348
+ }
349
+ catch {
350
+ return undefined;
351
+ }
352
+ }
353
+ function migrateTrustState(agentDir) {
354
+ const oldPath = join(agentDir, "trust.json");
355
+ if (!existsSync(oldPath))
356
+ return;
357
+ const newPath = stateFile(agentDir, "trust.json");
358
+ if (!existsSync(newPath)) {
359
+ mkdirSync(dirname(newPath), { recursive: true });
360
+ renameSync(oldPath, newPath);
361
+ return;
362
+ }
363
+ withFileLockSync(newPath, () => {
364
+ const legacy = readMigratedTrustFile(oldPath);
365
+ const canonical = readMigratedTrustFile(newPath);
366
+ if (!legacy || !canonical)
367
+ return;
368
+ const merged = { ...legacy, ...canonical };
369
+ const sorted = Object.fromEntries(Object.entries(merged).sort(([left], [right]) => left.localeCompare(right)));
370
+ writeFileAtomicSync(newPath, `${JSON.stringify(sorted, null, 2)}\n`);
371
+ unlinkSync(oldPath);
372
+ });
373
+ }
374
+ function migrationConflictPath(agentDir, legacyName, entryName) {
375
+ const conflictDir = stateFile(agentDir, "migration-conflicts", legacyName);
376
+ for (let suffix = 0; suffix < MAX_MIGRATION_CONFLICT_SUFFIXES; suffix++) {
377
+ const name = suffix === 0 ? entryName : `${entryName}.legacy-${suffix}`;
378
+ const candidate = join(conflictDir, name);
379
+ if (!existsSync(candidate))
380
+ return candidate;
381
+ }
382
+ return undefined;
383
+ }
337
384
  /**
338
- * Move confirmed root-level machine-managed stragglers into `state/`. Idempotent (a prior move
339
- * leaves nothing at the old path, so a re-run is a no-op) and partial-run-tolerant (a target that
340
- * already exists is left untouched -- never overwritten, so a half-completed earlier run converges
341
- * instead of clobbering data). Each move is independently try/catch-guarded: startup migrations must
342
- * never throw, and one straggler failing to move must not block the others or abort startup. Never
343
- * touches user config/resources -- only the explicit allowlist above.
385
+ * Relocate one known legacy root without traversing its contents. A whole-root rename is O(1);
386
+ * partial migrations scan a bounded number of top-level entries and preserve collisions under
387
+ * state/migration-conflicts instead of overwriting either copy.
344
388
  */
345
- export function migrateAgentDirLayout(agentDir) {
346
- const targetDir = stateDir(agentDir);
347
- for (const name of AGENT_DIR_ROOT_TO_STATE_STRAGGLERS) {
348
- try {
349
- const oldPath = join(agentDir, name);
350
- if (!existsSync(oldPath))
389
+ function migrateLegacyAgentDirectory(agentDir, legacyName, canonicalDir) {
390
+ const legacyDir = join(agentDir, legacyName);
391
+ if (!existsSync(legacyDir))
392
+ return;
393
+ const legacyStats = lstatSync(legacyDir);
394
+ if (!legacyStats.isDirectory() || legacyStats.isSymbolicLink())
395
+ return;
396
+ if (!existsSync(canonicalDir)) {
397
+ mkdirSync(dirname(canonicalDir), { recursive: true });
398
+ renameSync(legacyDir, canonicalDir);
399
+ return;
400
+ }
401
+ const canonicalStats = lstatSync(canonicalDir);
402
+ if (!canonicalStats.isDirectory() || canonicalStats.isSymbolicLink())
403
+ return;
404
+ const entries = readdirSync(legacyDir).slice(0, MAX_LEGACY_DIRECTORY_ENTRIES_TO_MIGRATE);
405
+ for (const entry of entries) {
406
+ const source = join(legacyDir, entry);
407
+ let target = join(canonicalDir, entry);
408
+ if (existsSync(target)) {
409
+ target = migrationConflictPath(agentDir, legacyName, entry) ?? "";
410
+ if (!target)
351
411
  continue;
352
- const newPath = join(targetDir, name);
353
- if (existsSync(newPath))
354
- continue; // Partial prior run: target already migrated, never overwrite.
355
- mkdirSync(targetDir, { recursive: true });
356
- renameSync(oldPath, newPath);
412
+ mkdirSync(dirname(target), { recursive: true });
413
+ }
414
+ try {
415
+ renameSync(source, target);
416
+ }
417
+ catch { }
418
+ }
419
+ try {
420
+ rmdirSync(legacyDir);
421
+ }
422
+ catch { }
423
+ }
424
+ function migrateLegacyAgentFile(agentDir, legacyName, canonicalPath) {
425
+ const legacyPath = join(agentDir, legacyName);
426
+ if (!existsSync(legacyPath))
427
+ return;
428
+ const legacyStats = lstatSync(legacyPath);
429
+ if (!legacyStats.isFile() || legacyStats.isSymbolicLink())
430
+ return;
431
+ let target = canonicalPath;
432
+ if (existsSync(target)) {
433
+ target = migrationConflictPath(agentDir, "root-files", legacyName.replaceAll(":", ".")) ?? "";
434
+ if (!target)
435
+ return;
436
+ }
437
+ mkdirSync(dirname(target), { recursive: true });
438
+ try {
439
+ renameSync(legacyPath, target);
440
+ }
441
+ catch (renameError) {
442
+ // Windows cannot rename an NTFS alternate data stream into a regular file. Preserve the
443
+ // bytes first, then remove only the named stream; never move or rewrite the owning auth file.
444
+ writeFileSync(target, readFileSync(legacyPath), { flag: "wx" });
445
+ try {
446
+ unlinkSync(legacyPath);
357
447
  }
358
448
  catch {
359
- // Best-effort: startup must not fail because one straggler could not be relocated.
449
+ try {
450
+ unlinkSync(target);
451
+ }
452
+ catch { }
453
+ throw renameError;
360
454
  }
361
455
  }
362
456
  }
457
+ /** Remove only empty real per-project session directories; transcript files are never retention-pruned. */
458
+ export function pruneEmptySessionNamespaces(agentDir) {
459
+ const root = sessionsDir(agentDir);
460
+ let candidates;
461
+ try {
462
+ candidates = readdirSync(root, { withFileTypes: true })
463
+ .slice(0, MAX_SESSION_NAMESPACES_TO_PRUNE)
464
+ .filter((entry) => entry.isDirectory() && !entry.isSymbolicLink())
465
+ .map((entry) => join(root, entry.name));
466
+ }
467
+ catch {
468
+ return [];
469
+ }
470
+ const removed = [];
471
+ for (const candidate of candidates) {
472
+ try {
473
+ const stats = lstatSync(candidate);
474
+ if (!stats.isDirectory() || stats.isSymbolicLink() || readdirSync(candidate).length > 0)
475
+ continue;
476
+ rmdirSync(candidate);
477
+ removed.push(candidate);
478
+ }
479
+ catch { }
480
+ }
481
+ return removed;
482
+ }
483
+ /**
484
+ * Consolidate known machine-managed layout generations. Each migration is independently guarded:
485
+ * startup never fails because cleanup is unavailable, and unknown files/resources remain untouched.
486
+ */
487
+ export function migrateAgentDirLayout(agentDir) {
488
+ try {
489
+ migrateTrustState(agentDir);
490
+ }
491
+ catch {
492
+ // Best-effort: startup must not fail because one straggler could not be relocated.
493
+ }
494
+ try {
495
+ migrateLegacyContextStores(agentDir);
496
+ pruneContextStores(agentDir);
497
+ }
498
+ catch { }
499
+ try {
500
+ migrateLegacyAgentDirectory(agentDir, "backups", configBackupsDir(agentDir));
501
+ }
502
+ catch { }
503
+ try {
504
+ migrateLegacyAgentDirectory(agentDir, "resource-profiles", directoryProfilesDir(agentDir));
505
+ }
506
+ catch { }
507
+ try {
508
+ migrateLegacyAgentDirectory(agentDir, "auto-learn", stateFile(agentDir, "legacy-layout", "auto-learn"));
509
+ }
510
+ catch { }
511
+ try {
512
+ migrateLegacyAgentDirectory(agentDir, "tmp", stateFile(agentDir, "legacy-layout", "tmp"));
513
+ }
514
+ catch { }
515
+ try {
516
+ migrateLegacyAgentFile(agentDir, "auth.json:Zone.Identifier", stateFile(agentDir, "legacy-layout", "sidecars", "auth.json.Zone.Identifier"));
517
+ }
518
+ catch { }
519
+ pruneEmptySessionNamespaces(agentDir);
520
+ }
363
521
  /**
364
522
  * Check for deprecated hooks/ and tools/ directories.
365
523
  * Note: tools/ may contain fd/rg binaries extracted by pi, so only warn if it has other files.
@@ -1 +1 @@
1
- {"version":3,"file":"migrations.js","sourceRoot":"","sources":["../src/migrations.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,KAAK,MAAM,OAAO,CAAC;AAC1B,OAAO,EAAE,SAAS,EAAE,UAAU,EAAE,SAAS,EAAE,WAAW,EAAE,Y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tB,OAAO,EAAE,CAAC;QAAA,CACV,CAAC;QACF,OAAO,CAAC,KAAK,CAAC,UAAU,EAAE,CAAC,IAAI,CAAC,CAAC;QACjC,OAAO,CAAC,KAAK,CAAC,MAAM,EAAE,CAAC;QACvB,OAAO,CAAC,KAAK,CAAC,IAAI,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;QACnC,OAAO,CAAC,KAAK,CAAC,IAAI,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC;QAClC,OAAO,CAAC,KAAK,CAAC,IAAI,CAAC,OAAO,EAAE,MAAM,CAAC,CAAC;IAAA,CACpC,CAAC,CAAC;IACH,OAAO,CAAC,GAAG,EAAE,CAAC;AAAA,CACd;AAED;;;;GAIG;AACH,MAAM,UAAU,aAAa,CAAC,GAAW,EAGvC;IACD,qBAAqB,CAAC,WAAW,EAAE,CAAC,CAAC;IACrC,MAAM,qBAAqB,GAAG,qBAAqB,EAAE,CAAC;IACtD,iCAAiC,EAAE,CAAC;IACpC,4BAA4B,EAAE,CAAC;IAC/B,iBAAiB,EAAE,CAAC;IACpB,4BAA4B,EAAE,CAAC;IAC/B,MAAM,mBAAmB,GAAG,sBAAsB,CAAC,GAAG,CAAC,CAAC;IACxD,OAAO,EAAE,qBAAqB,EAAE,mBAAmB,EAAE,CAAC;AAAA,CACtD","sourcesContent":["/**\n * One-time migrations that run on startup.\n */\n\nimport chalk from \"chalk\";\nimport { chmodSync, existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, writeFileSync } from \"fs\";\nimport { dirname, join } from \"path\";\nimport { CONFIG_DIR_NAME, getAgentDir, getBinDir } from \"./config.ts\";\nimport { stateDir } from \"./core/agent-paths.ts\";\nimport { migrateKeybindingsConfig } from \"./core/keybindings.ts\";\nimport { isLegacyEnvVarNameConfigValue } from \"./core/resolve-config-value.ts\";\nimport { stripJsonComments } from \"./utils/json.ts\";\n\nconst MIGRATION_GUIDE_URL =\n\t\"https://github.com/earendil-works/pi-mono/blob/main/packages/coding-agent/CHANGELOG.md#extensions-migration\";\nconst EXTENSIONS_DOC_URL =\n\t\"https://github.com/earendil-works/pi-mono/blob/main/packages/coding-agent/docs/extensions.md\";\n\n/**\n * Migrate legacy oauth.json and settings.json apiKeys to auth.json.\n *\n * @returns Array of provider names that were migrated\n */\nexport function migrateAuthToAuthJson(): string[] {\n\tconst agentDir = getAgentDir();\n\tconst authPath = join(agentDir, \"auth.json\");\n\tconst oauthPath = join(agentDir, \"oauth.json\");\n\tconst settingsPath = join(agentDir, \"settings.json\");\n\n\t// Skip if auth.json already exists\n\tif (existsSync(authPath)) return [];\n\n\tconst migrated: Record<string, unknown> = {};\n\tconst providers: string[] = [];\n\n\t// Migrate oauth.json\n\tif (existsSync(oauthPath)) {\n\t\ttry {\n\t\t\tconst oauth = JSON.parse(readFileSync(oauthPath, \"utf-8\"));\n\t\t\tfor (const [provider, cred] of Object.entries(oauth)) {\n\t\t\t\tmigrated[provider] = { type: \"oauth\", ...(cred as object) };\n\t\t\t\tproviders.push(provider);\n\t\t\t}\n\t\t\trenameSync(oauthPath, `${oauthPath}.migrated`);\n\t\t} catch {\n\t\t\t// Skip on error\n\t\t}\n\t}\n\n\t// Migrate settings.json apiKeys\n\tif (existsSync(settingsPath)) {\n\t\ttry {\n\t\t\tconst content = readFileSync(settingsPath, \"utf-8\");\n\t\t\tconst settings = JSON.parse(content);\n\t\t\tif (settings.apiKeys && typeof settings.apiKeys === \"object\") {\n\t\t\t\tfor (const [provider, key] of Object.entries(settings.apiKeys)) {\n\t\t\t\t\tif (!migrated[provider] && typeof key === \"string\") {\n\t\t\t\t\t\tmigrated[provider] = { type: \"api_key\", key };\n\t\t\t\t\t\tproviders.push(provider);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tdelete settings.apiKeys;\n\t\t\t\twriteFileSync(settingsPath, JSON.stringify(settings, null, 2));\n\t\t\t}\n\t\t} catch {\n\t\t\t// Skip on error\n\t\t}\n\t}\n\n\tif (Object.keys(migrated).length > 0) {\n\t\tmkdirSync(dirname(authPath), { recursive: true });\n\t\twriteFileSync(authPath, JSON.stringify(migrated, null, 2), { mode: 0o600 });\n\t}\n\n\treturn providers;\n}\n\ninterface ConfigValueMigration {\n\tlocation: string;\n\tfrom: string;\n\tto: string;\n}\n\nfunction migrateLegacyEnvVarString(value: string): string | undefined {\n\treturn isLegacyEnvVarNameConfigValue(value) ? `$${value}` : undefined;\n}\n\nfunction migrateStringProperty(\n\trecord: Record<string, unknown>,\n\tkey: string,\n\tlocation: string,\n\tmigrations: ConfigValueMigration[],\n): boolean {\n\tconst value = record[key];\n\tif (typeof value !== \"string\") return false;\n\tconst migrated = migrateLegacyEnvVarString(value);\n\tif (migrated === undefined) return false;\n\trecord[key] = migrated;\n\tmigrations.push({ location, from: value, to: migrated });\n\treturn true;\n}\n\nfunction migrateHeadersConfig(headers: unknown, location: string, migrations: ConfigValueMigration[]): boolean {\n\tif (typeof headers !== \"object\" || headers === null || Array.isArray(headers)) return false;\n\tconst headerRecord = headers as Record<string, unknown>;\n\tlet migrated = false;\n\tfor (const [key, value] of Object.entries(headerRecord)) {\n\t\tif (typeof value !== \"string\") continue;\n\t\tconst migratedValue = migrateLegacyEnvVarString(value);\n\t\tif (migratedValue === undefined) continue;\n\t\theaderRecord[key] = migratedValue;\n\t\tmigrations.push({ location: `${location}[${JSON.stringify(key)}]`, from: value, to: migratedValue });\n\t\tmigrated = true;\n\t}\n\treturn migrated;\n}\n\nfunction migrateAuthJsonConfigValues(agentDir: string): ConfigValueMigration[] {\n\tconst authPath = join(agentDir, \"auth.json\");\n\tif (!existsSync(authPath)) return [];\n\n\ttry {\n\t\tconst parsed = JSON.parse(readFileSync(authPath, \"utf-8\")) as unknown;\n\t\tif (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) return [];\n\t\tconst authData = parsed as Record<string, unknown>;\n\n\t\tconst migrations: ConfigValueMigration[] = [];\n\t\tfor (const [provider, credential] of Object.entries(authData)) {\n\t\t\tif (typeof credential !== \"object\" || credential === null || Array.isArray(credential)) continue;\n\t\t\tconst credentialRecord = credential as Record<string, unknown>;\n\t\t\tif (credentialRecord.type !== \"api_key\") continue;\n\t\t\tmigrateStringProperty(credentialRecord, \"key\", `auth.json[${JSON.stringify(provider)}].key`, migrations);\n\t\t}\n\n\t\tif (migrations.length === 0) return [];\n\t\twriteFileSync(authPath, `${JSON.stringify(parsed, null, 2)}\\n`, \"utf-8\");\n\t\tchmodSync(authPath, 0o600);\n\t\treturn migrations;\n\t} catch {\n\t\treturn [];\n\t}\n}\n\nfunction migrateModelsJsonConfigValues(agentDir: string): ConfigValueMigration[] {\n\tconst modelsPath = join(agentDir, \"models.json\");\n\tif (!existsSync(modelsPath)) return [];\n\n\tlet parsed: unknown;\n\ttry {\n\t\tparsed = JSON.parse(stripJsonComments(readFileSync(modelsPath, \"utf-8\"))) as unknown;\n\t} catch {\n\t\treturn [];\n\t}\n\tif (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) return [];\n\tconst modelsData = parsed as Record<string, unknown>;\n\tconst providers = modelsData.providers;\n\tif (typeof providers !== \"object\" || providers === null || Array.isArray(providers)) return [];\n\n\tconst migrations: ConfigValueMigration[] = [];\n\tfor (const [provider, providerConfig] of Object.entries(providers)) {\n\t\tif (typeof providerConfig !== \"object\" || providerConfig === null || Array.isArray(providerConfig)) continue;\n\t\tconst providerRecord = providerConfig as Record<string, unknown>;\n\t\tconst providerLocation = `models.json.providers[${JSON.stringify(provider)}]`;\n\t\tmigrateStringProperty(providerRecord, \"apiKey\", `${providerLocation}.apiKey`, migrations);\n\t\tmigrateHeadersConfig(providerRecord.headers, `${providerLocation}.headers`, migrations);\n\n\t\tif (Array.isArray(providerRecord.models)) {\n\t\t\tfor (let index = 0; index < providerRecord.models.length; index++) {\n\t\t\t\tconst modelConfig = providerRecord.models[index];\n\t\t\t\tif (typeof modelConfig !== \"object\" || modelConfig === null || Array.isArray(modelConfig)) continue;\n\t\t\t\tconst modelRecord = modelConfig as Record<string, unknown>;\n\t\t\t\tconst modelKey = typeof modelRecord.id === \"string\" ? JSON.stringify(modelRecord.id) : String(index);\n\t\t\t\tmigrateHeadersConfig(modelRecord.headers, `${providerLocation}.models[${modelKey}].headers`, migrations);\n\t\t\t}\n\t\t}\n\n\t\tconst modelOverrides = providerRecord.modelOverrides;\n\t\tif (typeof modelOverrides === \"object\" && modelOverrides !== null && !Array.isArray(modelOverrides)) {\n\t\t\tfor (const [modelId, modelOverride] of Object.entries(modelOverrides)) {\n\t\t\t\tif (typeof modelOverride !== \"object\" || modelOverride === null || Array.isArray(modelOverride)) continue;\n\t\t\t\tconst modelOverrideRecord = modelOverride as Record<string, unknown>;\n\t\t\t\tmigrateHeadersConfig(\n\t\t\t\t\tmodelOverrideRecord.headers,\n\t\t\t\t\t`${providerLocation}.modelOverrides[${JSON.stringify(modelId)}].headers`,\n\t\t\t\t\tmigrations,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n\n\tif (migrations.length === 0) return [];\n\twriteFileSync(modelsPath, `${JSON.stringify(parsed, null, 2)}\\n`, \"utf-8\");\n\treturn migrations;\n}\n\nfunction migrateExplicitEnvVarConfigValues(): void {\n\tconst agentDir = getAgentDir();\n\tconst migrations = [...migrateAuthJsonConfigValues(agentDir), ...migrateModelsJsonConfigValues(agentDir)];\n\tif (migrations.length === 0) return;\n\n\tconst details = migrations.map((migration) => ` - ${migration.location}: ${migration.from} -> ${migration.to}`);\n\tconsole.log(\n\t\tchalk.yellow(\n\t\t\t[\n\t\t\t\t\"Warning: Migrated API key/header environment references to explicit $ENV_VAR syntax. Plain strings will be treated as literals.\",\n\t\t\t\t...details,\n\t\t\t].join(\"\\n\"),\n\t\t),\n\t);\n}\n\n/**\n * Migrate sessions from ~/.pi/agent/*.jsonl to proper session directories.\n *\n * Bug in v0.30.0: Sessions were saved to ~/.pi/agent/ instead of\n * ~/.pi/agent/sessions/<encoded-cwd>/. This migration moves them\n * to the correct location based on the cwd in their session header.\n *\n * See: https://github.com/earendil-works/pi-mono/issues/320\n */\nexport function getMigratedSessionFileName(file: string): string | undefined {\n\tconst fileName = file.split(/[\\\\/]/).pop();\n\treturn fileName || undefined;\n}\n\nexport function migrateSessionsFromAgentRoot(): void {\n\tconst agentDir = getAgentDir();\n\n\t// Find all .jsonl files directly in agentDir (not in subdirectories)\n\tlet files: string[];\n\ttry {\n\t\tfiles = readdirSync(agentDir)\n\t\t\t.filter((f) => f.endsWith(\".jsonl\"))\n\t\t\t.map((f) => join(agentDir, f));\n\t} catch {\n\t\treturn;\n\t}\n\n\tif (files.length === 0) return;\n\n\tfor (const file of files) {\n\t\ttry {\n\t\t\t// Read first line to get session header\n\t\t\tconst content = readFileSync(file, \"utf8\");\n\t\t\tconst firstLine = content.split(\"\\n\")[0];\n\t\t\tif (!firstLine?.trim()) continue;\n\n\t\t\tconst header = JSON.parse(firstLine);\n\t\t\tif (header.type !== \"session\" || !header.cwd) continue;\n\n\t\t\tconst cwd: string = header.cwd;\n\n\t\t\t// Compute the correct session directory (same encoding as session-manager.ts)\n\t\t\tconst safePath = `--${cwd.replace(/^[/\\\\]/, \"\").replace(/[/\\\\:]/g, \"-\")}--`;\n\t\t\tconst correctDir = join(agentDir, \"sessions\", safePath);\n\n\t\t\t// Create directory if needed\n\t\t\tif (!existsSync(correctDir)) {\n\t\t\t\tmkdirSync(correctDir, { recursive: true });\n\t\t\t}\n\n\t\t\t// Move the file\n\t\t\tconst fileName = getMigratedSessionFileName(file);\n\t\t\tif (!fileName) continue;\n\t\t\tconst newPath = join(correctDir, fileName);\n\n\t\t\tif (existsSync(newPath)) continue; // Skip if target exists\n\n\t\t\trenameSync(file, newPath);\n\t\t} catch {\n\t\t\t// Skip files that can't be migrated\n\t\t}\n\t}\n}\n\n/**\n * Migrate commands/ to prompts/ if needed.\n * Works for both regular directories and symlinks.\n */\nfunction migrateCommandsToPrompts(baseDir: string, label: string): boolean {\n\tconst commandsDir = join(baseDir, \"commands\");\n\tconst promptsDir = join(baseDir, \"prompts\");\n\n\tif (existsSync(commandsDir) && !existsSync(promptsDir)) {\n\t\ttry {\n\t\t\trenameSync(commandsDir, promptsDir);\n\t\t\tconsole.log(chalk.green(`Migrated ${label} commands/ → prompts/`));\n\t\t\treturn true;\n\t\t} catch (err) {\n\t\t\tconsole.log(\n\t\t\t\tchalk.yellow(\n\t\t\t\t\t`Warning: Could not migrate ${label} commands/ to prompts/: ${err instanceof Error ? err.message : err}`,\n\t\t\t\t),\n\t\t\t);\n\t\t}\n\t}\n\treturn false;\n}\n\nfunction migrateKeybindingsConfigFile(): void {\n\tconst configPath = join(getAgentDir(), \"keybindings.json\");\n\tif (!existsSync(configPath)) return;\n\n\ttry {\n\t\tconst parsed = JSON.parse(readFileSync(configPath, \"utf-8\")) as unknown;\n\t\tif (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) {\n\t\t\treturn;\n\t\t}\n\t\tconst { config, migrated } = migrateKeybindingsConfig(parsed as Record<string, unknown>);\n\t\tif (!migrated) return;\n\t\twriteFileSync(configPath, `${JSON.stringify(config, null, 2)}\\n`, \"utf-8\");\n\t} catch {\n\t\t// Ignore malformed files during migration\n\t}\n}\n\n/**\n * Move fd/rg binaries from tools/ to bin/ if they exist.\n */\nfunction migrateToolsToBin(): void {\n\tconst agentDir = getAgentDir();\n\tconst toolsDir = join(agentDir, \"tools\");\n\tconst binDir = getBinDir();\n\n\tif (!existsSync(toolsDir)) return;\n\n\tconst binaries = [\"fd\", \"rg\", \"fd.exe\", \"rg.exe\"];\n\tlet movedAny = false;\n\n\tfor (const bin of binaries) {\n\t\tconst oldPath = join(toolsDir, bin);\n\t\tconst newPath = join(binDir, bin);\n\n\t\tif (existsSync(oldPath)) {\n\t\t\tif (!existsSync(binDir)) {\n\t\t\t\tmkdirSync(binDir, { recursive: true });\n\t\t\t}\n\t\t\tif (!existsSync(newPath)) {\n\t\t\t\ttry {\n\t\t\t\t\trenameSync(oldPath, newPath);\n\t\t\t\t\tmovedAny = true;\n\t\t\t\t} catch {\n\t\t\t\t\t// Ignore errors\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// Target exists, just delete the old one\n\t\t\t\ttry {\n\t\t\t\t\trmSync?.(oldPath, { force: true });\n\t\t\t\t} catch {\n\t\t\t\t\t// Ignore\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tif (movedAny) {\n\t\tconsole.log(chalk.green(`Migrated managed binaries tools/ → bin/`));\n\t}\n}\n\n/**\n * Root-level machine-managed stragglers to relocate into their canonical `state/` location.\n * Every other machine-managed file already writes through\n * `state/`/`cache/`/`work/` via `core/agent-paths.ts` -- this is the one confirmed root straggler.\n * Deliberately NOT included: `resource-profiles/` (moving it would also require updating the two\n * user-visible scope descriptions in `profile-menu-controller.ts`, out of this migration's file\n * scope -- kept at root, recorded OPEN) and reload-coordination (verified already `work/`-scoped via\n * `getReloadCoordinationDir`, so it was never a root straggler to begin with).\n */\nconst AGENT_DIR_ROOT_TO_STATE_STRAGGLERS = [\"trust.json\"];\n\n/**\n * Move confirmed root-level machine-managed stragglers into `state/`. Idempotent (a prior move\n * leaves nothing at the old path, so a re-run is a no-op) and partial-run-tolerant (a target that\n * already exists is left untouched -- never overwritten, so a half-completed earlier run converges\n * instead of clobbering data). Each move is independently try/catch-guarded: startup migrations must\n * never throw, and one straggler failing to move must not block the others or abort startup. Never\n * touches user config/resources -- only the explicit allowlist above.\n */\nexport function migrateAgentDirLayout(agentDir: string): void {\n\tconst targetDir = stateDir(agentDir);\n\tfor (const name of AGENT_DIR_ROOT_TO_STATE_STRAGGLERS) {\n\t\ttry {\n\t\t\tconst oldPath = join(agentDir, name);\n\t\t\tif (!existsSync(oldPath)) continue;\n\t\t\tconst newPath = join(targetDir, name);\n\t\t\tif (existsSync(newPath)) continue; // Partial prior run: target already migrated, never overwrite.\n\t\t\tmkdirSync(targetDir, { recursive: true });\n\t\t\trenameSync(oldPath, newPath);\n\t\t} catch {\n\t\t\t// Best-effort: startup must not fail because one straggler could not be relocated.\n\t\t}\n\t}\n}\n\n/**\n * Check for deprecated hooks/ and tools/ directories.\n * Note: tools/ may contain fd/rg binaries extracted by pi, so only warn if it has other files.\n */\nfunction checkDeprecatedExtensionDirs(baseDir: string, label: string): string[] {\n\tconst hooksDir = join(baseDir, \"hooks\");\n\tconst toolsDir = join(baseDir, \"tools\");\n\tconst warnings: string[] = [];\n\n\tif (existsSync(hooksDir)) {\n\t\twarnings.push(`${label} hooks/ directory found. Hooks have been renamed to extensions.`);\n\t}\n\n\tif (existsSync(toolsDir)) {\n\t\t// Check if tools/ contains anything other than fd/rg (which are auto-extracted binaries)\n\t\ttry {\n\t\t\tconst entries = readdirSync(toolsDir);\n\t\t\tconst customTools = entries.filter((e) => {\n\t\t\t\tconst lower = e.toLowerCase();\n\t\t\t\treturn (\n\t\t\t\t\tlower !== \"fd\" && lower !== \"rg\" && lower !== \"fd.exe\" && lower !== \"rg.exe\" && !e.startsWith(\".\") // Ignore .DS_Store and other hidden files\n\t\t\t\t);\n\t\t\t});\n\t\t\tif (customTools.length > 0) {\n\t\t\t\twarnings.push(\n\t\t\t\t\t`${label} tools/ directory contains custom tools. Custom tools have been merged into extensions.`,\n\t\t\t\t);\n\t\t\t}\n\t\t} catch {\n\t\t\t// Ignore read errors\n\t\t}\n\t}\n\n\treturn warnings;\n}\n\n/**\n * Run extension system migrations (commands→prompts) and collect warnings about deprecated directories.\n */\nfunction migrateExtensionSystem(cwd: string): string[] {\n\tconst agentDir = getAgentDir();\n\tconst projectDir = join(cwd, CONFIG_DIR_NAME);\n\n\t// Migrate commands/ to prompts/\n\tmigrateCommandsToPrompts(agentDir, \"Global\");\n\tmigrateCommandsToPrompts(projectDir, \"Project\");\n\n\t// Check for deprecated directories\n\tconst warnings = [\n\t\t...checkDeprecatedExtensionDirs(agentDir, \"Global\"),\n\t\t...checkDeprecatedExtensionDirs(projectDir, \"Project\"),\n\t];\n\n\treturn warnings;\n}\n\n/**\n * Print deprecation warnings and wait for keypress.\n */\nexport async function showDeprecationWarnings(warnings: string[]): Promise<void> {\n\tif (warnings.length === 0) return;\n\n\tfor (const warning of warnings) {\n\t\tconsole.log(chalk.yellow(`Warning: ${warning}`));\n\t}\n\tconsole.log(chalk.yellow(`\\nMove your extensions to the extensions/ directory.`));\n\tconsole.log(chalk.yellow(`Migration guide: ${MIGRATION_GUIDE_URL}`));\n\tconsole.log(chalk.yellow(`Documentation: ${EXTENSIONS_DOC_URL}`));\n\tif (!process.stdin.isTTY || !process.stdout.isTTY) {\n\t\tconsole.log();\n\t\treturn;\n\t}\n\tconsole.log(chalk.dim(`\\nPress any key to continue...`));\n\n\tawait new Promise<void>((resolve) => {\n\t\tlet settled = false;\n\t\tconst finish = () => {\n\t\t\tif (settled) return;\n\t\t\tsettled = true;\n\t\t\tprocess.stdin.removeListener(\"data\", finish);\n\t\t\tprocess.stdin.removeListener(\"end\", finish);\n\t\t\tprocess.stdin.removeListener(\"error\", finish);\n\t\t\tprocess.stdin.setRawMode?.(false);\n\t\t\tprocess.stdin.pause();\n\t\t\tresolve();\n\t\t};\n\t\tprocess.stdin.setRawMode?.(true);\n\t\tprocess.stdin.resume();\n\t\tprocess.stdin.once(\"data\", finish);\n\t\tprocess.stdin.once(\"end\", finish);\n\t\tprocess.stdin.once(\"error\", finish);\n\t});\n\tconsole.log();\n}\n\n/**\n * Run all migrations. Called once on startup.\n *\n * @returns Object with migration results and deprecation warnings\n */\nexport function runMigrations(cwd: string): {\n\tmigratedAuthProviders: string[];\n\tdeprecationWarnings: string[];\n} {\n\tmigrateAgentDirLayout(getAgentDir());\n\tconst migratedAuthProviders = migrateAuthToAuthJson();\n\tmigrateExplicitEnvVarConfigValues();\n\tmigrateSessionsFromAgentRoot();\n\tmigrateToolsToBin();\n\tmigrateKeybindingsConfigFile();\n\tconst deprecationWarnings = migrateExtensionSystem(cwd);\n\treturn { migratedAuthProviders, deprecationWarnings };\n}\n"]}
1
+ {"version":3,"file":"migrations.js","sourceRoot":"","sources":["../src/migrations.ts"],"names":[],"mappings":"AAAA;;GA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;AAED;;;;GAIG;AACH,MAAM,UAAU,aAAa,CAAC,GAAW,EAGvC;IACD,qBAAqB,CAAC,WAAW,EAAE,CAAC,CAAC;IACrC,MAAM,qBAAqB,GAAG,qBAAqB,EAAE,CAAC;IACtD,iCAAiC,EAAE,CAAC;IACpC,4BAA4B,EAAE,CAAC;IAC/B,iBAAiB,EAAE,CAAC;IACpB,4BAA4B,EAAE,CAAC;IAC/B,MAAM,mBAAmB,GAAG,sBAAsB,CAAC,GAAG,CAAC,CAAC;IACxD,OAAO,EAAE,qBAAqB,EAAE,mBAAmB,EAAE,CAAC;AAAA,CACtD","sourcesContent":["/**\n * One-time migrations that run on startup.\n */\n\nimport chalk from \"chalk\";\nimport {\n\tchmodSync,\n\texistsSync,\n\tlstatSync,\n\tmkdirSync,\n\treaddirSync,\n\treadFileSync,\n\trenameSync,\n\trmdirSync,\n\trmSync,\n\tunlinkSync,\n\twriteFileSync,\n} from \"fs\";\nimport { dirname, join } from \"path\";\nimport { CONFIG_DIR_NAME, getAgentDir, getBinDir } from \"./config.ts\";\nimport { configBackupsDir, directoryProfilesDir, sessionsDir, stateFile } from \"./core/agent-paths.ts\";\nimport { migrateLegacyContextStores, pruneContextStores } from \"./core/context/context-store-retention.ts\";\nimport { migrateKeybindingsConfig } from \"./core/keybindings.ts\";\nimport { isLegacyEnvVarNameConfigValue } from \"./core/resolve-config-value.ts\";\nimport { withFileLockSync, writeFileAtomicSync } from \"./core/util/atomic-file.ts\";\nimport { stripJsonComments } from \"./utils/json.ts\";\n\nconst MIGRATION_GUIDE_URL =\n\t\"https://github.com/earendil-works/pi-mono/blob/main/packages/coding-agent/CHANGELOG.md#extensions-migration\";\nconst EXTENSIONS_DOC_URL =\n\t\"https://github.com/earendil-works/pi-mono/blob/main/packages/coding-agent/docs/extensions.md\";\n\n/**\n * Migrate legacy oauth.json and settings.json apiKeys to auth.json.\n *\n * @returns Array of provider names that were migrated\n */\nexport function migrateAuthToAuthJson(): string[] {\n\tconst agentDir = getAgentDir();\n\tconst authPath = join(agentDir, \"auth.json\");\n\tconst oauthPath = join(agentDir, \"oauth.json\");\n\tconst settingsPath = join(agentDir, \"settings.json\");\n\n\t// Skip if auth.json already exists\n\tif (existsSync(authPath)) return [];\n\n\tconst migrated: Record<string, unknown> = {};\n\tconst providers: string[] = [];\n\n\t// Migrate oauth.json\n\tif (existsSync(oauthPath)) {\n\t\ttry {\n\t\t\tconst oauth = JSON.parse(readFileSync(oauthPath, \"utf-8\"));\n\t\t\tfor (const [provider, cred] of Object.entries(oauth)) {\n\t\t\t\tmigrated[provider] = { type: \"oauth\", ...(cred as object) };\n\t\t\t\tproviders.push(provider);\n\t\t\t}\n\t\t\trenameSync(oauthPath, `${oauthPath}.migrated`);\n\t\t} catch {\n\t\t\t// Skip on error\n\t\t}\n\t}\n\n\t// Migrate settings.json apiKeys\n\tif (existsSync(settingsPath)) {\n\t\ttry {\n\t\t\tconst content = readFileSync(settingsPath, \"utf-8\");\n\t\t\tconst settings = JSON.parse(content);\n\t\t\tif (settings.apiKeys && typeof settings.apiKeys === \"object\") {\n\t\t\t\tfor (const [provider, key] of Object.entries(settings.apiKeys)) {\n\t\t\t\t\tif (!migrated[provider] && typeof key === \"string\") {\n\t\t\t\t\t\tmigrated[provider] = { type: \"api_key\", key };\n\t\t\t\t\t\tproviders.push(provider);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tdelete settings.apiKeys;\n\t\t\t\twriteFileSync(settingsPath, JSON.stringify(settings, null, 2));\n\t\t\t}\n\t\t} catch {\n\t\t\t// Skip on error\n\t\t}\n\t}\n\n\tif (Object.keys(migrated).length > 0) {\n\t\tmkdirSync(dirname(authPath), { recursive: true });\n\t\twriteFileSync(authPath, JSON.stringify(migrated, null, 2), { mode: 0o600 });\n\t}\n\n\treturn providers;\n}\n\ninterface ConfigValueMigration {\n\tlocation: string;\n\tfrom: string;\n\tto: string;\n}\n\nfunction migrateLegacyEnvVarString(value: string): string | undefined {\n\treturn isLegacyEnvVarNameConfigValue(value) ? `$${value}` : undefined;\n}\n\nfunction migrateStringProperty(\n\trecord: Record<string, unknown>,\n\tkey: string,\n\tlocation: string,\n\tmigrations: ConfigValueMigration[],\n): boolean {\n\tconst value = record[key];\n\tif (typeof value !== \"string\") return false;\n\tconst migrated = migrateLegacyEnvVarString(value);\n\tif (migrated === undefined) return false;\n\trecord[key] = migrated;\n\tmigrations.push({ location, from: value, to: migrated });\n\treturn true;\n}\n\nfunction migrateHeadersConfig(headers: unknown, location: string, migrations: ConfigValueMigration[]): boolean {\n\tif (typeof headers !== \"object\" || headers === null || Array.isArray(headers)) return false;\n\tconst headerRecord = headers as Record<string, unknown>;\n\tlet migrated = false;\n\tfor (const [key, value] of Object.entries(headerRecord)) {\n\t\tif (typeof value !== \"string\") continue;\n\t\tconst migratedValue = migrateLegacyEnvVarString(value);\n\t\tif (migratedValue === undefined) continue;\n\t\theaderRecord[key] = migratedValue;\n\t\tmigrations.push({ location: `${location}[${JSON.stringify(key)}]`, from: value, to: migratedValue });\n\t\tmigrated = true;\n\t}\n\treturn migrated;\n}\n\nfunction migrateAuthJsonConfigValues(agentDir: string): ConfigValueMigration[] {\n\tconst authPath = join(agentDir, \"auth.json\");\n\tif (!existsSync(authPath)) return [];\n\n\ttry {\n\t\tconst parsed = JSON.parse(readFileSync(authPath, \"utf-8\")) as unknown;\n\t\tif (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) return [];\n\t\tconst authData = parsed as Record<string, unknown>;\n\n\t\tconst migrations: ConfigValueMigration[] = [];\n\t\tfor (const [provider, credential] of Object.entries(authData)) {\n\t\t\tif (typeof credential !== \"object\" || credential === null || Array.isArray(credential)) continue;\n\t\t\tconst credentialRecord = credential as Record<string, unknown>;\n\t\t\tif (credentialRecord.type !== \"api_key\") continue;\n\t\t\tmigrateStringProperty(credentialRecord, \"key\", `auth.json[${JSON.stringify(provider)}].key`, migrations);\n\t\t}\n\n\t\tif (migrations.length === 0) return [];\n\t\twriteFileSync(authPath, `${JSON.stringify(parsed, null, 2)}\\n`, \"utf-8\");\n\t\tchmodSync(authPath, 0o600);\n\t\treturn migrations;\n\t} catch {\n\t\treturn [];\n\t}\n}\n\nfunction migrateModelsJsonConfigValues(agentDir: string): ConfigValueMigration[] {\n\tconst modelsPath = join(agentDir, \"models.json\");\n\tif (!existsSync(modelsPath)) return [];\n\n\tlet parsed: unknown;\n\ttry {\n\t\tparsed = JSON.parse(stripJsonComments(readFileSync(modelsPath, \"utf-8\"))) as unknown;\n\t} catch {\n\t\treturn [];\n\t}\n\tif (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) return [];\n\tconst modelsData = parsed as Record<string, unknown>;\n\tconst providers = modelsData.providers;\n\tif (typeof providers !== \"object\" || providers === null || Array.isArray(providers)) return [];\n\n\tconst migrations: ConfigValueMigration[] = [];\n\tfor (const [provider, providerConfig] of Object.entries(providers)) {\n\t\tif (typeof providerConfig !== \"object\" || providerConfig === null || Array.isArray(providerConfig)) continue;\n\t\tconst providerRecord = providerConfig as Record<string, unknown>;\n\t\tconst providerLocation = `models.json.providers[${JSON.stringify(provider)}]`;\n\t\tmigrateStringProperty(providerRecord, \"apiKey\", `${providerLocation}.apiKey`, migrations);\n\t\tmigrateHeadersConfig(providerRecord.headers, `${providerLocation}.headers`, migrations);\n\n\t\tif (Array.isArray(providerRecord.models)) {\n\t\t\tfor (let index = 0; index < providerRecord.models.length; index++) {\n\t\t\t\tconst modelConfig = providerRecord.models[index];\n\t\t\t\tif (typeof modelConfig !== \"object\" || modelConfig === null || Array.isArray(modelConfig)) continue;\n\t\t\t\tconst modelRecord = modelConfig as Record<string, unknown>;\n\t\t\t\tconst modelKey = typeof modelRecord.id === \"string\" ? JSON.stringify(modelRecord.id) : String(index);\n\t\t\t\tmigrateHeadersConfig(modelRecord.headers, `${providerLocation}.models[${modelKey}].headers`, migrations);\n\t\t\t}\n\t\t}\n\n\t\tconst modelOverrides = providerRecord.modelOverrides;\n\t\tif (typeof modelOverrides === \"object\" && modelOverrides !== null && !Array.isArray(modelOverrides)) {\n\t\t\tfor (const [modelId, modelOverride] of Object.entries(modelOverrides)) {\n\t\t\t\tif (typeof modelOverride !== \"object\" || modelOverride === null || Array.isArray(modelOverride)) continue;\n\t\t\t\tconst modelOverrideRecord = modelOverride as Record<string, unknown>;\n\t\t\t\tmigrateHeadersConfig(\n\t\t\t\t\tmodelOverrideRecord.headers,\n\t\t\t\t\t`${providerLocation}.modelOverrides[${JSON.stringify(modelId)}].headers`,\n\t\t\t\t\tmigrations,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n\n\tif (migrations.length === 0) return [];\n\twriteFileSync(modelsPath, `${JSON.stringify(parsed, null, 2)}\\n`, \"utf-8\");\n\treturn migrations;\n}\n\nfunction migrateExplicitEnvVarConfigValues(): void {\n\tconst agentDir = getAgentDir();\n\tconst migrations = [...migrateAuthJsonConfigValues(agentDir), ...migrateModelsJsonConfigValues(agentDir)];\n\tif (migrations.length === 0) return;\n\n\tconst details = migrations.map((migration) => ` - ${migration.location}: ${migration.from} -> ${migration.to}`);\n\tconsole.log(\n\t\tchalk.yellow(\n\t\t\t[\n\t\t\t\t\"Warning: Migrated API key/header environment references to explicit $ENV_VAR syntax. Plain strings will be treated as literals.\",\n\t\t\t\t...details,\n\t\t\t].join(\"\\n\"),\n\t\t),\n\t);\n}\n\n/**\n * Migrate sessions from ~/.pi/agent/*.jsonl to proper session directories.\n *\n * Bug in v0.30.0: Sessions were saved to ~/.pi/agent/ instead of\n * ~/.pi/agent/sessions/<encoded-cwd>/. This migration moves them\n * to the correct location based on the cwd in their session header.\n *\n * See: https://github.com/earendil-works/pi-mono/issues/320\n */\nexport function getMigratedSessionFileName(file: string): string | undefined {\n\tconst fileName = file.split(/[\\\\/]/).pop();\n\treturn fileName || undefined;\n}\n\nexport function migrateSessionsFromAgentRoot(): void {\n\tconst agentDir = getAgentDir();\n\n\t// Find all .jsonl files directly in agentDir (not in subdirectories)\n\tlet files: string[];\n\ttry {\n\t\tfiles = readdirSync(agentDir)\n\t\t\t.filter((f) => f.endsWith(\".jsonl\"))\n\t\t\t.map((f) => join(agentDir, f));\n\t} catch {\n\t\treturn;\n\t}\n\n\tif (files.length === 0) return;\n\n\tfor (const file of files) {\n\t\ttry {\n\t\t\t// Read first line to get session header\n\t\t\tconst content = readFileSync(file, \"utf8\");\n\t\t\tconst firstLine = content.split(\"\\n\")[0];\n\t\t\tif (!firstLine?.trim()) continue;\n\n\t\t\tconst header = JSON.parse(firstLine);\n\t\t\tif (header.type !== \"session\" || !header.cwd) continue;\n\n\t\t\tconst cwd: string = header.cwd;\n\n\t\t\t// Compute the correct session directory (same encoding as session-manager.ts)\n\t\t\tconst safePath = `--${cwd.replace(/^[/\\\\]/, \"\").replace(/[/\\\\:]/g, \"-\")}--`;\n\t\t\tconst correctDir = join(agentDir, \"sessions\", safePath);\n\n\t\t\t// Create directory if needed\n\t\t\tif (!existsSync(correctDir)) {\n\t\t\t\tmkdirSync(correctDir, { recursive: true });\n\t\t\t}\n\n\t\t\t// Move the file\n\t\t\tconst fileName = getMigratedSessionFileName(file);\n\t\t\tif (!fileName) continue;\n\t\t\tconst newPath = join(correctDir, fileName);\n\n\t\t\tif (existsSync(newPath)) continue; // Skip if target exists\n\n\t\t\trenameSync(file, newPath);\n\t\t} catch {\n\t\t\t// Skip files that can't be migrated\n\t\t}\n\t}\n}\n\n/**\n * Migrate commands/ to prompts/ if needed.\n * Works for both regular directories and symlinks.\n */\nfunction migrateCommandsToPrompts(baseDir: string, label: string): boolean {\n\tconst commandsDir = join(baseDir, \"commands\");\n\tconst promptsDir = join(baseDir, \"prompts\");\n\n\tif (existsSync(commandsDir) && !existsSync(promptsDir)) {\n\t\ttry {\n\t\t\trenameSync(commandsDir, promptsDir);\n\t\t\tconsole.log(chalk.green(`Migrated ${label} commands/ → prompts/`));\n\t\t\treturn true;\n\t\t} catch (err) {\n\t\t\tconsole.log(\n\t\t\t\tchalk.yellow(\n\t\t\t\t\t`Warning: Could not migrate ${label} commands/ to prompts/: ${err instanceof Error ? err.message : err}`,\n\t\t\t\t),\n\t\t\t);\n\t\t}\n\t}\n\treturn false;\n}\n\nfunction migrateKeybindingsConfigFile(): void {\n\tconst configPath = join(getAgentDir(), \"keybindings.json\");\n\tif (!existsSync(configPath)) return;\n\n\ttry {\n\t\tconst parsed = JSON.parse(readFileSync(configPath, \"utf-8\")) as unknown;\n\t\tif (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) {\n\t\t\treturn;\n\t\t}\n\t\tconst { config, migrated } = migrateKeybindingsConfig(parsed as Record<string, unknown>);\n\t\tif (!migrated) return;\n\t\twriteFileSync(configPath, `${JSON.stringify(config, null, 2)}\\n`, \"utf-8\");\n\t} catch {\n\t\t// Ignore malformed files during migration\n\t}\n}\n\n/**\n * Move fd/rg binaries from tools/ to bin/ if they exist.\n */\nfunction migrateToolsToBin(): void {\n\tconst agentDir = getAgentDir();\n\tconst toolsDir = join(agentDir, \"tools\");\n\tconst binDir = getBinDir();\n\n\tif (!existsSync(toolsDir)) return;\n\n\tconst binaries = [\"fd\", \"rg\", \"fd.exe\", \"rg.exe\"];\n\tlet movedAny = false;\n\n\tfor (const bin of binaries) {\n\t\tconst oldPath = join(toolsDir, bin);\n\t\tconst newPath = join(binDir, bin);\n\n\t\tif (existsSync(oldPath)) {\n\t\t\tif (!existsSync(binDir)) {\n\t\t\t\tmkdirSync(binDir, { recursive: true });\n\t\t\t}\n\t\t\tif (!existsSync(newPath)) {\n\t\t\t\ttry {\n\t\t\t\t\trenameSync(oldPath, newPath);\n\t\t\t\t\tmovedAny = true;\n\t\t\t\t} catch {\n\t\t\t\t\t// Ignore errors\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// Target exists, just delete the old one\n\t\t\t\ttry {\n\t\t\t\t\trmSync?.(oldPath, { force: true });\n\t\t\t\t} catch {\n\t\t\t\t\t// Ignore\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tif (movedAny) {\n\t\tconsole.log(chalk.green(`Migrated managed binaries tools/ → bin/`));\n\t}\n}\n\n/**\n * Root-level machine-managed trust state is relocated into `state/`. If both layouts exist, valid\n * entries are merged under the canonical file's lock and canonical decisions win conflicts.\n */\nconst MAX_SESSION_NAMESPACES_TO_PRUNE = 10_000;\nconst MAX_LEGACY_DIRECTORY_ENTRIES_TO_MIGRATE = 10_000;\nconst MAX_MIGRATION_CONFLICT_SUFFIXES = 1_000;\n\ntype MigratedTrustFile = Record<string, boolean | null>;\n\nfunction readMigratedTrustFile(path: string): MigratedTrustFile | undefined {\n\ttry {\n\t\tconst parsed = JSON.parse(readFileSync(path, \"utf-8\")) as unknown;\n\t\tif (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) return undefined;\n\t\tconst trust: MigratedTrustFile = {};\n\t\tfor (const [key, value] of Object.entries(parsed)) {\n\t\t\tif (value !== true && value !== false && value !== null) return undefined;\n\t\t\ttrust[key] = value;\n\t\t}\n\t\treturn trust;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nfunction migrateTrustState(agentDir: string): void {\n\tconst oldPath = join(agentDir, \"trust.json\");\n\tif (!existsSync(oldPath)) return;\n\tconst newPath = stateFile(agentDir, \"trust.json\");\n\tif (!existsSync(newPath)) {\n\t\tmkdirSync(dirname(newPath), { recursive: true });\n\t\trenameSync(oldPath, newPath);\n\t\treturn;\n\t}\n\n\twithFileLockSync(newPath, () => {\n\t\tconst legacy = readMigratedTrustFile(oldPath);\n\t\tconst canonical = readMigratedTrustFile(newPath);\n\t\tif (!legacy || !canonical) return;\n\t\tconst merged = { ...legacy, ...canonical };\n\t\tconst sorted = Object.fromEntries(Object.entries(merged).sort(([left], [right]) => left.localeCompare(right)));\n\t\twriteFileAtomicSync(newPath, `${JSON.stringify(sorted, null, 2)}\\n`);\n\t\tunlinkSync(oldPath);\n\t});\n}\n\nfunction migrationConflictPath(agentDir: string, legacyName: string, entryName: string): string | undefined {\n\tconst conflictDir = stateFile(agentDir, \"migration-conflicts\", legacyName);\n\tfor (let suffix = 0; suffix < MAX_MIGRATION_CONFLICT_SUFFIXES; suffix++) {\n\t\tconst name = suffix === 0 ? entryName : `${entryName}.legacy-${suffix}`;\n\t\tconst candidate = join(conflictDir, name);\n\t\tif (!existsSync(candidate)) return candidate;\n\t}\n\treturn undefined;\n}\n\n/**\n * Relocate one known legacy root without traversing its contents. A whole-root rename is O(1);\n * partial migrations scan a bounded number of top-level entries and preserve collisions under\n * state/migration-conflicts instead of overwriting either copy.\n */\nfunction migrateLegacyAgentDirectory(agentDir: string, legacyName: string, canonicalDir: string): void {\n\tconst legacyDir = join(agentDir, legacyName);\n\tif (!existsSync(legacyDir)) return;\n\tconst legacyStats = lstatSync(legacyDir);\n\tif (!legacyStats.isDirectory() || legacyStats.isSymbolicLink()) return;\n\n\tif (!existsSync(canonicalDir)) {\n\t\tmkdirSync(dirname(canonicalDir), { recursive: true });\n\t\trenameSync(legacyDir, canonicalDir);\n\t\treturn;\n\t}\n\n\tconst canonicalStats = lstatSync(canonicalDir);\n\tif (!canonicalStats.isDirectory() || canonicalStats.isSymbolicLink()) return;\n\tconst entries = readdirSync(legacyDir).slice(0, MAX_LEGACY_DIRECTORY_ENTRIES_TO_MIGRATE);\n\tfor (const entry of entries) {\n\t\tconst source = join(legacyDir, entry);\n\t\tlet target = join(canonicalDir, entry);\n\t\tif (existsSync(target)) {\n\t\t\ttarget = migrationConflictPath(agentDir, legacyName, entry) ?? \"\";\n\t\t\tif (!target) continue;\n\t\t\tmkdirSync(dirname(target), { recursive: true });\n\t\t}\n\t\ttry {\n\t\t\trenameSync(source, target);\n\t\t} catch {}\n\t}\n\n\ttry {\n\t\trmdirSync(legacyDir);\n\t} catch {}\n}\n\nfunction migrateLegacyAgentFile(agentDir: string, legacyName: string, canonicalPath: string): void {\n\tconst legacyPath = join(agentDir, legacyName);\n\tif (!existsSync(legacyPath)) return;\n\tconst legacyStats = lstatSync(legacyPath);\n\tif (!legacyStats.isFile() || legacyStats.isSymbolicLink()) return;\n\tlet target = canonicalPath;\n\tif (existsSync(target)) {\n\t\ttarget = migrationConflictPath(agentDir, \"root-files\", legacyName.replaceAll(\":\", \".\")) ?? \"\";\n\t\tif (!target) return;\n\t}\n\tmkdirSync(dirname(target), { recursive: true });\n\ttry {\n\t\trenameSync(legacyPath, target);\n\t} catch (renameError) {\n\t\t// Windows cannot rename an NTFS alternate data stream into a regular file. Preserve the\n\t\t// bytes first, then remove only the named stream; never move or rewrite the owning auth file.\n\t\twriteFileSync(target, readFileSync(legacyPath), { flag: \"wx\" });\n\t\ttry {\n\t\t\tunlinkSync(legacyPath);\n\t\t} catch {\n\t\t\ttry {\n\t\t\t\tunlinkSync(target);\n\t\t\t} catch {}\n\t\t\tthrow renameError;\n\t\t}\n\t}\n}\n\n/** Remove only empty real per-project session directories; transcript files are never retention-pruned. */\nexport function pruneEmptySessionNamespaces(agentDir: string): string[] {\n\tconst root = sessionsDir(agentDir);\n\tlet candidates: string[];\n\ttry {\n\t\tcandidates = readdirSync(root, { withFileTypes: true })\n\t\t\t.slice(0, MAX_SESSION_NAMESPACES_TO_PRUNE)\n\t\t\t.filter((entry) => entry.isDirectory() && !entry.isSymbolicLink())\n\t\t\t.map((entry) => join(root, entry.name));\n\t} catch {\n\t\treturn [];\n\t}\n\n\tconst removed: string[] = [];\n\tfor (const candidate of candidates) {\n\t\ttry {\n\t\t\tconst stats = lstatSync(candidate);\n\t\t\tif (!stats.isDirectory() || stats.isSymbolicLink() || readdirSync(candidate).length > 0) continue;\n\t\t\trmdirSync(candidate);\n\t\t\tremoved.push(candidate);\n\t\t} catch {}\n\t}\n\treturn removed;\n}\n\n/**\n * Consolidate known machine-managed layout generations. Each migration is independently guarded:\n * startup never fails because cleanup is unavailable, and unknown files/resources remain untouched.\n */\nexport function migrateAgentDirLayout(agentDir: string): void {\n\ttry {\n\t\tmigrateTrustState(agentDir);\n\t} catch {\n\t\t// Best-effort: startup must not fail because one straggler could not be relocated.\n\t}\n\ttry {\n\t\tmigrateLegacyContextStores(agentDir);\n\t\tpruneContextStores(agentDir);\n\t} catch {}\n\ttry {\n\t\tmigrateLegacyAgentDirectory(agentDir, \"backups\", configBackupsDir(agentDir));\n\t} catch {}\n\ttry {\n\t\tmigrateLegacyAgentDirectory(agentDir, \"resource-profiles\", directoryProfilesDir(agentDir));\n\t} catch {}\n\ttry {\n\t\tmigrateLegacyAgentDirectory(agentDir, \"auto-learn\", stateFile(agentDir, \"legacy-layout\", \"auto-learn\"));\n\t} catch {}\n\ttry {\n\t\tmigrateLegacyAgentDirectory(agentDir, \"tmp\", stateFile(agentDir, \"legacy-layout\", \"tmp\"));\n\t} catch {}\n\ttry {\n\t\tmigrateLegacyAgentFile(\n\t\t\tagentDir,\n\t\t\t\"auth.json:Zone.Identifier\",\n\t\t\tstateFile(agentDir, \"legacy-layout\", \"sidecars\", \"auth.json.Zone.Identifier\"),\n\t\t);\n\t} catch {}\n\tpruneEmptySessionNamespaces(agentDir);\n}\n\n/**\n * Check for deprecated hooks/ and tools/ directories.\n * Note: tools/ may contain fd/rg binaries extracted by pi, so only warn if it has other files.\n */\nfunction checkDeprecatedExtensionDirs(baseDir: string, label: string): string[] {\n\tconst hooksDir = join(baseDir, \"hooks\");\n\tconst toolsDir = join(baseDir, \"tools\");\n\tconst warnings: string[] = [];\n\n\tif (existsSync(hooksDir)) {\n\t\twarnings.push(`${label} hooks/ directory found. Hooks have been renamed to extensions.`);\n\t}\n\n\tif (existsSync(toolsDir)) {\n\t\t// Check if tools/ contains anything other than fd/rg (which are auto-extracted binaries)\n\t\ttry {\n\t\t\tconst entries = readdirSync(toolsDir);\n\t\t\tconst customTools = entries.filter((e) => {\n\t\t\t\tconst lower = e.toLowerCase();\n\t\t\t\treturn (\n\t\t\t\t\tlower !== \"fd\" && lower !== \"rg\" && lower !== \"fd.exe\" && lower !== \"rg.exe\" && !e.startsWith(\".\") // Ignore .DS_Store and other hidden files\n\t\t\t\t);\n\t\t\t});\n\t\t\tif (customTools.length > 0) {\n\t\t\t\twarnings.push(\n\t\t\t\t\t`${label} tools/ directory contains custom tools. Custom tools have been merged into extensions.`,\n\t\t\t\t);\n\t\t\t}\n\t\t} catch {\n\t\t\t// Ignore read errors\n\t\t}\n\t}\n\n\treturn warnings;\n}\n\n/**\n * Run extension system migrations (commands→prompts) and collect warnings about deprecated directories.\n */\nfunction migrateExtensionSystem(cwd: string): string[] {\n\tconst agentDir = getAgentDir();\n\tconst projectDir = join(cwd, CONFIG_DIR_NAME);\n\n\t// Migrate commands/ to prompts/\n\tmigrateCommandsToPrompts(agentDir, \"Global\");\n\tmigrateCommandsToPrompts(projectDir, \"Project\");\n\n\t// Check for deprecated directories\n\tconst warnings = [\n\t\t...checkDeprecatedExtensionDirs(agentDir, \"Global\"),\n\t\t...checkDeprecatedExtensionDirs(projectDir, \"Project\"),\n\t];\n\n\treturn warnings;\n}\n\n/**\n * Print deprecation warnings and wait for keypress.\n */\nexport async function showDeprecationWarnings(warnings: string[]): Promise<void> {\n\tif (warnings.length === 0) return;\n\n\tfor (const warning of warnings) {\n\t\tconsole.log(chalk.yellow(`Warning: ${warning}`));\n\t}\n\tconsole.log(chalk.yellow(`\\nMove your extensions to the extensions/ directory.`));\n\tconsole.log(chalk.yellow(`Migration guide: ${MIGRATION_GUIDE_URL}`));\n\tconsole.log(chalk.yellow(`Documentation: ${EXTENSIONS_DOC_URL}`));\n\tif (!process.stdin.isTTY || !process.stdout.isTTY) {\n\t\tconsole.log();\n\t\treturn;\n\t}\n\tconsole.log(chalk.dim(`\\nPress any key to continue...`));\n\n\tawait new Promise<void>((resolve) => {\n\t\tlet settled = false;\n\t\tconst finish = () => {\n\t\t\tif (settled) return;\n\t\t\tsettled = true;\n\t\t\tprocess.stdin.removeListener(\"data\", finish);\n\t\t\tprocess.stdin.removeListener(\"end\", finish);\n\t\t\tprocess.stdin.removeListener(\"error\", finish);\n\t\t\tprocess.stdin.setRawMode?.(false);\n\t\t\tprocess.stdin.pause();\n\t\t\tresolve();\n\t\t};\n\t\tprocess.stdin.setRawMode?.(true);\n\t\tprocess.stdin.resume();\n\t\tprocess.stdin.once(\"data\", finish);\n\t\tprocess.stdin.once(\"end\", finish);\n\t\tprocess.stdin.once(\"error\", finish);\n\t});\n\tconsole.log();\n}\n\n/**\n * Run all migrations. Called once on startup.\n *\n * @returns Object with migration results and deprecation warnings\n */\nexport function runMigrations(cwd: string): {\n\tmigratedAuthProviders: string[];\n\tdeprecationWarnings: string[];\n} {\n\tmigrateAgentDirLayout(getAgentDir());\n\tconst migratedAuthProviders = migrateAuthToAuthJson();\n\tmigrateExplicitEnvVarConfigValues();\n\tmigrateSessionsFromAgentRoot();\n\tmigrateToolsToBin();\n\tmigrateKeybindingsConfigFile();\n\tconst deprecationWarnings = migrateExtensionSystem(cwd);\n\treturn { migratedAuthProviders, deprecationWarnings };\n}\n"]}
@@ -10,6 +10,7 @@
10
10
  */
11
11
  import type { ImageContent } from "@caupulican/pi-ai";
12
12
  import type { EditorComponent, TUI } from "@caupulican/pi-tui";
13
+ import type { SessionImageStore } from "../../core/session-image-store.ts";
13
14
  export type UserInputSubmission = {
14
15
  text: string;
15
16
  images?: ImageContent[];
@@ -21,10 +22,15 @@ export type PendingClipboardImage = {
21
22
  export interface ClipboardQueueHost {
22
23
  pendingClipboardImages: PendingClipboardImage[];
23
24
  clipboardImageCounter: number;
25
+ readonly clipboardImageStore?: Pick<SessionImageStore, "resolveReferences">;
24
26
  }
25
27
  export interface ClipboardInputHost extends ClipboardQueueHost {
26
- readonly editor: Pick<EditorComponent, "insertTextAtCursor">;
28
+ readonly editor: Pick<EditorComponent, "handleInput" | "insertTextAtCursor">;
27
29
  readonly ui: Pick<TUI, "requestRender">;
30
+ readonly autoResizeImages: boolean;
31
+ readonly blockImages: boolean;
32
+ readonly blockImagesReason?: string;
33
+ readonly imageStore?: Pick<SessionImageStore, "write">;
28
34
  showStatus(message: string): void;
29
35
  showWarning(message: string): void;
30
36
  }
@@ -1 +1 @@
1
- {"version":3,"file":"clipboard-input.d.ts","source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cesContent":["/**\n * Clipboard-image paste and user-input assembly extracted from interactive-mode.\n *\n * `handleClipboardImagePaste` reads an image off the clipboard, labels it, and\n * queues it for the next submission; `takeClipboardImagesForText` drains the\n * queued images whose labels survive in the submitted text; and\n * `buildUserInputSubmission` pairs the text with those images. They mutate the\n * pending-image queue/counter through a `ClipboardInputHost` seam;\n * interactive-mode keeps thin wrappers.\n */\n\nimport type { ImageContent } from \"@caupulican/pi-ai\";\nimport type { EditorComponent, TUI } from \"@caupulican/pi-tui\";\nimport { readClipboardImage } from \"../../utils/clipboard-image.ts\";\n\nexport type UserInputSubmission = {\n\ttext: string;\n\timages?: ImageContent[];\n};\n\nexport type PendingClipboardImage = {\n\tlabel: string;\n\tcontent: ImageContent;\n};\n\nexport interface ClipboardQueueHost {\n\tpendingClipboardImages: PendingClipboardImage[];\n\tclipboardImageCounter: number;\n}\n\nexport interface ClipboardInputHost extends ClipboardQueueHost {\n\treadonly editor: Pick<EditorComponent, \"insertTextAtCursor\">;\n\treadonly ui: Pick<TUI, \"requestRender\">;\n\tshowStatus(message: string): void;\n\tshowWarning(message: string): void;\n}\n\nexport interface BuildSubmissionHost {\n\ttakeClipboardImagesForText(text: string): ImageContent[] | undefined;\n}\n\nexport async function handleClipboardImagePaste(host: ClipboardInputHost): Promise<void> {\n\ttry {\n\t\tconst image = await readClipboardImage();\n\t\tif (!image) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst label = nextClipboardImageLabel(host);\n\t\tconst mimeType = image.mimeType.split(\";\")[0]?.trim().toLowerCase() || image.mimeType;\n\t\thost.pendingClipboardImages.push({\n\t\t\tlabel,\n\t\t\tcontent: {\n\t\t\t\ttype: \"image\",\n\t\t\t\tdata: Buffer.from(image.bytes).toString(\"base64\"),\n\t\t\t\tmimeType,\n\t\t\t},\n\t\t});\n\n\t\thost.editor.insertTextAtCursor?.(`${label} `);\n\t\thost.showStatus(`Attached clipboard image ${label} (${mimeType})`);\n\t\thost.ui.requestRender();\n\t} catch (error: unknown) {\n\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\thost.showWarning(`Failed to paste image: ${message}`);\n\t}\n}\n\nfunction nextClipboardImageLabel(host: ClipboardQueueHost): string {\n\tif (host.pendingClipboardImages.length === 0) {\n\t\thost.clipboardImageCounter = 0;\n\t}\n\thost.clipboardImageCounter += 1;\n\treturn `[Image #${host.clipboardImageCounter}]`;\n}\n\nexport function takeClipboardImagesForText(host: ClipboardQueueHost, text: string): ImageContent[] | undefined {\n\tif (host.pendingClipboardImages.length === 0) {\n\t\treturn undefined;\n\t}\n\n\tconst images = host.pendingClipboardImages\n\t\t.filter((image) => text.includes(image.label))\n\t\t.map((image) => image.content);\n\thost.pendingClipboardImages = [];\n\thost.clipboardImageCounter = 0;\n\treturn images.length > 0 ? images : undefined;\n}\n\nexport function buildUserInputSubmission(host: BuildSubmissionHost, text: string): UserInputSubmission {\n\tconst images = host.takeClipboardImagesForText(text);\n\treturn images ? { text, images } : { text };\n}\n"]}
1
+ {"version":3,"file":"clipboard-input.d.ts","sourceRoot":"","sources":["../../../src/modes/interactive/clipboard-input.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAEH,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AACtD,OAAO,KAAK,EAAE,eAAe,EAAE,GAAG,EAAE,MAAM,oBAAoB,CAAC;AAC/D,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,mCAAmC,CAAC;AAK3E,MAAM,MAAM,mBAAmB,GAAG;IACjC,IAAI,EAAE,MAAM,CAAC;IACb,MAAM,CAAC,EAAE,YAAY,EAAE,CAAC;CACxB,CAAC;AAEF,MAAM,MAAM,qBAAqB,GAAG;IACnC,KAAK,EAAE,MAAM,CAAC;IACd,OAAO,EAAE,YAAY,CAAC;CACtB,CAAC;AAEF,MAAM,WAAW,kBAAkB;IAClC,sBAAsB,EAAE,qBAAqB,EAAE,CAAC;IAChD,qBAAqB,EAAE,MAAM,CAAC;IAC9B,QAAQ,CAAC,mBAAmB,CAAC,EAAE,IAAI,CAAC,iBAAiB,EAAE,mBAAmB,CAAC,CAAC;CAC5E;AAED,MAAM,WAAW,kBAAmB,SAAQ,kBAAkB;IAC7D,QAAQ,CAAC,MAAM,EAAE,IAAI,CAAC,eAAe,EAAE,aAAa,GAAG,oBAAoB,CAAC,CAAC;IAC7E,QAAQ,CAAC,EAAE,EAAE,IAAI,CAAC,GAAG,EAAE,eAAe,CAAC,CAAC;IACxC,QAAQ,CAAC,gBAAgB,EAAE,OAAO,CAAC;IACnC,QAAQ,CAAC,WAAW,EAAE,OAAO,CAAC;IAC9B,QAAQ,CAAC,iBAAiB,CAAC,EAAE,MAAM,CAAC;IACpC,QAAQ,CAAC,UAAU,CAAC,EAAE,IAAI,CAAC,iBAAiB,EAAE,OAAO,CAAC,CAAC;IACvD,UAAU,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI,CAAC;IAClC,WAAW,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI,CAAC;CACnC;AAED,MAAM,WAAW,mBAAmB;IACnC,0BAA0B,CAAC,IAAI,EAAE,MAAM,GAAG,YAAY,EAAE,GAAG,SAAS,CAAC;CACrE;AAED,wBAAsB,yBAAyB,CAAC,IAAI,EAAE,kBAAkB,GAAG,OAAO,CAAC,IAAI,CAAC,CAwDvF;AAUD,wBAAgB,0BAA0B,CAAC,IAAI,EAAE,kBAAkB,EAAE,IAAI,EAAE,MAAM,GAAG,YAAY,EAAE,GAAG,SAAS,CAe7G;AAED,wBAAgB,wBAAwB,CAAC,IAAI,EAAE,mBAAmB,EAAE,IAAI,EAAE,MAAM,GAAG,mBAAmB,CAGrG","sourcesContent":["/**\n * Clipboard-image paste and user-input assembly extracted from interactive-mode.\n *\n * `handleClipboardImagePaste` reads an image off the clipboard, labels it, and\n * queues it for the next submission; `takeClipboardImagesForText` drains the\n * queued images whose labels survive in the submitted text; and\n * `buildUserInputSubmission` pairs the text with those images. They mutate the\n * pending-image queue/counter through a `ClipboardInputHost` seam;\n * interactive-mode keeps thin wrappers.\n */\n\nimport type { ImageContent } from \"@caupulican/pi-ai\";\nimport type { EditorComponent, TUI } from \"@caupulican/pi-tui\";\nimport type { SessionImageStore } from \"../../core/session-image-store.ts\";\nimport { readClipboardText } from \"../../utils/clipboard.ts\";\nimport { readClipboardImage } from \"../../utils/clipboard-image.ts\";\nimport { formatDimensionNote, resizeImage } from \"../../utils/image-resize.ts\";\n\nexport type UserInputSubmission = {\n\ttext: string;\n\timages?: ImageContent[];\n};\n\nexport type PendingClipboardImage = {\n\tlabel: string;\n\tcontent: ImageContent;\n};\n\nexport interface ClipboardQueueHost {\n\tpendingClipboardImages: PendingClipboardImage[];\n\tclipboardImageCounter: number;\n\treadonly clipboardImageStore?: Pick<SessionImageStore, \"resolveReferences\">;\n}\n\nexport interface ClipboardInputHost extends ClipboardQueueHost {\n\treadonly editor: Pick<EditorComponent, \"handleInput\" | \"insertTextAtCursor\">;\n\treadonly ui: Pick<TUI, \"requestRender\">;\n\treadonly autoResizeImages: boolean;\n\treadonly blockImages: boolean;\n\treadonly blockImagesReason?: string;\n\treadonly imageStore?: Pick<SessionImageStore, \"write\">;\n\tshowStatus(message: string): void;\n\tshowWarning(message: string): void;\n}\n\nexport interface BuildSubmissionHost {\n\ttakeClipboardImagesForText(text: string): ImageContent[] | undefined;\n}\n\nexport async function handleClipboardImagePaste(host: ClipboardInputHost): Promise<void> {\n\ttry {\n\t\tconst image = await readClipboardImage();\n\t\tif (!image) {\n\t\t\tconst text = await readClipboardText();\n\t\t\tif (text) {\n\t\t\t\thost.editor.handleInput(`\\x1b[200~${text}\\x1b[201~`);\n\t\t\t\thost.ui.requestRender();\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tif (host.blockImages) {\n\t\t\thost.showWarning(host.blockImagesReason ?? \"Image paste is blocked by images.blockImages.\");\n\t\t\treturn;\n\t\t}\n\n\t\tlet bytes = image.bytes;\n\t\tlet mimeType = image.mimeType.split(\";\")[0]?.trim().toLowerCase() || image.mimeType;\n\t\tlet dimensionNote: string | undefined;\n\t\tif (host.autoResizeImages) {\n\t\t\tconst resized = await resizeImage(bytes, mimeType);\n\t\t\tif (!resized) {\n\t\t\t\thost.showWarning(\"Clipboard image could not be resized below the inline image limit.\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tbytes = Buffer.from(resized.data, \"base64\");\n\t\t\tmimeType = resized.mimeType;\n\t\t\tdimensionNote = formatDimensionNote(resized);\n\t\t}\n\n\t\tlet storedSequence: number | undefined;\n\t\ttry {\n\t\t\tstoredSequence = host.imageStore?.write(bytes, mimeType).sequence;\n\t\t} catch (error: unknown) {\n\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\thost.showWarning(`Image attached but could not be stored: ${message}`);\n\t\t}\n\t\tconst label = storedSequence === undefined ? nextClipboardImageLabel(host) : `[Image #${storedSequence}]`;\n\t\tif (storedSequence !== undefined) host.clipboardImageCounter = storedSequence;\n\t\thost.pendingClipboardImages.push({\n\t\t\tlabel,\n\t\t\tcontent: {\n\t\t\t\ttype: \"image\",\n\t\t\t\tdata: Buffer.from(bytes).toString(\"base64\"),\n\t\t\t\tmimeType,\n\t\t\t},\n\t\t});\n\n\t\thost.editor.insertTextAtCursor?.(`${label}${dimensionNote ? ` ${dimensionNote}` : \"\"} `);\n\t\tconst sizeKiB = Math.max(1, Math.ceil(bytes.byteLength / 1024));\n\t\thost.showStatus(`Attached ${label} · ${mimeType.slice(\"image/\".length).toUpperCase()} · ${sizeKiB} KiB`);\n\t\thost.ui.requestRender();\n\t} catch (error: unknown) {\n\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\thost.showWarning(`Failed to paste image: ${message}`);\n\t}\n}\n\nfunction nextClipboardImageLabel(host: ClipboardQueueHost): string {\n\tif (host.pendingClipboardImages.length === 0) {\n\t\thost.clipboardImageCounter = 0;\n\t}\n\thost.clipboardImageCounter += 1;\n\treturn `[Image #${host.clipboardImageCounter}]`;\n}\n\nexport function takeClipboardImagesForText(host: ClipboardQueueHost, text: string): ImageContent[] | undefined {\n\tif (host.pendingClipboardImages.length === 0 && !host.clipboardImageStore) {\n\t\treturn undefined;\n\t}\n\n\tconst images = host.pendingClipboardImages\n\t\t.filter((image) => text.includes(image.label))\n\t\t.map((image) => image.content);\n\tfor (const stored of host.clipboardImageStore?.resolveReferences(text) ?? []) {\n\t\tif (!images.some((image) => image.mimeType === stored.mimeType && image.data === stored.data))\n\t\t\timages.push(stored);\n\t}\n\thost.pendingClipboardImages = [];\n\thost.clipboardImageCounter = 0;\n\treturn images.length > 0 ? images : undefined;\n}\n\nexport function buildUserInputSubmission(host: BuildSubmissionHost, text: string): UserInputSubmission {\n\tconst images = host.takeClipboardImagesForText(text);\n\treturn images ? { text, images } : { text };\n}\n"]}
@@ -8,25 +8,59 @@
8
8
  * pending-image queue/counter through a `ClipboardInputHost` seam;
9
9
  * interactive-mode keeps thin wrappers.
10
10
  */
11
+ import { readClipboardText } from "../../utils/clipboard.js";
11
12
  import { readClipboardImage } from "../../utils/clipboard-image.js";
13
+ import { formatDimensionNote, resizeImage } from "../../utils/image-resize.js";
12
14
  export async function handleClipboardImagePaste(host) {
13
15
  try {
14
16
  const image = await readClipboardImage();
15
17
  if (!image) {
18
+ const text = await readClipboardText();
19
+ if (text) {
20
+ host.editor.handleInput(`\x1b[200~${text}\x1b[201~`);
21
+ host.ui.requestRender();
22
+ }
16
23
  return;
17
24
  }
18
- const label = nextClipboardImageLabel(host);
19
- const mimeType = image.mimeType.split(";")[0]?.trim().toLowerCase() || image.mimeType;
25
+ if (host.blockImages) {
26
+ host.showWarning(host.blockImagesReason ?? "Image paste is blocked by images.blockImages.");
27
+ return;
28
+ }
29
+ let bytes = image.bytes;
30
+ let mimeType = image.mimeType.split(";")[0]?.trim().toLowerCase() || image.mimeType;
31
+ let dimensionNote;
32
+ if (host.autoResizeImages) {
33
+ const resized = await resizeImage(bytes, mimeType);
34
+ if (!resized) {
35
+ host.showWarning("Clipboard image could not be resized below the inline image limit.");
36
+ return;
37
+ }
38
+ bytes = Buffer.from(resized.data, "base64");
39
+ mimeType = resized.mimeType;
40
+ dimensionNote = formatDimensionNote(resized);
41
+ }
42
+ let storedSequence;
43
+ try {
44
+ storedSequence = host.imageStore?.write(bytes, mimeType).sequence;
45
+ }
46
+ catch (error) {
47
+ const message = error instanceof Error ? error.message : String(error);
48
+ host.showWarning(`Image attached but could not be stored: ${message}`);
49
+ }
50
+ const label = storedSequence === undefined ? nextClipboardImageLabel(host) : `[Image #${storedSequence}]`;
51
+ if (storedSequence !== undefined)
52
+ host.clipboardImageCounter = storedSequence;
20
53
  host.pendingClipboardImages.push({
21
54
  label,
22
55
  content: {
23
56
  type: "image",
24
- data: Buffer.from(image.bytes).toString("base64"),
57
+ data: Buffer.from(bytes).toString("base64"),
25
58
  mimeType,
26
59
  },
27
60
  });
28
- host.editor.insertTextAtCursor?.(`${label} `);
29
- host.showStatus(`Attached clipboard image ${label} (${mimeType})`);
61
+ host.editor.insertTextAtCursor?.(`${label}${dimensionNote ? ` ${dimensionNote}` : ""} `);
62
+ const sizeKiB = Math.max(1, Math.ceil(bytes.byteLength / 1024));
63
+ host.showStatus(`Attached ${label} · ${mimeType.slice("image/".length).toUpperCase()} · ${sizeKiB} KiB`);
30
64
  host.ui.requestRender();
31
65
  }
32
66
  catch (error) {
@@ -42,12 +76,16 @@ function nextClipboardImageLabel(host) {
42
76
  return `[Image #${host.clipboardImageCounter}]`;
43
77
  }
44
78
  export function takeClipboardImagesForText(host, text) {
45
- if (host.pendingClipboardImages.length === 0) {
79
+ if (host.pendingClipboardImages.length === 0 && !host.clipboardImageStore) {
46
80
  return undefined;
47
81
  }
48
82
  const images = host.pendingClipboardImages
49
83
  .filter((image) => text.includes(image.label))
50
84
  .map((image) => image.content);
85
+ for (const stored of host.clipboardImageStore?.resolveReferences(text) ?? []) {
86
+ if (!images.some((image) => image.mimeType === stored.mimeType && image.data === stored.data))
87
+ images.push(stored);
88
+ }
51
89
  host.pendingClipboardImages = [];
52
90
  host.clipboardImageCounter = 0;
53
91
  return images.length > 0 ? images : undefined;
@@ -1 +1 @@
1
- {"version":3,"file":"clipboard-input.js","sourceRoot":"","sources":["../../../src/modes/interactive/clipboard-input.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAIH,OAAO,EAAE,kBAAkB,EAAE,MAAM,gCAAgC,CAAC;AA4BpE,MAAM,CAAC,KAAK,UAAU,yBAAyB,CAAC,IAAwB,EAAiB;IACxF,IAAI,CAAC;QACJ,MAAM,KAAK,GAAG,MAAM,kBAAkB,EAAE,CAAC;QACzC,IAAI,CAAC,KAAK,EAAE,CAAC;YACZ,OAAO;QACR,CAAC;QAED,MAAM,KAAK,GAAG,uBAAuB,CAAC,IAAI,CAAC,CAAC;QAC5C,MAAM,QAAQ,GAAG,KAAK,CAAC,QAAQ,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,CAAC,WAAW,EAAE,IAAI,KAAK,CAAC,QAAQ,CAAC;QACtF,IAAI,CAAC,sBAAsB,CAAC,IAAI,CAAC;YAChC,KAAK;YACL,OAAO,EAAE;gBACR,IAAI,EAAE,OAAO;gBACb,IAAI,EAAE,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,QAAQ,CAAC,QAAQ,CAAC;gBACjD,QAAQ;aACR;SACD,CAAC,CAAC;QAEH,IAAI,CAAC,MAAM,CAAC,kBAAkB,EAAE,CAAC,GAAG,KAAK,GAAG,CAAC,CAAC;QAC9C,IAAI,CAAC,UAAU,CAAC,4BAA4B,KAAK,KAAK,QAAQ,GAAG,CAAC,CAAC;QACnE,IAAI,CAAC,EAAE,CAAC,aAAa,EAAE,CAAC;IACzB,CAAC;IAAC,OAAO,KAAc,EAAE,CAAC;QACzB,MAAM,OAAO,GAAG,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;QAC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interactive-mode.\n *\n * `handleClipboardImagePaste` reads an image off the clipboard, labels it, and\n * queues it for the next submission; `takeClipboardImagesForText` drains the\n * queued images whose labels survive in the submitted text; and\n * `buildUserInputSubmission` pairs the text with those images. They mutate the\n * pending-image queue/counter through a `ClipboardInputHost` seam;\n * interactive-mode keeps thin wrappers.\n */\n\nimport type { ImageContent } from \"@caupulican/pi-ai\";\nimport type { EditorComponent, TUI } from \"@caupulican/pi-tui\";\nimport { readClipboardImage } from \"../../utils/clipboard-image.ts\";\n\nexport type UserInputSubmission = {\n\ttext: string;\n\timages?: ImageContent[];\n};\n\nexport type PendingClipboardImage = {\n\tlabel: string;\n\tcontent: ImageContent;\n};\n\nexport interface ClipboardQueueHost {\n\tpendingClipboardImages: PendingClipboardImage[];\n\tclipboardImageCounter: number;\n}\n\nexport interface ClipboardInputHost extends ClipboardQueueHost {\n\treadonly editor: Pick<EditorComponent, \"insertTextAtCursor\">;\n\treadonly ui: Pick<TUI, \"requestRender\">;\n\tshowStatus(message: string): void;\n\tshowWarning(message: string): void;\n}\n\nexport interface BuildSubmissionHost {\n\ttakeClipboardImagesForText(text: string): ImageContent[] | undefined;\n}\n\nexport async function handleClipboardImagePaste(host: ClipboardInputHost): Promise<void> {\n\ttry {\n\t\tconst image = await readClipboardImage();\n\t\tif (!image) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst label = nextClipboardImageLabel(host);\n\t\tconst mimeType = image.mimeType.split(\";\")[0]?.trim().toLowerCase() || image.mimeType;\n\t\thost.pendingClipboardImages.push({\n\t\t\tlabel,\n\t\t\tcontent: {\n\t\t\t\ttype: \"image\",\n\t\t\t\tdata: Buffer.from(image.bytes).toString(\"base64\"),\n\t\t\t\tmimeType,\n\t\t\t},\n\t\t});\n\n\t\thost.editor.insertTextAtCursor?.(`${label} `);\n\t\thost.showStatus(`Attached clipboard image ${label} (${mimeType})`);\n\t\thost.ui.requestRender();\n\t} catch (error: unknown) {\n\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\thost.showWarning(`Failed to paste image: ${message}`);\n\t}\n}\n\nfunction nextClipboardImageLabel(host: ClipboardQueueHost): string {\n\tif (host.pendingClipboardImages.length === 0) {\n\t\thost.clipboardImageCounter = 0;\n\t}\n\thost.clipboardImageCounter += 1;\n\treturn `[Image #${host.clipboardImageCounter}]`;\n}\n\nexport function takeClipboardImagesForText(host: ClipboardQueueHost, text: string): ImageContent[] | undefined {\n\tif (host.pendingClipboardImages.length === 0) {\n\t\treturn undefined;\n\t}\n\n\tconst images = host.pendingClipboardImages\n\t\t.filter((image) => text.includes(image.label))\n\t\t.map((image) => image.content);\n\thost.pendingClipboardImages = [];\n\thost.clipboardImageCounter = 0;\n\treturn images.length > 0 ? images : undefined;\n}\n\nexport function buildUserInputSubmission(host: BuildSubmissionHost, text: string): UserInputSubmission {\n\tconst images = host.takeClipboardImagesForText(text);\n\treturn images ? { text, images } : { text };\n}\n"]}
1
+ {"version":3,"file":"clipboard-input.js","sourceRoot":"","sources":["../../../src/modes/interactive/clipboard-input.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAKH,OAAO,EAAE,iBAAiB,EAAE,MAAM,0BAA0B,CAAC;AAC7D,OAAO,EAAE,kBAAkB,EAAE,MAAM,gCAAgC,CAAC;AACpE,OAAO,EAAE,mBAAmB,EAAE,WAAW,EAAE,MAAM,6BAA6B,CAAC;AAiC/E,MAAM,CAAC,KAAK,UAAU,yBAAyB,CAAC,IAAwB,EAAiB;IACxF,IAAI,CAAC;QACJ,MAAM,KAAK,GAAG,MAAM,kBAAkB,EAAE,CAAC;QACzC,IAAI,CAAC,KAAK,EAAE,CAAC;YACZ,MAAM,IAAI,GAAG,MAAM,iBAAiB,EAAE,CAAC;YACvC,IAAI,IAAI,EAAE,CAAC;gBACV,IAAI,CAAC,MAAM,CAAC,WAAW,CAAC,YAAY,IAAI,WAAW,CAAC,CAAC;gBACrD,IAAI,CAAC,EAAE,CAAC,aAAa,EAAE,CAAC;YACzB,CAAC;YACD,OAAO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IAAI,CAAC,CAAC;IACrD,OAAO,MAAM,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,CAAC;AAAA,CAC5C","sourcesContent":["/**\n * Clipboard-image paste and user-input assembly extracted from interactive-mode.\n *\n * `handleClipboardImagePaste` reads an image off the clipboard, labels it, and\n * queues it for the next submission; `takeClipboardImagesForText` drains the\n * queued images whose labels survive in the submitted text; and\n * `buildUserInputSubmission` pairs the text with those images. They mutate the\n * pending-image queue/counter through a `ClipboardInputHost` seam;\n * interactive-mode keeps thin wrappers.\n */\n\nimport type { ImageContent } from \"@caupulican/pi-ai\";\nimport type { EditorComponent, TUI } from \"@caupulican/pi-tui\";\nimport type { SessionImageStore } from \"../../core/session-image-store.ts\";\nimport { readClipboardText } from \"../../utils/clipboard.ts\";\nimport { readClipboardImage } from \"../../utils/clipboard-image.ts\";\nimport { formatDimensionNote, resizeImage } from \"../../utils/image-resize.ts\";\n\nexport type UserInputSubmission = {\n\ttext: string;\n\timages?: ImageContent[];\n};\n\nexport type PendingClipboardImage = {\n\tlabel: string;\n\tcontent: ImageContent;\n};\n\nexport interface ClipboardQueueHost {\n\tpendingClipboardImages: PendingClipboardImage[];\n\tclipboardImageCounter: number;\n\treadonly clipboardImageStore?: Pick<SessionImageStore, \"resolveReferences\">;\n}\n\nexport interface ClipboardInputHost extends ClipboardQueueHost {\n\treadonly editor: Pick<EditorComponent, \"handleInput\" | \"insertTextAtCursor\">;\n\treadonly ui: Pick<TUI, \"requestRender\">;\n\treadonly autoResizeImages: boolean;\n\treadonly blockImages: boolean;\n\treadonly blockImagesReason?: string;\n\treadonly imageStore?: Pick<SessionImageStore, \"write\">;\n\tshowStatus(message: string): void;\n\tshowWarning(message: string): void;\n}\n\nexport interface BuildSubmissionHost {\n\ttakeClipboardImagesForText(text: string): ImageContent[] | undefined;\n}\n\nexport async function handleClipboardImagePaste(host: ClipboardInputHost): Promise<void> {\n\ttry {\n\t\tconst image = await readClipboardImage();\n\t\tif (!image) {\n\t\t\tconst text = await readClipboardText();\n\t\t\tif (text) {\n\t\t\t\thost.editor.handleInput(`\\x1b[200~${text}\\x1b[201~`);\n\t\t\t\thost.ui.requestRender();\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tif (host.blockImages) {\n\t\t\thost.showWarning(host.blockImagesReason ?? \"Image paste is blocked by images.blockImages.\");\n\t\t\treturn;\n\t\t}\n\n\t\tlet bytes = image.bytes;\n\t\tlet mimeType = image.mimeType.split(\";\")[0]?.trim().toLowerCase() || image.mimeType;\n\t\tlet dimensionNote: string | undefined;\n\t\tif (host.autoResizeImages) {\n\t\t\tconst resized = await resizeImage(bytes, mimeType);\n\t\t\tif (!resized) {\n\t\t\t\thost.showWarning(\"Clipboard image could not be resized below the inline image limit.\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tbytes = Buffer.from(resized.data, \"base64\");\n\t\t\tmimeType = resized.mimeType;\n\t\t\tdimensionNote = formatDimensionNote(resized);\n\t\t}\n\n\t\tlet storedSequence: number | undefined;\n\t\ttry {\n\t\t\tstoredSequence = host.imageStore?.write(bytes, mimeType).sequence;\n\t\t} catch (error: unknown) {\n\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\thost.showWarning(`Image attached but could not be stored: ${message}`);\n\t\t}\n\t\tconst label = storedSequence === undefined ? nextClipboardImageLabel(host) : `[Image #${storedSequence}]`;\n\t\tif (storedSequence !== undefined) host.clipboardImageCounter = storedSequence;\n\t\thost.pendingClipboardImages.push({\n\t\t\tlabel,\n\t\t\tcontent: {\n\t\t\t\ttype: \"image\",\n\t\t\t\tdata: Buffer.from(bytes).toString(\"base64\"),\n\t\t\t\tmimeType,\n\t\t\t},\n\t\t});\n\n\t\thost.editor.insertTextAtCursor?.(`${label}${dimensionNote ? ` ${dimensionNote}` : \"\"} `);\n\t\tconst sizeKiB = Math.max(1, Math.ceil(bytes.byteLength / 1024));\n\t\thost.showStatus(`Attached ${label} · ${mimeType.slice(\"image/\".length).toUpperCase()} · ${sizeKiB} KiB`);\n\t\thost.ui.requestRender();\n\t} catch (error: unknown) {\n\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\thost.showWarning(`Failed to paste image: ${message}`);\n\t}\n}\n\nfunction nextClipboardImageLabel(host: ClipboardQueueHost): string {\n\tif (host.pendingClipboardImages.length === 0) {\n\t\thost.clipboardImageCounter = 0;\n\t}\n\thost.clipboardImageCounter += 1;\n\treturn `[Image #${host.clipboardImageCounter}]`;\n}\n\nexport function takeClipboardImagesForText(host: ClipboardQueueHost, text: string): ImageContent[] | undefined {\n\tif (host.pendingClipboardImages.length === 0 && !host.clipboardImageStore) {\n\t\treturn undefined;\n\t}\n\n\tconst images = host.pendingClipboardImages\n\t\t.filter((image) => text.includes(image.label))\n\t\t.map((image) => image.content);\n\tfor (const stored of host.clipboardImageStore?.resolveReferences(text) ?? []) {\n\t\tif (!images.some((image) => image.mimeType === stored.mimeType && image.data === stored.data))\n\t\t\timages.push(stored);\n\t}\n\thost.pendingClipboardImages = [];\n\thost.clipboardImageCounter = 0;\n\treturn images.length > 0 ? images : undefined;\n}\n\nexport function buildUserInputSubmission(host: BuildSubmissionHost, text: string): UserInputSubmission {\n\tconst images = host.takeClipboardImagesForText(text);\n\treturn images ? { text, images } : { text };\n}\n"]}