dal-code 0.1.1 → 0.1.6

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 (110) hide show
  1. package/PRIVACY.md +1 -1
  2. package/dist/core/agent-session.d.ts +5 -0
  3. package/dist/core/agent-session.d.ts.map +1 -1
  4. package/dist/core/agent-session.js +7 -0
  5. package/dist/core/agent-session.js.map +1 -1
  6. package/dist/core/auth-guidance.d.ts.map +1 -1
  7. package/dist/core/auth-guidance.js +5 -1
  8. package/dist/core/auth-guidance.js.map +1 -1
  9. package/dist/core/extensions/types.d.ts +15 -1
  10. package/dist/core/extensions/types.d.ts.map +1 -1
  11. package/dist/core/extensions/types.js.map +1 -1
  12. package/dist/core/house-providers.d.ts +81 -0
  13. package/dist/core/house-providers.d.ts.map +1 -0
  14. package/dist/core/house-providers.js +128 -0
  15. package/dist/core/house-providers.js.map +1 -0
  16. package/dist/core/model-resolver.d.ts.map +1 -1
  17. package/dist/core/model-resolver.js +1 -3
  18. package/dist/core/model-resolver.js.map +1 -1
  19. package/dist/core/model-runtime.d.ts.map +1 -1
  20. package/dist/core/model-runtime.js +11 -0
  21. package/dist/core/model-runtime.js.map +1 -1
  22. package/dist/core/tools/bash.d.ts.map +1 -1
  23. package/dist/core/tools/bash.js +15 -2
  24. package/dist/core/tools/bash.js.map +1 -1
  25. package/dist/core/trust-manager.d.ts.map +1 -1
  26. package/dist/core/trust-manager.js +7 -0
  27. package/dist/core/trust-manager.js.map +1 -1
  28. package/dist/dal/builtins.d.ts +15 -0
  29. package/dist/dal/builtins.d.ts.map +1 -1
  30. package/dist/dal/builtins.js +21 -0
  31. package/dist/dal/builtins.js.map +1 -1
  32. package/dist/main.d.ts.map +1 -1
  33. package/dist/main.js +3 -1
  34. package/dist/main.js.map +1 -1
  35. package/dist/modes/interactive/components/model-selector.d.ts.map +1 -1
  36. package/dist/modes/interactive/components/model-selector.js +3 -2
  37. package/dist/modes/interactive/components/model-selector.js.map +1 -1
  38. package/dist/modes/interactive/interactive-mode.d.ts +6 -0
  39. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  40. package/dist/modes/interactive/interactive-mode.js +81 -42
  41. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  42. package/dist/modes/interactive/session-share.d.ts.map +1 -1
  43. package/dist/modes/interactive/session-share.js +6 -5
  44. package/dist/modes/interactive/session-share.js.map +1 -1
  45. package/dist/node_modules/@dalcode/dal-bridge/package.json +3 -3
  46. package/dist/node_modules/@dalcode/dal-gateway/package.json +3 -3
  47. package/dist/node_modules/@dalcode/dal-gateway/src/index.ts +21 -12
  48. package/dist/node_modules/@dalcode/dal-guard/package.json +5 -5
  49. package/dist/node_modules/@dalcode/dal-halo/package.json +2 -2
  50. package/dist/node_modules/@dalcode/dal-lang/package.json +4 -4
  51. package/dist/node_modules/@dalcode/dal-lang/src/index.ts +19 -2
  52. package/dist/node_modules/@dalcode/dal-lsp/package.json +7 -4
  53. package/dist/node_modules/@dalcode/dal-lsp/src/client.ts +241 -0
  54. package/dist/node_modules/@dalcode/dal-lsp/src/config.ts +176 -0
  55. package/dist/node_modules/@dalcode/dal-lsp/src/format.ts +88 -0
  56. package/dist/node_modules/@dalcode/dal-lsp/src/index.ts +149 -42
  57. package/dist/node_modules/@dalcode/dal-lsp/src/types.ts +21 -0
  58. package/dist/node_modules/@dalcode/dal-mcp/package.json +5 -5
  59. package/dist/node_modules/@dalcode/dal-mcp/src/config.ts +25 -3
  60. package/dist/node_modules/@dalcode/dal-mcp/src/index.ts +6 -1
  61. package/dist/node_modules/@dalcode/dal-pi-kit/dist/i18n.d.ts +8 -1
  62. package/dist/node_modules/@dalcode/dal-pi-kit/dist/i18n.d.ts.map +1 -1
  63. package/dist/node_modules/@dalcode/dal-pi-kit/dist/i18n.js +77 -4
  64. package/dist/node_modules/@dalcode/dal-pi-kit/dist/i18n.js.map +1 -1
  65. package/dist/node_modules/@dalcode/dal-pi-kit/package.json +1 -1
  66. package/dist/node_modules/@dalcode/dal-pi-kit/src/i18n.ts +81 -5
  67. package/dist/node_modules/@dalcode/dal-subagent/package.json +6 -6
  68. package/dist/node_modules/@dalcode/dal-telemetry/package.json +3 -3
  69. package/dist/node_modules/@dalcode/dal-telemetry/src/config.ts +31 -8
  70. package/dist/node_modules/@dalcode/dal-telemetry/src/index.ts +12 -4
  71. package/dist/node_modules/@dalcode/dal-telemetry/src/reporter.ts +14 -1
  72. package/dist/node_modules/@dalcode/deepailab/package.json +4 -4
  73. package/dist/node_modules/@dalcode/deepailab/src/index.ts +111 -21
  74. package/dist/node_modules/@dalcode/deepailab/src/model-defaults.ts +109 -5
  75. package/dist/node_modules/@earendil-works/pi-agent-core/package.json +3 -3
  76. package/dist/node_modules/@earendil-works/pi-ai/dist/api/openai-completions.d.ts.map +1 -1
  77. package/dist/node_modules/@earendil-works/pi-ai/dist/api/openai-completions.js +18 -1
  78. package/dist/node_modules/@earendil-works/pi-ai/dist/api/openai-completions.js.map +1 -1
  79. package/dist/node_modules/@earendil-works/pi-ai/dist/env-api-keys.d.ts +1 -0
  80. package/dist/node_modules/@earendil-works/pi-ai/dist/env-api-keys.d.ts.map +1 -1
  81. package/dist/node_modules/@earendil-works/pi-ai/dist/env-api-keys.js +18 -0
  82. package/dist/node_modules/@earendil-works/pi-ai/dist/env-api-keys.js.map +1 -1
  83. package/dist/node_modules/@earendil-works/pi-ai/dist/index.d.ts +1 -0
  84. package/dist/node_modules/@earendil-works/pi-ai/dist/index.d.ts.map +1 -1
  85. package/dist/node_modules/@earendil-works/pi-ai/dist/index.js +3 -0
  86. package/dist/node_modules/@earendil-works/pi-ai/dist/index.js.map +1 -1
  87. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/.manifest.json +1 -1
  88. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/amazon-bedrock.json +1 -1
  89. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/baseten.json +1 -1
  90. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/fireworks.json +1 -1
  91. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/huggingface.json +1 -1
  92. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/opencode-go.json +1 -1
  93. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/openrouter.json +1 -1
  94. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/vercel-ai-gateway.json +1 -1
  95. package/dist/node_modules/@earendil-works/pi-ai/package.json +2 -2
  96. package/dist/node_modules/@earendil-works/pi-client/package.json +2 -2
  97. package/dist/node_modules/@earendil-works/pi-protocol/package.json +1 -1
  98. package/dist/node_modules/@earendil-works/pi-telemetry/package.json +1 -1
  99. package/dist/node_modules/@earendil-works/pi-tui/package.json +1 -1
  100. package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
  101. package/examples/extensions/custom-provider-anthropic/package.json +1 -1
  102. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  103. package/examples/extensions/gondolin/package-lock.json +2 -2
  104. package/examples/extensions/gondolin/package.json +1 -1
  105. package/examples/extensions/sandbox/package-lock.json +2 -2
  106. package/examples/extensions/sandbox/package.json +1 -1
  107. package/examples/extensions/with-deps/package-lock.json +2 -2
  108. package/examples/extensions/with-deps/package.json +1 -1
  109. package/npm-shrinkwrap.json +13 -3
  110. package/package.json +3 -2
