pi-agent-ide 0.1.0 → 0.1.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 (511) hide show
  1. package/README.md +31 -9
  2. package/docs/architecture.md +18 -6
  3. package/docs/configuration.md +70 -40
  4. package/docs/development.md +14 -2
  5. package/docs/extensions.md +132 -150
  6. package/docs/generated/tool-catalog/c.md +9 -0
  7. package/docs/generated/tool-catalog/cmake.md +9 -0
  8. package/docs/generated/tool-catalog/cpp.md +9 -0
  9. package/docs/generated/tool-catalog/csharp.md +9 -0
  10. package/docs/generated/tool-catalog/css.md +10 -0
  11. package/docs/generated/tool-catalog/dockerfile.md +9 -0
  12. package/docs/generated/tool-catalog/go.md +10 -0
  13. package/docs/generated/tool-catalog/html.md +9 -0
  14. package/docs/generated/tool-catalog/index.md +30 -0
  15. package/docs/generated/tool-catalog/java.md +9 -0
  16. package/docs/generated/tool-catalog/javascript.md +10 -0
  17. package/docs/generated/tool-catalog/json.md +10 -0
  18. package/docs/generated/tool-catalog/kotlin.md +9 -0
  19. package/docs/generated/tool-catalog/lua.md +9 -0
  20. package/docs/generated/tool-catalog/markdown.md +9 -0
  21. package/docs/generated/tool-catalog/php.md +9 -0
  22. package/docs/generated/tool-catalog/python.md +10 -0
  23. package/docs/generated/tool-catalog/ruby.md +9 -0
  24. package/docs/generated/tool-catalog/rust.md +9 -0
  25. package/docs/generated/tool-catalog/shell.md +9 -0
  26. package/docs/generated/tool-catalog/sql.md +9 -0
  27. package/docs/generated/tool-catalog/swift.md +9 -0
  28. package/docs/generated/tool-catalog/terraform.md +9 -0
  29. package/docs/generated/tool-catalog/toml.md +9 -0
  30. package/docs/generated/tool-catalog/typescript.md +10 -0
  31. package/docs/generated/tool-catalog/xml.md +9 -0
  32. package/docs/generated/tool-catalog/yaml.md +9 -0
  33. package/node_modules/pi-agent-doctor/package.json +26 -0
  34. package/node_modules/pi-agent-doctor/src/catalog.ts +55 -0
  35. package/node_modules/pi-agent-doctor/src/connect-plugin.ts +53 -0
  36. package/node_modules/pi-agent-doctor/src/executable.ts +47 -0
  37. package/node_modules/pi-agent-doctor/src/plugin-protocol.ts +121 -0
  38. package/node_modules/pi-agent-filesystem/index.ts +42 -44
  39. package/node_modules/pi-agent-filesystem/package.json +11 -11
  40. package/node_modules/pi-agent-filesystem/src/resolver.ts +112 -135
  41. package/node_modules/pi-agent-filesystem-image/index.ts +5 -6
  42. package/node_modules/pi-agent-filesystem-image/package.json +8 -8
  43. package/node_modules/pi-agent-filesystem-pdf/index.ts +5 -6
  44. package/node_modules/pi-agent-filesystem-pdf/package.json +5 -5
  45. package/node_modules/pi-agent-filesystem-text/index.ts +11 -12
  46. package/node_modules/pi-agent-filesystem-text/package.json +8 -8
  47. package/node_modules/pi-agent-ide-ast/index.ts +1 -1
  48. package/node_modules/pi-agent-ide-ast/package.json +13 -12
  49. package/node_modules/pi-agent-ide-ast/src/ast/collect-files.ts +11 -16
  50. package/node_modules/pi-agent-ide-ast/src/ast/manager.ts +292 -322
  51. package/node_modules/pi-agent-ide-ast/src/ast/outline.ts +591 -656
  52. package/node_modules/pi-agent-ide-ast/src/ast/read-text.ts +15 -19
  53. package/node_modules/pi-agent-ide-ast/src/doctor-plugin.ts +105 -0
  54. package/node_modules/pi-agent-ide-ast/src/extension.ts +67 -64
  55. package/node_modules/pi-agent-ide-ast/src/outline-resolver.ts +51 -54
  56. package/node_modules/pi-agent-ide-ast/src/scope-handler.ts +168 -185
  57. package/node_modules/pi-agent-ide-ast/src/scope-resolver.ts +30 -36
  58. package/node_modules/pi-agent-ide-ast/src/search-resolver.ts +118 -129
  59. package/node_modules/pi-agent-ide-changes/index.ts +53 -51
  60. package/node_modules/pi-agent-ide-changes/package.json +12 -11
  61. package/node_modules/pi-agent-ide-changes/src/change-anchor.ts +68 -78
  62. package/node_modules/pi-agent-ide-changes/src/changes/change-groups.ts +230 -245
  63. package/node_modules/pi-agent-ide-changes/src/changes/change-service.ts +189 -192
  64. package/node_modules/pi-agent-ide-changes/src/changes/change-types.ts +75 -79
  65. package/node_modules/pi-agent-ide-changes/src/changes/git-changes-backend.ts +258 -276
  66. package/node_modules/pi-agent-ide-changes/src/current-change-presenter.ts +164 -190
  67. package/node_modules/pi-agent-ide-changes/src/doctor-plugin.ts +29 -0
  68. package/node_modules/pi-agent-ide-changes/src/index-mutation-queue.ts +10 -9
  69. package/node_modules/pi-agent-ide-changes/src/last-text-transaction-store.ts +49 -62
  70. package/node_modules/pi-agent-ide-changes/src/tool-index-change.ts +93 -93
  71. package/node_modules/pi-agent-ide-changes/src/tool-text-undo.ts +124 -126
  72. package/node_modules/pi-agent-ide-formatter/index.ts +22 -23
  73. package/node_modules/pi-agent-ide-formatter/package.json +5 -2
  74. package/node_modules/pi-agent-ide-formatter/src/catalog.ts +247 -0
  75. package/node_modules/pi-agent-ide-formatter/src/doctor-plugin.ts +104 -0
  76. package/node_modules/pi-agent-ide-formatter/src/formatter.ts +38 -40
  77. package/node_modules/pi-agent-ide-formatter/src/registry.ts +45 -21
  78. package/node_modules/pi-agent-ide-languages/index.ts +24 -0
  79. package/node_modules/pi-agent-ide-languages/package.json +16 -0
  80. package/node_modules/pi-agent-ide-languages/src/languages.ts +84 -0
  81. package/node_modules/pi-agent-ide-lint/index.ts +164 -198
  82. package/node_modules/pi-agent-ide-lint/package.json +8 -7
  83. package/node_modules/pi-agent-ide-lint/src/catalog.ts +283 -0
  84. package/node_modules/pi-agent-ide-lint/src/command-linter.ts +50 -152
  85. package/node_modules/pi-agent-ide-lint/src/diagnostics.ts +180 -0
  86. package/node_modules/pi-agent-ide-lint/src/doctor-plugin.ts +104 -0
  87. package/node_modules/pi-agent-ide-lint/src/registry.ts +43 -21
  88. package/node_modules/pi-agent-ide-lsp/index.ts +187 -208
  89. package/node_modules/pi-agent-ide-lsp/package.json +12 -11
  90. package/node_modules/pi-agent-ide-lsp/src/catalog.ts +248 -0
  91. package/node_modules/pi-agent-ide-lsp/src/code-view-resolvers.ts +109 -116
  92. package/node_modules/pi-agent-ide-lsp/src/doctor-plugin.ts +108 -0
  93. package/node_modules/pi-agent-ide-lsp/src/lsp/client.ts +361 -385
  94. package/node_modules/pi-agent-ide-lsp/src/lsp/code-views.ts +420 -458
  95. package/node_modules/pi-agent-ide-lsp/src/lsp/diagnostics.ts +128 -137
  96. package/node_modules/pi-agent-ide-lsp/src/lsp/index.ts +25 -20
  97. package/node_modules/pi-agent-ide-lsp/src/lsp/language-map.ts +31 -33
  98. package/node_modules/pi-agent-ide-lsp/src/lsp/lsp-compiler.ts +48 -56
  99. package/node_modules/pi-agent-ide-lsp/src/lsp/manager.ts +369 -411
  100. package/node_modules/pi-agent-ide-lsp/src/lsp/navigation.ts +58 -63
  101. package/node_modules/pi-agent-ide-lsp/src/lsp/registry.ts +153 -70
  102. package/node_modules/pi-agent-ide-lsp/src/lsp/rename.ts +36 -36
  103. package/node_modules/pi-agent-ide-lsp/src/lsp/symbol-search.ts +117 -127
  104. package/node_modules/pi-agent-ide-lsp/src/lsp/symbols.ts +108 -107
  105. package/node_modules/pi-agent-ide-lsp/src/lsp/types.ts +74 -57
  106. package/node_modules/pi-agent-ide-lsp/src/search-resolver.ts +36 -32
  107. package/node_modules/pi-agent-image/package.json +2 -2
  108. package/node_modules/pi-agent-image/src/image-converter.ts +210 -249
  109. package/node_modules/pi-agent-image/src/index.ts +4 -4
  110. package/node_modules/pi-agent-pdf/package.json +2 -2
  111. package/node_modules/pi-agent-pdf/src/index.ts +1 -5
  112. package/node_modules/pi-agent-pdf/src/pdf-converter.ts +130 -153
  113. package/node_modules/pi-agent-read/index.ts +1 -1
  114. package/node_modules/pi-agent-read/package.json +9 -9
  115. package/node_modules/pi-agent-read/src/api/connect-plugin.ts +38 -51
  116. package/node_modules/pi-agent-read/src/api/plugin-protocol.ts +26 -32
  117. package/node_modules/pi-agent-read/src/api/rendering.ts +3 -4
  118. package/node_modules/pi-agent-read/src/api/tools/read.ts +124 -132
  119. package/node_modules/pi-agent-read/src/core/extension.ts +28 -29
  120. package/node_modules/pi-agent-read/src/core/read-core.ts +281 -330
  121. package/node_modules/pi-agent-read/src/core/tools/read/output-truncation.ts +153 -156
  122. package/node_modules/pi-agent-read/src/core/tools/read/read-renderer.ts +294 -316
  123. package/node_modules/pi-agent-read/src/core/tools/read/read-result.ts +146 -155
  124. package/node_modules/pi-agent-read/src/core/tools/read/temp-resource-store.ts +165 -187
  125. package/node_modules/pi-agent-read/src/core/tools/tool-read.ts +644 -693
  126. package/node_modules/pi-agent-resource/package.json +1 -1
  127. package/node_modules/pi-agent-resource/src/content-conversion/connect-plugin.ts +50 -62
  128. package/node_modules/pi-agent-resource/src/content-conversion/content-converter.ts +27 -33
  129. package/node_modules/pi-agent-resource/src/content-conversion/content-description.ts +16 -20
  130. package/node_modules/pi-agent-resource/src/content-conversion/content-host.ts +52 -57
  131. package/node_modules/pi-agent-resource/src/content-conversion/content-runner.ts +115 -134
  132. package/node_modules/pi-agent-resource/src/content-conversion/plugin-protocol.ts +38 -39
  133. package/node_modules/pi-agent-resource/src/content-conversion/validation.ts +117 -107
  134. package/node_modules/pi-agent-resource/src/content.ts +5 -9
  135. package/node_modules/pi-agent-resource/src/index.ts +51 -40
  136. package/node_modules/pi-agent-resource/src/resolver.ts +11 -13
  137. package/node_modules/pi-agent-resource/src/resource.ts +17 -24
  138. package/node_modules/pi-agent-resource/src/validation.ts +106 -92
  139. package/node_modules/pi-agent-search/package.json +7 -7
  140. package/node_modules/pi-agent-search/src/api/connect-plugin.ts +37 -47
  141. package/node_modules/pi-agent-search/src/api/plugin-protocol.ts +26 -30
  142. package/node_modules/pi-agent-search/src/api/search.ts +61 -67
  143. package/node_modules/pi-agent-search/src/core/extension.ts +112 -92
  144. package/node_modules/pi-agent-search/src/core/search-core.ts +330 -359
  145. package/node_modules/pi-agent-search-semantic/index.ts +75 -83
  146. package/node_modules/pi-agent-search-semantic/package.json +5 -5
  147. package/node_modules/pi-agent-search-text/index.ts +40 -38
  148. package/node_modules/pi-agent-search-text/package.json +10 -9
  149. package/node_modules/pi-agent-search-text/src/doctor-plugin.ts +29 -0
  150. package/node_modules/pi-agent-search-text/src/file-search.ts +90 -86
  151. package/node_modules/pi-agent-search-text/src/lucene-query-parser.d.ts +17 -19
  152. package/node_modules/pi-agent-search-text/src/resolvers.ts +152 -157
  153. package/node_modules/pi-agent-search-text/src/ripgrep.ts +16 -0
  154. package/node_modules/pi-agent-search-text/src/search-backend.ts +215 -249
  155. package/node_modules/pi-agent-search-text/src/search-query.ts +85 -108
  156. package/node_modules/pi-agent-search-text/src/search-renderer.ts +310 -334
  157. package/node_modules/pi-agent-search-text/src/search-result.ts +151 -157
  158. package/node_modules/pi-agent-search-text/src/search-session.ts +255 -261
  159. package/node_modules/pi-agent-search-web/index.ts +65 -57
  160. package/node_modules/pi-agent-search-web/package.json +8 -7
  161. package/node_modules/pi-agent-search-web/src/config.ts +470 -409
  162. package/node_modules/pi-agent-search-web/src/doctor-plugin.ts +40 -0
  163. package/node_modules/pi-agent-search-web/src/providers/duckduckgo-html.ts +56 -60
  164. package/node_modules/pi-agent-search-web/src/providers/endpoints.ts +60 -68
  165. package/node_modules/pi-agent-search-web/src/providers/request.ts +359 -362
  166. package/node_modules/pi-agent-search-web/src/providers/response.ts +296 -345
  167. package/node_modules/pi-agent-search-web/src/search-format.ts +15 -20
  168. package/node_modules/pi-agent-search-web/src/search.ts +289 -347
  169. package/node_modules/pi-agent-search-web/src/types.ts +99 -111
  170. package/node_modules/pi-agent-text/package.json +2 -2
  171. package/node_modules/pi-agent-text/src/index.ts +30 -22
  172. package/node_modules/pi-agent-text/src/presented-text.ts +15 -17
  173. package/node_modules/pi-agent-text/src/source-line.ts +33 -36
  174. package/node_modules/pi-agent-text/src/text-anchor.ts +120 -117
  175. package/node_modules/pi-agent-text/src/text-converter.ts +71 -84
  176. package/node_modules/pi-agent-text/src/text-document.ts +99 -110
  177. package/node_modules/pi-agent-text-anchor-constant/index.ts +18 -20
  178. package/node_modules/pi-agent-text-anchor-constant/package.json +5 -5
  179. package/node_modules/pi-agent-text-anchor-constant/src/resolver.ts +29 -36
  180. package/node_modules/pi-agent-text-anchor-line-hash/index.ts +34 -36
  181. package/node_modules/pi-agent-text-anchor-line-hash/package.json +11 -11
  182. package/node_modules/pi-agent-text-anchor-line-hash/src/anchor.ts +75 -85
  183. package/node_modules/pi-agent-text-anchor-line-hash/src/read-handler.ts +35 -42
  184. package/node_modules/pi-agent-text-editor/index.ts +7 -9
  185. package/node_modules/pi-agent-text-editor/package.json +10 -10
  186. package/node_modules/pi-agent-text-editor/src/api/anchor-inspection.ts +16 -18
  187. package/node_modules/pi-agent-text-editor/src/api/connect-plugin.ts +40 -50
  188. package/node_modules/pi-agent-text-editor/src/api/edit-completion.ts +10 -13
  189. package/node_modules/pi-agent-text-editor/src/api/edit-pipeline.ts +31 -36
  190. package/node_modules/pi-agent-text-editor/src/api/last-resolved-resource.ts +25 -27
  191. package/node_modules/pi-agent-text-editor/src/api/mutation-guard.ts +26 -31
  192. package/node_modules/pi-agent-text-editor/src/api/mutation-preview.ts +18 -21
  193. package/node_modules/pi-agent-text-editor/src/api/mutation-result.ts +19 -19
  194. package/node_modules/pi-agent-text-editor/src/api/mutation-tool.ts +117 -132
  195. package/node_modules/pi-agent-text-editor/src/api/plugin-protocol.ts +155 -141
  196. package/node_modules/pi-agent-text-editor/src/api/post-edit.ts +93 -103
  197. package/node_modules/pi-agent-text-editor/src/api/stale-anchor-message.ts +17 -14
  198. package/node_modules/pi-agent-text-editor/src/api/text-selection-anchor.ts +84 -95
  199. package/node_modules/pi-agent-text-editor/src/api/tool-call-interceptor.ts +9 -9
  200. package/node_modules/pi-agent-text-editor/src/api/tool-renderer.ts +18 -22
  201. package/node_modules/pi-agent-text-editor/src/core/builtin-edit-filter.ts +41 -47
  202. package/node_modules/pi-agent-text-editor/src/core/extension.ts +115 -120
  203. package/node_modules/pi-agent-text-editor/src/core/mutation-result/agent-diff.ts +273 -311
  204. package/node_modules/pi-agent-text-editor/src/core/mutation-result/diff.ts +85 -95
  205. package/node_modules/pi-agent-text-editor/src/core/mutation-result/file-mutation-agent-result.ts +232 -289
  206. package/node_modules/pi-agent-text-editor/src/core/mutation-result/file-mutation-result.ts +534 -580
  207. package/node_modules/pi-agent-text-editor/src/core/mutation-result/inline-hints.ts +86 -98
  208. package/node_modules/pi-agent-text-editor/src/core/text-anchor-recovery.ts +12 -11
  209. package/node_modules/pi-agent-text-editor/src/core/text-anchor-registry.ts +282 -336
  210. package/node_modules/pi-agent-text-editor/src/core/text-change-engine.ts +181 -214
  211. package/node_modules/pi-agent-text-editor/src/core/text-edit-batch-coordinator.ts +476 -511
  212. package/node_modules/pi-agent-text-editor/src/core/text-edit-batch-execution.ts +93 -105
  213. package/node_modules/pi-agent-text-editor/src/core/text-edit-batch-recovery.ts +31 -33
  214. package/node_modules/pi-agent-text-editor/src/core/text-edit-batch-registrar.ts +367 -372
  215. package/node_modules/pi-agent-text-editor/src/core/text-edit-batch.ts +82 -88
  216. package/node_modules/pi-agent-text-editor/src/core/text-editor-core.ts +1837 -2035
  217. package/node_modules/pi-agent-text-editor/src/core/text-mutation-anchor-error.ts +19 -22
  218. package/node_modules/pi-agent-text-editor/src/core/text-mutation.ts +629 -631
  219. package/node_modules/pi-agent-text-editor/src/core/tool-call-interceptor/coordinator.ts +982 -1031
  220. package/node_modules/pi-agent-text-editor/src/core/tool-call-interceptor/partial-json-resolver.ts +19 -23
  221. package/node_modules/pi-agent-text-editor/src/core/tool-call-interceptor/partial-tool-recovery.ts +270 -273
  222. package/node_modules/pi-agent-text-editor/src/core/tool-call-interceptor/rendering.ts +2 -2
  223. package/node_modules/pi-agent-text-editor/src/core/tool-call-interceptor/streaming-provider.ts +353 -403
  224. package/node_modules/pi-agent-text-editor/src/core/tool-description.ts +9 -11
  225. package/node_modules/pi-agent-text-editor/src/tools/extension.ts +7 -8
  226. package/node_modules/pi-agent-text-editor/src/tools/text-selection.ts +69 -77
  227. package/node_modules/pi-agent-text-editor/src/tools/tool-text-copy.ts +109 -95
  228. package/node_modules/pi-agent-text-editor/src/tools/tool-text-delete.ts +69 -61
  229. package/node_modules/pi-agent-text-editor/src/tools/tool-text-insert.ts +52 -39
  230. package/node_modules/pi-agent-text-editor/src/tools/tool-text-move.ts +121 -115
  231. package/node_modules/pi-agent-text-editor/src/tools/tool-text-replace.ts +71 -54
  232. package/node_modules/pi-agent-text-editor/src/tools/tool-text-write.ts +24 -17
  233. package/node_modules/pi-agent-text-editor-argument-order/index.ts +16 -19
  234. package/node_modules/pi-agent-text-editor-argument-order/package.json +4 -4
  235. package/node_modules/pi-agent-text-editor-argument-order/src/argument-order-guard.ts +79 -91
  236. package/node_modules/pi-agent-text-editor-overwrite/index.ts +297 -323
  237. package/node_modules/pi-agent-text-editor-overwrite/package.json +4 -4
  238. package/node_modules/pi-agent-text-editor-renderer/index.ts +11 -12
  239. package/node_modules/pi-agent-text-editor-renderer/package.json +7 -7
  240. package/node_modules/pi-agent-text-editor-renderer/src/diff-model.ts +347 -359
  241. package/node_modules/pi-agent-text-editor-renderer/src/diff-renderer.ts +203 -219
  242. package/node_modules/pi-agent-text-editor-renderer/src/diff-theme.ts +297 -329
  243. package/node_modules/pi-agent-text-editor-renderer/src/diff-viewport.ts +19 -25
  244. package/node_modules/pi-agent-text-editor-renderer/src/frozen-viewport.ts +160 -168
  245. package/node_modules/pi-agent-text-editor-renderer/src/mutation-panel.ts +170 -182
  246. package/node_modules/pi-agent-text-editor-renderer/src/mutation-projection.ts +330 -340
  247. package/node_modules/pi-agent-text-editor-renderer/src/mutation-result.ts +115 -118
  248. package/node_modules/pi-agent-text-editor-renderer/src/render-resource.ts +3 -4
  249. package/node_modules/pi-agent-text-editor-renderer/src/renderer.ts +582 -629
  250. package/node_modules/pi-agent-text-editor-renderer/src/typing-interpolation.ts +144 -167
  251. package/node_modules/pi-agent-text-editor-stale-anchor/index.ts +317 -333
  252. package/node_modules/pi-agent-text-editor-stale-anchor/package.json +5 -5
  253. package/node_modules/pi-agent-tool-call-interception/package.json +1 -1
  254. package/node_modules/pi-agent-tool-call-interception/src/index.ts +334 -354
  255. package/node_modules/pi-agent-web/index.ts +24 -25
  256. package/node_modules/pi-agent-web/package.json +10 -10
  257. package/node_modules/pi-agent-web/src/resolver.ts +133 -155
  258. package/node_modules/pi-agent-web-html/index.ts +5 -6
  259. package/node_modules/pi-agent-web-html/package.json +6 -6
  260. package/node_modules/pi-agent-web-html/src/extract-readable-html.ts +58 -76
  261. package/node_modules/pi-agent-web-html/src/html-converter.ts +62 -75
  262. package/node_modules/pi-agent-web-image/index.ts +5 -6
  263. package/node_modules/pi-agent-web-image/package.json +5 -5
  264. package/node_modules/pi-agent-web-pdf/index.ts +5 -6
  265. package/node_modules/pi-agent-web-pdf/package.json +5 -5
  266. package/node_modules/pi-agent-web-text/index.ts +5 -6
  267. package/node_modules/pi-agent-web-text/package.json +5 -5
  268. package/package.json +72 -52
  269. package/src/api/code-view.ts +17 -17
  270. package/src/api/connect-doctor-plugin.ts +1 -0
  271. package/src/api/connect-plugin.ts +38 -48
  272. package/src/api/doctor.ts +1 -0
  273. package/src/api/plugin-protocol.ts +30 -38
  274. package/src/api/read.ts +6 -1
  275. package/src/api/resource.ts +3 -1
  276. package/src/api/search.ts +5 -1
  277. package/src/api/text-editor.ts +4 -1
  278. package/src/api/text.ts +3 -1
  279. package/src/api/tool-catalog.ts +1 -0
  280. package/src/api/tool-config.ts +365 -0
  281. package/src/api/toolchain.ts +18 -18
  282. package/src/code-view/diagnostic-view.ts +59 -58
  283. package/src/code-view/reference.ts +64 -82
  284. package/src/code-view/source-view.ts +159 -180
  285. package/src/composite/builtin-extensions.ts +39 -35
  286. package/src/composite/config.ts +75 -69
  287. package/src/composite/selection.ts +54 -52
  288. package/src/core/extension.ts +32 -36
  289. package/src/core/ide-core.ts +76 -93
  290. package/src/doctor/config-writer.ts +115 -0
  291. package/src/doctor/core.ts +174 -0
  292. package/src/doctor/discovery.ts +215 -0
  293. package/src/doctor/extension.ts +108 -0
  294. package/src/doctor/index.ts +1 -0
  295. package/src/doctor/inventory.ts +91 -0
  296. package/src/doctor/run.ts +196 -0
  297. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/index.ts +42 -44
  298. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/package.json +11 -11
  299. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-image/index.ts +5 -6
  300. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-image/package.json +8 -8
  301. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-pdf/index.ts +5 -6
  302. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-pdf/package.json +5 -5
  303. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-text/index.ts +11 -12
  304. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-text/package.json +8 -8
  305. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/src/resolver.ts +112 -135
  306. package/src/extensions/pi-agent-read/extensions/pi-agent-web/index.ts +24 -25
  307. package/src/extensions/pi-agent-read/extensions/pi-agent-web/package.json +10 -10
  308. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-html/index.ts +5 -6
  309. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-html/package.json +6 -6
  310. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-html/src/extract-readable-html.ts +58 -76
  311. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-html/src/html-converter.ts +62 -75
  312. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-image/index.ts +5 -6
  313. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-image/package.json +5 -5
  314. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-pdf/index.ts +5 -6
  315. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-pdf/package.json +5 -5
  316. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-text/index.ts +5 -6
  317. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-text/package.json +5 -5
  318. package/src/extensions/pi-agent-read/extensions/pi-agent-web/src/resolver.ts +133 -155
  319. package/src/extensions/pi-agent-read/index.ts +1 -1
  320. package/src/extensions/pi-agent-read/package.json +9 -9
  321. package/src/extensions/pi-agent-read/src/api/connect-plugin.ts +38 -51
  322. package/src/extensions/pi-agent-read/src/api/plugin-protocol.ts +26 -32
  323. package/src/extensions/pi-agent-read/src/api/rendering.ts +3 -4
  324. package/src/extensions/pi-agent-read/src/api/tools/read.ts +124 -132
  325. package/src/extensions/pi-agent-read/src/core/extension.ts +28 -29
  326. package/src/extensions/pi-agent-read/src/core/read-core.ts +281 -330
  327. package/src/extensions/pi-agent-read/src/core/tools/read/output-truncation.ts +153 -156
  328. package/src/extensions/pi-agent-read/src/core/tools/read/read-renderer.ts +294 -316
  329. package/src/extensions/pi-agent-read/src/core/tools/read/read-result.ts +146 -155
  330. package/src/extensions/pi-agent-read/src/core/tools/read/temp-resource-store.ts +165 -187
  331. package/src/extensions/pi-agent-read/src/core/tools/tool-read.ts +644 -693
  332. package/src/extensions/pi-agent-search/package.json +7 -7
  333. package/src/extensions/pi-agent-search/plugins/pi-agent-search-semantic/index.ts +75 -83
  334. package/src/extensions/pi-agent-search/plugins/pi-agent-search-semantic/package.json +5 -5
  335. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/index.ts +40 -38
  336. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/package.json +10 -9
  337. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/src/doctor-plugin.ts +29 -0
  338. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/src/file-search.ts +90 -86
  339. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/src/lucene-query-parser.d.ts +17 -19
  340. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/src/resolvers.ts +152 -157
  341. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/src/ripgrep.ts +16 -0
  342. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/src/search-backend.ts +215 -249
  343. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/src/search-query.ts +85 -108
  344. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/src/search-renderer.ts +310 -334
  345. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/src/search-result.ts +151 -157
  346. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/src/search-session.ts +255 -261
  347. package/src/extensions/pi-agent-search/plugins/pi-agent-search-web/index.ts +65 -57
  348. package/src/extensions/pi-agent-search/plugins/pi-agent-search-web/package.json +8 -7
  349. package/src/extensions/pi-agent-search/plugins/pi-agent-search-web/src/config.ts +470 -409
  350. package/src/extensions/pi-agent-search/plugins/pi-agent-search-web/src/doctor-plugin.ts +40 -0
  351. package/src/extensions/pi-agent-search/plugins/pi-agent-search-web/src/providers/duckduckgo-html.ts +56 -60
  352. package/src/extensions/pi-agent-search/plugins/pi-agent-search-web/src/providers/endpoints.ts +60 -68
  353. package/src/extensions/pi-agent-search/plugins/pi-agent-search-web/src/providers/request.ts +359 -362
  354. package/src/extensions/pi-agent-search/plugins/pi-agent-search-web/src/providers/response.ts +296 -345
  355. package/src/extensions/pi-agent-search/plugins/pi-agent-search-web/src/search-format.ts +15 -20
  356. package/src/extensions/pi-agent-search/plugins/pi-agent-search-web/src/search.ts +289 -347
  357. package/src/extensions/pi-agent-search/plugins/pi-agent-search-web/src/types.ts +99 -111
  358. package/src/extensions/pi-agent-search/src/api/connect-plugin.ts +37 -47
  359. package/src/extensions/pi-agent-search/src/api/plugin-protocol.ts +26 -30
  360. package/src/extensions/pi-agent-search/src/api/search.ts +61 -67
  361. package/src/extensions/pi-agent-search/src/core/extension.ts +112 -92
  362. package/src/extensions/pi-agent-search/src/core/search-core.ts +330 -359
  363. package/src/extensions/pi-agent-text-editor/index.ts +7 -9
  364. package/src/extensions/pi-agent-text-editor/package.json +10 -10
  365. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-constant/index.ts +18 -20
  366. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-constant/package.json +5 -5
  367. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-constant/src/resolver.ts +29 -36
  368. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-line-hash/index.ts +34 -36
  369. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-line-hash/package.json +11 -11
  370. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-line-hash/src/anchor.ts +75 -85
  371. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-line-hash/src/read-handler.ts +35 -42
  372. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-argument-order/index.ts +16 -19
  373. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-argument-order/package.json +4 -4
  374. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-argument-order/src/argument-order-guard.ts +79 -91
  375. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-overwrite/index.ts +297 -323
  376. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-overwrite/package.json +4 -4
  377. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/index.ts +11 -12
  378. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/package.json +7 -7
  379. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/src/diff-model.ts +347 -359
  380. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/src/diff-renderer.ts +203 -219
  381. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/src/diff-theme.ts +297 -329
  382. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/src/diff-viewport.ts +19 -25
  383. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/src/frozen-viewport.ts +160 -168
  384. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/src/mutation-panel.ts +170 -182
  385. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/src/mutation-projection.ts +330 -340
  386. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/src/mutation-result.ts +115 -118
  387. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/src/render-resource.ts +3 -4
  388. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/src/renderer.ts +582 -629
  389. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/src/typing-interpolation.ts +144 -167
  390. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-stale-anchor/index.ts +317 -333
  391. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-stale-anchor/package.json +5 -5
  392. package/src/extensions/pi-agent-text-editor/src/api/anchor-inspection.ts +16 -18
  393. package/src/extensions/pi-agent-text-editor/src/api/connect-plugin.ts +40 -50
  394. package/src/extensions/pi-agent-text-editor/src/api/edit-completion.ts +10 -13
  395. package/src/extensions/pi-agent-text-editor/src/api/edit-pipeline.ts +31 -36
  396. package/src/extensions/pi-agent-text-editor/src/api/last-resolved-resource.ts +25 -27
  397. package/src/extensions/pi-agent-text-editor/src/api/mutation-guard.ts +26 -31
  398. package/src/extensions/pi-agent-text-editor/src/api/mutation-preview.ts +18 -21
  399. package/src/extensions/pi-agent-text-editor/src/api/mutation-result.ts +19 -19
  400. package/src/extensions/pi-agent-text-editor/src/api/mutation-tool.ts +117 -132
  401. package/src/extensions/pi-agent-text-editor/src/api/plugin-protocol.ts +155 -141
  402. package/src/extensions/pi-agent-text-editor/src/api/post-edit.ts +93 -103
  403. package/src/extensions/pi-agent-text-editor/src/api/stale-anchor-message.ts +17 -14
  404. package/src/extensions/pi-agent-text-editor/src/api/text-selection-anchor.ts +84 -95
  405. package/src/extensions/pi-agent-text-editor/src/api/tool-call-interceptor.ts +9 -9
  406. package/src/extensions/pi-agent-text-editor/src/api/tool-renderer.ts +18 -22
  407. package/src/extensions/pi-agent-text-editor/src/core/builtin-edit-filter.ts +41 -47
  408. package/src/extensions/pi-agent-text-editor/src/core/extension.ts +115 -120
  409. package/src/extensions/pi-agent-text-editor/src/core/mutation-result/agent-diff.ts +273 -311
  410. package/src/extensions/pi-agent-text-editor/src/core/mutation-result/diff.ts +85 -95
  411. package/src/extensions/pi-agent-text-editor/src/core/mutation-result/file-mutation-agent-result.ts +232 -289
  412. package/src/extensions/pi-agent-text-editor/src/core/mutation-result/file-mutation-result.ts +534 -580
  413. package/src/extensions/pi-agent-text-editor/src/core/mutation-result/inline-hints.ts +86 -98
  414. package/src/extensions/pi-agent-text-editor/src/core/text-anchor-recovery.ts +12 -11
  415. package/src/extensions/pi-agent-text-editor/src/core/text-anchor-registry.ts +282 -336
  416. package/src/extensions/pi-agent-text-editor/src/core/text-change-engine.ts +181 -214
  417. package/src/extensions/pi-agent-text-editor/src/core/text-edit-batch-coordinator.ts +476 -511
  418. package/src/extensions/pi-agent-text-editor/src/core/text-edit-batch-execution.ts +93 -105
  419. package/src/extensions/pi-agent-text-editor/src/core/text-edit-batch-recovery.ts +31 -33
  420. package/src/extensions/pi-agent-text-editor/src/core/text-edit-batch-registrar.ts +367 -372
  421. package/src/extensions/pi-agent-text-editor/src/core/text-edit-batch.ts +82 -88
  422. package/src/extensions/pi-agent-text-editor/src/core/text-editor-core.ts +1837 -2035
  423. package/src/extensions/pi-agent-text-editor/src/core/text-mutation-anchor-error.ts +19 -22
  424. package/src/extensions/pi-agent-text-editor/src/core/text-mutation.ts +629 -631
  425. package/src/extensions/pi-agent-text-editor/src/core/tool-call-interceptor/coordinator.ts +982 -1031
  426. package/src/extensions/pi-agent-text-editor/src/core/tool-call-interceptor/partial-json-resolver.ts +19 -23
  427. package/src/extensions/pi-agent-text-editor/src/core/tool-call-interceptor/partial-tool-recovery.ts +270 -273
  428. package/src/extensions/pi-agent-text-editor/src/core/tool-call-interceptor/rendering.ts +2 -2
  429. package/src/extensions/pi-agent-text-editor/src/core/tool-call-interceptor/streaming-provider.ts +353 -403
  430. package/src/extensions/pi-agent-text-editor/src/core/tool-description.ts +9 -11
  431. package/src/extensions/pi-agent-text-editor/src/tools/extension.ts +7 -8
  432. package/src/extensions/pi-agent-text-editor/src/tools/text-selection.ts +69 -77
  433. package/src/extensions/pi-agent-text-editor/src/tools/tool-text-copy.ts +109 -95
  434. package/src/extensions/pi-agent-text-editor/src/tools/tool-text-delete.ts +69 -61
  435. package/src/extensions/pi-agent-text-editor/src/tools/tool-text-insert.ts +52 -39
  436. package/src/extensions/pi-agent-text-editor/src/tools/tool-text-move.ts +121 -115
  437. package/src/extensions/pi-agent-text-editor/src/tools/tool-text-replace.ts +71 -54
  438. package/src/extensions/pi-agent-text-editor/src/tools/tool-text-write.ts +24 -17
  439. package/src/pi-agent-ide.ts +10 -10
  440. package/src/plugins/pi-agent-ide-ast/index.ts +1 -1
  441. package/src/plugins/pi-agent-ide-ast/package.json +13 -12
  442. package/src/plugins/pi-agent-ide-ast/src/ast/collect-files.ts +11 -16
  443. package/src/plugins/pi-agent-ide-ast/src/ast/manager.ts +292 -322
  444. package/src/plugins/pi-agent-ide-ast/src/ast/outline.ts +591 -656
  445. package/src/plugins/pi-agent-ide-ast/src/ast/read-text.ts +15 -19
  446. package/src/plugins/pi-agent-ide-ast/src/doctor-plugin.ts +105 -0
  447. package/src/plugins/pi-agent-ide-ast/src/extension.ts +67 -64
  448. package/src/plugins/pi-agent-ide-ast/src/outline-resolver.ts +51 -54
  449. package/src/plugins/pi-agent-ide-ast/src/scope-handler.ts +168 -185
  450. package/src/plugins/pi-agent-ide-ast/src/scope-resolver.ts +30 -36
  451. package/src/plugins/pi-agent-ide-ast/src/search-resolver.ts +118 -129
  452. package/src/plugins/pi-agent-ide-changes/index.ts +53 -51
  453. package/src/plugins/pi-agent-ide-changes/package.json +12 -11
  454. package/src/plugins/pi-agent-ide-changes/src/change-anchor.ts +68 -78
  455. package/src/plugins/pi-agent-ide-changes/src/changes/change-groups.ts +230 -245
  456. package/src/plugins/pi-agent-ide-changes/src/changes/change-service.ts +189 -192
  457. package/src/plugins/pi-agent-ide-changes/src/changes/change-types.ts +75 -79
  458. package/src/plugins/pi-agent-ide-changes/src/changes/git-changes-backend.ts +258 -276
  459. package/src/plugins/pi-agent-ide-changes/src/current-change-presenter.ts +164 -190
  460. package/src/plugins/pi-agent-ide-changes/src/doctor-plugin.ts +29 -0
  461. package/src/plugins/pi-agent-ide-changes/src/index-mutation-queue.ts +10 -9
  462. package/src/plugins/pi-agent-ide-changes/src/last-text-transaction-store.ts +49 -62
  463. package/src/plugins/pi-agent-ide-changes/src/tool-index-change.ts +93 -93
  464. package/src/plugins/pi-agent-ide-changes/src/tool-text-undo.ts +124 -126
  465. package/src/plugins/pi-agent-ide-formatter/index.ts +22 -23
  466. package/src/plugins/pi-agent-ide-formatter/package.json +5 -2
  467. package/src/plugins/pi-agent-ide-formatter/src/catalog.ts +247 -0
  468. package/src/plugins/pi-agent-ide-formatter/src/doctor-plugin.ts +104 -0
  469. package/src/plugins/pi-agent-ide-formatter/src/formatter.ts +38 -40
  470. package/src/plugins/pi-agent-ide-formatter/src/registry.ts +45 -21
  471. package/src/plugins/pi-agent-ide-languages/index.ts +24 -0
  472. package/src/plugins/pi-agent-ide-languages/package.json +16 -0
  473. package/src/plugins/pi-agent-ide-languages/src/languages.ts +84 -0
  474. package/src/plugins/pi-agent-ide-lint/index.ts +164 -198
  475. package/src/plugins/pi-agent-ide-lint/package.json +8 -7
  476. package/src/plugins/pi-agent-ide-lint/src/catalog.ts +283 -0
  477. package/src/plugins/pi-agent-ide-lint/src/command-linter.ts +50 -152
  478. package/src/plugins/pi-agent-ide-lint/src/diagnostics.ts +180 -0
  479. package/src/plugins/pi-agent-ide-lint/src/doctor-plugin.ts +104 -0
  480. package/src/plugins/pi-agent-ide-lint/src/registry.ts +43 -21
  481. package/src/plugins/pi-agent-ide-lsp/index.ts +187 -208
  482. package/src/plugins/pi-agent-ide-lsp/package.json +12 -11
  483. package/src/plugins/pi-agent-ide-lsp/src/catalog.ts +248 -0
  484. package/src/plugins/pi-agent-ide-lsp/src/code-view-resolvers.ts +109 -116
  485. package/src/plugins/pi-agent-ide-lsp/src/doctor-plugin.ts +108 -0
  486. package/src/plugins/pi-agent-ide-lsp/src/lsp/client.ts +361 -385
  487. package/src/plugins/pi-agent-ide-lsp/src/lsp/code-views.ts +420 -458
  488. package/src/plugins/pi-agent-ide-lsp/src/lsp/diagnostics.ts +128 -137
  489. package/src/plugins/pi-agent-ide-lsp/src/lsp/index.ts +25 -20
  490. package/src/plugins/pi-agent-ide-lsp/src/lsp/language-map.ts +31 -33
  491. package/src/plugins/pi-agent-ide-lsp/src/lsp/lsp-compiler.ts +48 -56
  492. package/src/plugins/pi-agent-ide-lsp/src/lsp/manager.ts +369 -411
  493. package/src/plugins/pi-agent-ide-lsp/src/lsp/navigation.ts +58 -63
  494. package/src/plugins/pi-agent-ide-lsp/src/lsp/registry.ts +153 -70
  495. package/src/plugins/pi-agent-ide-lsp/src/lsp/rename.ts +36 -36
  496. package/src/plugins/pi-agent-ide-lsp/src/lsp/symbol-search.ts +117 -127
  497. package/src/plugins/pi-agent-ide-lsp/src/lsp/symbols.ts +108 -107
  498. package/src/plugins/pi-agent-ide-lsp/src/lsp/types.ts +74 -57
  499. package/src/plugins/pi-agent-ide-lsp/src/search-resolver.ts +36 -32
  500. package/src/post-edit/gate.ts +114 -122
  501. package/src/toolchain/diagnostic.ts +3 -4
  502. package/src/toolchain/gate.ts +278 -295
  503. package/src/toolchain/registry.ts +143 -165
  504. package/src/toolchain/types.ts +126 -103
  505. package/src/utils/required-value.ts +8 -0
  506. package/node_modules/pi-agent-ide-formatter/src/types.ts +0 -10
  507. package/node_modules/pi-agent-ide-lint/src/command-runner.ts +0 -51
  508. package/node_modules/pi-agent-ide-lint/src/types.ts +0 -10
  509. package/src/plugins/pi-agent-ide-formatter/src/types.ts +0 -10
  510. package/src/plugins/pi-agent-ide-lint/src/command-runner.ts +0 -51
  511. package/src/plugins/pi-agent-ide-lint/src/types.ts +0 -10
