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,45 +1,48 @@
1
- /** Runtime for intercepting streamed Pi tool calls. */
1
+ /**
2
+ Runtime for intercepting streamed Pi tool calls.
3
+ */
2
4
 
3
5
  import { Allow } from "partial-json";
4
6
  import {
5
- isToolCallAnnotation,
6
- type ToolCallAnnotation,
7
- withToolCallInterceptionDetails,
7
+ isToolCallAnnotation,
8
+ type ToolCallAnnotation,
9
+ withToolCallInterceptionDetails,
8
10
  } from "pi-agent-tool-call-interception";
9
11
  import { Guard } from "typebox-guard/guard";
10
12
 
11
13
  import { resolvePartial } from "./partial-json-resolver.js";
12
14
  import {
13
- type PartialToolRecoveryBatchEntry,
14
- PartialToolRecoveryRegistry,
15
- type PartialToolRecoveryResult,
15
+ type PartialToolRecoveryBatchEntry,
16
+ PartialToolRecoveryRegistry,
17
+ type PartialToolRecoveryResult,
16
18
  } from "./partial-tool-recovery.js";
17
19
  import { registerStreamingInterceptorProvider } from "./streaming-provider.js";
18
20
 
19
21
  import type {
20
- AgentToolResult,
21
- ExtensionAPI,
22
- ExtensionContext,
23
- MessageUpdateEvent,
22
+ AgentToolResult,
23
+ ExtensionAPI,
24
+ ExtensionContext,
25
+ MessageUpdateEvent,
24
26
  } from "@earendil-works/pi-coding-agent";
25
27
 
26
28
  export {
27
- getToolCallInterception,
28
- type ToolCallAnnotation,
29
- type ToolCallInterceptionDetails,
29
+ getToolCallInterception,
30
+ type ToolCallAnnotation,
31
+ type ToolCallInterceptionDetails,
30
32
  } from "pi-agent-tool-call-interception";
31
33
 
32
34
  type AssistantStreamEvent = MessageUpdateEvent["assistantMessageEvent"];
33
35
 
