pi-agent-ide 1.0.0 → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (121) hide show
  1. package/CHANGELOG.md +10 -0
  2. package/dist/{chunk-LG22ELG4.js → chunk-26SMC6OS.js} +1 -1
  3. package/dist/{chunk-QC6VFZSB.js → chunk-3BRGWFEI.js} +1 -1
  4. package/dist/chunk-3JBQYLJ4.js +5 -0
  5. package/dist/{chunk-LRAMFOUP.js → chunk-3KM5DSWL.js} +1 -1
  6. package/dist/{chunk-FVWMI4GP.js → chunk-7OAAM5FL.js} +1 -1
  7. package/dist/{chunk-X4CU7CMR.js → chunk-C327T6YP.js} +1 -1
  8. package/dist/{chunk-WZ7MNISG.js → chunk-KM4NOIOB.js} +1 -1
  9. package/dist/{chunk-NGWQRV25.js → chunk-L2YDUMZC.js} +1 -1
  10. package/dist/chunk-MCHU3BLO.js +53 -0
  11. package/dist/{chunk-AKUBFJAR.js → chunk-NSBRKTZ7.js} +1 -1
  12. package/dist/{chunk-SKHD2QIT.js → chunk-QUK5ZEYX.js} +1 -1
  13. package/dist/{chunk-E6G3UVS7.js → chunk-RYJEEBET.js} +1 -1
  14. package/dist/chunk-UN3XLVPR.js +18 -0
  15. package/dist/{chunk-KJ6HZC6L.js → chunk-VQ2RA43A.js} +1 -1
  16. package/dist/{chunk-HUICUICD.js → chunk-VWYI4WF7.js} +1 -1
  17. package/dist/{chunk-UHGHVYAW.js → chunk-W25HNEMR.js} +1 -1
  18. package/dist/entry-0.js +1 -1
  19. package/dist/entry-20.js +1 -1
  20. package/dist/entry-38.js +1 -1
  21. package/dist/entry-44.js +1 -1
  22. package/dist/entry-57.js +1 -1
  23. package/dist/entry-58.js +1 -1
  24. package/dist/entry-59.js +1 -1
  25. package/dist/entry-60.js +1 -1
  26. package/dist/entry-61.js +1 -1
  27. package/dist/entry-62.js +1 -1
  28. package/dist/entry-94.js +1 -1
  29. package/dist/pi-agent-ide.js +1 -1
  30. package/docs/nightly.md +7 -1
  31. package/docs/releases.md +1 -1
  32. package/node_modules/pi-agent-doctor/package.json +1 -1
  33. package/node_modules/pi-agent-documentation/package.json +1 -1
  34. package/node_modules/pi-agent-filesystem/package.json +7 -7
  35. package/node_modules/pi-agent-filesystem-image/package.json +3 -3
  36. package/node_modules/pi-agent-filesystem-jq/package.json +5 -5
  37. package/node_modules/pi-agent-filesystem-pdf/package.json +3 -3
  38. package/node_modules/pi-agent-filesystem-text/package.json +3 -3
  39. package/node_modules/pi-agent-ide-ast/package.json +13 -13
  40. package/node_modules/pi-agent-ide-changes/package.json +8 -8
  41. package/node_modules/pi-agent-ide-formatter/package.json +3 -3
  42. package/node_modules/pi-agent-ide-languages/package.json +2 -2
  43. package/node_modules/pi-agent-ide-lint/package.json +7 -7
  44. package/node_modules/pi-agent-ide-lsp/package.json +12 -12
  45. package/node_modules/pi-agent-ide-lsp/src/lsp/client.ts +28 -0
  46. package/node_modules/pi-agent-ide-lsp/src/lsp/corrected-names.ts +16 -5
  47. package/node_modules/pi-agent-ide-lsp/src/lsp/declaration-scan.ts +116 -0
  48. package/node_modules/pi-agent-ide-lsp/src/lsp/initialization-options.ts +37 -0
  49. package/node_modules/pi-agent-ide-lsp/src/lsp/manager.ts +138 -128
  50. package/node_modules/pi-agent-ide-lsp/src/lsp/navigation.ts +1 -24
  51. package/node_modules/pi-agent-ide-lsp/src/lsp/project.ts +40 -12
  52. package/node_modules/pi-agent-ide-lsp/src/lsp/symbol-search.ts +98 -40
  53. package/node_modules/pi-agent-ide-lsp/src/lsp/symbol-selectors.ts +48 -0
  54. package/node_modules/pi-agent-ide-lsp/src/lsp/symbols.ts +61 -0
  55. package/node_modules/pi-agent-ide-lsp/src/rename-plan.ts +1 -1
  56. package/node_modules/pi-agent-ide-lsp/src/search-resolver.ts +51 -2
  57. package/node_modules/pi-agent-image/package.json +2 -2
  58. package/node_modules/pi-agent-invariant/package.json +1 -1
  59. package/node_modules/pi-agent-pdf/package.json +2 -2
  60. package/node_modules/pi-agent-read/package.json +7 -7
  61. package/node_modules/pi-agent-resource/package.json +1 -1
  62. package/node_modules/pi-agent-search/package.json +4 -4
  63. package/node_modules/pi-agent-search/src/api/structured-result.ts +28 -4
  64. package/node_modules/pi-agent-search-text/package.json +10 -10
  65. package/node_modules/pi-agent-text/package.json +2 -2
  66. package/node_modules/pi-agent-text-anchor-constant/package.json +3 -3
  67. package/node_modules/pi-agent-text-anchor-exact/package.json +3 -3
  68. package/node_modules/pi-agent-text-anchor-line-hash/package.json +5 -5
  69. package/node_modules/pi-agent-text-editor/package.json +8 -8
  70. package/node_modules/pi-agent-text-editor-renderer/package.json +5 -5
  71. package/node_modules/pi-agent-text-editor-stale-anchor/package.json +4 -4
  72. package/node_modules/pi-agent-tool-call-interception/package.json +2 -2
  73. package/node_modules/pi-agent-tool-ui/package.json +1 -1
  74. package/node_modules/pi-agent-web/package.json +7 -7
  75. package/node_modules/pi-agent-web-html/package.json +2 -2
  76. package/node_modules/pi-agent-web-image/package.json +3 -3
  77. package/node_modules/pi-agent-web-pdf/package.json +3 -3
  78. package/node_modules/pi-agent-web-text/package.json +3 -3
  79. package/package.json +35 -35
  80. package/src/composite/script-values/lsp-search.ts +56 -12
  81. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/package.json +7 -7
  82. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-image/package.json +3 -3
  83. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-jq/package.json +5 -5
  84. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-pdf/package.json +3 -3
  85. package/src/extensions/pi-agent-read/extensions/pi-agent-filesystem/plugins/pi-agent-filesystem-text/package.json +3 -3
  86. package/src/extensions/pi-agent-read/extensions/pi-agent-web/package.json +7 -7
  87. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-html/package.json +2 -2
  88. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-image/package.json +3 -3
  89. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-pdf/package.json +3 -3
  90. package/src/extensions/pi-agent-read/extensions/pi-agent-web/plugins/pi-agent-web-text/package.json +3 -3
  91. package/src/extensions/pi-agent-read/package.json +7 -7
  92. package/src/extensions/pi-agent-search/package.json +4 -4
  93. package/src/extensions/pi-agent-search/plugins/pi-agent-search-text/package.json +10 -10
  94. package/src/extensions/pi-agent-search/src/api/structured-result.ts +28 -4
  95. package/src/extensions/pi-agent-text-editor/package.json +8 -8
  96. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-constant/package.json +3 -3
  97. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-exact/package.json +3 -3
  98. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-anchor-line-hash/package.json +5 -5
  99. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-renderer/package.json +5 -5
  100. package/src/extensions/pi-agent-text-editor/plugins/pi-agent-text-editor-stale-anchor/package.json +4 -4
  101. package/src/plugins/pi-agent-ide-ast/package.json +13 -13
  102. package/src/plugins/pi-agent-ide-changes/package.json +8 -8
  103. package/src/plugins/pi-agent-ide-formatter/package.json +3 -3
  104. package/src/plugins/pi-agent-ide-languages/package.json +2 -2
  105. package/src/plugins/pi-agent-ide-lint/package.json +7 -7
  106. package/src/plugins/pi-agent-ide-lsp/package.json +12 -12
  107. package/src/plugins/pi-agent-ide-lsp/src/lsp/client.ts +28 -0
  108. package/src/plugins/pi-agent-ide-lsp/src/lsp/corrected-names.ts +16 -5
  109. package/src/plugins/pi-agent-ide-lsp/src/lsp/declaration-scan.ts +116 -0
  110. package/src/plugins/pi-agent-ide-lsp/src/lsp/initialization-options.ts +37 -0
  111. package/src/plugins/pi-agent-ide-lsp/src/lsp/manager.ts +138 -128
  112. package/src/plugins/pi-agent-ide-lsp/src/lsp/navigation.ts +1 -24
  113. package/src/plugins/pi-agent-ide-lsp/src/lsp/project.ts +40 -12
  114. package/src/plugins/pi-agent-ide-lsp/src/lsp/symbol-search.ts +98 -40
  115. package/src/plugins/pi-agent-ide-lsp/src/lsp/symbol-selectors.ts +48 -0
  116. package/src/plugins/pi-agent-ide-lsp/src/lsp/symbols.ts +61 -0
  117. package/src/plugins/pi-agent-ide-lsp/src/rename-plan.ts +1 -1
  118. package/src/plugins/pi-agent-ide-lsp/src/search-resolver.ts +51 -2
  119. package/dist/chunk-4AEYLVSR.js +0 -5
  120. package/dist/chunk-DSB6A5P5.js +0 -53
  121. package/dist/chunk-YSGPCH52.js +0 -18