@@ -1,2348 +1,2150 @@
1
+ import { requiredValue } from "../../../../utils/required-value.js";
1
2
  import {
2
- isAgentContent,
3
- isResourceResolutionAttempt,
4
- type Resource,
5
- type ResourceResolver,
6
- type ResourceResolverContext,
7
- type ResourceWrite,
3
+ isAgentContent,
4
+ isResourceResolutionAttempt,
5
+ type Resource,
6
+ type ResourceResolver,
7
+ type ResourceResolverContext,
8
+ type ResourceWrite,
8
9
  } from "pi-agent-resource";
9
10
  import {
10
- createTextDocument,
11
- isTextPresenterRegistration,
12
- type TextAnchor,
13
- type TextAnchorResolverContext,
14
- type TextDocument,
15
- type TextPresentationContext,
16
- type TextPresenterRegistration,
11
+ createTextDocument,
12
+ isTextPresenterRegistration,
13
+ type TextAnchor,
14
+ type TextAnchorResolverContext,
15
+ type TextDocument,
16
+ type TextPresentationContext,
17
+ type TextPresenterRegistration,
17
18
  } from "pi-agent-text";
18
19
 
19
20
  import {
20
- isTextEditHandlerRegistration,
21
- type TextEditExecutionOutcome,
22
- type TextEditHandlerRegistration,
23
- type TextEditorToolPluginApi,
24
- type TextEditPipelineFailure,
25
- type TextEditPipelineStage,
26
- type TextEditState,
27
- type TextPreEditState,
21
+ isTextEditHandlerRegistration,
22
+ type TextEditExecutionOutcome,
23
+ type TextEditHandlerRegistration,
24
+ type TextEditorToolPluginApi,
25
+ type TextEditPipelineFailure,
26
+ type TextEditPipelineStage,
27
+ type TextEditState,
28
+ type TextPreEditState,
28
29
  } from "#src/api/edit-pipeline.js";
29
30
  import {
30
- type AnyTextMutationToolRegistration,
31
- assertTextMutationToolRegistration,
32
- type TextMutationToolListener,
31
+ type AnyTextMutationToolRegistration,
32
+ assertTextMutationToolRegistration,
33
+ type TextMutationToolListener,
33
34
  } from "#src/api/mutation-tool.js";
34
35
  import {
35
- isResourceResolverRegistration,
36
- isTextAnchorResolverRegistration,
37
- isTextEditorToolId,
38
- type PromptDescriptionSource,
39
- type ResourceResolverRegistration,
40
- TEXT_EDITOR_API_VERSION,
41
- TEXT_EDITOR_PROTOCOL,
42
- type TextAnchorResolverRegistration,
43
- type TextAnchorResourceResolverContext,
44
- type TextEditorPlugin,
45
- type TextEditorPluginApi,
46
- type TextEditorToolId,
36
+ isResourceResolverRegistration,
37
+ isTextAnchorResolverRegistration,
38
+ isTextEditorToolId,
39
+ type PromptDescriptionSource,
40
+ type ResourceResolverRegistration,
41
+ TEXT_EDITOR_API_VERSION,
42
+ TEXT_EDITOR_PROTOCOL,
43
+ type TextAnchorResolverRegistration,
44
+ type TextAnchorResourceResolverContext,
45
+ type TextEditorPlugin,
46
+ type TextEditorPluginApi,
47
+ type TextEditorToolId,
47
48
  } from "#src/api/plugin-protocol.js";
48
49
  import {
49
- isTextPostEditHandlerRegistration,
50
- type TextPostEditContribution,
51
- type TextPostEditHandlerRegistration,
52
- type TextPostEditTransaction,
50
+ isTextPostEditHandlerRegistration,
51
+ type TextPostEditContribution,
52
+ type TextPostEditHandlerRegistration,
53
+ type TextPostEditTransaction,
53
54
  } from "#src/api/post-edit.js";
54
55
  import {
55
- isTextEditorToolRendererRegistration,
56
- type TextEditorToolRendererRegistration,
56
+ isTextEditorToolRendererRegistration,
57
+ type TextEditorToolRendererRegistration,
57
58
  } from "#src/api/tool-renderer.js";
58
- import { TextAnchorRegistry, type TextAnchorRegistrySnapshot } from "#src/core/text-anchor-registry.js";
59
- import { applyTextChanges, type TextChange, type TextChangeResult } from "#src/core/text-change-engine.js";
59
+ import {
60
+ TextAnchorRegistry,
61
+ type TextAnchorRegistrySnapshot,
62
+ } from "#src/core/text-anchor-registry.js";
63
+ import {
64
+ applyTextChanges,
65
+ type TextChange,
66
+ type TextChangeResult,
67
+ } from "#src/core/text-change-engine.js";
60
68
  import { previewTextMutation } from "#src/core/text-mutation.js";
61
69
 
62
- import type { TextAnchorInspectionOutcome, TextAnchorInspectionRequest } from "#src/api/anchor-inspection.js";
63
- import type { TextEditCompletion, TextEditCompletionListener, TextEditIntent } from "#src/api/edit-completion.js";
64
70
  import type {
65
- TextMutationGuardContext,
66
- TextMutationGuardRegistration,
67
- TextMutationPlan,
71
+ TextAnchorInspectionOutcome,
72
+ TextAnchorInspectionRequest,
73
+ } from "#src/api/anchor-inspection.js";
74
+ import type {
75
+ TextEditCompletion,
76
+ TextEditCompletionListener,
77
+ TextEditIntent,
78
+ } from "#src/api/edit-completion.js";
79
+ import type {
80
+ TextMutationGuardContext,
81
+ TextMutationGuardRegistration,
82
+ TextMutationPlan,
68
83
  } from "#src/api/mutation-guard.js";
69
- import type { TextMutationPreviewOutcome, TextMutationPreviewRequest } from "#src/api/mutation-preview.js";
84
+ import type {
85
+ TextMutationPreviewOutcome,
86
+ TextMutationPreviewRequest,
87
+ } from "#src/api/mutation-preview.js";
70
88
 
71
89
  type PluginStatus = "active" | "pending";
72
90
 
