@mrclrchtr/supi-code-intelligence 11.3.0 → 12.0.0

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 (132) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/README.md +15 -9
  3. package/node_modules/@mrclrchtr/supi-code-runtime/package.json +1 -1
  4. package/node_modules/@mrclrchtr/supi-code-runtime/src/api.ts +3 -1
  5. package/node_modules/@mrclrchtr/supi-code-runtime/src/declaration-level.ts +34 -0
  6. package/node_modules/@mrclrchtr/supi-code-runtime/src/types.ts +64 -28
  7. package/node_modules/@mrclrchtr/supi-core/package.json +1 -1
  8. package/node_modules/@mrclrchtr/supi-lsp/README.md +22 -17
  9. package/node_modules/@mrclrchtr/supi-lsp/node_modules/@mrclrchtr/supi-code-runtime/package.json +1 -1
  10. package/node_modules/@mrclrchtr/supi-lsp/node_modules/@mrclrchtr/supi-code-runtime/src/api.ts +3 -1
  11. package/node_modules/@mrclrchtr/supi-lsp/node_modules/@mrclrchtr/supi-code-runtime/src/declaration-level.ts +34 -0
  12. package/node_modules/@mrclrchtr/supi-lsp/node_modules/@mrclrchtr/supi-code-runtime/src/types.ts +64 -28
  13. package/node_modules/@mrclrchtr/supi-lsp/node_modules/@mrclrchtr/supi-core/package.json +1 -1
  14. package/node_modules/@mrclrchtr/supi-lsp/node_modules/semver/classes/range.js +2 -2
  15. package/node_modules/@mrclrchtr/supi-lsp/node_modules/semver/internal/constants.js +30 -0
  16. package/node_modules/@mrclrchtr/supi-lsp/node_modules/semver/internal/trim-comparator-whitespace.js +438 -0
  17. package/node_modules/@mrclrchtr/supi-lsp/node_modules/semver/package.json +1 -1
  18. package/node_modules/@mrclrchtr/supi-lsp/package.json +3 -3
  19. package/node_modules/@mrclrchtr/supi-lsp/src/api.ts +2 -2
  20. package/node_modules/@mrclrchtr/supi-lsp/src/client/client-diagnostic-capabilities.ts +13 -3
  21. package/node_modules/@mrclrchtr/supi-lsp/src/client/client-diagnostics.ts +25 -9
  22. package/node_modules/@mrclrchtr/supi-lsp/src/client/client-document-sync.ts +7 -5
  23. package/node_modules/@mrclrchtr/supi-lsp/src/client/client-edit-capture.ts +258 -0
  24. package/node_modules/@mrclrchtr/supi-lsp/src/client/client.ts +64 -11
  25. package/node_modules/@mrclrchtr/supi-lsp/src/config/capabilities.ts +8 -0
  26. package/node_modules/@mrclrchtr/supi-lsp/src/config/operation-support.ts +48 -79
  27. package/node_modules/@mrclrchtr/supi-lsp/src/config/tsconfig-scope.ts +10 -0
  28. package/node_modules/@mrclrchtr/supi-lsp/src/manager/manager-typescript-coverage.ts +118 -0
  29. package/node_modules/@mrclrchtr/supi-lsp/src/manager/manager.ts +67 -3
  30. package/node_modules/@mrclrchtr/supi-lsp/src/manager/typescript-file-local.ts +87 -0
  31. package/node_modules/@mrclrchtr/supi-lsp/src/provider/lsp-refactor-provider.ts +21 -35
  32. package/node_modules/@mrclrchtr/supi-lsp/src/provider/refactor-command-capture.ts +139 -0
  33. package/node_modules/@mrclrchtr/supi-lsp/src/provider/refactor-planning.ts +202 -47
  34. package/node_modules/@mrclrchtr/supi-lsp/src/provider/semantic-symbol-mapper.ts +22 -17
  35. package/node_modules/@mrclrchtr/supi-lsp/src/session/route-boundary.ts +26 -0
  36. package/node_modules/@mrclrchtr/supi-lsp/src/session/runtime-registry.ts +106 -16
  37. package/node_modules/@mrclrchtr/supi-lsp/src/session/runtime-rename.ts +3 -0
  38. package/node_modules/@mrclrchtr/supi-lsp/src/session/workspace-lsp-runtime.ts +22 -1
  39. package/node_modules/@mrclrchtr/supi-tree-sitter/README.md +1 -1
  40. package/node_modules/@mrclrchtr/supi-tree-sitter/node_modules/@mrclrchtr/supi-code-runtime/package.json +1 -1
  41. package/node_modules/@mrclrchtr/supi-tree-sitter/node_modules/@mrclrchtr/supi-code-runtime/src/api.ts +3 -1
  42. package/node_modules/@mrclrchtr/supi-tree-sitter/node_modules/@mrclrchtr/supi-code-runtime/src/declaration-level.ts +34 -0
  43. package/node_modules/@mrclrchtr/supi-tree-sitter/node_modules/@mrclrchtr/supi-code-runtime/src/types.ts +64 -28
  44. package/node_modules/@mrclrchtr/supi-tree-sitter/node_modules/@mrclrchtr/supi-core/package.json +1 -1
  45. package/node_modules/@mrclrchtr/supi-tree-sitter/package.json +3 -3
  46. package/node_modules/@mrclrchtr/supi-tree-sitter/resources/grammars/tsx/tree-sitter-tsx.wasm +0 -0
  47. package/node_modules/@mrclrchtr/supi-tree-sitter/resources/grammars/tsx/tree-sitter-tsx.wasm.json +5 -1
  48. package/node_modules/@mrclrchtr/supi-tree-sitter/resources/grammars/typescript/tree-sitter-typescript.wasm +0 -0
  49. package/node_modules/@mrclrchtr/supi-tree-sitter/resources/grammars/typescript/tree-sitter-typescript.wasm.json +5 -1
  50. package/node_modules/@mrclrchtr/supi-tree-sitter/src/coordinates.ts +16 -2
  51. package/node_modules/@mrclrchtr/supi-tree-sitter/src/session/structural-worker-client.ts +3 -2
  52. package/node_modules/@mrclrchtr/supi-tree-sitter/src/syntax-errors.ts +2 -0
  53. package/node_modules/@mrclrchtr/supi-tree-sitter/src/tool/call-range.ts +94 -0
  54. package/node_modules/@mrclrchtr/supi-tree-sitter/src/tool/call-sites.ts +26 -6
  55. package/node_modules/@mrclrchtr/supi-tree-sitter/src/tool/callees.ts +6 -3
  56. package/node_modules/@mrclrchtr/supi-tree-sitter/src/tool/exports.ts +13 -4
  57. package/node_modules/@mrclrchtr/supi-tree-sitter/src/worker/runtime.ts +1 -9
  58. package/package.json +5 -5
  59. package/src/analysis/health/server-status.ts +41 -12
  60. package/src/analysis/helpers.ts +0 -7
  61. package/src/analysis/relations/implementations.ts +5 -0
  62. package/src/analysis/relations/references.ts +5 -0
  63. package/src/analysis/target/anchored-structural.ts +4 -1
  64. package/src/analysis/target/file-merge.ts +162 -0
  65. package/src/analysis/target/file-outline-omissions.ts +146 -0
  66. package/src/analysis/target/file-refinement.ts +7 -7
  67. package/src/analysis/target/file.ts +44 -156
  68. package/src/analysis/target/symbol.ts +5 -1
  69. package/src/analysis/target/types.ts +32 -6
  70. package/src/api.ts +1 -1
  71. package/src/app/app.ts +9 -3
  72. package/src/session/find-types.ts +8 -4
  73. package/src/session/find-workflow.ts +11 -16
  74. package/src/session/graph/collect.ts +2 -0
  75. package/src/session/graph-types.ts +3 -1
  76. package/src/session/graph-workflow.ts +5 -4
  77. package/src/session/input/health-refactor.ts +48 -34
  78. package/src/session/input/workflows.ts +45 -46
  79. package/src/session/inspect/file-point.ts +2 -2
  80. package/src/session/inspect-types.ts +1 -1
  81. package/src/session/inspect-workflow.ts +3 -3
  82. package/src/session/orientation/workspace-context.ts +3 -0
  83. package/src/session/orientation-workflow.ts +6 -3
  84. package/src/session/refactor-file-actions.ts +122 -0
  85. package/src/session/refactor-plan-pipeline.ts +152 -0
  86. package/src/session/refactor-plans.ts +18 -15
  87. package/src/session/refactor-types.ts +24 -12
  88. package/src/session/refactor-workflow.ts +70 -244
  89. package/src/session/session.ts +87 -12
  90. package/src/session/target-workflow.ts +23 -21
  91. package/src/tool/code_find/execute.ts +6 -7
  92. package/src/tool/code_find/spec.ts +9 -16
  93. package/src/tool/code_find/tui.ts +12 -6
  94. package/src/tool/code_graph/section.ts +4 -0
  95. package/src/tool/code_graph/spec.ts +6 -0
  96. package/src/tool/code_health/spec.ts +6 -0
  97. package/src/tool/code_health/structured-schema.ts +4 -4
  98. package/src/tool/code_health/structured.ts +15 -17
  99. package/src/tool/code_inspect/execute.ts +1 -1
  100. package/src/tool/code_inspect/markdown.ts +33 -6
  101. package/src/tool/code_inspect/result.ts +1 -1
  102. package/src/tool/code_inspect/spec.ts +14 -6
  103. package/src/tool/code_inspect/structured.ts +2 -2
  104. package/src/tool/code_inspect/tui.ts +2 -2
  105. package/src/tool/code_orientation/directory-navigation.ts +20 -31
  106. package/src/tool/code_orientation/spec.ts +8 -0
  107. package/src/tool/code_orientation/workspace-output.ts +40 -13
  108. package/src/tool/code_orientation/workspace-sections.ts +45 -2
  109. package/src/tool/code_refactor_apply/result.ts +2 -1
  110. package/src/tool/code_refactor_apply/spec.ts +7 -0
  111. package/src/tool/code_refactor_plan/execute.ts +0 -2
  112. package/src/tool/code_refactor_plan/result.ts +23 -13
  113. package/src/tool/code_refactor_plan/spec.ts +8 -2
  114. package/src/tool/code_refactor_plan/structured.ts +59 -12
  115. package/src/tool/code_refactor_plan/tui.ts +14 -17
  116. package/src/tool/code_resolve/guidance.ts +1 -1
  117. package/src/tool/code_resolve/markdown.ts +121 -34
  118. package/src/tool/code_resolve/result.ts +18 -15
  119. package/src/tool/code_resolve/spec.ts +6 -0
  120. package/src/tool/code_resolve/structured.ts +43 -10
  121. package/src/tool/namespace.ts +14 -0
  122. package/src/tool/refactor-markdown.ts +55 -15
  123. package/src/tool/register.ts +3 -0
  124. package/src/tool/result/model-budget.ts +2 -2
  125. package/src/tool/result/refactor-preview.ts +118 -0
  126. package/src/tool/result/refactor-unavailable.ts +16 -0
  127. package/src/tool/result/refactor.ts +8 -2
  128. package/src/tool/result/types.ts +13 -10
  129. package/src/tool/schemas.ts +63 -20
  130. package/src/tool/specs.ts +3 -0
  131. package/src/ui/status-overlay.ts +1 -1
  132. package/src/ui/tui/common.ts +10 -10