@@ -1,18 +1,18 @@
1
1
  {
2
2
  "name": "pi-agent-ide-lsp",
3
- "version": "1.0.0",
3
+ "version": "1.0.1",
4
4
  "type": "module",
5
5
  "dependencies": {
6
- "pi-agent-doctor": "1.0.0",
7
- "pi-agent-documentation": "1.0.0",
8
- "pi-agent-invariant": "1.0.0",
9
- "pi-agent-read": "1.0.0",
10
- "pi-agent-resource": "1.0.0",
11
- "pi-agent-search": "1.0.0",
12
- "pi-agent-text": "1.0.0",
13
- "pi-agent-text-editor": "1.0.0",
14
- "pi-agent-tool-call-interception": "1.0.0",
15
- "pi-agent-tool-ui": "1.0.0"
6
+ "pi-agent-doctor": "1.0.1",
7
+ "pi-agent-documentation": "1.0.1",
8
+ "pi-agent-invariant": "1.0.1",
9
+ "pi-agent-read": "1.0.1",
10
+ "pi-agent-resource": "1.0.1",
11
+ "pi-agent-search": "1.0.1",
12
+ "pi-agent-text": "1.0.1",
13
+ "pi-agent-text-editor": "1.0.1",
14
+ "pi-agent-tool-call-interception": "1.0.1",
15
+ "pi-agent-tool-ui": "1.0.1"
16
16
  },
17
17
  "pi": {
18
18
  "extensions": [
@@ -21,7 +21,7 @@
21
21
  },
22
22
  "peerDependencies": {
23
23
  "@earendil-works/pi-coding-agent": "*",
24
- "pi-agent-ide": "1.0.0",
24
+ "pi-agent-ide": "1.0.1",
25
25
  "typebox": "*"
26
26
  },
27
27
  "peerDependenciesMeta": {
@@ -181,6 +181,29 @@ export class LspClient {
181
181
  get commandName(): string {
182
182
  return configuredExecutableName(this._command);
183
183
  }
184
+ /** Known workspace/symbol cap for the server started by this client. */
185
+ get workspaceSymbolCandidateLimit(): number | undefined {
186
+ switch (this.commandName.replace(/\.exe$/iu, "")) {
187
+ case "gopls": {
188
+ return 100;
189
+ }
190
+ case "rust-analyzer": {
191
+ // rust-analyzer replaces its initialize options with a nonempty reply to
192
+ // workspace/configuration, requesting the "rust-analyzer" section.
193
+ const [settings] = configurationItems(this._settings, [{ section: "rust-analyzer" }]);
194
+ const options =
195
+ typeof settings === "object" && settings !== null && Object.keys(settings).length > 0
196
+ ? settings
197
+ : this._initOptions;
198
+ const [limit] = configurationItems(options, [{ section: "workspace.symbol.search.limit" }]);
199
+ return typeof limit === "number" && Number.isSafeInteger(limit) && limit >= 0 ? limit : 128;
200
+ }
201
+ default: {
202
+ return undefined;
203
+ }
204
+ }
205
+ }
206
+
184
207
  get diagnosticMode(): "unknown" | "pull" | "push" {
185
208
  return this._diagnosticMode;
186
209
  }
@@ -938,6 +961,11 @@ export class LspClient {
938
961
  ? decodeURIComponent(new URL(wireUri).pathname)
939
962
  : URI.parse(wireUri).fsPath;
940
963
  }
964
+ /** Convert a raw protocol result path to an owned LSP document URI. */
965
+ serverPathToDocumentUri(file: string): string {
966
+ const uri = URI.file(file).toString();
967
+ return this._ownerTransport?.fromServerUri(uri) ?? uri;
968
+ }
941
969
  openDocument(uri: string, text: string, languageId: string, version = 1): void {
942
970
  const currentVersion = this._documentVersions.get(uri);
943
971
 
@@ -148,8 +148,12 @@ export function withinTypoDistance(typo: string, name: string): boolean {
148
148
  return (previous[name.length] ?? Infinity) <= bound;
149
149
  }
150
150
 
151
- /** Text of an LSP range in `content`, or an empty string when the range does not fit it. */
152
- export function textInRange(content: string, range: LspRange): string {
151
+ /**
152
+ * Reads LSP ranges from `content`; each reader returns the range's text, or an empty string when
153
+ * the range does not fit. The line table is built once, so a caller that reads many ranges of one
154
+ * file, such as every declaration of a large outline, pays for the file once.
155
+ */
156
+ export function rangeTextReader(content: string): (range: LspRange) => string {
153
157
  const starts = [0];
154
158
  for (let index = content.indexOf("\n"); index !== -1; index = content.indexOf("\n", index + 1))
155
159
  starts.push(index + 1);
@@ -157,9 +161,16 @@ export function textInRange(content: string, range: LspRange): string {
157
161
  const start = starts[position.line];
158
162
  return start === undefined ? undefined : start + position.character;
159
163
  };
160
- const from = offset(range.start);
161
- const to = offset(range.end);
162
- return from === undefined || to === undefined || to < from ? "" : content.slice(from, to);
164
+ return (range) => {
165
+ const from = offset(range.start);
166
+ const to = offset(range.end);
167
+ return from === undefined || to === undefined || to < from ? "" : content.slice(from, to);
168
+ };
169
+ }
170
+
171
+ /** Text of an LSP range in `content`, or an empty string when the range does not fit it. */
172
+ export function textInRange(content: string, range: LspRange): string {
173
+ return rangeTextReader(content)(range);
163
174
  }
164
175
 
165
176
  /** Errors from the current diagnostics of each document that `open` synchronizes, read once. */
@@ -0,0 +1,116 @@
1
+ import type { LspClient } from "./client.ts";
2
+ import type { ClangCoverage } from "./clang-coverage.ts";
3
+ import { rangeTextReader } from "./corrected-names.ts";
4
+ import { isMethodNotFound } from "./errors.ts";
5
+ import type { LspManager } from "./manager.ts";
6
+ import { isMissingSource } from "./missing-sources.ts";
7
+ import type { LspCodeSymbol } from "./symbol-selectors.ts";
8
+ import type { LspWorkspaceSymbol } from "./symbols.ts";
9
+
10
+ /** Most files one search opens to read their declarations; the rest are reported as unchecked. */
11
+ export const MAX_SCANNED_FILES = 64;
12
+ const CONCURRENT_FILES = 8;
13
+
14
+ /** The identifier a query names exactly, or undefined for a fuzzy or multi-word query. */
15
+ export function exactIdentifier(query: string): string | undefined {
16
+ return /^[\p{L}_$][\p{L}\p{N}_$]*$/u.test(query) ? query : undefined;
17
+ }
18
+
19
+ /** Declarations found by reading the files that write a name. */
20
+ export interface DeclarationScan {
21
+ /** Declarations of the name per server that parsed their file, in workspace symbol form. */
22
+ readonly declarations: ReadonlyMap<LspClient, readonly LspWorkspaceSymbol[]>;
23
+ /** Files the scan could not check or list; present only when it is incomplete. */
24
+ readonly coverage?: ClangCoverage;
25
+ }
26
+
27
+ const nothingChecked = { fatal: [], missingDiagnostics: [] } as const;
28
+
29
+ /**
30
+ * Find the declarations of an exact name without asking the server's workspace index.
31
+ *
32
+ * A server fills that index from the projects it has loaded, and which projects those are depends
33
+ * on the files it was shown first: one TypeScript project, one clangd compilation database, one
34
+ * Go module. A text search lists the files under the scope that write the name; opening each one
35
+ * lets its server pick the project that owns the file, and the file's own symbols name the
36
+ * declarations. A file the scan did not open is reported, so the answer never claims a coverage
37
+ * it did not check.
38
+ */
39
+ export async function scanDeclarations(input: {
40
+ readonly manager: Pick<LspManager, "filesContainingInScope" | "openFile">;
41
+ readonly cwd: string;
42
+ readonly roots: readonly string[];
43
+ readonly word: string;
44
+ /** Files the search may list. */
45
+ readonly accepts: (source: string) => boolean;
46
+ readonly readText: (source: string) => Promise<string>;
47
+ readonly outlineOf: (client: LspClient, uri: string) => Promise<readonly LspCodeSymbol[]>;
48
+ readonly signal?: AbortSignal;
49
+ }): Promise<DeclarationScan> {
50
+ const { manager, cwd, word, signal } = input;
51
+ const listings = await Promise.all(
52
+ input.roots.map((root) => manager.filesContainingInScope(cwd, root, word, signal)),
53
+ );
54
+ const unlisted = listings.some((files) => files === undefined);
55
+ const files = [...new Set(listings.flatMap((found) => found ?? []))]
56
+ .filter((source) => input.accepts(source))
57
+ .sort();
58
+ const scanned = files.slice(0, MAX_SCANNED_FILES);
59
+ const declarations = new Map<LspClient, LspWorkspaceSymbol[]>();
60
+ const results: (readonly [LspClient, LspWorkspaceSymbol[]] | undefined)[] = [];
61
+ let next = 0;
62
+ const worker = async (): Promise<void> => {
63
+ for (let index = next++; index < scanned.length; index = next++) {
64
+ signal?.throwIfAborted();
65
+ const source = scanned[index] as string;
66
+ try {
67
+ results[index] = await declarationsIn(source);
68
+ } catch (error) {
69
+ // Deleted since the text search listed it: nothing in it to find.
70
+ if (!isMissingSource(error)) throw error;
71
+ }
72
+ }
73
+ };
74
+ const declarationsIn = async (source: string) => {
75
+ const opened = await manager.openFile(source, cwd, "symbols", signal, input.readText);
76
+ if (opened === null || !opened.client.hasWorkspaceSymbolCapability) return undefined;
77
+ const text = await input.readText(source);
78
+ // A server without document symbols is searched through its workspace index alone.
79
+ const outline = await input.outlineOf(opened.client, opened.uri).catch((error: unknown) => {
80
+ if (isMethodNotFound(error)) return undefined;
81
+ throw error;
82
+ });
83
+ if (outline === undefined) return undefined;
84
+ const found: LspWorkspaceSymbol[] = [];
85
+ const textAt = rangeTextReader(text);
86
+ const visit = (symbols: readonly LspCodeSymbol[]) => {
87
+ for (const symbol of symbols) {
88
+ // The name range holds the identifier even when the server decorates the symbol's name,
89
+ // such as gopls with `(*Engine).Start` or clangd with a destructor's `~`.
90
+ if (textAt(symbol.selectionRange) === word)
91
+ found.push({
92
+ name: symbol.name,
93
+ kind: symbol.kind,
94
+ location: { uri: opened.uri, range: symbol.selectionRange },
95
+ });
96
+ visit(symbol.children);
97
+ }
98
+ };
99
+ visit(outline);
100
+ return [opened.client, found] as const;
101
+ };
102
+ await Promise.all(
103
+ Array.from({ length: Math.min(CONCURRENT_FILES, scanned.length) }, () => worker()),
104
+ );
105
+ for (const result of results) {
106
+ if (result === undefined) continue;
107
+ declarations.set(result[0], [...(declarations.get(result[0]) ?? []), ...result[1]]);
108
+ }
109
+ const unchecked = files.slice(MAX_SCANNED_FILES);
110
+ return {
111
+ declarations,
112
+ ...((unchecked.length > 0 || unlisted) && {
113
+ coverage: { ...nothingChecked, unopened: unchecked, unlisted },
114
+ }),
115
+ };
116
+ }
@@ -1,9 +1,46 @@
1
+ import type path from "node:path";
2
+
3
+ const VUE_PLUGIN = "node_modules/@vue/typescript-plugin";
4
+ const DEFAULT_VUE_PLUGIN_LOCATION = `{project}/${VUE_PLUGIN}`;
5
+
6
+ export function usesWorkspaceVuePlugin(options: Record<string, unknown>): boolean {
7
+ return (
8
+ Array.isArray(options.plugins) &&
9
+ options.plugins.some(
10
+ (plugin: unknown) =>
11
+ typeof plugin === "object" &&
12
+ plugin !== null &&
13
+ "location" in plugin &&
14
+ plugin.location === DEFAULT_VUE_PLUGIN_LOCATION,
15
+ )
16
+ );
17
+ }
18
+
19
+ /** Resolve the catalog's plugin path against the source's package inside a monorepo. */
20
+ export async function vuePluginDirectory(
21
+ source: string,
22
+ root: string,
23
+ paths: typeof path.posix,
24
+ exists: (file: string) => Promise<boolean>,
25
+ ): Promise<string> {
26
+ for (let directory = paths.dirname(source); ; directory = paths.dirname(directory)) {
27
+ const relative = paths.relative(root, directory);
28
+ // Containment only, never probe packages outside the workspace.
29
+ // oxlint-disable-next-line repo/no-parent-paths -- containment check only.
30
+ if (relative.split(paths.sep)[0] === ".." || paths.isAbsolute(relative)) return root;
31
+ if (directory === root || directory === paths.dirname(directory)) return root;
32
+ if (await exists(paths.join(directory, VUE_PLUGIN, "package.json"))) return directory;
33
+ }
34
+ }
35
+
1
36
  /** Expand the project path in JSON initialization options, including plugin locations. */
2
37
  export function resolveInitializationOptions(
3
38
  value: Record<string, unknown>,
4
39
  projectRoot: string,
40
+ vuePluginRoot = projectRoot,
5
41
  ): Record<string, unknown> {
6
42
  const expand = (item: unknown): unknown => {
43
+ if (item === DEFAULT_VUE_PLUGIN_LOCATION) return `${vuePluginRoot}/${VUE_PLUGIN}`;
7
44
  if (typeof item === "string") return item.replaceAll("{project}", () => projectRoot);
8
45
  if (Array.isArray(item)) return item.map(expand);
9
46
  if (item !== null && typeof item === "object")
@@ -11,11 +11,15 @@ import { SharedStartup, waitWithSignal } from "./abort.ts";
11
11
  import { documentUri } from "./document-uri.ts";
12
12
  import { sourceChanged } from "./source-changes.ts";
13
13
  import type { LspWorkspaceOwner } from "./workspace-owner.ts";
14
- import { prepareProjectQuery } from "./project.ts";
14
+ import { hasTypeScriptProjectQueries, loadQueryProject } from "./project.ts";
15
15
  import { retainForCurrentOperation } from "./document-leases.ts";
16
16
  import { localFilesContaining } from "./files-containing.ts";
17
17
 
18
- import { resolveInitializationOptions } from "./initialization-options.ts";
18
+ import {
19
+ resolveInitializationOptions,
20
+ usesWorkspaceVuePlugin,
21
+ vuePluginDirectory,
22
+ } from "./initialization-options.ts";
19
23
  import { toDiagnostic } from "./diagnostics.ts";
20
24
  import { type LspDiagnostic, type ResolvedServer } from "./types.ts";
21
25
 
@@ -164,7 +168,27 @@ export class LspManager {
164
168
  : resolved.find((s) => s.config.capabilities.includes(capability));
165
169
  if (!match) return null;
166
170
  const rootUri = remote ? cwd : URI.file(cwd).toString();
167
- const clientKey = `${match.serverId}:${rootUri}`;
171
+ const options = match.config.initializationOptions;
172
+ const project = remote
173
+ ? decodeURIComponent(new URL(rootUri).pathname)
174
+ : URI.parse(rootUri).fsPath;
175
+ const vueRoot =
176
+ options &&
177
+ match.serverId === "vue-typescript-language-server" &&
178
+ usesWorkspaceVuePlugin(options)
179
+ ? await vuePluginDirectory(
180
+ remote
181
+ ? decodeURIComponent(new URL(documentUri(extension, rootUri)).pathname)
182
+ : path.resolve(cwd, extension),
183
+ project,
184
+ remote ? path.posix : path,
185
+ owner
186
+ ? (file) => owner.exists(documentUri(file, rootUri), signal)
187
+ : async (file) => (await stat(file).catch(() => undefined))?.isFile() === true,
188
+ )
189
+ : project;
190
+ signal?.throwIfAborted();
191
+ const clientKey = JSON.stringify([match.serverId, rootUri, vueRoot]);
168
192
  const pending = this._clientStarts.get(clientKey);
169
193
  if (pending) {
170
194
  if (pending.controller.signal.aborted) {
@@ -182,7 +206,14 @@ export class LspManager {
182
206
  return client;
183
207
  }
184
208
  const startup = new SharedStartup((startupSignal) =>
185
- this._startClient(clientKey, rootUri, match, client, startupSignal),
209
+ this._startClient(
210
+ clientKey,
211
+ rootUri,
212
+ match,
213
+ client,
214
+ options && resolveInitializationOptions(options, project, vueRoot),
215
+ startupSignal,
216
+ ),
186
217
  );
187
218
  this._clientStarts.set(clientKey, startup);
188
219
  const settled = () => {
@@ -213,6 +244,7 @@ export class LspManager {
213
244
  rootUri: string,
214
245
  match: ResolvedServer,
215
246
  client: LspClient | undefined,
247
+ initOptions: Record<string, unknown> | undefined,
216
248
  signal: AbortSignal,
217
249
  ): Promise<LspClient> {
218
250
  const startingClient =
@@ -228,14 +260,7 @@ export class LspManager {
228
260
  ...(!rootUri.startsWith("ssh://") &&
229
261
  this._options.sharedServers && { sharedServers: this._options.sharedServers }),
230
262
  ...(match.config.env && { env: match.config.env }),
231
- ...(match.config.initializationOptions && {
232
- initOptions: resolveInitializationOptions(
233
- match.config.initializationOptions,
234
- rootUri.startsWith("ssh://")
235
- ? decodeURIComponent(new URL(rootUri).pathname)
236
- : URI.parse(rootUri).fsPath,
237
- ),
238
- }),
263
+ ...(initOptions && { initOptions }),
239
264
  ...(match.config.settings && { settings: match.config.settings }),
240
265
  ...(match.config.timeoutMs && { timeoutMs: match.config.timeoutMs }),
241
266
  ...(this._options.idleTimeoutMs !== undefined && {
@@ -309,137 +334,106 @@ export class LspManager {
309
334
  return this.requireOwner().filesContaining?.(client.rootUri, word, extensions, signal);
310
335
  return localFilesContaining(URI.parse(client.rootUri).fsPath, word, extensions, signal);
311
336
  }
337
+ /**
338
+ * Sources under `root` of the workspace `cwd` whose text has `word` as a whole word, among files
339
+ * with a configured language server. A file `root` is its own only candidate. Undefined when the
340
+ * workspace owner has no text search.
341
+ */
342
+ async filesContainingInScope(
343
+ cwd: string,
344
+ root: string,
345
+ word: string,
346
+ signal?: AbortSignal,
347
+ ): Promise<readonly string[] | undefined> {
348
+ signal?.throwIfAborted();
349
+ const remote = cwd.startsWith("ssh://");
350
+ const selected = remote ? documentUri(root, cwd) : path.resolve(cwd, root);
351
+ if (await this.isSourceFile(selected, cwd, signal)) return [selected];
352
+ const extensions = [...this._registry.knownExtensions];
353
+ if (extensions.length === 0) return [];
354
+ return remote
355
+ ? this.requireOwner().filesContaining?.(selected, word, extensions, signal)
356
+ : localFilesContaining(selected, word, extensions, signal);
357
+ }
312
358
 
313
- /** Start symbol servers only for language families with files in this workspace. */
314
- async getWorkspaceClients(
359
+ /**
360
+ * Seed native workspace indexes. Most servers need one document per language extension;
361
+ * TypeScript needs one for each project represented in the scope.
362
+ */
363
+ async prepareWorkspaceSymbols(
315
364
  cwd: string,
316
- capability: "symbols" = "symbols",
317
365
  scope = cwd,
318
366
  acceptsFile: (source: string) => boolean = () => true,
319
367
  signal?: AbortSignal,
320
368
  readText?: SourceTextReader,
321
369
  ): Promise<LspClient[]> {
322
370
  signal?.throwIfAborted();
323
- if (cwd.startsWith("ssh://")) {
324
- const owner = this._owner;
325
- if (!owner)
326
- throw Object.assign(new Error("No language server workspace owner"), {
327
- code: "UNSUPPORTED_SOURCE",
328
- });
329
- const clients = new Set<LspClient>();
330
- const remaining = new Set(this._registry.knownExtensions);
331
- const ignored = new Set([".git", ".cache", "node_modules", "dist", "build"]);
332
- const visit = async (source: string): Promise<void> => {
333
- signal?.throwIfAborted();
334
- if (remaining.size === 0) return;
335
- for (const entry of await owner.entries(source, signal)) {
336
- signal?.throwIfAborted();
337
- const uri = documentUri(entry.name, `${source}/`);
338
- if (entry.kind === "directory") {
339
- if (!ignored.has(entry.name)) await visit(uri);
340
- } else if (entry.kind === "file") {
341
- const extension = path.posix.extname(entry.name).toLowerCase();
342
- if (!remaining.has(extension) || !acceptsFile(uri)) continue;
343
- const opened = await this.openFile(uri, cwd, capability, signal, readText);
344
- if (opened) {
345
- clients.add(opened.client);
346
- remaining.delete(extension);
347
- }
348
- }
371
+ const remote = cwd.startsWith("ssh://");
372
+ const owner = remote ? this.requireOwner() : undefined;
373
+ const remaining = new Set(this._registry.knownExtensions);
374
+ const projectFiles = new Map<LspClient, Set<string>>();
375
+ const typeScriptByExtension = new Map<string, LspClient>();
376
+ const clients = new Set<LspClient>();
377
+ const ignored = new Set([".git", ".cache", "node_modules", "dist", "build"]);
378
+ const extensionOf = (source: string) =>
379
+ (remote
380
+ ? path.posix.extname(decodeURIComponent(new URL(source).pathname))
381
+ : path.extname(source)
382
+ ).toLowerCase();
383
+
384
+ const seed = async (source: string, extension: string) => {
385
+ if (!acceptsFile(source)) return;
386
+ const known = typeScriptByExtension.get(extension);
387
+ if (known && projectFiles.get(known)?.has(known.serverDocumentPath(source))) return;
388
+ const opened = await this.openFile(source, cwd, "symbols", signal, readText);
389
+ if (opened === null) return;
390
+ const { client, uri } = opened;
391
+ if (client.hasWorkspaceSymbolCapability) {
392
+ clients.add(client);
393
+ if (hasTypeScriptProjectQueries(client)) {
394
+ const covered = projectFiles.get(client) ?? new Set<string>();
395
+ typeScriptByExtension.set(extension, client);
396
+ projectFiles.set(client, covered);
397
+ for (const file of await loadQueryProject(client, uri, signal)) covered.add(file);
398
+ return;
349
399
  }
350
- };
351
- const selected = documentUri(scope, cwd);
352
- if (await owner.isFile(selected, signal)) {
353
- if (!acceptsFile(selected)) return [];
354
- const opened = await this.openFile(selected, cwd, capability, signal, readText);
355
- return opened ? [opened.client] : [];
356
400
  }
357
- await visit(selected);
358
- return [...clients];
359
- }
360
- const clients = new Set<LspClient>();
361
- const remainingExtensions = new Set(this._registry.knownExtensions);
362
- const ignoredDirectories = new Set([".git", ".cache", "node_modules", "dist", "build"]);
363
-
401
+ remaining.delete(extension);
402
+ };
403
+ const localEntries = async (directory: string) => {
404
+ const entries = await readdir(directory, { withFileTypes: true }).catch(() => []);
405
+ return entries.map((entry) => ({
406
+ name: entry.name,
407
+ kind: entry.isDirectory() ? "directory" : entry.isFile() ? "file" : "other",
408
+ }));
409
+ };
364
410
  const visit = async (directory: string): Promise<void> => {
365
- signal?.throwIfAborted();
366
- if (remainingExtensions.size === 0) {
367
- return;
368
- }
369
-
370
- let entries;
371
-
372
- try {
373
- entries = await readdir(directory, { withFileTypes: true });
374
- } catch {
375
- return;
376
- }
377
-
411
+ if (remaining.size === 0) return;
412
+ const entries = owner
413
+ ? await owner.entries(directory, signal)
414
+ : await localEntries(directory);
378
415
  for (const entry of entries) {
379
416
  signal?.throwIfAborted();
380
- if (remainingExtensions.size === 0) {
381
- return;
382
- }
383
-
384
- if (entry.isDirectory()) {
385
- if (!ignoredDirectories.has(entry.name)) {
386
- await visit(path.join(directory, entry.name));
387
- }
388
-
389
- continue;
390
- }
391
-
392
- if (!entry.isFile()) {
393
- continue;
394
- }
395
-
396
- const extension = path.extname(entry.name).toLowerCase();
397
-
398
- if (!remainingExtensions.has(extension)) {
399
- continue;
400
- }
401
-
402
- const filePath = path.join(directory, entry.name);
403
- if (!acceptsFile(filePath)) continue;
404
- const opened = await this.openFile(filePath, cwd, capability, signal, readText);
405
-
406
- if (opened) {
407
- remainingExtensions.delete(extension);
408
- if (opened.client.hasWorkspaceSymbolCapability) {
409
- await prepareProjectQuery(opened.client, filePath);
410
- clients.add(opened.client);
411
- }
417
+ if (remaining.size === 0) return;
418
+ const source = remote
419
+ ? documentUri(entry.name, `${directory}/`)
420
+ : path.join(directory, entry.name);
421
+ if (entry.kind === "directory") {
422
+ if (!ignored.has(entry.name)) await visit(source);
423
+ } else if (entry.kind === "file") {
424
+ const extension = extensionOf(source);
425
+ if (remaining.has(extension)) await seed(source, extension);
412
426
  }
413
427
  }
414
428
  };
415
429
 
416
- const selected = path.resolve(cwd, scope);
417
- if ((await stat(selected)).isFile()) {
418
- if (!acceptsFile(selected)) return [];
419
- const opened = await this.openFile(selected, cwd, capability, signal, readText);
420
- if (opened === null || !opened.client.hasWorkspaceSymbolCapability) return [];
421
- await prepareProjectQuery(opened.client, selected);
422
- return [opened.client];
423
- }
424
- await visit(selected);
430
+ const selected = remote ? documentUri(scope, cwd) : path.resolve(cwd, scope);
431
+ if (await this.isSourceFile(selected, cwd, signal)) await seed(selected, extensionOf(selected));
432
+ else await visit(selected);
425
433
  signal?.throwIfAborted();
426
434
  return [...clients];
427
435
  }
428
436
 
429
- /**
430
- * Open matching source files before querying workspace symbols; excluded files start no server.
431
- * `readText` supplies the text each opened file is published with, as in {@link openFile}.
432
- */
433
- async prepareWorkspaceSymbols(
434
- cwd: string,
435
- scope = cwd,
436
- acceptsFile?: (source: string) => boolean,
437
- signal?: AbortSignal,
438
- readText?: SourceTextReader,
439
- ): Promise<LspClient[]> {
440
- return this.getWorkspaceClients(cwd, "symbols", scope, acceptsFile, signal, readText);
441
- }
442
-
443
437
  /**
444
438
  Check if there's any LSP server configured for this file extension.
445
439
  */
@@ -543,16 +537,32 @@ export class LspManager {
543
537
  return null;
544
538
  }
545
539
 
546
- const uri = client.toUri(absolutePath);
547
- retainForCurrentOperation(client, uri);
548
540
  const owner = remote ? this.requireOwner() : undefined;
549
541
  const resolved = owner
550
542
  ? await this._registry.resolveOwned(absolutePath, (source) => owner.exists(source, signal))
551
543
  : this._registry.resolve(absolutePath);
552
- const languageId = resolved[0]?.languageId ?? "plaintext";
544
+ const languageId =
545
+ resolved.find((match) => match.serverId === client.serverId)?.languageId ??
546
+ resolved[0]?.languageId ??
547
+ "plaintext";
548
+ return this.openClientFile(client, absolutePath, languageId, signal, readText);
549
+ }
550
+
551
+ /** Publish a declaration in the same project that discovered it. */
552
+ async openClientFile(
553
+ client: LspClient,
554
+ source: string,
555
+ languageId: string,
556
+ signal?: AbortSignal,
557
+ readText?: SourceTextReader,
558
+ ): Promise<{ client: LspClient; uri: string; languageId: string }> {
559
+ signal?.throwIfAborted();
560
+ const uri = client.toUri(source);
561
+ retainForCurrentOperation(client, uri);
562
+ const owner = uri.startsWith("ssh://") ? this.requireOwner() : undefined;
553
563
 
554
564
  if (owner) {
555
- const text = readText ? await readText(absolutePath) : await owner.readText(uri, signal);
565
+ const text = readText ? await readText(source) : await owner.readText(uri, signal);
556
566
  signal?.throwIfAborted();
557
567
  client.syncDocument(uri, text, languageId);
558
568
  await client.waitUntilLoaded(signal);
@@ -563,8 +573,8 @@ export class LspManager {
563
573
  try {
564
574
  const { readFile } = await import("node:fs/promises");
565
575
  const text = readText
566
- ? await readText(absolutePath)
567
- : await readFile(absolutePath, { encoding: "utf8", signal });
576
+ ? await readText(source)
577
+ : await readFile(source, { encoding: "utf8", signal });
568
578
  signal?.throwIfAborted();
569
579
  client.syncDocument(uri, text, languageId);
570
580
  } catch (error) {
@@ -1,6 +1,7 @@
1
1
  import { NAVIGATION_TIMEOUT_MS } from "pi-agent-resource";
2
2
  import type { LspClient } from "./client.ts";
3
3
  import { isMethodNotFound } from "./errors.ts";
4
+ import { loadQueryProject } from "./project.ts";
4
5
  import { sourceChanged } from "./source-changes.ts";
5
6
  import type { LspPosition, LspRange } from "./types.ts";
6
7
 
@@ -79,30 +80,6 @@ async function unlessUnsupported<T>(request: Promise<T>): Promise<T | undefined>
79
80
  }
80
81
  }
81
82
 
82
- /** Load unopened TypeScript project files before a workspace-wide query when the server advertises support. */
83
- export async function loadQueryProject(
84
- client: LspClient,
85
- uri: string,
86
- signal?: AbortSignal,
87
- ): Promise<void> {
88
- signal?.throwIfAborted();
89
- if (!client.supportsCommand("typescript.tsserverRequest")) return;
90
- const project = await client.sendRequest<{ success?: boolean } | null>(
91
- "workspace/executeCommand",
92
- {
93
- command: "typescript.tsserverRequest",
94
- arguments: [
95
- "projectInfo",
96
- { file: client.serverDocumentPath(uri), needFileNameList: true },
97
- { isAsync: false, expectsResult: true },
98
- ],
99
- },
100
- signal,
101
- );
102
- signal?.throwIfAborted();
103
- if (project?.success !== true)
104
- throw new Error("TypeScript could not load the project for the workspace query.");
105
- }
106
83
  export async function requestReferences(
107
84
  client: LspClient,
108
85
  uri: string,