@@ -0,0 +1,176 @@
1
+ import { accessSync, constants, existsSync, readFileSync } from "node:fs";
2
+ import { delimiter, extname, isAbsolute, join, resolve } from "node:path";
3
+ import { CONFIG_DIR_NAME, getAgentDir } from "@earendil-works/pi-coding-agent";
4
+ import type { LspServerConfig, LspServerSelection } from "./types.ts";
5
+
6
+ interface LspConfigFile {
7
+ lspServers?: Record<string, unknown>;
8
+ }
9
+
10
+ interface LspConfigLayer {
11
+ servers: Record<string, LspServerConfig>;
12
+ names: Set<string>;
13
+ disabled: Set<string>;
14
+ }
15
+
16
+ export const DEFAULT_LSP_SERVERS: Record<string, LspServerConfig> = {
17
+ typescript: {
18
+ command: "typescript-language-server",
19
+ args: ["--stdio"],
20
+ extensions: {
21
+ ".ts": "typescript",
22
+ ".tsx": "typescriptreact",
23
+ ".mts": "typescript",
24
+ ".cts": "typescript",
25
+ ".js": "javascript",
26
+ ".jsx": "javascriptreact",
27
+ ".mjs": "javascript",
28
+ ".cjs": "javascript",
29
+ },
30
+ installHint: "npm i -g typescript-language-server typescript",
31
+ },
32
+ python: {
33
+ command: "pyright-langserver",
34
+ args: ["--stdio"],
35
+ extensions: { ".py": "python", ".pyi": "python" },
36
+ installHint: "npm i -g pyright",
37
+ },
38
+ go: {
39
+ command: "gopls",
40
+ extensions: { ".go": "go" },
41
+ installHint: "go install golang.org/x/tools/gopls@latest",
42
+ },
43
+ rust: {
44
+ command: "rust-analyzer",
45
+ extensions: { ".rs": "rust" },
46
+ installHint: "rustup component add rust-analyzer",
47
+ },
48
+ };
49
+
50
+ const configProblems: string[] = [];
51
+
52
+ function isStringRecord(value: unknown): value is Record<string, string> {
53
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
54
+ return Object.values(value).every((entry) => typeof entry === "string");
55
+ }
56
+
57
+ function isDisabled(value: unknown): boolean {
58
+ return Boolean(value && typeof value === "object" && !Array.isArray(value) && "disabled" in value && value.disabled);
59
+ }
60
+
61
+ function parseServer(value: unknown): LspServerConfig | undefined {
62
+ if (!value || typeof value !== "object" || Array.isArray(value)) return undefined;
63
+ const record = value as Record<string, unknown>;
64
+ if (typeof record.command !== "string" || record.command.length === 0 || !isStringRecord(record.extensions)) {
65
+ return undefined;
66
+ }
67
+ return {
68
+ command: record.command,
69
+ ...(Array.isArray(record.args) && record.args.every((arg) => typeof arg === "string")
70
+ ? { args: record.args }
71
+ : {}),
72
+ ...(isStringRecord(record.env) ? { env: record.env } : {}),
73
+ extensions: Object.fromEntries(
74
+ Object.entries(record.extensions).map(([extension, languageId]) => [
75
+ extension.startsWith(".") ? extension.toLowerCase() : `.${extension.toLowerCase()}`,
76
+ languageId,
77
+ ]),
78
+ ),
79
+ ...(typeof record.installHint === "string" ? { installHint: record.installHint } : {}),
80
+ };
81
+ }
82
+
83
+ function emptyLayer(): LspConfigLayer {
84
+ return { servers: {}, names: new Set(), disabled: new Set() };
85
+ }
86
+
87
+ function readServersFile(path: string): LspConfigLayer {
88
+ if (!existsSync(path)) return emptyLayer();
89
+ try {
90
+ const parsed = JSON.parse(readFileSync(path, "utf8")) as LspConfigFile;
91
+ const layer = emptyLayer();
92
+ for (const [name, value] of Object.entries(parsed.lspServers ?? {})) {
93
+ if (isDisabled(value)) {
94
+ layer.names.add(name);
95
+ layer.disabled.add(name);
96
+ continue;
97
+ }
98
+ const config = parseServer(value);
99
+ if (!config) {
100
+ configProblems.push(`${path}: server ${JSON.stringify(name)} requires command and extensions`);
101
+ continue;
102
+ }
103
+ layer.names.add(name);
104
+ layer.servers[name] = config;
105
+ }
106
+ return layer;
107
+ } catch (error) {
108
+ configProblems.push(`${path}: ${error instanceof Error ? error.message : String(error)}`);
109
+ return emptyLayer();
110
+ }
111
+ }
112
+
113
+ function applyLayer(merged: Record<string, LspServerConfig>, layer: LspConfigLayer): void {
114
+ for (const name of layer.names) delete merged[name];
115
+ Object.assign(merged, layer.servers);
116
+ for (const name of layer.disabled) delete merged[name];
117
+ }
118
+
119
+ export function loadLspServerConfigs(cwd: string): Record<string, LspServerConfig> {
120
+ const merged = structuredClone(DEFAULT_LSP_SERVERS);
121
+ applyLayer(merged, readServersFile(join(getAgentDir(), "lsp.json")));
122
+ applyLayer(merged, readServersFile(join(cwd, CONFIG_DIR_NAME, "lsp.json")));
123
+ return merged;
124
+ }
125
+
126
+ export function takeLspConfigProblems(): string[] {
127
+ return configProblems.splice(0, configProblems.length);
128
+ }
129
+
130
+ function executableCandidates(path: string): string[] {
131
+ if (process.platform !== "win32" || extname(path)) return [path];
132
+ const extensions = (process.env.PATHEXT ?? ".COM;.EXE;.BAT;.CMD")
133
+ .split(";")
134
+ .filter(Boolean)
135
+ .map((extension) => extension.toLowerCase());
136
+ return [path, ...extensions.map((extension) => `${path}${extension}`)];
137
+ }
138
+
139
+ function isExecutable(path: string): boolean {
140
+ try {
141
+ accessSync(path, process.platform === "win32" ? constants.F_OK : constants.X_OK);
142
+ return true;
143
+ } catch {
144
+ return false;
145
+ }
146
+ }
147
+
148
+ export function resolveLspCommand(cwd: string, command: string): string | undefined {
149
+ if (isAbsolute(command) || command.includes("/") || command.includes("\\")) {
150
+ const commandPath = isAbsolute(command) ? command : resolve(cwd, command);
151
+ return executableCandidates(commandPath).find(isExecutable);
152
+ }
153
+
154
+ const localCommand = executableCandidates(join(cwd, "node_modules", ".bin", command)).find(isExecutable);
155
+ if (localCommand) return localCommand;
156
+
157
+ for (const pathEntry of (process.env.PATH ?? "").split(delimiter)) {
158
+ const normalizedEntry = pathEntry.replace(/^"|"$/g, "");
159
+ const found = executableCandidates(join(normalizedEntry, command)).find(isExecutable);
160
+ if (found) return found;
161
+ }
162
+ return undefined;
163
+ }
164
+
165
+ export function selectLspServer(cwd: string, filePath: string): LspServerSelection {
166
+ const extension = extname(filePath).toLowerCase();
167
+ let configured: LspServerSelection["configured"];
168
+ for (const [name, config] of Object.entries(loadLspServerConfigs(cwd))) {
169
+ const languageId = config.extensions[extension];
170
+ if (!languageId) continue;
171
+ configured ??= { name, config };
172
+ const command = resolveLspCommand(cwd, config.command);
173
+ if (command) return { configured, resolved: { name, config, languageId, command } };
174
+ }
175
+ return { configured };
176
+ }
@@ -0,0 +1,88 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { relative, sep } from "node:path";
3
+ import { fileURLToPath } from "node:url";
4
+ import type { LspRequestKind } from "./types.ts";
5
+
6
+ interface Position {
7
+ line: number;
8
+ character: number;
9
+ }
10
+
11
+ function isRecord(value: unknown): value is Record<string, unknown> {
12
+ return Boolean(value && typeof value === "object" && !Array.isArray(value));
13
+ }
14
+
15
+ function positionAt(value: unknown): Position | undefined {
16
+ if (!isRecord(value) || typeof value.line !== "number" || typeof value.character !== "number") return undefined;
17
+ return { line: value.line, character: value.character };
18
+ }
19
+
20
+ function locationFrom(value: unknown): { uri: string; position: Position } | undefined {
21
+ if (!isRecord(value)) return undefined;
22
+ const targetRange = isRecord(value.targetSelectionRange) ? value.targetSelectionRange : undefined;
23
+ const range = isRecord(value.range) ? value.range : undefined;
24
+ const uri =
25
+ typeof value.targetUri === "string" ? value.targetUri : typeof value.uri === "string" ? value.uri : undefined;
26
+ const position = positionAt(targetRange?.start) ?? positionAt(range?.start);
27
+ return uri && position ? { uri, position } : undefined;
28
+ }
29
+
30
+ function displayPath(cwd: string, filePath: string): string {
31
+ const local = relative(cwd, filePath);
32
+ if (local && local !== ".." && !local.startsWith(`..${sep}`)) return local.split(sep).join("/");
33
+ return filePath;
34
+ }
35
+
36
+ function sourceLine(filePath: string, line: number): string {
37
+ try {
38
+ return readFileSync(filePath, "utf8").split(/\r?\n/)[line]?.trim() ?? "";
39
+ } catch {
40
+ return "";
41
+ }
42
+ }
43
+
44
+ function formatLocation(cwd: string, value: unknown): string | undefined {
45
+ const location = locationFrom(value);
46
+ if (!location) return undefined;
47
+ let filePath: string;
48
+ try {
49
+ filePath = fileURLToPath(location.uri);
50
+ } catch {
51
+ return `${location.uri}:${location.position.line + 1}:${location.position.character + 1}`;
52
+ }
53
+ const prefix = `${displayPath(cwd, filePath)}:${location.position.line + 1}:${location.position.character + 1}`;
54
+ const source = sourceLine(filePath, location.position.line);
55
+ return source ? `${prefix} | ${source}` : prefix;
56
+ }
57
+
58
+ function hoverContents(value: unknown): string | undefined {
59
+ if (typeof value === "string") return value;
60
+ if (Array.isArray(value))
61
+ return value
62
+ .map(hoverContents)
63
+ .filter((part): part is string => Boolean(part))
64
+ .join("\n");
65
+ if (!isRecord(value)) return undefined;
66
+ return typeof value.value === "string" ? value.value : undefined;
67
+ }
68
+
69
+ export function formatLspResult(result: unknown, request: LspRequestKind, cwd: string, filePath: string): string {
70
+ if (result === null || result === undefined) return "(no result)";
71
+ if (request === "definition" || request === "references") {
72
+ const values = Array.isArray(result) ? result : [result];
73
+ const locations = values
74
+ .map((value) => formatLocation(cwd, value))
75
+ .filter((line): line is string => Boolean(line));
76
+ if (locations.length > 0) return locations.join("\n");
77
+ }
78
+ if (request === "hover" && isRecord(result)) {
79
+ const range = isRecord(result.range) ? result.range : undefined;
80
+ const position = positionAt(range?.start);
81
+ const prefix = position
82
+ ? `${displayPath(cwd, filePath)}:${position.line + 1}:${position.character + 1} | ${sourceLine(filePath, position.line)}`
83
+ : displayPath(cwd, filePath);
84
+ const contents = hoverContents(result.contents);
85
+ if (contents) return `${prefix}\n${contents}`;
86
+ }
87
+ return JSON.stringify(result);
88
+ }
@@ -1,19 +1,19 @@
1
1
  /**
2
2
  * dal-lsp: language-server queries for the agent.
3
3
  *
4
- * Gives the model an authoritative channel for type-level questions that grep
5
- * cannot answer: where a symbol is defined, where it is referenced, and what
6
- * its hover documentation says. The language servers themselves run inside the
7
- * DAL Code backend (server/src/services/lsp), which owns their lifecycle and
8
- * stdio pipes; pi talks to it through the same loopback bridge every other
9
- * server answer uses, so the extension stands down entirely when the bridge
10
- * environment is absent (i.e. every pi run outside DAL Code).
4
+ * DAL Code sessions keep using the editor bridge. Pure CLI sessions lazily
5
+ * start a local language server and reuse it for subsequent queries.
11
6
  */
