pi-agent-ide 0.5.1 → 0.6.1

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 (454) hide show
  1. package/CHANGELOG.md +71 -0
  2. package/README.md +82 -50
  3. package/assets/social-preview.png +0 -0
  4. package/dist/{chunk-LY6U5EAD.js → chunk-2527OQ4Y.js} +1 -1
  5. package/dist/chunk-4KUFOHWP.js +2 -0
  6. package/dist/chunk-4LDOV7QS.js +28 -0
  7. package/dist/chunk-5JELU6RV.js +7 -0
  8. package/dist/chunk-FA6BKC5Y.js +1 -0
  9. package/dist/chunk-FEDVTZJG.js +1 -0
  10. package/dist/chunk-I6Y3W4X6.js +27 -0
  11. package/dist/chunk-K5G4FDXD.js +1 -0
  12. package/dist/chunk-M5IVSCR2.js +1 -0
  13. package/dist/chunk-MPT3R4BL.js +0 -0
  14. package/dist/chunk-PZFOOHY2.js +15 -0
  15. package/dist/chunk-S6QRG3TQ.js +1 -0
  16. package/dist/chunk-T7I2VX3J.js +1 -0
  17. package/dist/chunk-VCTK4JSN.js +3 -0
  18. package/dist/chunk-W7CASEO3.js +1 -0
  19. package/dist/chunk-YEQOQMU7.js +5 -0
  20. package/dist/chunk-YT42LKFV.js +16 -0
  21. package/dist/entry-10.js +1 -1
  22. package/dist/entry-11.js +1 -1
  23. package/dist/entry-12.js +1 -1
  24. package/dist/entry-13.js +1 -1
  25. package/dist/entry-14.js +1 -1
  26. package/dist/entry-15.js +1 -1
  27. package/dist/entry-16.js +1 -0
  28. package/dist/entry-17.js +1 -1
  29. package/dist/entry-19.js +1 -1
  30. package/dist/entry-20.js +1 -1
  31. package/dist/entry-21.js +1 -1
  32. package/dist/entry-22.js +1 -2
  33. package/dist/entry-23.js +1 -1
  34. package/dist/entry-24.js +1 -1
  35. package/dist/entry-25.js +2 -1
  36. package/dist/entry-26.js +1 -1
  37. package/dist/entry-27.js +2 -12
  38. package/dist/entry-28.js +1 -1
  39. package/dist/entry-29.js +1 -1
  40. package/dist/entry-30.js +1 -1
  41. package/dist/entry-31.js +12 -1
  42. package/dist/entry-32.js +1 -4
  43. package/dist/entry-33.js +1 -9
  44. package/dist/entry-34.js +1 -1
  45. package/dist/entry-35.js +1 -1
  46. package/dist/entry-36.js +4 -1
  47. package/dist/entry-37.js +9 -1
  48. package/dist/entry-38.js +1 -1
  49. package/dist/entry-39.js +1 -1
  50. package/dist/entry-40.js +1 -1
  51. package/dist/entry-41.js +1 -18
  52. package/dist/entry-42.js +1 -1
  53. package/dist/entry-43.js +1 -1
  54. package/dist/entry-44.js +1 -1
  55. package/dist/entry-45.js +17 -1
  56. package/dist/entry-46.js +1 -7
  57. package/dist/entry-47.js +1 -11
  58. package/dist/entry-48.js +1 -1
  59. package/dist/entry-49.js +1 -1
  60. package/dist/entry-50.js +6 -1
  61. package/dist/entry-51.js +11 -1
  62. package/dist/entry-52.js +1 -1
  63. package/dist/entry-53.js +1 -1
  64. package/dist/entry-54.js +1 -1
  65. package/dist/entry-55.js +1 -1
  66. package/dist/entry-56.js +1 -0
  67. package/dist/entry-57.js +1 -1
  68. package/dist/entry-58.js +1 -0
  69. package/dist/entry-59.js +1 -1
  70. package/dist/entry-60.js +0 -1
  71. package/dist/entry-61.js +1 -1
  72. package/dist/entry-62.js +0 -1
  73. package/dist/entry-63.js +1 -1
  74. package/dist/entry-64.js +1 -1
  75. package/dist/entry-65.js +1 -0
  76. package/dist/entry-66.js +1 -1
  77. package/dist/entry-67.js +1 -0
  78. package/dist/entry-68.js +1 -1
  79. package/dist/entry-69.js +0 -1
  80. package/dist/entry-70.js +1 -1
  81. package/dist/entry-71.js +0 -203
  82. package/dist/entry-72.js +1 -30
  83. package/dist/entry-73.js +1 -2
  84. package/dist/entry-74.js +1 -1
  85. package/dist/entry-75.js +315 -1
  86. package/dist/entry-76.js +30 -3
  87. package/dist/entry-77.js +2 -3
  88. package/dist/entry-78.js +1 -1
  89. package/dist/entry-79.js +1 -1
  90. package/dist/entry-80.js +3 -1
  91. package/dist/entry-81.js +3 -0
  92. package/dist/entry-82.js +1 -0
  93. package/dist/entry-83.js +1 -0
  94. package/dist/entry-84.js +1 -0
  95. package/dist/entry-9.js +1 -1
  96. package/dist/pi-agent-ide.js +3 -3
  97. package/docs/agent-guides/apply.md +333 -0
  98. package/docs/agent-guides/debugger.md +5 -0
  99. package/docs/agent-guides/diagnostics.md +5 -0
  100. package/docs/agent-guides/editing.md +44 -0
  101. package/docs/agent-guides/git-changes.md +5 -0
  102. package/docs/agent-guides/json-reading.md +41 -0
  103. package/docs/agent-guides/read-resources.md +44 -0
  104. package/docs/agent-guides/search-code.md +29 -0
  105. package/docs/agent-guides/terminal.md +7 -0
  106. package/docs/agent-guides/vision.md +5 -0
  107. package/docs/configuration.md +9 -15
  108. package/docs/research/apply-read-latency.md +219 -0
  109. package/docs/tools.md +12 -0
  110. package/node_modules/pi-agent-doctor/package.json +6 -6
  111. package/node_modules/pi-agent-doctor/runtime/entry-22.js +1 -0
  112. package/node_modules/pi-agent-doctor/runtime/entry-23.js +1 -0
  113. package/node_modules/pi-agent-documentation/package.json +15 -0
  114. package/node_modules/pi-agent-documentation/runtime/entry-24.js +1 -0
  115. package/node_modules/pi-agent-documentation/src/index.ts +69 -0
  116. package/node_modules/pi-agent-filesystem/index.ts +0 -4
  117. package/node_modules/pi-agent-filesystem/package.json +7 -7
  118. package/node_modules/pi-agent-filesystem-image/package.json +4 -4
  119. package/node_modules/pi-agent-filesystem-image/runtime/entry-26.js +2 -0
  120. package/node_modules/pi-agent-filesystem-jq/index.ts +134 -0
  121. package/node_modules/pi-agent-filesystem-jq/package.json +23 -0
  122. package/node_modules/pi-agent-filesystem-jq/src/jq.ts +107 -0
  123. package/node_modules/pi-agent-filesystem-pdf/package.json +4 -4
  124. package/node_modules/pi-agent-filesystem-pdf/runtime/entry-28.js +2 -0
  125. package/node_modules/pi-agent-filesystem-text/package.json +4 -4
  126. package/node_modules/pi-agent-ide-ast/package.json +12 -11
  127. package/node_modules/pi-agent-ide-ast/runtime/entry-30.js +1 -0
  128. package/node_modules/pi-agent-ide-ast/src/search-resolver.ts +8 -6
  129. package/node_modules/pi-agent-ide-changes/index.ts +8 -0
  130. package/node_modules/pi-agent-ide-changes/package.json +9 -8
  131. package/node_modules/pi-agent-ide-changes/runtime/entry-32.js +1 -0
  132. package/node_modules/pi-agent-ide-formatter/package.json +4 -4
  133. package/node_modules/pi-agent-ide-formatter/runtime/entry-34.js +2 -0
  134. package/node_modules/pi-agent-ide-formatter/src/formatter.ts +1 -1
  135. package/node_modules/pi-agent-ide-languages/package.json +3 -3
  136. package/node_modules/pi-agent-ide-languages/runtime/entry-35.js +2 -0
  137. package/node_modules/pi-agent-ide-lint/index.ts +1 -1
  138. package/node_modules/pi-agent-ide-lint/package.json +8 -8
  139. package/node_modules/pi-agent-ide-lint/runtime/entry-36.js +2 -0
  140. package/node_modules/pi-agent-ide-lint/src/command-linter.ts +20 -2
  141. package/node_modules/pi-agent-ide-lsp/index.ts +0 -3
  142. package/node_modules/pi-agent-ide-lsp/package.json +10 -10
  143. package/node_modules/pi-agent-ide-lsp/runtime/entry-37.js +2 -0
  144. package/node_modules/pi-agent-image/package.json +3 -3
  145. package/node_modules/pi-agent-invariant/package.json +2 -2
  146. package/node_modules/pi-agent-pdf/package.json +3 -3
  147. package/node_modules/pi-agent-read/package.json +12 -11
  148. package/node_modules/pi-agent-read/runtime/entry-41.js +0 -1
  149. package/node_modules/pi-agent-read/runtime/entry-45.js +2 -0
  150. package/node_modules/pi-agent-read/src/api/read-parameters.ts +4 -4
  151. package/node_modules/pi-agent-read/src/core/extension.ts +16 -2
  152. package/node_modules/pi-agent-read/src/core/read-core.ts +4 -5
  153. package/node_modules/pi-agent-read/src/core/tools/read/read-renderer.ts +62 -8
  154. package/node_modules/pi-agent-read/src/core/tools/tool-read.ts +29 -17
  155. package/node_modules/pi-agent-resource/package.json +2 -2
  156. package/node_modules/pi-agent-resource/runtime/entry-46.js +1 -0
  157. package/node_modules/pi-agent-search/package.json +8 -7
  158. package/node_modules/pi-agent-search/runtime/entry-47.js +1 -0
  159. package/node_modules/pi-agent-search/src/core/extension.ts +29 -10
  160. package/node_modules/pi-agent-search-text/package.json +9 -9
  161. package/node_modules/pi-agent-search-text/runtime/entry-51.js +2 -0
  162. package/node_modules/pi-agent-search-text/runtime/entry-52.js +1 -0
  163. package/node_modules/pi-agent-text/package.json +3 -3
  164. package/node_modules/pi-agent-text-anchor-constant/package.json +4 -4
  165. package/node_modules/pi-agent-text-anchor-exact/index.ts +3 -3
  166. package/node_modules/pi-agent-text-anchor-exact/package.json +5 -5
  167. package/node_modules/pi-agent-text-anchor-exact/runtime/entry-56.js +2 -0
  168. package/node_modules/pi-agent-text-anchor-exact/src/config.ts +2 -2
  169. package/node_modules/pi-agent-text-anchor-line-hash/package.json +7 -7
  170. package/node_modules/pi-agent-text-anchor-line-hash/runtime/entry-58.js +2 -0
  171. package/node_modules/pi-agent-text-editor/index.ts +15 -0
  172. package/node_modules/pi-agent-text-editor/package.json +26 -25
  173. package/node_modules/pi-agent-text-editor/runtime/entry-71.js +0 -1
  174. package/node_modules/pi-agent-text-editor/runtime/entry-72.js +1 -0
  175. package/node_modules/pi-agent-text-editor/runtime/entry-73.js +1 -0
  176. package/node_modules/pi-agent-text-editor/runtime/entry-75.js +2 -0
  177. package/node_modules/pi-agent-text-editor/src/core/apply/execution.ts +131 -3
  178. package/node_modules/pi-agent-text-editor/src/core/apply/mixed-source.ts +1 -1
  179. package/node_modules/pi-agent-text-editor/src/core/apply/mutation-outcome.ts +14 -0
  180. package/node_modules/pi-agent-text-editor/src/core/apply/output.ts +36 -5
  181. package/node_modules/pi-agent-text-editor/src/core/apply/prompt.ts +5 -42
  182. package/node_modules/pi-agent-text-editor/src/core/apply/renderer.ts +50 -5
  183. package/node_modules/pi-agent-text-editor/src/core/apply/runtime.ts +187 -38
  184. package/node_modules/pi-agent-text-editor/src/core/apply/tool.ts +3 -8
  185. package/node_modules/pi-agent-text-editor/src/core/apply/transaction.ts +770 -237
  186. package/node_modules/pi-agent-text-editor/src/core/builtin-edit-filter.ts +1 -1
  187. package/node_modules/pi-agent-text-editor/src/core/diff-tool.ts +2 -2
  188. package/node_modules/pi-agent-text-editor/src/core/extension.ts +0 -11
  189. package/node_modules/pi-agent-text-editor/src/core/post-edit-scope.ts +5 -0
  190. package/node_modules/pi-agent-text-editor/src/core/text-editor-config.ts +4 -4
  191. package/node_modules/pi-agent-text-editor/src/core/text-editor-core.ts +9 -1
  192. package/node_modules/pi-agent-text-editor/src/core/text-mutation.ts +0 -2
  193. package/node_modules/pi-agent-text-editor/src/tools/text-tool-schema-properties.ts +53 -0
  194. package/node_modules/pi-agent-text-editor/src/tools/tool-text-copy.ts +11 -41
  195. package/node_modules/pi-agent-text-editor/src/tools/tool-text-delete.ts +8 -18
  196. package/node_modules/pi-agent-text-editor/src/tools/tool-text-move.ts +11 -41
  197. package/node_modules/pi-agent-text-editor/src/tools/tool-text-replace.ts +9 -19
  198. package/node_modules/pi-agent-text-editor-renderer/index.ts +17 -4
  199. package/node_modules/pi-agent-text-editor-renderer/package.json +6 -6
  200. package/node_modules/pi-agent-text-editor-renderer/src/mutation-panel.ts +23 -11
  201. package/node_modules/pi-agent-text-editor-renderer/src/renderer.ts +21 -16
  202. package/node_modules/pi-agent-text-editor-stale-anchor/package.json +5 -5
  203. package/node_modules/pi-agent-tool-call-interception/package.json +3 -3
  204. package/node_modules/pi-agent-tool-call-interception/runtime/entry-78.js +1 -0
  205. package/node_modules/pi-agent-tool-ui/package.json +2 -2
  206. package/node_modules/pi-agent-tool-ui/runtime/entry-79.js +1 -0
  207. package/node_modules/pi-agent-web/package.json +7 -7
  208. package/node_modules/pi-agent-web-html/package.json +3 -3
  209. package/node_modules/pi-agent-web-html/runtime/entry-81.js +2 -0
  210. package/node_modules/pi-agent-web-image/package.json +4 -4
  211. package/node_modules/pi-agent-web-image/runtime/entry-82.js +2 -0
  212. package/node_modules/pi-agent-web-pdf/package.json +4 -4
  213. package/node_modules/pi-agent-web-pdf/runtime/entry-83.js +2 -0
  214. package/node_modules/pi-agent-web-text/package.json +4 -4
  215. package/node_modules/pi-agent-web-text/runtime/entry-84.js +2 -0
  216. package/package.json +112 -43
  217. package/src/api/documentation.ts +2 -0
  218. package/src/api/path-identity.ts +15 -0
  219. package/src/composite/builtin-extensions.ts +14 -2
  220. package/src/composite/extensions-config.ts +6 -0
  221. package/src/composite/module-labels.ts +9 -0
  222. package/src/composite/module-settings-store.ts +3 -0
  223. package/src/composite/module-settings.ts +71 -17
  224. package/src/composite/preferences.ts +83 -3
  225. package/src/composite/presentation.ts +14 -0
  226. package/src/composite/presets.ts +57 -0
  227. package/src/composite/selection.ts +5 -1
  228. package/src/doctor/inventory.ts +7 -2
  229. package/src/documentation/extension.ts +295 -0
  230. package/src/documentation/registry.ts +98 -0
  231. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/index.ts +0 -4
  232. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/package.json +7 -7
  233. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-image/package.json +4 -4
  234. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-image/runtime/entry-26.js +2 -0
  235. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-jq/index.ts +134 -0
  236. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-jq/package.json +23 -0
  237. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-jq/runtime/entry-27.js +2 -0
  238. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-jq/src/jq.ts +107 -0
  239. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-pdf/package.json +4 -4
  240. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-pdf/runtime/entry-28.js +2 -0
  241. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-text/package.json +4 -4
  242. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-text/runtime/entry-29.js +2 -0
  243. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/runtime/entry-25.js +2 -0
  244. package/src/extensions/pi-agent-read/extensions/pi-agent-web/package.json +7 -7
  245. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-html/package.json +3 -3
  246. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-html/runtime/entry-81.js +2 -0
  247. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-image/package.json +4 -4
  248. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-image/runtime/entry-82.js +2 -0
  249. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-pdf/package.json +4 -4
  250. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-pdf/runtime/entry-83.js +2 -0
  251. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-text/package.json +4 -4
  252. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-text/runtime/entry-84.js +2 -0
  253. package/src/extensions/pi-agent-read/extensions/pi-agent-web/runtime/entry-80.js +2 -0
  254. package/src/extensions/pi-agent-read/package.json +12 -11
  255. package/src/extensions/pi-agent-read/runtime/entry-41.js +0 -1
  256. package/src/extensions/pi-agent-read/runtime/entry-42.js +1 -0
  257. package/src/extensions/pi-agent-read/runtime/entry-45.js +2 -0
  258. package/src/extensions/pi-agent-read/src/api/read-parameters.ts +4 -4
  259. package/src/extensions/pi-agent-read/src/core/extension.ts +16 -2
  260. package/src/extensions/pi-agent-read/src/core/read-core.ts +4 -5
  261. package/src/extensions/pi-agent-read/src/core/tools/read/read-renderer.ts +62 -8
  262. package/src/extensions/pi-agent-read/src/core/tools/tool-read.ts +29 -17
  263. package/src/extensions/pi-agent-search/package.json +8 -7
  264. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/package.json +9 -9
  265. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/runtime/entry-51.js +2 -0
  266. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/runtime/entry-52.js +1 -0
  267. package/src/extensions/pi-agent-search/runtime/entry-47.js +1 -0
  268. package/src/extensions/pi-agent-search/runtime/entry-48.js +1 -0
  269. package/src/extensions/pi-agent-search/runtime/entry-49.js +1 -0
  270. package/src/extensions/pi-agent-search/runtime/entry-50.js +2 -0
  271. package/src/extensions/pi-agent-search/src/core/extension.ts +29 -10
  272. package/src/extensions/pi-agent-text-editor/index.ts +15 -0
  273. package/src/extensions/pi-agent-text-editor/package.json +26 -25
  274. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-constant/package.json +4 -4
  275. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-exact/index.ts +3 -3
  276. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-exact/package.json +5 -5
  277. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-exact/runtime/entry-55.js +1 -0
  278. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-exact/runtime/entry-56.js +2 -0
  279. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-exact/src/config.ts +2 -2
  280. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-line-hash/package.json +7 -7
  281. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-line-hash/runtime/entry-57.js +1 -0
  282. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-line-hash/runtime/entry-58.js +2 -0
  283. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/index.ts +17 -4
  284. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/package.json +6 -6
  285. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/src/mutation-panel.ts +23 -11
  286. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/src/renderer.ts +21 -16
  287. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-stale-anchor/package.json +5 -5
  288. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-stale-anchor/runtime/entry-77.js +2 -0
  289. package/src/extensions/pi-agent-text-editor/runtime/entry-71.js +0 -1
  290. package/src/extensions/pi-agent-text-editor/runtime/entry-72.js +1 -0
  291. package/src/extensions/pi-agent-text-editor/runtime/entry-73.js +1 -0
  292. package/src/extensions/pi-agent-text-editor/runtime/entry-74.js +1 -0
  293. package/src/extensions/pi-agent-text-editor/runtime/entry-75.js +2 -0
  294. package/src/extensions/pi-agent-text-editor/src/core/apply/execution.ts +131 -3
  295. package/src/extensions/pi-agent-text-editor/src/core/apply/mixed-source.ts +1 -1
  296. package/src/extensions/pi-agent-text-editor/src/core/apply/mutation-outcome.ts +14 -0
  297. package/src/extensions/pi-agent-text-editor/src/core/apply/output.ts +36 -5
  298. package/src/extensions/pi-agent-text-editor/src/core/apply/prompt.ts +5 -42
  299. package/src/extensions/pi-agent-text-editor/src/core/apply/renderer.ts +50 -5
  300. package/src/extensions/pi-agent-text-editor/src/core/apply/runtime.ts +187 -38
  301. package/src/extensions/pi-agent-text-editor/src/core/apply/tool.ts +3 -8
  302. package/src/extensions/pi-agent-text-editor/src/core/apply/transaction.ts +770 -237
  303. package/src/extensions/pi-agent-text-editor/src/core/builtin-edit-filter.ts +1 -1
  304. package/src/extensions/pi-agent-text-editor/src/core/diff-tool.ts +2 -2
  305. package/src/extensions/pi-agent-text-editor/src/core/extension.ts +0 -11
  306. package/src/extensions/pi-agent-text-editor/src/core/post-edit-scope.ts +5 -0
  307. package/src/extensions/pi-agent-text-editor/src/core/text-editor-config.ts +4 -4
  308. package/src/extensions/pi-agent-text-editor/src/core/text-editor-core.ts +9 -1
  309. package/src/extensions/pi-agent-text-editor/src/core/text-mutation.ts +0 -2
  310. package/src/extensions/pi-agent-text-editor/src/tools/text-tool-schema-properties.ts +53 -0
  311. package/src/extensions/pi-agent-text-editor/src/tools/tool-text-copy.ts +11 -41
  312. package/src/extensions/pi-agent-text-editor/src/tools/tool-text-delete.ts +8 -18
  313. package/src/extensions/pi-agent-text-editor/src/tools/tool-text-move.ts +11 -41
  314. package/src/extensions/pi-agent-text-editor/src/tools/tool-text-replace.ts +9 -19
  315. package/src/pi-agent-ide.ts +21 -11
  316. package/src/plugins/pi-agent-ide-ast/package.json +12 -11
  317. package/src/plugins/pi-agent-ide-ast/runtime/entry-30.js +1 -0
  318. package/src/plugins/pi-agent-ide-ast/src/search-resolver.ts +8 -6
  319. package/src/plugins/pi-agent-ide-changes/index.ts +8 -0
  320. package/src/plugins/pi-agent-ide-changes/package.json +9 -8
  321. package/src/plugins/pi-agent-ide-changes/runtime/entry-32.js +1 -0
  322. package/src/plugins/pi-agent-ide-debugger/index.ts +13 -11
  323. package/src/plugins/pi-agent-ide-debugger/src/adapter-executables.ts +31 -0
  324. package/src/plugins/pi-agent-ide-debugger/src/breakpoint-view.ts +3 -1
  325. package/src/plugins/pi-agent-ide-debugger/src/catalog.ts +24 -23
  326. package/src/plugins/pi-agent-ide-debugger/src/dap-client.ts +5 -2
  327. package/src/plugins/pi-agent-ide-debugger/src/doctor-plugin.ts +55 -17
  328. package/src/plugins/pi-agent-ide-debugger/src/session-manager.ts +55 -22
  329. package/src/plugins/pi-agent-ide-diagnostics/src/extension.ts +9 -4
  330. package/src/plugins/pi-agent-ide-formatter/package.json +4 -4
  331. package/src/plugins/pi-agent-ide-formatter/runtime/entry-34.js +2 -0
  332. package/src/plugins/pi-agent-ide-formatter/src/formatter.ts +1 -1
  333. package/src/plugins/pi-agent-ide-languages/package.json +3 -3
  334. package/src/plugins/pi-agent-ide-languages/runtime/entry-35.js +2 -0
  335. package/src/plugins/pi-agent-ide-lint/index.ts +1 -1
  336. package/src/plugins/pi-agent-ide-lint/package.json +8 -8
  337. package/src/plugins/pi-agent-ide-lint/runtime/entry-36.js +2 -0
  338. package/src/plugins/pi-agent-ide-lint/src/command-linter.ts +20 -2
  339. package/src/plugins/pi-agent-ide-lsp/index.ts +0 -3
  340. package/src/plugins/pi-agent-ide-lsp/package.json +10 -10
  341. package/src/plugins/pi-agent-ide-lsp/runtime/entry-37.js +2 -0
  342. package/src/plugins/pi-agent-ide-processes/src/registry.ts +4 -0
  343. package/src/plugins/pi-agent-ide-processes/src/ui.ts +18 -9
  344. package/src/plugins/pi-agent-ide-terminal/index.ts +27 -2
  345. package/src/plugins/pi-agent-ide-terminal/src/process-provider.ts +1 -0
  346. package/src/plugins/pi-agent-ide-terminal/src/renderer.ts +27 -2
  347. package/src/plugins/pi-agent-ide-terminal/src/resources.ts +1 -4
  348. package/src/plugins/pi-agent-ide-terminal/src/search.ts +0 -3
  349. package/src/plugins/pi-agent-ide-terminal/src/session-manager.ts +1 -0
  350. package/src/plugins/pi-agent-ide-terminal/src/tools.ts +8 -5
  351. package/src/plugins/pi-agent-ide-terminal/src/types.ts +1 -0
  352. package/src/plugins/pi-agent-ide-vision/index.ts +234 -0
  353. package/src/plugins/pi-agent-ide-vision/src/vision.ts +530 -0
  354. package/src/plugins/pi-agent-ide-vision/src/windows-display-capture.ps1 +30 -0
  355. package/src/plugins/pi-agent-ide-vision/src/windows-window-capture.ps1 +33 -0
  356. package/dist/chunk-526E364R.js +0 -3
  357. package/dist/chunk-5PLV4HLG.js +0 -1
  358. package/dist/chunk-7ALCBKCW.js +0 -26
  359. package/dist/chunk-DQXPQOF7.js +0 -2
  360. package/dist/chunk-EJ5OACQM.js +0 -1
  361. package/dist/chunk-G725MARR.js +0 -16
  362. package/dist/chunk-HKXDP2FD.js +0 -7
  363. package/dist/chunk-IRECDTJG.js +0 -27
  364. package/dist/chunk-J4RTW44E.js +0 -1
  365. package/dist/chunk-NZYDMBM6.js +0 -1
  366. package/dist/chunk-WGGIQ7IJ.js +0 -1
  367. package/dist/entry-18.js +0 -1
  368. package/node_modules/pi-agent-doctor/runtime/entry-17.js +0 -1
  369. package/node_modules/pi-agent-doctor/runtime/entry-18.js +0 -1
  370. package/node_modules/pi-agent-filesystem/runtime/entry-22.js +0 -2
  371. package/node_modules/pi-agent-filesystem-image/runtime/entry-23.js +0 -2
  372. package/node_modules/pi-agent-filesystem-pdf/runtime/entry-24.js +0 -2
  373. package/node_modules/pi-agent-ide-ast/runtime/entry-26.js +0 -1
  374. package/node_modules/pi-agent-ide-changes/runtime/entry-28.js +0 -1
  375. package/node_modules/pi-agent-ide-formatter/runtime/entry-30.js +0 -2
  376. package/node_modules/pi-agent-ide-lint/runtime/entry-32.js +0 -2
  377. package/node_modules/pi-agent-image/runtime/entry-34.js +0 -1
  378. package/node_modules/pi-agent-invariant/runtime/entry-35.js +0 -1
  379. package/node_modules/pi-agent-pdf/runtime/entry-36.js +0 -1
  380. package/node_modules/pi-agent-read/runtime/entry-37.js +0 -1
  381. package/node_modules/pi-agent-search/runtime/entry-45.js +0 -1
  382. package/node_modules/pi-agent-search/runtime/entry-46.js +0 -2
  383. package/node_modules/pi-agent-search-text/runtime/entry-47.js +0 -2
  384. package/node_modules/pi-agent-text-anchor-exact/runtime/entry-51.js +0 -1
  385. package/node_modules/pi-agent-text-anchor-exact/runtime/entry-52.js +0 -2
  386. package/node_modules/pi-agent-text-editor/runtime/entry-56.js +0 -1
  387. package/node_modules/pi-agent-text-editor/runtime/entry-58.js +0 -1
  388. package/node_modules/pi-agent-text-editor-renderer/runtime/entry-72.js +0 -2
  389. package/node_modules/pi-agent-text-editor-renderer/src/config.ts +0 -73
  390. package/node_modules/pi-agent-text-editor-stale-anchor/runtime/entry-73.js +0 -2
  391. package/node_modules/pi-agent-tool-ui/runtime/entry-75.js +0 -1
  392. package/node_modules/pi-agent-web-image/runtime/entry-78.js +0 -2
  393. package/node_modules/pi-agent-web-pdf/runtime/entry-79.js +0 -2
  394. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-image/runtime/entry-23.js +0 -2
  395. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-pdf/runtime/entry-24.js +0 -2
  396. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-text/runtime/entry-25.js +0 -2
  397. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/runtime/entry-22.js +0 -2
  398. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-html/runtime/entry-77.js +0 -2
  399. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-image/runtime/entry-78.js +0 -2
  400. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-pdf/runtime/entry-79.js +0 -2
  401. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-text/runtime/entry-80.js +0 -2
  402. package/src/extensions/pi-agent-read/runtime/entry-37.js +0 -1
  403. package/src/extensions/pi-agent-read/runtime/entry-38.js +0 -1
  404. package/src/extensions/pi-agent-read/runtime/entry-39.js +0 -1
  405. package/src/extensions/pi-agent-read/runtime/entry-40.js +0 -1
  406. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/runtime/entry-47.js +0 -2
  407. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/runtime/entry-48.js +0 -1
  408. package/src/extensions/pi-agent-search/runtime/entry-45.js +0 -1
  409. package/src/extensions/pi-agent-search/runtime/entry-46.js +0 -2
  410. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-constant/runtime/entry-50.js +0 -2
  411. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-exact/runtime/entry-51.js +0 -1
  412. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-exact/runtime/entry-52.js +0 -2
  413. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-line-hash/runtime/entry-53.js +0 -1
  414. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/runtime/entry-72.js +0 -2
  415. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/src/config.ts +0 -73
  416. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-stale-anchor/runtime/entry-73.js +0 -2
  417. package/src/extensions/pi-agent-text-editor/runtime/entry-55.js +0 -1
  418. package/src/extensions/pi-agent-text-editor/runtime/entry-56.js +0 -1
  419. package/src/extensions/pi-agent-text-editor/runtime/entry-57.js +0 -1
  420. package/src/extensions/pi-agent-text-editor/runtime/entry-58.js +0 -1
  421. package/src/plugins/pi-agent-ide-ast/runtime/entry-26.js +0 -1
  422. package/src/plugins/pi-agent-ide-ast/runtime/entry-27.js +0 -2
  423. package/src/plugins/pi-agent-ide-changes/runtime/entry-28.js +0 -1
  424. package/src/plugins/pi-agent-ide-changes/runtime/entry-29.js +0 -2
  425. package/src/plugins/pi-agent-ide-formatter/runtime/entry-30.js +0 -2
  426. package/src/plugins/pi-agent-ide-lint/runtime/entry-32.js +0 -2
  427. /package/node_modules/{pi-agent-filesystem-text → pi-agent-filesystem}/runtime/entry-25.js +0 -0
  428. /package/node_modules/{pi-agent-ide-ast → pi-agent-filesystem-jq}/runtime/entry-27.js +0 -0
  429. /package/node_modules/{pi-agent-ide-changes → pi-agent-filesystem-text}/runtime/entry-29.js +0 -0
  430. /package/node_modules/{pi-agent-ide-languages → pi-agent-ide-ast}/runtime/entry-31.js +0 -0
  431. /package/node_modules/{pi-agent-ide-lsp → pi-agent-ide-changes}/runtime/entry-33.js +0 -0
  432. /package/node_modules/{pi-agent-read → pi-agent-image}/runtime/entry-38.js +0 -0
  433. /package/node_modules/{pi-agent-read → pi-agent-invariant}/runtime/entry-39.js +0 -0
  434. /package/node_modules/{pi-agent-read → pi-agent-pdf}/runtime/entry-40.js +0 -0
  435. /package/node_modules/{pi-agent-resource → pi-agent-read}/runtime/entry-42.js +0 -0
  436. /package/node_modules/{pi-agent-search → pi-agent-read}/runtime/entry-43.js +0 -0
  437. /package/node_modules/{pi-agent-search → pi-agent-read}/runtime/entry-44.js +0 -0
  438. /package/node_modules/{pi-agent-search-text → pi-agent-search}/runtime/entry-48.js +0 -0
  439. /package/node_modules/{pi-agent-text → pi-agent-search}/runtime/entry-49.js +0 -0
  440. /package/node_modules/{pi-agent-text-anchor-constant → pi-agent-search}/runtime/entry-50.js +0 -0
  441. /package/node_modules/{pi-agent-text-anchor-line-hash → pi-agent-text}/runtime/entry-53.js +0 -0
  442. /package/node_modules/{pi-agent-text-anchor-line-hash → pi-agent-text-anchor-constant}/runtime/entry-54.js +0 -0
  443. /package/node_modules/{pi-agent-text-editor → pi-agent-text-anchor-exact}/runtime/entry-55.js +0 -0
  444. /package/node_modules/{pi-agent-text-editor → pi-agent-text-anchor-line-hash}/runtime/entry-57.js +0 -0
  445. /package/node_modules/{pi-agent-tool-call-interception → pi-agent-text-editor}/runtime/entry-74.js +0 -0
  446. /package/node_modules/{pi-agent-web → pi-agent-text-editor-renderer}/runtime/entry-76.js +0 -0
  447. /package/node_modules/{pi-agent-web-html → pi-agent-text-editor-stale-anchor}/runtime/entry-77.js +0 -0
  448. /package/node_modules/{pi-agent-web-text → pi-agent-web}/runtime/entry-80.js +0 -0
  449. /package/src/extensions/{pi-agent-search → pi-agent-read}/runtime/entry-43.js +0 -0
  450. /package/src/extensions/{pi-agent-search → pi-agent-read}/runtime/entry-44.js +0 -0
  451. /package/src/extensions/pi-agent-text-editor/plugins/{pi-agent-text-anchor-line-hash → pi-agent-text-anchor-constant}/runtime/entry-54.js +0 -0
  452. /package/src/extensions/{pi-agent-read/extensions/pi-agent-web → pi-agent-text-editor/plugins/pi-agent-text-editor-renderer}/runtime/entry-76.js +0 -0
  453. /package/src/plugins/{pi-agent-ide-languages → pi-agent-ide-ast}/runtime/entry-31.js +0 -0
  454. /package/src/plugins/{pi-agent-ide-lsp → pi-agent-ide-changes}/runtime/entry-33.js +0 -0
