@duckmind/dm-darwin-x64 0.67.2 → 0.67.3

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 (605) hide show
  1. package/README.md +2 -2
  2. package/dm +1 -1
  3. package/extensions/.dm-extensions.json +611 -13
  4. package/extensions/dm-lens/clients/dispatch/runners/utils/runner-helpers.js +1 -1
  5. package/extensions/dm-lens/dist/clients/actionable-warnings-logger.js +24 -0
  6. package/extensions/dm-lens/dist/clients/actionable-warnings.js +1066 -0
  7. package/extensions/dm-lens/dist/clients/advisory-provenance.js +388 -0
  8. package/extensions/dm-lens/dist/clients/agent-behavior-client.js +94 -0
  9. package/extensions/dm-lens/dist/clients/agent-nudge.js +253 -0
  10. package/extensions/dm-lens/dist/clients/analysed-root.js +1 -0
  11. package/extensions/dm-lens/dist/clients/analysis-root.js +133 -0
  12. package/extensions/dm-lens/dist/clients/ast-grep-client.js +587 -0
  13. package/extensions/dm-lens/dist/clients/ast-grep-rule-manager.js +137 -0
  14. package/extensions/dm-lens/dist/clients/ast-grep-tool-logger.js +85 -0
  15. package/extensions/dm-lens/dist/clients/ast-grep-types.js +1 -0
  16. package/extensions/dm-lens/dist/clients/ast-grep-yaml-synth.js +109 -0
  17. package/extensions/dm-lens/dist/clients/atomic-write-staging.js +66 -0
  18. package/extensions/dm-lens/dist/clients/atomic-write.js +37 -0
  19. package/extensions/dm-lens/dist/clients/availability-probe-flight.js +11 -0
  20. package/extensions/dm-lens/dist/clients/bash-file-access.js +1257 -0
  21. package/extensions/dm-lens/dist/clients/biome-client.js +223 -0
  22. package/extensions/dm-lens/dist/clients/blocker-freshness.js +553 -0
  23. package/extensions/dm-lens/dist/clients/blocker-past-eof.js +51 -0
  24. package/extensions/dm-lens/dist/clients/bootstrap.js +246 -0
  25. package/extensions/dm-lens/dist/clients/bounded-cache.js +105 -0
  26. package/extensions/dm-lens/dist/clients/bounded-pid-file-lock.js +275 -0
  27. package/extensions/dm-lens/dist/clients/bounded-telemetry.js +110 -0
  28. package/extensions/dm-lens/dist/clients/build-identity.js +45 -0
  29. package/extensions/dm-lens/dist/clients/bundled-resource-health.js +41 -0
  30. package/extensions/dm-lens/dist/clients/bus-events-logger.js +48 -0
  31. package/extensions/dm-lens/dist/clients/bus-publish.js +117 -0
  32. package/extensions/dm-lens/dist/clients/cache/rule-cache.js +87 -0
  33. package/extensions/dm-lens/dist/clients/cache-manager.js +449 -0
  34. package/extensions/dm-lens/dist/clients/cache-observability.js +1105 -0
  35. package/extensions/dm-lens/dist/clients/call-graph.js +628 -0
  36. package/extensions/dm-lens/dist/clients/cargo-manifest.js +167 -0
  37. package/extensions/dm-lens/dist/clients/cascade-budget.js +52 -0
  38. package/extensions/dm-lens/dist/clients/cascade-format.js +301 -0
  39. package/extensions/dm-lens/dist/clients/cascade-logger.js +22 -0
  40. package/extensions/dm-lens/dist/clients/cascade-types.js +1 -0
  41. package/extensions/dm-lens/dist/clients/child-unref.js +59 -0
  42. package/extensions/dm-lens/dist/clients/code-quality-warnings.js +192 -0
  43. package/extensions/dm-lens/dist/clients/codebase-model.js +110 -0
  44. package/extensions/dm-lens/dist/clients/collateral-test-role.js +8 -0
  45. package/extensions/dm-lens/dist/clients/complexity-client.js +398 -0
  46. package/extensions/dm-lens/dist/clients/config-core/deny.js +117 -0
  47. package/extensions/dm-lens/dist/clients/config-core/index.js +2 -0
  48. package/extensions/dm-lens/dist/clients/config-core/merge.js +228 -0
  49. package/extensions/dm-lens/dist/clients/config-core/normalize.js +226 -0
  50. package/extensions/dm-lens/dist/clients/config-core/process-spec.js +147 -0
  51. package/extensions/dm-lens/dist/clients/config-core/provenance.js +54 -0
  52. package/extensions/dm-lens/dist/clients/config-core/records.js +79 -0
  53. package/extensions/dm-lens/dist/clients/config-core/resolve.js +48 -0
  54. package/extensions/dm-lens/dist/clients/config-core/safe-object.js +22 -0
  55. package/extensions/dm-lens/dist/clients/config-core/schema.js +93 -0
  56. package/extensions/dm-lens/dist/clients/config-diagnostic-codes.js +90 -0
  57. package/extensions/dm-lens/dist/clients/config-locations.js +169 -0
  58. package/extensions/dm-lens/dist/clients/config-resolve.js +359 -0
  59. package/extensions/dm-lens/dist/clients/config-schema.js +230 -0
  60. package/extensions/dm-lens/dist/clients/config-warn.js +146 -0
  61. package/extensions/dm-lens/dist/clients/confirmed-delete.js +11 -0
  62. package/extensions/dm-lens/dist/clients/console-guard-install.js +4 -0
  63. package/extensions/dm-lens/dist/clients/content-stamp.js +16 -0
  64. package/extensions/dm-lens/dist/clients/context-injection-ledger.js +157 -0
  65. package/extensions/dm-lens/dist/clients/cooperative-budget.js +36 -0
  66. package/extensions/dm-lens/dist/clients/custom-rule-locations.js +28 -0
  67. package/extensions/dm-lens/dist/clients/dead-code-client.js +408 -0
  68. package/extensions/dm-lens/dist/clients/dead-code-logger.js +18 -0
  69. package/extensions/dm-lens/dist/clients/deadline-utils.js +117 -0
  70. package/extensions/dm-lens/dist/clients/debug-handles.js +121 -0
  71. package/extensions/dm-lens/dist/clients/debug-heap.js +80 -0
  72. package/extensions/dm-lens/dist/clients/deferred-lsp-work.js +33 -0
  73. package/extensions/dm-lens/dist/clients/deferred-runner-blockers.js +146 -0
  74. package/extensions/dm-lens/dist/clients/deferred-test-targets.js +31 -0
  75. package/extensions/dm-lens/dist/clients/degradation-ledger.js +306 -0
  76. package/extensions/dm-lens/dist/clients/demoted-finding-render.js +64 -0
  77. package/extensions/dm-lens/dist/clients/dependency-checker.js +534 -0
  78. package/extensions/dm-lens/dist/clients/deps/ast-grep-napi.js +27 -0
  79. package/extensions/dm-lens/dist/clients/deps/dm-host-deps.js +10 -0
  80. package/extensions/dm-lens/dist/clients/deps/dm-tui-compat.js +58 -0
  81. package/extensions/dm-lens/dist/clients/deps/js-yaml.js +7 -0
  82. package/extensions/dm-lens/dist/clients/deps/minimatch.js +6 -0
  83. package/extensions/dm-lens/dist/clients/deps/pidusage.js +5 -0
  84. package/extensions/dm-lens/dist/clients/deps/typebox.js +5 -0
  85. package/extensions/dm-lens/dist/clients/deps/vscode-jsonrpc.js +8 -0
  86. package/extensions/dm-lens/dist/clients/deps/web-tree-sitter.js +11 -0
  87. package/extensions/dm-lens/dist/clients/diagnostic-dispositions.js +334 -0
  88. package/extensions/dm-lens/dist/clients/diagnostic-line-freshness.js +142 -0
  89. package/extensions/dm-lens/dist/clients/diagnostic-logger.js +60 -0
  90. package/extensions/dm-lens/dist/clients/diagnostic-tracker.js +89 -0
  91. package/extensions/dm-lens/dist/clients/diagnostics-publish.js +134 -0
  92. package/extensions/dm-lens/dist/clients/disk-change-consumers.js +312 -0
  93. package/extensions/dm-lens/dist/clients/disk-change-subscribers.js +191 -0
  94. package/extensions/dm-lens/dist/clients/disk-changes.js +165 -0
  95. package/extensions/dm-lens/dist/clients/dispatch/adopted-root-runners.js +22 -0
  96. package/extensions/dm-lens/dist/clients/dispatch/ast-grep-catalog.js +16 -0
  97. package/extensions/dm-lens/dist/clients/dispatch/auxiliary-lsp.js +162 -0
  98. package/extensions/dm-lens/dist/clients/dispatch/collect-later-tier.js +25 -0
  99. package/extensions/dm-lens/dist/clients/dispatch/diagnostic-taxonomy.js +58 -0
  100. package/extensions/dm-lens/dist/clients/dispatch/dispatcher.js +1240 -0
  101. package/extensions/dm-lens/dist/clients/dispatch/fact-provider-types.js +1 -0
  102. package/extensions/dm-lens/dist/clients/dispatch/fact-rule-runner.js +17 -0
  103. package/extensions/dm-lens/dist/clients/dispatch/fact-runner.js +18 -0
  104. package/extensions/dm-lens/dist/clients/dispatch/fact-scheduler.js +52 -0
  105. package/extensions/dm-lens/dist/clients/dispatch/fact-store.js +193 -0
  106. package/extensions/dm-lens/dist/clients/dispatch/facts/comment-facts.js +23 -0
  107. package/extensions/dm-lens/dist/clients/dispatch/facts/file-content.js +18 -0
  108. package/extensions/dm-lens/dist/clients/dispatch/facts/function-facts.js +274 -0
  109. package/extensions/dm-lens/dist/clients/dispatch/facts/import-facts.js +169 -0
  110. package/extensions/dm-lens/dist/clients/dispatch/facts/tree-sitter-facts.js +19 -0
  111. package/extensions/dm-lens/dist/clients/dispatch/facts/try-catch-facts.js +95 -0
  112. package/extensions/dm-lens/dist/clients/dispatch/finding-policy.js +188 -0
  113. package/extensions/dm-lens/dist/clients/dispatch/indent-detect.js +227 -0
  114. package/extensions/dm-lens/dist/clients/dispatch/inline-suppressions.js +52 -0
  115. package/extensions/dm-lens/dist/clients/dispatch/integration.js +1698 -0
  116. package/extensions/dm-lens/dist/clients/dispatch/known-runner-ids.js +13 -0
  117. package/extensions/dm-lens/dist/clients/dispatch/lane-copies.js +23 -0
  118. package/extensions/dm-lens/dist/clients/dispatch/lazy.js +8 -0
  119. package/extensions/dm-lens/dist/clients/dispatch/pending-runner-findings.js +133 -0
  120. package/extensions/dm-lens/dist/clients/dispatch/plan.js +284 -0
  121. package/extensions/dm-lens/dist/clients/dispatch/pre-edit-seed.js +57 -0
  122. package/extensions/dm-lens/dist/clients/dispatch/priorities.js +14 -0
  123. package/extensions/dm-lens/dist/clients/dispatch/rule-id-normalize.js +54 -0
  124. package/extensions/dm-lens/dist/clients/dispatch/rule-ignores.js +21 -0
  125. package/extensions/dm-lens/dist/clients/dispatch/rule-policy.js +102 -0
  126. package/extensions/dm-lens/dist/clients/dispatch/rules/async-noise.js +31 -0
  127. package/extensions/dm-lens/dist/clients/dispatch/rules/async-unnecessary-wrapper.js +27 -0
  128. package/extensions/dm-lens/dist/clients/dispatch/rules/cors-wildcard.js +35 -0
  129. package/extensions/dm-lens/dist/clients/dispatch/rules/error-obscuring.js +29 -0
  130. package/extensions/dm-lens/dist/clients/dispatch/rules/error-swallowing.js +29 -0
  131. package/extensions/dm-lens/dist/clients/dispatch/rules/framework-call-noise.js +31 -0
  132. package/extensions/dm-lens/dist/clients/dispatch/rules/high-complexity.js +41 -0
  133. package/extensions/dm-lens/dist/clients/dispatch/rules/high-fan-out.js +37 -0
  134. package/extensions/dm-lens/dist/clients/dispatch/rules/high-import-coupling.js +31 -0
  135. package/extensions/dm-lens/dist/clients/dispatch/rules/missing-error-propagation.js +45 -0
  136. package/extensions/dm-lens/dist/clients/dispatch/rules/no-commented-credentials.js +46 -0
  137. package/extensions/dm-lens/dist/clients/dispatch/rules/pass-through-wrappers.js +38 -0
  138. package/extensions/dm-lens/dist/clients/dispatch/rules/placeholder-comments.js +40 -0
  139. package/extensions/dm-lens/dist/clients/dispatch/rules/unsafe-boundary.js +101 -0
  140. package/extensions/dm-lens/dist/clients/dispatch/runner-context.js +41 -0
  141. package/extensions/dm-lens/dist/clients/dispatch/runners/actionlint.js +98 -0
  142. package/extensions/dm-lens/dist/clients/dispatch/runners/ast-grep-literal-anchors.js +58 -0
  143. package/extensions/dm-lens/dist/clients/dispatch/runners/ast-grep-napi.js +739 -0
  144. package/extensions/dm-lens/dist/clients/dispatch/runners/biome-check.js +196 -0
  145. package/extensions/dm-lens/dist/clients/dispatch/runners/cpp-check.js +190 -0
  146. package/extensions/dm-lens/dist/clients/dispatch/runners/credo.js +66 -0
  147. package/extensions/dm-lens/dist/clients/dispatch/runners/cue-vet.js +161 -0
  148. package/extensions/dm-lens/dist/clients/dispatch/runners/dart-analyze.js +151 -0
  149. package/extensions/dm-lens/dist/clients/dispatch/runners/detekt.js +158 -0
  150. package/extensions/dm-lens/dist/clients/dispatch/runners/dotnet-build.js +163 -0
  151. package/extensions/dm-lens/dist/clients/dispatch/runners/elixir-check.js +153 -0
  152. package/extensions/dm-lens/dist/clients/dispatch/runners/eslint.js +99 -0
  153. package/extensions/dm-lens/dist/clients/dispatch/runners/fact-rules.js +20 -0
  154. package/extensions/dm-lens/dist/clients/dispatch/runners/fish-indent.js +120 -0
  155. package/extensions/dm-lens/dist/clients/dispatch/runners/gleam-check.js +100 -0
  156. package/extensions/dm-lens/dist/clients/dispatch/runners/go-vet.js +52 -0
  157. package/extensions/dm-lens/dist/clients/dispatch/runners/golangci-lint.js +105 -0
  158. package/extensions/dm-lens/dist/clients/dispatch/runners/hadolint.js +83 -0
  159. package/extensions/dm-lens/dist/clients/dispatch/runners/helm-lint.js +147 -0
  160. package/extensions/dm-lens/dist/clients/dispatch/runners/helm-render.js +593 -0
  161. package/extensions/dm-lens/dist/clients/dispatch/runners/htmlhint.js +103 -0
  162. package/extensions/dm-lens/dist/clients/dispatch/runners/index.js +100 -0
  163. package/extensions/dm-lens/dist/clients/dispatch/runners/javac.js +82 -0
  164. package/extensions/dm-lens/dist/clients/dispatch/runners/ktlint.js +115 -0
  165. package/extensions/dm-lens/dist/clients/dispatch/runners/lsp.js +275 -0
  166. package/extensions/dm-lens/dist/clients/dispatch/runners/markdownlint.js +129 -0
  167. package/extensions/dm-lens/dist/clients/dispatch/runners/mypy.js +70 -0
  168. package/extensions/dm-lens/dist/clients/dispatch/runners/oxlint.js +296 -0
  169. package/extensions/dm-lens/dist/clients/dispatch/runners/php-lint.js +66 -0
  170. package/extensions/dm-lens/dist/clients/dispatch/runners/phpstan.js +90 -0
  171. package/extensions/dm-lens/dist/clients/dispatch/runners/prisma-validate.js +66 -0
  172. package/extensions/dm-lens/dist/clients/dispatch/runners/psscriptanalyzer.js +307 -0
  173. package/extensions/dm-lens/dist/clients/dispatch/runners/pyright.js +118 -0
  174. package/extensions/dm-lens/dist/clients/dispatch/runners/rubocop.js +79 -0
  175. package/extensions/dm-lens/dist/clients/dispatch/runners/ruff.js +69 -0
  176. package/extensions/dm-lens/dist/clients/dispatch/runners/rust-clippy.js +166 -0
  177. package/extensions/dm-lens/dist/clients/dispatch/runners/shellcheck.js +168 -0
  178. package/extensions/dm-lens/dist/clients/dispatch/runners/shfmt.js +92 -0
  179. package/extensions/dm-lens/dist/clients/dispatch/runners/spellcheck.js +74 -0
  180. package/extensions/dm-lens/dist/clients/dispatch/runners/spotbugs.js +208 -0
  181. package/extensions/dm-lens/dist/clients/dispatch/runners/sqlfluff.js +136 -0
  182. package/extensions/dm-lens/dist/clients/dispatch/runners/stylelint.js +118 -0
  183. package/extensions/dm-lens/dist/clients/dispatch/runners/swiftlint.js +143 -0
  184. package/extensions/dm-lens/dist/clients/dispatch/runners/taplo.js +109 -0
  185. package/extensions/dm-lens/dist/clients/dispatch/runners/terragrunt.js +110 -0
  186. package/extensions/dm-lens/dist/clients/dispatch/runners/tflint.js +104 -0
  187. package/extensions/dm-lens/dist/clients/dispatch/runners/tree-sitter.js +534 -0
  188. package/extensions/dm-lens/dist/clients/dispatch/runners/trivy-config.js +155 -0
  189. package/extensions/dm-lens/dist/clients/dispatch/runners/utils/availability-policy.js +313 -0
  190. package/extensions/dm-lens/dist/clients/dispatch/runners/utils/candidate-probe.js +66 -0
  191. package/extensions/dm-lens/dist/clients/dispatch/runners/utils/diagnostic-parsers.js +62 -0
  192. package/extensions/dm-lens/dist/clients/dispatch/runners/utils/lazy-installer.js +130 -0
  193. package/extensions/dm-lens/dist/clients/dispatch/runners/utils/runner-helpers.js +1143 -0
  194. package/extensions/dm-lens/dist/clients/dispatch/runners/utils/spawn-outcome.js +40 -0
  195. package/extensions/dm-lens/dist/clients/dispatch/runners/utils/tool-failure.js +110 -0
  196. package/extensions/dm-lens/dist/clients/dispatch/runners/utils/toolchain-availability.js +88 -0
  197. package/extensions/dm-lens/dist/clients/dispatch/runners/utils.js +8 -0
  198. package/extensions/dm-lens/dist/clients/dispatch/runners/vale.js +92 -0
  199. package/extensions/dm-lens/dist/clients/dispatch/runners/yaml-rule-parser.js +170 -0
  200. package/extensions/dm-lens/dist/clients/dispatch/runners/yamllint.js +83 -0
  201. package/extensions/dm-lens/dist/clients/dispatch/runners/zig-check.js +72 -0
  202. package/extensions/dm-lens/dist/clients/dispatch/suppress-writer.js +57 -0
  203. package/extensions/dm-lens/dist/clients/dispatch/tool-profile.js +30 -0
  204. package/extensions/dm-lens/dist/clients/dispatch/types.js +72 -0
  205. package/extensions/dm-lens/dist/clients/dispatch/utils/format-utils.js +58 -0
  206. package/extensions/dm-lens/dist/clients/dispatch/utils/lsp-diagnostics.js +32 -0
  207. package/extensions/dm-lens/dist/clients/disposition-logger.js +19 -0
  208. package/extensions/dm-lens/dist/clients/disposition-publish.js +88 -0
  209. package/extensions/dm-lens/dist/clients/durable-store.js +77 -0
  210. package/extensions/dm-lens/dist/clients/effective-config.js +170 -0
  211. package/extensions/dm-lens/dist/clients/env-utils.js +26 -0
  212. package/extensions/dm-lens/dist/clients/ephemeral-root.js +55 -0
  213. package/extensions/dm-lens/dist/clients/error-class.js +3 -0
  214. package/extensions/dm-lens/dist/clients/eval-timestamp.js +2 -0
  215. package/extensions/dm-lens/dist/clients/event-loop-hold.js +119 -0
  216. package/extensions/dm-lens/dist/clients/event-loop-monitor.js +84 -0
  217. package/extensions/dm-lens/dist/clients/extension-log.js +230 -0
  218. package/extensions/dm-lens/dist/clients/extension-mode.js +20 -0
  219. package/extensions/dm-lens/dist/clients/feature-hints.js +88 -0
  220. package/extensions/dm-lens/dist/clients/file-kinds.js +317 -0
  221. package/extensions/dm-lens/dist/clients/file-mutation-queue.js +91 -0
  222. package/extensions/dm-lens/dist/clients/file-role.js +50 -0
  223. package/extensions/dm-lens/dist/clients/file-time.js +112 -0
  224. package/extensions/dm-lens/dist/clients/file-utils.js +840 -0
  225. package/extensions/dm-lens/dist/clients/finding-delivery-gate.js +146 -0
  226. package/extensions/dm-lens/dist/clients/finding-identity.js +79 -0
  227. package/extensions/dm-lens/dist/clients/fix-run-restore.js +423 -0
  228. package/extensions/dm-lens/dist/clients/fix-worklog.js +75 -0
  229. package/extensions/dm-lens/dist/clients/format-events-publish.js +310 -0
  230. package/extensions/dm-lens/dist/clients/format-service.js +177 -0
  231. package/extensions/dm-lens/dist/clients/formatters-lazy.js +8 -0
  232. package/extensions/dm-lens/dist/clients/formatters.js +1367 -0
  233. package/extensions/dm-lens/dist/clients/freshness-cadence.js +1 -0
  234. package/extensions/dm-lens/dist/clients/freshness.js +8 -0
  235. package/extensions/dm-lens/dist/clients/generated-artifacts.js +209 -0
  236. package/extensions/dm-lens/dist/clients/generation-guard.js +147 -0
  237. package/extensions/dm-lens/dist/clients/generation-lock.js +181 -0
  238. package/extensions/dm-lens/dist/clients/git-guard.js +1208 -0
  239. package/extensions/dm-lens/dist/clients/git-tracked-ignore.js +120 -0
  240. package/extensions/dm-lens/dist/clients/gitleaks-client.js +290 -0
  241. package/extensions/dm-lens/dist/clients/go-client.js +47 -0
  242. package/extensions/dm-lens/dist/clients/govulncheck-client.js +416 -0
  243. package/extensions/dm-lens/dist/clients/gradle-ktfmt-style.js +177 -0
  244. package/extensions/dm-lens/dist/clients/grammar-source.js +263 -0
  245. package/extensions/dm-lens/dist/clients/grammar-wasm-imports.js +48 -0
  246. package/extensions/dm-lens/dist/clients/gzip-stage-write.js +174 -0
  247. package/extensions/dm-lens/dist/clients/hard-failure-summary.js +28 -0
  248. package/extensions/dm-lens/dist/clients/hashline-anchor.js +222 -0
  249. package/extensions/dm-lens/dist/clients/hook-budgets.js +17 -0
  250. package/extensions/dm-lens/dist/clients/host-edit-normalize.js +87 -0
  251. package/extensions/dm-lens/dist/clients/host-ports.js +35 -0
  252. package/extensions/dm-lens/dist/clients/indent-retarget.js +102 -0
  253. package/extensions/dm-lens/dist/clients/inline-blocker-dispositions.js +103 -0
  254. package/extensions/dm-lens/dist/clients/inline-blocker-fields.js +8 -0
  255. package/extensions/dm-lens/dist/clients/install-diagnostics.js +135 -0
  256. package/extensions/dm-lens/dist/clients/installer/index.js +3928 -0
  257. package/extensions/dm-lens/dist/clients/installer/managed-tool-refresh-session.js +17 -0
  258. package/extensions/dm-lens/dist/clients/installer/managed-tool-refresh.js +721 -0
  259. package/extensions/dm-lens/dist/clients/instance-reaper-state.js +3 -0
  260. package/extensions/dm-lens/dist/clients/instance-reaper.js +693 -0
  261. package/extensions/dm-lens/dist/clients/instance-registry-lock.js +166 -0
  262. package/extensions/dm-lens/dist/clients/instance-registry-tail.js +17 -0
  263. package/extensions/dm-lens/dist/clients/instance-registry.js +607 -0
  264. package/extensions/dm-lens/dist/clients/io-bridge-contract.js +7 -0
  265. package/extensions/dm-lens/dist/clients/io-bridge.js +357 -0
  266. package/extensions/dm-lens/dist/clients/jscpd-client.js +311 -0
  267. package/extensions/dm-lens/dist/clients/json-cache-read.js +25 -0
  268. package/extensions/dm-lens/dist/clients/knip-client.js +534 -0
  269. package/extensions/dm-lens/dist/clients/knip-scan-roots.js +26 -0
  270. package/extensions/dm-lens/dist/clients/language-policy.js +244 -0
  271. package/extensions/dm-lens/dist/clients/language-profile.js +259 -0
  272. package/extensions/dm-lens/dist/clients/language-registry.js +468 -0
  273. package/extensions/dm-lens/dist/clients/latency-logger.js +210 -0
  274. package/extensions/dm-lens/dist/clients/lazy-import.js +14 -0
  275. package/extensions/dm-lens/dist/clients/ledger-bounds.js +21 -0
  276. package/extensions/dm-lens/dist/clients/lens-config.js +254 -0
  277. package/extensions/dm-lens/dist/clients/lens-engine.js +188 -0
  278. package/extensions/dm-lens/dist/clients/lens-events.js +105 -0
  279. package/extensions/dm-lens/dist/clients/lens-flag-registry.js +308 -0
  280. package/extensions/dm-lens/dist/clients/lens-map.js +980 -0
  281. package/extensions/dm-lens/dist/clients/line-alignment.js +200 -0
  282. package/extensions/dm-lens/dist/clients/live-bus-emitter.js +53 -0
  283. package/extensions/dm-lens/dist/clients/log-cleanup.js +138 -0
  284. package/extensions/dm-lens/dist/clients/lsp/aggregation.js +89 -0
  285. package/extensions/dm-lens/dist/clients/lsp/auxiliary-lifecycle.js +23 -0
  286. package/extensions/dm-lens/dist/clients/lsp/capabilities.js +94 -0
  287. package/extensions/dm-lens/dist/clients/lsp/cascade-tier.js +318 -0
  288. package/extensions/dm-lens/dist/clients/lsp/client-registry.js +877 -0
  289. package/extensions/dm-lens/dist/clients/lsp/client.js +3232 -0
  290. package/extensions/dm-lens/dist/clients/lsp/config.js +571 -0
  291. package/extensions/dm-lens/dist/clients/lsp/content-limits.js +21 -0
  292. package/extensions/dm-lens/dist/clients/lsp/content-scan.js +69 -0
  293. package/extensions/dm-lens/dist/clients/lsp/created-import-targets.js +134 -0
  294. package/extensions/dm-lens/dist/clients/lsp/diagnostic-binding.js +113 -0
  295. package/extensions/dm-lens/dist/clients/lsp/document-drift.js +372 -0
  296. package/extensions/dm-lens/dist/clients/lsp/edits.js +1060 -0
  297. package/extensions/dm-lens/dist/clients/lsp/environment-gap.js +186 -0
  298. package/extensions/dm-lens/dist/clients/lsp/file-server-match.js +26 -0
  299. package/extensions/dm-lens/dist/clients/lsp/grouping.js +38 -0
  300. package/extensions/dm-lens/dist/clients/lsp/implicit-scope.js +205 -0
  301. package/extensions/dm-lens/dist/clients/lsp/index.js +4292 -0
  302. package/extensions/dm-lens/dist/clients/lsp/inferred-project.js +140 -0
  303. package/extensions/dm-lens/dist/clients/lsp/jvm-runtime.js +200 -0
  304. package/extensions/dm-lens/dist/clients/lsp/language.js +26 -0
  305. package/extensions/dm-lens/dist/clients/lsp/launch.js +606 -0
  306. package/extensions/dm-lens/dist/clients/lsp/lombok.js +133 -0
  307. package/extensions/dm-lens/dist/clients/lsp/path-utils.js +1 -0
  308. package/extensions/dm-lens/dist/clients/lsp/pending-aux-coverage.js +120 -0
  309. package/extensions/dm-lens/dist/clients/lsp/position-encoding.js +21 -0
  310. package/extensions/dm-lens/dist/clients/lsp/resolved-config.js +183 -0
  311. package/extensions/dm-lens/dist/clients/lsp/ruby-drive-dirs.js +42 -0
  312. package/extensions/dm-lens/dist/clients/lsp/server-config-files.js +11 -0
  313. package/extensions/dm-lens/dist/clients/lsp/server-covers.js +8 -0
  314. package/extensions/dm-lens/dist/clients/lsp/server-traits.js +45 -0
  315. package/extensions/dm-lens/dist/clients/lsp/server.js +2827 -0
  316. package/extensions/dm-lens/dist/clients/lsp/service-singleton.js +59 -0
  317. package/extensions/dm-lens/dist/clients/lsp/session-roots.js +83 -0
  318. package/extensions/dm-lens/dist/clients/lsp/spawn-history.js +15 -0
  319. package/extensions/dm-lens/dist/clients/lsp/sync-kind.js +30 -0
  320. package/extensions/dm-lens/dist/clients/lsp/tsserver-sync.js +156 -0
  321. package/extensions/dm-lens/dist/clients/lsp/wait-policy/capability-snapshot.js +1 -0
  322. package/extensions/dm-lens/dist/clients/lsp/wait-policy/classification.js +37 -0
  323. package/extensions/dm-lens/dist/clients/lsp/wait-policy/index.js +3 -0
  324. package/extensions/dm-lens/dist/clients/lsp/wait-policy/strategies.js +276 -0
  325. package/extensions/dm-lens/dist/clients/lsp/watch-queue.js +61 -0
  326. package/extensions/dm-lens/dist/clients/lsp/workspace-diagnostics-cache.js +395 -0
  327. package/extensions/dm-lens/dist/clients/lsp/workspace-diagnostics-session.js +42 -0
  328. package/extensions/dm-lens/dist/clients/lsp/workspace-sweep-hold.js +93 -0
  329. package/extensions/dm-lens/dist/clients/lsp-budget.js +87 -0
  330. package/extensions/dm-lens/dist/clients/lsp-document-symbols.js +93 -0
  331. package/extensions/dm-lens/dist/clients/lsp-lazy.js +8 -0
  332. package/extensions/dm-lens/dist/clients/lsp-mutation.js +309 -0
  333. package/extensions/dm-lens/dist/clients/lsp-status.js +35 -0
  334. package/extensions/dm-lens/dist/clients/map-with-concurrency.js +20 -0
  335. package/extensions/dm-lens/dist/clients/mcp/analyze.js +302 -0
  336. package/extensions/dm-lens/dist/clients/mcp/host-shim.js +14 -0
  337. package/extensions/dm-lens/dist/clients/mcp/ipc.js +344 -0
  338. package/extensions/dm-lens/dist/clients/mcp/review.js +137 -0
  339. package/extensions/dm-lens/dist/clients/mcp/session.js +300 -0
  340. package/extensions/dm-lens/dist/clients/memory-sampler.js +163 -0
  341. package/extensions/dm-lens/dist/clients/message-end-attribution.js +18 -0
  342. package/extensions/dm-lens/dist/clients/metrics-client.js +80 -0
  343. package/extensions/dm-lens/dist/clients/metrics-history.js +242 -0
  344. package/extensions/dm-lens/dist/clients/middle-man-analysis.js +161 -0
  345. package/extensions/dm-lens/dist/clients/model-provider.js +31 -0
  346. package/extensions/dm-lens/dist/clients/module-report-lsp.js +140 -0
  347. package/extensions/dm-lens/dist/clients/module-report.js +1648 -0
  348. package/extensions/dm-lens/dist/clients/mutating-tool.js +388 -0
  349. package/extensions/dm-lens/dist/clients/mutation-attribution.js +173 -0
  350. package/extensions/dm-lens/dist/clients/mutation-bridge.js +231 -0
  351. package/extensions/dm-lens/dist/clients/ndjson-logger.js +504 -0
  352. package/extensions/dm-lens/dist/clients/observed-mutation-sources.js +43 -0
  353. package/extensions/dm-lens/dist/clients/observed-mutation.js +735 -0
  354. package/extensions/dm-lens/dist/clients/oldtext-autopatch.js +100 -0
  355. package/extensions/dm-lens/dist/clients/opaque-mutation-scan.js +541 -0
  356. package/extensions/dm-lens/dist/clients/opengrep-client.js +224 -0
  357. package/extensions/dm-lens/dist/clients/opengrep-config.js +57 -0
  358. package/extensions/dm-lens/dist/clients/opengrep-rule-pack.js +19 -0
  359. package/extensions/dm-lens/dist/clients/out-of-band-changes.js +329 -0
  360. package/extensions/dm-lens/dist/clients/package-manager.js +332 -0
  361. package/extensions/dm-lens/dist/clients/package-root.js +21 -0
  362. package/extensions/dm-lens/dist/clients/partial-edit-apply.js +341 -0
  363. package/extensions/dm-lens/dist/clients/path-attribution-telemetry.js +31 -0
  364. package/extensions/dm-lens/dist/clients/path-birth.js +58 -0
  365. package/extensions/dm-lens/dist/clients/path-keyed-map.js +57 -0
  366. package/extensions/dm-lens/dist/clients/path-utils.js +654 -0
  367. package/extensions/dm-lens/dist/clients/performance-report.js +291 -0
  368. package/extensions/dm-lens/dist/clients/persist-debounce.js +37 -0
  369. package/extensions/dm-lens/dist/clients/persist-worker-stats.js +16 -0
  370. package/extensions/dm-lens/dist/clients/persistent-reverify.js +167 -0
  371. package/extensions/dm-lens/dist/clients/php-cs-fixer-config.js +15 -0
  372. package/extensions/dm-lens/dist/clients/pipeline.js +1473 -0
  373. package/extensions/dm-lens/dist/clients/post-autofix-notice.js +19 -0
  374. package/extensions/dm-lens/dist/clients/print-mode.js +3 -0
  375. package/extensions/dm-lens/dist/clients/probe-home-state.js +73 -0
  376. package/extensions/dm-lens/dist/clients/process-bridge.js +48 -0
  377. package/extensions/dm-lens/dist/clients/process-singletons.js +69 -0
  378. package/extensions/dm-lens/dist/clients/process-snapshot.js +130 -0
  379. package/extensions/dm-lens/dist/clients/project-changes.js +180 -0
  380. package/extensions/dm-lens/dist/clients/project-conventions.js +152 -0
  381. package/extensions/dm-lens/dist/clients/project-diagnostics/cache.js +91 -0
  382. package/extensions/dm-lens/dist/clients/project-diagnostics/extractors.js +53 -0
  383. package/extensions/dm-lens/dist/clients/project-diagnostics/fresh-fetch.js +413 -0
  384. package/extensions/dm-lens/dist/clients/project-diagnostics/runner-adapters/call-graph-impact.js +64 -0
  385. package/extensions/dm-lens/dist/clients/project-diagnostics/runner-adapters/dead-code.js +38 -0
  386. package/extensions/dm-lens/dist/clients/project-diagnostics/runner-adapters/gitleaks.js +21 -0
  387. package/extensions/dm-lens/dist/clients/project-diagnostics/runner-adapters/govulncheck.js +23 -0
  388. package/extensions/dm-lens/dist/clients/project-diagnostics/runner-adapters/jscpd.js +28 -0
  389. package/extensions/dm-lens/dist/clients/project-diagnostics/runner-adapters/knip.js +45 -0
  390. package/extensions/dm-lens/dist/clients/project-diagnostics/runner-adapters/madge.js +34 -0
  391. package/extensions/dm-lens/dist/clients/project-diagnostics/runner-adapters/opengrep.js +32 -0
  392. package/extensions/dm-lens/dist/clients/project-diagnostics/runner-adapters/runner-findings.js +79 -0
  393. package/extensions/dm-lens/dist/clients/project-diagnostics/runner-adapters/trivy.js +41 -0
  394. package/extensions/dm-lens/dist/clients/project-diagnostics/scanner.js +351 -0
  395. package/extensions/dm-lens/dist/clients/project-diagnostics/types.js +1 -0
  396. package/extensions/dm-lens/dist/clients/project-lens-config.js +462 -0
  397. package/extensions/dm-lens/dist/clients/project-report.js +527 -0
  398. package/extensions/dm-lens/dist/clients/project-root-markers.js +8 -0
  399. package/extensions/dm-lens/dist/clients/project-scale.js +60 -0
  400. package/extensions/dm-lens/dist/clients/project-scan-policy.js +4 -0
  401. package/extensions/dm-lens/dist/clients/project-snapshot-fingerprint.js +44 -0
  402. package/extensions/dm-lens/dist/clients/project-snapshot-persist-worker.js +31 -0
  403. package/extensions/dm-lens/dist/clients/project-snapshot.js +1355 -0
  404. package/extensions/dm-lens/dist/clients/project-trust.js +104 -0
  405. package/extensions/dm-lens/dist/clients/python-environment.js +388 -0
  406. package/extensions/dm-lens/dist/clients/python-provenance.js +551 -0
  407. package/extensions/dm-lens/dist/clients/quiet-window-config.js +16 -0
  408. package/extensions/dm-lens/dist/clients/quiet-window.js +129 -0
  409. package/extensions/dm-lens/dist/clients/read-bridge.js +53 -0
  410. package/extensions/dm-lens/dist/clients/read-expansion.js +218 -0
  411. package/extensions/dm-lens/dist/clients/read-guard-branch.js +126 -0
  412. package/extensions/dm-lens/dist/clients/read-guard-logger.js +186 -0
  413. package/extensions/dm-lens/dist/clients/read-guard-tool-lines.js +1044 -0
  414. package/extensions/dm-lens/dist/clients/read-guard.js +1517 -0
  415. package/extensions/dm-lens/dist/clients/recent-touches.js +126 -0
  416. package/extensions/dm-lens/dist/clients/redact/secrets.js +386 -0
  417. package/extensions/dm-lens/dist/clients/resource-sampler.js +344 -0
  418. package/extensions/dm-lens/dist/clients/reverse-deps.js +227 -0
  419. package/extensions/dm-lens/dist/clients/review-graph/builder.js +3780 -0
  420. package/extensions/dm-lens/dist/clients/review-graph/format.js +30 -0
  421. package/extensions/dm-lens/dist/clients/review-graph/git-identity.js +173 -0
  422. package/extensions/dm-lens/dist/clients/review-graph/import-resolvers.js +332 -0
  423. package/extensions/dm-lens/dist/clients/review-graph/persist-worker.js +8 -0
  424. package/extensions/dm-lens/dist/clients/review-graph/query.js +195 -0
  425. package/extensions/dm-lens/dist/clients/review-graph/revision-drift.js +3 -0
  426. package/extensions/dm-lens/dist/clients/review-graph/service.js +60 -0
  427. package/extensions/dm-lens/dist/clients/review-graph/shared-extraction-ir.js +54 -0
  428. package/extensions/dm-lens/dist/clients/review-graph/symbol-id.js +29 -0
  429. package/extensions/dm-lens/dist/clients/review-graph/tsconfig-paths.js +286 -0
  430. package/extensions/dm-lens/dist/clients/review-graph/types.js +1 -0
  431. package/extensions/dm-lens/dist/clients/review-graph/workspace-modules.js +374 -0
  432. package/extensions/dm-lens/dist/clients/review-graph-logger.js +51 -0
  433. package/extensions/dm-lens/dist/clients/ruff-client.js +107 -0
  434. package/extensions/dm-lens/dist/clients/rules-scanner.js +70 -0
  435. package/extensions/dm-lens/dist/clients/run-duration.js +9 -0
  436. package/extensions/dm-lens/dist/clients/runtime-agent-end.js +831 -0
  437. package/extensions/dm-lens/dist/clients/runtime-config.js +39 -0
  438. package/extensions/dm-lens/dist/clients/runtime-context.js +155 -0
  439. package/extensions/dm-lens/dist/clients/runtime-coordinator.js +1254 -0
  440. package/extensions/dm-lens/dist/clients/runtime-session.js +1806 -0
  441. package/extensions/dm-lens/dist/clients/runtime-tool-call.js +1026 -0
  442. package/extensions/dm-lens/dist/clients/runtime-tool-result.js +2068 -0
  443. package/extensions/dm-lens/dist/clients/runtime-turn.js +3198 -0
  444. package/extensions/dm-lens/dist/clients/rust-client.js +46 -0
  445. package/extensions/dm-lens/dist/clients/safe-spawn.js +1402 -0
  446. package/extensions/dm-lens/dist/clients/sanitize.js +5 -0
  447. package/extensions/dm-lens/dist/clients/scan-utils.js +7 -0
  448. package/extensions/dm-lens/dist/clients/scanner-temp-root.js +8 -0
  449. package/extensions/dm-lens/dist/clients/scratch-tree-policy.js +63 -0
  450. package/extensions/dm-lens/dist/clients/search-read-registration.js +76 -0
  451. package/extensions/dm-lens/dist/clients/secret-findings.js +69 -0
  452. package/extensions/dm-lens/dist/clients/security-scan-client.js +208 -0
  453. package/extensions/dm-lens/dist/clients/session-event-guard.js +111 -0
  454. package/extensions/dm-lens/dist/clients/session-lifecycle.js +309 -0
  455. package/extensions/dm-lens/dist/clients/session-repository.js +113 -0
  456. package/extensions/dm-lens/dist/clients/session-scope.js +451 -0
  457. package/extensions/dm-lens/dist/clients/session-start-observability.js +59 -0
  458. package/extensions/dm-lens/dist/clients/session-state-store.js +71 -0
  459. package/extensions/dm-lens/dist/clients/session-summary.js +8 -0
  460. package/extensions/dm-lens/dist/clients/sessionstart-logger.js +22 -0
  461. package/extensions/dm-lens/dist/clients/sg-runner.js +642 -0
  462. package/extensions/dm-lens/dist/clients/sgconfig.js +299 -0
  463. package/extensions/dm-lens/dist/clients/shared-checkout-guard.js +177 -0
  464. package/extensions/dm-lens/dist/clients/single-flight.js +53 -0
  465. package/extensions/dm-lens/dist/clients/situational-tool-telemetry.js +85 -0
  466. package/extensions/dm-lens/dist/clients/skills-resolver.js +38 -0
  467. package/extensions/dm-lens/dist/clients/slow-fs.js +77 -0
  468. package/extensions/dm-lens/dist/clients/smells-rollup.js +118 -0
  469. package/extensions/dm-lens/dist/clients/source-filter.js +323 -0
  470. package/extensions/dm-lens/dist/clients/source-walker.js +114 -0
  471. package/extensions/dm-lens/dist/clients/spawn-output-cap.js +35 -0
  472. package/extensions/dm-lens/dist/clients/spawn-timeout-cooldown.js +51 -0
  473. package/extensions/dm-lens/dist/clients/stale-marker.js +1 -0
  474. package/extensions/dm-lens/dist/clients/startup-scan.js +221 -0
  475. package/extensions/dm-lens/dist/clients/startup-timing.js +67 -0
  476. package/extensions/dm-lens/dist/clients/string-utils.js +6 -0
  477. package/extensions/dm-lens/dist/clients/subagent-mode.js +40 -0
  478. package/extensions/dm-lens/dist/clients/symbol-containment.js +16 -0
  479. package/extensions/dm-lens/dist/clients/symbol-types.js +1 -0
  480. package/extensions/dm-lens/dist/clients/test-runner-client.js +1686 -0
  481. package/extensions/dm-lens/dist/clients/test-runner-delivery.js +285 -0
  482. package/extensions/dm-lens/dist/clients/test-target-roots.js +17 -0
  483. package/extensions/dm-lens/dist/clients/todo-scanner.js +164 -0
  484. package/extensions/dm-lens/dist/clients/tool-agreement.js +640 -0
  485. package/extensions/dm-lens/dist/clients/tool-config.js +239 -0
  486. package/extensions/dm-lens/dist/clients/tool-cwd.js +236 -0
  487. package/extensions/dm-lens/dist/clients/tool-definition.js +22 -0
  488. package/extensions/dm-lens/dist/clients/tool-event.js +24 -0
  489. package/extensions/dm-lens/dist/clients/tool-policy.js +2386 -0
  490. package/extensions/dm-lens/dist/clients/tool-probe.js +13 -0
  491. package/extensions/dm-lens/dist/clients/tool-render.js +79 -0
  492. package/extensions/dm-lens/dist/clients/tool-set-policy.js +106 -0
  493. package/extensions/dm-lens/dist/clients/tree-sitter-cache.js +206 -0
  494. package/extensions/dm-lens/dist/clients/tree-sitter-client.js +3101 -0
  495. package/extensions/dm-lens/dist/clients/tree-sitter-logger.js +77 -0
  496. package/extensions/dm-lens/dist/clients/tree-sitter-navigator.js +198 -0
  497. package/extensions/dm-lens/dist/clients/tree-sitter-query-loader.js +401 -0
  498. package/extensions/dm-lens/dist/clients/tree-sitter-shared.js +87 -0
  499. package/extensions/dm-lens/dist/clients/tree-sitter-symbol-extractor.js +984 -0
  500. package/extensions/dm-lens/dist/clients/trivy-client.js +335 -0
  501. package/extensions/dm-lens/dist/clients/tui-fit.js +26 -0
  502. package/extensions/dm-lens/dist/clients/turn-context.js +48 -0
  503. package/extensions/dm-lens/dist/clients/turn-end/delivery-holds.js +59 -0
  504. package/extensions/dm-lens/dist/clients/turn-end/lane.js +1 -0
  505. package/extensions/dm-lens/dist/clients/turn-end/lanes/govulncheck.js +54 -0
  506. package/extensions/dm-lens/dist/clients/turn-end/lanes/secrets.js +131 -0
  507. package/extensions/dm-lens/dist/clients/turn-summary-render.js +56 -0
  508. package/extensions/dm-lens/dist/clients/turn-summary.js +84 -0
  509. package/extensions/dm-lens/dist/clients/typos-config.js +9 -0
  510. package/extensions/dm-lens/dist/clients/user-notify.js +15 -0
  511. package/extensions/dm-lens/dist/clients/vanished-instance-marker.js +18 -0
  512. package/extensions/dm-lens/dist/clients/warm-attach.js +232 -0
  513. package/extensions/dm-lens/dist/clients/widget-state.js +1014 -0
  514. package/extensions/dm-lens/dist/clients/word-index-logger.js +24 -0
  515. package/extensions/dm-lens/dist/clients/word-index-store.js +222 -0
  516. package/extensions/dm-lens/dist/clients/word-index.js +1503 -0
  517. package/extensions/dm-lens/dist/clients/workspace-topology.js +274 -0
  518. package/extensions/dm-lens/dist/clients/write-ordering-guard.js +28 -0
  519. package/extensions/dm-lens/dist/clients/zizmor-config.js +160 -0
  520. package/extensions/dm-lens/dist/i18n.js +67 -0
  521. package/extensions/dm-lens/dist/index.js +2144 -0
  522. package/extensions/dm-lens/dist/mcp/analyze-cli.js +205 -0
  523. package/extensions/dm-lens/dist/mcp/build-staleness.js +55 -0
  524. package/extensions/dm-lens/dist/mcp/cli.js +96 -0
  525. package/extensions/dm-lens/dist/mcp/server.js +1241 -0
  526. package/extensions/dm-lens/dist/mcp/tool-arguments.js +134 -0
  527. package/extensions/dm-lens/dist/mcp/worker.js +41 -0
  528. package/extensions/dm-lens/dist/scripts/lib/process-scan.mjs +375 -0
  529. package/extensions/dm-lens/dist/scripts/lib/skills-predicate.mjs +53 -0
  530. package/extensions/dm-lens/dist/scripts/lib/web-tree-sitter-dir.mjs +51 -0
  531. package/extensions/dm-lens/dist/tools/activate-tools.js +63 -0
  532. package/extensions/dm-lens/dist/tools/ast-grep-outline.js +128 -0
  533. package/extensions/dm-lens/dist/tools/ast-grep-replace.js +234 -0
  534. package/extensions/dm-lens/dist/tools/ast-grep-search.js +690 -0
  535. package/extensions/dm-lens/dist/tools/effective-config.js +59 -0
  536. package/extensions/dm-lens/dist/tools/lens-diagnostic-mark.js +251 -0
  537. package/extensions/dm-lens/dist/tools/lens-diagnostics.js +1693 -0
  538. package/extensions/dm-lens/dist/tools/lsp-diagnostics.js +1397 -0
  539. package/extensions/dm-lens/dist/tools/lsp-navigation.js +1301 -0
  540. package/extensions/dm-lens/dist/tools/lsp-structured-output.js +277 -0
  541. package/extensions/dm-lens/dist/tools/module-report.js +333 -0
  542. package/extensions/dm-lens/dist/tools/project-report.js +72 -0
  543. package/extensions/dm-lens/dist/tools/render-compact.js +272 -0
  544. package/extensions/dm-lens/dist/tools/scan-progress.js +31 -0
  545. package/extensions/dm-lens/dist/tools/shared.js +46 -0
  546. package/extensions/dm-lens/dist/tools/symbol-search.js +133 -0
  547. package/extensions/dm-mcp-adapter/dist/abort.js +35 -0
  548. package/extensions/dm-mcp-adapter/dist/agent-dir.js +45 -0
  549. package/extensions/dm-mcp-adapter/dist/agent-plugin-loader.js +392 -0
  550. package/extensions/dm-mcp-adapter/dist/agent-plugin-provenance.js +26 -0
  551. package/extensions/dm-mcp-adapter/dist/bearer-command-resolver.js +184 -0
  552. package/extensions/dm-mcp-adapter/dist/claude-plugin-loader.js +350 -0
  553. package/extensions/dm-mcp-adapter/dist/config.js +1984 -0
  554. package/extensions/dm-mcp-adapter/dist/consent-manager.js +84 -0
  555. package/extensions/dm-mcp-adapter/dist/elicitation-handler.js +374 -0
  556. package/extensions/dm-mcp-adapter/dist/errors.js +225 -0
  557. package/extensions/dm-mcp-adapter/dist/extraction-settings.js +43 -0
  558. package/extensions/dm-mcp-adapter/dist/http-ca.js +75 -0
  559. package/extensions/dm-mcp-adapter/dist/jev-client.js +359 -0
  560. package/extensions/dm-mcp-adapter/dist/jev-contracts.js +1 -0
  561. package/extensions/dm-mcp-adapter/dist/jev-key-store.js +189 -0
  562. package/extensions/dm-mcp-adapter/dist/json-schema-validator.js +70 -0
  563. package/extensions/dm-mcp-adapter/dist/lifecycle.js +387 -0
  564. package/extensions/dm-mcp-adapter/dist/logger.js +115 -0
  565. package/extensions/dm-mcp-adapter/dist/mcp-auth-fetch.js +86 -0
  566. package/extensions/dm-mcp-adapter/dist/mcp-auth-flow.js +956 -0
  567. package/extensions/dm-mcp-adapter/dist/mcp-auth.js +998 -0
  568. package/extensions/dm-mcp-adapter/dist/mcp-bearer-store.js +182 -0
  569. package/extensions/dm-mcp-adapter/dist/mcp-callback-server.js +380 -0
  570. package/extensions/dm-mcp-adapter/dist/mcp-oauth-provider.js +525 -0
  571. package/extensions/dm-mcp-adapter/dist/mcp-probe.js +151 -0
  572. package/extensions/dm-mcp-adapter/dist/mcp-tasks.js +339 -0
  573. package/extensions/dm-mcp-adapter/dist/mcp-trace.js +220 -0
  574. package/extensions/dm-mcp-adapter/dist/metadata-cache.js +411 -0
  575. package/extensions/dm-mcp-adapter/dist/npx-resolver.js +465 -0
  576. package/extensions/dm-mcp-adapter/dist/output-shape.js +312 -0
  577. package/extensions/dm-mcp-adapter/dist/package-mcp-loader.js +144 -0
  578. package/extensions/dm-mcp-adapter/dist/project-server-trust.js +274 -0
  579. package/extensions/dm-mcp-adapter/dist/request-headers-command.js +310 -0
  580. package/extensions/dm-mcp-adapter/dist/resource-tools.js +7 -0
  581. package/extensions/dm-mcp-adapter/dist/runtime-owner.js +95 -0
  582. package/extensions/dm-mcp-adapter/dist/sampling-handler.js +219 -0
  583. package/extensions/dm-mcp-adapter/dist/script-tools.js +72 -0
  584. package/extensions/dm-mcp-adapter/dist/secure-keyring.js +191 -0
  585. package/extensions/dm-mcp-adapter/dist/semantic-settings.js +51 -0
  586. package/extensions/dm-mcp-adapter/dist/server-log.js +19 -0
  587. package/extensions/dm-mcp-adapter/dist/server-manager.js +1635 -0
  588. package/extensions/dm-mcp-adapter/dist/session-approvals.js +127 -0
  589. package/extensions/dm-mcp-adapter/dist/session-recovery.js +83 -0
  590. package/extensions/dm-mcp-adapter/dist/state.js +1 -0
  591. package/extensions/dm-mcp-adapter/dist/task-entries.js +60 -0
  592. package/extensions/dm-mcp-adapter/dist/task-jobs.js +259 -0
  593. package/extensions/dm-mcp-adapter/dist/ts-shape.js +157 -0
  594. package/extensions/dm-mcp-adapter/dist/types.js +293 -0
  595. package/extensions/dm-mcp-adapter/dist/ui-app-bridge-helpers.js +36 -0
  596. package/extensions/dm-mcp-adapter/dist/ui-resource-handler.js +204 -0
  597. package/extensions/dm-mcp-adapter/dist/ui-stream-types.js +58 -0
  598. package/extensions/dm-mcp-adapter/dist/ui-tool-visibility.js +26 -0
  599. package/extensions/dm-mcp-adapter/dist/unix-socket-transport.js +83 -0
  600. package/extensions/dm-mcp-adapter/dist/utils.js +444 -0
  601. package/extensions/dm-mcp-adapter/mcp-keyring-helper.cjs +1 -1
  602. package/extensions/dm-ponytail/hooks/ponytail-activate.js +1 -1
  603. package/extensions/dm-ponytail/hooks/ponytail-instructions.js +1 -1
  604. package/extensions/dm-ponytail/hooks/ponytail-mode-tracker.js +1 -1
  605. package/package.json +1 -1