12
7
 
8
+ import { isAbsolute } from "node:path";
13
9
  import { BridgeClient, type FetchLike, readBridgeConfig } from "@dalcode/dal-bridge/client";
14
10
  import { t } from "@dalcode/dal-pi-kit";
15
11
  import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
16
12
  import { Type } from "typebox";
13
+ import { LspClient } from "./client.ts";
14
+ import { selectLspServer, takeLspConfigProblems } from "./config.ts";
15
+ import { formatLspResult } from "./format.ts";
16
+ import type { ResolvedLspServer } from "./types.ts";
17
17
 
18
18
  const lspSchema = Type.Object({
19
19
  filePath: Type.String({ description: t("要查询的文件的绝对路径") }),
@@ -32,11 +32,81 @@ interface LspResponse {
32
32
  /** Very large inspect payloads (e.g. a whole-module hover) get truncated. */
33
33
  const MAX_RESULT_CHARS = 24_000;
34
34
 
35
+ interface RunningLspServer {
36
+ client: LspClient;
37
+ ready: Promise<void>;
38
+ }
39
+
40
+ const localServers = new Map<string, RunningLspServer>();
41
+ let exitHookInstalled = false;
42
+
43
+ function serverKey(cwd: string, server: ResolvedLspServer): string {
44
+ return JSON.stringify([cwd, server.command, server.config.args ?? [], server.config.env ?? {}]);
45
+ }
46
+
47
+ async function getLocalClient(
48
+ cwd: string,
49
+ server: ResolvedLspServer,
50
+ onUpdate:
51
+ | ((result: { content: { type: "text"; text: string }[]; details: { starting: boolean } }) => void)
52
+ | undefined,
53
+ ): Promise<LspClient> {
54
+ const key = serverKey(cwd, server);
55
+ let running = localServers.get(key);
56
+ if (!running) {
57
+ onUpdate?.({
58
+ content: [{ type: "text", text: `${t("lsp: 正在启动语言服务器:")}${server.name}` }],
59
+ details: { starting: true },
60
+ });
61
+ const client = new LspClient(cwd, server.command, server.config, () => {
62
+ const current = localServers.get(key);
63
+ if (current?.client === client) localServers.delete(key);
64
+ });
65
+ running = { client, ready: client.connect() };
66
+ localServers.set(key, running);
67
+ }
68
+ try {
69
+ await running.ready;
70
+ return running.client;
71
+ } catch (error) {
72
+ if (localServers.get(key) === running) localServers.delete(key);
73
+ running.client.dispose();
74
+ throw error;
75
+ }
76
+ }
77
+
78
+ export async function shutdownLocalLspServers(): Promise<void> {
79
+ const servers = [...localServers.values()];
80
+ localServers.clear();
81
+ await Promise.allSettled(servers.map(async ({ client }) => client.shutdown()));
82
+ }
83
+
84
+ function disposeLocalLspServers(): void {
85
+ for (const { client } of localServers.values()) client.dispose();
86
+ localServers.clear();
87
+ }
88
+
89
+ function truncateResult(result: string): string {
90
+ return result.length > MAX_RESULT_CHARS
91
+ ? `${result.slice(0, MAX_RESULT_CHARS)}\n${t("… (结果过长,已截断)")}`
92
+ : result;
93
+ }
94
+
95
+ function serializeBridgeResult(result: unknown): string {
96
+ return truncateResult(JSON.stringify(result ?? null, null, 2));
97
+ }
98
+
35
99
  export default function (pi: ExtensionAPI, fetchImpl?: FetchLike) {
36
100
  const config = readBridgeConfig();
37
- if (!config) return; // Outside DAL Code there is no bridge — stand down.
101
+ const bridgeClient = config ? new BridgeClient(config, fetchImpl) : undefined;
38
102
 
39
- const client = new BridgeClient(config, fetchImpl);
103
+ pi.on("session_shutdown", async () => {
104
+ await shutdownLocalLspServers();
105
+ });
106
+ if (!exitHookInstalled) {
107
+ exitHookInstalled = true;
108
+ process.on("exit", disposeLocalLspServers);
109
+ }
40
110
 
41
111
  pi.registerTool<typeof lspSchema>({
42
112
  name: "lsp",
@@ -47,46 +117,83 @@ export default function (pi: ExtensionAPI, fetchImpl?: FetchLike) {
47
117
  ) + t("支持已配置语言服务器的语言(TypeScript/JavaScript 开箱即用)。"),
48
118
  promptSnippet: t("lsp - 用语言服务器查询权威类型信息(definition / references / hover)"),
49
119
  parameters: lspSchema,
50
- execute: async (_toolCallId, params, _signal, _onUpdate, ctx: ExtensionContext) => {
51
- const response = await client.post<LspResponse>("/api/internal/pi-bridge/lsp", {
52
- sessionId: ctx.sessionManager.getSessionId(),
53
- filePath: params.filePath,
54
- request: params.request,
55
- line: params.line,
56
- character: params.character,
57
- });
58
-
59
- // An unreachable bridge reads as failure — the agent falls back to
60
- // read/grep rather than treating LSP output as fact.
61
- if (!response) {
120
+ execute: async (_toolCallId, params, _signal, onUpdate, ctx: ExtensionContext) => {
121
+ const character = params.character ?? 1;
122
+ if (params.line < 1) throw new Error(t("lsp: line 必须从 1 开始。"));
123
+ if (character < 1) throw new Error(t("lsp: character 必须从 1 开始。"));
124
+
125
+ if (bridgeClient) {
126
+ const response = await bridgeClient.post<LspResponse>("/api/internal/pi-bridge/lsp", {
127
+ sessionId: ctx.sessionManager.getSessionId(),
128
+ filePath: params.filePath,
129
+ request: params.request,
130
+ line: params.line,
131
+ character: params.character,
132
+ });
133
+
134
+ // An unreachable bridge reads as failure — the agent falls back to
135
+ // read/grep rather than treating LSP output as fact.
136
+ if (!response) {
137
+ return {
138
+ content: [
139
+ {
140
+ type: "text" as const,
141
+ text: t("lsp: 无法联系 DAL Code 的 LSP 桥接,查询失败。改用 read/grep 继续。"),
142
+ },
143
+ ],
144
+ details: { ok: false, reason: "bridge unreachable" },
145
+ };
146
+ }
147
+ if (response.error) {
148
+ return {
149
+ content: [{ type: "text" as const, text: `lsp: ${response.error}` }],
150
+ details: { ok: false, reason: response.error },
151
+ };
152
+ }
153
+ return {
154
+ content: [{ type: "text" as const, text: serializeBridgeResult(response.result) }],
155
+ details: { ok: true },
156
+ };
157
+ }
158
+
159
+ if (!isAbsolute(params.filePath)) throw new Error(t("lsp: filePath 必须是绝对路径。"));
160
+ const selection = selectLspServer(ctx.cwd, params.filePath);
161
+ const problems = takeLspConfigProblems();
162
+ if (problems.length > 0) {
62
163
  return {
63
- content: [
64
- {
65
- type: "text" as const,
66
- text: t("lsp: 无法联系 DAL Code 的 LSP 桥接,查询失败。改用 read/grep 继续。"),
67
- },
68
- ],
69
- details: { ok: false, reason: "bridge unreachable" },
164
+ content: [{ type: "text" as const, text: `lsp: ${problems.join("\n")}` }],
165
+ details: { ok: false, reason: "invalid config" },
70
166
  };
71
167
  }
72
- if (response.error) {
168
+ const { configured, resolved: server } = selection;
169
+ if (!server) {
170
+ const reason = configured
171
+ ? `${t("未找到语言服务器命令:")}${configured.config.command}${t("。请安装:")}${configured.config.installHint ?? configured.config.command}`
172
+ : t("没有为该文件类型配置语言服务器。请在 .dal/lsp.json 的 lspServers 中配置。");
73
173
  return {
74
- content: [
75
- {
76
- type: "text" as const,
77
- text: `lsp: ${response.error}`,
78
- },
79
- ],
80
- details: { ok: false, reason: response.error },
174
+ content: [{ type: "text" as const, text: `lsp: ${reason}` }],
175
+ details: { ok: false, reason },
81
176
  };
82
177
  }
83
178
 
84
- const serialized = JSON.stringify(response.result ?? null, null, 2);
85
- const text =
86
- serialized.length > MAX_RESULT_CHARS
87
- ? `${serialized.slice(0, MAX_RESULT_CHARS)}\n${t("… (结果过长,已截断)")}`
88
- : serialized;
89
- return { content: [{ type: "text" as const, text }], details: { ok: true } };
179
+ try {
180
+ const client = await getLocalClient(ctx.cwd, server, onUpdate);
181
+ const result = await client.query(
182
+ params.filePath,
183
+ server.languageId,
184
+ params.request,
185
+ params.line,
186
+ character,
187
+ );
188
+ const text = truncateResult(formatLspResult(result, params.request, ctx.cwd, params.filePath));
189
+ return { content: [{ type: "text" as const, text }], details: { ok: true, server: server.name } };
190
+ } catch (error) {
191
+ const reason = error instanceof Error ? error.message : String(error);
192
+ return {
193
+ content: [{ type: "text" as const, text: `${t("lsp: 本地语言服务器查询失败:")}${reason}` }],
194
+ details: { ok: false, reason },
195
+ };
196
+ }
90
197
  },
91
198
  });
92
199
  }
@@ -0,0 +1,21 @@
1
+ export interface LspServerConfig {
2
+ command: string;
3
+ args?: string[];
4
+ env?: Record<string, string>;
5
+ extensions: Record<string, string>;
6
+ installHint?: string;
7
+ }
8
+
9
+ export interface ResolvedLspServer {
10
+ name: string;
11
+ config: LspServerConfig;
12
+ languageId: string;
13
+ command: string;
14
+ }
15
+
16
+ export interface LspServerSelection {
17
+ configured?: { name: string; config: LspServerConfig };
18
+ resolved?: ResolvedLspServer;
19
+ }
20
+
21
+ export type LspRequestKind = "definition" | "references" | "hover";
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dalcode/dal-mcp",
3
- "version": "0.1.1",
3
+ "version": "0.1.6",
4
4
  "private": true,
5
5
  "type": "module",
6
6
  "main": "./src/index.ts",
@@ -20,12 +20,12 @@
20
20
  ]
21
21
  },
22
22
  "dependencies": {
23
- "@dalcode/dal-pi-kit": "0.1.1",
24
- "@dalcode/dal-guard": "0.1.1",
25
- "@dalcode/dal-bridge": "0.1.1"
23
+ "@dalcode/dal-pi-kit": "0.1.6",
24
+ "@dalcode/dal-guard": "0.1.6",
25
+ "@dalcode/dal-bridge": "0.1.6"
26
26
  },
27
27
  "peerDependencies": {
28
- "@earendil-works/pi-coding-agent": "^0.1.1"
28
+ "@earendil-works/pi-coding-agent": "^0.1.2"
29
29
  },
30
30
  "peerDependenciesMeta": {
31
31
  "@earendil-works/pi-coding-agent": {
@@ -79,20 +79,42 @@ function readServersFile(path: string): McpConfigLayer {
79
79
  const parsed = JSON.parse(readFileSync(path, "utf8")) as McpConfigFile;
80
80
  const layer = emptyLayer();
81
81
  for (const [name, value] of Object.entries(parsed.mcpServers ?? {})) {
82
- layer.names.add(name);
83
82
  if (isDisabled(value)) {
83
+ layer.names.add(name);
84
84
  layer.disabled.add(name);
85
85
  continue;
86
86
  }
87
87
  const config = parseServer(value);
88
- if (config) layer.servers[name] = config;
88
+ if (!config) {
89
+ // Deliberately not added to `names`: layers are merged by name, so a
90
+ // project entry missing `command`/`url` used to shadow a working
91
+ // user-level server of the same name and take both out.
92
+ configProblems.push(`${path}: 服务器 "${name}" 缺少 command 或 url,已忽略`);
93
+ continue;
94
+ }
95
+ layer.names.add(name);
96
+ layer.servers[name] = config;
89
97
  }
90
98
  return layer;
91
- } catch {
99
+ } catch (error) {
100
+ // A stray comma here used to make every configured MCP server vanish with
101
+ // no error and no line number.
102
+ configProblems.push(`${path}: ${error instanceof Error ? error.message : String(error)}`);
92
103
  return emptyLayer();
93
104
  }
94
105
  }
95
106
 
107
+ /**
108
+ * Problems found while reading the config files, for the caller to surface.
109
+ * Collected rather than thrown: one bad file must not stop the other layers.
110
+ */
111
+ const configProblems: string[] = [];
112
+
113
+ /** Drains the problems recorded by the most recent config load. */
114
+ export function takeMcpConfigProblems(): string[] {
115
+ return configProblems.splice(0, configProblems.length);
116
+ }
117
+
96
118
  function shouldIncludeDefaults(opts?: LoadMcpServerConfigsOptions): boolean {
97
119
  if (opts?.includeDefaults !== undefined) return opts.includeDefaults;
98
120
  return Boolean(process.env.DALCODE_BRIDGE_URL);
@@ -17,7 +17,7 @@
17
17
  import { evaluateToolCall } from "@dalcode/dal-guard";
18
18
  import { t } from "@dalcode/dal-pi-kit";
19
19
  import type { ExtensionAPI, ExtensionContext, ToolCallEvent } from "@earendil-works/pi-coding-agent";
20
- import { loadMcpServerConfigs } from "./config.ts";
20
+ import { loadMcpServerConfigs, takeMcpConfigProblems } from "./config.ts";
21
21
  import { McpHttpClient } from "./http-client.ts";
22
22
  import { type McpStatusItem, rememberMcpSessionId, reportMcpStatus } from "./report.ts";
23
23
  import { McpStdioClient } from "./stdio-client.ts";
@@ -258,6 +258,11 @@ export default function (pi: ExtensionAPI) {
258
258
  const sessionId = ctx.sessionManager?.getSessionId?.();
259
259
  if (sessionId) rememberMcpSessionId(sessionId);
260
260
  const servers = loadMcpServerConfigs(ctx.cwd);
261
+ // A malformed mcp.json used to make every server disappear with no error
262
+ // and no line number; "未配置 MCP 服务器" was the only sign.
263
+ for (const problem of takeMcpConfigProblems()) {
264
+ ctx.ui.notify(`${t("MCP 配置有问题:")}${problem}`, "warning");
265
+ }
261
266
  for (const [name, config] of Object.entries(servers)) {
262
267
  try {
263
268
  await connectServer(pi, name, config, ctx.cwd);
@@ -12,7 +12,14 @@ export type DalLanguage = "zh" | "en";
12
12
  /** Whether the user has made an explicit, persisted language choice. */
13
13
  export declare function hasChosenLanguage(): boolean;
14
14
  export declare function getLanguage(): DalLanguage;
15
- export declare function setLanguage(language: DalLanguage): void;
15
+ /**
16
+ * Applies the language and persists the choice.
17
+ *
18
+ * Returns whether it was persisted. Callers must not claim success on a false:
19
+ * the one-time picker used to say "Restart dal to apply everywhere" after a
20
+ * failed write, so the user restarted into the old language and got asked again.
21
+ */
22
+ export declare function setLanguage(language: DalLanguage): boolean;
16
23
  /** Translate a Chinese source string. Identity for zh; catalog lookup for en. */
17
24
  export declare function t(zh: string): string;
18
25
  //# sourceMappingURL=i18n.d.ts.map