73
- interface PluginLifecycle
74
- {
75
- status: PluginStatus;
91
+ interface PluginLifecycle {
92
+ status: PluginStatus;
76
93
  }
77
94
 
78
- interface RegisteredPlugin
79
- {
80
- readonly lifecycle: PluginLifecycle;
81
- readonly plugin: TextEditorPlugin;
82
- readonly ready: Promise<void>;
95
+ interface RegisteredPlugin {
96
+ readonly lifecycle: PluginLifecycle;
97
+ readonly plugin: TextEditorPlugin;
98
+ readonly ready: Promise<void>;
83
99
  }
84
100
 
85
- interface RegisteredHandler
86
- {
87
- readonly pluginId: string;
88
- readonly registration: TextEditHandlerRegistration;
89
- readonly tool: TextEditorToolId;
101
+ interface RegisteredHandler {
102
+ readonly pluginId: string;
103
+ readonly registration: TextEditHandlerRegistration;
104
+ readonly tool: TextEditorToolId;
90
105
  }
91
106
 
92
- interface RegisteredResolver
93
- {
94
- readonly resolver: ResourceResolver;
95
- readonly priority: number;
96
- readonly order: number;
107
+ interface RegisteredResolver {
108
+ readonly resolver: ResourceResolver;
109
+ readonly priority: number;
110
+ readonly order: number;
97
111
  }
98
112
 
99
- interface ResolverContribution
100
- {
101
- readonly pluginId: string;
102
- readonly registration: ResourceResolverRegistration;
113
+ interface ResolverContribution {
114
+ readonly pluginId: string;
115
+ readonly registration: ResourceResolverRegistration;
103
116
  }
104
117
 
105
- interface TextAnchorResolverContribution
106
- {
107
- readonly pluginId: string;
108
- readonly registration: TextAnchorResolverRegistration;
118
+ interface TextAnchorResolverContribution {
119
+ readonly pluginId: string;
120
+ readonly registration: TextAnchorResolverRegistration;
109
121
  }
110
122
 
111
- interface TextPresenterContribution
112
- {
113
- readonly pluginId: string;
114
- readonly registration: TextPresenterRegistration;
123
+ interface TextPresenterContribution {
124
+ readonly pluginId: string;
125
+ readonly registration: TextPresenterRegistration;
115
126
  }
116
127
 
117
- interface RegisteredPresenter extends TextPresenterContribution
118
- {
119
- readonly order: number;
128
+ interface RegisteredPresenter extends TextPresenterContribution {
129
+ readonly order: number;
120
130
  }
121
- interface PromptContribution
122
- {
123
- readonly description: string;
124
- readonly pluginId: string;
125
- readonly tool: TextEditorToolId;
131
+ interface PromptContribution {
132
+ readonly description: string;
133
+ readonly pluginId: string;
134
+ readonly tool: TextEditorToolId;
126
135
  }
127
136
 
128
- interface WritablePromptContribution
129
- {
130
- readonly description: PromptDescriptionSource;
131
- readonly pluginId: string;
137
+ interface WritablePromptContribution {
138
+ readonly description: PromptDescriptionSource;
139
+ readonly pluginId: string;
132
140
  }
133
141
 
134
- interface PluginContributionDraft
135
- {
136
- readonly resolvers: ResolverContribution[];
137
- readonly anchorResolvers: TextAnchorResolverContribution[];
138
- readonly presenters?: TextPresenterContribution[];
139
- readonly handlers: RegisteredHandler[];
140
- readonly promptContributions: PromptContribution[];
141
- readonly writablePromptContributions: WritablePromptContribution[];
142
- readonly tools: TextEditorToolId[];
143
- readonly mutationTools?: AnyTextMutationToolRegistration[];
144
- readonly mutationToolListeners?: TextMutationToolListener[];
145
- readonly editCompletionListeners?: TextEditCompletionListener[];
146
- readonly mutationGuards?: TextMutationGuardRegistration[];
147
- readonly toolRenderers?: TextEditorToolRendererRegistration[];
142
+ interface PluginContributionDraft {
143
+ readonly resolvers: ResolverContribution[];
144
+ readonly anchorResolvers: TextAnchorResolverContribution[];
145
+ readonly presenters?: TextPresenterContribution[];
146
+ readonly handlers: RegisteredHandler[];
147
+ readonly promptContributions: PromptContribution[];
148
+ readonly writablePromptContributions: WritablePromptContribution[];
149
+ readonly tools: TextEditorToolId[];
150
+ readonly mutationTools?: AnyTextMutationToolRegistration[];
151
+ readonly mutationToolListeners?: TextMutationToolListener[];
152
+ readonly editCompletionListeners?: TextEditCompletionListener[];
153
+ readonly mutationGuards?: TextMutationGuardRegistration[];
154
+ readonly toolRenderers?: TextEditorToolRendererRegistration[];
148
155
  }
149
156
 
150
- interface PluginContributionController
151
- {
152
- readonly api: TextEditorPluginApi;
153
- close(): void;
154
- commit(): void;
157
+ interface PluginContributionController {
158
+ readonly api: TextEditorPluginApi;
159
+ close(): void;
160
+ commit(): void;
155
161
  }
156
162
 
157
- interface StageRunCompleted<State>
158
- {
159
- readonly kind: "completed";
160
- readonly state: State;
163
+ interface StageRunCompleted<State> {
164
+ readonly kind: "completed";
165
+ readonly state: State;
161
166
  }
162
167
 
163
- type StageRunOutcome<State> = StageRunCompleted<State> | {
164
- readonly kind: "failed";
165
- readonly failure: TextEditPipelineFailure;
166
- };
168
+ type StageRunOutcome<State> =
169
+ | StageRunCompleted<State>
170
+ | {
171
+ readonly kind: "failed";
172
+ readonly failure: TextEditPipelineFailure;
173
+ };
167
174
 
168
- export interface TextMutationResult<Result>
169
- {
170
- readonly text: string;
171
- readonly result: Result;
175
+ export interface TextMutationResult<Result> {
176
+ readonly text: string;
177
+ readonly result: Result;
172
178
  }
173
179
 
174
- export interface TextResourceEditFailure
175
- {
176
- readonly code:
177
- | "INVALID_REQUEST"
178
- | "INVALID_RESOLVER_RESULT"
179
- | "INVALID_RESOURCE_CONTENT"
180
- | "INVALID_WRITE_CONTENT"
181
- | "PLUGIN_FAILED"
182
- | "MUTATION_REJECTED"
183
- | "NO_RESOLVER"
184
- | "POST_WRITE_FAILED"
185
- | "READ_FAILED"
186
- | "RESOLVE_FAILED"
187
- | "UNSUPPORTED_CAPABILITY"
188
- | "UNSUPPORTED_CONTENT"
189
- | "WRITE_FAILED";
190
- readonly source: string;
191
- readonly resolverId?: string;
192
- readonly message: string;
193
- readonly cause?: unknown;
180
+ export interface TextResourceEditFailure {
181
+ readonly code:
182
+ | "INVALID_REQUEST"
183
+ | "INVALID_RESOLVER_RESULT"
184
+ | "INVALID_RESOURCE_CONTENT"
185
+ | "INVALID_WRITE_CONTENT"
186
+ | "PLUGIN_FAILED"
187
+ | "MUTATION_REJECTED"
188
+ | "NO_RESOLVER"
189
+ | "POST_WRITE_FAILED"
190
+ | "READ_FAILED"
191
+ | "RESOLVE_FAILED"
192
+ | "UNSUPPORTED_CAPABILITY"
193
+ | "UNSUPPORTED_CONTENT"
194
+ | "WRITE_FAILED";
195
+ readonly source: string;
196
+ readonly resolverId?: string;
197
+ readonly message: string;
198
+ readonly cause?: unknown;
194
199
  }
195
200
 
196
201
  export type TextResourceEditOutcome<Result> =
197
- | {
198
- readonly kind: "completed";
199
- readonly source: string;
200
- readonly resolvedBy: string;
201
- readonly before: TextDocument;
202
- readonly after: TextDocument;
203
- readonly result: Result;
204
- readonly postEditContributions: readonly TextPostEditContribution[];
202
+ | {
203
+ readonly kind: "completed";
204
+ readonly source: string;
205
+ readonly resolvedBy: string;
206
+ readonly before: TextDocument;
207
+ readonly after: TextDocument;
208
+ readonly result: Result;
209
+ readonly postEditContributions: readonly TextPostEditContribution[];
205
210
  }
206
- | { readonly kind: "failed"; readonly failure: TextResourceEditFailure; };
211
+ | { readonly kind: "failed"; readonly failure: TextResourceEditFailure };
207
212
 
208
- export interface TextResourceEditRequest
209
- {
210
- readonly source: string;
211
- readonly read: boolean;
212
- readonly allowReadFailure?: boolean;
213
+ export interface TextResourceEditRequest {
214
+ readonly source: string;
215
+ readonly read: boolean;
216
+ readonly allowReadFailure?: boolean;
213
217
  }
214
218
 
215
- export interface TextResourcesMutationResult<Result>
216
- {
217
- readonly changes: ReadonlyMap<string, readonly TextChange[]>;
218
- readonly result: Result;
219
+ export interface TextResourcesMutationResult<Result> {
220
+ readonly changes: ReadonlyMap<string, readonly TextChange[]>;
221
+ readonly result: Result;
219
222
  }
220
223
 
221
224
  export type TextResourcesEditOutcome<Result> =
222
- | {
223
- readonly kind: "completed";
224
- readonly resources: readonly Exclude<TextResourceEditOutcome<unknown>, { readonly kind: "failed"; }>[];
225
- readonly result: Result;
225
+ | {
226
+ readonly kind: "completed";
227
+ readonly resources: readonly Exclude<
228
+ TextResourceEditOutcome<unknown>,
229
+ { readonly kind: "failed" }
230
+ >[];
231
+ readonly result: Result;
226
232
  }
227
- | { readonly kind: "failed"; readonly failure: TextResourceEditFailure; readonly completed: readonly string[]; };
233
+ | {
234
+ readonly kind: "failed";
235
+ readonly failure: TextResourceEditFailure;
236
+ readonly completed: readonly string[];
237
+ };
228
238
 
229
239
  export type ResolveTextAnchor = (value: string, kinds?: readonly string[]) => Promise<TextAnchor>;
230
240
 
231
241
  export type ResolveResourceTextAnchor = (
232
- source: string,
233
- value: string,
234
- kinds?: readonly string[],
242
+ source: string,
243
+ value: string,
244
+ kinds?: readonly string[],
235
245
  ) => Promise<TextAnchor>;
236
246
 
237
- export interface TextResourcesEditContext extends ResourceResolverContext, TextMutationGuardContext
238
- {}
239
-
240
- export interface TextEditorCore
241
- {
242
- inspectTextAnchors(request: TextAnchorInspectionRequest): Promise<TextAnchorInspectionOutcome>;
243
- addAnchorResolver(registration: TextAnchorResolverRegistration): void;
244
- resolveTextAnchorResources(
245
- value: string,
246
- kinds: readonly string[],
247
- context: TextAnchorResourceResolverContext,
248
- ): Promise<readonly string[] | undefined>;
249
- editText<Result>(
250
- source: string,
251
- context: ResourceResolverContext,
252
- operation: (
253
- text: string,
254
- resolveAnchor: ResolveTextAnchor,
255
- ) => TextMutationResult<Result> | Promise<TextMutationResult<Result>>,
256
- ): Promise<TextResourceEditOutcome<Result>>;
257
- editTexts<Result>(
258
- sources: readonly TextResourceEditRequest[],
259
- context: TextResourcesEditContext,
260
- operation: (
261
- texts: ReadonlyMap<string, string>,
262
- resolveAnchor: ResolveResourceTextAnchor,
263
- ) => TextResourcesMutationResult<Result> | Promise<TextResourcesMutationResult<Result>>,
264
- ): Promise<TextResourcesEditOutcome<Result>>;
265
- previewTexts(
266
- sources: readonly TextResourceEditRequest[],
267
- context: ResourceResolverContext,
268
- operation: (
269
- texts: ReadonlyMap<string, string>,
270
- resolveAnchor: ResolveResourceTextAnchor,
271
- ) => TextResourcesMutationResult<unknown> | Promise<TextResourcesMutationResult<unknown>>,
272
- ): Promise<TextMutationPreviewOutcome>;
273
- executeEdit<Input, Result>(
274
- tool: TextEditorToolId,
275
- initialState: TextPreEditState<Input>,
276
- operation: (state: TextPreEditState<Input>) => Result | Promise<Result>,
277
- ): Promise<TextEditExecutionOutcome<Input, Result>>;
278
- addMutationTool(registration: AnyTextMutationToolRegistration): void;
279
- getMutationTools(): readonly AnyTextMutationToolRegistration[];
280
- onMutationTool(listener: TextMutationToolListener): () => void;
281
- onDidEdit(listener: TextEditCompletionListener): () => void;
282
- getToolRenderer(tool: TextEditorToolId): TextEditorToolRendererRegistration | undefined;
283
- registerPlugin(plugin: TextEditorPlugin): Promise<void>;
284
- registerPostEditHandler(registration: TextPostEditHandlerRegistration): () => void;
285
- registerTool(tool: TextEditorToolId): void;
286
- waitForPendingPlugins(): Promise<void>;
287
- renderGeneralPromptGuideline(): string | undefined;
288
- renderToolPromptGuideline(tool: TextEditorToolId): string | undefined;
247
+ export interface TextResourcesEditContext
248
+ extends ResourceResolverContext, TextMutationGuardContext {}
249
+
250
+ export interface TextEditorCore {
251
+ inspectTextAnchors(request: TextAnchorInspectionRequest): Promise<TextAnchorInspectionOutcome>;
252
+ addAnchorResolver(registration: TextAnchorResolverRegistration): void;
253
+ resolveTextAnchorResources(
254
+ value: string,
255
+ kinds: readonly string[],
256
+ context: TextAnchorResourceResolverContext,
257
+ ): Promise<readonly string[] | undefined>;
258
+ editText<Result>(
259
+ source: string,
260
+ context: ResourceResolverContext,
261
+ operation: (
262
+ text: string,
263
+ resolveAnchor: ResolveTextAnchor,
264
+ ) => TextMutationResult<Result> | Promise<TextMutationResult<Result>>,
265
+ ): Promise<TextResourceEditOutcome<Result>>;
266
+ editTexts<Result>(
267
+ sources: readonly TextResourceEditRequest[],
268
+ context: TextResourcesEditContext,
269
+ operation: (
270
+ texts: ReadonlyMap<string, string>,
271
+ resolveAnchor: ResolveResourceTextAnchor,
272
+ ) => TextResourcesMutationResult<Result> | Promise<TextResourcesMutationResult<Result>>,
273
+ ): Promise<TextResourcesEditOutcome<Result>>;
274
+ previewTexts(
275
+ sources: readonly TextResourceEditRequest[],
276
+ context: ResourceResolverContext,
277
+ operation: (
278
+ texts: ReadonlyMap<string, string>,
279
+ resolveAnchor: ResolveResourceTextAnchor,
280
+ ) => TextResourcesMutationResult<unknown> | Promise<TextResourcesMutationResult<unknown>>,
281
+ ): Promise<TextMutationPreviewOutcome>;
282
+ executeEdit<Input, Result>(
283
+ tool: TextEditorToolId,
284
+ initialState: TextPreEditState<Input>,
285
+ operation: (state: TextPreEditState<Input>) => Result | Promise<Result>,
286
+ ): Promise<TextEditExecutionOutcome<Input, Result>>;
287
+ addMutationTool(registration: AnyTextMutationToolRegistration): void;
288
+ getMutationTools(): readonly AnyTextMutationToolRegistration[];
289
+ onMutationTool(listener: TextMutationToolListener): () => void;
290
+ onDidEdit(listener: TextEditCompletionListener): () => void;
291
+ getToolRenderer(tool: TextEditorToolId): TextEditorToolRendererRegistration | undefined;
292
+ registerPlugin(plugin: TextEditorPlugin): Promise<void>;
293
+ registerPostEditHandler(registration: TextPostEditHandlerRegistration): () => void;
294
+ registerTool(tool: TextEditorToolId): void;
295
+ waitForPendingPlugins(): Promise<void>;
296
+ renderGeneralPromptGuideline(): string | undefined;
297
+ renderToolPromptGuideline(tool: TextEditorToolId): string | undefined;
289
298
  }
290
299
 
291
300
  export function createTextEditorCore(
292
- registerMutationTool?: (registration: AnyTextMutationToolRegistration, core: TextEditorCore) => void,
293
- ): TextEditorCore
294
- {
295
- const resolvers: RegisteredResolver[] = [];
296
- const anchorRegistry = new TextAnchorRegistry();
297
- const handlers: RegisteredHandler[] = [];
298
- const presenters: RegisteredPresenter[] = [];
299
- const postEditHandlers = new Map<string, TextPostEditHandlerRegistration>();
300
- const pendingPlugins = new Set<Promise<void>>();
301
- const plugins = new Map<string, RegisteredPlugin>();
302
- const promptContributions: PromptContribution[] = [];
303
- const writablePromptContributions: WritablePromptContribution[] = [];
304
- const registeredTools = new Set<TextEditorToolId>();
305
- const mutationTools = new Map<string, AnyTextMutationToolRegistration>();
306
- const mutationListeners = new Set<TextMutationToolListener>();
307
- const editCompletionListeners = new Set<TextEditCompletionListener>();
308
- const mutationGuards: TextMutationGuardRegistration[] = [];
309
- const toolRenderers = new Map<TextEditorToolId, TextEditorToolRendererRegistration>();
310
- let registrationQueue = Promise.resolve();
311
- const registerContributions = (draft: PluginContributionDraft): void =>
312
- {
313
- validateContributionDraft(
314
- draft,
315
- resolvers,
316
- handlers,
317
- promptContributions,
318
- writablePromptContributions,
319
- );
301
+ registerMutationTool?: (
302
+ registration: AnyTextMutationToolRegistration,
303
+ core: TextEditorCore,
304
+ ) => void,
305
+ ): TextEditorCore {
306
+ const resolvers: RegisteredResolver[] = [];
307
+ const anchorRegistry = new TextAnchorRegistry();
308
+ const handlers: RegisteredHandler[] = [];
309
+ const presenters: RegisteredPresenter[] = [];
310
+ const postEditHandlers = new Map<string, TextPostEditHandlerRegistration>();
311
+ const pendingPlugins = new Set<Promise<void>>();
312
+ const plugins = new Map<string, RegisteredPlugin>();
313
+ const promptContributions: PromptContribution[] = [];
314
+ const writablePromptContributions: WritablePromptContribution[] = [];
315
+ const registeredTools = new Set<TextEditorToolId>();
316
+ const mutationTools = new Map<string, AnyTextMutationToolRegistration>();
317
+ const mutationListeners = new Set<TextMutationToolListener>();
318
+ const editCompletionListeners = new Set<TextEditCompletionListener>();
319
+ const mutationGuards: TextMutationGuardRegistration[] = [];
320
+ const toolRenderers = new Map<TextEditorToolId, TextEditorToolRendererRegistration>();
321
+ let registrationQueue = Promise.resolve();
322
+ const registerContributions = (draft: PluginContributionDraft): void => {
323
+ validateContributionDraft(
324
+ draft,
325
+ resolvers,
326
+ handlers,
327
+ promptContributions,
328
+ writablePromptContributions,
329
+ );
320
330
 
321
- const incomingMutationNames = new Set<string>();
331
+ const incomingMutationNames = new Set<string>();
322
332
 
323
- for (const registration of draft.mutationTools ?? [])
324
- {
325
- assertTextMutationToolRegistration(registration);
333
+ for (const registration of draft.mutationTools ?? []) {
334
+ assertTextMutationToolRegistration(registration);
326
335
 
327
- if (mutationTools.has(registration.name) || incomingMutationNames.has(registration.name))
328
- {
329
- throw new Error(`Mutation tool ${registration.name} is already registered`);
330
- }
336
+ if (mutationTools.has(registration.name) || incomingMutationNames.has(registration.name)) {
337
+ throw new Error(`Mutation tool ${registration.name} is already registered`);
338
+ }
331
339
 
332
- incomingMutationNames.add(registration.name);
333
- }
340
+ incomingMutationNames.add(registration.name);
341
+ }
334
342
 
335
- for (const registration of draft.toolRenderers ?? [])
336
- {
337
- if (!isTextEditorToolRendererRegistration(registration))
338
- {
339
- throw new TypeError("Plugin provided an invalid text editor tool renderer");
340
- }
341
- }
343
+ for (const registration of draft.toolRenderers ?? []) {
344
+ if (!isTextEditorToolRendererRegistration(registration)) {
345
+ throw new TypeError("Plugin provided an invalid text editor tool renderer");
346
+ }
347
+ }
342
348
 
343
- anchorRegistry.assertCanAdd(draft.anchorResolvers.map(({ registration }) => registration));
344
- const incomingPresenters = draft.presenters ?? [];
345
- const presenterIds = new Set(presenters.map(({ registration }) => registration.presenter.id));
349
+ anchorRegistry.assertCanAdd(draft.anchorResolvers.map(({ registration }) => registration));
350
+ const incomingPresenters = draft.presenters ?? [];
351
+ const presenterIds = new Set(presenters.map(({ registration }) => registration.presenter.id));
346
352
 
347
- for (const contribution of incomingPresenters)
348
- {
349
- if (!isTextPresenterRegistration(contribution.registration))
350
- {
351
- throw new TypeError(`Plugin ${contribution.pluginId} provided an invalid text presenter`);
352
- }
353
+ for (const contribution of incomingPresenters) {
354
+ if (!isTextPresenterRegistration(contribution.registration)) {
355
+ throw new TypeError(`Plugin ${contribution.pluginId} provided an invalid text presenter`);
356
+ }
353
357
 
354
- if (presenterIds.has(contribution.registration.presenter.id))
355
- {
356
- throw new Error(`Text presenter ${contribution.registration.presenter.id} is already registered`);
357
- }
358
+ if (presenterIds.has(contribution.registration.presenter.id)) {
359
+ throw new Error(
360
+ `Text presenter ${contribution.registration.presenter.id} is already registered`,
361
+ );
362
+ }
358
363
 
359
- presenterIds.add(contribution.registration.presenter.id);
360
- }
364
+ presenterIds.add(contribution.registration.presenter.id);
365
+ }
361
366
 
362
- for (const contribution of draft.resolvers)
363
- {
364
- resolvers.push({
365
- resolver: contribution.registration.resolver,
366
- priority: contribution.registration.priority ?? 0,
367
- order: resolvers.length,
368
- });
369
- }
367
+ for (const contribution of draft.resolvers) {
368
+ resolvers.push({
369
+ resolver: contribution.registration.resolver,
370
+ priority: contribution.registration.priority ?? 0,
371
+ order: resolvers.length,
372
+ });
373
+ }
370
374
 
371
- for (const contribution of draft.anchorResolvers)
372
- {
373
- anchorRegistry.add(contribution.registration);
374
- }
375
+ for (const contribution of draft.anchorResolvers) {
376
+ anchorRegistry.add(contribution.registration);
377
+ }
375
378
 
376
- for (const contribution of incomingPresenters)
377
- {
378
- presenters.push({ ...contribution, order: presenters.length });
379
- }
379
+ for (const contribution of incomingPresenters) {
380
+ presenters.push({ ...contribution, order: presenters.length });
381
+ }
380
382
 
381
- handlers.push(...draft.handlers);
382
- mutationGuards.push(...(draft.mutationGuards ?? []));
383
- promptContributions.push(...draft.promptContributions);
384
- writablePromptContributions.push(...draft.writablePromptContributions);
383
+ handlers.push(...draft.handlers);
384
+ mutationGuards.push(...(draft.mutationGuards ?? []));
385
+ promptContributions.push(...draft.promptContributions);
386
+ writablePromptContributions.push(...draft.writablePromptContributions);
385
387
 
386
- for (const registration of draft.toolRenderers ?? [])
387
- {
388
- const current = toolRenderers.get(registration.tool);
389
- toolRenderers.set(registration.tool, mergeToolRenderer(current, registration));
390
- }
388
+ for (const registration of draft.toolRenderers ?? []) {
389
+ const current = toolRenderers.get(registration.tool);
390
+ toolRenderers.set(registration.tool, mergeToolRenderer(current, registration));
391
+ }
391
392
 
392
- for (const tool of draft.tools)
393
- {
394
- registeredTools.add(tool);
395
- }
393
+ for (const tool of draft.tools) {
394
+ registeredTools.add(tool);
395
+ }
396
396
 
397
- for (const registration of draft.mutationTools ?? [])
398
- {
399
- addMutationRegistration(
400
- registration,
401
- mutationTools,
402
- registeredTools,
403
- mutationListeners,
404
- registerMutationTool,
405
- core,
406
- );
407
- }
397
+ for (const registration of draft.mutationTools ?? []) {
398
+ addMutationRegistration(
399
+ registration,
400
+ mutationTools,
401
+ registeredTools,
402
+ mutationListeners,
403
+ registerMutationTool,
404
+ core,
405
+ );
406
+ }
408
407
 
409
- for (const listener of draft.mutationToolListeners ?? [])
410
- {
411
- replayMutationTools(listener, mutationTools);
412
- mutationListeners.add(listener);
413
- }
408
+ for (const listener of draft.mutationToolListeners ?? []) {
409
+ replayMutationTools(listener, mutationTools);
410
+ mutationListeners.add(listener);
411
+ }
414
412
 
415
- for (const listener of draft.editCompletionListeners ?? [])
416
- {
417
- editCompletionListeners.add(listener);
418
- }
419
- };
413
+ for (const listener of draft.editCompletionListeners ?? []) {
414
+ editCompletionListeners.add(listener);
415
+ }
416
+ };
417
+
418
+ const core: TextEditorCore = {
419
+ addAnchorResolver(registration): void {
420
+ if (!isTextAnchorResolverRegistration(registration)) {
421
+ throw new TypeError("Invalid text anchor resolver");
422
+ }
423
+
424
+ anchorRegistry.add(registration);
425
+ },
426
+ addMutationTool(registration): void {
427
+ addMutationRegistration(
428
+ registration,
429
+ mutationTools,
430
+ registeredTools,
431
+ mutationListeners,
432
+ registerMutationTool,
433
+ core,
434
+ );
435
+ },
436
+ getMutationTools(): readonly AnyTextMutationToolRegistration[] {
437
+ return [...mutationTools.values()];
438
+ },
439
+ onMutationTool(listener): () => void {
440
+ replayMutationTools(listener, mutationTools);
441
+ mutationListeners.add(listener);
442
+ return () => mutationListeners.delete(listener);
443
+ },
444
+ onDidEdit(listener): () => void {
445
+ editCompletionListeners.add(listener);
446
+ return () => editCompletionListeners.delete(listener);
447
+ },
448
+ getToolRenderer(tool): TextEditorToolRendererRegistration | undefined {
449
+ return toolRenderers.get(tool);
450
+ },
451
+ inspectTextAnchors(request): Promise<TextAnchorInspectionOutcome> {
452
+ return inspectTextResource(request, [...resolvers], anchorRegistry.snapshot());
453
+ },
454
+ resolveTextAnchorResources(value, kinds, context): Promise<readonly string[] | undefined> {
455
+ return anchorRegistry.snapshot().resolveResources(value, context, new Set(kinds));
456
+ },
457
+ editText<Result>(
458
+ source: string,
459
+ context: ResourceResolverContext,
460
+ operation: (
461
+ text: string,
462
+ resolveAnchor: ResolveTextAnchor,
463
+ ) => TextMutationResult<Result> | Promise<TextMutationResult<Result>>,
464
+ ): Promise<TextResourceEditOutcome<Result>> {
465
+ const resolverSnapshot = [...resolvers].sort(
466
+ (left, right) => left.priority - right.priority || left.order - right.order,
467
+ );
468
+ const presenterSnapshot = [...presenters].sort(
469
+ (left, right) =>
470
+ (left.registration.priority ?? 0) - (right.registration.priority ?? 0) ||
471
+ left.order - right.order,
472
+ );
473
+ return editTextResource(
474
+ source,
475
+ context,
476
+ resolverSnapshot,
477
+ anchorRegistry.snapshot(),
478
+ presenterSnapshot,
479
+ [...postEditHandlers.values()],
480
+ [...editCompletionListeners],
481
+ operation,
482
+ );
483
+ },
484
+ editTexts<Result>(
485
+ sources: readonly TextResourceEditRequest[],
486
+ context: TextResourcesEditContext,
487
+ operation: (
488
+ texts: ReadonlyMap<string, string>,
489
+ resolveAnchor: ResolveResourceTextAnchor,
490
+ ) => TextResourcesMutationResult<Result> | Promise<TextResourcesMutationResult<Result>>,
491
+ ): Promise<TextResourcesEditOutcome<Result>> {
492
+ const resolverSnapshot = [...resolvers].sort(
493
+ (left, right) => left.priority - right.priority || left.order - right.order,
494
+ );
495
+ const presenterSnapshot = [...presenters].sort(
496
+ (left, right) =>
497
+ (left.registration.priority ?? 0) - (right.registration.priority ?? 0) ||
498
+ left.order - right.order,
499
+ );
500
+ return editTextResources(
501
+ sources,
502
+ context,
503
+ resolverSnapshot,
504
+ anchorRegistry.snapshot(),
505
+ presenterSnapshot,
506
+ [...postEditHandlers.values()],
507
+ [...editCompletionListeners],
508
+ [...mutationGuards],
509
+ operation,
510
+ );
511
+ },
512
+ previewTexts(sources, context, operation): Promise<TextMutationPreviewOutcome> {
513
+ const resolverSnapshot = [...resolvers].sort(
514
+ (left, right) => left.priority - right.priority || left.order - right.order,
515
+ );
516
+ return previewTextResources(
517
+ sources,
518
+ context,
519
+ resolverSnapshot,
520
+ anchorRegistry.snapshot(),
521
+ operation,
522
+ );
523
+ },
524
+ async executeEdit<Input, Result>(
525
+ tool: TextEditorToolId,
526
+ initialState: TextPreEditState<Input>,
527
+ operation: (state: TextPreEditState<Input>) => Result | Promise<Result>,
528
+ ): Promise<TextEditExecutionOutcome<Input, Result>> {
529
+ if (!isTextEditorToolId(tool)) {
530
+ throw new Error(`Unsupported text editor tool ${String(tool)}`);
531
+ }
532
+
533
+ const invocationHandlers = handlers.filter((registered) => registered.tool === tool);
534
+ const preEdit = await runPreEditHandlers(initialState, invocationHandlers, tool);
535
+
536
+ if (preEdit.kind === "failed") {
537
+ return preEdit;
538
+ }
539
+
540
+ const result = await operation(preEdit.state);
541
+ const editState: TextEditState<Input, Result> = {
542
+ ...preEdit.state,
543
+ result,
544
+ };
545
+ const edit = await runResultHandlers("text-edit", editState, invocationHandlers, tool);
546
+
547
+ if (edit.kind === "failed") {
548
+ return edit;
549
+ }
550
+
551
+ const postEdit = await runResultHandlers(
552
+ "text-post-edit",
553
+ edit.state,
554
+ invocationHandlers,
555
+ tool,
556
+ );
557
+
558
+ if (postEdit.kind === "failed") {
559
+ return postEdit;
560
+ }
561
+
562
+ return { kind: "completed", state: postEdit.state };
563
+ },
564
+ registerPostEditHandler(registration): () => void {
565
+ if (!isTextPostEditHandlerRegistration(registration)) {
566
+ throw new TypeError("Invalid text editor post-edit handler registration");
567
+ }
568
+
569
+ if (postEditHandlers.has(registration.id)) {
570
+ throw new Error(`Post-edit handler ${registration.id} is already registered`);
571
+ }
572
+
573
+ postEditHandlers.set(registration.id, registration);
574
+ return () => {
575
+ if (postEditHandlers.get(registration.id) === registration) {
576
+ postEditHandlers.delete(registration.id);
577
+ }
578
+ };
579
+ },
580
+ registerTool(tool): void {
581
+ if (!isTextEditorToolId(tool)) {
582
+ throw new TypeError("Invalid text editor tool ID");
583
+ }
584
+
585
+ registeredTools.add(tool);
586
+ },
587
+ registerPlugin(plugin): Promise<void> {
588
+ const validationError = getPluginValidationError(plugin);
589
+
590
+ if (validationError !== undefined) {
591
+ return Promise.reject(validationError);
592
+ }
593
+
594
+ const existing = plugins.get(plugin.id);
595
+
596
+ if (existing?.plugin === plugin) {
597
+ return existing.ready;
598
+ }
599
+
600
+ if (existing !== undefined) {
601
+ return Promise.reject(new Error(`Plugin ${plugin.id} is already registered`));
602
+ }
603
+
604
+ const lifecycle: PluginLifecycle = { status: "pending" };
605
+ const contributions = createPluginContributionController(
606
+ plugin.id,
607
+ registerContributions,
608
+ (request) => inspectTextResource(request, [...resolvers], anchorRegistry.snapshot()),
609
+ (listener) => core.onMutationTool(listener),
610
+ (listener) => core.onDidEdit(listener),
611
+ (request) => previewTextMutation(core, request),
612
+ );
613
+ const ready = registrationQueue.then(async () => {
614
+ try {
615
+ await plugin.setup(contributions.api);
616
+ contributions.commit();
617
+ lifecycle.status = "active";
618
+ return;
619
+ } catch (error) {
620
+ contributions.close();
621
+ throw error;
622
+ }
623
+ });
624
+ const registeredPlugin: RegisteredPlugin = { lifecycle, plugin, ready };
625
+
626
+ plugins.set(plugin.id, registeredPlugin);
627
+ pendingPlugins.add(ready);
628
+ registrationQueue = ready.catch(() => {});
629
+ void ready.then(
630
+ () => {
631
+ pendingPlugins.delete(ready);
632
+ return;
633
+ },
634
+ () => {
635
+ pendingPlugins.delete(ready);
420
636
 
421
- const core: TextEditorCore = {
422
- addAnchorResolver(registration): void
423
- {
424
- if (!isTextAnchorResolverRegistration(registration))
425
- {
426
- throw new TypeError("Invalid text anchor resolver");
427
- }
637
+ if (plugins.get(plugin.id) === registeredPlugin) {
638
+ plugins.delete(plugin.id);
639
+ }
428
640
 
429
- anchorRegistry.add(registration);
430
- },
431
- addMutationTool(registration): void
432
- {
433
- addMutationRegistration(
434
- registration,
435
- mutationTools,
436
- registeredTools,
437
- mutationListeners,
438
- registerMutationTool,
439
- core,
440
- );
441
- },
442
- getMutationTools(): readonly AnyTextMutationToolRegistration[]
443
- {
444
- return [...mutationTools.values()];
445
- },
446
- onMutationTool(listener): () => void
447
- {
448
- replayMutationTools(listener, mutationTools);
449
- mutationListeners.add(listener);
450
- return () => mutationListeners.delete(listener);
451
- },
452
- onDidEdit(listener): () => void
453
- {
454
- editCompletionListeners.add(listener);
455
- return () => editCompletionListeners.delete(listener);
641
+ return;
456
642
  },
457
- getToolRenderer(tool): TextEditorToolRendererRegistration | undefined
458
- {
459
- return toolRenderers.get(tool);
460
- },
461
- inspectTextAnchors(request): Promise<TextAnchorInspectionOutcome>
462
- {
463
- return inspectTextResource(request, [...resolvers], anchorRegistry.snapshot());
464
- },
465
- resolveTextAnchorResources(value, kinds, context): Promise<readonly string[] | undefined>
466
- {
467
- return anchorRegistry.snapshot().resolveResources(value, context, new Set(kinds));
468
- },
469
- editText<Result>(
470
- source: string,
471
- context: ResourceResolverContext,
472
- operation: (
473
- text: string,
474
- resolveAnchor: ResolveTextAnchor,
475
- ) => TextMutationResult<Result> | Promise<TextMutationResult<Result>>,
476
- ): Promise<TextResourceEditOutcome<Result>>
477
- {
478
- const resolverSnapshot = [...resolvers].sort((left, right) =>
479
- left.priority - right.priority || left.order - right.order
480
- );
481
- const presenterSnapshot = [...presenters].sort((left, right) =>
482
- (left.registration.priority ?? 0) - (right.registration.priority ?? 0) || left.order - right.order
483
- );
484
- return editTextResource(
485
- source,
486
- context,
487
- resolverSnapshot,
488
- anchorRegistry.snapshot(),
489
- presenterSnapshot,
490
- [...postEditHandlers.values()],
491
- [...editCompletionListeners],
492
- operation,
493
- );
494
- },
495
- editTexts<Result>(
496
- sources: readonly TextResourceEditRequest[],
497
- context: TextResourcesEditContext,
498
- operation: (
499
- texts: ReadonlyMap<string, string>,
500
- resolveAnchor: ResolveResourceTextAnchor,
501
- ) => TextResourcesMutationResult<Result> | Promise<TextResourcesMutationResult<Result>>,
502
- ): Promise<TextResourcesEditOutcome<Result>>
503
- {
504
- const resolverSnapshot = [...resolvers].sort((left, right) =>
505
- left.priority - right.priority || left.order - right.order
506
- );
507
- const presenterSnapshot = [...presenters].sort((left, right) =>
508
- (left.registration.priority ?? 0) - (right.registration.priority ?? 0) || left.order - right.order
509
- );
510
- return editTextResources(
511
- sources,
512
- context,
513
- resolverSnapshot,
514
- anchorRegistry.snapshot(),
515
- presenterSnapshot,
516
- [...postEditHandlers.values()],
517
- [...editCompletionListeners],
518
- [...mutationGuards],
519
- operation,
520
- );
521
- },
522
- previewTexts(sources, context, operation): Promise<TextMutationPreviewOutcome>
523
- {
524
- const resolverSnapshot = [...resolvers].sort((left, right) =>
525
- left.priority - right.priority || left.order - right.order
526
- );
527
- return previewTextResources(sources, context, resolverSnapshot, anchorRegistry.snapshot(), operation);
528
- },
529
- async executeEdit<Input, Result>(
530
- tool: TextEditorToolId,
531
- initialState: TextPreEditState<Input>,
532
- operation: (state: TextPreEditState<Input>) => Result | Promise<Result>,
533
- ): Promise<TextEditExecutionOutcome<Input, Result>>
534
- {
535
- if (!isTextEditorToolId(tool))
536
- {
537
- throw new Error(`Unsupported text editor tool ${String(tool)}`);
538
- }
643
+ );
539
644
 
540
- const invocationHandlers = handlers.filter((registered) => registered.tool === tool);
541
- const preEdit = await runPreEditHandlers(initialState, invocationHandlers, tool);
645
+ return ready;
646
+ },
647
+ renderGeneralPromptGuideline(): string | undefined {
648
+ const sections: string[] = [];
649
+ const writableEntries: string[] = [];
542
650
 
543
- if (preEdit.kind === "failed")
544
- {
545
- return preEdit;
546
- }
651
+ for (const registeredPlugin of plugins.values()) {
652
+ if (registeredPlugin.lifecycle.status !== "active") {
653
+ continue;
654
+ }
547
655
 
548
- const result = await operation(preEdit.state);
549
- const editState: TextEditState<Input, Result> = {
550
- ...preEdit.state,
551
- result,
552
- };
553
- const edit = await runResultHandlers("text-edit", editState, invocationHandlers, tool);
656
+ const contribution = writablePromptContributions.find(
657
+ (candidate) => candidate.pluginId === registeredPlugin.plugin.id,
658
+ );
554
659
 
555
- if (edit.kind === "failed")
556
- {
557
- return edit;
558
- }
660
+ if (contribution === undefined) {
661
+ continue;
662
+ }
559
663
 
560
- const postEdit = await runResultHandlers("text-post-edit", edit.state, invocationHandlers, tool);
664
+ const description = renderDescriptionSource(contribution.description);
561
665
 
562
- if (postEdit.kind === "failed")
563
- {
564
- return postEdit;
565
- }
666
+ if (description !== undefined) {
667
+ writableEntries.push(renderPromptEntry(registeredPlugin.plugin.id, description));
668
+ }
669
+ }
566
670
 
567
- return { kind: "completed", state: postEdit.state };
568
- },
569
- registerPostEditHandler(registration): () => void
570
- {
571
- if (!isTextPostEditHandlerRegistration(registration))
572
- {
573
- throw new TypeError("Invalid text editor post-edit handler registration");
574
- }
671
+ if (writableEntries.length > 0) {
672
+ sections.push(
673
+ ["Text edits support these writable resources:", ...writableEntries].join("\n"),
674
+ );
675
+ }
575
676
 
576
- if (postEditHandlers.has(registration.id))
577
- {
578
- throw new Error(`Post-edit handler ${registration.id} is already registered`);
579
- }
677
+ const anchorSection = anchorRegistry.renderPromptSection();
580
678
 
581
- postEditHandlers.set(registration.id, registration);
582
- return () =>
583
- {
584
- if (postEditHandlers.get(registration.id) === registration)
585
- {
586
- postEditHandlers.delete(registration.id);
587
- }
588
- };
589
- },
590
- registerTool(tool): void
591
- {
592
- if (!isTextEditorToolId(tool))
593
- {
594
- throw new TypeError("Invalid text editor tool ID");
595
- }
679
+ if (anchorSection !== undefined) {
680
+ sections.push(anchorSection);
681
+ }
596
682
 
597
- registeredTools.add(tool);
598
- },
599
- registerPlugin(plugin): Promise<void>
600
- {
601
- const validationError = getPluginValidationError(plugin);
683
+ return sections.length === 0 ? undefined : indentGuidelineContinuation(sections.join("\n\n"));
684
+ },
685
+ renderToolPromptGuideline(tool): string | undefined {
686
+ const entries: string[] = [];
602
687
 
603
- if (validationError !== undefined)
604
- {
605
- return Promise.reject(validationError);
606
- }
688
+ for (const registeredPlugin of plugins.values()) {
689
+ if (registeredPlugin.lifecycle.status !== "active") {
690
+ continue;
691
+ }
607
692
 
608
- const existing = plugins.get(plugin.id);
693
+ const contribution = promptContributions.find(
694
+ (candidate) =>
695
+ candidate.pluginId === registeredPlugin.plugin.id && candidate.tool === tool,
696
+ );
609
697
 
610
- if (existing?.plugin === plugin)
611
- {
612
- return existing.ready;
613
- }
698
+ if (contribution !== undefined) {
699
+ entries.push(renderPromptEntry(registeredPlugin.plugin.id, contribution.description));
700
+ }
701
+ }
614
702
 
615
- if (existing !== undefined)
616
- {
617
- return Promise.reject(new Error(`Plugin ${plugin.id} is already registered`));
618
- }
619
-
620
- const lifecycle: PluginLifecycle = { status: "pending" };
621
- const contributions = createPluginContributionController(
622
- plugin.id,
623
- registerContributions,
624
- (request) => inspectTextResource(request, [...resolvers], anchorRegistry.snapshot()),
625
- (listener) => core.onMutationTool(listener),
626
- (listener) => core.onDidEdit(listener),
627
- (request) => previewTextMutation(core, request),
628
- );
629
- const ready = registrationQueue.then(async () =>
630
- {
631
- try
632
- {
633
- await plugin.setup(contributions.api);
634
- contributions.commit();
635
- lifecycle.status = "active";
636
- return;
637
- }
638
- catch (error)
639
- {
640
- contributions.close();
641
- throw error;
642
- }
643
- });
644
- const registeredPlugin: RegisteredPlugin = { lifecycle, plugin, ready };
645
-
646
- plugins.set(plugin.id, registeredPlugin);
647
- pendingPlugins.add(ready);
648
- registrationQueue = ready.catch(() =>
649
- {});
650
- void ready.then(
651
- () =>
652
- {
653
- pendingPlugins.delete(ready);
654
- return;
655
- },
656
- () =>
657
- {
658
- pendingPlugins.delete(ready);
659
-
660
- if (plugins.get(plugin.id) === registeredPlugin)
661
- {
662
- plugins.delete(plugin.id);
663
- }
664
-
665
- return;
666
- },
667
- );
668
-
669
- return ready;
670
- },
671
- renderGeneralPromptGuideline(): string | undefined
672
- {
673
- const sections: string[] = [];
674
- const writableEntries: string[] = [];
703
+ return entries.length === 0
704
+ ? undefined
705
+ : indentGuidelineContinuation(
706
+ [`${tool} supports these installed extensions:`, ...entries].join("\n"),
707
+ );
708
+ },
709
+ async waitForPendingPlugins(): Promise<void> {
710
+ await Promise.all(pendingPlugins);
711
+ },
712
+ };
713
+
714
+ return core;
715
+ }
675
716
 
676
- for (const registeredPlugin of plugins.values())
677
- {
678
- if (registeredPlugin.lifecycle.status !== "active")
679
- {
680
- continue;
681
- }
717
+ async function inspectTextResource(
718
+ request: TextAnchorInspectionRequest,
719
+ resolvers: readonly RegisteredResolver[],
720
+ anchors: TextAnchorRegistrySnapshot,
721
+ ): Promise<TextAnchorInspectionOutcome> {
722
+ const context: ResourceResolverContext = {
723
+ cwd: request.cwd,
724
+ ...(request.signal !== undefined && { signal: request.signal }),
725
+ };
726
+
727
+ for (const { resolver } of [...resolvers].sort(
728
+ (left, right) => left.priority - right.priority || left.order - right.order,
729
+ )) {
730
+ let attempt: unknown;
731
+
732
+ try {
733
+ attempt = await resolver.tryResolve(request.source, context);
734
+ } catch (error) {
735
+ return { kind: "failed", reason: `Resolver ${resolver.id} failed`, cause: error };
736
+ }
682
737
 
683
- const contribution = writablePromptContributions.find((candidate) =>
684
- candidate.pluginId === registeredPlugin.plugin.id
685
- );
738
+ if (!isResourceResolutionAttempt(attempt)) {
739
+ return {
740
+ kind: "failed",
741
+ reason: `Resolver ${resolver.id} returned an invalid result`,
742
+ cause: attempt,
743
+ };
744
+ }
686
745
 
687
- if (contribution === undefined)
688
- {
689
- continue;
690
- }
746
+ if (attempt.kind === "not-handled") {
747
+ continue;
748
+ }
691
749
 
692
- const description = renderDescriptionSource(contribution.description);
750
+ if (attempt.kind === "failed") {
751
+ return { kind: "failed", reason: `Resolver ${resolver.id} failed`, cause: attempt.error };
752
+ }
693
753
 
694
- if (description !== undefined)
695
- {
696
- writableEntries.push(renderPromptEntry(registeredPlugin.plugin.id, description));
697
- }
698
- }
754
+ const { resource } = attempt;
699
755
 
700
- if (writableEntries.length > 0)
701
- {
702
- sections.push(["Text edits support these writable resources:", ...writableEntries].join("\n"));
703
- }
756
+ if (resource.read === undefined) {
757
+ return { kind: "failed", reason: `Resource ${resource.source} is not readable text` };
758
+ }
704
759
 
705
- const anchorSection = anchorRegistry.renderPromptSection();
760
+ let content: unknown;
706
761
 
707
- if (anchorSection !== undefined)
708
- {
709
- sections.push(anchorSection);
710
- }
762
+ try {
763
+ content = await resource.read(request.signal === undefined ? {} : { signal: request.signal });
764
+ } catch (error) {
765
+ return { kind: "failed", reason: `Unable to read ${resource.source}`, cause: error };
766
+ }
711
767
 
712
- return sections.length === 0 ? undefined : indentGuidelineContinuation(sections.join("\n\n"));
713
- },
714
- renderToolPromptGuideline(tool): string | undefined
715
- {
716
- const entries: string[] = [];
768
+ if (!isAgentContent(content) || content.length !== 1 || content[0].type !== "text") {
769
+ return {
770
+ kind: "failed",
771
+ reason: `Resource ${resource.source} is not readable text`,
772
+ cause: content,
773
+ };
774
+ }
717
775
 
718
- for (const registeredPlugin of plugins.values())
719
- {
720
- if (registeredPlugin.lifecycle.status !== "active")
721
- {
722
- continue;
723
- }
724
-
725
- const contribution = promptContributions.find((candidate) =>
726
- candidate.pluginId === registeredPlugin.plugin.id && candidate.tool === tool
727
- );
728
-
729
- if (contribution !== undefined)
730
- {
731
- entries.push(renderPromptEntry(registeredPlugin.plugin.id, contribution.description));
732
- }
733
- }
734
-
735
- return entries.length === 0
736
- ? undefined
737
- : indentGuidelineContinuation([`${tool} supports these installed extensions:`, ...entries].join("\n"));
738
- },
739
- async waitForPendingPlugins(): Promise<void>
740
- {
741
- await Promise.all(pendingPlugins);
742
- },
743
- };
776
+ return anchors.inspect(request.anchors, request.kinds, {
777
+ source: resource.source,
778
+ content: content[0].text,
779
+ lines: content[0].text.length === 0 ? [] : content[0].text.split(/\r?\n/u),
780
+ cwd: request.cwd,
781
+ ...(request.signal !== undefined && { signal: request.signal }),
782
+ });
783
+ }
744
784
 
745
- return core;
785
+ return { kind: "failed", reason: `No resolver handled ${request.source}` };
746
786
  }
747
787
 
748
- async function inspectTextResource(
749
- request: TextAnchorInspectionRequest,
750
- resolvers: readonly RegisteredResolver[],
751
- anchors: TextAnchorRegistrySnapshot,
752
- ): Promise<TextAnchorInspectionOutcome>
753
- {
754
- const context: ResourceResolverContext = {
755
- cwd: request.cwd,
756
- ...(request.signal === undefined ? {} : { signal: request.signal }),
757
- };
758
-
759
- for (
760
- const { resolver } of [...resolvers].sort((left, right) =>
761
- left.priority - right.priority || left.order - right.order
762
- )
763
- )
764
- {
765
- let attempt: unknown;
766
-
767
- try
768
- {
769
- attempt = await resolver.tryResolve(request.source, context);
770
- }
771
- catch (error)
772
- {
773
- return { kind: "failed", reason: `Resolver ${resolver.id} failed`, cause: error };
774
- }
775
-
776
- if (!isResourceResolutionAttempt(attempt))
777
- {
778
- return { kind: "failed", reason: `Resolver ${resolver.id} returned an invalid result`, cause: attempt };
779
- }
788
+ async function previewTextResources(
789
+ requests: readonly TextResourceEditRequest[],
790
+ context: ResourceResolverContext,
791
+ resolvers: readonly RegisteredResolver[],
792
+ anchorResolvers: TextAnchorRegistrySnapshot,
793
+ operation: (
794
+ texts: ReadonlyMap<string, string>,
795
+ resolveAnchor: ResolveResourceTextAnchor,
796
+ ) => TextResourcesMutationResult<unknown> | Promise<TextResourcesMutationResult<unknown>>,
797
+ ): Promise<TextMutationPreviewOutcome> {
798
+ try {
799
+ const requestBySource = new Map(requests.map((request) => [request.source, request]));
800
+ const sources = [...requestBySource.keys()];
780
801
 
781
- if (attempt.kind === "not-handled")
782
- {
783
- continue;
784
- }
802
+ if (sources.length === 0 || sources.some((source) => source.length === 0)) {
803
+ return { kind: "failed", reason: "No source was provided" };
804
+ }
785
805
 
786
- if (attempt.kind === "failed")
787
- {
788
- return { kind: "failed", reason: `Resolver ${resolver.id} failed`, cause: attempt.error };
789
- }
806
+ const prepared = new Map<string, PreparedTextResource>();
790
807
 
791
- const { resource } = attempt;
808
+ for (const source of sources) {
809
+ const request = requiredValue(requestBySource.get(source));
810
+ const outcome = await prepareTextResource(
811
+ source,
812
+ request.read,
813
+ request.allowReadFailure ?? false,
814
+ context,
815
+ resolvers,
816
+ );
817
+
818
+ if ("failure" in outcome) {
819
+ return { kind: "failed", reason: outcome.failure.message };
820
+ }
821
+
822
+ prepared.set(source, outcome);
823
+ }
792
824
 
793
- if (resource.read === undefined)
794
- {
795
- return { kind: "failed", reason: `Resource ${resource.source} is not readable text` };
796
- }
825
+ const texts = new Map([...prepared].map(([source, item]) => [source, item.before.content]));
826
+ const mutation = await operation(texts, (source, value, kinds) => {
827
+ const item = prepared.get(source);
828
+
829
+ if (item === undefined) {
830
+ throw new Error(`Anchor refers to undeclared resource ${source}`);
831
+ }
832
+
833
+ return anchorResolvers.resolve(
834
+ value,
835
+ item.anchorContext,
836
+ kinds === undefined ? undefined : new Set(kinds),
837
+ );
838
+ });
839
+ const resources = sources.map((source) => {
840
+ const item = requiredValue(prepared.get(source));
841
+ const changes = mutation.changes.get(source);
842
+ const applied =
843
+ changes === undefined
844
+ ? { content: item.before.content, changes: [] }
845
+ : applyTextChanges(item.before.content, changes);
846
+ return {
847
+ path: source,
848
+ existed: item.existed,
849
+ beforeRanges: applied.changes.map(({ fromBefore: from, toBefore: to }) => ({ from, to })),
850
+ ...(item.resource.link !== undefined && { link: item.resource.link }),
851
+ beforeContent: item.before.content,
852
+ afterContent: applied.content,
853
+ ranges: applied.changes.map(({ fromAfter: from, toAfter: to }) => ({ from, to })),
854
+ };
855
+ });
797
856
 
798
- let content: unknown;
857
+ return { kind: "completed", resources };
858
+ } catch (error) {
859
+ return { kind: "failed", reason: error instanceof Error ? error.message : String(error) };
860
+ }
861
+ }
799
862
 
800
- try
801
- {
802
- content = await resource.read(request.signal === undefined ? {} : { signal: request.signal });
803
- }
804
- catch (error)
805
- {
806
- return { kind: "failed", reason: `Unable to read ${resource.source}`, cause: error };
807
- }
863
+ interface PreparedTextResource {
864
+ readonly requestedSource: string;
865
+ readonly resource: Resource & { readonly write: ResourceWrite };
866
+ readonly resolverId: string;
867
+ readonly existed: boolean;
868
+ readonly before: TextDocument;
869
+ readonly anchorContext: TextAnchorResolverContext;
870
+ }
808
871
 
809
- if (!isAgentContent(content) || content.length !== 1 || content[0].type !== "text")
810
- {
811
- return { kind: "failed", reason: `Resource ${resource.source} is not readable text`, cause: content };
812
- }
872
+ async function editTextResources<Result>(
873
+ requests: readonly TextResourceEditRequest[],
874
+ context: TextResourcesEditContext,
875
+ resolvers: readonly RegisteredResolver[],
876
+ anchorResolvers: TextAnchorRegistrySnapshot,
877
+ presenters: readonly RegisteredPresenter[],
878
+ postEditHandlers: readonly TextPostEditHandlerRegistration[],
879
+ editCompletionListeners: readonly TextEditCompletionListener[],
880
+ mutationGuards: readonly TextMutationGuardRegistration[],
881
+ operation: (
882
+ texts: ReadonlyMap<string, string>,
883
+ resolveAnchor: ResolveResourceTextAnchor,
884
+ ) => TextResourcesMutationResult<Result> | Promise<TextResourcesMutationResult<Result>>,
885
+ ): Promise<TextResourcesEditOutcome<Result>> {
886
+ const requestBySource = new Map(requests.map((request) => [request.source, request]));
887
+ const sources = [...requestBySource.keys()];
888
+
889
+ if (sources.length === 0 || sources.some((source) => source.length === 0)) {
890
+ const source = sources.find((candidate) => candidate.length === 0) ?? "";
891
+ return {
892
+ kind: "failed",
893
+ failure: { code: "INVALID_REQUEST", source, message: "No source was provided" },
894
+ completed: [],
895
+ };
896
+ }
897
+
898
+ const prepared = new Map<string, PreparedTextResource>();
899
+
900
+ for (const source of sources) {
901
+ const request = requiredValue(requestBySource.get(source));
902
+ const outcome = await prepareTextResource(
903
+ source,
904
+ request.read,
905
+ request.allowReadFailure ?? false,
906
+ context,
907
+ resolvers,
908
+ );
813
909
 
814
- return anchors.inspect(request.anchors, request.kinds, {
815
- source: resource.source,
816
- content: content[0].text,
817
- lines: content[0].text.length === 0 ? [] : content[0].text.split(/\r?\n/u),
818
- cwd: request.cwd,
819
- ...(request.signal === undefined ? {} : { signal: request.signal }),
820
- });
910
+ if ("failure" in outcome) {
911
+ return { kind: "failed", failure: outcome.failure, completed: [] };
821
912
  }
822
913
 
823
- return { kind: "failed", reason: `No resolver handled ${request.source}` };
824
- }
914
+ prepared.set(source, outcome);
915
+ }
825
916
 
826
- async function previewTextResources(
827
- requests: readonly TextResourceEditRequest[],
828
- context: ResourceResolverContext,
829
- resolvers: readonly RegisteredResolver[],
830
- anchorResolvers: TextAnchorRegistrySnapshot,
831
- operation: (
832
- texts: ReadonlyMap<string, string>,
833
- resolveAnchor: ResolveResourceTextAnchor,
834
- ) => TextResourcesMutationResult<unknown> | Promise<TextResourcesMutationResult<unknown>>,
835
- ): Promise<TextMutationPreviewOutcome>
836
- {
837
- try
838
- {
839
- const requestBySource = new Map(requests.map((request) => [request.source, request]));
840
- const sources = [...requestBySource.keys()];
841
-
842
- if (sources.length === 0 || sources.some((source) => source.length === 0))
843
- {
844
- return { kind: "failed", reason: "No source was provided" };
845
- }
917
+ const texts = new Map([...prepared].map(([source, item]) => [source, item.before.content]));
918
+ const mutation = await operation(texts, (source, value, kinds) => {
919
+ const item = prepared.get(source);
846
920
 
847
- const prepared = new Map<string, PreparedTextResource>();
921
+ if (item === undefined) {
922
+ throw new Error(`Anchor refers to undeclared resource ${source}`);
923
+ }
848
924
 
849
- for (const source of sources)
850
- {
851
- const request = requestBySource.get(source)!;
852
- const outcome = await prepareTextResource(
853
- source,
854
- request.read,
855
- request.allowReadFailure ?? false,
856
- context,
857
- resolvers,
858
- );
925
+ return anchorResolvers.resolve(
926
+ value,
927
+ item.anchorContext,
928
+ kinds === undefined ? undefined : new Set(kinds),
929
+ );
930
+ });
859
931
 
860
- if ("failure" in outcome)
861
- {
862
- return { kind: "failed", reason: outcome.failure.message };
863
- }
932
+ for (const source of mutation.changes.keys()) {
933
+ if (!prepared.has(source)) {
934
+ return {
935
+ kind: "failed",
936
+ failure: {
937
+ code: "INVALID_WRITE_CONTENT",
938
+ source,
939
+ message: `Text edit produced an undeclared resource ${source}`,
940
+ },
941
+ completed: [],
942
+ };
943
+ }
944
+ }
864
945
 
865
- prepared.set(source, outcome);
866
- }
946
+ const applied = new Map<string, TextChangeResult>();
947
+
948
+ for (const [source, changes] of mutation.changes) {
949
+ const item = requiredValue(prepared.get(source));
950
+ applied.set(source, applyTextChanges(item.before.content, changes));
951
+ }
867
952
 
868
- const texts = new Map([...prepared].map(([source, item]) => [source, item.before.content]));
869
- const mutation = await operation(texts, (source, value, kinds) =>
870
- {
871
- const item = prepared.get(source);
953
+ const plan: TextMutationPlan = {
954
+ resources: sources.flatMap((source) => {
955
+ const item = requiredValue(prepared.get(source));
956
+ const result = applied.get(source);
872
957
 
873
- if (item === undefined)
958
+ return result === undefined || result.content === item.before.content
959
+ ? []
960
+ : [
874
961
  {
875
- throw new Error(`Anchor refers to undeclared resource ${source}`);
876
- }
962
+ source: item.resource.source,
963
+ existed: item.existed,
964
+ before: item.before,
965
+ after: createTextDocument(item.resource.source, result.content),
966
+ changes: result.changes,
967
+ },
968
+ ];
969
+ }),
970
+ };
877
971
 
878
- return anchorResolvers.resolve(value, item.anchorContext, kinds === undefined ? undefined : new Set(kinds));
879
- });
880
- const resources = sources.map((source) =>
881
- {
882
- const item = prepared.get(source)!;
883
- const changes = mutation.changes.get(source);
884
- const applied = changes === undefined
885
- ? { content: item.before.content, changes: [] }
886
- : applyTextChanges(item.before.content, changes);
887
- return {
888
- path: source,
889
- existed: item.existed,
890
- beforeRanges: applied.changes.map(({ fromBefore: from, toBefore: to }) => ({ from, to })),
891
- ...(item.resource.link === undefined ? {} : { link: item.resource.link }),
892
- beforeContent: item.before.content,
893
- afterContent: applied.content,
894
- ranges: applied.changes.map(({ fromAfter: from, toAfter: to }) => ({ from, to })),
895
- };
896
- });
972
+ for (const registration of mutationGuards) {
973
+ let outcome;
897
974
 
898
- return { kind: "completed", resources };
975
+ try {
976
+ outcome = await registration.guard(plan, context);
977
+ } catch (error) {
978
+ return {
979
+ kind: "failed",
980
+ failure: {
981
+ code: "PLUGIN_FAILED",
982
+ source: sources[0] ?? "",
983
+ message: `Mutation guard ${registration.id} failed`,
984
+ cause: error,
985
+ },
986
+ completed: [],
987
+ };
899
988
  }
900
- catch (error)
901
- {
902
- return { kind: "failed", reason: error instanceof Error ? error.message : String(error) };
989
+
990
+ if (outcome.kind === "rejected") {
991
+ return {
992
+ kind: "failed",
993
+ failure: {
994
+ code: "MUTATION_REJECTED",
995
+ source: plan.resources[0]?.source ?? sources[0] ?? "",
996
+ message: outcome.rejection.message,
997
+ },
998
+ completed: [],
999
+ };
903
1000
  }
904
- }
1001
+ }
905
1002
 
906
- interface PreparedTextResource
907
- {
908
- readonly requestedSource: string;
909
- readonly resource: Resource & { readonly write: ResourceWrite; };
910
- readonly resolverId: string;
911
- readonly existed: boolean;
912
- readonly before: TextDocument;
913
- readonly anchorContext: TextAnchorResolverContext;
914
- }
1003
+ const completed: string[] = [];
1004
+ const outcomes: Exclude<TextResourceEditOutcome<unknown>, { readonly kind: "failed" }>[] = [];
915
1005
 
916
- async function editTextResources<Result>(
917
- requests: readonly TextResourceEditRequest[],
918
- context: TextResourcesEditContext,
919
- resolvers: readonly RegisteredResolver[],
920
- anchorResolvers: TextAnchorRegistrySnapshot,
921
- presenters: readonly RegisteredPresenter[],
922
- postEditHandlers: readonly TextPostEditHandlerRegistration[],
923
- editCompletionListeners: readonly TextEditCompletionListener[],
924
- mutationGuards: readonly TextMutationGuardRegistration[],
925
- operation: (
926
- texts: ReadonlyMap<string, string>,
927
- resolveAnchor: ResolveResourceTextAnchor,
928
- ) => TextResourcesMutationResult<Result> | Promise<TextResourcesMutationResult<Result>>,
929
- ): Promise<TextResourcesEditOutcome<Result>>
930
- {
931
- const requestBySource = new Map(requests.map((request) => [request.source, request]));
932
- const sources = [...requestBySource.keys()];
1006
+ for (const source of sources) {
1007
+ const text = applied.get(source)?.content;
1008
+ const item = requiredValue(prepared.get(source));
933
1009
 
934
- if (sources.length === 0 || sources.some((source) => source.length === 0))
935
- {
936
- const source = sources.find((candidate) => candidate.length === 0) ?? "";
937
- return {
938
- kind: "failed",
939
- failure: { code: "INVALID_REQUEST", source, message: "No source was provided" },
940
- completed: [],
941
- };
1010
+ if (text === undefined || text === item.before.content) {
1011
+ continue;
942
1012
  }
943
1013
 
944
- const prepared = new Map<string, PreparedTextResource>();
945
-
946
- for (const source of sources)
947
- {
948
- const request = requestBySource.get(source)!;
949
- const outcome = await prepareTextResource(
950
- source,
951
- request.read,
952
- request.allowReadFailure ?? false,
953
- context,
954
- resolvers,
955
- );
956
-
957
- if ("failure" in outcome)
958
- {
959
- return { kind: "failed", failure: outcome.failure, completed: [] };
960
- }
1014
+ const finalContent: unknown = [{ type: "text", text }];
961
1015
 
962
- prepared.set(source, outcome);
1016
+ if (!isAgentContent(finalContent)) {
1017
+ return {
1018
+ kind: "failed",
1019
+ failure: {
1020
+ code: "INVALID_WRITE_CONTENT",
1021
+ source,
1022
+ message: `Text edit for ${source} produced invalid content`,
1023
+ },
1024
+ completed,
1025
+ };
963
1026
  }
964
1027
 
965
- const texts = new Map([...prepared].map(([source, item]) => [source, item.before.content]));
966
- const mutation = await operation(texts, (source, value, kinds) =>
967
- {
968
- const item = prepared.get(source);
1028
+ try {
1029
+ await item.resource.write(
1030
+ finalContent,
1031
+ context.signal === undefined ? {} : { signal: context.signal },
1032
+ );
1033
+ } catch (error) {
1034
+ return {
1035
+ kind: "failed",
1036
+ failure: {
1037
+ code: "WRITE_FAILED",
1038
+ source,
1039
+ resolverId: item.resolverId,
1040
+ message: `Unable to write ${source}`,
1041
+ cause: error,
1042
+ },
1043
+ completed,
1044
+ };
1045
+ }
969
1046
 
970
- if (item === undefined)
971
- {
972
- throw new Error(`Anchor refers to undeclared resource ${source}`);
973
- }
1047
+ completed.push(source);
1048
+ outcomes.push(
1049
+ await finalizeTextResource({
1050
+ requestedSource: item.requestedSource,
1051
+ outcomeSource: item.requestedSource,
1052
+ resource: item.resource,
1053
+ resolvedBy: item.resolverId,
1054
+ existed: item.existed,
1055
+ before: item.before,
1056
+ requestedText: text,
1057
+ context,
1058
+ presenters,
1059
+ postEditHandlers,
1060
+ editCompletionListeners,
1061
+ result: mutation.result,
1062
+ }),
1063
+ );
1064
+ }
974
1065
 
975
- return anchorResolvers.resolve(value, item.anchorContext, kinds === undefined ? undefined : new Set(kinds));
976
- });
1066
+ return { kind: "completed", resources: outcomes, result: mutation.result };
1067
+ }
977
1068
 
978
- for (const source of mutation.changes.keys())
979
- {
980
- if (!prepared.has(source))
981
- {
982
- return {
983
- kind: "failed",
984
- failure: {
985
- code: "INVALID_WRITE_CONTENT",
986
- source,
987
- message: `Text edit produced an undeclared resource ${source}`,
988
- },
989
- completed: [],
990
- };
991
- }
1069
+ async function prepareTextResource(
1070
+ source: string,
1071
+ read: boolean,
1072
+ allowReadFailure: boolean,
1073
+ context: ResourceResolverContext,
1074
+ resolvers: readonly RegisteredResolver[],
1075
+ ): Promise<PreparedTextResource | { readonly failure: TextResourceEditFailure }> {
1076
+ for (const { resolver } of resolvers) {
1077
+ let attempt: unknown;
1078
+
1079
+ try {
1080
+ attempt = await resolver.tryResolve(source, context);
1081
+ } catch (error) {
1082
+ return {
1083
+ failure: {
1084
+ code: "RESOLVE_FAILED",
1085
+ source,
1086
+ resolverId: resolver.id,
1087
+ message: `Resolver ${resolver.id} failed`,
1088
+ cause: error,
1089
+ },
1090
+ };
992
1091
  }
993
1092
 
994
- const applied = new Map<string, TextChangeResult>();
995
-
996
- for (const [source, changes] of mutation.changes)
997
- {
998
- const item = prepared.get(source)!;
999
- applied.set(source, applyTextChanges(item.before.content, changes));
1093
+ if (!isResourceResolutionAttempt(attempt)) {
1094
+ return {
1095
+ failure: {
1096
+ code: "INVALID_RESOLVER_RESULT",
1097
+ source,
1098
+ resolverId: resolver.id,
1099
+ message: `Resolver ${resolver.id} returned an invalid result`,
1100
+ cause: attempt,
1101
+ },
1102
+ };
1000
1103
  }
1001
1104
 
1002
- const plan: TextMutationPlan = {
1003
- resources: sources.flatMap((source) =>
1004
- {
1005
- const item = prepared.get(source)!;
1006
- const result = applied.get(source);
1007
-
1008
- return result === undefined || result.content === item.before.content
1009
- ? []
1010
- : [{
1011
- source: item.resource.source,
1012
- existed: item.existed,
1013
- before: item.before,
1014
- after: createTextDocument(item.resource.source, result.content),
1015
- changes: result.changes,
1016
- }];
1017
- }),
1018
- };
1019
-
1020
- for (const registration of mutationGuards)
1021
- {
1022
- let outcome;
1105
+ if (attempt.kind === "not-handled") {
1106
+ continue;
1107
+ }
1023
1108
 
1024
- try
1025
- {
1026
- outcome = await registration.guard(plan, context);
1027
- }
1028
- catch (error)
1029
- {
1030
- return {
1031
- kind: "failed",
1032
- failure: {
1033
- code: "PLUGIN_FAILED",
1034
- source: sources[0] ?? "",
1035
- message: `Mutation guard ${registration.id} failed`,
1036
- cause: error,
1037
- },
1038
- completed: [],
1039
- };
1040
- }
1109
+ if (attempt.kind === "failed") {
1110
+ return {
1111
+ failure: {
1112
+ code: "RESOLVE_FAILED",
1113
+ source,
1114
+ resolverId: resolver.id,
1115
+ message: `Resolver ${resolver.id} failed`,
1116
+ cause: attempt.error,
1117
+ },
1118
+ };
1119
+ }
1041
1120
 
1042
- if (outcome.kind === "rejected")
1043
- {
1044
- return {
1045
- kind: "failed",
1046
- failure: {
1047
- code: "MUTATION_REJECTED",
1048
- source: plan.resources[0]?.source ?? sources[0] ?? "",
1049
- message: outcome.rejection.message,
1050
- },
1051
- completed: [],
1052
- };
1053
- }
1121
+ if (attempt.resource.write === undefined || (read && attempt.resource.read === undefined)) {
1122
+ return {
1123
+ failure: {
1124
+ code: "UNSUPPORTED_CAPABILITY",
1125
+ source: attempt.resource.source,
1126
+ resolverId: resolver.id,
1127
+ message: `Resource ${attempt.resource.source} does not support text editing`,
1128
+ },
1129
+ };
1054
1130
  }
1055
1131
 
1056
- const completed: string[] = [];
1057
- const outcomes: Exclude<TextResourceEditOutcome<unknown>, { readonly kind: "failed"; }>[] = [];
1132
+ let text = "";
1133
+ let isExisted = read;
1058
1134
 
1059
- for (const source of sources)
1060
- {
1061
- const text = applied.get(source)?.content;
1062
- const item = prepared.get(source)!;
1135
+ if (read) {
1136
+ let content: unknown;
1063
1137
 
1064
- if (text === undefined || text === item.before.content)
1065
- {
1066
- continue;
1138
+ try {
1139
+ content = await requiredValue(attempt.resource.read)(
1140
+ context.signal === undefined ? {} : { signal: context.signal },
1141
+ );
1142
+ } catch (error) {
1143
+ if (!allowReadFailure) {
1144
+ return {
1145
+ failure: {
1146
+ code: "READ_FAILED",
1147
+ source: attempt.resource.source,
1148
+ resolverId: resolver.id,
1149
+ message: `Unable to read ${attempt.resource.source}`,
1150
+ cause: error,
1151
+ },
1152
+ };
1067
1153
  }
1068
1154
 
1069
- const finalContent: unknown = [{ type: "text", text }];
1070
-
1071
- if (!isAgentContent(finalContent))
1072
- {
1073
- return {
1074
- kind: "failed",
1075
- failure: {
1076
- code: "INVALID_WRITE_CONTENT",
1077
- source,
1078
- message: `Text edit for ${source} produced invalid content`,
1079
- },
1080
- completed,
1081
- };
1082
- }
1155
+ isExisted = false;
1156
+ content = [{ type: "text", text: "" }];
1157
+ }
1083
1158
 
1084
- try
1085
- {
1086
- await item.resource.write(finalContent, context.signal === undefined ? {} : { signal: context.signal });
1087
- }
1088
- catch (error)
1089
- {
1090
- return {
1091
- kind: "failed",
1092
- failure: {
1093
- code: "WRITE_FAILED",
1094
- source,
1095
- resolverId: item.resolverId,
1096
- message: `Unable to write ${source}`,
1097
- cause: error,
1098
- },
1099
- completed,
1100
- };
1101
- }
1159
+ if (!isAgentContent(content) || content.length !== 1 || content[0].type !== "text") {
1160
+ return {
1161
+ failure: {
1162
+ code: "UNSUPPORTED_CONTENT",
1163
+ source: attempt.resource.source,
1164
+ resolverId: resolver.id,
1165
+ message: `Resource ${attempt.resource.source} is not editable text`,
1166
+ cause: content,
1167
+ },
1168
+ };
1169
+ }
1102
1170
 
1103
- completed.push(source);
1104
- outcomes.push(
1105
- await finalizeTextResource({
1106
- requestedSource: item.requestedSource,
1107
- outcomeSource: item.requestedSource,
1108
- resource: item.resource,
1109
- resolvedBy: item.resolverId,
1110
- existed: item.existed,
1111
- before: item.before,
1112
- requestedText: text,
1113
- context,
1114
- presenters,
1115
- postEditHandlers,
1116
- editCompletionListeners,
1117
- result: mutation.result,
1118
- }),
1119
- );
1171
+ text = content[0].text;
1120
1172
  }
1121
1173
 
1122
- return { kind: "completed", resources: outcomes, result: mutation.result };
1123
- }
1174
+ const before = createTextDocument(attempt.resource.source, text);
1175
+ return {
1176
+ requestedSource: source,
1177
+ resource: attempt.resource,
1178
+ resolverId: resolver.id,
1179
+ existed: isExisted,
1180
+ before,
1181
+ anchorContext: {
1182
+ source: attempt.resource.source,
1183
+ content: before.content,
1184
+ lines: before.lines.map((line) => line.content),
1185
+ cwd: context.cwd,
1186
+ ...(context.signal !== undefined && { signal: context.signal }),
1187
+ },
1188
+ };
1189
+ }
1124
1190
 
1125
- async function prepareTextResource(
1126
- source: string,
1127
- read: boolean,
1128
- allowReadFailure: boolean,
1129
- context: ResourceResolverContext,
1130
- resolvers: readonly RegisteredResolver[],
1131
- ): Promise<PreparedTextResource | { readonly failure: TextResourceEditFailure; }>
1132
- {
1133
- for (const { resolver } of resolvers)
1134
- {
1135
- let attempt: unknown;
1136
-
1137
- try
1138
- {
1139
- attempt = await resolver.tryResolve(source, context);
1140
- }
1141
- catch (error)
1142
- {
1143
- return {
1144
- failure: {
1145
- code: "RESOLVE_FAILED",
1146
- source,
1147
- resolverId: resolver.id,
1148
- message: `Resolver ${resolver.id} failed`,
1149
- cause: error,
1150
- },
1151
- };
1152
- }
1191
+ return { failure: { code: "NO_RESOLVER", source, message: `No resolver handled ${source}` } };
1192
+ }
1153
1193
 
1154
- if (!isResourceResolutionAttempt(attempt))
1155
- {
1156
- return {
1157
- failure: {
1158
- code: "INVALID_RESOLVER_RESULT",
1159
- source,
1160
- resolverId: resolver.id,
1161
- message: `Resolver ${resolver.id} returned an invalid result`,
1162
- cause: attempt,
1163
- },
1164
- };
1165
- }
1194
+ interface FinalizeTextResourceRequest<Result> {
1195
+ readonly requestedSource: string;
1196
+ readonly outcomeSource: string;
1197
+ readonly resource: Resource;
1198
+ readonly resolvedBy: string;
1199
+ readonly existed: boolean;
1200
+ readonly before: TextDocument;
1201
+ readonly requestedText: string;
1202
+ readonly context: ResourceResolverContext & { readonly intent?: TextEditIntent };
1203
+ readonly presenters: readonly RegisteredPresenter[];
1204
+ readonly postEditHandlers: readonly TextPostEditHandlerRegistration[];
1205
+ readonly editCompletionListeners: readonly TextEditCompletionListener[];
1206
+ readonly result: Result;
1207
+ }
1166
1208
 
1167
- if (attempt.kind === "not-handled")
1168
- {
1169
- continue;
1170
- }
1209
+ async function finalizeTextResource<Result>(
1210
+ request: FinalizeTextResourceRequest<Result>,
1211
+ ): Promise<Exclude<TextResourceEditOutcome<Result>, { readonly kind: "failed" }>> {
1212
+ const requestedAfter = createTextDocument(request.resource.source, request.requestedText);
1213
+ const transaction: TextPostEditTransaction = {
1214
+ source: request.requestedSource,
1215
+ resourceSource: request.resource.source,
1216
+ resolvedBy: request.resolvedBy,
1217
+ cwd: request.context.cwd,
1218
+ before: request.before,
1219
+ requestedAfter,
1220
+ ...(request.context.signal !== undefined && { signal: request.context.signal }),
1221
+ };
1222
+ const postEditContributions: TextPostEditContribution[] = [];
1223
+
1224
+ for (const registration of request.postEditHandlers) {
1225
+ try {
1226
+ const data = await registration.handler(transaction);
1227
+
1228
+ if (data !== undefined) {
1229
+ postEditContributions.push({ id: registration.id, data });
1230
+ }
1231
+ } catch {
1232
+ // Post-edit integrations do not change a successful write into a failure.
1233
+ }
1234
+ }
1171
1235
 
1172
- if (attempt.kind === "failed")
1173
- {
1174
- return {
1175
- failure: {
1176
- code: "RESOLVE_FAILED",
1177
- source,
1178
- resolverId: resolver.id,
1179
- message: `Resolver ${resolver.id} failed`,
1180
- cause: attempt.error,
1181
- },
1182
- };
1183
- }
1236
+ let finalText = request.requestedText;
1184
1237
 
1185
- if (attempt.resource.write === undefined || (read && attempt.resource.read === undefined))
1186
- {
1187
- return {
1188
- failure: {
1189
- code: "UNSUPPORTED_CAPABILITY",
1190
- source: attempt.resource.source,
1191
- resolverId: resolver.id,
1192
- message: `Resource ${attempt.resource.source} does not support text editing`,
1193
- },
1194
- };
1195
- }
1238
+ if (request.resource.read !== undefined) {
1239
+ try {
1240
+ const reread = await request.resource.read(
1241
+ request.context.signal === undefined ? {} : { signal: request.context.signal },
1242
+ );
1196
1243
 
1197
- let text = "";
1198
- let existed = read;
1244
+ if (isAgentContent(reread) && reread.length === 1 && reread[0].type === "text") {
1245
+ finalText = reread[0].text;
1246
+ }
1247
+ } catch {
1248
+ // The requested mutation remains the successful fallback when a final reread fails.
1249
+ }
1250
+ }
1251
+
1252
+ const finalAfter = createTextDocument(request.resource.source, finalText);
1253
+ const completion: TextEditCompletion = {
1254
+ source: request.requestedSource,
1255
+ resourceSource: request.resource.source,
1256
+ resolvedBy: request.resolvedBy,
1257
+ cwd: request.context.cwd,
1258
+ existed: request.existed,
1259
+ before: request.before,
1260
+ after: finalAfter,
1261
+ intent: request.context.intent ?? "edit",
1262
+ };
1263
+
1264
+ for (const listener of request.editCompletionListeners) {
1265
+ try {
1266
+ await listener(completion);
1267
+ } catch {
1268
+ // Completion observers cannot turn a successful write into a failure.
1269
+ }
1270
+ }
1271
+
1272
+ let after = finalAfter;
1273
+ const presentationContext: TextPresentationContext = {
1274
+ purpose: "edit-diff",
1275
+ source: request.resource.source,
1276
+ cwd: request.context.cwd,
1277
+ resolvedBy: request.resolvedBy,
1278
+ ...(request.context.signal !== undefined && { signal: request.context.signal }),
1279
+ };
1280
+
1281
+ for (const { registration } of request.presenters) {
1282
+ after = await registration.presenter.present(after, presentationContext);
1283
+ }
1284
+
1285
+ return {
1286
+ kind: "completed",
1287
+ source: request.outcomeSource,
1288
+ resolvedBy: request.resolvedBy,
1289
+ before: request.before,
1290
+ after,
1291
+ result: request.result,
1292
+ postEditContributions,
1293
+ };
1294
+ }
1199
1295
 
1200
- if (read)
1201
- {
1202
- let content: unknown;
1203
-
1204
- try
1205
- {
1206
- content = await attempt.resource.read!(context.signal === undefined ? {} : { signal: context.signal });
1207
- }
1208
- catch (error)
1209
- {
1210
- if (!allowReadFailure)
1211
- {
1212
- return {
1213
- failure: {
1214
- code: "READ_FAILED",
1215
- source: attempt.resource.source,
1216
- resolverId: resolver.id,
1217
- message: `Unable to read ${attempt.resource.source}`,
1218
- cause: error,
1219
- },
1220
- };
1221
- }
1222
-
1223
- existed = false;
1224
- content = [{ type: "text", text: "" }];
1225
- }
1226
-
1227
- if (!isAgentContent(content) || content.length !== 1 || content[0].type !== "text")
1228
- {
1229
- return {
1230
- failure: {
1231
- code: "UNSUPPORTED_CONTENT",
1232
- source: attempt.resource.source,
1233
- resolverId: resolver.id,
1234
- message: `Resource ${attempt.resource.source} is not editable text`,
1235
- cause: content,
1236
- },
1237
- };
1238
- }
1239
-
1240
- text = content[0].text;
1241
- }
1242
-
1243
- const before = createTextDocument(attempt.resource.source, text);
1244
- return {
1245
- requestedSource: source,
1246
- resource: attempt.resource,
1247
- resolverId: resolver.id,
1248
- existed,
1249
- before,
1250
- anchorContext: {
1251
- source: attempt.resource.source,
1252
- content: before.content,
1253
- lines: before.lines.map((line) => line.content),
1254
- cwd: context.cwd,
1255
- ...(context.signal === undefined ? {} : { signal: context.signal }),
1256
- },
1257
- };
1258
- }
1259
-
1260
- return { failure: { code: "NO_RESOLVER", source, message: `No resolver handled ${source}` } };
1261
- }
1262
-
1263
- interface FinalizeTextResourceRequest<Result>
1264
- {
1265
- readonly requestedSource: string;
1266
- readonly outcomeSource: string;
1267
- readonly resource: Resource;
1268
- readonly resolvedBy: string;
1269
- readonly existed: boolean;
1270
- readonly before: TextDocument;
1271
- readonly requestedText: string;
1272
- readonly context: ResourceResolverContext & { readonly intent?: TextEditIntent; };
1273
- readonly presenters: readonly RegisteredPresenter[];
1274
- readonly postEditHandlers: readonly TextPostEditHandlerRegistration[];
1275
- readonly editCompletionListeners: readonly TextEditCompletionListener[];
1276
- readonly result: Result;
1277
- }
1278
-
1279
- async function finalizeTextResource<Result>(
1280
- request: FinalizeTextResourceRequest<Result>,
1281
- ): Promise<Exclude<TextResourceEditOutcome<Result>, { readonly kind: "failed"; }>>
1282
- {
1283
- const requestedAfter = createTextDocument(request.resource.source, request.requestedText);
1284
- const transaction: TextPostEditTransaction = {
1285
- source: request.requestedSource,
1286
- resourceSource: request.resource.source,
1287
- resolvedBy: request.resolvedBy,
1288
- cwd: request.context.cwd,
1289
- before: request.before,
1290
- requestedAfter,
1291
- ...(request.context.signal === undefined ? {} : { signal: request.context.signal }),
1296
+ async function editTextResource<Result>(
1297
+ source: string,
1298
+ context: ResourceResolverContext,
1299
+ resolvers: readonly RegisteredResolver[],
1300
+ anchorResolvers: TextAnchorRegistrySnapshot,
1301
+ presenters: readonly RegisteredPresenter[],
1302
+ postEditHandlers: readonly TextPostEditHandlerRegistration[],
1303
+ editCompletionListeners: readonly TextEditCompletionListener[],
1304
+ operation: (
1305
+ text: string,
1306
+ resolveAnchor: ResolveTextAnchor,
1307
+ ) => TextMutationResult<Result> | Promise<TextMutationResult<Result>>,
1308
+ ): Promise<TextResourceEditOutcome<Result>> {
1309
+ if (source.length === 0) {
1310
+ return {
1311
+ kind: "failed",
1312
+ failure: {
1313
+ code: "INVALID_REQUEST",
1314
+ source,
1315
+ message: "No source was provided",
1316
+ },
1292
1317
  };
1293
- const postEditContributions: TextPostEditContribution[] = [];
1318
+ }
1294
1319
 
1295
- for (const registration of request.postEditHandlers)
1296
- {
1297
- try
1298
- {
1299
- const data = await registration.handler(transaction);
1320
+ for (const { resolver } of resolvers) {
1321
+ let attempt: unknown;
1300
1322
 
1301
- if (data !== undefined)
1302
- {
1303
- postEditContributions.push({ id: registration.id, data });
1304
- }
1305
- }
1306
- catch
1307
- {
1308
- // Post-edit integrations do not change a successful write into a failure.
1309
- }
1323
+ try {
1324
+ attempt = await resolver.tryResolve(source, context);
1325
+ } catch (error) {
1326
+ return {
1327
+ kind: "failed",
1328
+ failure: {
1329
+ code: "RESOLVE_FAILED",
1330
+ source,
1331
+ resolverId: resolver.id,
1332
+ message: `Resolver ${resolver.id} failed`,
1333
+ cause: error,
1334
+ },
1335
+ };
1310
1336
  }
1311
1337
 
1312
- let finalText = request.requestedText;
1313
-
1314
- if (request.resource.read !== undefined)
1315
- {
1316
- try
1317
- {
1318
- const reread = await request.resource.read(
1319
- request.context.signal === undefined ? {} : { signal: request.context.signal },
1320
- );
1321
-
1322
- if (isAgentContent(reread) && reread.length === 1 && reread[0].type === "text")
1323
- {
1324
- finalText = reread[0].text;
1325
- }
1326
- }
1327
- catch
1328
- {
1329
- // The requested mutation remains the successful fallback when a final reread fails.
1330
- }
1338
+ if (!isResourceResolutionAttempt(attempt)) {
1339
+ return {
1340
+ kind: "failed",
1341
+ failure: {
1342
+ code: "INVALID_RESOLVER_RESULT",
1343
+ source,
1344
+ resolverId: resolver.id,
1345
+ message: `Resolver ${resolver.id} returned an invalid result`,
1346
+ cause: attempt,
1347
+ },
1348
+ };
1331
1349
  }
1332
1350
 
1333
- const finalAfter = createTextDocument(request.resource.source, finalText);
1334
- const completion: TextEditCompletion = {
1335
- source: request.requestedSource,
1336
- resourceSource: request.resource.source,
1337
- resolvedBy: request.resolvedBy,
1338
- cwd: request.context.cwd,
1339
- existed: request.existed,
1340
- before: request.before,
1341
- after: finalAfter,
1342
- intent: request.context.intent ?? "edit",
1343
- };
1344
-
1345
- for (const listener of request.editCompletionListeners)
1346
- {
1347
- try
1348
- {
1349
- await listener(completion);
1350
- }
1351
- catch
1352
- {
1353
- // Completion observers cannot turn a successful write into a failure.
1354
- }
1351
+ if (attempt.kind === "not-handled") {
1352
+ continue;
1355
1353
  }
1356
1354
 
1357
- let after = finalAfter;
1358
- const presentationContext: TextPresentationContext = {
1359
- purpose: "edit-diff",
1360
- source: request.resource.source,
1361
- cwd: request.context.cwd,
1362
- resolvedBy: request.resolvedBy,
1363
- ...(request.context.signal === undefined ? {} : { signal: request.context.signal }),
1364
- };
1365
-
1366
- for (const { registration } of request.presenters)
1367
- {
1368
- after = await registration.presenter.present(after, presentationContext);
1355
+ if (attempt.kind === "failed") {
1356
+ return {
1357
+ kind: "failed",
1358
+ failure: {
1359
+ code: "RESOLVE_FAILED",
1360
+ source,
1361
+ resolverId: resolver.id,
1362
+ message: `Resolver ${resolver.id} failed`,
1363
+ cause: attempt.error,
1364
+ },
1365
+ };
1369
1366
  }
1370
1367
 
1371
- return {
1372
- kind: "completed",
1373
- source: request.outcomeSource,
1374
- resolvedBy: request.resolvedBy,
1375
- before: request.before,
1376
- after,
1377
- result: request.result,
1378
- postEditContributions,
1379
- };
1380
- }
1368
+ const resource = attempt.resource;
1381
1369
 
1382
- async function editTextResource<Result>(
1383
- source: string,
1384
- context: ResourceResolverContext,
1385
- resolvers: readonly RegisteredResolver[],
1386
- anchorResolvers: TextAnchorRegistrySnapshot,
1387
- presenters: readonly RegisteredPresenter[],
1388
- postEditHandlers: readonly TextPostEditHandlerRegistration[],
1389
- editCompletionListeners: readonly TextEditCompletionListener[],
1390
- operation: (
1391
- text: string,
1392
- resolveAnchor: ResolveTextAnchor,
1393
- ) => TextMutationResult<Result> | Promise<TextMutationResult<Result>>,
1394
- ): Promise<TextResourceEditOutcome<Result>>
1395
- {
1396
- if (source.length === 0)
1397
- {
1398
- return {
1399
- kind: "failed",
1400
- failure: {
1401
- code: "INVALID_REQUEST",
1402
- source,
1403
- message: "No source was provided",
1404
- },
1405
- };
1370
+ if (resource.read === undefined || resource.write === undefined) {
1371
+ return {
1372
+ kind: "failed",
1373
+ failure: {
1374
+ code: "UNSUPPORTED_CAPABILITY",
1375
+ source: resource.source,
1376
+ resolverId: resolver.id,
1377
+ message: `Resource ${resource.source} does not support text editing`,
1378
+ },
1379
+ };
1406
1380
  }
1407
1381
 
1408
- for (const { resolver } of resolvers)
1409
- {
1410
- let attempt: unknown;
1411
-
1412
- try
1413
- {
1414
- attempt = await resolver.tryResolve(source, context);
1415
- }
1416
- catch (error)
1417
- {
1418
- return {
1419
- kind: "failed",
1420
- failure: {
1421
- code: "RESOLVE_FAILED",
1422
- source,
1423
- resolverId: resolver.id,
1424
- message: `Resolver ${resolver.id} failed`,
1425
- cause: error,
1426
- },
1427
- };
1428
- }
1429
-
1430
- if (!isResourceResolutionAttempt(attempt))
1431
- {
1432
- return {
1433
- kind: "failed",
1434
- failure: {
1435
- code: "INVALID_RESOLVER_RESULT",
1436
- source,
1437
- resolverId: resolver.id,
1438
- message: `Resolver ${resolver.id} returned an invalid result`,
1439
- cause: attempt,
1440
- },
1441
- };
1442
- }
1443
-
1444
- if (attempt.kind === "not-handled")
1445
- {
1446
- continue;
1447
- }
1448
-
1449
- if (attempt.kind === "failed")
1450
- {
1451
- return {
1452
- kind: "failed",
1453
- failure: {
1454
- code: "RESOLVE_FAILED",
1455
- source,
1456
- resolverId: resolver.id,
1457
- message: `Resolver ${resolver.id} failed`,
1458
- cause: attempt.error,
1459
- },
1460
- };
1461
- }
1462
-
1463
- const resource = attempt.resource;
1464
-
1465
- if (resource.read === undefined || resource.write === undefined)
1466
- {
1467
- return {
1468
- kind: "failed",
1469
- failure: {
1470
- code: "UNSUPPORTED_CAPABILITY",
1471
- source: resource.source,
1472
- resolverId: resolver.id,
1473
- message: `Resource ${resource.source} does not support text editing`,
1474
- },
1475
- };
1476
- }
1477
-
1478
- let content: unknown;
1382
+ let content: unknown;
1479
1383
 
1480
- try
1481
- {
1482
- content = await resource.read({
1483
- ...(context.signal === undefined ? {} : { signal: context.signal }),
1484
- });
1485
- }
1486
- catch (error)
1487
- {
1488
- return {
1489
- kind: "failed",
1490
- failure: {
1491
- code: "READ_FAILED",
1492
- source: resource.source,
1493
- resolverId: resolver.id,
1494
- message: `Unable to read ${resource.source}`,
1495
- cause: error,
1496
- },
1497
- };
1498
- }
1384
+ try {
1385
+ content = await resource.read({
1386
+ ...(context.signal !== undefined && { signal: context.signal }),
1387
+ });
1388
+ } catch (error) {
1389
+ return {
1390
+ kind: "failed",
1391
+ failure: {
1392
+ code: "READ_FAILED",
1393
+ source: resource.source,
1394
+ resolverId: resolver.id,
1395
+ message: `Unable to read ${resource.source}`,
1396
+ cause: error,
1397
+ },
1398
+ };
1399
+ }
1499
1400
 
1500
- if (!isAgentContent(content))
1501
- {
1502
- return {
1503
- kind: "failed",
1504
- failure: {
1505
- code: "INVALID_RESOURCE_CONTENT",
1506
- source: resource.source,
1507
- resolverId: resolver.id,
1508
- message: `Resource ${resource.source} returned invalid content`,
1509
- cause: content,
1510
- },
1511
- };
1512
- }
1401
+ if (!isAgentContent(content)) {
1402
+ return {
1403
+ kind: "failed",
1404
+ failure: {
1405
+ code: "INVALID_RESOURCE_CONTENT",
1406
+ source: resource.source,
1407
+ resolverId: resolver.id,
1408
+ message: `Resource ${resource.source} returned invalid content`,
1409
+ cause: content,
1410
+ },
1411
+ };
1412
+ }
1513
1413
 
1514
- const block = content[0];
1515
-
1516
- if (content.length !== 1 || block.type !== "text")
1517
- {
1518
- return {
1519
- kind: "failed",
1520
- failure: {
1521
- code: "UNSUPPORTED_CONTENT",
1522
- source: resource.source,
1523
- resolverId: resolver.id,
1524
- message: `Resource ${resource.source} is not editable text`,
1525
- },
1526
- };
1527
- }
1414
+ const block = content[0];
1528
1415
 
1529
- const before = createTextDocument(resource.source, block.text);
1530
- const anchorContext: TextAnchorResolverContext = {
1531
- source: resource.source,
1532
- content: before.content,
1533
- lines: before.lines.map((line) => line.content),
1534
- cwd: context.cwd,
1535
- ...(context.signal === undefined ? {} : { signal: context.signal }),
1536
- };
1537
- const mutation = await operation(
1538
- block.text,
1539
- (value, kinds) =>
1540
- anchorResolvers.resolve(
1541
- value,
1542
- anchorContext,
1543
- kinds === undefined ? undefined : new Set(kinds),
1544
- ),
1545
- );
1546
- const finalContent: unknown = [{ type: "text", text: mutation.text }];
1547
-
1548
- if (!isAgentContent(finalContent))
1549
- {
1550
- return {
1551
- kind: "failed",
1552
- failure: {
1553
- code: "INVALID_WRITE_CONTENT",
1554
- source: resource.source,
1555
- resolverId: resolver.id,
1556
- message: `Text edit for ${resource.source} produced invalid content`,
1557
- cause: mutation,
1558
- },
1559
- };
1560
- }
1416
+ if (content.length !== 1 || block.type !== "text") {
1417
+ return {
1418
+ kind: "failed",
1419
+ failure: {
1420
+ code: "UNSUPPORTED_CONTENT",
1421
+ source: resource.source,
1422
+ resolverId: resolver.id,
1423
+ message: `Resource ${resource.source} is not editable text`,
1424
+ },
1425
+ };
1426
+ }
1561
1427
 
1562
- try
1563
- {
1564
- await resource.write(finalContent, {
1565
- ...(context.signal === undefined ? {} : { signal: context.signal }),
1566
- });
1567
- }
1568
- catch (error)
1569
- {
1570
- return {
1571
- kind: "failed",
1572
- failure: {
1573
- code: "WRITE_FAILED",
1574
- source: resource.source,
1575
- resolverId: resolver.id,
1576
- message: `Unable to write ${resource.source}`,
1577
- cause: error,
1578
- },
1579
- };
1580
- }
1428
+ const before = createTextDocument(resource.source, block.text);
1429
+ const anchorContext: TextAnchorResolverContext = {
1430
+ source: resource.source,
1431
+ content: before.content,
1432
+ lines: before.lines.map((line) => line.content),
1433
+ cwd: context.cwd,
1434
+ ...(context.signal !== undefined && { signal: context.signal }),
1435
+ };
1436
+ const mutation = await operation(block.text, (value, kinds) =>
1437
+ anchorResolvers.resolve(
1438
+ value,
1439
+ anchorContext,
1440
+ kinds === undefined ? undefined : new Set(kinds),
1441
+ ),
1442
+ );
1443
+ const finalContent: unknown = [{ type: "text", text: mutation.text }];
1581
1444
 
1582
- return finalizeTextResource({
1583
- requestedSource: source,
1584
- outcomeSource: resource.source,
1585
- resource,
1586
- resolvedBy: resolver.id,
1587
- existed: true,
1588
- before,
1589
- requestedText: mutation.text,
1590
- context,
1591
- presenters,
1592
- postEditHandlers,
1593
- editCompletionListeners,
1594
- result: mutation.result,
1595
- });
1445
+ if (!isAgentContent(finalContent)) {
1446
+ return {
1447
+ kind: "failed",
1448
+ failure: {
1449
+ code: "INVALID_WRITE_CONTENT",
1450
+ source: resource.source,
1451
+ resolverId: resolver.id,
1452
+ message: `Text edit for ${resource.source} produced invalid content`,
1453
+ cause: mutation,
1454
+ },
1455
+ };
1596
1456
  }
1597
1457
 
1598
- return {
1458
+ try {
1459
+ await resource.write(finalContent, {
1460
+ ...(context.signal !== undefined && { signal: context.signal }),
1461
+ });
1462
+ } catch (error) {
1463
+ return {
1599
1464
  kind: "failed",
1600
1465
  failure: {
1601
- code: "NO_RESOLVER",
1602
- source,
1603
- message: `No resolver handled ${source}`,
1466
+ code: "WRITE_FAILED",
1467
+ source: resource.source,
1468
+ resolverId: resolver.id,
1469
+ message: `Unable to write ${resource.source}`,
1470
+ cause: error,
1604
1471
  },
1605
- };
1472
+ };
1473
+ }
1474
+
1475
+ return finalizeTextResource({
1476
+ requestedSource: source,
1477
+ outcomeSource: resource.source,
1478
+ resource,
1479
+ resolvedBy: resolver.id,
1480
+ existed: true,
1481
+ before,
1482
+ requestedText: mutation.text,
1483
+ context,
1484
+ presenters,
1485
+ postEditHandlers,
1486
+ editCompletionListeners,
1487
+ result: mutation.result,
1488
+ });
1489
+ }
1490
+
1491
+ return {
1492
+ kind: "failed",
1493
+ failure: {
1494
+ code: "NO_RESOLVER",
1495
+ source,
1496
+ message: `No resolver handled ${source}`,
1497
+ },
1498
+ };
1606
1499
  }
1607
1500
 
1608
1501
  async function runPreEditHandlers<Input>(
1609
- initialState: TextPreEditState<Input>,
1610
- handlers: readonly RegisteredHandler[],
1611
- tool: TextEditorToolId,
1612
- ): Promise<StageRunOutcome<TextPreEditState<Input>>>
1613
- {
1614
- let state = initialState;
1615
-
1616
- for (const registered of handlers)
1617
- {
1618
- if (registered.registration.stage !== "text-pre-edit")
1619
- {
1620
- continue;
1621
- }
1502
+ initialState: TextPreEditState<Input>,
1503
+ handlers: readonly RegisteredHandler[],
1504
+ tool: TextEditorToolId,
1505
+ ): Promise<StageRunOutcome<TextPreEditState<Input>>> {
1506
+ let state = initialState;
1507
+
1508
+ for (const registered of handlers) {
1509
+ if (registered.registration.stage !== "text-pre-edit") {
1510
+ continue;
1511
+ }
1622
1512
 
1623
- try
1624
- {
1625
- state = await registered.registration.handler(state) as TextPreEditState<Input>;
1626
- }
1627
- catch (error)
1628
- {
1629
- return {
1630
- kind: "failed",
1631
- failure: pluginFailure(registered.pluginId, tool, "text-pre-edit", error),
1632
- };
1633
- }
1513
+ try {
1514
+ state = (await registered.registration.handler(state)) as TextPreEditState<Input>;
1515
+ } catch (error) {
1516
+ return {
1517
+ kind: "failed",
1518
+ failure: pluginFailure(registered.pluginId, tool, "text-pre-edit", error),
1519
+ };
1634
1520
  }
1521
+ }
1635
1522
 
1636
- return { kind: "completed", state };
1523
+ return { kind: "completed", state };
1637
1524
  }
1638
1525
 
1639
1526
  async function runResultHandlers<Input, Result>(
1640
- stage: "text-edit" | "text-post-edit",
1641
- initialState: TextEditState<Input, Result>,
1642
- handlers: readonly RegisteredHandler[],
1643
- tool: TextEditorToolId,
1644
- ): Promise<StageRunOutcome<TextEditState<Input, Result>>>
1645
- {
1646
- let state = initialState;
1647
-
1648
- for (const registered of handlers)
1649
- {
1650
- if (registered.registration.stage !== stage)
1651
- {
1652
- continue;
1653
- }
1527
+ stage: "text-edit" | "text-post-edit",
1528
+ initialState: TextEditState<Input, Result>,
1529
+ handlers: readonly RegisteredHandler[],
1530
+ tool: TextEditorToolId,
1531
+ ): Promise<StageRunOutcome<TextEditState<Input, Result>>> {
1532
+ let state = initialState;
1533
+
1534
+ for (const registered of handlers) {
1535
+ if (registered.registration.stage !== stage) {
1536
+ continue;
1537
+ }
1654
1538
 
1655
- try
1656
- {
1657
- state = await registered.registration.handler(state) as TextEditState<Input, Result>;
1658
- }
1659
- catch (error)
1660
- {
1661
- return {
1662
- kind: "failed",
1663
- failure: pluginFailure(registered.pluginId, tool, stage, error),
1664
- };
1665
- }
1539
+ try {
1540
+ state = (await registered.registration.handler(state)) as TextEditState<Input, Result>;
1541
+ } catch (error) {
1542
+ return {
1543
+ kind: "failed",
1544
+ failure: pluginFailure(registered.pluginId, tool, stage, error),
1545
+ };
1666
1546
  }
1547
+ }
1667
1548
 
1668
- return { kind: "completed", state };
1549
+ return { kind: "completed", state };
1669
1550
  }
1670
1551
 
1671
1552
  function pluginFailure(
1672
- pluginId: string,
1673
- tool: TextEditorToolId,
1674
- stage: TextEditPipelineStage,
1675
- cause: unknown,
1676
- ): TextEditPipelineFailure
1677
- {
1678
- return {
1679
- code: "PLUGIN_FAILED",
1680
- pluginId,
1681
- tool,
1682
- stage,
1683
- message: `Plugin ${pluginId} failed during ${stage}`,
1684
- cause,
1685
- };
1553
+ pluginId: string,
1554
+ tool: TextEditorToolId,
1555
+ stage: TextEditPipelineStage,
1556
+ cause: unknown,
1557
+ ): TextEditPipelineFailure {
1558
+ return {
1559
+ code: "PLUGIN_FAILED",
1560
+ pluginId,
1561
+ tool,
1562
+ stage,
1563
+ message: `Plugin ${pluginId} failed during ${stage}`,
1564
+ cause,
1565
+ };
1686
1566
  }
1687
1567
 
1688
1568
  function getPluginValidationError(plugin: {
1689
- readonly apiVersion: number;
1690
- readonly id: string;
1691
- readonly protocol: string;
1692
- }): Error | undefined
1693
- {
1694
- if (plugin.protocol !== TEXT_EDITOR_PROTOCOL)
1695
- {
1696
- return new Error(`Plugin ${plugin.id} uses an unsupported protocol`);
1697
- }
1569
+ readonly apiVersion: number;
1570
+ readonly id: string;
1571
+ readonly protocol: string;
1572
+ }): Error | undefined {
1573
+ if (plugin.protocol !== TEXT_EDITOR_PROTOCOL) {
1574
+ return new Error(`Plugin ${plugin.id} uses an unsupported protocol`);
1575
+ }
1576
+
1577
+ if (plugin.apiVersion !== TEXT_EDITOR_API_VERSION) {
1578
+ return new Error(`Plugin ${plugin.id} uses an unsupported API version`);
1579
+ }
1580
+
1581
+ if (plugin.id.trim().length === 0) {
1582
+ return new Error("Plugin ID must not be empty");
1583
+ }
1584
+
1585
+ return undefined;
1586
+ }
1698
1587
 
1699
- if (plugin.apiVersion !== TEXT_EDITOR_API_VERSION)
1700
- {
1701
- return new Error(`Plugin ${plugin.id} uses an unsupported API version`);
1588
+ function createPluginContributionController(
1589
+ pluginId: string,
1590
+ registerContributions: (draft: PluginContributionDraft) => void,
1591
+ inspectTextAnchors: (
1592
+ request: TextAnchorInspectionRequest,
1593
+ ) => Promise<TextAnchorInspectionOutcome>,
1594
+ onMutationTool: (listener: TextMutationToolListener) => () => void,
1595
+ onDidEdit: (listener: TextEditCompletionListener) => () => void,
1596
+ previewMutation: (request: TextMutationPreviewRequest) => Promise<TextMutationPreviewOutcome>,
1597
+ ): PluginContributionController {
1598
+ const setupDraft: PluginContributionDraft = {
1599
+ resolvers: [],
1600
+ anchorResolvers: [],
1601
+ presenters: [],
1602
+ handlers: [],
1603
+ promptContributions: [],
1604
+ writablePromptContributions: [],
1605
+ tools: [],
1606
+ mutationTools: [],
1607
+ mutationToolListeners: [],
1608
+ editCompletionListeners: [],
1609
+ mutationGuards: [],
1610
+ toolRenderers: [],
1611
+ };
1612
+ let state: "active" | "closed" | "setup" = "setup";
1613
+ const assertAvailable = (): void => {
1614
+ if (state === "closed") {
1615
+ throw new Error(`Plugin ${pluginId} API is closed`);
1702
1616
  }
1617
+ };
1618
+ const createToolApi = (tool: TextEditorToolId): TextEditorToolPluginApi => ({
1619
+ addHandler(registration): void {
1620
+ assertAvailable();
1703
1621
 
1704
- if (plugin.id.trim().length === 0)
1705
- {
1706
- return new Error("Plugin ID must not be empty");
1707
- }
1622
+ if (!isTextEditHandlerRegistration(registration)) {
1623
+ throw new TypeError(`Plugin ${pluginId} provided an invalid handler for ${tool}`);
1624
+ }
1708
1625
 
1709
- return undefined;
1710
- }
1626
+ const contribution: RegisteredHandler = { pluginId, registration, tool };
1711
1627
 
1712
- function createPluginContributionController(
1713
- pluginId: string,
1714
- registerContributions: (draft: PluginContributionDraft) => void,
1715
- inspectTextAnchors: (request: TextAnchorInspectionRequest) => Promise<TextAnchorInspectionOutcome>,
1716
- onMutationTool: (listener: TextMutationToolListener) => () => void,
1717
- onDidEdit: (listener: TextEditCompletionListener) => () => void,
1718
- previewMutation: (request: TextMutationPreviewRequest) => Promise<TextMutationPreviewOutcome>,
1719
- ): PluginContributionController
1720
- {
1721
- const setupDraft: PluginContributionDraft = {
1628
+ if (state === "setup") {
1629
+ assertNoDraftHandler(setupDraft.handlers, contribution);
1630
+ setupDraft.handlers.push(contribution);
1631
+ return;
1632
+ }
1633
+
1634
+ registerContributions({
1722
1635
  resolvers: [],
1723
1636
  anchorResolvers: [],
1724
- presenters: [],
1725
- handlers: [],
1637
+ handlers: [contribution],
1726
1638
  promptContributions: [],
1727
1639
  writablePromptContributions: [],
1728
1640
  tools: [],
1729
- mutationTools: [],
1730
- mutationToolListeners: [],
1731
- editCompletionListeners: [],
1732
- mutationGuards: [],
1733
- toolRenderers: [],
1734
- };
1735
- let state: "active" | "closed" | "setup" = "setup";
1736
- const assertAvailable = (): void =>
1737
- {
1738
- if (state === "closed")
1739
- {
1740
- throw new Error(`Plugin ${pluginId} API is closed`);
1741
- }
1742
- };
1743
- const createToolApi = (tool: TextEditorToolId): TextEditorToolPluginApi => ({
1744
- addHandler(registration): void
1745
- {
1746
- assertAvailable();
1747
-
1748
- if (!isTextEditHandlerRegistration(registration))
1749
- {
1750
- throw new TypeError(`Plugin ${pluginId} provided an invalid handler for ${tool}`);
1751
- }
1752
-
1753
- const contribution: RegisteredHandler = { pluginId, registration, tool };
1754
-
1755
- if (state === "setup")
1756
- {
1757
- assertNoDraftHandler(setupDraft.handlers, contribution);
1758
- setupDraft.handlers.push(contribution);
1759
- return;
1760
- }
1761
-
1762
- registerContributions({
1763
- resolvers: [],
1764
- anchorResolvers: [],
1765
- handlers: [contribution],
1766
- promptContributions: [],
1767
- writablePromptContributions: [],
1768
- tools: [],
1769
- });
1770
- },
1771
- describe(description): void
1772
- {
1773
- assertAvailable();
1774
- const contribution: PromptContribution = {
1775
- description: normalizeDescription(`Plugin prompt description for ${tool}`, description),
1776
- pluginId,
1777
- tool,
1778
- };
1779
-
1780
- if (state === "setup")
1781
- {
1782
- assertNoDraftDescription(setupDraft.promptContributions, contribution);
1783
- setupDraft.promptContributions.push(contribution);
1784
- return;
1785
- }
1786
-
1787
- registerContributions({
1788
- resolvers: [],
1789
- anchorResolvers: [],
1790
- handlers: [],
1791
- promptContributions: [contribution],
1792
- writablePromptContributions: [],
1793
- tools: [],
1794
- });
1795
- },
1796
- });
1797
- const api: TextEditorPluginApi = {
1798
- addMutationTool(registration): void
1799
- {
1800
- assertAvailable();
1801
- assertTextMutationToolRegistration(registration);
1802
-
1803
- if (state === "setup")
1804
- {
1805
- setupDraft.mutationTools!.push(registration);
1806
- return;
1807
- }
1808
-
1809
- registerContributions({
1810
- resolvers: [],
1811
- anchorResolvers: [],
1812
- handlers: [],
1813
- promptContributions: [],
1814
- writablePromptContributions: [],
1815
- tools: [],
1816
- mutationTools: [registration],
1817
- });
1818
- },
1819
- addToolRenderer(registration): void
1820
- {
1821
- assertAvailable();
1822
-
1823
- if (!isTextEditorToolRendererRegistration(registration))
1824
- {
1825
- throw new TypeError(`Plugin ${pluginId} provided an invalid text editor tool renderer`);
1826
- }
1827
-
1828
- if (state === "setup")
1829
- {
1830
- setupDraft.toolRenderers!.push(registration);
1831
- return;
1832
- }
1833
-
1834
- registerContributions({
1835
- resolvers: [],
1836
- anchorResolvers: [],
1837
- handlers: [],
1838
- promptContributions: [],
1839
- writablePromptContributions: [],
1840
- tools: [],
1841
- toolRenderers: [registration],
1842
- });
1843
- },
1844
- addMutationGuard(registration): void
1845
- {
1846
- assertAvailable();
1847
-
1848
- if (registration.id.trim().length === 0 || typeof registration.guard !== "function")
1849
- {
1850
- throw new TypeError(`Plugin ${pluginId} provided an invalid mutation guard`);
1851
- }
1852
-
1853
- if (state === "setup")
1854
- {
1855
- setupDraft.mutationGuards!.push(registration);
1856
- return;
1857
- }
1858
-
1859
- registerContributions({
1860
- resolvers: [],
1861
- anchorResolvers: [],
1862
- handlers: [],
1863
- promptContributions: [],
1864
- writablePromptContributions: [],
1865
- tools: [],
1866
- mutationGuards: [registration],
1867
- });
1868
- },
1869
- onMutationTool(listener): () => void
1870
- {
1871
- assertAvailable();
1872
-
1873
- if (state === "setup")
1874
- {
1875
- setupDraft.mutationToolListeners!.push(listener);
1876
- return () =>
1877
- {
1878
- const index = setupDraft.mutationToolListeners!.indexOf(listener);
1879
-
1880
- if (index !== -1)
1881
- {
1882
- setupDraft.mutationToolListeners!.splice(index, 1);
1883
- }
1884
- };
1885
- }
1886
-
1887
- return onMutationTool(listener);
1888
- },
1889
- onDidEdit(listener): () => void
1890
- {
1891
- assertAvailable();
1641
+ });
1642
+ },
1643
+ describe(description): void {
1644
+ assertAvailable();
1645
+ const contribution: PromptContribution = {
1646
+ description: normalizeDescription(`Plugin prompt description for ${tool}`, description),
1647
+ pluginId,
1648
+ tool,
1649
+ };
1892
1650
 
1893
- if (typeof listener !== "function")
1894
- {
1895
- throw new TypeError(`Plugin ${pluginId} provided an invalid edit completion listener`);
1896
- }
1651
+ if (state === "setup") {
1652
+ assertNoDraftDescription(setupDraft.promptContributions, contribution);
1653
+ setupDraft.promptContributions.push(contribution);
1654
+ return;
1655
+ }
1897
1656
 
1898
- if (state === "setup")
1899
- {
1900
- setupDraft.editCompletionListeners!.push(listener);
1901
- return () =>
1902
- {
1903
- const index = setupDraft.editCompletionListeners!.indexOf(listener);
1904
-
1905
- if (index !== -1)
1906
- {
1907
- setupDraft.editCompletionListeners!.splice(index, 1);
1908
- }
1909
- };
1910
- }
1911
-
1912
- return onDidEdit(listener);
1913
- },
1914
- inspectTextAnchors(request): Promise<TextAnchorInspectionOutcome>
1915
- {
1916
- assertAvailable();
1917
- return inspectTextAnchors(request);
1918
- },
1919
- previewMutation(request): Promise<TextMutationPreviewOutcome>
1920
- {
1921
- assertAvailable();
1922
- return previewMutation(request);
1923
- },
1924
- addResolver(registration): void
1925
- {
1926
- assertAvailable();
1657
+ registerContributions({
1658
+ resolvers: [],
1659
+ anchorResolvers: [],
1660
+ handlers: [],
1661
+ promptContributions: [contribution],
1662
+ writablePromptContributions: [],
1663
+ tools: [],
1664
+ });
1665
+ },
1666
+ });
1667
+ const api: TextEditorPluginApi = {
1668
+ addMutationTool(registration): void {
1669
+ assertAvailable();
1670
+ assertTextMutationToolRegistration(registration);
1671
+
1672
+ if (state === "setup") {
1673
+ requiredValue(setupDraft.mutationTools).push(registration);
1674
+ return;
1675
+ }
1676
+
1677
+ registerContributions({
1678
+ resolvers: [],
1679
+ anchorResolvers: [],
1680
+ handlers: [],
1681
+ promptContributions: [],
1682
+ writablePromptContributions: [],
1683
+ tools: [],
1684
+ mutationTools: [registration],
1685
+ });
1686
+ },
1687
+ addToolRenderer(registration): void {
1688
+ assertAvailable();
1689
+
1690
+ if (!isTextEditorToolRendererRegistration(registration)) {
1691
+ throw new TypeError(`Plugin ${pluginId} provided an invalid text editor tool renderer`);
1692
+ }
1693
+
1694
+ if (state === "setup") {
1695
+ requiredValue(setupDraft.toolRenderers).push(registration);
1696
+ return;
1697
+ }
1698
+
1699
+ registerContributions({
1700
+ resolvers: [],
1701
+ anchorResolvers: [],
1702
+ handlers: [],
1703
+ promptContributions: [],
1704
+ writablePromptContributions: [],
1705
+ tools: [],
1706
+ toolRenderers: [registration],
1707
+ });
1708
+ },
1709
+ addMutationGuard(registration): void {
1710
+ assertAvailable();
1711
+
1712
+ if (registration.id.trim().length === 0 || typeof registration.guard !== "function") {
1713
+ throw new TypeError(`Plugin ${pluginId} provided an invalid mutation guard`);
1714
+ }
1715
+
1716
+ if (state === "setup") {
1717
+ requiredValue(setupDraft.mutationGuards).push(registration);
1718
+ return;
1719
+ }
1720
+
1721
+ registerContributions({
1722
+ resolvers: [],
1723
+ anchorResolvers: [],
1724
+ handlers: [],
1725
+ promptContributions: [],
1726
+ writablePromptContributions: [],
1727
+ tools: [],
1728
+ mutationGuards: [registration],
1729
+ });
1730
+ },
1731
+ onMutationTool(listener): () => void {
1732
+ assertAvailable();
1733
+
1734
+ if (state === "setup") {
1735
+ requiredValue(setupDraft.mutationToolListeners).push(listener);
1736
+ return () => {
1737
+ const index = requiredValue(setupDraft.mutationToolListeners).indexOf(listener);
1738
+
1739
+ if (index !== -1) {
1740
+ requiredValue(setupDraft.mutationToolListeners).splice(index, 1);
1741
+ }
1742
+ };
1743
+ }
1927
1744
 
1928
- if (!isResourceResolverRegistration(registration))
1929
- {
1930
- throw new TypeError(`Plugin ${pluginId} provided an invalid resource resolver`);
1931
- }
1745
+ return onMutationTool(listener);
1746
+ },
1747
+ onDidEdit(listener): () => void {
1748
+ assertAvailable();
1932
1749
 
1933
- const contribution: ResolverContribution = { pluginId, registration };
1750
+ if (typeof listener !== "function") {
1751
+ throw new TypeError(`Plugin ${pluginId} provided an invalid edit completion listener`);
1752
+ }
1934
1753
 
1935
- if (state === "setup")
1936
- {
1937
- assertNoDraftResolver(setupDraft.resolvers, contribution);
1938
- setupDraft.resolvers.push(contribution);
1939
- return;
1940
- }
1941
-
1942
- registerContributions({
1943
- resolvers: [contribution],
1944
- anchorResolvers: [],
1945
- handlers: [],
1946
- promptContributions: [],
1947
- writablePromptContributions: [],
1948
- tools: [],
1949
- });
1950
- },
1951
- addAnchorResolver(registration): void
1952
- {
1953
- assertAvailable();
1754
+ if (state === "setup") {
1755
+ requiredValue(setupDraft.editCompletionListeners).push(listener);
1756
+ return () => {
1757
+ const index = requiredValue(setupDraft.editCompletionListeners).indexOf(listener);
1954
1758
 
1955
- if (!isTextAnchorResolverRegistration(registration))
1956
- {
1957
- throw new TypeError(`Plugin ${pluginId} provided an invalid text anchor resolver`);
1958
- }
1759
+ if (index !== -1) {
1760
+ requiredValue(setupDraft.editCompletionListeners).splice(index, 1);
1761
+ }
1762
+ };
1763
+ }
1764
+
1765
+ return onDidEdit(listener);
1766
+ },
1767
+ inspectTextAnchors(request): Promise<TextAnchorInspectionOutcome> {
1768
+ assertAvailable();
1769
+ return inspectTextAnchors(request);
1770
+ },
1771
+ previewMutation(request): Promise<TextMutationPreviewOutcome> {
1772
+ assertAvailable();
1773
+ return previewMutation(request);
1774
+ },
1775
+ addResolver(registration): void {
1776
+ assertAvailable();
1777
+
1778
+ if (!isResourceResolverRegistration(registration)) {
1779
+ throw new TypeError(`Plugin ${pluginId} provided an invalid resource resolver`);
1780
+ }
1781
+
1782
+ const contribution: ResolverContribution = { pluginId, registration };
1783
+
1784
+ if (state === "setup") {
1785
+ assertNoDraftResolver(setupDraft.resolvers, contribution);
1786
+ setupDraft.resolvers.push(contribution);
1787
+ return;
1788
+ }
1789
+
1790
+ registerContributions({
1791
+ resolvers: [contribution],
1792
+ anchorResolvers: [],
1793
+ handlers: [],
1794
+ promptContributions: [],
1795
+ writablePromptContributions: [],
1796
+ tools: [],
1797
+ });
1798
+ },
1799
+ addAnchorResolver(registration): void {
1800
+ assertAvailable();
1959
1801
 
1960
- const contribution: TextAnchorResolverContribution = { pluginId, registration };
1802
+ if (!isTextAnchorResolverRegistration(registration)) {
1803
+ throw new TypeError(`Plugin ${pluginId} provided an invalid text anchor resolver`);
1804
+ }
1961
1805
 
1962
- if (state === "setup")
1963
- {
1964
- setupDraft.anchorResolvers.push(contribution);
1965
- return;
1966
- }
1967
-
1968
- registerContributions({
1969
- resolvers: [],
1970
- anchorResolvers: [contribution],
1971
- handlers: [],
1972
- promptContributions: [],
1973
- writablePromptContributions: [],
1974
- tools: [],
1975
- });
1976
- },
1977
- addTextPresenter(registration): void
1978
- {
1979
- assertAvailable();
1806
+ const contribution: TextAnchorResolverContribution = { pluginId, registration };
1980
1807
 
1981
- if (!isTextPresenterRegistration(registration))
1982
- {
1983
- throw new TypeError(`Plugin ${pluginId} provided an invalid text presenter`);
1984
- }
1808
+ if (state === "setup") {
1809
+ setupDraft.anchorResolvers.push(contribution);
1810
+ return;
1811
+ }
1985
1812
 
1986
- const contribution: TextPresenterContribution = { pluginId, registration };
1813
+ registerContributions({
1814
+ resolvers: [],
1815
+ anchorResolvers: [contribution],
1816
+ handlers: [],
1817
+ promptContributions: [],
1818
+ writablePromptContributions: [],
1819
+ tools: [],
1820
+ });
1821
+ },
1822
+ addTextPresenter(registration): void {
1823
+ assertAvailable();
1987
1824
 
1988
- if (state === "setup")
1989
- {
1990
- setupDraft.presenters!.push(contribution);
1991
- return;
1992
- }
1993
-
1994
- registerContributions({
1995
- resolvers: [],
1996
- anchorResolvers: [],
1997
- presenters: [contribution],
1998
- handlers: [],
1999
- promptContributions: [],
2000
- writablePromptContributions: [],
2001
- tools: [],
2002
- });
2003
- },
2004
- describe(description): void
2005
- {
2006
- assertAvailable();
1825
+ if (!isTextPresenterRegistration(registration)) {
1826
+ throw new TypeError(`Plugin ${pluginId} provided an invalid text presenter`);
1827
+ }
2007
1828
 
2008
- if (setupDraft.writablePromptContributions.length > 0)
2009
- {
2010
- throw new Error(`Plugin ${pluginId} provides more than one writable resource description`);
2011
- }
1829
+ const contribution: TextPresenterContribution = { pluginId, registration };
2012
1830
 
2013
- const contribution: WritablePromptContribution = {
2014
- description: normalizeDescriptionSource(description),
2015
- pluginId,
2016
- };
1831
+ if (state === "setup") {
1832
+ requiredValue(setupDraft.presenters).push(contribution);
1833
+ return;
1834
+ }
2017
1835
 
2018
- if (state === "setup")
2019
- {
2020
- setupDraft.writablePromptContributions.push(contribution);
2021
- return;
2022
- }
2023
-
2024
- registerContributions({
2025
- resolvers: [],
2026
- anchorResolvers: [],
2027
- handlers: [],
2028
- promptContributions: [],
2029
- writablePromptContributions: [contribution],
2030
- tools: [],
2031
- });
2032
- },
2033
- tool(tool): TextEditorToolPluginApi
2034
- {
2035
- assertAvailable();
1836
+ registerContributions({
1837
+ resolvers: [],
1838
+ anchorResolvers: [],
1839
+ presenters: [contribution],
1840
+ handlers: [],
1841
+ promptContributions: [],
1842
+ writablePromptContributions: [],
1843
+ tools: [],
1844
+ });
1845
+ },
1846
+ describe(description): void {
1847
+ assertAvailable();
2036
1848
 
2037
- if (!isTextEditorToolId(tool))
2038
- {
2039
- throw new Error(`Plugin ${pluginId} provided an invalid tool ID`);
2040
- }
1849
+ if (setupDraft.writablePromptContributions.length > 0) {
1850
+ throw new Error(`Plugin ${pluginId} provides more than one writable resource description`);
1851
+ }
2041
1852
 
2042
- if (state === "setup")
2043
- {
2044
- if (!setupDraft.tools.includes(tool))
2045
- {
2046
- setupDraft.tools.push(tool);
2047
- }
2048
- }
2049
- else
2050
- {
2051
- registerContributions({
2052
- resolvers: [],
2053
- anchorResolvers: [],
2054
- handlers: [],
2055
- promptContributions: [],
2056
- writablePromptContributions: [],
2057
- tools: [tool],
2058
- });
2059
- }
2060
-
2061
- return createToolApi(tool);
2062
- },
2063
- };
1853
+ const contribution: WritablePromptContribution = {
1854
+ description: normalizeDescriptionSource(description),
1855
+ pluginId,
1856
+ };
2064
1857
 
2065
- return {
2066
- api,
2067
- close(): void
2068
- {
2069
- state = "closed";
2070
- },
2071
- commit(): void
2072
- {
2073
- if (state !== "setup")
2074
- {
2075
- throw new Error(`Plugin ${pluginId} setup contributions cannot be committed`);
2076
- }
1858
+ if (state === "setup") {
1859
+ setupDraft.writablePromptContributions.push(contribution);
1860
+ return;
1861
+ }
2077
1862
 
2078
- registerContributions(setupDraft);
2079
- state = "active";
2080
- },
2081
- };
1863
+ registerContributions({
1864
+ resolvers: [],
1865
+ anchorResolvers: [],
1866
+ handlers: [],
1867
+ promptContributions: [],
1868
+ writablePromptContributions: [contribution],
1869
+ tools: [],
1870
+ });
1871
+ },
1872
+ tool(tool): TextEditorToolPluginApi {
1873
+ assertAvailable();
1874
+
1875
+ if (!isTextEditorToolId(tool)) {
1876
+ throw new Error(`Plugin ${pluginId} provided an invalid tool ID`);
1877
+ }
1878
+
1879
+ if (state === "setup") {
1880
+ if (!setupDraft.tools.includes(tool)) {
1881
+ setupDraft.tools.push(tool);
1882
+ }
1883
+ } else {
1884
+ registerContributions({
1885
+ resolvers: [],
1886
+ anchorResolvers: [],
1887
+ handlers: [],
1888
+ promptContributions: [],
1889
+ writablePromptContributions: [],
1890
+ tools: [tool],
1891
+ });
1892
+ }
1893
+
1894
+ return createToolApi(tool);
1895
+ },
1896
+ };
1897
+
1898
+ return {
1899
+ api,
1900
+ close(): void {
1901
+ state = "closed";
1902
+ },
1903
+ commit(): void {
1904
+ if (state !== "setup") {
1905
+ throw new Error(`Plugin ${pluginId} setup contributions cannot be committed`);
1906
+ }
1907
+
1908
+ registerContributions(setupDraft);
1909
+ state = "active";
1910
+ },
1911
+ };
2082
1912
  }
2083
1913
 
2084
1914
  function validateContributionDraft(
2085
- draft: PluginContributionDraft,
2086
- registeredResolvers: readonly RegisteredResolver[],
2087
- registeredHandlers: readonly RegisteredHandler[],
2088
- registeredPromptContributions: readonly PromptContribution[],
2089
- registeredWritablePromptContributions: readonly WritablePromptContribution[],
2090
- ): void
2091
- {
2092
- const resolverIds = new Set(registeredResolvers.map(({ resolver }) => resolver.id));
2093
-
2094
- for (const contribution of draft.resolvers)
2095
- {
2096
- if (!isResourceResolverRegistration(contribution.registration))
2097
- {
2098
- throw new TypeError(`Plugin ${contribution.pluginId} provided an invalid resource resolver`);
2099
- }
1915
+ draft: PluginContributionDraft,
1916
+ registeredResolvers: readonly RegisteredResolver[],
1917
+ registeredHandlers: readonly RegisteredHandler[],
1918
+ registeredPromptContributions: readonly PromptContribution[],
1919
+ registeredWritablePromptContributions: readonly WritablePromptContribution[],
1920
+ ): void {
1921
+ const resolverIds = new Set(registeredResolvers.map(({ resolver }) => resolver.id));
1922
+
1923
+ for (const contribution of draft.resolvers) {
1924
+ if (!isResourceResolverRegistration(contribution.registration)) {
1925
+ throw new TypeError(`Plugin ${contribution.pluginId} provided an invalid resource resolver`);
1926
+ }
2100
1927
 
2101
- const resolverId = contribution.registration.resolver.id;
1928
+ const resolverId = contribution.registration.resolver.id;
2102
1929
 
2103
- if (resolverIds.has(resolverId))
2104
- {
2105
- throw new Error(`Resource resolver ${resolverId} is already registered`);
2106
- }
2107
-
2108
- resolverIds.add(resolverId);
1930
+ if (resolverIds.has(resolverId)) {
1931
+ throw new Error(`Resource resolver ${resolverId} is already registered`);
2109
1932
  }
2110
1933
 
2111
- const handlerKeys = new Set(registeredHandlers.map(handlerKey));
1934
+ resolverIds.add(resolverId);
1935
+ }
2112
1936
 
2113
- for (const handler of draft.handlers)
2114
- {
2115
- if (!isTextEditHandlerRegistration(handler.registration))
2116
- {
2117
- throw new TypeError(`Plugin ${handler.pluginId} provided an invalid handler for ${handler.tool}`);
2118
- }
1937
+ const handlerKeys = new Set(registeredHandlers.map(handlerKey));
2119
1938
 
2120
- const key = handlerKey(handler);
1939
+ for (const handler of draft.handlers) {
1940
+ if (!isTextEditHandlerRegistration(handler.registration)) {
1941
+ throw new TypeError(
1942
+ `Plugin ${handler.pluginId} provided an invalid handler for ${handler.tool}`,
1943
+ );
1944
+ }
2121
1945
 
2122
- if (handlerKeys.has(key))
2123
- {
2124
- throw new Error(
2125
- `Plugin ${handler.pluginId} already handles ${handler.registration.stage} for ${handler.tool}`,
2126
- );
2127
- }
1946
+ const key = handlerKey(handler);
2128
1947
 
2129
- handlerKeys.add(key);
1948
+ if (handlerKeys.has(key)) {
1949
+ throw new Error(
1950
+ `Plugin ${handler.pluginId} already handles ${handler.registration.stage} for ${handler.tool}`,
1951
+ );
2130
1952
  }
2131
1953
 
2132
- const descriptionKeys = new Set(registeredPromptContributions.map(descriptionKey));
1954
+ handlerKeys.add(key);
1955
+ }
2133
1956
 
2134
- for (const contribution of draft.promptContributions)
2135
- {
2136
- const key = descriptionKey(contribution);
1957
+ const descriptionKeys = new Set(registeredPromptContributions.map(descriptionKey));
2137
1958
 
2138
- if (descriptionKeys.has(key))
2139
- {
2140
- throw new Error(`Plugin ${contribution.pluginId} describes ${contribution.tool} more than once`);
2141
- }
1959
+ for (const contribution of draft.promptContributions) {
1960
+ const key = descriptionKey(contribution);
2142
1961
 
2143
- descriptionKeys.add(key);
1962
+ if (descriptionKeys.has(key)) {
1963
+ throw new Error(
1964
+ `Plugin ${contribution.pluginId} describes ${contribution.tool} more than once`,
1965
+ );
2144
1966
  }
2145
1967
 
2146
- const writablePluginIds = new Set(
2147
- registeredWritablePromptContributions.map(({ pluginId }) => pluginId),
2148
- );
1968
+ descriptionKeys.add(key);
1969
+ }
2149
1970
 
2150
- for (const contribution of draft.writablePromptContributions)
2151
- {
2152
- if (writablePluginIds.has(contribution.pluginId))
2153
- {
2154
- throw new Error(
2155
- `Plugin ${contribution.pluginId} provides more than one writable resource description`,
2156
- );
2157
- }
1971
+ const writablePluginIds = new Set(
1972
+ registeredWritablePromptContributions.map(({ pluginId }) => pluginId),
1973
+ );
2158
1974
 
2159
- writablePluginIds.add(contribution.pluginId);
1975
+ for (const contribution of draft.writablePromptContributions) {
1976
+ if (writablePluginIds.has(contribution.pluginId)) {
1977
+ throw new Error(
1978
+ `Plugin ${contribution.pluginId} provides more than one writable resource description`,
1979
+ );
2160
1980
  }
2161
1981
 
2162
- for (const tool of draft.tools)
2163
- {
2164
- if (!isTextEditorToolId(tool))
2165
- {
2166
- throw new TypeError("Plugin provided an invalid tool ID");
2167
- }
1982
+ writablePluginIds.add(contribution.pluginId);
1983
+ }
1984
+
1985
+ for (const tool of draft.tools) {
1986
+ if (!isTextEditorToolId(tool)) {
1987
+ throw new TypeError("Plugin provided an invalid tool ID");
2168
1988
  }
1989
+ }
2169
1990
  }
2170
1991
 
2171
1992
  function assertNoDraftResolver(
2172
- resolvers: readonly ResolverContribution[],
2173
- incoming: ResolverContribution,
2174
- ): void
2175
- {
2176
- const resolverId = incoming.registration.resolver.id;
2177
-
2178
- if (resolvers.some((resolver) => resolver.registration.resolver.id === resolverId))
2179
- {
2180
- throw new Error(`Resource resolver ${resolverId} is already registered`);
2181
- }
1993
+ resolvers: readonly ResolverContribution[],
1994
+ incoming: ResolverContribution,
1995
+ ): void {
1996
+ const resolverId = incoming.registration.resolver.id;
1997
+
1998
+ if (resolvers.some((resolver) => resolver.registration.resolver.id === resolverId)) {
1999
+ throw new Error(`Resource resolver ${resolverId} is already registered`);
2000
+ }
2182
2001
  }
2183
2002
 
2184
2003
  function assertNoDraftHandler(
2185
- handlers: readonly RegisteredHandler[],
2186
- incoming: RegisteredHandler,
2187
- ): void
2188
- {
2189
- if (handlers.some((handler) => handlerKey(handler) === handlerKey(incoming)))
2190
- {
2191
- throw new Error(
2192
- `Plugin ${incoming.pluginId} already handles ${incoming.registration.stage} for ${incoming.tool}`,
2193
- );
2194
- }
2004
+ handlers: readonly RegisteredHandler[],
2005
+ incoming: RegisteredHandler,
2006
+ ): void {
2007
+ if (handlers.some((handler) => handlerKey(handler) === handlerKey(incoming))) {
2008
+ throw new Error(
2009
+ `Plugin ${incoming.pluginId} already handles ${incoming.registration.stage} for ${incoming.tool}`,
2010
+ );
2011
+ }
2195
2012
  }
2196
2013
 
2197
2014
  function assertNoDraftDescription(
2198
- contributions: readonly PromptContribution[],
2199
- incoming: PromptContribution,
2200
- ): void
2201
- {
2202
- if (contributions.some((contribution) => descriptionKey(contribution) === descriptionKey(incoming)))
2203
- {
2204
- throw new Error(`Plugin ${incoming.pluginId} describes ${incoming.tool} more than once`);
2205
- }
2015
+ contributions: readonly PromptContribution[],
2016
+ incoming: PromptContribution,
2017
+ ): void {
2018
+ if (
2019
+ contributions.some((contribution) => descriptionKey(contribution) === descriptionKey(incoming))
2020
+ ) {
2021
+ throw new Error(`Plugin ${incoming.pluginId} describes ${incoming.tool} more than once`);
2022
+ }
2206
2023
  }
2207
2024
 
2208
- function handlerKey(handler: RegisteredHandler): string
2209
- {
2210
- return `${handler.pluginId}\0${handler.tool}\0${handler.registration.stage}`;
2025
+ function handlerKey(handler: RegisteredHandler): string {
2026
+ return `${handler.pluginId}\0${handler.tool}\0${handler.registration.stage}`;
2211
2027
  }
2212
2028
 
2213
- function descriptionKey(contribution: PromptContribution): string
2214
- {
2215
- return `${contribution.pluginId}\0${contribution.tool}`;
2029
+ function descriptionKey(contribution: PromptContribution): string {
2030
+ return `${contribution.pluginId}\0${contribution.tool}`;
2216
2031
  }
2217
2032
 
2218
- function normalizeDescriptionSource(value: unknown): PromptDescriptionSource
2219
- {
2220
- if (typeof value === "string")
2221
- {
2222
- return normalizeDescription("Writable resource prompt description", value);
2223
- }
2033
+ function normalizeDescriptionSource(value: unknown): PromptDescriptionSource {
2034
+ if (typeof value === "string") {
2035
+ return normalizeDescription("Writable resource prompt description", value);
2036
+ }
2224
2037
 
2225
- if (typeof value === "function")
2226
- {
2227
- return value as () => string | undefined;
2228
- }
2038
+ if (typeof value === "function") {
2039
+ return value as () => string | undefined;
2040
+ }
2229
2041
 
2230
- throw new TypeError("Writable resource prompt description must be a string or callback");
2042
+ throw new TypeError("Writable resource prompt description must be a string or callback");
2231
2043
  }
2232
2044
 
2233
- function renderDescriptionSource(source: PromptDescriptionSource): string | undefined
2234
- {
2235
- if (typeof source === "string")
2236
- {
2237
- return source;
2238
- }
2045
+ function renderDescriptionSource(source: PromptDescriptionSource): string | undefined {
2046
+ if (typeof source === "string") {
2047
+ return source;
2048
+ }
2239
2049
 
2240
- const value: unknown = source();
2241
- return value === undefined
2242
- ? undefined
2243
- : normalizeDescription("Writable resource prompt description", value);
2050
+ const value: unknown = source();
2051
+ return value === undefined
2052
+ ? undefined
2053
+ : normalizeDescription("Writable resource prompt description", value);
2244
2054
  }
2245
2055
 
2246
- function normalizeDescription(label: string, value: unknown): string
2247
- {
2248
- if (typeof value !== "string")
2249
- {
2250
- throw new TypeError(`${label} must be a string`);
2251
- }
2056
+ function normalizeDescription(label: string, value: unknown): string {
2057
+ if (typeof value !== "string") {
2058
+ throw new TypeError(`${label} must be a string`);
2059
+ }
2252
2060
 
2253
- const lines = value
2254
- .replaceAll("\r\n", "\n")
2255
- .replaceAll("\r", "\n")
2256
- .split("\n")
2257
- .map((line) => line.trimEnd());
2061
+ const lines = value
2062
+ .replaceAll("\r\n", "\n")
2063
+ .replaceAll("\r", "\n")
2064
+ .split("\n")
2065
+ .map((line) => line.trimEnd());
2258
2066
 
2259
- while (lines[0]?.trim().length === 0)
2260
- {
2261
- lines.shift();
2262
- }
2067
+ while (lines[0]?.trim().length === 0) {
2068
+ lines.shift();
2069
+ }
2263
2070
 
2264
- while (lines.at(-1)?.trim().length === 0)
2265
- {
2266
- lines.pop();
2267
- }
2071
+ while (lines.at(-1)?.trim().length === 0) {
2072
+ lines.pop();
2073
+ }
2268
2074
 
2269
- const description = lines.join("\n");
2075
+ const description = lines.join("\n");
2270
2076
 
2271
- if (description.trim().length === 0)
2272
- {
2273
- throw new Error(`${label} is empty`);
2274
- }
2077
+ if (description.trim().length === 0) {
2078
+ throw new Error(`${label} is empty`);
2079
+ }
2275
2080
 
2276
- return description;
2081
+ return description;
2277
2082
  }
2278
2083
 
2279
- function renderPromptEntry(pluginId: string, description: string): string
2280
- {
2281
- const [firstLine, ...continuationLines] = description.split("\n");
2084
+ function renderPromptEntry(pluginId: string, description: string): string {
2085
+ const [firstLine, ...continuationLines] = description.split("\n");
2282
2086
 
2283
- return [
2284
- `- \`${escapeInlineCode(pluginId)}\` — ${firstLine ?? ""}`,
2285
- ...continuationLines.map((line) => ` ${line}`),
2286
- ].join("\n");
2087
+ return [
2088
+ `- \`${escapeInlineCode(pluginId)}\` — ${firstLine ?? ""}`,
2089
+ ...continuationLines.map((line) => ` ${line}`),
2090
+ ].join("\n");
2287
2091
  }
2288
2092
 
2289
- function indentGuidelineContinuation(guideline: string): string
2290
- {
2291
- const [firstLine, ...continuationLines] = guideline.split("\n");
2292
- return [firstLine ?? "", ...continuationLines.map((line) => line.length === 0 ? line : ` ${line}`)].join("\n");
2093
+ function indentGuidelineContinuation(guideline: string): string {
2094
+ const [firstLine, ...continuationLines] = guideline.split("\n");
2095
+ return [
2096
+ firstLine ?? "",
2097
+ ...continuationLines.map((line) => (line.length === 0 ? line : ` ${line}`)),
2098
+ ].join("\n");
2293
2099
  }
2294
2100
 
2295
- function escapeInlineCode(value: string): string
2296
- {
2297
- return value.replaceAll("`", "\\`");
2101
+ function escapeInlineCode(value: string): string {
2102
+ return value.replaceAll("`", "\\`");
2298
2103
  }
2299
2104
 
2300
2105
  function mergeToolRenderer(
2301
- current: TextEditorToolRendererRegistration | undefined,
2302
- registration: TextEditorToolRendererRegistration,
2303
- ): TextEditorToolRendererRegistration
2304
- {
2305
- const merged = registration.fallback === true
2306
- ? { ...registration, ...current, tool: registration.tool }
2307
- : { ...current, ...registration, tool: registration.tool };
2308
- const { fallback: _fallback, ...renderer } = merged;
2309
- return renderer;
2106
+ current: TextEditorToolRendererRegistration | undefined,
2107
+ registration: TextEditorToolRendererRegistration,
2108
+ ): TextEditorToolRendererRegistration {
2109
+ const merged =
2110
+ registration.fallback === true
2111
+ ? { ...registration, ...current, tool: registration.tool }
2112
+ : { ...current, ...registration, tool: registration.tool };
2113
+ const { fallback: _fallback, ...renderer } = merged;
2114
+ return renderer;
2310
2115
  }
2311
2116
 
2312
2117
  function replayMutationTools(
2313
- listener: TextMutationToolListener,
2314
- mutationTools: ReadonlyMap<string, AnyTextMutationToolRegistration>,
2315
- ): void
2316
- {
2317
- for (const registration of mutationTools.values())
2318
- {
2319
- listener(registration);
2320
- }
2118
+ listener: TextMutationToolListener,
2119
+ mutationTools: ReadonlyMap<string, AnyTextMutationToolRegistration>,
2120
+ ): void {
2121
+ for (const registration of mutationTools.values()) {
2122
+ listener(registration);
2123
+ }
2321
2124
  }
2322
2125
 
2323
2126
  function addMutationRegistration(
2324
- registration: AnyTextMutationToolRegistration,
2325
- mutationTools: Map<string, AnyTextMutationToolRegistration>,
2326
- registeredTools: Set<TextEditorToolId>,
2327
- listeners: Set<TextMutationToolListener>,
2328
- registerMutationTool: ((registration: AnyTextMutationToolRegistration, core: TextEditorCore) => void) | undefined,
2329
- core: TextEditorCore,
2330
- ): void
2331
- {
2332
- assertTextMutationToolRegistration(registration);
2333
-
2334
- if (mutationTools.has(registration.name))
2335
- {
2336
- throw new Error(`Mutation tool ${registration.name} is already registered`);
2337
- }
2338
-
2339
- mutationTools.set(registration.name, registration);
2340
- registeredTools.add(registration.name);
2341
-
2342
- for (const listener of listeners)
2343
- {
2344
- listener(registration);
2345
- }
2346
-
2347
- registerMutationTool?.(registration, core);
2127
+ registration: AnyTextMutationToolRegistration,
2128
+ mutationTools: Map<string, AnyTextMutationToolRegistration>,
2129
+ registeredTools: Set<TextEditorToolId>,
2130
+ listeners: Set<TextMutationToolListener>,
2131
+ registerMutationTool:
2132
+ | ((registration: AnyTextMutationToolRegistration, core: TextEditorCore) => void)
2133
+ | undefined,
2134
+ core: TextEditorCore,
2135
+ ): void {
2136
+ assertTextMutationToolRegistration(registration);
2137
+
2138
+ if (mutationTools.has(registration.name)) {
2139
+ throw new Error(`Mutation tool ${registration.name} is already registered`);
2140
+ }
2141
+
2142
+ mutationTools.set(registration.name, registration);
2143
+ registeredTools.add(registration.name);
2144
+
2145
+ for (const listener of listeners) {
2146
+ listener(registration);
2147
+ }
2148
+
2149
+ registerMutationTool?.(registration, core);
2348
2150
  }