34
- interface PendingRecoveryBlock
35
- {
36
- readonly blocked: InterceptResult;
37
- readonly ctx: InterceptorContext;
36
+ interface PendingRecoveryBlock {
37
+ readonly blocked: InterceptResult;
38
+ readonly ctx: InterceptorContext;
38
39
  }
39
40
 
40
41
  // ── Utility type ──────────────────────────────────────────────────────
41
42
 
42
- /** Value or Promise of value — for sync/async interop. */
43
+ /**
44
+ Value or Promise of value — for sync/async interop.
45
+ */
43
46
  export type Awaitable<T> = T | Promise<T>;
44
47
 
45
48
  export const PARTIAL_TOOL_RECOVERY_CUSTOM_TYPE = "agentic-ide-partial-tool-recovery";
@@ -51,1185 +54,1133 @@ export type ToolCallAnnotationSink = (toolCallId: string, annotation: ToolCallAn
51
54
  const TOOL_CALL_ANNOTATION_EVENT = "pi-agent-text-editor/tool-call-annotation";
52
55
  const toolCallAnnotationSinkUnsubscribers = new WeakMap<ExtensionAPI, () => void>();
53
56
 
54
- interface ToolCallAnnotationEvent
55
- {
56
- readonly toolCallId: string;
57
- readonly annotation: ToolCallAnnotation;
57
+ interface ToolCallAnnotationEvent {
58
+ readonly toolCallId: string;
59
+ readonly annotation: ToolCallAnnotation;
58
60
  }
59
61
 
60
- export interface BlockedToolCallFact
61
- {
62
- readonly callId: string;
63
- readonly toolName: string;
64
- readonly arguments: Record<string, unknown>;
65
- readonly contentIndex?: number;
66
- readonly batchEntryIndex?: number;
67
- readonly details?: unknown;
68
- readonly result: AgentToolResult<unknown>;
69
- readonly nativeExecutionBlocked: boolean;
62
+ export interface BlockedToolCallFact {
63
+ readonly callId: string;
64
+ readonly toolName: string;
65
+ readonly arguments: Record<string, unknown>;
66
+ readonly contentIndex?: number;
67
+ readonly batchEntryIndex?: number;
68
+ readonly details?: unknown;
69
+ readonly result: AgentToolResult<unknown>;
70
+ readonly nativeExecutionBlocked: boolean;
70
71
  }
71
72
 
72
73
  export type BlockedToolCallSink = (blocked: BlockedToolCallFact) => void;
73
74
 
74
75
  // ── Public types ──────────────────────────────────────────────────────────
75
76
 
76
- export interface InterceptResult
77
- {
78
- message: {
79
- customType: string;
80
- content: string;
81
- display: boolean;
82
- details?: unknown;
83
- };
84
- annotation?: ToolCallAnnotation;
77
+ export interface InterceptResult {
78
+ message: {
79
+ customType: string;
80
+ content: string;
81
+ display: boolean;
82
+ details?: unknown;
83
+ };
84
+ annotation?: ToolCallAnnotation;
85
85
  }
86
86
 
87
- export interface GuardCallRecord
88
- {
89
- readonly originalArguments: Record<string, unknown>;
90
- readonly guardResult?: AgentToolResult<unknown>;
91
- readonly blockExecution?: boolean;
87
+ export interface GuardCallRecord {
88
+ readonly originalArguments: Record<string, unknown>;
89
+ readonly guardResult?: AgentToolResult<unknown>;
90
+ readonly blockExecution?: boolean;
92
91
  }
93
92
 
94
- export interface GuardInterception
95
- {
96
- readonly toolCallId: string;
97
- readonly arguments: Record<string, unknown>;
98
- readonly result: AgentToolResult<unknown>;
93
+ export interface GuardInterception {
94
+ readonly toolCallId: string;
95
+ readonly arguments: Record<string, unknown>;
96
+ readonly result: AgentToolResult<unknown>;
99
97
  }
100
98
 
101
- export interface InterceptorContext
102
- {
103
- toolCall: {
104
- id: string;
105
- name: string;
106
- arguments: Record<string, unknown>;
107
- thoughtSignature?: string;
108
- };
109
- args: Record<string, unknown>;
110
- /** Stream content index, used to isolate interceptor state. */
111
- /** Position and calls within the current streamed tool-call batch. */
112
- batchEntryIndex?: number;
113
- batchEntries?: readonly PartialToolRecoveryBatchEntry[];
114
- contentIndex?: number;
115
- /** Best-effort parsed arguments during streaming (set on toolcall_delta). */
116
- partialArgs?: Record<string, unknown>;
117
- cwd: string;
118
- signal: AbortSignal | undefined;
119
- /** Extension context with UI methods (select, input, editor, confirm, etc.). */
120
- ctx: ExtensionContext;
99
+ export interface InterceptorContext {
100
+ toolCall: {
101
+ id: string;
102
+ name: string;
103
+ arguments: Record<string, unknown>;
104
+ thoughtSignature?: string;
105
+ };
106
+ args: Record<string, unknown>;
107
+ /**
108
+ Stream content index, used to isolate interceptor state.
109
+ */
110
+ /**
111
+ Position and calls within the current streamed tool-call batch.
112
+ */
113
+ batchEntryIndex?: number;
114
+ batchEntries?: readonly PartialToolRecoveryBatchEntry[];
115
+ contentIndex?: number;
116
+ /**
117
+ Best-effort parsed arguments during streaming (set on toolcall_delta).
118
+ */
119
+ partialArgs?: Record<string, unknown>;
120
+ cwd: string;
121
+ signal: AbortSignal | undefined;
122
+ /**
123
+ Extension context with UI methods (select, input, editor, confirm, etc.).
124
+ */
125
+ ctx: ExtensionContext;
121
126
  }
122
127
 
123
- export interface ToolCallInterceptorHandler
124
- {
125
- /** Unique handler name (for debug/removal). */
126
- name: string;
127
- toolNames: string[];
128
- /** Block Pi's native tool_call before execution. Existing cooperative executors may leave this disabled. */
129
- blockExecution?: boolean;
130
- /**
131
- * Optional lifecycle hooks for handlers that keep per-content state.
132
- */
133
- onContentEnd?(contentIndex: number): void;
134
- onAgentEnd?(): void;
135
- onAbort?(contentIndex: number): void;
136
- /**
137
- * Predicate. Called on each toolcall_start/delta/end for toolNames.
138
- * Return InterceptResult — intercept (abort; return the result through tool_result).
139
- * Return undefined — skip, next handler.
140
- * Can be sync or async (returns Awaitable).
141
- */
142
- intercept(ctx: InterceptorContext): Awaitable<InterceptResult | undefined>;
128
+ export interface ToolCallInterceptorHandler {
129
+ /**
130
+ Unique handler name (for debug/removal).
131
+ */
132
+ name: string;
133
+ toolNames: string[];
134
+ /**
135
+ Block Pi's native tool_call before execution. Existing cooperative executors may leave this disabled.
136
+ */
137
+ blockExecution?: boolean;
138
+ /**
139
+ * Optional lifecycle hooks for handlers that keep per-content state.
140
+ */
141
+ onContentEnd?(contentIndex: number): void;
142
+ onAgentEnd?(): void;
143
+ onAbort?(contentIndex: number): void;
144
+ /**
145
+ * Predicate. Called on each toolcall_start/delta/end for toolNames.
146
+ * Return InterceptResult — intercept (abort; return the result through tool_result).
147
+ * Return undefined — skip, next handler.
148
+ * Can be sync or async (returns Awaitable).
149
+ */
150
+ intercept(context: InterceptorContext): Awaitable<InterceptResult | undefined>;
143
151
  }
144
152
 
145
- export interface ToolCallInterceptor
146
- {
147
- register(handler: ToolCallInterceptorHandler): void;
148
- unregister(name: string): void;
149
- registerRecovery(registration: Parameters<PartialToolRecoveryRegistry["register"]>[0]): void;
150
- unregisterRecovery(toolName: string): void;
151
- registerBlockedCallSink(sink: BlockedToolCallSink | undefined): void;
152
- processStreamEvent(event: AssistantStreamEvent, ctx: ExtensionContext): Promise<GuardInterception | undefined>;
153
- markStreamEventProcessed(event: AssistantStreamEvent): void;
154
- finalizeStreamInterception(contentIndex: number): void;
155
- getToolCallRecord(toolCallId: string): GuardCallRecord | undefined;
153
+ export interface ToolCallInterceptor {
154
+ register(handler: ToolCallInterceptorHandler): void;
155
+ unregister(name: string): void;
156
+ registerRecovery(registration: Parameters<PartialToolRecoveryRegistry["register"]>[0]): void;
157
+ unregisterRecovery(toolName: string): void;
158
+ registerBlockedCallSink(sink: BlockedToolCallSink | undefined): void;
159
+ processStreamEvent(
160
+ event: AssistantStreamEvent,
161
+ context: ExtensionContext,
162
+ ): Promise<GuardInterception | undefined>;
163
+ markStreamEventProcessed(event: AssistantStreamEvent): void;
164
+ finalizeStreamInterception(contentIndex: number): void;
165
+ getToolCallRecord(toolCallId: string): GuardCallRecord | undefined;
156
166
  }
157
167
 
158
168
  // ── Implementation ────────────────────────────────────────────────────────
159
169
 
160
- class InterceptorImpl implements ToolCallInterceptor
161
- {
162
- /** toolName → handler[] */
163
- private readonly handlers = new Map<string, ToolCallInterceptorHandler[]>();
164
- private readonly recoveryRegistry = new PartialToolRecoveryRegistry();
165
- /** All blocked calls collected during the current assistant batch. */
166
- private readonly pendingRecoveryBlocks: PendingRecoveryBlock[] = [];
167
- /** Short reason for the guard that aborted the current assistant message. */
168
- private pendingAbortReason: string | undefined;
169
- /** Source batch indexes that recovery actually applied. */
170
- private readonly recoveryAppliedBatchIndexes = new Set<number>();
171
- /** Accumulated raw partial JSON arguments per contentIndex. */
172
- private readonly partialBuffers = new Map<number, string>();
173
- /** Content items whose complete JSON arguments were already intercepted. */
174
- private readonly completeArgumentContentIndices = new Set<number>();
175
- /** Content items whose complete JSON arguments were already intercepted. */
176
- /** Completed/partial calls in the current assistant batch. */
177
- private readonly streamedBatchEntries = new Map<number, PartialToolRecoveryBatchEntry>();
178
- /** contentIndex → local position within the current edit batch. */
179
- private readonly batchEntryIndexes = new Map<number, number>();
180
- /** toolCallId → local batch entry index, retained until tool_result arrives. */
181
- private readonly toolCallBatchEntryIndexes = new Map<string, number>();
182
- /** Batch entries whose tool execution has already returned a result. */
183
- private readonly completedBatchEntryIndexes = new Set<number>();
184
- private nextBatchEntryIndex = 0;
185
- /** contentIndex → toolName (recorded on toolcall_start). */
186
- private readonly contentNames = new Map<number, string>();
187
- /** contentIndex → renderer/tool call id. */
188
- private readonly contentToolCallIds = new Map<number, string>();
189
- /** Annotations queued until a streamed content item exposes its id. */
190
- private readonly pendingToolCallAnnotations = new Map<number, ToolCallAnnotation[]>();
191
- private readonly emittedToolCallAnnotationKinds = new Map<number, Set<ToolCallAnnotation["kind"]>>();
192
-
193
- /** contentIndex → tool was aborted in toolcall_delta (skip toolcall_end dispatch). */
194
- private readonly abortedContentIndices = new Set<number>();
195
- /** Serialize asynchronous handler dispatch for each streamed content item. */
196
- private readonly dispatchQueues = new Map<number, Promise<GuardInterception | undefined>>();
197
- /** Abort listeners installed for active content items. */
198
- private readonly abortCleanups = new Map<number, () => void>();
199
- /** Stream events already dispatched by the provider wrapper. */
200
- private readonly processedStreamEvents = new WeakSet<object>();
201
- /** Provider events may be cloned before message_update; track tool events by stable identity too. */
202
- private readonly processedStreamEventKeys = new Map<string, number>();
203
- /** Original streamed arguments and the result returned by a guard. */
204
- private readonly toolCallRecords = new Map<string, GuardCallRecord>();
205
- private blockedCallSink: BlockedToolCallSink | undefined;
206
- constructor(private readonly pi: ExtensionAPI)
207
- {
208
- pi.on("tool_call", (event) =>
209
- {
210
- const record = this.toolCallRecords.get(event.toolCallId);
211
- const guardResult = record?.blockExecution ? record.guardResult : undefined;
212
-
213
- if (!guardResult)
214
- {
215
- return;
216
- }
217
-
218
- const reason = guardResult.content
219
- .filter((content) => content.type === "text")
220
- .map((content) => content.text)
221
- .join("\n");
222
-
223
- return {
224
- block: true,
225
- reason: reason || `Tool call ${event.toolName} was blocked by a streaming interceptor.`,
226
- };
227
- });
228
- pi.on("tool_result", (event) =>
229
- {
230
- const batchEntryIndex = this.toolCallBatchEntryIndexes.get(event.toolCallId);
231
-
232
- if (batchEntryIndex !== undefined)
233
- {
234
- this.completedBatchEntryIndexes.add(batchEntryIndex);
235
- }
236
-
237
- const guardResult = this.toolCallRecords.get(event.toolCallId)?.guardResult;
238
- this.toolCallRecords.delete(event.toolCallId);
239
-
240
- if (guardResult)
241
- {
242
- return {
243
- content: guardResult.content,
244
- details: guardResult.details,
245
- isError: true,
246
- };
247
- }
248
-
249
- return;
250
- });
251
- pi.on("message_update", async (event, ctx) =>
252
- {
253
- const streamEvent = event.assistantMessageEvent;
170
+ class InterceptorImpl implements ToolCallInterceptor {
171
+ /**
172
+ toolName → handler[]
173
+ */
174
+ private readonly handlers = new Map<string, ToolCallInterceptorHandler[]>();
175
+ private readonly recoveryRegistry = new PartialToolRecoveryRegistry();
176
+ /**
177
+ All blocked calls collected during the current assistant batch.
178
+ */
179
+ private readonly pendingRecoveryBlocks: PendingRecoveryBlock[] = [];
180
+ /**
181
+ Short reason for the guard that aborted the current assistant message.
182
+ */
183
+ private pendingAbortReason: string | undefined;
184
+ /**
185
+ Source batch indexes that recovery actually applied.
186
+ */
187
+ private readonly recoveryAppliedBatchIndexes = new Set<number>();
188
+ /**
189
+ Accumulated raw partial JSON arguments per contentIndex.
190
+ */
191
+ private readonly partialBuffers = new Map<number, string>();
192
+ /**
193
+ Content items whose complete JSON arguments were already intercepted.
194
+ */
195
+ private readonly completeArgumentContentIndices = new Set<number>();
196
+ /**
197
+ Content items whose complete JSON arguments were already intercepted.
198
+ */
199
+ /**
200
+ Completed/partial calls in the current assistant batch.
201
+ */
202
+ private readonly streamedBatchEntries = new Map<number, PartialToolRecoveryBatchEntry>();
203
+ /**
204
+ contentIndex → local position within the current edit batch.
205
+ */
206
+ private readonly batchEntryIndexes = new Map<number, number>();
207
+ /**
208
+ toolCallId → local batch entry index, retained until tool_result arrives.
209
+ */
210
+ private readonly toolCallBatchEntryIndexes = new Map<string, number>();
211
+ /**
212
+ Batch entries whose tool execution has already returned a result.
213
+ */
214
+ private readonly completedBatchEntryIndexes = new Set<number>();
215
+ private nextBatchEntryIndex = 0;
216
+ /**
217
+ contentIndex → toolName (recorded on toolcall_start).
218
+ */
219
+ private readonly contentNames = new Map<number, string>();
220
+ /**
221
+ contentIndex → renderer/tool call id.
222
+ */
223
+ private readonly contentToolCallIds = new Map<number, string>();
224
+ /**
225
+ Annotations queued until a streamed content item exposes its id.
226
+ */
227
+ private readonly pendingToolCallAnnotations = new Map<number, ToolCallAnnotation[]>();
228
+ private readonly emittedToolCallAnnotationKinds = new Map<
229
+ number,
230
+ Set<ToolCallAnnotation["kind"]>
231
+ >();
232
+
233
+ /**
234
+ contentIndex → tool was aborted in toolcall_delta (skip toolcall_end dispatch).
235
+ */
236
+ private readonly abortedContentIndices = new Set<number>();
237
+ /**
238
+ Serialize asynchronous handler dispatch for each streamed content item.
239
+ */
240
+ private readonly dispatchQueues = new Map<number, Promise<GuardInterception | undefined>>();
241
+ /**
242
+ Abort listeners installed for active content items.
243
+ */
244
+ private readonly abortCleanups = new Map<number, () => void>();
245
+ /**
246
+ Stream events already dispatched by the provider wrapper.
247
+ */
248
+ private readonly processedStreamEvents = new WeakSet<object>();
249
+ /**
250
+ Provider events may be cloned before message_update; track tool events by stable identity too.
251
+ */
252
+ private readonly processedStreamEventKeys = new Map<string, number>();
253
+ /**
254
+ Original streamed arguments and the result returned by a guard.
255
+ */
256
+ private readonly toolCallRecords = new Map<string, GuardCallRecord>();
257
+ private blockedCallSink: BlockedToolCallSink | undefined;
258
+ constructor(private readonly pi: ExtensionAPI) {
259
+ pi.on("tool_call", (event) => {
260
+ const record = this.toolCallRecords.get(event.toolCallId);
261
+ const guardResult = record?.blockExecution ? record.guardResult : undefined;
262
+
263
+ if (!guardResult) {
264
+ return;
265
+ }
254
266
 
255
- if (this.consumeProcessedStreamEvent(streamEvent))
256
- {
257
- return;
258
- }
267
+ const reason = guardResult.content
268
+ .filter((content) => content.type === "text")
269
+ .map((content) => content.text)
270
+ .join("\n");
259
271
 
260
- await this.processStreamEvent(streamEvent, ctx);
261
- });
272
+ return {
273
+ block: true,
274
+ reason: reason || `Tool call ${event.toolName} was blocked by a streaming interceptor.`,
275
+ };
276
+ });
277
+ pi.on("tool_result", (event) => {
278
+ const batchEntryIndex = this.toolCallBatchEntryIndexes.get(event.toolCallId);
262
279
 
263
- pi.on("message_end", async (event) =>
264
- {
265
- await this.finalizeRecovery();
266
- this.annotateIncompleteCalls();
267
-
268
- if (event.message.role !== "assistant")
269
- {
270
- return;
271
- }
272
-
273
- const reason = this.pendingAbortReason;
274
- this.pendingAbortReason = undefined;
275
-
276
- if (reason === undefined || event.message.stopReason !== "aborted")
277
- {
278
- return;
279
- }
280
-
281
- return {
282
- message: {
283
- ...event.message,
284
- errorMessage: reason,
285
- },
286
- };
287
- });
280
+ if (batchEntryIndex !== undefined) {
281
+ this.completedBatchEntryIndexes.add(batchEntryIndex);
282
+ }
288
283
 
289
- pi.on("agent_end", async () =>
290
- {
291
- await this.finalizeRecovery();
292
-
293
- for (const [contentIndex, entry] of this.streamedBatchEntries)
294
- {
295
- if (
296
- !entry.complete
297
- && !this.recoveryAppliedBatchIndexes.has(entry.index)
298
- && !this.emittedToolCallAnnotationKinds.get(contentIndex)?.has("stale-anchor")
299
- )
300
- {
301
- this.annotateContent(contentIndex, { kind: "aborted" });
302
- }
303
- }
304
-
305
- this.cleanupAll();
306
- });
307
- }
284
+ const guardResult = this.toolCallRecords.get(event.toolCallId)?.guardResult;
285
+ this.toolCallRecords.delete(event.toolCallId);
308
286
 
309
- processStreamEvent(event: AssistantStreamEvent, ctx: ExtensionContext): Promise<GuardInterception | undefined>
310
- {
311
- if (event.type === "toolcall_start")
312
- {
313
- const block = event.partial.content[event.contentIndex];
314
-
315
- if (block?.type === "toolCall")
316
- {
317
- const batchEntryIndex = this.getOrCreateBatchEntryIndex(event.contentIndex);
318
- this.contentNames.set(event.contentIndex, block.name);
319
-
320
- if (typeof block.id === "string")
321
- {
322
- this.bindToolCallId(event.contentIndex, block.id);
323
- }
324
-
325
- this.partialBuffers.set(event.contentIndex, "");
326
- this.streamedBatchEntries.set(event.contentIndex, {
327
- index: batchEntryIndex,
328
- toolName: block.name,
329
- args: {},
330
- complete: false,
331
- });
332
- this.installAbortCleanup(event.contentIndex, ctx.signal);
333
- }
334
-
335
- return Promise.resolve(undefined as GuardInterception | undefined);
336
- }
287
+ if (guardResult) {
288
+ return {
289
+ content: guardResult.content,
290
+ details: guardResult.details,
291
+ isError: true,
292
+ };
293
+ }
337
294
 
338
- if (event.type === "toolcall_delta")
339
- {
340
- return this.enqueue(event.contentIndex, async () =>
341
- {
342
- const toolName = this.contentNames.get(event.contentIndex);
343
- const toolCallId = this.contentToolCallIds.get(event.contentIndex);
344
-
345
- if (!toolName)
346
- {
347
- return;
348
- }
349
-
350
- const buffer = (this.partialBuffers.get(event.contentIndex) ?? "") + event.delta;
351
- this.partialBuffers.set(event.contentIndex, buffer);
352
- this.installAbortCleanup(event.contentIndex, ctx.signal);
353
- const partialArgs = resolvePartial(buffer, Allow.OBJ | Allow.ARR) ?? {};
354
- const completeArgs = parseCompleteArguments(buffer);
355
- const batchEntryIndex = this.getOrCreateBatchEntryIndex(event.contentIndex);
356
- this.streamedBatchEntries.set(event.contentIndex, {
357
- index: batchEntryIndex,
358
- toolName,
359
- args: partialArgs,
360
- complete: completeArgs !== undefined,
361
- });
362
-
363
- const handlers = this.handlers.get(toolName);
364
-
365
- if (
366
- !toolCallId || !handlers || handlers.length === 0
367
- || (!completeArgs && Object.keys(partialArgs).length === 0)
368
- )
369
- {
370
- return;
371
- }
372
-
373
- const hasCompleteArgs = completeArgs !== undefined;
374
-
375
- if (hasCompleteArgs && this.completeArgumentContentIndices.has(event.contentIndex))
376
- {
377
- return;
378
- }
379
-
380
- if (hasCompleteArgs)
381
- {
382
- this.completeArgumentContentIndices.add(event.contentIndex);
383
- }
384
-
385
- const args = completeArgs ?? partialArgs;
386
- const interception = await this.dispatchHandlers(handlers, {
387
- toolCall: { id: toolCallId, name: toolName, arguments: args },
388
- args,
389
- ...(hasCompleteArgs ? {} : { partialArgs }),
390
- batchEntryIndex,
391
- batchEntries: this.getBatchEntries(batchEntryIndex),
392
- contentIndex: event.contentIndex,
393
- cwd: ctx.cwd,
394
- signal: ctx.signal,
395
- ctx,
396
- });
397
-
398
- if (interception)
399
- {
400
- this.rememberOriginalArguments(interception.toolCallId, interception.arguments);
401
- }
402
-
403
- return interception;
404
- });
405
- }
295
+ return;
296
+ });
297
+ pi.on("message_update", async (event, context) => {
298
+ const streamEvent = event.assistantMessageEvent;
406
299
 
407
- if (event.type === "toolcall_end")
408
- {
409
- return this.enqueue(event.contentIndex, async () =>
410
- {
411
- const toolName = event.toolCall.name;
412
- const handlers = this.handlers.get(toolName);
413
- const batchEntryIndex = this.getOrCreateBatchEntryIndex(event.contentIndex);
414
- this.bindToolCallId(event.contentIndex, event.toolCall.id);
415
- const previous = this.toolCallRecords.get(event.toolCall.id);
416
- this.toolCallRecords.set(event.toolCall.id, {
417
- originalArguments: structuredClone(event.toolCall.arguments),
418
- ...(previous?.guardResult ? { guardResult: previous.guardResult } : {}),
419
- ...(previous?.blockExecution ? { blockExecution: true } : {}),
420
- });
421
- this.streamedBatchEntries.set(event.contentIndex, {
422
- index: batchEntryIndex,
423
- toolName,
424
- args: event.toolCall.arguments,
425
- complete: false,
426
- });
427
-
428
- const shouldIntercept = !this.completeArgumentContentIndices.has(event.contentIndex);
429
- let interception: GuardInterception | undefined;
430
-
431
- if (shouldIntercept)
432
- {
433
- this.completeArgumentContentIndices.add(event.contentIndex);
434
- interception = handlers && handlers.length > 0
435
- ? await this.dispatchHandlers(handlers, {
436
- toolCall: event.toolCall,
437
- args: event.toolCall.arguments,
438
- batchEntryIndex,
439
- batchEntries: this.getBatchEntries(batchEntryIndex),
440
- contentIndex: event.contentIndex,
441
- cwd: ctx.cwd,
442
- signal: ctx.signal,
443
- ctx,
444
- })
445
- : undefined;
446
- }
447
-
448
- const batchEntry = this.streamedBatchEntries.get(event.contentIndex);
449
-
450
- if (batchEntry)
451
- {
452
- this.streamedBatchEntries.set(event.contentIndex, { ...batchEntry, complete: true });
453
- }
454
-
455
- this.cleanupContent(event.contentIndex, toolName);
456
- return interception;
457
- });
458
- }
300
+ if (this.consumeProcessedStreamEvent(streamEvent)) {
301
+ return;
302
+ }
459
303
 
460
- return Promise.resolve(undefined as GuardInterception | undefined);
461
- }
462
- markStreamEventProcessed(event: AssistantStreamEvent): void
463
- {
464
- this.processedStreamEvents.add(event);
465
- const key = toolStreamEventKey(event);
466
-
467
- if (key !== undefined)
468
- {
469
- this.processedStreamEventKeys.set(key, (this.processedStreamEventKeys.get(key) ?? 0) + 1);
470
- }
471
- }
304
+ await this.processStreamEvent(streamEvent, context);
305
+ });
472
306
 
473
- private consumeProcessedStreamEvent(event: AssistantStreamEvent): boolean
474
- {
475
- const sameEvent = this.processedStreamEvents.delete(event);
476
- const key = toolStreamEventKey(event);
307
+ pi.on("message_end", async (event) => {
308
+ await this.finalizeRecovery();
309
+ this.annotateIncompleteCalls();
477
310
 
478
- if (key === undefined)
479
- {
480
- return sameEvent;
481
- }
311
+ if (event.message.role !== "assistant") {
312
+ return;
313
+ }
482
314
 
483
- const count = this.processedStreamEventKeys.get(key) ?? 0;
315
+ const reason = this.pendingAbortReason;
316
+ this.pendingAbortReason = undefined;
484
317
 
485
- if (count === 0)
486
- {
487
- return sameEvent;
488
- }
318
+ if (reason === undefined || event.message.stopReason !== "aborted") {
319
+ return;
320
+ }
489
321
 
490
- if (count === 1)
491
- {
492
- this.processedStreamEventKeys.delete(key);
493
- }
494
- else
495
- {
496
- this.processedStreamEventKeys.set(key, count - 1);
322
+ return {
323
+ message: {
324
+ ...event.message,
325
+ errorMessage: reason,
326
+ },
327
+ };
328
+ });
329
+
330
+ pi.on("agent_end", async () => {
331
+ await this.finalizeRecovery();
332
+
333
+ for (const [contentIndex, entry] of this.streamedBatchEntries) {
334
+ if (
335
+ !entry.complete &&
336
+ !this.recoveryAppliedBatchIndexes.has(entry.index) &&
337
+ !this.emittedToolCallAnnotationKinds.get(contentIndex)?.has("stale-anchor")
338
+ ) {
339
+ this.annotateContent(contentIndex, { kind: "aborted" });
497
340
  }
341
+ }
498
342
 
499
- return true;
500
- }
343
+ this.cleanupAll();
344
+ });
345
+ }
501
346
 
502
- finalizeStreamInterception(contentIndex: number): void
503
- {
504
- this.cleanupTransientContent(contentIndex, undefined, true);
505
- }
347
+ processStreamEvent(
348
+ event: AssistantStreamEvent,
349
+ context: ExtensionContext,
350
+ ): Promise<GuardInterception | undefined> {
351
+ if (event.type === "toolcall_start") {
352
+ const block = event.partial.content[event.contentIndex];
506
353
 
507
- getToolCallRecord(toolCallId: string): GuardCallRecord | undefined
508
- {
509
- return this.toolCallRecords.get(toolCallId);
510
- }
354
+ if (block?.type === "toolCall") {
355
+ const batchEntryIndex = this.getOrCreateBatchEntryIndex(event.contentIndex);
356
+ this.contentNames.set(event.contentIndex, block.name);
511
357
 
512
- private rememberOriginalArguments(toolCallId: string, originalArguments: Record<string, unknown>): void
513
- {
514
- const record = this.toolCallRecords.get(toolCallId);
515
-
516
- if (record)
517
- {
518
- this.toolCallRecords.set(toolCallId, {
519
- originalArguments: structuredClone(originalArguments),
520
- ...(record.guardResult ? { guardResult: record.guardResult } : {}),
521
- ...(record.blockExecution ? { blockExecution: true } : {}),
522
- });
358
+ if (typeof block.id === "string") {
359
+ this.bindToolCallId(event.contentIndex, block.id);
523
360
  }
524
- }
525
361
 
526
- private async dispatchHandlers(
527
- handlers: readonly ToolCallInterceptorHandler[],
528
- ctx: InterceptorContext,
529
- ): Promise<GuardInterception | undefined>
530
- {
531
- for (const handler of handlers)
532
- {
533
- const result = await handler.intercept(ctx);
534
-
535
- if (result !== undefined)
536
- {
537
- this.pendingRecoveryBlocks.push({ blocked: result, ctx });
538
- const guardResult: AgentToolResult<unknown> = {
539
- content: [{ type: "text", text: result.message.content }],
540
- details: result.message.details ?? null,
541
- };
542
- this.blockedCallSink?.({
543
- callId: ctx.toolCall.id,
544
- toolName: ctx.toolCall.name,
545
- arguments: structuredClone(ctx.args),
546
- ...(ctx.contentIndex === undefined ? {} : { contentIndex: ctx.contentIndex }),
547
- ...(ctx.batchEntryIndex === undefined ? {} : { batchEntryIndex: ctx.batchEntryIndex }),
548
- ...(result.message.details === undefined ? {} : { details: result.message.details }),
549
- result: guardResult,
550
- nativeExecutionBlocked: handler.blockExecution === true,
551
- });
552
- return {
553
- toolCallId: ctx.toolCall.id,
554
- arguments: structuredClone(ctx.args),
555
- result: this.abortToolCall(result, ctx, handler.name, handler.blockExecution === true),
556
- };
557
- }
558
- }
362
+ this.partialBuffers.set(event.contentIndex, "");
363
+ this.streamedBatchEntries.set(event.contentIndex, {
364
+ index: batchEntryIndex,
365
+ toolName: block.name,
366
+ args: {},
367
+ complete: false,
368
+ });
369
+ this.installAbortCleanup(event.contentIndex, context.signal);
370
+ }
559
371
 
560
- return undefined;
372
+ return Promise.resolve(undefined as GuardInterception | undefined);
561
373
  }
562
- private annotateIncompleteCalls(): void
563
- {
564
- for (const [contentIndex, entry] of this.streamedBatchEntries)
565
- {
566
- if (
567
- !entry.complete
568
- && !this.recoveryAppliedBatchIndexes.has(entry.index)
569
- && !this.emittedToolCallAnnotationKinds.get(contentIndex)?.has("stale-anchor")
570
- )
571
- {
572
- this.annotateContent(contentIndex, { kind: "aborted" });
573
- }
374
+
375
+ if (event.type === "toolcall_delta") {
376
+ return this.enqueue(event.contentIndex, async () => {
377
+ const toolName = this.contentNames.get(event.contentIndex);
378
+ const toolCallId = this.contentToolCallIds.get(event.contentIndex);
379
+
380
+ if (!toolName) {
381
+ return;
574
382
  }
575
- }
576
383
 
577
- private bindToolCallId(contentIndex: number, toolCallId: string): void
578
- {
579
- this.contentToolCallIds.set(contentIndex, toolCallId);
580
- const batchEntryIndex = this.batchEntryIndexes.get(contentIndex);
384
+ const buffer = (this.partialBuffers.get(event.contentIndex) ?? "") + event.delta;
385
+ this.partialBuffers.set(event.contentIndex, buffer);
386
+ this.installAbortCleanup(event.contentIndex, context.signal);
387
+ const partialArguments = resolvePartial(buffer, Allow.OBJ | Allow.ARR) ?? {};
388
+ const completeArguments = parseCompleteArguments(buffer);
389
+ const batchEntryIndex = this.getOrCreateBatchEntryIndex(event.contentIndex);
390
+ this.streamedBatchEntries.set(event.contentIndex, {
391
+ index: batchEntryIndex,
392
+ toolName,
393
+ args: partialArguments,
394
+ complete: completeArguments !== undefined,
395
+ });
396
+
397
+ const handlers = this.handlers.get(toolName);
581
398
 
582
- if (batchEntryIndex !== undefined)
583
- {
584
- this.toolCallBatchEntryIndexes.set(toolCallId, batchEntryIndex);
399
+ if (
400
+ !toolCallId ||
401
+ !handlers ||
402
+ handlers.length === 0 ||
403
+ (!completeArguments && Object.keys(partialArguments).length === 0)
404
+ ) {
405
+ return;
585
406
  }
586
407
 
587
- const pending = this.pendingToolCallAnnotations.get(contentIndex);
408
+ const hasCompleteArguments = completeArguments !== undefined;
409
+
410
+ if (hasCompleteArguments && this.completeArgumentContentIndices.has(event.contentIndex)) {
411
+ return;
412
+ }
588
413
 
589
- if (!pending)
590
- {
591
- return;
414
+ if (hasCompleteArguments) {
415
+ this.completeArgumentContentIndices.add(event.contentIndex);
592
416
  }
593
417
 
594
- for (const annotation of pending)
595
- {
596
- this.emitToolCallAnnotation(toolCallId, annotation);
418
+ const arguments_ = completeArguments ?? partialArguments;
419
+ const interception = await this.dispatchHandlers(handlers, {
420
+ toolCall: { id: toolCallId, name: toolName, arguments: arguments_ },
421
+ args: arguments_,
422
+ ...(!hasCompleteArguments && { partialArgs: partialArguments }),
423
+ batchEntryIndex,
424
+ batchEntries: this.getBatchEntries(batchEntryIndex),
425
+ contentIndex: event.contentIndex,
426
+ cwd: context.cwd,
427
+ signal: context.signal,
428
+ ctx: context,
429
+ });
430
+
431
+ if (interception) {
432
+ this.rememberOriginalArguments(interception.toolCallId, interception.arguments);
597
433
  }
598
434
 
599
- this.pendingToolCallAnnotations.delete(contentIndex);
435
+ return interception;
436
+ });
600
437
  }
601
438
 
602
- private annotateContent(contentIndex: number, annotation: ToolCallAnnotation): void
603
- {
604
- const emitted = this.emittedToolCallAnnotationKinds.get(contentIndex) ?? new Set<ToolCallAnnotation["kind"]>();
439
+ if (event.type === "toolcall_end") {
440
+ return this.enqueue(event.contentIndex, async () => {
441
+ const toolName = event.toolCall.name;
442
+ const handlers = this.handlers.get(toolName);
443
+ const batchEntryIndex = this.getOrCreateBatchEntryIndex(event.contentIndex);
444
+ this.bindToolCallId(event.contentIndex, event.toolCall.id);
445
+ const previous = this.toolCallRecords.get(event.toolCall.id);
446
+ this.toolCallRecords.set(event.toolCall.id, {
447
+ originalArguments: structuredClone(event.toolCall.arguments),
448
+ ...(previous?.guardResult && { guardResult: previous.guardResult }),
449
+ ...(previous?.blockExecution && { blockExecution: true }),
450
+ });
451
+ this.streamedBatchEntries.set(event.contentIndex, {
452
+ index: batchEntryIndex,
453
+ toolName,
454
+ args: event.toolCall.arguments,
455
+ complete: false,
456
+ });
605
457
 
606
- if (emitted.has(annotation.kind))
607
- {
608
- return;
458
+ const shouldIntercept = !this.completeArgumentContentIndices.has(event.contentIndex);
459
+ let interception: GuardInterception | undefined;
460
+
461
+ if (shouldIntercept) {
462
+ this.completeArgumentContentIndices.add(event.contentIndex);
463
+ interception =
464
+ handlers && handlers.length > 0
465
+ ? await this.dispatchHandlers(handlers, {
466
+ toolCall: event.toolCall,
467
+ args: event.toolCall.arguments,
468
+ batchEntryIndex,
469
+ batchEntries: this.getBatchEntries(batchEntryIndex),
470
+ contentIndex: event.contentIndex,
471
+ cwd: context.cwd,
472
+ signal: context.signal,
473
+ ctx: context,
474
+ })
475
+ : undefined;
609
476
  }
610
477
 
611
- emitted.add(annotation.kind);
612
- this.emittedToolCallAnnotationKinds.set(contentIndex, emitted);
613
-
614
- const toolCallId = this.contentToolCallIds.get(contentIndex);
478
+ const batchEntry = this.streamedBatchEntries.get(event.contentIndex);
615
479
 
616
- if (toolCallId)
617
- {
618
- this.emitToolCallAnnotation(toolCallId, annotation);
619
- return;
480
+ if (batchEntry) {
481
+ this.streamedBatchEntries.set(event.contentIndex, { ...batchEntry, complete: true });
620
482
  }
621
483
 
622
- const pending = this.pendingToolCallAnnotations.get(contentIndex) ?? [];
623
- pending.push(annotation);
624
- this.pendingToolCallAnnotations.set(contentIndex, pending);
484
+ this.cleanupContent(event.contentIndex, toolName);
485
+ return interception;
486
+ });
625
487
  }
626
488
 
627
- private emitToolCallAnnotation(toolCallId: string, annotation: ToolCallAnnotation): void
628
- {
629
- const event = { toolCallId, annotation } satisfies ToolCallAnnotationEvent;
630
- this.pi.events.emit(TOOL_CALL_ANNOTATION_EVENT, event);
489
+ return Promise.resolve(undefined as GuardInterception | undefined);
490
+ }
491
+ markStreamEventProcessed(event: AssistantStreamEvent): void {
492
+ this.processedStreamEvents.add(event);
493
+ const key = toolStreamEventKey(event);
494
+
495
+ if (key !== undefined) {
496
+ this.processedStreamEventKeys.set(key, (this.processedStreamEventKeys.get(key) ?? 0) + 1);
631
497
  }
498
+ }
632
499
 
633
- private getOrCreateBatchEntryIndex(contentIndex: number): number
634
- {
635
- const existing = this.batchEntryIndexes.get(contentIndex);
500
+ private consumeProcessedStreamEvent(event: AssistantStreamEvent): boolean {
501
+ const isSameEvent = this.processedStreamEvents.delete(event);
502
+ const key = toolStreamEventKey(event);
636
503
 
637
- if (existing !== undefined)
638
- {
639
- return existing;
640
- }
504
+ if (key === undefined) {
505
+ return isSameEvent;
506
+ }
507
+
508
+ const count = this.processedStreamEventKeys.get(key) ?? 0;
641
509
 
642
- const created = this.nextBatchEntryIndex;
643
- this.nextBatchEntryIndex += 1;
644
- this.batchEntryIndexes.set(contentIndex, created);
645
- return created;
510
+ if (count === 0) {
511
+ return isSameEvent;
646
512
  }
647
513
 
648
- private getBatchEntries(batchEntryIndex: number): readonly PartialToolRecoveryBatchEntry[]
649
- {
650
- return [...this.streamedBatchEntries.values()]
651
- .filter((entry) => entry.index <= batchEntryIndex)
652
- .sort((left, right) => left.index - right.index);
514
+ if (count === 1) {
515
+ this.processedStreamEventKeys.delete(key);
516
+ } else {
517
+ this.processedStreamEventKeys.set(key, count - 1);
653
518
  }
654
519
 
655
- private getAllBatchEntries(): readonly PartialToolRecoveryBatchEntry[]
656
- {
657
- return [...this.streamedBatchEntries.values()]
658
- .sort((left, right) => left.index - right.index);
520
+ return true;
521
+ }
522
+
523
+ finalizeStreamInterception(contentIndex: number): void {
524
+ this.cleanupTransientContent(contentIndex, undefined, true);
525
+ }
526
+
527
+ getToolCallRecord(toolCallId: string): GuardCallRecord | undefined {
528
+ return this.toolCallRecords.get(toolCallId);
529
+ }
530
+
531
+ private rememberOriginalArguments(
532
+ toolCallId: string,
533
+ originalArguments: Record<string, unknown>,
534
+ ): void {
535
+ const record = this.toolCallRecords.get(toolCallId);
536
+
537
+ if (record) {
538
+ this.toolCallRecords.set(toolCallId, {
539
+ originalArguments: structuredClone(originalArguments),
540
+ ...(record.guardResult && { guardResult: record.guardResult }),
541
+ ...(record.blockExecution && { blockExecution: true }),
542
+ });
659
543
  }
544
+ }
660
545
 
661
- private abortToolCall(
662
- result: InterceptResult,
663
- ctx: InterceptorContext,
664
- handlerName: string,
665
- blockExecution: boolean,
666
- ): AgentToolResult<unknown>
667
- {
668
- const reason = abortReason(result, handlerName);
669
- const annotation: ToolCallAnnotation = result.annotation
670
- ? result.annotation.kind === "aborted" && result.annotation.label === undefined
671
- ? { ...result.annotation, label: reason }
672
- : result.annotation
673
- : (result.message.customType === "text-editor-stale-anchor-block"
674
- ? { kind: "stale-anchor", label: reason }
675
- : { kind: "aborted", label: reason, color: "error" });
676
-
677
- if (ctx.contentIndex !== undefined)
678
- {
679
- this.abortedContentIndices.add(ctx.contentIndex);
680
- this.annotateContent(ctx.contentIndex, annotation);
681
- }
546
+ private async dispatchHandlers(
547
+ handlers: readonly ToolCallInterceptorHandler[],
548
+ context: InterceptorContext,
549
+ ): Promise<GuardInterception | undefined> {
550
+ for (const handler of handlers) {
551
+ const result = await handler.intercept(context);
682
552
 
553
+ if (result !== undefined) {
554
+ this.pendingRecoveryBlocks.push({ blocked: result, ctx: context });
683
555
  const guardResult: AgentToolResult<unknown> = {
684
- content: [{ type: "text", text: result.message.content }],
685
- details: withToolCallInterceptionDetails(result.message.details, annotation, reason),
556
+ content: [{ type: "text", text: result.message.content }],
557
+ details: result.message.details ?? null,
686
558
  };
687
- this.toolCallRecords.set(ctx.toolCall.id, {
688
- originalArguments: structuredClone(ctx.args),
689
- guardResult,
690
- ...(blockExecution ? { blockExecution: true } : {}),
559
+ this.blockedCallSink?.({
560
+ callId: context.toolCall.id,
561
+ toolName: context.toolCall.name,
562
+ arguments: structuredClone(context.args),
563
+ ...(context.contentIndex !== undefined && { contentIndex: context.contentIndex }),
564
+ ...(context.batchEntryIndex !== undefined && {
565
+ batchEntryIndex: context.batchEntryIndex,
566
+ }),
567
+ ...(result.message.details !== undefined && { details: result.message.details }),
568
+ result: guardResult,
569
+ nativeExecutionBlocked: handler.blockExecution === true,
691
570
  });
692
- return guardResult;
571
+ return {
572
+ toolCallId: context.toolCall.id,
573
+ arguments: structuredClone(context.args),
574
+ result: this.abortToolCall(
575
+ result,
576
+ context,
577
+ handler.name,
578
+ handler.blockExecution === true,
579
+ ),
580
+ };
581
+ }
693
582
  }
694
583
 
695
- private async finalizeRecovery(): Promise<void>
696
- {
697
- const pending = this.pendingRecoveryBlocks.splice(0);
698
-
699
- if (pending.length === 0)
700
- {
701
- return;
702
- }
703
-
704
- const groups = new Map<string, PendingRecoveryBlock[]>();
584
+ return undefined;
585
+ }
586
+ private annotateIncompleteCalls(): void {
587
+ for (const [contentIndex, entry] of this.streamedBatchEntries) {
588
+ if (
589
+ !entry.complete &&
590
+ !this.recoveryAppliedBatchIndexes.has(entry.index) &&
591
+ !this.emittedToolCallAnnotationKinds.get(contentIndex)?.has("stale-anchor")
592
+ ) {
593
+ this.annotateContent(contentIndex, { kind: "aborted" });
594
+ }
595
+ }
596
+ }
705
597
 
706
- for (const block of pending)
707
- {
708
- const recoveryKey = this.recoveryRegistry.recoveryKeyFor(block.ctx.toolCall.name);
598
+ private bindToolCallId(contentIndex: number, toolCallId: string): void {
599
+ this.contentToolCallIds.set(contentIndex, toolCallId);
600
+ const batchEntryIndex = this.batchEntryIndexes.get(contentIndex);
709
601
 
710
- if (recoveryKey === undefined)
711
- {
712
- continue;
713
- }
602
+ if (batchEntryIndex !== undefined) {
603
+ this.toolCallBatchEntryIndexes.set(toolCallId, batchEntryIndex);
604
+ }
714
605
 
715
- const group = groups.get(recoveryKey) ?? [];
716
- group.push(block);
717
- groups.set(recoveryKey, group);
718
- }
606
+ const pending = this.pendingToolCallAnnotations.get(contentIndex);
719
607
 
720
- for (const group of groups.values())
721
- {
722
- const first = group[0];
723
-
724
- if (!first)
725
- {
726
- continue;
727
- }
728
-
729
- const finalResult = await this.recoverIfNeeded(
730
- first.blocked,
731
- first.ctx,
732
- this.getAllBatchEntries(),
733
- group,
734
- );
735
-
736
- if (finalResult === first.blocked)
737
- {
738
- continue;
739
- }
740
-
741
- const details = finalResult.message.details;
742
- const recovery = Guard.IsObjectNotArray(details) && Guard.IsObjectNotArray(details.recovery)
743
- ? details.recovery
744
- : undefined;
745
- const appliedEntries = recovery?.appliedEntries;
746
-
747
- if (Array.isArray(appliedEntries))
748
- {
749
- for (const index of appliedEntries)
750
- {
751
- if (typeof index === "number")
752
- {
753
- this.recoveryAppliedBatchIndexes.add(index);
754
- }
755
- }
756
- }
757
- }
608
+ if (!pending) {
609
+ return;
758
610
  }
759
611
 
760
- private async recoverIfNeeded(
761
- result: InterceptResult,
762
- ctx: InterceptorContext,
763
- finalBatchEntries: readonly PartialToolRecoveryBatchEntry[],
764
- blocks: readonly PendingRecoveryBlock[],
765
- ): Promise<InterceptResult>
766
- {
767
- if (ctx.contentIndex === undefined)
768
- {
769
- return result;
770
- }
612
+ for (const annotation of pending) {
613
+ this.emitToolCallAnnotation(toolCallId, annotation);
614
+ }
771
615
 
772
- const details = result.message.details;
773
- const staleEntryIndex = Guard.IsObjectNotArray(details) && typeof details.entryIndex === "number"
774
- ? details.entryIndex
775
- : undefined;
776
- const blockedEntryIndexes = [
777
- ...new Set(
778
- blocks
779
- .map((block) => block.ctx.batchEntryIndex)
780
- .filter((index): index is number => index !== undefined),
781
- ),
782
- ];
783
- const blockedToolCallIds = [...new Set(blocks.map((block) => block.ctx.toolCall.id))];
784
- const blockedDetails = blocks.map((block) => block.blocked.message.details);
785
- const first = blocks[0];
786
- const recoveryKey = first
787
- ? this.recoveryRegistry.recoveryKeyFor(first.ctx.toolCall.name)
788
- : undefined;
789
-
790
- if (!recoveryKey)
791
- {
792
- return result;
793
- }
616
+ this.pendingToolCallAnnotations.delete(contentIndex);
617
+ }
794
618
 
795
- const recovery = await this.recoveryRegistry.recover({
796
- contentIndex: ctx.contentIndex,
797
- toolCallId: ctx.toolCall.id,
798
- toolName: ctx.toolCall.name,
799
- ...(staleEntryIndex === undefined ? {} : { staleEntryIndex }),
800
- staleDetails: details,
801
- ...(ctx.partialArgs ? { partialArgs: ctx.partialArgs } : {}),
802
- args: ctx.args,
803
- batchEntries: finalBatchEntries,
804
- ...(ctx.batchEntryIndex === undefined ? {} : { batchEntryIndex: ctx.batchEntryIndex }),
805
- recoverCompleteBatch: true,
806
- completedEntryIndexes: [...this.completedBatchEntryIndexes],
807
- blockedEntryIndexes,
808
- blockedToolCallIds,
809
- blockedDetails,
810
- recoveryKey,
811
- cwd: ctx.cwd,
812
- ctx: ctx.ctx,
813
- });
619
+ private annotateContent(contentIndex: number, annotation: ToolCallAnnotation): void {
620
+ const emitted =
621
+ this.emittedToolCallAnnotationKinds.get(contentIndex) ??
622
+ new Set<ToolCallAnnotation["kind"]>();
814
623
 
815
- return recovery && (recovery.appliedEntries.length > 0 || recovery.skippedEntries.length > 0)
816
- ? makeRecoveryResult(result, recovery)
817
- : result;
624
+ if (emitted.has(annotation.kind)) {
625
+ return;
818
626
  }
819
- private async enqueue(
820
- contentIndex: number,
821
- task: () => Promise<GuardInterception | undefined>,
822
- ): Promise<GuardInterception | undefined>
823
- {
824
- const previous = this.dispatchQueues.get(contentIndex) ?? Promise.resolve();
825
- const current = previous.catch(() =>
826
- {}).then(task);
827
- this.dispatchQueues.set(contentIndex, current);
828
-
829
- try
830
- {
831
- return await current;
832
- }
833
- finally
834
- {
835
- if (this.dispatchQueues.get(contentIndex) === current)
836
- {
837
- this.dispatchQueues.delete(contentIndex);
838
- }
839
- }
627
+
628
+ emitted.add(annotation.kind);
629
+ this.emittedToolCallAnnotationKinds.set(contentIndex, emitted);
630
+
631
+ const toolCallId = this.contentToolCallIds.get(contentIndex);
632
+
633
+ if (toolCallId) {
634
+ this.emitToolCallAnnotation(toolCallId, annotation);
635
+ return;
840
636
  }
841
637
 
842
- private installAbortCleanup(contentIndex: number, signal: AbortSignal | undefined): void
843
- {
844
- if (!signal || this.abortCleanups.has(contentIndex))
845
- {
846
- return;
847
- }
638
+ const pending = this.pendingToolCallAnnotations.get(contentIndex) ?? [];
639
+ pending.push(annotation);
640
+ this.pendingToolCallAnnotations.set(contentIndex, pending);
641
+ }
848
642
 
849
- const listener = () =>
850
- {
851
- const toolName = this.contentNames.get(contentIndex);
852
- const handlers = toolName ? this.handlers.get(toolName) : undefined;
643
+ private emitToolCallAnnotation(toolCallId: string, annotation: ToolCallAnnotation): void {
644
+ const event = { toolCallId, annotation } satisfies ToolCallAnnotationEvent;
645
+ this.pi.events.emit(TOOL_CALL_ANNOTATION_EVENT, event);
646
+ }
853
647
 
854
- for (const handler of handlers ?? [])
855
- {
856
- handler.onAbort?.(contentIndex);
857
- }
858
- };
648
+ private getOrCreateBatchEntryIndex(contentIndex: number): number {
649
+ const existing = this.batchEntryIndexes.get(contentIndex);
859
650
 
860
- signal.addEventListener("abort", listener, { once: true });
861
- this.abortCleanups.set(contentIndex, () =>
862
- {
863
- signal.removeEventListener("abort", listener);
864
- });
651
+ if (existing !== undefined) {
652
+ return existing;
865
653
  }
866
654
 
867
- private cleanupContent(contentIndex: number, toolName?: string): void
868
- {
869
- this.cleanupTransientContent(contentIndex, toolName);
870
- this.recoveryRegistry.cleanup(contentIndex);
655
+ const created = this.nextBatchEntryIndex;
656
+ this.nextBatchEntryIndex += 1;
657
+ this.batchEntryIndexes.set(contentIndex, created);
658
+ return created;
659
+ }
660
+
661
+ private getBatchEntries(batchEntryIndex: number): readonly PartialToolRecoveryBatchEntry[] {
662
+ return [...this.streamedBatchEntries.values()]
663
+ .filter((entry) => entry.index <= batchEntryIndex)
664
+ .sort((left, right) => left.index - right.index);
665
+ }
666
+
667
+ private getAllBatchEntries(): readonly PartialToolRecoveryBatchEntry[] {
668
+ return [...this.streamedBatchEntries.values()].sort((left, right) => left.index - right.index);
669
+ }
670
+
671
+ private abortToolCall(
672
+ result: InterceptResult,
673
+ context: InterceptorContext,
674
+ handlerName: string,
675
+ blockExecution: boolean,
676
+ ): AgentToolResult<unknown> {
677
+ const reason = abortReason(result, handlerName);
678
+ const annotation: ToolCallAnnotation = result.annotation
679
+ ? result.annotation.kind === "aborted" && result.annotation.label === undefined
680
+ ? { ...result.annotation, label: reason }
681
+ : result.annotation
682
+ : result.message.customType === "text-editor-stale-anchor-block"
683
+ ? { kind: "stale-anchor", label: reason }
684
+ : { kind: "aborted", label: reason, color: "error" };
685
+
686
+ if (context.contentIndex !== undefined) {
687
+ this.abortedContentIndices.add(context.contentIndex);
688
+ this.annotateContent(context.contentIndex, annotation);
871
689
  }
872
690
 
873
- private cleanupTransientContent(contentIndex: number, toolName?: string, aborted = false): void
874
- {
875
- const name = toolName ?? this.contentNames.get(contentIndex);
876
- const handlers = name ? this.handlers.get(name) : undefined;
877
-
878
- for (const handler of handlers ?? [])
879
- {
880
- if (aborted)
881
- {
882
- handler.onAbort?.(contentIndex);
883
- }
691
+ const guardResult: AgentToolResult<unknown> = {
692
+ content: [{ type: "text", text: result.message.content }],
693
+ details: withToolCallInterceptionDetails(result.message.details, annotation, reason),
694
+ };
695
+ this.toolCallRecords.set(context.toolCall.id, {
696
+ originalArguments: structuredClone(context.args),
697
+ guardResult,
698
+ ...(blockExecution && { blockExecution: true }),
699
+ });
700
+ return guardResult;
701
+ }
884
702
 
885
- handler.onContentEnd?.(contentIndex);
886
- }
703
+ private async finalizeRecovery(): Promise<void> {
704
+ const pending = this.pendingRecoveryBlocks.splice(0);
887
705
 
888
- this.abortCleanups.get(contentIndex)?.();
889
- this.abortCleanups.delete(contentIndex);
890
- this.contentNames.delete(contentIndex);
891
- this.contentToolCallIds.delete(contentIndex);
892
- this.pendingToolCallAnnotations.delete(contentIndex);
893
- this.emittedToolCallAnnotationKinds.delete(contentIndex);
894
- this.completeArgumentContentIndices.delete(contentIndex);
895
- this.partialBuffers.delete(contentIndex);
896
- this.abortedContentIndices.delete(contentIndex);
706
+ if (pending.length === 0) {
707
+ return;
897
708
  }
898
709
 
899
- private cleanupAll(): void
900
- {
901
- for (const handlers of this.handlers.values())
902
- {
903
- for (const handler of handlers)
904
- {
905
- handler.onAgentEnd?.();
906
- }
907
- }
710
+ const groups = new Map<string, PendingRecoveryBlock[]>();
908
711
 
909
- for (const cleanup of this.abortCleanups.values())
910
- {
911
- cleanup();
912
- }
712
+ for (const block of pending) {
713
+ const recoveryKey = this.recoveryRegistry.recoveryKeyFor(block.ctx.toolCall.name);
913
714
 
914
- this.abortCleanups.clear();
915
- this.contentNames.clear();
916
- this.contentToolCallIds.clear();
917
- this.pendingToolCallAnnotations.clear();
918
- this.completeArgumentContentIndices.clear();
919
- this.emittedToolCallAnnotationKinds.clear();
920
- this.partialBuffers.clear();
921
- this.streamedBatchEntries.clear();
922
- this.batchEntryIndexes.clear();
923
- this.toolCallBatchEntryIndexes.clear();
924
- this.toolCallRecords.clear();
925
- this.completedBatchEntryIndexes.clear();
926
- this.nextBatchEntryIndex = 0;
927
- this.abortedContentIndices.clear();
928
- this.pendingAbortReason = undefined;
929
- this.dispatchQueues.clear();
930
- this.processedStreamEventKeys.clear();
931
- this.recoveryRegistry.cleanupAll();
932
- this.pendingRecoveryBlocks.length = 0;
933
- this.recoveryAppliedBatchIndexes.clear();
934
- }
715
+ if (recoveryKey === undefined) {
716
+ continue;
717
+ }
935
718
 
936
- registerRecovery(registration: Parameters<PartialToolRecoveryRegistry["register"]>[0]): void
937
- {
938
- this.recoveryRegistry.register(registration);
719
+ const group = groups.get(recoveryKey) ?? [];
720
+ group.push(block);
721
+ groups.set(recoveryKey, group);
939
722
  }
940
723
 
941
- unregisterRecovery(toolName: string): void
942
- {
943
- this.recoveryRegistry.unregister(toolName);
724
+ for (const group of groups.values()) {
725
+ const first = group[0];
726
+
727
+ if (!first) {
728
+ continue;
729
+ }
730
+
731
+ const finalResult = await this.recoverIfNeeded(
732
+ first.blocked,
733
+ first.ctx,
734
+ this.getAllBatchEntries(),
735
+ group,
736
+ );
737
+
738
+ if (finalResult === first.blocked) {
739
+ continue;
740
+ }
741
+
742
+ const details = finalResult.message.details;
743
+ const recovery =
744
+ Guard.IsObjectNotArray(details) && Guard.IsObjectNotArray(details.recovery)
745
+ ? details.recovery
746
+ : undefined;
747
+ const appliedEntries = recovery?.appliedEntries;
748
+
749
+ if (Array.isArray(appliedEntries)) {
750
+ for (const index of appliedEntries) {
751
+ if (typeof index === "number") {
752
+ this.recoveryAppliedBatchIndexes.add(index);
753
+ }
754
+ }
755
+ }
756
+ }
757
+ }
758
+
759
+ private async recoverIfNeeded(
760
+ result: InterceptResult,
761
+ context: InterceptorContext,
762
+ finalBatchEntries: readonly PartialToolRecoveryBatchEntry[],
763
+ blocks: readonly PendingRecoveryBlock[],
764
+ ): Promise<InterceptResult> {
765
+ if (context.contentIndex === undefined) {
766
+ return result;
944
767
  }
945
768
 
946
- registerBlockedCallSink(sink: BlockedToolCallSink | undefined): void
947
- {
948
- this.blockedCallSink = sink;
769
+ const details = result.message.details;
770
+ const staleEntryIndex =
771
+ Guard.IsObjectNotArray(details) && typeof details.entryIndex === "number"
772
+ ? details.entryIndex
773
+ : undefined;
774
+ const blockedEntryIndexes = [
775
+ ...new Set(
776
+ blocks
777
+ .map((block) => block.ctx.batchEntryIndex)
778
+ .filter((index): index is number => index !== undefined),
779
+ ),
780
+ ];
781
+ const blockedToolCallIds = [...new Set(blocks.map((block) => block.ctx.toolCall.id))];
782
+ const blockedDetails = blocks.map((block) => block.blocked.message.details);
783
+ const first = blocks[0];
784
+ const recoveryKey = first
785
+ ? this.recoveryRegistry.recoveryKeyFor(first.ctx.toolCall.name)
786
+ : undefined;
787
+
788
+ if (!recoveryKey) {
789
+ return result;
949
790
  }
950
791
 
951
- register(handler: ToolCallInterceptorHandler): void
952
- {
953
- const targetTools = new Set(handler.toolNames);
954
-
955
- for (const [toolName, handlers] of this.handlers)
956
- {
957
- const index = handlers.findIndex((current) => current.name === handler.name);
958
-
959
- if (index === -1)
960
- {
961
- continue;
962
- }
963
-
964
- if (targetTools.has(toolName))
965
- {
966
- handlers[index] = handler;
967
- targetTools.delete(toolName);
968
- }
969
- else
970
- {
971
- handlers.splice(index, 1);
972
- }
973
- }
792
+ const recovery = await this.recoveryRegistry.recover({
793
+ contentIndex: context.contentIndex,
794
+ toolCallId: context.toolCall.id,
795
+ toolName: context.toolCall.name,
796
+ ...(staleEntryIndex !== undefined && { staleEntryIndex }),
797
+ staleDetails: details,
798
+ ...(context.partialArgs && { partialArgs: context.partialArgs }),
799
+ args: context.args,
800
+ batchEntries: finalBatchEntries,
801
+ ...(context.batchEntryIndex !== undefined && { batchEntryIndex: context.batchEntryIndex }),
802
+ recoverCompleteBatch: true,
803
+ completedEntryIndexes: [...this.completedBatchEntryIndexes],
804
+ blockedEntryIndexes,
805
+ blockedToolCallIds,
806
+ blockedDetails,
807
+ recoveryKey,
808
+ cwd: context.cwd,
809
+ ctx: context.ctx,
810
+ });
974
811
 
975
- for (const toolName of targetTools)
976
- {
977
- const handlers = this.handlers.get(toolName) ?? [];
978
- handlers.push(handler);
979
- this.handlers.set(toolName, handlers);
980
- }
812
+ return recovery && (recovery.appliedEntries.length > 0 || recovery.skippedEntries.length > 0)
813
+ ? makeRecoveryResult(result, recovery)
814
+ : result;
815
+ }
816
+ private async enqueue(
817
+ contentIndex: number,
818
+ task: () => Promise<GuardInterception | undefined>,
819
+ ): Promise<GuardInterception | undefined> {
820
+ const previous = this.dispatchQueues.get(contentIndex) ?? Promise.resolve();
821
+ const current = previous.catch(() => {}).then(task);
822
+ this.dispatchQueues.set(contentIndex, current);
823
+
824
+ try {
825
+ return await current;
826
+ } finally {
827
+ if (this.dispatchQueues.get(contentIndex) === current) {
828
+ this.dispatchQueues.delete(contentIndex);
829
+ }
981
830
  }
831
+ }
982
832
 
983
- unregister(name: string): void
984
- {
985
- for (const [toolName, handlers] of this.handlers)
986
- {
987
- this.handlers.set(toolName, handlers.filter((handler) => handler.name !== name));
988
- }
833
+ private installAbortCleanup(contentIndex: number, signal: AbortSignal | undefined): void {
834
+ if (!signal || this.abortCleanups.has(contentIndex)) {
835
+ return;
989
836
  }
990
- }
991
837
 
992
- function toolStreamEventKey(event: AssistantStreamEvent): string | undefined
993
- {
994
- if (event.type === "toolcall_end")
995
- {
996
- return `${event.type}\u0000${event.contentIndex}\u0000${event.toolCall.id}`;
997
- }
838
+ const listener = () => {
839
+ const toolName = this.contentNames.get(contentIndex);
840
+ const handlers = toolName ? this.handlers.get(toolName) : undefined;
998
841
 
999
- if (event.type !== "toolcall_start" && event.type !== "toolcall_delta")
1000
- {
1001
- return undefined;
1002
- }
842
+ for (const handler of handlers ?? []) {
843
+ handler.onAbort?.(contentIndex);
844
+ }
845
+ };
1003
846
 
1004
- const block = event.partial.content[event.contentIndex];
1005
- const toolCallId = block?.type === "toolCall" ? block.id : "";
1006
- const delta = event.type === "toolcall_delta" ? event.delta : "";
1007
- return `${event.type}\u0000${event.contentIndex}\u0000${toolCallId}\u0000${delta}`;
1008
- }
847
+ signal.addEventListener("abort", listener, { once: true });
848
+ this.abortCleanups.set(contentIndex, () => {
849
+ signal.removeEventListener("abort", listener);
850
+ });
851
+ }
852
+
853
+ private cleanupContent(contentIndex: number, toolName?: string): void {
854
+ this.cleanupTransientContent(contentIndex, toolName);
855
+ this.recoveryRegistry.cleanup(contentIndex);
856
+ }
857
+
858
+ private cleanupTransientContent(contentIndex: number, toolName?: string, aborted = false): void {
859
+ const name = toolName ?? this.contentNames.get(contentIndex);
860
+ const handlers = name ? this.handlers.get(name) : undefined;
861
+
862
+ for (const handler of handlers ?? []) {
863
+ if (aborted) {
864
+ handler.onAbort?.(contentIndex);
865
+ }
1009
866
 
1010
- function abortReason(result: InterceptResult, handlerName: string): string
1011
- {
1012
- if (result.annotation?.reason)
1013
- {
1014
- return result.annotation.reason;
867
+ handler.onContentEnd?.(contentIndex);
1015
868
  }
1016
869
 
1017
- if (result.annotation?.label)
1018
- {
1019
- return result.annotation.label;
870
+ this.abortCleanups.get(contentIndex)?.();
871
+ this.abortCleanups.delete(contentIndex);
872
+ this.contentNames.delete(contentIndex);
873
+ this.contentToolCallIds.delete(contentIndex);
874
+ this.pendingToolCallAnnotations.delete(contentIndex);
875
+ this.emittedToolCallAnnotationKinds.delete(contentIndex);
876
+ this.completeArgumentContentIndices.delete(contentIndex);
877
+ this.partialBuffers.delete(contentIndex);
878
+ this.abortedContentIndices.delete(contentIndex);
879
+ }
880
+
881
+ private cleanupAll(): void {
882
+ for (const handlers of this.handlers.values()) {
883
+ for (const handler of handlers) {
884
+ handler.onAgentEnd?.();
885
+ }
1020
886
  }
1021
887
 
1022
- if (result.message.customType === "text-editor-stale-anchor-block")
1023
- {
1024
- return "Stale Anchor";
888
+ for (const cleanup of this.abortCleanups.values()) {
889
+ cleanup();
1025
890
  }
1026
891
 
1027
- return handlerName
1028
- .replace(/[-_]+/g, " ")
1029
- .replace(/([a-z])([A-Z])/g, "$1 $2")
1030
- .replace(/\s+/g, " ")
1031
- .trim()
1032
- .replace(/\b\w/g, (letter) => letter.toUpperCase()) || "Blocked";
1033
- }
892
+ this.abortCleanups.clear();
893
+ this.contentNames.clear();
894
+ this.contentToolCallIds.clear();
895
+ this.pendingToolCallAnnotations.clear();
896
+ this.completeArgumentContentIndices.clear();
897
+ this.emittedToolCallAnnotationKinds.clear();
898
+ this.partialBuffers.clear();
899
+ this.streamedBatchEntries.clear();
900
+ this.batchEntryIndexes.clear();
901
+ this.toolCallBatchEntryIndexes.clear();
902
+ this.toolCallRecords.clear();
903
+ this.completedBatchEntryIndexes.clear();
904
+ this.nextBatchEntryIndex = 0;
905
+ this.abortedContentIndices.clear();
906
+ this.pendingAbortReason = undefined;
907
+ this.dispatchQueues.clear();
908
+ this.processedStreamEventKeys.clear();
909
+ this.recoveryRegistry.cleanupAll();
910
+ this.pendingRecoveryBlocks.length = 0;
911
+ this.recoveryAppliedBatchIndexes.clear();
912
+ }
913
+
914
+ registerRecovery(registration: Parameters<PartialToolRecoveryRegistry["register"]>[0]): void {
915
+ this.recoveryRegistry.register(registration);
916
+ }
917
+
918
+ unregisterRecovery(toolName: string): void {
919
+ this.recoveryRegistry.unregister(toolName);
920
+ }
921
+
922
+ registerBlockedCallSink(sink: BlockedToolCallSink | undefined): void {
923
+ this.blockedCallSink = sink;
924
+ }
925
+
926
+ register(handler: ToolCallInterceptorHandler): void {
927
+ const targetTools = new Set(handler.toolNames);
928
+
929
+ for (const [toolName, handlers] of this.handlers) {
930
+ const index = handlers.findIndex((current) => current.name === handler.name);
931
+
932
+ if (index === -1) {
933
+ continue;
934
+ }
935
+
936
+ if (targetTools.has(toolName)) {
937
+ handlers[index] = handler;
938
+ targetTools.delete(toolName);
939
+ } else {
940
+ handlers.splice(index, 1);
941
+ }
942
+ }
1034
943
 
1035
- function parseCompleteArguments(json: string): Record<string, unknown> | undefined
1036
- {
1037
- try
1038
- {
1039
- const value: unknown = JSON.parse(json);
1040
- return Guard.IsObjectNotArray(value) ? value : undefined;
944
+ for (const toolName of targetTools) {
945
+ const handlers = this.handlers.get(toolName) ?? [];
946
+ handlers.push(handler);
947
+ this.handlers.set(toolName, handlers);
1041
948
  }
1042
- catch
1043
- {
1044
- return undefined;
949
+ }
950
+
951
+ unregister(name: string): void {
952
+ for (const [toolName, handlers] of this.handlers) {
953
+ this.handlers.set(
954
+ toolName,
955
+ handlers.filter((handler) => handler.name !== name),
956
+ );
1045
957
  }
958
+ }
1046
959
  }
1047
960
 
1048
- function freshAnchorsAfterRecovery(recovery: PartialToolRecoveryResult): string[]
1049
- {
1050
- const normalResult = recovery.normalResult;
961
+ function toolStreamEventKey(event: AssistantStreamEvent): string | undefined {
962
+ if (event.type === "toolcall_end") {
963
+ return `${event.type}\u{0}${event.contentIndex}\u{0}${event.toolCall.id}`;
964
+ }
1051
965
 
1052
- if (!Guard.IsObjectNotArray(normalResult) || !Guard.IsObjectNotArray(normalResult.details))
1053
- {
1054
- return [];
1055
- }
966
+ if (event.type !== "toolcall_start" && event.type !== "toolcall_delta") {
967
+ return undefined;
968
+ }
1056
969
 
1057
- const results = normalResult.details.results;
970
+ const block = event.partial.content[event.contentIndex];
971
+ const toolCallId = block?.type === "toolCall" ? block.id : "";
972
+ const delta = event.type === "toolcall_delta" ? event.delta : "";
973
+ return `${event.type}\u{0}${event.contentIndex}\u{0}${toolCallId}\u{0}${delta}`;
974
+ }
1058
975
 
1059
- if (!Array.isArray(results))
1060
- {
1061
- return [];
1062
- }
976
+ function abortReason(result: InterceptResult, handlerName: string): string {
977
+ if (result.annotation?.reason) {
978
+ return result.annotation.reason;
979
+ }
980
+
981
+ if (result.annotation?.label) {
982
+ return result.annotation.label;
983
+ }
984
+
985
+ if (result.message.customType === "text-editor-stale-anchor-block") {
986
+ return "Stale Anchor";
987
+ }
988
+
989
+ return (
990
+ handlerName
991
+ .replace(/[-_]+/g, " ")
992
+ .replace(/([a-z])([A-Z])/g, "$1 $2")
993
+ .replace(/\s+/g, " ")
994
+ .trim()
995
+ .replace(/\b\w/g, (letter) => letter.toUpperCase()) || "Blocked"
996
+ );
997
+ }
1063
998
 
1064
- const stalePath = Guard.IsObjectNotArray(recovery.staleDetails) && typeof recovery.staleDetails.path === "string"
1065
- ? recovery.staleDetails.path
1066
- : undefined;
1067
- const candidates = results
1068
- .filter(Guard.IsObjectNotArray)
1069
- .map((result) => Guard.IsObjectNotArray(result.data) ? result.data : result);
1070
- const matching = stalePath === undefined
1071
- ? candidates
1072
- : candidates.filter((result) => result.path === stalePath);
1073
- const selected = matching.length > 0 ? matching : candidates;
1074
- const anchors = selected.flatMap((result) =>
1075
- {
1076
- const freshAnchors = result.freshAnchors;
1077
- return Array.isArray(freshAnchors)
1078
- ? freshAnchors.filter((anchor): anchor is string => typeof anchor === "string")
1079
- : [];
1080
- });
999
+ function parseCompleteArguments(json: string): Record<string, unknown> | undefined {
1000
+ try {
1001
+ const value: unknown = JSON.parse(json);
1002
+ return Guard.IsObjectNotArray(value) ? value : undefined;
1003
+ } catch {
1004
+ return undefined;
1005
+ }
1006
+ }
1081
1007
 
1082
- return [...new Set(anchors)];
1008
+ function freshAnchorsAfterRecovery(recovery: PartialToolRecoveryResult): string[] {
1009
+ const normalResult = recovery.normalResult;
1010
+
1011
+ if (!Guard.IsObjectNotArray(normalResult) || !Guard.IsObjectNotArray(normalResult.details)) {
1012
+ return [];
1013
+ }
1014
+
1015
+ const results = normalResult.details.results;
1016
+
1017
+ if (!Array.isArray(results)) {
1018
+ return [];
1019
+ }
1020
+
1021
+ const stalePath =
1022
+ Guard.IsObjectNotArray(recovery.staleDetails) && typeof recovery.staleDetails.path === "string"
1023
+ ? recovery.staleDetails.path
1024
+ : undefined;
1025
+ const candidates = results
1026
+ .filter(Guard.IsObjectNotArray)
1027
+ .map((result) => (Guard.IsObjectNotArray(result.data) ? result.data : result));
1028
+ const matching =
1029
+ stalePath === undefined ? candidates : candidates.filter((result) => result.path === stalePath);
1030
+ const selected = matching.length > 0 ? matching : candidates;
1031
+ const anchors = selected.flatMap((result) => {
1032
+ const freshAnchors = result.freshAnchors;
1033
+ return Array.isArray(freshAnchors)
1034
+ ? freshAnchors.filter((anchor): anchor is string => typeof anchor === "string")
1035
+ : [];
1036
+ });
1037
+
1038
+ return [...new Set(anchors)];
1083
1039
  }
1084
1040
 
1085
- function replaceCurrentAnchors(content: string, freshAnchors: readonly string[]): string
1086
- {
1087
- const marker = "\n\nCurrent nearby anchors:";
1088
- const markerIndex = content.indexOf(marker);
1089
- const base = markerIndex === -1 ? content : content.slice(0, markerIndex);
1090
- return `${base}\n\nCurrent nearby anchors:\n${freshAnchors.map((anchor) => ` ${anchor}`).join("\n")}`;
1041
+ function replaceCurrentAnchors(content: string, freshAnchors: readonly string[]): string {
1042
+ const marker = "\n\nCurrent nearby anchors:";
1043
+ const markerIndex = content.indexOf(marker);
1044
+ const base = markerIndex === -1 ? content : content.slice(0, markerIndex);
1045
+ return `${base}\n\nCurrent nearby anchors:\n${freshAnchors.map((anchor) => ` ${anchor}`).join("\n")}`;
1091
1046
  }
1092
1047
 
1093
1048
  function makeRecoveryResult(
1094
- blocked: InterceptResult,
1095
- recovery: PartialToolRecoveryResult,
1096
- ): InterceptResult
1097
- {
1098
- const appliedCount = recovery.appliedEntries.length;
1099
- const applied = appliedCount > 0
1100
- ? `${appliedCount} (indices: ${recovery.appliedEntries.join(", ")})`
1101
- : "0";
1102
- const skipped = recovery.skippedEntries.length > 0
1103
- ? recovery.skippedEntries.map((entry) => `${entry.index} (${entry.reason})`).join(", ")
1104
- : "none";
1105
- const execution = recovery.error
1106
- ? `Recovery execution failed: ${recovery.error}.`
1107
- : "Recovery execution completed.";
1108
- const freshAnchors = freshAnchorsAfterRecovery(recovery);
1109
- const blockedDetails = freshAnchors.length > 0 && Guard.IsObjectNotArray(blocked.message.details)
1110
- ? { ...blocked.message.details, freshAnchors }
1111
- : blocked.message.details;
1112
- const blockedContent = freshAnchors.length > 0
1113
- ? replaceCurrentAnchors(blocked.message.content, freshAnchors)
1114
- : blocked.message.content;
1115
- const displayedRecovery = freshAnchors.length > 0 && Guard.IsObjectNotArray(recovery.staleDetails)
1116
- ? { ...recovery, staleDetails: { ...recovery.staleDetails, freshAnchors } }
1117
- : recovery;
1118
-
1119
- return {
1120
- message: {
1121
- customType: PARTIAL_TOOL_RECOVERY_CUSTOM_TYPE,
1122
- content: `${blockedContent}\n\n[RECOVERY] Status: ${recovery.status}. Applied entries: ${applied}. `
1123
- + `Skipped entries: ${skipped}. ${execution}`,
1124
- display: false,
1125
- details: { blocked: blockedDetails, recovery: displayedRecovery },
1126
- },
1127
- };
1049
+ blocked: InterceptResult,
1050
+ recovery: PartialToolRecoveryResult,
1051
+ ): InterceptResult {
1052
+ const appliedCount = recovery.appliedEntries.length;
1053
+ const applied =
1054
+ appliedCount > 0 ? `${appliedCount} (indices: ${recovery.appliedEntries.join(", ")})` : "0";
1055
+ const skipped =
1056
+ recovery.skippedEntries.length > 0
1057
+ ? recovery.skippedEntries.map((entry) => `${entry.index} (${entry.reason})`).join(", ")
1058
+ : "none";
1059
+ const execution = recovery.error
1060
+ ? `Recovery execution failed: ${recovery.error}.`
1061
+ : "Recovery execution completed.";
1062
+ const freshAnchors = freshAnchorsAfterRecovery(recovery);
1063
+ const blockedDetails =
1064
+ freshAnchors.length > 0 && Guard.IsObjectNotArray(blocked.message.details)
1065
+ ? { ...blocked.message.details, freshAnchors }
1066
+ : blocked.message.details;
1067
+ const blockedContent =
1068
+ freshAnchors.length > 0
1069
+ ? replaceCurrentAnchors(blocked.message.content, freshAnchors)
1070
+ : blocked.message.content;
1071
+ const displayedRecovery =
1072
+ freshAnchors.length > 0 && Guard.IsObjectNotArray(recovery.staleDetails)
1073
+ ? { ...recovery, staleDetails: { ...recovery.staleDetails, freshAnchors } }
1074
+ : recovery;
1075
+
1076
+ return {
1077
+ message: {
1078
+ customType: PARTIAL_TOOL_RECOVERY_CUSTOM_TYPE,
1079
+ content:
1080
+ `${blockedContent}\n\n[RECOVERY] Status: ${recovery.status}. Applied entries: ${applied}. ` +
1081
+ `Skipped entries: ${skipped}. ${execution}`,
1082
+ display: false,
1083
+ details: { blocked: blockedDetails, recovery: displayedRecovery },
1084
+ },
1085
+ };
1128
1086
  }
1129
1087
 
1130
1088
  const coordinators = new WeakMap<ExtensionAPI, ToolCallInterceptor>();
1131
1089
 
1132
- function coordinatorFor(pi: ExtensionAPI): ToolCallInterceptor
1133
- {
1134
- const existing = coordinators.get(pi);
1135
-
1136
- if (existing)
1137
- {
1138
- return existing;
1139
- }
1140
-
1141
- const coordinator = new InterceptorImpl(pi);
1142
- coordinators.set(pi, coordinator);
1143
- registerStreamingInterceptorProvider(
1144
- pi,
1145
- (event, context) => coordinator.processStreamEvent(event, context),
1146
- (event) =>
1147
- {
1148
- coordinator.markStreamEventProcessed(event);
1149
- },
1150
- (contentIndex) =>
1151
- {
1152
- coordinator.finalizeStreamInterception(contentIndex);
1153
- },
1154
- );
1155
- return coordinator;
1090
+ function coordinatorFor(pi: ExtensionAPI): ToolCallInterceptor {
1091
+ const existing = coordinators.get(pi);
1092
+
1093
+ if (existing) {
1094
+ return existing;
1095
+ }
1096
+
1097
+ const coordinator = new InterceptorImpl(pi);
1098
+ coordinators.set(pi, coordinator);
1099
+ registerStreamingInterceptorProvider(
1100
+ pi,
1101
+ (event, context) => coordinator.processStreamEvent(event, context),
1102
+ (event) => {
1103
+ coordinator.markStreamEventProcessed(event);
1104
+ },
1105
+ (contentIndex) => {
1106
+ coordinator.finalizeStreamInterception(contentIndex);
1107
+ },
1108
+ );
1109
+ return coordinator;
1156
1110
  }
1157
1111
 
1158
- export function registerToolCallInterceptor(pi: ExtensionAPI, handler: ToolCallInterceptorHandler): void
1159
- {
1160
- coordinatorFor(pi).register(handler);
1112
+ export function registerToolCallInterceptor(
1113
+ pi: ExtensionAPI,
1114
+ handler: ToolCallInterceptorHandler,
1115
+ ): void {
1116
+ coordinatorFor(pi).register(handler);
1161
1117
  }
1162
1118
 
1163
- export function unregisterToolCallInterceptor(pi: ExtensionAPI, handlerName: string): void
1164
- {
1165
- coordinatorFor(pi).unregister(handlerName);
1119
+ export function unregisterToolCallInterceptor(pi: ExtensionAPI, handlerName: string): void {
1120
+ coordinatorFor(pi).unregister(handlerName);
1166
1121
  }
1167
1122
 
1168
1123
  export function registerToolCallRecovery(
1169
- pi: ExtensionAPI,
1170
- registration: Parameters<PartialToolRecoveryRegistry["register"]>[0],
1171
- ): void
1172
- {
1173
- coordinatorFor(pi).registerRecovery(registration);
1124
+ pi: ExtensionAPI,
1125
+ registration: Parameters<PartialToolRecoveryRegistry["register"]>[0],
1126
+ ): void {
1127
+ coordinatorFor(pi).registerRecovery(registration);
1174
1128
  }
1175
1129
 
1176
- export function unregisterToolCallRecovery(pi: ExtensionAPI, toolName: string): void
1177
- {
1178
- coordinatorFor(pi).unregisterRecovery(toolName);
1130
+ export function unregisterToolCallRecovery(pi: ExtensionAPI, toolName: string): void {
1131
+ coordinatorFor(pi).unregisterRecovery(toolName);
1179
1132
  }
1180
1133
 
1181
1134
  export function registerToolCallAnnotationSink(
1182
- pi: ExtensionAPI,
1183
- sink?: ToolCallAnnotationSink,
1184
- ): void
1185
- {
1186
- toolCallAnnotationSinkUnsubscribers.get(pi)?.();
1187
- toolCallAnnotationSinkUnsubscribers.delete(pi);
1188
-
1189
- if (sink === undefined)
1190
- {
1191
- return;
1135
+ pi: ExtensionAPI,
1136
+ sink?: ToolCallAnnotationSink,
1137
+ ): void {
1138
+ toolCallAnnotationSinkUnsubscribers.get(pi)?.();
1139
+ toolCallAnnotationSinkUnsubscribers.delete(pi);
1140
+
1141
+ if (sink === undefined) {
1142
+ return;
1143
+ }
1144
+
1145
+ const unsubscribe = pi.events.on(TOOL_CALL_ANNOTATION_EVENT, (event) => {
1146
+ if (
1147
+ !Guard.IsObjectNotArray(event) ||
1148
+ typeof event.toolCallId !== "string" ||
1149
+ !isToolCallAnnotation(event.annotation)
1150
+ ) {
1151
+ return;
1192
1152
  }
1193
1153
 
1194
- const unsubscribe = pi.events.on(TOOL_CALL_ANNOTATION_EVENT, (event) =>
1195
- {
1196
- if (
1197
- !Guard.IsObjectNotArray(event)
1198
- || typeof event.toolCallId !== "string"
1199
- || !isToolCallAnnotation(event.annotation)
1200
- )
1201
- {
1202
- return;
1203
- }
1204
-
1205
- sink(event.toolCallId, event.annotation);
1206
- });
1207
- toolCallAnnotationSinkUnsubscribers.set(pi, unsubscribe);
1154
+ sink(event.toolCallId, event.annotation);
1155
+ });
1156
+ toolCallAnnotationSinkUnsubscribers.set(pi, unsubscribe);
1208
1157
  }
1209
1158
 
1210
1159
  export function registerBlockedToolCallSink(
1211
- pi: ExtensionAPI,
1212
- sink: BlockedToolCallSink | undefined,
1213
- ): void
1214
- {
1215
- coordinatorFor(pi).registerBlockedCallSink(sink);
1160
+ pi: ExtensionAPI,
1161
+ sink: BlockedToolCallSink | undefined,
1162
+ ): void {
1163
+ coordinatorFor(pi).registerBlockedCallSink(sink);
1216
1164
  }
1217
1165
 
1218
1166
  export function processToolCallStreamEvent(
1219
- pi: ExtensionAPI,
1220
- event: AssistantStreamEvent,
1221
- ctx: ExtensionContext,
1222
- ): Promise<GuardInterception | undefined>
1223
- {
1224
- return coordinatorFor(pi).processStreamEvent(event, ctx);
1167
+ pi: ExtensionAPI,
1168
+ event: AssistantStreamEvent,
1169
+ context: ExtensionContext,
1170
+ ): Promise<GuardInterception | undefined> {
1171
+ return coordinatorFor(pi).processStreamEvent(event, context);
1225
1172
  }
1226
1173
 
1227
- export function markToolCallStreamEventProcessed(pi: ExtensionAPI, event: AssistantStreamEvent): void
1228
- {
1229
- coordinatorFor(pi).markStreamEventProcessed(event);
1174
+ export function markToolCallStreamEventProcessed(
1175
+ pi: ExtensionAPI,
1176
+ event: AssistantStreamEvent,
1177
+ ): void {
1178
+ coordinatorFor(pi).markStreamEventProcessed(event);
1230
1179
  }
1231
1180
 
1232
- export function getToolCallRecord(pi: ExtensionAPI, toolCallId: string): GuardCallRecord | undefined
1233
- {
1234
- return coordinatorFor(pi).getToolCallRecord(toolCallId);
1181
+ export function getToolCallRecord(
1182
+ pi: ExtensionAPI,
1183
+ toolCallId: string,
1184
+ ): GuardCallRecord | undefined {
1185
+ return coordinatorFor(pi).getToolCallRecord(toolCallId);
1235
1186
  }