@@ -0,0 +1,3232 @@
1
+ import { spawn as nodeSpawn } from "node:child_process";
2
+ import { EventEmitter } from "node:events";
3
+ import { access, lstat, readFile, stat } from "node:fs/promises";
4
+ import * as os from "node:os";
5
+ import { pathToFileURL } from "node:url";
6
+ import { emitBounded } from "../bounded-telemetry.js";
7
+ import { withTimeout } from "../deadline-utils.js";
8
+ import { minimatch } from "../deps/minimatch.js";
9
+ import { mapWithConcurrency } from "../map-with-concurrency.js";
10
+ import { incrementDegradationCount, recordDegradationOnce, truncateForLedger } from "../degradation-ledger.js";
11
+ import { CancellationTokenSource, createMessageConnection, StreamMessageReader, StreamMessageWriter } from "../deps/vscode-jsonrpc.js";
12
+ import { logExtension } from "../extension-log.js";
13
+ import { recordLspChild, removeLspChild } from "../instance-registry.js";
14
+ import { noteWorkspaceFileCreated, workspaceDiagnosticsCacheSessionStart } from "./workspace-diagnostics-session.js";
15
+ import { logLatency } from "../latency-logger.js";
16
+ import { newLspMutationCorrelationId } from "../lsp-mutation.js";
17
+ import { getProcessSingleton } from "../process-singletons.js";
18
+ import { getAmbientAbortSignal, isOwnLiveChild, releaseOwnChildPid } from "../safe-spawn.js";
19
+ import { raceToCompletion } from "./aggregation.js";
20
+ import { hashDiagnosticContent } from "./diagnostic-binding.js";
21
+ import { applyWorkspaceEdit, normalizeWorkspaceEditToUtf16 } from "./edits.js";
22
+ import { normalizeMapKey, uriToPath } from "./path-utils.js";
23
+ import { lineTextAt, scanDocumentContent } from "./content-scan.js";
24
+ import { ADVERTISED_POSITION_ENCODINGS, convertCharacterOffset, negotiatePositionEncoding } from "./position-encoding.js";
25
+ import { negotiateSaveOptions, negotiateSyncKind, TEXT_DOCUMENT_SYNC_KIND_FULL, TEXT_DOCUMENT_SYNC_KIND_INCREMENTAL } from "./sync-kind.js";
26
+ import { exceedsLspSyncLimits } from "./content-limits.js";
27
+ import { probeTsserverProjectIdentity } from "./tsserver-sync.js";
28
+ import { getStrategy } from "./wait-policy/index.js";
29
+ import { isAuxiliary } from "./server-traits.js";
30
+ import { FILE_CHANGED, FILE_CREATED, FILE_DELETED, WatchedFilesQueue, watchedTypeForOpen } from "./watch-queue.js";
31
+ import { pathBirthtimeMs } from "../path-birth.js";
32
+ import { BoundedSet } from "../bounded-cache.js";
33
+ import { clearAllWorkspaceDiagnosticsCaches, clearWorkspaceDiagnosticsCacheAtAndAbove } from "./workspace-diagnostics-cache.js";
34
+ const PUB_DEBUG = Boolean(process.env.PILENS_PUB_DEBUG);
35
+ function extractSpawnMarker(args) {
36
+ if (!args)
37
+ return;
38
+ const tmpDir = os.tmpdir();
39
+ for (let i = 0;i < args.length - 1; i++) {
40
+ const flag = args[i];
41
+ if (flag === "--config" || flag === "-c") {
42
+ const value = args[i + 1];
43
+ if (value?.startsWith(tmpDir))
44
+ return value;
45
+ }
46
+ }
47
+ return;
48
+ }
49
+ export const INITIALIZE_TIMEOUT_MS = positiveIntFromEnv("DM_LENS_LSP_INIT_TIMEOUT_MS", 15000);
50
+ export const CLIENT_CAPABILITIES = {
51
+ general: { positionEncodings: ADVERTISED_POSITION_ENCODINGS },
52
+ window: {},
53
+ workspace: {
54
+ workspaceFolders: true,
55
+ configuration: true,
56
+ didChangeWatchedFiles: { dynamicRegistration: true },
57
+ fileOperations: {
58
+ dynamicRegistration: false,
59
+ willRename: true,
60
+ didRename: true,
61
+ didCreate: true
62
+ }
63
+ },
64
+ textDocument: {
65
+ synchronization: {
66
+ dynamicRegistration: false,
67
+ willSave: false,
68
+ willSaveWaitUntil: false,
69
+ didSave: true
70
+ },
71
+ completion: {
72
+ dynamicRegistration: false,
73
+ completionItem: { snippetSupport: false }
74
+ },
75
+ hover: { dynamicRegistration: false },
76
+ signatureHelp: { dynamicRegistration: false },
77
+ definition: { dynamicRegistration: false },
78
+ typeDefinition: { dynamicRegistration: false },
79
+ implementation: { dynamicRegistration: false },
80
+ references: { dynamicRegistration: false },
81
+ documentSymbol: { dynamicRegistration: false },
82
+ codeAction: {
83
+ dynamicRegistration: false,
84
+ dataSupport: true,
85
+ resolveSupport: { properties: ["edit", "command"] },
86
+ codeActionLiteralSupport: {
87
+ codeActionKind: {
88
+ valueSet: [
89
+ "quickfix",
90
+ "refactor",
91
+ "refactor.extract",
92
+ "refactor.inline",
93
+ "refactor.rewrite",
94
+ "source",
95
+ "source.organizeImports"
96
+ ]
97
+ }
98
+ }
99
+ },
100
+ rename: { dynamicRegistration: false },
101
+ publishDiagnostics: {
102
+ relatedInformation: true,
103
+ versionSupport: true
104
+ }
105
+ }
106
+ };
107
+ const NAV_REQUEST_TIMEOUT_MS = positiveIntFromEnv("DM_LENS_LSP_NAV_REQUEST_TIMEOUT_MS", 1e4);
108
+ const DIAGNOSTICS_WAIT_TIMEOUT_MS = positiveIntFromEnv("DM_LENS_LSP_DIAGNOSTICS_WAIT_MS", 1e4);
109
+ const PULL_DIAGNOSTICS_RETRY_INTERVAL_MS = positiveIntFromEnv("DM_LENS_LSP_PULL_RETRY_INTERVAL_MS", 250);
110
+ const PULL_REQUEST_TIMEOUT_MS = positiveIntFromEnv("DM_LENS_LSP_PULL_REQUEST_TIMEOUT_MS", 1e4);
111
+ const PULL_MIN_USABLE_BUDGET_MS = 5;
112
+ const SHUTDOWN_REQUEST_TIMEOUT_MS = positiveIntFromEnv("DM_LENS_LSP_SHUTDOWN_TIMEOUT_MS", 1000);
113
+ const EXIT_NOTIFY_TIMEOUT_MS = positiveIntFromEnv("DM_LENS_LSP_EXIT_NOTIFY_TIMEOUT_MS", 1000);
114
+ const LIVENESS_PING_TIMEOUT_MS = positiveIntFromEnv("DM_LENS_LSP_LIVENESS_PING_TIMEOUT_MS", 300);
115
+ const LIVENESS_PING_QUERY = "__dm_lens_liveness_ping__";
116
+ const WORKSPACE_PULL_RESULT_CACHE_MAX = 4096;
117
+ const WORKSPACE_PULL_SCOPE = "*workspace*";
118
+ const REFRESH_REPULL_CONCURRENCY = 4;
119
+ const EXECUTE_COMMAND_TIMEOUT_MS = positiveIntFromEnv("DM_LENS_LSP_EXECUTE_COMMAND_TIMEOUT_MS", 30000);
120
+ const PROBE_COMMAND_TIMEOUT_MS = positiveIntFromEnv("DM_LENS_LSP_PROJECT_IDENTITY_PROBE_TIMEOUT_MS", 2500);
121
+ const LSP_CRASH_CODES = new Set([
122
+ "ERR_STREAM_DESTROYED",
123
+ "ERR_STREAM_WRITE_AFTER_END",
124
+ "EPIPE",
125
+ "ECONNRESET"
126
+ ]);
127
+ let crashGuardInstalled = false;
128
+ function isIgnorableLspRuntimeCrash(err) {
129
+ if (!(err instanceof Error))
130
+ return false;
131
+ const code = err.code;
132
+ if (code && LSP_CRASH_CODES.has(code))
133
+ return true;
134
+ const msg = err.message.toLowerCase();
135
+ const stack = (err.stack ?? "").toLowerCase();
136
+ return msg.includes("stream") || msg.includes("write after end") || stack.includes("vscode-jsonrpc/lib/node/ril.js");
137
+ }
138
+ function installCrashGuard() {
139
+ if (crashGuardInstalled)
140
+ return;
141
+ crashGuardInstalled = true;
142
+ process.on("uncaughtException", (err) => {
143
+ if (isIgnorableLspRuntimeCrash(err)) {
144
+ return;
145
+ }
146
+ throw err;
147
+ });
148
+ process.on("unhandledRejection", (reason) => {
149
+ if (isIgnorableLspRuntimeCrash(reason)) {
150
+ return;
151
+ }
152
+ throw reason instanceof Error ? reason : new Error(String(reason));
153
+ });
154
+ }
155
+ export const MAX_INCREMENTAL_TEXT_RETAINED_ENTRIES = 128;
156
+ export const MAX_INCREMENTAL_TEXT_RETAINED_BYTES = 64 * 1024 * 1024;
157
+ const ACTIVE_CLIENTS_FAMILY = "lsp-client.active-clients";
158
+ const ACTIVE_CLIENTS_VERSION = 1;
159
+ function activeLspClientSet() {
160
+ return getProcessSingleton(ACTIVE_CLIENTS_FAMILY, ACTIVE_CLIENTS_VERSION, () => new Set);
161
+ }
162
+ export function getLspDocumentTextRetentionSnapshot() {
163
+ let entries = 0;
164
+ let bytes = 0;
165
+ const roots = new Set;
166
+ const active = activeLspClientSet();
167
+ for (const state of active) {
168
+ entries += state.incrementalTextRetainedEntries ?? 0;
169
+ bytes += state.incrementalTextRetainedBytes ?? 0;
170
+ if (typeof state.root === "string" && state.root.length > 0) {
171
+ roots.add(state.root);
172
+ }
173
+ }
174
+ return { clients: active.size, entries, bytes, roots: roots.size };
175
+ }
176
+ function isClientAlive(state) {
177
+ return state.isConnected && !state.isDestroyed && !state.lspProcess.process.killed;
178
+ }
179
+ function disposeClientConnection(state) {
180
+ if (state.connectionDisposed)
181
+ return;
182
+ state.connectionDisposed = true;
183
+ activeLspClientSet().delete(state);
184
+ try {
185
+ state.connection.dispose();
186
+ } catch {}
187
+ }
188
+ export async function killProcessTree(proc, pid, options = {}) {
189
+ if ((proc.exitCode != null || proc.signalCode != null) && !options.processExiting) {
190
+ releaseOwnChildPid(pid);
191
+ proc.unref?.();
192
+ return;
193
+ }
194
+ if (process.platform === "win32" && pid > 0) {
195
+ if (options.processExiting) {
196
+ try {
197
+ proc.kill();
198
+ } catch {}
199
+ proc.unref?.();
200
+ return;
201
+ }
202
+ try {
203
+ const taskkill = `${process.env.SystemRoot ?? "C:\\Windows"}\\System32\\taskkill.exe`;
204
+ const killer = nodeSpawn(taskkill, ["/F", "/T", "/PID", String(pid)], {
205
+ shell: false,
206
+ windowsHide: true,
207
+ stdio: "ignore",
208
+ detached: !!options.fast
209
+ });
210
+ if (options.fast) {
211
+ killer.unref();
212
+ proc.unref?.();
213
+ return;
214
+ }
215
+ await new Promise((resolve) => {
216
+ killer.once("close", () => resolve());
217
+ killer.once("error", (err) => {
218
+ logLatency({
219
+ type: "phase",
220
+ phase: "lsp_kill_escalation",
221
+ filePath: "",
222
+ durationMs: 0,
223
+ metadata: { pid, platform: "win32", taskkillError: String(err) }
224
+ });
225
+ resolve();
226
+ });
227
+ });
228
+ } catch (err) {
229
+ logLatency({
230
+ type: "phase",
231
+ phase: "lsp_kill_escalation",
232
+ filePath: "",
233
+ durationMs: 0,
234
+ metadata: { pid, platform: "win32", taskkillSpawnError: String(err) }
235
+ });
236
+ }
237
+ return;
238
+ }
239
+ const killPosixProcessGroup = (signal) => {
240
+ if (!isOwnLiveChild(pid, "lsp-stop-posix-group"))
241
+ return false;
242
+ try {
243
+ process.kill(-pid, signal);
244
+ return true;
245
+ } catch {
246
+ return false;
247
+ }
248
+ };
249
+ const killDirectChild = (signal) => {
250
+ try {
251
+ proc.kill(signal);
252
+ } catch {}
253
+ };
254
+ try {
255
+ let exited = proc.exitCode != null || proc.signalCode != null;
256
+ proc.once?.("exit", () => {
257
+ exited = true;
258
+ });
259
+ if (!killPosixProcessGroup("SIGTERM")) {
260
+ killDirectChild("SIGTERM");
261
+ }
262
+ if (options.fast) {
263
+ const timer = setTimeout(() => {
264
+ if (!exited) {
265
+ logLatency({
266
+ type: "phase",
267
+ phase: "lsp_kill_escalation",
268
+ filePath: "",
269
+ durationMs: 1500,
270
+ metadata: { pid, platform: "posix", method: "SIGKILL", fast: true }
271
+ });
272
+ if (!killPosixProcessGroup("SIGKILL")) {
273
+ killDirectChild("SIGKILL");
274
+ }
275
+ }
276
+ releaseOwnChildPid(pid);
277
+ }, 1500);
278
+ timer.unref?.();
279
+ proc.unref?.();
280
+ return;
281
+ }
282
+ const exitedInTime = await new Promise((resolve) => {
283
+ if (proc.exitCode != null || proc.signalCode != null) {
284
+ resolve(true);
285
+ return;
286
+ }
287
+ const onExit = () => {
288
+ clearTimeout(timer);
289
+ resolve(true);
290
+ };
291
+ const timer = setTimeout(() => {
292
+ proc.off?.("exit", onExit);
293
+ resolve(false);
294
+ }, 1500);
295
+ proc.once?.("exit", onExit);
296
+ });
297
+ if (!exitedInTime && !exited) {
298
+ logLatency({
299
+ type: "phase",
300
+ phase: "lsp_kill_escalation",
301
+ filePath: "",
302
+ durationMs: 1500,
303
+ metadata: { pid, platform: "posix", method: "SIGKILL", fast: false }
304
+ });
305
+ if (!killPosixProcessGroup("SIGKILL")) {
306
+ killDirectChild("SIGKILL");
307
+ }
308
+ }
309
+ releaseOwnChildPid(pid);
310
+ } catch {}
311
+ }
312
+ export function stripDiagnosticNoiseLines(message) {
313
+ const cleaned = message.split(/\r?\n/).filter((line) => {
314
+ const trimmed = line.trim();
315
+ if (/^for further information visit\b/i.test(trimmed))
316
+ return false;
317
+ if (/^https?:\/\/\S+$/i.test(trimmed))
318
+ return false;
319
+ return true;
320
+ }).join(`
321
+ `).trim();
322
+ return cleaned || message.trim() || message;
323
+ }
324
+ function normalizeLspDiagnostic(diagnostic) {
325
+ const message = stripDiagnosticNoiseLines(diagnostic.message);
326
+ return message === diagnostic.message ? diagnostic : { ...diagnostic, message };
327
+ }
328
+ function normalizeLspDiagnostics(diagnostics) {
329
+ return diagnostics.map(normalizeLspDiagnostic);
330
+ }
331
+ function mergeDiagnosticLists(...lists) {
332
+ const merged = [];
333
+ const seen = new Set;
334
+ for (const diagnostic of lists.flatMap((list) => list ?? [])) {
335
+ const key = [
336
+ diagnostic.range.start.line,
337
+ diagnostic.range.start.character,
338
+ diagnostic.range.end.line,
339
+ diagnostic.range.end.character,
340
+ diagnostic.code ?? "",
341
+ diagnostic.source ?? "",
342
+ diagnostic.message
343
+ ].join(":");
344
+ if (seen.has(key))
345
+ continue;
346
+ seen.add(key);
347
+ merged.push(diagnostic);
348
+ }
349
+ return merged;
350
+ }
351
+ function getMergedDiagnosticsForPath(state, normalizedPath) {
352
+ const legacy = state;
353
+ return mergeDiagnosticLists(state.pushDiagnostics?.get(normalizedPath) ?? legacy.diagnostics?.get(normalizedPath), state.documentPullDiagnostics?.get(normalizedPath));
354
+ }
355
+ const PULL_SOURCE_KEY_SEPARATOR = "\x00";
356
+ const BARE_PULL_SOURCE = "";
357
+ function pullSourceKey(normalizedPath, identifier) {
358
+ return identifier === undefined ? normalizedPath : `${normalizedPath}${PULL_SOURCE_KEY_SEPARATOR}${identifier}`;
359
+ }
360
+ function pullSourceKeysForPath(state, normalizedPath) {
361
+ const prefix = `${normalizedPath}${PULL_SOURCE_KEY_SEPARATOR}`;
362
+ return [
363
+ normalizedPath,
364
+ ...[...state.pullResultIds?.keys() ?? []].filter((key) => key.startsWith(prefix))
365
+ ];
366
+ }
367
+ function pullSourcesFor(state, normalizedPath) {
368
+ if (!state.documentPullDiagnosticsBySource) {
369
+ state.documentPullDiagnosticsBySource = new Map;
370
+ }
371
+ let sources = state.documentPullDiagnosticsBySource.get(normalizedPath);
372
+ if (!sources) {
373
+ sources = new Map;
374
+ state.documentPullDiagnosticsBySource.set(normalizedPath, sources);
375
+ }
376
+ return sources;
377
+ }
378
+ function pullSourceDiagnostics(state, normalizedPath, identifier) {
379
+ const sources = state.documentPullDiagnosticsBySource?.get(normalizedPath);
380
+ const stored = sources?.get(identifier ?? BARE_PULL_SOURCE);
381
+ if (stored)
382
+ return stored;
383
+ return sources && sources.size > 0 ? [] : state.documentPullDiagnostics.get(normalizedPath) ?? [];
384
+ }
385
+ function storePullSourceDiagnostics(state, normalizedPath, identifier, diagnostics) {
386
+ const sources = pullSourcesFor(state, normalizedPath);
387
+ sources.set(identifier ?? BARE_PULL_SOURCE, diagnostics);
388
+ state.documentPullDiagnostics.set(normalizedPath, mergeDiagnosticLists(...sources.values()));
389
+ }
390
+ function pullGenerationFor(state, normalizedPath) {
391
+ return state.pullGenerations?.get(normalizedPath) ?? 0;
392
+ }
393
+ function bumpPullGeneration(state, normalizedPath) {
394
+ if (!state.pullGenerations)
395
+ state.pullGenerations = new Map;
396
+ state.pullGenerations.set(normalizedPath, (state.pullGenerations.get(normalizedPath) ?? 0) + 1);
397
+ }
398
+ function claimPullRequestSequence(state, sourceKey) {
399
+ if (!state.pullRequestSequences)
400
+ state.pullRequestSequences = new Map;
401
+ const next = (state.pullRequestSequences.get(sourceKey) ?? 0) + 1;
402
+ state.pullRequestSequences.set(sourceKey, next);
403
+ return next;
404
+ }
405
+ function isNewestPullRequest(state, sourceKey, sequence) {
406
+ return (state.pullRequestSequences?.get(sourceKey) ?? 0) === sequence;
407
+ }
408
+ function retirePullSource(state, identifier) {
409
+ const suffix = `${PULL_SOURCE_KEY_SEPARATOR}${identifier}`;
410
+ for (const source of [state.pullResultIds, state.pullRequestSequences]) {
411
+ if (!source)
412
+ continue;
413
+ for (const key of source.keys()) {
414
+ if (key.endsWith(suffix))
415
+ source.delete(key);
416
+ }
417
+ }
418
+ for (const [normalizedPath, sources] of state.documentPullDiagnosticsBySource ?? []) {
419
+ if (!sources.delete(identifier))
420
+ continue;
421
+ state.documentPullDiagnostics.set(normalizedPath, mergeDiagnosticLists(...sources.values()));
422
+ bumpDiagnosticsVersion(state, normalizedPath);
423
+ state.diagnosticEmitter.emit("diagnostics", normalizedPath);
424
+ }
425
+ }
426
+ export function pullDiagnosticSources(state) {
427
+ const identifiers = new Set;
428
+ for (const registration of state.dynamicRegistrations?.values() ?? []) {
429
+ if (registration.method !== "textDocument/diagnostic")
430
+ continue;
431
+ if (registration.identifier)
432
+ identifiers.add(registration.identifier);
433
+ }
434
+ return [undefined, ...[...identifiers].sort((a, b) => a.localeCompare(b))];
435
+ }
436
+ export function bumpDiagnosticsVersion(state, normalizedPath) {
437
+ state.diagnosticsVersion += 1;
438
+ state.diagnosticsVersionsByPath?.set(normalizedPath, state.diagnosticsVersion);
439
+ countPublication(state, normalizedPath);
440
+ }
441
+ function countPublication(state, normalizedPath) {
442
+ const counts = state.publicationStoreCountsByPath;
443
+ if (!counts)
444
+ return;
445
+ const { sent } = publicationCountsForPath(state, normalizedPath);
446
+ if (sent === 0)
447
+ return;
448
+ counts.set(normalizedPath, Math.min((counts.get(normalizedPath) ?? 0) + 1, sent));
449
+ }
450
+ export function rebaselineForRulesRefresh(state) {
451
+ const counts = state.publicationStoreCountsByPath;
452
+ for (const [normalizedPath, published] of counts) {
453
+ counts.set(normalizedPath, published - 1);
454
+ }
455
+ for (const normalizedPath of state.pendingDiagnostics.keys()) {
456
+ if (counts.has(normalizedPath) || publicationCountsForPath(state, normalizedPath).sent === 0)
457
+ continue;
458
+ counts.set(normalizedPath, -1);
459
+ }
460
+ logLatency({
461
+ type: "phase",
462
+ phase: "lsp_rules_refreshed",
463
+ filePath: state.root,
464
+ durationMs: 0,
465
+ metadata: {
466
+ serverId: state.serverId,
467
+ rebaselinedPaths: counts.size,
468
+ heldEmptyPublishes: state.heldEmptyPublishes ?? 0
469
+ }
470
+ });
471
+ state.heldEmptyPublishes = 0;
472
+ }
473
+ export function publicationCountsForPath(state, normalizedPath) {
474
+ const lastSent = state.documentVersions.get(normalizedPath);
475
+ return {
476
+ sent: (lastSent === undefined ? 0 : lastSent + 1) + (state.expectedPublicationsBeyondSends?.get(normalizedPath) ?? 0),
477
+ published: state.publicationStoreCountsByPath?.get(normalizedPath) ?? 0
478
+ };
479
+ }
480
+ export function diagnosticsVersionForPath(state, normalizedPath) {
481
+ return state.diagnosticsVersionsByPath?.get(normalizedPath) ?? 0;
482
+ }
483
+ const PENDING_RECEIPT_DROPPED = "pending-receipt-dropped";
484
+ export function clearDiagnosticsForPath(state, normalizedPath) {
485
+ const legacy = state;
486
+ state.pushDiagnostics?.delete(normalizedPath);
487
+ const pending = state.pendingDiagnostics?.get(normalizedPath);
488
+ if (pending) {
489
+ clearTimeout(pending);
490
+ countPublication(state, normalizedPath);
491
+ }
492
+ state.pendingDiagnostics?.delete(normalizedPath);
493
+ state.pushDiagnosticTimestamps?.delete(normalizedPath);
494
+ state.documentPullDiagnostics?.delete(normalizedPath);
495
+ state.documentPullDiagnosticTimestamps?.delete(normalizedPath);
496
+ state.diagnosticDocVersions?.delete(normalizedPath);
497
+ state.nonEmptyAnswerPhases?.delete(normalizedPath);
498
+ state.diagnosticBindings?.delete(normalizedPath);
499
+ state.diagnosticsVersionsByPath?.delete(normalizedPath);
500
+ for (const key of pullSourceKeysForPath(state, normalizedPath)) {
501
+ state.pullResultIds?.delete(key);
502
+ }
503
+ state.documentPullDiagnosticsBySource?.delete(normalizedPath);
504
+ bumpPullGeneration(state, normalizedPath);
505
+ state.workspacePullResultCache?.delete(normalizedPath);
506
+ legacy.diagnostics?.delete(normalizedPath);
507
+ legacy.diagnosticTimestamps?.delete(normalizedPath);
508
+ }
509
+ function logTypeScriptPullSettle(state, normalizedPath, durationMs, pullSettleSource) {
510
+ if (state.serverId !== "typescript")
511
+ return;
512
+ const diagnostics = state.documentPullDiagnostics.get(normalizedPath) ?? [];
513
+ const elapsedSinceDidOpenMs = Math.max(0, Date.now() - (state.documentOpenedAt.get(normalizedPath) ?? Date.now()));
514
+ const diagnosticCodes = [
515
+ ...new Set(diagnostics.map((diagnostic) => diagnostic.code).filter((code) => code !== undefined).map(String))
516
+ ].slice(0, 8);
517
+ const trackedVersion = state.diagnosticsVersionsByPath?.get(normalizedPath);
518
+ logLatency({
519
+ type: "phase",
520
+ phase: "lsp_typescript_diagnostic_sequence",
521
+ filePath: normalizedPath,
522
+ durationMs,
523
+ metadata: {
524
+ serverId: state.serverId,
525
+ outcome: "settled",
526
+ launchVariant: state.launchVariant ?? "unknown",
527
+ publicationIndex: state.diagnosticPublicationCounts.get(normalizedPath) ?? 0,
528
+ version: trackedVersion ?? "pull-unversioned",
529
+ diagnosticCount: diagnostics.length,
530
+ diagnosticCodes,
531
+ elapsedSinceDidOpenMs,
532
+ settledReturn: true,
533
+ settleSource: pullSettleSource
534
+ }
535
+ });
536
+ }
537
+ function recordSentContent(state, normalizedPath, version, content, coalescedCount = 0, contentHash) {
538
+ const scan = scanDocumentContent(content);
539
+ const previous = state.documentContentHashes.get(normalizedPath);
540
+ if (previous && previous.version > version) {
541
+ incrementDegradationCount({
542
+ kind: "lsp-document-send-order",
543
+ subject: `${state.serverId}:${normalizedPath}`,
544
+ reason: `recorded version ${version} after newer version ${previous.version}`
545
+ });
546
+ return;
547
+ }
548
+ if (previous?.text !== undefined) {
549
+ state.incrementalTextRetainedEntries = Math.max(0, (state.incrementalTextRetainedEntries ?? 1) - 1);
550
+ state.incrementalTextRetainedBytes = Math.max(0, (state.incrementalTextRetainedBytes ?? previous.text.length * 2) - previous.text.length * 2);
551
+ state.incrementalTextBearingPaths?.delete(normalizedPath);
552
+ }
553
+ state.documentContentHashes.delete(normalizedPath);
554
+ const hash = contentHash ?? hashDiagnosticContent(content);
555
+ state.documentContentHashes.set(normalizedPath, {
556
+ version,
557
+ hash,
558
+ savedHash: previous?.savedHash,
559
+ changedAtMs: previous?.hash === hash ? previous.changedAtMs : Date.now(),
560
+ openedAtMs: previous?.openedAtMs ?? Date.now(),
561
+ openedHash: previous === undefined ? hash : previous.openedHash,
562
+ ...state.syncKind === TEXT_DOCUMENT_SYNC_KIND_INCREMENTAL && {
563
+ text: content,
564
+ lastLine: scan.lastLine
565
+ }
566
+ });
567
+ if (state.syncKind === TEXT_DOCUMENT_SYNC_KIND_INCREMENTAL) {
568
+ state.incrementalTextRetainedEntries = (state.incrementalTextRetainedEntries ?? 0) + 1;
569
+ state.incrementalTextRetainedBytes = (state.incrementalTextRetainedBytes ?? 0) + content.length * 2;
570
+ if (!state.incrementalTextBearingPaths) {
571
+ state.incrementalTextBearingPaths = new Set;
572
+ }
573
+ state.incrementalTextBearingPaths.add(normalizedPath);
574
+ while ((state.incrementalTextRetainedEntries ?? 0) > MAX_INCREMENTAL_TEXT_RETAINED_ENTRIES || (state.incrementalTextRetainedBytes ?? 0) > MAX_INCREMENTAL_TEXT_RETAINED_BYTES) {
575
+ const oldestPath = state.incrementalTextBearingPaths?.values().next().value;
576
+ if (oldestPath === undefined)
577
+ break;
578
+ const binding = state.documentContentHashes.get(oldestPath);
579
+ state.incrementalTextBearingPaths.delete(oldestPath);
580
+ if (!binding || binding.text === undefined)
581
+ continue;
582
+ state.documentContentHashes.set(oldestPath, {
583
+ version: binding.version,
584
+ hash: binding.hash,
585
+ savedHash: binding.savedHash,
586
+ changedAtMs: binding.changedAtMs,
587
+ openedAtMs: binding.openedAtMs,
588
+ openedHash: binding.openedHash
589
+ });
590
+ state.incrementalTextRetainedEntries = Math.max(0, (state.incrementalTextRetainedEntries ?? 1) - 1);
591
+ state.incrementalTextRetainedBytes = Math.max(0, (state.incrementalTextRetainedBytes ?? 0) - binding.text.length * 2);
592
+ }
593
+ }
594
+ logLatency({
595
+ type: "phase",
596
+ phase: "lsp_document_send",
597
+ filePath: normalizedPath,
598
+ durationMs: 0,
599
+ metadata: {
600
+ version,
601
+ contentLength: content.length,
602
+ contentLineCount: scan.lfNewlineCount + 1,
603
+ ...coalescedCount > 0 && { coalescedCount }
604
+ }
605
+ });
606
+ }
607
+ function buildContentChanges(state, normalizedPath, content) {
608
+ if (state.syncKind !== TEXT_DOCUMENT_SYNC_KIND_INCREMENTAL) {
609
+ return [{ text: content }];
610
+ }
611
+ const previous = state.documentContentHashes.get(normalizedPath);
612
+ if (previous?.text === undefined) {
613
+ return [{ text: content }];
614
+ }
615
+ const previousText = previous.text;
616
+ const lastLine = previous.lastLine ?? scanDocumentContent(previousText).lastLine;
617
+ const lastLineText = previousText.slice(lastLine.start);
618
+ return [
619
+ {
620
+ range: {
621
+ start: { line: 0, character: 0 },
622
+ end: {
623
+ line: lastLine.index,
624
+ character: convertCharacterOffset(state.positionEncoding, lastLineText, lastLineText.length)
625
+ }
626
+ },
627
+ text: content
628
+ }
629
+ ];
630
+ }
631
+ const DYNAMIC_OPERATION_METHOD_MAP = {
632
+ "textDocument/definition": "definition",
633
+ "textDocument/typeDefinition": "typeDefinition",
634
+ "textDocument/declaration": "declaration",
635
+ "textDocument/references": "references",
636
+ "textDocument/hover": "hover",
637
+ "textDocument/signatureHelp": "signatureHelp",
638
+ "textDocument/documentSymbol": "documentSymbol",
639
+ "workspace/symbol": "workspaceSymbol",
640
+ "textDocument/codeAction": "codeAction",
641
+ "textDocument/rename": "rename",
642
+ "textDocument/implementation": "implementation",
643
+ "textDocument/prepareCallHierarchy": "callHierarchy"
644
+ };
645
+ export function applyDynamicCapabilities(state) {
646
+ const registrations = [...state.dynamicRegistrations.values()];
647
+ const registeredMethods = new Set(registrations.map((r) => r.method));
648
+ const hasDynamicPull = registeredMethods.has("textDocument/diagnostic") || registeredMethods.has("workspace/diagnostic");
649
+ if (hasDynamicPull) {
650
+ state.workspaceDiagnosticsSupport = {
651
+ advertised: true,
652
+ mode: "pull",
653
+ workspaceDiagnostics: registrations.some((r) => r.workspaceDiagnostics === true) || registeredMethods.has("workspace/diagnostic"),
654
+ diagnosticProviderKind: "dynamic"
655
+ };
656
+ } else if (state.staticDiagnosticsMode === "push-only" && state.workspaceDiagnosticsSupport.diagnosticProviderKind === "dynamic") {
657
+ state.workspaceDiagnosticsSupport = {
658
+ advertised: false,
659
+ mode: "push-only",
660
+ workspaceDiagnostics: false,
661
+ diagnosticProviderKind: "none"
662
+ };
663
+ }
664
+ for (const [method, key] of Object.entries(DYNAMIC_OPERATION_METHOD_MAP)) {
665
+ if (registeredMethods.has(method)) {
666
+ state.operationSupport[key] = true;
667
+ }
668
+ }
669
+ }
670
+ export function resolveConfigurationSection(initialization, section) {
671
+ if (!initialization)
672
+ return {};
673
+ if (!section)
674
+ return initialization;
675
+ let cur = initialization;
676
+ for (const part of section.split(".")) {
677
+ if (typeof cur !== "object" || cur === null || !Object.hasOwn(cur, part)) {
678
+ return {};
679
+ }
680
+ cur = cur[part];
681
+ }
682
+ return cur;
683
+ }
684
+ export const MAX_TRACKED_SERVER_MESSAGES = 8;
685
+ export function isConfigLoadFailureMessage(message) {
686
+ return /\b(?:fail|failed|fails|failure|unable|could not|error)\b/i.test(message) && /\b(?:download|load|fetch|resolve|read|parse)\b/i.test(message) && /\b(?:config|configuration|rules?|ruleset)\b/i.test(message);
687
+ }
688
+ export function noteServerShowMessage(state, params) {
689
+ const raw = typeof params?.message === "string" ? params.message.trim() : "";
690
+ if (!raw)
691
+ return;
692
+ const text = truncateForLedger(raw.replace(/\s+/g, " "));
693
+ const type = typeof params?.type === "number" ? params.type : 4;
694
+ const digest = hashDiagnosticContent(raw).slice(0, 12);
695
+ const isConfigFailure = type === 1 && isConfigLoadFailureMessage(raw);
696
+ let retractedPaths = 0;
697
+ if (isConfigFailure && state.configLoadFailure === undefined && isAuxiliary({ role: state.serverRole })) {
698
+ state.configLoadFailure = { message: text, atMs: Date.now() };
699
+ retractedPaths = retractUnscannedEmptyPublications(state);
700
+ }
701
+ const messages = state.serverMessages ??= new Map;
702
+ const known = messages.has(digest);
703
+ const cap = MAX_TRACKED_SERVER_MESSAGES + (isConfigFailure ? 1 : 0);
704
+ if (!known && messages.size >= cap) {
705
+ incrementDegradationCount({
706
+ kind: "lsp-server-message",
707
+ subject: `${state.serverId}:showMessage-cap`,
708
+ reason: `${type}: distinct showMessage texts reached ${MAX_TRACKED_SERVER_MESSAGES}; later ones are counted, not recorded`
709
+ });
710
+ return;
711
+ }
712
+ messages.set(digest, (messages.get(digest) ?? 0) + 1);
713
+ emitBounded("lsp_server_message", `${state.serverId}:message:${digest}`, {
714
+ filePath: state.root,
715
+ durationMs: 0,
716
+ metadata: {
717
+ serverId: state.serverId,
718
+ messageType: type,
719
+ message: text,
720
+ ...isConfigFailure && { configLoadFailure: true },
721
+ ...retractedPaths > 0 && { retractedPaths }
722
+ }
723
+ }, {
724
+ ledgerKind: isConfigFailure ? "lsp-server-config-load-failed" : "lsp-server-message",
725
+ reason: text,
726
+ risingEdgePer: "identity"
727
+ });
728
+ }
729
+ function answerPhase(state, filePath) {
730
+ return `${state.rulesGeneration ?? 0}:${state.documentVersions.get(filePath) ?? -1}`;
731
+ }
732
+ function auxiliaryEmptyIsNotEvidence(state, filePath, docVersion) {
733
+ const failure = state.configLoadFailure;
734
+ if (failure === undefined) {
735
+ if (docVersion !== undefined)
736
+ return false;
737
+ const phase = answerPhase(state, filePath);
738
+ if (state.nonEmptyAnswerPhases?.get(filePath) !== phase)
739
+ return false;
740
+ countPublication(state, filePath);
741
+ emitBounded("lsp_publish_dropped_empty_after_finding", `${state.serverId}:empty-after-finding:${filePath}`, {
742
+ filePath,
743
+ durationMs: 0,
744
+ metadata: { serverId: state.serverId, phase }
745
+ }, {
746
+ ledgerKind: "lsp-auxiliary-empty-after-finding",
747
+ reason: "empty publish dropped: a finding from the same rules generation and send stands",
748
+ risingEdgePer: "identity"
749
+ });
750
+ return true;
751
+ }
752
+ countPublication(state, filePath);
753
+ emitBounded("lsp_publish_dropped_server_config_failed", `${state.serverId}:dropped:${filePath}`, {
754
+ filePath,
755
+ durationMs: 0,
756
+ metadata: {
757
+ serverId: state.serverId,
758
+ via: "publish",
759
+ message: failure.message
760
+ }
761
+ }, {
762
+ ledgerKind: "lsp-server-config-load-failed",
763
+ reason: `empty publish dropped: ${failure.message}`,
764
+ risingEdgePer: "identity"
765
+ });
766
+ return true;
767
+ }
768
+ function retractUnscannedEmptyPublications(state) {
769
+ let retracted = 0;
770
+ const emptyStoredPaths = [];
771
+ for (const [normalizedPath, diags] of state.pushDiagnostics) {
772
+ if (diags.length === 0)
773
+ emptyStoredPaths.push(normalizedPath);
774
+ }
775
+ for (const normalizedPath of emptyStoredPaths) {
776
+ state.pushDiagnostics.delete(normalizedPath);
777
+ state.pushDiagnosticTimestamps.delete(normalizedPath);
778
+ state.diagnosticDocVersions.delete(normalizedPath);
779
+ state.diagnosticBindings.delete(normalizedPath);
780
+ state.diagnosticsVersionsByPath.delete(normalizedPath);
781
+ retracted += 1;
782
+ emitBounded("lsp_publish_dropped_server_config_failed", `${state.serverId}:dropped:${normalizedPath}`, {
783
+ filePath: normalizedPath,
784
+ durationMs: 0,
785
+ metadata: {
786
+ serverId: state.serverId,
787
+ via: "retracted",
788
+ message: state.configLoadFailure?.message ?? ""
789
+ }
790
+ }, {
791
+ ledgerKind: "lsp-server-config-load-failed",
792
+ reason: `stored empty answer retracted: ${state.configLoadFailure?.message ?? ""}`,
793
+ risingEdgePer: "identity"
794
+ });
795
+ }
796
+ return retracted;
797
+ }
798
+ export function setupIncomingHandlers(state, initialization, onDiagnosticsPublished) {
799
+ state.connection.onNotification("textDocument/publishDiagnostics", (params) => {
800
+ const publishReceivedAt = Date.now();
801
+ const filePath = uriToPath(params.uri);
802
+ const normalizedPath = normalizeMapKey(filePath);
803
+ const docVersion = params.version;
804
+ if (docVersion === undefined && getStrategy(state.serverId, state.launchVariant).publishesOnClose) {
805
+ return;
806
+ }
807
+ if (state.closedDocuments?.has(normalizedPath)) {
808
+ countPublication(state, normalizedPath);
809
+ return;
810
+ }
811
+ const newDiags = normalizeLspDiagnostics(params.diagnostics || []);
812
+ if (newDiags.length === 0 && auxiliaryEmptyIsNotEvidence(state, normalizedPath, docVersion)) {
813
+ return;
814
+ }
815
+ onDiagnosticsPublished?.(state.serverId);
816
+ const fence = state.diagnosticFences.get(normalizedPath);
817
+ if (docVersion === undefined && fence) {
818
+ fence.dropped += 1;
819
+ countPublication(state, normalizedPath);
820
+ if (getStrategy(state.serverId, state.launchVariant).emptyFirstPublish === "indexing" && !state.emptyFirstPublishHoldSpent && newDiags.length === 0 && !state.pushDiagnostics.has(normalizedPath) && !state.pendingDiagnostics.has(normalizedPath)) {
821
+ state.emptyFirstPublishHoldSpent = true;
822
+ logLatency({
823
+ type: "phase",
824
+ phase: "lsp_empty_first_publish_held",
825
+ filePath: normalizedPath,
826
+ durationMs: Math.max(0, publishReceivedAt - (state.documentOpenedAt.get(normalizedPath) ?? publishReceivedAt)),
827
+ metadata: {
828
+ serverId: state.serverId,
829
+ emptyFirstPublish: "indexing",
830
+ via: "fence-drop",
831
+ pubVersion: "push-unversioned"
832
+ }
833
+ });
834
+ }
835
+ return;
836
+ }
837
+ if (PUB_DEBUG) {
838
+ logExtension({
839
+ subsystem: "lsp-pub",
840
+ level: "debug",
841
+ message: `server=${state.serverId} pubVersion=${docVersion} docVersion=${state.documentVersions?.get(normalizedPath)} diags=${newDiags.length}`,
842
+ metadata: { path: normalizedPath }
843
+ });
844
+ }
845
+ const strategy = getStrategy(state.serverId, state.launchVariant);
846
+ const isTypeScriptTelemetry = state.serverId === "typescript";
847
+ const publicationIndex = isTypeScriptTelemetry ? (state.diagnosticPublicationCounts.get(normalizedPath) ?? 0) + 1 : 0;
848
+ if (isTypeScriptTelemetry) {
849
+ state.diagnosticPublicationCounts.set(normalizedPath, publicationIndex);
850
+ }
851
+ const diagnosticCodes = isTypeScriptTelemetry ? [
852
+ ...new Set(newDiags.map((diagnostic) => diagnostic.code).filter((code) => code !== undefined).map(String))
853
+ ].slice(0, 8) : [];
854
+ const logSequence = (settledReturn, settleSource, durationMs) => {
855
+ if (state.serverId !== "typescript")
856
+ return;
857
+ const elapsedSinceDidOpenMs = Math.max(0, Date.now() - (state.documentOpenedAt.get(normalizedPath) ?? Date.now()));
858
+ logLatency({
859
+ type: "phase",
860
+ phase: "lsp_typescript_diagnostic_sequence",
861
+ filePath: normalizedPath,
862
+ durationMs,
863
+ metadata: {
864
+ serverId: state.serverId,
865
+ outcome: settledReturn ? "settled" : "published",
866
+ launchVariant: state.launchVariant ?? "unknown",
867
+ publicationIndex,
868
+ version: docVersion ?? "push-unversioned",
869
+ diagnosticCount: newDiags.length,
870
+ diagnosticCodes,
871
+ elapsedSinceDidOpenMs,
872
+ settledReturn,
873
+ settleSource
874
+ }
875
+ });
876
+ };
877
+ const recordDocVersion = () => {
878
+ if (docVersion !== undefined) {
879
+ state.diagnosticDocVersions.set(normalizedPath, docVersion);
880
+ }
881
+ recordBinding();
882
+ };
883
+ const recordBinding = () => {
884
+ if (docVersion === undefined) {
885
+ state.diagnosticBindings.delete(normalizedPath);
886
+ return;
887
+ }
888
+ const sent = state.documentContentHashes.get(normalizedPath);
889
+ state.diagnosticBindings.set(normalizedPath, {
890
+ version: docVersion,
891
+ contentHash: sent && sent.version === docVersion ? sent.hash : undefined
892
+ });
893
+ };
894
+ const isSupersededPush = () => {
895
+ if (docVersion === undefined)
896
+ return false;
897
+ const currentVersion = state.documentVersions.get(normalizedPath);
898
+ return currentVersion !== undefined && docVersion < currentVersion;
899
+ };
900
+ if (strategy.emptyUntilRulesRefreshed && !state.rulesGeneration && newDiags.length === 0 && !state.pushDiagnostics.has(normalizedPath) && !state.pendingDiagnostics.has(normalizedPath)) {
901
+ state.heldEmptyPublishes = (state.heldEmptyPublishes ?? 0) + 1;
902
+ countPublication(state, normalizedPath);
903
+ return;
904
+ }
905
+ if (strategy.emptyFirstPublish === "indexing" && !state.emptyFirstPublishHoldSpent && newDiags.length === 0 && !state.pushDiagnostics.has(normalizedPath) && !state.pendingDiagnostics.has(normalizedPath)) {
906
+ state.emptyFirstPublishHoldSpent = true;
907
+ logLatency({
908
+ type: "phase",
909
+ phase: "lsp_empty_first_publish_held",
910
+ filePath: normalizedPath,
911
+ durationMs: Math.max(0, publishReceivedAt - (state.documentOpenedAt.get(normalizedPath) ?? publishReceivedAt)),
912
+ metadata: {
913
+ serverId: state.serverId,
914
+ emptyFirstPublish: strategy.emptyFirstPublish,
915
+ pubVersion: docVersion ?? "push-unversioned"
916
+ }
917
+ });
918
+ return;
919
+ }
920
+ if (newDiags.length > 0 && isAuxiliary({ role: state.serverRole })) {
921
+ (state.nonEmptyAnswerPhases ??= new Map).set(normalizedPath, answerPhase(state, normalizedPath));
922
+ }
923
+ if (strategy.seedFirstPush && !state.pushDiagnostics.has(normalizedPath)) {
924
+ if (isSupersededPush()) {
925
+ countPublication(state, normalizedPath);
926
+ return;
927
+ }
928
+ const olderTimer = state.pendingDiagnostics.get(normalizedPath);
929
+ if (olderTimer) {
930
+ clearTimeout(olderTimer);
931
+ state.pendingDiagnostics.delete(normalizedPath);
932
+ countPublication(state, normalizedPath);
933
+ }
934
+ state.pushDiagnostics.set(normalizedPath, newDiags);
935
+ state.pushDiagnosticTimestamps.set(normalizedPath, Date.now());
936
+ recordDocVersion();
937
+ bumpDiagnosticsVersion(state, normalizedPath);
938
+ state.diagnosticEmitter.emit("diagnostics", normalizedPath);
939
+ logSequence(true, "first-push", 0);
940
+ return;
941
+ }
942
+ logSequence(false, "publication", 0);
943
+ const existingTimer = state.pendingDiagnostics.get(normalizedPath);
944
+ if (existingTimer) {
945
+ clearTimeout(existingTimer);
946
+ countPublication(state, normalizedPath);
947
+ }
948
+ const timer = setTimeout(() => {
949
+ state.pendingDiagnostics.delete(normalizedPath);
950
+ if (isSupersededPush()) {
951
+ countPublication(state, normalizedPath);
952
+ state.diagnosticEmitter.emit(PENDING_RECEIPT_DROPPED, normalizedPath);
953
+ return;
954
+ }
955
+ if (newDiags.length === 0 && auxiliaryEmptyIsNotEvidence(state, normalizedPath, docVersion)) {
956
+ state.diagnosticEmitter.emit(PENDING_RECEIPT_DROPPED, normalizedPath);
957
+ return;
958
+ }
959
+ state.pushDiagnostics.set(normalizedPath, newDiags);
960
+ state.pushDiagnosticTimestamps.set(normalizedPath, Date.now());
961
+ recordDocVersion();
962
+ bumpDiagnosticsVersion(state, normalizedPath);
963
+ state.diagnosticEmitter.emit("diagnostics", normalizedPath);
964
+ logSequence(true, "quiet-window", Date.now() - publishReceivedAt);
965
+ }, strategy.debounceMs);
966
+ state.pendingDiagnostics.set(normalizedPath, timer);
967
+ });
968
+ state.connection.onRequest("workspace/workspaceFolders", () => [
969
+ { name: "workspace", uri: pathToFileURL(state.root).href }
970
+ ]);
971
+ state.connection.onRequest("client/registerCapability", async (params) => {
972
+ for (const reg of params?.registrations ?? []) {
973
+ const options = reg.registerOptions;
974
+ const commands = Array.isArray(options?.commands) ? options.commands.filter((cmd) => typeof cmd === "string") : undefined;
975
+ if (reg.id && reg.method) {
976
+ state.dynamicRegistrations.set(reg.id, {
977
+ method: reg.method,
978
+ ...typeof options?.identifier === "string" && options.identifier ? { identifier: options.identifier } : {},
979
+ ...typeof options?.workspaceDiagnostics === "boolean" ? { workspaceDiagnostics: options.workspaceDiagnostics } : {},
980
+ ...commands ? { commands } : {}
981
+ });
982
+ }
983
+ if (reg.method === "workspace/executeCommand" && commands) {
984
+ for (const cmd of commands)
985
+ state.advertisedCommands.add(cmd);
986
+ }
987
+ }
988
+ applyDynamicCapabilities(state);
989
+ });
990
+ state.connection.onRequest("client/unregisterCapability", async (params) => {
991
+ const retiredIdentifiers = new Set;
992
+ for (const unreg of params?.unregisterations ?? []) {
993
+ if (!unreg.id)
994
+ continue;
995
+ const registration = state.dynamicRegistrations.get(unreg.id);
996
+ state.dynamicRegistrations.delete(unreg.id);
997
+ if (registration?.method === "textDocument/diagnostic" && registration.identifier) {
998
+ retiredIdentifiers.add(registration.identifier);
999
+ }
1000
+ }
1001
+ const stillRegistered = new Set([...state.dynamicRegistrations.values()].filter((r) => r.method === "textDocument/diagnostic").map((r) => r.identifier));
1002
+ for (const identifier of retiredIdentifiers) {
1003
+ if (!stillRegistered.has(identifier)) {
1004
+ retirePullSource(state, identifier);
1005
+ }
1006
+ }
1007
+ applyDynamicCapabilities(state);
1008
+ });
1009
+ state.connection.onRequest("workspace/applyEdit", async (params) => {
1010
+ if (state.serverEditsAllowed <= 0 || !params?.edit) {
1011
+ return { applied: false, failureReason: "edit not solicited" };
1012
+ }
1013
+ const context = state.activeMutationContext;
1014
+ const telemetryContext = context ?? {
1015
+ cwd: state.root,
1016
+ correlationId: newLspMutationCorrelationId(),
1017
+ tool: "lsp-workspace-applyEdit",
1018
+ source: "lsp-execute-command"
1019
+ };
1020
+ try {
1021
+ await applyWorkspaceEdit(params.edit, state.root, {
1022
+ positionEncoding: state.positionEncoding,
1023
+ documentVersions: state.documentVersions,
1024
+ mutationContext: telemetryContext
1025
+ });
1026
+ return { applied: true };
1027
+ } catch (err) {
1028
+ return {
1029
+ applied: false,
1030
+ failureReason: err instanceof Error ? err.message : String(err)
1031
+ };
1032
+ }
1033
+ });
1034
+ state.connection.onRequest("workspace/configuration", async (params) => {
1035
+ const items = params?.items ?? [];
1036
+ return items.map((item) => resolveConfigurationSection(initialization, item?.section));
1037
+ });
1038
+ state.connection.onRequest("window/workDoneProgress/create", async () => {});
1039
+ state.connection.onNotification("window/showMessage", (params) => {
1040
+ noteServerShowMessage(state, params);
1041
+ });
1042
+ state.connection.onNotification("semgrep/rulesRefreshed", () => {
1043
+ state.rulesGeneration = (state.rulesGeneration ?? 0) + 1;
1044
+ delete state.configLoadFailure;
1045
+ rebaselineForRulesRefresh(state);
1046
+ });
1047
+ let refreshRepullRunning = false;
1048
+ let refreshRepullRerunRequested = false;
1049
+ const runRefreshRepullPool = async () => {
1050
+ do {
1051
+ refreshRepullRerunRequested = false;
1052
+ const toRepull = state.workspaceDiagnosticsSupport.mode === "pull" ? [...state.openDocuments] : [];
1053
+ if (toRepull.length > 0) {
1054
+ try {
1055
+ await mapWithConcurrency(toRepull, REFRESH_REPULL_CONCURRENCY, async (normalizedPath) => {
1056
+ const uri = state.openDocumentUris?.get(normalizedPath);
1057
+ const filePath = uri ? uriToPath(uri) : normalizedPath;
1058
+ await clientRequestPullDiagnostics(state, filePath);
1059
+ });
1060
+ } catch (err) {
1061
+ incrementDegradationCount({
1062
+ kind: "lsp-pull-unconfirmed",
1063
+ subject: state.serverId,
1064
+ reason: `refresh re-pull threw: ${err instanceof Error ? err.message : String(err)}`
1065
+ });
1066
+ }
1067
+ }
1068
+ } while (refreshRepullRerunRequested);
1069
+ refreshRepullRunning = false;
1070
+ };
1071
+ state.connection.onRequest("workspace/diagnostic/refresh", async () => {
1072
+ state.workspacePullResultCache.clear();
1073
+ clearAllWorkspaceDiagnosticsCaches();
1074
+ clearWorkspaceDiagnosticsCacheAtAndAbove(state.root);
1075
+ for (const normalizedPath of state.openDocuments) {
1076
+ clearDiagnosticsForPath(state, normalizedPath);
1077
+ }
1078
+ if (state.workspaceDiagnosticsSupport.mode === "pull" && state.openDocuments.size > 0) {
1079
+ if (refreshRepullRunning) {
1080
+ refreshRepullRerunRequested = true;
1081
+ } else {
1082
+ refreshRepullRunning = true;
1083
+ setImmediate(() => {
1084
+ runRefreshRepullPool();
1085
+ });
1086
+ }
1087
+ }
1088
+ return null;
1089
+ });
1090
+ }
1091
+ function markExitedIfUnset(state) {
1092
+ if (state.exitedAt === undefined) {
1093
+ state.exitedAt = Date.now();
1094
+ }
1095
+ }
1096
+ function setupConnectionLifecycle(state, recentStderr) {
1097
+ state.connection.onError(([error]) => {
1098
+ state.lastError = error instanceof Error ? error : new Error(String(error));
1099
+ state.isConnected = false;
1100
+ state.isDestroyed = true;
1101
+ markExitedIfUnset(state);
1102
+ disposeClientConnection(state);
1103
+ });
1104
+ state.connection.onClose(() => {
1105
+ state.isConnected = false;
1106
+ state.isDestroyed = true;
1107
+ markExitedIfUnset(state);
1108
+ disposeClientConnection(state);
1109
+ });
1110
+ state.lspProcess.process.on("exit", (code, signal) => {
1111
+ const wasIntentional = state.shutdownRequested;
1112
+ state.isConnected = false;
1113
+ state.isDestroyed = true;
1114
+ markExitedIfUnset(state);
1115
+ disposeClientConnection(state);
1116
+ if (!wasIntentional) {
1117
+ logLatency({
1118
+ type: "phase",
1119
+ phase: "lsp_server_unexpected_exit",
1120
+ filePath: state.root,
1121
+ durationMs: 0,
1122
+ metadata: {
1123
+ serverId: state.serverId,
1124
+ pid: state.lspProcess.pid,
1125
+ exitCode: code ?? null,
1126
+ exitSignal: signal ?? null,
1127
+ stderrTail: recentStderr(20)
1128
+ }
1129
+ });
1130
+ }
1131
+ });
1132
+ state.lspProcess.process.on("close", (code, signal) => {
1133
+ if (state.shutdownRequested)
1134
+ return;
1135
+ try {
1136
+ const stderrTail = recentStderr(20);
1137
+ incrementDegradationCount({
1138
+ kind: "lsp-server-unexpected-close",
1139
+ subject: state.serverId,
1140
+ reason: `closed unprompted: code=${code ?? "none"} signal=${signal ?? "none"} ` + `stderr=${stderrTail.length > 0 ? `present(${stderrTail.length}b)` : "empty"} root=${state.root}`
1141
+ });
1142
+ } catch {}
1143
+ });
1144
+ }
1145
+ const PULL_RACE_BACKSTOP_MARGIN_MS = 25;
1146
+ async function clientRequestPullDiagnostics(state, filePath, budgetMs = PULL_REQUEST_TIMEOUT_MS) {
1147
+ if (!isClientAlive(state))
1148
+ return { status: "unavailable" };
1149
+ const sources = pullDiagnosticSources(state);
1150
+ if (sources.length === 1) {
1151
+ return aggregatePullOutcomes(state, filePath, [
1152
+ await pullDiagnosticSource(state, filePath, budgetMs, undefined)
1153
+ ]);
1154
+ }
1155
+ const attempts = sources.map((identifier) => pullDiagnosticSource(state, filePath, budgetMs, identifier));
1156
+ const settled = await raceToCompletion(attempts, (results) => results.some((r) => r.status === "found" && r.primaryCount > 0), {
1157
+ timeoutMs: Math.max(1, Math.min(PULL_REQUEST_TIMEOUT_MS, budgetMs)) + PULL_RACE_BACKSTOP_MARGIN_MS
1158
+ });
1159
+ return aggregatePullOutcomes(state, filePath, settled);
1160
+ }
1161
+ function aggregatePullOutcomes(state, filePath, outcomes) {
1162
+ const found = outcomes.filter((o) => o.status === "found");
1163
+ if (found.length > 0) {
1164
+ const normalizedPath = normalizeMapKey(filePath);
1165
+ const unionCount = state.documentPullDiagnostics.get(normalizedPath)?.length ?? 0;
1166
+ return {
1167
+ status: "found",
1168
+ count: Math.max(unionCount, ...found.map((o) => o.count))
1169
+ };
1170
+ }
1171
+ if (outcomes.some((o) => o.status === "unavailable")) {
1172
+ return { status: "unavailable" };
1173
+ }
1174
+ return outcomes.some((o) => o.status === "clean") ? { status: "clean" } : { status: "unavailable" };
1175
+ }
1176
+ async function pullDiagnosticSource(state, filePath, budgetMs, identifier) {
1177
+ if (!isClientAlive(state))
1178
+ return { status: "unavailable" };
1179
+ const normalizedPath = normalizeMapKey(filePath);
1180
+ if (budgetMs < PULL_MIN_USABLE_BUDGET_MS) {
1181
+ emitBounded("lsp_pull_skipped_budget_exhausted", `${state.serverId}::${pullSourceKey(normalizedPath, identifier)}`, {
1182
+ type: "phase",
1183
+ filePath: normalizedPath,
1184
+ durationMs: 0,
1185
+ metadata: {
1186
+ identifier: identifier ?? "bare",
1187
+ remainingBudgetMs: budgetMs,
1188
+ server: state.serverId
1189
+ }
1190
+ }, {
1191
+ ledgerKind: "lsp-pull-skipped-budget-exhausted",
1192
+ reason: `pull skipped on ${state.serverId}: budget already exhausted (${budgetMs}ms remaining)`
1193
+ });
1194
+ return { status: "unavailable" };
1195
+ }
1196
+ const uri = pathToFileURL(filePath).href;
1197
+ const sourceKey = pullSourceKey(normalizedPath, identifier);
1198
+ if (state.abandonedPullRequests?.has(sourceKey)) {
1199
+ return { status: "unavailable" };
1200
+ }
1201
+ const previousResultId = state.pullResultIds.get(sourceKey);
1202
+ const generation = pullGenerationFor(state, normalizedPath);
1203
+ const requestSequence = claimPullRequestSequence(state, sourceKey);
1204
+ const requestStartedAt = Date.now();
1205
+ const effectiveTimeoutMs = Math.max(1, Math.min(PULL_REQUEST_TIMEOUT_MS, budgetMs));
1206
+ const pullAbort = new AbortController;
1207
+ const pullSettlement = { cancelled: false };
1208
+ const requestPromise = safeSendRequest(state.connection, "textDocument/diagnostic", {
1209
+ textDocument: { uri },
1210
+ ...identifier !== undefined && { identifier },
1211
+ ...previousResultId !== undefined && { previousResultId }
1212
+ }, pullAbort.signal, pullSettlement);
1213
+ try {
1214
+ const report = await withTimeout(requestPromise, effectiveTimeoutMs);
1215
+ if (!report) {
1216
+ recordPullFailure(state, "textDocument/diagnostic", new Error("empty response"));
1217
+ return { status: "unavailable" };
1218
+ }
1219
+ const now = Date.now();
1220
+ const sentHash = state.documentContentHashes.get(normalizedPath)?.hash;
1221
+ if (pullGenerationFor(state, normalizedPath) !== generation || !isNewestPullRequest(state, sourceKey, requestSequence)) {
1222
+ return { status: "unavailable" };
1223
+ }
1224
+ let primaryCount;
1225
+ if (report.kind === "unchanged") {
1226
+ primaryCount = pullSourceDiagnostics(state, normalizedPath, identifier).length;
1227
+ state.documentPullDiagnosticTimestamps.set(normalizedPath, now);
1228
+ } else {
1229
+ const primaryItems = normalizeLspDiagnostics(report.items ?? []);
1230
+ storePullSourceDiagnostics(state, normalizedPath, identifier, primaryItems);
1231
+ state.documentPullDiagnosticTimestamps.set(normalizedPath, now);
1232
+ bumpDiagnosticsVersion(state, normalizedPath);
1233
+ state.diagnosticBindings.set(normalizedPath, { contentHash: sentHash });
1234
+ primaryCount = primaryItems.length;
1235
+ }
1236
+ let totalCount = primaryCount;
1237
+ if (report.resultId !== undefined) {
1238
+ state.pullResultIds.set(sourceKey, report.resultId);
1239
+ } else {
1240
+ state.pullResultIds.delete(sourceKey);
1241
+ }
1242
+ if (report.relatedDocuments) {
1243
+ for (const [relatedUri, related] of Object.entries(report.relatedDocuments)) {
1244
+ const relatedPath = uriToPath(relatedUri);
1245
+ const relatedNormalized = normalizeMapKey(relatedPath);
1246
+ if (related?.kind === "unchanged") {
1247
+ totalCount += pullSourceDiagnostics(state, relatedNormalized, identifier).length;
1248
+ state.documentPullDiagnosticTimestamps.set(relatedNormalized, now);
1249
+ } else {
1250
+ const relatedItems = normalizeLspDiagnostics(related?.items ?? []);
1251
+ storePullSourceDiagnostics(state, relatedNormalized, identifier, relatedItems);
1252
+ state.documentPullDiagnosticTimestamps.set(relatedNormalized, now);
1253
+ state.diagnosticBindings.delete(relatedNormalized);
1254
+ totalCount += relatedItems.length;
1255
+ }
1256
+ if (related?.resultId !== undefined) {
1257
+ state.pullResultIds.set(pullSourceKey(relatedNormalized, identifier), related.resultId);
1258
+ }
1259
+ }
1260
+ }
1261
+ state.diagnosticEmitter.emit("diagnostics", normalizedPath);
1262
+ return totalCount > 0 ? { status: "found", count: totalCount, primaryCount } : { status: "clean" };
1263
+ } catch (err) {
1264
+ if (isPullTimeoutError(err, effectiveTimeoutMs)) {
1265
+ trackAbandonedPullRequest(state, sourceKey, requestPromise);
1266
+ pullAbort.abort();
1267
+ recordPullTimeoutTelemetry({
1268
+ scope: normalizedPath,
1269
+ identifier,
1270
+ effectiveBudgetMs: effectiveTimeoutMs,
1271
+ hadPreviousResultId: previousResultId !== undefined,
1272
+ elapsedMs: Date.now() - requestStartedAt,
1273
+ server: state.serverId
1274
+ });
1275
+ armLateAnswerTelemetry({
1276
+ requestPromise,
1277
+ scope: normalizedPath,
1278
+ identifier,
1279
+ subject: sourceKey,
1280
+ requestStartedAt,
1281
+ server: state.serverId,
1282
+ settlement: pullSettlement
1283
+ });
1284
+ }
1285
+ recordPullFailure(state, "textDocument/diagnostic", err);
1286
+ return { status: "unavailable" };
1287
+ }
1288
+ }
1289
+ function trackAbandonedPullRequest(state, sourceKey, requestPromise) {
1290
+ if (!state.abandonedPullRequests)
1291
+ state.abandonedPullRequests = new Map;
1292
+ state.abandonedPullRequests.set(sourceKey, requestPromise);
1293
+ const release = () => {
1294
+ if (state.abandonedPullRequests?.get(sourceKey) === requestPromise) {
1295
+ state.abandonedPullRequests.delete(sourceKey);
1296
+ }
1297
+ };
1298
+ requestPromise.then(release, release);
1299
+ }
1300
+ function isPullTimeoutError(err, timeoutMs) {
1301
+ return err instanceof Error && err.message === `Timeout after ${timeoutMs}ms`;
1302
+ }
1303
+ function recordPullTimeoutTelemetry(args) {
1304
+ emitBounded("lsp_pull_diagnostic_timeout", `${args.server}::${args.scope}::${args.identifier ?? "bare"}`, {
1305
+ type: "phase",
1306
+ filePath: args.scope,
1307
+ durationMs: args.elapsedMs,
1308
+ metadata: {
1309
+ identifier: args.identifier ?? "bare",
1310
+ effectiveBudgetMs: args.effectiveBudgetMs,
1311
+ hadPreviousResultId: args.hadPreviousResultId,
1312
+ server: args.server
1313
+ }
1314
+ }, {
1315
+ ledgerKind: "lsp-pull-diagnostic-timeout",
1316
+ reason: `pull timeout on ${args.server} after ${args.elapsedMs}ms (budget ${args.effectiveBudgetMs}ms)`
1317
+ });
1318
+ }
1319
+ function armLateAnswerTelemetry(args) {
1320
+ args.requestPromise.then(() => {
1321
+ if (args.settlement.cancelled)
1322
+ return;
1323
+ try {
1324
+ const elapsedMs = Date.now() - args.requestStartedAt;
1325
+ emitBounded("lsp_pull_late_answer_discarded", args.subject, {
1326
+ type: "phase",
1327
+ filePath: args.scope,
1328
+ durationMs: elapsedMs,
1329
+ metadata: { identifier: args.identifier ?? "bare" }
1330
+ }, {
1331
+ ledgerKind: "lsp-pull-late-answer",
1332
+ reason: `late pull answer discarded after ${elapsedMs}ms`
1333
+ });
1334
+ } catch {}
1335
+ }, (err) => {
1336
+ try {
1337
+ const elapsedMs = Date.now() - args.requestStartedAt;
1338
+ const candidate = err;
1339
+ const code = typeof candidate?.code === "number" || typeof candidate?.code === "string" ? candidate.code : undefined;
1340
+ emitBounded("lsp_pull_late_rejection", `${args.server}::${args.subject}`, {
1341
+ type: "phase",
1342
+ filePath: args.scope,
1343
+ durationMs: elapsedMs,
1344
+ metadata: {
1345
+ identifier: args.identifier ?? "bare",
1346
+ server: args.server,
1347
+ ...code !== undefined && { code }
1348
+ }
1349
+ }, {
1350
+ ledgerKind: "lsp-pull-late-rejection",
1351
+ reason: `late pull rejection ${elapsedMs}ms after timeout${code !== undefined ? ` (code ${code})` : ""}`
1352
+ });
1353
+ } catch {}
1354
+ });
1355
+ }
1356
+ const PULL_FAILURE_HISTORY_LIMIT = 10;
1357
+ function recordPullFailure(state, method, error) {
1358
+ const candidate = error;
1359
+ const message = typeof candidate.message === "string" ? candidate.message : "";
1360
+ const unsupportedMessage = /^(?:method not found|unknown method|unsupported method)(?::|$)/i;
1361
+ if (candidate.code === -32601 || candidate.code === "-32601" || unsupportedMessage.test(message.trim()))
1362
+ return;
1363
+ state.pullFailureHistory.push({
1364
+ timestamp: Date.now(),
1365
+ method,
1366
+ ...typeof candidate.code === "number" || typeof candidate.code === "string" ? { code: candidate.code } : {},
1367
+ message: typeof candidate.message === "string" ? candidate.message : String(error)
1368
+ });
1369
+ if (state.pullFailureHistory.length > PULL_FAILURE_HISTORY_LIMIT) {
1370
+ state.pullFailureHistory.splice(0, state.pullFailureHistory.length - PULL_FAILURE_HISTORY_LIMIT);
1371
+ }
1372
+ }
1373
+ export async function clientRequestWorkspaceDiagnostics(state, budgetMs) {
1374
+ if (!isClientAlive(state))
1375
+ return;
1376
+ if (!state.workspaceDiagnosticsSupport.workspaceDiagnostics)
1377
+ return;
1378
+ if (state.abandonedPullRequests?.has(WORKSPACE_PULL_SCOPE))
1379
+ return;
1380
+ const previousResultIds = Array.from(state.workspacePullResultCache.values()).map((entry) => ({ uri: entry.uri, value: entry.resultId }));
1381
+ if (budgetMs < PULL_MIN_USABLE_BUDGET_MS) {
1382
+ emitBounded("lsp_pull_skipped_budget_exhausted", `${state.serverId}::${WORKSPACE_PULL_SCOPE}`, {
1383
+ type: "phase",
1384
+ filePath: WORKSPACE_PULL_SCOPE,
1385
+ durationMs: 0,
1386
+ metadata: {
1387
+ identifier: "bare",
1388
+ remainingBudgetMs: budgetMs,
1389
+ server: state.serverId
1390
+ }
1391
+ }, {
1392
+ ledgerKind: "lsp-pull-skipped-budget-exhausted",
1393
+ reason: `workspace pull skipped on ${state.serverId}: budget already exhausted (${budgetMs}ms remaining)`
1394
+ });
1395
+ return;
1396
+ }
1397
+ const workspacePullStartedAt = Date.now();
1398
+ const workspacePullTimeoutMs = Math.max(1, budgetMs);
1399
+ const workspacePullAbort = new AbortController;
1400
+ const workspacePullSettlement = { cancelled: false };
1401
+ const workspaceRequestPromise = safeSendRequest(state.connection, "workspace/diagnostic", { previousResultIds }, workspacePullAbort.signal, workspacePullSettlement);
1402
+ try {
1403
+ const report = await withTimeout(workspaceRequestPromise, workspacePullTimeoutMs);
1404
+ if (!report || !Array.isArray(report.items))
1405
+ return;
1406
+ const out = [];
1407
+ const fallbackPullDeadline = Date.now() + Math.max(1, budgetMs);
1408
+ for (const item of report.items) {
1409
+ if (!item?.uri)
1410
+ continue;
1411
+ const filePath = uriToPath(item.uri);
1412
+ const normalizedPath = normalizeMapKey(filePath);
1413
+ if (item.kind === "unchanged") {
1414
+ const prior = state.workspacePullResultCache.get(normalizedPath);
1415
+ if (!prior) {
1416
+ const remainingMs = fallbackPullDeadline - Date.now();
1417
+ if (remainingMs <= 0) {
1418
+ incrementDegradationCount({
1419
+ kind: "lsp-pull-unconfirmed",
1420
+ subject: state.serverId,
1421
+ reason: "unchanged report with no workspacePullResultCache basis; the shared fallback-pull deadline was already exhausted by earlier files this sweep"
1422
+ });
1423
+ continue;
1424
+ }
1425
+ const outcome = await clientRequestPullDiagnostics(state, filePath, remainingMs);
1426
+ if (outcome.status === "found") {
1427
+ out.push({
1428
+ filePath,
1429
+ diagnostics: state.documentPullDiagnostics.get(normalizedPath) ?? [],
1430
+ contentHash: state.diagnosticBindings.get(normalizedPath)?.contentHash
1431
+ });
1432
+ } else if (outcome.status === "unavailable") {
1433
+ incrementDegradationCount({
1434
+ kind: "lsp-pull-unconfirmed",
1435
+ subject: state.serverId,
1436
+ reason: "unchanged report with no workspacePullResultCache basis, and the per-file fallback pull was unavailable"
1437
+ });
1438
+ }
1439
+ continue;
1440
+ }
1441
+ if (item.resultId !== undefined) {
1442
+ state.workspacePullResultCache.set(normalizedPath, {
1443
+ ...prior,
1444
+ resultId: item.resultId
1445
+ });
1446
+ }
1447
+ out.push({
1448
+ filePath,
1449
+ diagnostics: prior.diagnostics,
1450
+ contentHash: prior.contentHash
1451
+ });
1452
+ continue;
1453
+ }
1454
+ const diagnostics = normalizeLspDiagnostics(item.items ?? []);
1455
+ const sent = state.openDocuments.has(normalizedPath) ? state.documentContentHashes.get(normalizedPath) : undefined;
1456
+ const contentHash = sent !== undefined && sent.version === item.version ? sent.hash : undefined;
1457
+ if (item.resultId !== undefined) {
1458
+ if (state.workspacePullResultCache.size >= WORKSPACE_PULL_RESULT_CACHE_MAX) {
1459
+ state.workspacePullResultCache.clear();
1460
+ }
1461
+ state.workspacePullResultCache.set(normalizedPath, {
1462
+ uri: item.uri,
1463
+ resultId: item.resultId,
1464
+ diagnostics,
1465
+ contentHash
1466
+ });
1467
+ } else {
1468
+ state.workspacePullResultCache.delete(normalizedPath);
1469
+ }
1470
+ out.push({ filePath, diagnostics, contentHash });
1471
+ }
1472
+ return out;
1473
+ } catch (err) {
1474
+ if (isPullTimeoutError(err, workspacePullTimeoutMs)) {
1475
+ trackAbandonedPullRequest(state, WORKSPACE_PULL_SCOPE, workspaceRequestPromise);
1476
+ workspacePullAbort.abort();
1477
+ recordPullTimeoutTelemetry({
1478
+ scope: WORKSPACE_PULL_SCOPE,
1479
+ identifier: undefined,
1480
+ effectiveBudgetMs: workspacePullTimeoutMs,
1481
+ hadPreviousResultId: previousResultIds.length > 0,
1482
+ elapsedMs: Date.now() - workspacePullStartedAt,
1483
+ server: state.serverId
1484
+ });
1485
+ armLateAnswerTelemetry({
1486
+ requestPromise: workspaceRequestPromise,
1487
+ scope: WORKSPACE_PULL_SCOPE,
1488
+ identifier: undefined,
1489
+ subject: WORKSPACE_PULL_SCOPE,
1490
+ requestStartedAt: workspacePullStartedAt,
1491
+ server: state.serverId,
1492
+ settlement: workspacePullSettlement
1493
+ });
1494
+ }
1495
+ recordPullFailure(state, "workspace/diagnostic", err);
1496
+ return;
1497
+ }
1498
+ }
1499
+ export async function clientWaitForDiagnostics(state, filePath, timeoutMs, options = {}) {
1500
+ const normalizedPath = normalizeMapKey(filePath);
1501
+ const minVersion = options.minVersion;
1502
+ const pullSettleSource = options.pullSettleSource ?? "pull";
1503
+ const hasFreshDiagnostics = () => minVersion === undefined || diagnosticsVersionForPath(state, normalizedPath) > minVersion;
1504
+ const isVersionStale = () => {
1505
+ const cachedVersion = state.diagnosticDocVersions?.get(normalizedPath);
1506
+ if (cachedVersion === undefined)
1507
+ return false;
1508
+ const currentVersion = state.documentVersions?.get(normalizedPath);
1509
+ return currentVersion !== undefined && cachedVersion < currentVersion;
1510
+ };
1511
+ if (state.workspaceDiagnosticsSupport.mode === "pull") {
1512
+ const pullSettleStartedAt = Date.now();
1513
+ let outcome = await clientRequestPullDiagnostics(state, filePath, timeoutMs);
1514
+ if (outcome.status === "found") {
1515
+ logTypeScriptPullSettle(state, normalizedPath, Date.now() - pullSettleStartedAt, pullSettleSource);
1516
+ return;
1517
+ }
1518
+ let sawClean = outcome.status === "clean";
1519
+ const strategy = getStrategy(state.serverId, state.launchVariant);
1520
+ const retryBudgetMs = strategy.pullRetryBudgetMs > 0 ? Math.min(timeoutMs, strategy.pullRetryBudgetMs) : 0;
1521
+ const startedAt = Date.now();
1522
+ while (outcome.status !== "found" && Date.now() - startedAt < retryBudgetMs) {
1523
+ await new Promise((resolve) => setTimeout(resolve, PULL_DIAGNOSTICS_RETRY_INTERVAL_MS));
1524
+ outcome = await clientRequestPullDiagnostics(state, filePath, Math.max(0, retryBudgetMs - (Date.now() - startedAt)));
1525
+ if (outcome.status === "clean")
1526
+ sawClean = true;
1527
+ }
1528
+ if (options.pullOnly) {
1529
+ if (outcome.status === "found" || sawClean) {
1530
+ logTypeScriptPullSettle(state, normalizedPath, Date.now() - pullSettleStartedAt, pullSettleSource);
1531
+ }
1532
+ return;
1533
+ }
1534
+ if (outcome.status === "found" || sawClean) {
1535
+ logTypeScriptPullSettle(state, normalizedPath, Date.now() - pullSettleStartedAt, pullSettleSource);
1536
+ return;
1537
+ }
1538
+ }
1539
+ const laterReceiptPending = () => state.pendingDiagnostics.has(normalizedPath);
1540
+ const storedAnswerSettles = () => hasFreshDiagnostics() && !isVersionStale() && getMergedDiagnosticsForPath(state, normalizedPath).length > 0;
1541
+ if (storedAnswerSettles() && !laterReceiptPending()) {
1542
+ return;
1543
+ }
1544
+ const answerStored = () => hasFreshDiagnostics() && !isVersionStale() && (state.pushDiagnostics.has(normalizedPath) || state.documentPullDiagnostics.has(normalizedPath));
1545
+ return new Promise((resolve) => {
1546
+ let debounceTimer;
1547
+ let settleDeferred = storedAnswerSettles();
1548
+ const finish = () => {
1549
+ if (debounceTimer)
1550
+ clearTimeout(debounceTimer);
1551
+ state.diagnosticEmitter.off("diagnostics", onDiagnostics);
1552
+ state.diagnosticEmitter.off(PENDING_RECEIPT_DROPPED, onReceiptDropped);
1553
+ clearTimeout(timeout);
1554
+ resolve();
1555
+ };
1556
+ const onDiagnostics = (fp) => {
1557
+ if (normalizeMapKey(fp) !== normalizedPath)
1558
+ return;
1559
+ if (!hasFreshDiagnostics() || isVersionStale())
1560
+ return;
1561
+ if (debounceTimer)
1562
+ clearTimeout(debounceTimer);
1563
+ const strategy = getStrategy(state.serverId, state.launchVariant);
1564
+ const hit = state.pushDiagnosticTimestamps.get(normalizedPath);
1565
+ const timeSincePush = hit ? Date.now() - hit : 1 / 0;
1566
+ const remaining = Math.max(0, strategy.debounceMs - timeSincePush);
1567
+ debounceTimer = setTimeout(() => {
1568
+ debounceTimer = undefined;
1569
+ if (laterReceiptPending()) {
1570
+ settleDeferred = true;
1571
+ return;
1572
+ }
1573
+ if (!answerStored())
1574
+ return;
1575
+ finish();
1576
+ }, remaining);
1577
+ };
1578
+ const onReceiptDropped = (fp) => {
1579
+ if (normalizeMapKey(fp) !== normalizedPath)
1580
+ return;
1581
+ if (settleDeferred && answerStored())
1582
+ finish();
1583
+ };
1584
+ state.diagnosticEmitter.on("diagnostics", onDiagnostics);
1585
+ state.diagnosticEmitter.on(PENDING_RECEIPT_DROPPED, onReceiptDropped);
1586
+ const timeout = setTimeout(finish, timeoutMs);
1587
+ });
1588
+ }
1589
+ export function handleNotifyExternalChange(state, filePath, type) {
1590
+ if (!isClientAlive(state))
1591
+ return;
1592
+ const normalizedPath = normalizeMapKey(filePath);
1593
+ const uri = state.openDocumentUris?.get(normalizedPath) ?? pathToFileURL(filePath).href;
1594
+ enqueueWatchedChange(state, normalizedPath, uri, type);
1595
+ }
1596
+ function enqueueWatchedChange(state, normalizedPath, uri, type, onDisk = true) {
1597
+ if (type === FILE_CREATED && onDisk)
1598
+ state.createdAnnounced?.add(normalizedPath);
1599
+ else if (type === FILE_DELETED)
1600
+ state.createdAnnounced?.delete(normalizedPath);
1601
+ state.watchQueue.enqueue(uri, type);
1602
+ }
1603
+ function watchedTypeForExisting(state, normalizedPath, info) {
1604
+ const birth = pathBirthtimeMs(info, normalizedPath);
1605
+ if (birth === undefined)
1606
+ return FILE_CHANGED;
1607
+ if (watchedTypeForOpen(birth, state.startedAtMs) !== FILE_CREATED) {
1608
+ return FILE_CHANGED;
1609
+ }
1610
+ return state.createdAnnounced?.has(normalizedPath) ? FILE_CHANGED : FILE_CREATED;
1611
+ }
1612
+ async function handleAnnounceCreated(state, entries) {
1613
+ if (!isClientAlive(state))
1614
+ return;
1615
+ const didCreateUris = [];
1616
+ for (const { filePath, stat: info } of entries) {
1617
+ const normalizedPath = normalizeMapKey(filePath);
1618
+ if (watchedTypeForExisting(state, normalizedPath, info) !== FILE_CREATED) {
1619
+ continue;
1620
+ }
1621
+ const uri = state.openDocumentUris?.get(normalizedPath) ?? pathToFileURL(filePath).href;
1622
+ enqueueWatchedChange(state, normalizedPath, uri, FILE_CREATED);
1623
+ if (await fileOperationFiltersMatch(state.fileOperationFilters?.didCreate, uri, uri, filePath, filePath)) {
1624
+ didCreateUris.push(uri);
1625
+ }
1626
+ }
1627
+ if (didCreateUris.length > 0 && isClientAlive(state)) {
1628
+ await safeSendNotification(state.connection, "workspace/didCreateFiles", {
1629
+ files: didCreateUris.map((uri) => ({ uri }))
1630
+ });
1631
+ }
1632
+ state.watchQueue.flushIfCreated();
1633
+ }
1634
+ function expectSaveRescan(state, normalizedPath) {
1635
+ if (!getStrategy(state.serverId, state.launchVariant).rescansOnSave)
1636
+ return;
1637
+ const beyond = state.expectedPublicationsBeyondSends;
1638
+ beyond?.set(normalizedPath, (beyond.get(normalizedPath) ?? 0) + 1);
1639
+ }
1640
+ function giveBackSaveRescan(state, normalizedPath) {
1641
+ const beyond = state.expectedPublicationsBeyondSends;
1642
+ const current = beyond?.get(normalizedPath);
1643
+ if (beyond && current !== undefined && current > 0)
1644
+ beyond.set(normalizedPath, current - 1);
1645
+ }
1646
+ async function sendDidSave(state, normalizedPath, uri, content, onlyIfOwed = false) {
1647
+ const save = state.saveOptions;
1648
+ if (!save || !isClientAlive(state))
1649
+ return false;
1650
+ const covered = state.documentContentHashes.get(normalizedPath);
1651
+ if (onlyIfOwed && covered && covered.savedHash === covered.hash)
1652
+ return true;
1653
+ expectSaveRescan(state, normalizedPath);
1654
+ const limit = save.includeText && content !== undefined ? exceedsLspSyncLimits(content) : { tooLarge: false, reason: "" };
1655
+ if (limit.tooLarge) {
1656
+ recordDegradationOnce({
1657
+ kind: "lsp-did-save-text-omitted",
1658
+ subject: state.serverId,
1659
+ reason: limit.reason
1660
+ });
1661
+ }
1662
+ let sent = false;
1663
+ try {
1664
+ sent = await safeSendNotification(state.connection, "textDocument/didSave", {
1665
+ textDocument: { uri },
1666
+ ...save.includeText && content !== undefined && !limit.tooLarge ? { text: content } : {}
1667
+ });
1668
+ } catch {}
1669
+ if (!sent) {
1670
+ giveBackSaveRescan(state, normalizedPath);
1671
+ recordDidSaveSendFailed(state, normalizedPath);
1672
+ } else if (covered) {
1673
+ covered.savedHash = covered.hash;
1674
+ }
1675
+ return sent;
1676
+ }
1677
+ async function sendDidSaveForHeldDocument(state, normalizedPath, onlyIfOwed = false) {
1678
+ if (!state.saveOptions || !isClientAlive(state))
1679
+ return false;
1680
+ if (!state.openDocuments.has(normalizedPath))
1681
+ return false;
1682
+ const uri = state.openDocumentUris?.get(normalizedPath);
1683
+ if (uri === undefined)
1684
+ return false;
1685
+ return sendDidSave(state, normalizedPath, uri, undefined, onlyIfOwed);
1686
+ }
1687
+ function recordDidSaveSendFailed(state, normalizedPath) {
1688
+ recordDegradationOnce({
1689
+ kind: "lsp-did-save-send-failed",
1690
+ subject: state.serverId,
1691
+ reason: "textDocument/didSave did not leave the process",
1692
+ metadata: { filePath: normalizedPath }
1693
+ });
1694
+ }
1695
+ async function handleNotifyOpenOnce(state, filePath, content, languageId, preserveDiagnostics = false, silent = false, coalescedCount = 0, saved = false, contentHash) {
1696
+ if (!isClientAlive(state))
1697
+ return false;
1698
+ const normalizedPath = normalizeMapKey(filePath);
1699
+ const uri = state.openDocumentUris?.get(normalizedPath) ?? pathToFileURL(filePath).href;
1700
+ if (state.openDocuments.has(normalizedPath) || state.pendingOpens.has(normalizedPath)) {
1701
+ const version = (state.documentVersions.get(normalizedPath) ?? 0) + 1;
1702
+ state.documentVersions.set(normalizedPath, version);
1703
+ if (!preserveDiagnostics) {
1704
+ clearDiagnosticsForPath(state, normalizedPath);
1705
+ }
1706
+ if (getStrategy(state.serverId, state.launchVariant).reopenOnResync) {
1707
+ await safeSendNotification(state.connection, "textDocument/didClose", {
1708
+ textDocument: { uri }
1709
+ });
1710
+ state.openDocuments.delete(normalizedPath);
1711
+ state.openDocumentUris?.delete(normalizedPath);
1712
+ state.documentVersions.set(normalizedPath, version);
1713
+ state.documentOpenedAt.set(normalizedPath, Date.now());
1714
+ state.diagnosticPublicationCounts.set(normalizedPath, 0);
1715
+ if (!isClientAlive(state))
1716
+ return false;
1717
+ const reopenSent = await safeSendNotification(state.connection, "textDocument/didOpen", { textDocument: { uri, languageId, version, text: content } });
1718
+ if (reopenSent)
1719
+ recordSentContent(state, normalizedPath, version, content, coalescedCount, contentHash);
1720
+ state.openDocuments.add(normalizedPath);
1721
+ state.openDocumentUris?.set(normalizedPath, uri);
1722
+ if (saved && reopenSent)
1723
+ await sendDidSave(state, normalizedPath, uri, content);
1724
+ return reopenSent;
1725
+ }
1726
+ const changeSent = await sendFenced(state, normalizedPath, uri, "textDocument/didChange", {
1727
+ textDocument: { uri, version },
1728
+ contentChanges: buildContentChanges(state, normalizedPath, content)
1729
+ });
1730
+ if (changeSent)
1731
+ recordSentContent(state, normalizedPath, version, content, coalescedCount, contentHash);
1732
+ if (saved && changeSent)
1733
+ await sendDidSave(state, normalizedPath, uri, content);
1734
+ return changeSent;
1735
+ }
1736
+ if (await closedAndGone(state, filePath, normalizedPath))
1737
+ return false;
1738
+ state.pendingOpens.add(normalizedPath);
1739
+ state.documentVersions.set(normalizedPath, 0);
1740
+ state.documentOpenedAt.set(normalizedPath, Date.now());
1741
+ state.diagnosticPublicationCounts.set(normalizedPath, 0);
1742
+ clearDiagnosticsForPath(state, normalizedPath);
1743
+ if (!state.expectedPublicationsBeyondSends?.has(normalizedPath))
1744
+ state.publicationStoreCountsByPath?.delete(normalizedPath);
1745
+ if (!silent) {
1746
+ let watchedType = FILE_CREATED;
1747
+ let onDisk = false;
1748
+ let info;
1749
+ try {
1750
+ info = await stat(filePath);
1751
+ onDisk = true;
1752
+ watchedType = watchedTypeForExisting(state, normalizedPath, info);
1753
+ } catch {}
1754
+ if (info && watchedType === FILE_CREATED && await fileOperationFiltersMatch(state.fileOperationFilters?.didCreate, uri, uri, filePath, filePath)) {
1755
+ await safeSendNotification(state.connection, "workspace/didCreateFiles", {
1756
+ files: [{ uri }]
1757
+ });
1758
+ }
1759
+ enqueueWatchedChange(state, normalizedPath, uri, watchedType, onDisk);
1760
+ }
1761
+ if (!isClientAlive(state))
1762
+ return false;
1763
+ const openSent = await sendFenced(state, normalizedPath, uri, "textDocument/didOpen", { textDocument: { uri, languageId, version: 0, text: content } });
1764
+ if (openSent)
1765
+ recordSentContent(state, normalizedPath, 0, content, coalescedCount, contentHash);
1766
+ state.pendingOpens.delete(normalizedPath);
1767
+ state.openDocuments.add(normalizedPath);
1768
+ state.closedDocuments?.delete(normalizedPath);
1769
+ state.openDocumentUris?.set(normalizedPath, uri);
1770
+ if (saved && openSent)
1771
+ await sendDidSave(state, normalizedPath, uri, content);
1772
+ probeTsserverProjectIdentity({
1773
+ serverId: state.serverId,
1774
+ launchVariant: state.launchVariant,
1775
+ clientRoot: state.root,
1776
+ file: filePath,
1777
+ normalizedFile: normalizedPath,
1778
+ probedFiles: state.projectIdentityProbedFiles ?? (state.projectIdentityProbedFiles = new Set),
1779
+ commandChannel: {
1780
+ executeCommand: (command, args) => runReadOnlyServerCommand(state, command, args)
1781
+ }
1782
+ });
1783
+ return openSent;
1784
+ }
1785
+ function enqueueDocumentNotify(state, normalizedPath, run, saved = false, readStamp, close = false, saveOnly = false, onlyIfOwed = false) {
1786
+ let queue = state.notifyChangeQueues.get(normalizedPath);
1787
+ if (!queue) {
1788
+ queue = { running: false, active: undefined };
1789
+ state.notifyChangeQueues.set(normalizedPath, queue);
1790
+ }
1791
+ return new Promise((resolve, reject) => {
1792
+ if (queue.closing && !close) {
1793
+ resolve(false);
1794
+ return;
1795
+ }
1796
+ const previous = queue?.pending;
1797
+ const waiters = previous?.waiters ?? [];
1798
+ if (close) {
1799
+ for (const waiter of waiters)
1800
+ waiter.stale = true;
1801
+ queue.closing = true;
1802
+ }
1803
+ const lastSent = state.sentReadStamps.get(normalizedPath);
1804
+ const before = (a, b) => a !== undefined && b !== undefined && a < b;
1805
+ const stale = previous !== undefined && (saveOnly || before(readStamp, previous.readStamp) || before(readStamp, lastSent));
1806
+ const heldStamp = before(previous?.readStamp, lastSent) ? undefined : previous?.readStamp;
1807
+ waiters.push({ resolve, reject, stale });
1808
+ queue.pending = {
1809
+ run: stale ? previous.run : run,
1810
+ saveOnly: stale ? previous.saveOnly : saveOnly,
1811
+ waiters,
1812
+ coalescedCount: (previous?.coalescedCount ?? 0) + (previous && !saveOnly ? 1 : 0),
1813
+ saved: saved || previous?.saved === true,
1814
+ onlyIfOwed: onlyIfOwed && (previous === undefined || previous.onlyIfOwed === true),
1815
+ readStamp: close ? undefined : stale ? previous.readStamp : readStamp ?? heldStamp
1816
+ };
1817
+ if (queue.running)
1818
+ return;
1819
+ queue.running = true;
1820
+ Promise.resolve().then(async () => {
1821
+ try {
1822
+ for (;; ) {
1823
+ const next = queue.pending;
1824
+ if (!next)
1825
+ break;
1826
+ queue.pending = undefined;
1827
+ queue.active = next;
1828
+ const lastSent = state.sentReadStamps.get(normalizedPath);
1829
+ if (next.readStamp !== undefined && lastSent !== undefined && next.readStamp < lastSent) {
1830
+ if (next.saved)
1831
+ await sendDidSaveForHeldDocument(state, normalizedPath);
1832
+ for (const waiter of next.waiters)
1833
+ waiter.resolve(false);
1834
+ continue;
1835
+ }
1836
+ if (next.readStamp !== undefined)
1837
+ state.sentReadStamps.set(normalizedPath, next.readStamp);
1838
+ try {
1839
+ const sent = await next.run(next.coalescedCount, next.saved, next.onlyIfOwed);
1840
+ for (const waiter of next.waiters)
1841
+ waiter.resolve(sent !== false && !waiter.stale);
1842
+ } catch (error) {
1843
+ for (const waiter of next.waiters)
1844
+ waiter.reject(error);
1845
+ }
1846
+ }
1847
+ } finally {
1848
+ queue.active = undefined;
1849
+ queue.running = false;
1850
+ if (!queue.pending && state.notifyChangeQueues.get(normalizedPath) === queue) {
1851
+ state.notifyChangeQueues.delete(normalizedPath);
1852
+ }
1853
+ }
1854
+ });
1855
+ });
1856
+ }
1857
+ function cancelDocumentNotifyQueues(state) {
1858
+ for (const queue of state.notifyChangeQueues.values()) {
1859
+ for (const waiter of queue.pending?.waiters ?? [])
1860
+ waiter.resolve(false);
1861
+ queue.pending = undefined;
1862
+ }
1863
+ state.notifyChangeQueues.clear();
1864
+ }
1865
+ export function handleNotifySave(state, filePath, onlyIfOwed = false) {
1866
+ const normalizedPath = normalizeMapKey(filePath);
1867
+ return enqueueDocumentNotify(state, normalizedPath, (_count, _saved, debtOnly) => sendDidSaveForHeldDocument(state, normalizedPath, debtOnly), true, undefined, false, true, onlyIfOwed);
1868
+ }
1869
+ export function handleNotifyOpen(state, filePath, content, languageId, preserveDiagnostics = false, silent = false, saved = false, readStamp, contentHash) {
1870
+ const normalizedPath = normalizeMapKey(filePath);
1871
+ return enqueueDocumentNotify(state, normalizedPath, (coalescedCount, queuedSaved) => handleNotifyOpenOnce(state, filePath, content, languageId, preserveDiagnostics, silent, coalescedCount, queuedSaved, contentHash), saved, readStamp);
1872
+ }
1873
+ async function handleNotifyChangeOnce(state, filePath, content, normalizedPath, coalescedCount = 0, saved = false, contentHash) {
1874
+ if (!isClientAlive(state))
1875
+ return false;
1876
+ const uri = state.openDocumentUris?.get(normalizedPath) ?? pathToFileURL(filePath).href;
1877
+ if (!state.openDocuments.has(normalizedPath)) {
1878
+ if (await closedAndGone(state, filePath, normalizedPath))
1879
+ return false;
1880
+ const fallbackOpenSent = await sendFenced(state, normalizedPath, uri, "textDocument/didOpen", {
1881
+ textDocument: {
1882
+ uri,
1883
+ languageId: "plaintext",
1884
+ version: 0,
1885
+ text: content
1886
+ }
1887
+ });
1888
+ state.documentVersions.set(normalizedPath, 0);
1889
+ state.documentOpenedAt.set(normalizedPath, Date.now());
1890
+ state.diagnosticPublicationCounts.set(normalizedPath, 0);
1891
+ if (fallbackOpenSent)
1892
+ recordSentContent(state, normalizedPath, 0, content, coalescedCount, contentHash);
1893
+ state.openDocuments.add(normalizedPath);
1894
+ state.closedDocuments?.delete(normalizedPath);
1895
+ state.openDocumentUris?.set(normalizedPath, uri);
1896
+ if (saved && fallbackOpenSent)
1897
+ await sendDidSave(state, normalizedPath, uri, content);
1898
+ return fallbackOpenSent;
1899
+ }
1900
+ const version = (state.documentVersions.get(normalizedPath) ?? 0) + 1;
1901
+ state.documentVersions.set(normalizedPath, version);
1902
+ clearDiagnosticsForPath(state, normalizedPath);
1903
+ const changeSent = await sendFenced(state, normalizedPath, uri, "textDocument/didChange", {
1904
+ textDocument: { uri, version },
1905
+ contentChanges: buildContentChanges(state, normalizedPath, content)
1906
+ });
1907
+ if (changeSent)
1908
+ recordSentContent(state, normalizedPath, version, content, coalescedCount, contentHash);
1909
+ if (saved && changeSent)
1910
+ await sendDidSave(state, normalizedPath, uri, content);
1911
+ return changeSent;
1912
+ }
1913
+ export function handleNotifyChange(state, filePath, content, contentHash) {
1914
+ const normalizedPath = normalizeMapKey(filePath);
1915
+ return enqueueDocumentNotify(state, normalizedPath, (coalescedCount, queuedSaved) => handleNotifyChangeOnce(state, filePath, content, normalizedPath, coalescedCount, queuedSaved, contentHash));
1916
+ }
1917
+ async function closedAndGone(state, filePath, normalizedPath) {
1918
+ if (!state.closedDocuments?.has(normalizedPath))
1919
+ return false;
1920
+ try {
1921
+ await access(filePath);
1922
+ return false;
1923
+ } catch {
1924
+ return true;
1925
+ }
1926
+ }
1927
+ export async function closeDocument(state, filePath) {
1928
+ if (!isClientAlive(state))
1929
+ return;
1930
+ const normalizedPath = normalizeMapKey(filePath);
1931
+ await enqueueDocumentNotify(state, normalizedPath, () => closeDocumentOnce(state, filePath, normalizedPath), false, undefined, true);
1932
+ }
1933
+ async function closeDocumentOnce(state, filePath, normalizedPath) {
1934
+ if (!isClientAlive(state))
1935
+ return;
1936
+ if (!state.openDocuments.has(normalizedPath)) {
1937
+ state.closedDocuments?.add(normalizedPath);
1938
+ return;
1939
+ }
1940
+ await safeSendNotification(state.connection, "textDocument/didClose", {
1941
+ textDocument: {
1942
+ uri: state.openDocumentUris?.get(normalizedPath) ?? pathToFileURL(filePath).href
1943
+ }
1944
+ });
1945
+ state.openDocuments.delete(normalizedPath);
1946
+ state.closedDocuments?.add(normalizedPath);
1947
+ state.openDocumentUris?.delete(normalizedPath);
1948
+ state.expectedPublicationsBeyondSends?.set(normalizedPath, publicationCountsForPath(state, normalizedPath).sent);
1949
+ state.documentVersions.delete(normalizedPath);
1950
+ state.sentReadStamps.delete(normalizedPath);
1951
+ state.documentOpenedAt.delete(normalizedPath);
1952
+ state.diagnosticPublicationCounts.delete(normalizedPath);
1953
+ state.projectIdentityProbedFiles?.delete(normalizedPath);
1954
+ const retained = state.documentContentHashes.get(normalizedPath);
1955
+ if (retained?.text !== undefined) {
1956
+ state.incrementalTextRetainedEntries = Math.max(0, (state.incrementalTextRetainedEntries ?? 1) - 1);
1957
+ state.incrementalTextRetainedBytes = Math.max(0, (state.incrementalTextRetainedBytes ?? retained.text.length * 2) - retained.text.length * 2);
1958
+ state.incrementalTextBearingPaths?.delete(normalizedPath);
1959
+ }
1960
+ state.documentContentHashes.delete(normalizedPath);
1961
+ clearDiagnosticsForPath(state, normalizedPath);
1962
+ }
1963
+ function isAtLeastAsAggressiveShutdown(existing, requested) {
1964
+ return !!existing.fast >= !!requested.fast && !!existing.processExiting >= !!requested.processExiting;
1965
+ }
1966
+ export function clientShutdown(state, options = {}) {
1967
+ if (state.shutdownPromise && state.shutdownOptions && isAtLeastAsAggressiveShutdown(state.shutdownOptions, options)) {
1968
+ return state.shutdownPromise;
1969
+ }
1970
+ state.shutdownOptions = options;
1971
+ const attempt = clientShutdownOnce(state, options);
1972
+ state.shutdownPromise = attempt;
1973
+ attempt.catch(() => {
1974
+ if (state.shutdownPromise === attempt) {
1975
+ state.shutdownPromise = undefined;
1976
+ state.shutdownOptions = undefined;
1977
+ }
1978
+ });
1979
+ return attempt;
1980
+ }
1981
+ async function clientShutdownOnce(state, options) {
1982
+ const shutdownStart = Date.now();
1983
+ state.shutdownRequested = true;
1984
+ state.isConnected = false;
1985
+ state.isDestroyed = true;
1986
+ for (const timer of state.pendingDiagnostics.values()) {
1987
+ clearTimeout(timer);
1988
+ }
1989
+ state.pendingDiagnostics.clear();
1990
+ state.pendingOpens.clear();
1991
+ state.openDocuments.clear();
1992
+ state.openDocumentUris?.clear();
1993
+ cancelDocumentNotifyQueues(state);
1994
+ state.projectIdentityProbedFiles?.clear();
1995
+ state.watchQueue?.cancel();
1996
+ state.diagnosticEmitter.removeAllListeners();
1997
+ let shutdownRequestTimedOut = false;
1998
+ let exitNotifyTimedOut = false;
1999
+ let shutdownRequestUndelivered = false;
2000
+ let exitNotifyUndelivered = false;
2001
+ try {
2002
+ if (!options.fast) {
2003
+ try {
2004
+ const shutdownAck = await withTimeout(safeSendRequest(state.connection, "shutdown", {}), SHUTDOWN_REQUEST_TIMEOUT_MS);
2005
+ if (shutdownAck === undefined)
2006
+ shutdownRequestUndelivered = true;
2007
+ } catch (err) {
2008
+ if (isShutdownTimeoutError(err, SHUTDOWN_REQUEST_TIMEOUT_MS)) {
2009
+ shutdownRequestTimedOut = true;
2010
+ } else {
2011
+ shutdownRequestUndelivered = true;
2012
+ }
2013
+ }
2014
+ try {
2015
+ const exitSent = await withTimeout(safeSendNotification(state.connection, "exit", {}), EXIT_NOTIFY_TIMEOUT_MS);
2016
+ if (exitSent === false)
2017
+ exitNotifyUndelivered = true;
2018
+ } catch (err) {
2019
+ if (isShutdownTimeoutError(err, EXIT_NOTIFY_TIMEOUT_MS)) {
2020
+ exitNotifyTimedOut = true;
2021
+ } else {
2022
+ exitNotifyUndelivered = true;
2023
+ }
2024
+ }
2025
+ }
2026
+ } finally {
2027
+ disposeClientConnection(state);
2028
+ const pid = state.lspProcess.pid;
2029
+ logLatency({
2030
+ type: "phase",
2031
+ phase: "lsp_client_shutdown",
2032
+ filePath: state.root,
2033
+ durationMs: Date.now() - shutdownStart,
2034
+ metadata: {
2035
+ serverId: state.serverId,
2036
+ pid,
2037
+ fast: !!options.fast,
2038
+ processExiting: !!options.processExiting,
2039
+ shutdownRequestTimedOut,
2040
+ exitNotifyTimedOut,
2041
+ shutdownRequestUndelivered,
2042
+ exitNotifyUndelivered,
2043
+ shutdownOutcome: options.fast ? "fast" : shutdownRequestTimedOut || exitNotifyTimedOut || shutdownRequestUndelivered || exitNotifyUndelivered ? "forced" : "graceful"
2044
+ }
2045
+ });
2046
+ removeLspChild(pid, extractSpawnMarker(state.lspProcess.args)).catch((err) => {
2047
+ logLatency({
2048
+ type: "phase",
2049
+ phase: "lsp_registry_write_failed",
2050
+ filePath: "",
2051
+ durationMs: 0,
2052
+ metadata: { op: "remove", pid, error: String(err) }
2053
+ });
2054
+ });
2055
+ await killProcessTree(state.lspProcess.process, pid, options);
2056
+ }
2057
+ }
2058
+ async function toWirePosition(state, filePath, line, character) {
2059
+ if (state.positionEncoding === "utf-16")
2060
+ return { line, character };
2061
+ try {
2062
+ const content = await readFile(filePath, "utf8");
2063
+ return {
2064
+ line,
2065
+ character: convertCharacterOffset(state.positionEncoding, lineTextAt(content, line), character)
2066
+ };
2067
+ } catch {
2068
+ return { line, character };
2069
+ }
2070
+ }
2071
+ function navStaleDropEnabled() {
2072
+ return process.env.DM_LENS_LSP_NAV_STALE_DROP !== "0";
2073
+ }
2074
+ export async function navRequest(state, method, params, staleCheckPath, timeoutMs = NAV_REQUEST_TIMEOUT_MS, signal = getAmbientAbortSignal()) {
2075
+ if (!isClientAlive(state))
2076
+ return null;
2077
+ const normalizedPath = staleCheckPath !== undefined ? normalizeMapKey(staleCheckPath) : undefined;
2078
+ const requestVersion = normalizedPath !== undefined ? state.documentVersions.get(normalizedPath) : undefined;
2079
+ const requestStartedAt = Date.now();
2080
+ const requestPromise = safeSendRequest(state.connection, method, params, signal);
2081
+ const result = await withTimeout(requestPromise, timeoutMs).catch((err) => {
2082
+ if (isNavTimeoutError(err, timeoutMs)) {
2083
+ recordNavTimeoutTelemetry({
2084
+ method,
2085
+ scope: normalizedPath,
2086
+ budgetMs: timeoutMs,
2087
+ elapsedMs: Date.now() - requestStartedAt
2088
+ });
2089
+ armNavLateAnswerTelemetry({
2090
+ requestPromise,
2091
+ method,
2092
+ scope: normalizedPath,
2093
+ requestStartedAt
2094
+ });
2095
+ return;
2096
+ }
2097
+ if (err instanceof Error && err.message.startsWith("Timeout after")) {
2098
+ return;
2099
+ }
2100
+ throw err;
2101
+ });
2102
+ if (normalizedPath !== undefined && requestVersion !== undefined && navStaleDropEnabled()) {
2103
+ const currentVersion = state.documentVersions.get(normalizedPath);
2104
+ if (currentVersion !== undefined && currentVersion > requestVersion) {
2105
+ return;
2106
+ }
2107
+ }
2108
+ return result;
2109
+ }
2110
+ function isNavTimeoutError(err, timeoutMs) {
2111
+ return err instanceof Error && err.message === `Timeout after ${timeoutMs}ms`;
2112
+ }
2113
+ function isShutdownTimeoutError(err, timeoutMs) {
2114
+ return err instanceof Error && err.message === `Timeout after ${timeoutMs}ms`;
2115
+ }
2116
+ const NAV_REQUEST_NO_PATH_SCOPE = "*no-path*";
2117
+ function recordNavTimeoutTelemetry(args) {
2118
+ emitBounded("lsp_nav_request_timeout", `${args.method}:${args.scope ?? NAV_REQUEST_NO_PATH_SCOPE}`, {
2119
+ type: "phase",
2120
+ filePath: args.scope ?? NAV_REQUEST_NO_PATH_SCOPE,
2121
+ durationMs: args.elapsedMs,
2122
+ metadata: { method: args.method, effectiveBudgetMs: args.budgetMs }
2123
+ }, {
2124
+ ledgerKind: "lsp-nav-request-timeout",
2125
+ risingEdgePer: "identity",
2126
+ reason: `timeout budget=${args.budgetMs}ms elapsed=${args.elapsedMs}ms`
2127
+ });
2128
+ }
2129
+ function armNavLateAnswerTelemetry(args) {
2130
+ args.requestPromise.then(() => {
2131
+ try {
2132
+ const elapsedMs = Date.now() - args.requestStartedAt;
2133
+ emitBounded("lsp_nav_late_answer_discarded", `${args.method}:${args.scope ?? NAV_REQUEST_NO_PATH_SCOPE}`, {
2134
+ type: "phase",
2135
+ filePath: args.scope ?? NAV_REQUEST_NO_PATH_SCOPE,
2136
+ durationMs: elapsedMs,
2137
+ metadata: { method: args.method }
2138
+ }, {
2139
+ ledgerKind: "lsp-nav-late-answer",
2140
+ risingEdgePer: "identity",
2141
+ reason: `late nav answer discarded after ${elapsedMs}ms`
2142
+ });
2143
+ } catch {}
2144
+ }, () => {});
2145
+ }
2146
+ function chooseLivenessProbe(state) {
2147
+ if (state.operationSupport?.workspaceSymbol === true) {
2148
+ return {
2149
+ method: "workspace/symbol",
2150
+ params: { query: LIVENESS_PING_QUERY }
2151
+ };
2152
+ }
2153
+ const openUri = firstOpenDocumentUri(state);
2154
+ if (openUri === undefined)
2155
+ return;
2156
+ if (state.operationSupport?.documentSymbol === true) {
2157
+ return {
2158
+ method: "textDocument/documentSymbol",
2159
+ params: { textDocument: { uri: openUri } }
2160
+ };
2161
+ }
2162
+ if (state.operationSupport?.hover === true) {
2163
+ return {
2164
+ method: "textDocument/hover",
2165
+ params: {
2166
+ textDocument: { uri: openUri },
2167
+ position: { line: 0, character: 0 }
2168
+ }
2169
+ };
2170
+ }
2171
+ return;
2172
+ }
2173
+ function firstOpenDocumentUri(state) {
2174
+ for (const normalizedPath of state.openDocuments) {
2175
+ const uri = state.openDocumentUris?.get(normalizedPath);
2176
+ if (uri !== undefined)
2177
+ return uri;
2178
+ }
2179
+ return;
2180
+ }
2181
+ async function clientPingLiveness(state, timeoutMs = LIVENESS_PING_TIMEOUT_MS) {
2182
+ if (!isClientAlive(state))
2183
+ return false;
2184
+ const probe = chooseLivenessProbe(state);
2185
+ if (probe === undefined) {
2186
+ try {
2187
+ incrementDegradationCount({
2188
+ kind: "lsp-liveness-probe-unsupported",
2189
+ subject: state.serverId,
2190
+ reason: "no advertised request method to probe with (no " + "workspaceSymbolProvider, and no open document with " + "documentSymbolProvider or hoverProvider); liveness from " + "process and connection state only"
2191
+ });
2192
+ } catch {}
2193
+ return isClientAlive(state);
2194
+ }
2195
+ try {
2196
+ await withTimeout(safeSendRequest(state.connection, probe.method, probe.params), timeoutMs);
2197
+ } catch (err) {
2198
+ if (err instanceof Error && err.message.startsWith("Timeout after")) {
2199
+ return false;
2200
+ }
2201
+ }
2202
+ return isClientAlive(state);
2203
+ }
2204
+ function syncMutationContextSlot(state) {
2205
+ state.activeMutationContext = state.activeMutationDepth === 1 ? state.mutationContextOwner : undefined;
2206
+ }
2207
+ export async function runServerCommand(state, command, args, timeoutMs = EXECUTE_COMMAND_TIMEOUT_MS, mutationContext) {
2208
+ if (!isClientAlive(state)) {
2209
+ return { executed: false, reason: "lsp client not alive" };
2210
+ }
2211
+ if (!state.advertisedCommands.has(command)) {
2212
+ return {
2213
+ executed: false,
2214
+ reason: `command "${command}" is not advertised by the ${state.serverId} server`
2215
+ };
2216
+ }
2217
+ state.serverEditsAllowed += 1;
2218
+ state.activeMutationDepth = (state.activeMutationDepth ?? 0) + 1;
2219
+ const isMutationContextOwner = state.activeMutationDepth === 1;
2220
+ if (isMutationContextOwner) {
2221
+ state.mutationContextOwner = mutationContext;
2222
+ }
2223
+ syncMutationContextSlot(state);
2224
+ try {
2225
+ let result;
2226
+ try {
2227
+ result = await withTimeout(safeSendRequest(state.connection, "workspace/executeCommand", {
2228
+ command,
2229
+ arguments: args ?? []
2230
+ }), timeoutMs);
2231
+ } catch (err) {
2232
+ if (err instanceof Error && err.message.startsWith("Timeout after")) {
2233
+ return {
2234
+ executed: false,
2235
+ reason: `workspace/executeCommand timed out after ${timeoutMs}ms — the command may still be applying server-side`
2236
+ };
2237
+ }
2238
+ throw err;
2239
+ }
2240
+ return { executed: true, result };
2241
+ } finally {
2242
+ state.serverEditsAllowed -= 1;
2243
+ state.activeMutationDepth = Math.max(0, (state.activeMutationDepth ?? 0) - 1);
2244
+ if (isMutationContextOwner) {
2245
+ state.mutationContextOwner = undefined;
2246
+ }
2247
+ syncMutationContextSlot(state);
2248
+ }
2249
+ }
2250
+ export async function runReadOnlyServerCommand(state, command, args, timeoutMs = PROBE_COMMAND_TIMEOUT_MS) {
2251
+ if (!isClientAlive(state)) {
2252
+ return { executed: false, reason: "lsp client not alive" };
2253
+ }
2254
+ if (!state.advertisedCommands.has(command)) {
2255
+ return {
2256
+ executed: false,
2257
+ reason: `command "${command}" is not advertised by the ${state.serverId} server`
2258
+ };
2259
+ }
2260
+ const abandon = new AbortController;
2261
+ const request = safeSendRequest(state.connection, "workspace/executeCommand", { command, arguments: args ?? [] }, abandon.signal, undefined, true);
2262
+ try {
2263
+ const result = await withTimeout(request, timeoutMs);
2264
+ return { executed: true, result };
2265
+ } catch (err) {
2266
+ if (err instanceof Error && err.message.startsWith("Timeout after")) {
2267
+ abandon.abort();
2268
+ await request;
2269
+ recordDegradationOnce({
2270
+ kind: "lsp-readonly-command-released",
2271
+ subject: state.serverId,
2272
+ reason: `${command} timed out after ${timeoutMs}ms; the request was cancelled and released locally`
2273
+ });
2274
+ return {
2275
+ executed: false,
2276
+ reason: `workspace/executeCommand timed out after ${timeoutMs}ms`
2277
+ };
2278
+ }
2279
+ throw err;
2280
+ }
2281
+ }
2282
+ function validateWorkspaceEditVersions(state, edit) {
2283
+ for (const change of edit.documentChanges ?? []) {
2284
+ if (typeof change !== "object" || change === null || !("textDocument" in change))
2285
+ continue;
2286
+ const textDocument = change.textDocument;
2287
+ if (!textDocument || typeof textDocument.uri !== "string" || textDocument.version == null)
2288
+ continue;
2289
+ const current = state.documentVersions.get(normalizeMapKey(uriToPath(textDocument.uri)));
2290
+ if (current === undefined || current !== textDocument.version) {
2291
+ throw new Error(`stale workspace edit document version for ${textDocument.uri}`);
2292
+ }
2293
+ }
2294
+ }
2295
+ function stripDocumentVersions(edit) {
2296
+ if (!Array.isArray(edit.documentChanges))
2297
+ return edit;
2298
+ const documentChanges = edit.documentChanges.map((change) => {
2299
+ if (typeof change === "object" && change !== null && "textDocument" in change && "edits" in change) {
2300
+ const textDocument = change.textDocument;
2301
+ if (textDocument && typeof textDocument.version === "number") {
2302
+ return {
2303
+ ...change,
2304
+ textDocument: { ...textDocument, version: null }
2305
+ };
2306
+ }
2307
+ }
2308
+ return change;
2309
+ });
2310
+ return { ...edit, documentChanges };
2311
+ }
2312
+ export async function normalizeClientWorkspaceEdit(state, edit) {
2313
+ validateWorkspaceEditVersions(state, edit);
2314
+ const normalized = await normalizeWorkspaceEditToUtf16(edit, state.positionEncoding, state.root);
2315
+ return stripDocumentVersions(normalized);
2316
+ }
2317
+ async function resolveCodeActionBestEffort(state, action) {
2318
+ if (!isClientAlive(state))
2319
+ return action;
2320
+ if (action.edit) {
2321
+ return {
2322
+ ...action,
2323
+ edit: await normalizeClientWorkspaceEdit(state, action.edit)
2324
+ };
2325
+ }
2326
+ if (!state.operationSupport.codeActionResolve) {
2327
+ recordDegradationOnce({
2328
+ kind: "lsp-capability-skip",
2329
+ subject: `${state.serverId}:codeAction/resolve`,
2330
+ reason: "server did not advertise codeActionProvider.resolveProvider"
2331
+ });
2332
+ return action;
2333
+ }
2334
+ let resolved;
2335
+ try {
2336
+ resolved = await withTimeout(safeSendRequest(state.connection, "codeAction/resolve", action), NAV_REQUEST_TIMEOUT_MS);
2337
+ } catch {
2338
+ return action;
2339
+ }
2340
+ if (!resolved || typeof resolved !== "object")
2341
+ return action;
2342
+ const merged = { ...action, ...resolved };
2343
+ return merged.edit ? {
2344
+ ...merged,
2345
+ edit: await normalizeClientWorkspaceEdit(state, merged.edit)
2346
+ } : merged;
2347
+ }
2348
+ export function sentContentFor(state, filePath) {
2349
+ const sent = state.documentContentHashes.get(normalizeMapKey(filePath));
2350
+ return sent && {
2351
+ hash: sent.hash,
2352
+ savedHash: sent.savedHash,
2353
+ changedAtMs: sent.changedAtMs,
2354
+ openedAtMs: sent.openedAtMs,
2355
+ openedHash: sent.openedHash,
2356
+ clientStartedAtMs: state.startedAtMs
2357
+ };
2358
+ }
2359
+ export function hasNotifyInFlightFor(state, filePath) {
2360
+ const queue = state.notifyChangeQueues.get(normalizeMapKey(filePath));
2361
+ return queue?.active?.saveOnly === false || queue?.pending?.saveOnly === false;
2362
+ }
2363
+ export async function createLSPClient(options) {
2364
+ installCrashGuard();
2365
+ const { serverId, process: lspProcess, root, sessionCwd, initialization, initializeTimeoutMs = INITIALIZE_TIMEOUT_MS, launchVariant, settingsSection, role, onDiagnosticsPublished } = options;
2366
+ recordLspChild({
2367
+ pid: lspProcess.pid,
2368
+ serverId,
2369
+ command: lspProcess.command,
2370
+ marker: extractSpawnMarker(lspProcess.args),
2371
+ sessionIdentity: {
2372
+ projectRoot: sessionCwd ?? process.cwd(),
2373
+ rootSource: sessionCwd ? "service-cwd" : "lsp-fallback",
2374
+ startedAt: new Date(workspaceDiagnosticsCacheSessionStart()).toISOString()
2375
+ }
2376
+ }).catch((err) => {
2377
+ logLatency({
2378
+ type: "phase",
2379
+ phase: "lsp_registry_write_failed",
2380
+ filePath: "",
2381
+ durationMs: 0,
2382
+ metadata: { op: "record", pid: lspProcess.pid, error: String(err) }
2383
+ });
2384
+ });
2385
+ const startupState = {
2386
+ exitCode: null,
2387
+ exitSignal: null,
2388
+ closeCode: null,
2389
+ closeSignal: null,
2390
+ stderr: ""
2391
+ };
2392
+ const stderrRing = [];
2393
+ const MAX_STDERR_LINES = 100;
2394
+ const onStderr = (chunk) => {
2395
+ stderrRing.push(chunk.toString());
2396
+ if (stderrRing.length > MAX_STDERR_LINES)
2397
+ stderrRing.shift();
2398
+ if (startupState.stderr.length < 4096) {
2399
+ startupState.stderr += chunk.toString();
2400
+ }
2401
+ };
2402
+ const recentStderr = (lines = 10) => stderrRing.slice(-lines).join("").trim();
2403
+ const checkProcessAlive = () => {
2404
+ const exited = lspProcess.process.exitCode;
2405
+ if (exited !== null) {
2406
+ const tail = recentStderr(20);
2407
+ return `LSP server ${serverId} exited with code ${exited}${tail ? `. stderr: ${tail}` : ""}`;
2408
+ }
2409
+ if (lspProcess.process.killed) {
2410
+ return `LSP server ${serverId} was killed`;
2411
+ }
2412
+ return;
2413
+ };
2414
+ const onProcessExit = (code, signal) => {
2415
+ startupState.exitCode = code;
2416
+ startupState.exitSignal = signal;
2417
+ };
2418
+ const onProcessClose = (code, signal) => {
2419
+ startupState.closeCode = code;
2420
+ startupState.closeSignal = signal;
2421
+ };
2422
+ lspProcess.stderr.on("data", onStderr);
2423
+ lspProcess.process.on("exit", onProcessExit);
2424
+ lspProcess.process.on("close", onProcessClose);
2425
+ const streamErrorHandler = (_label) => (err) => {
2426
+ if (err.code === "ERR_STREAM_DESTROYED" || err.code === "ERR_STREAM_WRITE_AFTER_END" || err.code === "EPIPE" || err.code === "ECONNRESET")
2427
+ return;
2428
+ };
2429
+ lspProcess.stdin.on("error", streamErrorHandler("stdin"));
2430
+ lspProcess.stdout.on("error", streamErrorHandler("stdout"));
2431
+ lspProcess.stderr.on("error", streamErrorHandler("stderr"));
2432
+ const connection = createMessageConnection(new StreamMessageReader(lspProcess.stdout), new StreamMessageWriter(lspProcess.stdin));
2433
+ const diagnosticEmitter = new EventEmitter;
2434
+ diagnosticEmitter.setMaxListeners(50);
2435
+ const state = {
2436
+ isConnected: true,
2437
+ isDestroyed: false,
2438
+ startedAtMs: Date.now(),
2439
+ createdAnnounced: new BoundedSet(4096),
2440
+ shutdownRequested: false,
2441
+ shutdownPromise: undefined,
2442
+ shutdownOptions: undefined,
2443
+ exitedAt: undefined,
2444
+ connectionDisposed: false,
2445
+ lastError: undefined,
2446
+ connection,
2447
+ pushDiagnostics: new Map,
2448
+ pushDiagnosticTimestamps: new Map,
2449
+ documentPullDiagnostics: new Map,
2450
+ documentPullDiagnosticTimestamps: new Map,
2451
+ pullFailureHistory: [],
2452
+ pendingDiagnostics: new Map,
2453
+ diagnosticPublicationCounts: new Map,
2454
+ documentOpenedAt: new Map,
2455
+ diagnosticEmitter,
2456
+ diagnosticsVersion: 0,
2457
+ diagnosticsVersionsByPath: new Map,
2458
+ publicationStoreCountsByPath: new Map,
2459
+ expectedPublicationsBeyondSends: new Map,
2460
+ documentVersions: new Map,
2461
+ notifyChangeQueues: new Map,
2462
+ sentReadStamps: new Map,
2463
+ diagnosticDocVersions: new Map,
2464
+ documentContentHashes: new Map,
2465
+ incrementalTextRetainedEntries: 0,
2466
+ incrementalTextBearingPaths: new Set,
2467
+ incrementalTextRetainedBytes: 0,
2468
+ diagnosticBindings: new Map,
2469
+ pullResultIds: new Map,
2470
+ documentPullDiagnosticsBySource: new Map,
2471
+ pullGenerations: new Map,
2472
+ pullRequestSequences: new Map,
2473
+ workspacePullResultCache: new Map,
2474
+ openDocuments: new Set,
2475
+ ...role !== undefined && { serverRole: role },
2476
+ emptyFirstPublishHoldSpent: false,
2477
+ rulesGeneration: 0,
2478
+ diagnosticFences: new Map,
2479
+ closedDocuments: new Set,
2480
+ openDocumentUris: new Map,
2481
+ pendingOpens: new Set,
2482
+ projectIdentityProbedFiles: new Set,
2483
+ workspaceDiagnosticsSupport: undefined,
2484
+ operationSupport: undefined,
2485
+ staticDiagnosticsMode: "push-only",
2486
+ positionEncoding: "utf-16",
2487
+ syncKind: TEXT_DOCUMENT_SYNC_KIND_FULL,
2488
+ dynamicRegistrations: new Map,
2489
+ advertisedCommands: new Set,
2490
+ serverEditsAllowed: 0,
2491
+ activeMutationDepth: 0,
2492
+ serverId,
2493
+ launchVariant,
2494
+ root,
2495
+ lspProcess,
2496
+ watchQueue: undefined
2497
+ };
2498
+ activeLspClientSet().add(state);
2499
+ state.watchQueue = new WatchedFilesQueue((changes) => {
2500
+ if (!isClientAlive(state))
2501
+ return;
2502
+ safeSendNotification(state.connection, "workspace/didChangeWatchedFiles", { changes });
2503
+ }, undefined, (uris) => noteWorkspaceFileCreated(state.serverId, state.root, uris.map(uriToPath)));
2504
+ const settings = settingsSection && initialization ? { [settingsSection]: initialization } : initialization;
2505
+ setupIncomingHandlers(state, settings, onDiagnosticsPublished);
2506
+ connection.listen();
2507
+ setupConnectionLifecycle(state, recentStderr);
2508
+ let initResult;
2509
+ try {
2510
+ initResult = await withTimeout(safeSendRequest(connection, "initialize", {
2511
+ processId: process.pid,
2512
+ rootUri: pathToFileURL(root).href,
2513
+ workspaceFolders: [
2514
+ { name: "workspace", uri: pathToFileURL(root).href }
2515
+ ],
2516
+ capabilities: CLIENT_CAPABILITIES,
2517
+ initializationOptions: initialization
2518
+ }), initializeTimeoutMs);
2519
+ } catch (err) {
2520
+ state.shutdownRequested = true;
2521
+ const pid = lspProcess.pid;
2522
+ killProcessTree(lspProcess.process, pid);
2523
+ removeLspChild(pid, extractSpawnMarker(lspProcess.args)).catch((err) => {
2524
+ logLatency({
2525
+ type: "phase",
2526
+ phase: "lsp_registry_write_failed",
2527
+ filePath: "",
2528
+ durationMs: 0,
2529
+ metadata: { op: "remove", pid, error: String(err) }
2530
+ });
2531
+ });
2532
+ setTimeout(() => {
2533
+ if (lspProcess.process.exitCode === null && lspProcess.process.signalCode === null && process.platform !== "win32") {
2534
+ lspProcess.process.kill("SIGKILL");
2535
+ }
2536
+ }, 2000);
2537
+ throw err;
2538
+ } finally {
2539
+ lspProcess.stderr.off("data", onStderr);
2540
+ }
2541
+ if (initResult === undefined) {
2542
+ const compactStderr = startupState.stderr.replace(/\s+/g, " ").trim().slice(0, 320);
2543
+ const reinstallHint = serverId === "cpp" ? "Install clangd (LLVM/clang-tools) and ensure clangd.exe is on PATH." : `Try reinstalling: npm install -g ${serverId}-language-server.`;
2544
+ const telemetry = [
2545
+ `pid=${lspProcess.pid}`,
2546
+ `exitCode=${startupState.exitCode ?? "none"}`,
2547
+ `exitSignal=${startupState.exitSignal ?? "none"}`,
2548
+ `closeCode=${startupState.closeCode ?? "none"}`,
2549
+ `closeSignal=${startupState.closeSignal ?? "none"}`,
2550
+ `root=${root}`,
2551
+ compactStderr ? `stderr=${compactStderr}` : "stderr=<empty>"
2552
+ ].join(" ");
2553
+ throw new Error(`[lsp] ${serverId} failed to initialize - stream may have been destroyed. ` + `The server binary may be missing or crashed immediately. ${reinstallHint} ` + `telemetry: ${telemetry}`);
2554
+ }
2555
+ state.workspaceDiagnosticsSupport = detectWorkspaceDiagnosticsSupport(initResult);
2556
+ state.operationSupport = detectOperationSupport(initResult);
2557
+ const capabilities = initResult?.capabilities ?? {};
2558
+ const workspace = isCapabilityRecord(capabilities.workspace) ? capabilities.workspace : undefined;
2559
+ const fileOperations = isCapabilityRecord(workspace) ? workspace.fileOperations : undefined;
2560
+ const malformedFileOperationRegistrations = new Set;
2561
+ if (isCapabilityRecord(fileOperations)) {
2562
+ for (const operation of ["didCreate", "willRename", "didRename"]) {
2563
+ if (fileOperations[operation] !== undefined && parseFileOperationFilters(fileOperations[operation]) === undefined) {
2564
+ malformedFileOperationRegistrations.add(operation);
2565
+ }
2566
+ }
2567
+ }
2568
+ state.fileOperationMalformedRegistrations = malformedFileOperationRegistrations;
2569
+ if (isCapabilityRecord(fileOperations)) {
2570
+ state.fileOperationFilters = {
2571
+ didCreate: parseFileOperationFilters(fileOperations.didCreate),
2572
+ willRename: parseFileOperationFilters(fileOperations.willRename),
2573
+ didRename: parseFileOperationFilters(fileOperations.didRename)
2574
+ };
2575
+ }
2576
+ state.positionEncoding = negotiatePositionEncoding(initResult?.capabilities);
2577
+ state.syncKind = negotiateSyncKind(initResult?.capabilities);
2578
+ state.saveOptions = negotiateSaveOptions(initResult?.capabilities);
2579
+ state.rawCapabilityKeys = Object.keys(initResult?.capabilities ?? {}).sort((a, b) => a.localeCompare(b));
2580
+ for (const cmd of detectExecuteCommands(initResult)) {
2581
+ state.advertisedCommands.add(cmd);
2582
+ }
2583
+ state.staticDiagnosticsMode = state.workspaceDiagnosticsSupport.mode;
2584
+ await safeSendNotification(connection, "initialized", {});
2585
+ if (settings) {
2586
+ await safeSendNotification(connection, "workspace/didChangeConfiguration", {
2587
+ settings
2588
+ });
2589
+ }
2590
+ return {
2591
+ serverId,
2592
+ root,
2593
+ connection,
2594
+ isAlive: () => isClientAlive(state),
2595
+ processExited: () => lspProcess.process.exitCode !== null || lspProcess.process.killed === true,
2596
+ wasShutdownIntentional: () => state.shutdownRequested,
2597
+ getExitedAt: () => state.exitedAt,
2598
+ recentStderr: (lines) => recentStderr(lines),
2599
+ getPullFailureHistory: () => state.pullFailureHistory.map((entry) => ({
2600
+ ...entry,
2601
+ message: entry.message.slice(0, 200)
2602
+ })),
2603
+ checkAlive: () => checkProcessAlive(),
2604
+ pingLiveness: (timeoutMs) => clientPingLiveness(state, timeoutMs),
2605
+ getProcessPid: () => lspProcess.pid,
2606
+ notify: {
2607
+ async open(filePath, content, languageId, preserveDiagnostics, silent, saved, readStamp, contentHash) {
2608
+ return handleNotifyOpen(state, filePath, content, languageId, preserveDiagnostics, silent, saved, readStamp, contentHash);
2609
+ },
2610
+ async change(filePath, content, contentHash) {
2611
+ return handleNotifyChange(state, filePath, content, contentHash);
2612
+ },
2613
+ save(filePath, onlyIfOwed) {
2614
+ return handleNotifySave(state, filePath, onlyIfOwed);
2615
+ },
2616
+ watchedFileChange(filePath, type) {
2617
+ handleNotifyExternalChange(state, filePath, type);
2618
+ },
2619
+ flushWatched() {
2620
+ if (isClientAlive(state))
2621
+ state.watchQueue.flush();
2622
+ },
2623
+ announceCreated(entries) {
2624
+ handleAnnounceCreated(state, entries).catch((cause) => {
2625
+ incrementDegradationCount({
2626
+ kind: "lsp-sibling-announcement",
2627
+ subject: `${state.serverId}:workspace/didCreateFiles`,
2628
+ reason: `didCreateFiles failed: ${String(cause)}`
2629
+ });
2630
+ });
2631
+ }
2632
+ },
2633
+ getDiagnostics(filePath) {
2634
+ return getMergedDiagnosticsForPath(state, normalizeMapKey(filePath));
2635
+ },
2636
+ getConfigLoadFailure() {
2637
+ return state.configLoadFailure?.message;
2638
+ },
2639
+ getDiagnosticBinding(filePath) {
2640
+ return state.diagnosticBindings.get(normalizeMapKey(filePath));
2641
+ },
2642
+ getDiagnosticsVersionForPath(filePath) {
2643
+ return diagnosticsVersionForPath(state, normalizeMapKey(filePath));
2644
+ },
2645
+ getPublicationCountsForPath(filePath) {
2646
+ return publicationCountsForPath(state, normalizeMapKey(filePath));
2647
+ },
2648
+ getAllDiagnostics() {
2649
+ const result = new Map;
2650
+ const keys = new Set([
2651
+ ...state.pushDiagnostics.keys(),
2652
+ ...state.documentPullDiagnostics.keys()
2653
+ ]);
2654
+ for (const key of keys) {
2655
+ result.set(key, {
2656
+ diags: getMergedDiagnosticsForPath(state, key),
2657
+ ts: Math.max(state.pushDiagnosticTimestamps.get(key) ?? 0, state.documentPullDiagnosticTimestamps.get(key) ?? 0),
2658
+ binding: state.diagnosticBindings.get(key)
2659
+ });
2660
+ }
2661
+ return result;
2662
+ },
2663
+ getTrackedDiagnosticPaths() {
2664
+ return [
2665
+ ...new Set([
2666
+ ...state.pushDiagnostics.keys(),
2667
+ ...state.documentPullDiagnostics.keys()
2668
+ ])
2669
+ ].map((filePath) => process.platform === "win32" ? filePath.replace(/\//g, "\\") : filePath);
2670
+ },
2671
+ pruneDiagnostics(predicate) {
2672
+ let removed = 0;
2673
+ const keys = new Set([
2674
+ ...state.pushDiagnostics.keys(),
2675
+ ...state.documentPullDiagnostics.keys()
2676
+ ]);
2677
+ for (const key of keys) {
2678
+ const diags = getMergedDiagnosticsForPath(state, key);
2679
+ const ts = Math.max(state.pushDiagnosticTimestamps.get(key) ?? 0, state.documentPullDiagnosticTimestamps.get(key) ?? 0);
2680
+ if (!predicate(key, ts, diags))
2681
+ continue;
2682
+ clearDiagnosticsForPath(state, key);
2683
+ removed++;
2684
+ }
2685
+ return removed;
2686
+ },
2687
+ getWorkspaceDiagnosticsSupport() {
2688
+ return state.workspaceDiagnosticsSupport;
2689
+ },
2690
+ requestWorkspaceDiagnostics(budgetMs) {
2691
+ return clientRequestWorkspaceDiagnostics(state, budgetMs);
2692
+ },
2693
+ getOperationSupport() {
2694
+ return state.operationSupport;
2695
+ },
2696
+ getMalformedFileOperationRegistrations() {
2697
+ return state.fileOperationMalformedRegistrations ?? new Set;
2698
+ },
2699
+ getAdvertisedCommands() {
2700
+ return [...state.advertisedCommands];
2701
+ },
2702
+ getRawCapabilityKeys() {
2703
+ return state.rawCapabilityKeys ?? [];
2704
+ },
2705
+ getSaveOptions() {
2706
+ return state.saveOptions ? { ...state.saveOptions } : undefined;
2707
+ },
2708
+ getLaunchVariant() {
2709
+ return state.launchVariant;
2710
+ },
2711
+ async executeCommand(command, args, mutationContext) {
2712
+ return runServerCommand(state, command, args, EXECUTE_COMMAND_TIMEOUT_MS, mutationContext);
2713
+ },
2714
+ async executeReadOnlyCommand(command, args) {
2715
+ return runReadOnlyServerCommand(state, command, args);
2716
+ },
2717
+ get diagnosticsVersion() {
2718
+ return state.diagnosticsVersion;
2719
+ },
2720
+ async waitForDiagnostics(filePath, timeoutMs = DIAGNOSTICS_WAIT_TIMEOUT_MS, options) {
2721
+ return clientWaitForDiagnostics(state, filePath, timeoutMs, options);
2722
+ },
2723
+ async definition(filePath, line, character) {
2724
+ const result = await navRequest(state, "textDocument/definition", {
2725
+ textDocument: { uri: pathToFileURL(filePath).href },
2726
+ position: await toWirePosition(state, filePath, line, character)
2727
+ }, filePath);
2728
+ if (!result)
2729
+ return [];
2730
+ return Array.isArray(result) ? result : [result];
2731
+ },
2732
+ async typeDefinition(filePath, line, character) {
2733
+ const result = await navRequest(state, "textDocument/typeDefinition", {
2734
+ textDocument: { uri: pathToFileURL(filePath).href },
2735
+ position: await toWirePosition(state, filePath, line, character)
2736
+ }, filePath);
2737
+ if (!result)
2738
+ return [];
2739
+ return Array.isArray(result) ? result : [result];
2740
+ },
2741
+ async declaration(filePath, line, character) {
2742
+ const result = await navRequest(state, "textDocument/declaration", {
2743
+ textDocument: { uri: pathToFileURL(filePath).href },
2744
+ position: await toWirePosition(state, filePath, line, character)
2745
+ }, filePath);
2746
+ if (!result)
2747
+ return [];
2748
+ return Array.isArray(result) ? result : [result];
2749
+ },
2750
+ async references(filePath, line, character, includeDeclaration = true) {
2751
+ const result = await navRequest(state, "textDocument/references", {
2752
+ textDocument: { uri: pathToFileURL(filePath).href },
2753
+ position: await toWirePosition(state, filePath, line, character),
2754
+ context: { includeDeclaration }
2755
+ }, filePath);
2756
+ return result ?? [];
2757
+ },
2758
+ async hover(filePath, line, character) {
2759
+ const result = await navRequest(state, "textDocument/hover", {
2760
+ textDocument: { uri: pathToFileURL(filePath).href },
2761
+ position: await toWirePosition(state, filePath, line, character)
2762
+ }, filePath);
2763
+ return result ?? null;
2764
+ },
2765
+ async signatureHelp(filePath, line, character) {
2766
+ const result = await navRequest(state, "textDocument/signatureHelp", {
2767
+ textDocument: { uri: pathToFileURL(filePath).href },
2768
+ position: await toWirePosition(state, filePath, line, character)
2769
+ }, filePath);
2770
+ return result ?? null;
2771
+ },
2772
+ async documentSymbol(filePath) {
2773
+ const result = await navRequest(state, "textDocument/documentSymbol", { textDocument: { uri: pathToFileURL(filePath).href } }, filePath);
2774
+ return result ?? [];
2775
+ },
2776
+ isDocumentOpen(filePath) {
2777
+ return state.openDocuments.has(normalizeMapKey(filePath));
2778
+ },
2779
+ openDocumentPaths() {
2780
+ return [...state.openDocuments];
2781
+ },
2782
+ getSentContent(filePath) {
2783
+ return sentContentFor(state, filePath);
2784
+ },
2785
+ hasNotifyInFlight(filePath) {
2786
+ return hasNotifyInFlightFor(state, filePath);
2787
+ },
2788
+ isBusy() {
2789
+ return isConnectionBusy(connection);
2790
+ },
2791
+ getDocumentUri(filePath) {
2792
+ return state.openDocumentUris?.get(normalizeMapKey(filePath));
2793
+ },
2794
+ async workspaceSymbol(query) {
2795
+ if (!isClientAlive(state))
2796
+ return [];
2797
+ const result = await navRequest(state, "workspace/symbol", {
2798
+ query
2799
+ });
2800
+ return result ?? [];
2801
+ },
2802
+ async codeAction(filePath, line, character, endLine, endCharacter) {
2803
+ if (!isClientAlive(state))
2804
+ return [];
2805
+ const uri = pathToFileURL(filePath).href;
2806
+ const result = await navRequest(state, "textDocument/codeAction", {
2807
+ textDocument: { uri },
2808
+ range: {
2809
+ start: await toWirePosition(state, filePath, line, character),
2810
+ end: await toWirePosition(state, filePath, endLine, endCharacter)
2811
+ },
2812
+ context: {
2813
+ diagnostics: getMergedDiagnosticsForPath(state, normalizeMapKey(filePath))
2814
+ }
2815
+ }, filePath);
2816
+ if (!result || !Array.isArray(result))
2817
+ return [];
2818
+ const actions = result.filter((item) => typeof item === "object" && item !== null && ("title" in item));
2819
+ return Promise.all(actions.map((action) => resolveCodeActionBestEffort(state, action)));
2820
+ },
2821
+ async rename(filePath, line, character, newName) {
2822
+ const result = await navRequest(state, "textDocument/rename", {
2823
+ textDocument: { uri: pathToFileURL(filePath).href },
2824
+ position: await toWirePosition(state, filePath, line, character),
2825
+ newName
2826
+ }, filePath);
2827
+ return result ? await normalizeClientWorkspaceEdit(state, result) : null;
2828
+ },
2829
+ closeDocument: (filePath) => closeDocument(state, filePath),
2830
+ async willRenameFiles(oldFilePath, newFilePath) {
2831
+ if (!isClientAlive(state))
2832
+ return null;
2833
+ const oldUri = pathToFileURL(oldFilePath).href;
2834
+ const newUri = pathToFileURL(newFilePath).href;
2835
+ if (!await fileOperationFiltersMatch(state.fileOperationFilters?.willRename, oldUri, newUri, oldFilePath, newFilePath)) {
2836
+ recordDegradationOnce({
2837
+ kind: "lsp-capability-skip",
2838
+ subject: `${state.serverId}:workspace/willRenameFiles:filter`,
2839
+ reason: "filter-mismatch"
2840
+ });
2841
+ return null;
2842
+ }
2843
+ const result = await navRequest(state, "workspace/willRenameFiles", {
2844
+ files: [
2845
+ {
2846
+ oldUri,
2847
+ newUri
2848
+ }
2849
+ ]
2850
+ });
2851
+ return result ? await normalizeClientWorkspaceEdit(state, result) : null;
2852
+ },
2853
+ async didRenameFiles(oldFilePath, newFilePath, oldUri, newUri) {
2854
+ if (!isClientAlive(state))
2855
+ return;
2856
+ const wireOldUri = oldUri ?? pathToFileURL(oldFilePath).href;
2857
+ const wireNewUri = newUri ?? pathToFileURL(newFilePath).href;
2858
+ if (!await fileOperationFiltersMatch(state.fileOperationFilters?.didRename, wireOldUri, wireNewUri, oldFilePath, newFilePath)) {
2859
+ recordDegradationOnce({
2860
+ kind: "lsp-capability-skip",
2861
+ subject: `${state.serverId}:workspace/didRenameFiles:filter`,
2862
+ reason: "filter-mismatch"
2863
+ });
2864
+ return;
2865
+ }
2866
+ await safeSendNotification(state.connection, "workspace/didRenameFiles", {
2867
+ files: [
2868
+ {
2869
+ oldUri: wireOldUri,
2870
+ newUri: wireNewUri
2871
+ }
2872
+ ]
2873
+ });
2874
+ },
2875
+ async implementation(filePath, line, character) {
2876
+ const result = await navRequest(state, "textDocument/implementation", {
2877
+ textDocument: { uri: pathToFileURL(filePath).href },
2878
+ position: await toWirePosition(state, filePath, line, character)
2879
+ }, filePath);
2880
+ if (!result)
2881
+ return [];
2882
+ return Array.isArray(result) ? result : [result];
2883
+ },
2884
+ async prepareCallHierarchy(filePath, line, character) {
2885
+ const result = await navRequest(state, "textDocument/prepareCallHierarchy", {
2886
+ textDocument: { uri: pathToFileURL(filePath).href },
2887
+ position: await toWirePosition(state, filePath, line, character)
2888
+ }, filePath);
2889
+ if (!result)
2890
+ return [];
2891
+ return Array.isArray(result) ? result : [result];
2892
+ },
2893
+ async incomingCalls(item) {
2894
+ const result = await navRequest(state, "callHierarchy/incomingCalls", { item });
2895
+ return result ?? [];
2896
+ },
2897
+ async outgoingCalls(item) {
2898
+ const result = await navRequest(state, "callHierarchy/outgoingCalls", { item });
2899
+ return result ?? [];
2900
+ },
2901
+ async shutdown(options) {
2902
+ return clientShutdown(state, options);
2903
+ }
2904
+ };
2905
+ }
2906
+ function sendFenced(state, normalizedPath, uri, method, params) {
2907
+ const sent = safeSendNotification(state.connection, method, params);
2908
+ armDiagnosticsFence(state, normalizedPath, uri);
2909
+ return sent;
2910
+ }
2911
+ function armDiagnosticsFence(state, normalizedPath, uri) {
2912
+ if (getStrategy(state.serverId, state.launchVariant).diagnosticsFence !== "reply-first") {
2913
+ return;
2914
+ }
2915
+ if (state.operationSupport?.documentSymbol !== true) {
2916
+ if (!state.fenceSkipRecorded) {
2917
+ state.fenceSkipRecorded = true;
2918
+ logLatency({
2919
+ type: "phase",
2920
+ phase: "lsp_diagnostics_fence",
2921
+ filePath: normalizedPath,
2922
+ durationMs: 0,
2923
+ metadata: { serverId: state.serverId, outcome: "no-request" }
2924
+ });
2925
+ }
2926
+ return;
2927
+ }
2928
+ const armedAt = Date.now();
2929
+ const cancellation = new CancellationTokenSource;
2930
+ const end = (outcome) => {
2931
+ if (ended)
2932
+ return;
2933
+ ended = true;
2934
+ clearTimeout(bound);
2935
+ state.diagnosticFences.delete(normalizedPath);
2936
+ cancellation.cancel();
2937
+ cancellation.dispose();
2938
+ if (outcome === "timeout" || fence.dropped > 0) {
2939
+ logLatency({
2940
+ type: "phase",
2941
+ phase: "lsp_diagnostics_fence",
2942
+ filePath: normalizedPath,
2943
+ durationMs: Date.now() - armedAt,
2944
+ metadata: {
2945
+ serverId: state.serverId,
2946
+ outcome,
2947
+ droppedPublishes: fence.dropped
2948
+ }
2949
+ });
2950
+ }
2951
+ };
2952
+ let ended = false;
2953
+ const fence = {
2954
+ dropped: 0,
2955
+ supersede: () => end("superseded")
2956
+ };
2957
+ state.diagnosticFences.get(normalizedPath)?.supersede();
2958
+ state.diagnosticFences.set(normalizedPath, fence);
2959
+ const bound = setTimeout(() => end("timeout"), DIAGNOSTICS_WAIT_TIMEOUT_MS);
2960
+ bound.unref?.();
2961
+ let reply;
2962
+ try {
2963
+ reply = Promise.resolve(state.connection.sendRequest("textDocument/documentSymbol", { textDocument: { uri } }, cancellation.token));
2964
+ } catch (thrown) {
2965
+ reply = Promise.reject(thrown);
2966
+ }
2967
+ reply.then(() => end("reply"), () => end("reply"));
2968
+ }
2969
+ async function safeSendNotification(connection, method, params) {
2970
+ try {
2971
+ await connection.sendNotification(method, params);
2972
+ return true;
2973
+ } catch (err) {
2974
+ if (isStreamError(err)) {
2975
+ return false;
2976
+ }
2977
+ throw err;
2978
+ }
2979
+ }
2980
+ const activeRequestsByConnection = new WeakMap;
2981
+ const RELEASED_ON_ABORT = Symbol("released-on-abort");
2982
+ export function isConnectionBusy(connection) {
2983
+ return (activeRequestsByConnection.get(connection) ?? 0) > 0;
2984
+ }
2985
+ async function safeSendRequest(connection, method, params, signal, settlement, releaseOnAbort = false) {
2986
+ if (signal?.aborted)
2987
+ return;
2988
+ let tokenSource;
2989
+ let onAbort;
2990
+ let released;
2991
+ let release;
2992
+ if (signal) {
2993
+ tokenSource = new CancellationTokenSource;
2994
+ if (releaseOnAbort) {
2995
+ released = new Promise((resolve) => {
2996
+ release = () => resolve(RELEASED_ON_ABORT);
2997
+ });
2998
+ }
2999
+ onAbort = () => {
3000
+ tokenSource?.cancel();
3001
+ release?.();
3002
+ };
3003
+ signal.addEventListener("abort", onAbort, { once: true });
3004
+ }
3005
+ const send = () => tokenSource ? connection.sendRequest(method, params, tokenSource.token) : connection.sendRequest(method, params);
3006
+ activeRequestsByConnection.set(connection, (activeRequestsByConnection.get(connection) ?? 0) + 1);
3007
+ try {
3008
+ const MAX_ATTEMPTS = 2;
3009
+ for (let attempt = 1;; attempt++) {
3010
+ try {
3011
+ if (!released)
3012
+ return await send();
3013
+ const reply = await Promise.race([send(), released]);
3014
+ if (reply === RELEASED_ON_ABORT)
3015
+ return;
3016
+ return reply;
3017
+ } catch (err) {
3018
+ if (isCancellationError(err)) {
3019
+ if (settlement)
3020
+ settlement.cancelled = true;
3021
+ return;
3022
+ }
3023
+ if (isStreamError(err)) {
3024
+ return;
3025
+ }
3026
+ if (isContentModifiedError(err)) {
3027
+ if (attempt < MAX_ATTEMPTS && !signal?.aborted)
3028
+ continue;
3029
+ return;
3030
+ }
3031
+ throw err;
3032
+ }
3033
+ }
3034
+ } finally {
3035
+ const remaining = (activeRequestsByConnection.get(connection) ?? 1) - 1;
3036
+ if (remaining > 0)
3037
+ activeRequestsByConnection.set(connection, remaining);
3038
+ else
3039
+ activeRequestsByConnection.delete(connection);
3040
+ if (signal && onAbort)
3041
+ signal.removeEventListener("abort", onAbort);
3042
+ tokenSource?.dispose();
3043
+ }
3044
+ }
3045
+ function isCancellationError(err) {
3046
+ const code = err?.code;
3047
+ return code === -32800 || code === -32802;
3048
+ }
3049
+ function isContentModifiedError(err) {
3050
+ return err?.code === -32801;
3051
+ }
3052
+ function isStreamError(err) {
3053
+ if (!(err instanceof Error))
3054
+ return false;
3055
+ const msg = err.message.toLowerCase();
3056
+ return msg.includes("stream") || msg.includes("destroyed") || msg.includes("closed") || msg.includes("disposed") || msg.includes("cancelled") || err.code === "ERR_STREAM_DESTROYED" || err.code === "ERR_STREAM_WRITE_AFTER_END" || err.code === "EPIPE";
3057
+ }
3058
+ function positiveIntFromEnv(name, fallback) {
3059
+ const raw = process.env[name];
3060
+ if (!raw)
3061
+ return fallback;
3062
+ const parsed = Number.parseInt(raw, 10);
3063
+ if (!Number.isFinite(parsed) || parsed <= 0)
3064
+ return fallback;
3065
+ return parsed;
3066
+ }
3067
+ function detectWorkspaceDiagnosticsSupport(initResult) {
3068
+ const capabilities = typeof initResult === "object" && initResult !== null ? initResult.capabilities : undefined;
3069
+ const diagnosticProvider = capabilities?.diagnosticProvider;
3070
+ if (!diagnosticProvider) {
3071
+ return {
3072
+ advertised: false,
3073
+ mode: "push-only",
3074
+ workspaceDiagnostics: false,
3075
+ diagnosticProviderKind: "none"
3076
+ };
3077
+ }
3078
+ if (typeof diagnosticProvider === "boolean") {
3079
+ return {
3080
+ advertised: diagnosticProvider,
3081
+ mode: diagnosticProvider ? "pull" : "push-only",
3082
+ workspaceDiagnostics: false,
3083
+ diagnosticProviderKind: "boolean"
3084
+ };
3085
+ }
3086
+ if (typeof diagnosticProvider === "object") {
3087
+ return {
3088
+ advertised: true,
3089
+ mode: "pull",
3090
+ workspaceDiagnostics: diagnosticProvider.workspaceDiagnostics === true,
3091
+ diagnosticProviderKind: "object"
3092
+ };
3093
+ }
3094
+ return {
3095
+ advertised: false,
3096
+ mode: "push-only",
3097
+ workspaceDiagnostics: false,
3098
+ diagnosticProviderKind: typeof diagnosticProvider
3099
+ };
3100
+ }
3101
+ function detectExecuteCommands(initResult) {
3102
+ const capabilities = typeof initResult === "object" && initResult !== null ? initResult.capabilities : undefined;
3103
+ const provider = capabilities?.executeCommandProvider;
3104
+ if (typeof provider !== "object" || provider === null)
3105
+ return [];
3106
+ const commands = provider.commands;
3107
+ if (!Array.isArray(commands))
3108
+ return [];
3109
+ return commands.filter((cmd) => typeof cmd === "string");
3110
+ }
3111
+ function detectOperationSupport(initResult) {
3112
+ const capabilities = typeof initResult === "object" && initResult !== null ? initResult.capabilities : undefined;
3113
+ const hasProvider = (key) => {
3114
+ const value = capabilities?.[key];
3115
+ if (value === undefined || value === null)
3116
+ return false;
3117
+ if (typeof value === "boolean")
3118
+ return value;
3119
+ return isCapabilityRecord(value);
3120
+ };
3121
+ const codeActionProvider = capabilities?.codeActionProvider;
3122
+ const workspace = capabilities?.workspace;
3123
+ const fileOperations = isCapabilityRecord(workspace) ? workspace.fileOperations : undefined;
3124
+ return {
3125
+ definition: hasProvider("definitionProvider"),
3126
+ typeDefinition: hasProvider("typeDefinitionProvider"),
3127
+ declaration: hasProvider("declarationProvider"),
3128
+ references: hasProvider("referencesProvider"),
3129
+ hover: hasProvider("hoverProvider"),
3130
+ signatureHelp: hasProvider("signatureHelpProvider"),
3131
+ documentSymbol: hasProvider("documentSymbolProvider"),
3132
+ workspaceSymbol: hasProvider("workspaceSymbolProvider"),
3133
+ codeAction: hasProvider("codeActionProvider"),
3134
+ codeActionResolve: isCapabilityRecord(codeActionProvider) && codeActionProvider.resolveProvider === true,
3135
+ rename: hasProvider("renameProvider"),
3136
+ willRenameFiles: isCapabilityRecord(fileOperations) && isFileOperationRegistrationOptions(fileOperations.willRename),
3137
+ didRenameFiles: isCapabilityRecord(fileOperations) && isFileOperationRegistrationOptions(fileOperations.didRename),
3138
+ didCreateFiles: isCapabilityRecord(fileOperations) && isFileOperationRegistrationOptions(fileOperations.didCreate),
3139
+ implementation: hasProvider("implementationProvider"),
3140
+ callHierarchy: hasProvider("callHierarchyProvider")
3141
+ };
3142
+ }
3143
+ function isCapabilityRecord(value) {
3144
+ return typeof value === "object" && value !== null && !Array.isArray(value);
3145
+ }
3146
+ function isFileOperationRegistrationOptions(value) {
3147
+ return parseFileOperationFilters(value) !== undefined;
3148
+ }
3149
+ function parseFileOperationFilters(value) {
3150
+ if (!isCapabilityRecord(value) || !Array.isArray(value.filters)) {
3151
+ return;
3152
+ }
3153
+ const filters = [];
3154
+ for (const entry of value.filters) {
3155
+ if (!isCapabilityRecord(entry))
3156
+ return;
3157
+ const pattern = entry.pattern;
3158
+ if (!isCapabilityRecord(pattern) || typeof pattern.glob !== "string" || pattern.glob.trim() === "") {
3159
+ return;
3160
+ }
3161
+ if (entry.scheme !== undefined && (typeof entry.scheme !== "string" || entry.scheme.trim() === "" || !/^[A-Za-z][A-Za-z0-9+.-]*$/.test(entry.scheme))) {
3162
+ return;
3163
+ }
3164
+ const matches = pattern.matches;
3165
+ if (matches !== undefined && matches !== "file" && matches !== "folder") {
3166
+ return;
3167
+ }
3168
+ if (pattern.options !== undefined && !isCapabilityRecord(pattern.options)) {
3169
+ return;
3170
+ }
3171
+ const options = isCapabilityRecord(pattern.options) ? pattern.options : undefined;
3172
+ if (options?.ignoreCase !== undefined && typeof options.ignoreCase !== "boolean") {
3173
+ return;
3174
+ }
3175
+ filters.push({
3176
+ scheme: entry.scheme?.toLowerCase(),
3177
+ glob: pattern.glob,
3178
+ matches: matches === "file" || matches === "folder" ? matches : undefined,
3179
+ ignoreCase: options?.ignoreCase === true
3180
+ });
3181
+ }
3182
+ return filters;
3183
+ }
3184
+ async function fileOperationFiltersMatch(filters, oldUri, newUri, oldFilePath, newFilePath) {
3185
+ if (!filters || filters.length === 0)
3186
+ return false;
3187
+ const candidates = [oldUri, newUri].flatMap(fileOperationUriCandidates);
3188
+ const entityKind = filters.some((filter) => filter.matches !== undefined) ? await probeRenameEntityKind(oldFilePath, newFilePath) : undefined;
3189
+ for (const filter of filters) {
3190
+ if (filter.scheme !== undefined && filter.scheme !== "file")
3191
+ continue;
3192
+ if (filter.matches !== undefined && filter.matches !== entityKind)
3193
+ continue;
3194
+ for (const candidate of candidates) {
3195
+ try {
3196
+ if (minimatch(candidate, filter.glob, {
3197
+ nocase: filter.ignoreCase,
3198
+ dot: true
3199
+ })) {
3200
+ return true;
3201
+ }
3202
+ } catch {}
3203
+ }
3204
+ }
3205
+ return false;
3206
+ }
3207
+ function fileOperationUriCandidates(uri) {
3208
+ let parsed;
3209
+ try {
3210
+ parsed = new URL(uri);
3211
+ } catch {
3212
+ return [];
3213
+ }
3214
+ if (parsed.protocol.toLowerCase() !== "file:")
3215
+ return [];
3216
+ let uriPath;
3217
+ try {
3218
+ uriPath = decodeURIComponent(parsed.pathname).replace(/\\/g, "/");
3219
+ } catch {
3220
+ return [];
3221
+ }
3222
+ return [uriPath];
3223
+ }
3224
+ async function probeRenameEntityKind(oldFilePath, newFilePath) {
3225
+ for (const filePath of [oldFilePath, newFilePath]) {
3226
+ try {
3227
+ const info = await lstat(filePath);
3228
+ return info.isDirectory() ? "folder" : "file";
3229
+ } catch {}
3230
+ }
3231
+ return;
3232
+ }