@@ -1,9 +1,12 @@
1
1
  import { lstat, mkdir, readFile, rm, writeFile } from "node:fs/promises";
2
2
  import path from "node:path";
3
3
  import fs from "fs-extra";
4
+ import { requiredValue } from "pi-agent-invariant";
4
5
  import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
5
6
  import { applyTextChanges, type TextChange } from "#src/core/text-change-engine.js";
6
7
  import type { TextEditorCore } from "#src/core/text-editor-core.js";
8
+
9
+ import { forgetDeferredPostEdit } from "#src/core/post-edit-scope.js";
7
10
  import type {
8
11
  ScriptMutationFile,
9
12
  ScriptMutationOutcome,
@@ -14,176 +17,758 @@ export interface EditorSnapshot {
14
17
  readonly source: string;
15
18
  readonly content: string;
16
19
  }
17
-
18
20
  interface Selection {
19
21
  readonly document: string;
20
22
  readonly from: number;
21
23
  readonly to: number;
22
24
  readonly text: string;
25
+ readonly linewise?: boolean;
23
26
  }
24
-
25
27
  interface TextOperation {
26
28
  readonly kind: "replace";
27
29
  readonly selection: Selection;
28
30
  readonly text: string;
29
31
  }
30
-
32
+ type TextTransferOperation = {
33
+ readonly sources: readonly Selection[];
34
+ readonly destinations: readonly Selection[];
35
+ readonly text: string;
36
+ } & ({ readonly kind: "text-copy" } | { readonly kind: "text-move" });
37
+ interface WarningOperation {
38
+ readonly kind: "warning";
39
+ readonly document: string;
40
+ readonly query?: string;
41
+ readonly warning?: unknown;
42
+ }
31
43
  interface CreateOperation {
32
44
  readonly kind: "create";
33
45
  readonly path: string;
34
46
  readonly content: string;
35
47
  }
36
-
37
48
  interface FileOperation {
38
49
  readonly kind: "delete" | "copy" | "move";
39
50
  readonly path: string;
40
51
  readonly target?: string;
41
52
  readonly overwrite?: boolean;
42
53
  }
43
-
54
+ type Operation =
55
+ | TextOperation
56
+ | TextTransferOperation
57
+ | WarningOperation
58
+ | CreateOperation
59
+ | FileOperation;
44
60
  export interface EditorTransactionRequest {
45
61
  readonly snapshots: readonly EditorSnapshot[];
46
- readonly operations: readonly (TextOperation | CreateOperation | FileOperation)[];
62
+ readonly operations: readonly Operation[];
47
63
  }
48
-
49
- interface SavedPath {
64
+ /** Captured path state used to restore one failed operation. */
65
+ export interface SavedPath {
50
66
  readonly path: string;
51
67
  readonly existed: boolean;
52
68
  readonly bytes?: Uint8Array;
53
69
  }
70
+ export interface ApplyOperationOutcome {
71
+ readonly index: number;
72
+ readonly kind: Operation["kind"];
73
+ readonly status: "applied" | "warning" | "failed" | "unknown" | "blocked";
74
+ readonly effect: "applied" | "not-applied" | "unknown";
75
+ readonly resources: readonly string[];
76
+ readonly error?: { readonly code: string; readonly message: string };
77
+ readonly warning?: {
78
+ readonly code: string;
79
+ readonly message: string;
80
+ readonly presentation?: unknown;
81
+ };
82
+ }
83
+
84
+ export type TransactionEditor = Pick<
85
+ TextEditorCore,
86
+ "editTexts" | "postProcessFile" | "recordApplyUndo"
87
+ >;
54
88
 
55
- /** Commit one snapshot-guarded Apply transaction and restore touched paths after a write failure. */
89
+ /** Optional transaction execution dependencies for deterministic failure handling. */
90
+ export interface TransactionExecutionOptions {
91
+ /** Restore one captured path after an operation fails. */
92
+ readonly restorePath?: (state: SavedPath) => Promise<void>;
93
+ }
94
+
95
+ /** Commit staged operations independently and return every outcome in staging order. */
56
96
  export async function executeEditorTransaction(
57
- editor: TextEditorCore,
97
+ editor: TransactionEditor,
58
98
  input: unknown,
59
99
  signal: AbortSignal,
60
- context: ExtensionContext,
100
+ context: Pick<ExtensionContext, "cwd">,
101
+ options: TransactionExecutionOptions = {},
61
102
  ): Promise<ScriptMutationOutcome> {
62
103
  const request = parseRequest(input);
63
- if (request.operations.length === 0) throw invalid("apply() requires at least one staged change");
64
-
104
+ if (request.operations.length === 0) throw invalid("flush() requires at least one staged change");
65
105
  const snapshots = new Map(request.snapshots.map((snapshot) => [snapshot.id, snapshot]));
66
106
  if (snapshots.size !== request.snapshots.length) throw invalid("Duplicate editor snapshot id");
67
- const textChanges = new Map<string, TextChange[]>();
68
- const creates: CreateOperation[] = [];
69
- const fileOperations: FileOperation[] = [];
70
107
 
71
- for (const operation of request.operations) {
108
+ const accepted = new Map<string, TextChange[]>();
109
+ const unknown = new Set<string>();
110
+ const journal = new Map<string, SavedPath>();
111
+ const files: ScriptMutationFile[] = [];
112
+ const operations: ApplyOperationOutcome[] = [];
113
+ const cwd = context.cwd;
114
+ const batchedReplacements = new Set<number>();
115
+
116
+ for (const [index, operation] of request.operations.entries()) {
117
+ const resources = operationResources(operation, snapshots, cwd);
118
+ if (batchedReplacements.has(index)) continue;
119
+ if (operation.kind === "replace") {
120
+ const replacements: Array<{ index: number; operation: TextOperation }> = [];
121
+ for (
122
+ let candidateIndex = index;
123
+ candidateIndex < request.operations.length;
124
+ candidateIndex += 1
125
+ ) {
126
+ const candidate = request.operations[candidateIndex];
127
+ if (
128
+ candidate?.kind !== "replace" ||
129
+ candidate.selection.document !== operation.selection.document
130
+ )
131
+ break;
132
+ replacements.push({ index: candidateIndex, operation: candidate });
133
+ }
134
+ if (replacements.length > 1) {
135
+ for (const replacement of replacements) batchedReplacements.add(replacement.index);
136
+ const outcome = await executeReplacementBatch(
137
+ replacements,
138
+ snapshots,
139
+ accepted,
140
+ editor,
141
+ cwd,
142
+ signal,
143
+ options,
144
+ );
145
+ for (const state of outcome.saved)
146
+ if (!journal.has(state.path)) journal.set(state.path, state);
147
+ files.push(...outcome.files);
148
+ operations.push(...outcome.operations);
149
+ continue;
150
+ }
151
+ }
152
+ if (operation.kind === "warning") {
153
+ operations.push({
154
+ index,
155
+ kind: "warning",
156
+ status: "warning",
157
+ effect: "not-applied",
158
+ resources,
159
+ warning: warningDetails(operation),
160
+ });
161
+ continue;
162
+ }
163
+ if (resources.some((resource) => unknown.has(resource))) {
164
+ operations.push({
165
+ index,
166
+ kind: operation.kind,
167
+ status: "blocked",
168
+ effect: "unknown",
169
+ resources,
170
+ error: {
171
+ code: "DEPENDENCY_UNKNOWN",
172
+ message: "A prior operation left a required resource in an unknown state.",
173
+ },
174
+ });
175
+ continue;
176
+ }
72
177
  if (operation.kind === "replace") {
73
178
  const snapshot = snapshots.get(operation.selection.document);
74
- if (snapshot === undefined) throw invalid("Selection belongs to an unknown editor snapshot");
75
- const { from, to, text } = operation.selection;
179
+ const prior = snapshot === undefined ? [] : (accepted.get(snapshot.source) ?? []);
180
+ if (prior.some((change) => overlaps(change, operation.selection))) {
181
+ operations.push(
182
+ failed(
183
+ index,
184
+ operation,
185
+ resources,
186
+ invalid(`Overlapping selection in ${snapshot?.source ?? "unknown snapshot"}`),
187
+ ),
188
+ );
189
+ continue;
190
+ }
191
+ }
192
+
193
+ let saved: readonly SavedPath[] = [];
194
+ try {
195
+ await validateOperation(operation, snapshots, accepted, cwd);
196
+ saved = await Promise.all(resources.map(savePath));
197
+ const produced = await executeOperation(operation, snapshots, accepted, editor, cwd, signal);
198
+ for (const state of saved) if (!journal.has(state.path)) journal.set(state.path, state);
199
+ files.push(...produced);
200
+ operations.push({
201
+ index,
202
+ kind: operation.kind,
203
+ status: "applied",
204
+ effect: "applied",
205
+ resources,
206
+ });
207
+ } catch (error) {
208
+ const rollbackErrors = await rollback(saved, options.restorePath);
209
+ if (rollbackErrors.length > 0) {
210
+ for (const resource of resources) unknown.add(resource);
211
+ operations.push({
212
+ index,
213
+ kind: operation.kind,
214
+ status: "unknown",
215
+ effect: "unknown",
216
+ resources,
217
+ error: codedError(error, rollbackErrors),
218
+ });
219
+ } else operations.push(failed(index, operation, resources, error));
220
+ }
221
+ }
222
+
223
+ const successful = operations.some(({ effect }) => effect === "applied");
224
+ const transaction = successful ? await editor.recordApplyUndo([...journal.values()]) : undefined;
225
+ return {
226
+ operation: "apply",
227
+ ok: operations.length > 0 && operations.every(({ status }) => status === "applied"),
228
+ effect: unknown.size > 0 ? "unknown" : successful ? "applied" : "not-applied",
229
+ ...(transaction === undefined ? {} : { transaction }),
230
+ files,
231
+ completed: [
232
+ ...new Set(
233
+ operations
234
+ .filter(({ effect }) => effect === "applied")
235
+ .flatMap(({ resources }) => resources),
236
+ ),
237
+ ],
238
+ errors: operations.flatMap((item) =>
239
+ item.status === "warning" || item.error === undefined
240
+ ? []
241
+ : [{ source: item.resources.join(", "), ...item.error }],
242
+ ),
243
+ operations,
244
+ };
245
+ }
246
+
247
+ async function executeReplacementBatch(
248
+ replacements: readonly { readonly index: number; readonly operation: TextOperation }[],
249
+ snapshots: ReadonlyMap<string, EditorSnapshot>,
250
+ accepted: Map<string, TextChange[]>,
251
+ editor: TransactionEditor,
252
+ cwd: string,
253
+ signal: AbortSignal,
254
+ options: TransactionExecutionOptions,
255
+ ): Promise<{
256
+ readonly saved: readonly SavedPath[];
257
+ readonly files: readonly ScriptMutationFile[];
258
+ readonly operations: readonly ApplyOperationOutcome[];
259
+ }> {
260
+ const first = requiredValue(replacements[0]);
261
+ const snapshot = snapshots.get(first.operation.selection.document);
262
+ const resources = operationResources(first.operation, snapshots, cwd);
263
+ if (snapshot === undefined)
264
+ return {
265
+ saved: [],
266
+ files: [],
267
+ operations: replacements.map(({ index, operation }) =>
268
+ failed(
269
+ index,
270
+ operation,
271
+ resources,
272
+ invalid("Selection belongs to an unknown editor snapshot"),
273
+ ),
274
+ ),
275
+ };
276
+
277
+ const prior = accepted.get(snapshot.source) ?? [];
278
+ const additions: TextChange[] = [];
279
+ const operationResults = new Map<number, ApplyOperationOutcome>();
280
+ for (const { index, operation } of replacements) {
281
+ try {
282
+ validateSelection(operation, snapshot);
76
283
  if (
77
- !Number.isInteger(from) ||
78
- !Number.isInteger(to) ||
79
- from < 0 ||
80
- to < from ||
81
- to > snapshot.content.length
284
+ prior.some((change) => overlaps(change, operation.selection)) ||
285
+ additions.some((change) => overlaps(change, operation.selection))
82
286
  )
83
- throw invalid(`Selection ${from}-${to} is outside ${snapshot.source}`);
84
- if (snapshot.content.slice(from, to) !== text)
85
- throw invalid(`Selection text does not match ${snapshot.source}`);
86
- const changes = textChanges.get(snapshot.source) ?? [];
87
- changes.push({ from, to, insert: operation.text });
88
- textChanges.set(snapshot.source, changes);
89
- } else if (operation.kind === "create") creates.push(operation);
90
- else fileOperations.push(operation);
287
+ throw invalid(`Overlapping selection in ${snapshot.source}`);
288
+ additions.push({
289
+ from: operation.selection.from,
290
+ to: operation.selection.to,
291
+ insert: preserveLineEnding(operation.selection, operation.text),
292
+ });
293
+ } catch (error) {
294
+ operationResults.set(index, failed(index, operation, resources, error));
295
+ }
91
296
  }
297
+ if (additions.length === 0)
298
+ return {
299
+ saved: [],
300
+ files: [],
301
+ operations: replacements.map(({ index }) => requiredValue(operationResults.get(index))),
302
+ };
92
303
 
93
- validateTextChanges(textChanges);
94
- const cwd = context.cwd;
95
- const touched = touchedPaths(cwd, textChanges, creates, fileOperations);
96
- await preflight(touched, snapshots, textChanges, creates, fileOperations, cwd);
97
- const saved = await Promise.all([...touched].map(savePath));
98
- const files: ScriptMutationFile[] = [];
304
+ const before = applyTextChanges(snapshot.content, prior).content;
305
+ let current: string;
306
+ try {
307
+ current = await readFile(snapshot.source, "utf8");
308
+ if (current !== before) throw stale(snapshot.source);
309
+ } catch (error) {
310
+ for (const { index, operation } of replacements)
311
+ if (!operationResults.has(index))
312
+ operationResults.set(index, failed(index, operation, resources, error));
313
+ return {
314
+ saved: [],
315
+ files: [],
316
+ operations: replacements.map(({ index }) => requiredValue(operationResults.get(index))),
317
+ };
318
+ }
99
319
 
320
+ const saved = [await savePath(snapshot.source)];
321
+ const combined = [...prior, ...additions];
322
+ const applied = applyTextChanges(snapshot.content, combined);
100
323
  try {
101
- if (textChanges.size > 0 || creates.length > 0) {
102
- const createMap = new Map(
103
- creates.map((item) => [path.resolve(cwd, item.path), item.content]),
104
- );
105
- const sources = new Set([...textChanges.keys(), ...createMap.keys()]);
106
- const outcome = await editor.editTexts(
107
- [...sources].map((source) => ({
108
- source,
109
- read: true,
110
- ...(createMap.has(source) && { allowReadFailure: true }),
111
- })),
112
- { cwd, signal, intent: "edit" },
113
- (texts) => {
114
- for (const snapshot of snapshots.values()) {
115
- if (textChanges.has(snapshot.source) && texts.get(snapshot.source) !== snapshot.content)
116
- throw stale(snapshot.source);
117
- }
118
- const changes = new Map<string, readonly TextChange[]>();
119
- for (const source of sources) {
120
- const before = texts.get(source) ?? "";
121
- const planned = textChanges.get(source) ?? [
122
- { from: 0, to: 0, insert: createMap.get(source) ?? "" },
123
- ];
124
- changes.set(source, planned);
125
- const applied = applyTextChanges(before, planned, createMap.has(source));
126
- files.push({
127
- source,
128
- before: createMap.has(source) ? null : before,
129
- after: applied.content,
130
- action: createMap.has(source) ? "created" : "edited",
131
- changes: applied.changes.map((change, editIndex) => ({
132
- editIndex,
133
- fromA: change.fromBefore,
134
- toA: change.toBefore,
135
- fromB: change.fromAfter,
136
- toB: change.toAfter,
137
- removedText: change.removedText,
138
- insertedText: change.insertedText,
139
- })),
140
- formatting: { status: "not-reported" },
141
- });
142
- }
143
- return { changes, result: undefined };
324
+ await editOne(editor, snapshot.source, before, applied.content, cwd, signal, false);
325
+ accepted.set(snapshot.source, combined);
326
+ for (const { index, operation } of replacements)
327
+ if (!operationResults.has(index))
328
+ operationResults.set(index, {
329
+ index,
330
+ kind: operation.kind,
331
+ status: "applied",
332
+ effect: "applied",
333
+ resources,
334
+ });
335
+ return {
336
+ saved,
337
+ files: [
338
+ {
339
+ source: snapshot.source,
340
+ before,
341
+ after: applied.content,
342
+ action: "edited",
343
+ changes: applied.changes.map((change, editIndex) => ({
344
+ editIndex,
345
+ fromA: change.fromBefore,
346
+ toA: change.toBefore,
347
+ fromB: change.fromAfter,
348
+ toB: change.toAfter,
349
+ removedText: change.removedText,
350
+ insertedText: change.insertedText,
351
+ })),
352
+ formatting: { status: "not-reported" },
144
353
  },
354
+ ],
355
+ operations: replacements.map(({ index }) => requiredValue(operationResults.get(index))),
356
+ };
357
+ } catch (error) {
358
+ const rollbackErrors = await rollback(saved, options.restorePath);
359
+ for (const { index, operation } of replacements)
360
+ if (!operationResults.has(index))
361
+ operationResults.set(
362
+ index,
363
+ rollbackErrors.length === 0
364
+ ? failed(index, operation, resources, error)
365
+ : {
366
+ index,
367
+ kind: operation.kind,
368
+ status: "unknown",
369
+ effect: "unknown",
370
+ resources,
371
+ error: codedError(error, rollbackErrors),
372
+ },
373
+ );
374
+ return {
375
+ saved: rollbackErrors.length === 0 ? [] : saved,
376
+ files: [],
377
+ operations: replacements.map(({ index }) => requiredValue(operationResults.get(index))),
378
+ };
379
+ }
380
+ }
381
+
382
+ async function validateOperation(
383
+ operation: Operation,
384
+ snapshots: ReadonlyMap<string, EditorSnapshot>,
385
+ accepted: ReadonlyMap<string, readonly TextChange[]>,
386
+ cwd: string,
387
+ ): Promise<void> {
388
+ if (operation.kind === "warning") return;
389
+ if (operation.kind === "text-copy" || operation.kind === "text-move") {
390
+ const selected =
391
+ operation.kind === "text-move"
392
+ ? [...operation.destinations, ...operation.sources]
393
+ : [...operation.destinations];
394
+ for (const selection of [...operation.sources, ...operation.destinations])
395
+ validateSelection(
396
+ { kind: "replace", selection, text: "" },
397
+ snapshots.get(selection.document),
145
398
  );
146
- if (outcome.kind === "failed")
147
- throw outcome.failure.cause instanceof Error
148
- ? outcome.failure.cause
149
- : new Error(outcome.failure.message);
399
+ for (const [index, selection] of selected.entries()) {
400
+ const snapshot = requiredValue(snapshots.get(selection.document));
401
+ const prior = accepted.get(snapshot.source) ?? [];
402
+ if (
403
+ prior.some((change) => overlaps(change, selection)) ||
404
+ selected
405
+ .slice(0, index)
406
+ .some((other) => other.document === selection.document && rangesOverlap(other, selection))
407
+ )
408
+ throw invalid(`Overlapping selection in ${snapshot.source}`);
150
409
  }
151
-
152
- for (const operation of fileOperations) await performFileOperation(operation, cwd);
153
- for (const target of fileOperations.flatMap((operation) =>
154
- operation.target === undefined ? [] : [path.resolve(cwd, operation.target)],
410
+ for (const document of new Set(
411
+ [...operation.sources, ...operation.destinations].map(({ document }) => document),
155
412
  )) {
156
- if ((await optionalStat(target)) !== undefined)
157
- await editor.postProcessFile(target, { cwd, signal });
413
+ const snapshot = requiredValue(snapshots.get(document));
414
+ const expected = applyTextChanges(
415
+ snapshot.content,
416
+ accepted.get(snapshot.source) ?? [],
417
+ ).content;
418
+ let current;
419
+ try {
420
+ current = await readFile(snapshot.source, "utf8");
421
+ } catch {
422
+ throw stale(snapshot.source);
423
+ }
424
+ if (current !== expected) throw stale(snapshot.source);
158
425
  }
159
- const transaction = await editor.recordApplyUndo(saved);
160
- return {
161
- operation: "apply",
162
- transaction,
163
- ok: true,
164
- effect: "applied",
165
- files,
166
- completed: [...touched],
167
- errors: [],
168
- };
169
- } catch (error) {
170
- const rollbackErrors = await rollback(saved);
171
- throw Object.assign(new Error(error instanceof Error ? error.message : String(error)), {
172
- code: "TRANSACTION_FAILED",
173
- details: {
174
- effect: rollbackErrors.length === 0 ? "rolled-back" : "rollback-incomplete",
175
- files: [...touched],
176
- rollbackErrors,
426
+ return;
427
+ }
428
+ if (operation.kind === "replace") {
429
+ const snapshot = snapshots.get(operation.selection.document);
430
+ validateSelection(operation, snapshot);
431
+ const expected = applyTextChanges(
432
+ snapshot.content,
433
+ accepted.get(snapshot.source) ?? [],
434
+ ).content;
435
+ let current: string;
436
+ try {
437
+ current = await readFile(snapshot.source, "utf8");
438
+ } catch {
439
+ throw stale(snapshot.source);
440
+ }
441
+ if (current !== expected) throw stale(snapshot.source);
442
+ return;
443
+ }
444
+ const source = path.resolve(cwd, operation.path);
445
+ const sourceStat = await optionalStat(source);
446
+ if (operation.kind === "create") {
447
+ if (sourceStat !== undefined) throw invalid(`Create target exists: ${operation.path}`);
448
+ return;
449
+ }
450
+ if (sourceStat === undefined) throw invalid(`Source does not exist: ${operation.path}`);
451
+ if (!sourceStat.isFile() || sourceStat.isSymbolicLink())
452
+ throw invalid(`${source} is not a regular file`);
453
+ if (operation.kind === "delete") return;
454
+ const target = path.resolve(cwd, operation.target ?? "");
455
+ if (source === target) throw invalid("Source and target are the same file");
456
+ const targetStat = await optionalStat(target);
457
+ if (targetStat !== undefined && (!targetStat.isFile() || targetStat.isSymbolicLink()))
458
+ throw invalid(`${target} is not a regular file`);
459
+ if (targetStat !== undefined && operation.overwrite !== true)
460
+ throw invalid(`Target exists: ${operation.target}`);
461
+ }
462
+
463
+ async function executeOperation(
464
+ operation: Operation,
465
+ snapshots: ReadonlyMap<string, EditorSnapshot>,
466
+ accepted: Map<string, TextChange[]>,
467
+ editor: TransactionEditor,
468
+ cwd: string,
469
+ signal: AbortSignal,
470
+ ): Promise<ScriptMutationFile[]> {
471
+ if (operation.kind === "warning") return [];
472
+ if (operation.kind === "text-copy" || operation.kind === "text-move")
473
+ return executeTextTransfer(operation, snapshots, accepted, editor, cwd, signal);
474
+ if (operation.kind === "replace") {
475
+ const snapshot = snapshots.get(operation.selection.document);
476
+ if (snapshot === undefined) throw invalid("Selection belongs to an unknown editor snapshot");
477
+ const prior = accepted.get(snapshot.source) ?? [];
478
+ const next = [
479
+ ...prior,
480
+ {
481
+ from: operation.selection.from,
482
+ to: operation.selection.to,
483
+ insert: preserveLineEnding(operation.selection, operation.text),
484
+ },
485
+ ];
486
+ const before = applyTextChanges(snapshot.content, prior).content;
487
+ const applied = applyTextChanges(snapshot.content, next);
488
+ await editOne(editor, snapshot.source, before, applied.content, cwd, signal, false);
489
+ accepted.set(snapshot.source, next);
490
+ return [
491
+ {
492
+ source: snapshot.source,
493
+ before,
494
+ after: applied.content,
495
+ action: "edited",
496
+ changes: applied.changes.map((change, editIndex) => ({
497
+ editIndex,
498
+ fromA: change.fromBefore,
499
+ toA: change.toBefore,
500
+ fromB: change.fromAfter,
501
+ toB: change.toAfter,
502
+ removedText: change.removedText,
503
+ insertedText: change.insertedText,
504
+ })),
505
+ formatting: { status: "not-reported" },
506
+ },
507
+ ];
508
+ }
509
+ if (operation.kind === "create") {
510
+ const source = path.resolve(cwd, operation.path);
511
+ await editOne(editor, source, "", operation.content, cwd, signal, true);
512
+ return [
513
+ {
514
+ source,
515
+ before: null,
516
+ after: operation.content,
517
+ action: "created",
518
+ changes: [],
519
+ formatting: { status: "not-reported" },
177
520
  },
521
+ ];
522
+ }
523
+ await performFileOperation(operation, cwd);
524
+ if (operation.kind === "delete" || operation.kind === "move") {
525
+ forgetDeferredPostEdit(path.resolve(cwd, operation.path));
526
+ }
527
+ if (operation.target !== undefined) {
528
+ const target = path.resolve(cwd, operation.target);
529
+ if ((await optionalStat(target)) !== undefined)
530
+ await editor.postProcessFile(target, { cwd, signal });
531
+ }
532
+ return [];
533
+ }
534
+
535
+ function preserveLineEnding(selection: Selection, insert: string): string {
536
+ if (insert.length === 0 || selection.linewise !== true || /(?:\r\n|\r|\n)$/u.test(insert))
537
+ return insert;
538
+ return insert + (/(?:\r\n|\r|\n)$/u.exec(selection.text)?.[0] ?? "");
539
+ }
540
+ function rangesOverlap(left: Selection, right: Selection): boolean {
541
+ return left.from < right.to && right.from < left.to;
542
+ }
543
+ function transferInsert(snapshot: EditorSnapshot, destination: Selection, text: string): string {
544
+ if (destination.from !== destination.to || destination.linewise !== true || text.length === 0)
545
+ return text;
546
+ const separator = snapshot.content.includes("\r\n") ? "\r\n" : "\n";
547
+ const before = snapshot.content.slice(0, destination.from);
548
+ const after = snapshot.content.slice(destination.to);
549
+ const prefix = before.length > 0 && !/(?:\r\n|\r|\n)$/u.test(before) ? separator : "";
550
+ const suffix = after.length > 0 && !/(?:\r\n|\r|\n)$/u.test(text) ? separator : "";
551
+ return prefix + text + suffix;
552
+ }
553
+ async function executeTextTransfer(
554
+ operation: TextTransferOperation,
555
+ snapshots: ReadonlyMap<string, EditorSnapshot>,
556
+ accepted: Map<string, TextChange[]>,
557
+ editor: TransactionEditor,
558
+ cwd: string,
559
+ signal: AbortSignal,
560
+ ): Promise<ScriptMutationFile[]> {
561
+ const additions = new Map<string, TextChange[]>();
562
+ for (const destination of operation.destinations) {
563
+ const snapshot = requiredValue(snapshots.get(destination.document));
564
+ const changes = additions.get(snapshot.source) ?? [];
565
+ changes.push({
566
+ from: destination.from,
567
+ to: destination.to,
568
+ insert: transferInsert(snapshot, destination, operation.text),
178
569
  });
570
+ additions.set(snapshot.source, changes);
571
+ }
572
+ if (operation.kind === "text-move")
573
+ for (const source of operation.sources) {
574
+ const snapshot = requiredValue(snapshots.get(source.document));
575
+ const changes = additions.get(snapshot.source) ?? [];
576
+ changes.push({ from: source.from, to: source.to, insert: "" });
577
+ additions.set(snapshot.source, changes);
578
+ }
579
+ const sourcePaths = [...additions.keys()];
580
+ const before = new Map(
581
+ sourcePaths.map((source) => {
582
+ const snapshot = requiredValue(
583
+ [...snapshots.values()].find((item) => item.source === source),
584
+ );
585
+ return [
586
+ source,
587
+ applyTextChanges(snapshot.content, accepted.get(source) ?? []).content,
588
+ ] as const;
589
+ }),
590
+ );
591
+ const after = new Map<string, string>();
592
+ const outcome = await editor.editTexts(
593
+ sourcePaths.map((source) => ({ source, read: true })),
594
+ { cwd, signal, intent: "edit" },
595
+ (texts) => {
596
+ const changes = new Map<string, TextChange[]>();
597
+ for (const source of sourcePaths) {
598
+ if (texts.get(source) !== before.get(source)) throw stale(source);
599
+ const combined = [...(accepted.get(source) ?? []), ...(additions.get(source) ?? [])];
600
+ const snapshot = requiredValue(
601
+ [...snapshots.values()].find((item) => item.source === source),
602
+ );
603
+ after.set(source, applyTextChanges(snapshot.content, combined).content);
604
+ changes.set(source, additions.get(source) ?? []);
605
+ }
606
+ return { changes, result: undefined };
607
+ },
608
+ );
609
+ if (outcome.kind === "failed")
610
+ throw outcome.failure.cause instanceof Error
611
+ ? outcome.failure.cause
612
+ : new Error(outcome.failure.message);
613
+ const files: ScriptMutationFile[] = [];
614
+ for (const source of sourcePaths) {
615
+ const snapshot = requiredValue([...snapshots.values()].find((item) => item.source === source));
616
+ const combined = [...(accepted.get(source) ?? []), ...(additions.get(source) ?? [])];
617
+ accepted.set(source, combined);
618
+ const applied = applyTextChanges(snapshot.content, combined);
619
+ files.push({
620
+ source,
621
+ before: requiredValue(before.get(source)),
622
+ after: requiredValue(after.get(source)),
623
+ action: "edited",
624
+ changes: applied.changes.map((change, editIndex) => ({
625
+ editIndex,
626
+ fromA: change.fromBefore,
627
+ toA: change.toBefore,
628
+ fromB: change.fromAfter,
629
+ toB: change.toAfter,
630
+ removedText: change.removedText,
631
+ insertedText: change.insertedText,
632
+ })),
633
+ formatting: { status: "not-reported" },
634
+ });
635
+ }
636
+ return files;
637
+ }
638
+ async function editOne(
639
+ editor: TransactionEditor,
640
+ source: string,
641
+ before: string,
642
+ after: string,
643
+ cwd: string,
644
+ signal: AbortSignal,
645
+ create: boolean,
646
+ ): Promise<void> {
647
+ const outcome = await editor.editTexts(
648
+ [{ source, read: true, ...(create && { allowReadFailure: true }) }],
649
+ { cwd, signal, intent: "edit" },
650
+ (texts) => {
651
+ if ((texts.get(source) ?? "") !== before) throw stale(source);
652
+ return {
653
+ changes: new Map([[source, [{ from: 0, to: before.length, insert: after }]]]),
654
+ result: undefined,
655
+ };
656
+ },
657
+ );
658
+ if (outcome.kind === "failed")
659
+ throw outcome.failure.cause instanceof Error
660
+ ? outcome.failure.cause
661
+ : new Error(outcome.failure.message);
662
+ }
663
+
664
+ function validateSelection(
665
+ operation: TextOperation,
666
+ snapshot: EditorSnapshot | undefined,
667
+ ): asserts snapshot is EditorSnapshot {
668
+ if (snapshot === undefined) throw invalid("Selection belongs to an unknown editor snapshot");
669
+ const { from, to, text } = operation.selection;
670
+ if (
671
+ !Number.isInteger(from) ||
672
+ !Number.isInteger(to) ||
673
+ from < 0 ||
674
+ to < from ||
675
+ to > snapshot.content.length
676
+ )
677
+ throw invalid(`Selection ${from}-${to} is outside ${snapshot.source}`);
678
+ if (snapshot.content.slice(from, to) !== text)
679
+ throw invalid(`Selection text does not match ${snapshot.source}`);
680
+ }
681
+ function overlaps(change: TextChange, selection: Selection): boolean {
682
+ return selection.from < change.to && change.from < selection.to;
683
+ }
684
+ function operationResources(
685
+ operation: Operation,
686
+ snapshots: ReadonlyMap<string, EditorSnapshot>,
687
+ cwd: string,
688
+ ): string[] {
689
+ if (operation.kind === "text-copy" || operation.kind === "text-move")
690
+ return [
691
+ ...new Set(
692
+ [...operation.sources, ...operation.destinations].flatMap((selection) => {
693
+ const snapshot = snapshots.get(selection.document);
694
+ return snapshot === undefined ? [] : [path.resolve(cwd, snapshot.source)];
695
+ }),
696
+ ),
697
+ ];
698
+ if (operation.kind === "warning") {
699
+ const snapshot = snapshots.get(operation.document);
700
+ return snapshot === undefined ? [] : [path.resolve(cwd, snapshot.source)];
701
+ }
702
+ if (operation.kind === "replace") {
703
+ const snapshot = snapshots.get(operation.selection.document);
704
+ return snapshot === undefined ? [] : [path.resolve(cwd, snapshot.source)];
705
+ }
706
+ return [
707
+ path.resolve(cwd, operation.path),
708
+ ...("target" in operation && operation.target !== undefined
709
+ ? [path.resolve(cwd, operation.target)]
710
+ : []),
711
+ ];
712
+ }
713
+ function warningDetails(operation: WarningOperation): {
714
+ code: string;
715
+ message: string;
716
+ presentation?: unknown;
717
+ } {
718
+ if (operation.warning !== null && typeof operation.warning === "object") {
719
+ const value = operation.warning as Record<string, unknown>;
720
+ return {
721
+ code: typeof value.code === "string" ? value.code : "EMPTY_SELECTION",
722
+ message:
723
+ typeof value.message === "string"
724
+ ? value.message
725
+ : "SelectionSet is empty; no edit was applied.",
726
+ ...(value.presentation !== undefined && { presentation: value.presentation }),
727
+ };
179
728
  }
729
+ return {
730
+ code: "EMPTY_SELECTION",
731
+ message:
732
+ operation.query === undefined
733
+ ? "SelectionSet is empty; no edit was applied."
734
+ : `SelectionSet for "${operation.query}" is empty; no edit was applied.`,
735
+ };
736
+ }
737
+ function failed(
738
+ index: number,
739
+ operation: Operation,
740
+ resources: readonly string[],
741
+ error: unknown,
742
+ ): ApplyOperationOutcome {
743
+ return {
744
+ index,
745
+ kind: operation.kind,
746
+ status: "failed",
747
+ effect: "not-applied",
748
+ resources,
749
+ error: codedError(error),
750
+ };
751
+ }
752
+ function codedError(
753
+ error: unknown,
754
+ rollbackErrors: readonly string[] = [],
755
+ ): { code: string; message: string } {
756
+ const code =
757
+ error !== null && typeof error === "object" && "code" in error
758
+ ? String(error.code)
759
+ : "OPERATION_FAILED";
760
+ const message = error instanceof Error ? error.message : String(error);
761
+ return {
762
+ code: rollbackErrors.length ? "ROLLBACK_INCOMPLETE" : code,
763
+ message: rollbackErrors.length
764
+ ? `${message}; rollback failed: ${rollbackErrors.join("; ")}`
765
+ : message,
766
+ };
180
767
  }
181
768
 
182
769
  function parseRequest(value: unknown): EditorTransactionRequest {
183
- const request = record(value, "apply() transaction");
184
- const rawSnapshots = array(request.snapshots, "snapshots");
185
- const rawOperations = array(request.operations, "operations");
186
- const snapshots = rawSnapshots.map((value, index) => {
770
+ const request = record(value, "flush() transaction");
771
+ const snapshots = array(request.snapshots, "snapshots").map((value, index) => {
187
772
  const item = record(value, `snapshot ${index + 1}`);
188
773
  return {
189
774
  id: string(item.id, "snapshot id"),
@@ -191,43 +776,67 @@ function parseRequest(value: unknown): EditorTransactionRequest {
191
776
  content: text(item.content, "snapshot content"),
192
777
  };
193
778
  });
194
- const operations = rawOperations.map(
195
- (value, index): TextOperation | CreateOperation | FileOperation => {
196
- const item = record(value, `operation ${index + 1}`);
197
- const kind = string(item.kind, "operation kind");
198
- if (kind === "replace") {
199
- const selected = record(item.selection, "selection");
200
- return {
201
- kind,
202
- selection: {
203
- document: string(selected.document, "selection document"),
204
- from: integer(selected.from, "selection from"),
205
- to: integer(selected.to, "selection to"),
206
- text: text(selected.text, "selection text"),
207
- },
208
- text: text(item.text, "replacement text"),
209
- };
210
- }
211
- if (kind === "create")
212
- return {
213
- kind,
214
- path: string(item.path, "create path"),
215
- content: text(item.content, "create content"),
216
- };
217
- if (kind === "delete") return { kind, path: string(item.path, "delete path") };
218
- if (kind === "copy" || kind === "move")
219
- return {
220
- kind,
221
- path: string(item.path, `${kind} path`),
222
- target: string(item.target, `${kind} target`),
223
- ...(item.overwrite === true && { overwrite: true }),
224
- };
225
- throw invalid(`Unknown transaction operation: ${kind}`);
226
- },
227
- );
779
+ const operations = array(request.operations, "operations").map((value, index): Operation => {
780
+ const item = record(value, `operation ${index + 1}`);
781
+ const kind = string(item.kind, "operation kind");
782
+ if (kind === "replace") {
783
+ const selected = record(item.selection, "selection");
784
+ return {
785
+ kind,
786
+ selection: {
787
+ document: string(selected.document, "selection document"),
788
+ from: integer(selected.from, "selection from"),
789
+ to: integer(selected.to, "selection to"),
790
+ text: text(selected.text, "selection text"),
791
+ ...(selected.linewise === true && { linewise: true }),
792
+ },
793
+ text: text(item.text, "replacement text"),
794
+ };
795
+ }
796
+ if (kind === "text-copy" || kind === "text-move")
797
+ return {
798
+ kind,
799
+ sources: selections(item.sources, "transfer sources"),
800
+ destinations: selections(item.destinations, "transfer destinations"),
801
+ text: text(item.text, "transfer text"),
802
+ };
803
+ if (kind === "warning")
804
+ return {
805
+ kind,
806
+ document: string(item.document, "warning document"),
807
+ ...(typeof item.query === "string" && { query: item.query }),
808
+ ...(item.warning !== undefined && { warning: item.warning }),
809
+ };
810
+ if (kind === "create")
811
+ return {
812
+ kind,
813
+ path: string(item.path, "create path"),
814
+ content: text(item.content, "create content"),
815
+ };
816
+ if (kind === "delete") return { kind, path: string(item.path, "delete path") };
817
+ if (kind === "copy" || kind === "move")
818
+ return {
819
+ kind,
820
+ path: string(item.path, `${kind} path`),
821
+ target: string(item.target, `${kind} target`),
822
+ ...(item.overwrite === true && { overwrite: true }),
823
+ };
824
+ throw invalid(`Unknown transaction operation: ${kind}`);
825
+ });
228
826
  return { snapshots, operations };
229
827
  }
230
-
828
+ function selections(value: unknown, label: string): Selection[] {
829
+ return array(value, label).map((entry, index) => {
830
+ const item = record(entry, `${label} ${index + 1}`);
831
+ return {
832
+ document: string(item.document, "selection document"),
833
+ from: integer(item.from, "selection from"),
834
+ to: integer(item.to, "selection to"),
835
+ text: text(item.text, "selection text"),
836
+ ...(item.linewise === true && { linewise: true }),
837
+ };
838
+ });
839
+ }
231
840
  function record(value: unknown, label: string): Record<string, unknown> {
232
841
  if (value === null || typeof value !== "object" || Array.isArray(value))
233
842
  throw invalid(`${label} must be an object`);
@@ -250,82 +859,6 @@ function integer(value: unknown, label: string): number {
250
859
  if (!Number.isInteger(value)) throw invalid(`${label} must be an integer`);
251
860
  return value as number;
252
861
  }
253
-
254
- function validateTextChanges(changes: ReadonlyMap<string, readonly TextChange[]>): void {
255
- for (const [source, items] of changes) {
256
- const ordered = [...items].sort((a, b) => a.from - b.from || a.to - b.to);
257
- for (let index = 1; index < ordered.length; index += 1) {
258
- const previous = ordered[index - 1];
259
- const current = ordered[index];
260
- if (previous !== undefined && current !== undefined && current.from < previous.to)
261
- throw invalid(`Overlapping selections in ${source}`);
262
- }
263
- }
264
- }
265
-
266
- function touchedPaths(
267
- cwd: string,
268
- changes: ReadonlyMap<string, unknown>,
269
- creates: readonly CreateOperation[],
270
- operations: readonly FileOperation[],
271
- ): Set<string> {
272
- const result = new Set([...changes.keys()].map((source) => path.resolve(cwd, source)));
273
- for (const item of creates) result.add(path.resolve(cwd, item.path));
274
- for (const item of operations) {
275
- result.add(path.resolve(cwd, item.path));
276
- if (item.target !== undefined) result.add(path.resolve(cwd, item.target));
277
- }
278
- return result;
279
- }
280
-
281
- async function preflight(
282
- touched: ReadonlySet<string>,
283
- snapshots: ReadonlyMap<string, EditorSnapshot>,
284
- changes: ReadonlyMap<string, unknown>,
285
- creates: readonly CreateOperation[],
286
- operations: readonly FileOperation[],
287
- cwd: string,
288
- ): Promise<void> {
289
- for (const file of touched) {
290
- const stat = await optionalStat(file);
291
- if (stat !== undefined && (!stat.isFile() || stat.isSymbolicLink()))
292
- throw invalid(`${file} is not a regular file`);
293
- }
294
- for (const snapshot of snapshots.values()) {
295
- if (!changes.has(snapshot.source)) continue;
296
- let current: string;
297
- try {
298
- current = await readFile(snapshot.source, "utf8");
299
- } catch {
300
- throw stale(snapshot.source);
301
- }
302
- if (current !== snapshot.content) throw stale(snapshot.source);
303
- }
304
- const createPaths = creates.map((item) => path.resolve(cwd, item.path));
305
- if (new Set(createPaths).size !== createPaths.length)
306
- throw invalid("A transaction cannot create the same path more than once");
307
- for (const item of creates)
308
- if ((await optionalStat(path.resolve(cwd, item.path))) !== undefined)
309
- throw invalid(`Create target exists: ${item.path}`);
310
- const existence = new Map<string, boolean>();
311
- for (const file of touched) existence.set(file, (await optionalStat(file)) !== undefined);
312
- for (const item of creates) existence.set(path.resolve(cwd, item.path), true);
313
- for (const item of operations) {
314
- const source = path.resolve(cwd, item.path);
315
- if (existence.get(source) !== true) throw invalid(`Source does not exist: ${item.path}`);
316
- if (item.kind === "delete") {
317
- existence.set(source, false);
318
- continue;
319
- }
320
- const target = path.resolve(cwd, item.target ?? "");
321
- if (source === target) throw invalid("Source and target are the same file");
322
- if (existence.get(target) === true && item.overwrite !== true)
323
- throw invalid(`Target exists: ${item.target}`);
324
- existence.set(target, true);
325
- if (item.kind === "move") existence.set(source, false);
326
- }
327
- }
328
-
329
862
  async function performFileOperation(operation: FileOperation, cwd: string): Promise<void> {
330
863
  const source = path.resolve(cwd, operation.path);
331
864
  if (operation.kind === "delete") {
@@ -338,7 +871,6 @@ async function performFileOperation(operation: FileOperation, cwd: string): Prom
338
871
  await fs.copy(source, target, { overwrite: operation.overwrite === true, errorOnExist: true });
339
872
  else await fs.move(source, target, { overwrite: operation.overwrite === true });
340
873
  }
341
-
342
874
  async function savePath(file: string): Promise<SavedPath> {
343
875
  try {
344
876
  return { path: file, existed: true, bytes: await readFile(file) };
@@ -347,23 +879,26 @@ async function savePath(file: string): Promise<SavedPath> {
347
879
  throw error;
348
880
  }
349
881
  }
350
-
351
- async function rollback(saved: readonly SavedPath[]): Promise<readonly string[]> {
882
+ async function rollback(
883
+ saved: readonly SavedPath[],
884
+ restorePath: (state: SavedPath) => Promise<void> = restoreSavedPath,
885
+ ): Promise<readonly string[]> {
352
886
  const errors: string[] = [];
353
- for (const item of [...saved].reverse()) {
887
+ for (const item of [...saved].reverse())
354
888
  try {
355
- if (item.existed) {
356
- await mkdir(path.dirname(item.path), { recursive: true });
357
- await writeFile(item.path, item.bytes ?? new Uint8Array());
358
- } else await rm(item.path, { force: true });
889
+ await restorePath(item);
359
890
  } catch (error) {
360
891
  if (!item.existed && (isCode(error, "ENOENT") || isCode(error, "ENOTDIR"))) continue;
361
892
  errors.push(`${item.path}: ${error instanceof Error ? error.message : String(error)}`);
362
893
  }
363
- }
364
894
  return errors;
365
895
  }
366
-
896
+ async function restoreSavedPath(item: SavedPath): Promise<void> {
897
+ if (item.existed) {
898
+ await mkdir(path.dirname(item.path), { recursive: true });
899
+ await writeFile(item.path, item.bytes ?? new Uint8Array());
900
+ } else await rm(item.path, { force: true });
901
+ }
367
902
  async function optionalStat(file: string) {
368
903
  try {
369
904
  return await lstat(file);
@@ -372,16 +907,14 @@ async function optionalStat(file: string) {
372
907
  throw error;
373
908
  }
374
909
  }
375
-
376
910
  function isCode(error: unknown, code: string): boolean {
377
911
  return error !== null && typeof error === "object" && "code" in error && error.code === code;
378
912
  }
379
-
380
913
  function invalid(message: string): Error {
381
914
  return Object.assign(new Error(message), { code: "INVALID_TRANSACTION" });
382
915
  }
383
916
  function stale(source: string): Error {
384
- return Object.assign(new Error(`Snapshot changed before apply(): ${source}`), {
917
+ return Object.assign(new Error(`Snapshot changed before flush(): ${source}`), {
385
918
  code: "STALE_SNAPSHOT",
386
919
  });
387
920
  }