@@ -1,5 +1,6 @@
1
1
  // Public API surface for the LSP session-scoped service.
2
2
 
3
+ export type { CommandEditCaptureResult } from "./client/client-edit-capture.ts";
3
4
  export { isMissingFileError } from "./client/client-file-state.ts";
4
5
  export {
5
6
  getExplicitlyDisabledLanguages,
@@ -7,10 +8,8 @@ export {
7
8
  loadConfig,
8
9
  } from "./config/config.ts";
9
10
  export {
10
- codeActionKindsForOperation,
11
11
  getServerOperationSupport,
12
12
  isCodeActionKindInRange,
13
- REFACTOR_CODE_ACTION_KINDS,
14
13
  supportsCodeActionResolve,
15
14
  supportsCodeActions,
16
15
  supportsPrepareRename,
@@ -91,6 +90,7 @@ export type {
91
90
  ProcessCrashRecoveryOutcome,
92
91
  ProcessCrashRecoveryReport,
93
92
  RecoverDiagnosticsResult,
93
+ RoutedCodeActionResponse,
94
94
  RoutedMutationDocumentSnapshot,
95
95
  RoutedMutationResponse,
96
96
  SemanticReadinessResult,
@@ -7,6 +7,7 @@
7
7
  // dynamic set for `textDocument/diagnostic` is non-empty.
8
8
 
9
9
  import { posix as posixPath } from "node:path";
10
+ import type { CFamilyFileAssociationResolver } from "@mrclrchtr/supi-code-runtime/api";
10
11
  import { uriToFile } from "@mrclrchtr/supi-core/path";
11
12
  import { detectLanguageId } from "../utils.ts";
12
13
 
@@ -51,12 +52,21 @@ export function isValidDocumentSelector(value: unknown): boolean {
51
52
  );
52
53
  }
53
54
 
54
- /** Match one valid document selector against a file URI. */
55
- export function isDocumentSelectorApplicable(selector: unknown, uri: string): boolean {
55
+ /**
56
+ * Match one valid document selector against a file URI.
57
+ *
58
+ * Pass the client's file associations so the language matches the ID sent in
59
+ * `didOpen` (for example, a `.h` file associated with `cpp`).
60
+ */
61
+ export function isDocumentSelectorApplicable(
62
+ selector: unknown,
63
+ uri: string,
64
+ associations?: CFamilyFileAssociationResolver,
65
+ ): boolean {
56
66
  if (selector === undefined || selector === null) return true;
57
67
  if (!isValidDocumentSelector(selector)) return false;
58
68
  if (!Array.isArray(selector) || selector.length === 0) return false;
59
- const language = detectLanguageId(uriToFile(uri));
69
+ const language = detectLanguageId(uriToFile(uri), associations);
60
70
  const scheme = readUriScheme(uri);
61
71
  const filePath = uriToFile(uri).replaceAll("\\", "/");
62
72
  return selector.some((entry) => {
@@ -237,22 +237,17 @@ export class ClientDiagnostics {
237
237
  for (const update of updates) {
238
238
  const document = this.#openDocs.get(update.document.uri);
239
239
  if (!document) throw new Error("Semantic input changed while synchronization was running.");
240
- this.#synchronizeTrackedDocument(
241
- update.document.uri,
242
- update.document.filePath,
243
- update.content,
244
- document,
245
- );
240
+ this.#synchronizeTrackedDocument(update.document, update.content, document);
246
241
  this.#failedUris.delete(update.document.uri);
247
242
  }
248
243
  }
249
244
 
250
245
  /** Apply one tracked-document change with the shared client state. */
251
246
  #synchronizeTrackedDocument(
252
- uri: string,
253
- filePath: string,
247
+ { uri, filePath }: { readonly uri: string; readonly filePath: string },
254
248
  content: string,
255
249
  document: OpenDocumentState,
250
+ options: { fullText?: boolean } = {},
256
251
  ): void {
257
252
  synchronizeTrackedDocument({
258
253
  uri,
@@ -267,6 +262,7 @@ export class ClientDiagnostics {
267
262
  markUnversionedSyncMoment: () => this.#unversionedPushSyncMoments.set(uri, Date.now()),
268
263
  clearFailedFile: () => this.#failedUris.delete(uri),
269
264
  open: () => this.didOpen(filePath, content),
265
+ ...(options.fullText ? { fullText: true } : {}),
270
266
  });
271
267
  }
272
268
 
@@ -394,7 +390,27 @@ export class ClientDiagnostics {
394
390
  const nextFingerprint = fingerprintDocumentContent(content);
395
391
  if (doc.contentFingerprint === nextFingerprint) return;
396
392
  this.#advanceInputRevision();
397
- this.#synchronizeTrackedDocument(uri, filePath, content, doc);
393
+ this.#synchronizeTrackedDocument({ uri, filePath }, content, doc);
394
+ }
395
+
396
+ /**
397
+ * Re-send an open document's tracked content under a new version, even when
398
+ * it is unchanged. The tracked content matches disk: semantic requests
399
+ * synchronize open documents with disk before they run. Used after a server ran a command whose pushed
400
+ * edit was refused, so the server's model matches the client again.
401
+ * Returns the versions before and after, or null when the document is not open.
402
+ */
403
+ resynchronizeOpenDocument(filePath: string): { from: number; to: number } | null {
404
+ if (!this.host.isOperational()) return null;
405
+ const uri = fileToUri(filePath);
406
+ const doc = this.#openDocs.get(uri);
407
+ if (!doc) return null;
408
+ const from = doc.version;
409
+ this.#advanceInputRevision();
410
+ // Full text: the server may have changed its own copy, so a range computed
411
+ // from the client's content could no longer cover the whole document.
412
+ this.#synchronizeTrackedDocument({ uri, filePath }, doc.content, doc, { fullText: true });
413
+ return { from, to: doc.version };
398
414
  }
399
415
 
400
416
  /** Send a save after a disk change that the input barrier observed. */
@@ -73,6 +73,8 @@ interface SynchronizeDocumentOptions {
73
73
  documentSync: NormalizedDocumentSync;
74
74
  waiters: DiagnosticWaitRegistry;
75
75
  sendNotification: NotificationSender;
76
+ /** Send the whole text without a range, even under incremental sync (LSP allows both). */
77
+ fullText?: boolean;
76
78
  }
77
79
 
78
80
  function endPosition(content: string): { line: number; character: number } {
@@ -117,11 +119,9 @@ export function synchronizeDocument(options: SynchronizeDocumentOptions): void {
117
119
  retainDocumentSynchronization(options);
118
120
  options.document.version = options.version;
119
121
  options.document.synchronizationId = options.synchronizationId;
120
- const changes = contentChanges(
121
- options.document.content,
122
- options.content,
123
- options.documentSync.change,
124
- );
122
+ const changes = options.fullText
123
+ ? [{ text: options.content }]
124
+ : contentChanges(options.document.content, options.content, options.documentSync.change);
125
125
  options.document.content = options.content;
126
126
  options.document.contentFingerprint = fingerprintDocumentContent(options.content);
127
127
  if (options.documentSync.change === TextDocumentSyncKind.None) return;
@@ -161,6 +161,7 @@ export function synchronizeTrackedDocument(options: {
161
161
  markUnversionedSyncMoment?(): void;
162
162
  clearFailedFile?(): void;
163
163
  open(): void;
164
+ fullText?: boolean;
164
165
  }): void {
165
166
  if (!options.document) {
166
167
  options.open();
@@ -177,6 +178,7 @@ export function synchronizeTrackedDocument(options: {
177
178
  documentSync: options.documentSync,
178
179
  waiters: options.waiters,
179
180
  sendNotification: options.sendNotification,
181
+ ...(options.fullText ? { fullText: true } : {}),
180
182
  });
181
183
  options.clearFailedFile?.();
182
184
  }
@@ -0,0 +1,258 @@
1
+ /**
2
+ * Capture window for server-pushed `workspace/applyEdit` requests.
3
+ *
4
+ * SuPi never applies an edit that a server pushes. While one command runs for
5
+ * preview, each pushed edit is recorded and refused; outside that window every
6
+ * pushed edit is refused as unsolicited (LSP 3.17 `ApplyWorkspaceEditResult`).
7
+ */
8
+
9
+ import {
10
+ type CodeRequestControl,
11
+ isCodeRequestInterruption,
12
+ } from "@mrclrchtr/supi-code-runtime/api";
13
+ import { uriToFile } from "@mrclrchtr/supi-core/path";
14
+ import type { Command, WorkspaceEdit } from "../config/types.ts";
15
+ import { LSP_REQUEST_TIMEOUT_ERROR_CODE } from "../debug-telemetry.ts";
16
+ import { JsonRpcRequestError } from "./transport.ts";
17
+
18
+ /** Reply for an edit recorded for preview. */
19
+ export const CAPTURED_EDIT_REPLY = {
20
+ applied: false,
21
+ failureReason: "SuPi captured this edit for preview.",
22
+ } as const;
23
+
24
+ /** Reply for an edit that arrives outside a capture window. */
25
+ export const UNSOLICITED_EDIT_REPLY = {
26
+ applied: false,
27
+ failureReason: "SuPi does not accept unsolicited workspace edits.",
28
+ } as const;
29
+
30
+ /** Result of running one command inside a capture window. */
31
+ export type CommandEditCaptureResult =
32
+ | {
33
+ readonly kind: "captured";
34
+ /** The single edit the server pushed while the command ran. */
35
+ readonly edit: WorkspaceEdit;
36
+ /** Open documents re-sent afterwards, with their versions before and after. */
37
+ readonly resynced: readonly { file: string; from: number; to: number }[];
38
+ }
39
+ | { readonly kind: "unavailable"; readonly reason: string };
40
+
41
+ /** Reply for an edit from a command SuPi stopped waiting for. */
42
+ export const ABANDONED_EDIT_REPLY = {
43
+ applied: false,
44
+ failureReason: "SuPi stopped waiting for the command that produced this edit.",
45
+ } as const;
46
+
47
+ /**
48
+ * Records pushed edits for at most one capture per client. After a capture
49
+ * stops waiting (timeout, abort, deadline) the window keeps draining until the
50
+ * abandoned command settles, so its late edits are refused and can never be
51
+ * attributed to the next capture.
52
+ */
53
+ export class EditCaptureWindow {
54
+ #state: "idle" | "capturing" | "draining" = "idle";
55
+ #edits: unknown[] = [];
56
+ #onEdit: (() => void) | undefined;
57
+
58
+ /** Open the window. Returns false while another capture runs or drains. */
59
+ open(): boolean {
60
+ if (this.#state !== "idle") return false;
61
+ this.#state = "capturing";
62
+ this.#edits = [];
63
+ return true;
64
+ }
65
+
66
+ /** Stop capturing and return the edits pushed so far. */
67
+ close(): unknown[] {
68
+ const edits = this.#edits;
69
+ this.#edits = [];
70
+ this.#onEdit = undefined;
71
+ if (this.#state === "capturing") this.#state = "idle";
72
+ return edits;
73
+ }
74
+
75
+ /** Stop capturing but refuse new captures until `settled` resolves. */
76
+ drain(settled: Promise<void>): unknown[] {
77
+ const edits = this.close();
78
+ this.#state = "draining";
79
+ void settled.then(() => {
80
+ if (this.#state === "draining") this.#state = "idle";
81
+ });
82
+ return edits;
83
+ }
84
+
85
+ /** Wait up to `ms` for the first edit when none has arrived yet. */
86
+ async waitForEdit(ms: number): Promise<void> {
87
+ if (this.#edits.length > 0 || ms <= 0) return;
88
+ await new Promise<void>((resolve) => {
89
+ const timer = setTimeout(resolve, ms);
90
+ this.#onEdit = () => {
91
+ clearTimeout(timer);
92
+ resolve();
93
+ };
94
+ });
95
+ }
96
+
97
+ /** Answer one `workspace/applyEdit` request; the edit is never applied. */
98
+ handleApplyEdit(
99
+ params: unknown,
100
+ ): typeof CAPTURED_EDIT_REPLY | typeof UNSOLICITED_EDIT_REPLY | typeof ABANDONED_EDIT_REPLY {
101
+ if (this.#state === "draining") return ABANDONED_EDIT_REPLY;
102
+ if (this.#state === "idle") return UNSOLICITED_EDIT_REPLY;
103
+ const edit =
104
+ typeof params === "object" && params !== null
105
+ ? (params as { edit?: unknown }).edit
106
+ : undefined;
107
+ this.#edits.push(edit);
108
+ this.#onEdit?.();
109
+ return CAPTURED_EDIT_REPLY;
110
+ }
111
+ }
112
+
113
+ /** Collect the file URIs a captured edit touches, for resynchronization. */
114
+ export function editedDocumentUris(edit: unknown): string[] {
115
+ if (typeof edit !== "object" || edit === null) return [];
116
+ const uris = new Set<string>();
117
+ const { changes, documentChanges } = edit as {
118
+ changes?: unknown;
119
+ documentChanges?: unknown;
120
+ };
121
+ if (typeof changes === "object" && changes !== null) {
122
+ for (const uri of Object.keys(changes)) uris.add(uri);
123
+ }
124
+ if (Array.isArray(documentChanges)) {
125
+ for (const change of documentChanges) {
126
+ const uri = (change as { textDocument?: { uri?: unknown } } | null)?.textDocument?.uri;
127
+ if (typeof uri === "string") uris.add(uri);
128
+ }
129
+ }
130
+ return [...uris];
131
+ }
132
+
133
+ /** Default wait for an edit a server pushes just after answering the command. */
134
+ const DEFAULT_GRACE_MS = 250;
135
+
136
+ /** Collaborators for one command capture on one client. */
137
+ export interface CommandEditCaptureOptions {
138
+ readonly command: Command;
139
+ /** Upper bound for the command to finish. */
140
+ readonly timeoutMs: number;
141
+ /** Wait for an edit pushed after the command answers; LSP allows that order. */
142
+ readonly graceMs?: number;
143
+ /** Upper bound for refusing late edits from an abandoned command. */
144
+ readonly drainMs?: number;
145
+ readonly control?: CodeRequestControl;
146
+ readonly window: EditCaptureWindow;
147
+ /** Send one request and expose when its transport lifetime ends. */
148
+ sendRequestOwned(
149
+ method: string,
150
+ params: unknown,
151
+ options: { timeoutMs: number } & CodeRequestControl,
152
+ ): { result: Promise<unknown>; settled: Promise<void> };
153
+ /** Re-send one open document; null when it is not open. */
154
+ resynchronize(file: string): { from: number; to: number } | null;
155
+ }
156
+
157
+ /**
158
+ * Run one command inside a capture window. Exactly one pushed edit becomes the
159
+ * result; none, several, a timeout, or a server error are unavailable.
160
+ * Cancellation and deadline expiry propagate. Every touched open document is
161
+ * resynced, and an abandoned command keeps the window draining.
162
+ */
163
+ export async function runCommandEditCapture(
164
+ options: CommandEditCaptureOptions,
165
+ ): Promise<CommandEditCaptureResult> {
166
+ const { command, timeoutMs, control, window } = options;
167
+ if (!window.open()) {
168
+ return {
169
+ kind: "unavailable",
170
+ reason: "Another server command capture is running on this client; retry shortly.",
171
+ };
172
+ }
173
+ const request = options.sendRequestOwned(
174
+ "workspace/executeCommand",
175
+ { command: command.command, ...(command.arguments ? { arguments: command.arguments } : {}) },
176
+ { ...control, timeoutMs },
177
+ );
178
+ let serverError: string | undefined;
179
+ try {
180
+ await request.result;
181
+ } catch (error) {
182
+ if (!(error instanceof JsonRpcRequestError) || isCodeRequestInterruption(error, control)) {
183
+ return abandonCapture(options, request.settled, error);
184
+ }
185
+ // The server answered with an error, so the command is over. clangd
186
+ // reports that the refused edit "was not applied"; the edit still counts.
187
+ serverError = error.message;
188
+ }
189
+ if (serverError === undefined) await window.waitForEdit(options.graceMs ?? DEFAULT_GRACE_MS);
190
+ const edits = window.close();
191
+ const resynced = resynchronizeEdits(edits, options.resynchronize);
192
+ if (edits.length === 0) {
193
+ return {
194
+ kind: "unavailable",
195
+ reason:
196
+ serverError === undefined
197
+ ? "The server command produced no edit; there may be nothing to change."
198
+ : `The server command failed: ${serverError}`,
199
+ };
200
+ }
201
+ if (edits.length > 1) {
202
+ return {
203
+ kind: "unavailable",
204
+ reason: `The server command produced ${edits.length} edits; only one can be previewed.`,
205
+ };
206
+ }
207
+ return { kind: "captured", edit: edits[0] as WorkspaceEdit, resynced };
208
+ }
209
+
210
+ /** Close or drain the window after SuPi stopped waiting for the command, then report or rethrow. */
211
+ function abandonCapture(
212
+ options: CommandEditCaptureOptions,
213
+ settled: Promise<void>,
214
+ error: unknown,
215
+ ): CommandEditCaptureResult {
216
+ const { window, timeoutMs, control } = options;
217
+ const drainMs = options.drainMs ?? timeoutMs;
218
+ const edits = drainMs > 0 ? window.drain(boundedSettle(settled, drainMs)) : window.close();
219
+ resynchronizeEdits(edits, options.resynchronize);
220
+ if (isCodeRequestInterruption(error, control)) throw error;
221
+ return {
222
+ kind: "unavailable",
223
+ reason: isTimeout(error)
224
+ ? `The server command did not finish within ${timeoutMs} ms.`
225
+ : `The server command could not run: ${error instanceof Error ? error.message : String(error)}`,
226
+ };
227
+ }
228
+
229
+ function boundedSettle(settled: Promise<void>, ms: number): Promise<void> {
230
+ return Promise.race([settled, new Promise<void>((resolve) => setTimeout(resolve, ms))]);
231
+ }
232
+
233
+ function resynchronizeEdits(
234
+ edits: readonly unknown[],
235
+ resynchronize: CommandEditCaptureOptions["resynchronize"],
236
+ ): { file: string; from: number; to: number }[] {
237
+ const uris = new Set(edits.flatMap((edit) => editedDocumentUris(edit)));
238
+ const resynced: { file: string; from: number; to: number }[] = [];
239
+ for (const uri of uris) {
240
+ let file: string;
241
+ try {
242
+ file = uriToFile(uri);
243
+ } catch {
244
+ continue;
245
+ }
246
+ const versions = resynchronize(file);
247
+ if (versions) resynced.push({ file, ...versions });
248
+ }
249
+ return resynced;
250
+ }
251
+
252
+ function isTimeout(error: unknown): boolean {
253
+ return (
254
+ typeof error === "object" &&
255
+ error !== null &&
256
+ (error as { code?: unknown }).code === LSP_REQUEST_TIMEOUT_ERROR_CODE
257
+ );
258
+ }
@@ -23,6 +23,7 @@ import { CodeActionTriggerKind } from "vscode-languageserver-types";
23
23
  import { CLIENT_CAPABILITIES } from "../config/capabilities.ts";
24
24
  import {
25
25
  getServerOperationSupport,
26
+ isCodeActionKindWithin,
26
27
  supportsCodeActionResolve,
27
28
  supportsCodeActions,
28
29
  supportsPrepareRename,
@@ -32,6 +33,7 @@ import {
32
33
  import type {
33
34
  CodeAction,
34
35
  CodeActionContext,
36
+ Command,
35
37
  Diagnostic,
36
38
  DidChangeWatchedFilesParams,
37
39
  DocumentDiagnosticReport,
@@ -71,6 +73,11 @@ import { createTypeScriptDiagnosticRequestAdapter } from "./client-diagnostic-ty
71
73
  import { ClientDiagnostics } from "./client-diagnostics.ts";
72
74
  import type { ClientDiagnosticSnapshot, DiagnosticEntry } from "./client-document-state.ts";
73
75
  import { type NormalizedDocumentSync, normalizeDocumentSync } from "./client-document-sync.ts";
76
+ import {
77
+ type CommandEditCaptureResult,
78
+ EditCaptureWindow,
79
+ runCommandEditCapture,
80
+ } from "./client-edit-capture.ts";
74
81
  import {
75
82
  SemanticInputRequestRetryGuard,
76
83
  type SemanticInputRequestRetryReason,
@@ -244,13 +251,6 @@ function isLazyCodeAction(value: unknown): value is CodeAction {
244
251
  );
245
252
  }
246
253
 
247
- function codeActionKindMatchesFilter(kind: unknown, filter: string): boolean {
248
- return (
249
- filter === "" ||
250
- (typeof kind === "string" && (kind === filter || kind.startsWith(`${filter}.`)))
251
- );
252
- }
253
-
254
254
  function isValidCommand(value: unknown): value is NonNullable<CodeAction["command"]> {
255
255
  const command = isRecord(value) ? value : null;
256
256
  return (
@@ -546,8 +546,11 @@ export class LspClient {
546
546
  private readonly settingsSnapshot: JsonObject | undefined;
547
547
  private readonly diagnosticRequestAdapter: DiagnosticRequestAdapter;
548
548
  private readonly diagnostics: ClientDiagnostics;
549
+ private readonly editCapture = new EditCaptureWindow();
549
550
  /** Dynamic capability registrations for this client instance only. */
550
551
  private readonly dynamicRegistrations = new ClientDynamicRegistrations();
552
+ /** Workspace association snapshot shared by `didOpen` and selector matching. */
553
+ private readonly fileAssociations: CFamilyFileAssociationResolver | undefined;
551
554
 
552
555
  // ── Readiness (work-done-progress) ──────────────────────────────────
553
556
  private trackedTokens = new Map<ProgressToken, "created" | "active" | "ended">();
@@ -576,6 +579,7 @@ export class LspClient {
576
579
  ) {
577
580
  this.name = name;
578
581
  this.root = root;
582
+ this.fileAssociations = fileAssociations;
579
583
  this.settingsSnapshot = cloneSettings(config.settings);
580
584
  const nativeDiagnosticAdapter: DiagnosticRequestAdapter = {
581
585
  supports: (uri) => this.hasApplicableDiagnosticProvider(uri),
@@ -1053,12 +1057,18 @@ export class LspClient {
1053
1057
  if (
1054
1058
  staticRecord !== undefined &&
1055
1059
  isValidDiagnosticOptions(staticRecord) &&
1056
- isDocumentSelectorApplicable(staticRecord.documentSelector, uri)
1060
+ isDocumentSelectorApplicable(staticRecord.documentSelector, uri, this.fileAssociations)
1057
1061
  ) {
1058
1062
  return staticRecord;
1059
1063
  }
1060
1064
  for (const registration of this.dynamicRegistrations.get(DOCUMENT_DIAGNOSTIC_METHOD)) {
1061
- if (isDocumentSelectorApplicable(registration.options.documentSelector, uri)) {
1065
+ if (
1066
+ isDocumentSelectorApplicable(
1067
+ registration.options.documentSelector,
1068
+ uri,
1069
+ this.fileAssociations,
1070
+ )
1071
+ ) {
1062
1072
  return registration.options;
1063
1073
  }
1064
1074
  }
@@ -1239,6 +1249,37 @@ export class LspClient {
1239
1249
  return result.kind === "completed" ? readTypeScriptProjectMembership(result.data) : "unknown";
1240
1250
  }
1241
1251
 
1252
+ /**
1253
+ * Run one server command and capture the single edit it pushes through
1254
+ * `workspace/applyEdit`. Every pushed edit is refused, so no file changes.
1255
+ * Open documents the edit touches are re-sent afterwards under new versions.
1256
+ */
1257
+ async captureCommandEdits(
1258
+ command: Command,
1259
+ options: {
1260
+ timeoutMs: number;
1261
+ graceMs?: number;
1262
+ drainMs?: number;
1263
+ control?: CodeRequestControl;
1264
+ },
1265
+ ): Promise<CommandEditCaptureResult> {
1266
+ const rpc = this.rpc;
1267
+ if (!rpc || this._status !== "running") {
1268
+ return {
1269
+ kind: "unavailable",
1270
+ reason: "The server command is unavailable because the client is not running.",
1271
+ };
1272
+ }
1273
+ return runCommandEditCapture({
1274
+ command,
1275
+ ...options,
1276
+ window: this.editCapture,
1277
+ sendRequestOwned: (method, params, requestOptions) =>
1278
+ rpc.sendRequestOwned(method, params, requestOptions),
1279
+ resynchronize: (file) => this.diagnostics.resynchronizeOpenDocument(file),
1280
+ });
1281
+ }
1282
+
1242
1283
  async workspaceSymbol(
1243
1284
  query: string,
1244
1285
  control?: CodeRequestControl,
@@ -1430,7 +1471,17 @@ export class LspClient {
1430
1471
  control: CodeRequestControl | undefined,
1431
1472
  only: readonly string[] | undefined,
1432
1473
  ): Promise<CodeAction[]> {
1433
- const candidates = raw.map((value) => {
1474
+ // Servers may still return kinds that `only` excludes (typescript-language-server
1475
+ // adds quickfixes). Drop those before validation so they cannot fail the request.
1476
+ const requested = only
1477
+ ? raw.filter(
1478
+ (value) =>
1479
+ !isRecord(value) ||
1480
+ typeof value.kind !== "string" ||
1481
+ only.some((filter) => isCodeActionKindWithin(value.kind, filter)),
1482
+ )
1483
+ : raw;
1484
+ const candidates = requested.map((value) => {
1434
1485
  const candidate = normalizeCodeActionResponseEntry(value);
1435
1486
  if (!candidate)
1436
1487
  throw new Error("LSP server returned a malformed code action response entry.");
@@ -1443,7 +1494,7 @@ export class LspClient {
1443
1494
  !this.supportsCodeActionResolve ||
1444
1495
  !lazyAction ||
1445
1496
  (only !== undefined &&
1446
- !only.some((filter) => codeActionKindMatchesFilter(lazyAction.kind, filter)))
1497
+ !only.some((filter) => isCodeActionKindWithin(lazyAction.kind, filter)))
1447
1498
  ) {
1448
1499
  actions.push(action);
1449
1500
  continue;
@@ -1773,6 +1824,8 @@ export class LspClient {
1773
1824
 
1774
1825
  private handleServerRequest(method: string, params: unknown): unknown {
1775
1826
  switch (method) {
1827
+ case "workspace/applyEdit":
1828
+ return this.editCapture.handleApplyEdit(params);
1776
1829
  case "workspace/configuration":
1777
1830
  return this.buildWorkspaceConfigurationResult(params);
1778
1831
  case "workspace/workspaceFolders":
@@ -42,15 +42,20 @@ export const CLIENT_CAPABILITIES: ClientCapabilities = {
42
42
  "refactor.extract.constant",
43
43
  "refactor.extract.variable",
44
44
  "refactor.inline",
45
+ "refactor.move",
45
46
  "refactor.rewrite",
46
47
  "source",
47
48
  "source.organizeImports",
48
49
  "source.fixAll",
49
50
  "source.removeUnused",
51
+ "source.removeUnusedImports",
52
+ "source.sortImports",
50
53
  ],
51
54
  },
52
55
  },
53
56
  dataSupport: true,
57
+ // Never advertise `workspace.workspaceEdit.snippetEditSupport` (LSP 3.18):
58
+ // snippet edits cannot become exact previewable text plans.
54
59
  // SuPi resolves only the edit property. Commands and other fields
55
60
  // must remain server-owned and are never advertised as resolvable.
56
61
  resolveSupport: { properties: ["edit"] },
@@ -72,6 +77,9 @@ export const CLIENT_CAPABILITIES: ClientCapabilities = {
72
77
  workDoneProgress: true,
73
78
  },
74
79
  workspace: {
80
+ // Servers may push edits through workspace/applyEdit. SuPi records them
81
+ // only while previewing one command and always replies applied: false.
82
+ applyEdit: true,
75
83
  configuration: true,
76
84
  workspaceFolders: true,
77
85
  workspaceEdit: {